Skip to content
Python

docs: clarify SDK tools, approvals and builder skill usage

Rohit P43f7e63c8071
diff --git a/.github/workflows/sdk-skills.yml b/.github/workflows/sdk-skills.yml
index 6b5d68ee..8438318f 100644
--- a/.github/workflows/sdk-skills.yml
+++ b/.github/workflows/sdk-skills.yml
@@ -2,10 +2,10 @@ name: SDK skills
on:
pull_request:
- paths: ["skills/**", "harness/release/**", ".github/workflows/sdk-skills.yml"]
+ paths: ["skills/**", "harness/release/**", "harness/typescript-sdk/README.md", ".github/workflows/sdk-skills.yml"]
push:
branches: [main]
- paths: ["skills/**", "harness/release/**", ".github/workflows/sdk-skills.yml"]
+ paths: ["skills/**", "harness/release/**", "harness/typescript-sdk/README.md", ".github/workflows/sdk-skills.yml"]
workflow_dispatch:
permissions:
@@ -22,7 +22,7 @@ jobs:
node-version: 24
# No Rust build, Docker daemon, cloud credentials or model calls required.
- name: Test SDK compatibility and standalone skill installation
- run: node --test skills/install.test.mjs skills/package.test.mjs harness/release/contract.test.mjs
+ run: node --test skills/install.test.mjs skills/package.test.mjs skills/local-script.test.mjs harness/release/contract.test.mjs
- name: Compile skill examples against the SDK
run: |
npm --prefix harness/typescript-sdk ci
diff --git a/docs/harness/guides/desktop.md b/docs/harness/guides/desktop.md
index 16ff393a..da049d7e 100644
--- a/docs/harness/guides/desktop.md
+++ b/docs/harness/guides/desktop.md
@@ -35,7 +35,7 @@ Install the shared [OpenWorker app-building skill](../../../skills/README.md),
then paste this prompt into Codex or Claude Code in your app project:
```text
-Use the openworker-apps skill to build a desktop app that summarizes a
+Use the openworker-harness-builder skill to build a desktop app that summarizes a
selected code directory. Start from Code Atlas and explain the SDK calls as
you build. Run the relevant tests and prepare a local package.
```
@@ -50,13 +50,13 @@ skill. No OpenWorker repository checkout is required.
### Codex
```sh frame="none"
-npx @openworkerai/build-with-sdk-skills --agent codex --project .
+npx @openworkerai/openworker-harness-builder --agent codex --project .
```
### Claude Code
```sh frame="none"
-npx @openworkerai/build-with-sdk-skills --agent claude --project .
+npx @openworkerai/openworker-harness-builder --agent claude --project .
```
<!-- /sdk-install-tabs -->
@@ -65,7 +65,7 @@ Open a new coding-agent session in that project. The installer copies the same
skill, SDK snippets and Desktop/Web references into the tool's project skills directory.
For all your projects on this machine, replace `--project .` with `--global`.
That installs to your user skills directory; neither mode overwrites an existing
-skill. The `--global` option is new in the pending skills `0.1.0-beta.2` release.
+skill. Both project and global installation are available in the published Skill.
See the [skill installation guide](../../../skills/README.md) for availability,
local candidate installation and invocation details.
diff --git a/docs/harness/guides/server.md b/docs/harness/guides/server.md
index b4910ee7..120b8c26 100644
--- a/docs/harness/guides/server.md
+++ b/docs/harness/guides/server.md
@@ -35,7 +35,7 @@ Install the shared [OpenWorker app-building skill](../../../skills/README.md),
then paste this prompt into Codex or Claude Code in your app project:
```text
-Use the openworker-apps skill to build a web app where I can upload a PDF
+Use the openworker-harness-builder skill to build a web app where I can upload a PDF
and ask questions with page references. Start from PDF Notes, explain the
agent and session code, and prepare container deployment files.
```
@@ -50,13 +50,13 @@ skill. No OpenWorker repository checkout is required.
### Codex
```sh frame="none"
-npx @openworkerai/build-with-sdk-skills --agent codex --project .
+npx @openworkerai/openworker-harness-builder --agent codex --project .
```
### Claude Code
```sh frame="none"
-npx @openworkerai/build-with-sdk-skills --agent claude --project .
+npx @openworkerai/openworker-harness-builder --agent claude --project .
```
<!-- /sdk-install-tabs -->
@@ -65,7 +65,7 @@ Open a new coding-agent session in that project. The installer copies the same
skill, SDK snippets and Desktop/Web references into the tool's project skills directory.
For all your projects on this machine, replace `--project .` with `--global`.
That installs to your user skills directory; neither mode overwrites an existing
-skill. The `--global` option is new in the pending skills `0.1.0-beta.2` release.
+skill. Both project and global installation are available in the published Skill.
See the [skill installation guide](../../../skills/README.md) for availability,
local candidate installation and invocation details.
diff --git a/docs/harness/guides/sessions.md b/docs/harness/guides/sessions.md
index 3c7c284f..0ddb2463 100644
--- a/docs/harness/guides/sessions.md
+++ b/docs/harness/guides/sessions.md
@@ -209,7 +209,7 @@ Defaults allow four active children and 32 retained child identities. Shared sco
budgets count parent and child work; children cannot reset the allowance or spawn
further descendants. Existing explicit teams remain available separately.
-See the [complete tool contract and configuration](../../../skills/openworker-apps/references/subagents.md).
+See the [complete tool contract and configuration](../../../skills/openworker-harness-builder/references/subagents.md).
## Teams
diff --git a/harness/release/contract.test.mjs b/harness/release/contract.test.mjs
index 639ea874..a7212405 100644
--- a/harness/release/contract.test.mjs
+++ b/harness/release/contract.test.mjs
@@ -17,7 +17,8 @@ test('release versions and publishable Rust dependency closure agree',()=>{
assert.ok(existsSync(join(root,pkg.directory,'LICENSE')));
}
for(const folder of ['typescript-sdk','desktop-starters'])assert.equal(JSON.parse(readFileSync(join(root,folder,'package.json'))).version,manifest.version);
- assert.equal(JSON.parse(readFileSync(join(root,'../skills/package.json'))).openworkerSdkVersion,manifest.version);
+ // Skill compatibility is pinned/tested by its standalone package tests. Its
+ // published consumer SDK may differ from this native-release source manifest.
assert.ok(readFileSync(join(root,'typescript-sdk/src/version.ts'),'utf8').includes(JSON.stringify(manifest.version)));
assert.equal(new Set(manifest.targets.map(t=>t.rust)).size,manifest.targets.length);
});
diff --git a/harness/typescript-sdk/README.md b/harness/typescript-sdk/README.md
index 16a0fa07..86113df2 100644
--- a/harness/typescript-sdk/README.md
+++ b/harness/typescript-sdk/README.md
@@ -1,13 +1,35 @@
# OpenWorker TypeScript Harness SDK
-Registry candidate: **0.1.0-beta.2**. After publication, install with `npm install @openworkerai/[email protected]`; the matching native runtime is selected automatically. Until then, use the locally prepared client and platform archives. See the [Desktop guide](https://openworker.com/docs/sdk/desktop/) and [app-building skill](https://github.com/andrewyng/openworker/tree/main/skills).
+Published SDK: **0.1.0-beta.3**, for Node.js 20+ and ESM.
-Beta API, Node.js 20+, ESM. Registry-ready source/tarball distribution. The Rust host owns model/tool execution, policy, persistence,
-agent teams and run semantics. This package owns typed APIs and a managed private
-stdio connection. No browser runtime, native Node binding, REST server, or Python
-dependency. Python/Desktop remains separate.
+```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.
+
+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):
+
+```sh
+npx @openworkerai/openworker-harness-builder --agent codex --project .
+# For Claude Code, use --agent claude. For user-wide installation, use --global.
+```
+
+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.
-## Desktop QuickStart
+## Create an agent with application tools
For service deployments, [OpenShell integration](../../docs/harness/guides/openshell.md)
covers `RuntimeProfile.gitAccess` and `runtimeProfileGrants(profile)`. These select
@@ -29,15 +51,16 @@ 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: 'secure' },
+ credentials: { apiKeyEnv: 'OPENAI_API_KEY', storage: 'memory' },
});
-// A key collected by your UI can instead be supplied as { apiKey, storage: 'secure' }.
+// 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 };
@@ -45,18 +68,39 @@ await harness.registerTools({ namespace: 'app', tools: {
},
}});
const agent = harness.createAgent({
- name: 'assistant', instructions: 'Help the user and report progress in the app.',
+ 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(); // Check interruptions; do not assume success.
+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).
@@ -103,6 +147,73 @@ 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:
@@ -116,7 +227,7 @@ return new ToolImageResult(
);
```
-Requires a rebuilt host advertising `application_tool_images` and a vision-capable
+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
@@ -142,14 +253,14 @@ Missing usage remains unknown, not zero. See
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.
-This requires rebuilding the native harness; access tokens stay in memory.
+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. Rebuild your partner runtime too.
+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
@@ -251,16 +362,12 @@ const other = await builder.newSession({
`listAgents()` reads the current catalog. The `agents` property is the startup
snapshot. `resumeSession(reference)` checks the session's actual agent identity.
-The examples below also show the retained lower-level APIs. New applications should
-prefer shared providers and the desktop facade above.
+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
-After publication:
-
-```sh
-npm install @openworkerai/[email protected]
-```
+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
@@ -268,17 +375,9 @@ 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.
-Before publication, install the prepared client and your platform archive together:
-
-```sh
-npm install /absolute/release/openworkerai-harness-sdk-0.1.0-beta.2.tgz \
- /absolute/release/openworkerai-harness-runtime-darwin-arm64-0.1.0-beta.2.tgz
-```
-
-Choose the actual platform/architecture. The source manifest intentionally remains
-private and does not list unpublished runtime dependencies; use the repository's
-release preparer to stage distributable packages instead of publishing the source
-folder directly.
+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
@@ -286,7 +385,7 @@ 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.
-## QuickStart
+## 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`:
@@ -302,7 +401,8 @@ 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 core API in an installed consumer is:
+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';
@@ -348,22 +448,88 @@ The complete runnable echo example avoids this placeholder.
## Approvals and questions
-`session.run()` stops at completion, failure, cancellation or an interruption.
-After a real user decision:
+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
-await session.respond(interruption, { decision: 'once' });
-// Or: { decision: 'session' }, { decision: 'deny' }, { answer: userText }
-const result = await session.resume();
+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());
+ }
+}
```
-`session` approval covers the entire tool for this session, including changed
-valid arguments; grants survive restarts. `session.runWith(input, asyncHandler)`
-is available for inline UI/CLI handlers; return `{ defer: true }` to leave pending.
-Default policy asks. `approvals: { mode: 'only', tools: [...] }` is interrupt-on:
-the **Rust host approves unlisted tools once**, with durable `app_policy` attribution.
-Hard restrictions still apply. `reviewer` and `never` select the runtime reviewer
-and dangerous bypass modes; neither is a substitute for sandbox isolation.
+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
@@ -424,10 +590,9 @@ Add `subagents: [workerDefinition]` to a lead Agent. Starting the lead provision
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`.
-At most 15 workers per lead, 16 profiles per host, one subagent level and 1–64
-selected tools per agent. Application callbacks return bounded JSON. Changed
-callback semantics should use a new qualified name/version; descriptor identity
-is immutable. Timers and steering are reported as unsupported by `state()`.
+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: {
@@ -457,22 +622,18 @@ an isolated `OW_PG_TEST_URL` to exercise both real managed-process adapters.
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 are fixed at startup. Changing prompt/tools changes the pinned identity;
- create new sessions for changed definitions.
-- Model keys go through `setConnection`, not configuration/argv/agent prompts.
- They are memory-only by default, not cached by this SDK, and **must be supplied
- again after a process restart**. The app owns secure credential sourcing.
- Subscribe with `harness.onStateChange(listener)` to update the UI and resupply
- connections on `ready` after recovery; it returns an unsubscribe function.
- Handle asynchronous credential-provider errors in your application callback.
- Process readiness does not imply that memory-only model keys are configured.
- `persistence: 'secure'` is currently Windows DPAPI only; no plaintext fallback.
-- Only a small OS environment allowlist, the declared database/telemetry variables
- and explicit `inheritEnv` names reach the child. Do not broadly forward secrets.
-- For Anthropic, use `provider: 'anthropic'` on the model connection and the
- corresponding agent provider/fallback configuration. No TypeScript model driver.
-- No automatic binary download, npm publication, native in-process mode, browser
- secret handling, arbitrary JS tool callbacks, or distributed scheduling here.
+- 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
@@ -510,34 +671,32 @@ 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 (source preview)
+### 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 feature runtime; it is not in published runtime 0.1.0-beta.2.
+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
-The source candidate includes opt-in recording, per-turn timeline/grouped queries,
+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
-new APIs require matching local candidate builds and are not in the published
-0.1.0-beta.2 packages yet.
+SQLite/PostgreSQL, Langfuse export, content selection and audit references. These APIs require matching SDK/runtime versions and advertised capabilities.
-## User attachments (source preview)
+## User attachments
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`.
+Available in SDK/runtime 0.1.0-beta.3; update a custom executable along with its client.
-### Reviewer and summary guidance
+### 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:
diff --git a/skills/README.md b/skills/README.md
index 1d6b1e6d..032b7b4a 100644
--- a/skills/README.md
+++ b/skills/README.md
@@ -1,49 +1,49 @@
# Build apps with the OpenWorker skill
-One `openworker-apps` skill helps Codex and Claude Code build Desktop and Web
+One `openworker-harness-builder` skill helps Codex and Claude Code build Desktop, Web and Node.js
applications with the OpenWorker Harness SDK. It includes version-matched SDK
-snippets and separate Desktop/Web references. No OpenWorker checkout is required
+snippets, a scoped file-organizer example, a complete streaming approval loop and separate track references. No OpenWorker checkout is required
for the packaged skill, and installing it does not install the SDK or a runtime.
-This skill release targets SDK `0.1.0-beta.2`, including provider caching,
-attempt-aware streaming and per-turn session options.
+This skill release targets SDK `0.1.0-beta.3`, including provider caching,
+attempt-aware streaming, per-turn session options, and auto-approver/compaction guidance.
## Install the skill
From an existing app project, install the latest published skill:
```sh
-npx @openworkerai/build-with-sdk-skills --agent codex --project .
+npx @openworkerai/openworker-harness-builder --agent codex --project .
```
For Claude Code:
```sh
-npx @openworkerai/build-with-sdk-skills --agent claude --project .
+npx @openworkerai/openworker-harness-builder --agent claude --project .
```
-These project commands create `.agents/skills/openworker-apps/` for Codex or
-`.claude/skills/openworker-apps/` for Claude Code. It supports quoted project paths
+These project commands create `.agents/skills/openworker-harness-builder/` for Codex or
+`.claude/skills/openworker-harness-builder/` for Claude Code. It supports quoted project paths
on Windows and macOS, leaves global settings alone, and refuses to overwrite an
existing skill. Review/back up an existing installation before replacing it.
`references/installation.json` records the matching SDK version, without local
checkout paths or credentials. Use `sdkVersion` from that file for the SDK. Skill and SDK package versions may
-differ; this skill release targets SDK `0.1.0-beta.2`.
+differ; this skill release targets SDK `0.1.0-beta.3`.
### Across your projects
For user-wide installation, use `--global` instead of `--project`:
```sh
-npx @openworkerai/build-with-sdk-skills --agent claude --global
+npx @openworkerai/openworker-harness-builder --agent claude --global
```
```sh
-npx @openworkerai/build-with-sdk-skills --agent codex --global
+npx @openworkerai/openworker-harness-builder --agent codex --global
```
-This installs into `~/.claude/skills/openworker-apps/` for Claude Code or
-`~/.agents/skills/openworker-apps/` for Codex, making the skill available across
+This installs into `~/.claude/skills/openworker-harness-builder/` for Claude Code or
+`~/.agents/skills/openworker-harness-builder/` for Codex, making the skill available across
projects for your user on this machine. It does not install into Claude web or
Cowork, change account settings, or require `npm install -g` or administrator
access. Choose either `--global` or `--project`, not both. Both modes preserve an
@@ -54,16 +54,16 @@ reproducibility, append `@<version>` to the package name. The installer records
the compatible SDK version separately; the skill and SDK versions may differ.
The skill is discoverable in the selected scope. Restart the coding-agent session if it
-does not appear. Invoke `$openworker-apps` in Codex or `/openworker-apps` in Claude
+does not appear. Invoke `$openworker-harness-builder` in Codex or `/openworker-harness-builder` in Claude
Code, or ask:
-> Use the openworker-apps skill to build a desktop app that summarizes a selected code directory. Explain the SDK calls as you build, test the app, and prepare an unpacked desktop package.
+> Use the openworker-harness-builder skill to build a desktop app that summarizes a selected code directory. Explain the SDK calls as you build, test the app, and prepare an unpacked desktop package.
For the Web track:
-> Use the openworker-apps skill to build a web app where I can upload a PDF and ask questions with page references. Explain the agent and session code and test the application locally.
+> Use the openworker-harness-builder skill to build a web app where I can upload a PDF and ask questions with page references. Explain the agent and session code and test the application locally.
-The shared skill includes a [Railway deployment track](openworker-apps/references/railway.md)
+The shared skill includes a [Railway deployment track](openworker-harness-builder/references/railway.md)
and Docker assets. The default is one Node service serving the frontend and API,
with the Rust harness running as a managed child process. The recipe has been tested locally and on Railway with the
published SDK, including streamed Claude responses and conversation recovery
@@ -73,7 +73,7 @@ follow separately. This installer targets local Codex and Claude Code sessions.
## Claude workspace uploads
Claude's **Customize → Skills → Upload** is a separate installation route.
-For that flow, zip the complete installed `openworker-apps` directory, including
+For that flow, zip the complete installed `openworker-harness-builder` directory, including
its references, Docker assets and `references/installation.json`; uploading only
`SKILL.md` loses the supporting files. The npm `.tgz` package is not this upload
format. Uploading a skill provides instructions, not an installed SDK, runtime,
@@ -97,16 +97,22 @@ node skills/prepare.mjs /absolute/new-skills-candidate
Install the resulting archive into a temporary project or use it through npm exec:
```sh
-npm exec --package /absolute/new-skills-candidate/archives/openworkerai-build-with-sdk-skills-0.1.0-beta.3.tgz -- build-with-sdk-skills --agent codex --project /path/to/your-app
+npm exec --package /absolute/new-skills-candidate/archives/openworkerai-openworker-harness-builder-0.1.0-beta.5.tgz -- openworker-harness-builder --agent codex --project /path/to/your-app
```
The preparer never publishes. Source package manifests remain private; staged
candidates remove that marker for the separately reviewed publication step.
+The Skill's exact `openworkerSdkVersion` pin is independent of the native-release
+manifest in a checkout; preserve the SDK version qualified for that Skill release.
Installation locations follow the official [Codex skill documentation](https://learn.chatgpt.com/docs/build-skills)
and [Claude Code skill documentation](https://code.claude.com/docs/en/skills).
-Validate source and packed installation with `node --test skills/install.test.mjs skills/package.test.mjs`.
+Validate source, file scope and packed installation with
+`node --test skills/install.test.mjs skills/package.test.mjs skills/local-script.test.mjs`.
+To include the native approval/resume test, set `OW_SKILL_SDK_NODE_MODULES` to an
+absolute consumer `node_modules` containing the matching published SDK/runtime.
+That test uses a loopback model fixture and does not spend model tokens.
## Railway recipe checks
@@ -137,3 +143,5 @@ unauthenticated requests, streamed output before model completion, explicit
cancellation, graceful shutdown, unchanged session references after redeployment,
and real Anthropic recall of earlier conversation content. This qualifies the
single-service recipe; it does not establish multi-replica or zero-downtime behavior.
+
+When upgrading from the earlier `openworker-apps` skill, review and remove that old skill from the same installation scope after installing the new name. The installer preserves existing skill directories and local customizations.
diff --git a/skills/install.mjs b/skills/install.mjs
index b96aa646..7a8c6477 100644
--- a/skills/install.mjs
+++ b/skills/install.mjs
@@ -6,8 +6,8 @@ import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import { parseArgs } from 'node:util';
const source = dirname(fileURLToPath(import.meta.url));
-const usage = 'build-with-sdk-skills --agent codex|claude (--project /path/to/your-app | --global)';
-const files = ['SKILL.md','references/desktop.md','references/web.md','references/sdk.md','references/runtime-options.md','references/subagents.md','references/observability.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore','agents/openai.yaml'];
+const usage = 'openworker-harness-builder --agent codex|claude (--project /path/to/your-app | --global)';
+const files = ['SKILL.md','references/desktop.md','references/web.md','references/sdk.md','references/tools.md','references/approvals.md','references/local-script.md','references/runtime-options.md','references/subagents.md','references/observability.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore','assets/local-script/file-tools.mjs','assets/local-script/organizer.mjs','agents/openai.yaml'];
function validate({agent, project, global: userWide = false}) {
if (!['codex','claude'].includes(agent) || typeof userWide !== 'boolean' ||
(project !== undefined && (typeof project !== 'string' || !project.trim())) ||
@@ -23,7 +23,7 @@ export async function install(options, {userHome = homedir()} = {}) {
const {agent, project, global: userWide = false} = options;
const pkg = JSON.parse(await readFile(join(source,'package.json'),'utf8'));
// Validate package completeness before creating an installation directory.
- const content = await Promise.all(files.map(name => readFile(join(source,'openworker-apps',name))));
+ const content = await Promise.all(files.map(name => readFile(join(source,'openworker-harness-builder',name))));
const root = await realpath(userWide ? userHome : project);
if (!(await lstat(root)).isDirectory()) throw Error('Installation root must be an existing directory.');
let parent = root;
@@ -33,7 +33,7 @@ export async function install(options, {userHome = homedir()} = {}) {
const stat = await lstat(parent);
if (stat.isSymbolicLink() || !stat.isDirectory()) throw Error(`Expected a real directory: ${parent}`);
}
- const destination = join(parent, 'openworker-apps');
+ const destination = join(parent, 'openworker-harness-builder');
await mkdir(destination); // Exclusive: an existing install must be reviewed by its owner.
for (const [index,name] of files.entries()) {
await mkdir(dirname(join(destination,name)), {recursive:true});
@@ -44,13 +44,20 @@ export async function install(options, {userHome = homedir()} = {}) {
},null,2)+'\n');
return destination;
}
-if (process.argv[1] && await realpath(process.argv[1]).catch(() => resolve(process.argv[1])) === fileURLToPath(import.meta.url)) {
+// Canonicalize both sides: Windows may spell the same installed path with
+// different drive-letter casing or a short (8.3) temporary-directory name.
+const entryPath = process.argv[1] && await realpath(process.argv[1]).catch(() => resolve(process.argv[1]));
+const modulePath = await realpath(fileURLToPath(import.meta.url));
+const isMain = entryPath && (process.platform === 'win32'
+ ? entryPath.toLowerCase() === modulePath.toLowerCase()
+ : entryPath === modulePath);
+if (isMain) {
const args=process.argv.slice(2);
if(args.length===1 && args[0]==='--help') console.log(`${usage}\n--global installs for your user across projects on this machine (Codex: ~/.agents/skills; Claude Code: ~/.claude/skills).`);
else {
try {
const options = parseInstallArgs(args);
- console.log(`Installed: ${await install(options)}\nOpen a new coding-agent session${options.global ? '' : ' in that project'} to use openworker-apps.`);
+ console.log(`Installed: ${await install(options)}\nOpen a new coding-agent session${options.global ? '' : ' in that project'} to use openworker-harness-builder.`);
} catch(error) { console.error(error.code==='EEXIST' ? 'An installation already exists. Review or back it up before replacing it.' : error.message);process.exitCode=1; }
}
}
diff --git a/skills/install.test.mjs b/skills/install.test.mjs
index 7ce6f040..0df8defe 100644
--- a/skills/install.test.mjs
+++ b/skills/install.test.mjs
@@ -8,14 +8,16 @@ for (const agent of ['codex','claude']) test(`install complete ${agent} skill; p
const root=await mkdtemp(join(tmpdir(),'ow skill '));
try {
const dest=await install({agent,project:root});
+ assert.equal(dest,join(await realpath(root),agent==='codex'?'.agents':'.claude','skills/openworker-harness-builder'));
const skill=await readFile(join(dest,'SKILL.md'),'utf8');
+ assert.match(skill,/^name: openworker-harness-builder$/m);
for(const [,path] of skill.matchAll(/\]\((references\/[^)]+)\)/g)) assert.ok((await readFile(join(dest,path),'utf8')).length>0);
- assert.ok((await readFile(join(dest,'agents/openai.yaml'),'utf8')).includes('$openworker-apps'));
+ assert.ok((await readFile(join(dest,'agents/openai.yaml'),'utf8')).includes('$openworker-harness-builder'));
const metadata=JSON.parse(await readFile(join(dest,'references/installation.json'),'utf8'));
const pkg=JSON.parse(await readFile(new URL('./package.json',import.meta.url),'utf8'));
assert.equal(metadata.sdkPackage,'@openworkerai/harness-sdk');
assert.equal(metadata.sdkVersion,pkg.openworkerSdkVersion);
- assert.equal(metadata.package,'@openworkerai/build-with-sdk-skills');
+ assert.equal(metadata.package,'@openworkerai/openworker-harness-builder');
assert.equal(metadata.checkout,undefined);
await writeFile(join(dest,'SKILL.md'),'local customization');
await assert.rejects(install({agent,project:root}),{code:'EEXIST'});
@@ -29,7 +31,7 @@ for (const agent of ['codex','claude']) test(`install ${agent} user-wide indepen
await mkdir(userHome);await mkdir(project);
const local=await install({agent,project});
const destination=await install({agent,global:true},{userHome});
- assert.equal(destination,join(await realpath(userHome),agent==='codex'?'.agents':'.claude','skills/openworker-apps'));
+ assert.equal(destination,join(await realpath(userHome),agent==='codex'?'.agents':'.claude','skills/openworker-harness-builder'));
for(const name of ['SKILL.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore'])
assert.equal(await readFile(join(destination,name),'utf8'),await readFile(join(local,name),'utf8'));
await writeFile(join(destination,'SKILL.md'),'personal customization');
@@ -68,3 +70,16 @@ test('reject invalid agent and linked destination directories',async()=>{
assert.deepEqual(await readdir(outside),[]);
} finally {await rm(root,{recursive:true,force:true});await rm(outside,{recursive:true,force:true});}
});
+
+for(const agent of ['codex','claude'])test(`renamed ${agent} skill preserves the legacy install`,async()=>{
+ const project=await mkdtemp(join(tmpdir(),'ow-skill-rename-'));
+ try {
+ const legacy=join(project,agent==='codex'?'.agents':'.claude','skills/openworker-apps');
+ await mkdir(legacy,{recursive:true});
+ await writeFile(join(legacy,'SKILL.md'),'legacy customization');
+ const current=await install({agent,project});
+ assert.notEqual(current,legacy);
+ assert.equal(await readFile(join(legacy,'SKILL.md'),'utf8'),'legacy customization');
+ assert.match(await readFile(join(current,'SKILL.md'),'utf8'),/^name: openworker-harness-builder$/m);
+ }finally{await rm(project,{recursive:true,force:true});}
+});
diff --git a/skills/local-script.test.mjs b/skills/local-script.test.mjs
new file mode 100644
index 00000000..aae078a8
--- /dev/null
+++ b/skills/local-script.test.mjs
@@ -0,0 +1,128 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile, readFile, lstat, symlink, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createServer } from 'node:http';
+import { install } from './install.mjs';
+import { fileTools } from './openworker-harness-builder/assets/local-script/file-tools.mjs';
+
+test('bundled file handlers confine paths, honor cancellation and preserve existing files', async t => {
+ const root = await mkdtemp(join(tmpdir(), 'ow-skill-tools-'));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const workspace = join(root, 'files'); await mkdir(workspace);
+ await writeFile(join(workspace, 'note.txt'), 'sample');
+ await writeFile(join(root, 'outside.txt'), 'private');
+ const calls = [], progress = [];
+ const tools = (await fileTools(workspace, item => calls.push(item))).tools;
+ const controller = new AbortController();
+ const context = { workspace, sessionId: 's', turnId: 't', callId: 'c', signal: controller.signal,
+ progress: async message => { progress.push(message); } };
+ assert.equal((await tools.read_file.execute({ path: 'note.txt' }, context)).text, 'sample');
+ for (const path of ['../outside.txt', '/etc/passwd', 'a/../../outside.txt', 'C:\\outside.txt'])
+ await assert.rejects(() => tools.read_file.execute({ path }, context));
+ if (process.platform !== 'win32') {
+ await symlink(join(root, 'outside.txt'), join(workspace, 'linked.txt'));
+ await assert.rejects(() => tools.read_file.execute({ path: 'linked.txt' }, context), /Symlinks/);
+ await symlink(root, join(workspace, 'linked-dir'));
+ await assert.rejects(() => tools.create_directory.execute({ path: 'linked-dir/new' }, context), /Symlinks/);
+ }
+ await assert.rejects(() => tools.read_file.execute({ path: 'note.txt' }, { ...context, workspace: root }), /Wrong workspace/);
+ await tools.create_directory.execute({ path: 'notes' }, context);
+ await writeFile(join(workspace, 'notes/existing.txt'), 'keep');
+ await assert.rejects(() => tools.move_file.execute({ from: 'note.txt', to: 'notes/existing.txt' }, context));
+ assert.equal(await readFile(join(workspace, 'notes/existing.txt'), 'utf8'), 'keep');
+ assert.equal(await readFile(join(workspace, 'note.txt'), 'utf8'), 'sample');
+ await tools.move_file.execute({ from: 'note.txt', to: 'notes/note.txt' }, context);
+ await assert.rejects(() => lstat(join(workspace, 'note.txt')), { code: 'ENOENT' });
+ assert.equal(await readFile(join(workspace, 'notes/note.txt'), 'utf8'), 'sample');
+ await assert.rejects(() => tools.delete_directory.execute({ path: '.' }, context), /demo root/);
+ await assert.rejects(() => tools.delete_directory.execute({ path: 'notes' }, context));
+ await tools.create_directory.execute({ path: 'empty' }, context);
+ await tools.delete_directory.execute({ path: 'empty' }, context);
+ controller.abort();
+ await assert.rejects(() => tools.create_directory.execute({ path: 'cancelled' }, context));
+ assert.equal(calls[0].callId, 'c'); assert.ok(progress.length > 0);
+ assert.equal(await readFile(join(root, 'outside.txt'), 'utf8'), 'private');
+});
+
+// Set this to a consumer's node_modules containing the published SDK/runtime.
+// No source build, cloud credentials or scripted Rust host is needed.
+test('installed organizer streams and resumes real Rust approvals without replaying tools', {
+ skip: !process.env.OW_SKILL_SDK_NODE_MODULES, timeout: 60000,
+}, async t => {
+ const root = await mkdtemp(join(tmpdir(), 'ow-skill-native-'));
+ const calls = [], events = [], approvals = [], requests = [], text = [];
+ let harness;
+ const plan = [
+ ['list_files', { path: '.' }], ['read_file', { path: 'note.txt' }],
+ ['create_directory', { path: 'notes' }],
+ ['move_file', { from: 'note.txt', to: 'notes/note.txt' }],
+ ['create_directory', { path: 'denied' }],
+ ];
+ const server = createServer(async (req, res) => {
+ try {
+ let raw = ''; for await (const chunk of req) raw += chunk;
+ const input = JSON.parse(raw); requests.push(input);
+ const step = requests.length - 1;
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ const send = value => res.write(`data: ${JSON.stringify(value)}\n\n`);
+ if (step < plan.length) {
+ const [name, args] = plan[step];
+ send({ id: `fixture-${step}`, choices: [{ index: 0, delta: { role: 'assistant',
+ tool_calls: [{ index: 0, id: `call-${step}`, type: 'function',
+ function: { name: `files__${name}`, arguments: JSON.stringify(args) } }] }, finish_reason: null }] });
+ send({ id: `fixture-${step}`, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] });
+ } else {
+ send({ id: 'final', choices: [{ index: 0, delta: { role: 'assistant', content: 'Organized ' }, finish_reason: null }] });
+ send({ id: 'final', choices: [{ index: 0, delta: { content: 'one file; respected the denial.' }, finish_reason: 'stop' }] });
+ }
+ send({ id: step < plan.length ? `fixture-${step}` : 'final', choices: [], usage: { prompt_tokens: 80, completion_tokens: 10, total_tokens: 90 } });
+ res.end('data: [DONE]\n\n');
+ } catch { res.writeHead(500); res.end(); }
+ });
+ await new Promise(done => server.listen(0, '127.0.0.1', done));
+ t.after(async () => {
+ await harness?.shutdown(); server.closeAllConnections();
+ await new Promise(done => server.close(done));
+ await rm(root, { recursive: true, force: true });
+ });
+ await symlink(resolve(process.env.OW_SKILL_SDK_NODE_MODULES), join(root, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
+ const installed = await install({ agent: 'codex', project: root });
+ const { createOrganizer, streamWithApprovals } = await import(pathToFileURL(join(installed, 'assets/local-script/organizer.mjs')));
+ const { Harness } = await import(pathToFileURL(join(root, 'node_modules/@openworkerai/harness-sdk/dist/index.js')));
+ const workspace = join(root, 'workspace'); await mkdir(workspace);
+ await writeFile(join(workspace, 'note.txt'), 'project: sample');
+ harness = await Harness.start({ stateDir: join(root, 'state'), sandbox: 'off' });
+ await harness.setModelProvider({ name: 'Fixture', api: 'chat-completions',
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1` });
+ const agent = await createOrganizer(harness, workspace, { provider: 'Fixture', name: 'fixture' }, item => calls.push(item));
+ const session = await agent.newSession({ workspace, scratch: false });
+ const result = await streamWithApprovals(session, 'Organize the sample.', {
+ event: item => events.push(item), text: value => text.push(value),
+ approve: async item => {
+ approvals.push(item);
+ assert.ok(item.arguments, 'Show actual proposed arguments');
+ if (item.arguments.path === 'notes') await assert.rejects(() => lstat(join(workspace, 'notes')), { code: 'ENOENT' });
+ if (item.arguments.to) assert.equal(await readFile(join(workspace, 'note.txt'), 'utf8'), 'project: sample');
+ return item.arguments.path !== 'denied';
+ },
+ });
+ assert.equal(result.status, 'completed', JSON.stringify({ result, requests: requests.length,
+ failures: events.filter(e => /error|failed/.test(e.event.type)).map(e => e.event) }));
+ assert.equal(result.finalOutput, 'Organized one file; respected the denial.');
+ assert.equal(text.at(-1), result.finalOutput);
+ assert.equal(approvals.length, 3, 'Reads do not prompt; mutations prompt once each');
+ assert.equal(calls.length, 4, 'Denied creation never executes and previous callbacks do not replay');
+ assert.equal(requests.length, 6);
+ assert.equal(requests[0].tools.length, 5, 'Only selected file tools reach the model');
+ assert.ok(events.some(e => e.summary?.type === 'assistant_delta'));
+ assert.ok(events.some(e => e.event.type === 'tool_started' && e.event.data.arguments));
+ const ids = events.map(e => `${e.sessionId}/${e.event.event_id}`);
+ assert.equal(new Set(ids).size, ids.length, 'Checkpoint continuation must avoid replaying consumed events');
+ assert.equal(await readFile(join(workspace, 'notes/note.txt'), 'utf8'), 'project: sample');
+ await assert.rejects(() => lstat(join(workspace, 'denied')), { code: 'ENOENT' });
+ const lastMessages = requests.at(-1).messages;
+ assert.ok(lastMessages.some(m => m.role === 'tool' && m.content.includes('denied')), 'Working model sees denial');
+});
diff --git a/skills/openworker-apps/agents/openai.yaml b/skills/openworker-apps/agents/openai.yaml
deleted file mode 100644
index 5ae00774..00000000
--- a/skills/openworker-apps/agents/openai.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-interface:
- display_name: "Build with OpenWorker"
- short_description: "Build desktop and web apps with the OpenWorker SDK"
- default_prompt: "Use $openworker-apps to build an app with OpenWorker and explain the SDK integration."
diff --git a/skills/openworker-apps/SKILL.md b/skills/openworker-harness-builder/SKILL.md
similarity index 69%
rename from skills/openworker-apps/SKILL.md
rename to skills/openworker-harness-builder/SKILL.md
index d4ca5059..687b1449 100644
--- a/skills/openworker-apps/SKILL.md
+++ b/skills/openworker-harness-builder/SKILL.md
@@ -1,6 +1,6 @@
---
-name: openworker-apps
-description: Build or adapt desktop and web applications using the OpenWorker Harness SDK, including agent creation, streamed sessions, model configuration, application packaging and Railway deployment. Use for OpenWorker integrations, not general website design or unrelated agent frameworks.
+name: openworker-harness-builder
+description: Build or adapt desktop apps, web apps and Node.js scripts using the OpenWorker Harness SDK, including custom tools, approvals, streamed sessions, model configuration, application packaging and Railway deployment. Use for OpenWorker integrations, not general website design or unrelated agent frameworks.
---
# Build apps with OpenWorker
@@ -11,8 +11,11 @@ Preserve their chosen UI framework, model and deployment target.
## Choose the track
- Read [SDK integration](references/sdk.md) for the shared lifecycle and package contract.
+- For custom tools, directory scope and tool-activity display, read [Tools](references/tools.md).
+- For approval modes and the complete streaming/approval/resume loop, read [Approvals](references/approvals.md).
+- For a command-line demo or local utility without a frontend, read [Node scripts](references/local-script.md).
- For provider configuration, retry-safe streaming, reasoning display, migrated
- history or changing turn preferences, read [Runtime options](references/runtime-options.md).
+ history, auto-approver/compaction guidance or changing turn preferences, read [Runtime options](references/runtime-options.md).
- For model-created child agents, read [Standalone sub-agents](references/subagents.md)
and check its runtime-version gate before using the option.
- For optional turn traces, Langfuse export or evaluation evidence, read
@@ -42,14 +45,19 @@ Do not fall back to similarly named third-party packages.
IPC. Rust can embed the harness in-process.
- Keep model credentials in that trusted process. The application owns its UI,
authentication, session ownership and lifecycle.
+- Agent definitions are immutable within durable state. Changes to instructions,
+ tools or approval mode require a new agent name. Keep the previous identity
+ for existing sessions; use a separate fresh state directory for disposable demos.
- Select tools deliberately. The directory-summary and PDF examples supply their
own input, so use `tools: []` and disable planning, memory and scheduling there.
Other apps may need tools. Disabling optional memory does not disable history.
- File and document content is untrusted data. Render model text safely. The
directory reader's exclusions are not a secret scanner or an OS sandbox.
- The bundled examples select `sandbox: "off"` for application-owned input.
- Tools in that mode have host privileges. Consult the OpenShell guide if the
- product requires isolated tool execution.
+ Application callbacks in that mode have application privileges. `workspace`
+ is not an OS sandbox. Enforce directory scope in the callbacks as shown in
+ the bundled Tools reference. For strong isolation, use a supported sandbox
+ execution backend; enabling one does not sandbox arbitrary Node callbacks.
## Verify the integration
diff --git a/skills/openworker-harness-builder/agents/openai.yaml b/skills/openworker-harness-builder/agents/openai.yaml
new file mode 100644
index 00000000..b28f685f
--- /dev/null
+++ b/skills/openworker-harness-builder/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "OpenWorker Harness Builder"
+ short_description: "Build desktop and web apps with the OpenWorker SDK"
+ default_prompt: "Use $openworker-harness-builder to build an app with OpenWorker and explain the SDK integration."
diff --git a/skills/openworker-harness-builder/assets/local-script/file-tools.mjs b/skills/openworker-harness-builder/assets/local-script/file-tools.mjs
new file mode 100644
index 00000000..fb3c3d77
--- /dev/null
+++ b/skills/openworker-harness-builder/assets/local-script/file-tools.mjs
@@ -0,0 +1,90 @@
+import { lstat, realpath, readdir, readFile, mkdir, rmdir, link, unlink } from 'node:fs/promises';
+import { isAbsolute, join, resolve, relative, sep } from 'node:path';
+
+// Application-level scope for an app-owned demo directory. This is not OS
+// isolation: no other process should concurrently replace directory entries.
+export async function fileTools(directory, activity = () => {}) {
+ const root = await realpath(directory);
+ if (!(await lstat(root)).isDirectory()) throw Error('Expected a directory');
+ async function scoped(value, { missingLeaf = false } = {}) {
+ if (typeof value !== 'string' || !value || value.includes('\0') ||
+ isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.includes('\\') ||
+ value.split('/').some(part => part === '..' || part === ''))
+ throw Error('Use a relative path inside the demo directory');
+ const path = resolve(root, value);
+ const rel = relative(root, path);
+ if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) throw Error('Outside demo directory');
+ const parts = rel ? rel.split(sep) : [];
+ let current = root;
+ for (let i = 0; i < parts.length; i++) {
+ current = join(current, parts[i]);
+ try {
+ const stat = await lstat(current);
+ if (stat.isSymbolicLink()) throw Error('Symlinks are not allowed');
+ if (i < parts.length - 1 && !stat.isDirectory()) throw Error('Parent is not a directory');
+ } catch (error) {
+ if (error.code === 'ENOENT' && missingLeaf && i === parts.length - 1) return path;
+ throw error;
+ }
+ }
+ return path;
+ }
+ const schema = properties => ({ type: 'object', properties,
+ required: Object.keys(properties), additionalProperties: false });
+ const string = { type: 'string' };
+ const tool = (name, description, inputSchema, execute) => ({ description, inputSchema,
+ async execute(args, context) {
+ context.signal.throwIfAborted();
+ if (await realpath(context.workspace) !== root) throw Error('Wrong workspace');
+ // Upsert activity by these IDs: callback delivery can precede the UI's
+ // consumption of the durable tool_started event.
+ activity({ phase: 'callback', name: `files.${name}`, args,
+ sessionId: context.sessionId, turnId: context.turnId, callId: context.callId });
+ await context.progress(`Running files.${name}`);
+ const result = await execute(args);
+ return result;
+ },
+ });
+ return { namespace: 'files', tools: {
+ list_files: tool('list_files', 'List one directory inside the demo. Use . for its root.',
+ schema({ path: string }), async ({ path }) => {
+ const entries = await readdir(await scoped(path), { withFileTypes: true });
+ if (entries.length > 100) throw Error('Demo directory has too many entries');
+ return entries.filter(e => !e.isSymbolicLink()).map(e => ({ name: e.name, directory: e.isDirectory() }));
+ }),
+ read_file: tool('read_file', 'Read a UTF-8 demo file, at most 64 KiB.',
+ schema({ path: string }), async ({ path }) => {
+ const file = await scoped(path);
+ const stat = await lstat(file);
+ if (!stat.isFile() || stat.size > 65536) throw Error('Expected a small regular file');
+ return { text: await readFile(file, 'utf8') };
+ }),
+ create_directory: tool('create_directory', 'Create one subdirectory. Requires approval.',
+ schema({ path: string }), async ({ path }) => {
+ await mkdir(await scoped(path, { missingLeaf: true }));
+ return { created: path };
+ }),
+ delete_directory: tool('delete_directory', 'Remove an empty subdirectory only. Requires approval.',
+ schema({ path: string }), async ({ path }) => {
+ const target = await scoped(path);
+ if (target === root) throw Error('Cannot remove the demo root');
+ await rmdir(target);
+ return { removed: path };
+ }),
+ move_file: tool('move_file', 'Move one regular file without overwriting another file. Requires approval.',
+ schema({ from: string, to: string }), async ({ from, to }) => {
+ const source = await scoped(from);
+ const destination = await scoped(to, { missingLeaf: true });
+ if (!(await lstat(source)).isFile()) throw Error('Expected a regular file');
+ // link is exclusive: an existing destination is never overwritten.
+ // Both paths are on the same demo filesystem. No shell or Git access.
+ await link(source, destination);
+ try { await unlink(source); }
+ catch {
+ return { completed: false, destinationCreated: true, sourceRetained: true,
+ message: 'Both paths may exist. Inspect them before any retry.' };
+ }
+ return { moved: { from, to } };
+ }),
+ } };
+}
diff --git a/skills/openworker-harness-builder/assets/local-script/organizer.mjs b/skills/openworker-harness-builder/assets/local-script/organizer.mjs
new file mode 100644
index 00000000..94f5278a
--- /dev/null
+++ b/skills/openworker-harness-builder/assets/local-script/organizer.mjs
@@ -0,0 +1,115 @@
+import { Harness, AttemptOutput } from '@openworkerai/harness-sdk';
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createInterface } from 'node:readline/promises';
+import { stdin, stdout } from 'node:process';
+import { fileTools } from './file-tools.mjs';
+
+export async function createOrganizer(harness, directory, model, activity) {
+ await harness.registerTools(await fileTools(directory, activity));
+ const agent = harness.createAgent({
+ // Persisted definitions are immutable. Change this name when changing the
+ // prompt, tool set, approvals or other definition settings.
+ name: 'file-organizer-v1',
+ instructions: 'Organize only the demo files using files tools. Read before moving. Never overwrite files. Respect denials; report incomplete work.',
+ defaultModel: model,
+ tools: ['files.list_files', 'files.read_file', 'files.create_directory', 'files.delete_directory', 'files.move_file'],
+ planning: false, memory: false, scheduling: false,
+ builtinTools: { askUser: false, readHistory: false },
+ approvals: { mode: 'only', tools: ['files.create_directory', 'files.delete_directory', 'files.move_file'] },
+ limits: { maxModelCalls: 30, maxOutputTokens: 24000, maxOutputTokensPerCall: 2048, summaryTokens: 512 },
+ });
+ await agent.ready();
+ return agent;
+}
+
+// ui.text replaces the whole answer; ui.event upserts activity, not raw HTML.
+// ui.approve shows interruption.tool AND interruption.arguments, then returns
+// true or false. A browser app implements it with an approval card.
+export async function streamWithApprovals(session, text, ui) {
+ const output = new AttemptOutput();
+ let stream = (await session.send(text)).events();
+ while (true) {
+ for await (const item of stream) {
+ output.apply(item);
+ ui.event?.(item);
+ ui.text?.(output.text);
+ }
+ const result = await stream.result();
+ if (result.status !== 'interrupted') {
+ if (result.status === 'completed') ui.text?.(result.finalOutput ?? output.text);
+ else { output.interrupt(); ui.text?.(output.text); }
+ return result;
+ }
+ if (!result.interruptions.length) throw Error('Interrupted without a pending interaction');
+ for (const interruption of result.interruptions) {
+ // Safety holds need the safety-specific recovery flow. Do not treat them
+ // as approvals or automatically answer an unexpected question.
+ if (interruption.kind !== 'approval') return result;
+ const allowed = await ui.approve(interruption);
+ await session.respond(interruption, { decision: allowed ? 'once' : 'deny' });
+ }
+ // Continue the SAME submission, replaying from the last consumed cursor.
+ // Sending the original text again would create a different turn.
+ stream = await session.resumeStreamed(stream.checkpoint());
+ }
+}
+
+async function main() {
+ const model = process.env.MODEL_ID;
+ const anthropic = process.env.MODEL_API === 'anthropic';
+ const provider = anthropic ? 'Anthropic' : 'OpenAI';
+ const apiKeyEnv = anthropic ? 'ANTHROPIC_API_KEY' : 'OPENAI_API_KEY';
+ if (!model || !process.env[apiKeyEnv]) throw Error(`Set MODEL_ID and ${apiKeyEnv} before starting`);
+ // Fresh, dedicated workspace and separate durable state: nothing is seeded
+ // into an existing user directory. Print both paths for later inspection.
+ const demo = await mkdtemp(join(tmpdir(), 'openworker-organizer-'));
+ const workspace = join(demo, 'files');
+ const { mkdir } = await import('node:fs/promises');
+ await mkdir(workspace);
+ for (let i = 0; i < 10; i++) {
+ const category = ['meeting', 'recipe', 'travel', 'project', 'receipt'][i % 5];
+ await writeFile(join(workspace, `note-${i + 1}.txt`), `${category}: synthetic sample ${i + 1}\n`, { flag: 'wx' });
+ }
+ const stateDir = join(demo, 'state');
+ console.log({ workspace, stateDir });
+ const terminal = createInterface({ input: stdin, output: stdout });
+ let harness, session;
+ const cancel = () => { void session?.cancel().catch(() => {}); terminal.close(); };
+ process.on('SIGINT', cancel);
+ try {
+ harness = await Harness.start({ stateDir, sandbox: 'off' });
+ await harness.setModelProvider({ name: provider, api: anthropic ? 'anthropic' : 'responses',
+ credentials: { apiKeyEnv, storage: 'memory' } });
+ const agent = await createOrganizer(harness, workspace, { provider, name: model },
+ item => console.log('Tool', JSON.stringify(item)));
+ session = await agent.newSession({ workspace, scratch: false });
+ console.log('Session reference:', JSON.stringify(session.reference()));
+ let displayed = '';
+ const result = await streamWithApprovals(session,
+ 'Inspect the ten files. Create appropriate category directories and move the files into them. Summarize what changed.', {
+ approve: async pending => {
+ console.log('Proposed operation:', pending.tool, JSON.stringify(pending.arguments));
+ const answer = await terminal.question('Allow this operation once? [y/N] ');
+ return answer.trim().toLowerCase() === 'y';
+ },
+ event: item => {
+ const kind = item.summary?.type ?? item.event.type;
+ if (['model_attempt_started', 'model_activity', 'tool_started', 'tool_finished'].includes(kind))
+ console.log('Activity:', JSON.stringify(item.summary));
+ },
+ text: value => { if (value !== displayed) { displayed = value; console.log('Answer:', value); } },
+ });
+ console.log('Run status:', result.status);
+ if (result.status !== 'completed') process.exitCode = 1;
+ } finally {
+ process.off('SIGINT', cancel);
+ terminal.close();
+ await harness?.shutdown();
+ // Keep the demo workspace and state so the user can inspect the outcome.
+ }
+}
+if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url)
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
diff --git a/skills/openworker-apps/assets/railway/.dockerignore b/skills/openworker-harness-builder/assets/railway/.dockerignore
similarity index 100%
rename from skills/openworker-apps/assets/railway/.dockerignore
rename to skills/openworker-harness-builder/assets/railway/.dockerignore
diff --git a/skills/openworker-apps/assets/railway/Dockerfile b/skills/openworker-harness-builder/assets/railway/Dockerfile
similarity index 100%
rename from skills/openworker-apps/assets/railway/Dockerfile
rename to skills/openworker-harness-builder/assets/railway/Dockerfile
diff --git a/skills/openworker-harness-builder/references/approvals.md b/skills/openworker-harness-builder/references/approvals.md
new file mode 100644
index 00000000..c74ac9c5
--- /dev/null
+++ b/skills/openworker-harness-builder/references/approvals.md
@@ -0,0 +1,78 @@
+# Tool approvals and streamed interactions
+
+Set approval behavior explicitly when creating the agent. Changing it later
+requires a new agent name because persisted definitions are immutable.
+
+| Configuration | Behavior | Use it for |
+| --- | --- | --- |
+| `{ mode: 'always' }` | Ask a person for tool calls unless an existing valid session grant covers them. This is the default. | Interactive control. |
+| `{ mode: 'only', tools: ['files.move_file'] }` | Ask for selected tools; ordinary unlisted tools receive application-policy approval. | Approval for writes, routine reads allowed. |
+| `{ mode: 'auto', reviewerModel: { provider: 'OpenAI', name: modelId } }` | A selected model reviews eligible calls: allow executes, deny returns a denial, uncertain requests human approval. | Model-assisted approval. |
+| `{ mode: 'never' }` | Bypass the approval review. Hard policy checks still apply. | Trusted unattended operations. |
+
+`auto` is not unconditional approval. It can review read-only tools too. Hard
+denials and valid session grants are handled first. Privileged dynamic agent-type
+or child-creation operations can have additional approval requirements; `only`
+does not automatically exempt them merely because they are absent from its list.
+Model review is not a sandbox or a replacement for tool scope checks.
+
+Human responses are `{ decision: 'once' }`, `{ decision: 'deny' }` or
+`{ decision: 'session' }`. Use `once` when each mutation needs a separate card.
+A session grant covers that tool for the session, including different valid
+arguments, and survives restart. It does not override hard security checks.
+Structured questions are separate: answer them with `{ answer: '...' }`, or
+disable `builtinTools.askUser` when the product does not support questions.
+
+## Stream, show the proposal, respond, continue
+
+Use the complete [streamWithApprovals helper](../assets/local-script/organizer.mjs).
+Its core flow is:
+
+```typescript
+const display = new AttemptOutput();
+let stream = (await session.send(userText)).events();
+while (true) {
+ for await (const event of stream) {
+ display.apply(event);
+ renderText(display.text); // Replace, do not append the full projection.
+ renderActivity(event);
+ }
+ const result = await stream.result();
+ if (result.status !== 'interrupted') {
+ if (result.status === 'completed') renderText(result.finalOutput ?? display.text);
+ else { display.interrupt(); renderText(display.text); }
+ return result; // Check failed/cancelled as well as completed.
+ }
+ 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.
+ // The card must display pending.tool AND pending.arguments.
+ const allowed = await showApprovalCard(pending);
+ await session.respond(pending, { decision: allowed ? 'once' : 'deny' });
+ }
+ stream = await session.resumeStreamed(stream.checkpoint());
+}
+```
+
+The snippet belongs inside an async app function; import `AttemptOutput` from
+the SDK. Rendering/card functions are supplied by the app. It uses no new user
+message to resume: keep the submission ID and consumed journal cursors. Use
+`session.cancel()` for Stop. Closing the observer does not cancel execution and
+must not cause automatic approval. For process recovery, persist the session
+reference/checkpoint and reconcile pending interactions from durable state.
+
+## What the app can observe today
+
+The typed `auto_approved` summary describes application-policy approval, such as
+ordinary unlisted tools under `only`. It is not the model auto-approver's verdict.
+To display model decisions, inspect raw `interaction_required` and
+`interaction_resolved` events: `event.data.review` contains the safe
+`verdict`/`reason` when available; `origin` and nested `call.call_id` identify the
+decision source and call. Handle absent/withheld reasons. Never interpret a
+missing `auto_approved` summary as a denial or failure to review.
+
+The current denied tool response tells the working agent that execution was
+denied and not to retry or evade the decision. It does not currently include the
+reviewer's reason. The app can display an available safe journal reason itself;
+do not promise that the agent receives it. Application guidance for auto approval
+is described in [Runtime options](runtime-options.md).
diff --git a/skills/openworker-apps/references/desktop.md b/skills/openworker-harness-builder/references/desktop.md
similarity index 100%
rename from skills/openworker-apps/references/desktop.md
rename to skills/openworker-harness-builder/references/desktop.md
diff --git a/skills/openworker-harness-builder/references/local-script.md b/skills/openworker-harness-builder/references/local-script.md
new file mode 100644
index 00000000..0bbba069
--- /dev/null
+++ b/skills/openworker-harness-builder/references/local-script.md
@@ -0,0 +1,56 @@
+# A plain Node.js file-organizing agent
+
+Use this track for a terminal demo, local utility or automation without Electron,
+a browser UI or a web server. Node starts the managed Rust subprocess; npm
+installs the matching runtime. The agent uses real registered file tools and
+requires human approval for every create-directory, delete-empty-directory and
+move operation. Reads and directory listings do not ask for approval.
+
+Read `installation.json` beside this file and install its `sdkVersion`:
+
+```sh
+npm init -y
+npm install --save-exact @openworkerai/[email protected]
+```
+
+Copy both bundled files into your app, next to each other:
+
+- [organizer.mjs](../assets/local-script/organizer.mjs): agent creation, streaming,
+ approval prompts and session continuation.
+- [file-tools.mjs](../assets/local-script/file-tools.mjs): scoped filesystem callbacks.
+
+Then run it in a terminal with Node 20 or later. Choose an exact model ID your
+account supports:
+
+```sh
+MODEL_ID=YOUR_OPENAI_MODEL node --env-file="$HOME/.env" organizer.mjs
+```
+
+For Anthropic:
+
+```sh
+MODEL_API=anthropic MODEL_ID=YOUR_CLAUDE_MODEL node --env-file="$HOME/.env" organizer.mjs
+```
+
+`~/.env` should contain `OPENAI_API_KEY=...` or `ANTHROPIC_API_KEY=...`.
+Node's `--env-file` loads it; the SDK does not load the file by itself. On
+PowerShell, set `$env:MODEL_ID='...'` (and `$env:MODEL_API='anthropic'` if needed),
+then run `node --env-file="$HOME/.env" organizer.mjs`. In every case the provider
+key is resolved in Node, so `inheritEnv` is unnecessary for it.
+
+The script creates ten synthetic text files in a **new dedicated demo
+directory**, prints that directory and its separate state path, and leaves both
+for inspection. It does not organize an existing personal directory or delete
+files. Answer `y` to approve an operation once; any other answer denies it. Ctrl-C
+requests cancellation and shuts down the harness. Tool activity includes the
+actual arguments and call identity, plus elapsed model-wait updates.
+
+The sample uses `sandbox: 'off'` and deliberately scoped callbacks. Read
+[Tools](tools.md) for the filesystem assumptions and [Approvals](approvals.md)
+for adapting the terminal prompt to an approval card in a desktop/web app.
+Keep file contents and model output as escaped text in a graphical UI.
+
+The executable sample uses modern `createAgent`/`setModelProvider` APIs. Change
+its versioned agent name if adapting the definition inside existing durable
+state. For an existing session, register the identical definition and tools,
+resupply memory-only credentials, then use `agent.resumeSession(reference)`.
diff --git a/skills/openworker-apps/references/observability.md b/skills/openworker-harness-builder/references/observability.md
similarity index 89%
rename from skills/openworker-apps/references/observability.md
rename to skills/openworker-harness-builder/references/observability.md
index 06df829b..5b5db2dd 100644
--- a/skills/openworker-apps/references/observability.md
+++ b/skills/openworker-harness-builder/references/observability.md
@@ -1,12 +1,11 @@
# Optional turn traces and evaluations
-The high-level recording, query and evaluation APIs are an unpublished source
-candidate, not available in the currently published 0.1.0-beta.2 runtime. Use them
-only when the supplied SDK declarations and runtime capabilities both support
+The high-level recording, query and evaluation APIs are available in SDK/runtime
+0.1.0-beta.3. Use them only when matching SDK declarations and runtime capabilities support
`recording` (and `evaluations`/`evaluation_export` as needed). Otherwise use existing
`model_usage` events or configured OTLP; do not invent a compatibility fallback.
-For a supported candidate:
+For a supported runtime:
- Configure `Harness.start({recording:{database:{type:'sqlite',path:absolutePrivatePath}}})`
only if local trace retention is wanted. Keep it outside model-accessible workspaces.
diff --git a/skills/openworker-apps/references/railway.md b/skills/openworker-harness-builder/references/railway.md
similarity index 100%
rename from skills/openworker-apps/references/railway.md
rename to skills/openworker-harness-builder/references/railway.md
diff --git a/skills/openworker-apps/references/runtime-options.md b/skills/openworker-harness-builder/references/runtime-options.md
similarity index 78%
rename from skills/openworker-apps/references/runtime-options.md
rename to skills/openworker-harness-builder/references/runtime-options.md
index 65ed1d84..60149871 100644
--- a/skills/openworker-apps/references/runtime-options.md
+++ b/skills/openworker-harness-builder/references/runtime-options.md
@@ -138,3 +138,41 @@ For UI activity, `model_activity` reports elapsed waiting time at most once ever
five seconds; it is not task progress. Match tool callback UI with
`(sessionId, turnId, callId)`, not event arrival order. Do not retry side effects
because a stream disconnects; resume the durable run and reconcile its outcome.
+
+## Auto-approver and compaction guidance (SDK 0.1.0-beta.3)
+
+Use these options only with a matching runtime advertising `application_guidance`.
+They apply to embedded Rust and managed-process sessions. The cluster REST client
+does not expose session/turn guidance overrides yet.
+
+```typescript
+import type { AgentHandle } from '@openworkerai/harness-sdk';
+
+export async function continueWithGuidance(agent: AgentHandle) {
+ const session = await agent.newSession({
+ autoApproverContext: 'Staging workspace. Ask before publishing.',
+ compaction: { additionalInstructions: 'Preserve decisions and unfinished tests.' },
+ });
+ await session.run('Continue.', {
+ autoApproverContext: 'For this turn, changes must stay inside src/.',
+ compaction: { additionalInstructions: 'Keep the migration checklist.' },
+ });
+ return session;
+}
+```
+
+Agent defaults → session → turn; omission inherits and `''` clears guidance in
+that scope. Accepted options survive restart and bind the submission ID; changing
+them requires a new submission. Each string is limited to32,000 UTF-8 bytes with
+no NUL. A turn override does not alter the next turn's session defaults.
+
+Keep working-agent preferences in `instructionAddendum`; reviewer context goes
+only to the auto-approver and summary guidance only to the compactor. They are not
+user transcript messages. Context alone does not turn auto-approval on: configure
+`approvals: { mode: 'auto', reviewerModel }` separately. Hard policy checks still
+run first, and summary guidance supplements the required summary structure.
+
+Rust uses `Agent::auto_approver_context`, `SessionOptions::auto_approver_context`
+and `TurnOptions.auto_approver_context`. Use
+`CompactionOptions::additional_instructions(text)` with the agent/session
+`.compaction(...)` setter or `TurnOptions.compaction`.
diff --git a/skills/openworker-apps/references/sdk.md b/skills/openworker-harness-builder/references/sdk.md
similarity index 63%
rename from skills/openworker-apps/references/sdk.md
rename to skills/openworker-harness-builder/references/sdk.md
index 945f582f..30a7b684 100644
--- a/skills/openworker-apps/references/sdk.md
+++ b/skills/openworker-harness-builder/references/sdk.md
@@ -14,7 +14,7 @@ at application startup and a Rust compiler is not needed for TypeScript consumer
The release matrix covers darwin/win32/linux and arm64/x64; Linux artifacts target
glibc. Do not put a macOS helper into a Linux container or promise musl support.
-Run the SDK in Node.js (Electron main or an application server). For Rust, the
+Run the SDK in Node.js (a local script, Electron main or an application server). For Rust, the
crate name remains `openworker-sdk`; npm package renaming does not rename Cargo
crates. Rust in-process embedding and the TypeScript managed subprocess are
separate integration modes.
@@ -66,6 +66,23 @@ A provider name identifies its API/endpoint. Changing endpoint or API requires a
new provider name. Keep secrets outside renderer bundles, prompts and committed
files; memory-only credentials must be supplied again after app restart.
+For `setModelProvider` (also the `modelProviders` convenience option), `apiKeyEnv`
+is resolved in the **Node process** and the value is sent over private stdio to
+Rust. No `inheritEnv` is needed for that credential path. The SDK does not load
+`~/.env` automatically: load it in Node before provider configuration. Use
+`inheritEnv: ['VARIABLE_NAME']` only when Rust or another child process actually
+needs to resolve that variable itself; avoid passing all of Node's environment.
+
+Use `createAgent`, `setModelProvider` and automatic runtime discovery for new
+applications. The lower-level startup `agents` array, `setConnection` and explicit
+`executable` remain supported for advanced integrations; do not mix both styles
+in a basic tutorial. Set an explicit executable only for a custom/bundled host.
+
+Definitions are immutable: changing an existing agent's instructions, tools,
+approval mode or other definition fields requires a new name. Identical
+re-registration is safe. Keep old names for their durable sessions. A fresh
+`stateDir` is an optional development reset, not a migration of existing sessions.
+
## Sessions and streamed runs
Create one session for a conversation. Keep distinct documents, projects and users
@@ -91,8 +108,9 @@ if (result.status !== 'completed') {
// text a second time; use it to replace/reconcile the displayed answer.
```
-`renderText` and `sourceText` belong to the application. Handle pending approval or
-question interactions when enabling tools. A closed stream is not proof of a
+`renderText` and `sourceText` belong to the application. For tools, use the complete
+[approval loop](approvals.md) rather than assuming interruptions are errors.
+A closed stream is not proof of a
successful run. Use `session.cancel()` for Stop, and call `harness.shutdown()`
once when the application exits. Retain `session.reference()` when the product
needs to resume a durable conversation via `agent.resumeSession(reference)`.
@@ -100,9 +118,23 @@ needs to resume a durable conversation via `agent.resumeSession(reference)`.
For reasoning display, output buffering, provider usage and turn options, read
[Runtime options](runtime-options.md).
+## Workspace and scratch
+
+`agent.newSession({ workspace: absoluteDirectory, scratch: false })` uses that
+directory for the conversation. With no workspace, the default is a newly
+allocated scratch workspace under the configured scratch root. `scratch: false`
+requires an explicit workspace; `scratch: true` cannot accompany one. Scratch
+does not promise automatic deletion. Durable state and workspace files are
+separate application lifecycle decisions.
+
+The workspace supplies the working directory and scope for supported built-in
+path checks/backend mounts. Arbitrary Node callbacks can still access anything
+the app can access. See [Tools](tools.md) for app-owned directory restrictions.
+
## More APIs
-Inspect the installed `@openworkerai/harness-sdk` declarations before adding tools, teams
-or safety policies. The public guides are at https://openworker.com/docs/sdk/.
+Start with the bundled [custom tools](tools.md) and [approval](approvals.md)
+examples. Inspect the installed declarations for additional team or safety APIs.
+The public guides are at https://openworker.com/docs/sdk/.
Use the guide that matches the installed release; live website examples may be
newer. The bundled snippets above are the starting point for this skill version.
diff --git a/skills/openworker-apps/references/subagents.md b/skills/openworker-harness-builder/references/subagents.md
similarity index 95%
rename from skills/openworker-apps/references/subagents.md
rename to skills/openworker-harness-builder/references/subagents.md
index 75a927cd..55340aa6 100644
--- a/skills/openworker-apps/references/subagents.md
+++ b/skills/openworker-harness-builder/references/subagents.md
@@ -1,7 +1,6 @@
# Standalone sub-agents
-Source-feature preview: this option is not in the published 0.1.0-beta.2 runtime.
-Use this reference only with a matching candidate SDK/runtime whose handshake has
+Available in SDK/runtime 0.1.0-beta.3. Use a matching SDK/runtime whose handshake has
`standalone_subagents: true` (service: `standaloneSubagents`). Otherwise use the
installed version's existing explicit team API or explain the version requirement.
Do not silently substitute a team or upgrade an application.
diff --git a/skills/openworker-harness-builder/references/tools.md b/skills/openworker-harness-builder/references/tools.md
new file mode 100644
index 00000000..60cfa6bc
--- /dev/null
+++ b/skills/openworker-harness-builder/references/tools.md
@@ -0,0 +1,87 @@
+# Custom tools and directory scope
+
+Register application callbacks before creating the agent. The returned JSON is
+the model's tool result; tools run in Node and may be asynchronous.
+
+```typescript
+await harness.registerTools({ namespace: 'files', tools: {
+ read_file: {
+ description: 'Read a UTF-8 file inside the selected directory.',
+ inputSchema: { type: 'object', properties: { path: { type: 'string' } },
+ required: ['path'], additionalProperties: false },
+ execute: async (args, context) => {
+ context.signal.throwIfAborted();
+ await context.progress('Reading selected file');
+ // Supply an app-owned confined reader, NOT readFile(args.path).
+ return { text: await readConfinedFile(context.workspace, args.path) };
+ },
+ },
+} });
+const agent = harness.createAgent({
+ name: 'directory-reader-v1', instructions: 'Summarize the selected files.',
+ defaultModel: { provider: 'OpenAI', name: modelId },
+ tools: ['files.read_file'], approvals: { mode: 'always' },
+ planning: false, memory: false, scheduling: false,
+ builtinTools: { askUser: false, readHistory: false },
+});
+await agent.ready();
+const session = await agent.newSession({ workspace: absoluteDirectory, scratch: false });
+```
+
+`readConfinedFile` is application code. The complete executable
+[file tools](../assets/local-script/file-tools.mjs) show directory listing, bounded
+file reads, create/delete-empty-directory and non-overwriting moves. They restrict
+paths to one canonical root, reject absolute/traversal paths and symlinks, verify
+the session workspace, and expose no shell command. Use the
+[Node script](local-script.md) to run them with approvals.
+
+## Scope is not process isolation
+
+With `sandbox: 'off'`, application callbacks retain application privileges.
+`workspace` alone cannot confine arbitrary Node filesystem calls. Schema
+validation and model instructions are not path enforcement. Every file handler
+must enforce scope, including both source and destination of a move. Do not offer
+a generic shell tool as a shortcut around the file handlers.
+
+The bundled path checks assume an app-owned directory without other concurrent
+writers. A separate process can race path checks by replacing directory entries;
+these checks are not a kernel security boundary. For hostile code or concurrent
+untrusted filesystem writers, use an isolated execution backend and run the
+filesystem tools there. Node callbacks do not move into OpenShell merely because
+the harness uses it for other tools. For backend setup, see the optional public
+[OpenShell guide](https://openworker.com/docs/sdk/openshell/).
+
+Move operations can have an uncertain/partial outcome after a crash or failed
+unlink. Reconcile actual file state before retrying; approval is not a guarantee
+of exactly-once filesystem execution.
+
+## Tool names, arguments and activity
+
+Register and select `files.move_file`. Its model-facing alias is
+`files__move_file`; current events and approval requests may use that alias.
+Keep a mapping from your registered names to aliases for display. Do not rename
+tool identities in saved event payloads.
+
+The callback receives arguments directly, plus `context.sessionId`, `turnId` and
+`callId`. Use that tuple to upsert an activity item. Callback delivery can precede
+your consumption of the journal's `tool_started`; do not rely on arrival order.
+
+```typescript
+for await (const item of run.events()) {
+ 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 });
+ }
+ if (item.summary?.type === 'tool_finished') {
+ finishActivity(item.sessionId, item.event.turn_id, item.summary.callId);
+ }
+}
+```
+
+`updateActivity`/`finishActivity` are app UI functions. Typed start/finish summaries
+currently omit arguments; retain them from the raw start event or callback.
+Support absent/withheld data and render arguments as escaped text. Show only
+product-appropriate fields; arguments can contain sensitive user content.
+`context.progress(message, data)` supplies intermediate tool updates without new
+polling. `model_activity` is an elapsed-wait signal, not proof of task progress.
diff --git a/skills/openworker-apps/references/web.md b/skills/openworker-harness-builder/references/web.md
similarity index 100%
rename from skills/openworker-apps/references/web.md
rename to skills/openworker-harness-builder/references/web.md
diff --git a/skills/package.json b/skills/package.json
index eeea3bb7..fb0e4dae 100644
--- a/skills/package.json
+++ b/skills/package.json
@@ -1,6 +1,6 @@
{
- "name": "@openworkerai/build-with-sdk-skills",
- "version": "0.1.0-beta.3",
+ "name": "@openworkerai/openworker-harness-builder",
+ "version": "0.1.0-beta.5",
"description": "Install the OpenWorker app-building skill for Codex or Claude Code",
"type": "module",
"license": "MIT",
@@ -8,16 +8,16 @@
"node": ">=20"
},
"bin": {
- "build-with-sdk-skills": "install.mjs"
+ "openworker-harness-builder": "install.mjs"
},
"files": [
"install.mjs",
- "openworker-apps",
+ "openworker-harness-builder",
"README.md",
"LICENSE"
],
"scripts": {
- "test": "node --test install.test.mjs package.test.mjs"
+ "test": "node --test install.test.mjs package.test.mjs local-script.test.mjs"
},
"repository": {
"type": "git",
@@ -29,5 +29,5 @@
"tag": "beta"
},
"private": true,
- "openworkerSdkVersion": "0.1.0-beta.2"
+ "openworkerSdkVersion": "0.1.0-beta.3"
}
diff --git a/skills/package.test.mjs b/skills/package.test.mjs
index a0acb9c0..4184791a 100644
--- a/skills/package.test.mjs
+++ b/skills/package.test.mjs
@@ -19,21 +19,22 @@ test('packed installer works outside the checkout without SDK or native dependen
execFileSync(npm, ['install', '--offline', '--ignore-scripts', '--no-audit', '--no-fund',
'--cache', join(root, 'cache'), join(archives, archive)],
{cwd:consumer,stdio:'pipe',shell:process.platform==='win32'});
- const installed = join(consumer, 'node_modules/@openworkerai/build-with-sdk-skills');
+ const installed = join(consumer, 'node_modules/@openworkerai/openworker-harness-builder');
const pkg = JSON.parse(await readFile(join(installed, 'package.json'), 'utf8'));
assert.equal(pkg.private, undefined);
assert.equal(pkg.scripts, undefined);
assert.equal(pkg.dependencies, undefined);
assert.equal(pkg.optionalDependencies, undefined);
- assert.deepEqual(await readdir(join(consumer, 'node_modules/@openworkerai')), ['build-with-sdk-skills']);
+ assert.deepEqual(await readdir(join(consumer, 'node_modules/@openworkerai')), ['openworker-harness-builder']);
// Exercise npm's symlink on Unix. On Windows use the installed entry point
// directly so this test does not require cmd.exe quoting for project paths.
- const bin = join(consumer, 'node_modules/.bin/build-with-sdk-skills' + (process.platform==='win32'?'.cmd':''));
+ const bin = join(consumer, 'node_modules/.bin/openworker-harness-builder' + (process.platform==='win32'?'.cmd':''));
const run = (args) => process.platform === 'win32'
? execFileSync(process.execPath,[join(installed,'install.mjs'),...args],{cwd:consumer,encoding:'utf8'})
: execFileSync(bin,args,{cwd:consumer,encoding:'utf8'});
assert.match(run(['--help']), /--agent codex\|claude/);
assert.match(run(['--help']), /--global/);
+ if(process.platform==='win32')assert.match(execFileSync(process.execPath,[join(installed.toUpperCase(),'install.mjs'),'--help'],{cwd:consumer,encoding:'utf8'}),/--agent codex\|claude/);
// Mock only the child's OS home resolver; never write to the developer's
// actual home or override HOME/USERPROFILE while exercising the real CLI.
const userHome=join(root,'personal home');await mkdir(userHome);
@@ -44,17 +45,17 @@ test('packed installer works outside the checkout without SDK or native dependen
const project = join(root, `new ${agent} app`);
await mkdir(project);
assert.match(run(['--agent',agent,'--project',project]), /Installed:/);
- const dest = join(project,agent==='codex'?'.agents':'.claude','skills/openworker-apps');
+ const dest = join(project,agent==='codex'?'.agents':'.claude','skills/openworker-harness-builder');
const metadata = JSON.parse(await readFile(join(dest,'references/installation.json'),'utf8'));
assert.equal(metadata.sdkVersion,pkg.openworkerSdkVersion);
assert.equal(metadata.sdkPackage,'@openworkerai/harness-sdk');
assert.equal(metadata.version,pkg.version);
assert.match(runGlobal(['--agent',agent,'--global']),/Installed:/);
- const globalDest=join(userHome,agent==='codex'?'.agents':'.claude','skills/openworker-apps');
+ const globalDest=join(userHome,agent==='codex'?'.agents':'.claude','skills/openworker-harness-builder');
assert.deepEqual(JSON.parse(await readFile(join(globalDest,'references/installation.json'),'utf8')),metadata);
- for(const file of ['SKILL.md','references/railway.md','assets/railway/Dockerfile','assets/railway/.dockerignore'])
+ for(const file of ['SKILL.md','references/railway.md','references/tools.md','references/approvals.md','references/local-script.md','assets/local-script/organizer.mjs','assets/local-script/file-tools.mjs','assets/railway/Dockerfile','assets/railway/.dockerignore'])
assert.equal(await readFile(join(globalDest,file),'utf8'),await readFile(join(dest,file),'utf8'));
- await assert.rejects(readFile(join(consumer,agent==='codex'?'.agents':'.claude','skills/openworker-apps/SKILL.md')),{code:'ENOENT'});
+ await assert.rejects(readFile(join(consumer,agent==='codex'?'.agents':'.claude','skills/openworker-harness-builder/SKILL.md')),{code:'ENOENT'});
await writeFile(join(globalDest,'SKILL.md'),'personal customization');
assert.throws(()=>runGlobal(['--global','--agent',agent]));
assert.equal(await readFile(join(globalDest,'SKILL.md'),'utf8'),'personal customization');
diff --git a/skills/prepare.mjs b/skills/prepare.mjs
index ed61ceea..2df396b2 100644
--- a/skills/prepare.mjs
+++ b/skills/prepare.mjs
@@ -9,8 +9,11 @@ const source = dirname(fileURLToPath(import.meta.url));
export async function prepare(directory) {
const out = resolve(directory);
const pkg = JSON.parse(await readFile(join(source, 'package.json'), 'utf8'));
- const release = JSON.parse(await readFile(join(source, '../harness/release/manifest.json'), 'utf8'));
- if (pkg.openworkerSdkVersion !== release.version) throw Error('Skill SDK compatibility must match the SDK release');
+ // The independently published Skill pins a tested SDK, which need not be
+ // this checkout's native-release candidate. Do not rewrite that consumer pin.
+ if (typeof pkg.openworkerSdkVersion !== 'string' ||
+ !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*)?$/.test(pkg.openworkerSdkVersion))
+ throw Error('Skill SDK compatibility must pin an exact release version');
await mkdir(out); // An existing candidate must never be overwritten.
const staging = join(out, 'package');
await mkdir(staging);
diff --git a/skills/railway-container.test.mjs b/skills/railway-container.test.mjs
index 63143db9..a0dd1b5c 100644
--- a/skills/railway-container.test.mjs
+++ b/skills/railway-container.test.mjs
@@ -98,7 +98,7 @@ test(
// Supply immutable pre-publication tarballs without substituting the helper.
// The only Dockerfile adaptation is copying this offline dependency vendor dir.
const recipe = await readFile(
- join(here, "openworker-apps/assets/railway/Dockerfile"),
+ join(here, "openworker-harness-builder/assets/railway/Dockerfile"),
"utf8",
);
await writeFile(
@@ -109,7 +109,7 @@ test(
),
);
await copyFile(
- join(here, "openworker-apps/assets/railway/.dockerignore"),
+ join(here, "openworker-harness-builder/assets/railway/.dockerignore"),
join(app, ".dockerignore"),
);
docker("build", "--pull=false", "-t", image, app);
diff --git a/skills/snippets.test.mjs b/skills/snippets.test.mjs
index 8997d56d..50309d93 100644
--- a/skills/snippets.test.mjs
+++ b/skills/snippets.test.mjs
@@ -4,14 +4,17 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
-test('runtime-options examples compile against the matching SDK declarations', async () => {
+test('Skill options and README approval loop compile against the SDK declarations', async () => {
const sdk = resolve('harness/typescript-sdk');
const root = await mkdtemp(join(tmpdir(), 'ow-skill-snippets-'));
try {
await mkdir(join(root, 'node_modules/@openworkerai'), { recursive: true });
await symlink(sdk, join(root, 'node_modules/@openworkerai/harness-sdk'), 'junction');
await writeFile(join(root, 'package.json'), '{"type":"module"}');
- const text = (await Promise.all(['runtime-options.md','subagents.md'].map(name=>readFile('skills/openworker-apps/references/'+name,'utf8')))).join('\n');
+ 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 files = [];
for (const [index, match] of [...text.matchAll(/```typescript\r?\n([\s\S]*?)```/g)].entries()) {
const file = join(root, `example-${index}.ts`);
@@ -21,6 +24,6 @@ test('runtime-options examples compile against the matching SDK declarations', a
if (!files.length) throw Error('No examples found');
execFileSync(process.execPath, [join(sdk, 'node_modules/typescript/bin/tsc'), ...files,
'--noEmit', '--strict', '--skipLibCheck', '--target', 'es2022', '--module', 'nodenext',
- '--typeRoots', join(sdk, 'node_modules/@types')], { stdio: 'pipe' });
+ '--typeRoots', join(sdk, 'node_modules/@types')], { stdio: 'inherit' });
} finally { await rm(root, { recursive: true, force: true }); }
});