@gajae-code/coding-agent 0.11.1 → 0.11.2

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 (404) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/types/cli/config-cli.d.ts +11 -1
  3. package/dist/types/cli/notify-cli.d.ts +1 -0
  4. package/dist/types/cli/session-picker.d.ts +2 -1
  5. package/dist/types/cli/setup-cli.d.ts +1 -1
  6. package/dist/types/commands/mcp-serve.d.ts +33 -0
  7. package/dist/types/commands/mcp.d.ts +1 -1
  8. package/dist/types/commands/notify.d.ts +0 -2
  9. package/dist/types/commands/sdk.d.ts +1 -1
  10. package/dist/types/config/atomic-yaml-patch.d.ts +18 -0
  11. package/dist/types/config/file-lock.d.ts +14 -4
  12. package/dist/types/config/keybindings.d.ts +42 -1
  13. package/dist/types/config/model-auth.d.ts +3 -0
  14. package/dist/types/config/model-bindings-applier.d.ts +13 -0
  15. package/dist/types/config/model-discovery-manager.d.ts +49 -0
  16. package/dist/types/config/model-equivalence.d.ts +20 -0
  17. package/dist/types/config/model-registry.d.ts +16 -15
  18. package/dist/types/config/model-resolver.d.ts +28 -18
  19. package/dist/types/config/models-config-schema.d.ts +11 -0
  20. package/dist/types/config/settings-schema.d.ts +56 -1
  21. package/dist/types/config/settings.d.ts +14 -11
  22. package/dist/types/coordinator-mcp/policy.d.ts +5 -0
  23. package/dist/types/coordinator-mcp/question-gate-codec.d.ts +129 -0
  24. package/dist/types/coordinator-mcp/question-state.d.ts +356 -0
  25. package/dist/types/coordinator-mcp/server.d.ts +4 -0
  26. package/dist/types/discovery/helpers.d.ts +0 -6
  27. package/dist/types/edit/index.d.ts +3 -0
  28. package/dist/types/eval/py/env.d.ts +9 -0
  29. package/dist/types/extensibility/extensions/loader.d.ts +2 -1
  30. package/dist/types/extensibility/extensions/runner.d.ts +2 -2
  31. package/dist/types/extensibility/extensions/types.d.ts +34 -3
  32. package/dist/types/extensibility/hooks/runner.d.ts +1 -1
  33. package/dist/types/extensibility/shared-events.d.ts +2 -0
  34. package/dist/types/gjc-runtime/deep-interview-recorder.d.ts +10 -1
  35. package/dist/types/gjc-runtime/deep-interview-state.d.ts +44 -0
  36. package/dist/types/gjc-runtime/goal-mode-request.d.ts +11 -1
  37. package/dist/types/gjc-runtime/launch-worktree.d.ts +4 -2
  38. package/dist/types/gjc-runtime/linux-proc.d.ts +29 -0
  39. package/dist/types/gjc-runtime/session-resolution.d.ts +2 -2
  40. package/dist/types/gjc-runtime/state-migrations.d.ts +1 -1
  41. package/dist/types/gjc-runtime/state-writer.d.ts +2 -1
  42. package/dist/types/gjc-runtime/team-launch.d.ts +59 -0
  43. package/dist/types/gjc-runtime/team-notify.d.ts +45 -0
  44. package/dist/types/gjc-runtime/team-runtime.d.ts +29 -121
  45. package/dist/types/gjc-runtime/team-store.d.ts +160 -0
  46. package/dist/types/gjc-runtime/team-workers.d.ts +78 -0
  47. package/dist/types/gjc-runtime/tmux-owner-isolation.d.ts +8 -0
  48. package/dist/types/gjc-runtime/ultragoal-change-set.d.ts +13 -0
  49. package/dist/types/gjc-runtime/ultragoal-evidence.d.ts +38 -0
  50. package/dist/types/gjc-runtime/ultragoal-guard.d.ts +7 -0
  51. package/dist/types/gjc-runtime/ultragoal-pipeline.d.ts +23 -0
  52. package/dist/types/gjc-runtime/ultragoal-runtime.d.ts +55 -33
  53. package/dist/types/gjc-runtime/workflow-cli-common.d.ts +8 -0
  54. package/dist/types/gjc-runtime/workflow-manifest.d.ts +3 -0
  55. package/dist/types/goals/continuation-timeout-guard.d.ts +22 -0
  56. package/dist/types/goals/runtime.d.ts +1 -0
  57. package/dist/types/goals/state.d.ts +8 -0
  58. package/dist/types/harness-control-plane/lifecycle-reconciliation.d.ts +17 -0
  59. package/dist/types/harness-control-plane/phase-rollup.d.ts +4 -7
  60. package/dist/types/harness-control-plane/receipt-ingest.d.ts +5 -0
  61. package/dist/types/harness-control-plane/receipt-spool.d.ts +4 -0
  62. package/dist/types/hindsight/state.d.ts +11 -4
  63. package/dist/types/lsp/lspmux.d.ts +5 -3
  64. package/dist/types/lsp/path-trust.d.ts +1 -0
  65. package/dist/types/main.d.ts +3 -2
  66. package/dist/types/memories/storage.d.ts +1 -0
  67. package/dist/types/modes/action-registry.d.ts +29 -0
  68. package/dist/types/modes/components/chrome.d.ts +14 -0
  69. package/dist/types/modes/components/command-palette.d.ts +27 -0
  70. package/dist/types/modes/components/custom-provider-wizard.d.ts +1 -0
  71. package/dist/types/modes/components/index.d.ts +2 -1
  72. package/dist/types/modes/components/pet-selector.d.ts +1 -1
  73. package/dist/types/modes/components/plan-preview-overlay.d.ts +43 -0
  74. package/dist/types/modes/components/queue-mode-selector.d.ts +1 -1
  75. package/dist/types/modes/components/queue-pane.d.ts +12 -0
  76. package/dist/types/modes/components/read-tool-group.d.ts +6 -0
  77. package/dist/types/modes/components/session-observer-overlay.d.ts +3 -4
  78. package/dist/types/modes/components/sessions-dashboard.d.ts +32 -0
  79. package/dist/types/modes/components/settings-selector.d.ts +1 -1
  80. package/dist/types/modes/components/show-images-selector.d.ts +1 -1
  81. package/dist/types/modes/components/status-line/types.d.ts +1 -1
  82. package/dist/types/modes/components/status-line.d.ts +1 -94
  83. package/dist/types/modes/components/tasks-pane.d.ts +15 -0
  84. package/dist/types/modes/components/theme-selector.d.ts +1 -1
  85. package/dist/types/modes/components/tool-execution.d.ts +15 -0
  86. package/dist/types/modes/components/tool-status-header.d.ts +111 -0
  87. package/dist/types/modes/components/transcript-viewer-overlay.d.ts +42 -0
  88. package/dist/types/modes/controllers/goal-mode-controller.d.ts +62 -0
  89. package/dist/types/modes/controllers/input-controller.d.ts +8 -1
  90. package/dist/types/modes/controllers/mode-gate.d.ts +8 -0
  91. package/dist/types/modes/controllers/plan-mode-controller.d.ts +65 -0
  92. package/dist/types/modes/controllers/selector-controller.d.ts +15 -3
  93. package/dist/types/modes/controllers/stt-controller.d.ts +26 -0
  94. package/dist/types/modes/interactive-mode.d.ts +19 -17
  95. package/dist/types/modes/jobs-observer.d.ts +2 -0
  96. package/dist/types/modes/shared/agent-wire/deep-interview-gate.d.ts +4 -11
  97. package/dist/types/modes/shared/agent-wire/workflow-gate-broker.d.ts +20 -2
  98. package/dist/types/modes/shared/agent-wire/workflow-gate-types.d.ts +31 -0
  99. package/dist/types/modes/tasks-aggregator.d.ts +39 -0
  100. package/dist/types/modes/transcript-item-registry.d.ts +60 -0
  101. package/dist/types/modes/types.d.ts +20 -13
  102. package/dist/types/modes/utils/ui-helpers.d.ts +2 -2
  103. package/dist/types/runtime-mcp/manager.d.ts +1 -1
  104. package/dist/types/sdk/broker/broker.d.ts +78 -12
  105. package/dist/types/sdk/broker/lifecycle-codec.d.ts +4 -0
  106. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +15 -1
  107. package/dist/types/sdk/broker/lifecycle.d.ts +6 -2
  108. package/dist/types/sdk/broker/process-incarnation.d.ts +2 -0
  109. package/dist/types/sdk/broker/session-index.d.ts +0 -1
  110. package/dist/types/sdk/broker/state-version.d.ts +2 -0
  111. package/dist/types/sdk/bus/chat-effect-journal.d.ts +1 -0
  112. package/dist/types/sdk/bus/config-commands.d.ts +1 -1
  113. package/dist/types/sdk/bus/config.d.ts +11 -0
  114. package/dist/types/sdk/bus/daemon-paths.d.ts +1 -0
  115. package/dist/types/sdk/bus/html-format.d.ts +3 -2
  116. package/dist/types/sdk/bus/index.d.ts +27 -0
  117. package/dist/types/sdk/bus/lifecycle-control-runtime.d.ts +4 -0
  118. package/dist/types/sdk/bus/notification-service.d.ts +20 -0
  119. package/dist/types/sdk/bus/rate-limit-pool.d.ts +13 -2
  120. package/dist/types/sdk/bus/recent-activity.d.ts +21 -12
  121. package/dist/types/sdk/bus/rich-document.d.ts +7 -0
  122. package/dist/types/sdk/bus/rich-render.d.ts +18 -41
  123. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +9 -4
  124. package/dist/types/sdk/bus/telegram-daemon.d.ts +46 -3
  125. package/dist/types/sdk/bus/threaded-inbound.d.ts +1 -1
  126. package/dist/types/sdk/bus/threaded-render.d.ts +13 -0
  127. package/dist/types/sdk/bus/topic-registry.d.ts +24 -2
  128. package/dist/types/sdk/host/control/operations.d.ts +1 -1
  129. package/dist/types/sdk/host/host.d.ts +2 -0
  130. package/dist/types/sdk/index.d.ts +1 -0
  131. package/dist/types/sdk/session-directory.d.ts +56 -0
  132. package/dist/types/session/agent-session.d.ts +82 -47
  133. package/dist/types/session/agent-storage.d.ts +7 -0
  134. package/dist/types/session/fallback-chain-controller.d.ts +10 -2
  135. package/dist/types/session/internal/managed-session-scope.d.ts +102 -0
  136. package/dist/types/session/internal/managed-session-storage.d.ts +38 -0
  137. package/dist/types/session/messages.d.ts +16 -0
  138. package/dist/types/session/session-manager-internal.d.ts +14 -0
  139. package/dist/types/session/session-manager.d.ts +82 -12
  140. package/dist/types/session/session-storage.d.ts +43 -3
  141. package/dist/types/session/volatile-context-pruning.d.ts +15 -0
  142. package/dist/types/skill-state/{deep-interview-mutation-guard.d.ts → workflow-mutation-guard.d.ts} +24 -8
  143. package/dist/types/skill-state/workflow-state-contract.d.ts +1 -3
  144. package/dist/types/slash-commands/builtin-registry.d.ts +4 -1
  145. package/dist/types/system-prompt.d.ts +2 -11
  146. package/dist/types/task/executor.d.ts +3 -1
  147. package/dist/types/thinking.d.ts +7 -0
  148. package/dist/types/tool-discovery/tool-index.d.ts +1 -50
  149. package/dist/types/tools/ask.d.ts +64 -2
  150. package/dist/types/tools/bash.d.ts +3 -0
  151. package/dist/types/tools/browser/dead-tab-recovery.d.ts +24 -0
  152. package/dist/types/tools/browser/tab-supervisor.d.ts +21 -0
  153. package/dist/types/tools/cron.d.ts +2 -0
  154. package/dist/types/tools/fetch.d.ts +1 -0
  155. package/dist/types/tools/index.d.ts +30 -15
  156. package/dist/types/tools/output-meta.d.ts +1 -0
  157. package/dist/types/tools/read.d.ts +3 -0
  158. package/dist/types/tools/search-tool-bm25.d.ts +3 -4
  159. package/dist/types/utils/event-bus.d.ts +1 -1
  160. package/dist/types/web/search/index.d.ts +3 -1
  161. package/package.json +21 -9
  162. package/scripts/build-sdk-package-smoke.ts +34 -1
  163. package/scripts/generate-hotkeys-docs.ts +74 -0
  164. package/scripts/generate-sdk-operation-inventory.ts +64 -20
  165. package/scripts/verify-gjc-sdk-canonicalization.ts +182 -2
  166. package/src/async/job-manager.ts +49 -6
  167. package/src/cli/config-cli.ts +75 -2
  168. package/src/cli/notify-cli.ts +92 -26
  169. package/src/cli/session-picker.ts +20 -3
  170. package/src/cli/setup-cli.ts +1 -1
  171. package/src/cli.ts +1 -1
  172. package/src/commands/config.ts +1 -1
  173. package/src/commands/harness.ts +34 -106
  174. package/src/commands/launch.ts +6 -4
  175. package/src/commands/mcp-serve.ts +85 -8
  176. package/src/commands/mcp.ts +2 -2
  177. package/src/commands/notify.ts +8 -4
  178. package/src/commands/sdk.ts +61 -40
  179. package/src/commands/ultragoal.ts +4 -1
  180. package/src/config/atomic-yaml-patch.ts +80 -13
  181. package/src/config/file-lock.ts +105 -43
  182. package/src/config/keybindings.ts +64 -20
  183. package/src/config/model-auth.ts +9 -0
  184. package/src/config/model-bindings-applier.ts +139 -0
  185. package/src/config/model-discovery-manager.ts +224 -0
  186. package/src/config/model-equivalence.ts +66 -0
  187. package/src/config/model-registry.ts +169 -302
  188. package/src/config/model-resolver.ts +361 -369
  189. package/src/config/models-config-schema.ts +5 -4
  190. package/src/config/settings-schema.ts +159 -2
  191. package/src/config/settings.ts +458 -482
  192. package/src/coordinator-mcp/policy.ts +76 -11
  193. package/src/coordinator-mcp/question-gate-codec.ts +274 -0
  194. package/src/coordinator-mcp/question-state.ts +778 -0
  195. package/src/coordinator-mcp/server.ts +1702 -238
  196. package/src/debug/index.ts +1 -1
  197. package/src/defaults/gjc/skills/deep-interview/SKILL.md +13 -1
  198. package/src/defaults/gjc/skills/team/SKILL.md +16 -0
  199. package/src/discovery/helpers.ts +1 -50
  200. package/src/edit/index.ts +64 -0
  201. package/src/eval/py/env.ts +26 -0
  202. package/src/eval/py/kernel.ts +5 -3
  203. package/src/extensibility/extensions/loader.ts +9 -1
  204. package/src/extensibility/extensions/runner.ts +12 -3
  205. package/src/extensibility/extensions/types.ts +39 -1
  206. package/src/extensibility/gjc-plugins/installer.ts +16 -16
  207. package/src/extensibility/hooks/runner.ts +2 -2
  208. package/src/extensibility/runtime-skill-discovery.ts +33 -13
  209. package/src/extensibility/shared-events.ts +2 -0
  210. package/src/gjc-runtime/deep-interview-recorder.ts +63 -3
  211. package/src/gjc-runtime/deep-interview-runtime.ts +76 -27
  212. package/src/gjc-runtime/deep-interview-state.ts +317 -5
  213. package/src/gjc-runtime/goal-mode-request.ts +55 -8
  214. package/src/gjc-runtime/launch-tmux.ts +2 -5
  215. package/src/gjc-runtime/launch-worktree.ts +5 -5
  216. package/src/gjc-runtime/linux-proc.ts +71 -0
  217. package/src/gjc-runtime/ralplan-runtime.ts +74 -90
  218. package/src/gjc-runtime/session-resolution.ts +18 -3
  219. package/src/gjc-runtime/session-state-sidecar.ts +6 -107
  220. package/src/gjc-runtime/state-migrations.ts +1 -1
  221. package/src/gjc-runtime/state-runtime.ts +320 -249
  222. package/src/gjc-runtime/state-writer.ts +36 -40
  223. package/src/gjc-runtime/team-launch.ts +319 -0
  224. package/src/gjc-runtime/team-notify.ts +326 -0
  225. package/src/gjc-runtime/team-runtime.ts +1099 -1482
  226. package/src/gjc-runtime/team-store.ts +828 -0
  227. package/src/gjc-runtime/team-workers.ts +962 -0
  228. package/src/gjc-runtime/tmux-owner-isolation-cli.ts +2 -11
  229. package/src/gjc-runtime/tmux-owner-isolation.ts +14 -9
  230. package/src/gjc-runtime/tmux-sessions.ts +4 -21
  231. package/src/gjc-runtime/ultragoal-change-set.ts +172 -0
  232. package/src/gjc-runtime/ultragoal-evidence.ts +874 -0
  233. package/src/gjc-runtime/ultragoal-guard.ts +29 -5
  234. package/src/gjc-runtime/ultragoal-pipeline.ts +306 -0
  235. package/src/gjc-runtime/ultragoal-runtime.ts +84 -1311
  236. package/src/gjc-runtime/workflow-cli-common.ts +30 -0
  237. package/src/gjc-runtime/workflow-manifest.generated.json +58 -0
  238. package/src/gjc-runtime/workflow-manifest.ts +18 -0
  239. package/src/goals/continuation-timeout-guard.ts +79 -0
  240. package/src/goals/runtime.ts +7 -5
  241. package/src/goals/state.ts +18 -0
  242. package/src/harness-control-plane/lifecycle-reconciliation.ts +64 -0
  243. package/src/harness-control-plane/phase-rollup.ts +4 -7
  244. package/src/harness-control-plane/receipt-ingest.ts +5 -0
  245. package/src/harness-control-plane/receipt-spool.ts +51 -7
  246. package/src/harness-control-plane/session-lease.ts +12 -130
  247. package/src/hindsight/backend.ts +26 -27
  248. package/src/hindsight/state.ts +101 -32
  249. package/src/hooks/skill-state.ts +17 -11
  250. package/src/internal-urls/docs-index.generated.ts +21 -18
  251. package/src/lsp/client.ts +1 -1
  252. package/src/lsp/config.ts +145 -26
  253. package/src/lsp/index.ts +1 -1
  254. package/src/lsp/lspmux.ts +39 -10
  255. package/src/lsp/path-trust.ts +81 -0
  256. package/src/main.ts +28 -8
  257. package/src/memories/index.ts +1 -0
  258. package/src/memories/storage.ts +6 -2
  259. package/src/modes/action-registry.ts +165 -0
  260. package/src/modes/components/chrome.ts +40 -0
  261. package/src/modes/components/command-palette.ts +168 -0
  262. package/src/modes/components/custom-editor.ts +1 -1
  263. package/src/modes/components/custom-provider-wizard.ts +51 -14
  264. package/src/modes/components/index.ts +2 -1
  265. package/src/modes/components/pet-selector.ts +11 -17
  266. package/src/modes/components/plan-preview-overlay.ts +295 -0
  267. package/src/modes/components/queue-mode-selector.ts +10 -27
  268. package/src/modes/components/queue-pane.ts +79 -0
  269. package/src/modes/components/read-tool-group.ts +13 -0
  270. package/src/modes/components/session-observer-overlay.ts +207 -772
  271. package/src/modes/components/sessions-dashboard.ts +181 -0
  272. package/src/modes/components/settings-selector.ts +1 -1
  273. package/src/modes/components/show-images-selector.ts +10 -24
  274. package/src/modes/components/status-line/types.ts +1 -1
  275. package/src/modes/components/status-line.ts +1 -969
  276. package/src/modes/components/tasks-pane.ts +73 -0
  277. package/src/modes/components/theme-selector.ts +11 -31
  278. package/src/modes/components/tool-execution.ts +22 -0
  279. package/src/modes/components/tool-status-header.ts +1056 -0
  280. package/src/modes/components/transcript-viewer-overlay.ts +384 -0
  281. package/src/modes/controllers/btw-controller.ts +1 -0
  282. package/src/modes/controllers/event-controller.ts +3 -2
  283. package/src/modes/controllers/extension-ui-controller.ts +24 -1
  284. package/src/modes/controllers/goal-mode-controller.ts +474 -0
  285. package/src/modes/controllers/input-controller.ts +764 -229
  286. package/src/modes/controllers/mode-gate.ts +24 -0
  287. package/src/modes/controllers/plan-mode-controller.ts +517 -0
  288. package/src/modes/controllers/selector-controller.ts +225 -10
  289. package/src/modes/controllers/stt-controller.ts +125 -0
  290. package/src/modes/interactive-mode.ts +289 -1150
  291. package/src/modes/jobs-observer.ts +3 -0
  292. package/src/modes/runtime-init.ts +8 -0
  293. package/src/modes/shared/agent-wire/deep-interview-gate.ts +31 -106
  294. package/src/modes/shared/agent-wire/workflow-gate-broker.ts +71 -16
  295. package/src/modes/shared/agent-wire/workflow-gate-types.ts +177 -0
  296. package/src/modes/tasks-aggregator.ts +199 -0
  297. package/src/modes/transcript-item-registry.ts +229 -0
  298. package/src/modes/types.ts +45 -18
  299. package/src/modes/utils/ui-helpers.ts +17 -9
  300. package/src/prompts/agent-fragments/ralplan-persistence.md +6 -0
  301. package/src/prompts/agent-fragments/restricted-bash.md +1 -0
  302. package/src/prompts/agents/architect.md +2 -8
  303. package/src/prompts/agents/critic.md +2 -8
  304. package/src/prompts/agents/executor.md +3 -0
  305. package/src/prompts/agents/planner.md +4 -12
  306. package/src/prompts/system/custom-system-prompt.md +1 -23
  307. package/src/prompts/system/plan-mode-approved.md +8 -0
  308. package/src/prompts/system/system-prompt.md +17 -96
  309. package/src/prompts/tools/bash.md +4 -4
  310. package/src/prompts/tools/browser.md +15 -52
  311. package/src/prompts/tools/find.md +2 -2
  312. package/src/prompts/tools/hashline.md +13 -55
  313. package/src/prompts/tools/read.md +3 -6
  314. package/src/prompts/tools/search-tool-bm25.md +0 -2
  315. package/src/prompts/tools/search.md +2 -4
  316. package/src/prompts/tools/skill-discovery.md +1 -2
  317. package/src/prompts/tools/task.md +1 -1
  318. package/src/runtime-mcp/manager.ts +1 -1
  319. package/src/sdk/broker/broker.ts +206 -78
  320. package/src/sdk/broker/discovery.ts +1 -1
  321. package/src/sdk/broker/ensure.ts +3 -1
  322. package/src/sdk/broker/lifecycle-codec.ts +11 -0
  323. package/src/sdk/broker/lifecycle-ledger.ts +371 -74
  324. package/src/sdk/broker/lifecycle.ts +1399 -142
  325. package/src/sdk/broker/process-incarnation.ts +5 -13
  326. package/src/sdk/broker/session-index.ts +145 -56
  327. package/src/sdk/broker/state-version.ts +21 -0
  328. package/src/sdk/broker/transport.ts +1 -1
  329. package/src/sdk/bus/chat-daemon-cli.ts +2 -0
  330. package/src/sdk/bus/chat-daemon-control.ts +8 -28
  331. package/src/sdk/bus/chat-effect-journal.ts +10 -2
  332. package/src/sdk/bus/config-commands.ts +5 -4
  333. package/src/sdk/bus/config.ts +98 -0
  334. package/src/sdk/bus/conversation-store.ts +5 -29
  335. package/src/sdk/bus/daemon-paths.ts +2 -0
  336. package/src/sdk/bus/html-format.ts +20 -3
  337. package/src/sdk/bus/index.ts +778 -93
  338. package/src/sdk/bus/lifecycle-control-runtime.ts +91 -33
  339. package/src/sdk/bus/natives-augment.d.ts +26 -1
  340. package/src/sdk/bus/notification-service.ts +168 -20
  341. package/src/sdk/bus/rate-limit-pool.ts +58 -14
  342. package/src/sdk/bus/recent-activity.ts +188 -74
  343. package/src/sdk/bus/rich-document.ts +258 -0
  344. package/src/sdk/bus/rich-render.ts +62 -70
  345. package/src/sdk/bus/telegram-daemon-cli.ts +15 -59
  346. package/src/sdk/bus/telegram-daemon-contract.ts +9 -4
  347. package/src/sdk/bus/telegram-daemon.ts +1389 -237
  348. package/src/sdk/bus/threaded-inbound.ts +8 -3
  349. package/src/sdk/bus/threaded-render.ts +57 -1
  350. package/src/sdk/bus/topic-registry.ts +120 -13
  351. package/src/sdk/host/control/dispatch.ts +14 -2
  352. package/src/sdk/host/control/operations.ts +6 -1
  353. package/src/sdk/host/host.ts +31 -1
  354. package/src/sdk/host/query/handlers.ts +20 -22
  355. package/src/sdk/host/query/revision-store.ts +80 -57
  356. package/src/sdk/index.ts +1 -0
  357. package/src/sdk/protocol/operation-inventory.generated.json +943 -1907
  358. package/src/sdk/session-directory.ts +141 -0
  359. package/src/sdk/session.ts +458 -479
  360. package/src/session/agent-session.ts +1700 -583
  361. package/src/session/agent-storage.ts +18 -0
  362. package/src/session/cache-economics.ts +25 -8
  363. package/src/session/fallback-chain-controller.ts +53 -3
  364. package/src/session/internal/managed-session-scope.ts +2226 -0
  365. package/src/session/internal/managed-session-storage.ts +453 -0
  366. package/src/session/messages.ts +91 -2
  367. package/src/session/session-manager-internal.ts +33 -0
  368. package/src/session/session-manager.ts +1112 -333
  369. package/src/session/session-storage.ts +444 -39
  370. package/src/session/volatile-context-pruning.ts +78 -0
  371. package/src/setup/credential-auto-import.ts +2 -1
  372. package/src/setup/hermes/templates/operator-instructions.v1.md +1 -1
  373. package/src/setup/provider-onboarding.ts +36 -61
  374. package/src/setup/provider-presets.json +5 -0
  375. package/src/skill-state/active-state.ts +3 -13
  376. package/src/skill-state/{deep-interview-mutation-guard.ts → workflow-mutation-guard.ts} +47 -29
  377. package/src/skill-state/workflow-state-contract.ts +6 -41
  378. package/src/slash-commands/builtin-registry.ts +46 -11
  379. package/src/system-prompt.ts +37 -44
  380. package/src/task/agents.ts +19 -1
  381. package/src/task/executor.ts +90 -6
  382. package/src/task/index.ts +36 -21
  383. package/src/thinking.ts +21 -6
  384. package/src/tool-discovery/tool-index.ts +2 -134
  385. package/src/tools/ask.ts +157 -21
  386. package/src/tools/ast-edit.ts +1 -1
  387. package/src/tools/bash.ts +38 -0
  388. package/src/tools/browser/dead-tab-recovery.ts +78 -0
  389. package/src/tools/browser/tab-supervisor.ts +282 -36
  390. package/src/tools/computer.ts +10 -3
  391. package/src/tools/cron.ts +30 -16
  392. package/src/tools/eval.ts +1 -2
  393. package/src/tools/fetch.ts +11 -4
  394. package/src/tools/index.ts +76 -24
  395. package/src/tools/output-meta.ts +13 -5
  396. package/src/tools/read.ts +37 -1
  397. package/src/tools/resource-gc.ts +2 -2
  398. package/src/tools/search-tool-bm25.ts +11 -74
  399. package/src/utils/event-bus.ts +9 -4
  400. package/src/web/search/index.ts +3 -3
  401. package/dist/types/discovery/plugin-dir-roots.d.ts +0 -15
  402. package/dist/types/runtime-mcp/discoverable-tool-metadata.d.ts +0 -7
  403. package/src/discovery/plugin-dir-roots.ts +0 -28
  404. package/src/runtime-mcp/discoverable-tool-metadata.ts +0 -25
@@ -0,0 +1,778 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import { withFileLock } from "../config/file-lock";
5
+ import type { PrivateAskGateCodecV1, PublicReason } from "./question-gate-codec";
6
+
7
+ export type CoordinatorSessionState =
8
+ | "booting"
9
+ | "ready_for_input"
10
+ | "running"
11
+ | "needs_user_input"
12
+ | "completed"
13
+ | "errored"
14
+ | "stale"
15
+ | "unknown";
16
+ export interface CanonicalSessionSnapshotV1 {
17
+ schema_version: 1;
18
+ namespace_id: string;
19
+ session_id: string;
20
+ cwd: string;
21
+ created_at: string;
22
+ updated_at: string;
23
+ mpreset: string | null;
24
+ source: string | null;
25
+ model: string | null;
26
+ tmux: { session: string | null; window: string | null; pane: string | null };
27
+ broker: {
28
+ workspace: string | null;
29
+ endpoint_url: string;
30
+ endpoint_generation: number;
31
+ endpoint_incarnation: string;
32
+ };
33
+ ephemeral: boolean;
34
+ visible: boolean;
35
+ }
36
+ export interface CanonicalTurnSnapshotV1 {
37
+ schema_version: 1;
38
+ turn_id: string;
39
+ session_id: string;
40
+ namespace_id: string;
41
+ status: string;
42
+ prompt: { text: string; created_at: string; source: string };
43
+ delivery: Record<string, unknown>;
44
+ question_ids: string[];
45
+ final_response: Record<string, unknown>;
46
+ evidence: Record<string, unknown>[];
47
+ error: Record<string, unknown> | null;
48
+ liveness: Record<string, unknown>;
49
+ created_at: string;
50
+ updated_at: string;
51
+ started_at: string | null;
52
+ completed_at: string | null;
53
+ terminal_fence: { epoch: number; status: string; reason: PublicReason | null; at: string } | null;
54
+ }
55
+ export interface CanonicalReportSnapshotV1 {
56
+ schema_version: 1;
57
+ report_id: string;
58
+ operation_id: string;
59
+ session_id: string;
60
+ turn_id: string;
61
+ status: string;
62
+ summary: string;
63
+ blocker: string | null;
64
+ pr_url: string | null;
65
+ evidence_paths: string[];
66
+ created_at: string;
67
+ }
68
+ export type GateAuthorityEntryV1 = {
69
+ authority: { namespace_id: string; session_id: string; endpoint_incarnation: string; gate_id: string };
70
+ observation:
71
+ | {
72
+ kind: "valid";
73
+ first_provenance: {
74
+ runtime_turn_id: string;
75
+ gate_created_at: string;
76
+ schema_hash: string;
77
+ stage: string;
78
+ kind: string;
79
+ };
80
+ }
81
+ | {
82
+ kind: "malformed";
83
+ immutable_observation_digest: string;
84
+ malformed: "missing_runtime_turn" | "invalid_runtime_turn" | "invalid_gate_row" | "wrong_session";
85
+ };
86
+ outcome:
87
+ | { state: "deferred_link"; first_seen_at: string }
88
+ | { state: "pending" | "answered"; turn_id: string; question_id: string }
89
+ | { state: "stale" | "uncertain"; reason: PublicReason; turn_id?: string; question_id?: string }
90
+ | { state: "ownership_unavailable"; reason: "ownership_unavailable" }
91
+ | { state: "ownership_conflict"; reason: "ownership_conflict" };
92
+ first_seen_at: string;
93
+ updated_at: string;
94
+ };
95
+ export interface PrivateQuestionV1 {
96
+ question_id: string;
97
+ authority_id: string;
98
+ session_id: string;
99
+ turn_id: string;
100
+ endpoint_incarnation: string;
101
+ stage: string;
102
+ kind: string;
103
+ prompt: string;
104
+ status: "pending" | "resolving" | "answered" | "stale" | "uncertain";
105
+ binding_plaintext: string;
106
+ binding_sha256: string;
107
+ codec: PrivateAskGateCodecV1;
108
+ claim_fence_epoch: number | null;
109
+ answer_request_id: string | null;
110
+ created_at: string;
111
+ updated_at: string;
112
+ answered_at: string | null;
113
+ history: Array<{
114
+ at: string;
115
+ status: "pending" | "resolving" | "answered" | "stale" | "uncertain";
116
+ reason: PublicReason | null;
117
+ }>;
118
+ }
119
+ export interface AnswerRequestV1 {
120
+ request_id: string;
121
+ key_digest: string;
122
+ request_digest: string;
123
+ answer_hash: string;
124
+ answer_binding_sha256: string;
125
+ authority_id: string;
126
+ question_id: string;
127
+ turn_id: string;
128
+ endpoint_incarnation: string;
129
+ sdk_idempotency_key: string;
130
+ claim_fence_epoch: number;
131
+ phase: "claimed" | "remote_started" | "accepted" | "rejected" | "completed" | "uncertain";
132
+ safe_receipt?: {
133
+ status: "accepted" | "rejected";
134
+ answer_hash: string;
135
+ answer_binding_sha256: string;
136
+ authority_id: string;
137
+ turn_id: string;
138
+ endpoint_incarnation: string;
139
+ claim_fence_epoch: number;
140
+ resolved_at: string;
141
+ };
142
+ error_code?: PublicReason | "idempotency_conflict";
143
+ created_at: string;
144
+ updated_at: string;
145
+ }
146
+ export interface PromptRequestV1 {
147
+ request_id: string;
148
+ key_digest: string;
149
+ request_digest: string;
150
+ operation: "turn.prompt" | "turn.follow_up" | "turn.abort_and_prompt";
151
+ canonical_prompt: { text: string };
152
+ sdk_idempotency_key: string;
153
+ phase: "claimed" | "remote_started" | "accepted" | "linked" | "terminal" | "completed" | "uncertain";
154
+ runtime_receipt?: { accepted: true; command_id: string; turn_id: string };
155
+ coordinator_turn_id?: string;
156
+ safe_response?: Record<string, unknown>;
157
+ error_code?: PublicReason | "idempotency_conflict";
158
+ created_at: string;
159
+ updated_at: string;
160
+ }
161
+ export interface OperationRequestV1 {
162
+ operation_id: string;
163
+ tool: string;
164
+ key_digest: string;
165
+ request_digest: string;
166
+ local_id: string;
167
+ remote_id?: string;
168
+ phase: "claimed" | "remote_started" | "completed" | "uncertain";
169
+ intent: Record<string, unknown>;
170
+ safe_response?: Record<string, unknown>;
171
+ error_code?: PublicReason | "idempotency_conflict";
172
+ created_at: string;
173
+ updated_at: string;
174
+ }
175
+ export interface OutboxEventV1 {
176
+ id: string;
177
+ transaction_revision: number;
178
+ kind: string;
179
+ entity: "turn" | "question" | "report" | "session" | "deletion";
180
+ entity_id: string;
181
+ payload: Record<string, string | number | boolean | null>;
182
+ emitted: boolean;
183
+ }
184
+ export interface CoordinatorSessionTransactionV1 {
185
+ schema_version: 1;
186
+ namespace_id: string;
187
+ session_id: string;
188
+ revision: number;
189
+ endpoint: { incarnation: string; observed_at: string } | null;
190
+ canonical: {
191
+ session: CanonicalSessionSnapshotV1;
192
+ turns: Record<string, CanonicalTurnSnapshotV1>;
193
+ queue: {
194
+ ordered_turn_ids: string[];
195
+ active_turn_id: string | null;
196
+ selected_promotion: { from_turn_id: string; to_turn_id: string; revision: number } | null;
197
+ };
198
+ desired_session_state: CoordinatorSessionState;
199
+ reports: Record<string, CanonicalReportSnapshotV1>;
200
+ gate_authorities: Record<string, GateAuthorityEntryV1>;
201
+ questions: Record<string, PrivateQuestionV1>;
202
+ };
203
+ requests: {
204
+ prompts: Record<string, PromptRequestV1>;
205
+ answers: Record<string, AnswerRequestV1>;
206
+ operations: Record<string, OperationRequestV1>;
207
+ };
208
+ outbox: Record<string, OutboxEventV1>;
209
+ projection: {
210
+ applied_turns_revision: number;
211
+ applied_reports_revision: number;
212
+ applied_session_revision: number;
213
+ applied_active_revision: number;
214
+ applied_events_revision: number;
215
+ };
216
+ recovery: { prompt_watermark_at: string | null; last_repaired_at: string | null };
217
+ }
218
+ export type CanonicalCreateIntentV1 =
219
+ | {
220
+ kind: "register";
221
+ session: CanonicalSessionSnapshotV1;
222
+ initial_state: CoordinatorSessionState;
223
+ initial_events: Record<string, string | number | boolean | null>[];
224
+ }
225
+ | {
226
+ kind: "start";
227
+ session: CanonicalSessionSnapshotV1;
228
+ remote_create_key: string;
229
+ initial_state: CoordinatorSessionState;
230
+ initial_prompt: { text: string; caller_key_digest: string } | null;
231
+ initial_events: Record<string, string | number | boolean | null>[];
232
+ }
233
+ | {
234
+ kind: "delegate";
235
+ workflow: "plan" | "execute" | "team";
236
+ session: CanonicalSessionSnapshotV1;
237
+ remote_create_key: string;
238
+ initial_state: CoordinatorSessionState;
239
+ initial_prompt: { text: string; caller_key_digest: string };
240
+ initial_events: Record<string, string | number | boolean | null>[];
241
+ };
242
+ export interface CreationRequestV1 {
243
+ key_digest: string;
244
+ request_digest: string;
245
+ tool: string;
246
+ phase: "claimed" | "remote_started" | "wal_committed" | "projected" | "completed" | "uncertain";
247
+ canonical_create_intent: CanonicalCreateIntentV1 | null;
248
+ remote_create_key: string;
249
+ session_id: string | null;
250
+ endpoint_incarnation: string | null;
251
+ wal_revision?: number;
252
+ wal_digest?: string;
253
+ safe_response?: Record<string, unknown>;
254
+ created_at: string;
255
+ updated_at: string;
256
+ }
257
+ export interface NamespaceDeletionEntryV1 {
258
+ deletion_id: string;
259
+ session_id: string;
260
+ endpoint_incarnation: string;
261
+ operation_id: string;
262
+ key_digest: string;
263
+ request_digest: string;
264
+ close_key: string;
265
+ phase: "intent" | "broker_closed" | "cleanup_pending" | "completed" | "uncertain";
266
+ safe_response?: Record<string, unknown>;
267
+ cleanup: { wal: boolean; turns: boolean; reports: boolean; session: boolean; events: boolean };
268
+ authority_digest: string;
269
+ created_at: string;
270
+ updated_at: string;
271
+ }
272
+ export interface NamespaceRegistryV1 {
273
+ schema_version: 1;
274
+ namespace_id: string;
275
+ creations: Record<string, CreationRequestV1>;
276
+ deletions: Record<string, NamespaceDeletionEntryV1>;
277
+ }
278
+ export interface CoordinatorStatePaths {
279
+ root: string;
280
+ registry: string;
281
+ registryLock: string;
282
+ journal: string;
283
+ journalLock: string;
284
+ sessions: string;
285
+ }
286
+ const MAX_NORMAL_BYTES = 1024 * 1024;
287
+ const EMERGENCY_BYTES = 128 * 1024;
288
+ const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
289
+ const digest = (value: string): string => createHash("sha256").update(value).digest("hex");
290
+ export function coordinatorStatePaths(stateRoot: string, namespaceId: string): CoordinatorStatePaths {
291
+ const root = path.join(stateRoot, "v1", namespaceId);
292
+ return {
293
+ root,
294
+ registry: path.join(root, "namespace-registry.v1.json"),
295
+ registryLock: path.join(root, "namespace-registry.lock"),
296
+ journal: path.join(root, "events", "event-journal.jsonl"),
297
+ journalLock: path.join(root, "events", "event-journal.lock"),
298
+ sessions: path.join(root, "sessions"),
299
+ };
300
+ }
301
+ function safeSessionId(sessionId: string): string {
302
+ if (!/^[A-Za-z0-9._-]{1,256}$/.test(sessionId)) throw new Error("state_corrupt");
303
+ return sessionId;
304
+ }
305
+ export function transactionPath(paths: CoordinatorStatePaths, sessionId: string): string {
306
+ return path.join(paths.sessions, safeSessionId(sessionId), "transaction.v1.json");
307
+ }
308
+ export function transactionLockPath(paths: CoordinatorStatePaths, sessionId: string): string {
309
+ return path.join(paths.sessions, safeSessionId(sessionId), "transaction.lock");
310
+ }
311
+ async function fsyncDirectory(directory: string): Promise<void> {
312
+ const handle = await fs.open(directory, "r");
313
+ try {
314
+ await handle.sync();
315
+ } finally {
316
+ await handle.close();
317
+ }
318
+ }
319
+ async function ensureNamespaceParents(paths: CoordinatorStatePaths): Promise<void> {
320
+ await fs.mkdir(paths.root, { recursive: true, mode: 0o700 });
321
+ }
322
+
323
+ async function writeAtomic(file: string, value: unknown): Promise<void> {
324
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
325
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
326
+ const handle = await fs.open(temp, "wx", 0o600);
327
+ try {
328
+ await handle.writeFile(JSON.stringify(value));
329
+ await handle.sync();
330
+ } finally {
331
+ await handle.close();
332
+ }
333
+ await fs.rename(temp, file);
334
+ await fsyncDirectory(path.dirname(file));
335
+ }
336
+ async function readJson<T>(file: string): Promise<T | null> {
337
+ try {
338
+ return JSON.parse(await fs.readFile(file, "utf8")) as T;
339
+ } catch (error) {
340
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
341
+ throw new Error("state_corrupt");
342
+ }
343
+ }
344
+ function assertTransaction(transaction: CoordinatorSessionTransactionV1, namespaceId: string, sessionId: string): void {
345
+ if (
346
+ transaction.schema_version !== 1 ||
347
+ transaction.namespace_id !== namespaceId ||
348
+ transaction.session_id !== sessionId ||
349
+ transaction.canonical.session.namespace_id !== namespaceId ||
350
+ transaction.canonical.session.session_id !== sessionId ||
351
+ transaction.canonical.session.cwd !== path.resolve(transaction.canonical.session.cwd)
352
+ )
353
+ throw new Error("state_corrupt");
354
+ }
355
+ export async function initializeCoordinatorNamespace(paths: CoordinatorStatePaths): Promise<void> {
356
+ await ensureNamespaceParents(paths);
357
+ await fs.mkdir(paths.sessions, { recursive: true, mode: 0o700 });
358
+ await fs.mkdir(path.dirname(paths.journal), { recursive: true, mode: 0o700 });
359
+ await withFileLock(paths.registryLock, async () => {
360
+ const existing = await readJson<NamespaceRegistryV1>(paths.registry);
361
+ if (existing === null)
362
+ await writeAtomic(paths.registry, {
363
+ schema_version: 1,
364
+ namespace_id: path.basename(paths.root),
365
+ creations: {},
366
+ deletions: {},
367
+ });
368
+ else if (existing.schema_version !== 1 || existing.namespace_id !== path.basename(paths.root))
369
+ throw new Error("state_corrupt");
370
+ });
371
+ }
372
+ export async function withNamespaceRegistry<T>(
373
+ paths: CoordinatorStatePaths,
374
+ operation: (registry: NamespaceRegistryV1) => Promise<T>,
375
+ ): Promise<T> {
376
+ await ensureNamespaceParents(paths);
377
+ return await withFileLock(paths.registryLock, async () => {
378
+ const registry = await readJson<NamespaceRegistryV1>(paths.registry);
379
+ if (registry?.schema_version !== 1 || registry.namespace_id !== path.basename(paths.root))
380
+ throw new Error("state_corrupt");
381
+ const result = await operation(registry);
382
+ await writeAtomic(paths.registry, registry);
383
+ return result;
384
+ });
385
+ }
386
+ export async function withSessionTransaction<T>(
387
+ paths: CoordinatorStatePaths,
388
+ sessionId: string,
389
+ operation: (transaction: CoordinatorSessionTransactionV1) => Promise<T>,
390
+ ): Promise<T> {
391
+ const file = transactionPath(paths, sessionId);
392
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
393
+ return await withFileLock(transactionLockPath(paths, sessionId), async () => {
394
+ const transaction = await readJson<CoordinatorSessionTransactionV1>(file);
395
+ if (!transaction) throw new Error("resource_gone");
396
+ assertTransaction(transaction, path.basename(paths.root), sessionId);
397
+ const result = await operation(transaction);
398
+ transaction.revision++;
399
+ await writeAtomic(file, transaction);
400
+ return result;
401
+ });
402
+ }
403
+
404
+ /** Serializes a session mutation with namespace close admission. */
405
+ export async function withAdmittedSessionTransaction<T>(
406
+ paths: CoordinatorStatePaths,
407
+ sessionId: string,
408
+ operation: (transaction: CoordinatorSessionTransactionV1) => Promise<T>,
409
+ ): Promise<T> {
410
+ return await withNamespaceRegistry(
411
+ paths,
412
+ async registry =>
413
+ await withSessionTransaction(paths, sessionId, async transaction => {
414
+ assertCloseAdmission(registry, transaction);
415
+ return await operation(transaction);
416
+ }),
417
+ );
418
+ }
419
+
420
+ /** Claims a caller-visible creation request before any remote work or projection. */
421
+ export async function claimCreationRequest(
422
+ paths: CoordinatorStatePaths,
423
+ input: { key_digest: string; request_digest: string; tool: string },
424
+ ): Promise<CreationRequestV1> {
425
+ return await withNamespaceRegistry(paths, async registry => {
426
+ const existing = registry.creations[input.key_digest];
427
+ if (existing) {
428
+ if (existing.request_digest !== input.request_digest || existing.tool !== input.tool)
429
+ throw new Error("idempotency_conflict");
430
+ return existing;
431
+ }
432
+ const now = new Date().toISOString();
433
+ const request: CreationRequestV1 = {
434
+ key_digest: input.key_digest,
435
+ request_digest: input.request_digest,
436
+ tool: input.tool,
437
+ phase: "claimed",
438
+ canonical_create_intent: null,
439
+ remote_create_key: `remote_${input.key_digest}`,
440
+ session_id: null,
441
+ endpoint_incarnation: null,
442
+ created_at: now,
443
+ updated_at: now,
444
+ };
445
+ registry.creations[input.key_digest] = request;
446
+ return request;
447
+ });
448
+ }
449
+
450
+ /** Persists the remote result needed to resume a creation after a crash. */
451
+ export async function bindCreationRequest(
452
+ paths: CoordinatorStatePaths,
453
+ keyDigest: string,
454
+ intent: CanonicalCreateIntentV1,
455
+ ): Promise<CreationRequestV1> {
456
+ return await withNamespaceRegistry(paths, async registry => {
457
+ const request = registry.creations[keyDigest];
458
+ if (!request) throw new Error("state_corrupt");
459
+ const session = intent.session;
460
+ if (
461
+ request.session_id &&
462
+ (request.session_id !== session.session_id ||
463
+ request.endpoint_incarnation !== session.broker.endpoint_incarnation)
464
+ )
465
+ throw new Error("state_corrupt");
466
+ if (
467
+ Object.values(registry.deletions).some(
468
+ entry =>
469
+ entry.session_id === session.session_id &&
470
+ entry.endpoint_incarnation === session.broker.endpoint_incarnation,
471
+ )
472
+ )
473
+ throw new Error("session_closing");
474
+ request.canonical_create_intent = intent;
475
+ request.session_id = session.session_id;
476
+ request.endpoint_incarnation = session.broker.endpoint_incarnation;
477
+ if (request.phase === "claimed") request.phase = "remote_started";
478
+ request.updated_at = new Date().toISOString();
479
+ return request;
480
+ });
481
+ }
482
+
483
+ /** Creates the durable session WAL for an already claimed creation request. */
484
+ export async function commitCreationWal(
485
+ paths: CoordinatorStatePaths,
486
+ keyDigest: string,
487
+ intent: CanonicalCreateIntentV1,
488
+ ): Promise<CoordinatorSessionTransactionV1> {
489
+ await bindCreationRequest(paths, keyDigest, intent);
490
+ return await withNamespaceRegistry(paths, async registry => {
491
+ const request = registry.creations[keyDigest];
492
+ if (!request || request.canonical_create_intent === null) throw new Error("state_corrupt");
493
+ const session = intent.session;
494
+ let existing = await readJson<CoordinatorSessionTransactionV1>(transactionPath(paths, session.session_id));
495
+ if (existing) {
496
+ assertTransaction(existing, session.namespace_id, session.session_id);
497
+ if (existing.canonical.session.broker.endpoint_incarnation !== session.broker.endpoint_incarnation) {
498
+ const priorDeleted = Object.values(registry.deletions).some(
499
+ entry =>
500
+ entry.session_id === session.session_id &&
501
+ entry.endpoint_incarnation === existing!.canonical.session.broker.endpoint_incarnation &&
502
+ entry.phase === "completed",
503
+ );
504
+ if (!priorDeleted) throw new Error("session_closing");
505
+ await fs.rm(transactionPath(paths, session.session_id), { force: true });
506
+ existing = null;
507
+ }
508
+ if (existing) {
509
+ request.phase = "wal_committed";
510
+ request.wal_revision = existing.revision;
511
+ request.wal_digest = digest(JSON.stringify(existing));
512
+ request.updated_at = new Date().toISOString();
513
+ return existing;
514
+ }
515
+ }
516
+ const now = new Date().toISOString();
517
+ const transaction: CoordinatorSessionTransactionV1 = {
518
+ schema_version: 1,
519
+ namespace_id: session.namespace_id,
520
+ session_id: session.session_id,
521
+ revision: 1,
522
+ endpoint: { incarnation: session.broker.endpoint_incarnation, observed_at: now },
523
+ canonical: {
524
+ session,
525
+ turns: {},
526
+ queue: { ordered_turn_ids: [], active_turn_id: null, selected_promotion: null },
527
+ desired_session_state: intent.initial_state,
528
+ reports: {},
529
+ gate_authorities: {},
530
+ questions: {},
531
+ },
532
+ requests: { prompts: {}, answers: {}, operations: {} },
533
+ outbox: {},
534
+ projection: {
535
+ applied_turns_revision: 0,
536
+ applied_reports_revision: 0,
537
+ applied_session_revision: 0,
538
+ applied_active_revision: 0,
539
+ applied_events_revision: 0,
540
+ },
541
+ recovery: { prompt_watermark_at: null, last_repaired_at: null },
542
+ };
543
+ await writeAtomic(transactionPath(paths, session.session_id), transaction);
544
+ request.phase = "wal_committed";
545
+ request.wal_revision = transaction.revision;
546
+ request.wal_digest = digest(JSON.stringify(transaction));
547
+ request.updated_at = now;
548
+ return transaction;
549
+ });
550
+ }
551
+ export async function createSessionTransaction(
552
+ paths: CoordinatorStatePaths,
553
+ intent: CanonicalCreateIntentV1,
554
+ ): Promise<CoordinatorSessionTransactionV1> {
555
+ const session = intent.session;
556
+ return await withNamespaceRegistry(paths, async registry => {
557
+ const key = digest(`${intent.kind}\0${session.session_id}\0${session.broker.endpoint_incarnation}`);
558
+ if (
559
+ Object.values(registry.deletions).some(
560
+ entry =>
561
+ entry.session_id === session.session_id &&
562
+ entry.endpoint_incarnation === session.broker.endpoint_incarnation,
563
+ )
564
+ )
565
+ throw new Error("session_closing");
566
+ const prior = registry.creations[key];
567
+ if (prior?.phase === "completed" || prior?.phase === "projected" || prior?.phase === "wal_committed") {
568
+ const existing = await readJson<CoordinatorSessionTransactionV1>(transactionPath(paths, session.session_id));
569
+ if (!existing) throw new Error("state_corrupt");
570
+ return existing;
571
+ }
572
+ const now = new Date().toISOString();
573
+ registry.creations[key] = {
574
+ key_digest: key,
575
+ request_digest: key,
576
+ tool: intent.kind,
577
+ phase: "claimed",
578
+ canonical_create_intent: intent,
579
+ remote_create_key: `remote_${key}`,
580
+ session_id: session.session_id,
581
+ endpoint_incarnation: session.broker.endpoint_incarnation,
582
+ created_at: now,
583
+ updated_at: now,
584
+ };
585
+ const transaction: CoordinatorSessionTransactionV1 = {
586
+ schema_version: 1,
587
+ namespace_id: session.namespace_id,
588
+ session_id: session.session_id,
589
+ revision: 1,
590
+ endpoint: { incarnation: session.broker.endpoint_incarnation, observed_at: now },
591
+ canonical: {
592
+ session,
593
+ turns: {},
594
+ queue: { ordered_turn_ids: [], active_turn_id: null, selected_promotion: null },
595
+ desired_session_state: intent.initial_state,
596
+ reports: {},
597
+ gate_authorities: {},
598
+ questions: {},
599
+ },
600
+ requests: { prompts: {}, answers: {}, operations: {} },
601
+ outbox: {},
602
+ projection: {
603
+ applied_turns_revision: 0,
604
+ applied_reports_revision: 0,
605
+ applied_session_revision: 0,
606
+ applied_active_revision: 0,
607
+ applied_events_revision: 0,
608
+ },
609
+ recovery: { prompt_watermark_at: null, last_repaired_at: null },
610
+ };
611
+ await writeAtomic(transactionPath(paths, session.session_id), transaction);
612
+ registry.creations[key]!.phase = "wal_committed";
613
+ registry.creations[key]!.wal_revision = transaction.revision;
614
+ registry.creations[key]!.wal_digest = digest(JSON.stringify(transaction));
615
+ registry.creations[key]!.updated_at = now;
616
+ return transaction;
617
+ });
618
+ }
619
+ export function assertCloseAdmission(
620
+ registry: NamespaceRegistryV1,
621
+ transaction: CoordinatorSessionTransactionV1,
622
+ ): void {
623
+ if (
624
+ Object.values(registry.deletions).some(
625
+ entry =>
626
+ entry.session_id === transaction.session_id &&
627
+ entry.endpoint_incarnation === transaction.endpoint?.incarnation,
628
+ ) ||
629
+ Object.values(transaction.requests.operations).some(
630
+ request =>
631
+ (request.intent.kind === "stop" || request.intent.kind === "reap") && request.phase === "remote_started",
632
+ )
633
+ )
634
+ throw new Error("session_closing");
635
+ }
636
+ export function deterministicOutboxId(
637
+ sessionId: string,
638
+ revision: number,
639
+ kind: string,
640
+ entity: OutboxEventV1["entity"],
641
+ entityId: string,
642
+ ): string {
643
+ return `txn:${sessionId}:${revision}:${kind}:${entity}:${entityId}`;
644
+ }
645
+ export async function appendOutboxEvents(
646
+ paths: CoordinatorStatePaths,
647
+ transaction: CoordinatorSessionTransactionV1,
648
+ ): Promise<void> {
649
+ await fs.mkdir(path.dirname(paths.journal), { recursive: true, mode: 0o700 });
650
+ await withFileLock(paths.journalLock, async () => {
651
+ const existing = await fs.readFile(paths.journal, "utf8").catch(error => {
652
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
653
+ throw error;
654
+ });
655
+ const ids = new Set(
656
+ existing
657
+ .split("\n")
658
+ .filter(Boolean)
659
+ .map(line => {
660
+ try {
661
+ return (JSON.parse(line) as { id?: unknown }).id;
662
+ } catch {
663
+ return null;
664
+ }
665
+ })
666
+ .filter((id): id is string => typeof id === "string"),
667
+ );
668
+ const events = Object.values(transaction.outbox).filter(event => !event.emitted && !ids.has(event.id));
669
+ if (events.length > 0) {
670
+ const handle = await fs.open(paths.journal, "a", 0o600);
671
+ try {
672
+ await handle.writeFile(`${events.map(event => JSON.stringify(event)).join("\n")}\n`);
673
+ await handle.sync();
674
+ } finally {
675
+ await handle.close();
676
+ }
677
+ }
678
+ for (const event of Object.values(transaction.outbox)) event.emitted = true;
679
+ transaction.projection.applied_events_revision = transaction.revision;
680
+ });
681
+ }
682
+ export function compactTransaction(transaction: CoordinatorSessionTransactionV1, now = Date.now()): void {
683
+ const old = (time: string): boolean => Date.parse(time) + RETENTION_MS < now;
684
+ for (const [id, event] of Object.entries(transaction.outbox))
685
+ if (
686
+ event.emitted &&
687
+ event.transaction_revision < transaction.revision &&
688
+ old(String(event.payload.created_at ?? ""))
689
+ )
690
+ delete transaction.outbox[id];
691
+ for (const group of [transaction.requests.prompts, transaction.requests.answers, transaction.requests.operations])
692
+ for (const [id, request] of Object.entries(group))
693
+ if (
694
+ request.phase === "completed" &&
695
+ old(request.updated_at) &&
696
+ JSON.stringify(transaction.canonical).includes(id) === false
697
+ )
698
+ delete group[id];
699
+ if (Buffer.byteLength(JSON.stringify(transaction)) > MAX_NORMAL_BYTES + EMERGENCY_BYTES)
700
+ throw new Error("query_unavailable");
701
+ }
702
+
703
+ /** Records projection repair after projecting complete canonical snapshots. */
704
+ export async function repairProjections(
705
+ paths: CoordinatorStatePaths,
706
+ sessionId: string,
707
+ project: (canonical: CoordinatorSessionTransactionV1["canonical"]) => Promise<void>,
708
+ ): Promise<void> {
709
+ await withSessionTransaction(paths, sessionId, async transaction => {
710
+ await project(transaction.canonical);
711
+ await appendOutboxEvents(paths, transaction);
712
+ transaction.projection.applied_turns_revision = transaction.revision;
713
+ transaction.projection.applied_reports_revision = transaction.revision;
714
+ transaction.projection.applied_session_revision = transaction.revision;
715
+ transaction.projection.applied_active_revision = transaction.revision;
716
+ transaction.recovery.last_repaired_at = new Date().toISOString();
717
+ });
718
+ }
719
+
720
+ /** Advances a creation receipt only after its WAL or projection authority exists. */
721
+ export async function advanceCreationReceipt(
722
+ paths: CoordinatorStatePaths,
723
+ keyDigest: string,
724
+ phase: "projected" | "completed" | "uncertain",
725
+ safeResponse?: Record<string, unknown>,
726
+ ): Promise<void> {
727
+ await withNamespaceRegistry(paths, async registry => {
728
+ const request = registry.creations[keyDigest];
729
+ if (!request) throw new Error("state_corrupt");
730
+ if (request.phase === phase) return;
731
+ if (phase !== "uncertain" && request.phase !== "wal_committed" && request.phase !== "projected")
732
+ throw new Error("state_corrupt");
733
+ request.phase = phase;
734
+ request.safe_response = safeResponse;
735
+ request.updated_at = new Date().toISOString();
736
+ });
737
+ }
738
+
739
+ export function hasEmergencyCapacity(
740
+ transaction: CoordinatorSessionTransactionV1,
741
+ incomingBytes: number,
742
+ essential: boolean,
743
+ ): boolean {
744
+ const current = Buffer.byteLength(JSON.stringify(transaction));
745
+ return (
746
+ current + incomingBytes <= MAX_NORMAL_BYTES ||
747
+ (essential && current + incomingBytes <= MAX_NORMAL_BYTES + EMERGENCY_BYTES)
748
+ );
749
+ }
750
+
751
+ export async function recordDeletionIntent(
752
+ paths: CoordinatorStatePaths,
753
+ entry: NamespaceDeletionEntryV1,
754
+ ): Promise<void> {
755
+ await withNamespaceRegistry(paths, async registry => {
756
+ const existing = registry.deletions[entry.deletion_id];
757
+ if (existing && (existing.key_digest !== entry.key_digest || existing.request_digest !== entry.request_digest))
758
+ throw new Error("idempotency_conflict");
759
+ registry.deletions[entry.deletion_id] = existing ?? entry;
760
+ });
761
+ }
762
+
763
+ export async function advanceDeletion(
764
+ paths: CoordinatorStatePaths,
765
+ deletionId: string,
766
+ phase: NamespaceDeletionEntryV1["phase"],
767
+ cleanup?: Partial<NamespaceDeletionEntryV1["cleanup"]>,
768
+ safeResponse?: Record<string, unknown>,
769
+ ): Promise<void> {
770
+ await withNamespaceRegistry(paths, async registry => {
771
+ const entry = registry.deletions[deletionId];
772
+ if (!entry) throw new Error("resource_gone");
773
+ entry.phase = phase;
774
+ entry.cleanup = { ...entry.cleanup, ...cleanup };
775
+ entry.updated_at = new Date().toISOString();
776
+ if (safeResponse) entry.safe_response = safeResponse;
777
+ });
778
+ }