The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Fix docs of SDK (#326)
Abhishek Choudharya043725651e9
diff --git a/docs/api/overview.mdx b/docs/api/overview.mdxindex cef8cc68a..cf0e5fbcc 100644--- a/docs/api/overview.mdx+++ b/docs/api/overview.mdx@@ -1,10 +1,10 @@----title: 'SDK Overview'-sidebarTitle: 'Overview'-description: 'Understand Agent, Session, Turn, Event, and Delta, then drive TrueForge with the TypeScript SDK.'+title: 'SDK Concepts'+sidebarTitle: 'Concepts'+description: 'The mental model behind the SDK — Agent, Session, Turn, Event, and Delta — with one worked example.'----Everything the chat UI does, you can do in code. The TypeScript client [`@truefoundry/trueforge-sdk`](https://www.npmjs.com/package/@truefoundry/trueforge-sdk) creates sessions, streams turns, and handles approvals. This page explains the model; [Use an agent](/api/use-agent) is the runnable cookbook, and the **API Reference** tab has the raw HTTP schemas.+Already running? Jump to the [SDK Quickstart](/api/quickstart) to install and stream your first turn. This page is the mental model behind that code: how an [agent](#agent), a [session](#session), a [turn](#turn), an [event](#event), and a [delta](#delta) fit together. Once it clicks, [Use an agent](/api/use-agent) is the runnable cookbook, and the **API Reference** tab has the raw HTTP schemas.## Core concepts@@ -38,7 +38,7 @@ flowchart TDAn **agent** is a definition, not a running process. You define it once (the model, instructions, tools, and config), and any number of conversations can use it. `support-bot` is a support assistant that looks up orders and processes refunds through an MCP server. Its [AgentSpec](/create-agent/overview#create-an-agent-via-the-api) looks like this:-```json support-bot AgentSpec+```json support-bot AgentSpec wrap{"model": {"name": "anthropic/claude-sonnet-4-6",@@ -69,7 +69,7 @@ A **session** is one issue worked through with the agent. It holds the conversatJane's follow-ups about the refund stay in `sess-7f2a9c1b`. Bob's question runs in a separate session, so the two conversations never share context.-```json Session for Jane's refund issue+```json Session for Jane's refund issue wrap{"id": "sess-7f2a9c1b","agent": { "type": "ref", "agent_id": "agent-support-bot" },@@ -125,7 +125,7 @@ While a turn runs, the agent emits **events** on the SDK stream, one JSON objectSample payload:-```json turn.done+```json turn.done wrap{"type": "turn.done","id": "01jc...",@@ -143,7 +143,7 @@ Sample payload:}```-Every event carries an `id` and a `thread_id` (`"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events), plus a **sequence number** used for [resuming after a disconnect](/api/use-agent). The stream always opens with `turn.created` and closes with `turn.done`. Field-level schemas for every event type are in the [turn events reference](/api/turn-events).+Every event carries an `id` and a `thread_id` (`"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events), plus a **sequence number** used for [resuming after a disconnect](/api/use-agent). The stream always opens with `turn.created` and closes with `turn.done`. Field-level schemas for every event type are in the [turn events reference](/api/use-agent#turn-events-reference).### Delta@@ -151,11 +151,11 @@ Most events arrive as a complete payload. Model output is the exception: the LLMThe agent's full reply in Turn 1 is _"Your order ORD-2031 shipped on June 12. Total: $1,240.00."_ Your client receives:-```json Base event (empty shell)+```json Base event (empty shell) wrap{ "type": "model.message", "id": "msg-a1", "thread_id": "main", "content": "" }```-```json Deltas (merge into msg-a1 as they arrive)+```json Deltas (merge into msg-a1 as they arrive) wrap{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": "Your order ORD-2031" }{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": " shipped on June 12." }{ "type": "model.message.delta", "id": "msg-a1", "thread_id": "main", "content": " Total: $1,240.00.", "finish_reason": "stop" }@@ -163,7 +163,7 @@ The agent's full reply in Turn 1 is _"Your order ORD-2031 shipped on June 12. ToAppend each delta's `content` to the event with the matching `id` and re-render on every chunk. That's how the chat UI shows the reply word by word:-```text+```text wrapYour order ORD-2031Your order ORD-2031 shipped on June 12.Your order ORD-2031 shipped on June 12. Total: $1,240.00.@@ -231,22 +231,8 @@ sequenceDiagramA separate issue (Bob's shipping question, or Jane's next problem) runs in its own session, where Turn 1 starts fresh with no refund history.-## Call an authenticated API--When [login is off](/authentication/overview) (the default), omit any token. The SDK talks to the server as the shared local admin.--When [OIDC login](/authentication/overview) is enabled, the HTTP API requires authentication. The chat UI uses an HttpOnly cookie after sign-in; for the SDK (or any other HTTP client), send the same OIDC **ID token** as a bearer token:--```typescript-const client = new TrueForge({- baseUrl: 'https://trueforge.myorg.com',- token: process.env.TRUEFORGE_TOKEN,-});-```--That sets `Authorization: Bearer <id_token>` on every request. Get the token from your identity provider, or reuse a browser session. There's no device-code or client-credentials flow yet, so keep ID token lifetimes short at the IdP. A missing or expired token against an OIDC-enabled server returns `401`.-## Next steps-- [Use an agent](/api/use-agent) installs the SDK and walks through a runnable example plus the method recipes.+- [SDK Quickstart](/api/quickstart) installs the SDK, connects with a token, and streams your first turn.+- [Use an agent](/api/use-agent) is the full cookbook: streaming, approvals, questions, threads, and reconnects.- The **API Reference** tab has the raw HTTP endpoints and OpenAPI schemas.diff --git a/docs/api/quickstart.mdx b/docs/api/quickstart.mdxnew file mode 100644index 000000000..96f99a873--- /dev/null+++ b/docs/api/quickstart.mdx@@ -0,0 +1,121 @@+---+title: 'SDK Quickstart'+sidebarTitle: 'Quickstart'+description: 'Install the SDK, connect to your TrueForge server, and stream your first agent turn in a few minutes.'+---++Everything the chat UI does, you can do in code. The TypeScript client [`@truefoundry/trueforge-sdk`](https://www.npmjs.com/package/@truefoundry/trueforge-sdk) creates sessions, streams turns, and handles approvals. This page gets you running in three steps; the [concepts](/api/overview) and the [cookbook](/api/use-agent) — which ends with a full [event reference](/api/use-agent#turn-events-reference) — come after.++<Note>+ You need a running TrueForge server with at least one model provider configured. If you don't have one yet, start with the [Quickstart](/quickstart) — `npx @truefoundry/trueforge` gets you a local server at `http://localhost:8790`.+</Note>++## Install++```bash wrap+npm i @truefoundry/trueforge-sdk+```++## Get a token and connect++Point the client at your server's `baseUrl`, and pass a `token` only when the server requires login. How you authenticate depends on whether [OIDC login](/authentication/overview) is enabled:++| Server mode | Token | What to do |+| --- | --- | --- |+| **No login** (local `npx`, the default) | Not needed | Omit `token`. The SDK talks to the server as the shared local admin. |+| **OIDC login** (hosted / team deployments) | Required | Send your OIDC **ID token** as a bearer token. |++<Tabs>+ <Tab title="No login (default)">+ Local mode has no login, so you connect with just a `baseUrl`:+<CodeGroup>+ ```typescript wrap+ import { TrueForge } from '@truefoundry/trueforge-sdk';++ const client = new TrueForge({+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',+ timeoutInSeconds: 600, // raise for long-running SSE turns (default 60s)+ });+ ```+ </CodeGroup>+ </Tab>+ <Tab title="OIDC login">+ When [OIDC login](/authentication/overview) is on, every HTTP request needs an **ID token** from your identity provider, sent as `Authorization: Bearer <id_token>`:++ ```typescript wrap+ import { TrueForge } from '@truefoundry/trueforge-sdk';++ const client = new TrueForge({+ baseUrl: 'https://trueforge.myorg.com',+ token: process.env.TRUEFORGE_TOKEN, // OIDC ID token+ timeoutInSeconds: 600,+ });+ ```++ **Where to get the ID token:**++ - **From your identity provider** — run a standard OIDC Authorization Code flow against your IdP (the same one TrueForge is configured with) and read the `id_token` from the response. Most IdPs also expose a CLI or token tool for scripts and CI.+ - **From a browser session** — after you sign in to the TrueForge UI, your IdP has already issued an ID token; reuse one from that same flow.++ There's no device-code or client-credentials flow yet, so keep ID token lifetimes short at the IdP and refresh as needed. A missing or expired token against an OIDC-enabled server returns `401`.+ </Tab>+</Tabs>++## Run your first agent++Open a session, stream one turn, and print the reply as it arrives. This example passes an **inline agent spec**, so it works without saving an agent first — you only need a model provider configured on the server:++```typescript wrap+import { TrueForge } from '@truefoundry/trueforge-sdk';++const client = new TrueForge({+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',+ timeoutInSeconds: 600,+});++// Open a session with an inline agent (no saved agent needed).+const { data: session } = await client.sessions.create({+ agent: {+ spec: {+ model: { name: 'anthropic/claude-sonnet-4-6' }, // a model you configured in Settings+ instructions: 'You are a concise, helpful assistant.',+ },+ },+});++// Stream one turn and print the reply token by token.+const stream = await client.sessions.createTurnStream(session.id, {+ input: [{ type: 'user.message', content: 'In two sentences, what is TrueForge?' }],+});++for await (const { data: event } of stream.withMetadata()) {+ if (event.type === 'model.message.delta') process.stdout.write(event.content ?? '');+ if (event.type === 'turn.done') console.log('\n\nstatus:', event.state.status);+}+```++That's the whole loop: create a session, stream a turn, print each `model.message.delta`, and read the terminal `turn.done`. The stream always opens with `turn.created` and closes with `turn.done`.++<Tip>+ Prefer a saved agent? Build the **`web-research-brief`** agent in the [Quickstart](/quickstart), then reference it by name instead of an inline spec:++ ```typescript wrap+ const { data: session } = await client.sessions.create({ agent: { name: 'web-research-brief' } });+ ```+</Tip>++## Next steps++<CardGroup cols={2}>+ <Card title="Concepts" icon="diagram-project" href="/api/overview">+ The mental model behind the SDK: Agent → Session → Turn → Event → Delta.+ </Card>+ <Card title="Use an agent" icon="book" href="/api/use-agent">+ The full cookbook: streaming, approvals, questions, threads, and reconnects.+ </Card>+ <Card title="Turn events" icon="list" href="/api/use-agent#turn-events-reference">+ Field-level reference for every event streamed while a turn runs.+ </Card>+</CardGroup>++The **API Reference** tab has the raw HTTP endpoints and OpenAPI schemas.diff --git a/docs/api/turn-events.mdx b/docs/api/turn-events.mdxdeleted file mode 100644index 5051a2458..000000000--- a/docs/api/turn-events.mdx+++ /dev/null@@ -1,156 +0,0 @@-----title: 'Turn Events Reference'-sidebarTitle: 'Turn Events'-description: 'Every event type streamed while a turn runs — lifecycle, model output, tool activity, subagent threads, and pause events.'------While a turn runs, the SDK streams events to your app. Each event is a JSON object; the stream also carries a **sequence number** you can use to [reconnect](/api/use-agent) after a disconnect without missing or double-processing events.--<Note>- Field names on this page use the HTTP/JSON wire format (snake_case, e.g. `turn_id`, `source_event_id`). The TypeScript SDK returns the same fields camelCased (`turnId`, `sourceEventId`) — so a field you see here maps directly to its camelCase form in SDK code.-</Note>--Every event carries:--| Field | Description |-| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `type` | The event type — one of the types below. |-| `id` | Unique event id (monotonic ULID — sortable by creation order). |-| `created_at` | ISO 8601 timestamp. |-| `thread_id` | Which execution thread emitted it: `"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events (`turn.*`, `sandbox.created`, `mcp.auth_required`). |--A stream always opens with `turn.created` and closes with `turn.done`. When you list persisted session events afterwards, you get the same events with deltas pre-merged into their `model.message`.--## Lifecycle events--### `turn.created`--First event on every stream.--| Field | Description |-| ------------------ | --------------------------------------------------------- |-| `turn_id` | Id of this turn. |-| `previous_turn_id` | The turn this one chains from, or `null` for a root turn. |-| `input` | The turn's input items, echoed back. |-| `state` | `{ "status": "running" }` |--### `turn.done`--Last event on every stream. `state.status` is one of:--- **`done`** — carries `output` (the final `model.message`, or `null` when the turn ended paused), `required_actions` (pending `tool.approval_required` / `tool.response_required` / `mcp.auth_required` events, empty when none), `completed_at`, and optional `metrics`.-- **`cancelled`** — carries a `reason`: `client-cancelled`, `server-execution-timeout`, `cancelled-for-next-turn`, or `abandoned`.-- **`error`** — carries a `message`.--`metrics`, when present, aggregates the whole turn: `total_input_tokens`, `total_output_tokens`, `total_tokens`, `total_cache_read_tokens`, `total_cache_write_tokens`, `total_reasoning_tokens`, and `total_cost_in_usd`.--```json turn.done — paused for approval-{- "type": "turn.done",- "id": "01jc...",- "thread_id": null,- "created_at": "2026-06-24T10:01:12Z",- "state": {- "status": "done",- "output": null,- "required_actions": [- {- "type": "tool.approval_required",- "thread_id": "main",- "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]- }- ],- "completed_at": "2026-06-24T10:01:12Z",- "metrics": { "total_tokens": 2451, "total_cost_in_usd": 0.011 }- }-}-```--## Model output--### `model.message`--An assistant message — text content and/or tool calls. On a live stream the base event arrives first and fills in via deltas; the merged event carries:--| Field | Description |-| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `content` | Assistant text (may be empty when the message is only tool calls). |-| `tool_calls` | Tool invocations, each with an `id` and `function` (`name`, `arguments`). |-| `finish_reason` | Why generation stopped (`stop`, `tool_calls`, ...), `null` mid-stream. |-| `usage` | Token usage for this model call: `input_tokens`, `output_tokens`, optional cache counters, and `input_tokens_breakdown` (`harness`, `skills`, `instructions`, `tool_definitions`, `messages`). |--### `model.message.delta`--An incremental fragment of a `model.message` — text and/or tool-call chunks. All deltas share the base event's `id`; append `content` chunks and merge tool-call fragments by index. The most frequent event on a live stream. Not present when listing persisted events.--## Tool activity--### `tool.response`--The result of a tool the harness executed, linked to its call by `tool_call_id`:--```json-{- "type": "tool.response",- "id": "01jc...",- "thread_id": "main",- "tool_call_id": "call-get-order-01",- "content": "{\"order_id\":\"ORD-2031\",\"status\":\"shipped\",\"total\":1240.0}",- "created_at": "2026-06-24T10:00:04Z"-}-```--### `tool.approval_required`--A tool call needs [human approval](/create-agent/overview#whats-in-an-agent) before it can run. The turn ends after this event; resume with a `user.tool_approval` input.--| Field | Description |-| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |-| `tool_calls` | Pending calls: each `{ id, source_event_id }`, where `source_event_id` points at the `model.message` that contains the call's name and arguments. |--### `tool.response_required`--A client-side tool (e.g. [`ask_user_question`](/create-agent/overview#whats-in-an-agent)) needs a result from your app. Same shape as `tool.approval_required`; resume with a `user.tool_response` input.--## Subagent threads--### `thread.created`--A [subagent](/key-features/subagents) started. Subsequent events with this `thread_id` belong to it.--| Field | Description |-| ------------ | -------------------------------------------------------------------------------------- |-| `thread_id` | The new thread's id. |-| `title` | Human-readable subagent name. |-| `parent` | `{ thread_id, tool_call_id }` — the spawning thread and tool call. |-| `agent_info` | `{ type: "dynamic", name, input }` — the generated instructions the subagent received. |--### `thread.done`--The subagent finished. `state` is `{ status: "done", output: <model.message> }` or `{ status: "error", error, output? }`. Does not close the turn stream — the root agent continues.--## Environment events--### `mcp.initialize`--MCP server connections were initialized for a thread. `mcp_servers` lists each server: `{ id, name, session_id?, transport_type? }` (`streamable-http` or `sse`).--### `mcp.auth_required`--One or more MCP servers need [OAuth authorization](/mcp-servers#in-chat-authentication) before the agent can proceed. `mcp_servers` lists `{ id, name, auth_url }` — send the user to `auth_url`, then start the next turn. The turn ends after this event.--### `sandbox.created`--A [sandbox](/sandbox) was provisioned, carrying its `sandbox_id`. Emitted once per session — subsequent turns reuse the same sandbox and emit no new event.--## User input events--These are not streamed — they are the input items **you send** when creating a turn, listed here for completeness:--| Type | Fields | Purpose |-| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |-| `user.message` | `content` — string, or array of `{ type: "text", text }` / `{ type: "file", name, data }` parts (files as `data:<mime>;base64,...` URIs) | A user message. |-| `user.tool_approval` | `thread_id`, `tool_call_id`, `approval` — `{ status: "allow" }` or `{ status: "deny", reason? }` | Decision for a paused tool call. |-| `user.tool_response` | `thread_id`, `tool_call_id`, `content` | Answer for a paused client-side tool call. |--A turn's `input` cannot mix `user.message` items with approval or tool-response items.diff --git a/docs/api/use-agent.mdx b/docs/api/use-agent.mdxindex c045efdb0..41eb2d0c9 100644--- a/docs/api/use-agent.mdx+++ b/docs/api/use-agent.mdx@@ -4,7 +4,7 @@ sidebarTitle: 'Use an agent'description: 'Run a saved agent with the TypeScript SDK: a complete example, then recipes for streaming, approvals, questions, threads, and reconnects.'----The recipe book for running an agent with [`@truefoundry/trueforge-sdk`](https://www.npmjs.com/package/@truefoundry/trueforge-sdk). For the mental model (Agent → Session → Turn → Event → Delta), start with [SDK Overview](/api/overview); for every event field, see [Turn events](/api/turn-events).+The recipe book for running an agent with [`@truefoundry/trueforge-sdk`](https://www.npmjs.com/package/@truefoundry/trueforge-sdk). New here? Install and stream your first turn in the [SDK Quickstart](/api/quickstart) first. For the mental model (Agent → Session → Turn → Event → Delta), see [Concepts](/api/overview); for every event field, see the [turn events reference](#turn-events-reference) at the bottom of this page.<Note>Prerequisite: a named agent in the registry, or an inline [agent spec](/create-agent/overview#create-an-agent-via-the-api) you pass when creating the session. The examples below run the **`web-research-brief`** agent from the [Quickstart](/quickstart); build it there first, or swap in your own agent name / inline spec.@@ -14,11 +14,11 @@ Every snippet is self-contained and runnable. They all use the `client` from [In## Install and connect-```bash+```bash wrapnpm i @truefoundry/trueforge-sdk```-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -28,13 +28,13 @@ const client = new TrueForge({});```-Point `baseUrl` at your running TrueForge server; `http://localhost:8790` is the Quickstart default. When [OIDC login](/authentication/overview) is enabled, pass `token` (an ID token from your IdP; see [Call an authenticated API](/api/overview#call-an-authenticated-api)). When login is off, omit it.+Point `baseUrl` at your running TrueForge server; `http://localhost:8790` is the Quickstart default. When [OIDC login](/authentication/overview) is enabled, pass `token` (an ID token from your IdP; see [Get a token and connect](/api/quickstart#get-a-token-and-connect)). When login is off, omit it.## A complete example-The [SDK Overview](/api/overview) explains the concepts with a conceptual `support-bot`; here is a real agent you can run. In the [Quickstart](/quickstart) you built **`web-research-brief`**, an agent with Exa web search and the web-artifacts-builder skill. Here it is from the SDK: open a session on that agent, stream one research turn, and print the brief as it arrives. It fans out to [subagents](/key-features/subagents), so you'll see their threads in the same stream. It has no approval gate, so it runs end to end without pausing; for the approval and question pauses, see [Handle pauses](#handle-pauses).+The [Concepts](/api/overview) page explains the model with a conceptual `support-bot`; here is a real agent you can run. In the [Quickstart](/quickstart) you built **`web-research-brief`**, an agent with Exa web search and the web-artifacts-builder skill. Here it is from the SDK: open a session on that agent, stream one research turn, and print the brief as it arrives. It fans out to [subagents](/key-features/subagents), so you'll see their threads in the same stream. It has no approval gate, so it runs end to end without pausing; for the approval and question pauses, see [Handle pauses](#handle-pauses).-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -96,7 +96,7 @@ stateDiagram-v2### Open a session-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790' });@@ -119,7 +119,7 @@ const { data: inlineSession } = await client.sessions.create({Newest-first; filter with `agentId`. The returned `Page` is an async iterable and auto-paginates.-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790' });@@ -139,11 +139,11 @@ Creating a new turn in a session automatically cancels any turn still running in### Create and stream a turn-`createTurnStream` returns a stream of [turn events](/api/turn-events). `stream.withMetadata()` yields `{ data, id }`, where `data` is the parsed event and `id` is the per-stream sequence number used to [resume after a disconnect](#resume-a-stream). The stream opens with `turn.created` and closes with `turn.done`; read the terminal result from `turn.done.state`.+`createTurnStream` returns a stream of [turn events](#turn-events-reference). `stream.withMetadata()` yields `{ data, id }`, where `data` is the parsed event and `id` is the per-stream sequence number used to [resume after a disconnect](#resume-a-stream). The stream opens with `turn.created` and closes with `turn.done`; read the terminal result from `turn.done.state`.Keep an **`id`-keyed event index**. Model output streams as an empty `model.message` base followed by `model.message.delta` fragments that share the base's `id`; store each non-delta event under its `id`, and merge each delta into the base with `isEventDelta` / `mergeEventDelta`. (Deltas appear only while streaming; [`listTurnEvents`](#replay-a-finished-turn) returns them already merged.) The pause handlers below reuse this index to look up the `model.message` that emitted a tool call.-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -184,7 +184,7 @@ Turn `input` accepts three item types (a single turn can't mix a `user.message`If you don't need live events, `sessions.createTurn` (`stream: false`) returns immediately with `state.status: "running"` and runs in the background. Poll `getTurn` until the status is terminal (`done`, `cancelled`, `error`).-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790' });@@ -206,7 +206,7 @@ console.log(turn.state); // done → state.output / required_actions; else reasoOldest-first; each turn exposes its `input` and `state`. A `done` turn's `state.requiredActions` lists any pauses it surfaced.-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790' });@@ -223,7 +223,7 @@ for await (const turn of await client.sessions.listTurns('sess-abc123')) {A `user.message`'s `content` can be an array of parts: text plus one or more files as [data URIs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) (`data:<mime>;base64,<payload>`).-```typescript+```typescript wrapimport { readFileSync } from 'node:fs';import { TrueForge } from '@truefoundry/trueforge-sdk';@@ -257,7 +257,7 @@ Whether a file is understood depends on the agent's model, so send images only t`sessions.cancel(sessionId)` stops the running turn: it aborts the in-flight model request, waits for running MCP tool calls to finish, and force-stops any sandbox the turn provisioned. It's idempotent, and the backend closes the SSE stream gracefully (a terminal `turn.done`, then it ends, so don't `break`). Continue by creating a new turn, which chains on the cancelled turn's history.-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -279,7 +279,7 @@ for await (const { data: event } of stream.withMetadata()) {A turn ends **paused** when it needs something from you. Each pause populates `turn.done.state.requiredActions`; you resume by creating a **new turn** with the matching response item(s). A single turn can surface more than one pending item (e.g. parallel threads each hit a gate), so collect them all.-For approvals and questions, each pending ref carries the `sourceEventId` of the [`model.message`](/api/turn-events#model-message) that made the call. Look it up in the [event index](#create-and-stream-a-turn) to read the tool's name and arguments.+For approvals and questions, each pending ref carries the `sourceEventId` of the [`model.message`](#model-message) that made the call. Look it up in the [event index](#create-and-stream-a-turn) to read the tool's name and arguments.<Note>`web-research-brief` won't pause on its own; it has no gated tool or clarifying-question step. The snippets below are **illustrative**: point them at an agent that has a `require_approval_for_tools` tool, uses `ask_user_question`, or connects to an MCP server needing OAuth.@@ -287,9 +287,9 @@ For approvals and questions, each pending ref carries the `sourceEventId` of the### Tool approvals-A gated tool ([human approval](/create-agent/overview#whats-in-an-agent)) emits [`tool.approval_required`](/api/turn-events#tool-approval-required). Collect the pending events while streaming, then resume with one `user.tool_approval` per pending call, either allowing it or denying it with a reason.+A gated tool ([human approval](/create-agent/overview#whats-in-an-agent)) emits [`tool.approval_required`](#tool-approval-required). Collect the pending events while streaming, then resume with one `user.tool_approval` per pending call, either allowing it or denying it with a reason.-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -337,9 +337,9 @@ for await (const { data: event } of resume.withMetadata()) console.log(event.typ### Agent questions-When the agent uses the built-in [`ask_user_question`](/create-agent/overview#whats-in-an-agent) tool, it emits [`tool.response_required`](/api/turn-events#tool-response-required); the pending call's `arguments` carry the `question` and `options`. Resume with one `user.tool_response` per pending call.+When the agent uses the built-in [`ask_user_question`](/create-agent/overview#whats-in-an-agent) tool, it emits [`tool.response_required`](#tool-response-required); the pending call's `arguments` carry the `question` and `options`. Resume with one `user.tool_response` per pending call.-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -389,13 +389,13 @@ for await (const { data: event } of resume.withMetadata()) console.log(event.typ### MCP outbound auth-When a tool needs a server's OAuth, the turn ends with [`mcp.auth_required`](/api/turn-events#mcp-auth-required), listing each server and its `authUrl`. Send the user there, then resume. See [In-chat authentication](/mcp-servers#in-chat-authentication).+When a tool needs a server's OAuth, the turn ends with [`mcp.auth_required`](#mcp-auth-required), listing each server and its `authUrl`. Send the user there, then resume. See [In-chat authentication](/mcp-servers#in-chat-authentication).<Note>After `mcp.auth_required`, the resuming turn must **not** include a `user.message`; resume with empty `input` (or omit it).</Note>-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -430,7 +430,7 @@ for await (const { data: event } of resume.withMetadata()) console.log(event.typIf you lose the `createTurnStream` connection (e.g. a process restart), persist `session.id`, `turnId`, and `lastSequenceNumber`. To resume: call `getTurn` → if still `running`, reconnect with `subscribeToTurn` and `afterSequenceNumber` to skip events you already saw; if finished, rebuild from `listTurnEvents`.-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -492,8 +492,8 @@ if (turn.state.status === 'running') {A turn stream interleaves the root agent and any parallel [subagents](/key-features/subagents), exactly what the [complete example](#a-complete-example) above does. Every event carries a `threadId`:- `"main"`: the root agent.-- A unique id: a subagent thread. [`thread.created`](/api/turn-events#thread-created) and [`thread.done`](/api/turn-events#thread-done) bracket its lifecycle.-- `null`: a turn-level event, such as [`turn.created`](/api/turn-events#turn-created), [`turn.done`](/api/turn-events#turn-done), [`sandbox.created`](/api/turn-events#sandbox-created), and [`mcp.auth_required`](/api/turn-events#mcp-auth-required).+- A unique id: a subagent thread. [`thread.created`](#thread-created) and [`thread.done`](#thread-done) bracket its lifecycle.+- `null`: a turn-level event, such as [`turn.created`](#turn-created), [`turn.done`](#turn-done), [`sandbox.created`](#sandbox-created), and [`mcp.auth_required`](#mcp-auth-required).Keep a **per-thread** index (`Map<threadId, Map<id, event>>`) and merge deltas within the matching thread's bucket.@@ -516,7 +516,7 @@ sequenceDiagramMain-->>Client: model.message + deltas```-```typescript+```typescript wrapimport { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from '@truefoundry/trueforge-sdk';const client = new TrueForge({@@ -553,13 +553,13 @@ for await (const { data: event } of stream.withMetadata()) {### Replay a finished turn-`sessions.listTurnEvents()` yields a finished turn's [events](/api/turn-events) in order (auto-paginates; `order: "asc"` default, or `"desc"`). Events are **already merged**, so you can use each one directly.+`sessions.listTurnEvents()` yields a finished turn's [events](#turn-events-reference) in order (auto-paginates; `order: "asc"` default, or `"desc"`). Events are **already merged**, so you can use each one directly.<Note>Only available for completed turns; a running turn has no stored log yet, so stream it with `createTurnStream` or `subscribeToTurn` instead.</Note>-```typescript+```typescript wrapimport { TrueForge } from '@truefoundry/trueforge-sdk';const client = new TrueForge({ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790' });@@ -571,3 +571,156 @@ for await (const turn of await client.sessions.listTurns('sess-abc123')) {}}```++## Turn events reference++Field-level schemas for every event streamed while a turn runs. The recipes above link here for the exact shape of each event they handle.++<Note>+ Field names in this reference use the HTTP/JSON wire format (snake_case, e.g. `turn_id`, `source_event_id`). The TypeScript SDK returns the same fields camelCased (`turnId`, `sourceEventId`) — so a field you see here maps directly to its camelCase form in SDK code.+</Note>++Every event carries:++| Field | Description |+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `type` | The event type — one of the types below. |+| `id` | Unique event id (monotonic ULID — sortable by creation order). |+| `created_at` | ISO 8601 timestamp. |+| `thread_id` | Which execution thread emitted it: `"main"` for the root agent, a generated id for [subagents](/key-features/subagents), or `null` for run-level events (`turn.*`, `sandbox.created`, `mcp.auth_required`). |++A stream always opens with `turn.created` and closes with `turn.done`. When you list persisted session events afterwards, you get the same events with deltas pre-merged into their `model.message`.++### Lifecycle events++#### `turn.created`++First event on every stream.++| Field | Description |+| ------------------ | --------------------------------------------------------- |+| `turn_id` | Id of this turn. |+| `previous_turn_id` | The turn this one chains from, or `null` for a root turn. |+| `input` | The turn's input items, echoed back. |+| `state` | `{ "status": "running" }` |++#### `turn.done`++Last event on every stream. `state.status` is one of:++- **`done`** — carries `output` (the final `model.message`, or `null` when the turn ended paused), `required_actions` (pending `tool.approval_required` / `tool.response_required` / `mcp.auth_required` events, empty when none), `completed_at`, and optional `metrics`.+- **`cancelled`** — carries a `reason`: `client-cancelled`, `server-execution-timeout`, `cancelled-for-next-turn`, or `abandoned`.+- **`error`** — carries a `message`.++`metrics`, when present, aggregates the whole turn: `total_input_tokens`, `total_output_tokens`, `total_tokens`, `total_cache_read_tokens`, `total_cache_write_tokens`, `total_reasoning_tokens`, and `total_cost_in_usd`.++```json turn.done — paused for approval wrap+{+ "type": "turn.done",+ "id": "01jc...",+ "thread_id": null,+ "created_at": "2026-06-24T10:01:12Z",+ "state": {+ "status": "done",+ "output": null,+ "required_actions": [+ {+ "type": "tool.approval_required",+ "thread_id": "main",+ "tool_calls": [{ "id": "call-refund-01", "source_event_id": "msg-b2" }]+ }+ ],+ "completed_at": "2026-06-24T10:01:12Z",+ "metrics": { "total_tokens": 2451, "total_cost_in_usd": 0.011 }+ }+}+```++### Model output++#### `model.message`++An assistant message — text content and/or tool calls. On a live stream the base event arrives first and fills in via deltas; the merged event carries:++| Field | Description |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `content` | Assistant text (may be empty when the message is only tool calls). |+| `tool_calls` | Tool invocations, each with an `id` and `function` (`name`, `arguments`). |+| `finish_reason` | Why generation stopped (`stop`, `tool_calls`, ...), `null` mid-stream. |+| `usage` | Token usage for this model call: `input_tokens`, `output_tokens`, optional cache counters, and `input_tokens_breakdown` (`harness`, `skills`, `instructions`, `tool_definitions`, `messages`). |++#### `model.message.delta`++An incremental fragment of a `model.message` — text and/or tool-call chunks. All deltas share the base event's `id`; append `content` chunks and merge tool-call fragments by index. The most frequent event on a live stream. Not present when listing persisted events.++### Tool activity++#### `tool.response`++The result of a tool the harness executed, linked to its call by `tool_call_id`:++```json wrap+{+ "type": "tool.response",+ "id": "01jc...",+ "thread_id": "main",+ "tool_call_id": "call-get-order-01",+ "content": "{\"order_id\":\"ORD-2031\",\"status\":\"shipped\",\"total\":1240.0}",+ "created_at": "2026-06-24T10:00:04Z"+}+```++#### `tool.approval_required`++A tool call needs [human approval](/create-agent/overview#whats-in-an-agent) before it can run. The turn ends after this event; resume with a `user.tool_approval` input.++| Field | Description |+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |+| `tool_calls` | Pending calls: each `{ id, source_event_id }`, where `source_event_id` points at the `model.message` that contains the call's name and arguments. |++#### `tool.response_required`++A client-side tool (e.g. [`ask_user_question`](/create-agent/overview#whats-in-an-agent)) needs a result from your app. Same shape as `tool.approval_required`; resume with a `user.tool_response` input.++### Subagent thread events++#### `thread.created`++A [subagent](/key-features/subagents) started. Subsequent events with this `thread_id` belong to it.++| Field | Description |+| ------------ | -------------------------------------------------------------------------------------- |+| `thread_id` | The new thread's id. |+| `title` | Human-readable subagent name. |+| `parent` | `{ thread_id, tool_call_id }` — the spawning thread and tool call. |+| `agent_info` | `{ type: "dynamic", name, input }` — the generated instructions the subagent received. |++#### `thread.done`++The subagent finished. `state` is `{ status: "done", output: <model.message> }` or `{ status: "error", error, output? }`. Does not close the turn stream — the root agent continues.++### Environment events++#### `mcp.initialize`++MCP server connections were initialized for a thread. `mcp_servers` lists each server: `{ id, name, session_id?, transport_type? }` (`streamable-http` or `sse`).++#### `mcp.auth_required`++One or more MCP servers need [OAuth authorization](/mcp-servers#in-chat-authentication) before the agent can proceed. `mcp_servers` lists `{ id, name, auth_url }` — send the user to `auth_url`, then start the next turn. The turn ends after this event.++#### `sandbox.created`++A [sandbox](/sandbox) was provisioned, carrying its `sandbox_id`. Emitted once per session — subsequent turns reuse the same sandbox and emit no new event.++### User input events++These are not streamed — they are the input items **you send** when creating a turn, listed here for completeness:++| Type | Fields | Purpose |+| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `user.message` | `content` — string, or array of `{ type: "text", text }` / `{ type: "file", name, data }` parts (files as `data:<mime>;base64,...` URIs) | A user message. |+| `user.tool_approval` | `thread_id`, `tool_call_id`, `approval` — `{ status: "allow" }` or `{ status: "deny", reason? }` | Decision for a paused tool call. |+| `user.tool_response` | `thread_id`, `tool_call_id`, `content` | Answer for a paused client-side tool call. |++A turn's `input` cannot mix `user.message` items with approval or tool-response items.diff --git a/docs/authentication/overview.mdx b/docs/authentication/overview.mdxindex 9ee976f8a..294e6d18d 100644--- a/docs/authentication/overview.mdx+++ b/docs/authentication/overview.mdx@@ -205,7 +205,7 @@ Each signed-in person maps to exactly one role, decided by the role claim in the- **The [Agent Library](/agent-library) is shared** — agents created by anyone are visible to everyone on the instance.</Note>-To call the HTTP API or SDK against a server with login enabled, pass an ID token — see [Call an authenticated API](/api/overview#call-an-authenticated-api).+To call the HTTP API or SDK against a server with login enabled, pass an ID token — see [Get a token and connect](/api/quickstart#get-a-token-and-connect).## Troubleshooting@@ -216,7 +216,7 @@ To call the HTTP API or SDK against a server with login enabled, pass an ID toke| `invalid client secret` | App is SPA/public — recreate it as a **Web** (confidential) app with a client secret || Blank authorize screen when requesting `groups` | Custom Authorization Server is missing the `groups` scope and/or ID-token groups claim (Okta) || Login works but everyone is `role: "user"` | Groups/roles claim missing from the ID token, wrong claim name, or admin value mismatch (case-sensitive) |-| SDK returns `401` | OIDC is on and the request has no [ID token](/api/overview#call-an-authenticated-api) or session cookie |+| SDK returns `401` | OIDC is on and the request has no [ID token](/api/quickstart#get-a-token-and-connect) or session cookie |## Security checklistdiff --git a/docs/create-agent/overview.mdx b/docs/create-agent/overview.mdxindex 1db366451..c24b08cda 100644--- a/docs/create-agent/overview.mdx+++ b/docs/create-agent/overview.mdx@@ -159,7 +159,78 @@ Options available in the UI today: **model** (selection), **instructions**, **co## Create an agent via the API-The [SDK](/api/overview) exposes **every** option through the agent spec. Save the spec as a named agent and reference it by name, or pass it inline when you create a session. All fields are `snake_case`, and every field except `model` has a default.+The [SDK](/api/overview) and HTTP API expose **every** option through the **agent spec**. You either save the spec as a named, reusable agent and reference it by name, or pass it inline when you open a session. All fields are `snake_case`, and every field except `model` has a default.++### Save and run an agent++<Steps>+ <Step title="Connect the client">+ ```typescript+ import { TrueForge } from '@truefoundry/trueforge-sdk';++ const client = new TrueForge({+ baseUrl: process.env.TRUEFORGE_BASE_URL ?? 'http://localhost:8790',+ // token: process.env.TRUEFORGE_TOKEN, // ID token when OIDC login is enabled+ });+ ```++ When [OIDC login](/authentication/overview) is on, pass an ID token; see [Get a token and connect](/api/quickstart#get-a-token-and-connect). When login is off, omit `token`.+ </Step>++ <Step title="Save the spec as a named agent">+ `agents.create` (`POST /api/v1/agents`) stores the spec under a unique `name` and returns the agent with its server-generated `id`. The name is immutable and must be unique — a duplicate returns `409`.++ ```typescript+ const { data: agent } = await client.agents.create({+ name: 'support-bot',+ manifest: {+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'You help customers with orders. Always confirm before processing refunds.',+ },+ });+ ```+ </Step>++ <Step title="Open a session and run turns">+ Reference the saved agent by name, then stream a turn. See [Use an agent](/api/use-agent) for the full loop, including approvals and questions.++ ```typescript+ const { data: session } = await client.sessions.create({ agent: { name: 'support-bot' } });++ const stream = await client.sessions.createTurnStream(session.id, {+ input: [{ type: 'user.message', content: 'Where is order ORD-2031?' }],+ });+ for await (const { data: event } of stream.withMetadata()) console.log(event.type);+ ```+ </Step>+</Steps>++**Skip saving** — pass the spec inline when you create the session, and nothing is persisted to the registry:++```typescript+const { data: session } = await client.sessions.create({+ agent: {+ spec: {+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'You are a concise research assistant.',+ },+ },+});+```++**Manage saved agents** with the rest of the `agents` methods:++| Method | Endpoint | What it does |+| ---------------- | ------------------------------- | ---------------------------------------------------------------- |+| `agents.create` | `POST /api/v1/agents` | Save a new agent under a unique `name`; returns its `id`. |+| `agents.list` | `GET /api/v1/agents` | List all configured agents. |+| `agents.get` | `GET /api/v1/agents/{agent_id}` | Fetch one agent by its immutable `id`. |+| `agents.update` | `PUT /api/v1/agents/{agent_id}` | Replace an existing agent's manifest (the `name` can't change). |+| `agents.delete` | `DELETE /api/v1/agents/{agent_id}` | Delete an agent (idempotent). |++### The full agent spec++The `manifest` you save (or the inline `spec`) is the agent spec below — every field, with defaults.```json A complete example{diff --git a/docs/docs.json b/docs/docs.jsonindex be97ae520..d640e374a 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -2,6 +2,7 @@"$schema": "https://mintlify.com","theme": "mint","redirects": [+ { "source": "/api/turn-events", "destination": "/api/use-agent#turn-events-reference" },{ "source": "/create-agent/tool-approval", "destination": "/create-agent/overview#whats-in-an-agent" },{ "source": "/create-agent/ask-user-questions", "destination": "/create-agent/overview#whats-in-an-agent" },{ "source": "/create-agent/generative-ui", "destination": "/create-agent/overview#whats-in-an-agent" },@@ -66,7 +67,7 @@},{"group": "SDK",- "pages": ["api/overview", "api/use-agent", "api/turn-events"]+ "pages": ["api/quickstart", "api/overview", "api/use-agent"]},{"group": "UI Chat",@@ -115,8 +116,9 @@"navbar": {"links": [{- "type": "github",- "href": "https://github.com/truefoundry/trueforge"+ "label": "GitHub",+ "href": "https://github.com/truefoundry/trueforge",+ "icon": "github"}],"primary": {diff --git a/docs/introduction.mdx b/docs/introduction.mdxindex 09ec35fea..6c8a06cd0 100644--- a/docs/introduction.mdx+++ b/docs/introduction.mdx@@ -25,33 +25,20 @@ TrueForge is an **open-source agent harness** with three parts: a **core server*<img src="/images/chat-ui.png" alt="The TrueForge chat UI showing an agent response with the agent-steps panel expanded — reasoning, Exa tool calls, and a subagent" /></Frame>-### Key Components--```mermaid-flowchart LR- ui[Chat UI<br/><small>@truefoundry/trueforge-ui</small>]- code[Your code<br/><small>@truefoundry/trueforge-core</small>]- subgraph server [TrueForge server]- api[HTTP API]- loop[Agent loop]- api --> loop- end- db[(SQLite / Postgres)]- subgraph byo [Bring your own]- llm[Model providers]- mcp[MCP servers]- sandbox[Sandbox provider]- end-- ui --> api- code --> api- loop --> db- loop --> llm- loop --> mcp- loop --> sandbox-- style byo stroke-dasharray: 6 4-```+### Key Components++<Frame caption="Chat UI and SDK connect to the TrueForge server HTTP API and agent loop, which talks to SQLite or Postgres and bring-your-own models, MCP servers, and sandbox">+ <img+ className="block dark:hidden"+ src="/assets/architecture-light.svg"+ alt="TrueForge architecture: Chat UI and SDK connect to the TrueForge server HTTP API and agent loop, which talks to SQLite or Postgres and bring-your-own models, MCP servers, and sandbox"+ />+ <img+ className="hidden dark:block"+ src="/assets/architecture-dark.svg"+ alt="TrueForge architecture: Chat UI and SDK connect to the TrueForge server HTTP API and agent loop, which talks to SQLite or Postgres and bring-your-own models, MCP servers, and sandbox"+ />+</Frame>### TrueForge server@@ -77,7 +64,7 @@ Everything the server does is exposed as an API, so anything you see in the UI y- REST + Server-Sent Events, with an OpenAPI spec and interactive docs at `/api/v1/docs`- A TypeScript SDK (`@truefoundry/trueforge-core`) to create and call agents from your own code-See the [SDK overview](/api/overview).+See the [SDK Quickstart](/api/quickstart).### Chat UI + UI SDK@@ -124,7 +111,7 @@ The agent features are identical in both modes — only the backend around the s<Card title="Setup Login" icon="lock" href="/authentication/overview">Optional OIDC for shared deployments — admin vs user, with a local no-auth default.</Card>- <Card title="SDK" icon="code" href="/api/overview">+ <Card title="SDK" icon="code" href="/api/quickstart">HTTP API and TypeScript SDK to create sessions, stream turns, and automate agents.</Card><Card title="Chat UI" icon="palette" href="/chat-ui">diff --git a/docs/quickstart.mdx b/docs/quickstart.mdxindex bdb2d642b..ab6c6fd49 100644--- a/docs/quickstart.mdx+++ b/docs/quickstart.mdx@@ -236,7 +236,7 @@ With TrueForge open in your browser, this walkthrough takes you from an empty wo<Card title="Harness Capabilities" icon="layer-group" href="/key-features/overview">Subagents, deferred tools, code mode, compaction, and more.</Card>- <Card title="SDK" icon="code" href="/api/overview">+ <Card title="SDK" icon="code" href="/api/quickstart">Sessions, turns, events, and the agent spec.</Card></CardGroup>