@north-light/cli 0.3.707 → 0.3.709

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 (278) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/crons.d.ts +3 -0
  6. package/dist/api/dto/human.d.ts +9 -6
  7. package/dist/api/dto/inbox.d.ts +2 -0
  8. package/dist/api/dto/review-comments.d.ts +12 -35
  9. package/dist/api/dto/reviews.d.ts +3 -10
  10. package/dist/api/routes.d.ts +0 -1
  11. package/dist/api/routes.js +1 -1
  12. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +2 -2
  13. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  14. package/dist/clients/attach/chrome/canvas-panels.d.ts +1 -1
  15. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  16. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  17. package/dist/clients/attach/chrome/roster.js +6 -6
  18. package/dist/clients/attach/chrome/status-line.d.ts +1 -1
  19. package/dist/clients/attach/chrome/status-line.js +1 -1
  20. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  21. package/dist/clients/attach/input/capabilities.js +1 -1
  22. package/dist/clients/attach/input/controller.d.ts +4 -1
  23. package/dist/clients/attach/input/controller.js +3 -3
  24. package/dist/clients/attach/input/overlay-owner.d.ts +0 -1
  25. package/dist/clients/attach/input/overlay-owner.js +1 -1
  26. package/dist/clients/attach/overlays/graph.d.ts +3 -2
  27. package/dist/clients/attach/overlays/graph.js +1 -1
  28. package/dist/clients/attach/render/chat-view.d.ts +2 -0
  29. package/dist/clients/attach/render/chat-view.js +1 -1
  30. package/dist/clients/attach/render/doc-links.d.ts +1 -1
  31. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  32. package/dist/clients/attach/session/connection.d.ts +10 -9
  33. package/dist/clients/attach/session/connection.js +1 -1
  34. package/dist/clients/attach/session/context.d.ts +1 -1
  35. package/dist/clients/attach/session/document-links.d.ts +1 -1
  36. package/dist/clients/attach/session/document-links.js +1 -1
  37. package/dist/clients/attach/session/identity.d.ts +2 -0
  38. package/dist/clients/attach/session/identity.js +1 -1
  39. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  40. package/dist/clients/attach/session/input-wiring.js +1 -1
  41. package/dist/clients/attach/session/keys.d.ts +2 -2
  42. package/dist/clients/attach/session/keys.js +1 -1
  43. package/dist/clients/attach/session/pane-tag.d.ts +3 -1
  44. package/dist/clients/attach/session/pane-tag.js +1 -1
  45. package/dist/clients/attach/session/reconnect.js +1 -1
  46. package/dist/clients/attach/session/surface-host.d.ts +0 -5
  47. package/dist/clients/attach/session/surface-host.js +1 -1
  48. package/dist/clients/attach/session/teardown.d.ts +2 -2
  49. package/dist/clients/attach/session/teardown.js +9 -7
  50. package/dist/clients/attach/viewer.d.ts +7 -5
  51. package/dist/clients/attach/viewer.js +571 -584
  52. package/dist/clients/editor-roundtrip.js +3 -0
  53. package/dist/clients/inbox/controller.d.ts +1 -6
  54. package/dist/clients/inbox/controller.js +1 -1
  55. package/dist/clients/inbox/dto-adapt.js +1 -1
  56. package/dist/clients/inbox/tui/page-body.js +1 -1
  57. package/dist/clients/inbox/tui/render.js +2 -2
  58. package/dist/clients/open-browser.d.ts +2 -0
  59. package/dist/clients/open-browser.js +1 -0
  60. package/dist/clients/surfaces/host.d.ts +0 -6
  61. package/dist/commands/human/review.js +1 -1
  62. package/dist/commands/node/wait.js +2 -6
  63. package/dist/commands/sys/context/admin/shell.js +1 -1
  64. package/dist/core/broker-client/client.d.ts +6 -3
  65. package/dist/core/broker-client/client.js +1 -1
  66. package/dist/core/canvas/crons.d.ts +11 -1
  67. package/dist/core/canvas/crons.js +14 -14
  68. package/dist/core/canvas/executions.js +1 -1
  69. package/dist/core/canvas/schema-pg/025-review-anchors.sql +19 -0
  70. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  71. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  72. package/dist/core/canvas/schema-version.d.ts +1 -1
  73. package/dist/core/canvas/schema-version.js +1 -1
  74. package/dist/core/command.js +5 -5
  75. package/dist/core/feed/messages.d.ts +5 -0
  76. package/dist/core/feed/messages.js +5 -5
  77. package/dist/core/human/page-markdown.js +10 -12
  78. package/dist/core/human/tickets.js +1 -1
  79. package/dist/core/human/types.d.ts +4 -6
  80. package/dist/core/keybindings/attach-control.d.ts +0 -3
  81. package/dist/core/keybindings/attach-control.js +1 -1
  82. package/dist/core/keybindings/catalog.d.ts +1 -1
  83. package/dist/core/keybindings/catalog.js +1 -1
  84. package/dist/core/review/anchors.d.ts +28 -0
  85. package/dist/core/review/anchors.js +6 -0
  86. package/dist/core/review/comments.d.ts +2 -2
  87. package/dist/core/review/comments.js +7 -8
  88. package/dist/core/review/companion.d.ts +2 -1
  89. package/dist/core/review/companion.js +1 -1
  90. package/dist/core/review/document.d.ts +4 -17
  91. package/dist/core/review/document.js +1 -2
  92. package/dist/core/review/fork.js +2 -4
  93. package/dist/core/review/project.d.ts +1 -1
  94. package/dist/core/review/project.js +2 -2
  95. package/dist/core/review/realize.js +1 -1
  96. package/dist/core/review/stage.d.ts +2 -9
  97. package/dist/core/review/stage.js +1 -1
  98. package/dist/core/review/types.d.ts +16 -12
  99. package/dist/core/review/types.js +1 -1
  100. package/dist/core/runtime/bearings.js +4 -4
  101. package/dist/core/runtime/boot-root.js +4 -4
  102. package/dist/core/runtime/broker-cli.js +3 -3
  103. package/dist/core/runtime/broker-extension-render.js +1 -1
  104. package/dist/core/runtime/lifecycle.js +2 -2
  105. package/dist/core/runtime/revive.js +2 -2
  106. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  107. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  108. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  109. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  110. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  111. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  112. package/dist/core/runtime/runner/types.d.ts +19 -3
  113. package/dist/core/runtime/tmux-bindings.js +3 -3
  114. package/dist/daemon/api/bridge.d.ts +5 -0
  115. package/dist/daemon/api/bridge.js +3 -3
  116. package/dist/daemon/api/canvas-host.js +1 -1
  117. package/dist/daemon/api/document-page.d.ts +12 -1
  118. package/dist/daemon/api/document-page.js +6 -6
  119. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  120. package/dist/daemon/api/handlers/crons.js +1 -1
  121. package/dist/daemon/api/handlers/inbox.js +1 -1
  122. package/dist/daemon/api/handlers/nodes.js +1 -1
  123. package/dist/daemon/api/handlers/review-comments.js +1 -1
  124. package/dist/daemon/api/handlers/reviews.js +1 -1
  125. package/dist/daemon/api/map.js +2 -2
  126. package/dist/daemon/api/operations.js +1 -1
  127. package/dist/daemon/api/review-page.d.ts +3 -0
  128. package/dist/daemon/api/review-page.js +13 -0
  129. package/dist/daemon/broker-memory-cap.d.ts +9 -0
  130. package/dist/daemon/broker-memory-cap.js +2 -0
  131. package/dist/daemon/broker-signals/bus.d.ts +1 -1
  132. package/dist/daemon/broker-signals/bus.js +1 -1
  133. package/dist/daemon/cron/ended.d.ts +3 -0
  134. package/dist/daemon/cron/ended.js +2 -2
  135. package/dist/daemon/cron/lease-recovery.js +1 -1
  136. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  137. package/dist/daemon/cron/machine-fire.js +1 -1
  138. package/dist/daemon/cron/passes.js +1 -1
  139. package/dist/daemon/cron-run.js +2 -2
  140. package/dist/daemon/crtrd.js +14 -14
  141. package/dist/daemon/machine-daemon.js +1 -1
  142. package/dist/daemon/machine-link/client.js +1 -1
  143. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  144. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  145. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  146. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  147. package/dist/daemon/review/comment-notify.js +2 -2
  148. package/dist/daemon/review/deliver.d.ts +2 -2
  149. package/dist/daemon/review/deliver.js +6 -2
  150. package/dist/daemon/review/finish.js +1 -1
  151. package/dist/doc-editor/Geist-Variable.woff2 +0 -0
  152. package/dist/doc-editor/GeistMono-Variable.woff2 +0 -0
  153. package/dist/doc-editor/editor.css +1 -1
  154. package/dist/doc-editor/review.css +2 -0
  155. package/dist/doc-editor/review.js +149 -0
  156. package/dist/pi-extensions/canvas-review-boundary.js +3 -3
  157. package/docs/sdk/release-notes.md +6 -0
  158. package/package.json +13 -4
  159. package/packages/crouter-api/dist/api/client.js +0 -3
  160. package/packages/crouter-api/dist/api/contract.js +1 -1
  161. package/packages/crouter-api/dist/api/routes.js +0 -1
  162. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +3 -3
  163. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  164. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +17 -28
  165. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +2 -7
  166. package/packages/crouter-api/dist/clients/attach/chrome/ticket-panel.js +1 -1
  167. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +2 -1
  168. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -3
  169. package/packages/crouter-api/dist/clients/attach/input/overlay-owner.js +0 -7
  170. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  171. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  172. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  173. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  174. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  175. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  176. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  177. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -5
  178. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  179. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  180. package/packages/crouter-api/dist/clients/attach/session/surface-host.js +0 -17
  181. package/packages/crouter-api/dist/clients/attach/session/teardown.js +7 -4
  182. package/packages/crouter-api/dist/clients/attach/viewer.js +77 -67
  183. package/packages/crouter-api/dist/clients/{inbox/review/roundtrip.js → editor-roundtrip.js} +1 -1
  184. package/packages/crouter-api/dist/clients/inbox/controller.js +12 -31
  185. package/packages/crouter-api/dist/clients/inbox/dto-adapt.js +1 -0
  186. package/packages/crouter-api/dist/clients/inbox/tui/page-body.js +0 -7
  187. package/packages/crouter-api/dist/clients/inbox/tui/render.js +0 -7
  188. package/packages/crouter-api/dist/clients/open-browser.js +6 -0
  189. package/packages/crouter-api/dist/commands/human/review.js +17 -18
  190. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  191. package/packages/crouter-api/dist/commands/sys/context/admin/shell.js +1 -1
  192. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  193. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  194. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  195. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  196. package/packages/crouter-api/dist/core/command.js +3 -0
  197. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  198. package/packages/crouter-api/dist/core/human/page-markdown.js +2 -6
  199. package/packages/crouter-api/dist/core/human/tickets.js +2 -11
  200. package/packages/crouter-api/dist/core/keybindings/attach-control.js +0 -1
  201. package/packages/crouter-api/dist/core/keybindings/catalog.js +1 -3
  202. package/packages/crouter-api/dist/core/review/anchors.js +91 -0
  203. package/packages/crouter-api/dist/core/review/comments.js +27 -46
  204. package/packages/crouter-api/dist/core/review/companion.js +5 -9
  205. package/packages/crouter-api/dist/core/review/document.js +17 -89
  206. package/packages/crouter-api/dist/core/review/project.js +2 -1
  207. package/packages/crouter-api/dist/core/review/types.js +2 -2
  208. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  209. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  210. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  211. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  212. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  213. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  214. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +0 -5
  215. package/packages/crouter-api/dist/daemon/api/map.js +2 -6
  216. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  217. package/packages/crouter-api/dist/daemon/broker-signals/bus.js +1 -1
  218. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  219. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  220. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  221. package/packages/crouter-api/dist/daemon/review/deliver.js +4 -3
  222. package/packages/crouter-api/dist/daemon/review/finish.js +26 -47
  223. package/packages/crouter-api/package.json +1 -1
  224. package/packages/crouter-identity/package.json +1 -1
  225. package/packages/crouter-plugin/package.json +3 -3
  226. package/runtime.lock.json +1740 -505
  227. package/dist/clients/attach/overlays/file-review.d.ts +0 -10
  228. package/dist/clients/attach/overlays/file-review.js +0 -2
  229. package/dist/clients/inbox/review/anchors.d.ts +0 -41
  230. package/dist/clients/inbox/review/anchors.js +0 -1
  231. package/dist/clients/inbox/review/comments-client.d.ts +0 -74
  232. package/dist/clients/inbox/review/comments-client.js +0 -1
  233. package/dist/clients/inbox/review/companion-pane.d.ts +0 -47
  234. package/dist/clients/inbox/review/companion-pane.js +0 -1
  235. package/dist/clients/inbox/review/document-surface.d.ts +0 -212
  236. package/dist/clients/inbox/review/document-surface.js +0 -2
  237. package/dist/clients/inbox/review/frame.d.ts +0 -57
  238. package/dist/clients/inbox/review/frame.js +0 -1
  239. package/dist/clients/inbox/review/keys.d.ts +0 -69
  240. package/dist/clients/inbox/review/keys.js +0 -1
  241. package/dist/clients/inbox/review/launch.d.ts +0 -16
  242. package/dist/clients/inbox/review/launch.js +0 -1
  243. package/dist/clients/inbox/review/live-source.d.ts +0 -24
  244. package/dist/clients/inbox/review/live-source.js +0 -1
  245. package/dist/clients/inbox/review/nvim.d.ts +0 -15
  246. package/dist/clients/inbox/review/nvim.js +0 -1
  247. package/dist/clients/inbox/review/remap.d.ts +0 -51
  248. package/dist/clients/inbox/review/remap.js +0 -1
  249. package/dist/clients/inbox/review/review-client.d.ts +0 -43
  250. package/dist/clients/inbox/review/review-client.js +0 -1
  251. package/dist/clients/inbox/review/roundtrip.js +0 -3
  252. package/dist/clients/inbox/review/state.d.ts +0 -153
  253. package/dist/clients/inbox/review/state.js +0 -4
  254. package/dist/clients/inbox/review-adapter.d.ts +0 -17
  255. package/dist/clients/inbox/review-adapter.js +0 -1
  256. package/dist/core/review/remap.d.ts +0 -24
  257. package/dist/core/review/remap.js +0 -19
  258. package/dist/core/review/signal.d.ts +0 -5
  259. package/dist/core/review/signal.js +0 -1
  260. package/dist/core/runtime/starting-screen.d.ts +0 -12
  261. package/dist/core/runtime/starting-screen.js +0 -9
  262. package/packages/crouter-api/dist/clients/attach/overlays/file-review.js +0 -146
  263. package/packages/crouter-api/dist/clients/inbox/review/anchors.js +0 -89
  264. package/packages/crouter-api/dist/clients/inbox/review/comments-client.js +0 -103
  265. package/packages/crouter-api/dist/clients/inbox/review/companion-pane.js +0 -109
  266. package/packages/crouter-api/dist/clients/inbox/review/document-surface.js +0 -1268
  267. package/packages/crouter-api/dist/clients/inbox/review/frame.js +0 -309
  268. package/packages/crouter-api/dist/clients/inbox/review/keys.js +0 -133
  269. package/packages/crouter-api/dist/clients/inbox/review/launch.js +0 -170
  270. package/packages/crouter-api/dist/clients/inbox/review/live-source.js +0 -160
  271. package/packages/crouter-api/dist/clients/inbox/review/nvim.js +0 -43
  272. package/packages/crouter-api/dist/clients/inbox/review/remap.js +0 -157
  273. package/packages/crouter-api/dist/clients/inbox/review/review-client.js +0 -125
  274. package/packages/crouter-api/dist/clients/inbox/review/state.js +0 -315
  275. package/packages/crouter-api/dist/clients/inbox/review-adapter.js +0 -43
  276. package/packages/crouter-api/dist/core/review/signal.js +0 -12
  277. package/packages/crouter-api/dist/core/termrender/code-doc.js +0 -92
  278. /package/dist/clients/{inbox/review/roundtrip.d.ts → editor-roundtrip.d.ts} +0 -0
@@ -8,22 +8,23 @@ export type ReviewState = 'binding' | 'open' | 'approved' | 'canceled';
8
8
  export type ReviewOriginKind = 'ticket' | 'inline';
9
9
  export type CommentStatus = 'open' | 'resolved' | 'deleted';
10
10
  export type CommentAuthorKind = 'human' | 'node';
11
- export type CommentEventKind = 'created' | 'edited' | 'resolved' | 'reopened' | 'deleted' | 'reanchored' | 'notified' | 'notify_failed';
12
- export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'stale_revision' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | 'anchor_out_of_range' | 'text_too_long' | 'comment_limit_reached' | 'stale_comment' | 'range_batch_incomplete' | 'range_batch_stale';
11
+ export type CommentEventKind = 'created' | 'edited' | 'resolved' | 'reopened' | 'deleted' | 'notified' | 'notify_failed';
12
+ export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'stale_revision' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | 'quote_not_found' | 'text_too_long' | 'comment_limit_reached' | 'stale_comment';
13
13
  /** Limits */
14
14
  export declare const COMMENT_TEXT_MAX = 8000;
15
- export declare const COMMENT_QUOTE_MAX = 4000;
16
- export declare const COMMENT_LINE_TEXT_MAX = 8000;
15
+ export declare const COMMENT_QUOTE_MAX = 2000;
16
+ export declare const ANCHOR_CONTEXT_MAX = 32;
17
17
  export declare const LIVE_COMMENTS_MAX = 500;
18
18
  export declare const COMMENT_EVENTS_PAGE_DEFAULT = 200;
19
19
  export declare const COMMENT_EVENTS_PAGE_MAX = 1000;
20
20
  export declare const COMPANION_BIND_DEADLINE_MS = 90000;
21
21
  export interface CommentAnchor {
22
- line: number;
23
- end_line: number;
24
- col_start?: number;
25
- col_end?: number;
26
- quote?: string;
22
+ /** Selected text in the rendered document (whitespace-collapsed). */
23
+ quote: string;
24
+ prefix: string;
25
+ suffix: string;
26
+ /** Character offset in the rendered text when created; a tie-breaker only. */
27
+ offset: number;
27
28
  }
28
29
  export interface ReviewRow {
29
30
  review_id: string;
@@ -83,9 +84,6 @@ export interface ReviewComment {
83
84
  revision: number;
84
85
  text: string;
85
86
  anchor: CommentAnchor;
86
- anchor_state: 'live' | 'detached';
87
- anchor_line_text: string;
88
- anchor_doc_hash: string;
89
87
  author: {
90
88
  kind: CommentAuthorKind;
91
89
  node_id: string | null;
@@ -118,6 +116,12 @@ export interface ReviewCommentEvent {
118
116
  export interface ReviewResult {
119
117
  schema: 'humanloop.review-response/v1';
120
118
  review_id: string;
119
+ document: {
120
+ id: string;
121
+ name: string;
122
+ base_revision: string | null;
123
+ approved_revision: string | null;
124
+ } | null;
121
125
  file: string;
122
126
  submitted: true;
123
127
  approved: true;
@@ -1 +1 @@
1
- var r=Object.defineProperty;var E=(o,t)=>r(o,"name",{value:t,configurable:!0});const s=8e3,T=4e3,N=8e3,c=500,n=200,p=1e3,O=9e4;class A extends Error{static{E(this,"ReviewOperationError")}code;detail;constructor(t,_,e){super(_),this.code=t,this.detail=e,this.name="ReviewOperationError"}}export{n as COMMENT_EVENTS_PAGE_DEFAULT,p as COMMENT_EVENTS_PAGE_MAX,N as COMMENT_LINE_TEXT_MAX,T as COMMENT_QUOTE_MAX,s as COMMENT_TEXT_MAX,O as COMPANION_BIND_DEADLINE_MS,c as LIVE_COMMENTS_MAX,A as ReviewOperationError};
1
+ var _=Object.defineProperty;var e=(o,t)=>_(o,"name",{value:t,configurable:!0});const s=8e3,N=2e3,T=32,c=500,n=200,O=1e3,p=9e4;class A extends Error{static{e(this,"ReviewOperationError")}code;detail;constructor(t,r,E){super(r),this.code=t,this.detail=E,this.name="ReviewOperationError"}}export{T as ANCHOR_CONTEXT_MAX,n as COMMENT_EVENTS_PAGE_DEFAULT,O as COMMENT_EVENTS_PAGE_MAX,N as COMMENT_QUOTE_MAX,s as COMMENT_TEXT_MAX,p as COMPANION_BIND_DEADLINE_MS,c as LIVE_COMMENTS_MAX,A as ReviewOperationError};
@@ -1,7 +1,7 @@
1
- var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as k,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 w,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(E,"ancestorTrunk");const F=5;async function j(e){return(await Y(await g(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(j,"childNodes");async function B(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await E(e,n),o=await j(e);return C(e,n.kind,n.mode,t,o)}a(B,"buildGraphMap");async function R(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&k(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,o)}a(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)`}a(T,"armerPhrase");async function K(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
1
+ var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as k,fullName as d,isSafeNodeId as g,subscriptionsOf as N}from"../canvas/index.js";import{cadenceDisplay as v}from"../wake.js";import{renderKnowledge as x,renderWorkspaceOpen as _}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 w,orchestratorContextNote as p,profileNote as C,renderGraphMap as S,buildIdentityAssertion as E,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as Z}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":C(n.cwd,n.profile_id)}a(A,"profileNote");async function j(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(j,"ancestorTrunk");const K=5;async function B(e){return(await Y(await N(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(B,"childNodes");async function R(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await j(e,n),o=await B(e);return S(e,n.kind,n.mode,t,o)}a(R,"buildGraphMap");async function T(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&g(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return E(e,r?.kind??"general",r?.mode??"base",n,o)}a(T,"buildIdentityAssertion");function D(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(D,"armerPhrase");async function q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(q,"cronWakeOrigin");function z(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?v(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
2
  ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const t=T(e);return`<crtr-wake>
3
+ </crtr-wake>`;const t=D(e);return`<crtr-wake>
4
4
  ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, 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 ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,r,n){const t=await s(e),o=["<crtr-bearings>",await R(e,t)],i=await B(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await _(e)??"",m=t?.cwd!==void 0?f(t.cwd):"";return[o.join(`
5
+ </crtr-wake>`}a(z,"buildWakeBearings");function W(e){return O(e?.managed_worktree)}a(W,"managedWorktreeNote");async function H(e,r,n){const t=await s(e),o=["<crtr-bearings>",await T(e,t)],i=await R(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=W(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await $(e)??"",m=t?.cwd!==void 0&&(await k(e))?.runner==="process"?f(t.cwd):"";return[o.join(`
6
6
  `),r,n,h,m].filter(y=>y!=="").join(`
7
- `)}a(W,"bearingsShell");async function z(e,r){const n=await v(r),t=await x(r);return{content:await W(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,f as buildProjectContextBlock,q as buildWakeBearings,w as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
7
+ `)}a(H,"bearingsShell");async function J(e,r){const n=await x(r),t=await _(r);return{content:await H(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(J,"buildContextBearings");export{Z as CONTEXT_INTRO_CUSTOM_TYPE,J as buildContextBearings,R as buildGraphMap,f as buildProjectContextBlock,z as buildWakeBearings,w as contextDirNote,q as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
@@ -1,7 +1,7 @@
1
- var x=Object.defineProperty;var p=(e,o)=>x(e,"name",{value:o,configurable:!0});import{inTmux as b,currentTmux as w}from"./placement-tmux.js";import{selectProfileForCwd as g}from"../profiles/select.js";import{cliClient as c}from"../../commands/api-client.js";import{mark as s}from"../timing.js";import{handle as T}from"../io.js";import{loadedPersonSettings as k}from"../../commands/person-settings.js";import{showStartingScreen as C}from"./starting-screen.js";import{printComeBackNote as l}from"./come-back-note.js";function h(e,o){const i=e.kind;return{...i!==void 0?{kind:i}:{},mode:"base",prompt:e.prompt,profile:o,cwd:e.cwd,...e.name!==void 0?{name:e.name}:i!==void 0?{name:i}:{},root:!0,start:!0,prefer_warm:!0}}p(h,"rootCreateRequest");async function R(e){if(!b()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
1
+ var l=Object.defineProperty;var c=(e,i)=>l(e,"name",{value:i,configurable:!0});import{inTmux as x,currentTmux as p}from"./placement-tmux.js";import{selectProfileForCwd as _}from"../profiles/select.js";import{cliClient as a}from"../../commands/api-client.js";import{mark as d}from"../timing.js";import{handle as h}from"../io.js";import{loadedPersonSettings as b}from"../../commands/person-settings.js";import{printComeBackNote as u}from"./come-back-note.js";function w(e,i){const o=e.kind;return{...o!==void 0?{kind:o}:{},mode:"base",prompt:e.prompt,profile:i,cwd:e.cwd,...e.name!==void 0?{name:e.name}:o!==void 0?{name:o}:{},root:!0,start:!0,prefer_warm:!0}}c(w,"rootCreateRequest");async function P(e){if(!x()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
2
2
  ${t("crtr must be started from inside a tmux session.")}
3
3
  ${t("Start tmux first, e.g. tmux new -s work \u2014 then run crtr there.")}
4
4
 
5
- `),process.exit(1)}s("boot_root.start");const o=e.selectedProfileId??await g(e.cwd,e.profile,e.pickProfile??!1,!1);if(s("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await c().createNode(h(e,o)),r=w();r!==null&&await c().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
6
- `),await l(t.node_id,0),process.exit(0)}const{buildBannerInfo:i}=await import("../../clients/attach/session/banner.js"),{hint:$,..._}=i({cwd:e.cwd,profile_id:o}),a=C(_);s("boot_root.starting_painted");const f=import("../../clients/attach/viewer.js");f.catch(()=>{});let m;try{m=await c().createNode(h(e,o))}catch(t){throw a.stop(),t}const n=m.node_id;a.setNode(n),s("boot_root.node_created",{node:n});const d=w();d!==null&&c().registerFocus({node_id:n,pane:d.pane,session:d.session,window:d.window}).catch(()=>{});let u=0;try{const{runAttach:t}=await f;s("boot_root.viewer_attach"),await t(n,!1,void 0,!0,{node:m,settings:k(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},()=>a.stop())}catch(t){a.stop(),process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
7
- `),T(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}await l(n,u),process.exit(u)}p(R,"bootRoot");export{R as bootRoot,h as rootCreateRequest};
5
+ `),process.exit(1)}d("boot_root.start");const i=e.selectedProfileId??await _(e.cwd,e.profile,e.pickProfile??!1,!1);if(d("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await a().createNode(w(e,i)),r=p();r!==null&&await a().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
6
+ `),await u(t.node_id,0),process.exit(0)}const o=a().createNode(w(e,i));o.catch(()=>{});const f=import("../../clients/attach/viewer.js");f.catch(()=>{}),d("boot_root.create_started");const s=p();o.then(t=>{d("boot_root.node_created",{node:t.node_id}),s!==null&&a().registerFocus({node_id:t.node_id,pane:s.pane,session:s.session,window:s.window}).catch(()=>{})},()=>{});let m=0,n;try{const{runAttach:t}=await f;d("boot_root.viewer_attach"),await t({cwd:e.cwd,profile_id:i,created:o.then(r=>(n=r.node_id,r)),settings:b(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},!1)}catch(t){n!==void 0&&process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
7
+ `),h(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}n===void 0&&process.exit(typeof process.exitCode=="number"?process.exitCode:1),await u(n,m),process.exit(m)}c(P,"bootRoot");export{P as bootRoot,w as rootCreateRequest};
@@ -1,3 +1,3 @@
1
- var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{isSafeNodeId as d}from"../canvas/paths.js";import{emitEvent as p,flushBrokerLog as u}from"../events/emit.js";import{mark as a,timingProc as f}from"../timing.js";const l=process.hrtime.bigint(),m=new Date().toISOString(),t=process.argv.length>2?process.argv.at(-1):void 0;(t===void 0||!d(t))&&(process.stderr.write(`[broker] usage: broker-cli [--canvas-home <path>] [--epoch <id>] <nodeId>
2
- `),process.exit(1)),f("broker"),a("broker.entry",{node:t});const{runBroker:h,disposeActiveSession:g}=await import("./broker.js");a("broker.module_loaded");function s(e){try{g()}catch{}u().finally(()=>process.exit(e))}n(s,"disposeAndExit");function i(e,r){let o;try{o=p({level:"error",event:"broker.runtime.fatal",error:r,fields:{origin:e}})}catch{o=!1}o||process.stderr.write(`[broker] fatal (${e}): ${r instanceof Error?r.stack??r.message:String(r)}
3
- `)}n(i,"reportFatal"),process.on("uncaughtException",e=>{i("uncaughtException",e),s(1)}),process.on("unhandledRejection",e=>{i("unhandledRejection",e),s(1)}),h(t,l,m).catch(e=>{i("run_failure",e),s(1)});
1
+ var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{isSafeNodeId as d}from"../canvas/paths.js";import{emitEvent as p,flushBrokerLog as f}from"../events/emit.js";import{mark as a,timingProc as u}from"../timing.js";import{configureDaemonHttpDispatcher as l}from"../../daemon/http-dispatcher.js";const m=process.hrtime.bigint(),h=new Date().toISOString(),t=process.argv.length>2?process.argv.at(-1):void 0;(t===void 0||!d(t))&&(process.stderr.write(`[broker] usage: broker-cli [--canvas-home <path>] [--epoch <id>] <nodeId>
2
+ `),process.exit(1)),u("broker"),a("broker.entry",{node:t}),l();const{runBroker:g,disposeActiveSession:k}=await import("./broker.js");a("broker.module_loaded");function s(e){try{k()}catch{}f().finally(()=>process.exit(e))}n(s,"disposeAndExit");function i(e,r){let o;try{o=p({level:"error",event:"broker.runtime.fatal",error:r,fields:{origin:e}})}catch{o=!1}o||process.stderr.write(`[broker] fatal (${e}): ${r instanceof Error?r.stack??r.message:String(r)}
3
+ `)}n(i,"reportFatal"),process.on("uncaughtException",e=>{i("uncaughtException",e),s(1)}),process.on("unhandledRejection",e=>{i("unhandledRejection",e),s(1)}),g(t,m,h).catch(e=>{i("run_failure",e),s(1)});
@@ -1,3 +1,3 @@
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(`
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 the canvas document \`${r.target_file}\`, which you revise with \`crtr doc edit\`. 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 c=_(t);c!==""&&o.push("","## Your managed worktree",c),t.mode==="orchestrator"&&o.push("",w());const d=x(t);return d!==""&&o.push("",d),o.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[o.join(`
2
2
  `),r].filter(a=>a!=="").join(`
3
3
  `)}i(F,"buildForkBearingsFromState");export{F as buildForkBearingsFromState,S as editorLabelForBrokerNode};
@@ -1,2 +1,2 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{getNode as y,cancelCronsOnWake as B,transitionStatusIntent as D}from"../canvas/index.js";import{closeSync as J,constants as N,existsSync as j,fstatSync as F,readSync as P}from"node:fs";import{join as E}from"node:path";import{BROKER_RELEASED_MARKER as $,BROKER_RELAY_GENERATION as M,nodeRunDir as x}from"../canvas/paths.js";import{openBeneath as T,writeFileBeneath as W,isAbsentOrRefused as q}from"../spaces/open-beneath.js";import{emitEvent as C}from"../events/emit.js";import{composeNodeOutcomeDocument as K}from"./outcome-document.js";import{afterCommit as Y,withCanvasWrite as G}from"../canvas/db.js";import{nodeObject as z}from"../graph/objects.js";import{endMessageSubscriptions as V}from"../graph/watches.js";import{settleNodeObjectWaits as v}from"../canvas/waits.js";import{runStructuredRequestEffects as H,settlePendingStructuredRequestForNodeIn as I}from"../canvas/structured-requests.js";const p="*",Q={finish:"finished",park:"parked",cancel:"stranded",crash:"crashed","refresh-launch":null,revive:null},u=["active","idle"],U={finish:{status:"done",intent:"done",from:u},park:{status:"done",intent:"parked",from:u},cancel:{status:"canceled",intent:null,from:p},crash:{status:"dead",from:u},yield:{intent:"refresh",from:u},release:{status:"idle",intent:"idle-release",from:[...u,"done"]},"refresh-launch":{status:"active",intent:"refresh",from:p},revive:{status:"active",intent:null,from:p}};function X(t,e){const r=t.split(`
2
- `)[0]??"";let n=0,l="";for(const c of r){const s=Buffer.byteLength(c,"utf8");if(n+s>e)break;n+=s,l+=c}return l}o(X,"firstLineAtMost");function Z(t){if(t===void 0)return null;const e=t.message===void 0?void 0:X(t.message,500),r={...t,...e===void 0?{}:{message:e}},n=JSON.stringify(r);return Buffer.byteLength(n,"utf8")<=4*1024?n:JSON.stringify({schema:"crtr.node-outcome-detail/v1",truncated:!0,...e===void 0?{}:{message:e}})}o(Z,"detailJson");function ee(t,e){let r,n;return e==="finished"||e==="declined"?(r="done",n="done"):e==="parked"?(r="done",n="parked"):e==="closed"||e==="retired"||e==="stranded"||e==="deadline_exceeded"?(r="canceled",n=null):(r="dead",n=null),{...t,status:r,intent:n,terminal_reason:e}}o(ee,"nodeAtOutcome");async function Oe(t,e,r){const n=U[e],l=Object.prototype.hasOwnProperty.call(n,"status"),c=Object.prototype.hasOwnProperty.call(n,"intent"),s=r?.reason??Q[e],d={};l&&(d.status=n.status),c&&(d.intent=n.intent??null),s!==void 0&&(d.terminal_reason=s);const f=e==="finish"||e==="park"||e==="cancel"||e==="crash",_=f?new Date().toISOString():null,h=s,k=Z(r?.outcome?.detail),S=f?s==="deadline_exceeded"?{intended:"expired",failureReason:"node_deadline_exceeded",failureDetail:r?.outcome?.detail??null}:{intended:"failed",failureReason:s,failureDetail:r?.outcome?.detail??null}:null,w=await G(async i=>{const a=f?await y(t):null,O=f&&a?.kind!=="human",g=O&&a?.run_id!=null&&s!=="parked"&&a.outcome_at!==null&&(u.includes(a.status)||a.outcome_reason==="parked");let R;O&&a!==null&&(a.outcome_at===null||g)&&(R=JSON.stringify(await K({node:ee(a,h),outcome:{kind:"failure",reason:h,at:_,revision:(a.outcome_revision??0)+1,detailJson:k}})));const m=await D(t,d,{fromStatuses:n.from===p?void 0:n.from,requireNoFinalReport:e==="cancel",...O?{outcome:{kind:"failure",reason:h,detailJson:k,at:_,...g?{supersede:!0}:{},...R===void 0?{}:{documentJson:R}}}:{}});f&&m>0&&(await V(i,await z(i,t),"done"),await v(i,t));const A=m===1&&S!==null?await I(i,t,S):null;if(m===1&&(e==="release"||e==="park"||e==="finish"||e==="cancel")){const b=te(t);Y(()=>ne(t,b))}return{changes:m,settlement:A}});if(w.changes===0){const i=await y(t);if(i===null)throw new Error(`transition: unknown node ${t}`);if(e==="cancel"&&i.final_report!==null&&i.final_report!==void 0)return i;throw new Error(`illegal lifecycle transition: '${e}' from status='${i.status}' (node ${t})`)}return w.settlement?.changed&&H(w.settlement.row),(e==="finish"||e==="park"||e==="cancel")&&await B(t),await y(t)}o(Oe,"transition");function te(t){const e=x(t);let r;try{r=T(e,E(e,M),N.O_RDONLY|N.O_NOFOLLOW)}catch(n){if(q(n))return null;throw n}try{if(!F(r).isFile())return null;const n=Buffer.alloc(37),l=P(r,n,0,n.length,0),c=n.toString("utf8",0,l);return l===36&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(c)?c:null}finally{J(r)}}o(te,"brokerRelayGeneration");function ne(t,e){const r=x(t);if(!(e===null||!j(r)))try{W(r,E(r,$),e,{atomic:!0})}catch(n){C({level:"warn",event:"node.lifecycle.release_marker_failed",node_id:t,error:n})}}o(ne,"recordBrokerRelease");function re(t){return t.status==="done"&&t.intent==="parked"}o(re,"isParked");function Re(t){return re(t)&&t.lifecycle==="resident"&&t.final_report==null&&t.deleting_at==null}o(Re,"isParkedResident");function ye(t){return t?.intent==="idle-release"}o(ye,"hasIdleReleaseIntent");export{te as brokerRelayGeneration,ye as hasIdleReleaseIntent,re as isParked,Re as isParkedResident,ne as recordBrokerRelease,Oe as transition};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{getNode as y,cancelCronsOnWake as B,transitionStatusIntent as D}from"../canvas/index.js";import{closeSync as J,constants as N,existsSync as j,fstatSync as F,readSync as P}from"node:fs";import{join as E}from"node:path";import{BROKER_RELEASED_MARKER as $,BROKER_RELAY_GENERATION as M,nodeRunDir as x}from"../canvas/paths.js";import{openBeneath as T,writeFileBeneath as W,isAbsentOrRefused as q}from"../spaces/open-beneath.js";import{emitEvent as C}from"../events/emit.js";import{deleteSandboxOfEndedNode as K}from"./runner/delete-sandboxes.js";import{composeNodeOutcomeDocument as Y}from"./outcome-document.js";import{afterCommit as G,withCanvasWrite as z}from"../canvas/db.js";import{nodeObject as V}from"../graph/objects.js";import{endMessageSubscriptions as H}from"../graph/watches.js";import{settleNodeObjectWaits as Q}from"../canvas/waits.js";import{runStructuredRequestEffects as U,settlePendingStructuredRequestForNodeIn as X}from"../canvas/structured-requests.js";const p="*",Z={finish:"finished",park:"parked",cancel:"stranded",crash:"crashed","refresh-launch":null,revive:null},u=["active","idle"],I={finish:{status:"done",intent:"done",from:u},park:{status:"done",intent:"parked",from:u},cancel:{status:"canceled",intent:null,from:p},crash:{status:"dead",from:u},yield:{intent:"refresh",from:u},release:{status:"idle",intent:"idle-release",from:[...u,"done"]},"refresh-launch":{status:"active",intent:"refresh",from:p},revive:{status:"active",intent:null,from:p}};function v(t,e){const r=t.split(`
2
+ `)[0]??"";let n=0,l="";for(const c of r){const s=Buffer.byteLength(c,"utf8");if(n+s>e)break;n+=s,l+=c}return l}o(v,"firstLineAtMost");function ee(t){if(t===void 0)return null;const e=t.message===void 0?void 0:v(t.message,500),r={...t,...e===void 0?{}:{message:e}},n=JSON.stringify(r);return Buffer.byteLength(n,"utf8")<=4*1024?n:JSON.stringify({schema:"crtr.node-outcome-detail/v1",truncated:!0,...e===void 0?{}:{message:e}})}o(ee,"detailJson");function te(t,e){let r,n;return e==="finished"||e==="declined"?(r="done",n="done"):e==="parked"?(r="done",n="parked"):e==="closed"||e==="retired"||e==="stranded"||e==="deadline_exceeded"?(r="canceled",n=null):(r="dead",n=null),{...t,status:r,intent:n,terminal_reason:e}}o(te,"nodeAtOutcome");async function ye(t,e,r){const n=I[e],l=Object.prototype.hasOwnProperty.call(n,"status"),c=Object.prototype.hasOwnProperty.call(n,"intent"),s=r?.reason??Z[e],d={};l&&(d.status=n.status),c&&(d.intent=n.intent??null),s!==void 0&&(d.terminal_reason=s);const f=e==="finish"||e==="park"||e==="cancel"||e==="crash",_=f?new Date().toISOString():null,h=s,k=ee(r?.outcome?.detail),S=f?s==="deadline_exceeded"?{intended:"expired",failureReason:"node_deadline_exceeded",failureDetail:r?.outcome?.detail??null}:{intended:"failed",failureReason:s,failureDetail:r?.outcome?.detail??null}:null,O=await z(async i=>{const a=f?await y(t):null,w=f&&a?.kind!=="human",g=w&&a?.run_id!=null&&s!=="parked"&&a.outcome_at!==null&&(u.includes(a.status)||a.outcome_reason==="parked");let R;w&&a!==null&&(a.outcome_at===null||g)&&(R=JSON.stringify(await Y({node:te(a,h),outcome:{kind:"failure",reason:h,at:_,revision:(a.outcome_revision??0)+1,detailJson:k}})));const m=await D(t,d,{fromStatuses:n.from===p?void 0:n.from,requireNoFinalReport:e==="cancel",...w?{outcome:{kind:"failure",reason:h,detailJson:k,at:_,...g?{supersede:!0}:{},...R===void 0?{}:{documentJson:R}}}:{}});f&&m>0&&(await H(i,await V(i,t),"done"),await Q(i,t));const A=m===1&&S!==null?await X(i,t,S):null;if(m===1&&(e==="release"||e==="park"||e==="finish"||e==="cancel")){const b=ne(t);G(()=>re(t,b))}return{changes:m,settlement:A}});if(O.changes===0){const i=await y(t);if(i===null)throw new Error(`transition: unknown node ${t}`);if(e==="cancel"&&i.final_report!==null&&i.final_report!==void 0)return i;throw new Error(`illegal lifecycle transition: '${e}' from status='${i.status}' (node ${t})`)}return O.settlement?.changed&&U(O.settlement.row),(e==="finish"||e==="park"||e==="cancel")&&await B(t),(e==="finish"||e==="cancel"||e==="crash")&&K(t),await y(t)}o(ye,"transition");function ne(t){const e=x(t);let r;try{r=T(e,E(e,M),N.O_RDONLY|N.O_NOFOLLOW)}catch(n){if(q(n))return null;throw n}try{if(!F(r).isFile())return null;const n=Buffer.alloc(37),l=P(r,n,0,n.length,0),c=n.toString("utf8",0,l);return l===36&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(c)?c:null}finally{J(r)}}o(ne,"brokerRelayGeneration");function re(t,e){const r=x(t);if(!(e===null||!j(r)))try{W(r,E(r,$),e,{atomic:!0})}catch(n){C({level:"warn",event:"node.lifecycle.release_marker_failed",node_id:t,error:n})}}o(re,"recordBrokerRelease");function ie(t){return t.status==="done"&&t.intent==="parked"}o(ie,"isParked");function _e(t){return ie(t)&&t.lifecycle==="resident"&&t.final_report==null&&t.deleting_at==null}o(_e,"isParkedResident");function ke(t){return t?.intent==="idle-release"}o(ke,"hasIdleReleaseIntent");export{ne as brokerRelayGeneration,ke as hasIdleReleaseIntent,ie as isParked,_e as isParkedResident,re as recordBrokerRelease,ye as transition};
@@ -1,3 +1,3 @@
1
- var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as pe,abortExecution as F,endLiveExecution as he,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as xe,readGoal as x,readYieldMessage as Ee,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as mr}from"../command-hooks/transport/exec-lifecycle.js";async function dr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(dr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function hr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(hr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await hr(a)?{}:await dr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await Ee(e)===null&&!await xe(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const h=!k&&await a.reserveSlot(e);let o=null;if(h){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!h||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await a.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await he(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const h=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(h&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=h&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const E=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await vr(e,r,E,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(d.resumeSessionPath)?(await x(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await x(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
1
+ var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as he,recordExecutionPid as pe,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as mr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(hr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(a)?{}:await hr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.isClaimed(e))return await a.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await a.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await a.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof he)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,h=w?{}:await vr(e,r,x,!u),g=h.resumeSessionPath!==void 0,B=g&&h.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(h.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...h,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...h,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...h,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(E=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:E})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,dr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,hr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
@@ -5,6 +5,8 @@ export interface BlaxelConfig {
5
5
  /** Defaults to `https://api.blaxel.ai/v0`. */
6
6
  controlUrl?: string;
7
7
  fetch?: typeof fetch;
8
+ /** How long `createSandbox` waits for a sandbox being deleted to free its name. Default 60 s. */
9
+ deletingWaitMs?: number;
8
10
  }
9
11
  /** `BLAXEL_API_KEY`, `BLAXEL_WORKSPACE`, `BLAXEL_REGION` (H-1 names). Throws when one is missing. */
10
12
  export declare function blaxelConfigFromEnv(env?: NodeJS.ProcessEnv): BlaxelConfig;
@@ -32,6 +34,8 @@ export interface SandboxInfo {
32
34
  /** `RUNNING`, `STANDBY` (frozen), ...; reading it does not wake the sandbox. */
33
35
  state: string | null;
34
36
  status: string | null;
37
+ /** `spec.runtime.image`: an adopted sandbox keeps the image it was created with. */
38
+ image: string | null;
35
39
  }
36
40
  export type ProcessStatus = 'running' | 'completed' | 'failed' | 'killed' | 'stopped';
37
41
  export interface SandboxProcess {
@@ -1 +1 @@
1
- var $=Object.defineProperty;var p=(s,c)=>$(s,"name",{value:c,configurable:!0});function A(s=process.env){const c=p(n=>{const d=s[n];if(!d)throw new Error(`${n} is required for the Blaxel runner`);return d},"need");return{apiKey:c("BLAXEL_API_KEY"),workspace:c("BLAXEL_WORKSPACE"),region:c("BLAXEL_REGION")}}p(A,"blaxelConfigFromEnv");class w extends Error{static{p(this,"BlaxelApiError")}status;code;constructor(c,n,d){super(d),this.status=c,this.code=n,this.name="BlaxelApiError"}}const g=p(s=>s instanceof w&&s.status===404&&s.code==="WORKLOAD_UNAVAILABLE","isWorkloadUnavailable");function E(s){const c=s.metadata.url;if(!c)throw new Error(`Blaxel sandbox ${s.metadata.name} has no url`);return{name:s.metadata.name,url:c,state:s.state??null,status:s.status??null}}p(E,"toInfo");function y(s,c){const n=s??{},d=typeof n.error=="object"&&n.error!==null?n.error:{},i=typeof d.code=="string"?d.code:typeof n.code=="string"?n.code:null,l=[d.message,n.message,n.error].find(e=>typeof e=="string")??c.slice(0,300);return{code:i,message:l}}p(y,"errorFields");function T(s){const c=s.fetch??fetch,n=s.controlUrl??"https://api.blaxel.ai/v0",d=p(()=>({authorization:`Bearer ${s.apiKey}`,"x-blaxel-workspace":s.workspace,"content-type":"application/json"}),"headers");async function i(e,t,a,r=[]){const o=await c(e,{method:t,headers:d(),...a===void 0?{}:{body:JSON.stringify(a)}}),u=await o.text();let f=null;if(u!=="")try{f=JSON.parse(u)}catch{f={raw:u}}if(!o.ok){const{code:x,message:m}=y(f,u);if(o.status===404&&x==="WORKLOAD_UNAVAILABLE"||!r.includes(o.status))throw new w(o.status,x,`Blaxel ${t} ${e} failed (${o.status}): ${m}`)}return{status:o.status,json:f}}p(i,"call");const l=encodeURIComponent;return{config:s,async createSandbox(e){const t=[...e.ports??[]].map(u=>({name:u.name,target:u.target,protocol:"HTTP"})),a={metadata:{name:e.name},spec:{runtime:{image:e.image,memory:e.memoryMb,...t.length>0?{ports:t}:{}},region:s.region}},{status:r,json:o}=await i(`${n}/sandboxes`,"POST",a,[409]);if(r===409){const u=await this.getSandbox(e.name);if(u===null)throw new Error(`Blaxel sandbox ${e.name} reported as existing but cannot be read`);return{...u,created:!1}}return{...E(o),created:!0}},async getSandbox(e){const{status:t,json:a}=await i(`${n}/sandboxes/${l(e)}`,"GET",void 0,[404]);if(t===404)return null;const r=a;return r.status==="DELETING"||r.status==="TERMINATED"?null:E(r)},async deleteSandbox(e){await i(`${n}/sandboxes/${l(e)}`,"DELETE",void 0,[404])},async startProcess(e,t){const{json:a}=await i(`${e.url}/process`,"POST",t);return a},async getProcess(e,t){const{status:a,json:r}=await i(`${e.url}/process/${l(t)}`,"GET",void 0,[404]);return a===404?null:r},async stopProcess(e,t){await i(`${e.url}/process/${l(t)}`,"DELETE",void 0,[404])},async killProcess(e,t){await i(`${e.url}/process/${l(t)}/kill`,"DELETE",void 0,[404])},async exec(e,t,a,r,o){return await this.startProcess(e,{name:t,command:a,waitForCompletion:!0,timeout:r,...o?{env:o}:{}})},async putFile(e,t,a,r="0644"){await i(`${e.url}/filesystem/${t.replace(/^\/+/,"").split("/").map(l).join("/")}`,"PUT",{content:a,permissions:r})},async ensurePreview(e,t,a){const{json:r}=await i(`${n}/sandboxes/${l(e)}/previews`,"POST",{metadata:{name:t},spec:{port:a,public:!1}},[409]),o=r?.spec?.url;if(o)return o;const f=(await i(`${n}/sandboxes/${l(e)}/previews`,"GET")).json.find(x=>x.metadata.name===t);if(!f)throw new Error(`Blaxel preview ${t} of ${e} not found`);return f.spec.url},async createPreviewToken(e,t,a){const{json:r}=await i(`${n}/sandboxes/${l(e)}/previews/${l(t)}/tokens`,"POST",{spec:{expiresAt:a.toISOString()}}),o=r.spec;return{token:o.token,expiresAt:o.expiresAt}}}}p(T,"createBlaxelClient");export{w as BlaxelApiError,A as blaxelConfigFromEnv,T as createBlaxelClient,g as isWorkloadUnavailable};
1
+ var $=Object.defineProperty;var p=(t,i)=>$(t,"name",{value:i,configurable:!0});function b(t=process.env){const i=p(a=>{const u=t[a];if(!u)throw new Error(`${a} is required for the Blaxel runner`);return u},"need");return{apiKey:i("BLAXEL_API_KEY"),workspace:i("BLAXEL_WORKSPACE"),region:i("BLAXEL_REGION")}}p(b,"blaxelConfigFromEnv");class w extends Error{static{p(this,"BlaxelApiError")}status;code;constructor(i,a,u){super(u),this.status=i,this.code=a,this.name="BlaxelApiError"}}const A=p(t=>t instanceof w&&t.status===404&&t.code==="WORKLOAD_UNAVAILABLE","isWorkloadUnavailable");function x(t){const i=t.metadata.url;if(!i)throw new Error(`Blaxel sandbox ${t.metadata.name} has no url`);return{name:t.metadata.name,url:i,state:t.state??null,status:t.status??null,image:t.spec?.runtime?.image??null}}p(x,"toInfo");function y(t,i){const a=t??{},u=typeof a.error=="object"&&a.error!==null?a.error:{},c=typeof u.code=="string"?u.code:typeof a.code=="string"?a.code:null,l=[u.message,a.message,a.error].find(e=>typeof e=="string")??i.slice(0,300);return{code:c,message:l}}p(y,"errorFields");function T(t){const i=t.fetch??fetch,a=t.controlUrl??"https://api.blaxel.ai/v0",u=p(()=>({authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"}),"headers");async function c(e,s,o,r=[]){const n=await i(e,{method:s,headers:u(),...o===void 0?{}:{body:JSON.stringify(o)}}),f=await n.text();let d=null;if(f!=="")try{d=JSON.parse(f)}catch{d={raw:f}}if(!n.ok){const{code:m,message:E}=y(d,f);if(n.status===404&&m==="WORKLOAD_UNAVAILABLE"||!r.includes(n.status))throw new w(n.status,m,`Blaxel ${s} ${e} failed (${n.status}): ${E}`)}return{status:n.status,json:d}}p(c,"call");const l=encodeURIComponent;return{config:t,async createSandbox(e){const s=[...e.ports??[]].map(n=>({name:n.name,target:n.target,protocol:"HTTP"})),o={metadata:{name:e.name},spec:{runtime:{image:e.image,memory:e.memoryMb,...s.length>0?{ports:s}:{}},region:t.region,lifecycle:{expirationPolicies:[{type:"ttl-idle",value:"7d",action:"delete"}]}}},r=Date.now()+(t.deletingWaitMs??6e4);for(;;){const{status:n,json:f}=await c(`${a}/sandboxes`,"POST",o,[409]);if(n!==409)return{...x(f),created:!0};const d=await this.getSandbox(e.name);if(d!==null)return{...d,created:!1};if(Date.now()>=r)throw new Error(`Blaxel sandbox ${e.name} is still being deleted; its name did not free in time`);await new Promise(m=>setTimeout(m,1e3))}},async getSandbox(e){const{status:s,json:o}=await c(`${a}/sandboxes/${l(e)}`,"GET",void 0,[404]);if(s===404)return null;const r=o;return r.status==="DELETING"||r.status==="TERMINATED"?null:x(r)},async deleteSandbox(e){await c(`${a}/sandboxes/${l(e)}`,"DELETE",void 0,[404])},async startProcess(e,s){const{json:o}=await c(`${e.url}/process`,"POST",s);return o},async getProcess(e,s){const{status:o,json:r}=await c(`${e.url}/process/${l(s)}`,"GET",void 0,[404]);return o===404?null:r},async stopProcess(e,s){await c(`${e.url}/process/${l(s)}`,"DELETE",void 0,[404])},async killProcess(e,s){await c(`${e.url}/process/${l(s)}/kill`,"DELETE",void 0,[404])},async exec(e,s,o,r,n){return await this.startProcess(e,{name:s,command:o,waitForCompletion:!0,timeout:r,...n?{env:n}:{}})},async putFile(e,s,o,r="0644"){await c(`${e.url}/filesystem/${s.replace(/^\/+/,"").split("/").map(l).join("/")}`,"PUT",{content:o,permissions:r})},async ensurePreview(e,s,o){const{json:r}=await c(`${a}/sandboxes/${l(e)}/previews`,"POST",{metadata:{name:s},spec:{port:o,public:!1}},[409]),n=r?.spec?.url;if(n)return n;const d=(await c(`${a}/sandboxes/${l(e)}/previews`,"GET")).json.find(m=>m.metadata.name===s);if(!d)throw new Error(`Blaxel preview ${s} of ${e} not found`);return d.spec.url},async createPreviewToken(e,s,o){const{json:r}=await c(`${a}/sandboxes/${l(e)}/previews/${l(s)}/tokens`,"POST",{spec:{expiresAt:o.toISOString()}}),n=r.spec;return{token:n.token,expiresAt:n.expiresAt}}}}p(T,"createBlaxelClient");export{w as BlaxelApiError,b as blaxelConfigFromEnv,T as createBlaxelClient,A as isWorkloadUnavailable};
@@ -9,7 +9,8 @@ export declare const EXIT_NO_BROKER = 3;
9
9
  /** A failing start script prints a last line `crtr-sandbox-start: failed <reason>`; `status` reports the reason. */
10
10
  export declare const FAILURE_LINE: RegExp;
11
11
  export declare const brokerProcessName: (executionId: string) => string;
12
- export declare const sandboxNameFor: (execution: RunnerExecution) => string;
12
+ export declare const sandboxNameFor: (nodeId: string) => string;
13
+ export declare const cronProcessName: (runId: string) => string;
13
14
  /** What `start` needs from the control plane beyond the execution: the environment's image and size, the release object, the secrets. */
14
15
  export interface BlaxelLaunchContext {
15
16
  /** `environments.image_ref` for a recipe environment, else the release's own image (release-image.ts) when it was published with one, else `blaxel/base-image:latest`. */
@@ -30,8 +31,6 @@ export interface BlaxelRunnerDeps {
30
31
  mintToken?(input: RunnerStartInput): Promise<string>;
31
32
  /** The bootstrap script text passed as the process command (`scripts/sandbox-bootstrap.sh`). */
32
33
  bootstrap(): string;
33
- /** Sandbox names that belong to a node, for `delete`. Default: one per execution of the node (`sandboxNameFor`). */
34
- sandboxNamesForNode?(nodeId: string): Promise<string[]>;
35
34
  /** Seconds `stop` waits after SIGTERM before the kill. */
36
35
  stopGraceS?: number;
37
36
  }
@@ -1,3 +1,3 @@
1
- var $=Object.defineProperty;var i=(n,a)=>$(n,"name",{value:a,configurable:!0});import{openDb as k}from"../../../canvas/db.js";import{mintExecutionToken as S}from"../../../canvas/node-tokens.js";import{BlaxelApiError as T,isWorkloadUnavailable as m}from"./client.js";const f=4180,w="view",I="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",y=3,C=/^crtr-sandbox-start: failed (\S+)/m,h=2e3,p=i(n=>`broker-${n}`,"brokerProcessName"),d=i(n=>n.sandboxName??`${n.nodeId}-${n.attempt}`,"sandboxNameFor");async function A(n){const a=await(await k()).prepare("SELECT execution_id, attempt, sandbox_name FROM executions WHERE node_id = ? AND runner = 'blaxel'").all(n);return[...new Set(a.map(c=>d({executionId:c.execution_id,nodeId:n,attempt:Number(c.attempt),sandboxName:c.sandbox_name})))]}i(A,"defaultSandboxNames");function N(n){const a=`${n.logs}
2
- ${n.stderr}
3
- ${n.stdout}`,c=(n.stderr||n.logs||n.stdout||"").trim().slice(-h);return{state:"failed",reason:C.exec(a)?.[1]??"start_failed",code:n.exitCode,...c===""?{}:{output:c}}}i(N,"failureOf");function L(n){const{client:a}=n,c=(n.stopGraceS??10)*1e3,E=new Map;async function u(t){return await a.getSandbox(d(t))}i(u,"sandboxOf");async function g(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(c/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await a.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return i(g,"brokerGone"),{kind:"blaxel",async start(t){const r=await n.launchContext(t),e=d(t),o=await a.createSandbox({name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:w,target:f}]}),s=p(t.executionId);if((await a.getProcess(o,s))?.status==="running")return{pid:null,exited:null};await a.ensurePreview(e,w,f);const x=await(n.mintToken??(b=>S(b.executionId,b.nodeId)))(t),R={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:x,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await a.startProcess(o,{name:s,command:n.bootstrap(),env:R,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await u(t);if(r===null)return"no_broker";try{const e=await a.exec(r,`wake-${t.executionId}-${Date.now()}`,`${I} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===y)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(m(e))return"no_broker";throw e}},async stop(t,r){try{const e=await u(t);if(e===null)return{confirmed:!0};const o=p(t.executionId),s=i(async()=>(await a.getProcess(e,o))?.status==="running","running");if(await s()){await a.stopProcess(e,o);const l=Date.now()+c;for(;Date.now()<l&&await s();)await new Promise(x=>setTimeout(x,250));if(await s()&&await a.killProcess(e,o),await s())return{confirmed:!1}}return{confirmed:await g(e,t.executionId)}}catch(e){return m(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await u(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await a.getProcess(e,p(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?N(o):{state:"gone"}}catch(e){return m(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){for(const r of await(n.sandboxNamesForNode??A)(t))await a.deleteSandbox(r)},async deleteExecution(t){await a.deleteSandbox(d(t))},async viewerAddress(t){const r=d(t),e=E.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return _(e.url,e.token);const o=await a.ensurePreview(r,w,f),s=new Date(Date.now()+60*6e4),{token:l}=await a.createPreviewToken(r,w,s);return E.set(r,{url:o,token:l,expiresAt:s.getTime()}),_(o,l)},async sandboxState(t){return(await u(t))?.state??null}}}i(L,"createBlaxelRunner");function _(n,a){return{kind:"wss",url:`${n.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":a}}}i(_,"viewer");export{f as BROKER_VIEW_PORT,T as BlaxelApiError,y as EXIT_NO_BROKER,C as FAILURE_LINE,I as WAKE_COMMAND,p as brokerProcessName,L as createBlaxelRunner,d as sandboxNameFor};
1
+ var h=Object.defineProperty;var c=(a,n)=>h(a,"name",{value:n,configurable:!0});import{mintExecutionToken as S}from"../../../canvas/node-tokens.js";import{BlaxelApiError as P,isWorkloadUnavailable as R}from"./client.js";const b=4180,p="view",T="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",O=3,I=/^crtr-sandbox-start: failed (\S+)/m,A=2e3,E=c(a=>`broker-${a}`,"brokerProcessName"),l=c(a=>a,"sandboxNameFor"),_=c(a=>`cron-${a}`,"cronProcessName"),y=2e3,$="crtr",N="/opt/crtr/current/bin";function v(a){const n=`${a.logs}
2
+ ${a.stderr}
3
+ ${a.stdout}`,u=(a.stderr||a.logs||a.stdout||"").trim().slice(-A);return{state:"failed",reason:I.exec(n)?.[1]??"start_failed",code:a.exitCode,...u===""?{}:{output:u}}}c(v,"failureOf");function U(a){const{client:n}=a,u=(a.stopGraceS??10)*1e3,f=new Map;async function x(t){return await n.getSandbox(l(t.nodeId))}c(x,"sandboxOf");async function k(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(u/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await n.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return c(k,"brokerGone"),{kind:"blaxel",async start(t){const r=await a.launchContext(t),e=l(t.nodeId),o={name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:p,target:b}]};let i=await n.createSandbox(o);i.image!==r.image&&(await n.deleteSandbox(e),f.delete(e),i=await n.createSandbox(o));const d=E(t.executionId);if((await n.getProcess(i,d))?.status==="running")return{pid:null,exited:null};await n.ensurePreview(e,p,b);const g=await(a.mintToken??(m=>S(m.executionId,m.nodeId)))(t),w={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:g,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await n.startProcess(i,{name:d,command:a.bootstrap(),env:w,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await x(t);if(r===null)return"no_broker";try{const e=await n.exec(r,`wake-${t.executionId}-${Date.now()}`,`${T} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===O)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(R(e))return"no_broker";throw e}},async stop(t,r){try{const e=await x(t);if(e===null)return{confirmed:!0};const o=E(t.executionId),i=c(async()=>(await n.getProcess(e,o))?.status==="running","running");if(await i()){await n.stopProcess(e,o);const d=Date.now()+u;for(;Date.now()<d&&await i();)await new Promise(s=>setTimeout(s,250));if(await i()&&await n.killProcess(e,o),await i())return{confirmed:!1}}return{confirmed:await k(e,t.executionId)}}catch(e){return R(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await x(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await n.getProcess(e,E(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?v(o):{state:"gone"}}catch(e){return R(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){await n.deleteSandbox(l(t)),f.delete(l(t))},async viewerAddress(t){const r=l(t.nodeId),e=f.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return C(e.url,e.token);const o=await n.ensurePreview(r,p,b),i=new Date(Date.now()+60*6e4),{token:d}=await n.createPreviewToken(r,p,i);return f.set(r,{url:o,token:d,expiresAt:i.getTime()}),C(o,d)},async cronRun(t,r){const e=await n.getSandbox(l(t));if(e===null)throw new Error(`node ${t} has no sandbox, so the cron cannot run; the scheduler never starts a node to get one`);const o=_(r.runId),i=`exec nsenter -S "$(id -u ${$})" -G "$(id -g ${$})" bash -c "$CRTR_CRON_COMMAND"`,d={...r.env,CRTR_CRON_COMMAND:r.command,PATH:`${N}:/usr/local/bin:/usr/bin:/bin`};let s=await n.getProcess(e,o)??await n.startProcess(e,{name:o,command:i,workingDir:r.cwd,env:d,waitForCompletion:!1});const g=r.startedAtMs+r.timeoutS*1e3;for(;s.status==="running";){if(Date.now()>=g)return await n.killProcess(e,o),{exitCode:null,timedOut:!0,stdout:s.stdout,stderr:s.stderr};await new Promise(m=>setTimeout(m,y));let w;try{w=await n.getProcess(e,o)}catch{continue}if(w===null)return{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} is gone from the sandbox, so its outcome is unknown`};s=w}return s.status==="completed"||s.status==="failed"?{exitCode:s.exitCode,timedOut:!1,stdout:s.stdout,stderr:s.stderr}:{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} was ${s.status} from outside the run`}},async cronCancel(t,r){const e=await n.getSandbox(l(t));e!==null&&await n.killProcess(e,_(r))},async sandboxState(t){return(await x(t))?.state??null}}}c(U,"createBlaxelRunner");function C(a,n){return{kind:"wss",url:`${a.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":n}}}c(C,"viewer");export{b as BROKER_VIEW_PORT,P as BlaxelApiError,O as EXIT_NO_BROKER,I as FAILURE_LINE,T as WAKE_COMMAND,E as brokerProcessName,U as createBlaxelRunner,_ as cronProcessName,l as sandboxNameFor};
@@ -1,3 +1,8 @@
1
1
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
2
2
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
3
3
  export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
4
+ /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
5
+ * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
6
+ * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
7
+ * takes, so no new execution can start in the sandbox between them. */
8
+ export declare function deleteSandboxOfEndedNode(nodeId: string): void;
@@ -1 +1,6 @@
1
- var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{openDb as c}from"../../canvas/db.js";import{emitEvent as d}from"../../events/emit.js";async function u(e){if(e.length===0)return[];const t=e.map(()=>"?").join(","),a=await(await c()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${t})`).all(...e),r=[];for(const{node_id:o}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(o)}catch(i){r.push(o),d({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:o,error:i})}return r}n(u,"deleteNodeSandboxes");export{u as deleteNodeSandboxes};
1
+ var c=Object.defineProperty;var o=(e,n)=>c(e,"name",{value:n,configurable:!0});import{afterCommit as E,openDb as l,withCanvasWrite as s}from"../../canvas/db.js";import{emitEvent as i}from"../../events/emit.js";async function S(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),a=await(await l()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${n})`).all(...e),d=[];for(const{node_id:t}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(t)}catch(r){d.push(t),i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return d}o(S,"deleteNodeSandboxes");function _(e){E(()=>{s(async n=>{await n.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
2
+ AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
3
+ AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
4
+ AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
5
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
6
+ FOR UPDATE OF n`).get(e)!==void 0&&await(await import("./index.js")).runnerForExecution("blaxel").delete(e)}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(_,"deleteSandboxOfEndedNode");export{S as deleteNodeSandboxes,_ as deleteSandboxOfEndedNode};
@@ -3,7 +3,7 @@ export type RunnerKind = 'process' | 'blaxel' | 'machine';
3
3
  export interface RunnerExecution {
4
4
  executionId: string;
5
5
  nodeId: string;
6
- /** `executions.attempt`, the sandbox name suffix. */
6
+ /** `executions.attempt`. */
7
7
  attempt: number;
8
8
  /** `executions.sandbox_name`, null for the process runner. */
9
9
  sandboxName: string | null;
@@ -101,10 +101,26 @@ export interface Runner {
101
101
  status(execution: RunnerExecution, options?: RunnerStatusOptions): Promise<RunnerStatus>;
102
102
  /** Remove everything the runner holds for the node: the run dir (process) or the sandbox (Blaxel). */
103
103
  delete(nodeId: string): Promise<void>;
104
- /** Remove only what one failed execution created (the Blaxel sandbox `<node id>-<attempt>`), where each attempt has its own. */
105
- deleteExecution?(execution: RunnerExecution): Promise<void>;
106
104
  /** Where a viewer reaches this execution's broker. */
107
105
  viewerAddress(execution: RunnerExecution): Promise<RunnerViewerAddress>;
106
+ /** Blaxel only: run a cron fire's command to completion in the node's sandbox, as process `cron-<run id>`. A repeat for the same run id
107
+ * reads that process instead of starting another. Throws when the node has no sandbox. `error` says why there is no exit code. */
108
+ cronRun?(nodeId: string, run: {
109
+ runId: string;
110
+ command: string;
111
+ cwd: string;
112
+ env: Record<string, string>;
113
+ timeoutS: number;
114
+ startedAtMs: number;
115
+ }): Promise<{
116
+ exitCode: number | null;
117
+ timedOut: boolean;
118
+ stdout: string;
119
+ stderr: string;
120
+ error?: string;
121
+ }>;
122
+ /** Blaxel only: kill the process of that run id; no sandbox or no process is not an error. */
123
+ cronCancel?(nodeId: string, runId: string): Promise<void>;
108
124
  }
109
125
  /** The runner for an environment kind: `machine` → process, `blaxel` → Blaxel. */
110
126
  export type RunnerForKind = (kind: 'machine' | 'blaxel') => Runner;
@@ -1,4 +1,4 @@
1
- var Y=Object.defineProperty;var u=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{mkdtempSync as Z,rmSync as V,writeFileSync as ee}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ne,encodeAttachControlInput as q,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as G}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as h}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"literal-input",input:q("crtr.attach.reload-viewer")}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(h).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function j(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${h(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${h(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${h(`${r} >/dev/null 2>&1`)}`}}u(j,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${h(t)}`}}u(de,"directCommand");function z(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${h(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${h(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${h(n)}`}}case"command":return j(e.run);case"direct":return de(e.run);case"popup":return j(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(z,"menuActionCommand");function me(e){return z(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function F(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(F,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=F(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=F(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function K(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:q(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(K,"resolvedMenuActions");function R(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(R,"menuItems");function Pe(e){const n=e??G().bindings;return N(" crtr ",R(n,K(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
1
+ var Y=Object.defineProperty;var u=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{mkdtempSync as Z,rmSync as V,writeFileSync as ee}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ne,encodeAttachControlInput as q,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as G}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as k}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"literal-input",input:q("crtr.attach.reload-viewer")}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(k).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function j(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${k(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${k(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${k(`${r} >/dev/null 2>&1`)}`}}u(j,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${k(t)}`}}u(de,"directCommand");function z(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${k(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${k(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${k(n)}`}}case"command":return j(e.run);case"direct":return de(e.run);case"popup":return j(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(z,"menuActionCommand");function me(e){return z(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function F(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(F,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=F(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=F(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function K(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:q(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(K,"resolvedMenuActions");function R(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(R,"menuItems");function Pe(e){const n=e??G().bindings;return N(" crtr ",R(n,K(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
2
2
  `).find(r=>{const s=B(r);return s?.table===e&&s.key===n})??null:null}u($,"bindingAt");function Le(e){const n=f(["list-keys","-T",p]);if(!n.ok)return[];const t=new Set(n.stdout.split(`
3
- `).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function W(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(W,"isInstalledPair");function ke(e){if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.bindingId=="string"&&ne.has(n.bindingId)&&typeof n.gesture=="string"&&typeof n.key=="string"&&(typeof n.original=="string"||n.original===null)&&typeof n.wrapper=="string"&&(n.state==="owned"||n.state==="relinquished")}u(ke,"isWrappedRootBinding");function he(){const e=f(["show-options","-s","-q",A]);if(!e.ok)return null;if(e.stdout==="")return{pairs:[],wrappers:[]};const n=f(["show-options","-s","-qv",A]);if(!n.ok)return null;try{const t=JSON.parse(n.stdout);if(Array.isArray(t))return t.every(W)?{pairs:t,wrappers:[]}:null;if(typeof t!="object"||t===null)return null;const r=t;return!Array.isArray(r.pairs)||!r.pairs.every(W)||!Array.isArray(r.wrappers)||!r.wrappers.every(ke)?null:{pairs:r.pairs,wrappers:r.wrappers}}catch{return null}}u(he,"readManifest");function X(e){return f(["set-option","-s",A,JSON.stringify(e)])}u(X,"writeManifest");function C(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;")}u(C,"tmuxKeyArgument");function xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/;/g,"\\;")}"`}u(xe,"tmuxCommandToken");function ye(e){let n=null,t="";for(let r=0;r<e.length;r+=1){const s=e[r];if(n===null&&(s==="'"||s==='"')){n=s,t+=s;continue}if(n===s){n=null,t+=s;continue}if(s==="\\"&&r+1<e.length){const o=e[r+1];n===null&&o===";"?t+=";":t+=s+o,r+=1;continue}t+=s}return t}u(ye,"bindingCommandForBranch");function be(e){const n=Z(M(O(),"crtr-tmux-binding-")),t=M(n,"binding.conf");try{return ee(t,`${e}
4
- `,"utf8"),f(["source-file",t])}finally{V(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function H(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(H,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?G():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=he();if(l===null)return o.push({code:"tmux-error",message:`tmux is unavailable or ${A} is malformed`}),{ok:!1,installed:c,diagnostics:o};const x=new Map;for(const i of s){const a=_.find(d=>d.id===i);if(!(a===void 0||!re(a))){for(const d of r.gestures(i))if(!d.includes(" > "))for(const m of v(d))x.has(m)||x.set(m,{bindingId:i,gesture:d})}}const w=new Set,I=[];for(const i of l.wrappers){const a=x.get(i.key),d=$(p,i.key);if(d!==null&&d===i.original)continue;if(i.state==="relinquished"||d!==i.wrapper){w.add(i.key),a!==void 0&&I.push({...i,...a,state:"relinquished"});continue}const m=H(i);m.ok||(w.add(i.key),I.push(i),o.push({code:"tmux-error",bindingId:i.bindingId,gesture:i.gesture,message:`could not restore tmux binding ${p}:${i.key}: ${m.stderr}`}))}for(const i of l.pairs){if(i.table===p&&w.has(i.key))continue;const a=f(["unbind-key","-T",i.table,C(i.key)]);!a.ok&&$(i.table,i.key)!==null&&o.push({code:"tmux-error",message:`could not remove crouter binding ${i.table}:${i.key}: ${a.stderr}`})}if(o.some(i=>i.code==="tmux-error")){const i=X({pairs:l.pairs,wrappers:I});return i.ok||o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${i.stderr}`}),{ok:!1,installed:c,diagnostics:o}}const E=u((i,a,d,m,k)=>{if($(i,a)!==null)return o.push({code:"occupied",bindingId:m,gesture:k,message:`${i}:${a} is already bound by tmux; ${m} was not installed`}),!1;const g=f(["bind-key","-T",i,C(a),...d]);return g.ok?(c.push({table:i,key:a}),!0):(o.push({code:"tmux-error",bindingId:m,gesture:k,message:`could not install ${m}: ${g.stderr}`}),!1)},"install"),P=K(r),J=N(" crtr ",R(r,P));for(const i of r.gestures("crtr.tmux.menu.open"))for(const a of v(i))E(p,a,J,"crtr.tmux.menu.open",i);for(const i of _){if(i.pair?.field!=="menu")continue;const a=_.find(y=>y.id===i.pair?.pairedId);if(a?.pair?.field!=="global")continue;const d=i.id,m=a.id,k=P.get(d),g=k===void 0?null:z(k.action);if(g===null)throw new Error(`no direct tmux action for paired menu binding ${d}`);for(const y of r.gestures(m))for(const Q of v(y))E(p,Q,g.argv,m,y)}for(const i of["crtr.tmux.node.next","crtr.tmux.node.previous","crtr.tmux.inbox.toggle"])for(const a of r.gestures(i))for(const d of v(a))E(p,d,ve(i),i,a);const L=[];for(const[i,a]of x){if(w.has(i))continue;const d=$(p,i);if(d===null)continue;const m=B(d);if(m===null||m.command===""){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not parse occupied tmux binding ${p}:${i}`});continue}const k=f(["bind-key",...m.repeat?["-r"]:[],"-T",p,C(i),"if-shell","-F","#{!=:#{@crtr_attach},}",`send-keys ${xe(i)}`,ye(m.command)]);if(!k.ok){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not wrap ${p}:${i}: ${k.stderr}`});continue}const g=$(p,i);if(g===null||!g.includes("@crtr_attach")){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not fingerprint wrapped tmux binding ${p}:${i}`});continue}const y={...a,key:i,original:d,wrapper:g,state:"owned"};I.push(y),L.push(y)}const D=X({pairs:c,wrappers:I});if(!D.ok){o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${D.stderr}`});for(const i of L)$(p,i.key)===i.wrapper&&H(i)}return{ok:o.every(i=>i.code!=="tmux-error"),installed:c,diagnostics:o}}u(Ie,"reconcileTmuxBindings");export{Pe as crouterMenuTmuxArgs,we as inboxToggleTmuxCommand,De as installTmuxBindings,Le as occupiedTmuxRootGestures};
3
+ `).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function W(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(W,"isInstalledPair");function he(e){if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.bindingId=="string"&&ne.has(n.bindingId)&&typeof n.gesture=="string"&&typeof n.key=="string"&&(typeof n.original=="string"||n.original===null)&&typeof n.wrapper=="string"&&(n.state==="owned"||n.state==="relinquished")}u(he,"isWrappedRootBinding");function ke(){const e=f(["show-options","-s","-q",A]);if(!e.ok)return null;if(e.stdout==="")return{pairs:[],wrappers:[]};const n=f(["show-options","-s","-qv",A]);if(!n.ok)return null;try{const t=JSON.parse(n.stdout);if(Array.isArray(t))return t.every(W)?{pairs:t,wrappers:[]}:null;if(typeof t!="object"||t===null)return null;const r=t;return!Array.isArray(r.pairs)||!r.pairs.every(W)||!Array.isArray(r.wrappers)||!r.wrappers.every(he)?null:{pairs:r.pairs,wrappers:r.wrappers}}catch{return null}}u(ke,"readManifest");function X(e){return f(["set-option","-s",A,JSON.stringify(e)])}u(X,"writeManifest");function C(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;")}u(C,"tmuxKeyArgument");function xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/;/g,"\\;")}"`}u(xe,"tmuxCommandToken");function ye(e){let n=null,t="";for(let r=0;r<e.length;r+=1){const s=e[r];if(n===null&&(s==="'"||s==='"')){n=s,t+=s;continue}if(n===s){n=null,t+=s;continue}if(s==="\\"&&r+1<e.length){const o=e[r+1];n===null&&o===";"?t+=";":t+=s+o,r+=1;continue}t+=s}return t}u(ye,"bindingCommandForBranch");function be(e){const n=Z(M(O(),"crtr-tmux-binding-")),t=M(n,"binding.conf");try{return ee(t,`${e}
4
+ `,"utf8"),f(["source-file",t])}finally{V(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function H(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(H,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?G():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=ke();if(l===null)return o.push({code:"tmux-error",message:`tmux is unavailable or ${A} is malformed`}),{ok:!1,installed:c,diagnostics:o};const x=new Map;for(const i of s){const a=_.find(d=>d.id===i);if(!(a===void 0||!re(a))){for(const d of r.gestures(i))if(!d.includes(" > "))for(const m of v(d))x.has(m)||x.set(m,{bindingId:i,gesture:d})}}const w=new Set,I=[];for(const i of l.wrappers){const a=x.get(i.key),d=$(p,i.key);if(d!==null&&d===i.original)continue;if(i.state==="relinquished"||d!==i.wrapper){w.add(i.key),a!==void 0&&I.push({...i,...a,state:"relinquished"});continue}const m=H(i);m.ok||(w.add(i.key),I.push(i),o.push({code:"tmux-error",bindingId:i.bindingId,gesture:i.gesture,message:`could not restore tmux binding ${p}:${i.key}: ${m.stderr}`}))}for(const i of l.pairs){if(i.table===p&&w.has(i.key))continue;const a=f(["unbind-key","-T",i.table,C(i.key)]);!a.ok&&$(i.table,i.key)!==null&&o.push({code:"tmux-error",message:`could not remove crouter binding ${i.table}:${i.key}: ${a.stderr}`})}if(o.some(i=>i.code==="tmux-error")){const i=X({pairs:l.pairs,wrappers:I});return i.ok||o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${i.stderr}`}),{ok:!1,installed:c,diagnostics:o}}const E=u((i,a,d,m,h)=>{if($(i,a)!==null)return o.push({code:"occupied",bindingId:m,gesture:h,message:`${i}:${a} is already bound by tmux; ${m} was not installed`}),!1;const g=f(["bind-key","-T",i,C(a),...d]);return g.ok?(c.push({table:i,key:a}),!0):(o.push({code:"tmux-error",bindingId:m,gesture:h,message:`could not install ${m}: ${g.stderr}`}),!1)},"install"),P=K(r),J=N(" crtr ",R(r,P));for(const i of r.gestures("crtr.tmux.menu.open"))for(const a of v(i))E(p,a,J,"crtr.tmux.menu.open",i);for(const i of _){if(i.pair?.field!=="menu")continue;const a=_.find(y=>y.id===i.pair?.pairedId);if(a?.pair?.field!=="global")continue;const d=i.id,m=a.id,h=P.get(d),g=h===void 0?null:z(h.action);if(g===null)throw new Error(`no direct tmux action for paired menu binding ${d}`);for(const y of r.gestures(m))for(const Q of v(y))E(p,Q,g.argv,m,y)}for(const i of["crtr.tmux.node.next","crtr.tmux.node.previous","crtr.tmux.inbox.toggle"])for(const a of r.gestures(i))for(const d of v(a))E(p,d,ve(i),i,a);const L=[];for(const[i,a]of x){if(w.has(i))continue;const d=$(p,i);if(d===null)continue;const m=B(d);if(m===null||m.command===""){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not parse occupied tmux binding ${p}:${i}`});continue}const h=f(["bind-key",...m.repeat?["-r"]:[],"-T",p,C(i),"if-shell","-F","#{!=:#{@crtr_attach},}",`send-keys ${xe(i)}`,ye(m.command)]);if(!h.ok){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not wrap ${p}:${i}: ${h.stderr}`});continue}const g=$(p,i);if(g===null||!g.includes("@crtr_attach")){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not fingerprint wrapped tmux binding ${p}:${i}`});continue}const y={...a,key:i,original:d,wrapper:g,state:"owned"};I.push(y),L.push(y)}const D=X({pairs:c,wrappers:I});if(!D.ok){o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${D.stderr}`});for(const i of L)$(p,i.key)===i.wrapper&&H(i)}return{ok:o.every(i=>i.code!=="tmux-error"),installed:c,diagnostics:o}}u(Ie,"reconcileTmuxBindings");export{Pe as crouterMenuTmuxArgs,we as inboxToggleTmuxCommand,De as installTmuxBindings,Le as occupiedTmuxRootGestures};
@@ -15,6 +15,11 @@ export declare const REMOTE_ATTACH_HEARTBEAT_MS = 25000;
15
15
  * quiet attach is a normal close the remote peer re-attaches from, and real work
16
16
  * is anchored by its own keep-alive, not by this ping.
17
17
  *
18
+ * A broker on a machine (`address.kind === 'machine'`, a Mac) is the exception:
19
+ * there is no sandbox to suspend, and the network route closes a silent
20
+ * connection about 125s after the last ping, which disconnects an idle viewer.
21
+ * Its heartbeat never goes quiet and pings for as long as the viewer is attached.
22
+ *
18
23
  * The clock starts when the attach OPENS, not at its first relayed frame: a
19
24
  * never-relaying attach still gets pings until this window elapses. The welcome
20
25
  * frame lands in milliseconds, so this only pads the tail of the very first