@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
@@ -29,35 +29,48 @@ Extensions are TypeScript modules that extend Atomic's behavior. They can subscr
29
29
 
30
30
  See [examples/extensions/](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions) for working implementations.
31
31
 
32
- Atomic also ships an environment-gated [Herdr reporter](/herdr). It combines settled agent activity, extension prompt events, and observed workflow roots under one parent pane owner. It defers to loaded community or legacy reporters and can be disabled with `herdr.enabled` in settings. The tested Herdr release and observed CLI behaviour are listed under [Compatibility](/herdr#compatibility).
32
+ Atomic also ships an environment-gated [Herdr reporter](/herdr). It combines settled agent activity, extension prompt events, and observed workflow roots under one parent pane owner. It defers to loaded community or legacy reporters and can be disabled with `herdr.enabled` in settings. See [Herdr setup](/herdr#setup) for the supported version and [status indicators](/herdr#status-indicators) for reported activity.
33
+
34
+ ## Where to go next
35
+
36
+ Extensions are TypeScript modules that add tools, commands, event handlers, and custom UI. Read this page for startup behavior, locations, imports, and a first extension, then continue:
37
+
38
+ - [Writing extensions](/extensions/authoring) — build one, manage its state, and register custom tools.
39
+ - [Extension events](/extensions/events) — every event, its payload, and its return contract.
40
+ - [Extension UI](/extensions/ui) — render custom UI from an extension.
41
+ - [Extension API reference](/extensions/api-reference) — `ExtensionContext`, `ExtensionCommandContext`, `ExtensionAPI` methods, and error handling.
42
+ - [Extension examples](/extensions/examples) — runnable examples shipped with Atomic.
43
+ - [Security](/security) — the project-trust boundary that decides whether a project's extensions load, and what an extension can reach once it does. Read this before installing an extension you did not write.
44
+
45
+ If an extension is heavier than you need, compare the lighter mechanisms on [Build with Atomic](/build).
33
46
 
34
47
  ## Table of Contents
35
48
 
36
- - [Startup and lazy discovery](#startup-and-lazy-discovery)
37
- - [Interactive callback isolation](#interactive-callback-isolation)
38
- - [Quick Start](#quick-start)
39
- - [Extension Locations](#extension-locations)
40
- - [Available Imports](#available-imports)
41
- - [Writing an Extension](#writing-an-extension)
42
- - [Extension Styles](#extension-styles)
43
- - [Events](#events)
44
- - [Lifecycle Overview](#lifecycle-overview)
45
- - [Resource Events](#resource-events)
46
- - [Session Events](#session-events)
47
- - [Agent Events](#agent-events)
48
- - [Model Events](#model-events)
49
- - [Tool Events](#tool-events)
50
- - [Workflow activity and lifecycle hooks](#workflow-activity-and-lifecycle-hooks)
51
- - [ExtensionContext](#extensioncontext)
52
- - [ExtensionCommandContext](#extensioncommandcontext)
53
- - [ExtensionAPI Methods](#extensionapi-methods)
54
- - [State Management](#state-management)
55
- - [Session-scoped in-memory state](#session-scoped-in-memory-state)
56
- - [Custom Tools](#custom-tools)
57
- - [Custom UI](#custom-ui)
58
- - [Error Handling](#error-handling)
59
- - [Mode Behavior](#mode-behavior)
60
- - [Examples Reference](#examples-reference)
49
+ - [Startup and lazy discovery](/extensions#startup-and-lazy-discovery)
50
+ - [Interactive callback isolation](/extensions#interactive-callback-isolation)
51
+ - [Quick Start](/extensions#quick-start)
52
+ - [Extension Locations](/extensions#extension-locations)
53
+ - [Available Imports](/extensions#available-imports)
54
+ - [Writing an Extension](/extensions/authoring#writing-an-extension)
55
+ - [Extension Styles](/extensions/authoring#extension-styles)
56
+ - [Events](/extensions/events#events)
57
+ - [Lifecycle Overview](/extensions/events#lifecycle-overview)
58
+ - [Resource Events](/extensions/events#resource-events)
59
+ - [Session Events](/extensions/events#session-events)
60
+ - [Agent Events](/extensions/events#agent-events)
61
+ - [Model Events](/extensions/events#model-events)
62
+ - [Tool Events](/extensions/events#tool-events)
63
+ - [Workflow activity and lifecycle hooks](/extensions/events#workflow-activity-and-lifecycle-hooks)
64
+ - [ExtensionContext](/extensions/api-reference#extensioncontext)
65
+ - [ExtensionCommandContext](/extensions/api-reference#extensioncommandcontext)
66
+ - [ExtensionAPI Methods](/extensions/api-reference#extensionapi-methods)
67
+ - [State Management](/extensions/authoring#state-management)
68
+ - [Session-scoped in-memory state](/extensions/authoring#session-scoped-in-memory-state)
69
+ - [Custom Tools](/extensions/authoring#custom-tools)
70
+ - [Custom UI](/extensions/ui#custom-ui)
71
+ - [Error Handling](/extensions/api-reference#error-handling)
72
+ - [Mode Behavior](/extensions#mode-behavior)
73
+ - [Examples Reference](/extensions/examples#examples-reference)
61
74
 
62
75
  ## Startup and lazy discovery
63
76
 
@@ -109,9 +122,9 @@ The engine child is launched with an environment that never contains Atomic's en
109
122
 
110
123
  Dialogs and `ctx.ui.custom()` components are proxied to the host as rendered lines with asynchronous input forwarding. Custom UI results must be JSON-safe. APIs that require a synchronous callback in the terminal process—raw `onTerminalInput` transforms, synchronous `getEditorText`, custom editor factories, autocomplete wrappers, component-factory widgets, and custom header/footer factories—are unavailable in isolated interactive mode and produce a warning rather than executing extension code in the host. Print and public RPC modes retain their existing execution model.
111
124
 
112
- For session-style list pickers use `ctx.ui.hostSessionPicker(request)` instead of remote-rendering a selector through `ctx.ui.custom()`: the terminal host mounts the real built-in session selector natively, fed with JSON-safe rows (`HostSessionPickerRow`: `SessionInfo` with `createdAt`/`modifiedAt` epoch millis). Arrow-key navigation and search never cross the process boundary; only semantic events do — the returned handle exposes `result` (resolves with the selected row's `path`, or `undefined` on cancel), `update(rows)`, `error(message)`, and `close()`, and the request's `onDelete(path)` callback owns deletion (the host keeps the row until the extension replies with `update` or `error`). Every interactive host implements the identical API — in-process (no IPC) when not isolated, over the engine protocol when isolated — so callers never branch; the member is absent only on non-interactive surfaces (headless RPC, print), where commands should fail with an actionable error. See [Host-native session picker](/tui#host-native-session-picker) for an example.
125
+ For session-style list pickers use `ctx.ui.hostSessionPicker(request)` instead of remote-rendering a selector through `ctx.ui.custom()`: the terminal host mounts the real built-in session selector natively, fed with JSON-safe rows (`HostSessionPickerRow`: `SessionInfo` with `createdAt`/`modifiedAt` epoch millis). Arrow-key navigation and search never cross the process boundary; only semantic events do — the returned handle exposes `result` (resolves with the selected row's `path`, or `undefined` on cancel), `update(rows)`, `error(message)`, and `close()`, and the request's `onDelete(path)` callback owns deletion (the host keeps the row until the extension replies with `update` or `error`). Every interactive host implements the identical API — in-process (no IPC) when not isolated, over the engine protocol when isolated — so callers never branch; the member is absent only on non-interactive surfaces (headless RPC, print), where commands should fail with an actionable error. See [Host-native session picker](/tui/reference#host-native-session-picker) for an example.
113
126
 
114
- For structured forms use `ctx.ui.hostInputForm(request)`. It accepts JSON-safe field descriptors (`string`, `text`, `number`, `integer`, `boolean`, or `select`, each with a raw `initialValue`) and resolves to a raw string record or `undefined` on cancellation. The terminal host owns the component, focus, validation, configured-keybinding handling, and mutable text state, so Tab, arrows, editing, Enter, Escape, and Ctrl+C are host-local rather than asynchronously forwarded to the engine child. Both interactive modes expose the same optional API; headless RPC and print omit it. See [Host-native input form](/tui#host-native-input-form).
127
+ For structured forms use `ctx.ui.hostInputForm(request)`. It accepts JSON-safe field descriptors (`string`, `text`, `number`, `integer`, `boolean`, or `select`, each with a raw `initialValue`) and resolves to a raw string record or `undefined` on cancellation. The terminal host owns the component, focus, validation, configured-keybinding handling, and mutable text state, so Tab, arrows, editing, Enter, Escape, and Ctrl+C are host-local rather than asynchronously forwarded to the engine child. Both interactive modes expose the same optional API; headless RPC and print omit it. See [Host-native input form](/tui/reference#host-native-input-form).
115
128
 
116
129
  ## Quick Start
117
130
 
@@ -223,2906 +236,471 @@ Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
223
236
 
224
237
  ## Writing an Extension
225
238
 
226
- An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous:
239
+ Moved to [Writing extensions](/extensions/authoring#writing-an-extension).
227
240
 
228
- ```typescript
229
- import type { ExtensionAPI } from "@bastani/atomic";
241
+ ### Async factory functions
230
242
 
231
- export default function (pi: ExtensionAPI) {
232
- // Subscribe to events
233
- pi.on("event_name", async (event, ctx) => {
234
- // ctx.ui for user interaction
235
- const ok = await ctx.ui.confirm("Title", "Are you sure?");
236
- ctx.ui.notify("Done!", "info");
237
- ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
238
- ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
239
- });
243
+ Moved to [Writing extensions](/extensions/authoring#async-factory-functions).
240
244
 
241
- // Register tools, commands, shortcuts, flags
242
- pi.registerTool({ ... });
243
- pi.registerCommand("name", { ... });
244
- pi.registerShortcut("ctrl+x", { ... });
245
- pi.registerFlag("my-flag", { ... });
246
- }
247
- ```
245
+ ### Long-lived resources and shutdown
248
246
 
249
- Editable user, project, and package extensions and user workflows are loaded through [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation. `/reload` uses content-hash invalidation across the complete imported file graph: an unchanged graph can reuse its evaluated factory, while a direct edit or a transitive dependency edit re-evaluates that extension's modules.
247
+ Moved to [Writing extensions](/extensions/authoring#long-lived-resources-and-shutdown).
250
248
 
251
- Imports from Atomic's supplied core packages keep the running host's classes and shared state across `/reload`, including on Windows. The supported `@earendil-works/pi-coding-agent` compatibility import shares those exports with `@bastani/atomic`, so class comparisons and `instanceof` checks work across both names after reload. Edits to your extension and its imported local helpers still take effect; restart Atomic after updating Atomic itself.
249
+ ### Extension Styles
252
250
 
253
- In Bun compiled or bundled single-file builds, Atomic's five fixed installed builtin extension bundles (workflows, subagents, MCP, web access, and Intercom) take a separate startup path. Atomic installs its live host-module bridge, imports each precompiled bundle natively once, and reuses the evaluated factory across `/reload`. This avoids jiti source reads, transforms, hashing, and graph manifests for immutable shipped code. A builtin bundle's module-scoped state is therefore **not** re-evaluated by `/reload` in those builds. This optimization is limited to exact installed entries of identity-verified Atomic packages; editable extensions and workflows retain the dynamic behavior above.
251
+ Moved to [Writing extensions](/extensions/authoring#extension-styles).
254
252
 
255
- If the factory returns a `Promise`, Atomic awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `pi.registerProvider()` are flushed.
253
+ ## Events
256
254
 
257
- ### Async factory functions
255
+ Moved to [Extension events](/extensions/events#events).
258
256
 
259
- Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
257
+ ### Lifecycle Overview
260
258
 
261
- ```typescript
262
- import type { ExtensionAPI } from "@bastani/atomic";
259
+ Moved to [Extension events](/extensions/events#lifecycle-overview).
263
260
 
264
- export default async function (pi: ExtensionAPI) {
265
- const response = await fetch("http://localhost:1234/v1/models");
266
- const payload = (await response.json()) as {
267
- data: Array<{
268
- id: string;
269
- name?: string;
270
- context_window?: number;
271
- max_tokens?: number;
272
- }>;
273
- };
274
-
275
- pi.registerProvider("local-openai", {
276
- baseUrl: "http://localhost:1234/v1",
277
- apiKey: "$LOCAL_OPENAI_API_KEY",
278
- api: "openai-completions",
279
- models: payload.data.map((model) => ({
280
- id: model.id,
281
- name: model.name ?? model.id,
282
- reasoning: false,
283
- input: ["text"],
284
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
285
- contextWindow: model.context_window ?? 128000,
286
- maxTokens: model.max_tokens ?? 4096,
287
- })),
288
- });
289
- }
290
- ```
261
+ ### Startup Events
291
262
 
292
- This pattern makes the fetched models available during normal startup and to `atomic --list-models`.
263
+ Moved to [Extension events](/extensions/events#startup-events).
293
264
 
294
- ### Long-lived resources and shutdown
265
+ #### project_trust
295
266
 
296
- Extension factories may run in invocations that never start a session, such as metadata commands or early configuration checks. Do not start background resources such as processes, sockets, file watchers, or timers from the factory.
267
+ Moved to [Extension events](/extensions/events#project_trust).
297
268
 
298
- Defer background resource startup until `session_start` or the command/tool/event that needs the resource. Register an idempotent `session_shutdown` handler to close any session-scoped resources you start.
269
+ ### Resource Events
299
270
 
300
- ### Extension Styles
271
+ Moved to [Extension events](/extensions/events#resource-events).
301
272
 
302
- **Single file** - simplest, for small extensions:
273
+ #### resources_discover
303
274
 
304
- ```
305
- ~/.atomic/agent/extensions/
306
- └── my-extension.ts
307
- ```
275
+ Moved to [Extension events](/extensions/events#resources_discover).
308
276
 
309
- **Directory with index.ts** - for multi-file extensions:
277
+ ### Session Events
310
278
 
311
- ```
312
- ~/.atomic/agent/extensions/
313
- └── my-extension/
314
- ├── index.ts # Entry point (exports default function)
315
- ├── tools.ts # Helper module
316
- └── utils.ts # Helper module
317
- ```
279
+ Moved to [Extension events](/extensions/events#session-events).
318
280
 
319
- **Package with dependencies** - for extensions that need npm packages:
281
+ #### session_start
320
282
 
321
- ```
322
- ~/.atomic/agent/extensions/
323
- └── my-extension/
324
- ├── package.json # Declares dependencies and entry points
325
- ├── bun.lock
326
- ├── node_modules/ # After dependency install
327
- └── src/
328
- └── index.ts
329
- ```
283
+ Moved to [Extension events](/extensions/events#session_start).
330
284
 
331
- ```json
332
- // package.json
333
- {
334
- "name": "my-extension",
335
- "dependencies": {
336
- "zod": "^3.0.0",
337
- "chalk": "^5.0.0"
338
- },
339
- "atomic": {
340
- "extensions": ["./src/index.ts"]
341
- }
342
- }
343
- ```
285
+ #### session_info_changed
344
286
 
345
- The manifest key is the configured Atomic app name (`atomic` here, from the running Atomic package/config), not the extension package's own `"name"` field. The legacy `pi` key is still accepted as a compatibility shim. Run `bun install` in the extension directory, then imports from `node_modules/` work automatically.
287
+ Moved to [Extension events](/extensions/events#session_info_changed).
346
288
 
347
- ## Events
289
+ #### session_before_switch
348
290
 
349
- ### Lifecycle Overview
291
+ Moved to [Extension events](/extensions/events#session_before_switch).
350
292
 
351
- Interactive trust-gated startup first emits `session_start` and `resources_discover` for the permitted trust-safe extensions, then resolves `project_trust`. After authorization, newly loaded extensions receive `session_start`; resource discovery runs again against the completed set. Existing reporters keep their session and do not receive a second `session_start`. Noninteractive startup resolves trust before the ordinary session lifecycle.
293
+ #### session_before_fork
352
294
 
353
- ```
354
- Atomic starts
355
-
356
- ├─► session_start / resources_discover (trust-safe interactive bootstrap, when needed)
357
- ├─► project_trust (user/global and CLI extensions only, before project resources load)
358
- ├─► session_start { reason: "startup" } (extensions not already started)
359
- └─► resources_discover { reason: "startup" }
360
-
361
-
362
- user sends prompt ─────────────────────────────────────────┐
363
- │ │
364
- ├─► (extension commands checked first, bypass if found) │
365
- ├─► input (can intercept, transform, or handle) │
366
- ├─► (skill/template expansion if not handled) │
367
- ├─► before_agent_start (can inject message, modify system prompt)
368
- ├─► agent_start │
369
- ├─► message_start / message_update / message_end │
370
- │ │
371
- │ ┌─── turn (repeats while LLM calls tools) ───┐ │
372
- │ │ │ │
373
- │ ├─► turn_start │ │
374
- │ ├─► context (can modify messages) │ │
375
- │ ├─► before_provider_request (can inspect or replace payload)
376
- │ ├─► after_provider_response (status + headers, before stream consume)
377
- │ │ │ │
378
- │ │ LLM responds, may call tools: │ │
379
- │ │ ├─► tool_execution_start │ │
380
- │ │ ├─► tool_call (can block) │ │
381
- │ │ ├─► tool_execution_update │ │
382
- │ │ ├─► tool_result (can modify) │ │
383
- │ │ └─► tool_execution_end │ │
384
- │ │ │ │
385
- │ ├─► turn_end │ │
386
- │ └─► post-tool threshold preflight │ │
387
- │ (may compact before the next provider request) │
388
- └─► agent_end │
389
-
390
- user sends another prompt ◄────────────────────────────────┘
391
-
392
- /new (new session) or /resume (switch session)
393
- ├─► session_before_switch (can cancel)
394
- ├─► session_shutdown
395
- ├─► session_start { reason: "new" | "resume", previousSessionFile? }
396
- └─► resources_discover { reason: "startup" }
397
-
398
- /fork or /clone
399
- ├─► session_before_fork (can cancel)
400
- ├─► session_shutdown
401
- ├─► session_start { reason: "fork", previousSessionFile }
402
- └─► resources_discover { reason: "startup" }
403
-
404
- /compact or auto-compaction
405
- ├─► compaction_start / compaction_end (verbatim line-compaction status)
406
- ├─► session_before_compact (can cancel or provide compactedText)
407
- ├─► session_compact (after the compaction boundary is persisted)
408
- └─► session_compact_failed (failure or cancellation)
409
-
410
- /tree navigation
411
- ├─► session_before_tree (can cancel or customize)
412
- └─► session_tree
413
-
414
- /model or CTRL+P (model selection/cycling)
415
- ├─► thinking_level_select (if model change changes/clamps thinking level)
416
- └─► model_select
417
-
418
- thinking level changes (settings, keybinding, pi.setThinkingLevel())
419
- └─► thinking_level_select
420
-
421
- exit (CTRL+C, CTRL+D, SIGHUP, SIGTERM)
422
- └─► session_shutdown
423
- ```
295
+ Moved to [Extension events](/extensions/events#session_before_fork).
424
296
 
425
- ### Startup Events
297
+ #### session_before_compact / session_compact / session_compact_failed
426
298
 
427
- #### project_trust
299
+ Moved to [Extension events](/extensions/events#session_before_compact-/-session_compact-/-session_compact_failed).
428
300
 
429
- Fired before Atomic decides whether to trust a project with dynamic configs (`.atomic`, legacy `.pi`, or `.agents/skills`). It runs during startup and when session replacement (for example `/resume`) enters a cwd whose trust has not been resolved in the current process. Only user/global extensions and CLI `-e` extensions participate; project-local extensions are not loaded until after trust is resolved.
301
+ #### session_before_tree / session_tree
430
302
 
431
- ```typescript
432
- pi.on("project_trust", async (event, ctx) => {
433
- // event.cwd - current working directory
434
- // ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers
435
- if (ctx.hasUI && await ctx.ui.confirm("Trust project?", event.cwd)) {
436
- return { trusted: "yes", remember: true };
437
- }
438
- return { trusted: "undecided" };
439
- });
440
- ```
303
+ Moved to [Extension events](/extensions/events#session_before_tree-/-session_tree).
441
304
 
442
- A `project_trust` handler must return `{ trusted: "yes" | "no" | "undecided" }`. A user/global or CLI extension that returns `"yes"` or `"no"` owns the decision; the first yes/no decision wins and suppresses the built-in trust prompt. Use `remember: true` to persist a yes/no decision; otherwise it applies only to the current process. Return `"undecided"` to let later handlers or the built-in trust flow decide. Check `ctx.hasUI` before prompting. If no handler returns yes/no, normal trust resolution continues: saved `trust.json` decisions apply first, then `defaultProjectTrust` controls whether Atomic asks, trusts, or declines by default.
305
+ #### session_shutdown
443
306
 
444
- ### Resource Events
307
+ Moved to [Extension events](/extensions/events#session_shutdown).
445
308
 
446
- #### resources_discover
309
+ ### Agent Events
447
310
 
448
- Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
449
- The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
311
+ Moved to [Extension events](/extensions/events#agent-events).
450
312
 
451
- ```typescript
452
- pi.on("resources_discover", async (event, _ctx) => {
453
- // event.cwd - current working directory
454
- // event.reason - "startup" | "reload"
455
- return {
456
- skillPaths: ["/path/to/skills"],
457
- promptPaths: ["/path/to/prompts"],
458
- themePaths: ["/path/to/themes"],
459
- };
460
- });
461
- ```
313
+ #### before_agent_start
462
314
 
463
- ### Session Events
315
+ Moved to [Extension events](/extensions/events#before_agent_start).
464
316
 
465
- See [Session Format](/session-format) for session storage internals and the SessionManager API.
317
+ #### agent_start / agent_end / agent_settled
466
318
 
467
- #### session_start
319
+ Moved to [Extension events](/extensions/events#agent_start-/-agent_end-/-agent_settled).
468
320
 
469
- Fired when a session is started, loaded, or reloaded.
321
+ #### ui_prompt_start / ui_prompt_end
470
322
 
471
- ```typescript
472
- pi.on("session_start", async (event, ctx) => {
473
- // event.reason - "startup" | "reload" | "new" | "resume" | "fork"
474
- // event.previousSessionFile - present for "new", "resume", and "fork"
475
- ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
476
- });
477
- ```
323
+ Moved to [Extension events](/extensions/events#ui_prompt_start-/-ui_prompt_end).
478
324
 
479
- #### session_info_changed
325
+ #### turn_start / turn_end
480
326
 
481
- Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`.
327
+ Moved to [Extension events](/extensions/events#turn_start-/-turn_end).
482
328
 
483
- ```typescript
484
- pi.on("session_info_changed", async (event, ctx) => {
485
- // event.name - current normalized name, or undefined if cleared
486
- ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info");
487
- });
488
- ```
329
+ #### message_start / message_update / message_end
489
330
 
490
- #### session_before_switch
331
+ Moved to [Extension events](/extensions/events#message_start-/-message_update-/-message_end).
491
332
 
492
- Fired before starting a new session (`/new`) or switching sessions (`/resume`).
333
+ #### tool_execution_start / tool_execution_update / tool_execution_end
493
334
 
494
- ```typescript
495
- pi.on("session_before_switch", async (event, ctx) => {
496
- // event.reason - "new" or "resume"
497
- // event.targetSessionFile - session we're switching to (only for "resume")
498
-
499
- if (event.reason === "new") {
500
- const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
501
- if (!ok) return { cancel: true };
502
- }
503
- });
504
- ```
335
+ Moved to [Extension events](/extensions/events#tool_execution_start-/-tool_execution_update-/-tool_execution_end).
505
336
 
506
- After a successful switch or new-session action, Atomic emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`.
507
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
337
+ #### context
508
338
 
509
- #### session_before_fork
339
+ Moved to [Extension events](/extensions/events#context).
510
340
 
511
- Fired when forking via `/fork` or cloning via `/clone`.
341
+ #### before_provider_headers
512
342
 
513
- ```typescript
514
- pi.on("session_before_fork", async (event, ctx) => {
515
- // event.entryId - ID of the selected entry
516
- // event.position - "before" for /fork, "at" for /clone
517
- return { cancel: true }; // Cancel fork/clone
518
- // OR
519
- return { skipConversationRestore: true }; // Reserved for future conversation restore control
520
- });
521
- ```
343
+ Moved to [Extension events](/extensions/events#before_provider_headers).
522
344
 
523
- After a successful fork or clone, Atomic emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
524
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
345
+ #### before_provider_request
525
346
 
526
- #### session_before_compact / session_compact / session_compact_failed
347
+ Moved to [Extension events](/extensions/events#before_provider_request).
527
348
 
528
- Fired by `/compact` and auto-compaction, including a threshold crossing detected after tool results enter the prospective next-turn context. Atomic prepares the complete active transcript except for the exact newest `preserve_recent` context-visible messages. Extensions may cancel or provide a complete, non-empty `compactedText` replacement for that region; they cannot move `firstKeptEntryId`. The override is persisted verbatim and works without provider credentials. A successful post-tool compaction returns its rebuilt context directly to the already-active Pi loop; it does not start a separate continuation. Cancellation or failure prevents that loop's follow-up provider request.
349
+ #### after_provider_response
529
350
 
530
- ```typescript
531
- pi.on("session_before_compact", async (event) => {
532
- const { preparation, branchEntries, parameters, reason, signal } = event;
533
-
534
- // preparation.region.lines - unnumbered compactable transcript lines
535
- // preparation.firstKeptEntryId - fixed start of the exact tail, or null when the tail is empty
536
- // preparation.tokensBefore - whole-context token estimate
537
- // parameters - compression_ratio, preserve_recent, query
538
- // branchEntries - raw entries on the active branch
539
- // reason - "manual" | "threshold" | "overflow"
540
- // preparation is a deep-frozen clone
541
-
542
- if (signal.aborted) return { cancel: true };
543
-
544
- // Cancel compaction:
545
- return { cancel: true };
546
-
547
- // Or replace only the prepared region. Whitespace-only text is rejected.
548
- return {
549
- compactedText: preparation.region.lines.slice(0, 40).join("\n"),
550
- };
551
- });
552
-
553
- pi.on("session_compact", async (event) => {
554
- // event.result - VerbatimCompactionResult (text, boundary, stats, parameters, rung)
555
- // event.compactionEntry - saved CompactionEntry with strategy "verbatim-lines"
556
- // event.fromExtension - true when session_before_compact provided compactedText
557
- // Observe-only: errors are isolated after persistence.
558
- });
559
-
560
- pi.on("session_compact_failed", async (event) => {
561
- // event.reason - "manual" | "threshold" | "overflow"
562
- // event.errorMessage - absent for cancellation
563
- // event.aborted / event.willRetry - terminal state
564
- // event.fromExtension - whether extension-provided text was active
565
- });
566
- ```
351
+ Moved to [Extension events](/extensions/events#after_provider_response).
567
352
 
568
- #### session_before_tree / session_tree
353
+ ### Model Events
569
354
 
570
- Fired on `/tree` navigation. See [Sessions](/sessions) for tree navigation concepts.
355
+ Moved to [Extension events](/extensions/events#model-events).
571
356
 
572
- ```typescript
573
- pi.on("session_before_tree", async (event, ctx) => {
574
- const { preparation, signal } = event;
575
- return { cancel: true };
576
- // OR provide custom summary:
577
- return { summary: { summary: "...", details: {} } };
578
- });
579
-
580
- pi.on("session_tree", async (event, ctx) => {
581
- // event.newLeafId, oldLeafId, summaryEntry, fromExtension
582
- });
583
- ```
357
+ #### model_select
584
358
 
585
- #### session_shutdown
359
+ Moved to [Extension events](/extensions/events#model_select).
586
360
 
587
- Fired before a started session runtime is torn down. Use this to clean up resources opened from `session_start` or other session-scoped hooks.
361
+ #### thinking_level_select
588
362
 
589
- ```typescript
590
- pi.on("session_shutdown", async (event, ctx) => {
591
- // event.reason - "quit" | "reload" | "new" | "resume" | "fork"
592
- // event.targetSessionFile - destination session for session replacement flows
593
- // Cleanup, save state, etc.
594
- });
595
- ```
363
+ Moved to [Extension events](/extensions/events#thinking_level_select).
596
364
 
597
- ### Agent Events
365
+ ### Tool Events
598
366
 
599
- #### before_agent_start
367
+ Moved to [Extension events](/extensions/events#tool-events).
600
368
 
601
- Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
369
+ #### tool_call
602
370
 
603
- ```typescript
604
- pi.on("before_agent_start", async (event, ctx) => {
605
- // event.prompt - user's prompt text
606
- // event.images - attached images (if any)
607
- // event.systemPrompt - current chained system prompt for this handler
608
- // (includes changes from earlier before_agent_start handlers)
609
- // event.systemPromptOptions - structured options used to build the system prompt
610
- // .customPrompt - any custom system prompt (from --system-prompt, SYSTEM.md, or custom templates)
611
- // .selectedTools - tools currently active in the prompt
612
- // .toolSnippets - one-line descriptions for each tool
613
- // .promptGuidelines - custom guideline bullets
614
- // .appendSystemPrompt - text from --append-system-prompt flags
615
- // .cwd - working directory
616
- // .contextFiles - AGENTS.md files and other loaded context files
617
- // .skills - loaded skills
618
-
619
- return {
620
- // Inject a persistent message (stored in session, sent to LLM)
621
- message: {
622
- customType: "my-extension",
623
- content: "Additional context for the LLM",
624
- display: true,
625
- },
626
- // Replace the system prompt for this turn (chained across extensions)
627
- systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
628
- };
629
- });
630
- ```
371
+ Moved to [Extension events](/extensions/events#tool_call).
631
372
 
632
- The `systemPromptOptions` field gives extensions access to the same structured data Atomic uses to build the system prompt. This lets you inspect what Atomic has loaded — custom prompts, guidelines, tool snippets, context files, skills — without re-discovering resources or re-parsing flags. Use it when your extension needs to make deep, informed changes to the system prompt while respecting user-provided configuration.
373
+ #### Typing custom tool input
633
374
 
634
- Inside `before_agent_start`, `event.systemPrompt` and `ctx.getSystemPrompt()` both reflect the chained system prompt as of the current handler. Later `before_agent_start` handlers can still modify it again.
375
+ Moved to [Extension events](/extensions/events#typing-custom-tool-input).
635
376
 
636
- #### agent_start / agent_end / agent_settled
377
+ #### tool_result
637
378
 
638
- `agent_start` begins a low-level run. `agent_end` fires when that run ends, but Atomic may still retry, compact and retry, or deliver queued follow-ups. Use `agent_settled` when a status integration needs to know Atomic has no automatic continuation left, including a chain of repeated output-cap continuations. Silence during a provider request or between these runs is not settlement.
379
+ Moved to [Extension events](/extensions/events#tool_result).
639
380
 
640
- ```typescript
641
- pi.on("agent_start", async (_event, ctx) => {});
642
- pi.on("agent_end", async (event, ctx) => {
643
- // event.messages - messages from this low-level run
644
- });
645
- pi.on("agent_settled", async (_event, ctx) => {
646
- // ctx.isIdle() is true unless another extension started a run.
647
- });
648
- ```
381
+ ### User Bash Events
649
382
 
650
- #### ui_prompt_start / ui_prompt_end
383
+ Moved to [Extension events](/extensions/events#user-bash-events).
651
384
 
652
- These notification-only events wrap blocking user-facing prompts. Each event has `reason: "ui_prompt" | "project_trust"`, the prompt `kind`, and the prompt `title` when available. Host and status integrations can use the pair to distinguish waiting for the user from active work.
385
+ #### user_bash
653
386
 
654
- - `ui_prompt`: extension prompts opened through `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`, `ctx.ui.editor()`, and `ctx.ui.custom()`.
655
- Custom inspection/navigation components can pass `{ purpose: "navigation" }` to omit their own prompt span. The default remains `"prompt"`. Nested approval calls still emit events; mounting or hiding the workflow graph is not itself an approval.
656
- - `project_trust`: interactive startup and resume trust dialogs (including trust-hook `select`, `confirm`, and `input` dialogs and borrowed extension-source authorization), plus the built-in `/trust` selector. In isolated interactive mode, the engine owns startup/resume decisions and uses the host UI; host-owned `/trust` notifications are forwarded to the engine. If the current engine has not bound yet, the transport retains the start and end in order until it binds, even if the selector closes first. Separate completed dialogs retain separate lifecycle pairs when delivered together. This does not delay the trust decision; retiring that engine discards its pending notifications.
387
+ Moved to [Extension events](/extensions/events#user_bash).
657
388
 
658
- Startup first loads only permitted user/global, builtin, and explicitly authorized CLI extensions, and binds them to a real session before asking for trust. Existing handlers receive the live `ExtensionContext` while the dialog is waiting: `ctx.cwd`, `ctx.sessionManager`, and other session APIs are available. Approval completes resources in that same session without rerunning safe extension factories or their `session_start` handlers. Newly authorized project extensions receive `session_start` only after loading; they do not receive historical prompt events. Untrusted project and borrowed project-local code is never loaded just to observe a prompt. Silent saved/default/CLI policy decisions and noninteractive startup emit no artificial waits.
389
+ ### Input Events
659
390
 
660
- Interactive resume trust dialogs use the outgoing session's live extension context. Destination validation and `session_before_switch` cancellation precede trust preparation; failed preparation leaves that session active. Project resources load only when the prepared replacement continues after shutdown. Attaching subscribers does not replay earlier notifications.
391
+ Moved to [Extension events](/extensions/events#input-events).
661
392
 
662
- Atomic coalesces nested or overlapping prompts, including mixed reasons, into one shared outer span. The end event retains the original outer prompt's reason, kind, and title and fires after every prompt in the span settles, including rejected promises and synchronous failures. Cancelling or disposing the `/trust` selector ends its wait. Rebinding the host UI context closes an active span before a prompt from the new context can begin. Notifications are not replayed to a replacement engine if the engine exits while a host selector is open.
393
+ #### input
663
394
 
664
- At session replacement, Atomic waits up to 1,000 ms for a snapshot of pending prompt notification deliveries before shutdown. Prompt display and answers never await observers. Start and end dispatch independently, invoking each observer in notification order without awaiting other observers; an earlier slow observer cannot make later subscribers receive an end before its start. An observer's own asynchronous start and end work can overlap, so update lifecycle state before awaiting unrelated work. If an observer hangs, Atomic warns and continues replacement; its context is not guaranteed to remain valid after that finite boundary.
395
+ Moved to [Extension events](/extensions/events#input).
665
396
 
666
- Handlers run best-effort from the microtask queue. Atomic does not await them before opening or closing the prompt, so notifications do not block the UI.
397
+ ## ExtensionContext
667
398
 
668
- ```typescript
669
- pi.on("ui_prompt_start", (event) => {
670
- // event.reason - "ui_prompt" | "project_trust"
671
- // event.kind - "select" | "confirm" | "input" | "editor" | "custom"
672
- // event.title - prompt title when available
673
- });
674
-
675
- pi.on("ui_prompt_end", (event) => {
676
- // Atomic is no longer waiting on this outer prompt span.
677
- });
678
- ```
399
+ Moved to [Extension API reference](/extensions/api-reference#extensioncontext).
679
400
 
680
- #### turn_start / turn_end
401
+ ### ctx.ui
681
402
 
682
- Fired for each turn (one LLM response + tool calls).
403
+ Moved to [Extension API reference](/extensions/api-reference#ctx-ui).
683
404
 
684
- ```typescript
685
- pi.on("turn_start", async (event, ctx) => {
686
- // event.turnIndex, event.timestamp
687
- });
405
+ ### ctx.hasUI
688
406
 
689
- pi.on("turn_end", async (event, ctx) => {
690
- // event.turnIndex, event.message, event.toolResults
691
- });
692
- ```
407
+ Moved to [Extension API reference](/extensions/api-reference#ctx-hasui).
693
408
 
694
- #### message_start / message_update / message_end
409
+ ### ctx.cwd
695
410
 
696
- Fired for message lifecycle updates.
411
+ Moved to [Extension API reference](/extensions/api-reference#ctx-cwd).
697
412
 
698
- - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
699
- - `message_update` fires for assistant streaming updates.
700
- - `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
413
+ ### ctx.isProjectTrusted()
701
414
 
702
- ```typescript
703
- pi.on("message_start", async (event, ctx) => {
704
- // event.message
705
- });
706
-
707
- pi.on("message_update", async (event, ctx) => {
708
- // event.assistantMessageEvent (token-by-token delta; no cumulative message)
709
- });
710
-
711
- pi.on("message_end", async (event, ctx) => {
712
- if (event.message.role !== "assistant") return;
713
-
714
- return {
715
- message: {
716
- ...event.message,
717
- usage: {
718
- ...event.message.usage,
719
- cost: {
720
- ...event.message.usage.cost,
721
- total: 0.123,
722
- },
723
- },
724
- },
725
- };
726
- });
727
- ```
415
+ Moved to [Extension API reference](/extensions/api-reference#ctx-isprojecttrusted).
728
416
 
729
- #### tool_execution_start / tool_execution_update / tool_execution_end
417
+ ### ctx.sessionManager
730
418
 
731
- Fired for tool execution lifecycle updates.
419
+ Moved to [Extension API reference](/extensions/api-reference#ctx-sessionmanager).
732
420
 
733
- In parallel tool mode:
734
- - `tool_execution_start` is emitted in assistant source order during the preflight phase
735
- - `tool_execution_update` events may interleave across tools
736
- - `tool_execution_end` is emitted in tool completion order after each tool is finalized
737
- - final `toolResult` message events are still emitted later in assistant source order
421
+ ### ctx.modelRegistry / ctx.model / ctx.scopedModels
738
422
 
739
- ```typescript
740
- pi.on("tool_execution_start", async (event, ctx) => {
741
- // event.toolCallId, event.toolName, event.args
742
- });
423
+ Moved to [Extension API reference](/extensions/api-reference#ctx-modelregistry-/-ctx-model-/-ctx-scopedmodels).
743
424
 
744
- pi.on("tool_execution_update", async (event, ctx) => {
745
- // event.toolCallId, event.toolName, event.args, event.partialResult
746
- });
425
+ ### ctx.signal
747
426
 
748
- pi.on("tool_execution_end", async (event, ctx) => {
749
- // event.toolCallId, event.toolName, event.result, event.isError
750
- });
751
- ```
427
+ Moved to [Extension API reference](/extensions/api-reference#ctx-signal).
752
428
 
753
- #### context
429
+ ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
754
430
 
755
- Fired before each LLM call. Modify messages non-destructively. See [Session Format](/session-format) for message types. When tool output crosses the buffered compaction threshold, the post-tool compaction preflight finishes before this hook runs for the follow-up call, so `event.messages` contains the rebuilt compacted context.
431
+ Moved to [Extension API reference](/extensions/api-reference#ctx-isidle-/-ctx-abort-/-ctx-haspendingmessages).
756
432
 
757
- ```typescript
758
- pi.on("context", async (event, ctx) => {
759
- // event.messages - deep copy, safe to modify
760
- const filtered = event.messages.filter(m => !shouldPrune(m));
761
- return { messages: filtered };
762
- });
763
- ```
433
+ ### ctx.isProjectTrusted()
764
434
 
765
- #### before_provider_headers
435
+ Moved to [Extension API reference](/extensions/api-reference#ctx-isprojecttrusted-2).
766
436
 
767
- Fires after outgoing HTTP headers are assembled. Mutate `event.headers` to add, override, or remove headers. The event also identifies the provider and model.
437
+ ### ctx.shutdown()
768
438
 
769
- ```typescript
770
- pi.on("before_provider_headers", (event, ctx) => {
771
- event.headers["x-session-id"] = ctx.sessionManager.getSessionId();
772
- delete event.headers["x-remove-me"];
773
- });
774
- ```
439
+ Moved to [Extension API reference](/extensions/api-reference#ctx-shutdown).
775
440
 
776
- #### before_provider_request
441
+ ### ctx.getContextUsage()
777
442
 
778
- Fired after the provider-specific payload is built, right before the request is sent. Handlers run in extension load order. Returning `undefined` keeps the payload unchanged. Returning any other value replaces the payload for later handlers and for the actual request.
443
+ Moved to [Extension API reference](/extensions/api-reference#ctx-getcontextusage).
779
444
 
780
- This hook can rewrite provider-level system instructions or remove them entirely. Those payload-level changes are not reflected by `ctx.getSystemPrompt()`, which reports Atomic's system prompt string rather than the final serialized provider payload.
445
+ ### ctx.compact()
781
446
 
782
- ```typescript
783
- pi.on("before_provider_request", (event, ctx) => {
784
- console.log(JSON.stringify(event.payload, null, 2));
447
+ Moved to [Extension API reference](/extensions/api-reference#ctx-compact).
785
448
 
786
- // Optional: replace payload
787
- // return { ...event.payload, temperature: 0 };
788
- });
789
- ```
449
+ ### ctx.getSystemPrompt()
790
450
 
791
- This is mainly useful for debugging provider serialization and cache behavior.
451
+ Moved to [Extension API reference](/extensions/api-reference#ctx-getsystemprompt).
792
452
 
793
- #### after_provider_response
453
+ ### ctx.getSkillCatalog()
794
454
 
795
- Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
455
+ Moved to [Extension API reference](/extensions/api-reference#ctx-getskillcatalog).
796
456
 
797
- ```typescript
798
- pi.on("after_provider_response", (event, ctx) => {
799
- // event.status - HTTP status code
800
- // event.headers - normalized response headers
801
- if (event.status === 429) {
802
- console.log("rate limited", event.headers["retry-after"]);
803
- }
804
- });
805
- ```
457
+ ## ExtensionCommandContext
806
458
 
807
- Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
459
+ Moved to [Extension API reference](/extensions/api-reference#extensioncommandcontext).
808
460
 
809
- ### Model Events
461
+ ### ctx.waitForIdle()
810
462
 
811
- #### model_select
463
+ Moved to [Extension API reference](/extensions/api-reference#ctx-waitforidle).
812
464
 
813
- Fired when the model changes via `/model` command, model cycling (`CTRL+P`), or session restore.
465
+ ### ctx.newSession(options?)
814
466
 
815
- ```typescript
816
- pi.on("model_select", async (event, ctx) => {
817
- // event.model - newly selected model
818
- // event.previousModel - previous model (undefined if first selection)
819
- // event.source - "set" | "cycle" | "restore"
820
-
821
- const prev = event.previousModel
822
- ? `${event.previousModel.provider}/${event.previousModel.id}`
823
- : "none";
824
- const next = `${event.model.provider}/${event.model.id}`;
825
-
826
- ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
827
- });
828
- ```
467
+ Moved to [Extension API reference](/extensions/api-reference#ctx-newsession-options).
829
468
 
830
- Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
469
+ ### ctx.fork(entryId, options?)
831
470
 
832
- #### thinking_level_select
471
+ Moved to [Extension API reference](/extensions/api-reference#ctx-fork-entryid-options).
833
472
 
834
- Fired when the thinking level changes. This is notification-only; handler return values are ignored.
473
+ ### ctx.navigateTree(targetId, options?)
835
474
 
836
- ```typescript
837
- pi.on("thinking_level_select", async (event, ctx) => {
838
- // event.level - newly selected thinking level
839
- // event.previousLevel - previous thinking level
475
+ Moved to [Extension API reference](/extensions/api-reference#ctx-navigatetree-targetid-options).
840
476
 
841
- ctx.ui.setStatus("thinking", `thinking: ${event.level}`);
842
- });
843
- ```
477
+ ### ctx.switchSession(sessionPath, options?)
844
478
 
845
- Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
479
+ Moved to [Extension API reference](/extensions/api-reference#ctx-switchsession-sessionpath-options).
846
480
 
847
- ### Tool Events
481
+ ### Session replacement lifecycle and footguns
848
482
 
849
- #### tool_call
483
+ Moved to [Extension API reference](/extensions/api-reference#session-replacement-lifecycle-and-footguns).
850
484
 
851
- Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
485
+ ### ctx.reload()
852
486
 
853
- Before `tool_call` runs, Atomic waits for previously emitted Agent events to finish draining through `AgentSession`. This means `ctx.sessionManager` is up to date through the current assistant tool-calling message.
487
+ Moved to [Extension API reference](/extensions/api-reference#ctx-reload).
854
488
 
855
- In the default parallel tool execution mode, sibling tool calls from the same assistant message are preflighted sequentially, then executed concurrently. `tool_call` is not guaranteed to see sibling tool results from that same assistant message in `ctx.sessionManager`.
489
+ ## ExtensionAPI Methods
856
490
 
857
- `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
491
+ Moved to [Extension API reference](/extensions/api-reference#extensionapi-methods).
858
492
 
859
- Behavior guarantees:
860
- - Mutations to `event.input` affect the actual tool execution
861
- - Later `tool_call` handlers see mutations made by earlier handlers
862
- - No re-validation is performed after your mutation
863
- - Return values from `tool_call` control blocking via `{ block: true, reason?: string, terminate?: boolean }`
864
- - `terminate` only applies to a blocked call; the agent stops early only when every finalized result in the batch is terminating
865
- - `terminate` applies only to a blocked call; the agent stops early only when every finalized result in the batch is terminating
493
+ ### pi.on(event, handler)
866
494
 
867
- ```typescript
868
- import { isToolCallEventType } from "@bastani/atomic";
495
+ Moved to [Extension API reference](/extensions/api-reference#pi-on-event-handler).
869
496
 
870
- pi.on("tool_call", async (event, ctx) => {
871
- // event.toolName - "bash", "powershell", "read", "write", "edit", "find", "search", etc.
872
- // event.toolCallId
873
- // event.input - tool parameters (mutable)
497
+ ### pi.registerTool(definition)
874
498
 
875
- // Built-in tools: no type params needed
876
- if (isToolCallEventType("bash", event)) {
877
- // event.input is { command: string; timeout?: number }
878
- event.input.command = `source ~/.profile\n${event.input.command}`;
499
+ Moved to [Extension API reference](/extensions/api-reference#pi-registertool-definition).
879
500
 
880
- if (event.input.command.includes("rm -rf")) {
881
- return { block: true, reason: "Dangerous command", terminate: true };
882
- }
883
- }
884
-
885
- if (isToolCallEventType("powershell", event)) {
886
- // event.input is typed as PowerShellToolInput
887
- event.input.command = `$ErrorActionPreference = "Stop"\n${event.input.command}`;
888
- }
889
-
890
- if (isToolCallEventType("read", event)) {
891
- // event.input is { path: string }
892
- console.log(`Reading: ${event.input.path}`);
893
- }
894
-
895
- if (isToolCallEventType("search", event)) {
896
- // event.input is typed as SearchToolInput
897
- event.input.paths ??= ".";
898
- }
899
- });
900
- ```
501
+ #### Built-in tool prompt contributions
901
502
 
902
- #### Typing custom tool input
503
+ Moved to [Extension API reference](/extensions/api-reference#built-in-tool-prompt-contributions).
903
504
 
904
- Custom tools should export their input type:
505
+ ### pi.sendMessage(message, options?)
905
506
 
906
- ```typescript
907
- // my-extension.ts
908
- export type MyToolInput = Static<typeof myToolSchema>;
909
- ```
507
+ Moved to [Extension API reference](/extensions/api-reference#pi-sendmessage-message-options).
910
508
 
911
- Use `isToolCallEventType` with explicit type parameters:
509
+ ### pi.sendMessages(messages, options?)
912
510
 
913
- ```typescript
914
- import { isToolCallEventType } from "@bastani/atomic";
915
- import type { MyToolInput } from "my-extension";
916
-
917
- pi.on("tool_call", (event) => {
918
- if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
919
- event.input.action; // typed
920
- }
921
- });
922
- ```
511
+ Moved to [Extension API reference](/extensions/api-reference#pi-sendmessages-messages-options).
923
512
 
924
- #### tool_result
513
+ ### pi.sendUserMessage(content, options?)
925
514
 
926
- Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
515
+ Moved to [Extension API reference](/extensions/api-reference#pi-sendusermessage-content-options).
927
516
 
928
- In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in tool completion order, while final `toolResult` message events are still emitted later in assistant source order.
517
+ ### pi.appendEntry(customType, data?)
929
518
 
930
- `tool_result` handlers chain like middleware:
931
- - Handlers run in extension load order
932
- - Each handler sees the latest result after previous handler changes
933
- - Handlers can return partial patches (`content`, `details`, or `isError`); omitted fields keep their current values
519
+ Moved to [Extension API reference](/extensions/api-reference#pi-appendentry-customtype-data).
934
520
 
935
- After all handlers finish, Atomic normalizes image blocks returned by the tool or inserted by a handler according to `images.autoResize` before saving the result to history. If image processing fails, the original image remains in the result.
521
+ ### pi.registerEntryRenderer(customType, renderer)
936
522
 
937
- Use `ctx.signal` for nested async work inside the handler. This lets Escape cancel model calls, `fetch()`, and other abort-aware operations started by the extension.
523
+ Moved to [Extension API reference](/extensions/api-reference#pi-registerentryrenderer-customtype-renderer).
938
524
 
939
- ```typescript
940
- import { isBashToolResult, isPowerShellToolResult, isSearchToolResult } from "@bastani/atomic";
525
+ ### pi.setSessionName(name)
941
526
 
942
- pi.on("tool_result", async (event, ctx) => {
943
- // event.toolName, event.toolCallId, event.input
944
- // event.content, event.details, event.isError
527
+ Moved to [Extension API reference](/extensions/api-reference#pi-setsessionname-name).
945
528
 
946
- if (isBashToolResult(event)) {
947
- // event.details is typed as BashToolDetails
948
- }
529
+ ### pi.getSessionName()
949
530
 
950
- if (isPowerShellToolResult(event)) {
951
- // event.details is typed as PowerShellToolDetails | undefined
952
- }
531
+ Moved to [Extension API reference](/extensions/api-reference#pi-getsessionname).
953
532
 
954
- if (isSearchToolResult(event)) {
955
- // event.details is typed as SearchToolDetails | undefined
956
- }
533
+ ### pi.setLabel(entryId, label)
957
534
 
958
- const response = await fetch("https://example.com/summarize", {
959
- method: "POST",
960
- body: JSON.stringify({ content: event.content }),
961
- signal: ctx.signal,
962
- });
535
+ Moved to [Extension API reference](/extensions/api-reference#pi-setlabel-entryid-label).
963
536
 
964
- // Modify result:
965
- return { content: [...], details: {...}, isError: false };
966
- });
967
- ```
537
+ ### pi.registerCommand(name, options)
968
538
 
969
- ### User Bash Events
539
+ Moved to [Extension API reference](/extensions/api-reference#pi-registercommand-name-options).
970
540
 
971
- #### user_bash
541
+ ### pi.getCommands()
972
542
 
973
- Fired when user executes `!` or `!!` commands. **Can intercept.**
543
+ Moved to [Extension API reference](/extensions/api-reference#pi-getcommands).
974
544
 
975
- ```typescript
976
- import { createLocalBashOperations } from "@bastani/atomic";
977
-
978
- pi.on("user_bash", (event, ctx) => {
979
- // event.command - the bash command
980
- // event.excludeFromContext - true if !! prefix
981
- // event.cwd - working directory
982
-
983
- // Option 1: Provide custom operations (e.g., SSH)
984
- return { operations: remoteBashOps };
985
-
986
- // Option 2: Wrap atomic's built-in local bash backend
987
- const local = createLocalBashOperations();
988
- return {
989
- operations: {
990
- exec(command, cwd, options) {
991
- return local.exec(`source ~/.profile\n${command}`, cwd, options);
992
- }
993
- }
994
- };
545
+ ### pi.registerMessageRenderer(customType, renderer)
995
546
 
996
- // Option 3: Full replacement - return result directly
997
- return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
998
- });
999
- ```
547
+ Moved to [Extension API reference](/extensions/api-reference#pi-registermessagerenderer-customtype-renderer).
1000
548
 
1001
- ### Input Events
549
+ ### pi.registerMarkdownTransformer(transformer)
1002
550
 
1003
- #### input
551
+ Moved to [Extension API reference](/extensions/api-reference#pi-registermarkdowntransformer-transformer).
1004
552
 
1005
- Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded.
553
+ ### pi.registerShortcut(shortcut, options)
1006
554
 
1007
- Direct `session.steer()` and `session.followUp()` calls also run input handlers before skill/template expansion and queue admission. A handled input is not queued; transformed text and images are queued instead. Their optional third argument sets `source`, defaulting to `interactive`; RPC queue commands use `rpc`.
555
+ Moved to [Extension API reference](/extensions/api-reference#pi-registershortcut-shortcut-options).
1008
556
 
1009
- **Processing order:**
1010
- 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
1011
- 2. `input` event fires - can intercept, transform, or handle
1012
- 3. If not handled: skill commands (`/skill:name`) expanded to skill content
1013
- 4. If not handled: prompt templates (`/template`) expanded to template content
1014
- 5. Agent processing begins (`before_agent_start`, etc.)
557
+ ### pi.registerFlag(name, options)
1015
558
 
1016
- ```typescript
1017
- pi.on("input", async (event, ctx) => {
1018
- // event.text - raw input (before skill/template expansion)
1019
- // event.images - attached images, if any
1020
- // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
1021
-
1022
- // Transform: rewrite input before expansion
1023
- if (event.text.startsWith("?quick "))
1024
- return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
1025
-
1026
- // Handle: respond without LLM (extension shows its own feedback)
1027
- if (event.text === "ping") {
1028
- ctx.ui.notify("pong", "info");
1029
- return { action: "handled" };
1030
- }
1031
-
1032
- // Route by source: skip processing for extension-injected messages
1033
- if (event.source === "extension") return { action: "continue" };
1034
-
1035
- // Intercept skill commands before expansion
1036
- if (event.text.startsWith("/skill:")) {
1037
- // Could transform, block, or let pass through
1038
- }
1039
-
1040
- return { action: "continue" }; // Default: pass through to expansion
1041
- });
1042
- ```
559
+ Moved to [Extension API reference](/extensions/api-reference#pi-registerflag-name-options).
1043
560
 
1044
- **Results:**
1045
- - `continue` - pass through unchanged (default if handler returns nothing)
1046
- - `transform` - modify text/images, then continue to expansion
1047
- - `handled` - skip agent entirely (first handler to return this wins)
561
+ ### pi.exec(command, args, options?)
1048
562
 
1049
- Transforms chain across handlers. See [input-transform.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/input-transform.ts) and [input-transform-streaming.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/input-transform-streaming.ts) for `streamingBehavior`-aware routing.
563
+ Moved to [Extension API reference](/extensions/api-reference#pi-exec-command-args-options).
1050
564
 
1051
- ## Workflow activity and lifecycle hooks
565
+ ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1052
566
 
1053
- The host exposes typed workflow observation contracts. A workflow provider must register and publish activity; these APIs alone do not connect the workflow scheduler. Without a publisher snapshot, availability is `unavailable`, not an empty ready state.
567
+ Moved to [Extension API reference](/extensions/api-reference#pi-getactivetools-/-pi-getalltools-/-pi-setactivetools-names).
1054
568
 
1055
- The workflows package also contains a pure root-activity projector. It combines a store snapshot with runtime ownership of executing stages and tools, retries, stopping runs, and acknowledged failures. Nested runs fold into one root summary; historical `running` status alone never counts as execution. Runnable stage handoffs remain `working`, while a stage parked on its own prompt contributes attention rather than execution. Independent work keeps the root `working` with `needsAttention: true`. With no work progressing, human waits and unresolved failures are `blocked`; paused runs are `idle` with reason `paused`, and completed or intentionally stopped runs are `idle` with reason `quiescent`.
569
+ ### pi.setModel(model)
1056
570
 
1057
- Live executor ownership also keeps a running root `working` with reason `automatic_continuation` after its nodes settle and before author code admits the next node. This requires all stages to be completed or skipped and all tools completed, with no prompt, active block, or stop. It does not add to the execution count. Historical snapshots without live ownership, paused runs, and parked nodes do not qualify.
571
+ Moved to [Extension API reference](/extensions/api-reference#pi-setmodel-model).
1058
572
 
1059
- Stopping a child suppresses handoffs only in that child's subtree, not in its parent or sibling runs. With no other active waits, a paused stage keeps the root `idle` with reason `paused` after independent execution finishes, even when the stored run status remains `running`. Its retained prompt does not request attention until the stage resumes; independent active waits still do. The projector does not change stored run or stage outcomes.
573
+ ### pi.getThinkingLevel() / pi.setThinkingLevel(level)
1060
574
 
1061
- Stopping ownership follows each run's `parentRunId` chain and then its root identity, even when a named ancestor's snapshot is absent. The root reports `working` with reason `stopping` only when all executing contributions are draining under a stop and no unaffected retry or handoff can progress. Independent work retains the usual `retrying`, `executing`, or `automatic_continuation` reason; a stopped run with no execution left does not select the reason. Removing history does not release runtime execution or stop ownership.
575
+ Moved to [Extension API reference](/extensions/api-reference#pi-getthinkinglevel-/-pi-setthinkinglevel-level).
1062
576
 
1063
- The projection module's `workflowActivityNodeKey(runId, nodeId)` helper builds `${runId}:${nodeId}` keys for `executingStageIds`, `executingToolNodeIds`, and `retryingStageIds`. The first colon separates the runtime UUID run ID from the node ID, which may contain colons. Bare node IDs do not establish ownership: two runs can contain the same tool hash. `stoppingRunIds` and `acknowledgedFailureRunIds` use plain run IDs.
577
+ ### pi.events
1064
578
 
1065
- The projector and its ownership-key helper are internal to the workflows package, not exports of the supported `@bastani/atomic/workflows` SDK. Extension consumers use `ctx.observeWorkflowActivity` rather than importing the projector.
579
+ Moved to [Extension API reference](/extensions/api-reference#pi-events).
1066
580
 
1067
- The workflows extension registers a publisher on activation and publishes this activity stream for its owning session: root snapshots and changes, plus `workflow_lifecycle`, `workflow_stage_completed`, and `workflow_heartbeat` hooks (the runtime state table is in [`workflows/operations.md`](/workflows/operations#workflow-activity-for-extensions)). It does not change chat notifications. The built-in [Herdr reporter](/herdr) consumes this stream to reflect workflow execution and human-input waits in the owning pane.
581
+ ### Native providers
1068
582
 
583
+ Moved to [Extension API reference](/extensions/api-reference#native-providers).
1069
584
 
1070
- | Hook | Payload and semantics |
1071
- | --- | --- |
1072
- | `workflow_lifecycle` | `WorkflowLifecycleEvent`: run, stage, tool, or prompt target with typed status, optional previous status, event identity, cursor, ownership, timestamps, and `live` or `replay` delivery. Run targets may carry a control `action`, distinct from its eventual outcome. |
1073
- | `workflow_activity_changed` | `WorkflowActivityChangedEvent`: full root replacement and the same cursor as the observer's `changed` frame. No initial snapshot guarantee. |
1074
- | `workflow_stage_completed` | `WorkflowStageCompletedEvent`: the lifecycle envelope with a stage target whose status is `completed`. Shares the lifecycle event ID and cursor. Failed, skipped, cancelled, and killed outcomes do not produce this hook. |
1075
- | `workflow_heartbeat` | `WorkflowHeartbeatEvent`: run/root/owner identity, `scheduledAt`, and `intervalMinutes`. Observation only, with no scheduler or cadence change. |
585
+ ### pi.registerProvider(name, config)
1076
586
 
1077
- Run control actions describe the caller's request: an already-aborted caller signal still emits `kill` after run registration, and a whole-run pause at a task-result checkpoint emits `pause` while graceful suspension retains the paused outcome and `exitReason: "quit"`. A control event alone does not mean execution has drained.
587
+ Moved to [Extension API reference](/extensions/api-reference#pi-registerprovider-name-config).
1078
588
 
1079
- Use `ctx.observeWorkflowActivity` for status consumers. Registration captures a snapshot atomically with attaching the observer. Delivery is asynchronous, snapshot first, then FIFO updates. Each callback finishes before the next callback for that observer starts; a slow observer does not delay the publisher or other observers.
589
+ ### pi.unregisterProvider(name)
1080
590
 
1081
- ```typescript
1082
- import type { ExtensionAPI, WorkflowActivitySubscription, WorkflowRootActivity } from "@bastani/atomic";
591
+ Moved to [Extension API reference](/extensions/api-reference#pi-unregisterprovider-name).
1083
592
 
1084
- export default function (pi: ExtensionAPI) {
1085
- let lease: WorkflowActivitySubscription | undefined;
1086
- const roots = new Map<string, WorkflowRootActivity>();
1087
-
1088
- pi.on("session_start", (_event, ctx) => {
1089
- lease?.dispose();
1090
- lease = ctx.observeWorkflowActivity((frame) => {
1091
- if (frame.kind === "snapshot") {
1092
- roots.clear();
1093
- if (frame.availability !== "ready") {
1094
- // Unknown activity must not be interpreted as idle.
1095
- return;
1096
- }
1097
- for (const root of frame.roots) roots.set(root.rootRunId, root);
1098
- } else if (frame.kind === "changed") {
1099
- roots.set(frame.root.rootRunId, frame.root);
1100
- } else {
1101
- roots.delete(frame.rootRunId);
1102
- }
1103
- });
1104
- });
1105
- pi.on("session_shutdown", () => lease?.dispose());
1106
- pi.on("workflow_stage_completed", (event) => {
1107
- // Canonical nested identity, not the display name.
1108
- console.log(event.eventId, event.target.stageId, event.delivery);
1109
- });
1110
- }
1111
- ```
593
+ ## State Management
1112
594
 
1113
- Frames are ordinary objects with a `{ epoch: string, revision: number }` cursor. Revisions increase within an epoch; lifecycle publication may leave gaps between activity revisions. A new publisher starts a new epoch and an `unavailable` snapshot. Never compare revision numbers across epochs. A `ready` snapshot has a `roots` array, including an empty array when known empty. `recovering` and `unavailable` snapshots omit `roots`. Subsequent snapshots replace all prior knowledge. Changes replace a complete root, not increment counters. Removals contain `rootRunId`. Root summaries include `state`, `reason`, execution/wait counts, and `needsAttention`.
595
+ Moved to [Writing extensions](/extensions/authoring#state-management).
1114
596
 
1115
- Providers call `pi.registerWorkflowActivityPublisher()` and retain its returned `WorkflowActivityPublisher`. Its methods are `publishSnapshot({ availability: "ready", roots })`, `publishSnapshot({ availability: "recovering" | "unavailable" })`, `publishChanged(root)`, `publishRemoved(rootRunId)`, `publishLifecycle(event)`, `publishHeartbeat(event)`, and `dispose()`. Lifecycle input includes `type: "workflow_lifecycle"` and the envelope except `cursor`, which the host supplies. Heartbeat input includes `type: "workflow_heartbeat"`. IDs, names, timestamps, zero counts and optional attribution are preserved. Roots are keyed by `rootRunId`; duplicate snapshot IDs use the last value at the first insertion position. Removing an absent ID is permitted. Changes do not turn an unknown source into `ready`; publish a snapshot to establish readiness.
597
+ ### Session-scoped in-memory state
1116
598
 
1117
- Workflow hooks published during extension factory initialization are retained until the runner binds dispatch, then delivered asynchronously in publication order before later live publications. Buffered events keep their original payloads and cursors; publisher retirement and runner disposal fence them just like live events.
599
+ Moved to [Writing extensions](/extensions/authoring#session-scoped-in-memory-state).
1118
600
 
1119
- Observation leases and publisher disposal are idempotent. Runner retirement on reload disposes every observer and fences publishers. Already-running callbacks cannot be cancelled, but no queued observer callbacks run after disposal. Runner retirement, publisher disposal, and publisher replacement also fence every workflow hook handler that has not started, including later handlers in the same or another extension when a previous handler is awaiting. Already-published activity frames remain ordered before the new source snapshot. Activity recovery never synthesizes lifecycle completions; explicit lifecycle replay retains the supplied event ID and `delivery: "replay"`.
601
+ ## Custom Tools
1120
602
 
1121
- The host hub retains at most 256 diagnostics, available through its host-side `diagnostics()` inspection API. These are diagnostic records, not thrown observation errors:
603
+ Moved to [Writing extensions](/extensions/authoring#custom-tools).
1122
604
 
1123
- - `ObserverDisposed`: an observation lease was retired.
1124
- - `SourceRecovering`: the provider is hydrating state.
1125
- - `SourceUnavailable`: no current source snapshot is known.
1126
- - `ObserverDeliveryFailed`: a callback threw or rejected; other observers and publication continue.
1127
- - `ObserverOverflow`: a per-observer queue reached its 256-frame limit. Pending frames are cleared and a fresh snapshot replaces them, invalidating continuity instead of silently losing updates.
1128
- - `PublisherFenced`: a disposed or superseded publisher attempted publication.
605
+ ### Tool Definition
1129
606
 
1130
- ## ExtensionContext
607
+ Moved to [Writing extensions](/extensions/authoring#tool-definition).
1131
608
 
1132
- All handlers receive `ctx: ExtensionContext`.
609
+ #### Constrained sampling
1133
610
 
1134
- ### ctx.ui
611
+ Moved to [Writing extensions](/extensions/authoring#constrained-sampling).
1135
612
 
1136
- UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
613
+ ### Fireworks deferred tool loading
1137
614
 
1138
- ### ctx.hasUI
615
+ Moved to [Writing extensions](/extensions/authoring#fireworks-deferred-tool-loading).
1139
616
 
1140
- `false` in print mode (`-p`) and JSON mode. `true` in interactive and RPC mode. In RPC mode, dialog methods (`select`, `confirm`, `input`, `editor`) work via the extension UI sub-protocol, and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) emit requests to the client. Some TUI-specific methods are no-ops or return defaults (see [RPC mode](/rpc#extension-ui-protocol)).
617
+ ### Overriding Built-in Tools
1141
618
 
1142
- ### ctx.cwd
619
+ Moved to [Writing extensions](/extensions/authoring#overriding-built-in-tools).
1143
620
 
1144
- Current working directory.
621
+ ### Remote Execution
1145
622
 
1146
- Built-in cwd-sensitive tools (`read`, `write`, `edit`, `search`, `find`, `ls`, `bash`, `powershell`) resolve relative paths against `ctx.cwd` when an extension invokes them, falling back to the cwd captured when the tool was created. An extension that registers a tool and forwards its own context therefore gets paths resolved against the live session cwd rather than a stale one.
623
+ Moved to [Writing extensions](/extensions/authoring#remote-execution).
1147
624
 
1148
- Use `CONFIG_DIR_NAME` instead of hardcoding `.atomic` (or legacy `.pi`) when constructing project-local config paths. Rebranded distributions can use a different config directory name.
625
+ ### Output Truncation
1149
626
 
1150
- ```typescript
1151
- import { CONFIG_DIR_NAME, type ExtensionAPI } from "@bastani/atomic";
1152
- import { join } from "node:path";
627
+ Moved to [Writing extensions](/extensions/authoring#output-truncation).
1153
628
 
1154
- export default function (pi: ExtensionAPI) {
1155
- pi.on("session_start", (_event, ctx) => {
1156
- const projectConfigPath = join(ctx.cwd, CONFIG_DIR_NAME, "my-extension.json");
1157
- // ...
1158
- });
1159
- }
1160
- ```
629
+ ### Multiple Tools
1161
630
 
1162
- ### ctx.isProjectTrusted()
631
+ Moved to [Writing extensions](/extensions/authoring#multiple-tools).
1163
632
 
1164
- Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not just saved decisions in the global trust store.
633
+ ### Custom Rendering
1165
634
 
1166
- Use this before reading project-local extension configuration that should only be honored for trusted projects.
635
+ Moved to [Writing extensions](/extensions/authoring#custom-rendering).
1167
636
 
637
+ #### renderCall
1168
638
 
1169
- ### ctx.sessionManager
639
+ Moved to [Writing extensions](/extensions/authoring#rendercall).
1170
640
 
1171
- Read-only access to session state. See [Session Format](/session-format) for the full SessionManager API and entry types.
641
+ #### renderResult
1172
642
 
1173
- For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message.
643
+ Moved to [Writing extensions](/extensions/authoring#renderresult).
1174
644
 
1175
- ```typescript
1176
- ctx.sessionManager.getEntries() // All entries
1177
- ctx.sessionManager.getBranch() // Current branch
1178
- ctx.sessionManager.getLeafId() // Current leaf entry ID
1179
- ```
645
+ #### Keybinding Hints
1180
646
 
1181
- ### ctx.modelRegistry / ctx.model / ctx.scopedModels
647
+ Moved to [Writing extensions](/extensions/authoring#keybinding-hints).
1182
648
 
1183
- Access models, auth state, and provider-aware requests.
649
+ #### Best Practices
1184
650
 
1185
- Use `ctx.modelRegistry.complete()` for an extension model request that must use Atomic's provider composition. It dispatches through the active `ModelRuntime`, retaining registered custom providers and resolved request auth: the credential-specific `baseUrl`, headers (including `null` suppression markers), and environment values.
651
+ Moved to [Writing extensions](/extensions/authoring#best-practices).
1186
652
 
1187
- For streaming requests, use `ctx.modelRegistry.streamSimple(model, context, options)` with provider-neutral options, or `stream()` with API-specific options. Both use configured providers and request-time authentication, including extension registrations. Iterate the returned `AssistantMessageEventStream` for events and await `.result()` for the final message. Setup failures produce error events and error results. The global compatibility streaming functions do not see extension provider registrations.
653
+ #### Fallback
1188
654
 
1189
- ```typescript
1190
- const model = ctx.modelRegistry.find("github-copilot", "gpt-5.5");
1191
- if (!model) throw new Error("Model not found");
655
+ Moved to [Writing extensions](/extensions/authoring#fallback).
1192
656
 
1193
- const response = await ctx.modelRegistry.complete(
1194
- model,
1195
- { messages },
1196
- { signal: ctx.signal },
1197
- );
1198
- ```
657
+ ## Custom UI
1199
658
 
1200
- Use `getApiKeyAndHeaders()` only when an extension must inspect auth before dispatch; normal requests do not need to resolve or overlay auth themselves.
659
+ Moved to [Extension UI](/extensions/ui#custom-ui).
1201
660
 
1202
- OpenRouter Chat Completions and Anthropic Messages requests send `x-session-id` by default when `sessionId` is supplied and prompt caching is enabled. Set the model's `compat.sendSessionAffinityHeaders` to `false` to opt out, or set `cacheRetention: "none"` on the request to disable cache-related affinity. Explicit request headers override generated headers.
661
+ ### Dialogs
1203
662
 
1204
- `await ctx.modelRegistry.refresh(options)` returns `{ aborted, errors }`, not just completion. `errors` is a per-provider map, so extensions can report partial refresh failures; `aborted` reports cancellation. Host integrations that call `ModelRuntime.setRuntimeApiKey(providerId, apiKey, options)` must note that it records the runtime credential but does not refresh the catalog; call `refresh({ providers: [providerId], signal })` explicitly when a fresh catalog is needed.
663
+ Moved to [Extension UI](/extensions/ui#dialogs).
1205
664
 
1206
- `ctx.scopedModels` is the read-only list of models scoped to the current session — the same set the `/scoped-models` command shows. It is resolved from the `--models` CLI flag and the `enabledModels` setting, matched against the available catalogue. It is empty when no scoping is configured, meaning every available model is usable. Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (for example `anthropic/*:high`). Use it to populate a model picker that mirrors the built-in one instead of enumerating the whole catalogue.
665
+ #### Timed Dialogs with Countdown
1207
666
 
1208
- The value is resolved at access time, so it tracks session replacement. Under the isolated interactive engine it reflects the engine's catalogue rather than a stale host snapshot.
1209
-
1210
- It reports the scope and cannot change it. `ctx.scopedModels` is a getter with no setter, typed `readonly ScopedModel[]`, so assigning to it or pushing an entry is a compile error. The guarantee also holds at runtime, where the type does not reach: each read returns a fresh copy — of the array, of every `{ model, thinkingLevel }` entry in it, and of each entry's model — and all three are frozen. A JavaScript extension, or one that asserts the `readonly` away, therefore cannot widen the set of models the session may use by pushing an entry, nor change which model it selects by swapping one in place; the attempt throws rather than quietly working. Read it, and change scope through the commands and settings that own it.
1211
-
1212
- ```typescript
1213
- for (const { model, thinkingLevel } of ctx.scopedModels) {
1214
- console.log(`${model.provider}/${model.id}${thinkingLevel ? `:${thinkingLevel}` : ""}`);
1215
- }
1216
- ```
1217
-
1218
- Both types are exported: `ScopedModel` for one entry, `ExtensionScopedModels` for the accessor's own type. They are declared at the public extension type path (`core/extensions/types.ts`) and re-exported from the package root, so an extension never reaches into an internal module to describe what it just read.
1219
-
1220
- ```typescript
1221
- import type { ExtensionScopedModels, ScopedModel } from "@bastani/atomic";
1222
-
1223
- function firstScoped(scope: ExtensionScopedModels): ScopedModel | undefined {
1224
- return scope[0];
1225
- }
1226
- ```
1227
-
1228
- ### ctx.signal
1229
-
1230
- The current agent abort signal, or `undefined` when no agent turn is active.
1231
-
1232
- Use this for abort-aware nested work started by extension handlers, for example:
1233
- - `fetch(..., { signal: ctx.signal })`
1234
- - model calls that accept `signal`
1235
- - file or process helpers that accept `AbortSignal`
1236
-
1237
- `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
1238
- It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while Atomic is idle.
1239
-
1240
- ```typescript
1241
- pi.on("tool_result", async (event, ctx) => {
1242
- const response = await fetch("https://example.com/api", {
1243
- method: "POST",
1244
- body: JSON.stringify(event),
1245
- signal: ctx.signal,
1246
- });
1247
-
1248
- const data = await response.json();
1249
- return { details: data };
1250
- });
1251
- ```
1252
-
1253
- ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
1254
-
1255
- Control flow helpers.
1256
-
1257
- ### ctx.isProjectTrusted()
1258
-
1259
- Returns whether project-local trust is active for the current extension context. Use this before reading project-local config, loading project-local resources, or exposing actions that should only run after the user has trusted the cwd.
1260
-
1261
- ```typescript
1262
- pi.registerCommand("project-status", {
1263
- description: "Show trust state",
1264
- handler: async (_args, ctx) => {
1265
- ctx.ui.notify(ctx.isProjectTrusted() ? "Project is trusted" : "Project is not trusted", "info");
1266
- },
1267
- });
1268
- ```
1269
-
1270
- ### ctx.shutdown()
1271
-
1272
- Request a graceful shutdown of Atomic.
1273
-
1274
- - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
1275
- - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
1276
- - **Print mode:** No-op. The process exits automatically when all prompts are processed.
1277
-
1278
- Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
1279
-
1280
- ```typescript
1281
- pi.on("tool_call", (event, ctx) => {
1282
- if (isFatal(event.input)) {
1283
- ctx.shutdown();
1284
- }
1285
- });
1286
- ```
1287
-
1288
- ### ctx.getContextUsage()
1289
-
1290
- Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
1291
-
1292
- ```typescript
1293
- const usage = ctx.getContextUsage();
1294
- if (usage && usage.tokens > 100_000) {
1295
- // ...
1296
- }
1297
- ```
1298
-
1299
- ### ctx.compact()
1300
-
1301
- Trigger Atomic's verbatim line compactor without awaiting completion. The planner emits numbered deleted-line ranges only; Atomic validates them and reconstructs retained text mechanically. Use `compression_ratio` (fraction of compactable lines to keep), client-side `preserve_recent` (an exact context-visible message count), and `query` to tune the run, and `onComplete`/`onError` for follow-up actions.
1302
-
1303
- ```typescript
1304
- ctx.compact({
1305
- compression_ratio: 0.5, // fraction of compactable lines to keep
1306
- preserve_recent: 2, // protect exactly the newest two context-visible messages
1307
- query: "keep active migration details",
1308
- onComplete: (result) => {
1309
- ctx.ui.notify(`Compaction kept ${result.stats.linesKept}/${result.stats.linesBefore} lines`, "info");
1310
- },
1311
- onError: (error) => {
1312
- ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
1313
- },
1314
- });
1315
- ```
1316
-
1317
- The planner cannot author context text: only validated line ranges enter the mechanical reconstruction path. The `query` parameter guides relevance selection inside the fixed prompt; it is not replacement prose. Extensions that need an offline replacement can return `compactedText` from `session_before_compact`.
1318
-
1319
- ### ctx.getSystemPrompt()
1320
-
1321
- Returns Atomic's current system prompt string.
1322
-
1323
- - During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
1324
- - It does not include later `context` message mutations.
1325
- - It does not include `before_provider_request` payload rewrites.
1326
- - If later-loaded extensions run after yours, they can still change what is ultimately sent.
1327
-
1328
- ```typescript
1329
- pi.on("before_agent_start", (event, ctx) => {
1330
- const prompt = ctx.getSystemPrompt();
1331
- console.log(`System prompt length: ${prompt.length}`);
1332
- });
1333
- ```
1334
-
1335
- ### ctx.getSkillCatalog()
1336
-
1337
- Returns the current loader-owned skill catalog when the host provides one. Use it to resolve exact skill selectors, including source-qualified names such as `tdd@builtin`, without falling back to the bare precedence winner.
1338
-
1339
- ```typescript
1340
- pi.on("session_start", (_event, ctx) => {
1341
- const catalog = ctx.getSkillCatalog?.();
1342
- const resolved = catalog?.resolve("tdd@builtin");
1343
- if (resolved?.ok) {
1344
- ctx.ui.notify(`Using ${resolved.candidate.selector}`, "info");
1345
- }
1346
- });
1347
- ```
1348
-
1349
- `pi.getCommands()` already includes the same advertised `/skill:name` and `/skill:name@source` names. See [Skill Commands](/skills#skill-commands).
1350
-
1351
- ## ExtensionCommandContext
1352
-
1353
- Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
1354
-
1355
- ### ctx.waitForIdle()
1356
-
1357
- Wait for the agent to finish streaming:
1358
-
1359
- ```typescript
1360
- pi.registerCommand("my-cmd", {
1361
- handler: async (args, ctx) => {
1362
- await ctx.waitForIdle();
1363
- // Agent is now idle, safe to modify session
1364
- },
1365
- });
1366
- ```
1367
-
1368
- ### ctx.newSession(options?)
1369
-
1370
- Create a new session:
1371
-
1372
- ```typescript
1373
- const parentSession = ctx.sessionManager.getSessionFile();
1374
- const kickoff = "Continue in the replacement session";
1375
-
1376
- const result = await ctx.newSession({
1377
- parentSession,
1378
- setup: async (sm) => {
1379
- sm.appendMessage({
1380
- role: "user",
1381
- content: [{ type: "text", text: "Context from previous session..." }],
1382
- timestamp: Date.now(),
1383
- });
1384
- },
1385
- withSession: async (ctx) => {
1386
- // Use only the replacement-session ctx here.
1387
- await ctx.sendUserMessage(kickoff);
1388
- },
1389
- });
1390
-
1391
- if (result.cancelled) {
1392
- // An extension cancelled the new session
1393
- }
1394
- ```
1395
-
1396
- Options:
1397
- - `parentSession`: parent session file to record in the new session header
1398
- - `setup`: mutate the new session's `SessionManager` before `withSession` runs
1399
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1400
-
1401
- ### ctx.fork(entryId, options?)
1402
-
1403
- Fork from a specific entry, creating a new session file:
1404
-
1405
- ```typescript
1406
- const result = await ctx.fork("entry-id-123", {
1407
- withSession: async (ctx) => {
1408
- // Use only the replacement-session ctx here.
1409
- ctx.ui.notify("Now in the forked session", "info");
1410
- },
1411
- });
1412
- if (result.cancelled) {
1413
- // An extension cancelled the fork
1414
- }
1415
-
1416
- const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
1417
- if (cloneResult.cancelled) {
1418
- // An extension cancelled the clone
1419
- }
1420
- ```
1421
-
1422
- Options:
1423
- - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
1424
- - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
1425
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1426
-
1427
- ### ctx.navigateTree(targetId, options?)
1428
-
1429
- Navigate to a different point in the session tree. Navigation rejects while a response, compaction, or branch summarization is active, even with `summarize: false`. Rejection leaves the active branch unchanged. Wait for the active operation to finish and retry.
1430
-
1431
- ```typescript
1432
- const result = await ctx.navigateTree("entry-id-456", {
1433
- summarize: true,
1434
- customInstructions: "Focus on error handling changes",
1435
- replaceInstructions: false, // true = replace default prompt entirely
1436
- label: "review-checkpoint",
1437
- });
1438
- ```
1439
-
1440
- Options:
1441
- - `summarize`: Whether to generate a summary of the abandoned branch
1442
- - `customInstructions`: Custom instructions for the summarizer
1443
- - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
1444
- - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
1445
-
1446
- ### ctx.switchSession(sessionPath, options?)
1447
-
1448
- Switch to a different session file:
1449
-
1450
- ```typescript
1451
- const result = await ctx.switchSession("/path/to/session.jsonl", {
1452
- withSession: async (ctx) => {
1453
- await ctx.sendUserMessage("Resume work in the replacement session");
1454
- },
1455
- });
1456
- if (result.cancelled) {
1457
- // An extension cancelled the switch via session_before_switch
1458
- }
1459
- ```
1460
-
1461
- Options:
1462
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1463
-
1464
- To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
1465
-
1466
- ```typescript
1467
- import { SessionManager } from "@bastani/atomic";
1468
-
1469
- pi.registerCommand("switch", {
1470
- description: "Switch to another session",
1471
- handler: async (args, ctx) => {
1472
- const sessions = await SessionManager.list(ctx.cwd);
1473
- if (sessions.length === 0) return;
1474
- const choice = await ctx.ui.select(
1475
- "Pick session:",
1476
- sessions.map(s => s.file),
1477
- );
1478
- if (choice) {
1479
- await ctx.switchSession(choice, {
1480
- withSession: async (ctx) => {
1481
- ctx.ui.notify("Switched session", "info");
1482
- },
1483
- });
1484
- }
1485
- },
1486
- });
1487
- ```
1488
-
1489
- ### Session replacement lifecycle and footguns
1490
-
1491
- `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
1492
-
1493
- Lifecycle and footguns:
1494
- - `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`.
1495
- - The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts.
1496
- - Captured old `pi` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work.
1497
- - Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement.
1498
- - Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config.
1499
- - Long-lived callbacks that need to classify a stale API error should use `isStaleExtensionContextError(error)` from `@bastani/atomic`, not match the host's error message.
1500
-
1501
- Safe pattern:
1502
-
1503
- ```typescript
1504
- pi.registerCommand("handoff", {
1505
- handler: async (_args, ctx) => {
1506
- const kickoff = "Continue from the replacement session";
1507
- await ctx.newSession({
1508
- withSession: async (ctx) => {
1509
- await ctx.sendUserMessage(kickoff);
1510
- },
1511
- });
1512
- },
1513
- });
1514
- ```
1515
-
1516
- Unsafe pattern:
1517
-
1518
- ```typescript
1519
- pi.registerCommand("handoff", {
1520
- handler: async (_args, ctx) => {
1521
- const oldSessionManager = ctx.sessionManager;
1522
- await ctx.newSession({
1523
- withSession: async (_ctx) => {
1524
- // stale old objects: do not do this
1525
- oldSessionManager.getSessionFile();
1526
- pi.sendUserMessage("wrong");
1527
- },
1528
- });
1529
- },
1530
- });
1531
- ```
1532
-
1533
- ### ctx.reload()
1534
-
1535
- Run the same reload flow as `/reload`.
1536
-
1537
- ```typescript
1538
- pi.registerCommand("reload-runtime", {
1539
- description: "Reload extensions, skills, prompts, and themes",
1540
- handler: async (_args, ctx) => {
1541
- await ctx.reload();
1542
- return;
1543
- },
1544
- });
1545
- ```
1546
-
1547
- Important behavior:
1548
- - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
1549
- - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
1550
- - The currently running command handler still continues in the old call frame
1551
- - Code after `await ctx.reload()` still runs from the pre-reload version
1552
- - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
1553
- - After the handler returns, future commands/events/tool calls use the new extension version
1554
-
1555
- For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1556
-
1557
- Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
1558
-
1559
- Example tool the LLM can call to trigger reload:
1560
-
1561
- ```typescript
1562
- import type { ExtensionAPI } from "@bastani/atomic";
1563
- import { Type } from "typebox";
1564
-
1565
- export default function (pi: ExtensionAPI) {
1566
- pi.registerCommand("reload-runtime", {
1567
- description: "Reload extensions, skills, prompts, and themes",
1568
- handler: async (_args, ctx) => {
1569
- await ctx.reload();
1570
- return;
1571
- },
1572
- });
1573
-
1574
- pi.registerTool({
1575
- name: "reload_runtime",
1576
- label: "Reload Runtime",
1577
- description: "Reload extensions, skills, prompts, and themes",
1578
- parameters: Type.Object({}),
1579
- async execute() {
1580
- pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
1581
- return {
1582
- content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
1583
- };
1584
- },
1585
- });
1586
- }
1587
- ```
1588
-
1589
- ## ExtensionAPI Methods
1590
-
1591
- ### pi.on(event, handler)
1592
-
1593
- Subscribe to events. See [Events](#events) for event types and return values.
1594
-
1595
- ### pi.registerTool(definition)
1596
-
1597
- Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1598
-
1599
- `pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` and are callable by the LLM without `/reload`.
1600
-
1601
- Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime. Atomic always restores mandatory ordinary `intercom`; other tool behavior is unchanged.
1602
-
1603
- Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
1604
-
1605
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
1606
-
1607
- See [dynamic-tools.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/dynamic-tools.ts) for a full example.
1608
-
1609
- #### Built-in tool prompt contributions
1610
-
1611
- Atomic exports immutable prompt metadata for its built-in coding tools. Use these constants when a custom harness or tool registry needs the same prompt entries as the built-in factories:
1612
-
1613
- ```typescript
1614
- import {
1615
- bashToolSystemPromptContribution,
1616
- editToolSystemPromptContribution,
1617
- findToolSystemPromptContribution,
1618
- lsToolSystemPromptContribution,
1619
- readToolSystemPromptContribution,
1620
- searchToolSystemPromptContribution,
1621
- writeToolSystemPromptContribution,
1622
- } from "@bastani/atomic";
1623
-
1624
- const { snippet, guidelines } = readToolSystemPromptContribution;
1625
- ```
1626
-
1627
- Each contribution has a readonly `snippet` for the `Available tools` section and readonly `guidelines` for the active tool's `Guidelines` entries. The seven exports are `bash`, `edit`, `find`, `ls`, `read`, `search`, and `write`; Atomic's public `search` export is the corresponding surface for pi's upstream `grep` tool. The built-in factories use these values directly, so consumers do not need to duplicate prompt text.
1628
-
1629
- Use Atomic's export rather than importing `StringEnum` directly from Pi. It preserves Pi's Google-compatible runtime schema while keeping the schema typed against Atomic's direct TypeBox version.
1630
-
1631
- ```typescript
1632
- import { Type } from "typebox";
1633
- import { StringEnum } from "@bastani/atomic";
1634
-
1635
- pi.registerTool({
1636
- name: "my_tool",
1637
- label: "My Tool",
1638
- description: "What this tool does",
1639
- promptSnippet: "Summarize or transform text according to action",
1640
- promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
1641
- parameters: Type.Object({
1642
- action: StringEnum(["list", "add"] as const),
1643
- text: Type.Optional(Type.String()),
1644
- }),
1645
- prepareArguments(args) {
1646
- // Optional compatibility shim. Runs before schema validation.
1647
- // Return the current schema shape, for example to fold legacy fields
1648
- // into the modern parameter object.
1649
- return args;
1650
- },
1651
-
1652
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1653
- // Stream progress
1654
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
1655
-
1656
- return {
1657
- content: [{ type: "text", text: "Done" }],
1658
- details: { result: "..." },
1659
- };
1660
- },
1661
-
1662
- // Optional: Custom rendering
1663
- renderCall(args, theme, context) { ... },
1664
- renderResult(result, options, theme, context) { ... },
1665
- });
1666
- ```
1667
-
1668
- ### pi.sendMessage(message, options?)
1669
-
1670
- Inject a custom message into the session. The call returns `void | Promise<void>` for compatibility with synchronous hosts; use `await Promise.resolve(pi.sendMessage(...))` when admission or routing failure must be observed. Atomic's AgentSession runtime returns an admission receipt: it settles after the message is accepted by the local queue or workflow late-message route, without waiting for the resulting model turn to finish.
1671
-
1672
- ```typescript
1673
- pi.sendMessage({
1674
- customType: "my-extension",
1675
- content: "Message text",
1676
- display: true,
1677
- details: { ... },
1678
- }, {
1679
- triggerTurn: true,
1680
- deliverAs: "steer",
1681
- });
1682
- ```
1683
-
1684
- **Options:**
1685
- - `deliverAs` - Delivery mode:
1686
- - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1687
- - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1688
- - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1689
- - `"interrupt"` - With `triggerTurn: true`, aborts an active streaming turn and immediately starts a new turn with the custom message. When idle, behaves like a triggered custom message.
1690
- - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Required for `"interrupt"`; ignored for `"nextTurn"`.
1691
- - `excludeFromContext: true` - Render and persist the custom message without adding it to LLM context. With no `deliverAs`, this remains display-only even while the agent is streaming.
1692
- - `interruptAbortMessage` - Optional text used to replace generic abort results (for example `Operation aborted`) when `deliverAs: "interrupt"` aborts an active turn.
1693
-
1694
- ### pi.sendMessages(messages, options?)
1695
-
1696
- Atomically admit a batch of custom messages in array order. The call returns `void | Promise<void>` for compatibility with synchronous hosts; use `await Promise.resolve(pi.sendMessages(...))` when admission or routing failure must be observed. The promise is an admission receipt and does not wait for the resulting model turn. Admission is indivisible; use this when a prelude and terminal notice must stay contiguous without globally serializing other extension work.
1697
-
1698
- ```typescript
1699
- pi.sendMessages([
1700
- { customType: "worker-update", content: "Ready", display: true },
1701
- { customType: "worker-terminal", content: "Completed", display: true },
1702
- ], { triggerTurn: true });
1703
- ```
1704
-
1705
- The batch supports `triggerTurn`, `excludeFromContext`, and `deliverAs: "steer" | "followUp" | "nextTurn"`. Interrupt delivery remains a single-message operation.
1706
-
1707
- ### pi.sendUserMessage(content, options?)
1708
-
1709
- Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. Always triggers a turn.
1710
-
1711
- ```typescript
1712
- // Simple text message
1713
- pi.sendUserMessage("What is 2+2?");
1714
-
1715
- // With content array (text + images)
1716
- pi.sendUserMessage([
1717
- { type: "text", text: "Describe this image:" },
1718
- { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1719
- ]);
1720
-
1721
- // During streaming - must specify delivery mode
1722
- pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1723
- pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1724
-
1725
- // Opt in to extension command dispatch and skill/prompt template expansion
1726
- pi.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
1727
- ```
1728
-
1729
- **Options:**
1730
- - `deliverAs` - Required when agent is streaming:
1731
- - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1732
- - `"followUp"` - Waits for agent to finish all tools
1733
-
1734
- - `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates instead of sending the text literally. Defaults to `false`, so an extension-authored message is sent as-is unless it opts in; an unknown command falls through to a literal send.
1735
-
1736
- When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1737
-
1738
- See [send-user-message.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/send-user-message.ts) for a complete example.
1739
-
1740
- ### pi.appendEntry(customType, data?)
1741
-
1742
- Persist extension state (does NOT participate in LLM context).
1743
-
1744
- ```typescript
1745
- pi.appendEntry("my-state", { count: 42 });
1746
-
1747
- // Restore on reload
1748
- pi.on("session_start", async (_event, ctx) => {
1749
- for (const entry of ctx.sessionManager.getEntries()) {
1750
- if (entry.type === "custom" && entry.customType === "my-state") {
1751
- // Reconstruct from entry.data
1752
- }
1753
- }
1754
- });
1755
- ```
1756
-
1757
- Appending emits `entry_appended` with the durable entry. This lets extensions react to session entries without polling.
1758
-
1759
- ### pi.registerEntryRenderer(customType, renderer)
1760
-
1761
- Register a TUI renderer for durable custom entries created by `pi.appendEntry()`. These entries render in the transcript but do not enter model context.
1762
-
1763
- ```typescript
1764
- import { Text } from "@earendil-works/pi-tui";
1765
-
1766
- pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) =>
1767
- new Text(theme.fg("accent", `${expanded ? "Details" : "Status"}: ${JSON.stringify(entry.data)}`), 0, 0)
1768
- );
1769
- ```
1770
-
1771
-
1772
- ### pi.setSessionName(name)
1773
-
1774
- Set the session display name (shown in session selector instead of first message).
1775
-
1776
- ```typescript
1777
- pi.setSessionName("Refactor auth module");
1778
- ```
1779
-
1780
- ### pi.getSessionName()
1781
-
1782
- Get the current session name, if set.
1783
-
1784
- ```typescript
1785
- const name = pi.getSessionName();
1786
- if (name) {
1787
- console.log(`Session: ${name}`);
1788
- }
1789
- ```
1790
-
1791
- ### pi.setLabel(entryId, label)
1792
-
1793
- Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1794
-
1795
- ```typescript
1796
- // Set a label
1797
- pi.setLabel(entryId, "checkpoint-before-refactor");
1798
-
1799
- // Clear a label
1800
- pi.setLabel(entryId, undefined);
1801
-
1802
- // Read labels via sessionManager
1803
- const label = ctx.sessionManager.getLabel(entryId);
1804
- ```
1805
-
1806
- Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1807
-
1808
- ### pi.registerCommand(name, options)
1809
-
1810
- Register a command.
1811
-
1812
- If multiple extensions register the same command name, Atomic keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
1813
-
1814
- ```typescript
1815
- pi.registerCommand("stats", {
1816
- description: "Show session statistics",
1817
- handler: async (args, ctx) => {
1818
- const count = ctx.sessionManager.getEntries().length;
1819
- ctx.ui.notify(`${count} entries`, "info");
1820
- }
1821
- });
1822
- ```
1823
-
1824
- Optional: add argument auto-completion for `/command ...`:
1825
-
1826
- ```typescript
1827
- import type { AutocompleteItem } from "@earendil-works/pi-tui";
1828
-
1829
- pi.registerCommand("deploy", {
1830
- description: "Deploy to an environment",
1831
- getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1832
- const envs = ["dev", "staging", "prod"];
1833
- const items = envs.map((e) => ({ value: e, label: e }));
1834
- const filtered = items.filter((i) => i.value.startsWith(prefix));
1835
- return filtered.length > 0 ? filtered : null;
1836
- },
1837
- handler: async (args, ctx) => {
1838
- ctx.ui.notify(`Deploying: ${args}`, "info");
1839
- },
1840
- });
1841
- ```
1842
-
1843
- ### pi.getCommands()
1844
-
1845
- Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1846
- The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1847
-
1848
- ```typescript
1849
- const commands = pi.getCommands();
1850
- const bySource = commands.filter((command) => command.source === "extension");
1851
- const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
1852
- ```
1853
-
1854
- Each entry has this shape:
1855
-
1856
- ```typescript
1857
- {
1858
- name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
1859
- description?: string;
1860
- source: "extension" | "prompt" | "skill";
1861
- sourceInfo: {
1862
- path: string;
1863
- source: string;
1864
- scope: "user" | "project" | "temporary";
1865
- origin: "package" | "top-level";
1866
- baseDir?: string;
1867
- };
1868
- }
1869
- ```
1870
-
1871
- Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1872
-
1873
- Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1874
- mode and would not execute if sent via `prompt`.
1875
-
1876
- ### pi.registerMessageRenderer(customType, renderer)
1877
-
1878
- Register a custom TUI renderer for messages with your `customType`. The renderer options contain `expanded` and the current numeric `outputPad`, so custom output can align with built-in messages. The same options are provided in normal and isolated-engine rendering. See [Custom UI](#custom-ui).
1879
-
1880
- ### pi.registerMarkdownTransformer(transformer)
1881
-
1882
- Register a synchronous, display-only transformer for Markdown in normal user text, assistant text, and thinking blocks. Atomic runs transformers in extension load order. Each extension retains one transformer, so a later call from that extension replaces its prior transformer. Each transformer receives the Markdown returned by the prior transformer, then Atomic renders the final value with its built-in Markdown renderer.
1883
-
1884
- The transformer receives the Markdown string and a context with:
1885
-
1886
- - `messageType` — `"user"`, `"assistant"`, or `"assistant-thinking"`
1887
- - `isStreaming` — `true` for partial assistant updates; `false` for user, finalized assistant, and restored messages
1888
- - `availableWidth` — exact terminal columns available for the transformed Markdown content
1889
-
1890
- Return the transformed Markdown:
1891
-
1892
- ```typescript
1893
- pi.registerMarkdownTransformer((markdown, { messageType, isStreaming }) => {
1894
- if (isStreaming || messageType === "assistant-thinking") return markdown;
1895
- return markdown.replaceAll("-->", "→");
1896
- });
1897
- ```
1898
-
1899
- If a transformer throws, Atomic keeps the Markdown produced so far and continues with the next transformer. The hook never changes the original message, session transcript, or model context. It runs for new user messages, assistant streaming updates, restored session messages, and terminal-width changes, so keep transformers synchronous and inexpensive. Isolated-engine rendering does not run host-side display transformers.
1900
-
1901
- ### pi.registerShortcut(shortcut, options)
1902
-
1903
- Register a keyboard shortcut. See [Keybindings](/keybindings) for the shortcut format and built-in keybindings.
1904
-
1905
- ```typescript
1906
- pi.registerShortcut("ctrl+shift+p", {
1907
- description: "Toggle plan mode",
1908
- handler: async (ctx) => {
1909
- ctx.ui.notify("Toggled!");
1910
- },
1911
- });
1912
- ```
1913
-
1914
- ### pi.registerFlag(name, options)
1915
-
1916
- Register a CLI flag.
1917
-
1918
- ```typescript
1919
- pi.registerFlag("plan", {
1920
- description: "Start in plan mode",
1921
- type: "boolean",
1922
- default: false,
1923
- });
1924
-
1925
- // Check value
1926
- if (pi.getFlag("plan")) {
1927
- // Plan mode enabled
1928
- }
1929
- ```
1930
-
1931
- ### pi.exec(command, args, options?)
1932
-
1933
- Execute a shell command.
1934
-
1935
- ```typescript
1936
- const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1937
- // result.stdout, result.stderr, result.code, result.killed
1938
- ```
1939
-
1940
- ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1941
-
1942
- Manage active tools. This works for both built-in tools and dynamically registered tools. `pi.getActiveTools()` returns the active tool names as `string[]`; `pi.getAllTools()` returns metadata for all configured tools.
1943
-
1944
- ```typescript
1945
- const active = pi.getActiveTools(); // ["read", "bash", ...]
1946
- const all = pi.getAllTools();
1947
- // all = [{
1948
- // name: "read",
1949
- // description: "Read file contents...",
1950
- // parameters: ...,
1951
- // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1952
- // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1953
- // }, ...]
1954
- const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1955
- const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1956
- pi.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
1957
- pi.setActiveTools(["read", "bash"]); // Switch to read-only
1958
- ```
1959
-
1960
- `pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`.
1961
-
1962
- Typical `sourceInfo.source` values:
1963
- - `builtin` for built-in tools
1964
- - `sdk` for tools passed via `createAgentSession({ customTools })`
1965
- - extension source metadata for tools registered by extensions
1966
-
1967
- ### pi.setModel(model)
1968
-
1969
- Set the model for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured `defaultProvider` or `defaultModel` used by new sessions. Returns `false` if authentication is not configured for the model's provider. See [Custom models](/models) for configuring custom models.
1970
-
1971
- ```typescript
1972
- const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1973
- if (model) {
1974
- const success = await pi.setModel(model);
1975
- if (!success) {
1976
- ctx.ui.notify("No API key for this model", "error");
1977
- }
1978
- }
1979
- ```
1980
-
1981
- ### pi.getThinkingLevel() / pi.setThinkingLevel(level)
1982
-
1983
- Get the current thinking level. Level is clamped to model capabilities (non-reasoning models always use `"off"`; `"xhigh"` and `"max"` require model support). Changes emit `thinking_level_select`.
1984
-
1985
- `pi.setThinkingLevel()` changes the thinking level for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured default used by new sessions.
1986
-
1987
- ```typescript
1988
- const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
1989
- pi.setThinkingLevel("high");
1990
- ```
1991
-
1992
- ### pi.events
1993
-
1994
- Shared event bus for communication between active extensions. A subscription made with `on()` is removed automatically when its extension reloads or the session disposes. Use the returned function if you need to stop listening sooner:
1995
-
1996
- ```typescript
1997
- const unsubscribe = pi.events.on("my:event", (data) => { ... });
1998
- pi.events.emit("my:event", { ... });
1999
- unsubscribe();
2000
- ```
2001
-
2002
- `pi.events` belongs to the extension instance that received it. Register listeners again when that instance reloads, and do not retain the object for later use: calling `on()` or `emit()` through a captured handle after reload or disposal throws. To keep in-memory state across `/reload`, pass this facade to [`sessionScopedExtensionState`](#session-scoped-in-memory-state); do not capture the facade itself.
2003
-
2004
- If you implement an `ExtensionRuntime` for an embedded host, provide `trackEventBusSubscription(unsubscribe)` and retain each returned subscription until that extension runtime is reloaded or disposed. `ExtensionUIContext.getChatRenderSettings()` must return `markdownTransformers`; it may also return `renderLatex` to control terminal math rendering. These fields keep event subscriptions and display transforms scoped to the active extension instance.
2005
-
2006
-
2007
- ### Native providers
2008
-
2009
- In addition to `registerProvider(name, config)`, extensions can register a complete native `Provider` from `@bastani/pi-ai` with `pi.registerProvider(provider)`. Use the native overload for provider-owned authentication, catalog refresh, and transport behavior; use the config overload for ordinary proxies and custom endpoints.
2010
-
2011
- ### pi.registerProvider(name, config)
2012
-
2013
- Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
2014
-
2015
- Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a `/reload`.
2016
-
2017
- If you need to discover models from a remote endpoint, prefer an async extension factory over deferring the fetch to `session_start`. Atomic waits for the factory before startup continues, so the registered models are available immediately, including to `atomic --list-models`.
2018
-
2019
- ```typescript
2020
- // Register a new provider with custom models
2021
- pi.registerProvider("my-proxy", {
2022
- name: "My Proxy",
2023
- baseUrl: "https://proxy.example.com",
2024
- apiKey: "$PROXY_API_KEY", // env var reference; omit $ for a literal
2025
- api: "anthropic-messages",
2026
- models: [
2027
- {
2028
- id: "claude-sonnet-4-20250514",
2029
- name: "Claude 4 Sonnet (proxy)",
2030
- reasoning: false,
2031
- input: ["text", "image"],
2032
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2033
- contextWindow: 200000,
2034
- maxTokens: 16384
2035
- }
2036
- ]
2037
- });
2038
-
2039
- // Override baseUrl for an existing provider (keeps all models)
2040
- pi.registerProvider("anthropic", {
2041
- baseUrl: "https://proxy.example.com"
2042
- });
2043
-
2044
- // Register provider with OAuth support for /login
2045
- pi.registerProvider("corporate-ai", {
2046
- baseUrl: "https://ai.corp.com",
2047
- api: "openai-responses",
2048
- models: [...],
2049
- oauth: {
2050
- name: "Corporate AI (SSO)",
2051
- async login(callbacks, signal) {
2052
- // Custom OAuth flow
2053
- callbacks.onAuth({ url: "https://sso.corp.com/..." });
2054
- const code = await callbacks.onPrompt({ message: "Enter code:" });
2055
- signal.throwIfAborted();
2056
- return { refresh: code, access: code, expires: Date.now() + 3600000 };
2057
- },
2058
- async refreshToken(credentials, signal) {
2059
- // Forward signal to the refresh request.
2060
- signal.throwIfAborted();
2061
- return credentials;
2062
- },
2063
- getApiKey(credentials) {
2064
- return credentials.access;
2065
- }
2066
- }
2067
- });
2068
-
2069
- // Register provider-owned API-key setup for /login
2070
- pi.registerProvider("local-server", {
2071
- name: "Local Server",
2072
- auth: {
2073
- apiKey: {
2074
- name: "Local server connection",
2075
- async login({ signal, prompt }) {
2076
- const baseUrl = await prompt({
2077
- type: "text",
2078
- message: "Server URL",
2079
- placeholder: "http://localhost:8080"
2080
- });
2081
- if (signal.aborted) throw new Error("Login cancelled");
2082
- return { type: "api_key", env: { LOCAL_SERVER_URL: baseUrl } };
2083
- }
2084
- }
2085
- }
2086
- });
2087
- ```
2088
-
2089
- **Config options:**
2090
- - `name` - Display name for the provider in UI such as `/login`.
2091
- - `baseUrl` - API endpoint URL. Required when defining models.
2092
- - `apiKey` - API key literal or explicit environment variable reference (`$ENV_VAR` or `${ENV_VAR}`). Required when defining models (unless `oauth` provided).
2093
- - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
2094
- - `headers` - Custom headers to include in requests.
2095
- - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
2096
- - `models` - Array of model definitions. If provided, replaces all existing models for this provider. Model definitions can set `baseUrl` to override the provider endpoint for that model.
2097
- - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
2098
- - `auth.apiKey` - Provider-owned API-key or connection setup for `/login`. Its `name` appears in the provider list and `login({ signal, prompt })` returns the credential Atomic persists. Extension providers registered only in the isolated interactive engine child are synchronized into the host's `/login` list; their login callback and credential-dependent model refresh still execute in the child, while prompts are rendered by the terminal host.
2099
- - `streamSimple` - Custom streaming implementation for non-standard APIs.
2100
-
2101
- See [Custom providers](/custom-provider) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
2102
-
2103
- ### pi.unregisterProvider(name)
2104
-
2105
- Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered.
2106
-
2107
- Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
2108
-
2109
- ```typescript
2110
- pi.registerCommand("my-setup-teardown", {
2111
- description: "Remove the custom proxy provider",
2112
- handler: async (_args, _ctx) => {
2113
- pi.unregisterProvider("my-proxy");
2114
- },
2115
- });
2116
- ```
2117
-
2118
- ## State Management
2119
-
2120
- Choose the store that matches the lifetime you need:
2121
-
2122
- - **Tool result `details`** — reconstructs across `/branch` and `/resume` from the transcript.
2123
- - **`pi.appendEntry()`** — durable custom entries that survive process restart. They do not enter model context.
2124
- - **`sessionScopedExtensionState()`** — in-memory objects that survive `/reload` for the current process. They do not survive process restart.
2125
-
2126
- In Bun single-file builds, an editable file extension whose imported graph is unchanged can reuse its evaluated factory, so its module-scoped variables may survive `/reload`. An edit anywhere in that graph re-evaluates its modules and resets those singletons. The five fixed installed builtin bundles always reuse their evaluated factories and module state across `/reload`, as described above.
2127
-
2128
- Extensions with state that must follow conversation branches should store it in tool result `details`:
2129
-
2130
- ```typescript
2131
- export default function (pi: ExtensionAPI) {
2132
- let items: string[] = [];
2133
-
2134
- // Reconstruct state from session
2135
- pi.on("session_start", async (_event, ctx) => {
2136
- items = [];
2137
- for (const entry of ctx.sessionManager.getBranch()) {
2138
- if (entry.type === "message" && entry.message.role === "toolResult") {
2139
- if (entry.message.toolName === "my_tool") {
2140
- items = entry.message.details?.items ?? [];
2141
- }
2142
- }
2143
- }
2144
- });
2145
-
2146
- pi.registerTool({
2147
- name: "my_tool",
2148
- // ...
2149
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2150
- items.push("new item");
2151
- return {
2152
- content: [{ type: "text", text: "Added" }],
2153
- details: { items: [...items] }, // Store for reconstruction
2154
- };
2155
- },
2156
- });
2157
- }
2158
- ```
2159
-
2160
- ### Session-scoped in-memory state
2161
-
2162
- Import `sessionScopedExtensionState` from `@bastani/atomic` when an extension must keep a live object across `/reload` — registries, abort controllers, connection pools, or any other handle that cannot be rebuilt from the transcript.
2163
-
2164
- ```typescript
2165
- import { sessionScopedExtensionState, type ExtensionAPI } from "@bastani/atomic";
2166
-
2167
- interface CounterState {
2168
- count: number;
2169
- }
2170
-
2171
- export default function (pi: ExtensionAPI) {
2172
- const state = sessionScopedExtensionState(pi.events, "my-extension:counter:v1", () => ({
2173
- count: 0,
2174
- }));
2175
-
2176
- pi.registerCommand("bump", {
2177
- description: "Increment a counter that survives /reload",
2178
- handler: async (_args, ctx) => {
2179
- state.count += 1;
2180
- ctx.ui.notify(`count=${state.count}`, "info");
2181
- },
2182
- });
2183
- }
2184
- ```
2185
-
2186
- **Required scope.** Pass the extension's `pi.events` facade (or the session `EventBus` itself). The host resolves that facade to the canonical session bus, so every load generation of one session re-binds to the same object. Two in-process sessions with distinct buses stay isolated. Do not pass an arbitrary object: an unregistered scope is treated as its own bus and will not re-bind after reload.
2187
-
2188
- **Session-wide key namespace.** Keys are not automatically namespaced by extension. Two extensions that pass the same key on the same session receive the first extension's object; the later factory is not called. Prefix every key with a stable extension identity.
2189
-
2190
- **Key-versioning.** Append a version suffix and bump it when the stored shape changes, for example `"my-extension:counter:v1"` → `"my-extension:counter:v2"`. The new key declines the incompatible predecessor instead of reusing it under a new type.
2191
-
2192
- **Reload behavior.** `/reload` builds a new `pi.events` facade that still forwards to the same bus. Calling `sessionScopedExtensionState` again with the same namespaced key returns the existing object and does not invoke `create`. The reload transaction does not clone this object or roll back mutations that extension factory code makes to it. Keep factory setup idempotent, and mutate durable state only after the new generation starts when failed reloads must not affect it. Entries live exactly as long as that bus. They are not written to the session file; use `pi.appendEntry()` when the data must survive process restart.
2193
-
2194
- **Shutdown.** `session_shutdown` still runs for resources you opened. If the object holds sockets, watchers, or timers, close them there. The next `session_start` or first use can recreate them inside the same session-scoped object.
2195
-
2196
-
2197
- ## Custom Tools
2198
-
2199
- Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
2200
-
2201
- Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
2202
-
2203
- Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
2204
-
2205
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
2206
-
2207
- Note: Some models are idiots and include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
2208
-
2209
- If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other.
2210
-
2211
- Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost.
2212
-
2213
- Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet.
2214
-
2215
- Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
2216
-
2217
- ```typescript
2218
- import { withFileMutationQueue } from "@bastani/atomic";
2219
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2220
- import { dirname, resolve } from "node:path";
2221
-
2222
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2223
- const absolutePath = resolve(ctx.cwd, params.path);
2224
-
2225
- return withFileMutationQueue(absolutePath, async () => {
2226
- await mkdir(dirname(absolutePath), { recursive: true });
2227
- const current = await readFile(absolutePath, "utf8");
2228
- const next = current.replace(params.oldText, params.newText);
2229
- await writeFile(absolutePath, next, "utf8");
2230
-
2231
- return {
2232
- content: [{ type: "text", text: `Updated ${params.path}` }],
2233
- details: {},
2234
- };
2235
- });
2236
- }
2237
- ```
2238
-
2239
- ### Tool Definition
2240
-
2241
- `parameters` is required, including for no-argument tools (use `Type.Object({})`). Registration rejects missing, null, array, and primitive schema values before they can break a provider request. This checks the schema container, not its JSON Schema `type`: object-valued union and non-object-type schemas remain accepted and unchanged.
2242
-
2243
- ```typescript
2244
- import { Type } from "typebox";
2245
- import { StringEnum } from "@bastani/atomic";
2246
- import { Text } from "@earendil-works/pi-tui";
2247
-
2248
- pi.registerTool({
2249
- name: "my_tool",
2250
- label: "My Tool",
2251
- description: "What this tool does (shown to LLM)",
2252
- promptSnippet: "List or add items in the project todo list",
2253
- promptGuidelines: [
2254
- "Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
2255
- ],
2256
- parameters: Type.Object({
2257
- action: StringEnum(["list", "add"] as const), // Atomic's Pi-compatible TypeBox helper
2258
- text: Type.Optional(Type.String()),
2259
- }),
2260
- prepareArguments(args) {
2261
- if (!args || typeof args !== "object") return args;
2262
- const input = args as { action?: string; oldAction?: string };
2263
- if (typeof input.oldAction === "string" && input.action === undefined) {
2264
- return { ...input, action: input.oldAction };
2265
- }
2266
- return args;
2267
- },
2268
-
2269
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2270
- // Check for cancellation
2271
- if (signal?.aborted) {
2272
- return { content: [{ type: "text", text: "Cancelled" }] };
2273
- }
2274
-
2275
- // Stream progress updates
2276
- onUpdate?.({
2277
- content: [{ type: "text", text: "Working..." }],
2278
- details: { progress: 50 },
2279
- });
2280
-
2281
- // Run commands via pi.exec (captured from extension closure)
2282
- const result = await pi.exec("some-command", [], { signal });
2283
-
2284
- // Return result
2285
- return {
2286
- content: [{ type: "text", text: "Done" }], // Sent to LLM
2287
- details: { data: result }, // For rendering & state
2288
- // Optional: stop after this tool batch when every finalized tool result
2289
- // in the batch also returns terminate: true.
2290
- terminate: true,
2291
- };
2292
- },
2293
-
2294
- // Optional: Custom rendering
2295
- renderCall(args, theme, context) { ... },
2296
- renderResult(result, options, theme, context) { ... },
2297
- });
2298
- ```
2299
-
2300
- **Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
2301
-
2302
- **Early termination:** Return `terminate: true` from `execute()` to hint that the automatic follow-up LLM call should be skipped after the current tool batch. This only takes effect when every finalized tool result in that batch is terminating. Atomic does not register `structured_output` in normal agent sessions by default; use `createStructuredOutputTool({ schema, capture, output, name })` when an extension, SDK session, or workflow stage needs a schema-backed final-answer tool. The factory uses the supplied schema as the tool parameters directly, captures the tool arguments as whatever JSON value matches the schema, emits the same pretty-printed JSON as the terminating tool-result text for `atomic -p`, optionally writes them to the configured `output.outputPath`, and terminates the turn. In text print mode, a terminating result from a factory-created structured-output tool is emitted to stdout as the final response. Custom factory names are opt-in tools: if you register `final_decision`, include `final_decision` in any explicit `tools` allowlist; if you register the default `structured_output` name, it is available only to that session/runtime.
2303
-
2304
- ```typescript
2305
- // Correct: throw to signal an error
2306
- async execute(toolCallId, params) {
2307
- if (!isValid(params.input)) {
2308
- throw new Error(`Invalid input: ${params.input}`);
2309
- }
2310
- return { content: [{ type: "text", text: "OK" }], details: {} };
2311
- }
2312
- ```
2313
-
2314
- **Important:** Use `StringEnum` from `@bastani/atomic` for string enums. It retains Pi's Google-compatible schema and composes with Atomic's direct TypeBox types; `Type.Union`/`Type.Literal` doesn't work with Google's API.
2315
-
2316
- #### Constrained sampling
2317
-
2318
- `ToolDefinition.constrainedSampling` is preserved for extension tools, SDK `customTools`, wrappers, and isolated execution. It accepts `false` or the exported `ConstrainedSamplingConfig`:
2319
-
2320
- ```typescript
2321
- pi.registerTool({
2322
- name: "strict_edit",
2323
- label: "Strict edit",
2324
- description: "Edit one file",
2325
- parameters: Type.Object({ path: Type.String(), content: Type.String() }),
2326
- constrainedSampling: { type: "json_schema", strict: "prefer" },
2327
- async execute(_id, params) {
2328
- return { content: [{ type: "text", text: params.path }], details: {} };
2329
- },
2330
- });
2331
- ```
2332
-
2333
- Exact modes:
2334
-
2335
- - `{ type: "json_schema", strict: "prefer" }` requests strict provider enforcement and falls back to ordinary tool calling when unavailable.
2336
- - `{ type: "json_schema", strict: "require" }` fails the request rather than silently weakening the constraint.
2337
- - `{ type: "grammar", variants: { openai_lark?: string, openai_regex?: string } }` requests an OpenAI custom grammar tool; Lark wins when both non-empty variants are present.
2338
- - `false` explicitly opts out. Its runtime effect matches omission, but public tool inspection preserves `false` as a present property.
2339
-
2340
- Built-in `read`, `edit`, `write`, `bash`, and its Windows PowerShell variant request strict JSON-schema sampling with `prefer` by default. This is a provider hint, not a schema rewrite or a sandbox. Unsupported providers retain ordinary tool calling. Other experimental tool hints still follow the experimental environment flag.
2341
-
2342
- Atomic preserves the optional property's exact own-key state across wrappers, active-session inspection, staged extension inspection, bundled tools, and isolated transport: omission stays absent; explicitly present `undefined` stays present; `false` and config objects remain unchanged. This distinction matters to SDK/extension code that uses `Object.hasOwn()` rather than an ordinary property read.
2343
-
2344
- Grammar tools require an object schema with exactly one required string property. They are emitted only when model metadata advertises `supportsOpenAIGrammarTools` (also exposed as Atomic's `supportsGrammarTools` alias); otherwise provider handling falls back to the normal function/JSON-schema path. Older OpenAI models and gateways that rewrite schemas cannot honor custom grammar tools. Typed RPC clients receive these claims through optional `ModelInfo.compat`. See [Custom Models](/models#constrained-tool-sampling) and [RPC](/rpc#get_available_models).
2345
-
2346
- **Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it only when a custom tool must normalize arguments before validation. Return the object you want validated against `parameters`, keep the public schema strict, and avoid advertising deprecated fields.
2347
-
2348
- ```typescript
2349
- pi.registerTool({
2350
- name: "deploy_plan",
2351
- label: "Deploy Plan",
2352
- description: "Create a deployment plan for one target environment",
2353
- parameters: Type.Object({
2354
- environment: Type.String(),
2355
- dryRun: Type.Optional(Type.Boolean()),
2356
- }),
2357
- prepareArguments(args) {
2358
- if (!args || typeof args !== "object") return args;
2359
- const input = args as { env?: unknown; environment?: unknown; dryRun?: unknown };
2360
- if (typeof input.environment === "string") return args;
2361
- if (typeof input.env !== "string") return args;
2362
- return { environment: input.env, dryRun: input.dryRun };
2363
- },
2364
- async execute(toolCallId, params) {
2365
- return {
2366
- content: [{ type: "text", text: `Planning deploy to ${params.environment}` }],
2367
- details: {},
2368
- };
2369
- },
2370
- });
2371
- ```
2372
-
2373
- ### Fireworks deferred tool loading
2374
-
2375
- Extensions making requests directly through `@bastani/pi-ai` can use native deferred tool loading with Fireworks `anthropic-messages` models. Supply the tool definitions in `context.tools` and record newly loaded tool names in the loader result's `addedToolNames` field. The provider serializes deferred definitions with `defer_loading` and inserts `tool_reference` content at the load point.
2376
-
2377
- Name the loader `ToolSearch` or `tool_search` to keep deferred schemas out of the initial prompt prefix. Other names work, but Fireworks includes the schemas in the prefix and loses that cache benefit. Fireworks GLM models and Kimi K3 still use Chat Completions; this feature does not change their routing.
2378
-
2379
- This is an AI SDK capability. Atomic's `pi.setActiveTools()` updates the active tool list but does not automatically populate `addedToolNames`. See the [AI SDK deferred tool-loading guide](https://github.com/bastani-inc/atomic/blob/main/packages/ai/README.md#fireworks-deferred-tools) for details.
2380
-
2381
- ### Overriding Built-in Tools
2382
-
2383
- Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `find`, `search`, `ask_user_question`, `todo`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
2384
-
2385
- ```bash
2386
- # Extension's read tool replaces built-in read
2387
- atomic -e ./tool-override.ts
2388
- ```
2389
-
2390
- Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled:
2391
- ```bash
2392
- # No built-in tools, only extension tools
2393
- atomic --no-builtin-tools -e ./my-extension.ts
2394
- ```
2395
-
2396
- See [examples/extensions/tool-override.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
2397
-
2398
- **Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI.
2399
-
2400
- **Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly.
2401
-
2402
- **Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking.
2403
-
2404
- Built-in tool implementations:
2405
- - [read.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
2406
- - [bash.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
2407
- - [edit.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/edit.ts)
2408
- - [write.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/write.ts)
2409
- - [grep.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
2410
- - [find.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
2411
- - [ls.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
2412
-
2413
- ### Remote Execution
2414
-
2415
- Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
2416
-
2417
- ```typescript
2418
- import { createReadTool, createBashTool, type ReadOperations } from "@bastani/atomic";
2419
-
2420
- // Create tool with custom operations
2421
- const remoteRead = createReadTool(cwd, {
2422
- operations: {
2423
- readFile: (path) => sshExec(remote, `cat ${path}`),
2424
- access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
2425
- }
2426
- });
2427
-
2428
- // Register, checking flag at execution time
2429
- pi.registerTool({
2430
- ...remoteRead,
2431
- async execute(id, params, signal, onUpdate, _ctx) {
2432
- const ssh = getSshConfig();
2433
- if (ssh) {
2434
- const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
2435
- return tool.execute(id, params, signal, onUpdate);
2436
- }
2437
- return localRead.execute(id, params, signal, onUpdate);
2438
- },
2439
- });
2440
- ```
2441
-
2442
- `ReadOperations` may also provide `stat` and `listDir` to keep directory-tree reads on the injected filesystem. The Harness factory supplies both. A custom read backend without both members keeps the existing file-only remote behavior. Archive, SQLite, internal-resource, notebook, and path-variant helpers still use Atomic's local filesystem unless the tool gains dedicated remote seams.
2443
-
2444
- **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2445
-
2446
- For `user_bash`, extensions can reuse atomic's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
2447
-
2448
- The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
2449
-
2450
- ```typescript
2451
- import { createBashTool } from "@bastani/atomic";
2452
-
2453
- const bashTool = createBashTool(cwd, {
2454
- spawnHook: ({ command, cwd, env }) => ({
2455
- command: `source ~/.profile\n${command}`,
2456
- cwd: `/mnt/sandbox${cwd}`,
2457
- env: { ...env, CI: "1" },
2458
- }),
2459
- });
2460
- ```
2461
-
2462
- See [examples/extensions/ssh.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2463
-
2464
- ### Output Truncation
2465
-
2466
- **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
2467
- - Context overflow errors (prompt too long)
2468
- - Compaction failures
2469
- - Degraded model performance
2470
-
2471
- The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
2472
-
2473
- ```typescript
2474
- import {
2475
- truncateHead, // Keep first N lines/bytes (good for file reads, search results)
2476
- truncateTail, // Keep last N lines/bytes (good for logs, command output)
2477
- truncateLine, // Truncate a single line to maxBytes with ellipsis
2478
- formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
2479
- DEFAULT_MAX_BYTES, // 50KB
2480
- DEFAULT_MAX_LINES, // 2000
2481
- } from "@bastani/atomic";
2482
-
2483
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2484
- const output = await runCommand();
2485
-
2486
- // Apply truncation
2487
- const truncation = truncateHead(output, {
2488
- maxLines: DEFAULT_MAX_LINES,
2489
- maxBytes: DEFAULT_MAX_BYTES,
2490
- });
2491
-
2492
- let result = truncation.content;
2493
-
2494
- if (truncation.truncated) {
2495
- // Write full output to temp file
2496
- const tempFile = writeTempFile(output);
2497
-
2498
- // Inform the LLM where to find complete output
2499
- result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
2500
- result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
2501
- result += ` Full output saved to: ${tempFile}]`;
2502
- }
2503
-
2504
- return { content: [{ type: "text", text: result }] };
2505
- }
2506
- ```
2507
-
2508
- **Key points:**
2509
- - Use `truncateHead` for content where the beginning matters (search results, file reads)
2510
- - Use `truncateTail` for content where the end matters (logs, command output)
2511
- - Always inform the LLM when output is truncated and where to find the full version
2512
- - Document the truncation limits in your tool's description
2513
-
2514
- See [examples/extensions/truncated-tool.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
2515
-
2516
- ### Multiple Tools
2517
-
2518
- One extension can register multiple tools with shared state:
2519
-
2520
- ```typescript
2521
- export default function (pi: ExtensionAPI) {
2522
- let connection = null;
2523
-
2524
- pi.registerTool({ name: "db_connect", ... });
2525
- pi.registerTool({ name: "db_query", ... });
2526
- pi.registerTool({ name: "db_close", ... });
2527
-
2528
- pi.on("session_shutdown", async () => {
2529
- connection?.close();
2530
- });
2531
- }
2532
- ```
2533
-
2534
- ### Custom Rendering
2535
-
2536
- Tools can provide `renderCall` and `renderResult` for custom TUI display. See [TUI components](/tui) for the full component API and [tool-execution.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.
2537
-
2538
- By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
2539
-
2540
- Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles.
2541
-
2542
- ```typescript
2543
- pi.registerTool({
2544
- name: "my_tool",
2545
- label: "My Tool",
2546
- description: "Custom shell example",
2547
- parameters: Type.Object({}),
2548
- renderShell: "self",
2549
- async execute() {
2550
- return { content: [{ type: "text", text: "ok" }], details: undefined };
2551
- },
2552
- renderCall(args, theme, context) {
2553
- return new Text(theme.fg("accent", "my custom shell"), 0, 0);
2554
- },
2555
- });
2556
- ```
2557
-
2558
- `renderCall` and `renderResult` each receive a `context` object with:
2559
- - `args` - the current tool call arguments
2560
- - `state` - shared row-local state across `renderCall` and `renderResult`
2561
- - `lastComponent` - the previously returned component for that slot, if any
2562
- - `invalidate()` - request a rerender of this tool row
2563
- - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
2564
-
2565
- Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders.
2566
-
2567
- #### renderCall
2568
-
2569
- Renders the tool call or header:
2570
-
2571
- ```typescript
2572
- import { Text } from "@earendil-works/pi-tui";
2573
-
2574
- renderCall(args, theme, context) {
2575
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
2576
- let content = theme.fg("toolTitle", theme.bold("my_tool "));
2577
- content += theme.fg("muted", args.action);
2578
- if (args.text) {
2579
- content += " " + theme.fg("dim", `"${args.text}"`);
2580
- }
2581
- text.setText(content);
2582
- return text;
2583
- }
2584
- ```
2585
-
2586
- #### renderResult
2587
-
2588
- Renders the tool result or output:
2589
-
2590
- ```typescript
2591
- renderResult(result, { expanded, isPartial }, theme, context) {
2592
- if (isPartial) {
2593
- return new Text(theme.fg("warning", "Processing..."), 0, 0);
2594
- }
2595
-
2596
- if (result.details?.error) {
2597
- return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
2598
- }
2599
-
2600
- let text = theme.fg("success", "✓ Done");
2601
- if (expanded && result.details?.items) {
2602
- for (const item of result.details.items) {
2603
- text += "\n " + theme.fg("dim", item);
2604
- }
2605
- }
2606
- return new Text(text, 0, 0);
2607
- }
2608
- ```
2609
-
2610
- If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
2611
-
2612
- #### Keybinding Hints
2613
-
2614
- Use `keyHintIfBound()` when an affordance should disappear if the action has no effective keybinding. Add surrounding punctuation only when the helper returns text:
2615
-
2616
- ```typescript
2617
- import { keyHintIfBound } from "@bastani/atomic";
2618
-
2619
- renderResult(result, { expanded }, theme, context) {
2620
- let text = theme.fg("success", "✓ Done");
2621
- const expandHint = keyHintIfBound("app.tools.expand", "to expand");
2622
- if (!expanded && expandHint) {
2623
- text += ` (${expandHint})`;
2624
- }
2625
- return new Text(text, 0, 0);
2626
- }
2627
- ```
2628
-
2629
- Available functions:
2630
- - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`; use it when the binding is required by the surrounding UI
2631
- - `keyHintIfBound(keybinding, description)` - Formats the hint only when the action has an effective key list; use it for optional affordances and conditionally compose parentheses or separators
2632
- - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
2633
- - `rawKeyHint(key, description)` - Format a raw key string
2634
-
2635
- Use namespaced keybinding ids:
2636
- - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
2637
- - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
2638
-
2639
- For the exhaustive list of keybinding ids and defaults, see [Keybindings](/keybindings). `keybindings.json` uses those same namespaced ids.
2640
-
2641
- Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`.
2642
-
2643
- #### Best Practices
2644
-
2645
- - Use `Text` with padding `(0, 0)`. The default Box handles padding.
2646
- - Use `\n` for multi-line content.
2647
- - Handle `isPartial` for streaming progress.
2648
- - Support `expanded` for detail on demand.
2649
- - Keep default view compact.
2650
- - Read `context.args` in `renderResult` instead of copying args into `context.state`.
2651
- - Use `context.state` only for data that must be shared across call and result slots.
2652
- - Reuse `context.lastComponent` when the same component instance can be updated in place.
2653
- - Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background.
2654
-
2655
- #### Fallback
2656
-
2657
- If a slot renderer is not defined or throws:
2658
- - `renderCall`: Shows the tool name
2659
- - `renderResult`: Shows raw text from `content`
2660
-
2661
- ## Custom UI
2662
-
2663
- Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
2664
-
2665
- **For custom components, see [TUI components](/tui)** which has copy-paste patterns for:
2666
- - Selection dialogs (SelectList)
2667
- - Async operations with cancel (BorderedLoader)
2668
- - Settings toggles (SettingsList)
2669
- - Status indicators (setStatus)
2670
- - Working message, visibility, and indicator from accepted prompt startup through active turns (`setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator`)
2671
- - Widgets above/below editor (setWidget)
2672
- - Autocomplete providers layered on top of built-in slash/path completion (addAutocompleteProvider)
2673
- - Custom footers (setFooter)
2674
-
2675
- ### Dialogs
2676
-
2677
- ```typescript
2678
- // Select from options
2679
- const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
2680
-
2681
- // Confirm dialog
2682
- const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
2683
-
2684
- // Text input
2685
- const name = await ctx.ui.input("Name:", "placeholder");
2686
-
2687
- // Multi-line editor
2688
- const text = await ctx.ui.editor("Edit:", "prefilled text");
2689
-
2690
- // Notification (non-blocking)
2691
- ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
2692
- ```
2693
-
2694
- Notifications emitted while extensions load or startup is in progress always appear below the startup `RESOURCES` disclosure line, never above it.
2695
-
2696
- #### Timed Dialogs with Countdown
2697
-
2698
- Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
2699
-
2700
- ```typescript
2701
- // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
2702
- const confirmed = await ctx.ui.confirm(
2703
- "Timed Confirmation",
2704
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2705
- { timeout: 5000 }
2706
- );
2707
-
2708
- if (confirmed) {
2709
- // User confirmed
2710
- } else {
2711
- // User cancelled or timed out
2712
- }
2713
- ```
2714
-
2715
- **Return values on timeout:**
2716
- - `select()` returns `undefined`
2717
- - `confirm()` returns `false`
2718
- - `input()` returns `undefined`
667
+ Moved to [Extension UI](/extensions/ui#timed-dialogs-with-countdown).
2719
668
 
2720
669
  #### Manual Dismissal with AbortSignal
2721
670
 
2722
- For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
2723
-
2724
- ```typescript
2725
- const controller = new AbortController();
2726
- const timeoutId = setTimeout(() => controller.abort(), 5000);
2727
-
2728
- const confirmed = await ctx.ui.confirm(
2729
- "Timed Confirmation",
2730
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2731
- { signal: controller.signal }
2732
- );
2733
-
2734
- clearTimeout(timeoutId);
2735
-
2736
- if (confirmed) {
2737
- // User confirmed
2738
- } else if (controller.signal.aborted) {
2739
- // Dialog timed out
2740
- } else {
2741
- // User cancelled (pressed Escape or selected "No")
2742
- }
2743
- ```
2744
-
2745
- See [examples/extensions/timed-confirm.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/timed-confirm.ts) for complete examples.
671
+ Moved to [Extension UI](/extensions/ui#manual-dismissal-with-abortsignal).
2746
672
 
2747
673
  ### Widgets, Status, and Footer
2748
674
 
2749
- ```typescript
2750
- // Status in footer (persistent until cleared)
2751
- ctx.ui.setStatus("my-ext", "Processing...");
2752
- ctx.ui.setStatus("my-ext", undefined); // Clear
2753
-
2754
- // Working loader customization (active from accepted prompt startup through the agent turn)
2755
- ctx.ui.setWorkingMessage("Thinking deeply...");
2756
- ctx.ui.setWorkingMessage(); // Restore default
2757
- ctx.ui.setWorkingVisible(false); // Hide the built-in working indicator entirely
2758
- ctx.ui.setWorkingVisible(true); // Show the built-in working indicator
2759
-
2760
- // Working indicator customization (same lifecycle; see TUI Pattern 4b)
2761
- ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
2762
- ctx.ui.setWorkingIndicator({
2763
- frames: [
2764
- ctx.ui.theme.fg("dim", "·"),
2765
- ctx.ui.theme.fg("muted", "•"),
2766
- ctx.ui.theme.fg("accent", "●"),
2767
- ctx.ui.theme.fg("muted", "•"),
2768
- ],
2769
- intervalMs: 120,
2770
- });
2771
- ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
2772
- ctx.ui.setWorkingIndicator(); // Restore the default one-cell ∀ luminance ramp
2773
- // The working status uses a standalone row by default. A CustomEditor can opt
2774
- // into placing it in the top border with { embedWorkingStatus: true }.
2775
-
2776
- // Widget above editor (default)
2777
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2778
- // Widget below editor
2779
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2780
- ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
2781
- ctx.ui.setWidget("my-widget", undefined); // Clear
2782
-
2783
- // Custom footer (replaces built-in footer entirely)
2784
- ctx.ui.setFooter((tui, theme) => ({
2785
- render(width) { return [theme.fg("dim", "Custom footer")]; },
2786
- invalidate() {},
2787
- }));
2788
- ctx.ui.setFooter(undefined); // Restore built-in footer
2789
-
2790
- // Terminal title
2791
- ctx.ui.setTitle("atomic - my-project");
2792
-
2793
- // Editor text
2794
- ctx.ui.setEditorText("Prefill text");
2795
- const current = ctx.ui.getEditorText();
2796
-
2797
- // Paste into editor (triggers paste handling, including collapse for large content)
2798
- ctx.ui.pasteToEditor("pasted content");
2799
-
2800
- // Stack custom autocomplete behavior on top of the built-in provider
2801
- ctx.ui.addAutocompleteProvider((current) => ({
2802
- async getSuggestions(lines, line, col, options) {
2803
- const beforeCursor = (lines[line] ?? "").slice(0, col);
2804
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2805
- if (!match) {
2806
- return current.getSuggestions(lines, line, col, options);
2807
- }
2808
-
2809
- return {
2810
- prefix: `#${match[1] ?? ""}`,
2811
- items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }],
2812
- };
2813
- },
2814
- applyCompletion(lines, line, col, item, prefix) {
2815
- return current.applyCompletion(lines, line, col, item, prefix);
2816
- },
2817
- shouldTriggerFileCompletion(lines, line, col) {
2818
- return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true;
2819
- },
2820
- }));
2821
-
2822
- // Tool output expansion
2823
- const wasExpanded = ctx.ui.getToolsExpanded();
2824
- ctx.ui.setToolsExpanded(true);
2825
- ctx.ui.setToolsExpanded(wasExpanded);
2826
-
2827
- // Custom editor (vim mode, emacs mode, etc.)
2828
- ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
2829
- const currentEditor = ctx.ui.getEditorComponent();
2830
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2831
- new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings))
2832
- );
2833
- ctx.ui.setEditorComponent(undefined); // Restore default editor
2834
-
2835
- // Theme management (see themes.md for creating themes)
2836
- const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
2837
- const lightTheme = ctx.ui.getTheme("light"); // Load without switching
2838
- const result = ctx.ui.setTheme("light"); // Switch by name
2839
- if (!result.success) {
2840
- ctx.ui.notify(`Failed: ${result.error}`, "error");
2841
- }
2842
- ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
2843
- ctx.ui.theme.fg("accent", "styled text"); // Access current theme
2844
- ```
2845
-
2846
- Calling `setToolsExpanded()` with the current value is a no-op.
2847
-
2848
- Atomic's default working indicator keeps the literal one-cell `∀` fixed while following the active theme's optional `workingIndicator` tone overrides through a dark → accent → bright/bold → accent → dark ramp every 88ms. Any omitted tones are derived from selected-surface, `accent`, and `text` roles. `NO_COLOR` keeps regular/bold activity without foreground-color escapes, and `ATOMIC_REDUCED_MOTION=1` uses a static regular accent `∀` without a timer. Custom working-indicator frames and intervals are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`.
2849
-
2850
- These APIs customize presentation only; they do not start work or emit an extension stream event before prompt startup. See [Working Indicator Customization](/tui#pattern-4b-working-indicator-customization) for accepted-prompt, pre-stream, and agent-turn handoff timing.
675
+ Moved to [Extension UI](/extensions/ui#widgets-status-and-footer).
2851
676
 
2852
677
  ### Autocomplete Providers
2853
678
 
2854
- Use `ctx.ui.addAutocompleteProvider()` to stack custom autocomplete logic on top of the built-in slash-command and path provider.
2855
-
2856
- Typical pattern:
2857
-
2858
- - inspect the text before the cursor
2859
- - return your own suggestions when your extension-specific syntax matches
2860
- - otherwise delegate to `current.getSuggestions(...)`
2861
- - delegate `applyCompletion(...)` unless you need custom insertion behavior
2862
-
2863
- ```typescript
2864
- pi.on("session_start", (_event, ctx) => {
2865
- ctx.ui.addAutocompleteProvider((current) => ({
2866
- async getSuggestions(lines, cursorLine, cursorCol, options) {
2867
- const line = lines[cursorLine] ?? "";
2868
- const beforeCursor = line.slice(0, cursorCol);
2869
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2870
- if (!match) {
2871
- return current.getSuggestions(lines, cursorLine, cursorCol, options);
2872
- }
2873
-
2874
- return {
2875
- prefix: `#${match[1] ?? ""}`,
2876
- items: [
2877
- { value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" },
2878
- { value: "#2753", label: "#2753", description: "Reload stale resource settings" },
2879
- ],
2880
- };
2881
- },
2882
-
2883
- applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
2884
- return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
2885
- },
2886
-
2887
- shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
2888
- return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
2889
- },
2890
- }));
2891
- });
2892
- ```
2893
-
2894
- See [github-issue-autocomplete.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/github-issue-autocomplete.ts) for a complete example that preloads the latest open GitHub issues with `gh issue list` and filters them locally for fast `#...` completion. It requires GitHub CLI (`gh`) and a GitHub repository checkout.
679
+ Moved to [Extension UI](/extensions/ui#autocomplete-providers).
2895
680
 
2896
681
  ### Custom Components
2897
682
 
2898
- For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
2899
-
2900
- ```typescript
2901
- import { Text, type Component } from "@earendil-works/pi-tui";
2902
-
2903
- class ConfirmPrompt implements Component {
2904
- render(width: number): string[] {
2905
- return new Text("Enter Confirm · Escape Cancel", 1, 1).render(width);
2906
- }
2907
-
2908
- invalidate(): void {}
2909
-
2910
- handleInput(data: string): boolean {
2911
- if (data === "\r") {
2912
- this.done(true);
2913
- return true;
2914
- }
2915
- if (data === "\x1b") {
2916
- this.done(false);
2917
- return true;
2918
- }
2919
- return false;
2920
- }
2921
-
2922
- constructor(private readonly done: (value: boolean) => void) {}
2923
- }
2924
-
2925
- const result = await ctx.ui.custom<boolean>((_tui, _theme, _keybindings, done) => {
2926
- return new ConfirmPrompt(done);
2927
- });
2928
-
2929
- if (result) {
2930
- // User pressed Enter
2931
- }
2932
- ```
2933
-
2934
- The callback receives:
2935
- - `tui` - TUI instance (for screen dimensions, focus management)
2936
- - `theme` - Current theme for styling
2937
- - `keybindings` - App keybinding manager (for checking shortcuts)
2938
- - `done(value)` - Call to close component and return value
2939
-
2940
- Pass `{ signal }` to dismiss the custom UI if an operation is aborted; the returned promise rejects with the signal reason.
2941
- Custom component `handleInput` methods must return `true` when they consume an input and `false` (or `undefined`) when they do not. In fullscreen mode, an unhandled viewport key continues to the transcript; remote components also fall through on a failed or timed-out reply.
2942
-
2943
- Custom component `handleInput` methods must return `true` when they consume an input and `false` or `undefined` when they do not. In fullscreen mode, an unhandled viewport key continues to the transcript; remote components also fall through on a failed or timed-out reply. Return `true` for a handled key so it is not applied twice.
2944
-
2945
- A handler that returns a promise is judged when it settles: only a resolved `true` consumes the key, while `false`, `undefined`, and a rejection fall through to the viewport. A component with no `handleInput` declines everything, so viewport keys still scroll the transcript behind it.
2946
-
2947
- Pass `{ handlesCtrlC: true }` when the component binds Ctrl+C itself (cancel, skip, close). In isolated interactive sessions the host otherwise closes a component that owns input on the first Ctrl+C, so that a component which never resolves cannot trap the keyboard. See [Interactive callback isolation](#interactive-callback-isolation).
2948
-
2949
- See [TUI components](/tui) for the full component API.
683
+ Moved to [Extension UI](/extensions/ui#custom-components).
2950
684
 
2951
685
  #### Overlay Mode (Experimental)
2952
686
 
2953
- Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
2954
-
2955
- ```typescript
2956
- const result = await ctx.ui.custom<string | null>(
2957
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2958
- { overlay: true }
2959
- );
2960
- ```
2961
-
2962
- For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control visibility programmatically:
2963
-
2964
- ```typescript
2965
- const result = await ctx.ui.custom<string | null>(
2966
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2967
- {
2968
- overlay: true,
2969
- overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
2970
- onHandle: (handle) => { /* handle.setHidden(true/false) */ }
2971
- }
2972
- );
2973
- ```
2974
-
2975
- See [TUI components](/tui) for the full `OverlayOptions` API and [overlay-qa-tests.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/overlay-qa-tests.ts) for examples.
2976
-
2977
- Pass `{ reserveTranscriptRows: true }` for a blocking bottom-anchored dialog. A reserving overlay must set `overlayOptions.anchor` to `bottom-left`, `bottom-center`, or `bottom-right`; `row` and a nonzero `offsetY` are rejected because they invalidate the transcript-intersection model. Horizontal placement options remain supported. An overlay is composited over the transcript rather than measured into the layout, so without this option a tall dialog can cover the whole screen and the transcript rows it covers can never be scrolled above it. With it, the host bounds the overlay so at least six transcript rows stay visible. Top and bottom margins limit the wrapper before pi-tui composition, preventing a second fixed-head crop. Numeric and percentage `maxHeight` values are also resolved before active-row windowing and removed from the options passed to pi-tui. The host computes each visible bottom overlay's real intersection with the transcript and reserves the connected covered suffix once, so scrolling to the end keeps the newest output readable. A measured height change on mount or resize requests one automatic settling repaint. Margins, overlapping overlays, resize, and temporary visibility changes are reflected each frame. A temporarily hidden overlay — through `OverlayHandle.setHidden(true)` or a false `OverlayOptions.visible` result — contributes no intersection until it becomes visible again. Permanent handle removal, closure, and raw host removal release that exact overlay's registration; the shared reserve remains until its final overlay leaves. Leave the option unset for an overlay that is meant to take the screen, such as a full-screen graph. The built-in `ask_user_question` dialog sets it.
2978
-
2979
- ```typescript
2980
- const result = await ctx.ui.custom<string | null>(
2981
- (tui, theme, keybindings, done) => new MyDialog({ onClose: done }),
2982
- {
2983
- overlay: true,
2984
- reserveTranscriptRows: true,
2985
- overlayOptions: { anchor: "bottom-center", width: "100%" },
2986
- }
2987
- );
2988
- ```
2989
-
2990
- A component mounted with `reserveTranscriptRows` always releases configured fullscreen transcript actions and vertical wheel input to the host viewport, including while a nested input has focus. The component keeps all other keyboard and mouse input, including text editing, arrows, confirmation, cancellation, and clicks. This rule applies only to reserving overlays; other focused overlays still receive page and wheel input first and can keep it by returning `true`.
2991
-
2992
- Bounding a tall dialog means dropping rows, and the host would otherwise have to guess which. Embed `OVERLAY_ACTIVE_ROW_MARKER` in the line your component most needs kept — the selected row of a list — and the host places what it keeps around that row instead of taking a fixed head, even when the effective `maxHeight` is only one row. The mark is a zero-width APC sequence that `visibleWidth` measures as zero, terminated with ST as ECMA-48 requires. The renderer strips it centrally, in the last transform over the composited screen before it is written out, so it never reaches the terminal — from a reserving overlay, an ordinary overlay, an inline mount, a widget, or a workflow stage chat alike. Embed it once per frame; the host uses the first line that carries it. Put it anywhere on that line: a mark buried mid-line is removed just as a trailing one is. The `ask_user_question` dialog marks every active selectable row, including single- and multi-select options, Next, Submit, Cancel, and inline sentinel rows. Focused pi-tui inputs also anchor the bound through their cursor marker, so arrow keys and text input stay visible on a 16-row terminal.
2993
-
2994
- ```typescript
2995
- import { OVERLAY_ACTIVE_ROW_MARKER } from "@bastani/atomic";
2996
-
2997
- render(width: number): string[] {
2998
- return this.items.map((item, index) =>
2999
- index === this.selected ? `${this.row(item, width)}${OVERLAY_ACTIVE_ROW_MARKER}` : this.row(item, width),
3000
- );
3001
- }
3002
- ```
687
+ Moved to [Extension UI](/extensions/ui#overlay-mode-experimental).
3003
688
 
3004
689
  ### Custom Editor
3005
690
 
3006
- Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
3007
-
3008
- ```typescript
3009
- import { CustomEditor, type ExtensionAPI } from "@bastani/atomic";
3010
- import { matchesKey } from "@earendil-works/pi-tui";
3011
-
3012
- class VimEditor extends CustomEditor {
3013
- private mode: "normal" | "insert" = "insert";
3014
-
3015
- handleInput(data: string): boolean {
3016
- if (matchesKey(data, "escape") && this.mode === "insert") {
3017
- this.mode = "normal";
3018
- return true;
3019
- }
3020
- if (this.mode === "normal" && data === "i") {
3021
- this.mode = "insert";
3022
- return true;
3023
- }
3024
- return super.handleInput(data); // App keybindings + text editing
3025
- }
3026
- }
3027
-
3028
- export default function (pi: ExtensionAPI) {
3029
- pi.on("session_start", (_event, ctx) => {
3030
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
3031
- new VimEditor(tui, theme, keybindings)
3032
- );
3033
- });
3034
- }
3035
- ```
3036
-
3037
- **Key points:**
3038
- - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
3039
- - Call `super.handleInput(data)` for keys you don't handle
3040
- - Editors keep the standalone working row by default. Pass `{ embedWorkingStatus: true }` as the fourth `CustomEditor` constructor argument to opt into the editor-border spinner.
3041
- - Factory receives `tui`, `theme`, and `keybindings` from the app
3042
- - Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor
3043
- - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
3044
- - When a custom editor installed through `ctx.ui.setEditorComponent()` exposes `setAutocompleteMaxVisible()`, Atomic initializes it from the active `autocompleteMaxVisible` setting.
3045
-
3046
- To compose with another extension that already replaced the editor, capture the previous factory before setting yours:
3047
-
3048
- ```typescript
3049
- const previous = ctx.ui.getEditorComponent();
3050
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
3051
- new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) })
3052
- );
3053
- ```
3054
-
3055
- See [TUI components](/tui) Pattern 7 for a complete example with mode indicator.
691
+ Moved to [Extension UI](/extensions/ui#custom-editor).
3056
692
 
3057
693
  ### Message Rendering
3058
694
 
3059
- Register a custom renderer for messages with your `customType`:
3060
-
3061
- ```typescript
3062
- import { Text } from "@earendil-works/pi-tui";
3063
-
3064
- pi.registerMessageRenderer("my-extension", (message, options, theme) => {
3065
- const { expanded, outputPad } = options;
3066
- let text = theme.fg("accent", `[${message.customType}] `);
3067
- text += message.content;
3068
-
3069
- if (expanded && message.details) {
3070
- text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
3071
- }
3072
-
3073
- return new Text(text, outputPad, 0);
3074
- });
3075
- ```
3076
-
3077
- Messages are sent via `pi.sendMessage()`:
3078
-
3079
- ```typescript
3080
- pi.sendMessage({
3081
- customType: "my-extension", // Matches registerMessageRenderer
3082
- content: "Status update",
3083
- display: true, // Show in TUI
3084
- details: { ... }, // Available in renderer
3085
- });
3086
- ```
695
+ Moved to [Extension UI](/extensions/ui#message-rendering).
3087
696
 
3088
697
  ### Theme Colors
3089
698
 
3090
- All render functions receive a `theme` object. See [Themes](/themes) for creating custom themes and the full color palette.
3091
-
3092
- ```typescript
3093
- // Foreground colors
3094
- theme.fg("toolTitle", text) // Tool names
3095
- theme.fg("accent", text) // Highlights
3096
- theme.fg("success", text) // Success (green)
3097
- theme.fg("error", text) // Errors (red)
3098
- theme.fg("warning", text) // Warnings (yellow)
3099
- theme.fg("muted", text) // Secondary text
3100
- theme.fg("dim", text) // Tertiary text
3101
-
3102
- // Text styles
3103
- theme.bold(text)
3104
- theme.italic(text)
3105
- theme.strikethrough(text)
3106
- ```
3107
-
3108
- For syntax highlighting in custom tool renderers:
3109
-
3110
- ```typescript
3111
- import { highlightCode, getLanguageFromPath } from "@bastani/atomic";
3112
-
3113
- // Highlight code with explicit language
3114
- const highlighted = highlightCode("const x = 1;", "typescript", theme);
3115
-
3116
- // Auto-detect language from file path
3117
- const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
3118
- const highlighted = highlightCode(code, lang, theme);
3119
- ```
699
+ Moved to [Extension UI](/extensions/ui#theme-colors).
3120
700
 
3121
701
  ## Error Handling
3122
702
 
3123
- - Extension errors are logged, agent continues
3124
- - `tool_call` errors block the tool (fail-safe)
3125
- - Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
703
+ Moved to [Extension API reference](/extensions/api-reference#error-handling).
3126
704
 
3127
705
  ## Mode Behavior
3128
706
 
@@ -3137,84 +715,8 @@ In non-interactive modes, check `ctx.hasUI` before using UI methods.
3137
715
 
3138
716
  ## Examples Reference
3139
717
 
3140
- All examples in [examples/extensions/](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions).
3141
-
3142
- | Example | Description | Key APIs |
3143
- |---------|-------------|----------|
3144
- | **Tools** |||
3145
- | `hello.ts` | Minimal tool registration | `registerTool` |
3146
- | `question.ts` | Width-wrapped single-question custom UI with option descriptions and typed answers | `registerTool`, `ui.custom` |
3147
- | `questionnaire.ts` | Width-wrapped multi-step wizard with tab navigation and typed answers | `registerTool`, `ui.custom` |
3148
- | `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
3149
- | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
3150
- | `structured-output.ts` | Opt-in schema-specific `structured_output` tool using the canonical factory | `createStructuredOutputTool`, `registerTool`, terminating tool results |
3151
- | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
3152
- | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
3153
- | **Commands** |||
3154
- | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
3155
- | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
3156
- | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
3157
- | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
3158
- | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
3159
- | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
3160
- | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
3161
- | **Events & Gates** |||
3162
- | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
3163
- | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
3164
- | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
3165
- | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
3166
- | `input-transform.ts` | Transform user input | `on("input")` |
3167
- | `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
3168
- | `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
3169
- | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
3170
- | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
3171
- | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
3172
- | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
3173
- | `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
3174
- | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
3175
- | **Compaction & Sessions** |||
3176
- | `custom-compaction.ts` | Offline compacted-text override | `on("session_before_compact")` |
3177
- | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
3178
- | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` |
3179
- | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
3180
- | **UI Components** |||
3181
- | `status-line.ts` | Footer status indicator | `setStatus`, session events |
3182
- | `working-indicator.ts` | Customize the Working indicator used during prompt startup and active turns | `setWorkingIndicator`, `registerCommand` |
3183
- | `github-issue-autocomplete.ts` | Add `#1234` issue completions on top of built-in autocomplete by preloading recent open issues from `gh issue list` | `addAutocompleteProvider`, `on("session_start")`, `exec` |
3184
- | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
3185
- | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
3186
- | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
3187
- | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
3188
- | `widget-placement.ts` | Widget above/below editor | `setWidget` |
3189
- | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
3190
- | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
3191
- | `notify.ts` | Simple notifications | `ui.notify` |
3192
- | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
3193
- | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
3194
- | **Complex Extensions** |||
3195
- | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
3196
- | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
3197
- | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
3198
- | **Remote & Sandbox** |||
3199
- | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
3200
- | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
3201
- | `sandbox/` | Sandboxed tool execution | Tool operations |
3202
- | `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
3203
- | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
3204
- | **Games** |||
3205
- | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
3206
- | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
3207
- | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
3208
- | **Providers** |||
3209
- | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
3210
- | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
3211
- | **Messages & Communication** |||
3212
- | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
3213
- | `event-bus.ts` | Inter-extension events | `pi.events` |
3214
- | **Session Metadata** |||
3215
- | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
3216
- | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
3217
- | **Misc** |||
3218
- | `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
3219
- | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
3220
- | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |
718
+ Moved to [Extension examples](/extensions/examples#examples-reference).
719
+
720
+ ## Workflow activity and lifecycle hooks
721
+
722
+ Moved to [Extension events](/extensions/events#workflow-activity-and-lifecycle-hooks).