Skip to content
Python

docs: simplify Harness SDK onboarding and add architecture visual

Rohit Pea495cd09280
diff --git a/README.md b/README.md
index ddb8da51..b792207a 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
<h1 align="center">OpenWorker</h1>
-<p align="center"><strong><a href="https://openworker.com">openworker.com</a></strong> · <a href="#download">Download</a> · <a href="https://github.com/andrewyng/openworker/issues">Issues</a></p>
+<p align="center"><strong><a href="https://openworker.com">openworker.com</a></strong> · <a href="#download">Download</a> · <a href="#build-with-the-openworker-harness-sdk">Harness SDK</a> · <a href="https://github.com/andrewyng/openworker/issues">Issues</a></p>
<p align="center"><a href="https://trendshift.io/repositories/91434?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-91434" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/91434/daily" alt="andrewyng%2Fopenworker | Trendshift" width="250" height="55"/></a></p>
@@ -12,11 +12,27 @@ It runs on your machine and doesn't lock you into any model: bring your own API
[![How OpenWorker works](docs/assets/how-it-works.png)](https://openworker.com)
-## Download
+## Build with the OpenWorker Harness SDK
+
+**Your app, powered by agents.** Build a desktop app, web app or local utility
+with your own interface and tools. The Harness SDK manages model calls, approvals,
+streaming and durable sessions, so you can focus on the product experience.
-Building your own agentic application? The [OpenWorker Harness](harness/README.md)
-release-candidate source includes Rust and TypeScript SDKs, desktop starters and
-server deployment references. It is separate from the Desktop app's Python engine.
+Use the TypeScript SDK from npm, or embed the Rust engine in your application.
+Connect cloud or local models, add sub-agents and teams, isolate configured tools
+with NVIDIA OpenShell, and inspect runs through optional traces and telemetry.
+The Harness SDK is a separate Rust engine from the Desktop app's Python engine.
+
+```sh
+npm install --save-exact @openworkerai/[email protected]
+```
+
+[**Explore the Harness SDK →**](harness/README.md) ·
+[Desktop guide](docs/harness/guides/desktop.md) ·
+[Web guide](docs/harness/guides/server.md) ·
+[Build with Codex or Claude Code](skills/README.md)
+
+## Download
[**⬇ macOS (Apple Silicon)**](https://download.openworker.com/mac)
<sub>macOS 12+ · signed & notarized · auto-updates</sub>
@@ -139,6 +155,7 @@ Tests: `.venv/bin/pytest` (server), `npm test` and `npm run e2e` in `surfaces/gu
| Directory | What's in it |
|---|---|
| `coworker/` | Python backend - agent engine, model providers, connectors, MCP client, memory, automations |
+| `harness/` | Rust agent runtime, Rust/TypeScript SDKs, service and SDK examples |
| `surfaces/gui/` | Desktop app - React UI + Tauri shell that supervises the server |
| `stt/` | Speech-to-text sidecar (Rust) for voice input |
| `packaging/` | Installer builds (macOS DMG, Windows), auto-update manifest, dev bootstrap |
diff --git a/docs/harness/assets/architecture.svg b/docs/harness/assets/architecture.svg
new file mode 100644
index 00000000..7438d407
--- /dev/null
+++ b/docs/harness/assets/architecture.svg
@@ -0,0 +1,53 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1100" height="620" viewBox="0 0 1100 620" role="img" aria-labelledby="title desc">
+ <title id="title">OpenWorker Harness architecture</title>
+ <desc id="desc">Your desktop or web application uses TypeScript or Rust to control one Rust agent runtime. The harness manages model calls, durable sessions, tools and approvals. It connects to cloud or local models. Application callbacks keep app privileges; configured file and shell tools can run inside NVIDIA OpenShell, while the agent loop remains outside that sandbox.</desc>
+ <defs>
+ <marker id="arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
+ <path d="M1 1 7 4 1 7" fill="none" stroke="#85909e" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+ </marker>
+ </defs>
+ <rect width="1100" height="620" rx="24" fill="#f5f6f8"/>
+ <g fill="none" stroke="#a3acb8" stroke-width="1.5" marker-end="url(#arrow)">
+ <path d="M285 126V155"/>
+ <path d="M815 126V155"/>
+ <path d="M285 228V263"/>
+ <path d="M815 228V263"/>
+ <path d="M255 404V445"/>
+ <path d="M785 404V445"/>
+ </g>
+ <g font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif" fill="#17202b">
+ <rect x="40" y="36" width="1020" height="90" rx="16" fill="#fff" stroke="#dce1e8"/>
+ <text x="68" y="75" font-size="23" font-weight="600">Your desktop or web app</text>
+ <text x="68" y="103" font-size="16" fill="#586474">Your interface · authentication · product workflow</text>
+
+ <rect x="40" y="156" width="490" height="72" rx="14" fill="#fff" stroke="#dce1e8"/>
+ <text x="68" y="185" font-size="19" font-weight="600">TypeScript SDK</text>
+ <text x="68" y="209" font-size="15" fill="#586474">Node.js / Electron main / your server · managed Rust child</text>
+ <rect x="570" y="156" width="490" height="72" rx="14" fill="#fff" stroke="#dce1e8"/>
+ <text x="598" y="185" font-size="19" font-weight="600">Rust SDK</text>
+ <text x="598" y="209" font-size="15" fill="#586474">Embedded in-process · optional managed child</text>
+
+ <rect x="40" y="264" width="1020" height="140" rx="16" fill="#202b3a"/>
+ <text x="68" y="304" font-size="24" font-weight="600" fill="#fff">OpenWorker Harness</text>
+ <text x="910" y="303" font-size="15" fill="#c0cad7">Rust runtime</text>
+ <text x="68" y="342" font-size="17" fill="#edf1f7">Model calls &amp; agent loop</text>
+ <text x="392" y="342" font-size="17" fill="#edf1f7">Durable sessions &amp; recovery</text>
+ <text x="730" y="342" font-size="17" fill="#edf1f7">Tools, approvals &amp; guardrails</text>
+ <text x="68" y="377" font-size="15" fill="#c0cad7">Optional: agent teams · memory · observability</text>
+
+ <rect x="40" y="446" width="430" height="124" rx="16" fill="#fff" stroke="#dce1e8"/>
+ <text x="68" y="479" font-size="20" font-weight="600">Cloud or local models</text>
+ <text x="68" y="511" font-size="15" fill="#586474">OpenAI · Anthropic · compatible endpoints</text>
+ <text x="68" y="537" font-size="15" fill="#586474">Ollama, vLLM or a Nemotron endpoint</text>
+
+ <rect x="500" y="446" width="560" height="124" rx="16" fill="#fff" stroke="#dce1e8"/>
+ <text x="528" y="478" font-size="20" font-weight="600">Tool execution</text>
+ <rect x="520" y="493" width="230" height="59" rx="10" fill="#f5f6f8"/>
+ <text x="536" y="517" font-size="16" font-weight="600">Application callbacks</text>
+ <text x="536" y="539" font-size="14" fill="#586474">Your app's privileges</text>
+ <rect x="766" y="493" width="274" height="59" rx="10" fill="#eef4ff" stroke="#c7d8f5"/>
+ <text x="782" y="517" font-size="16" font-weight="600" fill="#244c89">NVIDIA OpenShell</text>
+ <text x="782" y="539" font-size="14" fill="#42618b">Isolated file &amp; shell tools</text>
+ <text x="40" y="601" font-size="14" fill="#586474">OpenShell contains isolated tools. The agent loop stays in the trusted harness.</text>
+ </g>
+</svg>
diff --git a/docs/harness/guides/providers.md b/docs/harness/guides/providers.md
index a58031fc..93c865a5 100644
--- a/docs/harness/guides/providers.md
+++ b/docs/harness/guides/providers.md
@@ -18,6 +18,20 @@ environment-variable reference for server deployments; for desktop UI input,
pass `credentials: { apiKey, storage: "memory" }` and use your application's secret
store for persistence. Only choose SDK secure persistence on a supported platform.
+## Where credentials are read
+
+| Interface | What resolves an environment-key reference? |
+| --- | --- |
+| TypeScript `setModelProvider` / `modelProviders` | The Node process reads `apiKeyEnv` and sends the value over private stdio to the Rust child. |
+| Embedded Rust `Credentials::from_env` | The Rust application process reads its environment. |
+
+`inheritEnv` is unnecessary for the TypeScript provider convenience API. Use it
+only for variables that Rust or another child must resolve itself; avoid passing
+the whole environment. Neither SDK automatically loads env files. Memory-only
+credentials must be supplied when the application starts. Secure provider storage
+uses macOS Keychain or Windows DPAPI; on Linux choose memory-only credentials or
+server provisioning. Callback functions also need registration on app startup.
+
A custom proxy can supply short-lived bearer tokens through the provider-auth
callback interface and proactively rotate them. Authentication refresh does not
create another session or silently change the selected model.
diff --git a/docs/harness/guides/releases.md b/docs/harness/guides/releases.md
index 58441a6f..738b9969 100644
--- a/docs/harness/guides/releases.md
+++ b/docs/harness/guides/releases.md
@@ -1,9 +1,15 @@
# Versions and compatibility
-Keep the SDK and harness executable on the same version. During beta, pin a
+Use the native runtime version pinned by your SDK release. During beta, pin a
repository revision or an explicitly published release rather than following a
moving branch in a production application.
+The published TypeScript client **0.1.0-beta.4** is a documentation-only update
+using native runtime **0.1.0-beta.3**. npm installs that exact dependency; keep
+optional dependencies enabled. Executable code and API declarations are unchanged
+from client beta.3. The native compatibility check remains strict: a client package
+version is not permission to substitute an arbitrary runtime version.
+
## Install from a checkout
Source manifests are development packages. A version in a manifest does not mean
@@ -19,8 +25,8 @@ build the SDK and any ToolRunner/helper executable from the same revision.
## Upgrade an application
1. Back up durable state before changing versions.
-2. Update the SDK and native executable together; retain the previous application
- package for rollback planning.
+2. Install the runtime dependency selected by the SDK; update an explicit/custom
+ executable to that required version. Retain the previous app package for rollback.
3. Read the [storage migration instructions](guardrails.md#upgrade-an-existing-installation)
before restarting an application or service against existing state.
4. For services, drain workers and coordinate API/worker upgrades. Do not downgrade
@@ -35,7 +41,7 @@ executable automatically.
## Session and streaming API updates
The new turn options, history import, built-in tool controls and provider settings
-require rebuilding the native harness alongside the SDK. They are not enabled by
+require a native harness that advertises those capabilities. They are not enabled by
updating a TypeScript declaration file alone. Existing sessions and omitted
configuration keep their previous tool selection and per-call limits.
diff --git a/docs/harness/guides/sessions.md b/docs/harness/guides/sessions.md
index 0ddb2463..999d57c3 100644
--- a/docs/harness/guides/sessions.md
+++ b/docs/harness/guides/sessions.md
@@ -9,6 +9,20 @@ timers. On restart, reattach to the saved session rather than creating a replace
Reconnect/replay does not mean replaying side effects. If an action's outcome is
unknown, inspect its status before retrying it.
+## Agent identity and workspace
+
+Agent names identify persisted immutable definitions. Changing instructions,
+tools, approval mode or other definition fields requires a new name. Identical
+registration is idempotent; creating another session does not replace a definition.
+Keep old identities for their existing sessions. A fresh state directory is a
+separate development environment, not a migration of existing conversations.
+
+An explicit `workspace` selects the working directory. Omitting it normally
+allocates a private scratch workspace. `scratch: false` requires an explicit
+workspace; `scratch: true` cannot accompany one. Scratch does not promise automatic
+deletion. Keep state outside files available to tools, and enforce directory scope
+in app callbacks; a workspace is not an OS sandbox.
+
## Context and limits for each turn
Use `instructionAddendum` in TypeScript, or `TurnOptions.instruction_addendum` in
@@ -94,7 +108,7 @@ session/turn overrides are not yet exposed by the service-cluster REST client.
## Attach a file
-The source preview supports images, PDFs and UTF-8 files as ordered user-message
+The SDK supports images, PDFs and UTF-8 files as ordered user-message
content. See [Attachments](attachments.md) for the convenience and interleaved
forms, storage limits and guardrail behavior.
@@ -136,9 +150,31 @@ assembled request, including imported history, before the next model call.
## Approvals and questions
Render durable approval/question interruptions in your UI, then send the user's
-actual response. “Allow always” applies to the session. Auto-approval uses a
-reviewer; an inconclusive decision still asks the human. Bypass skips human approval
-but does not remove required guardrails or sandbox restrictions.
+actual response. Configure the decision path in the agent definition:
+
+| TypeScript mode | Behavior |
+| --- | --- |
+| `always` (default) | Requests a human decision unless a valid session grant covers the tool. |
+| `only` with a tool list | Requests approval for listed tools; ordinary unlisted tools receive application-policy approval. |
+| `auto` with `reviewerModel` | An explicit LLM reviews eligible calls: allow executes, deny returns a denial, uncertain requests human input. |
+| `never` | Bypasses approval review; hard security checks still apply. |
+
+Rust exposes `Approvals::Always`, `Only`, `auto(model)` and `Never`. Auto review
+can include read-only tools. Hard denials and valid session grants are checked
+first. Privileged child/type-creation operations have additional requirements;
+omission from an `only` list does not automatically exempt them.
+
+Use `once` when each mutation requires a new card. A `session` grant covers the
+entire tool, including different valid arguments, survives restart and does not
+override hard checks. Questions are separate from approval decisions. See the
+[complete streamed approval loop](streaming.md#streaming-with-tool-approvals).
+
+The typed `auto_approved` summary currently describes application-policy approval,
+not a model review verdict. Raw `interaction_required` / `interaction_resolved`
+events can include `data.review.verdict`, a safe `reason`, `origin` and nested
+`call.call_id`; handle absent/withheld content. A denied tool result tells the
+working model not to retry or evade the denial, but currently omits the reviewer's
+reason. The app can display an available safe journal reason itself.
A tool-free guide can disable optional tools, memory, planning and scheduling.
Auto-skip questions is a separate setting, not an authorization mode.
@@ -167,8 +203,8 @@ existing agent definitions and session schema digests across upgrades.
## Standalone sub-agents
-**Source preview:** this requires the matching feature runtime; it is not available
-in npm runtime 0.1.0-beta.2. An ordinary agent can let its model delegate work:
+Requires a runtime advertising `standalone_subagents`, available in native
+runtime 0.1.0-beta.3. An ordinary agent can let its model delegate work:
<!-- sdk-tabs -->
### TypeScript
diff --git a/docs/harness/guides/streaming.md b/docs/harness/guides/streaming.md
index 075fdac2..ba94a18e 100644
--- a/docs/harness/guides/streaming.md
+++ b/docs/harness/guides/streaming.md
@@ -123,3 +123,56 @@ Upstream response bodies, prompts, keys and arbitrary error messages are not
included in these diagnostics. Use the request ID with the provider when more
detail is needed. A retryable provider error does not authorize an application to
replay tool actions: retain the SDK's run reference and reconcile unknown outcomes.
+
+## Streaming with tool approvals
+
+Use one durable submission for the turn, including time spent waiting for approval.
+The UI shows the actual proposed tool and arguments; never invent an approval.
+
+### Stream, approve and continue the same turn
+
+This helper supplies the full loop. The app provides escaped-text rendering,
+activity UI and an approval card showing both `pending.tool` and
+`pending.arguments`.
+
+```typescript
+import { AttemptOutput, type Session, type RunEvent, type Interruption }
+ from '@openworkerai/harness-sdk';
+
+type Approval = Extract<Interruption, { kind: 'approval' }>;
+export async function streamWithApprovals(session: Session, text: string, ui: {
+ renderText(text: string): void;
+ renderActivity(event: RunEvent): void;
+ approve(proposal: Approval): Promise<boolean>;
+}) {
+ const display = new AttemptOutput();
+ let stream = (await session.send(text)).events();
+ while (true) {
+ for await (const event of stream) {
+ display.apply(event);
+ ui.renderText(display.text); // Replace; do not append the whole projection.
+ ui.renderActivity(event);
+ }
+ const result = await stream.result();
+ if (result.status !== 'interrupted') {
+ if (result.status === 'completed') ui.renderText(result.finalOutput ?? display.text);
+ else { display.interrupt(); ui.renderText(display.text); }
+ return result;
+ }
+ if (!result.interruptions.length) throw new Error('No pending interaction');
+ for (const pending of result.interruptions) {
+ if (pending.kind !== 'approval') return result; // Route questions/safety separately.
+ const allowed = await ui.approve(pending);
+ await session.respond(pending, { decision: allowed ? 'once' : 'deny' });
+ }
+ stream = await session.resumeStreamed(stream.checkpoint());
+ }
+}
+```
+
+Do not resend the user message to continue after approval: retain the submission
+and consumed cursors. Use `session.cancel()` for Stop. Closing an observer does not
+cancel execution or justify automatic approval. Persist the session reference
+and stream checkpoint for crash recovery, then reconcile pending interactions.
+For a non-streaming flow, `session.runWith(input, handler)` invokes a real app
+handler for interruptions; `{ defer: true }` leaves the decision pending.
diff --git a/docs/harness/guides/tools.md b/docs/harness/guides/tools.md
index ee65c69c..8fce4676 100644
--- a/docs/harness/guides/tools.md
+++ b/docs/harness/guides/tools.md
@@ -16,7 +16,78 @@ file, network or screen access.
Use the bundled coding tools for workspace files, search, patches, processes and
Git. Use the [tools SDK](../../../harness/tools-sdk/README.md) for native tools
-and the [TypeScript SDK](../../../harness/typescript-sdk/README.md) for app callbacks.
+and the app callback examples below.
+
+## Register an application callback
+
+Register tools before creating an agent, then select their qualified names in
+its definition. These helpers register one status tool; your application owns
+the UI. Add `app.show_status` to the agent's selected tools and use the
+[streamed approval loop](streaming.md#streaming-with-tool-approvals) for decisions.
+
+<!-- sdk-tabs -->
+### TypeScript
+
+```typescript
+import type { Harness } from '@openworkerai/harness-sdk';
+
+export async function registerStatusTool(harness: Harness, showStatus: (text: string) => void) {
+ await harness.registerTools({ namespace: 'app', tools: {
+ show_status: {
+ description: 'Display a status update in this app.',
+ inputSchema: { type: 'object', properties: { text: { type: 'string' } },
+ required: ['text'], additionalProperties: false },
+ execute: async (args, context) => {
+ context.signal.throwIfAborted();
+ await context.progress('Updating app');
+ if (typeof args.text !== 'string') throw new Error('Expected text');
+ showStatus(args.text); // Render as escaped text in a graphical UI.
+ return { displayed: true };
+ },
+ },
+ } });
+}
+```
+
+### Rust
+
+```rust
+use openworker_sdk::{Harness, Tool};
+use serde_json::json;
+
+pub async fn register_status_tool(harness: &Harness) -> openworker_sdk::Result<()> {
+ harness.register_tools("app", [Tool::new("show_status")
+ .description("Display a status update in this app.")
+ .input_schema(json!({"type":"object","properties":{"text":{"type":"string"}},
+ "required":["text"],"additionalProperties":false}))
+ .handler(|args, context| async move {
+ context.progress("Updating app", json!({})).await?;
+ println!("{}", args["text"].as_str().unwrap_or_default());
+ Ok(json!({"displayed":true}))
+ })]).await
+}
+```
+
+<!-- /sdk-tabs -->
+
+The Rust callback example uses `serde_json = "1"` in the app's dependencies.
+Callbacks use the application's privileges. For scoped filesystem operations,
+see the complete [file-organizer tools](../../../skills/openworker-harness-builder/assets/local-script/file-tools.mjs)
+and [Node example](../../../skills/openworker-harness-builder/references/local-script.md).
+
+## Tool names and directory scope
+
+Register/select `files.move_file`; the model-facing alias is `files__move_file`.
+Current events and approval requests can contain that alias. Use your registered
+mapping for UI labels and preserve original IDs in saved event data.
+
+`workspace` supplies a working directory and scope for supported built-in path
+checks/backend mounts. Arbitrary app callbacks can access everything their app can
+access. Each file handler must constrain both source and destination, reject
+traversal/absolute paths and handle symlinks. The bundled demo does this for an
+app-owned directory without concurrent untrusted writers. Path checks are not
+kernel isolation; use an isolated execution backend for hostile code. Configuring
+OpenShell does not move arbitrary Node callbacks into its sandbox.
For external services, keep endpoints and credentials in trusted registration
configuration. Guardrails may inspect selected arguments/results, and authorization
@@ -43,3 +114,41 @@ A provider response that reuses a call ID from retained model context is rejecte
before dispatching that new call. Earlier completed actions remain completed; a
failed later turn does not undo them. The correlation fields help your UI
preserve that distinction.
+
+Typed start/finish summaries omit arguments. They are supplied directly to the
+callback and available in raw `tool_started` data; retain them for the finished
+UI row. Support missing/withheld content and display only appropriate fields.
+
+```typescript
+// Inside an application's run event loop:
+if (item.event.type === 'tool_started') {
+ const data = item.event.data as Record<string, unknown>;
+ updateActivity({ sessionId: item.sessionId, turnId: item.event.turn_id,
+ callId: data.call_id, tool: data.name, arguments: data.arguments });
+}
+```
+
+`updateActivity` is application UI code. `context.progress(message, data)` supplies
+intermediate updates without introducing new polling.
+
+## Images from application callbacks
+
+An application callback can explicitly return one image alongside JSON metadata:
+
+```typescript
+import { ToolImageResult } from '@openworkerai/harness-sdk';
+// Inside execute(): capture only the app-authorized surface.
+return new ToolImageResult(
+ { width: 960, height: 600, scope: 'game-preview' },
+ { mimeType: 'image/jpeg', base64: screenshotBytes.toString('base64') },
+);
+```
+
+Requires a host advertising `application_tool_images` and a vision-capable
+model. JPEG/PNG only, one image, at most 768,000 base64 characters; ordinary metadata
+retains its 128,000-character bound. The host validates image signatures. Only the
+latest image per session is kept ephemerally for up to five minutes; durable events
+and history contain a reference, not pixels. Older images must be recaptured when
+needed. The provider receives pixels and applies its own retention rules. This API
+does not grant capture permission or make callbacks sandboxed: applications must
+authorize and constrain what they capture. Plain JSON return values are unchanged.
diff --git a/docs/harness/guides/troubleshooting.md b/docs/harness/guides/troubleshooting.md
index 5e899c13..5c84eaf4 100644
--- a/docs/harness/guides/troubleshooting.md
+++ b/docs/harness/guides/troubleshooting.md
@@ -16,3 +16,19 @@ profile, session/run IDs and sanitized error/event codes. Exclude API keys,
provider tokens, prompts, file contents and private state directories.
[Versions and compatibility](releases.md) · [Guardrails guide](guardrails.md)
+
+## Agent registration is rejected
+
+A generic “Harness rejected the request” can mean that the agent name already
+belongs to a different immutable definition. Check changes to instructions,
+tools and approval mode. Re-register the identical definition, or use a new name
+for the new definition; a new session alone does not change it. Keep existing
+state for old sessions. Do not log prompts or credentials to diagnose the conflict.
+
+## A tool action has an unknown outcome
+
+A disconnected stream is not evidence that execution failed. Save the session
+reference and submission ID, reattach, and inspect durable state. For a write
+with no known outcome, inspect the target system before retrying. Cancellation
+is not rollback. Use `session.cancel()` to request Stop; closing an observer only
+stops observation.
diff --git a/harness/README.md b/harness/README.md
index b6da9c54..bd678e27 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -1,61 +1,128 @@
-# OpenWorker Harness
+# OpenWorker Harness SDK
-> **Under active development:** Please do not open pull requests for the Harness SDK yet—we are still evolving it. Please try it out and [open issues](https://github.com/andrewyng/openworker/issues) for feature requests and bug reports. Your feedback is welcome!
+## Build your app. OpenWorker handles the agents.
-Build your product and user experience. Let OpenWorker run the agents.
+Give your desktop or web app agents that can use tools, work together and keep
+conversations across restarts. Keep your interface and product workflow while
+the harness manages the agent loop, model calls, approvals and session storage.
-OpenWorker Harness is a Rust agent runtime with Rust and TypeScript SDKs. It
-manages model requests, tools, approvals, durable sessions and agent teams.
-Embed it in a desktop application or deploy the service with PostgreSQL.
-The shipped Rust runtime does not require Python. The existing OpenWorker
-Desktop application continues to use its Python harness.
+[Get started](#choose-your-starting-point) · [Documentation](https://openworker.com/docs/sdk/) · [Builder Skill](../skills/README.md) · [Examples](#try-an-example)
-Use a pinned checkout and build the SDK and executable from the same revision.
-Source manifests are development packages; see [versions and compatibility](../docs/harness/guides/releases.md).
+![OpenWorker architecture: your application uses the TypeScript or Rust SDK to control one Rust harness, which connects to cloud/local models and app-owned or OpenShell-isolated tools.](../docs/harness/assets/architecture.svg)
-## Start here
+One Rust engine powers both SDKs. TypeScript runs it as a managed child process;
+Rust can embed it in-process. The current OpenWorker Desktop application uses
+its separate Python engine.
-- [SDK guides](../docs/harness/guides/index.md) — choose a desktop or web application.
-- [Desktop app](../docs/harness/guides/desktop.md) — build Code Atlas with an Electron UI and the TypeScript SDK; a Rust agent example is included.
-- [Web app](../docs/harness/guides/server.md) — upload a PDF and ask questions about it.
-- [Arcade Studio](examples/arcade/README.md) — a desktop game-building application.
-- [Rust SDK](harness-sdk/README.md) and [TypeScript SDK](typescript-sdk/README.md).
-- [Tools and MCP](../docs/harness/guides/tools.md), [sessions and teams](../docs/harness/guides/sessions.md), and [model credentials](../docs/harness/guides/providers.md).
-- [Guardrails](../docs/harness/guides/guardrails.md), [alignment](../docs/harness/guides/alignment.md), [compliance](../docs/harness/guides/compliance.md), and [observability](../docs/harness/guides/observability.md).
-- [Deployment options](../docs/harness/guides/deployment.md) — local containers, Kubernetes and cloud deployments.
-- [Documentation site](../docs-site/README.md) — build the HTML guides from Markdown.
+> **Under active development.** Please try the SDK and [open issues](https://github.com/andrewyng/openworker/issues) for bugs and feature requests. Please hold off on SDK pull requests while the API is evolving.
-## What the harness handles
+## Choose your starting point
-- Responses, Chat Completions and Anthropic Messages APIs, cloud proxies and compatible local model servers.
-- Streaming, tools, cancellation, compaction and durable session recovery.
-- Human approvals, optional model-based review and session-scoped grants.
-- Rust tools, application callbacks and explicitly registered MCP servers.
-- Agent teams with durable inboxes and boards, on SQLite or PostgreSQL.
-- Guardrails, hooks, compliance recording and optional security/SIEM adapters.
-- Observability export and artifact storage for service deployments.
+| You are building… | Start here |
+| --- | --- |
+| A Windows or Mac desktop app | [Desktop walkthrough](../docs/harness/guides/desktop.md) · [Electron/Tauri starters](desktop-starters/README.md) |
+| A web app with its own backend | [Web walkthrough](../docs/harness/guides/server.md) |
+| A local script or command-line utility | [Runnable file-organizer agent](../skills/openworker-harness-builder/references/local-script.md) |
+| A Rust application | [Rust SDK quickstart](harness-sdk/README.md) |
+| A shared agent service | [Deployment choices](../docs/harness/guides/deployment.md) · [Local service setup](../deploy/service/README.md) |
-Your application owns its UI, authentication and product workflow. Keep model keys
-and service credentials in trusted configuration, outside prompts and browser code.
-Use SDK/service interfaces instead of reading runtime tables directly.
+### TypeScript: install from npm
-## Pick an integration
+```sh
+npm install --save-exact @openworkerai/[email protected]
+```
-| Application | Interface |
-|---|---|
-| Rust desktop app | Run `openworker-sdk` in your Tokio process or use a managed child |
-| TypeScript desktop app | `@openworkerai/harness-sdk` manages the Rust child over private stdio |
-| Custom tool host | [Native host builder](partner/README.md) and [tools SDK](tools-sdk/README.md) |
-| Service | [API and workers](server-reference/README.md), [CLI](service-cli/README.md), REST/SSE and PostgreSQL |
+npm includes the matching native runtime automatically. No Rust compiler or
+Python installation is needed. This client documentation release uses native
+runtime **0.1.0-beta.3**. Run the SDK in Node.js 20+, Electron main or your server;
+the browser talks to your app's API. See the [TypeScript quickstart](typescript-sdk/README.md).
-For local containers and Kubernetes, start with the [service deployment README](../deploy/service/README.md).
-The Rust and TypeScript SDKs share the same engine; TypeScript does not reimplement
-agent logic.
+### Rust: embed from a pinned checkout
-## Build from this checkout
+Use `openworker-sdk` from a pinned checkout with the repository's Rust toolchain.
+The [Rust quickstart](harness-sdk/README.md) includes dependencies and a complete
+program. npm availability does not imply Cargo registry publication.
-Use the pinned Rust toolchain in `rust-toolchain.toml`, Node.js 24 and npm 11+,
-plus your platform's native build prerequisites.
+### Build with Codex or Claude Code
+
+```sh
+npx @openworkerai/openworker-harness-builder --agent claude --project .
+```
+
+Use `--agent codex` for Codex or `--global` for user-wide installation. Existing
+installs ask before replacing and save a backup; scripts can use
+`--replace-existing`. The [Skill](../skills/README.md) includes version-matched
+instructions and runnable examples without requiring a repository checkout.
+
+## What your application gains
+
+| Outcome | What the harness provides |
+| --- | --- |
+| Ship your product experience sooner | One agent loop for provider requests, tools, streaming and compaction. |
+| Keep conversations across restarts | Durable sessions and explicit recovery, without blindly replaying uncertain actions. |
+| Keep people in control | Human approvals, session grants and optional LLM-assisted review. |
+| Choose where work happens | App-owned tools or isolated execution through NVIDIA OpenShell. |
+| Divide larger tasks | Standalone sub-agents and agent teams with durable messages and boards. |
+| Use the model that fits | OpenAI, Anthropic and compatible cloud/local endpoints, with app-owned credentials. |
+| Understand what happened | Opt-in turn traces, usage accounting and telemetry export to tools such as Langfuse. |
+
+## Your app and the harness
+
+Your app owns the UI, authentication, user/session ownership and product workflow.
+It chooses the tools, models and policies. The harness enforces its configured
+controls; an application callback still has the application's privileges.
+
+OpenShell isolates configured shell/file execution while the agent loop stays
+in the trusted harness. A workspace path alone is not an OS sandbox. See
+[execution boundaries](../docs/harness/guides/openshell.md),
+[guardrails and hooks](../docs/harness/guides/guardrails.md),
+[alignment](../docs/harness/guides/alignment.md) and
+[compliance](../docs/harness/guides/compliance.md).
+
+## Try an example
+
+| Example | What it demonstrates |
+| --- | --- |
+| [File organizer](../skills/openworker-harness-builder/references/local-script.md) | Custom tools, confined directory operations, activity and per-operation approvals. |
+| [Code Atlas](examples/quickstart/README.md) | A desktop UI that explains a selected code directory. |
+| [PDF Notes](../docs/harness/guides/server.md) | A web app that accepts a PDF and answers questions about it. |
+| [Arcade Studio](examples/arcade/README.md) | A desktop application that builds and previews games. |
+
+## Deployment and operations
+
+Start in one application process or container. Use the service when you need
+API/worker separation, durable shared storage and separately managed execution.
+The service uses PostgreSQL; local apps can use SQLite.
+
+- [Local containers and Kubernetes](../deploy/service/README.md)
+- [AWS](../docs/harness/guides/aws.md), [Azure](../docs/harness/guides/azure.md), [GCP](../docs/harness/guides/gcp.md) and [private Kubernetes](../docs/harness/guides/private-kubernetes.md)
+- [Management CLI](service-cli/README.md), [management UI](service-ui/README.md) and [observability](../docs/harness/guides/observability.md)
+
+Cloud deployment paths are experimental references. Qualify your configuration
+in the target environment before using it for production. Read
+[versions and compatibility](../docs/harness/guides/releases.md) before upgrading.
+
+## For developers and coding agents
+
+Start with the matching package README: [TypeScript](typescript-sdk/README.md) or
+[Rust](harness-sdk/README.md). Use the builder Skill's `installation.json` to find
+its exact SDK pin. Source release manifests and npm client/native versions can
+differ; do not infer registry availability from a source version string.
+
+- Preserve immutable agent identities; changing instructions/tools/approvals requires a new name.
+- Keep credentials and durable state outside model-readable files.
+- Use real user decisions for approvals; observation is independent from execution.
+- Reconcile unknown tool outcomes before retrying.
+- Prefer public SDK/service interfaces over runtime tables or private transport methods.
+
+Need to change the engine or register native tools? See the [native host guide](partner/README.md),
+[Tools SDK](tools-sdk/README.md) and [workspace CI](../.github/workflows/rust-sdk.yml).
+
+<details>
+<summary>Build and test this checkout</summary>
+
+Use the [pinned toolchain](rust-toolchain.toml), Node.js and your platform's native
+prerequisites. See [Windows build notes](WINDOWS.md) when applicable.
```sh
cd harness
@@ -64,51 +131,18 @@ npm --prefix typescript-sdk ci
npm --prefix typescript-sdk run build
```
-The executable is `target/release/openworker-harness` (`.exe` on Windows).
-
-## Execution and safety
-
-The runtime defaults to NVIDIA OpenShell. Provision Docker/OpenShell before using
-that mode. Unavailable sandboxing fails rather than silently falling back.
-Desktop examples explicitly select `sandbox: "off"` for application-owned work;
-that work runs with the application's privileges and has no OS isolation from
-other host resources. See [OpenShell integration](../docs/harness/guides/openshell.md).
-
-Linux is the service/OpenShell reference platform. Windows and macOS have desktop
-SDK integrations; native build and packaging prerequisites apply. See
-[Windows build notes](WINDOWS.md). Build and test on the OS/architecture you ship.
-
-## Layout
-
-```text
-runtime/ Agent loop, policy, sessions and execution
-harness-sdk/ Rust SDK and native executable
-typescript-sdk/ Node/TypeScript client
-tools-sdk/ Native Rust tool interface
-store-postgres/ Service persistence and coordination
-artifacts/ Filesystem and object-store artifacts
-telemetry/ OpenTelemetry integration
-server-reference/ Service API and workers
-service-cli/ ows CLI
-service-ui/ Management UI
-desktop-starters/ Electron and Tauri project generators
-examples/ Runnable applications and integrations
-tests/ Shared contracts and test entry points
-```
-
-## Test changes
+The host is `target/release/openworker-harness` (`.exe` on Windows). Build a custom
+SDK/helper pair from the same revision; npm consumers normally use the packaged runtime.
```sh
-cd harness
cargo fmt --all -- --check
cargo test --locked -p openworker-sdk --features test-support --test provider_auth
npm --prefix typescript-sdk test
-node --test desktop-starters/test.mjs tests/stdio-client.test.mjs
```
-The workspace/storage matrix is in [CI](../.github/workflows/rust-sdk.yml).
-Tests requiring PostgreSQL, OpenShell, credentials or a visible desktop must be
-explicitly enabled with their prerequisites. A skipped external test is not a pass.
+OpenShell, PostgreSQL and live-provider checks require their documented setup.
+The [documentation site](../docs-site/README.md) is built from repository Markdown.
+
+</details>
-Licensed under the repository's [MIT license](../LICENSE). Third-party example
-assets retain their own notices and licenses.
+[MIT license](../LICENSE).
diff --git a/harness/harness-sdk/README.md b/harness/harness-sdk/README.md
index 09e1bbca..da7d973c 100644
--- a/harness/harness-sdk/README.md
+++ b/harness/harness-sdk/README.md
@@ -1,398 +1,115 @@
-# OpenWorker Harness SDK (development API)
+# OpenWorker Harness SDK for Rust
-Registry candidate: **0.1.0-beta.2**. See the [installation guide](https://github.com/andrewyng/openworker/blob/openworker-harness-sdk/docs/harness/guides/installation.md) and [tested desktop QuickStart](https://github.com/andrewyng/openworker/blob/openworker-harness-sdk/docs/harness/guides/desktop.md). Registry publication is a separate release step; prepared tarballs are available for pre-publication testing.
+Embed an agent runtime in your Rust application, with model connections, tools,
+approvals and durable conversations. Use the same engine through a managed child
+process when your product needs that process boundary.
-One Rust client, two deployment backends, the same native engine. This is a beta
-crate with an explicit SDK/runtime compatibility contract. It is distinct
-from `openworker-tools`, which defines partner-owned tools.
+[SDK overview](../README.md) · [Desktop guide](../../docs/harness/guides/desktop.md) · [Tools](../../docs/harness/guides/tools.md) · [Examples](../examples/)
-For service coding teams, see [Sessions and teams](../../docs/harness/guides/sessions.md)
-for independent OpenShell checkouts, exact-submission verification and explicit
-integration. [OpenShell integration](../../docs/harness/guides/openshell.md)
-documents optional named RuntimeProfile grants; artifacts need no child Git key.
+## Add the SDK
-**Storage-selectable host:** use `HostConfig` with either `Storage::Sqlite` or
-`Storage::Postgres`, and register one or more trusted coworkers. Both
-`HarnessClient::embedded` and `HarnessClient::managed_stdio` support this host,
-including Teams. See [Sessions and teams](../../docs/harness/guides/sessions.md)
-for configuration, native child packaging and the tested four-way matrix.
-The host may also start with zero agents. `agents::Harness::create_agent(definition)`
-registers an agent after startup and returns an `AgentHandle` with `new_session`,
-`new_session_with_model` and `resume_session`. `Agent::default_model(ModelChoice)`
-sets the reusable default. Live SDK agents require an explicit model choice.
-Dynamic definitions persist in the app state directory and restore before session
-recovery; exact re-registration is idempotent and conflicting identity reuse fails.
-Use `list_agents().await` for the current catalog, not the startup `agents()` snapshot.
-Desktop defaults, shared providers, application callbacks and the send/state API
-are implemented. For a complete app, use the [desktop starters](../desktop-starters/README.md).
-The executable is bundled beside your app (or supplied explicitly); no executable
-is selected from PATH. Rust embeds the engine by default. A managed child is optional.
-The examples below retain the compatible single-coworker `RuntimeConfig` API.
+Use a pinned OpenWorker checkout and add the crate to your application's
+`Cargo.toml`. These instructions use source dependencies; npm publication does
+not publish a Rust crate. Use the checkout's [pinned Rust toolchain](../rust-toolchain.toml).
-```text
-Partner Rust application → HarnessClient
- ├─ embedded → Runtime::dispatch
- └─ managed stdio → owned child → existing JSON-RPC server
+```toml
+[dependencies]
+openworker-sdk = { path = "/absolute/path/to/openworker/harness/harness-sdk" }
+tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
+anyhow = "1"
```
-## Quick start: the agents API
+The current builder also requires a runner helper, even when the agent loop is
+embedded and the agent has no tools. Build it from the same checkout:
-For a lesson guide or text-only assistant, use an empty tool list with optional
-capabilities disabled. It receives no implicit question/history tools. See
-[Sessions and teams](../../docs/harness/guides/sessions.md) for Rust/TypeScript
-examples and regression coverage.
-
-```rust,no_run
-use openworker_sdk::{Agent, Credentials, Harness, Model, ModelProvider, Sandbox, Tool};
-use futures_util::StreamExt;
-use serde_json::json;
-# async fn example() -> anyhow::Result<()> {
-let harness = Harness::builder()
- .sandbox(Sandbox::Off) // Explicit: trusted app callbacks, not OS-isolated tools.
- .start().await?;
-harness.set_model_provider(ModelProvider::responses("OpenAI")
- .credentials(Credentials::from_env("OPENAI_API_KEY"))).await?;
-harness.register_tools("app", [Tool::new("show_status")
- .description("Display a status update in this app.")
- .input_schema(json!({"type":"object","properties":{"text":{"type":"string"}},"required":["text"],"additionalProperties":false}))
- .handler(|args, context| async move {
- context.progress("Updating app", json!({})).await?;
- // Forward args["text"] to your application's UI here.
- let _ = args;
- Ok(json!({"displayed":true}))
- })]).await?;
-let agent = harness.create_agent(Agent::new("assistant")
- .instructions("Help the user and report progress in the app.")
- .default_model(Model::new("OpenAI", "YOUR_MODEL_ID"))
- .tool("app.show_status")).await?;
-let session = agent.new_session().await?;
-let saved_reference = session.reference().clone(); // Persist in app project metadata.
-let run = session.send("Help me plan my day.").await?;
-let mut events = run.events();
-while let Some(event) = events.next().await { let event = event?; /* render event */ }
-let result = run.result().await?; // May be Interrupted; show the real approval/question.
-let state = session.state().await?;
-harness.shutdown().await?;
-# Ok(()) }
-```
-
-For a local model, use `ModelProvider::chat_completions("Ollama")`
-with `.base_url("http://127.0.0.1:11434/v1")` and no credential. Use the exact
-installed model ID. Providers are shared by this harness; sessions pin the resolved
-provider identity, API, endpoint and model. Rotation preserves that identity;
-changing API/endpoint requires a new name. No model fallback is performed.
-
-Chat Completions requests streaming usage by default. For a compatible server
-that rejects `stream_options`, add `.stream_usage(false)` to its `ModelProvider`.
-The setting persists across restart and key rotation. Missing usage is unknown,
-not zero; see [streaming token usage](../../docs/harness/guides/providers.md#streaming-token-usage).
-
-Anthropic Messages enables automatic prompt caching by default. Set
-`.prompt_caching(false)` on its `ModelProvider` to opt out. Google Gemini uses
-the Chat Completions adapter with private thought-signature replay; see
-[models and credentials](../../docs/harness/guides/providers.md).
-
-Windows uses DPAPI and macOS uses Keychain for secure credentials. On Linux,
-choose `.memory_only()` explicitly or use server-managed credentials; there is no
-plaintext fallback. Keys never belong in agent definitions. Re-register callback
-functions after restarting your app; only descriptors persist. Callback code runs
-with app privileges even when other tools use a sandbox.
-
-Use `session.send(SessionInput::Approval { .. })` or `SessionInput::Answer { .. }`
-for explicit controls. A plain string is always a user message, never an approval.
-Use `agent.resume_session(saved_reference)` after restart. Dropping an event stream
-does not cancel a run; call `session.cancel()` explicitly.
-
-## Turn context and conversation migration
-
-```rust,no_run
-use openworker_sdk::{Agent, BuiltinTools, Harness, HistoryItem, Model,
- SessionOptions, TurnLimits, TurnOptions};
-# async fn migration(harness: &Harness) -> anyhow::Result<()> {
-// Register app.lookup and the provider before this example.
-let agent = harness.create_agent(Agent::new("naming")
- .instructions("Help the user choose a name.")
- .tool("app.lookup")
- .builtin_tools(BuiltinTools { ask_user: Some(false), read_history: Some(false) })
- .default_model(Model::new("OpenAI", "YOUR_MODEL_ID"))).await?;
-let session = agent.new_session_with(SessionOptions::default().initial_history(vec![
- HistoryItem::User { text: "Find a short name.".into() },
- HistoryItem::Assistant { text: "You liked Atlas.".into() },
-])).await?;
-let run = session.send_with_options("Suggest another name.", TurnOptions {
- submission_id: Some("naming-turn-42".into()),
- instruction_addendum: Some("Prefer .ai domains. Budget: $40.".into()),
- limits: Some(TurnLimits {
- max_model_calls: 8, max_output_tokens: 60000,
- max_output_tokens_per_call: 24000, summary_tokens: 512,
- }),
- ..Default::default()
-}).await?;
-let result = run.result().await?;
-# Ok(()) }
-```
-
-An instruction addendum is trusted application context for one turn, including
-retries and recovery. It is not user transcript text and does not grant authority.
-The 8,192-token per-call default can be changed independently of the total turn
-budget; the remaining budget and summary reserve still apply. Imported histories
-are validated and saved atomically, and imported tools never execute. See
-[session options](../../docs/harness/guides/sessions.md) for the portable import
-format, limits, provider metadata restrictions and built-in tool defaults.
-Use an updated native runtime with these APIs; a TypeScript-only update cannot
-add host capabilities. Unchanged definitions with omitted options stay compatible.
-
-## Lower-level and compatibility examples
-
-Current limits: 16 profiles per host, one subagent level, and 0–64 selected tools
-per agent. Callback descriptors are immutable and bounded to 128 per host; changed
-tool semantics should use a new qualified name/version. Callback outputs are JSON,
-not binary streams. Timers and steering are explicitly unsupported in `state()`.
-
-Most applications should start with `openworker_sdk::agents`: define agents as
-values, run them, handle typed interruptions. It is a thin layer over the
-`HarnessClient` described below. See [Sessions and teams](../../docs/harness/guides/sessions.md).
-
-```rust,ignore
-use openworker_sdk::agents::*;
-
-let agent = Agent::new("assistant")
- .instructions("Help the user with their workspace.")
- .tools(["files.read", "files.write"])
- .planning(true)
- .interrupt_on(["files.write"]);
-
-let harness = Harness::builder().state_dir(state_dir).executable(runner).agent(agent).tools(registry).embedded().await?;
-let session = harness.session("assistant", workspace).await?;
-let result = session
- .run_with("Tidy the docs folder", |_| Response::Approve(ApprovalDecision::Once))
- .await?;
-println!("{}", result.final_output.unwrap_or_default());
-```
-
-## Choose a backend
-
-```rust,ignore
-use openworker_sdk::{ClientOptions, HarnessClient, ProcessConfig, RestartPolicy,
- RuntimeConfig, Sandbox, ToolRegistry};
-
-let mut config = RuntimeConfig::new(state_dir, coworker_bundle, runner_binary);
-// Explicit opt-out; required for today's native Windows profile.
-config.sandbox = Sandbox::Off;
-
-// Optional fallback provider. Named model connections take precedence.
-config.provider = openworker_sdk::ProviderKind::Anthropic;
-config.model = "claude-sonnet-5-5".into();
-
-// Embedded: your application supplies its own Tokio runtime and native tools.
-let mut tools = ToolRegistry::default();
-example_tools::register(&mut tools)?;
-let client = HarnessClient::embedded(config, tools, ClientOptions::default()).await?;
-
-// Alternatively: SDK starts the partner executable and privately owns its pipes.
-let client = HarnessClient::managed_stdio(ProcessConfig {
- program: example_runtime_binary,
- runtime: config,
- restart: RestartPolicy::default(),
-}, ClientOptions::default()).await?;
+```sh
+cargo +1.96.0 build --manifest-path /absolute/path/to/openworker/harness/Cargo.toml \
+ --locked -p openworker-sdk --bin openworker-harness
```
-Those are alternatives, not two simultaneous owners of one state directory.
-All configuration paths must be absolute. `RuntimeConfig` loads one coworker;
-`HostConfig` routes multiple profiles through the same selected storage adapter.
-Coworker native tool names resolve against the
-embedded registry or the registry linked into the selected child executable.
-The SDK cannot transmit a Rust implementation over stdio. Both modes may load
-app-owned `servers.json` via `RuntimeConfig.servers`.
-
-Embedded mode is direct dispatch, not an internal pipe, and does not install
-signal handlers or start/stop the application's Tokio runtime. It still requires
-a compatible OpenWorker runner executable for subprocess tool/sandbox helpers;
-it does not mean every MCP/sandbox component runs inside the application.
-Native tools share process trust and must not block/detach work. A native crash
-can take down the embedding application; this is not a sandbox.
-
-## Use the same operations
-
-```rust,ignore
-let mut notifications = client.subscribe(); // before attaching/starting work
-let mut connection = client.connection(); // watch channel, current state retained
-let capabilities = client.info(); // initial initialize handshake
-
-let session = client.create_session(SessionOptions {
- name: "My assistant".into(), coworker: "example".into(), workspace,
- model: Some(ModelChoice { connection: "openai".into(), model: "gpt-6-sol".into() }),
- permissions: None, // existing runtime default: Ask
-}).await?;
-let snapshot = client.attach(&session, saved_processed_cursor).await?;
-client.start_turn(&session, &persisted_submission_id, "Help with this task").await?;
-
-// Only after the app obtains the user's actual decision:
-client.approve(&session, &approval_id, ApprovalDecision::Session).await?;
-client.answer(&session, &question_id, &user_answer).await?;
-client.cancel_turn(&session, &turn_id).await?;
-client.shutdown().await?; // deterministic cleanup; closes all client clones
+Set `OPENWORKER_EXECUTABLE` to its absolute path under `harness/target/debug/`
+(`openworker-harness.exe` on Windows). Bundle this helper with a distributed app.
+
+## Run your first agent
+
+Save as `src/main.rs`. Set `OPENAI_API_KEY` privately in the process environment
+and `OPENWORKER_MODEL` to an exact model ID available to your account. Cargo does
+not load env files automatically.
+
+```rust
+use openworker_sdk::{Agent, Credentials, Harness, Model, ModelProvider, Sandbox};
+use openworker_sdk::agents::RunStatus;
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let model = std::env::var("OPENWORKER_MODEL")?;
+ let harness = Harness::builder()
+ .state_dir(std::env::current_dir()?.join(".openworker-state"))
+ .executable(std::env::var("OPENWORKER_EXECUTABLE")?)
+ .sandbox(Sandbox::Off)
+ .start().await?;
+ let outcome = async {
+ harness.set_model_provider(ModelProvider::responses("OpenAI")
+ .base_url(std::env::var("OPENWORKER_MODEL_URL")
+ .unwrap_or_else(|_| "https://api.openai.com/v1".into()))
+ .credentials(Credentials::from_env("OPENAI_API_KEY").memory_only()))
+ .await?;
+ let agent = harness.create_agent(Agent::new("first-agent-v1")
+ .instructions("Give concise, helpful answers.")
+ .default_model(Model::new("OpenAI", model))
+ .tools([] as [&str; 0]).planning(false).memory(false).scheduling(false))
+ .await?;
+ let session = agent.new_session().await?;
+ let result = session.run("Suggest three names for a file-organizing app.").await?;
+ anyhow::ensure!(matches!(result.status, RunStatus::Completed),
+ "Run ended: {:?}", result.status);
+ println!("{}", result.final_output.unwrap_or_default());
+ Ok::<(), anyhow::Error>(())
+ }.await;
+ harness.shutdown().await?;
+ outcome
+}
```
-`snapshot` reads current state without journal replay or cursor advancement.
-`attach` returns a snapshot, remembers the session, and emits replay events from
-the supplied cursor (up to 100 journal pages per operation). Subscribe first,
-consume concurrently for long replays, and deduplicate `(session_id,event_id)`.
-`acknowledge` updates the SDK's in-memory processed cursor only after your app has
-processed the event; it does not acknowledge or approve tool execution. Persist
-that cursor and session ID yourself to recover after an application restart.
-Do not advance a processed cursor past an unresolved replay gap merely because
-a later live notification arrived; snapshots and replay may overlap.
-
-Requests are typed for the core flow; evolving snapshots/results remain JSON.
-The bounded `request(method, params)` escape hatch covers model connections,
-defaults, policies, permissions/revocation, skills, history and native tool controls
-using the SDK-owned process protocol. Initialization is SDK-owned.
-Use `attach` for replay subscriptions. Model credentials should be configured via
-`connection/set`, never executable arguments or coworker bundles. Managed children
-receive a narrow OS/runtime environment allowlist, not inherited provider keys.
-Raw stderr is discarded, not copied into UI/telemetry. Memory credentials do not
-survive a child restart; query connection status and obtain them from the app again.
-
-## Process recovery contract
-
-- Startup/handshake failures return an error; they do not enter a restart loop.
-- After successful startup, unexpected exit, broken/malformed stdio or an unknown
- request outcome triggers bounded recovery. Default: **three restarts per client
- lifetime**, 250 ms exponential backoff capped at 5 seconds. Success does not reset
- the budget. States: Starting → Ready → Recovering → Ready, or Failed.
-- SDK closes and reaps its exact child before launching another. No shell launch,
- network listener, port allocation or shared machine service is involved.
-- Recovery initializes a new connection, attaches remembered sessions, emits
- replay plus `Recovered` snapshots, and returns Ready. A session-level failure
- is surfaced as `RecoveryFailed`, not silently recreated or resumed.
-- **No requests or tool calls are automatically resubmitted.** An interrupted
- in-flight request returns `OutcomeUnknown`, even if it may have committed.
- Reconcile the snapshot/journal. For an intentionally retried turn submission,
- reuse the original stable submission ID—never invent one to hide ambiguity.
-- Requests while unavailable/full queues are rejected, not held for surprise
- execution later. Queued requests are bound to their connection generation.
-- Dropping a request future does not retract work already queued or accepted;
- use the explicit turn-cancellation operation and reconcile durable state.
-- Pending approvals/questions remain durable. Started uncertain effects are
- interrupted by the existing harness recovery rules, never replayed. Restarts
- do not restore screen/input leases or bypass any permission checks.
-- Events are at-least-once recovery hints, not exactly-once messages. The 256-slot
- broadcast stream can return `Lagged`; `Gap` also means recover by journal cursor.
- `event/read` remains available if automatic replay reaches its bounded limit.
-- Explicit `shutdown` and last-handle drop never restart the child. Always await
- shutdown before tearing down the host Tokio runtime. Drop requests best-effort
- cleanup; it cannot synchronously await shutdown. Embedded shutdown failures are
- reported; an in-process SDK cannot forcibly isolate noncooperative native code.
-
-This release keeps existing binary/tool/policy identity pinning. A process restart
-with the same installation can resume saved sessions. Upgrading the executable
-or switching an existing session between embedding and child binaries may require
-a new session. Compatible upgrade/rebinding policy is separate work; the SDK does
-not weaken saved approval identities to make upgrades appear seamless.
-
-## Example and verification
-
-For service deployments, [OpenShell integration](../../docs/harness/guides/openshell.md)
-explains `RuntimeProfile.git_access`, operator-owned provider pins and
-`RuntimeProfile::delegated_grants()` for bounded child placement. Git credentials
-remain in OpenShell; the SDK selects a versioned grant name.
-
-`cargo run -p openworker-sdk --example connect -- <embedded|stdio> <absolute-state>
-<absolute-bundle> <absolute-runner> <absolute-workspace> [--sandbox-off]`
-
-The example discovers a coworker, creates/attaches a session and shuts down without
-calling a model. Its empty registry supports MCP-based bundles; native partner
-bundles require registering their crates in the embedded executable.
-
-Native Linux/Windows conformance:
-
```sh
-cargo test --locked -p openworker-sdk --features test-support -- --test-threads=1
-cargo clippy --locked -p openworker-sdk --all-targets --features test-support -- -D warnings
-```
-
-The feature-gated `sdk-test-host` is a development fixture, not a partner binary.
-Tests use scripted models and real subprocesses/native file effects, with no API
-keys: both backends' session/approval flows, stable submissions, shutdown, crash
-reattachment, no repeated uncertain effects, transient access revocation, bounded
-restart exhaustion and in-flight outcome uncertainty. Test/debug binaries have
-large hashed identities: Linux container runs use the normal 60-second request
-timeout and serial test execution. Mac host compilation is not a native Mac port.
-
-### Turn limits
-
-Set an agent default with `.limits(TurnLimits { ..Default::default() })`; use
-`session.send_with_limits(text, limits)` for one new message. Resuming keeps the
-original limits and consumption. The runtime reserves a bounded final-summary
-response; process lifetime remains separate from turn completion.
-
-
-Service coding teams can select an optional trusted Git broker.
-The app supplies a named repository, permitted ref and exact commit. The harness
-stages verified artifacts and ToolRunner imports them before the lead starts;
-GitHub credentials stay outside the sandbox. Publication is a separately selected
-registered native tool with ordinary approvals and a RuntimeProfile scope ceiling.
-This Linux service adapter does not add a Git executable to the core SDK.
-
-### Standalone sub-agents (source preview)
-
-Use `Agent::allow_subagents(true)` to let a normal agent create children with an
-explicit prompt, context and tool subset. Children use the existing durable
-coordination engine without application-managed team setup. This requires a
-matching feature runtime; it is not in published runtime 0.1.0-beta.2.
-See [standalone sub-agents](../../docs/harness/guides/sessions.md#standalone-sub-agents)
-for limits, approvals and shared-sandbox behavior.
-
-
-## Optional turn traces and evaluation evidence
-
-The source candidate includes opt-in recording, per-turn timeline/grouped queries,
-child drill-down and durable evaluation results. Recording and evaluation delivery
-are disabled until configured; browser UI is a separate optional component.
-See the [observability guide](../../docs/harness/guides/observability.md) for local
-SQLite/PostgreSQL, Langfuse export, content selection and audit references. These
-new APIs require matching local candidate builds and are not in the published
-0.1.0-beta.2 packages yet.
-
-## User attachments (source preview)
-
-Attach images, PDFs and UTF-8 text files to a session with ordered content and
-immutable recovery references. See [Attachments](../../docs/harness/guides/attachments.md)
-for the Rust/TypeScript APIs, service uploads, limits and upgrade instructions.
-This API requires matching source builds; it is not in npm `0.1.0-beta.2`.
-
-## Reviewer and compaction guidance
-
-```rust,no_run
-# use openworker_sdk::*;
-# async fn example(agent: AgentHandle) -> openworker_sdk::Result<()> {
-let session = agent.new_session_with(
- SessionOptions::default()
- .auto_approver_context("Staging workspace. Ask before publishing.")
- .compaction(CompactionOptions::additional_instructions(
- "Preserve architectural decisions and unfinished tests."
- ))
-).await?;
-
-let run = session.send_with_options("Continue.", TurnOptions {
- auto_approver_context: Some("Changes must remain inside src/.".into()),
- compaction: Some(CompactionOptions::additional_instructions(
- "Keep the migration checklist."
- )),
- ..Default::default()
-}).await?;
-let result = run.result().await?;
-# Ok(())
-# }
+cargo +1.96.0 run
```
-The same two setters on `Agent` define reusable defaults. Precedence is agent →
-session → turn. Omission inherits; an empty string clears inherited guidance.
-Session defaults and turn overrides are durable, separate from user history,
-and included in submission idempotency checks. Each string is bounded to 32,000
-UTF-8 bytes with no NUL. Context does not enable auto-approval: configure
-`Approvals::auto(reviewer_model)` separately. Hard policy checks still run first;
-summary guidance supplements the required summary sections. Both embedded and
-managed-subprocess transports support these options. Service REST session/turn
-overrides are not exposed yet.
+`OPENWORKER_MODEL_URL` optionally selects another Responses-compatible endpoint.
+
+Rust embeds the harness by default. This text-only example exposes no tools and
+explicitly selects `Sandbox::Off`. App callbacks keep the application's privileges.
+For isolated shell/file execution, configure [OpenShell](../../docs/harness/guides/openshell.md).
+Use `HarnessClient::managed_stdio` or the custom host interfaces only when you
+need an explicit process boundary; see the [native host guide](../partner/README.md).
+
+## Add the next capability
+
+| You want to… | Start here |
+| --- | --- |
+| Register native or app-owned tools | [Tools and MCP](../../docs/harness/guides/tools.md) · [Tools SDK](../tools-sdk/README.md) |
+| Handle streaming, approvals and cancellation | [Streaming](../../docs/harness/guides/streaming.md) · [Sessions](../../docs/harness/guides/sessions.md) |
+| Use local models or rotate credentials | [Models and credentials](../../docs/harness/guides/providers.md) |
+| Add teams, memory or scheduling | [Sessions and teams](../../docs/harness/guides/sessions.md) |
+| Add guardrails or inspect traces | [Guardrails](../../docs/harness/guides/guardrails.md) · [Observability](../../docs/harness/guides/observability.md) |
+| Deploy a service | [Deployment options](../../docs/harness/guides/deployment.md) |
+
+## Integration contract
+
+- Define agents once and create a session per conversation. Persist its reference
+ and call `agent.resume_session(reference)` after restart.
+- Definitions persist and are immutable. Use a new agent name when changing its
+ instructions, tools or approvals; identical registration is idempotent.
+- Credentials resolve in the Rust application process. `memory_only()` requires
+ supplying them again after app restart. Keep keys out of instructions and files
+ available to agent tools.
+- A workspace selects the working directory and supported path-policy scope.
+ Arbitrary callbacks retain application privileges; it is not an OS sandbox.
+- Treat interruptions as requests for a real app/user decision. Dropping an event
+ stream does not cancel execution; call `session.cancel()` explicitly.
+- Reconcile unknown tool outcomes before retrying, and keep state outside tool-readable directories.
+
+Generate full API documentation from the checkout with
+`cargo doc --manifest-path harness/Cargo.toml -p openworker-sdk --no-deps`.
+See [versions](../../docs/harness/guides/releases.md) and
+[troubleshooting](../../docs/harness/guides/troubleshooting.md) before upgrading an app.
diff --git a/harness/typescript-sdk/README.md b/harness/typescript-sdk/README.md
index 4a1a305f..967cff99 100644
--- a/harness/typescript-sdk/README.md
+++ b/harness/typescript-sdk/README.md
@@ -1,735 +1,107 @@
-# OpenWorker TypeScript Harness SDK
+# OpenWorker Harness SDK for TypeScript
-Published SDK: **0.1.0-beta.3**, for Node.js 20+ and ESM.
+Build a desktop app, web app or Node.js utility with an agent that can use your
+tools and keep its conversation across restarts. Your app owns the interface;
+OpenWorker manages the agent loop.
-```sh
-npm install --save-exact @openworkerai/[email protected]
-```
-
-npm installs the matching native runtime for your platform. Keep optional
-dependencies enabled; no Rust compiler or startup binary download is needed.
-The Rust harness owns the agent loop, tools, approvals and durable sessions.
-TypeScript controls it through private stdio from a Node script, Electron main
-process or application server. Browser code calls your application's API or IPC.
+[SDK overview](../README.md) · [Desktop guide](../../docs/harness/guides/desktop.md) · [Web guide](../../docs/harness/guides/server.md) · [API declarations](src/index.ts)
-Start with `Harness.start()`, `setModelProvider()` and `createAgent()` below.
-The startup `agents` array, `setConnection()` and explicit executables remain
-available for advanced integrations; they are not required for a new application.
-
-For a coding agent to help build your app, install the
-[OpenWorker Harness Builder skill](../../skills/README.md):
+## Install
```sh
-npx @openworkerai/openworker-harness-builder --agent codex --project .
-# For Claude Code, use --agent claude. For user-wide installation, use --global.
+npm install --save-exact @openworkerai/[email protected]
```
-If the Skill is already installed, interactive runs ask before replacing it.
-Use `--replace-existing` for an explicit update without prompting. Both paths
-save a backup outside the active skills directory; non-interactive updates require
-the flag. See the [Skill update instructions](../../skills/README.md#update-an-existing-installation).
-
-See the [Desktop guide](https://openworker.com/docs/sdk/desktop/),
-[Web guide](https://openworker.com/docs/sdk/server/) or the bundled
-[plain Node file-organizer example](../../skills/openworker-harness-builder/references/local-script.md).
-The Skill includes tool registration, directory scope and an executable approval loop.
+Requires Node.js 20+ and ESM. This documentation-only client release uses the
+unchanged native runtime **0.1.0-beta.3**. npm selects the exact platform package;
+keep optional dependencies enabled. No Rust compiler or Python installation is
+needed. Run the SDK in Node, Electron's main process or your application server;
+browser code calls your app's API or IPC.
-## Create an agent with application tools
+## Run your first agent
-For service deployments, [OpenShell integration](../../docs/harness/guides/openshell.md)
-covers `RuntimeProfile.gitAccess` and `runtimeProfileGrants(profile)`. These select
-operator-installed grants without passing Git credentials through the SDK.
-For artifact-first builders and verifiers, see [Sessions and teams](../../docs/harness/guides/sessions.md)
-and `isolatedCodingServiceTeam`; exact submitted revisions cross independent
-sandboxes without sharing a filesystem or GitHub credential.
-
-For server/container coding agents, see [Tools and MCP](../../docs/harness/guides/tools.md).
-`autoSkipQuestions` is independent of `approvals`; select `coding.*` tools explicitly.
-
-The [desktop starters](../desktop-starters/README.md) bundle the runtime and wire
-model settings, chat, approvals and an isolated playable preview. Application code
-runs in Electron's trusted main process, not the renderer.
+Save as `agent.mjs`. Provide `OPENAI_API_KEY` and `OPENWORKER_MODEL` in your process
+environment or a private env file. Use an exact model ID available to your account.
```typescript
+import { resolve } from 'node:path';
import { Harness } from '@openworkerai/harness-sdk';
-const harness = await Harness.start({ sandbox: 'off' }); // Trusted app callbacks only.
-await harness.setModelProvider({
- name: 'OpenAI', api: 'responses',
- credentials: { apiKeyEnv: 'OPENAI_API_KEY', storage: 'memory' },
-});
-// A key collected by your UI can instead be supplied as { apiKey, storage: 'memory' }.
-await harness.registerTools({ namespace: 'app', tools: {
- show_status: {
- description: 'Display a status update in the app.',
- inputSchema: { type: 'object', properties: { text: { type: 'string' } },
- required: ['text'], additionalProperties: false },
- execute: async (args, context) => {
- context.signal.throwIfAborted();
- await context.progress('Updating app');
- // Forward args.text to your UI; honor context.signal for cancellation.
- return { displayed: true };
- },
- },
-}});
-const agent = harness.createAgent({
- name: 'assistant-v1', instructions: 'Help the user and report progress in the app.',
- defaultModel: { provider: 'OpenAI', name: 'YOUR_MODEL_ID' },
- tools: ['app.show_status'],
- approvals: { mode: 'always' },
- builtinTools: { askUser: false, readHistory: false },
- planning: false, memory: false, scheduling: false,
-});
-await agent.ready();
-const session = await agent.newSession();
-const reference = session.reference(); // Save in your app's project metadata.
-const run = await session.send('Help me plan my day.');
-for await (const event of run.events()) { /* render event */ }
-const result = await run.result(); // An approval may leave status === 'interrupted'.
-// To handle the proposed tool and continue this turn, use the complete
-// streaming approval loop below. Do not send the original message again.
-await harness.shutdown();
-```
-
-The UI owns status rendering and approval cards. The sample registers a callback
-and selects it explicitly; the model does not gain arbitrary access to Node APIs.
-Use the [approval loop](#approvals-and-questions) for an interactive tool-using app.
-For filesystem tools, start from the
-[scoped file handlers](../../skills/openworker-harness-builder/assets/local-script/file-tools.mjs).
-
-### Agent definitions are immutable
-
-Agent names identify persisted definitions. Re-registering the identical definition
-is safe; changing instructions, tools, approval mode or other definition fields
-requires a **new agent name**. Keep old identities for their existing sessions.
-A separate fresh `stateDir` is useful for disposable demos; it does not migrate
-existing sessions. A generic registration rejection can currently mean an agent
-name already has a different definition.
-
-For a guide that must only return text, set `tools: []`, `planning: false`,
-`memory: false` and `scheduling: false`. No implicit `ask_user` or `read_history`
-tools are exposed. See [Sessions and teams](../../docs/harness/guides/sessions.md).
-
-When the built-in `read_history` tool is available, its `after` and `offset`
-arguments are transcript positions, not journal event IDs. Start with
-`after: 0, offset: 0`, then pass each result's `next_index` as `after` and
-`next_offset` as `offset`. Stop when `has_more` is false. Invalid positions return
-an `invalid_history_cursor` tool error with reset guidance, allowing the model to
-correct the call in the same turn. Missing sessions and storage failures remain
-runtime errors. History excerpts never expose provider-private reasoning.
-
-No-key local providers use `api: 'chat-completions'` and an explicit `baseUrl`,
-such as `http://127.0.0.1:11434/v1`. Configure the provider before creating a live
-session. Use the agent's `defaultModel`, or override `model` in `newSession()`.
-The resolved selection survives restart. Endpoint/API changes require a new name.
-
-Use `session.send(text, { instructionAddendum, limits })` for trusted application
-context and output limits that apply to only this turn. `limits.maxOutputTokensPerCall`
-defaults to 8,192 and is distinct from the total `maxOutputTokens` turn budget.
-Use `agent.newSession({ initialHistory })` to import a completed portable
-conversation without replaying its tools. `builtinTools: { askUser: false,
-readHistory: false }` on an agent suppresses those implicit tools even when the
-agent has application tools. See [session options and migration](../../docs/harness/guides/sessions.md)
-for full examples, validation limits and compatibility rules. These options need
-an updated native runtime; the client rejects unsupported hosts explicitly.
-
-`Harness.start()` accepts optional executable/state paths, `appId`,
-`sessions: { persist, directory }`, `scratch: { directory }`,
-`compaction: { triggerAtContextFraction, contextWindow }`, `modelProviders` and
-`mcpServers`. State defaults to the app directory under `~/.openworker`.
-The bundled executable is resolved without PATH lookup. Persistent state is the
-default; opting out does not erase workspace files or logs.
-
-`session.state()` reports active work, pending interactions and whether another
-message is admissible. `session.send({type:'approval', interactionId, decision:'once'})`
-and `session.send({type:'answer', interactionId, text})` are explicit controls.
-Strings or `{text}` are only messages. `run.events()` and `run.result()` are
-independent; stopping observation does not stop execution. Use `session.cancel()`.
-
-Secure keys use Windows DPAPI/macOS Keychain. Linux requires explicit `storage:
-'memory'` or server provisioning; no plaintext fallback. Application callbacks use
-private stdio, not a listening MCP server. Register them again after app restart.
-The SDK rebinds retained callbacks after child restart but never replays uncertain
-side effects. Callbacks retain the app's privileges, not an OS sandbox's.
-
-## Credentials, workspace and directory scope
-
-For `setModelProvider()` and the startup `modelProviders` convenience option,
-**Node resolves `apiKeyEnv`**, then sends the value to the managed Rust harness
-over private stdio. `inheritEnv` is unnecessary for this path. The SDK does not
-load `~/.env` automatically: use Node's `--env-file` or your application's loader
-before configuring providers. `storage: 'memory'` credentials must be supplied
-again when the app starts. Secure provider storage uses macOS Keychain or Windows
-DPAPI; Linux requires memory-only credentials or server provisioning.
-
-`inheritEnv: ['VARIABLE_NAME']` is for variables that Rust or another child
-process must resolve itself. The child otherwise receives a small OS allowlist
-and declared database/telemetry variables. Avoid passing the entire environment.
-
-```typescript
-const session = await agent.newSession({
- workspace: '/absolute/path/to/demo-files',
- scratch: false,
-});
-```
-
-`workspace` selects the working directory and supplies the base for supported
-built-in path checks and execution-backend mounts. Omitting it normally allocates
-a private scratch workspace under the configured scratch root. `scratch: false`
-requires an explicit workspace; `scratch: true` cannot accompany one. Scratch does
-not mean files will be automatically deleted. State and workspace retention are
-application lifecycle decisions.
-
-With `sandbox: 'off'`, an application callback has the application's privileges.
-**Setting `workspace` does not confine arbitrary Node filesystem calls.** Enforce
-scope inside each callback, including both ends of a move. The bundled file tools
-canonicalize their root, reject traversal/absolute paths and symlinks, bound reads
-and avoid overwrites. They assume an app-owned directory without concurrent
-untrusted writers; path checks are not a kernel isolation boundary. Exposing a
-shell would give the model a way around those restricted handlers.
-
-For hostile code, run tools in an isolated execution backend such as OpenShell.
-Configuring that backend does not automatically move arbitrary Node callbacks
-inside its sandbox. See [tool scope](../../skills/openworker-harness-builder/references/tools.md)
-and [OpenShell integration](../../docs/harness/guides/openshell.md).
-
-## Tool names, arguments and activity
-
-Register/select `files.move_file`; its model-facing alias is `files__move_file`.
-Current events and approval requests may contain the alias. Use the tool registry's
-known mapping for UI labels and preserve the original identifiers in saved data.
-
-Typed `tool_started` / `tool_finished` summaries contain the name and `callId`,
-not arguments. Arguments are supplied directly to the application callback and
-are available in the raw start event:
-
-```typescript
-if (item.event.type === 'tool_started') {
- const data = item.event.data as Record<string, unknown>;
- updateActivity({ sessionId: item.sessionId, turnId: item.event.turn_id,
- callId: data.call_id, tool: data.name, arguments: data.arguments });
-}
-```
-
-`updateActivity` is application UI code. Retain arguments from the start/callback
-for the finished row; support absent or withheld data. Upsert by
-`(sessionId, turnId, callId)`, because callback delivery can precede consumption of
-`tool_started`. Render only appropriate argument fields as escaped text; arguments
-can contain sensitive user data. `context.progress(message, data)` provides
-intermediate updates without adding polling. `model_activity` reports elapsed
-model waiting time, not completion of task work.
-
-## Application-tool screenshots
-
-An application callback can explicitly return one image alongside JSON metadata:
-
-```typescript
-import { ToolImageResult } from '@openworkerai/harness-sdk';
-// Inside execute(): capture only the app-authorized surface.
-return new ToolImageResult(
- { width: 960, height: 600, scope: 'game-preview' },
- { mimeType: 'image/jpeg', base64: screenshotBytes.toString('base64') },
-);
-```
-
-Requires a matching host advertising `application_tool_images` and a vision-capable
-model. JPEG/PNG only, one image, at most 768,000 base64 characters; ordinary metadata
-retains its 128,000-character bound. The host validates image signatures. Only the
-latest image per session is kept ephemerally for up to five minutes; durable events
-and history contain a reference, not pixels. Older images must be recaptured when
-needed. The provider receives pixels and applies its own retention rules. This API
-does not grant capture permission or make callbacks sandboxed: applications must
-authorize and constrain what they capture. Plain JSON return values are unchanged.
-
-## Chat Completions streaming compatibility
-
-Google Gemini's compatible endpoint supports signed tool conversations; the
-harness preserves provider-private thought signatures across tool results and
-restart. See [Gemini tool conversations](../../docs/harness/guides/providers.md#gemini-tool-conversations).
-Anthropic Messages enables automatic prompt caching by default; use
-`promptCaching: false` to opt out. See [Anthropic prompt caching](../../docs/harness/guides/providers.md#anthropic-prompt-caching).
-
-The harness requests streaming token usage by default. Set `streamUsage: false`
-on `setModelProvider({ api: "chat-completions", ... })` only when a compatible
-server rejects `stream_options`. This persisted setting survives credential
-rotation; omitting it during re-registration preserves the existing choice.
-Missing usage remains unknown, not zero. See
-[streaming token usage](../../docs/harness/guides/providers.md#streaming-token-usage).
-
-For partner proxies with short-lived bearer JWTs, use `auth.getToken` and
-`harness.updateProviderCredentials()`. See [models and credentials](../../docs/harness/guides/providers.md) for provider setup.
-Use a matching SDK/native runtime; access tokens stay in memory.
-
-The Rust host accepts both OpenAI's empty-choices usage trailer and OpenRouter's
-content-free usage trailer that repeats the finish reason. The latter must match
-the generation and finish reason, contain valid usage and no new text/tool payload,
-and still end with `[DONE]`. It does not create another message or execute a tool
-twice. This behavior lives in the Rust runtime: updating the TypeScript package
-alone will not fix an older bundled executable. Update a custom partner executable too; the published SDK installs its matching runtime.
-
-Incremental text is available in `run.events()` as the raw event
-`event.type === "assistant_delta"`, with `event.data.text` and
-`event.data.attempt_id`. Summaries of type `message` describe completed messages,
-not text deltas. Keep partial output grouped by attempt and handle failed/retried
-attempts separately; do not blindly concatenate a failed attempt into its retry.
-The game-builder starter's existing UI displays progress and completed messages;
-incremental-text rendering is a separate UI improvement.
-
-For typed attempt events, opt-in reasoning display, optional attempt buffering and
-safe provider diagnostics, see [Streaming and retries](../../docs/harness/guides/streaming.md).
-`AttemptOutput` provides a bounded UI projection that removes failed candidates.
-
-Application tools receive `context.callId`. Tool-start and tool-finish summaries
-expose that same ID as `item.summary.callId`; the raw journal uses
-`item.event.data.call_id`. Use it to correlate calls, including repeated calls to
-the same tool. The runtime records `tool_started` before executing the callback,
-but callback delivery and journal consumption are independent: your callback can
-run before your event iterator observes that record. Do not make a callback wait
-for the UI to consume `tool_started`.
-
-Providers may reuse call IDs in later turns. Upsert UI entries by
-`(sessionId, turnId, callId)` from either channel. A late start event
-should enrich an existing entry without resetting an already finished status:
-
-```ts
-// In the application's tool callback:
-toolRows.upsert(context.sessionId, context.turnId, context.callId, { label: "Showing preview" });
-
-// In the application's run event loop:
-const summary = item.summary;
-if (summary?.type === "tool_started" || summary?.type === "tool_finished") {
- toolRows.upsert(item.sessionId, item.event.turn_id, summary.callId, {
- tool: summary.tool,
- ...(summary.type === "tool_finished" ? { status: "finished" } : {}),
- });
-}
-```
-
-`toolRows` above represents your UI state store, not an SDK object. The same IDs
-are preserved when you consume the journal after the run has already completed.
-
-To run the synthetic OpenRouter compatibility tests against a built native host:
-
-```sh
-# Set OW_TS_TEST_HOST to an absolute openworker-harness executable path.
-npm run test:openrouter-streaming
-```
-
-These tests use loopback HTTP, the real Rust runtime, and private stdio. They cover
-incremental delivery, usage trailers, approval-gated fragmented tool calls and
-rejection of content/conflicts after completion. No cloud key or request is used.
-
-## Existing coworker packages
-
-Trusted application code can load an existing coworker package without rewriting
-its MCP/policy configuration as an inline agent:
-
-```typescript
-const harness = await Harness.start({
- executable, stateDir, sandbox: 'off', // Explicit host execution for this app.
- coworkers: [{ bundle: bundlePath, model: modelId,
- servers: serversPath, toolPolicy: classificationPath,
- runtimePolicy: resourcePolicyPath }],
-});
-```
-
-Paths must be absolute. Package policy remains authoritative. An optional
-`onJournalHint((method, params) => ...)` subscription exposes `session/event` and
-`stream/gap` as best-effort wakeups; return its unsubscribe function when done.
-Use durable snapshots and event cursors to reconstruct the UI, not the hints alone.
-Most apps should use `run.events()` instead. See the desktop starters for
-SDK-owned process recovery and conversation restoration.
-
-## Register agents after startup
-
-The host can start without `agents`. `createAgent()` returns a reusable handle;
-`ready()` confirms registration, and `newSession()` also waits for it. Definitions
-persist under the app's state directory, so managed process recovery does not lose
-them. Exact repeats are idempotent; changed definitions need a new agent name.
-
-```typescript
-const harness = await Harness.start({ executable, stateDir });
-const builder = harness.createAgent({
- name: "builder",
- instructions: "Build the requested project.",
- tools: ["game.read_file"], // Must already exist in the harness/MCP registry.
- defaultModel: { provider: "OpenAI", name: modelId },
- servers: serversPath,
-});
-await builder.ready();
-// Configure the shared OpenAI provider before creating a live session.
-const session = await builder.newSession({ workspace });
-// Optional per-session override, leaving the definition unchanged:
-const other = await builder.newSession({
- workspace, model: { provider: "OpenAI", name: otherModelId },
-});
-```
-
-`listAgents()` reads the current catalog. The `agents` property is the startup
-snapshot. `resumeSession(reference)` checks the session's actual agent identity.
-The advanced example below retains the lower-level API for custom integrations.
-New applications should use shared providers and `createAgent()` above.
-
-## Install and pair with a runtime
-
-The published SDK and all platform runtimes use version `0.1.0-beta.3`.
-
-The client installs the matching `@openworkerai/harness-runtime-<platform>-<arch>`
-optional dependency. That package contains the prebuilt executable. Keep optional
-dependencies enabled: there is no postinstall download or compilation, and the
-application does not fetch a helper at startup. Electron apps must bundle the
-helper outside ASAR; `resolveRuntimeExecutable()` returns its installed path.
-
-For an unpublished candidate, install the exact client and platform archives
-supplied by its maintainer together. A source manifest is not a registry release.
-The source package remains private; use the release preparer to stage artifacts.
-
-For a custom native tool registry, build a partner executable from the same SDK
-revision and pass its absolute path through `executable`. The partner entry point
-registers those tools with `openworker_sdk::cli::main_with_registry(registry)`.
-Keep SDK and executable versions paired; protocol 0.1 alone does not promise
-compatibility between arbitrary releases.
-
-## Advanced: explicit executables and connection APIs
-
-Run the included example with an absolute `OPENWORKER_BIN`, an available model ID
-in `OPENWORKER_MODEL`, and a privately supplied `OPENAI_API_KEY`:
-
-```sh
-node examples/quickstart.mjs /absolute/path/to/demo-data
-```
-
-It registers the included Node MCP echo provider, asks for human approval, runs
-one tool, saves a session reference, and shuts down. `sandbox: "off"` is explicit
-and **provides no isolation**; only use this example with trusted tools. OpenShell
-is the SDK default and requires the corresponding environment/setup and tool
-placement policy. Scripted acceptance can use `OW_EXAMPLE_SCRIPTED=1` with a
-test-support binary; that is not a live model demonstration.
-
-The following lower-level API is retained for integrations that need an explicit
-custom executable, startup agent definitions and per-agent connections:
-
-```typescript
-import { Harness, type Agent } from '@openworkerai/harness-sdk';
-
-const assistant: Agent = {
- id: 'assistant',
- instructions: 'Research the user question and cite your sources.',
- tools: ['acme.search'], // Must exist in your binary registry or configured MCP provider.
- servers: '/absolute/path/to/servers.json',
- model: { connection: 'primary', model: process.env.OPENWORKER_MODEL! },
- planning: true,
-};
-
+const model = process.env.OPENWORKER_MODEL;
+if (!model) throw new Error('Set OPENWORKER_MODEL');
const harness = await Harness.start({
- executable: '/absolute/path/to/partner-harness',
- stateDir: '/absolute/path/to/private-state',
- agents: [assistant],
- storage: { type: 'sqlite' },
- sandbox: 'off', // Trusted local smoke test only.
+ stateDir: resolve('.openworker-state'), sandbox: 'off',
});
try {
- await harness.setConnection({
- coworker: 'assistant', id: 'primary', label: 'OpenAI',
- provider: 'openai', apiKey: process.env.OPENAI_API_KEY!,
+ await harness.setModelProvider({
+ name: 'OpenAI', api: 'responses',
+ baseUrl: process.env.OPENWORKER_MODEL_URL ?? 'https://api.openai.com/v1',
+ credentials: { apiKeyEnv: 'OPENAI_API_KEY', storage: 'memory' },
});
- const session = await harness.session('assistant', {
- workspace: '/absolute/path/to/existing-project',
+ const agent = harness.createAgent({
+ name: 'first-agent-v1', instructions: 'Give concise, helpful answers.',
+ defaultModel: { provider: 'OpenAI', name: model },
+ tools: [], planning: false, memory: false, scheduling: false,
});
- const result = await session.run('Compare database options.');
- if (result.status === 'interrupted') {
- // Render result.interruptions in your UI. Do not invent user responses.
- } else {
- console.log(result.status, result.finalOutput);
- }
+ const session = await agent.newSession();
+ const result = await session.run('Suggest three names for a file-organizing app.');
+ if (result.status !== 'completed') throw new Error(`Run ended: ${result.status}`);
+ console.log(result.finalOutput);
} finally {
await harness.shutdown();
}
```
-State, workspace, bundle and configuration paths must satisfy the Rust host's
-containment rules. `acme.search` is illustrative, not a bundled built-in.
-The complete runnable echo example avoids this placeholder.
-
-## Approvals and questions
-
-Configure `approvals` when creating an agent:
-
-| Configuration | Behavior | Typical use |
-| --- | --- | --- |
-| `{ mode: 'always' }` | Requests human approval unless a valid session grant covers the tool. This is the default. | Interactive control. |
-| `{ mode: 'only', tools: ['files.move_file'] }` | Requests approval for listed tools; ordinary unlisted tools receive application-policy approval. | Approve writes while allowing reads. |
-| `{ mode: 'auto', reviewerModel: { provider: 'OpenAI', name: modelId } }` | Uses an explicitly selected model to review eligible calls: allow executes, deny returns a denial, uncertain requests human input. | Model-assisted approval. |
-| `{ mode: 'never' }` | Bypasses approval review; hard security checks still apply. | Trusted unattended workflows. |
-
-`auto` does not mean unconditional approval. Read-only tools can be reviewed too;
-hard denials and valid session grants are handled first. Privileged dynamic
-agent-type/child-creation tools have additional checks: their absence from an
-`only` list does not automatically exempt them. None of these modes substitutes
-for sandbox isolation or callback scope checks.
-
-Human responses are `{ decision: 'once' }`, `{ decision: 'deny' }`, or
-`{ decision: 'session' }`. Use `once` when each mutation requires approval.
-A session grant covers the entire tool, including different valid arguments,
-and survives restart. It does not override hard security checks. Structured
-questions use `{ answer: userText }` separately; disable `builtinTools.askUser`
-if the product does not support questions.
-
-### Stream, approve and continue the same turn
-
-This helper supplies the full loop. The app provides escaped-text rendering,
-activity UI and an approval card showing both `pending.tool` and
-`pending.arguments`.
-
-```typescript
-import { AttemptOutput, type Session, type RunEvent, type Interruption }
- from '@openworkerai/harness-sdk';
-
-type Approval = Extract<Interruption, { kind: 'approval' }>;
-export async function streamWithApprovals(session: Session, text: string, ui: {
- renderText(text: string): void;
- renderActivity(event: RunEvent): void;
- approve(proposal: Approval): Promise<boolean>;
-}) {
- const display = new AttemptOutput();
- let stream = (await session.send(text)).events();
- while (true) {
- for await (const event of stream) {
- display.apply(event);
- ui.renderText(display.text); // Replace; do not append the whole projection.
- ui.renderActivity(event);
- }
- const result = await stream.result();
- if (result.status !== 'interrupted') {
- if (result.status === 'completed') ui.renderText(result.finalOutput ?? display.text);
- else { display.interrupt(); ui.renderText(display.text); }
- return result;
- }
- if (!result.interruptions.length) throw new Error('No pending interaction');
- for (const pending of result.interruptions) {
- if (pending.kind !== 'approval') return result; // Route questions/safety separately.
- const allowed = await ui.approve(pending);
- await session.respond(pending, { decision: allowed ? 'once' : 'deny' });
- }
- stream = await session.resumeStreamed(stream.checkpoint());
- }
-}
-```
-
-Do not resend the user message to continue after approval: retain the submission
-and consumed cursors. Use `session.cancel()` for Stop. Closing an observer does not
-cancel execution or justify automatic approval. Persist the session reference
-and stream checkpoint for crash recovery, then reconcile pending interactions.
-For a non-streaming flow, `session.runWith(input, handler)` invokes a real app
-handler for interruptions; `{ defer: true }` leaves the decision pending.
-
-### Auto-approver decisions in the UI
-
-The typed `auto_approved` summary currently means **application-policy approval**,
-such as an ordinary unlisted tool under `only`. It is not a model review verdict.
-Raw `interaction_required` / `interaction_resolved` events contain
-`event.data.review.verdict` and a safe `reason` when available, plus `origin` and
-nested `call.call_id`. Handle absent/withheld fields when displaying them.
-
-Currently, a denied tool response tells the working model that execution was denied
-and not to retry or evade the decision. The reviewer's reason is not included in
-that tool response. The application can display an available safe journal reason;
-do not assume the model has received it.
-
-## Streaming and recovery
-
-```typescript
-const stream = await session.runStreamed('Review the project', {
- submissionId: savedRequestId,
-});
-for await (const event of stream) {
- // Forward event.summary/event.event to your UI; after processing, persist
- // stream.checkpoint() alongside session.reference().
-}
-const result = await stream.result(); // Includes pending interruptions.
-```
-
-Streaming reads the durable journal with bounded long-polls, not just transient
-notifications. Events include raw records and typed summaries. A slow reader does
-not stall Rust execution or accumulate an unbounded SDK queue. All pages are
-drained even when the host already reports completion. Only one consumer at a
-time; after breaking iteration you can continue it or call `result()` to drain.
-
-Save `session.reference()` as JSON; after application restart use
-`await harness.resume(reference)`, then `session.resume({ submissionId })`.
-For replay use `resumeStreamed({ submissionId, cursors })` with saved checkpoints.
-Without cursors, resume streaming starts at current journal positions. UI delivery
-is at-least-once across application crashes; deduplicate `(session_id,event_id)`.
-
-The SDK restarts the child up to three times by default. `await harness.ready()`
-waits for recovery; saved session objects remain usable. Journal reads reconnect
-automatically. **Mutations never retry automatically.** `HarnessError` distinguishes:
-
-- `Unavailable`: this request was not sent; wait for readiness.
-- `OutcomeUnknown`: it may have executed. Inspect durable state first.
-- `Remote`: the host rejected it. Raw tool/provider diagnostics are not reflected.
-- `Closed`, `Aborted`, `InvalidInput`, `Protocol`, `Setup`: explicit client states.
-
-`run()` errors carry `context.submissionId`; persist your own ID before sending if
-you must survive an app crash. To reconcile a lost `run/start` response, reuse the
-**same ID and text**; the host deduplicates it. Do not automatically replay tool
-calls. Team mutations accept explicit request IDs and include them in error context.
-`agent/session` is not idempotent: a lost creation response requires reconciliation
-through the session catalog, not a blind second creation.
-
-`AbortSignal` stops waiting (normally within the bounded long-poll); it does not
-cancel agent work. Use `session.cancel()` for active turns, or
-`session.cancel({ endTeam: true })` to cancel queued team work too. `session.close()`
-requires idle members. Partial member failures are errors, not reported successes.
-Cancellation is not rollback. PostgreSQL's durable call ledger can return
-`status: 'failed', failure: 'interrupted'` with an outcome-unknown journal record
-when a tool was already admitted but has no saved result. Preserve and display
-that uncertainty; do not relabel it as cleanly cancelled or automatically retry.
-SQLite's local cancellation does not expose that same server call-ledger detail.
-Always await `harness.shutdown()`; it closes stdin gracefully, then force-stops a
-child that exceeds the shutdown deadline. It does not erase durable state.
-
-## Teams and storage
-
-Add `subagents: [workerDefinition]` to a lead Agent. Starting the lead provisions
-the team and member sessions. Worker approvals appear in the lead run, tagged by
-agent and worker session ID. `session.team()` exposes `board`, `events`,
-`createItem`, `assign`, `transition`, `postMessage` and `cancel`.
-Application callbacks return bounded JSON. Changed callback semantics should use
-a new qualified name/version; descriptor identity is immutable. Consult the
-installed declarations and runtime capabilities for team limits and timer support.
-
-```typescript
-storage: {
- type: 'postgres', connectionEnv: 'DATABASE_URL', schema: 'ow_product',
- caFile: '/absolute/path/to/root-ca.pem',
-}
-```
-
-Run the existing Rust storage migration **explicitly before startup**, using
-`Storage::migrate()`; follow the
-[storage migration instructions](../../docs/harness/guides/guardrails.md#upgrade-an-existing-installation). Node does not implement
-SQL adapters or run unrequested migrations. The same agent/team APIs work with
-either store. A PostgreSQL SDK host is **one supervisor per schema**, not a
-multi-node worker pool; use the distributed server deployment for that role.
-
-## Tools, credentials and process boundaries
-
-Named multi-instance teams use `harness.newTeam(...)` and optional
-`delegation: { tools: ["coding.read_file"] }`. This exposes `team_define_type`
-under the app's ceiling. Exact approvals and private role revisions survive
-restart on either database; they are not global agent registrations. See
-[Sessions and teams](../../docs/harness/guides/sessions.md).
-Run `npm run test:team-types` with `OW_TS_TEST_HOST` and, for PostgreSQL,
-an isolated `OW_PG_TEST_URL` to exercise both real managed-process adapters.
-
-- TypeScript app tools use callbacks over private stdio. External tools can use
- app-configured MCP servers. Rust-native tools are compiled into the selected
- partner executable.
-- Agent definitions are serialized data; JS callbacks cannot cross stdio.
-- Agents can be registered after startup. Changing a persisted definition requires
- a new agent name; new sessions alone do not replace that identity.
-- Configure shared providers through `setModelProvider`; keep credentials outside
- prompts/configuration files/argv. The lower-level `setConnection` remains
- available for advanced per-agent integrations.
-- Application callbacks must be registered again when the app starts. The SDK
- rebinds retained callbacks after managed-child recovery but never automatically
- replays uncertain side effects.
-- Readiness does not imply that memory-only provider keys have been configured.
- Handle credential-provider errors and resupply credentials on application restart.
-- TypeScript does not embed Rust in-process or run in the browser. Local execution
- and distributed service deployment are separate integration choices.
-
-## Verification
-
```sh
-npm ci
-npm test
-cd ..
-cargo build --locked -p openworker-sdk --features test-support --bin sdk-test-host
-cd typescript-sdk
-OW_TS_TEST_HOST=/absolute/path/to/sdk-test-host npm run test:integration
+node --env-file=/path/to/private.env agent.mjs
```
-Run integration on Linux. Set `OW_PG_TEST_URL` to a disposable loopback PostgreSQL
-database to include that adapter; the fixture creates fresh schemas and migrates
-them explicitly. No provider secrets needed. The unit suite runs process faults
-on macOS/Linux. Platform-native Windows and live-model qualification remain
-separate; cross-platform Node APIs alone are not evidence of Windows acceptance.
-
-### Turn limits
-
-Agent definitions accept `limits: { maxModelCalls, maxOutputTokens, summaryTokens? }`.
-A new message can override them with `session.send(text, { limits })`; the service
-SDK accepts the same limits plus its usual `idempotencyKey`. Resuming keeps the
-original budget. See [Sessions and teams](../../docs/harness/guides/sessions.md)
-for counting rules, the final-summary reserve and sandbox-owned process tools.
-
-### Service teams with private types
-
-`ServiceSession.createTeam` accepts optional `delegation: { tools, models? }`.
-Tools must belong to the lead's activated release; models must be explicitly
-allowed by that release. The lead can then use `team_define_type` through the
-existing exact-definition approval flow. Definitions remain private to that lead.
-The service controller and worker restore the same approved revision after restart.
-This adapter currently shares the original team environment; nondefault remote
-workspace/new/member placement is still gated. See the
-[Sessions and teams](../../docs/harness/guides/sessions.md).
-
-### Standalone sub-agents
-
-Set `subagents: { enabled: true }` on an ordinary agent to let its model create
-children, message them and wait for results. Each child starts fresh with an explicit
-tool subset. The legacy `subagents: Agent[]` form remains unchanged. This requires
-a matching runtime advertising `standalone_subagents`, available in 0.1.0-beta.3.
-See [standalone sub-agents](../../docs/harness/guides/sessions.md#standalone-sub-agents)
-for limits, approvals and shared-sandbox behavior.
-
-
-## Optional turn traces and evaluation evidence
-
-SDK/runtime 0.1.0-beta.3 includes opt-in recording, per-turn timeline/grouped queries,
-child drill-down and durable evaluation results. Recording and evaluation delivery
-are disabled until configured; browser UI is a separate optional component.
-See the [observability guide](../../docs/harness/guides/observability.md) for local
-SQLite/PostgreSQL, Langfuse export, content selection and audit references. These APIs require matching SDK/runtime versions and advertised capabilities.
+`OPENWORKER_MODEL_URL` optionally selects another Responses-compatible endpoint.
-## User attachments
+This text-only example exposes no tools and explicitly disables sandboxing.
+When adding tools, choose their execution boundary deliberately. Node callbacks
+retain your app's privileges; `workspace` alone does not confine filesystem access.
+See [custom tools and scope](../../docs/harness/guides/tools.md).
-Attach images, PDFs and UTF-8 text files to a session with ordered content and
-immutable recovery references. See [Attachments](../../docs/harness/guides/attachments.md)
-for the Rust/TypeScript APIs, service uploads, limits and upgrade instructions.
-Available in SDK/runtime 0.1.0-beta.3; update a custom executable along with its client.
+## Build with your coding agent
-### Auto-approver and compaction guidance
-
-Supply application facts to the auto-approver and extra instructions to the
-compactor when defining an agent or starting a session:
-
-```ts
-const session = await agent.newSession({
- autoApproverContext: "This is a staging workspace. Ask before publishing.",
- compaction: {
- additionalInstructions: "Preserve architectural decisions and unfinished tests.",
- },
-});
-
-await session.run("Continue the implementation.", {
- autoApproverContext: "For this turn, changes must remain inside src/.",
- compaction: { additionalInstructions: "Keep the migration checklist." },
-});
-```
-
-Precedence is agent → session → turn. Session defaults and accepted turn options
-survive restart. Omit a field to inherit it; use `""` to clear inherited guidance
-for that scope. A turn override does not change the next turn's defaults. Each
-string is limited to 32,000 UTF-8 bytes and cannot contain NUL. Reusing a submission
-ID with different guidance is rejected. These options require an updated runtime
-advertising `application_guidance`.
-
-Reviewer context is separate from the working agent's instructions and from user
-history. Enable auto-approval with `approvals: { mode: "auto", reviewerModel }`;
-context alone never enables it or grants permissions. Hard restrictions still
-apply first. Summary guidance supplements the required summary structure.
-These options are available for embedded/managed SDK sessions; the service-cluster
-REST client does not yet expose these overrides.
+```sh
+npx @openworkerai/openworker-harness-builder --agent claude --project .
+```
+
+Use `--agent codex` for Codex or `--global` for user-wide installation. Existing
+installs prompt before replacement; `--replace-existing` skips the prompt and
+saves a backup. The Skill's `installation.json` records its tested SDK version.
+See the [Skill guide](../../skills/README.md) and runnable
+[file-organizer example](../../skills/openworker-harness-builder/references/local-script.md).
+
+## Add the next capability
+
+| You want to… | Start here |
+| --- | --- |
+| Add tools and show their arguments | [Tools and MCP](../../docs/harness/guides/tools.md) |
+| Stream text and handle approval cards | [Streaming and approval loop](../../docs/harness/guides/streaming.md#streaming-with-tool-approvals) |
+| Change models or refresh credentials | [Models and credentials](../../docs/harness/guides/providers.md) |
+| Resume a conversation or delegate work | [Sessions and teams](../../docs/harness/guides/sessions.md) |
+| Accept images, PDFs and text files | [Attachments](../../docs/harness/guides/attachments.md) |
+| Isolate tools and inspect content | [OpenShell](../../docs/harness/guides/openshell.md) · [Guardrails](../../docs/harness/guides/guardrails.md) |
+| Inspect turns and export traces | [Observability](../../docs/harness/guides/observability.md) |
+| Run a shared service | [Deployment options](../../docs/harness/guides/deployment.md) |
+
+## Integration contract
+
+- Start one harness for the app/service lifecycle; always shut it down on exit.
+- Use `createAgent` and `setModelProvider` for new apps. Explicit executables,
+ startup agent arrays and `setConnection` are advanced interfaces.
+- Agent definitions are immutable in durable state. Change the name when changing
+ instructions, tools or approval mode. Identical registration is safe.
+- Node resolves `apiKeyEnv` and sends the key over private stdio. `inheritEnv` is
+ unnecessary for this credential path. Memory-only keys must be resupplied after
+ app restart; the SDK does not load env files automatically.
+- Save `session.reference()` and use `agent.resumeSession(reference)` for recovery.
+ Stopping observation does not cancel work; use `session.cancel()` for Stop.
+- Never automatically retry an action whose outcome is unknown. Reconcile durable
+ state and the external system first.
+
+See [versions and compatibility](../../docs/harness/guides/releases.md) and
+[troubleshooting](../../docs/harness/guides/troubleshooting.md).
diff --git a/skills/snippets.test.mjs b/skills/snippets.test.mjs
index 50309d93..aafa5bc1 100644
--- a/skills/snippets.test.mjs
+++ b/skills/snippets.test.mjs
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
-test('Skill options and README approval loop compile against the SDK declarations', async () => {
+test('Skill, package README and shared guide examples compile against the SDK declarations', async () => {
const sdk = resolve('harness/typescript-sdk');
const root = await mkdtemp(join(tmpdir(), 'ow-skill-snippets-'));
try {
@@ -12,9 +12,13 @@ test('Skill options and README approval loop compile against the SDK declaration
await symlink(sdk, join(root, 'node_modules/@openworkerai/harness-sdk'), 'junction');
await writeFile(join(root, 'package.json'), '{"type":"module"}');
const readme = await readFile(join(sdk,'README.md'),'utf8');
- const approvalSection = readme.split('### Stream, approve and continue the same turn')[1]?.split('### Auto-approver decisions in the UI')[0];
- if (!approvalSection) throw Error('Missing README approval loop');
- const text = (await Promise.all(['runtime-options.md','subagents.md'].map(name=>readFile('skills/openworker-harness-builder/references/'+name,'utf8')))).join('\n')+'\n'+approvalSection;
+ const streaming = await readFile('docs/harness/guides/streaming.md','utf8');
+ const approvalSection = streaming.split('### Stream, approve and continue the same turn')[1];
+ if (!approvalSection) throw Error('Missing shared streaming approval loop');
+ const tools = await readFile('docs/harness/guides/tools.md','utf8');
+ const callbackSection = tools.split('## Register an application callback')[1]?.split('## Tool names and directory scope')[0];
+ if (!callbackSection) throw Error('Missing app callback example');
+ const text = (await Promise.all(['runtime-options.md','subagents.md'].map(name=>readFile('skills/openworker-harness-builder/references/'+name,'utf8')))).join('\n')+'\n'+readme+'\n'+approvalSection+'\n'+callbackSection;
const files = [];
for (const [index, match] of [...text.matchAll(/```typescript\r?\n([\s\S]*?)```/g)].entries()) {
const file = join(root, `example-${index}.ts`);