@north-light/crouter 0.3.352 → 0.3.354

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 (616) hide show
  1. package/dist/api/client.d.ts +35 -25
  2. package/dist/api/client.js +2 -2
  3. package/dist/api/dto/broker-ops.d.ts +2 -36
  4. package/dist/api/dto/canvas.d.ts +8 -13
  5. package/dist/api/dto/config.d.ts +4 -0
  6. package/dist/api/dto/delivery.d.ts +61 -0
  7. package/dist/api/dto/docs.d.ts +133 -0
  8. package/dist/api/dto/docs.js +1 -0
  9. package/dist/api/dto/health.d.ts +26 -79
  10. package/dist/api/dto/node-outcomes.d.ts +1 -3
  11. package/dist/api/dto/nodes.d.ts +5 -26
  12. package/dist/api/dto/objects.d.ts +167 -0
  13. package/dist/api/dto/objects.js +1 -0
  14. package/dist/api/dto/profiles.d.ts +14 -8
  15. package/dist/api/dto/reports.d.ts +9 -7
  16. package/dist/api/dto/reviews.d.ts +9 -3
  17. package/dist/api/dto/worktree.d.ts +1 -1
  18. package/dist/api/index.d.ts +0 -1
  19. package/dist/api/index.js +1 -1
  20. package/dist/api/routes.d.ts +14 -12
  21. package/dist/api/routes.js +1 -1
  22. package/dist/build-root.js +1 -1
  23. package/dist/builtin-memory/00-runtime-base/00-authoring.md +10 -5
  24. package/dist/builtin-memory/04-orchestration-kernel.md +7 -7
  25. package/dist/builtin-memory/05-kinds/advisor/01-orchestrator.md +1 -1
  26. package/dist/builtin-memory/05-kinds/explore/00-base.md +2 -2
  27. package/dist/builtin-memory/05-kinds/explore/01-orchestrator.md +2 -2
  28. package/dist/builtin-memory/crouter-concepts/INDEX.md +2 -2
  29. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  30. package/dist/builtin-memory/crouter-concepts/memory.md +15 -15
  31. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +1 -1
  32. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +5 -5
  33. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  34. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  35. package/dist/builtin-memory/crouter-sdk/INDEX.md +2 -2
  36. package/dist/builtin-memory/crouter-sdk/README.md +5 -6
  37. package/dist/builtin-memory/crouter-sdk/errors.md +0 -13
  38. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -1
  39. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +2 -2
  40. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -2
  41. package/dist/builtin-memory/crouter-sdk/resources.md +0 -1
  42. package/dist/builtin-memory/explore/exploration-doc.md +4 -4
  43. package/dist/builtin-memory/insights/capture.md +6 -6
  44. package/dist/builtin-memory/insights/init.md +14 -14
  45. package/dist/builtin-memory/internal/INDEX.md +4 -4
  46. package/dist/builtin-memory/internal/agent-shaping.md +20 -20
  47. package/dist/builtin-memory/internal/examples/imessage-assistant.md +2 -2
  48. package/dist/builtin-memory/internal/marketplaces.md +2 -2
  49. package/dist/builtin-memory/internal/memory-loading.md +31 -30
  50. package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
  51. package/dist/builtin-memory/internal/plugins.md +16 -14
  52. package/dist/builtin-memory/internal/storage-tiers.md +4 -4
  53. package/dist/builtin-memory/memory-read-orientation.md +1 -1
  54. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +32 -40
  55. package/dist/clients/attach/input/controller.js +1 -1
  56. package/dist/clients/attach/input/ref-autocomplete.js +1 -1
  57. package/dist/clients/attach/input/titled-editor.js +1 -1
  58. package/dist/clients/attach/render/chat-view.js +1 -1
  59. package/dist/clients/attach/render/crtr-output.d.ts +1 -2
  60. package/dist/clients/attach/render/crtr-output.js +17 -17
  61. package/dist/clients/attach/render/group-activity.d.ts +8 -8
  62. package/dist/clients/attach/render/group-activity.js +2 -2
  63. package/dist/clients/attach/render/group-recap.js +1 -1
  64. package/dist/clients/attach/render/tool-calls.d.ts +1 -1
  65. package/dist/clients/attach/session/profile-files.js +1 -1
  66. package/dist/clients/attach/slash/dispatch.js +1 -1
  67. package/dist/clients/attach/viewer.js +806 -1553
  68. package/dist/commands/api-client.d.ts +2 -0
  69. package/dist/commands/api-client.js +3 -3
  70. package/dist/commands/canvas/edges.d.ts +2 -0
  71. package/dist/commands/canvas/edges.js +2 -0
  72. package/dist/commands/canvas/list.d.ts +4 -0
  73. package/dist/commands/canvas/list.js +3 -0
  74. package/dist/commands/canvas/read.d.ts +8 -0
  75. package/dist/commands/canvas/read.js +5 -0
  76. package/dist/commands/canvas/search.d.ts +2 -0
  77. package/dist/commands/canvas/search.js +3 -0
  78. package/dist/commands/canvas/unwatch.d.ts +2 -0
  79. package/dist/commands/canvas/unwatch.js +1 -0
  80. package/dist/commands/canvas/watch.d.ts +3 -0
  81. package/dist/commands/canvas/watch.js +1 -0
  82. package/dist/commands/canvas-analytics.js +1 -1
  83. package/dist/commands/canvas-history/grep.js +4 -4
  84. package/dist/commands/canvas-history/read.js +2 -2
  85. package/dist/commands/canvas-history/search.js +7 -7
  86. package/dist/commands/canvas-history/shared.d.ts +0 -1
  87. package/dist/commands/canvas-history/shared.js +1 -1
  88. package/dist/commands/canvas-history/stats.js +2 -2
  89. package/dist/commands/canvas-history.js +1 -1
  90. package/dist/commands/canvas.js +1 -1
  91. package/dist/commands/doc/delete.d.ts +2 -0
  92. package/dist/commands/doc/delete.js +1 -0
  93. package/dist/commands/doc/edit.d.ts +2 -0
  94. package/dist/commands/doc/edit.js +1 -0
  95. package/dist/commands/doc/history.d.ts +2 -0
  96. package/dist/commands/doc/history.js +2 -0
  97. package/dist/commands/doc/lint.d.ts +2 -0
  98. package/dist/commands/doc/lint.js +2 -0
  99. package/dist/commands/doc/list.d.ts +2 -0
  100. package/dist/commands/doc/list.js +1 -0
  101. package/dist/commands/doc/move.d.ts +2 -0
  102. package/dist/commands/doc/move.js +1 -0
  103. package/dist/commands/doc/read.d.ts +2 -0
  104. package/dist/commands/doc/read.js +1 -0
  105. package/dist/commands/doc/shared.d.ts +25 -0
  106. package/dist/commands/doc/shared.js +2 -0
  107. package/dist/commands/doc/write.d.ts +2 -0
  108. package/dist/commands/doc/write.js +1 -0
  109. package/dist/commands/{memory.d.ts → doc.d.ts} +1 -1
  110. package/dist/commands/doc.js +1 -0
  111. package/dist/commands/human/review.js +1 -1
  112. package/dist/commands/node/bash.js +2 -2
  113. package/dist/commands/node/create.js +1 -1
  114. package/dist/commands/node/inspect.js +10 -10
  115. package/dist/commands/node/lifecycle.js +2 -2
  116. package/dist/commands/node/outcome.js +1 -1
  117. package/dist/commands/node/subscription.js +1 -1
  118. package/dist/commands/node-context.js +2 -2
  119. package/dist/commands/pkg/browse/catalog.js +1 -1
  120. package/dist/commands/pkg/browse/doc-view.js +1 -1
  121. package/dist/commands/pkg/browse/model.d.ts +9 -17
  122. package/dist/commands/pkg/plugin-inspect.js +1 -1
  123. package/dist/commands/pkg/plugin-manage.d.ts +4 -8
  124. package/dist/commands/pkg/plugin-manage.js +15 -17
  125. package/dist/commands/profile/list.js +1 -1
  126. package/dist/commands/profile/new.js +1 -1
  127. package/dist/commands/profile/project.js +1 -1
  128. package/dist/commands/profile/show.js +1 -1
  129. package/dist/commands/push.js +3 -3
  130. package/dist/commands/sys/config.js +1 -1
  131. package/dist/commands/sys/context/admin/actions.d.ts +18 -43
  132. package/dist/commands/sys/context/admin/actions.js +1 -2
  133. package/dist/commands/sys/context/admin/detail-panel.d.ts +17 -25
  134. package/dist/commands/sys/context/admin/detail-panel.js +2 -1
  135. package/dist/commands/sys/context/admin/docs-panel.d.ts +7 -6
  136. package/dist/commands/sys/context/admin/docs-panel.js +1 -1
  137. package/dist/commands/sys/context/admin/list-view.d.ts +12 -12
  138. package/dist/commands/sys/context/admin/list-view.js +1 -1
  139. package/dist/commands/sys/context/admin/model.d.ts +96 -69
  140. package/dist/commands/sys/context/admin/model.js +1 -1
  141. package/dist/commands/sys/context/admin/rail-panel.d.ts +7 -5
  142. package/dist/commands/sys/context/admin/rail-panel.js +1 -1
  143. package/dist/commands/sys/context/admin/read-view.d.ts +10 -14
  144. package/dist/commands/sys/context/admin/read-view.js +1 -2
  145. package/dist/commands/sys/context/admin/shell.d.ts +26 -31
  146. package/dist/commands/sys/context/admin/shell.js +1 -1
  147. package/dist/commands/sys/context/admin.js +2 -2
  148. package/dist/commands/sys/context/doc.js +2 -3
  149. package/dist/commands/sys/context/expose.js +2 -2
  150. package/dist/commands/sys/context/prompt-review.js +4 -4
  151. package/dist/commands/sys/context/resolve.d.ts +92 -65
  152. package/dist/commands/sys/context/resolve.js +7 -9
  153. package/dist/commands/sys/context.js +1 -1
  154. package/dist/commands/sys/doctor.js +1 -1
  155. package/dist/commands/sys/migrate.js +1 -1
  156. package/dist/commands/sys/panels/profiles-panel.d.ts +3 -1
  157. package/dist/commands/sys/panels/profiles-panel.js +1 -1
  158. package/dist/commands/sys/sync-deps.d.ts +6 -11
  159. package/dist/commands/sys/sync-deps.js +7 -8
  160. package/dist/commands/sys/sync-project-guidance.js +5 -4
  161. package/dist/commands/sys/sync-shared.d.ts +41 -4
  162. package/dist/commands/sys/sync-shared.js +1 -1
  163. package/dist/commands/sys/sync-skills.js +2 -2
  164. package/dist/commands/sys/sync.js +1 -1
  165. package/dist/core/bash-job-supervisor.d.ts +2 -3
  166. package/dist/core/bash-job-supervisor.js +3 -3
  167. package/dist/core/bash-jobs.d.ts +0 -5
  168. package/dist/core/bash-jobs.js +7 -7
  169. package/dist/core/bootstrap.js +2 -2
  170. package/dist/core/canvas/canvas.d.ts +6 -50
  171. package/dist/core/canvas/canvas.js +16 -21
  172. package/dist/core/canvas/db.d.ts +4 -1
  173. package/dist/core/canvas/db.js +2 -2
  174. package/dist/core/canvas/history.d.ts +11 -39
  175. package/dist/core/canvas/history.js +9 -20
  176. package/dist/core/canvas/install-id.d.ts +2 -2
  177. package/dist/core/canvas/install-id.js +1 -1
  178. package/dist/core/canvas/memory-reads.d.ts +5 -0
  179. package/dist/core/canvas/memory-reads.js +1 -1
  180. package/dist/core/canvas/migrations.js +215 -41
  181. package/dist/core/canvas/node-agent-paths.js +1 -1
  182. package/dist/core/canvas/node-tokens.js +1 -1
  183. package/dist/core/canvas/paths.d.ts +0 -4
  184. package/dist/core/canvas/paths.js +1 -1
  185. package/dist/core/canvas/remote-canvas-source.d.ts +0 -1
  186. package/dist/core/canvas/remote-canvas-source.js +1 -1
  187. package/dist/core/canvas/render-source.d.ts +9 -6
  188. package/dist/core/canvas/render-source.js +6 -6
  189. package/dist/core/canvas/sessions.js +2 -2
  190. package/dist/core/canvas/source.d.ts +6 -0
  191. package/dist/core/canvas/tree.d.ts +29 -0
  192. package/dist/core/canvas/tree.js +12 -0
  193. package/dist/core/canvas/types.d.ts +0 -20
  194. package/dist/core/command-plugins/bundle.js +1 -1
  195. package/dist/core/config.d.ts +1 -1
  196. package/dist/core/conversation-store/listener.js +4 -2
  197. package/dist/core/feed/feed.d.ts +9 -7
  198. package/dist/core/feed/feed.js +3 -7
  199. package/dist/core/feed/inbox.d.ts +3 -5
  200. package/dist/core/feed/inbox.js +1 -10
  201. package/dist/core/feed/messages.d.ts +33 -6
  202. package/dist/core/feed/messages.js +10 -7
  203. package/dist/core/feed/reports.d.ts +10 -0
  204. package/dist/core/feed/reports.js +2 -0
  205. package/dist/core/grants/remove.js +1 -1
  206. package/dist/core/graph/access.d.ts +24 -0
  207. package/dist/core/graph/access.js +8 -0
  208. package/dist/core/graph/bodies.d.ts +6 -0
  209. package/dist/core/graph/bodies.js +1 -0
  210. package/dist/core/graph/deletion.d.ts +9 -0
  211. package/dist/core/graph/deletion.js +5 -0
  212. package/dist/core/graph/diff.d.ts +4 -0
  213. package/dist/core/graph/diff.js +4 -0
  214. package/dist/core/graph/documents.d.ts +160 -0
  215. package/dist/core/graph/documents.js +7 -0
  216. package/dist/core/graph/edges.d.ts +24 -0
  217. package/dist/core/graph/edges.js +1 -0
  218. package/dist/core/graph/events.d.ts +26 -0
  219. package/dist/core/graph/events.js +6 -0
  220. package/dist/core/graph/exposures.d.ts +53 -0
  221. package/dist/core/graph/exposures.js +4 -0
  222. package/dist/core/graph/jobs.d.ts +31 -0
  223. package/dist/core/graph/jobs.js +2 -0
  224. package/dist/core/graph/names.d.ts +28 -0
  225. package/dist/core/graph/names.js +3 -0
  226. package/dist/core/graph/objects.d.ts +55 -0
  227. package/dist/core/graph/objects.js +9 -0
  228. package/dist/core/graph/package-docs.d.ts +31 -0
  229. package/dist/core/graph/package-docs.js +5 -0
  230. package/dist/core/graph/package-files.d.ts +20 -0
  231. package/dist/core/graph/package-files.js +2 -0
  232. package/dist/core/graph/reader.d.ts +21 -0
  233. package/dist/core/graph/reader.js +3 -0
  234. package/dist/core/graph/repo-sync/exchange.d.ts +34 -0
  235. package/dist/core/graph/repo-sync/exchange.js +2 -0
  236. package/dist/core/graph/repo-sync/identity.d.ts +30 -0
  237. package/dist/core/graph/repo-sync/identity.js +1 -0
  238. package/dist/core/graph/repo-sync/index.d.ts +4 -0
  239. package/dist/core/graph/repo-sync/index.js +1 -0
  240. package/dist/core/graph/repo-sync/mirror.d.ts +30 -0
  241. package/dist/core/graph/repo-sync/mirror.js +6 -0
  242. package/dist/core/graph/repo-sync/ref-format.d.ts +76 -0
  243. package/dist/core/graph/repo-sync/ref-format.js +2 -0
  244. package/dist/core/graph/repo-sync/repos.d.ts +17 -0
  245. package/dist/core/graph/repo-sync/repos.js +3 -0
  246. package/dist/core/graph/repo-sync/sync.d.ts +42 -0
  247. package/dist/core/graph/repo-sync/sync.js +2 -0
  248. package/dist/core/graph/rules.d.ts +26 -0
  249. package/dist/core/graph/rules.js +3 -0
  250. package/dist/core/graph/spaces/app.d.ts +3 -0
  251. package/dist/core/graph/spaces/app.js +1 -0
  252. package/dist/core/graph/spaces/index.d.ts +19 -0
  253. package/dist/core/graph/spaces/index.js +1 -0
  254. package/dist/core/graph/spaces/person.d.ts +5 -0
  255. package/dist/core/graph/spaces/person.js +2 -0
  256. package/dist/core/graph/spaces/repo.d.ts +4 -0
  257. package/dist/core/graph/spaces/repo.js +1 -0
  258. package/dist/core/graph/types.d.ts +75 -0
  259. package/dist/core/graph/types.js +1 -0
  260. package/dist/core/graph/watches.d.ts +62 -0
  261. package/dist/core/graph/watches.js +18 -0
  262. package/dist/core/human/feedback-companion.js +1 -1
  263. package/dist/core/human/requests.d.ts +3 -1
  264. package/dist/core/human/requests.js +6 -6
  265. package/dist/core/inspector/model.js +2 -2
  266. package/dist/core/io.js +5 -5
  267. package/dist/core/layout-migrate/index.d.ts +24 -1
  268. package/dist/core/layout-migrate/index.js +4 -4
  269. package/dist/core/layout-migrate/paths.d.ts +4 -0
  270. package/dist/core/layout-migrate/paths.js +1 -1
  271. package/dist/core/layout-migrate/stored-paths.d.ts +7 -0
  272. package/dist/core/layout-migrate/stored-paths.js +11 -11
  273. package/dist/core/layout-migrate/stores.d.ts +19 -6
  274. package/dist/core/layout-migrate/stores.js +3 -4
  275. package/dist/core/manifest.d.ts +0 -2
  276. package/dist/core/manifest.js +1 -1
  277. package/dist/core/{memory/extensions.d.ts → plugin-extensions.d.ts} +9 -10
  278. package/dist/core/plugin-extensions.js +1 -0
  279. package/dist/core/preview-registry.d.ts +1 -1
  280. package/dist/core/preview-registry.js +3 -2
  281. package/dist/core/profiles/manifest.d.ts +7 -7
  282. package/dist/core/profiles/manifest.js +1 -1
  283. package/dist/core/profiles/select.js +3 -3
  284. package/dist/core/review/birth.js +1 -1
  285. package/dist/core/review/companion.js +1 -1
  286. package/dist/core/review/stage.d.ts +12 -1
  287. package/dist/core/review/stage.js +1 -1
  288. package/dist/core/review/store.d.ts +2 -0
  289. package/dist/core/review/store.js +1 -1
  290. package/dist/core/review/types.d.ts +7 -1
  291. package/dist/core/runs/events.js +1 -1
  292. package/dist/core/runs/operations.js +5 -5
  293. package/dist/core/runs/questions.js +2 -2
  294. package/dist/core/runtime/bearings-render.d.ts +13 -7
  295. package/dist/core/runtime/bearings-render.js +12 -12
  296. package/dist/core/runtime/bearings.d.ts +8 -18
  297. package/dist/core/runtime/bearings.js +7 -7
  298. package/dist/core/runtime/broker/daemon-ops.d.ts +7 -12
  299. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  300. package/dist/core/runtime/broker/fault-retry.d.ts +2 -0
  301. package/dist/core/runtime/broker/fault-retry.js +1 -1
  302. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  303. package/dist/core/runtime/broker/frame-memory-refs.d.ts +7 -2
  304. package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
  305. package/dist/core/runtime/broker/inbox.d.ts +1 -4
  306. package/dist/core/runtime/broker/inbox.js +1 -10
  307. package/dist/core/runtime/broker/rebind.js +1 -1
  308. package/dist/core/runtime/broker/retry-card-elision.d.ts +7 -0
  309. package/dist/core/runtime/broker/retry-card-elision.js +1 -0
  310. package/dist/core/runtime/broker-extension-render.d.ts +0 -13
  311. package/dist/core/runtime/broker-extension-render.js +2 -4
  312. package/dist/core/runtime/broker-persona-guidance.js +3 -3
  313. package/dist/core/runtime/broker-protocol.d.ts +1 -1
  314. package/dist/core/runtime/broker.js +1 -1
  315. package/dist/core/runtime/close.d.ts +9 -4
  316. package/dist/core/runtime/close.js +1 -1
  317. package/dist/core/runtime/deliver-live.js +1 -1
  318. package/dist/core/runtime/kickoff.js +17 -19
  319. package/dist/core/runtime/launch-target.d.ts +7 -0
  320. package/dist/core/runtime/launch-target.js +1 -1
  321. package/dist/core/runtime/ledger.d.ts +10 -0
  322. package/dist/core/runtime/ledger.js +3 -0
  323. package/dist/core/runtime/lifecycle.js +2 -2
  324. package/dist/core/runtime/nodes.d.ts +10 -2
  325. package/dist/core/runtime/nodes.js +1 -1
  326. package/dist/core/runtime/outcome-document.d.ts +2 -2
  327. package/dist/core/runtime/outcome-document.js +1 -1
  328. package/dist/core/runtime/persona.js +2 -2
  329. package/dist/core/runtime/placement.js +1 -1
  330. package/dist/core/runtime/promote.d.ts +2 -2
  331. package/dist/core/runtime/promote.js +1 -1
  332. package/dist/core/runtime/prospective-inventory-cli.js +2 -2
  333. package/dist/core/runtime/recycle.js +1 -1
  334. package/dist/core/runtime/reopen.js +1 -1
  335. package/dist/core/runtime/revive.js +2 -2
  336. package/dist/core/runtime/roadmap.d.ts +17 -9
  337. package/dist/core/runtime/roadmap.js +4 -4
  338. package/dist/core/runtime/spawn-env.js +1 -1
  339. package/dist/core/runtime/spawn.d.ts +5 -3
  340. package/dist/core/runtime/spawn.js +2 -2
  341. package/dist/core/runtime/structured-output.d.ts +3 -1
  342. package/dist/core/runtime/structured-output.js +4 -4
  343. package/dist/core/scope.d.ts +1 -32
  344. package/dist/core/scope.js +1 -1
  345. package/dist/core/scoped-state/db.js +2 -1
  346. package/dist/core/scoped-state/migrate.js +2 -2
  347. package/dist/core/scoped-state/profiles.d.ts +11 -0
  348. package/dist/core/scoped-state/profiles.js +1 -1
  349. package/dist/core/scoped-state/schema.d.ts +1 -1
  350. package/dist/core/scoped-state/schema.js +7 -5
  351. package/dist/core/spaces/permissions.d.ts +0 -14
  352. package/dist/core/spaces/permissions.js +1 -1
  353. package/dist/core/spaces/stop.d.ts +13 -0
  354. package/dist/core/spaces/stop.js +2 -2
  355. package/dist/core/storage/tables.d.ts +1 -1
  356. package/dist/core/substrate/delivery/corpus.d.ts +21 -0
  357. package/dist/core/substrate/delivery/corpus.js +3 -0
  358. package/dist/core/substrate/delivery/deliver.d.ts +76 -0
  359. package/dist/core/substrate/delivery/deliver.js +6 -0
  360. package/dist/core/substrate/delivery/listings.d.ts +27 -0
  361. package/dist/core/substrate/delivery/listings.js +4 -0
  362. package/dist/core/substrate/delivery/match.d.ts +28 -0
  363. package/dist/core/substrate/delivery/match.js +1 -0
  364. package/dist/core/substrate/delivery/plan.d.ts +67 -0
  365. package/dist/core/substrate/delivery/plan.js +3 -0
  366. package/dist/core/substrate/delivery/render-boot.d.ts +20 -0
  367. package/dist/core/substrate/delivery/render-boot.js +54 -0
  368. package/dist/core/substrate/delivery/render-event.d.ts +47 -0
  369. package/dist/core/substrate/delivery/render-event.js +6 -0
  370. package/dist/core/substrate/delivery/sub-persona-menu.d.ts +2 -0
  371. package/dist/core/substrate/delivery/sub-persona-menu.js +6 -0
  372. package/dist/core/substrate/delivery/types.d.ts +30 -0
  373. package/dist/core/substrate/delivery/types.js +0 -0
  374. package/dist/core/substrate/gate-explain.d.ts +0 -13
  375. package/dist/core/substrate/gate-explain.js +1 -1
  376. package/dist/core/substrate/schema.d.ts +11 -139
  377. package/dist/core/substrate/schema.js +1 -1
  378. package/dist/core/substrate/subject-fields.d.ts +3 -0
  379. package/dist/core/substrate/subject.d.ts +2 -1
  380. package/dist/core/substrate/subject.js +1 -1
  381. package/dist/daemon/api/app-listener.js +11 -11
  382. package/dist/daemon/api/handlers/app-profiles.js +1 -1
  383. package/dist/daemon/api/handlers/bash-jobs.js +1 -2
  384. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  385. package/dist/daemon/api/handlers/canvas.js +5 -5
  386. package/dist/daemon/api/handlers/daemon.js +1 -1
  387. package/dist/daemon/api/handlers/delivery.d.ts +2 -0
  388. package/dist/daemon/api/handlers/delivery.js +1 -0
  389. package/dist/daemon/api/handlers/{memory.d.ts → docs.d.ts} +1 -1
  390. package/dist/daemon/api/handlers/docs.js +1 -0
  391. package/dist/daemon/api/handlers/hook-exec.js +1 -1
  392. package/dist/daemon/api/handlers/messages.js +2 -2
  393. package/dist/daemon/api/handlers/modelauth.d.ts +3 -0
  394. package/dist/daemon/api/handlers/modelauth.js +1 -1
  395. package/dist/daemon/api/handlers/node-records.js +2 -2
  396. package/dist/daemon/api/handlers/nodes.js +1 -1
  397. package/dist/daemon/api/handlers/objects.d.ts +2 -0
  398. package/dist/daemon/api/handlers/objects.js +5 -0
  399. package/dist/daemon/api/handlers/package-docs.d.ts +2 -0
  400. package/dist/daemon/api/handlers/package-docs.js +1 -0
  401. package/dist/daemon/api/handlers/profiles.js +1 -1
  402. package/dist/daemon/api/handlers/reports.d.ts +2 -2
  403. package/dist/daemon/api/handlers/reports.js +4 -4
  404. package/dist/daemon/api/handlers/reviews.js +1 -1
  405. package/dist/daemon/api/handlers/vendor-status.d.ts +8 -0
  406. package/dist/daemon/api/handlers/vendor-status.js +1 -0
  407. package/dist/daemon/api/map.d.ts +2 -2
  408. package/dist/daemon/api/map.js +2 -2
  409. package/dist/daemon/api/operations.d.ts +1 -1
  410. package/dist/daemon/api/operations.js +1 -1
  411. package/dist/daemon/api/principal.d.ts +5 -0
  412. package/dist/daemon/api/principal.js +1 -1
  413. package/dist/daemon/api/reader.d.ts +17 -0
  414. package/dist/daemon/api/reader.js +1 -0
  415. package/dist/daemon/api/server.js +1 -1
  416. package/dist/daemon/control.d.ts +2 -3
  417. package/dist/daemon/crtrd.js +8 -6
  418. package/dist/daemon/fleet.js +4 -4
  419. package/dist/daemon/reconcilers/bash-deadline.d.ts +11 -1
  420. package/dist/daemon/reconcilers/bash-deadline.js +2 -1
  421. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  422. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  423. package/dist/daemon/reconcilers/node-deadline.js +1 -1
  424. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  425. package/dist/daemon/reconcilers/storage-maintenance.d.ts +1 -0
  426. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  427. package/dist/daemon/review/deliver.js +2 -2
  428. package/dist/daemon/review/finish.js +1 -1
  429. package/dist/hook-authoring.d.ts +0 -1
  430. package/dist/hook-authoring.js +3 -3
  431. package/dist/migrations/004-canvas-documents/apply.d.ts +10 -0
  432. package/dist/migrations/004-canvas-documents/apply.js +1 -0
  433. package/dist/migrations/004-canvas-documents/fields.d.ts +24 -0
  434. package/dist/migrations/004-canvas-documents/fields.js +2 -0
  435. package/dist/migrations/004-canvas-documents/index.d.ts +16 -0
  436. package/dist/migrations/004-canvas-documents/index.js +2 -0
  437. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +16 -0
  438. package/dist/migrations/004-canvas-documents/legacy/discover.js +1 -0
  439. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +5 -0
  440. package/dist/migrations/004-canvas-documents/legacy/history.js +2 -0
  441. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +7 -0
  442. package/dist/migrations/004-canvas-documents/legacy/nested.js +1 -0
  443. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +14 -0
  444. package/dist/migrations/004-canvas-documents/legacy/parse.js +1 -0
  445. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +91 -0
  446. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  447. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +6 -0
  448. package/dist/migrations/004-canvas-documents/legacy-edges.js +18 -0
  449. package/dist/migrations/004-canvas-documents/plan.d.ts +102 -0
  450. package/dist/migrations/004-canvas-documents/plan.js +3 -0
  451. package/dist/migrations/004-canvas-documents/pointers.d.ts +23 -0
  452. package/dist/migrations/004-canvas-documents/pointers.js +4 -0
  453. package/dist/migrations/activation.d.ts +9 -18
  454. package/dist/migrations/activation.js +2 -2
  455. package/dist/pi-extensions/broker-local.d.ts +2 -2
  456. package/dist/pi-extensions/broker-local.js +2 -2
  457. package/dist/pi-extensions/canvas-bash-valve.js +5 -4
  458. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  459. package/dist/pi-extensions/canvas-doc-substrate.d.ts +0 -1
  460. package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
  461. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  462. package/dist/pi-extensions/canvas-passive-context.js +1 -1
  463. package/dist/pi-extensions/canvas-recap.js +2 -2
  464. package/dist/pi-extensions/canvas-stophook.d.ts +1 -1
  465. package/dist/pi-extensions/canvas-stophook.js +1 -1
  466. package/dist/prompts/review.js +3 -3
  467. package/dist/shared/env.d.ts +5 -0
  468. package/dist/shared/env.js +1 -1
  469. package/dist/shared/generated-context.js +2 -10
  470. package/dist/shared/inbox-entry-body.d.ts +22 -0
  471. package/dist/shared/inbox-entry-body.js +10 -0
  472. package/dist/{core/memory → shared}/inline-ref-guidance.d.ts +2 -2
  473. package/dist/shared/inline-ref-guidance.js +2 -0
  474. package/dist/types.d.ts +3 -1
  475. package/docs/cli/memory-and-preferences.md +12 -14
  476. package/docs/concepts/README.md +1 -1
  477. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  478. package/docs/concepts/memory.md +15 -15
  479. package/docs/concepts/nodes-and-the-canvas.md +1 -1
  480. package/docs/concepts/profiles-kinds-and-modes.md +5 -5
  481. package/docs/concepts/scopes-and-trust.md +1 -1
  482. package/docs/concepts/why-a-daemon.md +1 -1
  483. package/docs/sdk/README.md +5 -6
  484. package/docs/sdk/errors.md +0 -13
  485. package/docs/sdk/guides/README.md +0 -1
  486. package/docs/sdk/nodes.md +0 -2
  487. package/docs/sdk/resources.md +0 -1
  488. package/package.json +2 -2
  489. package/packages/crouter-identity/package.json +1 -1
  490. package/runtime.lock.json +11 -11
  491. package/dist/api/dto/memory.d.ts +0 -171
  492. package/dist/api/dto/memory.js +0 -1
  493. package/dist/builtin-memory/crouter-sdk/guides/app-memory.md +0 -73
  494. package/dist/builtin-memory/crouter-sdk/memory.md +0 -87
  495. package/dist/commands/broker-permissions.d.ts +0 -2
  496. package/dist/commands/broker-permissions.js +0 -1
  497. package/dist/commands/memory/client.d.ts +0 -11
  498. package/dist/commands/memory/client.js +0 -1
  499. package/dist/commands/memory/delete.d.ts +0 -1
  500. package/dist/commands/memory/delete.js +0 -1
  501. package/dist/commands/memory/edit.d.ts +0 -1
  502. package/dist/commands/memory/edit.js +0 -21
  503. package/dist/commands/memory/find.d.ts +0 -1
  504. package/dist/commands/memory/find.js +0 -1
  505. package/dist/commands/memory/history.d.ts +0 -1
  506. package/dist/commands/memory/history.js +0 -5
  507. package/dist/commands/memory/lint.d.ts +0 -1
  508. package/dist/commands/memory/lint.js +0 -1
  509. package/dist/commands/memory/list.d.ts +0 -1
  510. package/dist/commands/memory/list.js +0 -1
  511. package/dist/commands/memory/move.d.ts +0 -1
  512. package/dist/commands/memory/move.js +0 -1
  513. package/dist/commands/memory/origin.d.ts +0 -1
  514. package/dist/commands/memory/origin.js +0 -1
  515. package/dist/commands/memory/read.d.ts +0 -1
  516. package/dist/commands/memory/read.js +0 -6
  517. package/dist/commands/memory/shared.d.ts +0 -22
  518. package/dist/commands/memory/shared.js +0 -1
  519. package/dist/commands/memory/write.d.ts +0 -1
  520. package/dist/commands/memory/write.js +0 -13
  521. package/dist/commands/memory.js +0 -1
  522. package/dist/commands/node-inspect-artifacts.d.ts +0 -1
  523. package/dist/commands/node-inspect-artifacts.js +0 -8
  524. package/dist/core/help/memory-extensions.d.ts +0 -3
  525. package/dist/core/help/memory-extensions.js +0 -2
  526. package/dist/core/memory/cli-selector.d.ts +0 -13
  527. package/dist/core/memory/cli-selector.js +0 -1
  528. package/dist/core/memory/doc-link-grammar.d.ts +0 -20
  529. package/dist/core/memory/doc-link-grammar.js +0 -2
  530. package/dist/core/memory/extensions.js +0 -1
  531. package/dist/core/memory/history.d.ts +0 -87
  532. package/dist/core/memory/history.js +0 -6
  533. package/dist/core/memory/identity.d.ts +0 -65
  534. package/dist/core/memory/identity.js +0 -1
  535. package/dist/core/memory/inline-ref-guidance.js +0 -2
  536. package/dist/core/memory/inline-ref-inventory.d.ts +0 -9
  537. package/dist/core/memory/inline-ref-inventory.js +0 -1
  538. package/dist/core/memory/lint.d.ts +0 -163
  539. package/dist/core/memory/lint.js +0 -2
  540. package/dist/core/memory/mutation-domain.d.ts +0 -113
  541. package/dist/core/memory/mutation-domain.js +0 -12
  542. package/dist/core/memory/mutations.d.ts +0 -74
  543. package/dist/core/memory/mutations.js +0 -1
  544. package/dist/core/memory/project-namespace.d.ts +0 -31
  545. package/dist/core/memory/project-namespace.js +0 -2
  546. package/dist/core/memory/repository-association.d.ts +0 -31
  547. package/dist/core/memory/repository-association.js +0 -1
  548. package/dist/core/memory/service.d.ts +0 -145
  549. package/dist/core/memory/service.js +0 -2
  550. package/dist/core/memory/tree.d.ts +0 -39
  551. package/dist/core/memory/tree.js +0 -1
  552. package/dist/core/memory-resolver.d.ts +0 -280
  553. package/dist/core/memory-resolver.js +0 -2
  554. package/dist/core/nested-stores.d.ts +0 -18
  555. package/dist/core/nested-stores.js +0 -1
  556. package/dist/core/runtime/memory.d.ts +0 -3
  557. package/dist/core/runtime/memory.js +0 -1
  558. package/dist/core/substrate/frontmatter-validation.d.ts +0 -11
  559. package/dist/core/substrate/frontmatter-validation.js +0 -1
  560. package/dist/core/substrate/gate.d.ts +0 -16
  561. package/dist/core/substrate/gate.js +0 -1
  562. package/dist/core/substrate/index.d.ts +0 -18
  563. package/dist/core/substrate/index.js +0 -1
  564. package/dist/core/substrate/injected-store.d.ts +0 -75
  565. package/dist/core/substrate/injected-store.js +0 -2
  566. package/dist/core/substrate/listings.d.ts +0 -28
  567. package/dist/core/substrate/listings.js +0 -1
  568. package/dist/core/substrate/memory-events.d.ts +0 -6
  569. package/dist/core/substrate/memory-events.js +0 -1
  570. package/dist/core/substrate/on-read-node.d.ts +0 -6
  571. package/dist/core/substrate/on-read-node.js +0 -1
  572. package/dist/core/substrate/on-read.d.ts +0 -101
  573. package/dist/core/substrate/on-read.js +0 -9
  574. package/dist/core/substrate/plan.d.ts +0 -94
  575. package/dist/core/substrate/plan.js +0 -1
  576. package/dist/core/substrate/render-node.d.ts +0 -12
  577. package/dist/core/substrate/render-node.js +0 -1
  578. package/dist/core/substrate/render.d.ts +0 -41
  579. package/dist/core/substrate/render.js +0 -65
  580. package/dist/core/substrate/session-cache.d.ts +0 -27
  581. package/dist/core/substrate/session-cache.js +0 -1
  582. package/dist/core/substrate/surface-match.d.ts +0 -73
  583. package/dist/core/substrate/surface-match.js +0 -1
  584. package/dist/daemon/api/handlers/memory.js +0 -5
  585. package/dist/migrations/001-surfaces-frontmatter.d.ts +0 -2
  586. package/dist/migrations/001-surfaces-frontmatter.js +0 -1
  587. package/dist/migrations/002-profile-project-memory.d.ts +0 -2
  588. package/dist/migrations/002-profile-project-memory.js +0 -1
  589. package/dist/migrations/003-repository-root-memory-identity/front-door.d.ts +0 -26
  590. package/dist/migrations/003-repository-root-memory-identity/front-door.js +0 -11
  591. package/dist/migrations/003-repository-root-memory-identity/index.d.ts +0 -2
  592. package/dist/migrations/003-repository-root-memory-identity/index.js +0 -5
  593. package/dist/migrations/003-repository-root-memory-identity/references.d.ts +0 -95
  594. package/dist/migrations/003-repository-root-memory-identity/references.js +0 -5
  595. package/dist/migrations/003-repository-root-memory-identity/repository-facts.d.ts +0 -39
  596. package/dist/migrations/003-repository-root-memory-identity/repository-facts.js +0 -3
  597. package/dist/migrations/convergent.d.ts +0 -43
  598. package/dist/migrations/convergent.js +0 -2
  599. package/dist/migrations/corpus.d.ts +0 -75
  600. package/dist/migrations/corpus.js +0 -3
  601. package/dist/migrations/frontmatter-splice.d.ts +0 -15
  602. package/dist/migrations/frontmatter-splice.js +0 -8
  603. package/dist/migrations/profile-manifests.d.ts +0 -30
  604. package/dist/migrations/profile-manifests.js +0 -2
  605. package/dist/migrations/registry.d.ts +0 -7
  606. package/dist/migrations/registry.js +0 -1
  607. package/dist/migrations/runner.d.ts +0 -43
  608. package/dist/migrations/runner.js +0 -1
  609. package/dist/migrations/types.d.ts +0 -211
  610. package/dist/shared/birth-announcement.d.ts +0 -12
  611. package/dist/shared/birth-announcement.js +0 -1
  612. package/docs/sdk/guides/app-memory.md +0 -22
  613. package/docs/sdk/memory.md +0 -85
  614. /package/dist/{migrations/types.js → api/dto/delivery.js} +0 -0
  615. /package/dist/{core/memory → shared}/inline-ref-grammar.d.ts +0 -0
  616. /package/dist/{core/memory → shared}/inline-ref-grammar.js +0 -0
@@ -1,5 +1,5 @@
1
1
  import { type Cron } from '../canvas/index.js';
2
- import type { ExposureTarget } from '../substrate/injected-store.js';
2
+ import type { DeliveredDoc, RenderContext } from '../substrate/delivery/render-event.js';
3
3
  import { buildProjectContextBlock, contextDirNote, orchestratorContextNote } from './bearings-render.js';
4
4
  /** The bearings custom type is shared with every attached renderer. */
5
5
  export { CONTEXT_INTRO_CUSTOM_TYPE } from '../../shared/generated-context.js';
@@ -47,20 +47,10 @@ export declare function cronWakeOrigin(c: Cron, kind: WakeOrigin['kind']): WakeO
47
47
  * carry the signal, and a raw ISO instant is noise an agent cannot cheaply turn
48
48
  * into an elapsed delta. */
49
49
  export declare function buildWakeBearings(origin: WakeOrigin): string;
50
- /** The full boot intro, four top-level sections:
51
- *
52
- * 1. `<crtr-bearings>` — the orienting facts about THIS node: the identity
53
- * assertion (always first, so it overrides any copied-in persona), then a
54
- * `## Your place in the canvas` graph map and a `## Your context directory`
55
- * note. The across-cycles context-dir framing is added ONLY for an
56
- * orchestrator (by mode) — the one node whose dir a future cycle resumes
57
- * from.
58
- * 2. `<memory kind="knowledge">` — the consultable boot catalog, a SIBLING of
59
- * the bearings (never nested under the context dir). Dropped when empty.
60
- * 3. `<auto-loaded-context>` — memories whose `on: workspace-open` entry fires
61
- * because cwd/profile mounted their owning project store. Dropped when empty.
62
- * 4. `<project_context>` — the cwd/git environment snapshot. pi's own
63
- * AGENTS.md/CLAUDE.md injection stays suppressed (`noContextFiles` in
64
- * broker.ts); `crtr sys sync project-guidance` imports that guidance into
65
- * the directory's `.crouter/memory/INDEX.md` front door. */
66
- export declare function buildContextBearings(nodeId: string, target?: ExposureTarget): string;
50
+ /** The bearings on the row-backed delivery engine: the knowledge catalog and
51
+ * the workspace-open documents render against `ctx`'s ledger; `delivered`
52
+ * lists what they delivered, for the caller to record. */
53
+ export declare function buildContextBearings(nodeId: string, ctx: RenderContext): {
54
+ content: string;
55
+ delivered: DeliveredDoc[];
56
+ };
@@ -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 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
- ${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
- </crtr-wake>`;const o=T(e);return`<crtr-wake>
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,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
- `),w,h,m,k].filter(b=>b!=="").join(`
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};
1
+ var k=Object.defineProperty;var a=(e,n)=>k(e,"name",{value:n,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as y,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as p,orchestratorContextNote as h,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{CONTEXT_INTRO_CUSTOM_TYPE as J}from"../../shared/generated-context.js";function Y(e){const n=s(e);return n===null?"":$(n.cwd,n.profile_id)}a(Y,"profileNote");function E(e){const n=[],r=new Set([e]);let o=s(e)?.parent??null;for(;o!==null&&o!==""&&!r.has(o);){r.add(o);const t=s(o);if(t===null)break;n.unshift(t),o=t.parent??null}return n}a(E,"ancestorTrunk");const X=5;function j(e){return g(e).map(n=>s(n.node_id)).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>l(n.status)-l(r.status))}a(j,"childNodes");function A(e){const n=s(e);if(n===null)return"";const r=E(e),o=j(e);return C(e,n.kind,n.mode,r,o)}a(A,"buildGraphMap");function B(e){const n=s(e),r=n?.fork_from,o=r!=null&&r!==""&&y(r)?s(r):null,t=o!==null?`${r} ("${d(o)}")`:r??"";return S(e,n?.kind??"general",n?.mode??"base",r,t)}a(B,"buildIdentityAssertion");function R(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(R,"armerPhrase");function F(e,n){const r=e.created_by!=null?s(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:d(r)}:{},armedAt:e.created,recur:e.recur}}a(F,"cronWakeOrigin");function I(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
+ ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} 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
+ </crtr-wake>`;const o=R(e);return`<crtr-wake>
4
+ ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. 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>`}a(I,"buildWakeBearings");function T(e){return O(e?.managed_worktree)}a(T,"managedWorktreeNote");function D(e,n,r){const o=s(e),t=["<crtr-bearings>",B(e)],u=A(e);u!==""&&t.push("","## Your place in the canvas",u),t.push("","## Your documents and context directory",p(e,o?.grantee));const i=Y(e);i!==""&&t.push("",i);const c=T(o);c!==""&&t.push("","## Your managed worktree",c),o?.mode==="orchestrator"&&t.push("",h()),t.push("</crtr-bearings>");const w=_(e)??"",m=o?.cwd!==void 0?f(o.cwd):"";return[t.join(`
6
+ `),n,r,w,m].filter(b=>b!=="").join(`
7
+ `)}a(D,"bearingsShell");function K(e,n){const r=v(n),o=x(n);return{content:D(e,r.content,o.content),delivered:[...r.delivered,...o.delivered]}}a(K,"buildContextBearings");export{J as CONTEXT_INTRO_CUSTOM_TYPE,K as buildContextBearings,A as buildGraphMap,f as buildProjectContextBlock,I as buildWakeBearings,p as contextDirNote,F as cronWakeOrigin,h as orchestratorContextNote,Y as profileNote};
@@ -1,9 +1,9 @@
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';
1
+ import type { BrokerExtensionStateDTO, 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';
6
+ import type { BackgroundedJobDTO, BackgroundedJobRequest, DeliveryRequest, DeliveryResponse } from '../../../api/dto/delivery.js';
7
7
  import type { NodeLogAppendResultDTO, NodeMessageBodyDTO, NodePushedFinalResultDTO, NodeTelemetryRecordRequest } from '../../../api/dto/node-records.js';
8
8
  export declare function appendBrokerLog(nodeId: string, record: string): Promise<NodeLogAppendResultDTO>;
9
9
  export declare function putBrokerTelemetry(nodeId: string, telemetry: Omit<NodeTelemetryRecordRequest, 'expected_execution_id'>): Promise<void>;
@@ -19,6 +19,8 @@ export declare function startBrokerBashJob(nodeId: string, request: {
19
19
  }): Promise<{
20
20
  pid: number;
21
21
  }>;
22
+ /** Record a command the valve just backgrounded as this node's job object. */
23
+ export declare function recordBackgroundedJob(nodeId: string, jobId: string, request: BackgroundedJobRequest): Promise<BackgroundedJobDTO>;
22
24
  export declare function stopBrokerBashJob(nodeId: string, jobId: string): Promise<void>;
23
25
  export declare function brokerExecutionId(): string;
24
26
  export declare function bindBrokerSession(nodeId: string, request: Omit<BrokerSessionBoundRequest, 'executionId'>): Promise<BrokerSessionBoundResultDTO>;
@@ -44,12 +46,9 @@ export declare function clearNodeFault(nodeId: string, opts?: {
44
46
  * exposes no generic node/database facade. */
45
47
  export declare function commitBrokerModel(nodeId: string, request: BrokerInput<BrokerModelCommitRequest>): Promise<BrokerModelCommitResultDTO>;
46
48
  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>;
49
+ /** The node's one delivery route: every rule-driven document delivery the
50
+ * broker applies, recorded by crtrd in the same request. */
51
+ export declare function brokerDelivery(nodeId: string, request: BrokerInput<DeliveryRequest>): Promise<DeliveryResponse>;
53
52
  export declare function commitBrokerGeneratedName(nodeId: string, request: BrokerInput<BrokerGeneratedNameRequest>): Promise<BrokerGeneratedNameResultDTO>;
54
53
  export declare function commitBrokerPersonaAck(nodeId: string, request: BrokerInput<BrokerPersonaAckRequest>): Promise<BrokerPersonaAckResultDTO>;
55
54
  /** Reports still use the canonical daemon report handler; this broker adapter
@@ -59,8 +58,4 @@ export declare function publishBrokerReport(nodeId: string, request: PushReportR
59
58
  * a replacement broker and tears down this broker. Callers must not await it
60
59
  * from Pi's session-start dispatch. */
61
60
  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;
66
61
  export {};
@@ -1 +1 @@
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};
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 x}from"../../../api/errors.js";import{envExecutionId as l}from"../../../shared/env.js";import{reportRefNodeId as m}from"../../../shared/inbox-entry-body.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 P(e,r){return o().putNodeTelemetry(e,{...r,expected_execution_id:n()})}t(P,"putBrokerTelemetry");function N(e,r){return o().putNodeRecap(e,{briefing:r,expected_execution_id:n()})}t(N,"putBrokerRecap");function v(e,r){return o().readNodePassiveMessage(e,r)}t(v,"readBrokerPassiveMessage");function E(e){return o().nodePushedFinal(e,{action:"clear",expected_execution_id:n()})}t(E,"clearBrokerPushedFinal");function g(e){return o().nodePushedFinal(e,{action:"consume",expected_execution_id:n()})}t(g,"consumeBrokerPushedFinal");function w(e,r){return o().request("POST",`/v1/nodes/${encodeURIComponent(e)}/jobs/start`,{...r,expected_execution_id:n()})}t(w,"startBrokerBashJob");function F(e,r,i){return o().recordBackgroundedJob(e,r,i)}t(F,"recordBackgroundedJob");function I(e,r){return o().request("DELETE",`/v1/nodes/${encodeURIComponent(e)}/jobs/${encodeURIComponent(r)}?foreground=1`,{expected_execution_id:n()})}t(I,"stopBrokerBashJob");function n(){const e=l();if(e===void 0||e==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return e}t(n,"brokerExecutionId");function T(e,r){return o().bindBrokerSession(e,{...r,executionId:n()})}t(T,"bindBrokerSession");function M(e,r){return o().settleBroker(e,{...r,expected_execution_id:n()})}t(M,"settleBroker");function C(e,r){return o().completeBrokerPark(e,{...r,expected_execution_id:n()})}t(C,"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 D(e,r){const i=o(),p=n(),d=await i.claimNodeMail(e,{execution_id:p,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||m(a)===void 0)return c;try{const{content:u}=await i.readNodeInboxReport(e,a,p);return{...c,entry:{...c.entry,data:{...c.entry.data,report_body:u}}}}catch(u){if(u instanceof x&&u.status===404)return c;throw u}}));return{...d,deliveries:s}}t(D,"claimBrokerMail");function J(e,r){return o().acknowledgeNodeMail(e,{execution_id:n(),deliveries:r})}t(J,"acknowledgeBrokerMail");function U(e,r){return o().recordBrokerTurn(e,{...r,expected_execution_id:n()})}t(U,"recordBrokerTurn");function L(e,r){return o().mutateBrokerProviderRetry(e,{...r,expected_execution_id:n()})}t(L,"mutateBrokerProviderRetry");function $(e,r){return o().mutateBrokerFault(e,{...r,expected_execution_id:n()})}t($,"mutateBrokerFault");function j(e){return o().getBrokerRecovery(e,n())}t(j,"brokerRecovery");function G(e,r){return o().recordNodeFault(e,r)}t(G,"recordNodeFault");function O(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(O,"clearNodeFault");function q(e,r){return o().commitBrokerModel(e,{...r,expected_execution_id:n()})}t(q,"commitBrokerModel");function z(e){return o().brokerExtensionState(e)}t(z,"brokerExtensionState");function X(e,r){return o().nodeDelivery(e,{...r,expected_execution_id:n()})}t(X,"brokerDelivery");function H(e,r){return o().commitBrokerGeneratedName(e,{...r,expected_execution_id:n()})}t(H,"commitBrokerGeneratedName");function K(e,r){return o().commitBrokerPersonaAck(e,{...r,expected_execution_id:n()})}t(K,"commitBrokerPersonaAck");async function Q(e,r){try{await o().pushReport(e,r)}catch(i){if(r.tier==="final"&&i instanceof x&&i.code==="already_finalized")return;throw i}}t(Q,"publishBrokerReport");function V(e){return o().relaunchRoot(e)}t(V,"relaunchBrokerRoot");export{J as acknowledgeBrokerMail,R as appendBrokerLog,T as bindBrokerSession,X as brokerDelivery,n as brokerExecutionId,z as brokerExtensionState,j as brokerRecovery,D as claimBrokerMail,E as clearBrokerPushedFinal,O as clearNodeFault,H as commitBrokerGeneratedName,q as commitBrokerModel,K as commitBrokerPersonaAck,C as completeBrokerPark,g as consumeBrokerPushedFinal,$ as mutateBrokerFault,L as mutateBrokerProviderRetry,Q as publishBrokerReport,N as putBrokerRecap,P as putBrokerTelemetry,v as readBrokerPassiveMessage,F as recordBackgroundedJob,A as recordBrokerParkActivity,S as recordBrokerTelemetry,U as recordBrokerTurn,G as recordNodeFault,V as relaunchBrokerRoot,M as settleBroker,w as startBrokerBashJob,I as stopBrokerBashJob};
@@ -19,6 +19,8 @@ type FaultRetryDeps = {
19
19
  formatModelSpec: (model: BrokerSession['model'], thinkingLevel?: string) => string | null;
20
20
  broadcastModelChanged: (persist?: boolean) => Promise<void>;
21
21
  turnAdmission: TurnAdmissionGate;
22
+ /** Re-snapshot every attached viewer; an in-place rewind emits no relayed event. */
23
+ reWelcomeAll: () => void;
22
24
  };
23
25
  /** The kind and retry disposition of a turn that settled on a provider error.
24
26
  * A final daemon refusal (the model adapter's refusal diagnostic) is fatal
@@ -1 +1 @@
1
- var z=Object.defineProperty;var v=(s,e)=>z(s,"name",{value:e,configurable:!0});import{envModelIntent as P,envNodeCwd as G,envProfileId as O}from"../../../shared/env.js";import{isContextOverflow as H}from"@earendil-works/pi-ai";import{classify as L}from"../../fault-classifier.js";import{isModelNotFoundError as J,isProviderUnconfiguredError as K}from"../fault.js";import{brokerRecovery as Q,mutateBrokerFault as $,mutateBrokerProviderRetry as b}from"./daemon-ops.js";import{extractCoolingDeadline as Z}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as ee}from"../../provider-failure.js";import{expandModelCandidates as D,modelRequestFromConfig as T,probeRouteAvailability as te}from"../../model-routes.js";import{operationIdContext as N}from"../../events/operation-id.js";import{emitEvent as F}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as ie,PROVIDER_FAULT_RECOVERY_BODY as ne,formatCard as U,formatModelFallbackRecovery as re}from"../../../shared/generated-context.js";import{markFatalOnExhaust as B,nextFaultRetry as q,policyFor as Y}from"../fault-recovery.js";import{parseModelSpec as V}from"../model-selection.js";import{endedByAbort as se}from"../session-cycles.js";import{resolveProviderCandidates as oe}from"../../subscription-state.js";import{announceMessageOrigin as W}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as ae}from"./model-adapter.js";const de=2147483647;function I(s){return{link:s.link,op:s.op,kind:s.kind,retry:s.retry,message:s.message,since:s.since,operation_id:s.operation_id,...s.anchor_entry_id===void 0?{}:{anchorEntryId:s.anchor_entry_id},...s.provider_error===void 0?{}:{providerError:s.provider_error}}}v(I,"policyFault");function M(s){return{link:s.link,op:s.op,kind:s.kind,retry:s.retry,message:s.message,...s.operation_id===void 0?{}:{operation_id:s.operation_id},...s.since===void 0?{}:{since:s.since},...s.anchorEntryId===void 0?{}:{anchor_entry_id:s.anchorEntryId},...s.providerError===void 0?{}:{provider_error:s.providerError}}}v(M,"faultInput");function j(s,e){const t=v(i=>`${i.providerId}/${i.modelId}`===e.modelSpec,"onLiveModel");return(s.find(i=>t(i)&&i.thinkingLevel===e.thinkingLevel)??s.find(t))?.rank}v(j,"liveRouteRank");function le(s){const e=L("pi\u2192provider",s),t=s.diagnostics?.some(i=>i.type===ae)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}v(le,"settledProviderFault");class Ae{static{v(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;personaGateFailed=!1;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null,this.personaGateFailed=!1}notePersonaGateFailure(){this.personaGateFailed=!0}state(){return Q(this.deps.nodeId)}async recordFault(e){return(await $(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await $(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await b(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t=e.stagedProviderAgentEnd,i=e.stagedWatchdogAbort,n=e.stagedRefreshAbort,o=e.stagedOverflowFailure,l=this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null,a=this.personaGateFailed;this.stagedCapacityFailure=null,this.personaGateFailed=!1,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const r=e.session,p=await this.state(),h=p.fault,f=p.episode,u=this.sessionId(r),g=this.isActiveAutoFault(h)&&h.link==="pi\u2192provider"?h:f?.state==="admitted"&&f.session_id===u&&this.isActiveAutoFault(f.fault)?f.fault:null,d=g===null?null:{since:g.since,anchorEntryId:g.anchor_entry_id,attempt:g.retry.attempt},c=[...Array.isArray(t?.messages)?t.messages:[]].reverse().find(E=>typeof E=="object"&&E!==null&&E.role==="assistant");if(a){await this.clearEpisode(r);return}if(l!==null||o!==null){await this.clearFault("pi\u2192provider"),await this.clearEpisode(r),await this.recordFault({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:l?.errorMessage??o.errorMessage,anchor_entry_id:r.sessionManager.getLeafId?.()??void 0});return}if(i&&c?.stopReason==="aborted"){await this.recordPendingProviderFault(r,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...d?.attempt!==void 0?{attempt:d.attempt}:{}},message:typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)",...d!==null?{since:d.since}:{},anchor_entry_id:d?.anchorEntryId??r.sessionManager.getLeafId?.()??void 0});return}if(c?.stopReason!=="error"){c!==void 0&&await this.clearEpisode(r);return}if(n){await this.clearEpisode(r);return}const k=typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)";if(se({stopReason:"error",errorMessage:k})){await this.clearEpisode(r);return}const y=H(c,r.model?.contextWindow),{classified:X,disposition:w}=le(c),R=Z(c),A=ee(c),S=typeof c.provider=="string"&&c.provider!==""?c.provider:r.model?.provider,x=typeof c.model=="string"&&c.model!==""?c.model:r.model?.id,C=A===void 0||S===void 0||x===void 0?void 0:{provider:S,model:x,...A};y&&(await this.clearFault("pi\u2192provider"),await this.clearEpisode(r));const _={link:"pi\u2192provider",op:"generation turn",kind:y?"context-overflow":X.kind,retry:y?{disposition:"fatal"}:w==="auto"?{disposition:"auto",by:"daemon",...R!==void 0?{nextAt:new Date(R).toISOString()}:{},...d?.attempt!==void 0?{attempt:d.attempt}:{}}:{disposition:w},message:k,...!y&&w==="auto"&&d!==null?{since:d.since}:{},anchor_entry_id:!y&&w==="auto"&&d?.anchorEntryId!==void 0?d.anchorEntryId:r.sessionManager.getLeafId?.()??void 0,...C===void 0?{}:{provider_error:C}};_.retry.disposition==="auto"?await this.recordPendingProviderFault(r,_):(await this.clearEpisode(r),await this.recordFault(_))}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(await this.state()).episode,i=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&i!==null&&t.session_id===i&&await b(this.deps.nodeId,{op:"invalidate",session_id:i}),"none";if(t===null||i===null||t.session_id!==i)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await b(this.deps.nodeId,{op:"reopen",session_id:i})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";return await this.recordFault(M(I(t.fault))),await this.schedule(),"retry-armed"}hasProgressPastAnchor(e,t){const i=e.sessionManager.getBranch(),n=i.findIndex(l=>l.id===t);return(n===-1?i:i.slice(n+1)).some(l=>{if(l.type!=="message")return!1;const{message:a}=l;return a.role==="toolResult"?!0:a.role==="assistant"&&Array.isArray(a.content)&&a.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(e===void 0||t.isStreaming||this.timer!==null)return;const i=await this.state(),n=i.fault;if(!this.isActiveAutoFault(n)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,n,i)){this.clearTimer();return}const o=this.faultRetryDelayMs(n,Date.now());o!==null&&this.clearAndArmFaultRetry(o,e)}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=L("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const i=this.deps.installedGeneration();if(i===void 0)return;const n=this.deps.currentSession(),o=this.deps.currentServices(),l=this.deps.formatModelSpec(n.model,n.thinkingLevel);if(l===null)return;const a=T(this.deps.cfg.model,P(),!1);if(a===void 0)return;const r=D(a,G()??this.deps.cfg.cwd,O()),p=V(l),h=j(r,p),f=h===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(r.slice(h+1),this.deps.registryOf(o),n.getContextUsage()?.tokens,d=>!this.failedRetryRoutes.has(d.routeId));if(f.route===void 0){f.capacityExhausted&&(this.stageCapacityFailure(i,n),queueMicrotask(()=>{this.deps.installedGeneration()===i&&this.deps.currentSession()===n&&n.abortRetry()}));return}const u=f.route,g=(async()=>{const d=this.deps.registryOf(o).find(u.providerId,u.modelId);if(!d||(await n.setModel(d),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n))return;const m=`${u.providerId}/${u.modelId}`===p.modelSpec?p.thinkingLevel:u.thinkingLevel;n.setThinkingLevel(m??"off"),this.failedRetryRoutes.add(u.routeId),await this.deps.broadcastModelChanged(!1)})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===i&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=g}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=K(e.message.errorMessage??"");if(!t&&!J(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const i=this.deps.installedGeneration();if(i===void 0)return;const n=this.deps.currentSession(),o=this.deps.currentServices(),l=this.deps.formatModelSpec(n.model,n.thinkingLevel);if(l===null)return;const a=V(l);this.notFoundModels.add(a.modelSpec);const r=T(this.deps.cfg.model,P(),!1),p=r?D(r,G()??this.deps.cfg.cwd,O()):[],h=j(p,a),f=h===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(p.slice(h+1),this.deps.registryOf(o),n.getContextUsage()?.tokens,m=>!this.notFoundModels.has(`${m.providerId}/${m.modelId}`));if(f.route===void 0){f.capacityExhausted&&this.stageCapacityFailure(i,n);return}const u=f.route,g=`${u.providerId}/${u.modelId}${u.thinkingLevel?`:${u.thinkingLevel}`:""}`,d=(async()=>{const m=this.deps.registryOf(o).find(u.providerId,u.modelId);if(m===void 0){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${g} is not registered`}});return}if(await n.setModel(m),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n)return;n.setThinkingLevel(u.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const c=this.deps.formatModelSpec(n.model,n.thinkingLevel)??g;if(F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${l} unavailable \u2192 ${c}; re-driving turn`}}),await n.agent.waitForIdle(),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n)return;t&&await this.clearFault("pi\u2192provider");const k=U("recovery",{},re(l,c,t?"credential":"not-found"));W(k,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(y=>N.fresh(()=>n.prompt(k,{preflightResult:y})))})().catch(m=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${m instanceof Error?m.message:String(m)}`}})}).finally(()=>{this.deps.installedGeneration()===i&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=d}nextEligibleFallbackRoute(e,t,i,n){let o=0,l=0;for(const a of e){if(!n(a)||oe([{...a,...te(a,t),automaticFallback:!0}]).candidates.length===0)continue;const r=t.find(a.providerId,a.modelId);if(r!==void 0){if(o++,this.targetCannotFitContext(r.contextWindow,i)){l++;continue}return{route:a,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:o>0&&o===l}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const i=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(i)?`All available fallback models have context windows smaller than the current conversation (${i} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const i=this.sessionId(e);if(i===null){await this.recordFault(t);return}await b(this.deps.nodeId,{op:"record-pending",session_id:i,input:t})}pendingEpisodeMatches(e,t,i){const n=this.sessionId(e),o=i.episode;return n!==null&&o!==null&&o.state==="pending"&&o.session_id===n&&o.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const i=Date.parse(e.retry.nextAt)-t;return Number.isFinite(i)?Math.max(0,i):null}return q(I(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const i=Math.min(Math.max(0,e),de),n=Math.max(0,e-i);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(n>0){this.clearAndArmFaultRetry(n,t);return}this.runFaultRetry().catch(o=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${o instanceof Error?o.message:String(o)}`}})})}},i),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const i=(await this.state()).fault;if(!this.isActiveAutoFault(i))return;let n=i;if(i.kind==="connection"){const r=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const p=(await this.state()).fault;if(!this.isActiveAutoFault(p)||p.since!==i.since)return;if(!r){this.clearAndArmFaultRetry(Y(p.kind).baseDelayMs,e);return}n=p}const o=n.retry.attempt??0,l=Y(n.kind);if(o>=l.max){await this.recordFault(M(B(I(n)))),await this.clearEpisode(t);return}const a=q(I(n),Date.now());if(a===null){await this.recordFault(M(B(I(n)))),await this.clearEpisode(t);return}if(n.anchor_entry_id!==void 0)try{if((t.sessionManager.getLeafId?.()??null)!==n.anchor_entry_id&&(await t.navigateTree(n.anchor_entry_id),this.deps.installedGeneration()!==e||this.deps.currentSession()!==t))return}catch(r){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${r instanceof Error?r.message:String(r)}`}})}this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||await this.deps.turnAdmission.admit(async r=>{const p=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(p)||p.since!==n.since){r();return}const h=this.sessionId(t);if(h===null){r();return}if(!(await b(this.deps.nodeId,{op:"admit",session_id:h,fault_id:p.fault_id,retry:a.fault.retry})).applied){r();return}const u=U("recovery",{attempt:a.attempt,max:a.max},n.kind==="connection"?ie:ne);return W(u,{type:"runtime",kind:"recovery"}),N.fresh(()=>t.prompt(u,{preflightResult:r}))})}}export{Ae as FaultRetry,le as settledProviderFault};
1
+ var z=Object.defineProperty;var v=(s,e)=>z(s,"name",{value:e,configurable:!0});import{envModelIntent as P,envNodeCwd as G,envProfileId as O}from"../../../shared/env.js";import{isContextOverflow as H}from"@earendil-works/pi-ai";import{classify as L}from"../../fault-classifier.js";import{isModelNotFoundError as J,isProviderUnconfiguredError as K}from"../fault.js";import{brokerRecovery as Q,mutateBrokerFault as $,mutateBrokerProviderRetry as b}from"./daemon-ops.js";import{extractCoolingDeadline as Z}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as ee}from"../../provider-failure.js";import{expandModelCandidates as D,modelRequestFromConfig as T,probeRouteAvailability as te}from"../../model-routes.js";import{operationIdContext as N}from"../../events/operation-id.js";import{emitEvent as F}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as ie,PROVIDER_FAULT_RECOVERY_BODY as ne,formatCard as U,formatModelFallbackRecovery as re}from"../../../shared/generated-context.js";import{markFatalOnExhaust as B,nextFaultRetry as q,policyFor as W}from"../fault-recovery.js";import{parseModelSpec as Y}from"../model-selection.js";import{endedByAbort as se}from"../session-cycles.js";import{resolveProviderCandidates as oe}from"../../subscription-state.js";import{announceMessageOrigin as V}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as ae}from"./model-adapter.js";const de=2147483647;function I(s){return{link:s.link,op:s.op,kind:s.kind,retry:s.retry,message:s.message,since:s.since,operation_id:s.operation_id,...s.anchor_entry_id===void 0?{}:{anchorEntryId:s.anchor_entry_id},...s.provider_error===void 0?{}:{providerError:s.provider_error}}}v(I,"policyFault");function M(s){return{link:s.link,op:s.op,kind:s.kind,retry:s.retry,message:s.message,...s.operation_id===void 0?{}:{operation_id:s.operation_id},...s.since===void 0?{}:{since:s.since},...s.anchorEntryId===void 0?{}:{anchor_entry_id:s.anchorEntryId},...s.providerError===void 0?{}:{provider_error:s.providerError}}}v(M,"faultInput");function j(s,e){const t=v(i=>`${i.providerId}/${i.modelId}`===e.modelSpec,"onLiveModel");return(s.find(i=>t(i)&&i.thinkingLevel===e.thinkingLevel)??s.find(t))?.rank}v(j,"liveRouteRank");function le(s){const e=L("pi\u2192provider",s),t=s.diagnostics?.some(i=>i.type===ae)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}v(le,"settledProviderFault");class Re{static{v(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;personaGateFailed=!1;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null,this.personaGateFailed=!1}notePersonaGateFailure(){this.personaGateFailed=!0}state(){return Q(this.deps.nodeId)}async recordFault(e){return(await $(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await $(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await b(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t=e.stagedProviderAgentEnd,i=e.stagedWatchdogAbort,n=e.stagedRefreshAbort,o=e.stagedOverflowFailure,l=this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null,a=this.personaGateFailed;this.stagedCapacityFailure=null,this.personaGateFailed=!1,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const r=e.session,p=await this.state(),h=p.fault,f=p.episode,u=this.sessionId(r),g=this.isActiveAutoFault(h)&&h.link==="pi\u2192provider"?h:f?.state==="admitted"&&f.session_id===u&&this.isActiveAutoFault(f.fault)?f.fault:null,d=g===null?null:{since:g.since,anchorEntryId:g.anchor_entry_id,attempt:g.retry.attempt},c=[...Array.isArray(t?.messages)?t.messages:[]].reverse().find(E=>typeof E=="object"&&E!==null&&E.role==="assistant");if(a){await this.clearEpisode(r);return}if(l!==null||o!==null){await this.clearFault("pi\u2192provider"),await this.clearEpisode(r),await this.recordFault({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:l?.errorMessage??o.errorMessage,anchor_entry_id:r.sessionManager.getLeafId?.()??void 0});return}if(i&&c?.stopReason==="aborted"){await this.recordPendingProviderFault(r,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...d?.attempt!==void 0?{attempt:d.attempt}:{}},message:typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)",...d!==null?{since:d.since}:{},anchor_entry_id:d?.anchorEntryId??r.sessionManager.getLeafId?.()??void 0});return}if(c?.stopReason!=="error"){c!==void 0&&await this.clearEpisode(r);return}if(n){await this.clearEpisode(r);return}const k=typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)";if(se({stopReason:"error",errorMessage:k})){await this.clearEpisode(r);return}const y=H(c,r.model?.contextWindow),{classified:X,disposition:w}=le(c),A=Z(c),R=ee(c),S=typeof c.provider=="string"&&c.provider!==""?c.provider:r.model?.provider,x=typeof c.model=="string"&&c.model!==""?c.model:r.model?.id,C=R===void 0||S===void 0||x===void 0?void 0:{provider:S,model:x,...R};y&&(await this.clearFault("pi\u2192provider"),await this.clearEpisode(r));const _={link:"pi\u2192provider",op:"generation turn",kind:y?"context-overflow":X.kind,retry:y?{disposition:"fatal"}:w==="auto"?{disposition:"auto",by:"daemon",...A!==void 0?{nextAt:new Date(A).toISOString()}:{},...d?.attempt!==void 0?{attempt:d.attempt}:{}}:{disposition:w},message:k,...!y&&w==="auto"&&d!==null?{since:d.since}:{},anchor_entry_id:!y&&w==="auto"&&d?.anchorEntryId!==void 0?d.anchorEntryId:r.sessionManager.getLeafId?.()??void 0,...C===void 0?{}:{provider_error:C}};_.retry.disposition==="auto"?await this.recordPendingProviderFault(r,_):(await this.clearEpisode(r),await this.recordFault(_))}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(await this.state()).episode,i=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&i!==null&&t.session_id===i&&await b(this.deps.nodeId,{op:"invalidate",session_id:i}),"none";if(t===null||i===null||t.session_id!==i)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await b(this.deps.nodeId,{op:"reopen",session_id:i})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";return await this.recordFault(M(I(t.fault))),await this.schedule(),"retry-armed"}hasProgressPastAnchor(e,t){const i=e.sessionManager.getBranch(),n=i.findIndex(l=>l.id===t);return(n===-1?i:i.slice(n+1)).some(l=>{if(l.type!=="message")return!1;const{message:a}=l;return a.role==="toolResult"?!0:a.role==="assistant"&&Array.isArray(a.content)&&a.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(e===void 0||t.isStreaming||this.timer!==null)return;const i=await this.state(),n=i.fault;if(!this.isActiveAutoFault(n)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,n,i)){this.clearTimer();return}const o=this.faultRetryDelayMs(n,Date.now());o!==null&&this.clearAndArmFaultRetry(o,e)}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=L("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const i=this.deps.installedGeneration();if(i===void 0)return;const n=this.deps.currentSession(),o=this.deps.currentServices(),l=this.deps.formatModelSpec(n.model,n.thinkingLevel);if(l===null)return;const a=T(this.deps.cfg.model,P(),!1);if(a===void 0)return;const r=D(a,G()??this.deps.cfg.cwd,O()),p=Y(l),h=j(r,p),f=h===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(r.slice(h+1),this.deps.registryOf(o),n.getContextUsage()?.tokens,d=>!this.failedRetryRoutes.has(d.routeId));if(f.route===void 0){f.capacityExhausted&&(this.stageCapacityFailure(i,n),queueMicrotask(()=>{this.deps.installedGeneration()===i&&this.deps.currentSession()===n&&n.abortRetry()}));return}const u=f.route,g=(async()=>{const d=this.deps.registryOf(o).find(u.providerId,u.modelId);if(!d||(await n.setModel(d),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n))return;const m=`${u.providerId}/${u.modelId}`===p.modelSpec?p.thinkingLevel:u.thinkingLevel;n.setThinkingLevel(m??"off"),this.failedRetryRoutes.add(u.routeId),await this.deps.broadcastModelChanged(!1)})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===i&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=g}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=K(e.message.errorMessage??"");if(!t&&!J(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const i=this.deps.installedGeneration();if(i===void 0)return;const n=this.deps.currentSession(),o=this.deps.currentServices(),l=this.deps.formatModelSpec(n.model,n.thinkingLevel);if(l===null)return;const a=Y(l);this.notFoundModels.add(a.modelSpec);const r=T(this.deps.cfg.model,P(),!1),p=r?D(r,G()??this.deps.cfg.cwd,O()):[],h=j(p,a),f=h===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(p.slice(h+1),this.deps.registryOf(o),n.getContextUsage()?.tokens,m=>!this.notFoundModels.has(`${m.providerId}/${m.modelId}`));if(f.route===void 0){f.capacityExhausted&&this.stageCapacityFailure(i,n);return}const u=f.route,g=`${u.providerId}/${u.modelId}${u.thinkingLevel?`:${u.thinkingLevel}`:""}`,d=(async()=>{const m=this.deps.registryOf(o).find(u.providerId,u.modelId);if(m===void 0){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${g} is not registered`}});return}if(await n.setModel(m),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n)return;n.setThinkingLevel(u.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const c=this.deps.formatModelSpec(n.model,n.thinkingLevel)??g;if(F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${l} unavailable \u2192 ${c}; re-driving turn`}}),await n.agent.waitForIdle(),this.deps.installedGeneration()!==i||this.deps.currentSession()!==n)return;t&&await this.clearFault("pi\u2192provider");const k=U("recovery",{},re(l,c,t?"credential":"not-found"));V(k,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(y=>N.fresh(()=>n.prompt(k,{preflightResult:y})))})().catch(m=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${m instanceof Error?m.message:String(m)}`}})}).finally(()=>{this.deps.installedGeneration()===i&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=d}nextEligibleFallbackRoute(e,t,i,n){let o=0,l=0;for(const a of e){if(!n(a)||oe([{...a,...te(a,t),automaticFallback:!0}]).candidates.length===0)continue;const r=t.find(a.providerId,a.modelId);if(r!==void 0){if(o++,this.targetCannotFitContext(r.contextWindow,i)){l++;continue}return{route:a,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:o>0&&o===l}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const i=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(i)?`All available fallback models have context windows smaller than the current conversation (${i} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const i=this.sessionId(e);if(i===null){await this.recordFault(t);return}await b(this.deps.nodeId,{op:"record-pending",session_id:i,input:t})}pendingEpisodeMatches(e,t,i){const n=this.sessionId(e),o=i.episode;return n!==null&&o!==null&&o.state==="pending"&&o.session_id===n&&o.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const i=Date.parse(e.retry.nextAt)-t;return Number.isFinite(i)?Math.max(0,i):null}return q(I(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const i=Math.min(Math.max(0,e),de),n=Math.max(0,e-i);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(n>0){this.clearAndArmFaultRetry(n,t);return}this.runFaultRetry().catch(o=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${o instanceof Error?o.message:String(o)}`}})})}},i),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const i=(await this.state()).fault;if(!this.isActiveAutoFault(i))return;let n=i;if(i.kind==="connection"){const r=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const p=(await this.state()).fault;if(!this.isActiveAutoFault(p)||p.since!==i.since)return;if(!r){this.clearAndArmFaultRetry(W(p.kind).baseDelayMs,e);return}n=p}const o=n.retry.attempt??0,l=W(n.kind);if(o>=l.max){await this.recordFault(M(B(I(n)))),await this.clearEpisode(t);return}const a=q(I(n),Date.now());if(a===null){await this.recordFault(M(B(I(n)))),await this.clearEpisode(t);return}if(n.anchor_entry_id!==void 0)try{if((t.sessionManager.getLeafId?.()??null)!==n.anchor_entry_id){const r=await t.navigateTree(n.anchor_entry_id);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t)return;r.cancelled||this.deps.reWelcomeAll()}}catch(r){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${r instanceof Error?r.message:String(r)}`}})}this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||await this.deps.turnAdmission.admit(async r=>{const p=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(p)||p.since!==n.since){r();return}const h=this.sessionId(t);if(h===null){r();return}if(!(await b(this.deps.nodeId,{op:"admit",session_id:h,fault_id:p.fault_id,retry:a.fault.retry})).applied){r();return}const u=U("recovery",{attempt:a.attempt,max:a.max},n.kind==="connection"?ie:ne);return V(u,{type:"runtime",kind:"recovery"}),N.fresh(()=>t.prompt(u,{preflightResult:r}))})}}export{Re as FaultRetry,le as settledProviderFault};
@@ -29,7 +29,7 @@ export type FrameDispatchDeps = {
29
29
  formatModelSpec: (model: BrokerSession['model'], thinkingLevel?: string) => string | null;
30
30
  formatExactModelSpec: (model: BrokerSession['model'], thinkingLevel?: string) => string | null;
31
31
  turnAdmission: TurnAdmissionGate;
32
- memoryInventory: import('../../../api/dto/broker-ops.js').BrokerMemoryRefsDTO;
32
+ memoryInventory: import('./frame-memory-refs.js').ComposerNames;
33
33
  };
34
34
  export type FrameDispatchContext = ReturnType<typeof createFrameDispatchContext>;
35
35
  /** Owns frame-local input state while dispatching through explicit broker collaborators. */
@@ -1,4 +1,3 @@
1
- import type { BrokerMemoryRefsDTO } from '../../../api/dto/broker-ops.js';
2
1
  import type { RefMeta } from '../broker-protocol.js';
3
2
  import type { BrokerSession } from './read-ops.js';
4
3
  /**
@@ -9,6 +8,12 @@ import type { BrokerSession } from './read-ops.js';
9
8
  * corpus is KNOWN to have changed (a successful `session.reload()`); a failed
10
9
  * reload leaves the memo intact.
11
10
  */
11
+ export interface ComposerNames {
12
+ refs: RefMeta[];
13
+ names: string[];
14
+ }
15
+ /** The display names in the node's view, from the delivery route. */
16
+ export declare function composerNames(nodeId: string): Promise<ComposerNames>;
12
17
  export type MemoryRefGuidance = {
13
18
  /** The memoized inventory rows the `list_memory_refs` read-op replies with. */
14
19
  refs(): RefMeta[];
@@ -17,4 +22,4 @@ export type MemoryRefGuidance = {
17
22
  /** Refresh the inventory after a successful session reload. */
18
23
  invalidate(): Promise<void>;
19
24
  };
20
- export declare function createMemoryRefGuidance(session: () => BrokerSession, nodeId: string, initial: BrokerMemoryRefsDTO): MemoryRefGuidance;
25
+ export declare function createMemoryRefGuidance(session: () => BrokerSession, nodeId: string, initial: ComposerNames): MemoryRefGuidance;
@@ -1 +1 @@
1
- var i=Object.defineProperty;var t=(r,n)=>i(r,"name",{value:n,configurable:!0});import{emitEvent as s}from"../../events/emit.js";import{brokerMemoryRefs as f}from"./daemon-ops.js";import{buildGuidance as u}from"../../memory/inline-ref-guidance.js";import{isLeadingEngineCommand as c}from"./engine-routing.js";function g(r,n,m){let o={refs:m.refs,names:new Set(m.names)};return{refs:t(()=>o.refs,"refs"),guidanceFor(e){try{return c(e,r())?null:u(e,o.names)}catch(a){return s({level:"warn",event:"broker.memory_refs.guidance_resolve_failed",error:a}),null}},async invalidate(){const e=await f(n);o={refs:e.refs,names:new Set(e.names)}}}}t(g,"createMemoryRefGuidance");export{g as createMemoryRefGuidance};
1
+ var i=Object.defineProperty;var t=(r,e)=>i(r,"name",{value:e,configurable:!0});import{emitEvent as m}from"../../events/emit.js";import{brokerDelivery as f}from"./daemon-ops.js";import{buildGuidance as u}from"../../../shared/inline-ref-guidance.js";import{isLeadingEngineCommand as c}from"./engine-routing.js";async function d(r){const e=await f(r,{activity:"names"});if(e.refs===void 0||e.names===void 0)throw new Error(`delivery route returned no names for ${r}`);return{refs:e.refs,names:e.names}}t(d,"composerNames");function g(r,e,o){let a={refs:o.refs,names:new Set(o.names)};return{refs:t(()=>a.refs,"refs"),guidanceFor(n){try{return c(n,r())?null:u(n,a.names)}catch(s){return m({level:"warn",event:"broker.memory_refs.guidance_resolve_failed",error:s}),null}},async invalidate(){const n=await d(e);a={refs:n.refs,names:new Set(n.names)}}}}t(g,"createMemoryRefGuidance");export{d as composerNames,g as createMemoryRefGuidance};
@@ -1,10 +1,7 @@
1
1
  import type { MailEntryDTO } from '../../../api/dto/mail.js';
2
+ export { reportRefNodeId } from '../../../shared/inbox-entry-body.js';
2
3
  export type BrokerInboxEntryId = string;
3
4
  export type BrokerInboxEntry = MailEntryDTO;
4
- /** The node id a canonical report ref points at, or undefined when the ref is
5
- * absent, absolute, or not a report path. Callers use it to tell whether the
6
- * report-node projection they hold can still resolve the ref. */
7
- export declare function reportRefNodeId(ref: string | undefined): string | undefined;
8
5
  /** One-shot runtime cards an entry carries (rendered envelopes written by the
9
6
  * message API). They ride the delivery their own entry belongs to, so a note
10
7
  * can never land ahead of an unrelated person's message — except in the one
@@ -1,10 +1 @@
1
- var h=Object.defineProperty;var s=(n,t)=>h(n,"name",{value:t,configurable:!0});import{formatInboxCard as m,formatInboxRefInstruction as f}from"../../../shared/generated-context.js";import{renderBirthAnnouncementBody as b}from"../../../shared/birth-announcement.js";const u=12,a=1e3,x=1e3;function g(n){const t=typeof n.data?.body=="string"?String(n.data.body).trim():"";return t===""||t===n.label?"":t}s(g,"inlineBody");function y(n){let t=n,r=!1;const d=t.split(`
2
- `);return d.length>u&&(t=d.slice(0,u).join(`
3
- `),r=!0),t.length>a&&(t=t.slice(0,a),r=!0),{text:t.trimEnd(),clipped:r}}s(y,"clipBody");function k(n){if(n===void 0||n.startsWith("/"))return;const t=n.indexOf(":");if(t<=0)return;const r=n.slice(t+1);if(!(!r.startsWith("reports/")||r.includes("..")||r.startsWith("/")))return n.slice(0,t)}s(k,"reportRefNodeId");function A(n){if(k(n.ref)===void 0)return null;const t=n.data?.report_body;return typeof t=="string"&&t.length<x?t:null}s(A,"inlineReport");function B(n){const t=b(n.data,n.ts);if(t!==null)return t;const r=A(n);if(r!==null)return`${r.trimEnd()}
4
-
5
- ${f(n.ref)}`;const d=g(n);if(d==="")return n.ref===void 0?n.label:`${n.label}
6
-
7
- ${f(n.ref)}`;const{text:e,clipped:i}=y(d);return n.ref!==void 0?`${e}
8
-
9
- ${f(n.ref)}`:i?`${e}
10
- \u2026 (body clipped)`:e}s(B,"entryBody");function I(n){return{kind:n.kind,body:B(n),...n.ref===void 0?{}:{ref:n.ref},...n.disposition===void 0?{}:{disposition:n.disposition}}}s(I,"cardEntry");function l(n){const t=n.data?.cards;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}s(l,"entryCards");function E(n){const t=[];let r=[];const d=s(()=>{if(r.length===0)return;const e=new Map;for(const o of r){const c=o.from??"system";e.has(c)||e.set(c,[]),e.get(c).push(o)}const i=[...e].map(([o,c])=>({id:o,entries:c.map(p=>I(p))}));t.push({kind:"card",text:m(i),cards:r.flatMap(o=>l(o)),entries:r}),r=[]},"flushRun");for(const e of n){if((e.from??"system")!=="human"){r.push(e);continue}d();const i=e.data?.body;t.push({kind:"human",text:typeof i=="string"?i:e.label,cards:l(e),entries:[e]})}d();for(let e=t.length-2;e>=0;e-=1){const i=t[e],o=t[e+1];i.kind!=="card"||o.kind!=="human"||i.entries.every(c=>c.tier==="deferred")&&(t[e]={...o,cards:[...i.cards,i.text,...o.cards],entries:[...i.entries,...o.entries]},t.splice(e+1,1))}return t}s(E,"coalesceBrokerInbox");export{E as coalesceBrokerInbox,l as entryCards,k as reportRefNodeId};
1
+ var u=Object.defineProperty;var d=(e,t)=>u(e,"name",{value:t,configurable:!0});import{formatInboxCard as p}from"../../../shared/generated-context.js";import{renderEntryBody as m}from"../../../shared/inbox-entry-body.js";import{reportRefNodeId as I}from"../../../shared/inbox-entry-body.js";function y(e){const t=e.data?.report_body;return m(e,typeof t=="string"?t:null)}d(y,"entryBody");function l(e){return{kind:e.kind,body:y(e),...e.ref===void 0?{}:{ref:e.ref},...e.disposition===void 0?{}:{disposition:e.disposition}}}d(l,"cardEntry");function c(e){const t=e.data?.cards;return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}d(c,"entryCards");function b(e){const t=[];let s=[];const a=d(()=>{if(s.length===0)return;const r=new Map;for(const n of s){const i=n.from??"system";r.has(i)||r.set(i,[]),r.get(i).push(n)}const o=[...r].map(([n,i])=>({id:n,entries:i.map(f=>l(f))}));t.push({kind:"card",text:p(o),cards:s.flatMap(n=>c(n)),entries:s}),s=[]},"flushRun");for(const r of e){if((r.from??"system")!=="human"){s.push(r);continue}a();const o=r.data?.body;t.push({kind:"human",text:typeof o=="string"?o:r.label,cards:c(r),entries:[r]})}a();for(let r=t.length-2;r>=0;r-=1){const o=t[r],n=t[r+1];o.kind!=="card"||n.kind!=="human"||o.entries.every(i=>i.tier==="deferred")&&(t[r]={...n,cards:[...o.cards,o.text,...n.cards],entries:[...o.entries,...n.entries]},t.splice(r+1,1))}return t}d(b,"coalesceBrokerInbox");export{b as coalesceBrokerInbox,c as entryCards,I as reportRefNodeId};
@@ -1 +1 @@
1
- var k=Object.defineProperty;var l=(a,e)=>k(a,"name",{value:e,configurable:!0});import{mkdirSync as v,writeFileSync as _}from"node:fs";import{join as A}from"node:path";import{nodeRunJobDir as I}from"../../canvas/paths.js";import{emitEvent as u}from"../../events/emit.js";import{operationIdContext as c}from"../../events/operation-id.js";import{installPersonaTransitionGate as E}from"../broker-persona-guidance.js";import{abortSessionFromExtension as T}from"./extension-abort.js";import{brokerRecovery as w,mutateBrokerFault as S,mutateBrokerProviderRetry as x}from"./daemon-ops.js";const f=2,m=3e4,b=Symbol("replacement-deadline-exceeded"),P="(interrupted)",g=Symbol.for("crtr.trailing-thinking-guard");function V(a){for(let e=a.length-1;e>=0;e--){const t=a[e];if(t!==void 0){if(t.type==="text"){if(t.text.trim().length===0)continue;return t}if(t.type==="thinking"){const n=t.thinkingSignature,r=typeof n=="string"&&n.trim().length>0;if(t.redacted!==!0&&t.thinking.trim().length===0&&!r)continue;return t}return t}}}l(V,"lastSerializedBlock");function y(a){return a.map(e=>e.role!=="assistant"||V(e.content)?.type!=="thinking"?e:{...e,content:[...e.content,{type:"text",text:P}]})}l(y,"guardTrailingThinking");function N(a){const e=a.convertToLlm;if(e[g]===!0)return;const t=l(n=>{const r=e(n);return r instanceof Promise?r.then(y):y(r)},"wrapped");t[g]=!0,a.convertToLlm=t}l(N,"installTrailingThinkingGuard");class O{static{l(this,"RebindDriver")}deps;sessionValue;servicesValue;unsubscribe;installed;nextSubscriptionGeneration=0;rebindTail=Promise.resolve();latestRebindRequest=0;replacementTail=Promise.resolve();admittedReplacements=0;agentRunActiveValue=!1;shutdownRequested=!1;constructor(e){this.deps=e,this.sessionValue=e.session,this.servicesValue=e.services}session(){return this.sessionValue}services(){return this.servicesValue}installedGeneration(){return this.installed}isAgentRunActive(){return this.agentRunActiveValue}isReplacing(){return this.admittedReplacements>0}requestShutdown(){if(!this.agentRunActiveValue){this.deps.disposeAndExit("shutdown-hook");return}this.shutdownRequested=!0}setRebindSession(){this.deps.runtime?.setRebindSession(e=>this.enqueueRebind(e,this.deps.runtime.services))}enqueueRebind(e,t){const n=++this.latestRebindRequest,r=this.rebindTail.then(async()=>{if(n!==this.latestRebindRequest)return;if(this.installed!==void 0){typeof this.sessionValue.sessionFile=="string"&&this.sessionValue.sessionFile!==""&&await x(this.deps.nodeId,{op:"invalidate",session_id:this.sessionValue.sessionManager.getSessionId()});const s=(await w(this.deps.nodeId)).fault;s?.link==="pi\u2192provider"&&s.retry.disposition==="auto"&&s.retry.by==="daemon"&&await S(this.deps.nodeId,{op:"clear",link:"pi\u2192provider",preserve_episode:!0})}if(this.installed?.executingTools.clear(),this.removeInstalledSubscription(),this.deps.setActiveSession(e),this.deps.projection().reset(),this.deps.faultRetry().reset(),this.agentRunActiveValue=!1,this.deps.onSessionRebind(),this.deps.toolGroups.resetForSession(),await e.bindExtensions({uiContext:this.deps.uiContext(),mode:"rpc",abortHandler:l(()=>T(e,()=>{const s=this.installed;s?.session===e&&(s.stagedRefreshAbort=!0)}),"abortHandler"),shutdownHandler:l(()=>this.requestShutdown(),"shutdownHandler")}),n!==this.latestRebindRequest)return;this.removeInstalledSubscription(),this.sessionValue=e,this.servicesValue=t;const d=e.agent;if(d&&(E(this.deps.nodeId,{agent:d,sessionManager:e.sessionManager},()=>this.deps.faultRetry().notePersonaGateFailure()),d.steeringMode="all",d.followUpMode="all",N(d)),this.deps.cfg.editorName!==void 0&&this.deps.cfg.editorName!=="")try{e.setSessionName(this.deps.cfg.editorName)}catch{}const o={id:++this.nextSubscriptionGeneration,session:e,fallback:{blocked:!1},stagedProviderAgentEnd:null,stagedWatchdogAbort:!1,stagedRefreshAbort:!1,stagedOverflowFailure:null,executingTools:new Set};this.unsubscribe=this.sessionValue.subscribe(s=>{if(!this.deps.projection().isCurrent(o))return;if(c.current()!==void 0){this.executeSubscriptionCallback(o,s);return}const i=o.fallback;if(s.type==="turn_start"&&i.storedId!==void 0){i.storedId=void 0,i.blocked=!0,c.fresh(()=>{u({level:"warn",event:"broker.turn.fallback_overlap",fields:{generation:o.id,engine_event:s.type}}),this.executeSubscriptionCallback(o,s)});return}if(s.type==="turn_start"&&!i.blocked){c.fresh(R=>{i.storedId=R,this.executeSubscriptionCallback(o,s)});return}const h=i.storedId;if(h!==void 0&&!i.blocked){c.run(h,()=>{this.executeSubscriptionCallback(o,s),s.type==="agent_settled"&&i.storedId===h&&(i.storedId=void 0)});return}this.executeSubscriptionCallback(o,s)}),this.installed=o,this.deps.projection().rearmIfStreaming(o),this.captureSystemPrompt(e)});return this.rebindTail=r.catch(()=>{}),r}runReplacement(e,t,n){const r=this.deps.runtime;if(r===void 0){this.deps.registry.sendFrame(e,{type:"error",code:"engine_error",message:"session replacement unsupported at this engine pin"});return}if(this.admittedReplacements>=f){c.fresh(()=>u({level:"warn",event:"broker.session_replacement.rejected",outcome:"skipped",fields:{op:t,reason:"capacity",admitted:f,cap:f}})),this.ackTo(e,t,!1,`session replacement busy (${f} active or queued)`);return}this.admittedReplacements++;const d=this.replacementTail.then(async()=>{try{await c.fresh(async()=>{const o=process.hrtime.bigint();let s;try{const p=new Promise(h=>{s=setTimeout(()=>h(b),m)}),i=await Promise.race([n(r),p]);if(i===b){u({level:"error",event:"broker.session_replacement.timed_out",outcome:"failed",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{op:t,deadline_ms:m,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement timed out; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-timeout",1);return}i.cancelled||this.deps.reWelcomeAll(),this.ackTo(e,t,!i.cancelled,i.cancelled?i.detail??"cancelled by extension":void 0)}catch(p){u({level:"error",event:"broker.session_replacement.failed",outcome:"failed",error:p,fields:{op:t,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement failed; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-failed",1)}finally{clearTimeout(s)}})}finally{this.admittedReplacements--,this.admittedReplacements===0&&this.deps.onReplacementIdle?.()}});this.replacementTail=d.catch(()=>{})}removeInstalledSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0,this.installed=void 0}captureSystemPrompt(e){try{const t=I(this.deps.nodeId);v(t,{recursive:!0}),_(A(t,"system-prompt.md"),e.systemPrompt,"utf8")}catch{}}executeSubscriptionCallback(e,t){try{t.type==="agent_start"&&(this.agentRunActiveValue=!0),t.type==="agent_end"&&(e.stagedProviderAgentEnd=t,e.stagedOverflowFailure=null),t.type==="compaction_end"&&t.reason==="overflow"&&t.willRetry===!1&&typeof t.errorMessage=="string"&&(e.stagedOverflowFailure={errorMessage:t.errorMessage}),t.type==="agent_settled"&&(this.agentRunActiveValue=!1,this.publishAndScheduleProviderRecovery(e)),this.deps.toolGroups.observeToolGroupEvent(t),this.deps.projection().relayEvent(t,e)}catch(n){u({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`event relay threw: ${String(n)}`}})}}async publishAndScheduleProviderRecovery(e){try{if(await this.deps.faultRetry().publishSettledProviderFault(e),this.shutdownRequested){this.deps.disposeAndExit("shutdown-after-settle");return}await this.deps.faultRetry().schedule()}catch(t){u({level:"error",event:"broker.daemon.operation.failed",node_id:this.deps.nodeId,error:t,fields:{operation:"provider_fault_settlement"}}),this.shutdownRequested&&this.deps.disposeAndExit("shutdown-after-settle")}}ackTo(e,t,n=!0,r,d){this.deps.registry.sendFrame(e,{type:"ack",for:t,ok:n,...r!==void 0?{detail:r}:{},...d!==void 0?{id:d}:{}})}}export{O as RebindDriver};
1
+ var k=Object.defineProperty;var l=(d,e)=>k(d,"name",{value:e,configurable:!0});import{mkdirSync as v,writeFileSync as _}from"node:fs";import{join as A}from"node:path";import{nodeRunJobDir as E}from"../../canvas/paths.js";import{emitEvent as u}from"../../events/emit.js";import{operationIdContext as c}from"../../events/operation-id.js";import{installPersonaTransitionGate as I}from"../broker-persona-guidance.js";import{installRetryCardElision as T}from"./retry-card-elision.js";import{abortSessionFromExtension as w}from"./extension-abort.js";import{brokerRecovery as S,mutateBrokerFault as x,mutateBrokerProviderRetry as P}from"./daemon-ops.js";const f=2,m=3e4,b=Symbol("replacement-deadline-exceeded"),V="(interrupted)",g=Symbol.for("crtr.trailing-thinking-guard");function C(d){for(let e=d.length-1;e>=0;e--){const t=d[e];if(t!==void 0){if(t.type==="text"){if(t.text.trim().length===0)continue;return t}if(t.type==="thinking"){const n=t.thinkingSignature,r=typeof n=="string"&&n.trim().length>0;if(t.redacted!==!0&&t.thinking.trim().length===0&&!r)continue;return t}return t}}}l(C,"lastSerializedBlock");function y(d){return d.map(e=>e.role!=="assistant"||C(e.content)?.type!=="thinking"?e:{...e,content:[...e.content,{type:"text",text:V}]})}l(y,"guardTrailingThinking");function N(d){const e=d.convertToLlm;if(e[g]===!0)return;const t=l(n=>{const r=e(n);return r instanceof Promise?r.then(y):y(r)},"wrapped");t[g]=!0,d.convertToLlm=t}l(N,"installTrailingThinkingGuard");class K{static{l(this,"RebindDriver")}deps;sessionValue;servicesValue;unsubscribe;installed;nextSubscriptionGeneration=0;rebindTail=Promise.resolve();latestRebindRequest=0;replacementTail=Promise.resolve();admittedReplacements=0;agentRunActiveValue=!1;shutdownRequested=!1;constructor(e){this.deps=e,this.sessionValue=e.session,this.servicesValue=e.services}session(){return this.sessionValue}services(){return this.servicesValue}installedGeneration(){return this.installed}isAgentRunActive(){return this.agentRunActiveValue}isReplacing(){return this.admittedReplacements>0}requestShutdown(){if(!this.agentRunActiveValue){this.deps.disposeAndExit("shutdown-hook");return}this.shutdownRequested=!0}setRebindSession(){this.deps.runtime?.setRebindSession(e=>this.enqueueRebind(e,this.deps.runtime.services))}enqueueRebind(e,t){const n=++this.latestRebindRequest,r=this.rebindTail.then(async()=>{if(n!==this.latestRebindRequest)return;if(this.installed!==void 0){typeof this.sessionValue.sessionFile=="string"&&this.sessionValue.sessionFile!==""&&await P(this.deps.nodeId,{op:"invalidate",session_id:this.sessionValue.sessionManager.getSessionId()});const s=(await S(this.deps.nodeId)).fault;s?.link==="pi\u2192provider"&&s.retry.disposition==="auto"&&s.retry.by==="daemon"&&await x(this.deps.nodeId,{op:"clear",link:"pi\u2192provider",preserve_episode:!0})}if(this.installed?.executingTools.clear(),this.removeInstalledSubscription(),this.deps.setActiveSession(e),this.deps.projection().reset(),this.deps.faultRetry().reset(),this.agentRunActiveValue=!1,this.deps.onSessionRebind(),this.deps.toolGroups.resetForSession(),await e.bindExtensions({uiContext:this.deps.uiContext(),mode:"rpc",abortHandler:l(()=>w(e,()=>{const s=this.installed;s?.session===e&&(s.stagedRefreshAbort=!0)}),"abortHandler"),shutdownHandler:l(()=>this.requestShutdown(),"shutdownHandler")}),n!==this.latestRebindRequest)return;this.removeInstalledSubscription(),this.sessionValue=e,this.servicesValue=t;const a=e.agent;if(a&&(I(this.deps.nodeId,{agent:a,sessionManager:e.sessionManager},()=>this.deps.faultRetry().notePersonaGateFailure()),T(a),a.steeringMode="all",a.followUpMode="all",N(a)),this.deps.cfg.editorName!==void 0&&this.deps.cfg.editorName!=="")try{e.setSessionName(this.deps.cfg.editorName)}catch{}const o={id:++this.nextSubscriptionGeneration,session:e,fallback:{blocked:!1},stagedProviderAgentEnd:null,stagedWatchdogAbort:!1,stagedRefreshAbort:!1,stagedOverflowFailure:null,executingTools:new Set};this.unsubscribe=this.sessionValue.subscribe(s=>{if(!this.deps.projection().isCurrent(o))return;if(c.current()!==void 0){this.executeSubscriptionCallback(o,s);return}const i=o.fallback;if(s.type==="turn_start"&&i.storedId!==void 0){i.storedId=void 0,i.blocked=!0,c.fresh(()=>{u({level:"warn",event:"broker.turn.fallback_overlap",fields:{generation:o.id,engine_event:s.type}}),this.executeSubscriptionCallback(o,s)});return}if(s.type==="turn_start"&&!i.blocked){c.fresh(R=>{i.storedId=R,this.executeSubscriptionCallback(o,s)});return}const h=i.storedId;if(h!==void 0&&!i.blocked){c.run(h,()=>{this.executeSubscriptionCallback(o,s),s.type==="agent_settled"&&i.storedId===h&&(i.storedId=void 0)});return}this.executeSubscriptionCallback(o,s)}),this.installed=o,this.deps.projection().rearmIfStreaming(o),this.captureSystemPrompt(e)});return this.rebindTail=r.catch(()=>{}),r}runReplacement(e,t,n){const r=this.deps.runtime;if(r===void 0){this.deps.registry.sendFrame(e,{type:"error",code:"engine_error",message:"session replacement unsupported at this engine pin"});return}if(this.admittedReplacements>=f){c.fresh(()=>u({level:"warn",event:"broker.session_replacement.rejected",outcome:"skipped",fields:{op:t,reason:"capacity",admitted:f,cap:f}})),this.ackTo(e,t,!1,`session replacement busy (${f} active or queued)`);return}this.admittedReplacements++;const a=this.replacementTail.then(async()=>{try{await c.fresh(async()=>{const o=process.hrtime.bigint();let s;try{const p=new Promise(h=>{s=setTimeout(()=>h(b),m)}),i=await Promise.race([n(r),p]);if(i===b){u({level:"error",event:"broker.session_replacement.timed_out",outcome:"failed",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{op:t,deadline_ms:m,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement timed out; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-timeout",1);return}i.cancelled||this.deps.reWelcomeAll(),this.ackTo(e,t,!i.cancelled,i.cancelled?i.detail??"cancelled by extension":void 0)}catch(p){u({level:"error",event:"broker.session_replacement.failed",outcome:"failed",error:p,fields:{op:t,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement failed; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-failed",1)}finally{clearTimeout(s)}})}finally{this.admittedReplacements--,this.admittedReplacements===0&&this.deps.onReplacementIdle?.()}});this.replacementTail=a.catch(()=>{})}removeInstalledSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0,this.installed=void 0}captureSystemPrompt(e){try{const t=E(this.deps.nodeId);v(t,{recursive:!0}),_(A(t,"system-prompt.md"),e.systemPrompt,"utf8")}catch{}}executeSubscriptionCallback(e,t){try{t.type==="agent_start"&&(this.agentRunActiveValue=!0),t.type==="agent_end"&&(e.stagedProviderAgentEnd=t,e.stagedOverflowFailure=null),t.type==="compaction_end"&&t.reason==="overflow"&&t.willRetry===!1&&typeof t.errorMessage=="string"&&(e.stagedOverflowFailure={errorMessage:t.errorMessage}),t.type==="agent_settled"&&(this.agentRunActiveValue=!1,this.publishAndScheduleProviderRecovery(e)),this.deps.toolGroups.observeToolGroupEvent(t),this.deps.projection().relayEvent(t,e)}catch(n){u({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`event relay threw: ${String(n)}`}})}}async publishAndScheduleProviderRecovery(e){try{if(await this.deps.faultRetry().publishSettledProviderFault(e),this.shutdownRequested){this.deps.disposeAndExit("shutdown-after-settle");return}await this.deps.faultRetry().schedule()}catch(t){u({level:"error",event:"broker.daemon.operation.failed",node_id:this.deps.nodeId,error:t,fields:{operation:"provider_fault_settlement"}}),this.shutdownRequested&&this.deps.disposeAndExit("shutdown-after-settle")}}ackTo(e,t,n=!0,r,a){this.deps.registry.sendFrame(e,{type:"ack",for:t,ok:n,...r!==void 0?{detail:r}:{},...a!==void 0?{id:a}:{}})}}export{K as RebindDriver};
@@ -0,0 +1,7 @@
1
+ import type { Agent, AgentMessage } from '@earendil-works/pi-agent-core';
2
+ /** Remove fault-retry cards from a provider request. A card stays only when
3
+ * removing it would leave two assistant turns adjacent — the one shape where
4
+ * it is load-bearing rather than transcript bookkeeping. */
5
+ export declare function elideRetryCards(messages: AgentMessage[]): AgentMessage[];
6
+ /** Wrap the agent's context transform so every provider request omits retry cards. */
7
+ export declare function installRetryCardElision(agent: Pick<Agent, 'transformContext'>): void;
@@ -0,0 +1 @@
1
+ var i=Object.defineProperty;var e=(t,n)=>i(t,"name",{value:n,configurable:!0});import{CONNECTION_FAULT_RECOVERY_BODY as s,PROVIDER_FAULT_RECOVERY_BODY as l,parseCard as u}from"../../../shared/generated-context.js";const a=new Set([s,l]);function f(t){if(t.role!=="user")return!1;const n=u(t);return n!==null&&n.kind==="recovery"&&n.facts.attempt!==void 0&&a.has(n.body)}e(f,"isRetryCard");function c(t){return t.role==="assistant"&&(t.stopReason==="error"||t.stopReason==="aborted")}e(c,"isDroppedAssistant");function d(t){let n=null;for(let r=0;r<t.length;r++){const o=t[r];if(f(o)&&!R(t,r)){n??=t.slice(0,r);continue}n?.push(o)}return n??t}e(d,"elideRetryCards");function R(t,n){for(let r=n-1;r>=0;r--){const o=t[r];if(!(o.role==="system"||c(o)))return o.role==="assistant"}return!1}e(R,"followsCompletedAssistant");function E(t){const n=t.transformContext;t.transformContext=async(r,o)=>d(n===void 0?r:await n(r,o))}e(E,"installRetryCardElision");export{d as elideRetryCards,E as installRetryCardElision};
@@ -1,16 +1,3 @@
1
- import type { MemoryTarget } from '../memory-resolver.js';
2
- import type { NodeConfigSubject } from '../substrate/subject-fields.js';
3
- import type { ExposureTarget } from '../substrate/injected-store.js';
4
1
  import type { BrokerExtensionNodeDTO, BrokerExtensionStateDTO } from '../../api/dto/broker-ops.js';
5
2
  export declare function editorLabelForBrokerNode(node: BrokerExtensionNodeDTO): string;
6
- /** Same environment-only project context rendered at normal boot, without a
7
- * canvas import. */
8
- export declare function buildProjectContextBlockForBroker(cwd: string): string;
9
- /** `situational` is the node's stored situational card, placed in the bearings
10
- * BODY — the one place in the system where a runtime card nests inside
11
- * another (see situational-context.ts). '' when none is set. */
12
- export declare function buildContextBearingsFromState(state: BrokerExtensionStateDTO, projectContext: string, situational?: string, target?: ExposureTarget): string;
13
3
  export declare function buildForkBearingsFromState(state: BrokerExtensionStateDTO, situational?: string): string;
14
- /** The same preference block without the extension-state DTO, for the daemon-side
15
- * claim path that holds a node's subject directly. */
16
- export declare function renderPreferencesForNodeSubject(nodeId: string, subject: NodeConfigSubject | null, target?: ExposureTarget, grantee?: string, memoryTarget?: MemoryTarget): string;
@@ -1,5 +1,3 @@
1
- var k=Object.defineProperty;var s=(e,r)=>k(e,"name",{value:r,configurable:!0});import{contextDir as h,interpolateNodePaths as b}from"../canvas/paths.js";import{fullName as l}from"../canvas/labels.js";import{renderKnowledgeForSubject as v,renderPreferencesForSubject as x}from"../substrate/render.js";import{renderWorkspaceOpenDocsForSubject as _}from"../substrate/on-read.js";import{buildProjectContextBlock as $,contextDirNote as N,profileNote as j,relativeLabel as S,renderGraphMap as F,buildIdentityAssertion as T,worktreeNote as B}from"./bearings-render.js";function M(e){const r=(e.icon??"").trim(),t=e.name!==e.kind?e.name.trim():"",o=t!==""?t:(e.description??"").trim()||e.name;return r===""?o:`${r} ${o}`}s(M,"editorLabelForBrokerNode");function W(e){return $(e)}s(W,"buildProjectContextBlockForBroker");function C(e,r){return N(e,r)}s(C,"contextDirNote");function p(e){return j(e.cwd,e.profile_id)}s(p,"profileNote");function O(e){return S(e)}s(O,"relativeLabel");function f(e){const{ancestors:r,children:t,node:o}=e;return F(o.node_id,o.kind,o.mode,r,t)}s(f,"graphMap");function w(e){const{node:r,fork_source:t}=e,o=t===null?r.fork_from??"":`${r.fork_from} ("${l(t)}")`;return T(r.node_id,r.kind,r.mode,r.fork_from,o)}s(w,"identity");function g(e){return B(e.managed_worktree)}s(g,"worktreeNote");function Y(e){const r=e.review_binding;if(r==null)return"";if(r.kind==="page_feedback"){const t=r.review_id,o=r.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${t}\`, page source \`${o}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${t} --page ${o}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${t}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of \`${r.target_file}\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}s(Y,"reviewNote");function q(e,r,t="",o){const{node:i}=e,n=["<crtr-bearings>",w(e)],c=f(e);c!==""&&n.push("","## Your place in the canvas",c),n.push("","## Your context directory",C(i.node_id,i.grantee));const d=p(i);d!==""&&n.push("",d);const u=g(i);u!==""&&n.push("","## Your managed worktree",u),i.mode==="orchestrator"&&n.push("",`Because you persist across refresh cycles, your context directory (${h(i.node_id,i.grantee)}) 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.`),n.push("</crtr-bearings>");const a=v(e.subject,i.node_id,o,void 0,i.grantee),m=_(e.subject,i.cwd,i.profile_id,o);return[n.join(`
2
- `),a,m,t,r].filter(y=>y!=="").join(`
3
- `)}s(q,"buildContextBearingsFromState");function E(e,r=""){const{node:t,fork_source:o}=e,i=o?.status==="active"||o?.status==="idle"?`Source node ${o.node_id} ("${l(o)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",n=["<crtr-bearings>",w(e),"",i,"","## Your node now",`Lifecycle: ${t.lifecycle}.`],c=f(e);if(n.push(...c===""?["Canvas: independent root with no parent or inherited graph edges."]:["",c]),n.push(`Context directory: \`${h(t.node_id,t.grantee)}\` (\`$CRTR_CONTEXT_DIR\`). Use this path in place of every source-node context path above.`),(o===null||o.cwd!==t.cwd)&&n.push(`Working directory: \`${t.cwd}\`.`),o===null||o.profile_id!==t.profile_id){const a=p(t);a!==""&&n.push(a)}const d=g(t);d!==""&&n.push("","## Your managed worktree",d),t.mode==="orchestrator"&&n.push("",`Because you persist across refresh cycles, your context directory (${h(t.node_id,t.grantee)}) 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.`);const u=Y(t);return u!==""&&n.push("",u),n.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[n.join(`
1
+ var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import{fullName as h}from"../canvas/labels.js";import{profileNote as f,renderGraphMap as p,buildIdentityAssertion as m,forkContextNote as g,orchestratorContextNote as w,worktreeNote as k}from"./bearings-render.js";function S(e){const r=(e.icon??"").trim(),t=e.name!==e.kind?e.name.trim():"",n=t!==""?t:(e.description??"").trim()||e.name;return r===""?n:`${r} ${n}`}i(S,"editorLabelForBrokerNode");function y(e){return f(e.cwd,e.profile_id)}i(y,"profileNote");function b(e){const{ancestors:r,children:t,node:n}=e;return p(n.node_id,n.kind,n.mode,r,t)}i(b,"graphMap");function v(e){const{node:r,fork_source:t}=e,n=t===null?r.fork_from??"":`${r.fork_from} ("${h(t)}")`;return m(r.node_id,r.kind,r.mode,r.fork_from,n)}i(v,"identity");function _(e){return k(e.managed_worktree)}i(_,"worktreeNote");function x(e){const r=e.review_binding;if(r==null)return"";if(r.kind==="page_feedback"){const t=r.review_id,n=r.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${t}\`, page source \`${n}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${t} --page ${n}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${t}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of \`${r.target_file}\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}i(x,"reviewNote");function F(e,r=""){const{node:t,fork_source:n}=e,l=n?.status==="active"||n?.status==="idle"?`Source node ${n.node_id} ("${h(n)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",o=["<crtr-bearings>",v(e),"",l,"","## Your node now",`Lifecycle: ${t.lifecycle}.`],s=b(e);if(o.push(...s===""?["Canvas: independent root with no parent or inherited graph edges."]:["",s]),o.push(g(t.node_id,t.grantee,t.fork_from??"")),(n===null||n.cwd!==t.cwd)&&o.push(`Working directory: \`${t.cwd}\`.`),n===null||n.profile_id!==t.profile_id){const a=y(t);a!==""&&o.push(a)}const d=_(t);d!==""&&o.push("","## Your managed worktree",d),t.mode==="orchestrator"&&o.push("",w());const c=x(t);return c!==""&&o.push("",c),o.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[o.join(`
4
2
  `),r].filter(a=>a!=="").join(`
5
- `)}s(E,"buildForkBearingsFromState");function G(e,r,t,o,i){return b(x(r,t,void 0,i).block,e,o)}s(G,"renderPreferencesForNodeSubject");export{q as buildContextBearingsFromState,E as buildForkBearingsFromState,W as buildProjectContextBlockForBroker,M as editorLabelForBrokerNode,G as renderPreferencesForNodeSubject};
3
+ `)}i(F,"buildForkBearingsFromState");export{F as buildForkBearingsFromState,S as editorLabelForBrokerNode};
@@ -1,4 +1,4 @@
1
- var C=Object.defineProperty;var s=(o,e)=>C(o,"name",{value:e,configurable:!0});import{contextDir as h}from"../canvas/paths.js";import{existsSync as S,readFileSync as v}from"node:fs";import{join as E}from"node:path";import{emitEvent as T}from"../events/emit.js";import{brokerContext as P,brokerContextEvent as Y,brokerExtensionState as y,commitBrokerContext as w,commitBrokerPersonaAck as k}from"./broker/daemon-ops.js";import{buildSubPersonaMenu as x}from"../substrate/render.js";import{contextExposureStatesEqual as _,mergeContextExposureState as j,replaceContextExposureState as D,restoreContextExposure as g,sharedContextExposureState as $,snapshotContextExposure as B}from"../substrate/injected-store.js";import{formatCard as G}from"../../shared/generated-context.js";function H(o,e){return`Because you persist across refresh cycles, your context directory (${h(o,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(H,"orchestratorContextNote");function M(o){const e=E(h(o.node_id,o.grantee),"roadmap.md"),r=S(e)?v(e,"utf8"):"(no roadmap yet)";return[`You are now a ${o.kind.toUpperCase()} ORCHESTRATOR. Your scarce resource is your own context window.`,"Your job is to manage context and delegate \u2014 not to do the goal yourself.","",`Your roadmap scaffold (\`${e}\`) \u2014 author it now: state the goal, exit criteria, and the phase skeleton, using the approach below. Current contents:`,"",r,"",H(o.node_id,o.grantee),"",'Your three long-term memory scopes (user-global, project, node-local) already surface in your bearings at boot. What promotion changes is USE, not access: you now persist across refresh cycles, so node-local carries what THIS goal needs between your refreshes, and durable facts you commit to user-global or project outlive this node. Use `crtr memory write` to save a document; `crtr memory list` to browse; `crtr memory find` to search (see "Your long-term memory" above for the full substrate flow).',"","Then delegate each phase with `crtr node new --kind <kind>`. When your context fills, run `crtr node yield` to refresh against this roadmap."].join(`
2
- `)}s(M,"orchestrationGuidance");function A(){return"You are HANDS-ON again \u2014 base mode. Do the work yourself in THIS window and finish it here; stop delegating by default. You no longer drive a roadmap, so `crtr node yield` is not your exit. Spawn a child only for a cleanly separable unit, never as your first move."}s(A,"baseModeGuidance");function N(o,e){if(o.kind===e.kind)return"";const r=x(o.kind),t=x(e.kind);return r===t?"":t===""?`The ${e.kind} kind has no specialist sub-personas available.`:t}s(N,"subPersonaGuidance");function O(o,e,r,t){const n=[];return e.mode!==r.mode&&n.push(r.mode==="orchestrator"?M(o.node):A()),n.push(N(e,r)),n.push(t),n.filter(c=>c!=="").join(`
1
+ var g=Object.defineProperty;var a=(n,e)=>g(n,"name",{value:e,configurable:!0});import{emitEvent as b}from"../events/emit.js";import{brokerDelivery as v,brokerExtensionState as p,commitBrokerPersonaAck as m}from"./broker/daemon-ops.js";import{buildSubPersonaMenu as h}from"../substrate/delivery/sub-persona-menu.js";import{orchestratorContextNote as x}from"./bearings-render.js";import{formatCard as T}from"../../shared/generated-context.js";function C(n){return[`You are now a ${n.kind.toUpperCase()} ORCHESTRATOR. Your scarce resource is your own context window.`,"Your job is to manage context and delegate \u2014 not to do the goal yourself.","","Your roadmap is your document `roadmap`; it loads at every new session of yours. Author it now with `crtr doc edit roadmap`: state the goal, exit criteria, and the phase skeleton, using the approach below.","",x(),"","What promotion changes is how long your documents matter: you now persist across refresh cycles, so the documents you own (`crtr doc write`) carry what this goal needs between your refreshes, and a lesson that should outlive this node gets another owner (`--owner user|repo|profile`).","","Then delegate each phase with `crtr node new --kind <kind>`. When your context fills, run `crtr node yield` to refresh against this roadmap."].join(`
2
+ `)}a(C,"orchestrationGuidance");function P(){return"You are HANDS-ON again \u2014 base mode. Do the work yourself in THIS window and finish it here; stop delegating by default. You no longer drive a roadmap, so `crtr node yield` is not your exit. Spawn a child only for a cleanly separable unit, never as your first move."}a(P,"baseModeGuidance");function S(n,e){if(n.kind===e.kind)return"";const r=h(n.kind),o=h(e.kind);return r===o?"":o===""?`The ${e.kind} kind has no specialist sub-personas available.`:o}a(S,"subPersonaGuidance");function D(n,e,r,o){const t=[];return e.mode!==r.mode&&t.push(r.mode==="orchestrator"?C(n.node):P()),t.push(S(e,r)),t.push(o),t.filter(i=>i!=="").join(`
3
3
 
4
- `)}s(O,"transitionGuidance");function m(o){const e=o.node,r={kind:e.kind,mode:e.mode,lifecycle:e.lifecycle},t=e.persona_ack,n=t===void 0?r:{kind:t.kind??e.kind,mode:t.mode,lifecycle:t.lifecycle};return n.kind===r.kind&&n.mode===r.mode&&n.lifecycle===r.lifecycle?null:{from:n,to:r}}s(m,"personaDriftFromBrokerState");async function Q(o){const e=m(o);if(e===null)return!1;if(!(await k(o.node.node_id,e)).applied)throw new Error(`persona baseline acknowledgment was rejected for ${o.node.node_id}`);return!0}s(Q,"acknowledgePersonaBaseline");async function R(o,e){const r=o.node.node_id,t=$(r),n=await P(r,"preferences"),c=g(n.snapshot);if(j(t,c),t.preferenceSnapshot===null)throw new Error(`context preference snapshot is missing for ${r}`);_(t,c)||await w(r,B(t),n.loads);let i=o,d=m(i);if(d===null)return!1;let a=d.from;for(;;){const u={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle};if(a.kind!==u.kind||a.mode!==u.mode||a.lifecycle!==u.lifecycle){const l=await Y(r,"persona"),f=O(i,a,u,l.content);f!==""&&await e(G("persona-transition",{},f)),a=u,await w(r,l.snapshot,l.loads),D(t,g(l.snapshot))}if(d=m(i),d===null||(await k(r,d)).applied)return!0;i=await y(r)}}s(R,"deliverPendingPersonaTransition");function V(o,e,r=()=>{}){const{agent:t}=e,n=t.transformContext;t.transformContext=async(c,i)=>{const d=n===void 0?c:await n(c,i);try{const a=await y(o);return await R(a,u=>{const p={nodeId:o},l={role:"custom",customType:"crtr-persona-transition",content:u,display:!0,details:p,timestamp:Date.now()};e.sessionManager.appendCustomMessageEntry("crtr-persona-transition",u,!0,p);const f=t.state.messages;for(const b of new Set([f,c,d]))b.push(l)}),d}catch(a){throw r(),T({event:"broker.daemon.operation.failed",level:"error",node_id:o,error:a,fields:{operation:"persona_transition"}}),a}}}s(V,"installPersonaTransitionGate");export{Q as acknowledgePersonaBaseline,R as deliverPendingPersonaTransition,V as installPersonaTransitionGate,m as personaDriftFromBrokerState};
4
+ `)}a(D,"transitionGuidance");function u(n){const e=n.node,r={kind:e.kind,mode:e.mode,lifecycle:e.lifecycle},o=e.persona_ack,t=o===void 0?r:{kind:o.kind??e.kind,mode:o.mode,lifecycle:o.lifecycle};return t.kind===r.kind&&t.mode===r.mode&&t.lifecycle===r.lifecycle?null:{from:t,to:r}}a(u,"personaDriftFromBrokerState");async function B(n){const e=u(n);if(e===null)return!1;if(!(await m(n.node.node_id,e)).applied)throw new Error(`persona baseline acknowledgment was rejected for ${n.node.node_id}`);return!0}a(B,"acknowledgePersonaBaseline");async function Y(n,e){const r=n.node.node_id;let o=n,t=u(o);if(t===null)return!1;let i=t.from;for(;;){const s={kind:o.node.kind,mode:o.node.mode,lifecycle:o.node.lifecycle};if(i.kind!==s.kind||i.mode!==s.mode||i.lifecycle!==s.lifecycle){const d=await v(r,{activity:"persona"}),c=D(o,i,s,d.content);c!==""&&await e(T("persona-transition",{},c)),i=s}if(t=u(o),t===null||(await m(r,t)).applied)return!0;o=await p(r)}}a(Y,"deliverPendingPersonaTransition");function H(n,e,r=()=>{}){const{agent:o}=e,t=o.transformContext;o.transformContext=async(i,s)=>{const l=t===void 0?i:await t(i,s);try{const d=await p(n);return await Y(d,c=>{const f={nodeId:n},y={role:"custom",customType:"crtr-persona-transition",content:c,display:!0,details:f,timestamp:Date.now()};e.sessionManager.appendCustomMessageEntry("crtr-persona-transition",c,!0,f);const w=o.state.messages;for(const k of new Set([w,i,l]))k.push(y)}),l}catch(d){throw r(),b({event:"broker.daemon.operation.failed",level:"error",node_id:n,error:d,fields:{operation:"persona_transition"}}),d}}}a(H,"installPersonaTransitionGate");export{B as acknowledgePersonaBaseline,Y as deliverPendingPersonaTransition,H as installPersonaTransitionGate,u as personaDriftFromBrokerState};
@@ -519,7 +519,7 @@ export interface WireSettings extends SettingsConfig {
519
519
  }
520
520
  /** Metadata for one resolvable inline memory reference (design: inline memory
521
521
  * references). `name` is the canonical name a token resolves to (e.g. `'dev'`,
522
- * `'taste/foo'`) and what `crtr memory read <name>` expects; `scope` is the
522
+ * `'taste/foo'`) and what `crtr canvas read <name>` expects; `scope` is the
523
523
  * WINNING scope after first-wins-by-name precedence dedup (display only —
524
524
  * resolution is by `name` alone). No body/source path: this is a metadata-only
525
525
  * inventory, never the document content. `gatewayVisible` is broker-computed