@north-light/crouter 0.3.349 → 0.3.351

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 (629) hide show
  1. package/bin/crtr-launcher +4 -0
  2. package/bin/runtime-generation-manifest.mjs +12 -2
  3. package/dist/api/client.d.ts +50 -7
  4. package/dist/api/client.js +2 -2
  5. package/dist/api/dto/analytics.d.ts +184 -0
  6. package/dist/api/dto/analytics.js +0 -0
  7. package/dist/api/dto/broker-ops.d.ts +43 -1
  8. package/dist/api/dto/config.d.ts +11 -0
  9. package/dist/api/dto/grants.d.ts +14 -0
  10. package/dist/api/dto/grants.js +0 -0
  11. package/dist/api/dto/human-requests.d.ts +14 -0
  12. package/dist/api/dto/memory.d.ts +6 -0
  13. package/dist/api/dto/modelauth.d.ts +35 -0
  14. package/dist/api/dto/node-records.d.ts +35 -0
  15. package/dist/api/dto/node-records.js +0 -0
  16. package/dist/api/dto/nodes.d.ts +5 -0
  17. package/dist/api/dto/profiles.d.ts +38 -3
  18. package/dist/api/dto/worktree.d.ts +11 -0
  19. package/dist/api/errors.d.ts +23 -1
  20. package/dist/api/errors.js +1 -1
  21. package/dist/api/index.d.ts +2 -0
  22. package/dist/api/index.js +1 -1
  23. package/dist/api/node-transport.js +1 -1
  24. package/dist/api/routes.d.ts +22 -0
  25. package/dist/api/routes.js +1 -1
  26. package/dist/build-root.d.ts +6 -1
  27. package/dist/build-root.js +1 -1
  28. package/dist/builtin-memory/crouter-sdk/client.md +34 -0
  29. package/dist/builtin-memory/crouter-sdk/errors.md +2 -0
  30. package/dist/builtin-memory/crouter-sdk/memory.md +2 -2
  31. package/dist/builtin-memory/crouter-sdk/streaming.md +21 -0
  32. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/claude-plugin-commands.ts +8 -4
  33. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +39 -118
  34. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.d.ts +6 -1
  35. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.js +41 -27
  36. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.ts +52 -29
  37. package/dist/cli.js +9 -8
  38. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  39. package/dist/clients/attach/chrome/roster.js +1 -1
  40. package/dist/clients/attach/config.js +1 -1
  41. package/dist/clients/attach/overlays/auth.js +2 -2
  42. package/dist/clients/attach/overlays/graph.js +1 -1
  43. package/dist/clients/attach/render/tool-calls.js +3 -3
  44. package/dist/clients/attach/session/connection.js +1 -1
  45. package/dist/clients/attach/session/profile-files.js +1 -1
  46. package/dist/clients/attach/viewer.js +1569 -816
  47. package/dist/commands/api-client.js +3 -3
  48. package/dist/commands/broker-permissions.d.ts +2 -0
  49. package/dist/commands/broker-permissions.js +1 -0
  50. package/dist/commands/canvas-analytics/chart.d.ts +52 -0
  51. package/dist/commands/canvas-analytics/chart.js +1 -0
  52. package/dist/commands/canvas-analytics/drilldown.d.ts +34 -0
  53. package/dist/commands/canvas-analytics/drilldown.js +1 -0
  54. package/dist/commands/canvas-analytics/format.d.ts +29 -0
  55. package/dist/commands/canvas-analytics/format.js +1 -0
  56. package/dist/commands/canvas-analytics/graph-detail.d.ts +2 -0
  57. package/dist/commands/canvas-analytics/graph-detail.js +2 -0
  58. package/dist/commands/canvas-analytics/graphs.d.ts +9 -0
  59. package/dist/commands/canvas-analytics/graphs.js +1 -0
  60. package/dist/commands/canvas-analytics/memory.d.ts +2 -0
  61. package/dist/commands/canvas-analytics/memory.js +1 -0
  62. package/dist/commands/canvas-analytics/overview.d.ts +2 -0
  63. package/dist/commands/canvas-analytics/overview.js +1 -0
  64. package/dist/commands/canvas-analytics/shell.d.ts +60 -0
  65. package/dist/commands/canvas-analytics/shell.js +2 -0
  66. package/dist/commands/canvas-analytics/time.d.ts +2 -0
  67. package/dist/commands/canvas-analytics/time.js +1 -0
  68. package/dist/commands/canvas-analytics/usage.d.ts +2 -0
  69. package/dist/commands/canvas-analytics/usage.js +1 -0
  70. package/dist/commands/canvas-analytics/view.d.ts +85 -0
  71. package/dist/commands/canvas-analytics/view.js +1 -0
  72. package/dist/commands/canvas-analytics.d.ts +2 -0
  73. package/dist/commands/canvas-analytics.js +1 -0
  74. package/dist/commands/canvas-prune.js +1 -1
  75. package/dist/commands/canvas.js +1 -1
  76. package/dist/commands/cron.js +5 -5
  77. package/dist/commands/human/components.d.ts +2 -0
  78. package/dist/commands/human/components.js +2 -2
  79. package/dist/commands/human/prompts.js +1 -1
  80. package/dist/commands/human/queue.js +1 -1
  81. package/dist/commands/memory/client.d.ts +11 -0
  82. package/dist/commands/memory/client.js +1 -0
  83. package/dist/commands/memory/delete.js +1 -1
  84. package/dist/commands/memory/edit.js +3 -3
  85. package/dist/commands/memory/find.js +1 -1
  86. package/dist/commands/memory/history.js +4 -4
  87. package/dist/commands/memory/lint.js +1 -1
  88. package/dist/commands/memory/list.d.ts +0 -2
  89. package/dist/commands/memory/list.js +1 -1
  90. package/dist/commands/memory/move.js +1 -1
  91. package/dist/commands/memory/origin.js +1 -1
  92. package/dist/commands/memory/read.d.ts +0 -5
  93. package/dist/commands/memory/read.js +3 -3
  94. package/dist/commands/memory/shared.d.ts +0 -178
  95. package/dist/commands/memory/shared.js +1 -12
  96. package/dist/commands/memory/write.js +5 -5
  97. package/dist/commands/node/bash.js +5 -5
  98. package/dist/commands/node/create.d.ts +0 -17
  99. package/dist/commands/node/create.js +2 -3
  100. package/dist/commands/node/inspect.js +6 -6
  101. package/dist/commands/node/lifecycle.js +2 -2
  102. package/dist/commands/node-context.js +2 -2
  103. package/dist/commands/node-inspect-artifacts.js +6 -6
  104. package/dist/commands/pkg/browse/catalog.js +1 -1
  105. package/dist/commands/pkg/browse/model.d.ts +1 -1
  106. package/dist/commands/pkg/market-manage.js +1 -1
  107. package/dist/commands/pkg/plugin-manage.js +10 -10
  108. package/dist/commands/profile/daemon-profiles.d.ts +13 -0
  109. package/dist/commands/profile/daemon-profiles.js +4 -0
  110. package/dist/commands/profile/delete.js +1 -1
  111. package/dist/commands/profile/env.d.ts +6 -0
  112. package/dist/commands/profile/env.js +2 -2
  113. package/dist/commands/profile/kind.js +1 -2
  114. package/dist/commands/profile/list.js +1 -1
  115. package/dist/commands/profile/meta.js +1 -1
  116. package/dist/commands/profile/new.js +1 -1
  117. package/dist/commands/profile/pause.js +1 -1
  118. package/dist/commands/profile/project.js +1 -1
  119. package/dist/commands/profile/rename.js +1 -1
  120. package/dist/commands/profile/show.js +1 -1
  121. package/dist/commands/profile.js +1 -1
  122. package/dist/commands/push.js +3 -3
  123. package/dist/commands/surface-inspect.js +1 -1
  124. package/dist/commands/sys/branch.js +1 -1
  125. package/dist/commands/sys/config.js +1 -1
  126. package/dist/commands/sys/connect.js +3 -3
  127. package/dist/commands/sys/context/admin/actions.js +1 -1
  128. package/dist/commands/sys/context/admin/model.d.ts +1 -0
  129. package/dist/commands/sys/context/admin/model.js +1 -1
  130. package/dist/commands/sys/context/admin.js +1 -1
  131. package/dist/commands/sys/context/expose.js +2 -1
  132. package/dist/commands/sys/context/prompt-review.js +2 -2
  133. package/dist/commands/sys/context/resolve.js +7 -7
  134. package/dist/commands/sys/context/sysprompt.js +1 -1
  135. package/dist/commands/sys/join.d.ts +1 -0
  136. package/dist/commands/sys/join.js +1 -0
  137. package/dist/commands/sys/migrate.js +1 -1
  138. package/dist/commands/sys/panels/models-panel.js +1 -1
  139. package/dist/commands/sys/panels/profiles-panel.d.ts +0 -1
  140. package/dist/commands/sys/panels/profiles-panel.js +1 -1
  141. package/dist/commands/sys/provider-login.js +6 -6
  142. package/dist/commands/sys/setup-core.d.ts +1 -1
  143. package/dist/commands/sys/setup-core.js +6 -6
  144. package/dist/commands/sys/setup-settings-runner.js +1 -1
  145. package/dist/commands/sys/setup.js +1 -1
  146. package/dist/commands/sys/spaces.d.ts +1 -0
  147. package/dist/commands/sys/spaces.js +2 -0
  148. package/dist/commands/sys/sync-deps.js +2 -2
  149. package/dist/commands/sys/sync-project-guidance.js +4 -4
  150. package/dist/commands/sys/sync-skills.js +2 -2
  151. package/dist/commands/sys/worktrees.d.ts +1 -0
  152. package/dist/commands/sys/worktrees.js +1 -1
  153. package/dist/commands/sys.js +1 -1
  154. package/dist/core/auth-file.js +2 -2
  155. package/dist/core/bash-job-supervisor.d.ts +6 -0
  156. package/dist/core/bash-job-supervisor.js +4 -0
  157. package/dist/core/bash-jobs.d.ts +13 -6
  158. package/dist/core/bash-jobs.js +8 -7
  159. package/dist/core/broker-client/transport-relay.d.ts +6 -3
  160. package/dist/core/broker-client/transport-relay.js +1 -1
  161. package/dist/core/broker-client/transport-socket.d.ts +6 -1
  162. package/dist/core/broker-client/transport-socket.js +1 -1
  163. package/dist/core/canvas/canvas.d.ts +39 -18
  164. package/dist/core/canvas/canvas.js +21 -20
  165. package/dist/core/canvas/context-strip.d.ts +20 -0
  166. package/dist/core/canvas/context-strip.js +5 -0
  167. package/dist/core/canvas/crons.d.ts +12 -20
  168. package/dist/core/canvas/crons.js +15 -13
  169. package/dist/core/canvas/db.js +2 -2
  170. package/dist/core/canvas/deliveries.d.ts +4 -1
  171. package/dist/core/canvas/deliveries.js +1 -1
  172. package/dist/core/canvas/executions.js +1 -1
  173. package/dist/core/canvas/history.d.ts +2 -1
  174. package/dist/core/canvas/history.js +17 -18
  175. package/dist/core/canvas/memory-reads.d.ts +19 -0
  176. package/dist/core/canvas/memory-reads.js +1 -0
  177. package/dist/core/canvas/migrations.d.ts +0 -4
  178. package/dist/core/canvas/migrations.js +99 -32
  179. package/dist/core/canvas/nav-render.js +1 -1
  180. package/dist/core/canvas/node-agent-paths.d.ts +8 -0
  181. package/dist/core/canvas/node-agent-paths.js +1 -0
  182. package/dist/core/canvas/node-recap.d.ts +2 -2
  183. package/dist/core/canvas/node-recap.js +2 -2
  184. package/dist/core/canvas/node-tokens.d.ts +24 -0
  185. package/dist/core/canvas/node-tokens.js +5 -0
  186. package/dist/core/canvas/paths.d.ts +16 -19
  187. package/dist/core/canvas/paths.js +1 -1
  188. package/dist/core/canvas/render-source.d.ts +2 -2
  189. package/dist/core/canvas/render-source.js +6 -9
  190. package/dist/core/canvas/sessions.d.ts +18 -0
  191. package/dist/core/canvas/sessions.js +4 -1
  192. package/dist/core/canvas/types.d.ts +22 -6
  193. package/dist/core/command-hooks/compose.js +1 -1
  194. package/dist/core/command-hooks/discovery.d.ts +15 -1
  195. package/dist/core/command-hooks/discovery.js +1 -1
  196. package/dist/core/command-hooks/help.d.ts +2 -2
  197. package/dist/core/command-hooks/lifecycle-create.d.ts +1 -1
  198. package/dist/core/command-hooks/lifecycle-create.js +1 -1
  199. package/dist/core/command-hooks/transport/exec-invoke.d.ts +2 -0
  200. package/dist/core/command-hooks/transport/exec-invoke.js +1 -1
  201. package/dist/core/command-hooks/transport/exec-lifecycle.d.ts +1 -0
  202. package/dist/core/command-hooks/transport/exec-lifecycle.js +1 -1
  203. package/dist/core/command-hooks/transport/plan.d.ts +3 -0
  204. package/dist/core/command-hooks/transport/plan.js +1 -0
  205. package/dist/core/command-plugins/discovery.js +1 -1
  206. package/dist/core/command.d.ts +6 -2
  207. package/dist/core/command.js +6 -6
  208. package/dist/core/config.d.ts +8 -5
  209. package/dist/core/config.js +1 -1
  210. package/dist/core/conversation-store/client-worker.d.ts +1 -0
  211. package/dist/core/conversation-store/client-worker.js +1 -0
  212. package/dist/core/conversation-store/client.d.ts +2 -0
  213. package/dist/core/conversation-store/client.js +2 -0
  214. package/dist/core/conversation-store/file-store.d.ts +37 -0
  215. package/dist/core/conversation-store/file-store.js +9 -0
  216. package/dist/core/conversation-store/index.d.ts +50 -0
  217. package/dist/core/conversation-store/index.js +1 -0
  218. package/dist/core/conversation-store/listener.d.ts +4 -0
  219. package/dist/core/conversation-store/listener.js +3 -0
  220. package/dist/core/conversation-store/patch.d.ts +1 -0
  221. package/dist/core/conversation-store/patch.js +1 -0
  222. package/dist/core/directory/join.d.ts +27 -0
  223. package/dist/core/directory/join.js +1 -0
  224. package/dist/core/disk-usage.d.ts +4 -0
  225. package/dist/core/disk-usage.js +1 -0
  226. package/dist/core/events/emit.d.ts +2 -0
  227. package/dist/core/events/emit.js +3 -1
  228. package/dist/core/feed/feed.js +4 -4
  229. package/dist/core/feed/messages.d.ts +3 -0
  230. package/dist/core/feed/messages.js +6 -6
  231. package/dist/core/fs-utils.d.ts +2 -0
  232. package/dist/core/fs-utils.js +3 -3
  233. package/dist/core/grants/local.d.ts +4 -0
  234. package/dist/core/grants/local.js +1 -0
  235. package/dist/core/grants/mirror.d.ts +44 -0
  236. package/dist/core/grants/mirror.js +4 -0
  237. package/dist/core/grants/on-sync.d.ts +22 -0
  238. package/dist/core/grants/on-sync.js +1 -0
  239. package/dist/core/grants/remove.d.ts +7 -0
  240. package/dist/core/grants/remove.js +1 -0
  241. package/dist/core/grants/sandboxes.d.ts +7 -0
  242. package/dist/core/grants/sandboxes.js +1 -0
  243. package/dist/core/grants/sync.d.ts +12 -0
  244. package/dist/core/grants/sync.js +1 -0
  245. package/dist/core/help/memory-extensions.d.ts +3 -0
  246. package/dist/core/help/memory-extensions.js +2 -0
  247. package/dist/core/help.d.ts +14 -0
  248. package/dist/core/help.js +7 -7
  249. package/dist/core/host-exports/builtins.js +3 -3
  250. package/dist/core/host-exports/export.js +3 -3
  251. package/dist/core/human/action-binding.d.ts +2 -0
  252. package/dist/core/human/action-binding.js +1 -1
  253. package/dist/core/human/feedback-companion.d.ts +0 -1
  254. package/dist/core/human/feedback-companion.js +1 -1
  255. package/dist/core/human/page-schema.d.ts +1 -1
  256. package/dist/core/inspector/core.d.ts +2 -0
  257. package/dist/core/inspector/core.js +1 -1
  258. package/dist/core/inspector/tui.js +2 -2
  259. package/dist/core/installed-plugins.js +1 -1
  260. package/dist/core/io.js +6 -6
  261. package/dist/core/keybindings/catalog.d.ts +1 -1
  262. package/dist/core/keybindings/catalog.js +1 -1
  263. package/dist/core/layout-migrate/index.d.ts +15 -0
  264. package/dist/core/layout-migrate/index.js +4 -0
  265. package/dist/core/layout-migrate/paths.d.ts +26 -0
  266. package/dist/core/layout-migrate/paths.js +1 -0
  267. package/dist/core/layout-migrate/stored-paths.d.ts +2 -0
  268. package/dist/core/layout-migrate/stored-paths.js +11 -0
  269. package/dist/core/layout-migrate/stores.d.ts +17 -0
  270. package/dist/core/layout-migrate/stores.js +4 -0
  271. package/dist/core/layout.d.ts +26 -0
  272. package/dist/core/layout.js +2 -0
  273. package/dist/core/llm/run.d.ts +60 -0
  274. package/dist/core/llm/run.js +4 -0
  275. package/dist/core/memory/cli-selector.d.ts +13 -0
  276. package/dist/core/memory/cli-selector.js +1 -0
  277. package/dist/core/memory/history.d.ts +5 -4
  278. package/dist/core/memory/history.js +6 -6
  279. package/dist/core/memory/inline-ref-inventory.d.ts +2 -1
  280. package/dist/core/memory/inline-ref-inventory.js +1 -1
  281. package/dist/core/memory/lint.js +2 -2
  282. package/dist/core/memory/mutation-domain.d.ts +2 -2
  283. package/dist/core/memory/mutation-domain.js +8 -7
  284. package/dist/core/memory/mutations.js +1 -1
  285. package/dist/core/memory/service.d.ts +5 -0
  286. package/dist/core/memory/service.js +2 -2
  287. package/dist/core/memory-resolver.d.ts +11 -7
  288. package/dist/core/memory-resolver.js +2 -2
  289. package/dist/core/model-auth/daemon-login.d.ts +13 -0
  290. package/dist/core/model-auth/daemon-login.js +1 -0
  291. package/dist/core/model-auth/flows.d.ts +45 -0
  292. package/dist/core/model-auth/flows.js +1 -0
  293. package/dist/core/model-auth/handoff-jti.d.ts +4 -0
  294. package/dist/core/model-auth/handoff-jti.js +1 -0
  295. package/dist/core/model-routes.js +1 -1
  296. package/dist/core/nested-stores.d.ts +2 -1
  297. package/dist/core/nested-stores.js +1 -2
  298. package/dist/core/preview-registry.js +2 -2
  299. package/dist/core/profiles/env-store.js +2 -2
  300. package/dist/core/profiles/manifest.d.ts +16 -5
  301. package/dist/core/profiles/manifest.js +1 -1
  302. package/dist/core/provider-management.js +1 -1
  303. package/dist/core/review/birth.js +1 -1
  304. package/dist/core/review/companion.d.ts +0 -2
  305. package/dist/core/review/companion.js +1 -1
  306. package/dist/core/review/fork.js +2 -2
  307. package/dist/core/review/realize.js +1 -1
  308. package/dist/core/review/stage.d.ts +1 -1
  309. package/dist/core/review/stage.js +1 -1
  310. package/dist/core/review/types.d.ts +1 -1
  311. package/dist/core/runs/events.d.ts +34 -0
  312. package/dist/core/runs/events.js +1 -0
  313. package/dist/core/runs/operations.d.ts +43 -0
  314. package/dist/core/runs/operations.js +12 -0
  315. package/dist/core/runtime/bearings-render.d.ts +2 -2
  316. package/dist/core/runtime/bearings-render.js +11 -11
  317. package/dist/core/runtime/bearings.js +2 -2
  318. package/dist/core/runtime/broker/cli-relay.d.ts +5 -0
  319. package/dist/core/runtime/broker/cli-relay.js +1 -0
  320. package/dist/core/runtime/broker/client-registry.d.ts +0 -5
  321. package/dist/core/runtime/broker/client-registry.js +1 -1
  322. package/dist/core/runtime/broker/daemon-ops.d.ts +28 -1
  323. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  324. package/dist/core/runtime/broker/engine-drive.d.ts +0 -2
  325. package/dist/core/runtime/broker/engine-drive.js +1 -1
  326. package/dist/core/runtime/broker/fault-retry.d.ts +9 -0
  327. package/dist/core/runtime/broker/fault-retry.js +1 -1
  328. package/dist/core/runtime/broker/frame-dispatch.d.ts +5 -9
  329. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  330. package/dist/core/runtime/broker/frame-engine-control.d.ts +3 -2
  331. package/dist/core/runtime/broker/frame-engine-control.js +1 -1
  332. package/dist/core/runtime/broker/frame-memory-refs.d.ts +4 -3
  333. package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
  334. package/dist/core/runtime/broker/frame-read.js +1 -1
  335. package/dist/core/runtime/broker/frame-session.js +1 -1
  336. package/dist/core/runtime/broker/held-deferred-inbox.d.ts +3 -1
  337. package/dist/core/runtime/broker/held-deferred-inbox.js +1 -1
  338. package/dist/core/runtime/broker/inbox.d.ts +1 -2
  339. package/dist/core/runtime/broker/inbox.js +7 -10
  340. package/dist/core/runtime/broker/model-adapter.d.ts +9 -0
  341. package/dist/core/runtime/broker/model-adapter.js +2 -0
  342. package/dist/core/runtime/broker/node-token.d.ts +3 -0
  343. package/dist/core/runtime/broker/node-token.js +1 -0
  344. package/dist/core/runtime/broker/read-ops.js +1 -1
  345. package/dist/core/runtime/broker/rebind.d.ts +2 -0
  346. package/dist/core/runtime/broker/rebind.js +1 -1
  347. package/dist/core/runtime/broker/tool-groups.js +1 -1
  348. package/dist/core/runtime/broker/turn-ignition.d.ts +3 -3
  349. package/dist/core/runtime/broker/turn-ignition.js +1 -1
  350. package/dist/core/runtime/broker-cli.js +3 -3
  351. package/dist/core/runtime/broker-extension-render.d.ts +2 -5
  352. package/dist/core/runtime/broker-extension-render.js +4 -4
  353. package/dist/core/runtime/broker-persona-guidance.js +3 -3
  354. package/dist/core/runtime/broker-protocol.d.ts +7 -8
  355. package/dist/core/runtime/broker.js +1 -1
  356. package/dist/core/runtime/canvas-extensions.d.ts +1 -0
  357. package/dist/core/runtime/canvas-extensions.js +1 -1
  358. package/dist/core/runtime/close.d.ts +9 -0
  359. package/dist/core/runtime/close.js +1 -1
  360. package/dist/core/runtime/deliver-live.js +1 -1
  361. package/dist/core/runtime/fleet.d.ts +1 -1
  362. package/dist/core/runtime/front-door-login.js +1 -1
  363. package/dist/core/runtime/front-door.js +2 -2
  364. package/dist/core/runtime/headless-pi.d.ts +1 -1
  365. package/dist/core/runtime/headless-pi.js +1 -1
  366. package/dist/core/runtime/host.d.ts +1 -1
  367. package/dist/core/runtime/host.js +3 -1
  368. package/dist/core/runtime/invocation.d.ts +3 -0
  369. package/dist/core/runtime/kickoff.d.ts +1 -0
  370. package/dist/core/runtime/kickoff.js +16 -16
  371. package/dist/core/runtime/launch-target.d.ts +1 -1
  372. package/dist/core/runtime/launch-target.js +1 -1
  373. package/dist/core/runtime/launch.d.ts +10 -35
  374. package/dist/core/runtime/launch.js +1 -1
  375. package/dist/core/runtime/lifecycle.js +2 -2
  376. package/dist/core/runtime/memory.d.ts +1 -1
  377. package/dist/core/runtime/memory.js +1 -1
  378. package/dist/core/runtime/model-registry.js +1 -1
  379. package/dist/core/runtime/model-swap.d.ts +17 -19
  380. package/dist/core/runtime/model-swap.js +1 -1
  381. package/dist/core/runtime/node-read.js +3 -2
  382. package/dist/core/runtime/nodes.d.ts +7 -0
  383. package/dist/core/runtime/nodes.js +1 -1
  384. package/dist/core/runtime/outcome-document.js +1 -1
  385. package/dist/core/runtime/package-health.js +2 -2
  386. package/dist/core/runtime/persona.js +2 -2
  387. package/dist/core/runtime/pi-vendored.js +1 -1
  388. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  389. package/dist/core/runtime/placement-tmux.js +1 -1
  390. package/dist/core/runtime/placement.js +1 -1
  391. package/dist/core/runtime/promote.js +1 -1
  392. package/dist/core/runtime/provider-credential-gate.js +2 -2
  393. package/dist/core/runtime/recovery-hold.d.ts +2 -0
  394. package/dist/core/runtime/recovery-hold.js +1 -0
  395. package/dist/core/runtime/recycle.js +1 -1
  396. package/dist/core/runtime/reopen.js +1 -1
  397. package/dist/core/runtime/reset.js +1 -1
  398. package/dist/core/runtime/revive.d.ts +1 -1
  399. package/dist/core/runtime/revive.js +2 -3
  400. package/dist/core/runtime/roadmap.js +4 -4
  401. package/dist/core/runtime/run-command.d.ts +6 -0
  402. package/dist/core/runtime/run-command.js +1 -1
  403. package/dist/core/runtime/session-branch.d.ts +2 -8
  404. package/dist/core/runtime/session-branch.js +1 -1
  405. package/dist/core/runtime/session-list-cache.d.ts +6 -22
  406. package/dist/core/runtime/session-list-cache.js +1 -1
  407. package/dist/core/runtime/situational-context.js +2 -2
  408. package/dist/core/runtime/spawn-env.d.ts +6 -6
  409. package/dist/core/runtime/spawn-env.js +1 -1
  410. package/dist/core/runtime/spawn.d.ts +5 -0
  411. package/dist/core/runtime/spawn.js +2 -2
  412. package/dist/core/runtime/stop-guard.js +2 -2
  413. package/dist/core/runtime/stop-signals.d.ts +2 -2
  414. package/dist/core/runtime/stop-signals.js +1 -1
  415. package/dist/core/runtime/structured-output.d.ts +10 -4
  416. package/dist/core/runtime/structured-output.js +4 -4
  417. package/dist/core/runtime/tmux-bindings.js +3 -3
  418. package/dist/core/runtime/tmux-driver.d.ts +4 -0
  419. package/dist/core/runtime/tmux-driver.js +7 -7
  420. package/dist/core/runtime/view-socket.d.ts +9 -2
  421. package/dist/core/runtime/view-socket.js +1 -1
  422. package/dist/core/runtime/warm-pool.js +1 -1
  423. package/dist/core/scope.d.ts +3 -2
  424. package/dist/core/scope.js +1 -1
  425. package/dist/core/scoped-state/db.js +1 -1
  426. package/dist/core/scoped-state/migrate.js +3 -3
  427. package/dist/core/scoped-state/profiles.d.ts +2 -1
  428. package/dist/core/scoped-state/profiles.js +1 -1
  429. package/dist/core/scoped-state/schema.d.ts +2 -1
  430. package/dist/core/scoped-state/schema.js +4 -4
  431. package/dist/core/scopes.d.ts +2 -2
  432. package/dist/core/scopes.js +1 -1
  433. package/dist/core/secrets.d.ts +1 -0
  434. package/dist/core/secrets.js +2 -2
  435. package/dist/core/spaces/mounts.d.ts +32 -0
  436. package/dist/core/spaces/mounts.js +1 -0
  437. package/dist/core/spaces/open-beneath.d.ts +71 -0
  438. package/dist/core/spaces/open-beneath.js +1 -0
  439. package/dist/core/spaces/permissions.d.ts +46 -0
  440. package/dist/core/spaces/permissions.js +1 -0
  441. package/dist/core/spaces/process.d.ts +27 -0
  442. package/dist/core/spaces/process.js +1 -0
  443. package/dist/core/spaces/space.d.ts +8 -0
  444. package/dist/core/spaces/space.js +2 -0
  445. package/dist/core/spaces/stop.d.ts +8 -0
  446. package/dist/core/spaces/stop.js +2 -0
  447. package/dist/core/spaces/users.d.ts +19 -0
  448. package/dist/core/spaces/users.js +1 -0
  449. package/dist/core/subscription-state.d.ts +2 -0
  450. package/dist/core/subscription-state.js +3 -3
  451. package/dist/core/substrate/frontmatter-validation.js +1 -1
  452. package/dist/core/substrate/injected-store.d.ts +28 -3
  453. package/dist/core/substrate/injected-store.js +2 -1
  454. package/dist/core/substrate/listings.js +1 -1
  455. package/dist/core/substrate/memory-events.d.ts +6 -0
  456. package/dist/core/substrate/memory-events.js +1 -0
  457. package/dist/core/substrate/on-read-node.js +1 -1
  458. package/dist/core/substrate/on-read.d.ts +6 -6
  459. package/dist/core/substrate/on-read.js +5 -5
  460. package/dist/core/substrate/plan.js +1 -1
  461. package/dist/core/substrate/render-node.js +1 -1
  462. package/dist/core/substrate/render.d.ts +4 -3
  463. package/dist/core/substrate/render.js +38 -38
  464. package/dist/core/substrate/schema.d.ts +6 -0
  465. package/dist/core/substrate/schema.js +1 -1
  466. package/dist/core/tui/panel.js +1 -1
  467. package/dist/core/user-settings.d.ts +12 -0
  468. package/dist/core/user-settings.js +1 -1
  469. package/dist/core/worktree-mutation-async.js +5 -5
  470. package/dist/core/worktree-quarantine.js +1 -1
  471. package/dist/core/worktree-remove.d.ts +15 -0
  472. package/dist/core/worktree-remove.js +1 -0
  473. package/dist/core/worktree-sweep.js +6 -6
  474. package/dist/daemon/analytics/compute.d.ts +37 -0
  475. package/dist/daemon/analytics/compute.js +1 -0
  476. package/dist/daemon/analytics/scan-worker.d.ts +1 -0
  477. package/dist/daemon/analytics/scan-worker.js +2 -0
  478. package/dist/daemon/analytics/scan.d.ts +37 -0
  479. package/dist/daemon/analytics/scan.js +1 -0
  480. package/dist/daemon/api/app-listener.d.ts +11 -0
  481. package/dist/daemon/api/app-listener.js +21 -0
  482. package/dist/daemon/api/bridge.js +5 -5
  483. package/dist/daemon/api/handlers/analytics.d.ts +2 -0
  484. package/dist/daemon/api/handlers/analytics.js +1 -0
  485. package/dist/daemon/api/handlers/attach.js +1 -1
  486. package/dist/daemon/api/handlers/bash-jobs.js +2 -2
  487. package/dist/daemon/api/handlers/bash.js +1 -1
  488. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  489. package/dist/daemon/api/handlers/canvas.d.ts +1 -1
  490. package/dist/daemon/api/handlers/canvas.js +6 -6
  491. package/dist/daemon/api/handlers/crons.js +1 -1
  492. package/dist/daemon/api/handlers/files.d.ts +1 -1
  493. package/dist/daemon/api/handlers/files.js +1 -1
  494. package/dist/daemon/api/handlers/health.js +2 -2
  495. package/dist/daemon/api/handlers/hook-exec.d.ts +2 -0
  496. package/dist/daemon/api/handlers/hook-exec.js +1 -0
  497. package/dist/daemon/api/handlers/human-requests.js +1 -1
  498. package/dist/daemon/api/handlers/inbox.js +1 -1
  499. package/dist/daemon/api/handlers/llm.d.ts +2 -0
  500. package/dist/daemon/api/handlers/llm.js +3 -0
  501. package/dist/daemon/api/handlers/memory-reads.d.ts +4 -0
  502. package/dist/daemon/api/handlers/memory-reads.js +1 -0
  503. package/dist/daemon/api/handlers/memory.js +5 -1
  504. package/dist/daemon/api/handlers/messages.js +2 -2
  505. package/dist/daemon/api/handlers/modelauth.js +1 -1
  506. package/dist/daemon/api/handlers/node-outcomes.js +1 -1
  507. package/dist/daemon/api/handlers/node-records.d.ts +2 -0
  508. package/dist/daemon/api/handlers/node-records.js +3 -0
  509. package/dist/daemon/api/handlers/nodes.d.ts +1 -1
  510. package/dist/daemon/api/handlers/nodes.js +1 -1
  511. package/dist/daemon/api/handlers/profiles.d.ts +4 -1
  512. package/dist/daemon/api/handlers/profiles.js +1 -1
  513. package/dist/daemon/api/handlers/reports.js +5 -3
  514. package/dist/daemon/api/handlers/reviews.d.ts +1 -1
  515. package/dist/daemon/api/handlers/reviews.js +1 -1
  516. package/dist/daemon/api/handlers/run-routes.d.ts +2 -0
  517. package/dist/daemon/api/handlers/run-routes.js +1 -0
  518. package/dist/daemon/api/handlers/runs.d.ts +9 -0
  519. package/dist/daemon/api/handlers/runs.js +1 -0
  520. package/dist/daemon/api/handlers/subscriptions.js +1 -1
  521. package/dist/daemon/api/handlers/worktree.js +1 -1
  522. package/dist/daemon/api/map.d.ts +10 -4
  523. package/dist/daemon/api/map.js +2 -2
  524. package/dist/daemon/api/operations.d.ts +18 -0
  525. package/dist/daemon/api/operations.js +1 -0
  526. package/dist/daemon/api/principal.d.ts +42 -0
  527. package/dist/daemon/api/principal.js +1 -0
  528. package/dist/daemon/api/router.d.ts +27 -3
  529. package/dist/daemon/api/router.js +1 -1
  530. package/dist/daemon/api/server.d.ts +4 -0
  531. package/dist/daemon/api/server.js +1 -1
  532. package/dist/daemon/api/vendor-signin.d.ts +7 -0
  533. package/dist/daemon/api/vendor-signin.js +77 -0
  534. package/dist/daemon/api/viewer-presence.d.ts +3 -0
  535. package/dist/daemon/api/viewer-presence.js +1 -0
  536. package/dist/daemon/cron/armed-context.d.ts +4 -0
  537. package/dist/daemon/cron/armed-context.js +1 -1
  538. package/dist/daemon/cron/escalation.js +3 -3
  539. package/dist/daemon/cron/lease-recovery.js +1 -1
  540. package/dist/daemon/cron/sinks.js +2 -2
  541. package/dist/daemon/cron-run.d.ts +5 -5
  542. package/dist/daemon/cron-run.js +1 -1
  543. package/dist/daemon/crtrd.js +8 -7
  544. package/dist/daemon/delivery/run-delivery.d.ts +4 -0
  545. package/dist/daemon/delivery/run-delivery.js +1 -1
  546. package/dist/daemon/fleet.d.ts +1 -1
  547. package/dist/daemon/fleet.js +6 -6
  548. package/dist/daemon/human/finish.js +7 -7
  549. package/dist/daemon/joined-owner.d.ts +5 -0
  550. package/dist/daemon/joined-owner.js +1 -0
  551. package/dist/daemon/manage.js +2 -2
  552. package/dist/daemon/messaging/node-message.js +1 -1
  553. package/dist/daemon/park-activity.js +1 -1
  554. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  555. package/dist/daemon/reconcilers/broker-supervision.d.ts +1 -1
  556. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  557. package/dist/daemon/reconcilers/delivery-lane.js +1 -1
  558. package/dist/daemon/reconcilers/live-obligation.d.ts +7 -0
  559. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  560. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  561. package/dist/daemon/reconcilers/storage-maintenance.d.ts +20 -1
  562. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  563. package/dist/daemon/runs/append-section.d.ts +6 -0
  564. package/dist/daemon/runs/append-section.js +2 -0
  565. package/dist/daemon/runs/observer.d.ts +5 -0
  566. package/dist/daemon/runs/observer.js +4 -0
  567. package/dist/launcher/bwrap.d.ts +4 -0
  568. package/dist/launcher/bwrap.js +2 -0
  569. package/dist/launcher/client.d.ts +2 -0
  570. package/dist/launcher/client.js +3 -0
  571. package/dist/launcher/main.d.ts +1 -0
  572. package/dist/launcher/main.js +3 -0
  573. package/dist/launcher/netrule.d.ts +1 -0
  574. package/dist/launcher/netrule.js +1 -0
  575. package/dist/launcher/seccomp.d.ts +1 -0
  576. package/dist/launcher/seccomp.js +1 -0
  577. package/dist/launcher/spec.d.ts +88 -0
  578. package/dist/launcher/spec.js +1 -0
  579. package/dist/launcher/users.d.ts +18 -0
  580. package/dist/launcher/users.js +7 -0
  581. package/dist/launcher/validate.d.ts +22 -0
  582. package/dist/launcher/validate.js +1 -0
  583. package/dist/migrations/corpus.js +3 -3
  584. package/dist/migrations/runner.js +1 -1
  585. package/dist/native/linux/addon.node +0 -0
  586. package/dist/native/linux.d.ts +29 -0
  587. package/dist/native/linux.js +1 -0
  588. package/dist/pi-extensions/broker-local.js +2 -2
  589. package/dist/pi-extensions/canvas-bash-valve.d.ts +1 -3
  590. package/dist/pi-extensions/canvas-bash-valve.js +4 -7
  591. package/dist/pi-extensions/canvas-context-intro.d.ts +1 -2
  592. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  593. package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
  594. package/dist/pi-extensions/canvas-inbox-watcher.d.ts +2 -1
  595. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -1
  596. package/dist/pi-extensions/canvas-passive-context.d.ts +1 -1
  597. package/dist/pi-extensions/canvas-passive-context.js +11 -11
  598. package/dist/pi-extensions/canvas-recap.js +6 -6
  599. package/dist/pi-extensions/canvas-stophook.js +1 -1
  600. package/dist/pi-extensions/canvas-structured-output.js +4 -4
  601. package/dist/pi-extensions/canvas-tool-guide.js +1 -1
  602. package/dist/pi-extensions/system-prompt-entry.d.ts +15 -0
  603. package/dist/pi-extensions/system-prompt-entry.js +1 -0
  604. package/dist/shared/env.d.ts +5 -1
  605. package/dist/shared/env.js +1 -1
  606. package/dist/shared/strip-cd-prefix.d.ts +1 -0
  607. package/dist/shared/strip-cd-prefix.js +1 -0
  608. package/dist/types.d.ts +31 -15
  609. package/docs/cli/memory-and-preferences.md +3 -1
  610. package/docs/sdk/client.md +34 -0
  611. package/docs/sdk/errors.md +2 -0
  612. package/docs/sdk/memory.md +2 -2
  613. package/docs/sdk/streaming.md +21 -0
  614. package/package.json +18 -4
  615. package/packages/crouter-identity/dist/index.d.ts +54 -0
  616. package/packages/crouter-identity/dist/index.js +166 -0
  617. package/packages/crouter-identity/package.json +33 -0
  618. package/runtime.lock.json +34 -8
  619. package/scripts/build-native-linux.mjs +16 -0
  620. package/scripts/install-runtime.mjs +9 -7
  621. package/scripts/lib/isolation-env.mjs +42 -0
  622. package/scripts/runtime-smoke.mjs +49 -0
  623. package/src/native/linux/addon.c +249 -0
  624. package/dist/core/profiles/state-block.d.ts +0 -4
  625. package/dist/core/profiles/state-block.js +0 -3
  626. package/dist/core/runtime/broker/auth-reload.d.ts +0 -41
  627. package/dist/core/runtime/broker/auth-reload.js +0 -1
  628. package/dist/core/substrate/cli-context-delivery.d.ts +0 -22
  629. package/dist/core/substrate/cli-context-delivery.js +0 -1
@@ -24,8 +24,6 @@ type ExactModelRegistry = InitialModelRegistryLike<ExactModel>;
24
24
  export declare function captureOrigin(originNodeId: string, deps?: {
25
25
  registry?: ExactModelRegistry;
26
26
  }): Promise<OriginCapture>;
27
- /** Materialize the immutable review fork, reusing only an already-valid branch. */
28
- export declare function materializeReviewBranch(reviewId: string, capture: OriginCapture): string;
29
27
  /** Create the ordinary, promptless companion node. Realization owns its launch. */
30
28
  export declare function spawnReviewCompanion(spec: ReviewCompanionSpec): Promise<void>;
31
29
  /** A companion is bound only when its session coordinates and visible boundary are durable. */
@@ -1 +1 @@
1
- var S=Object.defineProperty;var t=(e,i)=>S(e,"name",{value:i,configurable:!0});import{randomUUID as I}from"node:crypto";import{existsSync as c}from"node:fs";import{basename as k,isAbsolute as f,resolve as y}from"node:path";import{BrokerClient as v}from"../broker-client/index.js";import{deleteNode as x,getNode as _}from"../canvas/index.js";import{ensureReviewDir as F,reviewBranchPath as E}from"../canvas/paths.js";import{expandModelCandidates as B,selectInitialModelRoute as C}from"../model-routes.js";import{buildLaunchSpec as M}from"../runtime/launch.js";import{openModelRegistry as L}from"../runtime/model-registry.js";import{isBrokerLive as R}from"../runtime/model-swap.js";import{spawnNode as D}from"../runtime/nodes.js";import{SessionManager as m}from"../runtime/broker-sdk.js";import{materializeSessionBranchAt as O}from"../runtime/session-branch.js";import{isReviewBoundary as P}from"../runtime/session-visibility.js";import{initializeForkContextExposure as $}from"../substrate/injected-store.js";import{ReviewOperationError as h}from"./types.js";const g=/^[^/\s:]+\/[^/\s:]+:(?:off|minimal|low|medium|high|xhigh|max)$/,q=100;function z(e){return new h("review_origin_missing","review origin was not found",{origin_node_id:e})}t(z,"originMissing");function u(e,i,o={}){return new h("review_origin_unforkable","review origin has no forkable exact session",{origin_node_id:e,reason:i,...o})}t(u,"originUnforkable");async function p(e,i,o){if(!f(i.sourceFile)||!c(i.sourceFile)||i.sourceSessionId===""||i.leafId===null||i.leafId==="")throw u(e,"no_forkable_session");if(i.modelSpec===null||!g.test(i.modelSpec))throw u(e,"model_unresolvable");const r=C({kind:"exact",spec:i.modelSpec},o??await L(),{cwd:i.cwd,profileId:i.profileId});if(r.selected===void 0)throw u(e,"model_unresolvable",{model_reason:r.rejected[0]?.reason});return{sourceFile:i.sourceFile,sourceSessionId:i.sourceSessionId,leafId:i.leafId,modelSpec:i.modelSpec}}t(p,"validateCapture");function A(e){return new Promise((i,o)=>{const r=new v(e);let s=!1;function d(n){s||(s=!0,r.close(),n())}t(d,"finish"),r.on("error",n=>d(()=>o(n))),r.on("close",()=>d(()=>o(new Error("origin broker closed before fork coordinates were read")))),r.on("connect",()=>{r.send({type:"hello",role:"observer",client_id:I()}),r.request({type:"get_human_fork_coordinates"}).then(n=>{if(n.kind!=="human_fork_coordinates"){d(()=>o(new Error("origin broker returned an unexpected fork-coordinate response")));return}d(()=>i(n))}).catch(n=>d(()=>o(n)))}),r.connect()})}t(A,"captureLiveOrigin");async function ne(e,i={}){const o=_(e);if(o===null)throw z(e);if(R(o)){const l=await A(e);return p(e,{...l,cwd:o.cwd,profileId:o.profile_id},i.registry)}const r=typeof o.pi_session_file=="string"?o.pi_session_file:"";let s="",d=null,n=null;if(f(r)&&c(r)){let l;try{l=m.open(r)}catch{return p(e,{sourceFile:r,sourceSessionId:s,leafId:d,modelSpec:n,cwd:o.cwd,profileId:o.profile_id},i.registry)}s=l.getSessionId(),d=l.getLeafId();const w=o.launch?.model,a=typeof w=="string"?B({kind:"exact",spec:w},o.cwd,o.profile_id)[0]:void 0;if(a!==void 0){const b=a.thinkingLevel??(l.buildSessionContext().thinkingLevel||"off");n=`${a.providerId}/${a.modelId}:${b}`}}return p(e,{sourceFile:r,sourceSessionId:s,leafId:d,modelSpec:n,cwd:o.cwd,profileId:o.profile_id},i.registry)}t(ne,"captureOrigin");function te(e,i){F(e);const o=E(e);if(c(o)){const r=m.open(o);if(r.getSessionFile()===y(o)&&r.getSessionId()!=="")return o}return O(i,o),o}t(te,"materializeReviewBranch");async function se(e){if(!f(e.branchFile)||!f(e.targetFile))throw new Error("review companion requires absolute branch and target paths");if(!g.test(e.modelSpec))throw new Error("review companion requires an exact model spec");const{launch:i}=M("review/companion","base",{lifecycle:"resident",hasManager:!1,model:e.modelSpec,modelExact:!0,cwd:e.cwd,profileId:e.profileId}),o=await D({nodeId:e.nodeId,kind:"review/companion",mode:"base",lifecycle:"resident",cwd:e.cwd,profile_id:e.profileId,parent:e.originNodeId,creator:e.originNodeId,subscribe:!1,forkFrom:e.branchFile,forkSourceFile:e.branchFile,modelOverride:e.modelSpec,reviewBinding:{review_id:e.reviewId,origin_node_id:e.originNodeId,branch_file:e.branchFile,target_file:e.targetFile},name:`review ${k(e.targetFile)}`,launch:i});try{$(o.node_id,e.originNodeId)}catch(r){throw x(o.node_id),r}}t(se,"spawnReviewCompanion");function U(e){const i=_(e),o=i?.review_binding,r=i?.pi_session_file;if(o==null||i?.pi_session_id==null||typeof r!="string"||!c(r))return!1;try{return m.open(r).getEntries().some(s=>P(s,o.review_id))}catch{return!1}}t(U,"isReviewCompanionBound");async function de(e,i){const o=Date.now()+Math.max(0,i);for(;;){if(U(e))return!0;const r=o-Date.now();if(r<=0)return!1;await new Promise(s=>setTimeout(s,Math.min(q,r)))}}t(de,"awaitCompanionBind");export{de as awaitCompanionBind,ne as captureOrigin,U as isReviewCompanionBound,te as materializeReviewBranch,se as spawnReviewCompanion};
1
+ var y=Object.defineProperty;var d=(e,o)=>y(e,"name",{value:o,configurable:!0});import{randomUUID as v}from"node:crypto";import{conversationIdFromPath as u,conversationStore as w,ConversationNotFoundError as p}from"../conversation-store/index.js";import{basename as F,isAbsolute as c}from"node:path";import{BrokerClient as x}from"../broker-client/index.js";import{deleteNode as C,getNode as g}from"../canvas/index.js";import{expandModelCandidates as E,selectInitialModelRoute as M}from"../model-routes.js";import{buildLaunchSpec as L}from"../runtime/launch.js";import{openModelRegistry as B}from"../runtime/model-registry.js";import{isBrokerLive as O}from"../runtime/model-swap.js";import{spawnNode as R}from"../runtime/nodes.js";import{SessionManager as D}from"../runtime/broker-sdk.js";import{isReviewBoundary as P}from"../runtime/session-visibility.js";import{initializeForkContextExposure as $}from"../substrate/injected-store.js";import{ReviewOperationError as b}from"./types.js";const I=/^[^/\s:]+\/[^/\s:]+:(?:off|minimal|low|medium|high|xhigh|max)$/,q=100;function U(e){return new b("review_origin_missing","review origin was not found",{origin_node_id:e})}d(U,"originMissing");function f(e,o,r={}){return new b("review_origin_unforkable","review origin has no forkable exact session",{origin_node_id:e,reason:o,...r})}d(f,"originUnforkable");async function k(e,o,r){const n=u(o.sourceFile);if(!c(o.sourceFile)||n===null||n!==o.sourceSessionId||o.leafId===null||o.leafId==="")throw f(e,"no_forkable_session");try{w().header(n)}catch(i){throw i instanceof p?f(e,"no_forkable_session"):i}if(o.modelSpec===null||!I.test(o.modelSpec))throw f(e,"model_unresolvable");const t=M({kind:"exact",spec:o.modelSpec},r??await B(),{cwd:o.cwd,profileId:o.profileId});if(t.selected===void 0)throw f(e,"model_unresolvable",{model_reason:t.rejected[0]?.reason});return{sourceFile:o.sourceFile,sourceSessionId:o.sourceSessionId,leafId:o.leafId,modelSpec:o.modelSpec}}d(k,"validateCapture");function A(e){return new Promise((o,r)=>{const n=new x(e);let t=!1;function i(s){t||(t=!0,n.close(),s())}d(i,"finish"),n.on("error",s=>i(()=>r(s))),n.on("close",()=>i(()=>r(new Error("origin broker closed before fork coordinates were read")))),n.on("connect",()=>{n.send({type:"hello",role:"observer",client_id:v()}),n.request({type:"get_human_fork_coordinates"}).then(s=>{if(s.kind!=="human_fork_coordinates"){i(()=>r(new Error("origin broker returned an unexpected fork-coordinate response")));return}i(()=>o(s))}).catch(s=>i(()=>r(s)))}),n.connect()})}d(A,"captureLiveOrigin");async function re(e,o={}){const r=g(e);if(r===null)throw U(e);if(O(r)){const a=await A(e);return k(e,{...a,cwd:r.cwd,profileId:r.profile_id},o.registry)}const n=typeof r.pi_session_file=="string"?r.pi_session_file:"";let t="",i=null,s=null;const h=u(n);if(c(n)&&h!==null)try{const a=w().read(h),m=D.inMemory(a.header.cwd,void 0,[a.header,...a.entries]);t=m.getSessionId(),i=m.getLeafId();const _=r.launch?.model,l=typeof _=="string"?E({kind:"exact",spec:_},r.cwd,r.profile_id)[0]:void 0;if(l!==void 0){const S=l.thinkingLevel??(m.buildSessionContext().thinkingLevel||"off");s=`${l.providerId}/${l.modelId}:${S}`}}catch(a){if(!(a instanceof p))throw a}return k(e,{sourceFile:n,sourceSessionId:t,leafId:i,modelSpec:s,cwd:r.cwd,profileId:r.profile_id},o.registry)}d(re,"captureOrigin");async function ne(e){if(!c(e.branchFile)||!c(e.targetFile))throw new Error("review companion requires absolute branch and target paths");if(!I.test(e.modelSpec))throw new Error("review companion requires an exact model spec");const{launch:o}=L("review/companion","base",{lifecycle:"resident",hasManager:!1,model:e.modelSpec,modelExact:!0,cwd:e.cwd,profileId:e.profileId}),r=await R({nodeId:e.nodeId,kind:"review/companion",mode:"base",lifecycle:"resident",cwd:e.cwd,profile_id:e.profileId,parent:e.originNodeId,creator:e.originNodeId,subscribe:!1,forkFrom:e.branchFile,forkSourceFile:e.branchFile,modelOverride:e.modelSpec,reviewBinding:{review_id:e.reviewId,origin_node_id:e.originNodeId,branch_file:e.branchFile,target_file:e.targetFile},name:`review ${F(e.targetFile)}`,launch:o});try{$(r.node_id,e.originNodeId)}catch(n){throw C(r.node_id),n}}d(ne,"spawnReviewCompanion");function N(e){const o=g(e),r=o?.review_binding,n=o?.pi_session_file,t=typeof n=="string"?u(n):null;if(r==null||o?.pi_session_id==null||t===null)return!1;try{return w().read(t).entries.some(i=>P(i,r.review_id))}catch(i){if(i instanceof p)return!1;throw i}}d(N,"isReviewCompanionBound");async function ie(e,o){const r=Date.now()+Math.max(0,o);for(;;){if(N(e))return!0;const n=r-Date.now();if(n<=0)return!1;await new Promise(t=>setTimeout(t,Math.min(q,n)))}}d(ie,"awaitCompanionBind");export{ie as awaitCompanionBind,re as captureOrigin,N as isReviewCompanionBound,ne as spawnReviewCompanion};
@@ -1,5 +1,5 @@
1
- var m=Object.defineProperty;var d=(o,n)=>m(o,"name",{value:n,configurable:!0});import{basename as c}from"node:path";import{getNode as s}from"../canvas/index.js";import{ensureReviewForkDir as w,reviewForkBranchPath as p}from"../canvas/paths.js";import{materializeSessionBranchAt as l}from"../runtime/session-branch.js";import{spawnChildPrepared as _}from"../runtime/spawn.js";import{getComment as f}from"./comments.js";import{captureOrigin as h}from"./companion.js";import{requireVisibleReview as u}from"./store.js";import{ReviewOperationError as a}from"./types.js";function v(o,n){const{line:e,end_line:i}=n.anchor,t=i>e?`lines ${e}-${i}`:`line ${e}`,r=n.anchor_line_text===""?"":`
1
+ var m=Object.defineProperty;var d=(o,n)=>m(o,"name",{value:n,configurable:!0});import{basename as c}from"node:path";import{getNode as s}from"../canvas/index.js";import{materializeSessionBranch as p}from"../runtime/session-branch.js";import{spawnChildPrepared as w}from"../runtime/spawn.js";import{getComment as l}from"./comments.js";import{captureOrigin as _}from"./companion.js";import{requireVisibleReview as f}from"./store.js";import{ReviewOperationError as a}from"./types.js";function h(o,n){const{line:e,end_line:i}=n.anchor,t=i>e?`lines ${e}-${i}`:`line ${e}`,r=n.anchor_line_text===""?"":`
2
2
  > ${n.anchor_line_text}
3
3
  `;return[`The person handed you this one comment on \`${o.file}\` so it can be worked in parallel. The review companion you were forked from keeps the rest of the document.`,`${t}:${r}`,n.text,`Address it by editing only the lines this comment is about \u2014 other forks may be editing the same file \u2014 then resolve it with \`crtr human review comment resolve ${n.comment_id}\`, and tell the companion what changed with \`crtr push update\`.`].join(`
4
4
 
5
- `)}d(v,"forkTask");async function T(o){const n=f(o);if(n===null)throw new a("unknown_comment","comment was not found",{received:o});if(n.status!=="open")throw new a("comment_deleted","only an open comment can be forked",{comment_id:o,status:n.status});const e=u(n.review_id);if(e.state!=="open")throw new a("review_terminal","review already has a terminal outcome",{state:e.state,requested:"fork",review:e});const i=s(e.companion_node_id);if(i===null)throw new a("review_companion_unbound","review companion is gone",{companion_node_id:e.companion_node_id});const t=await h(e.companion_node_id);w(e.review_id);const r=p(e.review_id,o);return l(t,r),{node_id:(await _({kind:"review/companion",mode:"base",cwd:i.cwd,parent:e.companion_node_id,creator:e.companion_node_id,rootLifecycle:"resident",prompt:v(e,n),forkFrom:r,model:t.modelSpec,name:`comment on ${c(e.file)}`,reviewBinding:{review_id:e.review_id,origin_node_id:e.origin_node_id,branch_file:r,target_file:e.file}})).node.node_id,cwd:i.cwd}}d(T,"forkReviewComment");export{T as forkReviewComment};
5
+ `)}d(h,"forkTask");async function R(o){const n=l(o);if(n===null)throw new a("unknown_comment","comment was not found",{received:o});if(n.status!=="open")throw new a("comment_deleted","only an open comment can be forked",{comment_id:o,status:n.status});const e=f(n.review_id);if(e.state!=="open")throw new a("review_terminal","review already has a terminal outcome",{state:e.state,requested:"fork",review:e});const i=s(e.companion_node_id);if(i===null)throw new a("review_companion_unbound","review companion is gone",{companion_node_id:e.companion_node_id});const t=await _(e.companion_node_id),r=p(t);return{node_id:(await w({kind:"review/companion",mode:"base",cwd:i.cwd,parent:e.companion_node_id,creator:e.companion_node_id,rootLifecycle:"resident",prompt:h(e,n),forkFrom:r,model:t.modelSpec,name:`comment on ${c(e.file)}`,reviewBinding:{review_id:e.review_id,origin_node_id:e.origin_node_id,branch_file:r,target_file:e.file}})).node.node_id,cwd:i.cwd}}d(R,"forkReviewComment");export{R as forkReviewComment};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var o=(i,e)=>l(i,"name",{value:e,configurable:!0});import{existsSync as p}from"node:fs";import{getNode as s}from"../canvas/index.js";import{openRequest as m,cancelBindingRequest as v,getRequest as g}from"../human/requests.js";import{NodeIdConflictError as h}from"../runtime/nodes.js";import{reviveNode as q}from"../runtime/revive.js";import{awaitCompanionBind as b,spawnReviewCompanion as y}from"./companion.js";import{signalReviewActivity as _}from"./signal.js";import{COMPANION_BIND_DEADLINE_MS as u,ReviewOperationError as n}from"./types.js";function f(i){const e=g(i);if(e===null||e.kind!=="review")throw new n("unknown_review","review was not found",{received:i});return e}o(f,"requireBinding");function N(i){try{const e=JSON.parse(i.specification_json);if(typeof e!="object"||e===null)throw new Error("not an object");return e}catch(e){throw new Error(`corrupt review specification: ${i.request_id}`,{cause:e})}}o(N,"specification");async function A(i){let e=f(i);if(e.state!=="binding")return e;const a=N(e),r=a.branch_file;if(typeof r!="string"||!p(r))throw v(e.request_id,new Date().toISOString(),"branch_lost")&&_(),new n("branch_lost","review branch was lost before realization",{review_id:e.request_id});if(e.file===null||e.requester_node_id===null||e.companion_node_id===null)throw new Error(`binding review has incomplete identity: ${e.request_id}`);const t=s(e.requester_node_id);if(t===null)throw new n("review_origin_missing","review origin was not found",{origin_node_id:e.requester_node_id});if(s(e.companion_node_id)===null){const c=a.model_spec;if(typeof c!="string")throw new Error(`binding review has no model spec: ${e.request_id}`);try{await y({nodeId:e.companion_node_id,reviewId:e.request_id,originNodeId:e.requester_node_id,branchFile:r,targetFile:e.file,modelSpec:c,cwd:t.cwd,profileId:t.profile_id??null})}catch(w){if(!(w instanceof h))throw w}}const d=s(e.companion_node_id);if(d===null)throw new n("review_companion_unbound","review companion was not created",{review_id:e.request_id});if(d.pi_session_id===null&&await q(d.node_id,{resume:!1,capacity:"refuse"}),!await b(e.companion_node_id,u))throw new n("review_companion_unbound","review companion did not bind in time",{review_id:e.request_id,waited_ms:u});return m(e.request_id,new Date().toISOString())&&_(),e=f(i),e}o(A,"realizeReview");export{A as realizeReview};
1
+ var m=Object.defineProperty;var r=(i,e)=>m(i,"name",{value:e,configurable:!0});import{conversationIdFromPath as v,conversationStore as h,ConversationNotFoundError as g}from"../conversation-store/index.js";import{getNode as s}from"../canvas/index.js";import{openRequest as q,cancelBindingRequest as b,getRequest as y}from"../human/requests.js";import{NodeIdConflictError as I}from"../runtime/nodes.js";import{reviveNode as N}from"../runtime/revive.js";import{awaitCompanionBind as E,spawnReviewCompanion as S}from"./companion.js";import{signalReviewActivity as l}from"./signal.js";import{COMPANION_BIND_DEADLINE_MS as f,ReviewOperationError as o}from"./types.js";function p(i){const e=y(i);if(e===null||e.kind!=="review")throw new o("unknown_review","review was not found",{received:i});return e}r(p,"requireBinding");function R(i){try{const e=JSON.parse(i.specification_json);if(typeof e!="object"||e===null)throw new Error("not an object");return e}catch(e){throw new Error(`corrupt review specification: ${i.request_id}`,{cause:e})}}r(R,"specification");async function k(i){let e=p(i);if(e.state!=="binding")return e;const w=R(e),t=w.branch_file,d=typeof t=="string"?v(t):null;let u=d===null;if(d!==null)try{h().header(d)}catch(n){if(!(n instanceof g))throw n;u=!0}if(u)throw b(e.request_id,new Date().toISOString(),"branch_lost")&&l(),new o("branch_lost","review branch was lost before realization",{review_id:e.request_id});if(e.file===null||e.requester_node_id===null||e.companion_node_id===null)throw new Error(`binding review has incomplete identity: ${e.request_id}`);const a=s(e.requester_node_id);if(a===null)throw new o("review_origin_missing","review origin was not found",{origin_node_id:e.requester_node_id});if(s(e.companion_node_id)===null){const n=w.model_spec;if(typeof n!="string")throw new Error(`binding review has no model spec: ${e.request_id}`);try{await S({nodeId:e.companion_node_id,reviewId:e.request_id,originNodeId:e.requester_node_id,branchFile:t,targetFile:e.file,modelSpec:n,cwd:a.cwd,profileId:a.profile_id??null})}catch(_){if(!(_ instanceof I))throw _}}const c=s(e.companion_node_id);if(c===null)throw new o("review_companion_unbound","review companion was not created",{review_id:e.request_id});if(c.pi_session_id===null&&await N(c.node_id,{resume:!1,capacity:"refuse"}),!await E(e.companion_node_id,f))throw new o("review_companion_unbound","review companion did not bind in time",{review_id:e.request_id,waited_ms:f});return q(e.request_id,new Date().toISOString())&&l(),e=p(i),e}r(k,"realizeReview");export{k as realizeReview};
@@ -19,7 +19,7 @@ export type StagedReview = {
19
19
  review_dir: string;
20
20
  };
21
21
  /** Remove only review-directory state that was never committed to a review row. */
22
- export declare function discardStaging(reviewId: string): void;
22
+ export declare function discardStaging(reviewId: string, branchFile?: string): void;
23
23
  /**
24
24
  * Capture an existing origin and write its immutable branch without creating a
25
25
  * canvas node or review row. The caller alone commits or discards this stage.
@@ -1 +1 @@
1
- var b=Object.defineProperty;var n=(e,i)=>b(e,"name",{value:i,configurable:!0});import{createHash as S}from"node:crypto";import{existsSync as R,readFileSync as k,realpathSync as O,rmSync as x,statSync as F}from"node:fs";import{isAbsolute as D}from"node:path";import{getNode as I}from"../canvas/index.js";import{ensureReviewDir as z,reviewBranchPath as A,reviewDir as d}from"../canvas/paths.js";import{checkReviewableFile as B}from"../human/visible-paths.js";import{newNodeId as m}from"../runtime/nodes.js";import{captureOrigin as j,materializeReviewBranch as h}from"./companion.js";import{getRequestByIdempotencyKey as C}from"../human/requests.js";import{ReviewOperationError as s}from"./types.js";function c(e,i){return new s("review_target_unreviewable","review target cannot be staged",{phase:"create",file:e,reason:i})}n(c,"targetError");function E(e){if(!D(e))throw c(e,"not_absolute");if(!R(e))throw c(e,"missing");try{if(!F(e).isFile())throw c(e,"not_a_file")}catch(t){throw t instanceof s?t:c(e,"missing")}const i=B(e);if(!i.ok){const t=i.reason==="file is not UTF-8 text"?"binary":i.reason==="file is too large to review (2 MB limit)"?"too_large":i.reason==="file is too long to review (5,000 line limit)"?"too_many_lines":"not_a_file";throw c(e,t)}try{return O(e)}catch{throw c(e,"missing")}}n(E,"validateReviewFile");function g(e){return e instanceof Error&&e.message==="source session id does not match captured coordinates"}n(g,"sessionIdentityChanged");function p(e){return new s("review_branch_unavailable","review branch could not be materialized",{reason:"materialize_failed",origin_node_id:e})}n(p,"branchUnavailable");async function f(e){try{return await j(e)}catch(i){throw i instanceof s&&i.code==="review_origin_missing"?new s("review_origin_missing","review origin was not found",{origin_node_id:e,reason:"origin_missing"}):i}}n(f,"captureStagedOrigin");function U(e){return new s("review_origin_unstable","review origin changed sessions while staging",{origin_node_id:e})}n(U,"originUnstable");function q(e,i,t,r){return(async()=>{let o=t,a=r;try{return h(e,o),{capture:o,capturedAt:a}}catch(l){if(!g(l))throw p(i)}o=await f(i),a=new Date().toISOString();try{return h(e,o),{capture:o,capturedAt:a}}catch(l){throw g(l)?U(i):p(i)}})()}n(q,"materializeWithOneRecapture");function H(e){try{x(d(e),{recursive:!0,force:!0})}catch{}}n(H,"discardStaging");async function Y(e){const i=C(e.idempotency_key);if(i!==null)return{existing:i};if(I(e.origin_node_id)===null)throw new s("review_origin_missing","review origin was not found",{origin_node_id:e.origin_node_id,reason:"origin_missing"});const t=E(e.file),r=m(),o=m();try{z(r);const a=await f(e.origin_node_id),l=new Date().toISOString(),u=k(t),w=S("sha256").update(u).digest("hex"),{capture:_,capturedAt:v}=await q(r,e.origin_node_id,a,l),y=new Date().toISOString();return{row:{review_id:r,idempotency_key:e.idempotency_key,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,companion_node_id:o,review_dir:d(r),file:t,origin_session_file:_.sourceFile,origin_session_id:_.sourceSessionId,origin_leaf_id:_.leafId,model_spec:_.modelSpec,branch_file:A(r),baseline_sha256:w,baseline_bytes:u.length,anchor_base_sha256:w,anchor_base_bytes:u,state:"binding",created:y,captured_at:v,opened_at:null,submit_requested_at:null,output_path:e.output_path??null,subtitle:e.subtitle??null,approved_at:null,approved_sha256:null,changed:null,comments_total:null,comments_unresolved:null,result_json:null,canceled_at:null,cancel_reason:null,cancel_actor:null,delivery_entry_id:null,delivered_at:null,delivery_error:null,projected_at:null,projection_error:null},review_dir:d(r)}}catch(a){throw H(r),a}}n(Y,"stageReview");export{H as discardStaging,Y as stageReview};
1
+ var p=Object.defineProperty;var o=(e,i)=>p(e,"name",{value:i,configurable:!0});import{createHash as g}from"node:crypto";import{existsSync as f,readFileSync as v,realpathSync as y,rmSync as b,statSync as S}from"node:fs";import{isAbsolute as I}from"node:path";import{getNode as k}from"../canvas/index.js";import{conversationIdFromPath as F,conversationStore as x,ConversationNotFoundError as R}from"../conversation-store/index.js";import{ensureReviewDir as O,reviewDir as _}from"../canvas/paths.js";import{checkReviewableFile as z}from"../human/visible-paths.js";import{newNodeId as u}from"../runtime/nodes.js";import{captureOrigin as D}from"./companion.js";import{materializeSessionBranch as E}from"../runtime/session-branch.js";import{getRequestByIdempotencyKey as j}from"../human/requests.js";import{ReviewOperationError as a}from"./types.js";function s(e,i){return new a("review_target_unreviewable","review target cannot be staged",{phase:"create",file:e,reason:i})}o(s,"targetError");function B(e){if(!I(e))throw s(e,"not_absolute");if(!f(e))throw s(e,"missing");try{if(!S(e).isFile())throw s(e,"not_a_file")}catch(n){throw n instanceof a?n:s(e,"missing")}const i=z(e);if(!i.ok){const n=i.reason==="file is not UTF-8 text"?"binary":i.reason==="file is too large to review (2 MB limit)"?"too_large":i.reason==="file is too long to review (5,000 line limit)"?"too_many_lines":"not_a_file";throw s(e,n)}try{return y(e)}catch{throw s(e,"missing")}}o(B,"validateReviewFile");function N(e){return new a("review_branch_unavailable","review branch could not be materialized",{reason:"materialize_failed",origin_node_id:e})}o(N,"branchUnavailable");async function q(e){try{return await D(e)}catch(i){throw i instanceof a&&i.code==="review_origin_missing"?new a("review_origin_missing","review origin was not found",{origin_node_id:e,reason:"origin_missing"}):i}}o(q,"captureStagedOrigin");function A(e,i){try{return E(i)}catch{throw N(e)}}o(A,"materialize");function U(e,i){if(i!==void 0){const n=F(i);if(n===null)throw new Error(`invalid staged conversation path: ${i}`);try{x().delete(n)}catch(r){if(!(r instanceof R))throw r}}try{b(_(e),{recursive:!0,force:!0})}catch{}}o(U,"discardStaging");async function X(e){const i=j(e.idempotency_key);if(i!==null)return{existing:i};if(k(e.origin_node_id)===null)throw new a("review_origin_missing","review origin was not found",{origin_node_id:e.origin_node_id,reason:"origin_missing"});const n=B(e.file),r=u(),m=u();let c;try{O(r);const t=await q(e.origin_node_id),w=new Date().toISOString(),l=v(n),d=g("sha256").update(l).digest("hex");c=A(e.origin_node_id,t);const h=new Date().toISOString();return{row:{review_id:r,idempotency_key:e.idempotency_key,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,companion_node_id:m,review_dir:_(r),file:n,origin_session_file:t.sourceFile,origin_session_id:t.sourceSessionId,origin_leaf_id:t.leafId,model_spec:t.modelSpec,branch_file:c,baseline_sha256:d,baseline_bytes:l.length,anchor_base_sha256:d,anchor_base_bytes:l,state:"binding",created:h,captured_at:w,opened_at:null,submit_requested_at:null,output_path:e.output_path??null,subtitle:e.subtitle??null,approved_at:null,approved_sha256:null,changed:null,comments_total:null,comments_unresolved:null,result_json:null,canceled_at:null,cancel_reason:null,cancel_actor:null,delivery_entry_id:null,delivered_at:null,delivery_error:null,projected_at:null,projection_error:null},review_dir:_(r)}}catch(t){throw U(r,c),t}}o(X,"stageReview");export{U as discardStaging,X as stageReview};
@@ -9,7 +9,7 @@ export type ReviewOriginKind = 'ticket' | 'inline';
9
9
  export type CommentStatus = 'open' | 'resolved' | 'deleted';
10
10
  export type CommentAuthorKind = 'human' | 'node';
11
11
  export type CommentEventKind = 'created' | 'edited' | 'resolved' | 'reopened' | 'deleted' | 'reanchored' | 'notified' | 'notify_failed';
12
- export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_origin_unstable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | 'anchor_out_of_range' | 'text_too_long' | 'comment_limit_reached' | 'stale_comment' | 'range_batch_incomplete' | 'range_batch_stale';
12
+ export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | 'anchor_out_of_range' | 'text_too_long' | 'comment_limit_reached' | 'stale_comment' | 'range_batch_incomplete' | 'range_batch_stale';
13
13
  /** Limits */
14
14
  export declare const COMMENT_TEXT_MAX = 8000;
15
15
  export declare const COMMENT_QUOTE_MAX = 4000;
@@ -0,0 +1,34 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ export interface RunEvent {
3
+ type: string;
4
+ run_id: string;
5
+ node_id: string;
6
+ sequence_number: number;
7
+ ts: string;
8
+ metadata: Record<string, unknown>;
9
+ [field: string]: unknown;
10
+ }
11
+ export declare function appendRunEvent(db: DatabaseSync, runId: string, nodeId: string, type: string, fields?: Record<string, unknown>): RunEvent;
12
+ export declare function emitRunEvent(runId: string, nodeId: string, type: string, fields?: Record<string, unknown>): RunEvent;
13
+ export declare function emitRunSettlement(runId: string, nodeId: string, type: 'node.settled' | 'child.settled', fields: {
14
+ outcome: {
15
+ revision: number;
16
+ };
17
+ [field: string]: unknown;
18
+ }): void;
19
+ export declare function readRunEvents(runId: string, after?: number): {
20
+ events: RunEvent[];
21
+ earliest_sequence: number | null;
22
+ latest_sequence: number;
23
+ backlog_count: number;
24
+ backlog_bytes: number;
25
+ };
26
+ export declare function subscribeRunEvents(runId: string, wake: () => void): () => void;
27
+ export declare function notifyRunDeleted(runId: string): void;
28
+ /** OWN-11 for a joined runtime: the legacy `user:local` grantee is the terminal app. */
29
+ export declare function rewriteLocalRunEventGrantee(db: DatabaseSync): number;
30
+ export declare function expireRunEvents(now: number): void;
31
+ /** Track an open `run.events` stream an app caller holds under `grant`. */
32
+ export declare function registerGrantStream(grant: string, close: () => void): () => void;
33
+ /** Close every open stream held under a grant that is no longer active. */
34
+ export declare function closeGrantStreams(grant: string): number;
@@ -0,0 +1 @@
1
+ var v=Object.defineProperty;var o=(e,t)=>v(e,"name",{value:t,configurable:!0});import{openDb as R,withCanvasWrite as _}from"../canvas/db.js";import{repairRunConversations as S}from"../canvas/sessions.js";const i=new Map;function p(e,t,n,s,u={}){const r=e.prepare("SELECT event_cursor, grantee, metadata_json FROM nodes WHERE node_id = ? AND run_id = ?").get(t,t);if(!r||r.event_cursor===null)throw new Error(`missing run event cursor: ${t}`);const a={type:s,run_id:t,node_id:n,sequence_number:r.event_cursor,ts:new Date().toISOString(),metadata:r.metadata_json?JSON.parse(r.metadata_json):{},...u};return e.prepare("INSERT INTO run_events (run_id, sequence_number, node_id, type, ts, body_json, grantee) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t,a.sequence_number,n,s,a.ts,JSON.stringify(a),r.grantee),e.prepare("UPDATE nodes SET event_cursor = event_cursor + 1, last_activity_at = ? WHERE node_id = ?").run(a.ts,t),queueMicrotask(()=>{for(const E of i.get(t)??[])E()}),a}o(p,"appendRunEvent");function l(e,t,n,s={}){return _(u=>p(u,e,t,n,s))}o(l,"emitRunEvent");function d(e,t,n,s){_(u=>{u.prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = ? AND json_extract(body_json, '$.outcome.revision') = ? LIMIT 1").get(e,t,n,s.outcome.revision)||p(u,e,t,n,s)})}o(d,"emitRunSettlement");function b(e,t=0){S(e);const n=R(),s=n.prepare("SELECT event_cursor FROM nodes WHERE node_id = ? AND run_id = ?").get(e,e);if(!s)throw new Error(`run not found: ${e}`);const u=n.prepare("SELECT MIN(sequence_number) AS sequence FROM run_events WHERE run_id = ?").get(e),r=n.prepare("SELECT COUNT(*) AS count, COALESCE(SUM(LENGTH(body_json)), 0) AS bytes FROM run_events WHERE run_id = ? AND sequence_number > ?").get(e,t);return{events:(r.count>1e3||r.bytes>32*1024*1024?[]:n.prepare("SELECT body_json FROM run_events WHERE run_id = ? AND sequence_number > ? ORDER BY sequence_number LIMIT 1000").all(e,t)).map(E=>JSON.parse(E.body_json)),earliest_sequence:u.sequence,latest_sequence:s.event_cursor-1,backlog_count:r.count,backlog_bytes:r.bytes}}o(b,"readRunEvents");function T(e,t){let n=i.get(e);return n||(n=new Set,i.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&i.delete(e)}}o(T,"subscribeRunEvents");function N(e){queueMicrotask(()=>{for(const t of i.get(e)??[])t()})}o(N,"notifyRunDeleted");function O(e){return Number(e.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}o(O,"rewriteLocalRunEventGrantee");function D(e){_(t=>{t.prepare("DELETE FROM run_events WHERE ts < ?").run(new Date(e-720*60*60*1e3).toISOString())})}o(D,"expireRunEvents");const c=new Map;function M(e,t){let n=c.get(e);return n||(n=new Set,c.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&c.delete(e)}}o(M,"registerGrantStream");function A(e){const t=[...c.get(e)??[]];for(const n of t)n();return t.length}o(A,"closeGrantStreams");export{p as appendRunEvent,A as closeGrantStreams,l as emitRunEvent,d as emitRunSettlement,D as expireRunEvents,N as notifyRunDeleted,b as readRunEvents,M as registerGrantStream,O as rewriteLocalRunEventGrantee,T as subscribeRunEvents};
@@ -0,0 +1,43 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ import type { NodeMeta } from '../canvas/types.js';
3
+ import type { AppPrincipal } from '../../daemon/api/principal.js';
4
+ /** OWN-11 for a joined runtime: the legacy `user:local` grantee is the terminal app. */
5
+ export declare function rewriteLocalIdempotencyGrantee(db: DatabaseSync): number;
6
+ export declare class RunError extends Error {
7
+ readonly status: number;
8
+ readonly code: string;
9
+ readonly param?: string | undefined;
10
+ readonly details?: unknown | undefined;
11
+ readonly scope?: string | undefined;
12
+ readonly retryable: boolean;
13
+ constructor(status: number, code: string, message: string, param?: string | undefined, details?: unknown | undefined, scope?: string | undefined, retryable?: boolean);
14
+ }
15
+ export declare function ownedRun(id: string, grantee: string, allowDeleting?: boolean): NodeMeta;
16
+ export declare function runObject(root: NodeMeta): Record<string, unknown>;
17
+ export declare function startRun(principal: AppPrincipal, input: {
18
+ prompt: string;
19
+ scopes: string[] | null;
20
+ metadata: Record<string, unknown>;
21
+ profile?: string;
22
+ }, idempotencyKey?: string): Promise<Record<string, unknown>>;
23
+ export declare function listRuns(grantee: string | null, options: {
24
+ status?: string;
25
+ after?: string;
26
+ limit: number;
27
+ }): {
28
+ runs: Record<string, unknown>[];
29
+ next: string | null;
30
+ };
31
+ export declare function waitRun(id: string, grantee: string, seconds: number): Promise<Record<string, unknown>>;
32
+ export declare function messageRun(root: NodeMeta, message: string): Promise<{
33
+ run_id: string;
34
+ message_id: string;
35
+ sequence_number: number;
36
+ }>;
37
+ export declare function interruptRun(root: NodeMeta, children?: 'stop' | 'continue'): Promise<Record<string, unknown>>;
38
+ export declare function cancelRun(root: NodeMeta, _options?: {
39
+ keepSchedules?: boolean;
40
+ }): Promise<Record<string, unknown>>;
41
+ export declare function deleteRun(root: NodeMeta): Promise<void>;
42
+ export declare function traceRun(id: string, grantee: string, format?: string): Record<string, unknown>;
43
+ export declare function requestedScopes(held: readonly string[], value: unknown, grantee: string): string[] | null;
@@ -0,0 +1,12 @@
1
+ var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as ne}from"node:crypto";import{join as re}from"node:path";import{SessionManager as se}from"@earendil-works/pi-coding-agent";import{covers as b}from"@north-light/crouter-identity";import{openDb as oe,withCanvasWrite as F}from"../canvas/db.js";import{repairRunConversations as H}from"../canvas/sessions.js";import{getNode as w,nodeFiles as ie,removeNodeFiles as de}from"../canvas/canvas.js";import{liveExecutionForNode as x}from"../canvas/executions.js";import{nodeAgentDir as ae,reportsDir as ce}from"../canvas/node-agent-paths.js";import{isAbsentOrRefused as W,readdirBeneath as ue,readFileBeneath as me}from"../spaces/open-beneath.js";import{conversationStore as q,isConversationNotFound as pe}from"../conversation-store/index.js";import{enqueueNodeMail as _e}from"../feed/messages.js";import{ensureAppProfile as le,loadExactProfileManifest as fe}from"../profiles/manifest.js";import{stopNodeSandboxes as B}from"../spaces/stop.js";import{BrokerUnreachableError as Ee}from"../runtime/broker-request.js";import{interruptLive as ge}from"../runtime/interactive-deliver.js";import{isBrokerLive as j}from"../runtime/model-swap.js";import{newNodeId as ye}from"../runtime/nodes.js";import{writeGoal as Re}from"../runtime/kickoff.js";import{reviveNode as J}from"../runtime/revive.js";import{spawnChildPrepared as we}from"../runtime/spawn.js";import{cycleAwareMessages as he}from"../runtime/session-cycles.js";import{originFor as P}from"../runtime/stamp/protocol.js";import{readOutputResult as Se}from"../runtime/structured-output.js";import{toRunOutcomeDTO as Ne}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as ve}from"../../daemon/runs/observer.js";import{closeNode as $}from"../runtime/close.js";import{parseScope as Oe}from"@north-light/crouter-identity";import{appendRunEvent as U,subscribeRunEvents as Te}from"./events.js";import{appSpace as be}from"../layout.js";import{ensureAppSpace as De}from"../spaces/space.js";function at(e){return Number(e.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}u(at,"rewriteLocalIdempotencyGrantee");class E extends Error{static{u(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,i,n,d,c,r,s=t===503){super(n),this.status=t,this.code=i,this.param=d,this.details=c,this.scope=r,this.retryable=s}}const D=u((e,t)=>new E(400,"invalid_request",e,t),"invalid"),C=u(()=>new E(404,"not_found","run not found"),"missing"),I=u(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),y=u(()=>oe(),"db");function L(e,t,i=!1){const n=w(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!i&&n.deleting_at)throw C();return n}u(L,"ownedRun");function O(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=y().prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
2
+ (n.last_settled_at IS NULL OR EXISTS (
3
+ SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
4
+ AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
5
+ WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),i=y().prepare("SELECT 1 FROM deliveries WHERE destination_kind = 'node_inbox' AND destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?) AND state IN ('armed', 'pending') AND wake = 1 LIMIT 1").get(e.node_id);return t||i||!e.last_settled_at?"running":"idle"}u(O,"runStatus");function M(e){H(e.node_id),e=w(e.node_id)??e;const t=O(e),i=ae(e.node_id),n=ce(e.node_id);let d;try{d=ue(i,n).filter(o=>o.isFile()).map(o=>o.name).filter(o=>/-(?:update|urgent|final)\.md$/.test(o)).sort().at(-1)}catch(o){if(!W(o))throw o}let c;try{c=d?me(i,re(n,d)).toString("utf8").replace(/^---\n[\s\S]*?\n---\n/,""):void 0}catch(o){if(!W(o))throw o}const r=t==="settled"?Ne(e):null,s=r?.kind==="result"?Se(e.node_id,e.grantee):void 0;return{run_id:e.node_id,status:t,...r?{outcome:r}:{},...s===void 0?{}:{result:s},...c!==void 0?{last_report:c}:{},pending_question_ids:[],usage:JSON.parse(e.usage_json??JSON.stringify(I())),payer:"user",scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at}}u(M,"runObject");async function ct(e,t,i){const n=ne("sha256").update(JSON.stringify(t)).digest("hex");if(i){const o=y().prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e.grantee,i);if(o&&Date.now()-Date.parse(o.created_at)<864e5){if(o.body_hash!==n)throw new E(409,"idempotency_conflict","key used with a different request");const _=L(o.run_id,e.grantee);return!_.pi_pid&&O(_)==="running"&&await J(_.node_id,{resume:!0,capacity:"freeze"}),JSON.parse(o.response_json)}}await De(e.grantee);const d=t.profile===void 0?le(e.grantee):fe(t.profile),c=d.manifest.grantee??"app:terminal";if(c!==e.grantee){const o=`crtr:memory:rw:${c}:profile:${d.profileId}`;if(!e.resolved.some(_=>b(_,o))||t.scopes!==null&&!t.scopes.some(_=>b(_,o)))throw new E(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}const r=ye();let s;if(await we({kind:"developer",mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:be(e.grantee).files,profile:d.profileId,prompt:t.prompt,nodeId:r,...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:r,event_cursor:1,usage_json:JSON.stringify(I())},withinCreate:u((o,_)=>{Re(r,t.prompt),s={run_id:r,node_id:r,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:"user",status:"running",created_at:_.created,metadata:t.metadata,sequence_number:0},U(o,r,r,"run.started",{served_model:_.launch?.model??null,scopes:t.scopes,payer:"user",usage:I()}),i&&(o.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(e.grantee,i,new Date(Date.now()-864e5).toISOString()),o.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.grantee,i,n,r,JSON.stringify(s),_.created))},"withinCreate")}),!s)throw new Error("run creation did not commit");return s}u(ct,"startRun");function ut(e,t){let i;if(t.after)try{const s=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!s||typeof s!="object"||!("activity"in s)||typeof s.activity!="string"||!("id"in s)||typeof s.id!="string")throw new Error("invalid cursor");i={activity:s.activity,id:s.id}}catch{throw D("invalid list cursor","after")}const d=y().prepare(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM nodes
7
+ WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}
8
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e]).filter(({activity:s,node_id:o})=>!i||s<i.activity||s===i.activity&&o<i.id).map(s=>({root:w(s.node_id),activity:s.activity})).filter(({root:s})=>!t.status||O(s)===t.status),c=d.slice(0,t.limit),r=c.at(-1);return{runs:c.map(({root:s})=>M(s)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}u(ut,"listRuns");async function mt(e,t,i){const n=L(e,t),d=u(()=>M(L(e,t)),"read");return!i||["idle","settled"].includes(O(n))?d():new Promise((c,r)=>{const s=u(()=>{clearTimeout(T),clearInterval(_),o();try{c(d())}catch(h){r(h)}},"finish"),o=Te(e,()=>{try{["idle","settled"].includes(String(d().status))&&s()}catch(h){clearTimeout(T),clearInterval(_),o(),r(h)}}),_=setInterval(()=>{["idle","settled"].includes(String(d().status))&&s()},250),T=setTimeout(s,i*1e3)})}u(mt,"waitRun");async function pt(e,t){if(e.status==="canceled"||e.outcome_reason==="closed")throw new E(409,"run_settled","canceled run cannot receive a message");if(e.final_report&&!e.pi_pid){const{commitReopenResident:d}=await import("../runtime/reopen.js");d(e.node_id)}const i=_e(e.node_id,{kind:"message",label:t.slice(0,120),senderNodeId:"human",bodyJson:{body:t},urgency:"normal",wake:1,withinEnqueue:u((d,c)=>{U(d,e.node_id,e.node_id,"node.message.accepted",{message_id:c})},"withinEnqueue")}),n=y().prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e.node_id).event_cursor-1;return e.pi_pid||await J(e.node_id,{resume:!0,capacity:"freeze"}),{run_id:e.node_id,message_id:i.messageId,sequence_number:n}}u(pt,"messageRun");async function Le(e){const t=u(()=>new E(503,"server_error",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let i=0;i<2;i++){const n=w(e);if(!n)throw C();if(!j(n)){if(n.streaming)throw t();return}const d=x(e)?.executionId;try{await ge(e);return}catch(c){if(!(c instanceof Ee))throw c;const r=w(e);if(!r)throw C();if(!r.streaming)return;if(i===0&&j(r)&&x(e)?.executionId!==d)continue;throw t()}}throw t()}u(Le,"interruptNode");async function _t(e,t="stop"){const i=t==="stop"?y().prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id).map(({node_id:n})=>n):[e.node_id];return await Promise.all(i.map(n=>Le(n))),M(w(e.node_id)??e)}u(_t,"interruptRun");async function lt(e,t={}){const i=y().prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(r=>r.node_id),n=[];if(O(e)!=="settled")n.push(...$(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"}).closed);else for(const r of i){if(r===e.node_id)continue;const s=w(r);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...$(r,{preserveEmpty:!0,stopReason:"run_canceled"}).closed)}if((await Promise.all([...new Set([e.node_id,...n])].map(r=>B(r,"run_canceled")))).some(r=>!r.confirmed))throw new E(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const c=w(e.node_id);return M(c??e)}u(lt,"cancelRun");async function ft(e){const t=F(r=>(r.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),r.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(s=>s.node_id)));if((await Promise.all(t.map(r=>B(r,"run_deleted",{deleting:!0})))).some(r=>!r.confirmed))throw new E(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const n=t.map(r=>{const s=ie(r);if(s.app===null)throw new Error(`run node missing during deletion: ${r}`);return s}),d=y().prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:r}of d)try{q().delete(r)}catch(s){if(!pe(s))throw s}F(r=>{r.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),r.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const s=r.prepare("SELECT message_id FROM messages WHERE sender_node_id IN (SELECT node_id FROM nodes WHERE run_id = ?) UNION SELECT message_id FROM deliveries WHERE destination_kind = 'node_inbox' AND destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id,e.node_id);r.prepare("DELETE FROM deliveries WHERE destination_kind = 'node_inbox' AND destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").run(e.node_id);for(const{message_id:o}of s)r.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(o,o);for(const o of t)r.prepare("DELETE FROM nodes WHERE node_id = ?").run(o)});for(const r of n)de(r);const{notifyRunDeleted:c}=await import("./events.js");c(e.node_id)}u(ft,"deleteRun");function Et(e,t,i){L(e,t),H(e);const n=y();n.exec("BEGIN");try{const c=n.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e).map(m=>({node_id:m.node_id,parent_node_id:m.parent,conversations:n.prepare("SELECT DISTINCT session_id FROM sessions WHERE node_id = ? ORDER BY created_at").all(m.node_id).map(({session_id:l})=>{const{header:S,entries:f}=q().read(l);if(i==="entries")return{conversation_id:l,header:S,entries:f};const G=se.inMemory(S.cwd,void 0,[S,...f]),X=he(G)??[],k=new Map(f.map((p,R)=>[p.id,R])),z=f.filter(p=>p.type==="custom"&&p.customType==="crtr-system-prompt").map(p=>({id:p.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in p?p.data:void 0,timestamp:p.timestamp}})),V=m.node_id===e?f.find(p=>{if(p.type!=="message"||p.message.role!=="user")return!1;const R=P(f,p.message.timestamp);return R?.type==="runtime"&&R.kind==="kickoff"})?.id:void 0,Q=[...X,...z].sort((p,R)=>(k.get(p.id)??Number.MAX_SAFE_INTEGER)-(k.get(R.id)??Number.MAX_SAFE_INTEGER)).map(({id:p,message:R})=>{const a=R,N=a.usage,A=a.role==="user"?P(f,Number(a.timestamp)):null,Z=A?.type==="human"||p===V,v=a.role==="toolResult"?"tool_result":a.role==="bashExecution"?"bash_execution":a.role==="compactionSummary"?"compaction_summary":a.role==="branchSummary"?"branch_summary":a.role==="custom"&&a.customType==="crtr-system-prompt"?"system":a.role==="user"?Z?"user":"custom":a.role,K=v==="custom"?a.role==="custom"?a.customType:A?.type==="runtime"?A.kind:"unknown":void 0,ee=v==="system"&&a.customType==="crtr-system-prompt"?[{type:"text",text:a.data?.text??""}]:typeof a.content=="string"?[{type:"text",text:a.content}]:Array.isArray(a.content)?a.content.map(g=>g.type==="toolCall"?{type:"tool_call",tool_call_id:g.id,name:g.name,arguments:g.arguments}:g.type==="image"?{type:"image",mime_type:g.mimeType}:g.type==="thinking"?{type:"thinking",text:g.thinking}:g):[];return{entry_id:p,role:v,...v==="custom"?{custom_type:K}:{},time:typeof a.timestamp=="string"?a.timestamp:new Date(Number(a.timestamp??Date.now())).toISOString(),content:ee,...v==="assistant"?{model:a.model,provider:a.provider,stop_reason:a.stopReason,...a.errorMessage?{error_message:a.errorMessage}:{},...N?{usage:{input_tokens:N.input??0,output_tokens:N.output??0,cache_read_tokens:N.cacheRead??0,cache_write_tokens:N.cacheWrite??0,cost_usd:N.cost?.total??0}}:{}}:{},...v==="tool_result"?{tool_call_id:a.toolCallId,tool_name:a.toolName,is_error:a.isError}:{}}})??[];return{conversation_id:l,messages:Q}})})),s=n.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e).event_cursor-1,o=new Map(c.map(m=>[m.node_id,ve(m.node_id)])),_=n.prepare(`SELECT node_id, sequence_number FROM run_events
9
+ WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
10
+ ORDER BY sequence_number`).all(e,s);for(const m of _){const l=o.get(m.node_id);l!=null&&m.sequence_number>=l&&o.set(m.node_id,null)}const T=n.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
11
+ WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
12
+ ORDER BY sequence_number`).all(e,s),h=new Map;for(const m of T){const l=o.get(m.node_id);if(l==null||m.sequence_number<l)continue;const S=JSON.parse(m.body_json),f=h.get(m.node_id)??{thinking:"",text:""};m.type==="node.thinking.delta"?f.thinking+=S.delta:f.text+=S.delta,h.set(m.node_id,f)}const Y=c.map(m=>({...m,in_progress_message:o.get(m.node_id)==null?null:h.get(m.node_id)??{thinking:"",text:""}}));return n.exec("COMMIT"),{run_id:e,latest_sequence:s,nodes:Y}}catch(d){throw n.exec("ROLLBACK"),d}}u(Et,"traceRun");function gt(e,t,i){if(t===void 0){if(!e.some(n=>b(n,"crtr:llm")))throw new E(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw D("scopes must be a list of scope strings","scopes");for(const n of t){try{Oe(n)}catch{throw D(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===i.slice(4))throw D(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===i.slice(4))&&!e.some(c=>b(c,n)))throw new E(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new E(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}u(gt,"requestedScopes");export{E as RunError,lt as cancelRun,ft as deleteRun,_t as interruptRun,ut as listRuns,pt as messageRun,L as ownedRun,gt as requestedScopes,at as rewriteLocalIdempotencyGrantee,M as runObject,ct as startRun,Et as traceRun,mt as waitRun};
@@ -11,7 +11,7 @@ export declare function buildProjectContextBlock(cwd: string): string;
11
11
  * never scopes a sibling block) and frames the dir as durable, shared scratch.
12
12
  * Present for every node, rendered as the `## Your context directory`
13
13
  * subsection of <crtr-bearings>. */
14
- export declare function contextDirNote(nodeId: string): string;
14
+ export declare function contextDirNote(nodeId: string, grantee?: string): string;
15
15
  /** The profile-purview note — rendered ONLY when the profile resolves to a
16
16
  * manifest that names at least one project dir. Phrased as PURVIEW, not a cwd
17
17
  * replacement: the node's cwd is still its one working dir (bash/edits run
@@ -25,7 +25,7 @@ export declare function profileNote(cwd: string, profileId: string | null | unde
25
25
  * so its context dir is also where a future cycle of itself resumes the work.
26
26
  * Used inside the bearings block AND in the promotion guidance dump, so a
27
27
  * promoted node gets the same note a born-orchestrator gets. */
28
- export declare function orchestratorContextNote(nodeId: string): string;
28
+ export declare function orchestratorContextNote(nodeId: string, grantee?: string): string;
29
29
  export interface RelativeLabelNode extends NamedNode {
30
30
  node_id: string;
31
31
  kind: string;
@@ -1,18 +1,18 @@
1
- var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{contextDir as f}from"../canvas/paths.js";import{fullName as w}from"../canvas/labels.js";import{tmuxSessionsReachable as k}from"./tmux-driver.js";import{spawnSync as x}from"node:child_process";import{readdirSync as v}from"node:fs";import{hostname as D}from"node:os";import{loadProfileManifest as A}from"../profiles/manifest.js";function j(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(j,"escapeAttribute");function _(){const e=k();return`Host: ${[`${process.platform} ${process.arch}`,D(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(_,"runtimeLine");function C(e){try{const n=v(e,{withFileTypes:!0}).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(C,"directoryListingLines");function m(e,t,n,r){const o=x(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(m,"runCommand");function $(){return{...process.env,GIT_OPTIONAL_LOCKS:"0"}}s($,"gitEnv");function p(e,t){const n=m(e,"git",t,$());return n.ok?n.stdout:""}s(p,"runGit");function E(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(E,"parseWorktrees");function N(e){const t=m(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=p(e,["branch","--show-current"])||p(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=p(e,["rev-parse","--short","HEAD"])||"unknown",o=p(e,["status","--porcelain"]).split(`
1
+ var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{contextDir as f}from"../canvas/paths.js";import{fullName as w}from"../canvas/labels.js";import{tmuxSessionsReachable as k}from"./tmux-driver.js";import{spawnSync as v}from"node:child_process";import{readdirBeneath as x}from"../spaces/open-beneath.js";import{hostname as _}from"node:os";import{loadProfileManifest as A}from"../profiles/manifest.js";function C(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(C,"escapeAttribute");function D(){const e=k();return`Host: ${[`${process.platform} ${process.arch}`,_(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(D,"runtimeLine");function N(e){try{const r=x("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),n=r.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=r.length-n.length;return o>0?[...n,`[+${o} more]`]:n}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(N,"directoryListingLines");function m(e,t,r,n){const o=v(t,r,{cwd:e,encoding:"utf8",...n===void 0?{}:{env:n}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(m,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function p(e,t){const r=m(e,"git",t,$());return r.ok?r.stdout:""}s(p,"runGit");function T(e){const t=[];let r={};for(const n of e)n.startsWith("worktree ")?(r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),r={path:n.slice(9)}):n.startsWith("branch ")&&(r.branch=n.slice(7).replace(/^refs\/heads\//,""));return r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),t}s(T,"parseWorktrees");function G(e){const t=m(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const r=p(e,["branch","--show-current"])||p(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",n=p(e,["rev-parse","--short","HEAD"])||"unknown",o=p(e,["status","--porcelain"]).split(`
2
2
  `).filter(c=>c!=="").length,i=p(e,["worktree","list","--porcelain"]).split(`
3
- `),a=E(i),h=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,u=`Git: ${n} @ ${r}; ${h}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[u,l]}s(N,"gitSnapshotLines");function P(e){const t=C(e),n=N(e);let r=`<project_context>
3
+ `),a=T(i),h=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,u=`Git: ${r} @ ${n}; ${h}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[u,l]}s(G,"gitSnapshotLines");function Y(e){const t=N(e),r=G(e);let n=`<project_context>
4
4
 
5
- `;return r+=`<environment cwd="${j(e)}">
6
- `,r+=`${_()}
7
- `,r+=`Directory:
5
+ `;return n+=`<environment cwd="${C(e)}">
6
+ `,n+=`${D()}
7
+ `,n+=`Directory:
8
8
  ${t.map(o=>` ${o}`).join(`
9
9
  `)}
10
- `,r+=`${n.map(o=>`${o}`).join(`
10
+ `,n+=`${r.map(o=>`${o}`).join(`
11
11
  `)}
12
- `,r+=`</environment>
13
- </project_context>`,r}s(P,"buildProjectContextBlock");function B(e){return`Your context directory is \`${f(e)}\` (also in the env as \`$CRTR_CONTEXT_DIR\`) \u2014 durable scratch space on disk where you write documents to share with other nodes on the canvas. Put documents here that you want to share by reference instead of re-explaining them in a prompt: specs, designs, findings, notes worth pointing a sibling, child, or parent at. It is a shared document store, not a task tracker. **Address it by absolute path** \u2014 write artifacts as \`$CRTR_CONTEXT_DIR/<name>.md\` (or the full path above). Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here. When you report a file, report its absolute path.`}s(B,"contextDirNote");function I(e,t){if(t==null||t==="")return"";let n;try{n=A(t)}catch{return""}const r=n.manifest.projects.map(o=>o.path);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(I,"profileNote");function M(e){return`Because you persist across refresh cycles, your context directory (${f(e)}) is also where a future cycle of you resumes the work \u2014 keep the working notes and decisions a refreshed you would need there, alongside the docs you share with the nodes you spawn.`}s(M,"orchestratorContextNote");function g(e){const t=w(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(g,"relativeLabel");const T=5;function X(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,d)=>{a.push(`${i(d)}${d===0?"":"\u2514 "}${g(c)}`)});const h=r.length;a.push(`${i(h)}${h===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const u=o.slice(0,T),l=o.length-u.length;return u.forEach((c,d)=>{const y=d===u.length-1&&l===0;a.push(`${i(h+1)}${y?"\u2514 ":"\u251C "}${g(c)}`)}),l>0&&a.push(`${i(h+1)}\u2514 +${l} more`),a.join(`
14
- `)}s(X,"renderGraphMap");function z(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
- `)}s(z,"buildIdentityAssertion");function K(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
12
+ `,n+=`</environment>
13
+ </project_context>`,n}s(Y,"buildProjectContextBlock");function B(e,t){return`Your context directory is \`${f(e,t)}\` (also in the env as \`$CRTR_CONTEXT_DIR\`) \u2014 durable scratch space on disk where you write documents to share with other nodes on the canvas. Put documents here that you want to share by reference instead of re-explaining them in a prompt: specs, designs, findings, notes worth pointing a sibling, child, or parent at. It is a shared document store, not a task tracker. **Address it by absolute path** \u2014 write artifacts as \`$CRTR_CONTEXT_DIR/<name>.md\` (or the full path above). Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here. When you report a file, report its absolute path.`}s(B,"contextDirNote");function P(e,t){if(t==null||t==="")return"";let r;try{r=A(t)}catch{return""}const n=r.manifest.projects.map(o=>o.path);return n.length===0?"":`Your working dir is \`${e}\`. Your profile **${r.manifest.name}** also has purview over: ${n.join(", ")}.`}s(P,"profileNote");function M(e,t){return`Because you persist across refresh cycles, your context directory (${f(e,t)}) is also where a future cycle of you resumes the work \u2014 keep the working notes and decisions a refreshed you would need there, alongside the docs you share with the nodes you spawn.`}s(M,"orchestratorContextNote");function g(e){const t=w(e),r=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${r}`}s(g,"relativeLabel");const O=5;function F(e,t,r,n,o){if(n.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];n.forEach((c,d)=>{a.push(`${i(d)}${d===0?"":"\u2514 "}${g(c)}`)});const h=n.length;a.push(`${i(h)}${h===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${r})`);const u=o.slice(0,O),l=o.length-u.length;return u.forEach((c,d)=>{const y=d===u.length-1&&l===0;a.push(`${i(h+1)}${y?"\u2514 ":"\u251C "}${g(c)}`)}),l>0&&a.push(`${i(h+1)}\u2514 +${l} more`),a.join(`
14
+ `)}s(F,"renderGraphMap");function X(e,t,r,n,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${r}.`];return n!=null&&n!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
+ `)}s(X,"buildIdentityAssertion");function z(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
16
16
  Worktree: \`${e.path}\`
17
17
  Base: \`${e.base_ref}\` @ \`${e.base_sha}\`
18
- Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(K,"worktreeNote");export{z as buildIdentityAssertion,P as buildProjectContextBlock,B as contextDirNote,j as escapeAttribute,M as orchestratorContextNote,I as profileNote,g as relativeLabel,X as renderGraphMap,K as worktreeNote};
18
+ Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(z,"worktreeNote");export{X as buildIdentityAssertion,Y as buildProjectContextBlock,B as contextDirNote,C as escapeAttribute,M as orchestratorContextNote,P as profileNote,g as relativeLabel,F as renderGraphMap,z as worktreeNote};
@@ -1,7 +1,7 @@
1
- var y=Object.defineProperty;var t=(e,r)=>y(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as c,isSafeNodeId as N,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as v}from"../wake.js";import{renderKnowledgeBlock as x,renderWorkspaceOpenDocs as _}from"../substrate/index.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as d}from"../canvas/node-order.js";import{buildProjectContextBlock as l,contextDirNote as f,orchestratorContextNote as p,profileNote as $,renderGraphMap as O,buildIdentityAssertion as S,worktreeNote as Y}from"./bearings-render.js";import{CONTEXT_INTRO_CUSTOM_TYPE as Q}from"../../shared/generated-context.js";function B(e){const r=s(e);return r===null?"":$(r.cwd,r.profile_id)}t(B,"profileNote");function E(e){const r=[],n=new Set([e]);let o=s(e)?.parent??null;for(;o!==null&&o!==""&&!n.has(o);){n.add(o);const a=s(o);if(a===null)break;r.unshift(a),o=a.parent??null}return r}t(E,"ancestorTrunk");const X=5;function j(e){return g(e).map(r=>s(r.node_id)).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>d(r.status)-d(n.status))}t(j,"childNodes");function A(e){const r=s(e);if(r===null)return"";const n=E(e),o=j(e);return O(e,r.kind,r.mode,n,o)}t(A,"buildGraphMap");function R(e){const r=s(e),n=r?.fork_from,o=n!=null&&n!==""&&N(n)?s(n):null,a=o!==null?`${n} ("${c(o)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,a)}t(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}t(T,"armerPhrase");function F(e,r){const n=e.created_by!=null?s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:c(n)}:{},armedAt:e.created,recur:e.recur}}t(F,"cronWakeOrigin");function K(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?v(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
1
+ var y=Object.defineProperty;var t=(e,r)=>y(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as c,isSafeNodeId as g,subscriptionsOf as N}from"../canvas/index.js";import{cadenceDisplay as v}from"../wake.js";import{renderKnowledgeBlock as x,renderWorkspaceOpenDocs as _}from"../substrate/index.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as d}from"../canvas/node-order.js";import{buildProjectContextBlock as l,contextDirNote as f,orchestratorContextNote as p,profileNote as $,renderGraphMap as O,buildIdentityAssertion as S,worktreeNote as Y}from"./bearings-render.js";import{CONTEXT_INTRO_CUSTOM_TYPE as Q}from"../../shared/generated-context.js";function B(e){const r=s(e);return r===null?"":$(r.cwd,r.profile_id)}t(B,"profileNote");function E(e){const r=[],n=new Set([e]);let o=s(e)?.parent??null;for(;o!==null&&o!==""&&!n.has(o);){n.add(o);const a=s(o);if(a===null)break;r.unshift(a),o=a.parent??null}return r}t(E,"ancestorTrunk");const X=5;function j(e){return N(e).map(r=>s(r.node_id)).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>d(r.status)-d(n.status))}t(j,"childNodes");function A(e){const r=s(e);if(r===null)return"";const n=E(e),o=j(e);return O(e,r.kind,r.mode,n,o)}t(A,"buildGraphMap");function R(e){const r=s(e),n=r?.fork_from,o=n!=null&&n!==""&&g(n)?s(n):null,a=o!==null?`${n} ("${c(o)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,a)}t(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}t(T,"armerPhrase");function F(e,r){const n=e.created_by!=null?s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:c(n)}:{},armedAt:e.created,recur:e.recur}}t(F,"cronWakeOrigin");function K(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?v(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
2
  ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
3
  </crtr-wake>`;const o=T(e);return`<crtr-wake>
4
4
  ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}t(K,"buildWakeBearings");function D(e){return Y(e?.managed_worktree)}t(D,"managedWorktreeNote");function q(e,r){const n=s(e),o=["<crtr-bearings>",R(e)],a=A(e);a!==""&&o.push("","## Your place in the canvas",a),o.push("","## Your context directory",f(e));const u=B(e);u!==""&&o.push("",u);const i=D(n);i!==""&&o.push("","## Your managed worktree",i),n?.mode==="orchestrator"&&o.push("",p(e)),o.push("</crtr-bearings>");const w=x(e,r),h=_(e,r),m=C(e)??"",k=n?.cwd!==void 0?l(n.cwd):"";return[o.join(`
5
+ </crtr-wake>`}t(K,"buildWakeBearings");function D(e){return Y(e?.managed_worktree)}t(D,"managedWorktreeNote");function q(e,r){const n=s(e),o=["<crtr-bearings>",R(e)],a=A(e);a!==""&&o.push("","## Your place in the canvas",a),o.push("","## Your context directory",f(e,n?.grantee));const u=B(e);u!==""&&o.push("",u);const i=D(n);i!==""&&o.push("","## Your managed worktree",i),n?.mode==="orchestrator"&&o.push("",p(e,n.grantee)),o.push("</crtr-bearings>");const w=x(e,r),h=_(e,r),m=C(e)??"",k=n?.cwd!==void 0?l(n.cwd):"";return[o.join(`
6
6
  `),w,h,m,k].filter(b=>b!=="").join(`
7
7
  `)}t(q,"buildContextBearings");export{Q as CONTEXT_INTRO_CUSTOM_TYPE,q as buildContextBearings,A as buildGraphMap,l as buildProjectContextBlock,K as buildWakeBearings,f as contextDirNote,F as cronWakeOrigin,p as orchestratorContextNote,B as profileNote};
@@ -0,0 +1,5 @@
1
+ /** The broker alone holds the bearer. CLI processes see only this socket path. */
2
+ export declare function serveCliRelay(nodeId: string, token: string): Promise<{
3
+ path: string;
4
+ close(): void;
5
+ }>;
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var d=(s,n)=>m(s,"name",{value:n,configurable:!0});import{createServer as h,request as f}from"node:http";import{chmodSync as y,existsSync as l,unlinkSync as p}from"node:fs";import{join as S}from"node:path";import{apiSocketPath as u,nodeRunDir as k}from"../../canvas/paths.js";async function H(s,n){const r=S(k(s),"cli.sock"),o=h((t,e)=>{const i={...t.headers,authorization:`Bearer ${n}`};delete i.connection;const c=f({socketPath:u(),path:t.url,method:t.method,headers:i},a=>{e.writeHead(a.statusCode??502,a.headers),a.pipe(e)});c.on("error",a=>{e.headersSent||e.writeHead(503,{"content-type":"application/json"}),e.end(JSON.stringify({error:{code:"daemon_unavailable",message:a.message}}))}),t.pipe(c),e.on("close",()=>c.destroy())});return l(r)&&p(r),await new Promise((t,e)=>{o.once("error",e),o.listen(r,()=>{o.off("error",e),t()})}),y(r,384),{path:r,close(){o.closeAllConnections(),o.close(),l(r)&&p(r)}}}d(H,"serveCliRelay");export{H as serveCliRelay};
@@ -1,10 +1,5 @@
1
1
  import type { Socket } from 'node:net';
2
2
  import { FrameDecoder, type BrokerSnapshot, type BrokerToClient, type ClientRole } from '../broker-protocol.js';
3
- /** True when the live broker has at least one client that declared itself to
4
- * be attending the conversation. A system observer may read the same stream
5
- * without keeping an otherwise idle broker alive. Callers establish broker
6
- * liveness separately because a crash can leave the last persisted count behind. */
7
- export declare function hasAttachedBrokerViewers(nodeId: string): boolean;
8
3
  export interface BrokerClient {
9
4
  id: string;
10
5
  role: ClientRole;
@@ -1 +1 @@
1
- var c=Object.defineProperty;var d=(s,e)=>c(s,"name",{value:e,configurable:!0});import{existsSync as o,mkdirSync as l,readFileSync as h,unlinkSync as u,writeFileSync as p}from"node:fs";import{jobDir as a}from"../../canvas/paths.js";import{emitEvent as y}from"../../events/emit.js";import{encodeFrame as f,FrameDecoder as g,BROKER_READ_CAPS as m}from"../broker-protocol.js";const S=1e3,w=32*1024*1024;function B(s){try{const e=JSON.parse(h(`${a(s)}/attach.json`,"utf8"));return typeof e.viewers=="number"&&e.viewers>0}catch{return!1}}d(B,"hasAttachedBrokerViewers");class A{static{d(this,"BrokerClientRegistry")}nodeId;attachPath;clients=new Set;displayStatuses=new Map;displayWidgets=new Map;displayTitle;constructor(e){this.nodeId=e,this.attachPath=`${a(e)}/attach.json`}create(e){const t={id:"",role:"observer",socket:e,decoder:new g(m),helloed:!1,attends:!0,snapshotTail:void 0,pendingBytes:0,queuedFrames:0};return this.clients.add(t),t}writableClients(){const e=[];for(const t of this.clients)!t.helloed||t.role!=="controller"||t.socket.destroyed||t.socket.readableEnded||!t.socket.writable||e.push(t);return e}persistAttachState(){try{let e=0;for(const i of this.clients)i.helloed&&i.attends&&(e+=1);const t=a(this.nodeId);o(t)||l(t,{recursive:!0}),p(this.attachPath,JSON.stringify({viewers:e,updated:new Date().toISOString()},null,2),"utf8")}catch{}}dropClient(e,t){if(this.clients.has(e)){y({level:"info",event:"broker.runtime.diagnostic",fields:{message:`dropping viewer ${e.id||"(pre-hello)"} \u2014 ${t}`}}),this.removeClient(e);try{e.socket.destroy()}catch{}}}removeClient(e){this.clients.delete(e),this.persistAttachState()}sendFrame(e,t,i=!1){let n;try{n=f(t)}catch{return}const r=Buffer.byteLength(n);if(!i&&(e.queuedFrames+1>S||e.pendingBytes+r>w)){this.dropClient(e,`backpressure high-water mark exceeded (queued=${e.queuedFrames}, pending=${e.pendingBytes}B)`);return}e.queuedFrames+=1,e.pendingBytes+=r;try{e.socket.write(n,()=>{e.queuedFrames-=1,e.pendingBytes-=r})}catch{e.queuedFrames-=1,e.pendingBytes-=r}}broadcast(e){for(const t of this.clients)t.helloed&&this.sendFrame(t,e)}broadcastUi(e){e.type==="extension_ui_request"&&(e.method==="setStatus"?(this.displayStatuses.delete(e.statusKey),e.statusText!==void 0&&this.displayStatuses.set(e.statusKey,e.statusText)):e.method==="setWidget"?(this.displayWidgets.delete(e.widgetKey),e.widgetLines!==void 0&&this.displayWidgets.set(e.widgetKey,{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"})):e.method==="setTitle"&&(this.displayTitle=e.title)),this.broadcast(e)}displaySnapshot(){return{statuses:Object.fromEntries(this.displayStatuses),widgets:Object.fromEntries([...this.displayWidgets].map(([e,t])=>[e,{lines:[...t.lines],placement:t.placement}])),title:this.displayTitle}}forEachHelloed(e){for(const t of this.clients)t.helloed&&e(t)}dispose(){for(const e of this.clients)try{e.socket.destroy()}catch{}this.clients.clear()}clearAttachState(){try{o(this.attachPath)&&u(this.attachPath)}catch{}}}export{A as BrokerClientRegistry,B as hasAttachedBrokerViewers};
1
+ var l=Object.defineProperty;var o=(d,e)=>l(d,"name",{value:e,configurable:!0});import{existsSync as r,mkdirSync as c,unlinkSync as h,writeFileSync as u}from"node:fs";import{nodeRunJobDir as a}from"../../canvas/paths.js";import{emitEvent as p}from"../../events/emit.js";import{encodeFrame as y,FrameDecoder as f,BROKER_READ_CAPS as g}from"../broker-protocol.js";const m=1e3,S=32*1024*1024;class B{static{o(this,"BrokerClientRegistry")}nodeId;attachPath;clients=new Set;displayStatuses=new Map;displayWidgets=new Map;displayTitle;constructor(e){this.nodeId=e,this.attachPath=`${a(e)}/attach.json`}create(e){const t={id:"",role:"observer",socket:e,decoder:new f(g),helloed:!1,attends:!0,snapshotTail:void 0,pendingBytes:0,queuedFrames:0};return this.clients.add(t),t}writableClients(){const e=[];for(const t of this.clients)!t.helloed||t.role!=="controller"||t.socket.destroyed||t.socket.readableEnded||!t.socket.writable||e.push(t);return e}persistAttachState(){try{let e=0;for(const s of this.clients)s.helloed&&s.attends&&(e+=1);const t=a(this.nodeId);r(t)||c(t,{recursive:!0}),u(this.attachPath,JSON.stringify({viewers:e,updated:new Date().toISOString()},null,2),"utf8")}catch{}}dropClient(e,t){if(this.clients.has(e)){p({level:"info",event:"broker.runtime.diagnostic",fields:{message:`dropping viewer ${e.id||"(pre-hello)"} \u2014 ${t}`}}),this.removeClient(e);try{e.socket.destroy()}catch{}}}removeClient(e){this.clients.delete(e),this.persistAttachState()}sendFrame(e,t,s=!1){let n;try{n=y(t)}catch{return}const i=Buffer.byteLength(n);if(!s&&(e.queuedFrames+1>m||e.pendingBytes+i>S)){this.dropClient(e,`backpressure high-water mark exceeded (queued=${e.queuedFrames}, pending=${e.pendingBytes}B)`);return}e.queuedFrames+=1,e.pendingBytes+=i;try{e.socket.write(n,()=>{e.queuedFrames-=1,e.pendingBytes-=i})}catch{e.queuedFrames-=1,e.pendingBytes-=i}}broadcast(e){for(const t of this.clients)t.helloed&&this.sendFrame(t,e)}broadcastUi(e){e.type==="extension_ui_request"&&(e.method==="setStatus"?(this.displayStatuses.delete(e.statusKey),e.statusText!==void 0&&this.displayStatuses.set(e.statusKey,e.statusText)):e.method==="setWidget"?(this.displayWidgets.delete(e.widgetKey),e.widgetLines!==void 0&&this.displayWidgets.set(e.widgetKey,{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"})):e.method==="setTitle"&&(this.displayTitle=e.title)),this.broadcast(e)}displaySnapshot(){return{statuses:Object.fromEntries(this.displayStatuses),widgets:Object.fromEntries([...this.displayWidgets].map(([e,t])=>[e,{lines:[...t.lines],placement:t.placement}])),title:this.displayTitle}}forEachHelloed(e){for(const t of this.clients)t.helloed&&e(t)}dispose(){for(const e of this.clients)try{e.socket.destroy()}catch{}this.clients.clear()}clearAttachState(){try{r(this.attachPath)&&h(this.attachPath)}catch{}}}export{B as BrokerClientRegistry};
@@ -1,8 +1,25 @@
1
- import type { BrokerExtensionStateDTO, BrokerGeneratedNameRequest, BrokerGeneratedNameResultDTO, BrokerModelCommitRequest, BrokerModelCommitResultDTO, BrokerParkActivityResultDTO, BrokerParkCompleteRequest, BrokerPersonaAckRequest, BrokerPersonaAckResultDTO, BrokerSessionBoundRequest, BrokerSessionBoundResultDTO, BrokerSettleDirective, BrokerSettleRequest, BrokerTelemetryRequest } from '../../../api/dto/broker-ops.js';
1
+ import type { BrokerExtensionStateDTO, BrokerContextDTO, BrokerMemoryRefsDTO, BrokerContextSnapshotDTO, BrokerContextEventRequest, BrokerGeneratedNameRequest, BrokerGeneratedNameResultDTO, BrokerModelCommitRequest, BrokerModelCommitResultDTO, BrokerParkActivityResultDTO, BrokerParkCompleteRequest, BrokerPersonaAckRequest, BrokerPersonaAckResultDTO, BrokerSessionBoundRequest, BrokerSessionBoundResultDTO, BrokerSettleDirective, BrokerSettleRequest, BrokerTelemetryRequest } from '../../../api/dto/broker-ops.js';
2
2
  import type { AcknowledgeMailResultDTO, ClaimMailResultDTO, MailReceiptDTO } from '../../../api/dto/mail.js';
3
3
  import type { BrokerFaultInputDTO, BrokerFaultRequest, BrokerFaultResultDTO, BrokerProviderRetryRequest, BrokerProviderRetryResultDTO, BrokerTurnRequest, BrokerTurnResultDTO, RecoveryStateDTO } from '../../../api/dto/recovery.js';
4
4
  import type { RelaunchRootResultDTO } from '../../../api/dto/lifecycle.js';
5
5
  import type { PushReportRequest } from '../../../api/dto/reports.js';
6
+ import type { MemoryLoad } from '../../substrate/injected-store.js';
7
+ import type { NodeLogAppendResultDTO, NodeMessageBodyDTO, NodePushedFinalResultDTO, NodeTelemetryRecordRequest } from '../../../api/dto/node-records.js';
8
+ export declare function appendBrokerLog(nodeId: string, record: string): Promise<NodeLogAppendResultDTO>;
9
+ export declare function putBrokerTelemetry(nodeId: string, telemetry: Omit<NodeTelemetryRecordRequest, 'expected_execution_id'>): Promise<void>;
10
+ export declare function putBrokerRecap(nodeId: string, briefing: string): Promise<void>;
11
+ /** The body of a direct message the daemon spilled into this node's records. */
12
+ export declare function readBrokerPassiveMessage(nodeId: string, ref: string): Promise<NodeMessageBodyDTO>;
13
+ export declare function clearBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
14
+ export declare function consumeBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
15
+ export declare function startBrokerBashJob(nodeId: string, request: {
16
+ job_id: string;
17
+ cwd: string;
18
+ env: NodeJS.ProcessEnv;
19
+ }): Promise<{
20
+ pid: number;
21
+ }>;
22
+ export declare function stopBrokerBashJob(nodeId: string, jobId: string): Promise<void>;
6
23
  export declare function brokerExecutionId(): string;
7
24
  export declare function bindBrokerSession(nodeId: string, request: Omit<BrokerSessionBoundRequest, 'executionId'>): Promise<BrokerSessionBoundResultDTO>;
8
25
  type BrokerInput<T> = T extends unknown ? Omit<T, 'expected_execution_id'> : never;
@@ -27,6 +44,12 @@ export declare function clearNodeFault(nodeId: string, opts?: {
27
44
  * exposes no generic node/database facade. */
28
45
  export declare function commitBrokerModel(nodeId: string, request: BrokerInput<BrokerModelCommitRequest>): Promise<BrokerModelCommitResultDTO>;
29
46
  export declare function brokerExtensionState(nodeId: string): Promise<BrokerExtensionStateDTO>;
47
+ export declare function brokerMemoryRefs(nodeId: string): Promise<BrokerMemoryRefsDTO>;
48
+ export declare function brokerContext(nodeId: string, mode: 'baseline' | 'compact' | 'preferences'): Promise<BrokerContextDTO>;
49
+ /** Commit a context snapshot; pass the prepared `loads` once they are delivered
50
+ * so crtrd records them as `loaded` memory-log events. */
51
+ export declare function commitBrokerContext(nodeId: string, snapshot: BrokerContextSnapshotDTO, loads?: BrokerContextDTO['loads']): Promise<void>;
52
+ export declare function brokerContextEvent(nodeId: string, event: BrokerContextEventRequest['event'], value?: string): Promise<BrokerContextDTO>;
30
53
  export declare function commitBrokerGeneratedName(nodeId: string, request: BrokerInput<BrokerGeneratedNameRequest>): Promise<BrokerGeneratedNameResultDTO>;
31
54
  export declare function commitBrokerPersonaAck(nodeId: string, request: BrokerInput<BrokerPersonaAckRequest>): Promise<BrokerPersonaAckResultDTO>;
32
55
  /** Reports still use the canonical daemon report handler; this broker adapter
@@ -36,4 +59,8 @@ export declare function publishBrokerReport(nodeId: string, request: PushReportR
36
59
  * a replacement broker and tears down this broker. Callers must not await it
37
60
  * from Pi's session-start dispatch. */
38
61
  export declare function relaunchBrokerRoot(nodeId: string): Promise<RelaunchRootResultDTO>;
62
+ /** Record full bodies a broker delivered into its context as `loaded` memory-log
63
+ * events. Fire-and-forget: the send never rejects and callers do not await it,
64
+ * so delivery never waits on crtrd. */
65
+ export declare function recordMemoryEvents(nodeId: string, loads: readonly MemoryLoad[]): void;
39
66
  export {};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var o=(e,r)=>c(e,"name",{value:r,configurable:!0});import{localClient as u}from"../../../api/node-transport.js";import{ApiError as d}from"../../../api/errors.js";import{envExecutionId as a}from"../../../shared/env.js";function t(){return u({autostart:!1})}o(t,"daemonClient");function n(){const e=a();if(e===void 0||e==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return e}o(n,"brokerExecutionId");function f(e,r){return t().bindBrokerSession(e,{...r,executionId:n()})}o(f,"bindBrokerSession");function m(e,r){return t().settleBroker(e,{...r,expected_execution_id:n()})}o(m,"settleBroker");function B(e,r){return t().completeBrokerPark(e,{...r,expected_execution_id:n()})}o(B,"completeBrokerPark");function _(e){return t().recordBrokerParkActivity(e,{expected_execution_id:n()})}o(_,"recordBrokerParkActivity");function s(e,r){return t().recordBrokerTelemetry(e,{...r,expected_execution_id:n()})}o(s,"recordBrokerTelemetry");function y(e,r){return t().claimNodeMail(e,{execution_id:n(),channel:r})}o(y,"claimBrokerMail");function v(e,r){return t().acknowledgeNodeMail(e,{execution_id:n(),deliveries:r})}o(v,"acknowledgeBrokerMail");function E(e,r){return t().recordBrokerTurn(e,{...r,expected_execution_id:n()})}o(E,"recordBrokerTurn");function R(e,r){return t().mutateBrokerProviderRetry(e,{...r,expected_execution_id:n()})}o(R,"mutateBrokerProviderRetry");function h(e,r){return t().mutateBrokerFault(e,{...r,expected_execution_id:n()})}o(h,"mutateBrokerFault");function N(e){return t().getBrokerRecovery(e,n())}o(N,"brokerRecovery");function b(e,r){return t().recordNodeFault(e,r)}o(b,"recordNodeFault");function P(e,r={}){return t().clearNodeFault(e,{...r.link===void 0?{}:{link:r.link},...r.preserveEpisode===void 0?{}:{preserve_episode:r.preserveEpisode}}).then(i=>i.cleared)}o(P,"clearNodeFault");function w(e,r){return t().commitBrokerModel(e,{...r,expected_execution_id:n()})}o(w,"commitBrokerModel");function F(e){return t().brokerExtensionState(e)}o(F,"brokerExtensionState");function M(e,r){return t().commitBrokerGeneratedName(e,{...r,expected_execution_id:n()})}o(M,"commitBrokerGeneratedName");function T(e,r){return t().commitBrokerPersonaAck(e,{...r,expected_execution_id:n()})}o(T,"commitBrokerPersonaAck");async function A(e,r){try{await t().pushReport(e,r)}catch(i){if(r.tier==="final"&&i instanceof d&&i.code==="already_finalized")return;throw i}}o(A,"publishBrokerReport");function I(e){return t().relaunchRoot(e)}o(I,"relaunchBrokerRoot");export{v as acknowledgeBrokerMail,f as bindBrokerSession,n as brokerExecutionId,F as brokerExtensionState,N as brokerRecovery,y as claimBrokerMail,P as clearNodeFault,M as commitBrokerGeneratedName,w as commitBrokerModel,T as commitBrokerPersonaAck,B as completeBrokerPark,h as mutateBrokerFault,R as mutateBrokerProviderRetry,A as publishBrokerReport,_ as recordBrokerParkActivity,s as recordBrokerTelemetry,E as recordBrokerTurn,b as recordNodeFault,I as relaunchBrokerRoot,m as settleBroker};
1
+ var f=Object.defineProperty;var t=(e,r)=>f(e,"name",{value:r,configurable:!0});import{localClient as k}from"../../../api/node-transport.js";import{ApiError as p}from"../../../api/errors.js";import{envExecutionId as m}from"../../../shared/env.js";import{memoryEvents as l,sendMemoryEvents as _}from"../../substrate/memory-events.js";function o(){return k({autostart:!1})}t(o,"daemonClient");function R(e,r){return o().appendNodeLog(e,{record:r,expected_execution_id:n()})}t(R,"appendBrokerLog");function v(e,r){return o().putNodeTelemetry(e,{...r,expected_execution_id:n()})}t(v,"putBrokerTelemetry");function P(e,r){return o().putNodeRecap(e,{briefing:r,expected_execution_id:n()})}t(P,"putBrokerRecap");function N(e,r){return o().readNodePassiveMessage(e,r)}t(N,"readBrokerPassiveMessage");function C(e){return o().nodePushedFinal(e,{action:"clear",expected_execution_id:n()})}t(C,"clearBrokerPushedFinal");function M(e){return o().nodePushedFinal(e,{action:"consume",expected_execution_id:n()})}t(M,"consumeBrokerPushedFinal");function g(e,r){return o().request("POST",`/v1/nodes/${encodeURIComponent(e)}/jobs/start`,{...r,expected_execution_id:n()})}t(g,"startBrokerBashJob");function w(e,r){return o().request("DELETE",`/v1/nodes/${encodeURIComponent(e)}/jobs/${encodeURIComponent(r)}?foreground=1`,{expected_execution_id:n()})}t(w,"stopBrokerBashJob");function n(){const e=m();if(e===void 0||e==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return e}t(n,"brokerExecutionId");function F(e,r){return o().bindBrokerSession(e,{...r,executionId:n()})}t(F,"bindBrokerSession");function T(e,r){return o().settleBroker(e,{...r,expected_execution_id:n()})}t(T,"settleBroker");function I(e,r){return o().completeBrokerPark(e,{...r,expected_execution_id:n()})}t(I,"completeBrokerPark");function A(e){return o().recordBrokerParkActivity(e,{expected_execution_id:n()})}t(A,"recordBrokerParkActivity");function S(e,r){return o().recordBrokerTelemetry(e,{...r,expected_execution_id:n()})}t(S,"recordBrokerTelemetry");async function U(e,r){const i=o(),x=n(),d=await i.claimNodeMail(e,{execution_id:x,channel:r});if(d.action==="hold")return d;const s=await Promise.all(d.deliveries.map(async c=>{const a=c.entry.ref;if(a===void 0||!/^[a-z0-9-]+:reports\/[^/]+\.md$/.test(a))return c;try{const{content:u}=await i.readNodeInboxReport(e,a,x);return{...c,entry:{...c.entry,data:{...c.entry.data,report_body:u}}}}catch(u){if(u instanceof p&&u.status===404)return c;throw u}}));return{...d,deliveries:s}}t(U,"claimBrokerMail");function $(e,r){return o().acknowledgeNodeMail(e,{execution_id:n(),deliveries:r})}t($,"acknowledgeBrokerMail");function L(e,r){return o().recordBrokerTurn(e,{...r,expected_execution_id:n()})}t(L,"recordBrokerTurn");function j(e,r){return o().mutateBrokerProviderRetry(e,{...r,expected_execution_id:n()})}t(j,"mutateBrokerProviderRetry");function z(e,r){return o().mutateBrokerFault(e,{...r,expected_execution_id:n()})}t(z,"mutateBrokerFault");function D(e){return o().getBrokerRecovery(e,n())}t(D,"brokerRecovery");function G(e,r){return o().recordNodeFault(e,r)}t(G,"recordNodeFault");function J(e,r={}){return o().clearNodeFault(e,{...r.link===void 0?{}:{link:r.link},...r.preserveEpisode===void 0?{}:{preserve_episode:r.preserveEpisode}}).then(i=>i.cleared)}t(J,"clearNodeFault");function O(e,r){return o().commitBrokerModel(e,{...r,expected_execution_id:n()})}t(O,"commitBrokerModel");function q(e){return o().brokerExtensionState(e)}t(q,"brokerExtensionState");function X(e){return o().brokerMemoryRefs(e,n())}t(X,"brokerMemoryRefs");function H(e,r){return o().brokerContext(e,{mode:r,expected_execution_id:n()})}t(H,"brokerContext");function K(e,r,i){return o().commitBrokerContext(e,{snapshot:r,...i===void 0||i.length===0?{}:{loads:i},expected_execution_id:n()})}t(K,"commitBrokerContext");function Q(e,r,i){return o().brokerContextEvent(e,{event:r,...i===void 0?{}:{value:i},expected_execution_id:n()})}t(Q,"brokerContextEvent");function V(e,r){return o().commitBrokerGeneratedName(e,{...r,expected_execution_id:n()})}t(V,"commitBrokerGeneratedName");function W(e,r){return o().commitBrokerPersonaAck(e,{...r,expected_execution_id:n()})}t(W,"commitBrokerPersonaAck");async function Y(e,r){try{await o().pushReport(e,r)}catch(i){if(r.tier==="final"&&i instanceof p&&i.code==="already_finalized")return;throw i}}t(Y,"publishBrokerReport");function Z(e){return o().relaunchRoot(e)}t(Z,"relaunchBrokerRoot");function ee(e,r){_(e,l(r,"loaded"))}t(ee,"recordMemoryEvents");export{$ as acknowledgeBrokerMail,R as appendBrokerLog,F as bindBrokerSession,H as brokerContext,Q as brokerContextEvent,n as brokerExecutionId,q as brokerExtensionState,X as brokerMemoryRefs,D as brokerRecovery,U as claimBrokerMail,C as clearBrokerPushedFinal,J as clearNodeFault,K as commitBrokerContext,V as commitBrokerGeneratedName,O as commitBrokerModel,W as commitBrokerPersonaAck,I as completeBrokerPark,M as consumeBrokerPushedFinal,z as mutateBrokerFault,j as mutateBrokerProviderRetry,Y as publishBrokerReport,P as putBrokerRecap,v as putBrokerTelemetry,N as readBrokerPassiveMessage,A as recordBrokerParkActivity,S as recordBrokerTelemetry,L as recordBrokerTurn,ee as recordMemoryEvents,G as recordNodeFault,Z as relaunchBrokerRoot,T as settleBroker,g as startBrokerBashJob,w as stopBrokerBashJob};
@@ -4,7 +4,6 @@ import type { BrokerClient, BrokerClientRegistry } from './client-registry.js';
4
4
  import type { EventProjection } from './event-projection.js';
5
5
  import type { MemoryRefGuidance } from './frame-memory-refs.js';
6
6
  import type { FrameReplies } from './frame-replies.js';
7
- import type { AuthReloadGate } from './auth-reload.js';
8
7
  import type { BrokerSession } from './read-ops.js';
9
8
  import type { RebindDriver } from './rebind.js';
10
9
  import type { ToolGroupTracker } from './tool-groups.js';
@@ -29,7 +28,6 @@ export declare function createEngineDriver(deps: {
29
28
  session: () => BrokerSession;
30
29
  dispatches: PromptDispatchTracker;
31
30
  memoryRefs: MemoryRefGuidance;
32
- authReloadGate: AuthReloadGate;
33
31
  rebind: RebindDriver;
34
32
  projection: EventProjection;
35
33
  toolGroups: ToolGroupTracker;
@@ -1 +1 @@
1
- var z=Object.defineProperty;var s=(y,h)=>z(y,"name",{value:h,configurable:!0});import{emitEvent as R}from"../../events/emit.js";import{operationIdContext as k}from"../../events/operation-id.js";import{parkSummaryGraceMs as H}from"../../../shared/env.js";import{headlessTurn as K}from"../headless-pi.js";import{completeBrokerPark as L,recordBrokerParkActivity as Q}from"./daemon-ops.js";import{promptWithAdvertisedCommandInvocation as g}from"../advertised-command-invocation.js";import{heldDeferredInboxPromptJoin as V}from"./held-deferred-inbox.js";import{announceMessageOrigin as X}from"../stamp/channel.js";import{chooseGuidanceDeliveryMode as Y,promptWithNextTurnGuidance as Z,resolveEngineRoute as tt,resolveSteerCall as et}from"./engine-routing.js";function pt(y){const{nodeId:h,registry:u,replies:A,session:r,dispatches:l,memoryRefs:S,authReloadGate:I,rebind:f,projection:E,toolGroups:T,turnAdmission:P}=y,{ackTo:B,engineErrorTo:M}=A,_=s(e=>{let t;return{relay:s(n=>{t=n,u.sendFrame(e,{type:"error",code:"engine_error",message:String(n)})},"relay"),failure:s(()=>t,"failure")}},"errorRelay"),v=s((e,t)=>r().sendCustomMessage({customType:"crtr-memory-refs",content:e,display:!1},{deliverAs:t}).catch(n=>{R({level:"warn",event:"broker.memory_refs.guidance_send_failed",error:n})}),"sendGuidance");let p=!1;const C=s(async()=>{if(!p)return;if((await Q(h)).activity!=="recorded")throw new Error("parking completion took priority before input admission")},"recordParkActivityBeforeInput"),O=s(e=>{p=!0;const t=r(),n=t.model,o=t.sessionManager;(n===void 0||typeof n.provider!="string"||typeof n.id!="string"?Promise.resolve("failed"):K({systemPrompt:t.systemPrompt,userPrompt:e,modelSpec:`${n.provider}/${n.id}`,timeoutMs:H(),seedMessages:o.buildSessionContext().messages,sessionId:o.getSessionId(),toolPolicy:"builtin"})).catch(()=>"failed").then(i=>L(h,{outcome:i})).then(i=>{i.action==="shutdown"&&f.requestShutdown()}).catch(i=>{R({level:"error",event:"broker.park.complete_failed",error:i})}).finally(()=>{p=!1})},"runParkTurn"),x=s((e,t,n)=>{const o=n.relay,a=s(c=>c.then(()=>n.failure()),"settle"),i=s(c=>{const d=tt(t,r().isStreaming),J=d.call==="prompt"?d.options:void 0,m=S.guidanceFor(t.text),N=s(()=>{t.delivery?.origin!==void 0&&X(t.text,t.delivery.origin)},"announceDelivery"),b=s(async()=>{if(d.call==="prompt"&&!r().isStreaming)try{await V()?.(r())}catch{}N(),await r().prompt(t.text,{...J,preflightResult:c})},"prompt");if(m===null)return d.call==="prompt"?a(l.track(k.fresh(()=>g(r(),t.text,b).catch(o)))):(c(),a(r().followUp(t.text,t.images).catch(o)));const w=Y(t.type,d.call,r().isStreaming);return d.call==="prompt"?a(w==="nextTurn"?l.track(Z(r(),m,()=>k.fresh(()=>g(r(),t.text,b))).catch(o)):l.track(k.fresh(()=>g(r(),t.text,b).catch(o).then(()=>v(m,w))))):(c(),a(r().followUp(t.text,t.images).catch(o).then(()=>v(m,w))))},"drive"),F=s(()=>P.admit(c=>p?C().then(()=>i(c),d=>(o(d),n.failure())):i(c)),"dispatch"),G=r().isStreaming?void 0:I.inFlight();if(G===void 0)return F();const j=f.installedGeneration(),q=r();return G.then(()=>f.installedGeneration()!==j||r()!==q?(o(new Error("session changed while prompt waited for authentication reload")),n.failure()):F())},"drivePromptOrFollowUp"),U=s((e,t,n)=>(async()=>(r().isBashRunning?r().abortBash():(await l.waitUntilAbortable(),r().isStreaming&&await r().abort()),x(e,{type:"prompt",text:t.text,...t.images!==void 0?{images:t.images}:{}},_(e))))().catch(o=>(n.relay(o),n.failure())),"driveInterruptPrompt"),D=s((e,t)=>{const n=t.relay,o=s(a=>{if(et(e.text,r())==="prompt")return g(r(),e.text,()=>r().prompt(e.text,{images:e.images,streamingBehavior:"steer",preflightResult:a}));a();const i=S.guidanceFor(e.text);return i===null?r().steer(e.text,e.images):r().steer(e.text,e.images).then(()=>v(i,"steer"))},"drive");P.admit(a=>p?C().then(()=>o(a),i=>{n(i)}):o(a)).catch(n)},"driveSteer"),W=s((e,t,n)=>{if(r().isBashRunning){r().abortBash(),t.id!==void 0&&B(e,"abort",!0,"bash",t.id);return}if(t.id===void 0){r().abort().catch(n.relay);return}(async()=>{try{await l.waitUntilAbortable();const o=r().isStreaming?"turn":"idle";await r().abort(),B(e,"abort",!0,o,t.id)}catch(o){M(e,t.id)(o)}})()},"driveAbort"),$=s((e,t,n)=>{const o=t.command;if(o.trim()==="")return;if(r().isBashRunning){u.sendFrame(e,{type:"error",code:"bash_busy",message:"A bash command is already running"});return}const a=t.excludeFromContext===!0;E.flush(),T.finishOpenToolGroup(),u.broadcast({type:"bash_start",command:o,excludeFromContext:a}),r().executeBash(o,i=>u.broadcast({type:"bash_output",chunk:i}),{excludeFromContext:a}).then(i=>{u.broadcast({type:"bash_end",exitCode:i.exitCode,cancelled:i.cancelled,truncated:i.truncated,fullOutputPath:i.fullOutputPath})}).catch(n.relay)},"driveBash");return(e,t)=>{if((t.type==="prompt"||t.type==="follow_up")&&t.delivery?.origin?.type==="runtime"&&t.delivery.origin.kind==="park"){O(t.text);return}const n=_(e);switch(t.type){case"prompt":return t.interrupt===!0?U(e,t,n):x(e,t,n);case"follow_up":return x(e,t,n);case"steer":D(t,n);return;case"abort":W(e,t,n);return;case"bash":$(e,t,n);return}}}s(pt,"createEngineDriver");export{pt as createEngineDriver};
1
+ var $=Object.defineProperty;var s=(g,h)=>$(g,"name",{value:h,configurable:!0});import{emitEvent as C}from"../../events/emit.js";import{operationIdContext as w}from"../../events/operation-id.js";import{parkSummaryGraceMs as j}from"../../../shared/env.js";import{headlessTurn as q}from"../headless-pi.js";import{completeBrokerPark as J,recordBrokerParkActivity as N}from"./daemon-ops.js";import{promptWithAdvertisedCommandInvocation as y}from"../advertised-command-invocation.js";import{heldDeferredInboxPromptJoin as z}from"./held-deferred-inbox.js";import{announceMessageOrigin as H}from"../stamp/channel.js";import{chooseGuidanceDeliveryMode as K,promptWithNextTurnGuidance as L,resolveEngineRoute as Q,resolveSteerCall as V}from"./engine-routing.js";function ct(g){const{nodeId:h,registry:u,replies:A,session:n,dispatches:l,memoryRefs:k,rebind:F,projection:I,toolGroups:R,turnAdmission:S}=g,{ackTo:P,engineErrorTo:T}=A,B=s(e=>{let t;return{relay:s(r=>{t=r,u.sendFrame(e,{type:"error",code:"engine_error",message:String(r)})},"relay"),failure:s(()=>t,"failure")}},"errorRelay"),v=s((e,t)=>n().sendCustomMessage({customType:"crtr-memory-refs",content:e,display:!1},{deliverAs:t}).catch(r=>{C({level:"warn",event:"broker.memory_refs.guidance_send_failed",error:r})}),"sendGuidance");let p=!1;const _=s(async()=>{if(!p)return;if((await N(h)).activity!=="recorded")throw new Error("parking completion took priority before input admission")},"recordParkActivityBeforeInput"),E=s(e=>{p=!0;const t=n(),r=t.model,o=t.sessionManager;(r===void 0||typeof r.provider!="string"||typeof r.id!="string"?Promise.resolve("failed"):q({systemPrompt:t.systemPrompt,userPrompt:e,modelSpec:`${r.provider}/${r.id}`,timeoutMs:j(),seedMessages:o.buildSessionContext().messages,sessionId:o.getSessionId(),toolPolicy:"builtin"})).catch(()=>"failed").then(i=>J(h,{outcome:i})).then(i=>{i.action==="shutdown"&&F.requestShutdown()}).catch(i=>{C({level:"error",event:"broker.park.complete_failed",error:i})}).finally(()=>{p=!1})},"runParkTurn"),f=s((e,t,r)=>{const o=r.relay,a=s(c=>c.then(()=>r.failure()),"settle"),i=s(c=>{const d=Q(t,n().isStreaming),D=d.call==="prompt"?d.options:void 0,m=k.guidanceFor(t.text),W=s(()=>{t.delivery?.origin!==void 0&&H(t.text,t.delivery.origin)},"announceDelivery"),x=s(async()=>{if(d.call==="prompt"&&!n().isStreaming)try{await z()?.(n())}catch{}W(),await n().prompt(t.text,{...D,preflightResult:c})},"prompt");if(m===null)return d.call==="prompt"?a(l.track(w.fresh(()=>y(n(),t.text,x).catch(o)))):(c(),a(n().followUp(t.text,t.images).catch(o)));const b=K(t.type,d.call,n().isStreaming);return d.call==="prompt"?a(b==="nextTurn"?l.track(L(n(),m,()=>w.fresh(()=>y(n(),t.text,x))).catch(o)):l.track(w.fresh(()=>y(n(),t.text,x).catch(o).then(()=>v(m,b))))):(c(),a(n().followUp(t.text,t.images).catch(o).then(()=>v(m,b))))},"drive");return s(()=>S.admit(c=>p?_().then(()=>i(c),d=>(o(d),r.failure())):i(c)),"dispatch")()},"drivePromptOrFollowUp"),M=s((e,t,r)=>(async()=>(n().isBashRunning?n().abortBash():(await l.waitUntilAbortable(),n().isStreaming&&await n().abort()),f(e,{type:"prompt",text:t.text,...t.images!==void 0?{images:t.images}:{}},B(e))))().catch(o=>(r.relay(o),r.failure())),"driveInterruptPrompt"),G=s((e,t)=>{const r=t.relay,o=s(a=>{if(V(e.text,n())==="prompt")return y(n(),e.text,()=>n().prompt(e.text,{images:e.images,streamingBehavior:"steer",preflightResult:a}));a();const i=k.guidanceFor(e.text);return i===null?n().steer(e.text,e.images):n().steer(e.text,e.images).then(()=>v(i,"steer"))},"drive");S.admit(a=>p?_().then(()=>o(a),i=>{r(i)}):o(a)).catch(r)},"driveSteer"),O=s((e,t,r)=>{if(n().isBashRunning){n().abortBash(),t.id!==void 0&&P(e,"abort",!0,"bash",t.id);return}if(t.id===void 0){n().abort().catch(r.relay);return}(async()=>{try{await l.waitUntilAbortable();const o=n().isStreaming?"turn":"idle";await n().abort(),P(e,"abort",!0,o,t.id)}catch(o){T(e,t.id)(o)}})()},"driveAbort"),U=s((e,t,r)=>{const o=t.command;if(o.trim()==="")return;if(n().isBashRunning){u.sendFrame(e,{type:"error",code:"bash_busy",message:"A bash command is already running"});return}const a=t.excludeFromContext===!0;I.flush(),R.finishOpenToolGroup(),u.broadcast({type:"bash_start",command:o,excludeFromContext:a}),n().executeBash(o,i=>u.broadcast({type:"bash_output",chunk:i}),{excludeFromContext:a}).then(i=>{u.broadcast({type:"bash_end",exitCode:i.exitCode,cancelled:i.cancelled,truncated:i.truncated,fullOutputPath:i.fullOutputPath})}).catch(r.relay)},"driveBash");return(e,t)=>{if((t.type==="prompt"||t.type==="follow_up")&&t.delivery?.origin?.type==="runtime"&&t.delivery.origin.kind==="park"){E(t.text);return}const r=B(e);switch(t.type){case"prompt":return t.interrupt===!0?M(e,t,r):f(e,t,r);case"follow_up":return f(e,t,r);case"steer":G(t,r);return;case"abort":O(e,t,r);return;case"bash":U(e,t,r);return}}}s(ct,"createEngineDriver");export{ct as createEngineDriver};