Developer API

Embed a tool with your own hooks and buttons

Put a Wellfriend tool inside your own page, with preset and locked parameters, your own buttons, a beforeRun hook and run events.

Overview

A tool embed shows one Wellfriend tool workspace (any tool in the tool reference, with its live preview) inside your own page. You choose the tool, preset its parameters, lock the ones your users may not change, add your own buttons, and react to each step in your own code.

Your server creates a short-lived embed session with your API key, and your page mounts it. Runs from the embed are charged to your account like the same API calls, from your plan's request units and credits; there is nothing extra to buy.

1. Create a session on your server

Call POST /api/v2/embed-sessions with "surface": "TOOL" using a key with the embeds.write scope. The parent origin must be your page's exact origin and one of your workspace's allowed embed origins. The response carries a token that lives 60 to 900 seconds (600 by default); refresh it with POST /api/v2/embed-sessions/{id}/refresh and revoke it with POST /api/v2/embed-sessions/{id}/revoke. Send only the session object to the browser, never your key.

FieldMeaning
surface"TOOL".
toolIdAny tool of the tool reference (the same ids as document operations).
presetParameters the workspace starts with, checked against the tool's options.
lockedParametersParameter names your users cannot change. A locked parameter keeps its preset value on every run, whatever the page or the frame sends.
sourceOptional {documentId, versionId?} of your workspace that the tool opens with.
parentOriginYour page's exact origin, such as https://app.example.com.
brandingOptional {theme: light | dark | system, accent: #RRGGBB, title, logoUrl}.
hostReferenceYour own reference, returned when you read the session.
ttlSeconds60 to 900.
cURL
# On your server: create the session with your secret key, then give the browser
# only { sessionId, token, frameUrl, parentOrigin } from the answer.
export WELLFRIEND_API_KEY="YOUR_API_KEY"   # placeholder: read it from your secret store
curl -sS -X POST "https://wellfriend.dev/api/v2/embed-sessions" \
  -H "Authorization: Bearer $WELLFRIEND_API_KEY" -H "Content-Type: application/json" \
  -d '{"surface":"TOOL","toolId":"add-watermark","parentOrigin":"https://app.example.com","preset":{"type":"text","text":"Case 0921","opacity":35},"lockedParameters":["text"],"ttlSeconds":600}'
TypeScript (server)
import { Wellfriend } from "wellfriend-document-sdk";

// The key stays on your server. WELLFRIEND_API_KEY holds your key ("YOUR_API_KEY" is the placeholder).
const wf = new Wellfriend({ apiKey: process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY" });

export async function toolEmbedSession() {
  const session = await wf.embedSessions.createTool({
    toolId: "add-watermark",
    parentOrigin: "https://app.example.com",
    preset: {"type":"text","text":"Case 0921","opacity":35},
    lockedParameters: ["text"],
    ttlSeconds: 600,
  });
  return session; // { sessionId, token, frameUrl, parentOrigin, protocol }
}
Python (server)
import os

from wellfriend import Wellfriend

wf = Wellfriend(api_key=os.environ.get("WELLFRIEND_API_KEY", "YOUR_API_KEY"))  # placeholder fallback

session = wf.embed_sessions.create_tool(
    "add-watermark",
    "https://app.example.com",
    preset={"type":"text","text":"Case 0921","opacity":35},
    locked_parameters=["text"],
    ttl_seconds=600,
)
# Send session.session_id, session.token, session.frame_url and session.parent_origin to the page.
Go (server)
package main

import (
	"context"
	"fmt"
	"os"

	"wellfriend.dev/go/wellfriend"
)

func main() {
	key := os.Getenv("WELLFRIEND_API_KEY") // "YOUR_API_KEY" is the placeholder
	wf := wellfriend.New(wellfriend.WithAPIKey(key))
	session, err := wf.EmbedSessions.CreateTool(context.Background(), &wellfriend.ToolEmbedSessionParams{
		ToolID:           "add-watermark",
		ParentOrigin:     "https://app.example.com",
		Preset:           map[string]any{"type": "text", "text": "Case 0921", "opacity": 35},
		LockedParameters: []string{"text"},
		TTLSeconds:       wellfriend.Int64(600),
	})
	if err != nil {
		panic(err)
	}
	// { sessionId, token, frameUrl, parentOrigin, protocol }: send it to the page.
	fmt.Println(string(session.Raw))
}
Rust (server)
use serde_json::json;
use wellfriend::{ToolEmbedSession, Wellfriend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("WELLFRIEND_API_KEY").unwrap_or_else(|_| "YOUR_API_KEY".into()); // placeholder
    let wf = Wellfriend::builder().api_key(key).build()?;
    let mut session = ToolEmbedSession::new("add-watermark", "https://app.example.com");
    session.preset = json!({"type":"text","text":"Case 0921","opacity":35}).as_object().cloned();
    session.locked_parameters = vec!["text".into()];
    session.ttl_seconds = Some(600);
    let created = wf.embed_sessions().create_tool(session).await?;
    // { sessionId, token, frameUrl, parentOrigin, protocol }: send it to the page.
    println!("{}", serde_json::Value::Object(created));
    Ok(())
}

2. Mount it in your page, with your hooks and buttons

The browser loader ships with the TypeScript SDK as wellfriend-document-sdk/embed. It frames the tool, checks that your page's origin matches the session, and gives you events, commands, the beforeRun hook and your own buttons.

React (browser)
import { useEffect, useRef } from "react";
import { WellfriendToolEmbed } from "wellfriend-document-sdk/embed";

// session = what your server returned (sessionId, token, frameUrl, parentOrigin, protocol).
export function CaseTool({ session, caseId }) {
  const host = useRef(null);
  useEffect(() => {
    const embed = new WellfriendToolEmbed({
      container: host.current,
      session,
      // Your veto or patch before every run (unlocked parameters only).
      beforeRun: async ({ parameters }) => (caseId ? { parameters } : { allow: false, reason: "Choose a case first." }),
      buttons: [{ id: "attach", label: "Attach to case" }],
    });
    embed.on("buttonClicked", ({ id, parameters }) => myHandler(id, parameters));
    embed.on("runCompleted", ({ outputVersionId }) => saveToMyCase(caseId, outputVersionId));
    embed.on("paramsChanged", ({ parameters }) => console.log(parameters)); // add-watermark: text locked
    return () => embed.destroy();
  }, [session, caseId]);
  return <div ref={host} style={{ height: 720 }} />;
}

Events from the tool

EventPayload
ready{toolId}: the tool can take commands.
fileSelected{name, mimeType, pages}
paramsChanged{parameters}: the exact parameters a run would send.
runStarted{operationId}
runCompleted{operationId, outputDocumentId, outputVersionId}: read or chain the output with your key.
runFailed{code, message}
buttonClicked{id, parameters}: one of your buttons was pressed.

Commands, your own buttons and methods

setParameters, getParameters, loadVersion, run and reset drive the tool from your page. addButton and removeButton add up to six of your own buttons to its settings panel. callMethod calls one of the documented methods by name, for generic integrations. Any other command is refused.

TypeScript
// Commands from your page; each resolves with the frame's answer.
await embed.setParameters({ opacity: 60 });        // locked parameters are refused
const { parameters } = await embed.getParameters();
await embed.loadVersion({ documentId, versionId }); // the session's start version or an output of this session
await embed.run();                                  // runs beforeRun first
await embed.reset();                                // back to the upload step
await embed.addButton({ id: "approve", label: "Send for approval" });
await embed.callMethod("setParameters", { parameters: { opacity: 40 } }); // documented methods only

The beforeRun hook

When you pass beforeRun, the tool asks your page before every run and waits up to 10 seconds. Answer { allow: false, reason } to stop the run (the reason is shown to your user), or { parameters } to change unlocked parameters first, for example to stamp your own case number. Locked parameters cannot be changed this way either.

TypeScript
// beforeRun: stop a run, or change unlocked parameters first.
const embed = new WellfriendToolEmbed({
  container, session,
  beforeRun: async ({ parameters }) => {
    if (!(await myPolicy.allows(caseId))) return { allow: false, reason: "This case is closed." };
    return { parameters: { ...parameters, opacity: 25 } };
  },
});

Security model

  • Isolated: the frame runs on the Wellfriend origin and cannot read your page, and your page cannot read the frame. Messages are checked (protocol, session id, size) and accepted only from the session's exact parent origin, and only that origin may frame the tool (frame-ancestors).
  • No access to anyone else's data: the session token reaches only that session's tool, its start version and the outputs of its own runs; never another document of your workspace and never another customer's data.
  • Locked parameters are enforced on every run by Wellfriend, not only in the browser.
  • No file bytes cross the page boundary: your server reads a result through the API with your own key.
  • Tokens are short-lived and work for one embed only; Wellfriend stores only a hash. Refresh or revoke them at any time.

How embedded runs are charged

Each run from the embed is charged to the account that created the session, like the same API calls: request units per run, and credits for OCR and AI-mode tools, from your plan. Embedded runs never use the website's free runs, and there is no separate embed plan or price.