@bastani/atomic 0.9.19-alpha.6 → 0.9.19-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -2
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  7. package/dist/builtin/web-access/index.bundle.mjs +22 -3
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/builtin/workflows/CHANGELOG.md +19 -0
  10. package/dist/builtin/workflows/README.md +1 -1
  11. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  12. package/dist/builtin/workflows/builtin/{chunk-vhmnzdj9.js → chunk-1jth021m.js} +1 -1
  13. package/dist/builtin/workflows/builtin/{chunk-p8jjwfg6.js → chunk-2377r57g.js} +4 -2
  14. package/dist/builtin/workflows/builtin/{chunk-hbnwv56f.js → chunk-31j2gs7h.js} +2 -2
  15. package/dist/builtin/workflows/builtin/{chunk-n8zysf1t.js → chunk-ngkqkzej.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-1nbq96fh.js → chunk-nkrafh9s.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-1kx4aggw.js → chunk-wf741bv3.js} +2 -2
  18. package/dist/builtin/workflows/builtin/{chunk-t6x2d78s.js → chunk-z29qbehr.js} +1 -1
  19. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  20. package/dist/builtin/workflows/builtin/goal.js +3 -3
  21. package/dist/builtin/workflows/builtin/index.js +7 -7
  22. package/dist/builtin/workflows/builtin/ralph.js +3 -3
  23. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  24. package/dist/builtin/workflows/package.json +1 -1
  25. package/dist/builtin/workflows/src/extension/index.bundle.mjs +590 -256
  26. package/dist/builtin/workflows/src/index.js +67 -19
  27. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -0
  28. package/dist/modes/interactive/components/task-live-transcript.d.ts +1 -1
  29. package/dist/modes/interactive/components/task-live-transcript.d.ts.map +1 -1
  30. package/dist/modes/interactive/components/task-live-transcript.js +19 -11
  31. package/dist/modes/interactive/components/task-live-transcript.js.map +1 -1
  32. package/docs/background-tasks.md +1 -1
  33. package/docs/build.md +51 -0
  34. package/docs/changelog.mdx +8 -8
  35. package/docs/compaction/reference.md +267 -0
  36. package/docs/compaction.md +36 -219
  37. package/docs/computer-use.md +35 -0
  38. package/docs/containerization.md +2 -0
  39. package/docs/custom-provider/api-reference.md +145 -0
  40. package/docs/custom-provider/oauth.md +131 -0
  41. package/docs/custom-provider/override.md +34 -0
  42. package/docs/custom-provider/registration.md +163 -0
  43. package/docs/custom-provider/streaming.md +214 -0
  44. package/docs/custom-provider.md +43 -607
  45. package/docs/development.md +76 -0
  46. package/docs/docs.json +199 -77
  47. package/docs/environment-variables.md +1 -1
  48. package/docs/extensions/api-reference.md +1001 -0
  49. package/docs/extensions/authoring.md +676 -0
  50. package/docs/extensions/events.md +793 -0
  51. package/docs/extensions/examples.md +94 -0
  52. package/docs/extensions/ui.md +470 -0
  53. package/docs/extensions.md +270 -2768
  54. package/docs/getting-started/authentication.md +55 -0
  55. package/docs/getting-started/first-session.md +172 -0
  56. package/docs/getting-started/installation.md +154 -0
  57. package/docs/getting-started/project-instructions.md +43 -0
  58. package/docs/guides/configuration.md +65 -0
  59. package/docs/guides/intercom.md +24 -0
  60. package/docs/guides/non-interactive.md +33 -0
  61. package/docs/guides/subagents.md +24 -0
  62. package/docs/guides/workflows.md +27 -0
  63. package/docs/guides.md +41 -0
  64. package/docs/index.md +13 -45
  65. package/docs/intercom/operations.md +178 -0
  66. package/docs/intercom/reference.md +146 -0
  67. package/docs/intercom.md +54 -259
  68. package/docs/json.md +17 -0
  69. package/docs/llama-cpp.md +5 -0
  70. package/docs/models/artificial-analysis-index.md +89 -0
  71. package/docs/models/evals.md +2 -2
  72. package/docs/models/model-selection.md +3 -3
  73. package/docs/models/pareto-efficiency.md +2 -2
  74. package/docs/models/reference.md +601 -0
  75. package/docs/models.md +45 -550
  76. package/docs/packages/authoring.md +88 -0
  77. package/docs/packages/reference.md +43 -0
  78. package/docs/packages.md +28 -107
  79. package/docs/programmatic.md +29 -0
  80. package/docs/prompt-templates.md +11 -0
  81. package/docs/providers/reference.md +23 -0
  82. package/docs/providers.md +10 -15
  83. package/docs/quickstart.md +44 -238
  84. package/docs/reference/cli.md +252 -0
  85. package/docs/reference.md +52 -0
  86. package/docs/rpc/examples.md +64 -0
  87. package/docs/rpc/extension-ui.md +198 -0
  88. package/docs/rpc/protocol.md +1341 -0
  89. package/docs/rpc.md +109 -1346
  90. package/docs/sdk/reference.md +1090 -0
  91. package/docs/sdk.md +56 -1002
  92. package/docs/session-format.md +2 -0
  93. package/docs/sessions.md +6 -10
  94. package/docs/settings.md +6 -45
  95. package/docs/skills/authoring.md +95 -0
  96. package/docs/skills/reference.md +60 -0
  97. package/docs/skills.md +20 -122
  98. package/docs/subagents/authoring.md +37 -0
  99. package/docs/subagents/reference.md +60 -0
  100. package/docs/subagents.md +39 -95
  101. package/docs/terminal-setup.md +1 -1
  102. package/docs/themes/reference.md +176 -0
  103. package/docs/themes.md +21 -135
  104. package/docs/tmux.md +5 -0
  105. package/docs/tools/edit.md +5 -0
  106. package/docs/tools.md +5 -0
  107. package/docs/tui/reference.md +343 -0
  108. package/docs/tui.md +23 -286
  109. package/docs/usage.md +26 -209
  110. package/docs/web-access.md +2 -0
  111. package/docs/windows.md +2 -1
  112. package/docs/workflows/api-reference.md +11 -4
  113. package/docs/workflows/authoring.md +4 -2
  114. package/docs/workflows/builtins.md +2 -2
  115. package/docs/workflows/operations.md +15 -10
  116. package/docs/workflows/reliable-design.md +21 -3
  117. package/docs/workflows/verification.md +8 -0
  118. package/npm-shrinkwrap.json +32 -32
  119. package/package.json +3 -3
@@ -0,0 +1,1090 @@
1
+ ---
2
+ title: SDK API reference
3
+ sidebarTitle: "SDK API"
4
+ description: SDK options, resource loaders, return values, run modes, and exports.
5
+ ---
6
+
7
+ # SDK API reference
8
+
9
+ ## Options Reference
10
+
11
+ ### Directories
12
+
13
+ ```typescript
14
+ const { session } = await createAgentSession({
15
+ // Working directory for DefaultResourceLoader discovery
16
+ cwd: process.cwd(), // default
17
+
18
+ // Global config directory
19
+ agentDir: "~/.atomic/agent", // default (expands ~)
20
+ });
21
+ ```
22
+
23
+ Atomic reads primary `.atomic` locations first and legacy `.pi` locations for compatibility when multiple config directories are supported. Passing an explicit `agentDir` makes that directory the user override.
24
+
25
+ `cwd` is used by `DefaultResourceLoader` for:
26
+ - Project extensions (`.atomic/extensions/`, then legacy `.pi/extensions/`)
27
+ - Project skills:
28
+ - `.atomic/skills/`, then legacy `.pi/skills/`
29
+ - `.agents/skills/` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo)
30
+ - Project prompts (`.atomic/prompts/`, then legacy `.pi/prompts/`)
31
+ - Context files (`AGENTS.override.md`, `AGENTS.md`, or `CLAUDE.md` walking up from cwd)
32
+ - Session directory naming
33
+
34
+ `agentDir` is used by `DefaultResourceLoader` for:
35
+ - Global extensions (`extensions/`)
36
+ - Global skills:
37
+ - `skills/` under `agentDir` (for example `~/.atomic/agent/skills/`; legacy `~/.pi/agent/skills/` is also considered by default)
38
+ - `~/.agents/skills/`
39
+ - Global prompts (`prompts/`)
40
+ - Global context files (`AGENTS.override.md`, `AGENTS.md`, or `CLAUDE.md` under `agentDir`)
41
+ - Settings (`settings.json`)
42
+ - Custom models (`models.json`)
43
+ - Credentials (`auth.json`)
44
+ - Sessions (`sessions/`)
45
+
46
+ When you pass a custom `ResourceLoader`, `cwd` and `agentDir` no longer control resource discovery. They still influence session naming and tool path resolution.
47
+
48
+ ### Model
49
+
50
+ ```typescript
51
+ import { getModel } from "@bastani/pi-ai/compat";
52
+ import { ModelRuntime } from "@bastani/atomic";
53
+
54
+ const modelRuntime = await ModelRuntime.create();
55
+
56
+ // Find specific built-in model (doesn't check if credentials exist)
57
+ const opus = getModel("anthropic", "claude-opus-4-5");
58
+ if (!opus) throw new Error("Model not found");
59
+
60
+ // Find any model by provider/id, including custom models from models.json
61
+ const customModel = modelRuntime.getModel("my-provider", "my-model");
62
+
63
+ // Get only models whose providers have configured authentication
64
+ const available = await modelRuntime.getAvailable();
65
+
66
+ const { session } = await createAgentSession({
67
+ model: opus,
68
+ thinkingLevel: "medium", // off, minimal, low, medium, high, xhigh, max (when supported by the model)
69
+
70
+ // Models for cycling (CTRL+P in interactive mode)
71
+ scopedModels: [
72
+ { model: opus, thinkingLevel: "high" },
73
+ { model: haiku, thinkingLevel: "off" },
74
+ ],
75
+
76
+ modelRuntime,
77
+ });
78
+ ```
79
+
80
+ `ModelRegistry` keeps synchronous reads for extension compatibility, while catalog refresh is asynchronous. Extensions should await `modelRegistry.refresh()` before synchronous `getAll()`, `find()`, or `getAvailable()` reads when a provider may update its catalog. New SDK integrations use `ModelRuntime`; `await modelRuntime.refresh()` reports `aborted` and per-provider `errors`, and failed providers retain their last-known models.
81
+
82
+ If no model is provided:
83
+ 1. Tries to restore from session (if continuing)
84
+ 2. Uses default from settings
85
+ 3. Falls back to first available model
86
+
87
+ > See [examples/sdk/02-custom-model.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/02-custom-model.ts)
88
+
89
+ #### Model catalog persistence and refresh
90
+
91
+ `ModelRuntime.create()` restores cached catalogs from local persistence but does not contact
92
+ pi.dev unless you opt in. `allowModelNetwork` (default `false`) enables a create-time network
93
+ refresh, and `modelRefreshTimeoutMs` (default `15_000`) bounds how long that refresh may run
94
+ before it is aborted. Pass `refreshOnCreate: false` to skip the initial catalog and
95
+ availability refresh entirely; built-in models remain available.
96
+
97
+ ```typescript
98
+ const refreshedRuntime = await ModelRuntime.create({
99
+ allowModelNetwork: true,
100
+ modelRefreshTimeoutMs: 15_000,
101
+ });
102
+ ```
103
+
104
+ Remote catalogs are persisted locally so later runtimes can restore them without a network
105
+ request. The default file is `models-store.json` next to `models.json` — with the default
106
+ `modelsPath` that is `~/.atomic/agent/models-store.json`. Set `modelsStorePath` to choose
107
+ another location, or inject `modelsStore` to control persistence entirely; a runtime created
108
+ with `modelsPath: null` keeps its store in memory. Network refreshes are throttled to once
109
+ per provider every four hours unless forced. To force an immediate refresh, call
110
+ `await modelRuntime.refresh({ allowNetwork: true, force: true, signal })`. Setting
111
+ `ATOMIC_OFFLINE` (legacy alias `PI_OFFLINE`) disables model network access, and a
112
+ `refresh()` call that omits `allowNetwork` follows that same runtime network policy.
113
+
114
+ ### API Keys and OAuth
115
+
116
+ `ModelRuntime` is the asynchronous SDK engine for provider composition, credentials, model catalogs, and requests. `ModelRegistry` remains a thin compatibility facade for extensions; `await modelRegistry.complete(model, context, options)` routes a request through its runtime with the resolved provider and auth. New SDK integrations should pass `modelRuntime` to `createAgentSession` and use `modelRuntime.complete()` directly when they issue standalone requests.
117
+
118
+ Credential resolution combines runtime API-key overrides, stored `auth.json` credentials, environment variables, and the active `models.json` provider configuration. OAuth acquisition is provider-owned and runs through `ModelRuntime.login()`.
119
+
120
+ ```typescript
121
+ import { AuthStorage, ModelRuntime } from "@bastani/atomic";
122
+
123
+ const authStorage = AuthStorage.create();
124
+ const modelRuntime = await ModelRuntime.create({ credentials: authStorage });
125
+
126
+ const { session } = await createAgentSession({
127
+ sessionManager: SessionManager.inMemory(),
128
+ modelRuntime,
129
+ });
130
+
131
+ // Runtime API key override (not persisted to disk). Setting the key updates
132
+ // auth state; refresh the provider explicitly when its catalog must be current.
133
+ const providerId = "anthropic";
134
+ const authController = new AbortController();
135
+ await modelRuntime.setRuntimeApiKey(providerId, "sk-my-temp-key", { signal: authController.signal });
136
+ await modelRuntime.refresh({ providers: [providerId], signal: authController.signal });
137
+
138
+ // Custom credential and model configuration locations
139
+ const customRuntime = await ModelRuntime.create({
140
+ authPath: "/my/app/auth.json",
141
+ modelsPath: "/my/app/models.json",
142
+ });
143
+
144
+ const customSession = await createAgentSession({
145
+ sessionManager: SessionManager.inMemory(),
146
+ modelRuntime: customRuntime,
147
+ });
148
+
149
+ // Disable models.json while retaining built-in providers
150
+ const builtinsOnly = await ModelRuntime.create({ modelsPath: null });
151
+ ```
152
+
153
+ > See the complete [`ModelRuntime` credential and model configuration example](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/09-api-keys-and-oauth.ts).
154
+
155
+ ### System Prompt
156
+
157
+ Use a `ResourceLoader` to override the system prompt:
158
+
159
+ ```typescript
160
+ import { createAgentSession, DefaultResourceLoader } from "@bastani/atomic";
161
+
162
+ const loader = new DefaultResourceLoader({
163
+ systemPromptOverride: () => "You are a helpful assistant.",
164
+ });
165
+ await loader.reload();
166
+
167
+ const { session } = await createAgentSession({ resourceLoader: loader });
168
+ ```
169
+
170
+ > See [examples/sdk/03-custom-prompt.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/03-custom-prompt.ts)
171
+
172
+ ### Tools
173
+
174
+ Specify which tools to expose by name:
175
+
176
+ - Built-in tool names enabled by default: `read`, `bash`, `kill`, `edit`, `write`, `find`, `search`, `ask_user_question`, `todo`
177
+ - `find` discovers filesystem paths by glob; `search` searches file contents with regex patterns across files, directories, globs, and internal URLs.
178
+ - `tools` is an allowlist: when provided, only the listed built-in, extension, and custom tool names are exposed, plus mandatory ordinary `intercom`.
179
+ - `excludedTools` is a blocklist: matching built-in, extension, and custom tool names are omitted from the final registry and active tool set, except mandatory ordinary `intercom`. If both are provided, `tools` is applied first and `excludedTools` subtracts from it.
180
+ - `noTools: "all"` disables every tool except mandatory ordinary `intercom`
181
+ - `noTools: "builtin"` disables default built-ins while keeping extension and custom tools enabled, except names listed in `excludedTools`
182
+
183
+ ```typescript
184
+ import { createAgentSession } from "@bastani/atomic";
185
+
186
+ // Read-only mode. `tools` selects optional tools; ordinary Intercom remains active.
187
+ const { session } = await createAgentSession({
188
+ tools: ["read", "search", "find", "ls"],
189
+ });
190
+
191
+ // Pick specific optional tools. Ordinary Intercom remains active even when omitted.
192
+ const { session } = await createAgentSession({
193
+ tools: ["read", "bash", "search"],
194
+ });
195
+
196
+ // Keep defaults but remove HITL prompts
197
+ const { session } = await createAgentSession({
198
+ excludedTools: ["ask_user_question"],
199
+ });
200
+
201
+ // Allowlist first, then subtract exclusions
202
+ const { session } = await createAgentSession({
203
+ tools: ["read", "bash", "ask_user_question"],
204
+ excludedTools: ["ask_user_question"], // optional tools: read, bash; ordinary Intercom remains active
205
+ });
206
+ ```
207
+
208
+ #### Bash tool behavior
209
+
210
+ Atomic's built-in `bash` tool matches upstream pi: when `bash` is enabled, commands execute through the configured shell with the Atomic process permissions. Use `tools`, `excludedTools`, or `noTools` to decide whether a session exposes the `bash` tool at all. Atomic no longer provides a command-level allow/deny option for `bash`; use an operating-system/container sandbox or a custom tool/extension when you need command allowlisting or stronger isolation.
211
+
212
+
213
+ #### Waiting for existing shell tasks
214
+
215
+ Both Bash and PowerShell factories accept `{ action: "wait", id: taskId, budgetMs: 1000 }` with a trusted `taskOwner` binding. No command is executed. `BashToolInput` and `PowerShellToolInput` distinguish command launches from existing-task waits; narrow by `action` before reading `command`.
216
+
217
+ `budgetMs` is optional, finite, and non-negative. Omission uses the owner's command wait policy and zero polls. Results keep the `WaitOutcome` in `details.observation`, available exit information in `details.exitCode`, and retained output in text content. Failure and cancellation metadata remain in the settled observation. Yielded waits advance through bounded retained-output pages for the same owned task, even when the tool is recreated. Partial UTF-8 characters continue on the next page. Settled waits return all retained output again, subject to labelled gaps and truncation. Aborting the call releases only its observation. A binding from `AgentTaskHost.ownerBinding` also releases waits for incoming owner messages.
218
+
219
+ Do not mix wait arguments with launch fields. Unknown or foreign IDs and unbound waits are rejected before execution hooks. Custom `operations.exec` does not provide existing-task ownership. See [Background tasks](/background-tasks) for examples and lifetime rules.
220
+
221
+ #### PowerShell tool behavior
222
+
223
+ `createPowerShellTool()` and `createPowerShellToolDefinition()` provide the same tool used by interactive sessions. When their default local operations execute on native Windows, they prefer `pwsh.exe`, fall back to `powershell.exe`, and throw a clear error when neither executable is available. `createLocalPowerShellOperations()` and `getPowerShellConfig()` are also exported for custom integrations. The PowerShell factories expose the current `ATOMIC_*` and legacy `PI_*` session snapshot by default; set `exposeSessionEnvironment: false` to opt out.
224
+
225
+ PowerShell tools and local operations accept a trusted `taskOwner` binding and the same
226
+ `wait` observation policy as bash. Owned native Windows execution automatically yields
227
+ after the owner's command budget (normally 10000 ms); explicit per-call budgets override it,
228
+ and execution timeout remains separate. Commands use encoded PowerShell transport internally,
229
+ while task descriptions retain the original command text. Without a supported owner,
230
+ explicit background requests are refused and foreground execution waits for completion.
231
+
232
+ ```typescript
233
+ import { createPowerShellTool } from "@bastani/atomic";
234
+
235
+ const powershell = createPowerShellTool("C:\\path\\to\\project");
236
+ ```
237
+
238
+ #### Tools with Custom cwd
239
+
240
+ When you pass a custom `cwd`, `createAgentSession()` builds selected built-in tools for that cwd.
241
+
242
+ ```typescript
243
+ import { createAgentSession, SessionManager } from "@bastani/atomic";
244
+
245
+ const cwd = "/path/to/project";
246
+
247
+ // Use default tools for custom cwd
248
+ const { session } = await createAgentSession({
249
+ cwd,
250
+ sessionManager: SessionManager.inMemory(cwd),
251
+ });
252
+
253
+ // Or pick specific tools for custom cwd
254
+ const { session } = await createAgentSession({
255
+ cwd,
256
+ tools: ["read", "bash", "search"],
257
+ sessionManager: SessionManager.inMemory(cwd),
258
+ });
259
+ ```
260
+
261
+ > See [examples/sdk/05-tools.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/05-tools.ts)
262
+
263
+ ### Custom Tools
264
+
265
+ ```typescript
266
+ import { Type } from "typebox";
267
+ import { createAgentSession, defineTool } from "@bastani/atomic";
268
+
269
+ // Inline custom tool
270
+ const myTool = defineTool({
271
+ name: "my_tool",
272
+ label: "My Tool",
273
+ description: "Does something useful",
274
+ parameters: Type.Object({
275
+ input: Type.String({ description: "Input value" }),
276
+ }),
277
+ execute: async (_toolCallId, params) => ({
278
+ content: [{ type: "text", text: `Result: ${params.input}` }],
279
+ details: {},
280
+ }),
281
+ });
282
+
283
+ // Pass custom tools directly
284
+ const { session } = await createAgentSession({
285
+ customTools: [myTool],
286
+ });
287
+ ```
288
+
289
+ Use `defineTool()` for standalone definitions and arrays like `customTools: [myTool]`. Inline `pi.registerTool({ ... })` already infers parameter types correctly.
290
+
291
+ Custom tools passed via `customTools` are combined with extension-registered tools. Extensions loaded by the ResourceLoader can also register tools via `pi.registerTool()`.
292
+
293
+ If you pass `tools`, include each custom or extension tool name you want enabled, for example `tools: ["read", "bash", "my_tool"]`. Use `excludedTools` to remove a custom or extension tool by name from the final exposed set.
294
+
295
+ `ToolDefinition.constrainedSampling` is part of the public SDK and survives `defineTool()`, `customTools`, tool wrappers, session/staged inspection, and isolated execution. Use `{ type: "json_schema", strict: "prefer" | "require" }`, `{ type: "grammar", variants: { openai_lark?: string, openai_regex?: string } }`, or `false`. `prefer` can fall back; `require` fails when the active model cannot enforce strict JSON Schema. Grammar constraints require one required string parameter and capable model metadata. Public inspection preserves optional-property identity exactly: an omitted key stays absent, an explicitly present `undefined` stays present, and `false` or a config object remains unchanged. The exported `ConstrainedSamplingConfig` type and [extension reference](/extensions/authoring#constrained-sampling) define the exact shape. Typed RPC clients receive the four model capability flags through optional `ModelInfo.compat`; see [RPC](/rpc/protocol#get_available_models).
296
+
297
+ Factory-created `createBashTool()` instances receive the same execution-time `ATOMIC_SESSION_*`/`PI_SESSION_*` model and session snapshot as the built-in bash tool. Set `exposeSessionEnvironment: false` only when the subprocess must not receive it. `MessageRenderOptions.outputPad` is likewise passed to normal and isolated custom message renderers.
298
+
299
+ Normal sessions also expose `kill({ id: taskId })` for their owned bash and PowerShell background tasks. Include `kill` when using a `tools` allowlist if the agent should be able to stop those tasks. The exported `createKillTool` and `createKillToolDefinition` factories accept `KillToolOptions.taskOwner`, a trusted execution-time callback returning the same owner binding used by shell launch. Without a binding they reject execution. The result details preserve the supervisor's `CancelReceipt`, including its decision, execution outcome, and cleanup state. See [Background tasks](/background-tasks#stop-a-shell-task-from-a-tool-call).
300
+
301
+ #### Structured output final results
302
+
303
+ `structured_output` is not registered in normal agent sessions by default. Add it only when a caller needs a machine-readable final-answer contract by registering the exported factory as a custom tool:
304
+
305
+ ```typescript
306
+ import { Type, type Static } from "typebox";
307
+ import {
308
+ createAgentSession,
309
+ createStructuredOutputTool,
310
+ type StructuredOutputCapture,
311
+ } from "@bastani/atomic";
312
+
313
+ const DecisionSchema = Type.Object({
314
+ approved: Type.Boolean(),
315
+ findings: Type.Array(Type.String()),
316
+ }, { additionalProperties: false });
317
+
318
+ type Decision = Static<typeof DecisionSchema>;
319
+ const capture: StructuredOutputCapture<Decision> = {
320
+ called: false,
321
+ value: undefined,
322
+ };
323
+
324
+ const structuredOutput = createStructuredOutputTool({
325
+ schema: DecisionSchema,
326
+ capture,
327
+ });
328
+
329
+ const { session } = await createAgentSession({
330
+ customTools: [structuredOutput],
331
+ });
332
+ ```
333
+
334
+ The tool parameters are exactly the supplied schema: with `DecisionSchema`, the model calls `structured_output({ approved, findings })`. Array and primitive schemas are also accepted by the factory when the target provider/tool runtime supports them; the captured value is whatever JSON value matches the schema. A successful call stores the params in `capture.value`, returns them as pretty-printed JSON tool-result text for text print mode, keeps the flat value in tool `details`, writes the same JSON to the configured `output.outputPath` when an `output` file sink is configured, and sets `terminate: true` so there is no extra follow-up assistant turn. Atomic relies on the tool schema instead of extra structured-output parsing or sidecar validation. Structured-output tool definitions opt out of oversized-result persistence.
335
+
336
+ Custom tool names are supported, and the prompt metadata follows the configured name. If you use a custom name such as `final_decision`, include that name in any explicit `tools` allowlist. If the standard `structured_output` name is required, register the factory with its default name:
337
+
338
+ ```typescript
339
+ const finalDecision = createStructuredOutputTool({
340
+ name: "final_decision",
341
+ schema: DecisionSchema,
342
+ capture,
343
+ });
344
+ // The model is prompted to call final_decision exactly once, not structured_output.
345
+
346
+ await createAgentSession({
347
+ customTools: [finalDecision],
348
+ tools: ["final_decision"], // only this tool is enabled
349
+ });
350
+
351
+ await createAgentSession({
352
+ customTools: [createStructuredOutputTool({ schema: DecisionSchema, capture })],
353
+ // Registers the standard structured_output tool for this session only.
354
+ });
355
+ ```
356
+
357
+ > See [examples/sdk/05-tools.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/05-tools.ts)
358
+
359
+ ### Extensions
360
+
361
+ Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.atomic/agent/extensions/` and `.atomic/extensions/` first, then legacy `~/.pi/agent/extensions/` and `.pi/extensions/`, plus settings.json extension sources.
362
+
363
+ ```typescript
364
+ import { createAgentSession, DefaultResourceLoader } from "@bastani/atomic";
365
+
366
+ const loader = new DefaultResourceLoader({
367
+ additionalExtensionPaths: ["/path/to/my-extension.ts"],
368
+ extensionFactories: [
369
+ (pi) => {
370
+ pi.on("agent_start", () => {
371
+ console.log("[Inline Extension] Agent starting");
372
+ });
373
+ },
374
+ ],
375
+ });
376
+ await loader.reload();
377
+
378
+ const { session } = await createAgentSession({ resourceLoader: loader });
379
+ ```
380
+
381
+ `createAgentSession()` preserves resources from a supplied loader but restores Atomic's mandatory bundled Intercom extension after loader overrides, deferred reloads, and same-name extension or `customTools` collisions. The supplied loader still controls every optional extension.
382
+
383
+ Strict reloads (`failOnExtensionErrors: true`) require the loader's transactional `prepareReload()` support so a failed candidate cannot mutate live state before validation. `DefaultResourceLoader` provides that support. Custom loaders without it remain compatible with ordinary reloads, but strict reload fails before calling their mutating `reload()` method.
384
+
385
+ Extensions can register tools, subscribe to events, add commands, and more. See [Extensions](/extensions) for the full API.
386
+
387
+ **Event Bus:** Extensions can communicate via `pi.events`. Pass a shared `eventBus` to `DefaultResourceLoader` if you need to emit or listen from outside:
388
+
389
+ ```typescript
390
+ import { createEventBus, DefaultResourceLoader } from "@bastani/atomic";
391
+
392
+ const eventBus = createEventBus();
393
+ const loader = new DefaultResourceLoader({
394
+ eventBus,
395
+ });
396
+ await loader.reload();
397
+
398
+ eventBus.on("my-extension:status", (data) => console.log(data));
399
+ ```
400
+
401
+ > See [examples/sdk/06-extensions.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/06-extensions.ts) and [Extensions](/extensions)
402
+
403
+ ### Skills
404
+
405
+ ```typescript
406
+ import {
407
+ createAgentSession,
408
+ DefaultResourceLoader,
409
+ type Skill,
410
+ } from "@bastani/atomic";
411
+
412
+ const customSkill: Skill = {
413
+ name: "my-skill",
414
+ description: "Custom instructions",
415
+ filePath: "/path/to/SKILL.md",
416
+ baseDir: "/path/to",
417
+ source: "custom",
418
+ };
419
+
420
+ const loader = new DefaultResourceLoader({
421
+ skillsOverride: (current) => ({
422
+ skills: [...current.skills, customSkill],
423
+ diagnostics: current.diagnostics,
424
+ }),
425
+ });
426
+ await loader.reload();
427
+
428
+ const { session } = await createAgentSession({ resourceLoader: loader });
429
+ ```
430
+
431
+ > See [examples/sdk/04-skills.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/04-skills.ts)
432
+
433
+ ### Context Files
434
+
435
+ ```typescript
436
+ import { createAgentSession, DefaultResourceLoader } from "@bastani/atomic";
437
+
438
+ const loader = new DefaultResourceLoader({
439
+ agentsFilesOverride: (current) => ({
440
+ agentsFiles: [
441
+ ...current.agentsFiles,
442
+ { path: "/virtual/AGENTS.md", content: "# Guidelines\n\n- Be concise" },
443
+ ],
444
+ }),
445
+ });
446
+ await loader.reload();
447
+
448
+ const { session } = await createAgentSession({ resourceLoader: loader });
449
+ ```
450
+
451
+ > See [examples/sdk/07-context-files.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/07-context-files.ts)
452
+
453
+ ### Slash Commands
454
+
455
+ ```typescript
456
+ import {
457
+ createAgentSession,
458
+ DefaultResourceLoader,
459
+ type PromptTemplate,
460
+ } from "@bastani/atomic";
461
+
462
+ const customCommand: PromptTemplate = {
463
+ name: "deploy",
464
+ description: "Deploy the application",
465
+ source: "(custom)",
466
+ content: "# Deploy\n\n1. Build\n2. Test\n3. Deploy",
467
+ };
468
+
469
+ const loader = new DefaultResourceLoader({
470
+ promptsOverride: (current) => ({
471
+ prompts: [...current.prompts, customCommand],
472
+ diagnostics: current.diagnostics,
473
+ }),
474
+ });
475
+ await loader.reload();
476
+
477
+ const { session } = await createAgentSession({ resourceLoader: loader });
478
+ ```
479
+
480
+ > See [examples/sdk/08-prompt-templates.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/08-prompt-templates.ts)
481
+
482
+ ### Session Management
483
+
484
+ Sessions use a tree structure with `id`/`parentId` linking, enabling in-place branching.
485
+
486
+ ```typescript
487
+ import {
488
+ type CreateAgentSessionRuntimeFactory,
489
+ createAgentSession,
490
+ createAgentSessionFromServices,
491
+ createAgentSessionRuntime,
492
+ createAgentSessionServices,
493
+ getAgentDir,
494
+ SessionManager,
495
+ } from "@bastani/atomic";
496
+
497
+ // In-memory (no persistence)
498
+ const { session } = await createAgentSession({
499
+ sessionManager: SessionManager.inMemory(),
500
+ });
501
+
502
+ // New persistent session
503
+ const { session: persisted } = await createAgentSession({
504
+ sessionManager: SessionManager.create(process.cwd()),
505
+ });
506
+
507
+ // Continue most recent
508
+ const { session: continued, modelFallbackMessage } = await createAgentSession({
509
+ sessionManager: SessionManager.continueRecent(process.cwd()),
510
+ });
511
+ if (modelFallbackMessage) {
512
+ console.log("Note:", modelFallbackMessage);
513
+ }
514
+
515
+ // Open specific file
516
+ const { session: opened } = await createAgentSession({
517
+ sessionManager: SessionManager.open("/path/to/session.jsonl"),
518
+ });
519
+
520
+ // List sessions
521
+ const currentProjectSessions = await SessionManager.list(process.cwd());
522
+ const allSessions = await SessionManager.listAll(process.cwd());
523
+
524
+ // Session replacement API for /new, /resume, /fork, /clone, and import flows.
525
+ const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
526
+ const services = await createAgentSessionServices({ cwd });
527
+ return {
528
+ ...(await createAgentSessionFromServices({
529
+ services,
530
+ sessionManager,
531
+ sessionStartEvent,
532
+ })),
533
+ services,
534
+ diagnostics: services.diagnostics,
535
+ };
536
+ };
537
+
538
+ const runtime = await createAgentSessionRuntime(createRuntime, {
539
+ cwd: process.cwd(),
540
+ agentDir: getAgentDir(),
541
+ sessionManager: SessionManager.create(process.cwd()),
542
+ });
543
+
544
+ // Replace the active session with a fresh one
545
+ await runtime.newSession();
546
+
547
+ // Replace the active session with another saved session
548
+ await runtime.switchSession("/path/to/session.jsonl");
549
+
550
+ // Replace the active session with a fork from a specific user entry
551
+ await runtime.fork("entry-id");
552
+
553
+ // Clone the active path through a specific entry
554
+ await runtime.fork("entry-id", { position: "at" });
555
+ ```
556
+
557
+ **SessionManager tree API:**
558
+
559
+ ```typescript
560
+ const sm = SessionManager.open("/path/to/session.jsonl");
561
+
562
+ // Session listing
563
+ const currentProjectSessions = await SessionManager.list(process.cwd());
564
+ const allSessions = await SessionManager.listAll(process.cwd());
565
+
566
+ // Tree traversal
567
+ const entries = sm.getEntries(); // All entries (excludes header)
568
+ const tree = sm.getTree(); // Full tree structure
569
+ const path = sm.getPath(); // Path from root to current leaf
570
+ const leaf = sm.getLeafEntry(); // Current leaf entry
571
+ const entry = sm.getEntry(id); // Get entry by ID
572
+ const children = sm.getChildren(id); // Direct children of entry
573
+
574
+ // Labels
575
+ const label = sm.getLabel(id); // Get label for entry
576
+ sm.appendLabelChange(id, "checkpoint"); // Set label
577
+
578
+ // Branching
579
+ sm.branch(entryId); // Move leaf to earlier entry
580
+ sm.branchWithSummary(id, "Summary..."); // Branch with context summary
581
+ sm.createBranchedSession(leafId); // Extract path to new file
582
+ ```
583
+
584
+ > See [examples/sdk/11-sessions.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/11-sessions.ts) and [Session Format](/session-format)
585
+
586
+ ### Settings Management
587
+
588
+ ```typescript
589
+ import { createAgentSession, SettingsManager, SessionManager } from "@bastani/atomic";
590
+
591
+ // Default: loads from files (global + project merged)
592
+ const { session } = await createAgentSession({
593
+ settingsManager: SettingsManager.create(),
594
+ });
595
+
596
+ // With overrides
597
+ const settingsManager = SettingsManager.create();
598
+ settingsManager.applyOverrides({
599
+ compaction: { enabled: false },
600
+ retry: { enabled: true, maxRetries: 5 },
601
+ });
602
+ const { session } = await createAgentSession({ settingsManager });
603
+
604
+ // In-memory (no file I/O, for testing)
605
+ const { session } = await createAgentSession({
606
+ settingsManager: SettingsManager.inMemory({ compaction: { enabled: false } }),
607
+ sessionManager: SessionManager.inMemory(),
608
+ });
609
+
610
+ // Custom directories
611
+ const { session } = await createAgentSession({
612
+ settingsManager: SettingsManager.create("/custom/cwd", "/custom/agent"),
613
+ });
614
+ ```
615
+
616
+ **Static factories:**
617
+ - `SettingsManager.create(cwd?, agentDir?)` - Load from files
618
+ - `SettingsManager.inMemory(settings?)` - No file I/O
619
+
620
+ **Project-specific settings:**
621
+
622
+ Settings load from Atomic-first locations and merge:
623
+ 1. Global: `~/.atomic/agent/settings.json`, then legacy `~/.pi/agent/settings.json`
624
+ 2. Project: `<cwd>/.atomic/settings.json`, then legacy `<cwd>/.pi/settings.json`
625
+
626
+ Project overrides global. Nested objects merge keys. Setters modify global settings by default.
627
+
628
+ **Persistence and error handling semantics:**
629
+
630
+ - Settings getters/setters are synchronous for in-memory state.
631
+ - Setters enqueue persistence writes asynchronously.
632
+ - Call `await settingsManager.flush()` when you need a durability boundary (for example, before process exit or before asserting file contents in tests).
633
+ - `SettingsManager` does not print settings I/O errors. Use `settingsManager.drainErrors()` and report them in your app layer.
634
+
635
+ > See [examples/sdk/10-settings.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/sdk/10-settings.ts)
636
+
637
+ ## ResourceLoader
638
+
639
+ Use `DefaultResourceLoader` to discover extensions, skills, prompts, themes, and context files.
640
+
641
+ ```typescript
642
+ import {
643
+ DefaultResourceLoader,
644
+ getAgentDir,
645
+ } from "@bastani/atomic";
646
+
647
+ const loader = new DefaultResourceLoader({
648
+ cwd,
649
+ agentDir: getAgentDir(),
650
+ });
651
+ await loader.reload();
652
+
653
+ const extensions = loader.getExtensions();
654
+ const skills = loader.getSkills();
655
+ const prompts = loader.getPrompts();
656
+ const themes = loader.getThemes();
657
+ const contextFiles = loader.getAgentsFiles().agentsFiles;
658
+ ```
659
+
660
+ ## Return Value
661
+
662
+ `createAgentSession()` returns:
663
+
664
+ ```typescript
665
+ interface CreateAgentSessionResult {
666
+ // The session
667
+ session: AgentSession;
668
+
669
+ // Extensions result (for runner setup)
670
+ extensionsResult: LoadExtensionsResult;
671
+
672
+ // Warning if session model couldn't be restored
673
+ modelFallbackMessage?: string;
674
+ }
675
+
676
+ interface LoadExtensionsResult {
677
+ extensions: Extension[];
678
+ errors: Array<{ path: string; error: string }>;
679
+ runtime: ExtensionRuntime;
680
+ }
681
+ ```
682
+
683
+ ## Run Modes
684
+
685
+ The SDK exports run mode utilities for building custom interfaces on top of `createAgentSession()`:
686
+
687
+ ### InteractiveMode
688
+
689
+ Full TUI interactive mode with editor, chat history, and all built-in commands:
690
+
691
+ ```typescript
692
+ import {
693
+ type CreateAgentSessionRuntimeFactory,
694
+ createAgentSessionFromServices,
695
+ createAgentSessionRuntime,
696
+ createAgentSessionServices,
697
+ getAgentDir,
698
+ InteractiveMode,
699
+ SessionManager,
700
+ } from "@bastani/atomic";
701
+
702
+ const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
703
+ const services = await createAgentSessionServices({ cwd });
704
+ return {
705
+ ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })),
706
+ services,
707
+ diagnostics: services.diagnostics,
708
+ };
709
+ };
710
+ const runtime = await createAgentSessionRuntime(createRuntime, {
711
+ cwd: process.cwd(),
712
+ agentDir: getAgentDir(),
713
+ sessionManager: SessionManager.create(process.cwd()),
714
+ });
715
+
716
+ const mode = new InteractiveMode(runtime, {
717
+ migratedProviders: [],
718
+ modelFallbackMessage: undefined,
719
+ initialMessage: "Hello",
720
+ initialImages: [],
721
+ initialMessages: [],
722
+ });
723
+
724
+ await mode.run();
725
+ ```
726
+
727
+ ### runPrintMode
728
+
729
+ Single-shot mode: send prompts, output result, exit:
730
+
731
+ ```typescript
732
+ import {
733
+ type CreateAgentSessionRuntimeFactory,
734
+ createAgentSessionFromServices,
735
+ createAgentSessionRuntime,
736
+ createAgentSessionServices,
737
+ getAgentDir,
738
+ runPrintMode,
739
+ SessionManager,
740
+ } from "@bastani/atomic";
741
+
742
+ const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
743
+ const services = await createAgentSessionServices({ cwd });
744
+ return {
745
+ ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })),
746
+ services,
747
+ diagnostics: services.diagnostics,
748
+ };
749
+ };
750
+ const runtime = await createAgentSessionRuntime(createRuntime, {
751
+ cwd: process.cwd(),
752
+ agentDir: getAgentDir(),
753
+ sessionManager: SessionManager.create(process.cwd()),
754
+ });
755
+
756
+ await runPrintMode(runtime, {
757
+ mode: "text",
758
+ initialMessage: "Hello",
759
+ initialImages: [],
760
+ messages: ["Follow up"],
761
+ });
762
+ ```
763
+
764
+ ### runRpcMode
765
+
766
+ JSON-RPC mode for subprocess integration:
767
+
768
+ ```typescript
769
+ import {
770
+ type CreateAgentSessionRuntimeFactory,
771
+ createAgentSessionFromServices,
772
+ createAgentSessionRuntime,
773
+ createAgentSessionServices,
774
+ getAgentDir,
775
+ runRpcMode,
776
+ SessionManager,
777
+ } from "@bastani/atomic";
778
+
779
+ const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
780
+ const services = await createAgentSessionServices({ cwd });
781
+ return {
782
+ ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })),
783
+ services,
784
+ diagnostics: services.diagnostics,
785
+ };
786
+ };
787
+ const runtime = await createAgentSessionRuntime(createRuntime, {
788
+ cwd: process.cwd(),
789
+ agentDir: getAgentDir(),
790
+ sessionManager: SessionManager.create(process.cwd()),
791
+ });
792
+
793
+ await runRpcMode(runtime);
794
+ ```
795
+
796
+ See [RPC documentation](/rpc) for the JSON protocol.
797
+
798
+ ## Exports
799
+
800
+ The main entry point exports:
801
+
802
+ ```typescript
803
+ // Factory
804
+ createAgentSession
805
+ createAgentSessionRuntime
806
+ AgentSessionRuntime
807
+
808
+ // Auth and Models
809
+ AuthStorage
810
+ ModelRegistry
811
+
812
+ // Resource loading
813
+ DefaultResourceLoader
814
+ type ResourceLoader
815
+ createEventBus
816
+
817
+ // Constants and helpers
818
+ CONFIG_DIR_NAME
819
+ defineTool
820
+ STRUCTURED_OUTPUT_TOOL_NAME
821
+ createStructuredOutputTool
822
+ createStructuredOutputCapture
823
+ getAgentDir
824
+ getPackageDir
825
+ getReadmePath
826
+ getDocsPath
827
+ getExamplesPath
828
+ generateDiffString
829
+ generateUnifiedPatch
830
+ type EditDiffResult
831
+
832
+ // Session management
833
+ SessionManager
834
+ SettingsManager
835
+
836
+ // Tool factories
837
+ createCodingTools
838
+ createReadOnlyTools
839
+ createReadTool, createBashTool, createEditTool, createWriteTool
840
+ createGrepTool, createFindTool, createLsTool
841
+
842
+ // Types
843
+ type CreateAgentSessionOptions
844
+ type CreateAgentSessionResult
845
+ type StructuredOutputCapture
846
+ type StructuredOutputToolOptions
847
+ type ExtensionFactory
848
+ type ExtensionAPI
849
+ type ToolDefinition
850
+ type Skill
851
+ type PromptTemplate
852
+ type Tool
853
+ ```
854
+
855
+ For extension types, see [Extensions](/extensions) for the full API.
856
+
857
+ ## Owner-bound task supervisor (S1)
858
+
859
+ S1 adds an SDK-only task foundation in `src/core/tasks/contracts.ts` and
860
+ `src/core/tasks/supervisor.ts`, backed by the native `TaskSupervisor`. It is an
861
+ internal trusted-host integration surface, not a new CLI command. The package root
862
+ exports the narrow `AgentTaskHost` adapter and its integration types, not the raw
863
+ supervisor. Runtime-created subagent contexts use it; bash/PTY and task UI integration are separate slices.
864
+
865
+ `AgentTaskHost` binds an actual trusted scope and mandatory `authorizeLaunch` guard.
866
+ Its `startAgentTask(intent, operation, runnerFactory)` returns a Result containing
867
+ `{taskId, lease}` after setup. Each launch supplies its own factory receiving the
868
+ original `AbortSignal`, reference and `reportActivity` context. Return separate
869
+ `result` and `cleanup` promises; yielding never replaces either promise, and only
870
+ confirmed cleanup may report `reaped`. Exact operation replay never calls another factory.
871
+ `observeAgentLaunch(taskId, policy?)` delegates to S1 initial observation; `waitForTask`,
872
+ `resolveTask`, `cancelTask`, `watchOwnerTasks` and `close` remain owner-scoped S1 doors.
873
+ Observation returns the exact Result/WaitOutcome DTO, not a new model response shape.
874
+ These APIs are for trusted first-party hosts, never model-supplied ownership or permission.
875
+
876
+ For already-admitted in-process tasks, the optional `taskExecution` runner hooks
877
+ retain the original execution and cleanup promises. An exact Intercom commit
878
+ yields the registered observation. In an explicit foreground group it also yields
879
+ active sibling observations through the existing group signal, once per child;
880
+ neither path detaches or completes those executions. Public launches in actual sessions use this bridge by default.
881
+
882
+ Each workflow admission boundary allocates one process-private stage attempt identity.
883
+ The actual stage session binds its original session/run/stage identity; fallback session
884
+ replacement keeps that identity and the same lazily bound `bindAgentTaskHost` owner.
885
+ Replacement disposal does not close tasks. Boundary sealing fences task admission and
886
+ starts owner closure; generation close awaits independent cleanup and surfaces failure.
887
+ Fresh boundaries have fresh identities, including restoration; history is not a restart
888
+ capability. Public producers, durable callback joins and nonvisual completion intent/admission use this owner binding.
889
+
890
+ When a task completion outbox is created from session history, it immediately retries
891
+ unacknowledged terminal completion intents through the current admission boundary.
892
+ It does not wait for another task to settle or recreate execution capabilities.
893
+ Acknowledged intents are not redelivered. Failed admission keeps the original completion
894
+ identity pending for retry; a closed boundary prevents admission.
895
+ Top-level session initialization restores admission keys from persisted custom messages,
896
+ so a crash after delivery is persisted but before its outbox acknowledgement does not
897
+ deliver the same completion again.
898
+
899
+ A host binds its actual session or workflow-stage scope with `bindHostSession`,
900
+ provides launch authorization and a runner factory, then calls `openTaskOwner`.
901
+ Authorization runs before native admission. `startAgentTask` registers an agent
902
+ task before runner setup and returns its lease without waiting for completion.
903
+ Exact operation replay reuses that task and execution; a fresh operation creates
904
+ a distinct task. Leases are environment-local capabilities, cannot be serialized,
905
+ and cannot be reconstructed from task IDs or historical records.
906
+
907
+ `initialObservation` applies launch policy: omitted policy yields
908
+ `default-background`, explicit background yields `explicit`, and foreground
909
+ registers a wait with its requested budget. A ready terminal result wins.
910
+ `await waitForTask(task, budgetMs?, designation?)` and
911
+ `await foregroundTask(task, budgetMs?)` return a Result containing a WaitOutcome,
912
+ not a lease. Native registration and the WaitId registry are populated synchronously
913
+ before either door awaits. Host lifecycle actions can use `findWait(waitId)` to
914
+ yield or dispose a registered observation; ordinary callers need no extra observe call.
915
+ SDK waits do not replace the host designation unless given a matching HostSession.
916
+ An elapsed/explicit yield or observer disposal never stops or relaunches execution;
917
+ a later yield of a disposed wait replays its ObserverCancelled Result.
918
+
919
+ Requested agent waits default to 30000 ms. Supply owner-host settings through
920
+ `bindHostSession({ scope, tasks: { wait: { kind: "automatic", agentBudgetMs: 5000 } },
921
+ authorizeLaunch, createRunner })`; `{ kind: "until-settled" }` disables timed yielding.
922
+ Per-call budgets override settings, including zero for immediate yield. These settings
923
+ apply to explicit foreground-first launch, live foregrounding and task-ID waits,
924
+ never to a default independent launch. Wide numeric budgets are not narrowed to u32.
925
+ Accepted `NaN` budgets (including configured `agentBudgetMs`) do not panic native
926
+ scheduling. The implementation leaves such observations pending until explicit yield,
927
+ settlement, observer disposal or owner closure: the elapsed comparison never reaches
928
+ `NaN`. It uses bounded sleep chunks without rewriting the caller's budget. This is
929
+ scheduling behavior, not a new finite-only input restriction or an RFC-mandated deadline;
930
+ other numeric budgets and per-call precedence are unchanged.
931
+
932
+ `await cancelTask(task, cause)` returns a Result containing a cancellation receipt
933
+ and preserves the first accepted cause. `closeTaskOwner` seals admission before
934
+ draining and succeeds only after independent cleanup acknowledgement. The trusted
935
+ runner supplies separate result and cleanup promises: confirmed reaping after
936
+ cancellation can close even if no result arrives. Natural cleanup-first delivery
937
+ waits for its outcome before acknowledging reaping. External native owner closure
938
+ also aborts resources attached to already-settled results without rewriting them.
939
+ Failed cleanup remains observable; absent acknowledgement can leave close pending.
940
+ User cancellation retains pending input attention until settlement or owner closure;
941
+ event-reduced and reattached snapshots report the same native facts. Runner result
942
+ rejections become failed `RunnerFailed` results; cleanup rejections become diagnostic
943
+ `CleanupFailed` resources, never successful reaping. Setup throws retain `SpawnFailed`
944
+ and unconfirmed cleanup. Strings and Error messages are preserved verbatim; other JS
945
+ values use safe string conversion, with `Unprintable JavaScript rejection` if conversion
946
+ throws. Cancelled cleanup still does not depend on the result promise settling.
947
+ This slice exercises fake runners, not force-stop or real-process cleanup guarantees.
948
+
949
+ ### Supervised command SDK
950
+
951
+ `startCommandTask(owner, intent, operation)` starts an owned Unix pipe/PTY or Windows pipe/ConPTY command.
952
+ The command intent keeps execution timeout separate from observation: `waitForTask`
953
+ defaults to 10000 ms for commands, and expiry returns a yielded observation without
954
+ terminating the process. On Unix, owner closure sends TERM, allows 250 ms grace, then KILL,
955
+ reaps the leader and confirms process-group exit and reader drain. A cleanup failure
956
+ retains diagnostics instead of claiming a closed owner. This is normal owner/host
957
+ shutdown cleanup, not a guarantee for forced host death or a blocked JavaScript loop.
958
+
959
+ Both native and facade `CommandIntent` accept optional `shell: { program, args }`:
960
+ the executable is launched directly with `command` appended as one final argv argument.
961
+ Omitting `shell` preserves the default native pipe shell. `inheritEnv` defaults to
962
+ `true`; `false` uses exactly the supplied environment rather than inheriting the host's.
963
+ Both fields participate in operation replay identity.
964
+
965
+ `taskStdin(task)` returns a non-serializable stdin capability. `writeTaskInput` takes
966
+ an operation ID and `{kind:"bytes", bytes:Uint8Array}` or `{kind:"eof"}`. Empty bytes
967
+ are a no-op. Input has 65536 byte credits, refuses excess input before admission,
968
+ and replays recorded receipts without resending bytes. Ambiguous partial delivery
969
+ returns `InputDeliveryUnknown`, including operation ID and known accepted-byte count.
970
+
971
+ `readTaskOutput(task, {start, maximumBytes})` returns owned byte chunks at decimal
972
+ offsets, requested bounds, omitted ranges and an optional next offset. Requests
973
+ are clamped to the 1 MiB live-preview bound before allocating or reading a page;
974
+ use `nextOffset` to continue. It does not sanitize or normalize bytes. Retention
975
+ uses a 1 MiB live head/tail, 8 MiB foreground spill threshold and 5 GiB disk cap.
976
+ Retained output is not conversation history. File-spool policy uses supervised
977
+ pipe drains, never inherited direct file writers. Stdout, stderr and descendants
978
+ share one serialized disk budget; crossing writes retain only the permitted prefix.
979
+ The file remains within the cap during foreground collection and termination.
980
+ After foreground collection yields, rejected overflow kills the group and settles
981
+ `OutputLimitExceeded` after confirmed cleanup. Spool setup failure refuses launch
982
+ with `SpawnFailed`. Drained pipe/PTY output instead keeps running with bounded
983
+ retained bytes and omissions.
984
+ Unix PTY resize uses the retained portable-pty master; Windows PTY uses ConPTY.
985
+ Windows pipe and ConPTY commands start suspended and enter a kill-on-close Job Object
986
+ before resume. Failed containment refuses execution, with no unsupervised spawn fallback.
987
+ Cleanup must be confirmed; failures retain diagnostic resources rather than reporting reaping.
988
+ Native Windows legacy WSL `bash.exe` stdin transport remains refused for owned launch:
989
+ Windows jobs cannot supervise the Linux guest process tree. Atomic running inside WSL
990
+ uses the normal POSIX/Bash path instead.
991
+
992
+ Bash tools and `createLocalBashOperations` accept a trusted `taskOwner` binding.
993
+ On Unix and native Windows, that binding obtains pipe/PTY processes through supervised admission,
994
+ preserving configured shell arguments, cwd, environment and existing authorization.
995
+ Foreground collection honors the owner's command wait configuration, including
996
+ `until-settled`; the automatic default is 10000 ms. A yielded process stays owned
997
+ and its retained output remains readable. Bash output inserts explicit
998
+ `[Output omitted: bytes start-end]` markers, with an exclusive end offset, between
999
+ retained chunks rather than silently joining gaps. Without that binding, existing
1000
+ bash and native PTY execution are unchanged. No UI is added.
1001
+
1002
+ `watchOwnerTasks(owner, cursor?)` provides an opaque `lease`, snapshot,
1003
+ decimal-string cursor and disposable `AsyncIterable<NativeEvent>`. Each iterator
1004
+ observes one contiguous delivery epoch. On local backlog overflow or native journal
1005
+ reset, the subscription updates its authoritative `snapshot` and `cursor`, discards
1006
+ stale queued deltas, and completes the old iterator (`next()` returns `done:true`,
1007
+ including an already-pending read). This also works when an oversized final settlement
1008
+ leaves no retained event, without later activity or cleanup. No synthetic reset event
1009
+ is inserted and the `NativeEvent` and subscription types are unchanged.
1010
+
1011
+ After any iterator completion, reconcile `subscription.snapshot` at
1012
+ `subscription.cursor`. If the owner is still live and observation is still wanted,
1013
+ obtain another iterator from the **same** `subscription.events`; the old iterator stays
1014
+ done. Reset does not dispose the subscription or close the owner. Subsequent deltas
1015
+ are authentic and ordered; ignore events at or below an already-applied snapshot
1016
+ cursor. Explicit `dispose()` (idempotent) or breaking out of a live iterator ends
1017
+ observation, not the owner. Owner closure also ends delivery. Track your own disposal
1018
+ when deciding whether to resume. New subscriptions are refused once owner closing
1019
+ begins; existing subscriptions continue through cleanup/closure.
1020
+ Calling `dispose()` from `onReconcile` also stops the active drain from publishing
1021
+ its retained events. Pending and newly created iterators finish without those events;
1022
+ the reconciled snapshot remains available.
1023
+
1024
+ The optional `subscription.onReconcile` callback is a convenience, not required for
1025
+ correctness; callback exceptions remain visible as `subscription.failure`. Raw strings
1026
+ and Error messages are preserved; unprintable values (including hostile conversion or
1027
+ revoked proxies) use `Unprintable JavaScript rejection`. Diagnostic conversion cannot
1028
+ interrupt event delivery or rearming the fallback poll. Native callbacks are wake hints;
1029
+ journal drains and reset snapshots are authoritative. Each live subscription has one
1030
+ fallback poll, stopped on disposal or observed closure.
1031
+ The native byte journal and facade delivery backlog are bounded. Each task separately
1032
+ retains its most recent 256 accepted activity report IDs, SHA-256 payload hashes and
1033
+ receipts (`TASK_REPORT_IDENTITY_WINDOW`). Within that window, identical payloads return
1034
+ `duplicate` with the original cursor; conflicting payloads return `ReportConflict`.
1035
+ Neither check emits events or refreshes retention order. An evicted ID is fresh: while
1036
+ the task is live it is `accepted`, applies its activity again and gets a new cursor;
1037
+ existing terminal and owner-close guards still apply. Terminal outcome reports and
1038
+ their recorded receipts are retained separately for the task record's lifetime and
1039
+ never evicted by activity churn. This bounds identity entry count, not caller ID length,
1040
+ task count, terminal payloads or total task-history memory. S1 adds no persistence layer.
1041
+
1042
+ Activity IDs have no reserved spellings, including `runner-outcome`, empty strings
1043
+ and isolated surrogates. The facade submits its own result through private trusted
1044
+ runner support: the actor selects a free terminal identity and accepts the outcome
1045
+ under the same lock. With at most 256 retained activity IDs, at most 257 distinct
1046
+ candidates suffice; selection emits no events and retains no extra ID history.
1047
+ Caller-supplied reports still use the unchanged `reportTaskOutcome` contract:
1048
+ same-ID cross-kind reports conflict, and terminal replay retains its original receipt.
1049
+ The internal support also reuses an accepted terminal identity, so a different result
1050
+ cannot replace it; cancellation-first still rejects late natural outcomes. Normal,
1051
+ rejected and setup-failure results all use this path without bypassing cleanup evidence.
1052
+
1053
+ Caller-provided strings retain their exact JavaScript UTF-16 code units, including
1054
+ isolated surrogates, valid pairs and embedded NUL, across scopes, intent, operation/report
1055
+ identity, activity, results and nested output/cleanup metadata. They remain ordinary
1056
+ `string` fields, not encoded wrappers. Replacing a surrogate with U+FFFD is a changed
1057
+ payload or identity, never an exact replay. Nonempty descriptions supply the title;
1058
+ otherwise the first nonblank task line is copied without rewriting its code units,
1059
+ falling back to the agent name. Absent optional fields, empty strings, known zero metrics
1060
+ and ordered duplicate data remain distinct. The optional `elapsedMs`, `toolCount` and `tokenCount` metrics and
1061
+ completed/failed `exitCode` preserve JavaScript numbers without narrowing or normalization,
1062
+ including fractional and extreme values. Within the retained activity window (and for
1063
+ terminal reports throughout the task record's lifetime), exact replay distinguishes
1064
+ omission, zero and negative zero; repeated NaN and infinite values acknowledge once.
1065
+ Changed numeric payloads return `ReportConflict` without earning another event. `OutputRef` is
1066
+ metadata, not proof of retained bytes: output
1067
+ storage, `readTaskOutput`, command input, persistence, completion delivery and
1068
+ real agent/Intercom integration belong to later slices. The credential-free
1069
+ repository fixture `test/fixtures/task-s1-demo.ts` exercises this real facade and
1070
+ native actor with one fake runner.
1071
+
1072
+ ### Task transcript references
1073
+
1074
+ An admitted runner can call `context.bindTranscript(sessionManager)` with its existing
1075
+ child session history. `readTaskTranscript(task, cursor?)` in `core/tasks/transcript.ts`
1076
+ reads that binding through the task capability. It returns message and content-block
1077
+ references, not copied text: `id`, `kind`, `source`, and `toolCallId` when applicable.
1078
+ Kinds are `prompt`, `assistant`, `tool-call`, `tool-result`, and `response`.
1079
+ Thinking blocks and non-conversation entries are excluded. Repeated source IDs are
1080
+ deduplicated; repeated messages with different IDs remain distinct.
1081
+
1082
+ The first page contains up to 100 recent references in source order. Pass the opaque
1083
+ `nextCursor` to read earlier references; `omittedEarlier` identifies remaining older
1084
+ content. Cursors belong to one task and bound session. An unknown task returns
1085
+ `UnknownTask`, a cursor from another task/session returns `ScopeMismatch`, and an
1086
+ unbound or empty history returns `TranscriptUnavailable` with `Transcript unavailable`.
1087
+ This adapter does not launch work or reconstruct live capabilities from history.
1088
+ Production subagent runners bind their child history, and main and attached workflow
1089
+ chat hosts mount the shared inspector. Command detail reads are scoped to the current
1090
+ selection and view lifetime: late results and errors cannot overwrite another view.