Use the Thinkfree agent loop with your own chat UI
Your page keeps its own chat UI, and the Thinkfree agent loop from @thinkfree.dev/tfo-ai-sdk/headless calls the model
and runs the document tools. Compare the options in Choose an integration.
The headless agent is the same agent loop that runs inside Thinkfree Office's built-in AI Agent, without a UI. It
exposes Thinkfree Office's document tools to the model, runs the tool the model picks through Editor SDK inside the browser,
and repeats until the model answers. You build only the chat UI: a message list and an input box that send text to the
agent's session and render the replies.
The model never touches the document directly. It only picks tools; Editor SDK in the browser runs them. A relay server forwards model requests, which can include document content read by tools; it never opens or edits the document.
Before you begin
- An open URL for the document. See Document URLs and the
iframe requirements.
attachDocument()connects Editor SDK and waits for Thinkfree Office, so you do not callOffice.word()orwhenReady()yourself. AddhideContentBar=1to the open URL so the Thinkfree Office's built-in AI Agent panel does not appear next to your chat. - A model connection. By default the agent uses Thinkfree Office's admin AI Provider settings, so no key or endpoint appears in your page. To choose the model in the page, use a relay server, or a provider API key for local tests only.
- Node.js and npm, and a local static server for the sample page.
Install
npm install @thinkfree.dev/tfo-ai-sdk
Install one package. Editor SDK comes with it and is bundled into each entry point, so the import map needs only the
/headless entry.
<script type="importmap">
{ "imports": {
"@thinkfree.dev/tfo-ai-sdk/headless": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/headless.js"
} }
</script>
| Entry point | Contents |
|---|---|
@thinkfree.dev/tfo-ai-sdk/headless | mountHeadless() and getProviderCatalog(); the agent runtime, no UI. Used on this page |
@thinkfree.dev/tfo-ai-sdk/chat-ui | Chat UI bridge for the Thinkfree chat UI with your own loop (option 2) |
@thinkfree.dev/tfo-ai-sdk/ui, /chat | Thinkfree chat UI component, and mountChat() that combines it with this agent (option 4) |
Sample page
The page shows Thinkfree Office on the left and your chat on the right. Save both files, replace
YOUR_OFFICE_DOCUMENT_OPEN_URL, and serve the folder from a local static server.
chat.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Headless agent with my chat UI</title>
<script type="importmap">
{ "imports": { "@thinkfree.dev/tfo-ai-sdk/headless": "./node_modules/@thinkfree.dev/tfo-ai-sdk/dist/headless.js" } }
</script>
<style>
html, body { height: 100%; margin: 0; font: 14px/1.5 system-ui, sans-serif; }
body { display: grid; grid-template-columns: 1fr 380px; }
#editor { width: 100%; height: 100%; border: 0; }
#chat { display: grid; grid-template-rows: auto 1fr auto; border-left: 1px solid #ddd; min-height: 0; }
#chat header { padding: 8px 12px; border-bottom: 1px solid #ddd; color: #555; }
#messages { overflow: auto; padding: 10px 12px; }
.msg { margin: 0 0 10px; white-space: pre-wrap; }
.msg.user { color: #1f5fbf; }
.msg.tool { font: 12px/1.4 monospace; color: #666; }
.msg.error { color: #b00020; }
form { display: flex; gap: 6px; padding: 10px 12px; border-top: 1px solid #ddd; }
textarea { flex: 1; resize: none; height: 56px; }
</style>
</head>
<body>
<!-- Office. chat.js sets src to the open URL -->
<iframe id="editor" title="Thinkfree Office document"></iframe>
<!-- Your own chat UI: a message list and an input box -->
<section id="chat">
<header id="status">Preparing…</header>
<div id="messages"></div>
<form id="composer">
<textarea id="prompt" placeholder="Add the heading 'Quarterly summary' at the top" disabled></textarea>
<button type="submit" disabled>Send</button>
</form>
</section>
<script type="module" src="./chat.js"></script>
</body>
</html>
chat.js
import { mountHeadless } from "@thinkfree.dev/tfo-ai-sdk/headless";
// Open URL issued by your Office/storage integration, and the module that matches it
const OPEN_URL = "YOUR_OFFICE_DOCUMENT_OPEN_URL";
const MODULE = "word"; // "word" | "cell" | "show"
// "office": read Office's admin AI Provider settings when the document connects
const AI = "office";
const $status = document.getElementById("status");
const $messages = document.getElementById("messages");
const $form = document.getElementById("composer");
const $prompt = document.getElementById("prompt");
const $send = $form.querySelector("button");
function say(kind, text) {
const el = document.createElement("div");
el.className = "msg " + kind;
el.textContent = text;
$messages.appendChild(el);
$messages.scrollTop = $messages.scrollHeight;
}
// 1. Open Office. hideContentBar=1 hides Office's built-in AI Agent panel
const iframe = document.getElementById("editor");
const url = new URL(OPEN_URL);
url.searchParams.set("hideContentBar", "1");
iframe.src = url.toString();
// 2. Mount the agent. The document is in a child iframe, so connect it later with attachDocument
const agent = mountHeadless({
transport: { kind: "iframe" },
aiProviderConfig: AI,
systemPrompt: "You help the user edit the open document. Prefer tools over prose. Reply in the user's language.",
});
// 3. Show tool calls. The event already carries the parsed ToolResult
agent.onToolCall((e) => {
if (e.phase === "start") { say("tool", "⚙ " + e.name + " " + JSON.stringify(e.args)); return; }
const summary = e.result
? JSON.stringify(e.result.success ? e.result.data ?? "" : e.result.failure)
: JSON.stringify(e.raw);
say("tool", (e.success ? "✓ " : "✕ ") + e.name + " " + summary.slice(0, 200));
});
// 4. When Office has loaded, connect the document and register its tools
iframe.addEventListener("load", async () => {
try {
const toolNames = await agent.attachDocument({ iframeEl: iframe, module: MODULE });
$status.textContent = `Connected · ${toolNames.length} document tools`;
$prompt.disabled = false; $send.disabled = false; $prompt.focus();
} catch (err) {
$status.textContent = "Connection failed";
say("error", `${err.code ?? ""} ${err.message}`);
}
}, { once: true });
// 5. User input -> session.send -> final answer
$form.addEventListener("submit", async (ev) => {
ev.preventDefault();
const text = $prompt.value.trim();
if (!text) return;
$prompt.value = "";
say("user", text);
$send.disabled = true;
try {
const result = await agent.session.send(text); // resolves after the tool calls finish
if (result?.text) say("assistant", result.text);
} catch (err) {
say("error", String(err?.message ?? err));
} finally {
$send.disabled = false; $prompt.focus();
}
});
// 6. Clean up: unregister tools, disconnect Editor SDK, dispose the runtime
window.addEventListener("pagehide", () => agent.destroy());
Expected result: the status line shows the number of document tools. Ask "Add the heading 'Quarterly
summary' at the top"; the chat shows a tool call such as ⚙ insert_paragraph with a ✓ result,
the heading appears in the document, and the model replies.
Connect the model
aiProviderConfig decides how the agent calls the model. The default "office" follows Thinkfree Office's admin settings;
pass an object to decide in the page. Use "office" or relay in production and direct only on your own workstation.
"office" | relay | direct | |
|---|---|---|---|
| Flow | Reads the admin settings (relay URL, provider, model) when the document connects | Browser → your relay server → provider | Browser → provider API |
| Key | On the server | On the server | In the page, visible in developer tools |
| Use for | Production default; follows admin changes | A model other than the Thinkfree Office setting | Local tests |
// office (default): follow Office's admin AI Provider settings; re-read on every attachDocument
const AI = "office";
// relay: your relay server holds the key
const AI = {
connectionMode: "relay",
aiProvider: "google", // must match the provider in the admin settings when you use the Office relay
model: "YOUR_MODEL_ID",
relayRequest: { endpoint: "https://relay.example.com/ai-agent/relay", method: "POST" },
maxToolIterations: 20,
};
// direct: local tests only, the key is visible to the page
const AI = {
connectionMode: "direct",
aiProvider: "google", // "google" | "claude" | "openai" | "openai-compatible"
model: "YOUR_MODEL_ID",
auth: { kind: "apiKey", apiKey: "YOUR_TEST_API_KEY", exposeToEvents: false },
maxToolIterations: 20,
};
maxToolIterationscaps tool calls in one turn (default 100). Keep it between 10 and 30 for typical edits.relayRequest.methodaccepts only POST.- An OpenAI-compatible server (for example an in-house LLM) uses
aiProvider: "openai-compatible"withopenAiCompatible: { preset: "custom", endpoint: "http://host:port/v1", path: "chat/completions" }. Omitauthwhen the server needs no key. - With the relay that ships with Thinkfree Office (
<Office origin>/ai-agent/relay), the key and model come from the admin settings andaiProvidermust match them. In that case"office"is simpler.
Never ship a provider key in JavaScript or static files. Shared environments always use a relay.
Mount the agent and connect the document
const agent = mountHeadless({
transport: { kind: "iframe" }, // the document is in a child iframe -> attachDocument
aiProviderConfig: AI,
systemPrompt: "…", // optional; appended after the module prompt and toolkit rules
// preset: "core", // optional; default "full". "core" leaves out execute_script
});
const toolNames = await agent.attachDocument({
iframeEl: iframe,
module: "word", // "word" | "cell" | "show"
// frameworkOrigin: "https://…", // only when the origin cannot be derived from iframe.src
});
mountHeadless()is synchronous. It creates the runtime, session, andmodelContext; it does not know the document yet. Options:transport(required),aiProviderConfig,systemPrompt,preset,sessionId,sdkTimeoutMs(default 5,000 ms), andreadyTimeoutMs(default 60,000 ms).- The handle has
session,modelContext,runtime,toolsReady,registeredToolCount,attachDocument()anddetachDocument()(iframe transport only),onToolCall(),abortTurn(), anddestroy(). attachDocument()connects Editor SDK to Thinkfree Office (includingwhenReady()), registers the module's document tools, and resolves with their names. With"office"it also reads the admin settings. Call it after the iframeloadevent.- To open another document, call
detachDocument(), change the iframesrc, and callattachDocument()again. - Tools go through the Thinkfree Office toolkit. The model receives a
ToolResultfor every call, and the module prompt and toolkit rules are added to the system prompt automatically. - When the document is in the same window or the parent window instead of a child iframe, mount with
transport: { kind: "targetWindow", window, frameworkOrigin, module }. The document connects at mount time; wait foragent.toolsReadyinstead of callingattachDocument().
Send messages and observe tool calls
agent.session is one conversation. Send with send(), observe tools with agent.onToolCall(), and cancel with
agent.abortTurn().
const result = await agent.session.send("Add the heading 'Quarterly summary' at the top");
result.text; // the model's final answer (may be empty)
result.toolCalls; // tools run in this turn
const off = agent.onToolCall((e) => {
e.phase; // "start" | "result"
e.name; e.args; e.toolCallId;
e.success; // result phase: includes ToolResult failures
e.result; // result phase: ToolResult { success, data | failure: { code, message } }
e.raw; // result phase: the raw MCP result from the runtime
e.error; // result phase: failure reason
});
off(); // unsubscribe
agent.abortTurn(); // cancel the model request in progress; a tool already running is not stopped
send()repeats model call → tool calls → model call withinmaxToolIterationsand resolves when the model answers without tools. Disable the input box meanwhile.- The session keeps the conversation history. To start over,
destroy()the agent and mount again, or mount with a newsessionId. onToolCall()merges the runtime's tool-call start and result events into one event and parses theToolResult. If you subscribe to runtime events withsession.on()instead, the result arrives in MCP shape and theToolResultJSON is in its text block.
Add your own tools and instructions
Register tools that run in your page next to the document tools, for example a tool that opens a document from your storage. The tool list is read at the start of every turn, so a tool registered at any time is used from the next turn.
agent.modelContext.registerTool({
name: "open_document",
description: "Open a document by URL in the Office pane.",
inputSchema: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
async execute({ url }) {
agent.detachDocument();
iframe.src = String(url);
await new Promise((r) => iframe.addEventListener("load", r, { once: true }));
await agent.attachDocument({ iframeEl: iframe, module: "word" });
return { content: [{ type: "text", text: "Document opened." }] };
},
});
systemPrompt is appended after the module prompt and the toolkit rules. Put your service's rules there: reply language,
tone, and what the assistant must not do. The toolkit rules already explain how to use the document tools.
Clean up and rules
window.addEventListener("pagehide", () => agent.destroy());
destroy()is idempotent. It unregisters the tools, disconnects Editor SDK, and disposes the runtime. Thinkfree Office and the document are not affected.- The model receives prompts, history, tool schemas, and tool results, including document content read by tools. Decide what may leave the browser; see Safety.
- Keep the tool set small.
preset: "core"or a narrower registration reduces wrong choices and speeds up responses. - Edits already applied are not rolled back when a turn fails or you call
abortTurn(). Ask the user to confirm sensitive operations before they run.
Troubleshooting
| Symptom | Check |
|---|---|
"Connection failed" with TIMEOUT | The open URL is not an open URL, or Thinkfree Office runs on a different origin than the iframe src. See Document URLs. |
| 0 document tools | The module value does not match the document type (app= in the open URL), or the Thinkfree Office build does not expose that module's tools. |
| Provider error on the first send | With "office", Thinkfree Office has no admin AI Provider settings (a console warning appears). With an object, connectionMode, aiProvider, or model is missing; direct needs auth.apiKey, relay needs relayRequest.endpoint. |
| Relay request blocked by CORS | The relay must allow your page's origin. Check Access-Control-Allow-Origin on the OPTIONS response. |
| The model answers without using tools | The request is vague or there are too many tools. Be specific and try preset: "core". |
| The same tool repeats until the turn stops | The turn hit maxToolIterations. Split the request or use a larger model. |
| A tool result shows ✕ | Branch on failure.code: stale, invalid, permission, capability, no-op, internal. See Document tools and error handling. |