subharness 0.0.7 → 0.0.10

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 (297) hide show
  1. package/README.md +40 -9
  2. package/dist/adapters/claude-events.d.ts +71 -0
  3. package/dist/adapters/claude-events.js +860 -0
  4. package/dist/adapters/claude-events.js.map +1 -0
  5. package/dist/adapters/claude-worker-client.d.ts +11 -0
  6. package/dist/adapters/claude-worker-client.js +219 -5
  7. package/dist/adapters/claude-worker-client.js.map +1 -1
  8. package/dist/adapters/claude-worker-protocol.d.ts +58 -0
  9. package/dist/adapters/claude-worker-protocol.js.map +1 -1
  10. package/dist/adapters/claude-worker.js +48 -3
  11. package/dist/adapters/claude-worker.js.map +1 -1
  12. package/dist/adapters/claude.d.ts +5 -1
  13. package/dist/adapters/claude.js +14 -2
  14. package/dist/adapters/claude.js.map +1 -1
  15. package/dist/adapters/codex-events.d.ts +52 -0
  16. package/dist/adapters/codex-events.js +672 -0
  17. package/dist/adapters/codex-events.js.map +1 -0
  18. package/dist/adapters/codex-turn-failure.d.ts +2 -0
  19. package/dist/adapters/codex-turn-failure.js +116 -0
  20. package/dist/adapters/codex-turn-failure.js.map +1 -0
  21. package/dist/adapters/codex.js +44 -7
  22. package/dist/adapters/codex.js.map +1 -1
  23. package/dist/adapters/copilot-events.d.ts +68 -0
  24. package/dist/adapters/copilot-events.js +650 -0
  25. package/dist/adapters/copilot-events.js.map +1 -0
  26. package/dist/adapters/copilot.js +24 -4
  27. package/dist/adapters/copilot.js.map +1 -1
  28. package/dist/adapters/cursor-acp-events.d.ts +36 -0
  29. package/dist/adapters/cursor-acp-events.js +251 -0
  30. package/dist/adapters/cursor-acp-events.js.map +1 -0
  31. package/dist/adapters/cursor-cli-session.d.ts +1 -0
  32. package/dist/adapters/cursor-cli-session.js +26 -5
  33. package/dist/adapters/cursor-cli-session.js.map +1 -1
  34. package/dist/adapters/cursor-cli.js +5 -0
  35. package/dist/adapters/cursor-cli.js.map +1 -1
  36. package/dist/adapters/cursor-sdk-events.d.ts +30 -0
  37. package/dist/adapters/cursor-sdk-events.js +233 -0
  38. package/dist/adapters/cursor-sdk-events.js.map +1 -0
  39. package/dist/adapters/cursor-session.js +56 -7
  40. package/dist/adapters/cursor-session.js.map +1 -1
  41. package/dist/adapters/cursor-startup.js +8 -2
  42. package/dist/adapters/cursor-startup.js.map +1 -1
  43. package/dist/adapters/event-normalizer.d.ts +57 -0
  44. package/dist/adapters/event-normalizer.js +143 -0
  45. package/dist/adapters/event-normalizer.js.map +1 -0
  46. package/dist/adapters/event-secrets.d.ts +17 -0
  47. package/dist/adapters/event-secrets.js +28 -0
  48. package/dist/adapters/event-secrets.js.map +1 -0
  49. package/dist/adapters/event-types.d.ts +58 -0
  50. package/dist/adapters/event-types.js +2 -0
  51. package/dist/adapters/event-types.js.map +1 -0
  52. package/dist/adapters/fx-events.d.ts +37 -0
  53. package/dist/adapters/fx-events.js +393 -0
  54. package/dist/adapters/fx-events.js.map +1 -0
  55. package/dist/adapters/fx-rpc.d.ts +2 -0
  56. package/dist/adapters/fx-rpc.js +11 -5
  57. package/dist/adapters/fx-rpc.js.map +1 -1
  58. package/dist/adapters/fx.js +73 -8
  59. package/dist/adapters/fx.js.map +1 -1
  60. package/dist/adapters/opencode-events.d.ts +58 -0
  61. package/dist/adapters/opencode-events.js +653 -0
  62. package/dist/adapters/opencode-events.js.map +1 -0
  63. package/dist/adapters/opencode-http.d.ts +1 -0
  64. package/dist/adapters/opencode-http.js +8 -7
  65. package/dist/adapters/opencode-http.js.map +1 -1
  66. package/dist/adapters/opencode.js +50 -9
  67. package/dist/adapters/opencode.js.map +1 -1
  68. package/dist/adapters/rpc.d.ts +2 -0
  69. package/dist/adapters/rpc.js +11 -5
  70. package/dist/adapters/rpc.js.map +1 -1
  71. package/dist/adapters/types.d.ts +2 -0
  72. package/dist/adapters/types.js.map +1 -1
  73. package/dist/cli/args.d.ts +6 -1
  74. package/dist/cli/args.js +63 -5
  75. package/dist/cli/args.js.map +1 -1
  76. package/dist/cli/catalog-worker.js +3 -2
  77. package/dist/cli/catalog-worker.js.map +1 -1
  78. package/dist/cli/dashboard-client.d.ts +1 -0
  79. package/dist/cli/dashboard-client.js +13 -1
  80. package/dist/cli/dashboard-client.js.map +1 -1
  81. package/dist/cli/dashboard-controller.js +6 -7
  82. package/dist/cli/dashboard-controller.js.map +1 -1
  83. package/dist/cli/dashboard-detail-view.d.ts +14 -8
  84. package/dist/cli/dashboard-detail-view.js +15 -44
  85. package/dist/cli/dashboard-detail-view.js.map +1 -1
  86. package/dist/cli/dashboard-history-view.d.ts +3 -12
  87. package/dist/cli/dashboard-history-view.js +18 -82
  88. package/dist/cli/dashboard-history-view.js.map +1 -1
  89. package/dist/cli/dashboard-live.d.ts +32 -0
  90. package/dist/cli/dashboard-live.js +177 -0
  91. package/dist/cli/dashboard-live.js.map +1 -0
  92. package/dist/cli/dashboard-renderer.d.ts +21 -1
  93. package/dist/cli/dashboard-renderer.js +85 -21
  94. package/dist/cli/dashboard-renderer.js.map +1 -1
  95. package/dist/cli/dashboard-steps.d.ts +53 -0
  96. package/dist/cli/dashboard-steps.js +157 -0
  97. package/dist/cli/dashboard-steps.js.map +1 -0
  98. package/dist/cli/dashboard-task-format.d.ts +15 -0
  99. package/dist/cli/dashboard-task-format.js +119 -0
  100. package/dist/cli/dashboard-task-format.js.map +1 -0
  101. package/dist/cli/dashboard-task-view.d.ts +66 -0
  102. package/dist/cli/dashboard-task-view.js +325 -0
  103. package/dist/cli/dashboard-task-view.js.map +1 -0
  104. package/dist/cli/dashboard.d.ts +2 -0
  105. package/dist/cli/dashboard.js +71 -6
  106. package/dist/cli/dashboard.js.map +1 -1
  107. package/dist/cli/extensions-client.d.ts +23 -0
  108. package/dist/cli/extensions-client.js +147 -0
  109. package/dist/cli/extensions-client.js.map +1 -0
  110. package/dist/cli/extensions.d.ts +15 -0
  111. package/dist/cli/extensions.js +187 -0
  112. package/dist/cli/extensions.js.map +1 -0
  113. package/dist/cli/help.d.ts +1 -0
  114. package/dist/cli/help.js +34 -6
  115. package/dist/cli/help.js.map +1 -1
  116. package/dist/cli/main.js +100 -10
  117. package/dist/cli/main.js.map +1 -1
  118. package/dist/cli/output.js +5 -1
  119. package/dist/cli/output.js.map +1 -1
  120. package/dist/config/access.d.ts +2 -1
  121. package/dist/config/access.js +18 -7
  122. package/dist/config/access.js.map +1 -1
  123. package/dist/config/loader.d.ts +2 -0
  124. package/dist/config/loader.js +20 -6
  125. package/dist/config/loader.js.map +1 -1
  126. package/dist/config/project-context.d.ts +9 -0
  127. package/dist/config/project-context.js +41 -0
  128. package/dist/config/project-context.js.map +1 -0
  129. package/dist/config/resolve-access.d.ts +2 -1
  130. package/dist/config/resolve-access.js +5 -2
  131. package/dist/config/resolve-access.js.map +1 -1
  132. package/dist/events/content.d.ts +43 -0
  133. package/dist/events/content.js +249 -0
  134. package/dist/events/content.js.map +1 -0
  135. package/dist/events/queue.d.ts +59 -0
  136. package/dist/events/queue.js +144 -0
  137. package/dist/events/queue.js.map +1 -0
  138. package/dist/events/validate.d.ts +22 -0
  139. package/dist/events/validate.js +542 -0
  140. package/dist/events/validate.js.map +1 -0
  141. package/dist/extensions/catalog.d.ts +34 -0
  142. package/dist/extensions/catalog.js +103 -0
  143. package/dist/extensions/catalog.js.map +1 -0
  144. package/dist/extensions/child-protocol.d.ts +38 -0
  145. package/dist/extensions/child-protocol.js +2 -0
  146. package/dist/extensions/child-protocol.js.map +1 -0
  147. package/dist/extensions/child.d.ts +1 -0
  148. package/dist/extensions/child.js +125 -0
  149. package/dist/extensions/child.js.map +1 -0
  150. package/dist/extensions/consent.d.ts +13 -0
  151. package/dist/extensions/consent.js +204 -0
  152. package/dist/extensions/consent.js.map +1 -0
  153. package/dist/extensions/environment.d.ts +1 -0
  154. package/dist/extensions/environment.js +12 -0
  155. package/dist/extensions/environment.js.map +1 -0
  156. package/dist/extensions/identity.d.ts +9 -0
  157. package/dist/extensions/identity.js +28 -0
  158. package/dist/extensions/identity.js.map +1 -0
  159. package/dist/extensions/log.d.ts +5 -0
  160. package/dist/extensions/log.js +80 -0
  161. package/dist/extensions/log.js.map +1 -0
  162. package/dist/extensions/manifest.d.ts +7 -0
  163. package/dist/extensions/manifest.js +213 -0
  164. package/dist/extensions/manifest.js.map +1 -0
  165. package/dist/extensions/types.d.ts +24 -0
  166. package/dist/extensions/types.js +2 -0
  167. package/dist/extensions/types.js.map +1 -0
  168. package/dist/extensions.d.ts +5 -0
  169. package/dist/extensions.js +2 -0
  170. package/dist/extensions.js.map +1 -0
  171. package/dist/index.d.ts +1 -0
  172. package/dist/index.js.map +1 -1
  173. package/dist/runtime/approval-registry.d.ts +6 -2
  174. package/dist/runtime/approval-registry.js +31 -3
  175. package/dist/runtime/approval-registry.js.map +1 -1
  176. package/dist/runtime/capture.d.ts +4 -4
  177. package/dist/runtime/capture.js +59 -15
  178. package/dist/runtime/capture.js.map +1 -1
  179. package/dist/runtime/catalog.d.ts +6 -1
  180. package/dist/runtime/catalog.js +1 -1
  181. package/dist/runtime/catalog.js.map +1 -1
  182. package/dist/runtime/coordinator.d.ts +9 -4
  183. package/dist/runtime/coordinator.js +130 -27
  184. package/dist/runtime/coordinator.js.map +1 -1
  185. package/dist/runtime/daemon.js +9 -1
  186. package/dist/runtime/daemon.js.map +1 -1
  187. package/dist/runtime/dashboard.d.ts +4 -0
  188. package/dist/runtime/dashboard.js +8 -0
  189. package/dist/runtime/dashboard.js.map +1 -1
  190. package/dist/runtime/definition.d.ts +1 -1
  191. package/dist/runtime/definition.js +2 -2
  192. package/dist/runtime/definition.js.map +1 -1
  193. package/dist/runtime/event-operation.d.ts +41 -0
  194. package/dist/runtime/event-operation.js +290 -0
  195. package/dist/runtime/event-operation.js.map +1 -0
  196. package/dist/runtime/event-owner.d.ts +94 -0
  197. package/dist/runtime/event-owner.js +429 -0
  198. package/dist/runtime/event-owner.js.map +1 -0
  199. package/dist/runtime/event-source.d.ts +39 -0
  200. package/dist/runtime/event-source.js +344 -0
  201. package/dist/runtime/event-source.js.map +1 -0
  202. package/dist/runtime/extension-instance.d.ts +61 -0
  203. package/dist/runtime/extension-instance.js +356 -0
  204. package/dist/runtime/extension-instance.js.map +1 -0
  205. package/dist/runtime/extension-protocol.d.ts +47 -0
  206. package/dist/runtime/extension-protocol.js +33 -0
  207. package/dist/runtime/extension-protocol.js.map +1 -0
  208. package/dist/runtime/extension-service.d.ts +10 -0
  209. package/dist/runtime/extension-service.js +35 -0
  210. package/dist/runtime/extension-service.js.map +1 -0
  211. package/dist/runtime/extension-supervisor.d.ts +33 -0
  212. package/dist/runtime/extension-supervisor.js +254 -0
  213. package/dist/runtime/extension-supervisor.js.map +1 -0
  214. package/dist/runtime/select-native.d.ts +3 -1
  215. package/dist/runtime/select-native.js +32 -5
  216. package/dist/runtime/select-native.js.map +1 -1
  217. package/dist/runtime/service.d.ts +5 -0
  218. package/dist/runtime/service.js +113 -15
  219. package/dist/runtime/service.js.map +1 -1
  220. package/dist/runtime/session-event-wire.d.ts +29 -0
  221. package/dist/runtime/session-event-wire.js +2 -0
  222. package/dist/runtime/session-event-wire.js.map +1 -0
  223. package/dist/runtime/session-events-service.d.ts +8 -0
  224. package/dist/runtime/session-events-service.js +124 -0
  225. package/dist/runtime/session-events-service.js.map +1 -0
  226. package/dist/runtime/session-events-transport.d.ts +8 -0
  227. package/dist/runtime/session-events-transport.js +142 -0
  228. package/dist/runtime/session-events-transport.js.map +1 -0
  229. package/dist/runtime/startup-lock.d.ts +2 -0
  230. package/dist/runtime/startup-lock.js +49 -5
  231. package/dist/runtime/startup-lock.js.map +1 -1
  232. package/dist/runtime/state.d.ts +2 -1
  233. package/dist/runtime/state.js +4 -0
  234. package/dist/runtime/state.js.map +1 -1
  235. package/dist/runtime/transport.d.ts +1 -0
  236. package/dist/runtime/transport.js +2 -0
  237. package/dist/runtime/transport.js.map +1 -1
  238. package/dist/runtime/types.d.ts +24 -0
  239. package/dist/runtime/types.js.map +1 -1
  240. package/dist/runtime/worker-client.js +42 -13
  241. package/dist/runtime/worker-client.js.map +1 -1
  242. package/dist/runtime/worker-event-channel.d.ts +30 -0
  243. package/dist/runtime/worker-event-channel.js +141 -0
  244. package/dist/runtime/worker-event-channel.js.map +1 -0
  245. package/dist/runtime/worker-event-protocol.d.ts +88 -0
  246. package/dist/runtime/worker-event-protocol.js +114 -0
  247. package/dist/runtime/worker-event-protocol.js.map +1 -0
  248. package/dist/runtime/worker-events.d.ts +73 -0
  249. package/dist/runtime/worker-events.js +704 -0
  250. package/dist/runtime/worker-events.js.map +1 -0
  251. package/dist/runtime/worker-server.d.ts +3 -1
  252. package/dist/runtime/worker-server.js +64 -9
  253. package/dist/runtime/worker-server.js.map +1 -1
  254. package/dist/sdk/connected-events.d.ts +3 -0
  255. package/dist/sdk/connected-events.js +259 -0
  256. package/dist/sdk/connected-events.js.map +1 -0
  257. package/dist/sdk/connected-types.d.ts +2 -0
  258. package/dist/sdk/connected-types.js.map +1 -1
  259. package/dist/sdk/connected.js +3 -0
  260. package/dist/sdk/connected.js.map +1 -1
  261. package/dist/sdk/event-types.d.ts +182 -0
  262. package/dist/sdk/event-types.js +2 -0
  263. package/dist/sdk/event-types.js.map +1 -0
  264. package/dist/sdk/execution-driver.js +1 -1
  265. package/dist/sdk/execution-driver.js.map +1 -1
  266. package/dist/sdk/execution-types.d.ts +2 -0
  267. package/dist/sdk/execution-types.js.map +1 -1
  268. package/dist/sdk/runner.js +2 -0
  269. package/dist/sdk/runner.js.map +1 -1
  270. package/package.json +5 -1
  271. package/sdk/access-config.md +9 -7
  272. package/sdk/adapter-contract.md +25 -3
  273. package/sdk/agent-skill.md +8 -5
  274. package/sdk/cli/dashboard-design.md +37 -9
  275. package/sdk/cli/dashboard-inspection.md +14 -6
  276. package/sdk/cli/extensions.md +44 -0
  277. package/sdk/cli/index.md +53 -14
  278. package/sdk/cli/output.md +14 -2
  279. package/sdk/completion-notifications.md +2 -2
  280. package/sdk/config.md +65 -11
  281. package/sdk/copilot.md +1 -1
  282. package/sdk/cursor.md +2 -2
  283. package/sdk/diagnostics.md +68 -0
  284. package/sdk/distribution.md +13 -3
  285. package/sdk/events.md +339 -0
  286. package/sdk/execution.md +32 -10
  287. package/sdk/extensions.md +189 -0
  288. package/sdk/fx.md +4 -2
  289. package/sdk/harnesses.md +1 -1
  290. package/sdk/index.md +4 -0
  291. package/sdk/message-delivery.md +2 -0
  292. package/sdk/opencode.md +1 -1
  293. package/sdk/plugins/sub-agents.md +3 -1
  294. package/sdk/project-root.md +97 -0
  295. package/sdk/project-team.md +10 -4
  296. package/sdk/sessions.md +4 -0
  297. package/sdk/v1-runtime.md +22 -8
@@ -1,6 +1,6 @@
1
1
  # Package Distribution
2
2
 
3
- The npm package name is `subharness`. One package provides the TypeScript SDK and the `subharness` executable and its `agent` compatibility alias. Agent definitions import public helpers from `subharness`. The website workspace remains private and is not part of the npm package.
3
+ The npm package name is `subharness`. One package provides the TypeScript SDK and the `subharness` executable and its `agent` compatibility alias. Agent definitions import public helpers from `subharness`. Every event, subscription and capability type is exported from that root and re-exported as a type from `subharness/extensions`; extension authoring types use the `subharness/extensions` subpath. Compiled extension modules use no Subharness runtime import. The website workspace remains private and is not part of the npm package.
4
4
 
5
5
  The source repository is [vercel-labs/subharness](https://github.com/vercel-labs/subharness). Its GitHub visibility is internal, so cloning requires repository access. The product name is subharness. The primary CLI command is `subharness`; `agent` remains an identical compatibility alias. Agent discovery and personal configuration live under `.subharness/`.
6
6
 
@@ -20,11 +20,21 @@ Repository scripts use pnpm, including workspace command forwarding and content-
20
20
 
21
21
  A tarball built from a source checkout can differ from the registry release with the same version. The current package version is `0.0.3`, producing `subharness-0.0.3.tgz`. Install a local tarball with `npm install --save-dev /absolute/path/to/subharness-0.0.3.tgz`. Run the project's local executable with `npx subharness`.
22
22
 
23
+ ## Extension directories and authoring types
24
+
25
+ The core package contains live event normalization/transport, manifest discovery, per-user consent in `~/.subharness/extensions.json` and coordinator supervision of extension children. `subharness/extensions` supplies TypeScript authoring declarations. User modules default-export a plain definition object and import its type with `import type`; their compiled ESM does not require Subharness as a runtime dependency. Embedded SDK applications consume events directly through the root package's event API.
26
+
27
+ An extension distribution contains `extension.json`, its compiled ESM entry and any required packaged dependencies. It is installed as a self-contained directory in the user's global or repository extension location. The coordinator starts a separate supervised child for an enabled installation when its first matching session is admitted; that child loads the entry. Listing and discovery inspect only static manifests, never import code, install packages or build TypeScript. User extension code and dependencies are not part of the core package or bundle.
28
+
29
+ The CLI task screen's renderer belongs to the core package and consumes live events directly. It does not load extension code. See [User extensions](extensions.md) for the type-only definition API and self-contained logger, and [extension commands](cli/extensions.md) for directory placement and explicit enablement.
30
+
31
+ The existing native SDK dependencies and native executable requirements are unchanged. Core release publishing follows the procedure below and does not publish user extension directories.
32
+
23
33
  ## Package contents and release checks
24
34
 
25
- Packages built from this source contain the built JavaScript, declaration files and source maps under `dist/`, SDK Markdown documentation under `sdk/`, the README, the Apache License 2.0, and package metadata. Source maps embed the original TypeScript so debuggers can display it without a separate source checkout. Website code, development agents, skills, source assets, tests, `.context`, personal settings, and environment files are excluded.
35
+ Packages built from this source contain the built JavaScript, declaration files and source maps under `dist/`, SDK Markdown documentation under `sdk/`, the README, the Apache License 2.0, and package metadata. Package metadata exports `.` for the root SDK and `./extensions` for the `subharness/extensions` authoring declarations. The subpath supplies `ExtensionDefinition`, `ExtensionContext`, `ExtensionInstance` and `ExtensionManifest`, and re-exports every event, subscription and capability type from `subharness` as a type. Compiled extension code requires no runtime import from that subpath. Source maps embed the original TypeScript so debuggers can display it without a separate source checkout. Website code, development agents, skills, source assets, tests, `.context`, access configuration, extension consent files and logs, and environment files are excluded.
26
36
 
27
- Packing builds the SDK from the current source before assembling its files. The CLI's `--version` output matches the package version. A clean consumer must be able to import the execution SDK, run an inline definition against a controlled native protocol fixture, and discover a TypeScript agent definition using the installed executable without access to the source checkout or a paid model call. `pnpm run check:package` packs with pnpm and verifies this clean-consumer behavior and the packaged file boundary without running a coding model. It requires network access to install dependencies from the public npm registry and disables install lifecycle scripts in the temporary consumer.
37
+ Packing builds the SDK from the current source before assembling its files. The CLI's `--version` output matches the package version. A clean consumer must be able to import the execution SDK, resolve the packaged `./extensions` subpath, type-check a definition and `SessionEvent` import from `subharness/extensions`, compile it without a Subharness runtime import, run an inline definition against a controlled native protocol fixture, and discover a TypeScript agent definition using the installed executable without access to the source checkout or a paid model call. `pnpm run check:package` packs with pnpm and verifies this clean-consumer behavior and the packaged file boundary without running a coding model. It requires network access to install dependencies from the public npm registry and disables install lifecycle scripts in the temporary consumer.
28
38
 
29
39
  The committed lockfile pins dependency content with integrity hashes and does not embed company registry URLs. pnpm resolves packages through the configured registry, which defaults to the public npm registry. Installation and package verification do not change the developer's global npm registry configuration. Registry authentication remains with npm.
30
40
 
package/sdk/events.md ADDED
@@ -0,0 +1,339 @@
1
+ # Live session events
2
+
3
+ The [execution SDK](execution.md) exposes normalized live events through `runner.events` and `client.events`. Applications can build agent interfaces and decide whether and where to persist events. Subharness forwards events to current subscribers without retaining event or chat content for later observation. Existing task metadata, original requests and complete responses keep their separate [execution contracts](execution.md).
4
+
5
+ Events include session, task and turn lifecycle, assistant text, provider-exposed reasoning, tool calls and results, approvals, and safe errors. Content is bounded and redacted, and coverage depends on the selected native route. The CLI task screen consumes this public event API directly. [User extensions](extensions.md) receive live events through coordinator-supervised processes. Observing never controls execution or acknowledges a managed child's result.
6
+
7
+ ## Identity and ordering
8
+
9
+ A session is one native conversation. A task is an admitted request and its managed continuations. A turn is one adapter invocation, including its native tool loop. An item is an assistant content block, exposed reasoning block, or tool call. A task can contain several turns. In-flight native steering stays within its turn; steering a waiting task starts another turn in that task. Interrupt-and-replace creates another task.
10
+
11
+ The execution owner assigns opaque event, turn and item identifiers. `ownerId` identifies the embedded runner or coordinator instance. `sessionId`, `taskId` and `responseId` reuse execution identities. `turnOrdinal` increases within a task; `itemOrdinal` increases within a turn. Both start at one. Item revisions increase on published mutations. An item is keyed by owner, session, task, turn and item ID. Native IDs are optional correlation data, never authorization capabilities. Native child-agent IDs do not create managed `parentTaskId` lineage.
12
+
13
+ `sequence` is a positive, increasing safe integer assigned across an owner's accepted events in receive order. Each subscription delivers events in increasing `sequence` order. `eventId` identifies one event. Filtering and intervals without a subscriber can skip sequence numbers; consecutive numbers are not promised. `observedAt` is Unix milliseconds for display, not an ordering key. Neither timestamps nor identifiers let a subscriber retrieve prior events.
14
+
15
+ ## Event types
16
+
17
+ Every event, subscription and capability type documented on this page is exported from `subharness` and re-exported as a type from `subharness/extensions`. `HarnessKind`, `TaskState`, `ApprovalRequest` and `ErrorInfo` are the existing SDK types.
18
+
19
+ ```ts
20
+ export type NativeRoute =
21
+ | "codex-app-server" | "claude-agent-sdk" | "fx-acp"
22
+ | "opencode-http" | "copilot-sdk" | "cursor-acp" | "cursor-sdk";
23
+
24
+ export interface NativeCorrelation {
25
+ readonly sessionId?: string;
26
+ readonly turnId?: string;
27
+ readonly messageId?: string;
28
+ readonly itemId?: string;
29
+ readonly toolCallId?: string;
30
+ readonly agentId?: string;
31
+ readonly parentToolCallId?: string;
32
+ }
33
+ export interface EventBase {
34
+ readonly version: 1;
35
+ readonly eventId: string;
36
+ readonly ownerId: string;
37
+ readonly sequence: number;
38
+ readonly observedAt: number;
39
+ readonly sessionId: string;
40
+ readonly harness?: HarnessKind; // Absent until selection succeeds.
41
+ readonly route?: NativeRoute;
42
+ readonly origin: "owner" | "adapter"; // Owner is the coordinator or embedded runner that admitted the session.
43
+ readonly native?: NativeCorrelation;
44
+ }
45
+ export interface TaskEventBase extends EventBase {
46
+ readonly taskId: string;
47
+ readonly parentTaskId?: string; // Managed lineage only.
48
+ }
49
+ export interface TurnEventBase extends TaskEventBase {
50
+ readonly turnId: string;
51
+ readonly turnOrdinal: number;
52
+ }
53
+
54
+ // Content is display data, not a tool invocation or a replacement tool result.
55
+ export interface EventContent {
56
+ readonly format: "text" | "json";
57
+ readonly text: string;
58
+ readonly status: "complete" | "truncated" | "redacted" | "unavailable";
59
+ readonly originalBytes?: number; // Only when actually known.
60
+ }
61
+ export interface ItemBase {
62
+ readonly itemId: string;
63
+ readonly itemOrdinal: number;
64
+ readonly revision: number; // Starts at 1; increases for published item mutations.
65
+ readonly identity: "native" | "synthetic";
66
+ readonly native?: NativeCorrelation;
67
+ }
68
+ export interface AssistantItem extends ItemBase {
69
+ readonly kind: "assistant";
70
+ readonly state: "streaming" | "completed" | "interrupted" | "incomplete";
71
+ readonly phase: "progress" | "final" | "unspecified";
72
+ readonly body: EventContent;
73
+ }
74
+ export interface ReasoningItem extends ItemBase {
75
+ readonly kind: "reasoning";
76
+ readonly state: "streaming" | "completed" | "interrupted" | "incomplete";
77
+ readonly visibility: "summary" | "text" | "unavailable";
78
+ readonly body: EventContent;
79
+ }
80
+ export interface ToolItem extends ItemBase {
81
+ readonly kind: "tool";
82
+ readonly name: string;
83
+ readonly state: "pending" | "running" | "succeeded" | "failed" | "cancelled" | "unknown";
84
+ readonly input: EventContent;
85
+ readonly output: EventContent;
86
+ readonly exitCode?: number;
87
+ readonly durationMs?: number;
88
+ }
89
+ export type SessionItem = AssistantItem | ReasoningItem | ToolItem;
90
+
91
+ export interface SessionStateEvent extends EventBase {
92
+ readonly type: "session.state";
93
+ readonly state: "open" | "closing" | "closed";
94
+ }
95
+ export interface SessionCapabilitiesEvent extends EventBase {
96
+ readonly type: "session.capabilities";
97
+ readonly capabilities: SessionEventCapabilities;
98
+ }
99
+ export interface TaskStateEvent extends TaskEventBase {
100
+ readonly type: "task.state";
101
+ readonly state: TaskState;
102
+ readonly stopUnconfirmed: boolean;
103
+ }
104
+ export interface TurnStartedEvent extends TurnEventBase {
105
+ readonly type: "turn.started";
106
+ readonly cause: "prompt" | "child-results" | "steer-continuation" | "recovery";
107
+ }
108
+ export interface TurnCompletedEvent extends TurnEventBase {
109
+ readonly type: "turn.completed";
110
+ readonly outcome: "completed" | "failed" | "cancelled" | "interrupted";
111
+ readonly responseId?: string; // Existing rsp_ identity, when a response exists.
112
+ readonly finalItemId?: string; // Only if reliably mapped to that response.
113
+ }
114
+ export interface ItemStartedEvent extends TurnEventBase {
115
+ readonly type: "item.started";
116
+ readonly item: SessionItem;
117
+ }
118
+ export interface ItemUpdatedEvent extends TurnEventBase {
119
+ readonly type: "item.updated";
120
+ readonly item: SessionItem; // Full bounded replacement, not a patch.
121
+ }
122
+ export type ItemDeltaHeader = {
123
+ readonly itemId: string;
124
+ readonly itemOrdinal: number;
125
+ readonly identity: "native" | "synthetic";
126
+ } & (
127
+ | { readonly kind: "assistant"; readonly state: AssistantItem["state"] }
128
+ | { readonly kind: "reasoning"; readonly state: ReasoningItem["state"] }
129
+ | { readonly kind: "tool"; readonly state: ToolItem["state"]; readonly name: string }
130
+ );
131
+ export interface ItemDeltaEvent extends TurnEventBase {
132
+ readonly type: "item.delta";
133
+ readonly item: ItemDeltaHeader;
134
+ readonly baseRevision: number;
135
+ readonly revision: number;
136
+ readonly field: "body" | "output"; // Only fields whose EventContent.format is "text".
137
+ readonly text: string; // Append only this newly delivered text, never JSON-patch.
138
+ }
139
+ export interface ItemCompletedEvent extends TurnEventBase {
140
+ readonly type: "item.completed";
141
+ readonly item: SessionItem; // Bounded replacement; chunk-only mid-item turn-boundary views remain incomplete.
142
+ readonly completion: "native" | "turn-boundary" | "interrupted";
143
+ }
144
+ export interface ApprovalRequestedEvent extends TurnEventBase {
145
+ readonly type: "approval.requested";
146
+ readonly request: ApprovalRequest; // Same registry ID/actions, bounded context.
147
+ readonly itemId?: string;
148
+ }
149
+ export interface ApprovalResolvedEvent extends TurnEventBase {
150
+ readonly type: "approval.resolved";
151
+ readonly requestId: string;
152
+ readonly itemId?: string;
153
+ readonly resolution: "answered" | "withdrawn";
154
+ readonly actionId?: string; // Answer submission, not operation success.
155
+ }
156
+ export interface SessionErrorEvent extends EventBase {
157
+ readonly type: "session.error";
158
+ readonly taskId?: string;
159
+ readonly turnId?: string;
160
+ readonly category: "execution" | "capture";
161
+ readonly error: ErrorInfo; // Existing safe diagnostic policy.
162
+ readonly fatal: boolean; // Fatal to the indicated category, not an inference.
163
+ }
164
+ export type SessionEvent = SessionStateEvent | SessionCapabilitiesEvent
165
+ | TaskStateEvent | TurnStartedEvent | TurnCompletedEvent
166
+ | ItemStartedEvent | ItemUpdatedEvent | ItemDeltaEvent | ItemCompletedEvent
167
+ | ApprovalRequestedEvent | ApprovalResolvedEvent | SessionErrorEvent;
168
+ ```
169
+
170
+ `item.started`, `item.updated` and `item.completed` are bounded item snapshots. They replace an observed snapshot rather than being appended as additional text. Adapters begin normalizing when a matching subscriber registers and keep no extra content for later observation. Content produced before registration appears only if the native route itself later supplies it in a snapshot, such as Codex `item/completed` or a Claude assistant message. Subscribers display that native snapshot as received, with the existing bounds and redaction; adapters do not reconstruct earlier content. `item.delta` is self-describing: its `item` header carries item ID, ordinal, native/synthetic identity, kind and state, plus a tool name for tools. It does not require an earlier `item.started` to make the new text displayable. Tool names are bounded display labels; unavailable native names must be identified as unknown rather than guessed.
171
+
172
+ A subscriber joining mid-item whose first event is a delta starts with the text delivered from that point. It does not invent an empty earlier snapshot or treat the visible suffix as the whole item. A later native snapshot replaces that partial view and includes earlier content only when the native route supplies it. On chunk-only routes (`fx-acp` and `cursor-acp`), a mid-item subscriber's turn-boundary snapshot covers only content normalized since registration and has item state `"incomplete"`. `baseRevision` and `revision` relate successive updates; the first received delta can have a base the subscriber never saw. Subsequent deltas append in delivery order for that item, and duplicate/older revisions are ignored. Deltas apply only to body or output fields whose `EventContent.format` is `"text"`. Fields with `format: "json"` change only through full snapshots; no JSON-format field receives a delta. Native chunk boundaries are not a public guarantee.
173
+
174
+ `origin` identifies the component that raises the normalized event. `owner` means the coordinator or embedded runner that admitted the session; approvals remain owner events even when a native adapter initiates the permission flow. Adapters raise `session.error` only with `category: "capture"` and `origin: "adapter"`. Execution failures use `category: "execution"` and are reported by the owner with `origin: "owner"`, including native transport failures surfaced by an adapter. Event-processing failures detected by the owner itself, such as dropping an invalid adapter draft, use `session.error` with `category: "capture"` and `origin: "owner"`.
175
+
176
+ | Event type | `origin` |
177
+ | --- | --- |
178
+ | `session.state` | `"owner"` |
179
+ | `session.capabilities` | `"owner"` |
180
+ | `task.state` | `"owner"` |
181
+ | `turn.started` | `"owner"` |
182
+ | `turn.completed` | `"owner"` |
183
+ | `item.started`, `item.delta`, `item.updated`, `item.completed` | `"adapter"` |
184
+ | `approval.requested`, `approval.resolved` | `"owner"` |
185
+ | Adapter-raised `session.error` with `category: "capture"` | `"adapter"` |
186
+ | Owner-raised `session.error` with `category: "execution"` or `category: "capture"` | `"owner"` |
187
+
188
+ Content status or format changes require a snapshot. Retraction/supersession replaces affected content with unavailable content and incomplete/unknown state. A completed item is not task completion. Text ending at a native prompt boundary can use `completion: "turn-boundary"`; a tool without a terminal native result closes as `unknown`, never inferred `succeeded`. Items still open when a turn ends without native completion, including turn failure, transport loss, an invalid native terminal result or interruption, close with `item.completed` and `completion: "interrupted"`. Assistant and reasoning items use state `"interrupted"`; tool items use state `"unknown"`. This closure rule also applies to partial views on chunk-only routes. Custom-tool and streamed observations are deduplicated only through reliable native identity. Unattributable late frames are never assigned to whichever task happens to be active.
189
+
190
+ `phase: "final"` and `finalItemId` are supplied only when reliably associated with the adapter's selected complete response. Intermediate messages do not change `task.result`. `turn.completed` follows native completion or confirmed stop and callback draining. Failed stop confirmation produces failed task state with `stopUnconfirmed: true`. When native stop remains unconfirmed, open items stay open until the session is retired, then close with the same `completion: "interrupted"` and interrupted/unknown states defined above; no `turn.completed` is invented for that unconfirmed stop. For a confirmed turn end, accepted item frames, including item closures, precede turn completion and its corresponding terminal task event. This is producer ordering, never a wait for a subscriber or extension handler.
191
+
192
+ Approval events reuse the existing request IDs/actions. Resolution reports answer submission or withdrawal, not tool success; answers use the separate approval API. Session errors use safe library codes and messages. The `capture` error category describes live event processing; it does not change execution outcomes. Native nested attribution is included only when reliably bound to the owning turn. Observation does not enable otherwise-hidden native subagent text.
193
+
194
+ ## Effective route capabilities
195
+
196
+ ```ts
197
+ export interface EventFeature {
198
+ readonly support: "available" | "unsupported" | "unverified";
199
+ readonly delivery: readonly ("delta" | "snapshot")[];
200
+ readonly note?: string;
201
+ }
202
+ export interface SessionEventCapabilities {
203
+ readonly route: NativeRoute;
204
+ readonly nativeVersion?: string;
205
+ readonly assistant: EventFeature;
206
+ readonly reasoning: EventFeature;
207
+ readonly tools: EventFeature;
208
+ readonly approvals: EventFeature;
209
+ }
210
+ ```
211
+
212
+ `capabilities(sessionId)` returns the selected route's current effective capabilities. It rejects with `UNKNOWN_SESSION` for an unknown session and resolves `undefined` only before harness selection for a known session. It never starts a harness. Changes publish `session.capabilities` to matching subscribers. `available` means a supported normalized format is exposed, not that every model emits it. `unsupported` means known unavailable. `unverified` means the adapter cannot confirm that the route emits that feature: events of that kind may or may not arrive, and callers must not depend on them. Unsupported and unverified features have empty delivery lists. Available approvals always declare `delivery: ["snapshot"]`; approval requests and resolutions are complete records, never deltas. All routes supply execution-owner lifecycle and safe execution errors.
213
+
214
+ `SessionEventCapabilities.nativeVersion` is optional. When present, it contains at most 64 bytes of printable ASCII (characters `0x20` through `0x7E`). An unavailable version or one that does not meet these bounds is omitted.
215
+
216
+ The `copilot-sdk` route omits `nativeVersion`. The pinned SDK package version is not the native runtime version, and the adapter does not expose a verified runtime version through this capability.
217
+
218
+ Startup-only output options are enabled for every native session, including Claude `includePartialMessages` and Copilot `streaming`. A later subscriber therefore receives supported deltas without restarting or reconfiguring the native session. When no subscriber matches, adapters still perform required native protocol/execution work but skip event normalization and event IPC.
219
+
220
+ Snapshot delivery includes item starts, replacements and completion; deltas are additional incremental text. Installed versions can reduce coverage; the effective declaration is authoritative.
221
+
222
+ | Route | Assistant | Exposed reasoning | Tools | Approvals and limits |
223
+ | --- | --- | --- | --- | --- |
224
+ | `codex-app-server` | Delta and snapshot | Summary/text delta and snapshot | Snapshots of command, file-change, MCP and dynamic calls; command output deltas | Supported command/file and grant requests. Reasoning summary and exposed text remain distinguishable. |
225
+ | `claude-agent-sdk` | Delta and snapshot | Text delta and snapshot; opaque thinking unavailable | Tool-use/result snapshots correlated by tool-use ID; valid input snapshots only | Existing `canUseTool` flow. Result messages close turns. Native nested text visibility can be partial. |
226
+ | `fx-acp` | Chunk deltas and turn-boundary snapshots | Unverified | ACP call/update snapshots with input/output previews | Offered ACP permissions. Stable native message IDs distinguish progress from the last selected response. Reasoning emission is unverified. |
227
+ | `opencode-http` | Message/part deltas and snapshots | Part deltas and snapshots | Call-ID snapshots of pending/running/completed/error state and input/output | Existing once/reject permissions. Native idle alone does not establish successful completion. Coverage follows the pinned 1.18.32 route. |
228
+ | `copilot-sdk` | Deltas and complete snapshots | Deltas and complete snapshots | Call-ID start/progress/partial-result/completion snapshots | Existing approve-once/reject flow. Native idle confirmation retains its execution meaning. |
229
+ | `cursor-acp` | Chunk deltas and turn-boundary snapshots | Unverified | Unverified | Offered once-only permissions. Some backend failures appear only as assistant text; no error classifier infers failure from prose. |
230
+ | `cursor-sdk` | Available; `["snapshot"]` (final responses) | Unverified; `[]` | Call-ID running/completed/error snapshots with args/results and native truncation preserved | Interactive approvals unsupported. Native request identifiers are not approval requests. |
231
+
232
+ The table defines normalized route coverage. For `cursor-sdk`, assistant support is `"available"` with delivery `["snapshot"]`; reasoning support is `"unverified"` with delivery `[]`. For `fx-acp` and `cursor-acp`, mid-item turn-boundary assistant snapshots retain only content normalized since registration and use state `"incomplete"`. Native persistence settings and close-time deletion behavior are unchanged.
233
+
234
+ There is no raw native payload in this event union. Usage/cost, plans, file attribution, auth/account events, opaque thinking, arbitrary metadata and unsupported native variants are excluded. Malformed required execution protocol data keeps its existing failure behavior.
235
+
236
+ ## Subscription API
237
+
238
+ ```ts
239
+ export type EventScope =
240
+ | { readonly kind: "all" }
241
+ | { readonly kind: "session"; readonly sessionId: string }
242
+ | { readonly kind: "task"; readonly sessionId: string; readonly taskId: string };
243
+ export interface EventOpenOptions {
244
+ readonly scope: EventScope;
245
+ readonly signal?: AbortSignal;
246
+ }
247
+ export type EventSubscription = AsyncIterable<SessionEvent> & {
248
+ close(): Promise<void>;
249
+ };
250
+ export interface SessionEventSource {
251
+ open(options: EventOpenOptions): Promise<EventSubscription>;
252
+ capabilities(sessionId: string): Promise<SessionEventCapabilities | undefined>;
253
+ }
254
+ ```
255
+
256
+ Both `Runner` and `Client` expose `readonly events: SessionEventSource`. `scope` is required. `all` covers the execution owner's sessions, including future ones; session scope covers that conversation; task scope checks both IDs and excludes managed descendants. Task scope also includes its containing session's state/capability events while the subscription is open. Applications authorize and filter events before forwarding them to browser users.
257
+
258
+ The `open` promise resolves after registration. Only events accepted after that registration boundary are delivered. Past events are not replayed. Earlier content can appear only in a snapshot later supplied by the native route; chunk-only mid-item turn-boundary views retain the incomplete-state rule above. Await it before submitting a prompt to observe that prompt's initial events. Values are detached read-only `SessionEvent` objects directly; opening does not synthesize an initial state or emit control records. One subscriber cannot mutate another subscriber's view through a shared event object. Query task/session snapshots and `capabilities` separately when current metadata is needed. Opening another subscription begins another live observation and never supplies events missed while detached.
259
+
260
+ `close()` and iterator `return()` are idempotent; they end only observation and release pending delivery. `open()` with an already aborted signal rejects with `OBSERVATION_CLOSED` without registering. A later explicit signal abort rejects a pending read with `OBSERVATION_CLOSED`. No observation operation cancels a task or acknowledges child results. A task subscription drains accepted events and ends at the current or next terminal outcome; one opened on an already terminal task ends without earlier events. A session subscription ends on session close; `all` ends on owner close. Ended iterators do not reopen for private recovery. Connected disconnect rejects affected streams with `COORDINATOR_UNAVAILABLE` and leaves agents running. The event source does not reconnect automatically.
261
+
262
+ If closing an execution owner fails, every open subscription of that owner ends, regardless of scope. Embedded runner subscriptions reject pending reads with `OBSERVATION_CLOSED`; connected subscriptions reject pending reads with `COORDINATOR_UNAVAILABLE`.
263
+
264
+ ## Forwarding and flow control
265
+
266
+ Adapters normalize and forward only while at least one subscriber matches the session. Extensions subscribe through their supervised child processes for their admission-selected sessions; an open dashboard task screen counts as a task subscriber. Embedded runners serve explicit application subscriptions and do not load extensions. Closing the last matching subscriber stops event normalization and event IPC; it does not stop native execution.
267
+
268
+ There is no event-content store. Only bounded in-flight delivery/redaction data and metadata needed to identify live operations are used. After forwarding, event content is not retained for another observation. A dashboard owns the text currently displayed on its open screen; applications/extensions explicitly own any content they choose to keep. Required native execution state and the existing complete-response records are separate from the event API.
269
+
270
+ Each adapter keeps normalization state for at most 1,024 open items per session. Items beyond that bound are not forwarded. The adapter raises one `session.error` with `category: "capture"` and `origin: "adapter"` per turn that overflows, without changing the execution outcome.
271
+
272
+ The Codex, Claude Code, fx, Copilot and Cursor SDK adapters also track at most 1,024 distinct item identities per turn. After that bound is reached, later new identities are not forwarded and the adapter raises one capture error for the turn. Previously admitted identities may still complete. Identity-bound capture errors do not change the execution outcome.
273
+
274
+ Each subscriber has at most 128 events or 1 MiB of pending serialized event data, whichever limit is reached first. A subscriber that exceeds either bound has its stream rejected with `EVENT_BACKPRESSURE`; its queued delivery is released. Event delivery never waits for a consumer or applies backpressure to native execution. One slow subscriber does not delay other subscribers. Execution replies, approvals and cancellation have an independent control path. No dropped-content recovery is attempted by the event source.
275
+
276
+ Worker frames bind lease, operation and source sequence to the owning turn. Identity, schema and content limits are validated before forwarding. Claude's private SDK worker retains its existing environment/callback isolation. Connected events use a separate bounded stream on the authenticated, loopback, instance-bound SDK transport with the `session-events-v1` capability. Private dashboard projections and execution-command JSONL do not carry live steps. Missing support rejects the SDK event operation with `COORDINATOR_INCOMPATIBLE` while core execution/inspection remains usable. The CLI task screen maps missing `session-events-v1` support to `COORDINATOR_OUTDATED` with restart guidance in place of live steps, while retaining its core content. Observing never launches a native harness or replaces a coordinator.
277
+
278
+ ## Content bounds and redaction
279
+
280
+ All sizes below use UTF-8 bytes. Previews are display data; they never replace actual tool arguments, results or final responses. The existing 1 MiB complete-response/text-tool limits and rich-tool limits remain effective.
281
+
282
+ | Content | Limit |
283
+ | --- | --- |
284
+ | Serialized event | 128 KiB, including the existing bounded approval request |
285
+ | Delta text | 8 KiB |
286
+ | Assistant or reasoning body | 16 KiB per item |
287
+ | Tool input / output | 8 KiB / 32 KiB per item |
288
+ | Native ID or tool label | 256 bytes |
289
+ | Optional native version | 64 bytes of printable ASCII; omitted otherwise |
290
+ | Safe diagnostic or capability note | 1 KiB |
291
+ | Structured traversal | Depth 16 and 1,000 entries |
292
+
293
+ Truncation preserves valid UTF-8, marks `status: "truncated"`, and supplies `originalBytes` only when known. Redacted spans use explicit placeholders. If content is both redacted and truncated, the status is `truncated` and the redaction placeholders remain visible; `redacted` means redaction without truncation. `unavailable` supplies a fixed explanation without source content. Oversized native correlation IDs are omitted rather than truncated into ambiguous identities; normalized synthetic identity remains stable. Tool labels may be visibly truncated. Binary/image/audio blocks use unavailable descriptions, never base64. Truncated JSON previews retain `format: "json"` but must not be parsed as complete arguments.
294
+
295
+ Only allowlisted content fields cross the producer boundary. Environment/configuration blobs, credentials, coordinator/launcher tokens, native stderr, exception objects, HTTP/RPC error bodies, auth events, encrypted reasoning, signatures and arbitrary metadata are excluded. Known resolved secret values are scrubbed; structured authorization/password/secret/token/api-key keys and normalized equivalents are recursively redacted before serialization. Split deltas cannot release parts of a known secret: producers use only bounded in-flight redaction state and release a stable safe prefix. That transient state is discarded when it is no longer needed for delivery; it is not retained for another subscriber. Unknown arbitrary secrets in source code or prose cannot be guaranteed detectable. No raw/unredacted bypass exists.
296
+
297
+ Reasoning means only provider-exposed text or summaries. Opaque thinking is unavailable and is never reconstructed. The coordinator revalidates event bounds. Terminal controls in retained content remain untrusted text: the CLI sanitizes before measuring or adding its own ANSI; SDK applications escape for their own output surface. Applications and enabled extensions remain responsible for any data they store or transmit.
298
+
299
+ ## Errors and an application example
300
+
301
+ Invalid option shapes reject with `INVALID_ARGUMENT`; unknown sessions/tasks use `UNKNOWN_SESSION`/`UNKNOWN_TASK`. Backpressure, abort and transport failures use the codes above with safe `AgentError` messages. Native execution failure is event data and task state, not automatically a subscription failure. An event-processing failure does not rewrite a successful native result.
302
+
303
+ SDK applications implement custom behavior by consuming `events.open` directly. This example observes before admitting work and lets the application decide how to handle each event. A separate application component handles pending approvals.
304
+
305
+ ```ts
306
+ import { createRunner, type AgentDefinition, type EventSubscription, type SessionEvent } from "subharness";
307
+
308
+ async function observe(
309
+ definition: AgentDefinition,
310
+ cwd: string,
311
+ consume: (event: SessionEvent) => Promise<void>,
312
+ ): Promise<string> {
313
+ const runner = createRunner();
314
+ let subscription: EventSubscription | undefined;
315
+ let reading: Promise<void> | undefined;
316
+ try {
317
+ const session = await runner.createSession(definition, { cwd });
318
+ subscription = await runner.events.open({
319
+ scope: { kind: "session", sessionId: session.id },
320
+ });
321
+ reading = (async () => {
322
+ for await (const event of subscription!) await consume(event);
323
+ })();
324
+ // Observe failures again below without an unhandled rejection while work runs.
325
+ void reading.catch(() => {});
326
+ const { task } = await session.prompt("Review the current diff.");
327
+ const result = await task.result;
328
+ await session.close();
329
+ await reading;
330
+ return result.text;
331
+ } finally {
332
+ await subscription?.close();
333
+ await reading?.catch(() => {});
334
+ await runner.close();
335
+ }
336
+ }
337
+ ```
338
+
339
+ A connected application uses `client.events` with the same types and registration semantics. Its own handlers run in that application; installed user extensions instead execute in coordinator-supervised child processes under the [extension contract](extensions.md). Disconnecting a connected application leaves the coordinator and its agents/extensions running.
package/sdk/execution.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Connected and embedded execution
2
2
 
3
- The Node.js SDK runs native agents inside an application or connects to the shared local coordinator used by the CLI. It provides task states, complete responses, and structured approvals. Native harness executables remain required. Applications own their UI transport and user authorization; this is not a browser/edge runtime or an implementation of the A2A wire protocol.
3
+ The Node.js SDK runs native agents inside an application or connects to the shared local coordinator used by the CLI. It provides task states, complete responses, structured approvals and normalized [live session events](events.md). Native harness executables remain required. Applications own their UI transport and user authorization; this is not a browser/edge runtime or an implementation of the A2A wire protocol.
4
4
 
5
5
  Two entry points serve different ownership needs. **`connect()` connects to the same selected local coordinator as the CLI, starting it if absent**: it finds existing conversations without recreating agents, or connects to a newly started empty coordinator. `connect({ start: false })` requires that coordinator to exist already. **`createRunner()` embeds execution in the application process**: it owns isolated sessions and can use application tool closures. Both expose the same session and task handles. A session is a native conversation with a queue; a task is coordinated work including child agents and parent continuations.
6
6
 
@@ -8,7 +8,7 @@ A connected client disconnects without stopping the shared coordinator or its ag
8
8
 
9
9
  Read the examples in order, or jump to [connection startup](#connect-without-running-the-cli-first), [agent discovery and creation](#discover-check-and-create-connected-sessions), [CLI attachment](#connect-to-cli-work), [paged inspection](#list-and-inspect-execution), [reconnection](#disconnect-and-reconnect), [embedded teams](#define-an-embedded-team), [queueing](#follow-up-or-queue-work), [steering](#correct-or-replace-active-work), [UI controls](#serve-a-ui), [approval buttons](#render-approval-buttons), [grant forms](#select-permission-grants), [chat tools](#consult-from-a-chat-tool), [response replay](#replay-complete-responses), [signatures](#signature-reference), or [CLI/library parity](#one-library-for-sdk-and-cli).
10
10
 
11
- Examples awaiting only `task.result` assume no interactive approval is needed, or a separate UI/component handles requests. Pending approvals never auto-resolve. Helpers identified as application-owned are illustrative, not SDK exports. The first version exposes task states, complete responses, and approvals; live tokens and native tool-progress events are outside its scope.
11
+ Examples awaiting only `task.result` assume no interactive approval is needed, or a separate UI/component handles requests. Pending approvals never auto-resolve. Helpers identified as application-owned are illustrative, not SDK exports. The separate [events API](events.md) exposes normalized assistant text, provider-exposed reasoning, tool previews, lifecycle, approvals and safe errors. Applications own persistence; Subharness has no chat database. SDK applications consume that source directly for custom behavior. [User extensions](extensions.md) run in separate coordinator-supervised processes for sessions selected at admission; embedded runners do not load them.
12
12
 
13
13
  ## Connect without running the CLI first
14
14
 
@@ -65,13 +65,15 @@ A string selects a discovered qualified reference or unambiguous name. Reserved
65
65
 
66
66
  Catalog discovery imports trusted definition modules in isolated coordinator-owned evaluation; it does not start native harnesses or call models. The finite discovered-definition inventory remains unpaginated; there is no artificial catalog-size cap. Discovery is not proof of readiness. `check` opens and closes a disposable native startup session without a prompt, retained conversation, or task; it rejects safely on startup/authentication/configuration/cleanup failure and does not promise a later model call will succeed.
67
67
 
68
+ Explicit definition-file targets belong to CLI `run` and `check`; connected SDK string targets do not accept paths. Embedded callers can import an arbitrary definition module and supply the definition object to `runner.createSession()`.
69
+
68
70
  `create` resolves the target and captures its loaded definition graph and environment once, then returns an empty session. Editing definition files affects newly created sessions, not an existing captured conversation. Definition functions live on the coordinator host; client closures cannot be transferred. Native harness startup stays lazy until dispatch. Invalid creation returns no session. A separate invalid `prompt` can leave a valid empty session, which the caller may reuse or close. The CLI's atomic first-prompt boundary is preserved separately below.
69
71
 
70
72
  For connected creation/check, omission of `env` snapshots the calling process environment at that operation. An explicit `env` replaces it, with undefined entries omitted. Inherited `AGENT_PARENT_TOKEN` and `AGENT_CLI_PATH` are stripped, and the selected coordinator supplies `AGENT_STATE_DIR`; managed authority is bound separately. This resulting environment governs definition resolution and module evaluation as well as native startup/execution, so environment-dependent imports use the same chosen values. Catalog listing evaluates definitions with its implicit caller snapshot under the same stripping/injection rules. Existing cwd-based project discovery and personal-settings conventions still apply. The environment is privately transferred and captured for the session; follow-ups do not replace it. No caller-supplied environment grants parent authority. Neither the host cwd nor the shared daemon's `process.env` is mutated, and environment/access values never appear in metadata or errors.
71
73
 
72
74
  Connected and CLI-created sessions retain their loaded definition graph in an isolated owner process. Custom-tool callbacks execute in that graph owner's creation directory and captured environment, including callbacks used by managed children. A child's native harness may use a different requested working directory and native environment; that does not change the captured callback's ambient `process.cwd()` or `process.env`. Tools that operate on a child-specific location must use explicit paths or arguments. The graph owner does not inherit caller-supplied managed parent or launcher authority; native delegation instructions and launchers are bound separately to each session. This preserves closure state and avoids re-importing changed source or mutating shared process context.
73
75
 
74
- Connected sessions retain the CLI's existing per-project personal-settings and native-worker access resolution. Embedded runners retain their explicit `RunnerOptions.env`/`access` behavior and do not start reading those personal settings. Model credentials remain in the server/coordinator execution path, not UI payloads.
76
+ Public connected creation/check retains the CLI's default cwd-based project discovery, personal settings, and native-worker access resolution. [CLI `--root`](project-root.md) adds no field to connected or embedded creation options. A connected client can inspect or continue a CLI-created session with its retained logical root; it does not reselect that project. Embedded runners retain their explicit `RunnerOptions.env`/`access` behavior and do not start reading those personal settings. Model credentials remain in the server/coordinator execution path, not UI payloads.
75
77
 
76
78
  ## Connect to CLI work
77
79
 
@@ -132,9 +134,9 @@ openDetails({ prompt: details.prompt, response: details.latestResponse });
132
134
 
133
135
  Session/task pages default to 100 entries, with integer `limit` from 1 through 1,000. Entries follow admission insertion order. The first page captures a membership watermark; later pages exclude newly admitted records. Each page contains current state when read, not a transactionally frozen state snapshot. Opaque cursors bind the collection, coordinator instance, and filter; repeat the same `sessionId` filter when continuing. The limit may change between pages. Invalid or mismatched cursors reject with `INVALID_CURSOR`; cursors remain valid while that coordinator retains its records. No cursor means a fresh traversal.
134
136
 
135
- There is no collection-watch API in this version. Poll paged lists to find new work, and attach `task.watch()` for race-free current-state observation of selected tasks. Per-task revisions are not global list cursors. Lists contain no full prompts, responses, credentials, or environment values. `task.inspect()` adds the original admission prompt to the task snapshot; it is separate from every watch update. Steering does not overwrite that original prompt.
137
+ There is no collection snapshot-watch API. Poll paged lists for retained metadata and attach `task.watch()` for race-free current-state observation of selected tasks. `events.open({ scope: { kind: "all" } })` can observe live session/task activity, including future sessions, but its live stream is not a collection snapshot. Per-task revisions and list cursors remain metadata interfaces, separate from live events. Lists contain no full prompts, responses, credentials, or environment values. `task.inspect()` adds the original admission prompt to the task snapshot; it is separate from every watch update. Steering does not overwrite that original prompt.
136
138
 
137
- Task titles use the existing first nonempty prompt line, normalize whitespace/remove terminal controls, and cap at 120 Unicode code points. Task ordinals count admission within a session from one; steering retains the task's ordinal. Timestamps are Unix milliseconds. `updatedAt` starts at admission and records the coordinator's latest task activity update, not an observer read. `dispatchedAt` records first dispatch and is retained across native continuations and private recovery; it is absent for never-dispatched work. `failedAt` records the latest execution or stop-confirmation failure, and `finishedAt` records the terminal transition. Both terminal timestamps are cleared when private recovery reopens the task and are populated again on its next failure/terminal transition. Session summaries include execution cwd and workspace identity. Connected sessions can resolve repository grouping using existing CLI behavior; embedded sessions use their directory without introducing Git discovery.
139
+ Task titles use the existing first nonempty prompt line, normalize whitespace/remove terminal controls, and cap at 120 Unicode code points. Task ordinals count admission within a session from one; steering retains the task's ordinal. Timestamps are Unix milliseconds. `updatedAt` starts at admission and records the coordinator's latest task activity update, not an observer read. `dispatchedAt` records first dispatch and is retained across native continuations and private recovery; it is absent for never-dispatched work. `failedAt` records the latest execution or stop-confirmation failure, and `finishedAt` records the terminal transition. Both terminal timestamps are cleared when private recovery reopens the task and are populated again on its next failure/terminal transition. Session summaries include execution cwd and workspace identity. Connected sessions resolve repository grouping from actual execution cwd using existing CLI behavior; a CLI-selected logical root does not replace that workspace identity. Embedded sessions use their directory without introducing Git discovery.
138
140
 
139
141
  ## Disconnect and reconnect
140
142
 
@@ -313,7 +315,7 @@ async function stopTask(user: User, chatId: string, taskId: string) {
313
315
 
314
316
  A browser disconnect aborts only that watch. Do not disconnect the shared client in an HTTP request's `finally` block. The server disconnects it when its connection scope ends; explicit `task.cancel()` stops a task, and `session.close()` closes server-side execution for that session. An embedded backend instead owns a bounded runner, uses its local lookups and `respond`, and closes that runner when its chat/job scope ends.
315
317
 
316
- An initial list followed by each selected task's `watch()` gives a current view and race-free per-task observation: watch begins with the latest snapshot. It does not subscribe to newly created tasks; refresh the list as needed. There is no collection-watch API or global revision cursor. Parent snapshots include descendant approvals even when the parent is `running`. Authorize those relationships and treat displayed native content as untrusted data.
318
+ An initial list followed by each selected task's `watch()` gives a current view and race-free per-task observation: watch begins with the latest snapshot. It does not subscribe to newly created tasks; refresh the list as needed. There is no collection snapshot-watch API or global task-revision cursor. A separate bounded `events.open({ scope: { kind: "all" } })` stream can observe live activity; it does not replace metadata enumeration. Parent snapshots include descendant approvals even when the parent is `running`. Authorize those relationships and treat displayed native content as untrusted data.
317
319
 
318
320
  ## Render approval buttons
319
321
 
@@ -467,6 +469,7 @@ interface AgentSummary {
467
469
  interface PageOptions { readonly limit?: number; readonly cursor?: string }
468
470
  interface Page<T> { readonly items: readonly T[]; readonly nextCursor?: string }
469
471
  interface Client {
472
+ readonly events: SessionEventSource;
470
473
  readonly agents: {
471
474
  list(options: { readonly cwd: string }): Promise<{ readonly items: readonly AgentSummary[] }>;
472
475
  check(options: ConnectedSessionOptions): Promise<void>;
@@ -490,6 +493,7 @@ declare function createRunner(options?: RunnerOptions): Runner;
490
493
  type Delivery = "queue" | "steer" | "interrupt";
491
494
 
492
495
  interface Runner {
496
+ readonly events: SessionEventSource;
493
497
  createSession(
494
498
  definition: AgentDefinition,
495
499
  options: { readonly cwd: string },
@@ -578,6 +582,8 @@ interface TaskResult {
578
582
  }
579
583
  ```
580
584
 
585
+ `SessionEventSource` and its subscription/event types are defined in [Live session events](events.md). Opening a subscription registers live delivery before its promise resolves; it does not change session configuration. Routes requiring startup-only partial-output options enable them for every session. SDK applications consume events directly. Coordinator session admission also resolves the current user's enabled global and repository extensions, including for `client.sessions.create`; those modules run only in separate supervised children. CLI root-selected sessions use that root's repository extension scope independently of execution cwd, while public connected creation retains default cwd-based scope. Embedded runners never load user extensions.
586
+
581
587
  `createSession` validates and captures the definition and existing absolute working directory, but starts native execution lazily when work is dispatched. A prompt must contain non-whitespace text and fit the existing 1 MiB limit. `prompt` returns after admission or acceptance of steering, not after native startup or completion. Invalid admission rejects without creating a task. A native startup failure after admission is a failed task.
582
588
 
583
589
  `task.result` resolves only when the parent task reaches `completed`, after children, child-result delivery, and parent continuations finish. Its text comes from the final parent response, not the first waiting response, a child response, or concatenated history. Empty text is valid. Completion reports execution completion, not proof that the requested objective succeeded: an answer explaining a failing test can still be complete.
@@ -647,9 +653,9 @@ The normalization covers the existing adapters without extending their native pe
647
653
 
648
654
  ### Ownership and transport boundaries
649
655
 
650
- Discovery precedence is explicit `ConnectOptions.stateDirectory`, then `AGENT_STATE_DIR`, then `~/.subharness/state/shared`. Explicit paths must be nonempty absolute local paths and are canonicalized. The CLI uses the same environment/default selection rule; installation location and cwd do not create separate default coordinators. Endpoint metadata is owner-private, with a private authentication token and loopback-only transport. Invalid state-directory or endpoint configuration rejects with `INVALID_CONFIG`.
656
+ Discovery precedence is explicit `ConnectOptions.stateDirectory`, then `AGENT_STATE_DIR`, then `~/.subharness/state/shared`. Explicit paths must be nonempty absolute local paths and are canonicalized. The CLI uses the same environment/default selection rule; installation location, cwd, and CLI `--root` do not create separate default coordinators. Endpoint metadata is owner-private, with a private authentication token and loopback-only transport. Invalid state-directory or endpoint configuration rejects with `INVALID_CONFIG`.
651
657
 
652
- The handshake validates the endpoint's coordinator instance ID, SDK protocol version `1`, and the `sdk-v1` capability; the private CLI bridge additionally requires `cli-v1`. Package versions need not match. A missing/incompatible protocol or required capability rejects with `COORDINATOR_INCOMPATIBLE`; authentication rejection uses `COORDINATOR_AUTH_FAILED`. Missing strict-attachment targets and uncertain reachability use `COORDINATOR_UNAVAILABLE`. A live incompatible or unreachable coordinator is never replaced to make connection succeed.
658
+ The handshake validates the endpoint's coordinator instance ID, SDK protocol version `1`, and the `sdk-v1` capability; the private CLI bridge additionally requires `cli-v1`. The handshake advertises `session-events-v1` for live event operations. Its absence rejects an event operation with `COORDINATOR_INCOMPATIBLE` while leaving supported execution and inspection operations usable. Package versions need not match. A missing/incompatible protocol or required capability rejects with `COORDINATOR_INCOMPATIBLE`; authentication rejection uses `COORDINATOR_AUTH_FAILED`. Missing strict-attachment targets and uncertain reachability use `COORDINATOR_UNAVAILABLE`. A live incompatible or unreachable coordinator is never replaced to make connection succeed.
653
659
 
654
660
  `connect()` defaults to start-or-connect; `start: false` never starts. The entire discovery, health check, handshake, and startup path has a 15-second deadline, including attachment without startup. Final confirmation may add at most one second for unpublished-candidate retirement and 250 milliseconds for a final endpoint check. The final check distinguishes a candidate that published at the deadline from one that retired, without replacing uncertain execution. Attach/health/handshake deadline failures use `COORDINATOR_UNAVAILABLE`; startup failure uses `STARTUP_FAILED`. Neither path can wait indefinitely.
655
661
 
@@ -670,13 +676,15 @@ The CLI consumes the same library connection, discovery, admission, observation,
670
676
  | Private operation | Preserved behavior |
671
677
  | --- | --- |
672
678
  | Catalog and readiness | Ordinary top-level CLI `list`/`check` use the same library helpers behind `client.agents` without requiring or starting a coordinator. Managed calls carrying `AGENT_PARENT_TOKEN` must first attach to the existing coordinator, validate the active parent, and narrow the child capability before discovery/check. Validation failure never falls back to external-owner authority. Definition loading and disposable readiness startup keep their existing side effects. |
679
+ | Logical project selection | CLI `--root` selects and retains project/access roots independently of execution cwd, including for all target forms and managed descendants. Root-selected runs and managed `list`, `check`, or `run` commands supplying `--root` require `cli-root-v1`; unsupported live coordinators yield `COORDINATOR_OUTDATED` before submission. Public connected/embedded creation signatures remain unchanged. See [logical project roots](project-root.md). |
673
680
  | Atomic `run` | Resolve/capture the target, environment, and first prompt before publishing one session and its first task together. Invalid input publishes neither; native failure after admission becomes task failure. It is not two independently visible public calls. |
674
681
  | Attached run/send and `wait` | Use a one-observation helper returning the existing response, approval, or terminal record. Preserve response-cursor precedence, detach boundaries, and steering acknowledgement. Do not replace first-response waiting with final `task.result`. |
675
682
  | Managed delegation | Bind the active parent capability out-of-band. Preserve declared-child discovery, lineage, maximum depth, self/ancestor restrictions, and strict-descendant authority. The public client neither accepts raw parent tokens nor infers them from environment variables. |
676
683
  | Managed wait acknowledgement | Only the private active-parent observation path acknowledges delivered terminal child results under existing rules. Public result/watch/replay never perform that coordination effect. |
677
684
  | CLI `resume` | Retain the private operation and receipt/observation compatibility with a fresh observation scope. Codex, Claude Code, and fx all reject prompt-free native recovery with `RECOVERY_UNSUPPORTED`; no public resume method or successful recovery guarantee is added. |
685
+ | CLI `close` | Reuse connected `session.close()` semantics through the existing `sdk-session-close` service operation. The CLI attaches only, emits its own `closed` presentation record after cleanup, and maps a coordinator without that operation to `COORDINATOR_OUTDATED`. |
678
686
  | Status and queue | Preserve the existing status response projection: default response text is sliced to 4,000 characters with its truncation flag, while `--full` returns the complete response. Queue descriptions remain the raw admission prompt's first 120 characters (`prompt.slice(0, 120)`), with existing active/queued records and paused state. Normalized public titles are not a substitute for this CLI output. |
679
- | Dashboard inspection | Derive summaries and expanded detail from the common records; keep terminal-specific grouping, truncation, and efficient private payload formatting outside the public model. |
687
+ | Dashboard inspection | Derive summaries and task-screen details from common records; keep terminal grouping, truncation and private metadata projections outside the public model. The core task screen renders steps from the public live event API and does not load user extensions. |
680
688
 
681
689
  CLI connection policy stays command-specific: `run` can start the coordinator; follow-up, observation, and control commands attach only. An absent coordinator leaves the dashboard in its existing waiting view without auto-start. These policies use the shared connection implementation, not a second transport.
682
690
 
@@ -712,11 +720,25 @@ Host custom tools keep the existing `execute(input)` signature. They run in the
712
720
 
713
721
  The SDK exports `AgentError` and `ErrorInfo`. Input/lookup/control errors reject calls; execution failure after admission is task data. Existing error codes remain in use. `RUNNER_CLOSED` and `SESSION_CLOSED` identify closed-owner admission/control attempts; reads and close retries remain available. `cancel` on terminal work is still an inspection even after close. Unknown option/input shapes reject with `INVALID_ARGUMENT`, invalid definitions with `INVALID_DEFINITION`, and invalid access configuration with `INVALID_CONFIG`.
714
722
 
723
+ Live event errors use the same safe `AgentError` / `ErrorInfo` contract:
724
+
725
+ | Code | Event operation behavior |
726
+ | --- | --- |
727
+ | `EVENT_BACKPRESSURE` | A subscription exceeds 128 events or 1 MiB of pending delivery; its stream rejects without slowing execution. |
728
+ | `OBSERVATION_CLOSED` | `events.open` rejects an already aborted signal without registering; a later signal abort rejects the pending event read. Observation cancellation does not cancel execution. |
729
+ | `COORDINATOR_INCOMPATIBLE` | The connected event operation requires the missing `session-events-v1` capability; supported execution/inspection operations remain available. |
730
+ | `UNKNOWN_SESSION` | Event subscription or capability lookup names an unknown session. `capabilities` returns `undefined` only for a known session before harness selection. |
731
+ | `UNKNOWN_TASK` | Task-scoped subscription names an unknown task. |
732
+
733
+ The dashboard maps the event operation's missing `session-events-v1` support to `COORDINATOR_OUTDATED` with coordinator restart guidance in place of live steps while keeping core task content visible. This presentation does not change the SDK error code.
734
+
735
+ Extension-instance failures remain separate from task failures. The CLI displays `EXTENSION_*` codes and safe messages only through `subharness extensions list`, under [Error diagnostics](diagnostics.md#live-events-and-extensions). They also remain available through the coordinator's existing safe diagnostics, never including extension log contents. The dashboard neither loads nor hosts extensions and does not display extension diagnostics.
736
+
715
737
  ## Contract boundaries
716
738
 
717
739
  Connected and embedded execution share the session, task, and approval contracts above. Native adapters retain their documented capability limits; the SDK does not add a model loop or native permission system.
718
740
 
719
- No public native recovery, collection watch, automatic mutation retry, public idempotency keys, arbitrary remote endpoints, closure transfer, or restart persistence is promised. Polling, per-task observation, explicit connection failure, and breaking-release migration are the defined behavior. Original tool input and the exclusion of persistent settings changes remain approval limits; applications own the UI layout.
741
+ No public native recovery, collection snapshot watch, automatic mutation retry, public idempotency keys, arbitrary remote endpoints, closure transfer or restart persistence is promised. Polling, per-task observation, scoped live events, explicit connection failure and breaking-release migration are the defined behavior. Original tool input and the exclusion of persistent settings changes remain approval limits; applications own the UI layout.
720
742
 
721
743
  ## Hosted delegation
722
744