@north-light/cli 0.3.694 → 0.3.696

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 (189) hide show
  1. package/README.md +4 -7
  2. package/dist/api/command-manifest/result.d.ts +5 -5
  3. package/dist/api/command-manifest/result.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -0
  7. package/dist/api/dto/run-events.js +1 -0
  8. package/dist/api/dto/worktree.d.ts +0 -4
  9. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  10. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  11. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  12. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  14. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  15. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  16. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  17. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  18. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  19. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  20. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  21. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  22. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  23. package/dist/clients/attach/session/connection.d.ts +11 -2
  24. package/dist/clients/attach/session/connection.js +1 -1
  25. package/dist/clients/attach/session/keys.d.ts +2 -0
  26. package/dist/clients/attach/session/keys.js +1 -1
  27. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  28. package/dist/clients/attach/session/reconnect.js +1 -1
  29. package/dist/clients/attach/viewer.js +539 -538
  30. package/dist/commands/node-worktree.js +1 -1
  31. package/dist/commands/surface/node/placement.d.ts +2 -2
  32. package/dist/commands/surface/node/placement.js +1 -1
  33. package/dist/commands/surface.js +1 -1
  34. package/dist/core/broker-client/client.d.ts +6 -9
  35. package/dist/core/broker-client/client.js +1 -1
  36. package/dist/core/broker-client/transport-relay.d.ts +12 -1
  37. package/dist/core/broker-client/transport-relay.js +1 -1
  38. package/dist/core/canvas/canvas.js +5 -5
  39. package/dist/core/canvas/types.d.ts +0 -2
  40. package/dist/core/conversation-store/row-store.js +10 -10
  41. package/dist/core/graph/names.js +9 -9
  42. package/dist/core/keybindings/attach-control.d.ts +3 -0
  43. package/dist/core/keybindings/attach-control.js +1 -1
  44. package/dist/core/keybindings/catalog.js +1 -1
  45. package/dist/core/ledger/chunks.d.ts +3 -1
  46. package/dist/core/ledger/chunks.js +2 -2
  47. package/dist/core/ledger/index.d.ts +1 -1
  48. package/dist/core/ledger/index.js +1 -1
  49. package/dist/core/ledger/read.d.ts +4 -0
  50. package/dist/core/ledger/read.js +2 -2
  51. package/dist/core/llm/run.js +2 -2
  52. package/dist/core/logged-step-timings.d.ts +7 -0
  53. package/dist/core/logged-step-timings.js +1 -0
  54. package/dist/core/permissions/evaluator.d.ts +2 -1
  55. package/dist/core/permissions/evaluator.js +2 -2
  56. package/dist/core/providers/receipts.js +1 -1
  57. package/dist/core/runs/operations.js +8 -8
  58. package/dist/core/runtime/broker/model-adapter.js +3 -3
  59. package/dist/core/runtime/broker.js +1 -1
  60. package/dist/core/runtime/nodes.d.ts +1 -1
  61. package/dist/core/runtime/nodes.js +1 -1
  62. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  63. package/dist/core/runtime/placement-tmux.js +1 -1
  64. package/dist/core/runtime/revive.js +2 -2
  65. package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
  66. package/dist/core/runtime/runner/machine/executor.js +1 -1
  67. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  68. package/dist/core/runtime/runner/machine/ops.d.ts +7 -13
  69. package/dist/core/runtime/runner/machine/ops.js +1 -1
  70. package/dist/core/runtime/runner/machine/runner.d.ts +3 -2
  71. package/dist/core/runtime/runner/machine/runner.js +1 -1
  72. package/dist/core/runtime/tmux-bindings.js +3 -3
  73. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  74. package/dist/core/runtime/tmux-driver.js +6 -6
  75. package/dist/core/step-timings.d.ts +7 -1
  76. package/dist/core/step-timings.js +1 -1
  77. package/dist/core/worktree-close.js +4 -6
  78. package/dist/core/worktree-landing.d.ts +0 -38
  79. package/dist/core/worktree-landing.js +2 -3
  80. package/dist/core/worktree-sweep.d.ts +0 -1
  81. package/dist/core/worktree-sweep.js +4 -6
  82. package/dist/core/worktree.d.ts +0 -4
  83. package/dist/core/worktree.js +13 -15
  84. package/dist/daemon/api/app-listener.d.ts +1 -0
  85. package/dist/daemon/api/app-listener.js +10 -10
  86. package/dist/daemon/api/bridge.js +5 -5
  87. package/dist/daemon/api/handlers/attach.js +1 -1
  88. package/dist/daemon/api/handlers/conversations.js +3 -3
  89. package/dist/daemon/api/server.d.ts +1 -1
  90. package/dist/daemon/api/server.js +1 -1
  91. package/dist/daemon/cron/armed-context.js +1 -1
  92. package/dist/daemon/crtrd.js +20 -18
  93. package/dist/daemon/machine-daemon.js +1 -1
  94. package/dist/daemon/machine-link/client.d.ts +7 -1
  95. package/dist/daemon/machine-link/client.js +1 -1
  96. package/dist/daemon/machine-link/forward.d.ts +2 -4
  97. package/dist/daemon/machine-link/forward.js +1 -1
  98. package/dist/daemon/machine-link/holder.js +5 -5
  99. package/dist/daemon/pidfile.js +2 -1
  100. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  101. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  102. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
  104. package/dist/daemon/runs/append-section.js +2 -2
  105. package/dist/daemon/runs/observer.js +3 -3
  106. package/docs/apps/guides/stream-a-run.md +6 -7
  107. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  108. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  109. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  110. package/docs/concepts/scopes-and-trust.md +1 -1
  111. package/docs/concepts/why-a-daemon.md +1 -1
  112. package/docs/sdk/README.md +13 -41
  113. package/docs/sdk/client.md +5 -7
  114. package/docs/sdk/docker.md +1 -1
  115. package/docs/sdk/errors.md +3 -43
  116. package/docs/sdk/getting-started.md +11 -83
  117. package/docs/sdk/release-notes.md +10 -0
  118. package/docs/sdk/resources.md +11 -44
  119. package/package.json +3 -3
  120. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  121. package/packages/crouter-api/dist/api/contract.js +1 -1
  122. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  123. package/packages/crouter-api/dist/clients/attach/session/connection.js +73 -25
  124. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  125. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  126. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  127. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  128. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  129. package/packages/crouter-api/dist/commands/surface.js +2 -3
  130. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  131. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
  132. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
  133. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  134. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  135. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  136. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  137. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  138. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  139. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  140. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  141. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  142. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  143. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  144. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  145. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  146. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  147. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  148. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  149. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  150. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +14 -32
  151. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  152. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  153. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  154. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  155. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  156. package/packages/crouter-api/dist/core/worktree.js +9 -74
  157. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  158. package/packages/crouter-api/dist/daemon/machine-link/forward.js +22 -10
  159. package/packages/crouter-api/dist/daemon/machine-link/holder.js +7 -0
  160. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  161. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  162. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  163. package/packages/crouter-api/package.json +1 -1
  164. package/packages/crouter-identity/package.json +1 -1
  165. package/packages/crouter-plugin/dist/serve.js +1 -1
  166. package/packages/crouter-plugin/package.json +3 -3
  167. package/runtime.lock.json +14 -14
  168. package/scripts/self-update.mjs +7 -3
  169. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  170. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  171. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  172. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  173. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  174. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  175. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  176. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  177. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  178. package/dist/commands/surface-reload.d.ts +0 -7
  179. package/dist/commands/surface-reload.js +0 -1
  180. package/docs/sdk/bash.md +0 -39
  181. package/docs/sdk/files.md +0 -49
  182. package/docs/sdk/guides/README.md +0 -17
  183. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  184. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  185. package/docs/sdk/guides/human-approval.md +0 -24
  186. package/docs/sdk/guides/typed-extraction.md +0 -24
  187. package/docs/sdk/nodes.md +0 -194
  188. package/docs/sdk/streaming.md +0 -149
  189. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -42,6 +42,7 @@ export function installGlobalKeys(ctx, hooks) {
42
42
  'crtr.attach.profile-files': hooks.openProfileFiles,
43
43
  'crtr.attach.search': hooks.openSearch,
44
44
  'crtr.attach.whip': hooks.whip,
45
+ 'crtr.attach.reload-viewer': hooks.reloadViewer,
45
46
  };
46
47
  return tui.addInputListener((data) => {
47
48
  // Terminal focus reporting (DECSET 1004, enabled after tui.start; tmux forwards it per-pane with `focus-events on`). Pane focus drives the editor's fake cursor — solid block focused, hollow outline blurred — so a wall of attach panes shows exactly which one keys go to. The events are stripped rather than blanket-consumed in case the chunk coalesced them with real keystrokes.
@@ -17,9 +17,8 @@ export function createReconnect(ctx, hooks) {
17
17
  let lastSocketError;
18
18
  let reconnecting = false;
19
19
  let viewerDormant = hooks.initialDormant === true;
20
- // Captured at give-up: a terminal `done` is a CLEAN finalize — the viewer
21
- // closes its pane instead of freezing a scary "broker gone" corpse.
22
- // `dead`/`canceled` keep the corpse.
20
+ // Captured at give-up: a finished node closes its pane; a deleted one keeps
21
+ // the "broker gone" corpse.
23
22
  let finalizedDone = false;
24
23
  let stopped = false;
25
24
  let resolveStopped = () => { };
@@ -63,9 +62,8 @@ export function createReconnect(ctx, hooks) {
63
62
  term: { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 },
64
63
  });
65
64
  };
66
- // On close we HOLD the pane and keep re-dialing for as long as the canvas
67
- // source says the node can come back, giving up ONLY when it is genuinely
68
- // terminal (done/dead/canceled or row reaped). There is deliberately NO
65
+ // On close we HOLD the pane and keep re-dialing until the node is deleted or
66
+ // finished with a final report (`reconnectShouldGiveUp`). There is deliberately NO
69
67
  // wall-clock give-up: a fixed deadline races the daemon's legitimate relaunch
70
68
  // latency (a slow supervision tick on a big canvas, the 20s crash-revive
71
69
  // grace, a slow pi boot), and losing that race dumped the user to a shell
@@ -91,9 +89,10 @@ export function createReconnect(ctx, hooks) {
91
89
  row = undefined;
92
90
  }
93
91
  if (row !== undefined && reconnectShouldGiveUp(row)) {
94
- finalizedDone = row?.status === 'done'; // clean finalize vs dead/canceled
95
- break; // genuinely gone → clean close (done) or broker-gone corpse
92
+ finalizedDone = row !== null;
93
+ break;
96
94
  }
95
+ const deadOrCanceled = row?.status === 'dead' || row?.status === 'canceled';
97
96
  // A dormant node has NO broker until its next wake. We still track that
98
97
  // (the dormant flag routes a submitted prompt through the wake path
99
98
  // instead of a dead socket), but we DON'T shout about it: a parked pane
@@ -103,18 +102,15 @@ export function createReconnect(ctx, hooks) {
103
102
  // keep the reconnecting notice only for a transient broker relaunch.
104
103
  const dormant = row?.status === 'idle'
105
104
  || row?.intent === 'idle-release'
106
- || (row?.lifecycle === 'resident'
107
- && row.status === 'done'
108
- && row.intent === 'parked'
109
- && row.final_report == null);
105
+ || row?.status === 'done';
110
106
  const enteredDormancy = dormant && !viewerDormant;
111
107
  viewerDormant = dormant;
112
108
  if (enteredDormancy)
113
109
  hooks.onEnterDormancy();
114
- hooks.setNotice(dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
110
+ hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
115
111
  try {
116
112
  const redialed = await Promise.race([
117
- socket.redial({ brokerUnavailableIsExpected: dormant }).then(() => true),
113
+ socket.redial({ brokerUnavailableIsExpected: dormant || deadOrCanceled }).then(() => true),
118
114
  stoppedSignal.then(() => false),
119
115
  ]);
120
116
  if (!redialed || stopped || hooks.isTornDown())
@@ -126,7 +122,7 @@ export function createReconnect(ctx, hooks) {
126
122
  }
127
123
  catch {
128
124
  // ENOENT (socket not recreated yet) / ECONNREFUSED (listen not ready) → retry.
129
- const elapsed = await waitForRetry(dormant ? RECONNECT_DORMANT_DELAY_MS : Math.min(delay, RECONNECT_ACTIVE_DELAY_CAP_MS));
125
+ const elapsed = await waitForRetry(dormant || deadOrCanceled ? RECONNECT_DORMANT_DELAY_MS : Math.min(delay, RECONNECT_ACTIVE_DELAY_CAP_MS));
130
126
  if (!elapsed)
131
127
  return;
132
128
  delay *= 2;
@@ -101,11 +101,11 @@ onConnected) {
101
101
  // read, native slash command, pane tag and lifecycle action gates on it,
102
102
  // and no collaborator may re-derive it.
103
103
  mark('viewer.connect_start', { node: nodeId });
104
- const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
105
- mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
106
- const { remote, canvasSource, meta, socket } = connection;
107
104
  const role = resolveHelloRole(observer);
108
105
  const clientId = randomUUID();
106
+ const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node, { role, clientId });
107
+ mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
108
+ const { remote, canvasSource, meta, socket } = connection;
109
109
  // 2. Theme + keybindings — pi's components throw "Theme not initialized"
110
110
  // otherwise. One KeybindingsManager feeds BOTH editor and input; the
111
111
  // editor may resolve a separate pi-tui instance, so mirror onto it (and
@@ -165,6 +165,11 @@ onConnected) {
165
165
  const whipAnimation = new WhipAnimation(tui, pal);
166
166
  containers.header.addChild(whipAnimation);
167
167
  containers.header.addChild(recapHeader.component);
168
+ // A viewer that restarted itself in place hands its unsent draft to its successor.
169
+ const restoredDraft = process.env['CRTR_ATTACH_DRAFT'];
170
+ delete process.env['CRTR_ATTACH_DRAFT'];
171
+ if (restoredDraft !== undefined)
172
+ editor.setText(restoredDraft);
168
173
  const ctx = { nodeId, remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
169
174
  // The pending-request strip below the recap goal line. Its hooks close over
170
175
  // collaborators built later (paneFocus, roster, inbox, setNotice) — all are
@@ -590,8 +595,37 @@ onConnected) {
590
595
  crouterBindings = crouterBindingSettings.bindings;
591
596
  },
592
597
  modelThinkingLabel: sync.modelThinkingLabel,
593
- onWelcome: () => scheduleTmuxBindingInstall(),
598
+ onWelcome: () => {
599
+ scheduleTmuxBindingInstall();
600
+ if (!remote)
601
+ void restartIfReleaseChanged();
602
+ },
594
603
  });
604
+ // The one restart path: replace this process with a fresh viewer for the same
605
+ // node and flags, through the `crtr` launcher so it loads the selected
606
+ // release. A shell hosting the viewer stays alive underneath.
607
+ const restartViewer = (env = {}) => {
608
+ const draft = editor.getText();
609
+ // Checked before teardown: a failed exec after it would close the pane and lose the draft.
610
+ if (process.execve === undefined || Buffer.byteLength(draft) > 100_000) {
611
+ setNotice(process.execve === undefined ? `This Node.js ${process.version} cannot restart the viewer in place` : 'The unsent draft is too long to carry across a restart');
612
+ return;
613
+ }
614
+ teardown('detach');
615
+ const args = ['surface', 'attach', 'to', nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
616
+ process.execve(process.execPath, [process.execPath, ...process.execArgv, process.argv[1], ...args], { ...process.env, ...env, CRTR_ATTACH_DRAFT: draft, CRTR_ATTACH_WAKE_PARKED: '0' });
617
+ };
618
+ // One automatic restart per daemon release: if the launcher still loads another release, a second try would loop.
619
+ const restartedFor = process.env['CRTR_ATTACH_RESTARTED_FOR'];
620
+ delete process.env['CRTR_ATTACH_RESTARTED_FOR'];
621
+ const restartIfReleaseChanged = async () => {
622
+ const { processGeneration } = await import('../../commands/sys/shared.js');
623
+ const mine = processGeneration()?.id;
624
+ const daemons = (await cliClient().status().catch(() => undefined))?.generation_id;
625
+ if (mine !== undefined && daemons != null && daemons !== mine && daemons !== restartedFor && !lifecycle.isTornDown()) {
626
+ restartViewer({ CRTR_ATTACH_RESTARTED_FOR: daemons });
627
+ }
628
+ };
595
629
  // Last resort for a background daemon call that escaped its owner's catch.
596
630
  // Node's default for an unhandled rejection is to exit, and this process IS
597
631
  // the person's pane: one stray promise from a fire-and-forget refresh closed
@@ -843,6 +877,7 @@ onConnected) {
843
877
  search.open();
844
878
  },
845
879
  whip,
880
+ reloadViewer: () => restartViewer(),
846
881
  });
847
882
  // Registered only now: every collaborator `stopLocal` touches (the key
848
883
  // listener included) finally exists, so a signal cannot race a half-built
@@ -864,8 +899,10 @@ onConnected) {
864
899
  if (connection.initialSnapshot !== undefined)
865
900
  scheduleTmuxBindingInstall();
866
901
  if (connection.initialSnapshot === undefined) {
902
+ // The hello went out during the connect and the broker's welcome answered it; replay what it sent through the handlers just installed.
867
903
  mark('viewer.hello_sent');
868
- reconnect.sendHello();
904
+ for (const frame of connection.takeEarlyFrames())
905
+ socket.emit('frame', frame);
869
906
  }
870
907
  else {
871
908
  reconnect.startDormant();
@@ -85,8 +85,7 @@ const worktreeClose = defineLeaf({
85
85
  { name: 'worktree_removed', type: 'boolean', required: true, constraint: 'Always false for an active caller: its checkout remains intact rather than being removed beneath the node.' },
86
86
  { name: 'worktree_remove_error', type: 'string', required: true, constraint: 'The named deferred-cleanup state and safe manual follow-up after the caller exits.' },
87
87
  { name: 'branch_deleted', type: 'boolean', required: true, constraint: 'False while the deferred-cleanup checkout still has this branch checked out.' },
88
- { name: 'branch_delete_error', type: 'string', required: true, constraint: 'The safe branch-cleanup follow-up after the checkout is removed.' },
89
- { name: 'base_checkout_stash', type: 'string', required: false, constraint: 'Present when conflicting base-checkout changes were retained in a stash; names the exact stash SHA and command required to recover them.' }
88
+ { name: 'branch_delete_error', type: 'string', required: true, constraint: 'The safe branch-cleanup follow-up after the checkout is removed.' }
90
89
  ],
91
90
  outputKind: 'object',
92
91
  effects: [
@@ -117,9 +116,6 @@ const worktreeClose = defineLeaf({
117
116
  if (r['branch_deleted'] === false) {
118
117
  notes.push(String(r['branch_delete_error'] ?? `local branch ${branch} could not be deleted automatically.`));
119
118
  }
120
- if (typeof r['base_checkout_stash'] === 'string') {
121
- notes.push(`Warning: ${r['base_checkout_stash']}`);
122
- }
123
119
  if (notes.length > 0)
124
120
  return `${base} Note: ${notes.join(' ')}`;
125
121
  return base;
@@ -1,8 +1,8 @@
1
1
  // `crtr surface node` — pure tmux placement for node viewers.
2
- import { closePane, currentTmux, displayPopup, ensureSession, getPaneOption, openNodeWindow, paneCurrentPath, paneExists, panePid, paneStartCommand, respawnPaneInPlace, respawnPaneSync, selectPane, selectWindow, shellQuote, viewerSplitEnv, } from '../../../core/runtime/placement-tmux.js';
2
+ import { closePane, currentTmux, displayPopup, ensureSession, getPaneOption, openNodeWindow, paneCurrentPath, paneExists, paneStartCommand, respawnPaneSync, selectPane, selectWindow, shellQuote, viewerSplitEnv, } from '../../../core/runtime/placement-tmux.js';
3
3
  import { focusViewer as focusViewerWith, viewerEnv, viewerPaneOf, } from '../../../core/runtime/focus-viewer.js';
4
4
  import { cliClient, rethrowAsCliError } from '../../api-client.js';
5
- export { closePane, currentTmux, displayPopup, paneCurrentPath, paneExists, panePid, paneStartCommand, respawnPaneInPlace, respawnPaneSync, shellQuote, viewerSplitEnv };
5
+ export { closePane, currentTmux, displayPopup, paneCurrentPath, paneExists, paneStartCommand, respawnPaneSync, shellQuote, viewerSplitEnv };
6
6
  export { viewerEnv, viewerPaneOf };
7
7
  /** `focusViewer` bound to the CLI's daemon client, with daemon failures
8
8
  * rethrown as clean CLI errors. The implementation is shared with the attach
@@ -7,7 +7,6 @@ import { tmuxSpreadLeaf } from './surface-tmux-spread.js';
7
7
  import { surfaceEditLeaf } from './surface-edit.js';
8
8
  import { registerSurfaceNode } from './surface-node.js';
9
9
  import { surfaceInspectLeaf } from './surface-inspect.js';
10
- import { surfaceReloadLeaf } from './surface-reload.js';
11
10
  import { surfaceInboxLeaf } from './surface-inbox.js';
12
11
  import { surfaceDashboardLeaf } from './surface-dashboard.js';
13
12
  export function registerSurface() {
@@ -22,8 +21,8 @@ export function registerSurface() {
22
21
  help: {
23
22
  name: 'surface',
24
23
  summary: 'open and manage screen-facing surfaces',
25
- model: 'Choose `node` for navigation among node viewers. The other commands open a broker attachment, node Inspector, subtree spread, reload, or adjacent editor pane.',
24
+ model: 'Choose `node` for navigation among node viewers. The other commands open a broker attachment, node Inspector, subtree spread, or adjacent editor pane.',
26
25
  },
27
- children: [registerSurfaceNode(), attach, surfaceInspectLeaf, surfaceReloadLeaf, tmuxSpreadLeaf, surfaceEditLeaf, surfaceInboxLeaf, surfaceDashboardLeaf],
26
+ children: [registerSurfaceNode(), attach, surfaceInspectLeaf, tmuxSpreadLeaf, surfaceEditLeaf, surfaceInboxLeaf, surfaceDashboardLeaf],
28
27
  });
29
28
  }
@@ -36,24 +36,12 @@ export { RelayTransport } from './transport-relay.js';
36
36
  * rejecting — bounds a pending picker fetch if the broker drops the request
37
37
  * (it should always reply with `data` or a correlated `error`). */
38
38
  const REQUEST_TIMEOUT_MS = 10_000;
39
- /** The reconnect supervisor's give-up predicate (extracted pure so it is
40
- * testable without a socket or TUI). After a broker close the viewer KEEPS
41
- * re-dialing the same target while the node is still alive — a yield
42
- * leaves `status='active'` (intent='refresh') and the daemon revives a fresh
43
- * broker on the same path. It gives up only when the node is genuinely gone:
44
- * a terminal status (done/dead/canceled) or a reaped row (null). `idle` and an
45
- * exact unfinalized parked resident are NOT terminal — either can wake while
46
- * the viewer remains seated. Local canvas rows only — a remote target has no
47
- * local row, so callers driving a remote attach must not consult this. */
39
+ /** The reconnect supervisor's give-up predicate. A node can be revived from
40
+ * any status, so the viewer keeps re-dialing through dead and canceled; it
41
+ * gives up only when the row is deleted (null) or the node finished with a
42
+ * final report. */
48
43
  export function reconnectShouldGiveUp(row) {
49
- if (row === null)
50
- return true;
51
- if (row.lifecycle === 'resident'
52
- && row.status === 'done'
53
- && row.intent === 'parked'
54
- && row.final_report == null)
55
- return false;
56
- return row.status === 'done' || row.status === 'dead' || row.status === 'canceled';
44
+ return row === null || (row.status === 'done' && row.final_report != null);
57
45
  }
58
46
  export class BrokerClient extends EventEmitter {
59
47
  nodeId;
@@ -10,7 +10,7 @@ import { EventEmitter } from 'node:events';
10
10
  import { WebSocket } from 'ws';
11
11
  import { classify } from '../fault-classifier.js';
12
12
  import { AttachRefusedError, BrokerUnavailableError } from './transport.js';
13
- function relayUrl(target, nodeId) {
13
+ function relayUrl(target, nodeId, wakeParked) {
14
14
  if ('socketPath' in target) {
15
15
  return `ws+unix://${target.socketPath}:/v1/nodes/${encodeURIComponent(nodeId)}/attach?revive=0`;
16
16
  }
@@ -20,24 +20,30 @@ function relayUrl(target, nodeId) {
20
20
  // A person typed `crtr surface attach` at this node, so an exact parked
21
21
  // resident is woken for it — the same thing the LOCAL attach ensure does for
22
22
  // a direct attach. The bridge leaves a parked node parked without this, which
23
- // is what a product page reconnecting its viewport wants.
24
- url.search = '?wakeParked=1';
23
+ // is what a product page reconnecting its viewport wants, and what a focus
24
+ // of a parked node wants for its first dial.
25
+ url.search = wakeParked ? '?wakeParked=1' : '';
25
26
  url.hash = '';
26
27
  return url.toString();
27
28
  }
28
29
  export class RelayTransport extends EventEmitter {
29
30
  nodeId;
30
31
  target;
32
+ wakeParked;
31
33
  ws;
32
34
  closeEmitted = false;
33
- constructor(nodeId, target) {
35
+ constructor(nodeId, target,
36
+ /** Whether the first dial wakes an exact parked resident; every redial does. */
37
+ wakeParked = true) {
34
38
  super();
35
39
  this.nodeId = nodeId;
36
40
  this.target = target;
41
+ this.wakeParked = wakeParked;
37
42
  }
38
43
  refusal;
44
+ refusalError;
39
45
  get url() {
40
- return relayUrl(this.target, this.nodeId);
46
+ return relayUrl(this.target, this.nodeId, this.wakeParked);
41
47
  }
42
48
  dial() {
43
49
  const ws = new WebSocket(this.url, {
@@ -51,6 +57,7 @@ export class RelayTransport extends EventEmitter {
51
57
  text += c.toString(); });
52
58
  res.on('end', () => {
53
59
  this.refusal = refusalMessage(res.statusCode, text);
60
+ this.refusalError = refusalOf(res.statusCode, text);
54
61
  ws.terminate();
55
62
  });
56
63
  });
@@ -68,6 +75,7 @@ export class RelayTransport extends EventEmitter {
68
75
  }
69
76
  /** Re-dial the same daemon attach endpoint after a broker replacement. */
70
77
  redial(_options) {
78
+ this.wakeParked = true;
71
79
  this.destroy();
72
80
  this.closeEmitted = false;
73
81
  return new Promise((resolve, reject) => {
@@ -93,7 +101,7 @@ export class RelayTransport extends EventEmitter {
93
101
  catch {
94
102
  /* ignore */
95
103
  }
96
- reject(this.refusal === undefined ? err : new Error(this.refusal));
104
+ reject(this.refusal === undefined ? err : Object.assign(new Error(this.refusal), { refusal: this.refusalError }));
97
105
  });
98
106
  ws.on('close', (code, reason) => {
99
107
  if (!settled)
@@ -139,7 +147,7 @@ export class RelayTransport extends EventEmitter {
139
147
  this.emit('frame', frame);
140
148
  }
141
149
  onError(err) {
142
- this.emitError(new Error(`relay transport error: ${this.refusal ?? err.message}`));
150
+ this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal ?? err.message}`), { refusal: this.refusalError }));
143
151
  // 'close' follows 'error'; teardown converges there.
144
152
  }
145
153
  /** A 1008 invalid-id close or a 1011 whose reason starts with "no running
@@ -174,6 +182,15 @@ export class RelayTransport extends EventEmitter {
174
182
  this.emit('error', err);
175
183
  }
176
184
  }
185
+ function refusalOf(status, body) {
186
+ try {
187
+ const e = JSON.parse(body).error;
188
+ if (status !== undefined && typeof e?.code === 'string')
189
+ return { status, code: e.code, message: typeof e.message === 'string' ? e.message : '' };
190
+ }
191
+ catch { /* not JSON */ }
192
+ return undefined;
193
+ }
177
194
  /** `409 broker_not_ready: <message>` from a refused upgrade's `{error:{code,message}}` body. */
178
195
  export function refusalMessage(status, body) {
179
196
  try {
@@ -63,8 +63,8 @@ async function seedRow(meta, db) {
63
63
  // A node directly under an app is readable by the person it was made for.
64
64
  if (profile === null && meta.sub)
65
65
  await writeActsFor(db, meta.node_id, meta.sub);
66
- await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill('?').join(', ')})`)
67
- .run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.usage_json ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
66
+ await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill('?').join(', ')})`)
67
+ .run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
68
68
  }
69
69
  /** The `node_rows` view projects the active fault's columns under a `fault_`
70
70
  * prefix; strip it and hydrate through the same mapper `readFault` uses. */
@@ -102,7 +102,6 @@ function rowFrom(r) {
102
102
  run_id: r['run_id'] ?? null,
103
103
  event_cursor: r['event_cursor'] ?? null,
104
104
  last_activity_at: r['last_activity_at'] ?? null,
105
- usage_json: r['usage_json'] ?? null,
106
105
  caused_by: r['caused_by'] ?? null,
107
106
  last_turn_error_json: r['last_turn_error_json'] ?? null,
108
107
  deleting_at: r['deleting_at'] ?? null,
@@ -5,6 +5,8 @@ import { SessionManager } from '@earendil-works/pi-coding-agent';
5
5
  import { blobStore } from '../blobs/index.js';
6
6
  import { openDb, withCanvasWrite } from '../canvas/db.js';
7
7
  import { appSpace } from '../layout.js';
8
+ import { timedSpan } from '../logged-step-timings.js';
9
+ import { addStepTiming } from '../step-timings.js';
8
10
  import { appendConversationEvents, rootRepromptPending } from '../../daemon/runs/append-section.js';
9
11
  import { ConversationNotFoundError } from './index.js';
10
12
  const OWNER_ORDER = 's.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC';
@@ -149,7 +151,7 @@ export function createRowStore() {
149
151
  const store = {
150
152
  async create(nodeId, header, entries, _path) {
151
153
  const db = await openDb();
152
- const node = await db.prepare('SELECT grantee, run_id FROM node_rows WHERE node_id = ?').get(nodeId);
154
+ const node = await timedSpan('owner_read', async () => await db.prepare('SELECT grantee, run_id FROM node_rows WHERE node_id = ?').get(nodeId));
153
155
  if (!node)
154
156
  throw new Error(`missing conversation owner ${nodeId}`);
155
157
  const id = header.id;
@@ -157,8 +159,9 @@ export function createRowStore() {
157
159
  const body = encode([header, ...entries]);
158
160
  const key = keyFor(nodeId, id, 0);
159
161
  const reprompt = node.run_id ? await rootRepromptPending(node.run_id, nodeId, entries) : false;
160
- await (await blobStore()).put(key, body);
161
- await withCanvasWrite(async (tx) => {
162
+ addStepTiming('blob_bytes', Buffer.byteLength(body));
163
+ await timedSpan('blob_put', async () => await (await blobStore()).put(key, body));
164
+ await timedSpan('transaction', () => withCanvasWrite(async (tx) => {
162
165
  if (await tx.prepare('SELECT 1 FROM conversation_parts WHERE conversation_id = ?').get(id))
163
166
  throw new Error(`conversation already exists: ${id}`);
164
167
  const created = at();
@@ -170,7 +173,7 @@ export function createRowStore() {
170
173
  const pending = await appendConversationEvents(tx, node.run_id, nodeId, entries, [], reprompt);
171
174
  await tx.prepare('UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?').run(entries.at(-1)?.id ?? null, JSON.stringify(pending), id, nodeId);
172
175
  }
173
- });
176
+ }, { timingName: 'create_tx' }));
174
177
  return { conversation_id: id, path };
175
178
  },
176
179
  async append(id, entries) {
@@ -1,8 +1,8 @@
1
1
  import { isSafeNodeId } from '../canvas/paths.js';
2
2
  import { OBJECT_TYPE } from '../permissions/builtin.js';
3
- import { ceilingFrag, readablePackageApps, resolveCeiling } from '../permissions/ceiling.js';
3
+ import { ceilingFrag, readablePackageApps } from '../permissions/ceiling.js';
4
4
  import { compilePermission } from '../permissions/compile.js';
5
- import { permits, readerUser, resolveReader, subjectSet } from '../permissions/evaluator.js';
5
+ import { ceilingOf, permits, readerUser, resolveReader, subjectSet } from '../permissions/evaluator.js';
6
6
  import { loadDefinitions } from '../permissions/schemas.js';
7
7
  import { and, or, raw } from '../permissions/sql.js';
8
8
  import { flatMapAsync } from '../async-array.js';
@@ -35,7 +35,7 @@ export async function viewOf(db, reader) {
35
35
  * schema-typed object has had its facts removed, so only the `permits` branch answers it: its own namespace's app. */
36
36
  export async function readableOrDeleted(db, ev, alias) {
37
37
  const live = await permits(db, ev, 'read', alias);
38
- const ceiling = await resolveCeiling(db, ev.reader, ev.userId, 'read');
38
+ const ceiling = await ceilingOf(db, ev, 'read');
39
39
  const grants = compilePermission(await loadDefinitions(db), ev.subjects, OBJECT_TYPE, 'read', raw('gr.id'));
40
40
  const chain = { sql: `EXISTS (WITH RECURSIVE up(id, depth) AS (
41
41
  SELECT ${alias}.id, 0
@@ -44,28 +44,15 @@ export async function readableOrDeleted(db, ev, alias) {
44
44
  const deleted = and([raw(`${alias}.deleted_at IS NOT NULL AND ${alias}.schema_type IS NULL`), ...(ceiling === null ? [] : [ceilingFrag(ceiling, alias)]), chain]);
45
45
  return or([live, deleted]);
46
46
  }
47
- // A resolution asks for `readableOrDeleted(ev, 'o')` once per owner in the reader's view, and a corpus resolves every name with one `ev`: each
48
- // ask recompiled the schema and re-resolved the ceiling (several queries apiece). The fragment depends only on `ev`, which lives for one
49
- // resolution or one corpus, so compute it once per `ev`.
50
- const readFrags = new WeakMap();
51
- function readableFrag(db, ev) {
52
- let frag = readFrags.get(ev);
53
- if (frag === undefined) {
54
- frag = readableOrDeleted(db, ev, 'o');
55
- frag.catch(() => readFrags.delete(ev));
56
- readFrags.set(ev, frag);
57
- }
58
- return frag;
59
- }
60
47
  /** Whether the reader may read the object `id`, live or deleted. */
61
48
  export async function canReadOrDeleted(db, ev, id) {
62
- const p = await readableFrag(db, ev);
49
+ const p = await readableOrDeleted(db, ev, 'o');
63
50
  const row = await db.prepareUncached(`SELECT ${p.sql} AS ok FROM objects o WHERE o.id = ?`).get(...p.params, id);
64
51
  return row?.ok === true;
65
52
  }
66
53
  /** The documents and custom objects named `name` under `owner` that the reader may read. */
67
54
  async function namedObjects(db, ev, owner, name, deleted, stubs = false) {
68
- const read = await readableFrag(db, ev);
55
+ const read = await readableOrDeleted(db, ev, 'o');
69
56
  return await db.prepareUncached(`SELECT o.* FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0) AND o.owner = ? AND o.name = ? AND o.home_machine IS ${stubs ? 'NOT NULL' : 'NULL'}
70
57
  AND o.deleted_at IS ${deleted ? 'NOT NULL' : 'NULL'} AND ${read.sql}${deleted ? ' ORDER BY o.deleted_at DESC' : ''}`).all(owner.id, name, ...read.params);
71
58
  }
@@ -109,7 +96,7 @@ export async function viewResolutions(db, context, names) {
109
96
  const settled = plain.filter((n) => !ids.has(n));
110
97
  for (const n of settled)
111
98
  hits.set(n, null);
112
- const read = await readableFrag(db, context.ev);
99
+ const read = await readableOrDeleted(db, context.ev, 'o');
113
100
  const rows = await db.prepareUncached(`SELECT o.id, o.owner, o.name FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0)
114
101
  AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${read.sql}`)
115
102
  .all(context.view.map((o) => o.id), settled, ...read.params);
@@ -148,7 +135,7 @@ export async function resolveNames(db, reader, raws, context) {
148
135
  const found = new Map();
149
136
  const wanted = [...new Set(normal.values())];
150
137
  if (wanted.length > 0) {
151
- const read = await readableFrag(db, ev);
138
+ const read = await readableOrDeleted(db, ev, 'o');
152
139
  const byId = await db.prepareUncached(`SELECT o.*, ${read.sql} AS readable_ok FROM objects o WHERE o.id = ANY(?::text[])`)
153
140
  .all(...read.params, wanted);
154
141
  for (const { readable_ok, ...row } of byId)
@@ -12,6 +12,7 @@ export const ATTACH_CONTROL_BINDINGS = [
12
12
  { menuId: 'crtr.tmux.menu.attach.profile-files', actionId: 'crtr.attach.profile-files' },
13
13
  { menuId: 'crtr.tmux.menu.attach.search', actionId: 'crtr.attach.search' },
14
14
  { menuId: 'crtr.tmux.menu.attach.whip', actionId: 'crtr.attach.whip' },
15
+ { menuId: 'crtr.tmux.menu.attach.reload-viewer', actionId: 'crtr.attach.reload-viewer' },
15
16
  ];
16
17
  const ATTACH_CONTROL_PREFIX = '\x1b_crtr;';
17
18
  const ATTACH_CONTROL_SUFFIX = '\x1b\\';
@@ -69,7 +69,7 @@ export const BINDING_CATALOG = Object.freeze([
69
69
  ...menuEntry('graph', 'Canvas graph', 'Open the canvas graph.', ['g'], ['tmux.menu']),
70
70
  ...menuEntry('focus-manager', 'Go to manager', 'Focus this node’s manager.', ['h'], ['tmux.menu']),
71
71
  ...menuEntry('copy-id', 'Copy node id', 'Copy the focused node id to the system clipboard.', ['y'], ['tmux.menu']),
72
- ...menuEntry('reload-viewer', 'Reload viewer', 'Respawn this pane’s viewer onto the current runtime generation.', ['r'], ['tmux.menu']),
72
+ ...menuEntry('reload-viewer', 'Reload viewer', 'Restart this pane’s viewer in place on the installed release, keeping its flags and unsent draft.', ['r'], ['tmux.menu']),
73
73
  ...menuEntry('recap', 'Generate recap', 'Generate the focused node’s Goal and State recap and refresh its generated title.', ['s'], ['tmux.menu']),
74
74
  ...menuEntry('issues', 'Open create menu', 'Open the create submenu.', ['c'], ['tmux.menu']),
75
75
  ...menuEntry('issue.idea', 'Create idea', 'Create an idea issue.', ['i'], ['tmux.menu.issue']),
@@ -89,6 +89,7 @@ export const BINDING_CATALOG = Object.freeze([
89
89
  ...attachEntry('crtr.tmux.menu.attach.file-review', 'crtr.attach.file-review', 'Review a file', 'Open a line-anchored review of a file named in the transcript.', [], ['alt+shift+r']),
90
90
  ...attachEntry('crtr.tmux.menu.attach.profile-files', 'crtr.attach.profile-files', 'Search profile files', 'Fuzzy-match path segments across the node family’s working directories, their context directories (files), profile projects and the profile’s own directory; Ctrl+Y copies a selected path.', ['f'], ['ctrl+f']),
91
91
  ...attachEntry('crtr.tmux.menu.attach.search', 'crtr.attach.search', 'Search transcript', 'Search the transcript as it is currently displayed — folded tool output is not searched until it is unfolded.', ['/'], ['alt+/']),
92
+ ...attachEntry('crtr.tmux.menu.attach.reload-viewer', 'crtr.attach.reload-viewer', 'Reload viewer', 'Restart this viewer in place on the installed release.', [], []),
92
93
  ...attachEntry('crtr.tmux.menu.attach.whip', 'crtr.attach.whip', 'Whip agent', 'Interrupt the agent and send a playful command.', ['w'], []),
93
94
  b('crtr.attach.scroll.up', 'Attach', 'Scroll up', 'Scroll the transcript one line up.', ['shift+up'], 'terminal', ATTACH_CONTEXTS),
94
95
  b('crtr.attach.scroll.down', 'Attach', 'Scroll down', 'Scroll the transcript one line down.', ['shift+down'], 'terminal', ATTACH_CONTEXTS),
@@ -6,8 +6,12 @@ import { blobStore } from '../blobs/index.js';
6
6
  import { openDb } from '../canvas/db.js';
7
7
  import { chargeOf } from './charges.js';
8
8
  const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
9
- /** The moved rows of a month (or of every month), read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
9
+ /** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
10
10
  export class ChunkRows {
11
+ since;
12
+ constructor(since = '0000-00') {
13
+ this.since = since;
14
+ }
11
15
  byMonth = new Map();
12
16
  all;
13
17
  rows(month) {
@@ -21,8 +25,8 @@ export class ChunkRows {
21
25
  return found;
22
26
  }
23
27
  async load(month) {
24
- const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks${month === undefined ? '' : ' WHERE month = ?'} ORDER BY month, payer`)
25
- .all(...(month === undefined ? [] : [month]));
28
+ const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks WHERE month >= ?${month === undefined ? '' : ' AND month = ?'} ORDER BY month, payer`)
29
+ .all(this.since, ...(month === undefined ? [] : [month]));
26
30
  if (chunks.length === 0)
27
31
  return [];
28
32
  const store = await blobStore();
@@ -5,6 +5,6 @@ export { payerOf } from './payer.js';
5
5
  export { writeCharge, receiptChargeId, chargeOf } from './charges.js';
6
6
  export { check, findRefusal, refusalError, refusedMark, userActionOf } from './check.js';
7
7
  export { upsertLimit, deleteLimit, listLimits } from './limits.js';
8
- export { usageFor, listCharges, monthTotals, assertReference } from './read.js';
8
+ export { usageFor, runUsage, listCharges, monthTotals, assertReference } from './read.js';
9
9
  export { REBUILD_ALL_TOTALS, rebuildTotalsFor } from './totals.js';
10
10
  export { appsHeldBy } from './account.js';
@@ -2,6 +2,7 @@
2
2
  // Everything here reads this runtime only.
3
3
  import { openDb } from '../canvas/db.js';
4
4
  import { subjectSet } from '../permissions/evaluator.js';
5
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
5
6
  import { RunError } from '../runs/operations.js';
6
7
  import { appsHeldBy } from './account.js';
7
8
  import { chargeOf } from './charges.js';
@@ -118,7 +119,7 @@ function decodeCursor(cursor) {
118
119
  * is given), otherwise the month's rows (default the current month). */
119
120
  export async function listCharges(filter = {}) {
120
121
  const limit = Math.min(Math.max(Math.trunc(filter.limit ?? 1000), 1), 10_000);
121
- const chunks = new ChunkRows();
122
+ const chunks = new ChunkRows(filter.since);
122
123
  const conditions = [];
123
124
  const params = [];
124
125
  const tests = [];
@@ -164,6 +165,22 @@ export async function listCharges(filter = {}) {
164
165
  const charges = filter.under !== undefined && filter.reader !== undefined ? await visibleChain(page, filter.reader, chunks) : page;
165
166
  return { charges, next: rows.length > limit ? encodeCursor(page[limit - 1]) : null };
166
167
  }
168
+ /** A run's usage, summed from the rows under `run:<id>` when read (refused and take rows excluded): the ledger is its only copy. */
169
+ export async function runUsage(runId) {
170
+ const usage = { ...ZERO_RUN_USAGE }, since = (await (await openDb()).prepare('SELECT created FROM nodes WHERE node_id = ?').get(runId))?.created.slice(0, 7);
171
+ for (let page; page === undefined || page.next !== null;) {
172
+ page = await listCharges({ under: `run:${runId}`, since, limit: 10_000, ...(page?.next ? { after: page.next } : {}) });
173
+ for (const row of page.charges.filter((charge) => charge.refused === null && charge.kind !== 'take')) {
174
+ const units = (row.kind === 'model' ? row.units ?? {} : {});
175
+ usage.input_tokens += units.input ?? 0;
176
+ usage.output_tokens += units.output ?? 0;
177
+ usage.cache_read_tokens += units.cache_read ?? 0;
178
+ usage.cache_write_tokens += units.cache_write ?? 0;
179
+ usage.cost_usd += Number(row.usd ?? 0);
180
+ }
181
+ }
182
+ return usage;
183
+ }
167
184
  /** The payers a `user:<id>` answers for: itself, and every app held (`ledger_holder`) by it or by a team it belongs to. */
168
185
  export async function payersOf(owner) {
169
186
  const db = await openDb();
@@ -530,7 +530,7 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
530
530
  // When the endpoint's admission row (id `admission:<id>`) is already in this ledger, this insert is a no-op. Otherwise it is the only row
531
531
  // the local `grant:<id>` limit can count, so it carries the list-price amount: a null usd rolls up as zero and the cap never refuses.
532
532
  if (spend !== undefined && paid !== null) {
533
- await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
533
+ await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, units: { input: completed.usage.input, output: completed.usage.output, cache_read: completed.usage.cacheRead, cache_write: completed.usage.cacheWrite }, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
534
534
  }
535
535
  }
536
536
  else if (spend !== undefined && paid !== null) {