@north-light/cli 0.3.694 → 0.3.695

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 (178) 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 +538 -537
  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/canvas/canvas.js +5 -5
  37. package/dist/core/canvas/types.d.ts +0 -2
  38. package/dist/core/conversation-store/row-store.js +10 -10
  39. package/dist/core/graph/names.js +9 -9
  40. package/dist/core/keybindings/attach-control.d.ts +3 -0
  41. package/dist/core/keybindings/attach-control.js +1 -1
  42. package/dist/core/keybindings/catalog.js +1 -1
  43. package/dist/core/ledger/chunks.d.ts +3 -1
  44. package/dist/core/ledger/chunks.js +2 -2
  45. package/dist/core/ledger/index.d.ts +1 -1
  46. package/dist/core/ledger/index.js +1 -1
  47. package/dist/core/ledger/read.d.ts +4 -0
  48. package/dist/core/ledger/read.js +2 -2
  49. package/dist/core/llm/run.js +2 -2
  50. package/dist/core/logged-step-timings.d.ts +7 -0
  51. package/dist/core/logged-step-timings.js +1 -0
  52. package/dist/core/permissions/evaluator.d.ts +2 -1
  53. package/dist/core/permissions/evaluator.js +2 -2
  54. package/dist/core/providers/receipts.js +1 -1
  55. package/dist/core/runs/operations.js +8 -8
  56. package/dist/core/runtime/broker/model-adapter.js +3 -3
  57. package/dist/core/runtime/broker.js +1 -1
  58. package/dist/core/runtime/nodes.d.ts +1 -1
  59. package/dist/core/runtime/nodes.js +1 -1
  60. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  61. package/dist/core/runtime/placement-tmux.js +1 -1
  62. package/dist/core/runtime/revive.js +2 -2
  63. package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
  64. package/dist/core/runtime/runner/machine/ops.js +1 -1
  65. package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
  66. package/dist/core/runtime/runner/machine/runner.js +1 -1
  67. package/dist/core/runtime/tmux-bindings.js +3 -3
  68. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  69. package/dist/core/runtime/tmux-driver.js +6 -6
  70. package/dist/core/step-timings.d.ts +7 -1
  71. package/dist/core/step-timings.js +1 -1
  72. package/dist/core/worktree-close.js +4 -6
  73. package/dist/core/worktree-landing.d.ts +0 -38
  74. package/dist/core/worktree-landing.js +2 -3
  75. package/dist/core/worktree-sweep.d.ts +0 -1
  76. package/dist/core/worktree-sweep.js +4 -6
  77. package/dist/core/worktree.d.ts +0 -4
  78. package/dist/core/worktree.js +13 -15
  79. package/dist/daemon/api/app-listener.d.ts +1 -0
  80. package/dist/daemon/api/app-listener.js +10 -10
  81. package/dist/daemon/api/bridge.js +4 -4
  82. package/dist/daemon/api/handlers/attach.js +1 -1
  83. package/dist/daemon/api/handlers/conversations.js +3 -3
  84. package/dist/daemon/api/server.d.ts +1 -1
  85. package/dist/daemon/api/server.js +1 -1
  86. package/dist/daemon/cron/armed-context.js +1 -1
  87. package/dist/daemon/crtrd.js +20 -18
  88. package/dist/daemon/machine-link/client.d.ts +5 -1
  89. package/dist/daemon/machine-link/client.js +1 -1
  90. package/dist/daemon/machine-link/forward.js +1 -1
  91. package/dist/daemon/machine-link/holder.js +3 -3
  92. package/dist/daemon/pidfile.js +2 -1
  93. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  94. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  95. package/dist/daemon/runs/append-section.js +2 -2
  96. package/dist/daemon/runs/observer.js +3 -3
  97. package/docs/apps/guides/stream-a-run.md +6 -7
  98. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  99. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  100. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  101. package/docs/concepts/scopes-and-trust.md +1 -1
  102. package/docs/concepts/why-a-daemon.md +1 -1
  103. package/docs/sdk/README.md +13 -41
  104. package/docs/sdk/client.md +5 -7
  105. package/docs/sdk/docker.md +1 -1
  106. package/docs/sdk/errors.md +3 -43
  107. package/docs/sdk/getting-started.md +11 -83
  108. package/docs/sdk/release-notes.md +10 -0
  109. package/docs/sdk/resources.md +11 -44
  110. package/package.json +3 -3
  111. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  112. package/packages/crouter-api/dist/api/contract.js +1 -1
  113. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  114. package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
  115. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  116. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  117. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  118. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  119. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  120. package/packages/crouter-api/dist/commands/surface.js +2 -3
  121. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  122. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
  123. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  124. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  125. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  126. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  127. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  128. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  129. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  130. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  131. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  132. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  133. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  134. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  135. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  136. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  137. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  138. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  139. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  140. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
  141. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  142. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  143. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  144. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  145. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  146. package/packages/crouter-api/dist/core/worktree.js +9 -74
  147. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  148. package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
  149. package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
  150. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  151. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  152. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  153. package/packages/crouter-api/package.json +1 -1
  154. package/packages/crouter-identity/package.json +1 -1
  155. package/packages/crouter-plugin/dist/serve.js +1 -1
  156. package/packages/crouter-plugin/package.json +3 -3
  157. package/runtime.lock.json +14 -14
  158. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  159. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  160. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  161. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  162. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  163. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  164. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  165. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  166. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  167. package/dist/commands/surface-reload.d.ts +0 -7
  168. package/dist/commands/surface-reload.js +0 -1
  169. package/docs/sdk/bash.md +0 -39
  170. package/docs/sdk/files.md +0 -49
  171. package/docs/sdk/guides/README.md +0 -17
  172. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  173. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  174. package/docs/sdk/guides/human-approval.md +0 -24
  175. package/docs/sdk/guides/typed-extraction.md +0 -24
  176. package/docs/sdk/nodes.md +0 -194
  177. package/docs/sdk/streaming.md +0 -149
  178. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -18,6 +18,7 @@ import { activeGrant, terminalGrant } from '../grants/mirror.js';
18
18
  import { callerPerson, nodeTerminalGrant } from '../grants/terminal.js';
19
19
  import { grantSnapshotMissing } from '../../daemon/readiness.js';
20
20
  import { appendRunEvent } from '../runs/events.js';
21
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
21
22
  import { isCloudRole, personId } from '../canvas/person.js';
22
23
  import { InputError } from '../io.js';
23
24
  import { ApiError } from '../../api/errors.js';
@@ -319,7 +320,6 @@ export async function spawnNode(opts) {
319
320
  metadata_json: isRoot ? opts.run?.metadata_json ?? null : null,
320
321
  run_id: isRoot ? nodeId : opts.run?.run_id ?? null,
321
322
  event_cursor: isRoot ? opts.run?.event_cursor ?? 1 : null,
322
- usage_json: isRoot ? opts.run?.usage_json ?? JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) : null,
323
323
  passive_default: opts.passiveDefault ?? false,
324
324
  caused_by: opts.causedBy ?? null,
325
325
  ...(opts.managedWorktree !== undefined ? { managed_worktree: opts.managedWorktree } : {}),
@@ -494,7 +494,7 @@ export async function spawnNode(opts) {
494
494
  if (row.run_id && row.run_id !== row.node_id)
495
495
  await assertRunNotDeleting(db, row.run_id);
496
496
  if (isRoot && opts.run === undefined)
497
- await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage: JSON.parse(row.usage_json) });
497
+ await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage: ZERO_RUN_USAGE });
498
498
  await opts.withinCreate?.(db, row);
499
499
  await recordBirth(db, row);
500
500
  } }));
@@ -20,7 +20,7 @@ import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout,
20
20
  import { BROKER_VIEW_SOCKET_WAIT_MS } from './view-socket.js';
21
21
  // Re-export the pure tmux driver verbs the CLI/viewer consumers need without
22
22
  // exposing the canvas focuses table or sending command modules to the raw driver.
23
- export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, respawnPaneInPlace, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, panePid, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
23
+ export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
24
24
  export { installTmuxBindings } from './tmux-bindings.js';
25
25
  // view.sock readiness — the one shared broker-cold-start primitive
26
26
  export { BROKER_VIEW_SOCKET_WAIT_MS, waitForBrokerViewSocket } from './view-socket.js';
@@ -42,7 +42,7 @@ import { isCloudRole } from '../canvas/person.js';
42
42
  import { asNodePerson } from '../../daemon/reconcilers/node-lifecycle/node-person.js';
43
43
  import { processRunner } from './runner/process.js';
44
44
  import { runnerForEnvironment } from './runner/index.js';
45
- import { MachineLaunchUncertainError, MachineOfflineError } from './runner/machine/ops.js';
45
+ import { MachineOfflineError } from './runner/machine/ops.js';
46
46
  import { blaxelEnvironmentOf } from './blaxel-environment.js';
47
47
  import { recordLaunchFailure } from '../../daemon/reconcilers/node-lifecycle/launch-failure.js';
48
48
  import { acceptedRelease, remoteMachineEnvironmentOf, checkBilledWake, EnvironmentImagePending, imageForWake } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
@@ -679,7 +679,7 @@ async function launchRevive(nodeId, meta, opts) {
679
679
  }
680
680
  }
681
681
  catch (error) {
682
- // A machine with no live link started nothing: the node is not crashed, the caller leaves it dormant with its mail pending (the outer catch ends the execution).
682
+ // A machine call that failed (offline, or sent and unanswered) does not crash the node; the caller leaves it dormant with its mail pending (the outer catch ends the execution).
683
683
  if (error instanceof MachineOfflineError)
684
684
  throw error;
685
685
  try {
@@ -734,9 +734,9 @@ async function launchRevive(nodeId, meta, opts) {
734
734
  };
735
735
  }
736
736
  catch (error) {
737
- // A forwarded start whose outcome is unknown leaves its execution launching: the Mac may have spawned the broker, and the lifecycle
738
- // tick asks `status` of this execution after the link returns (adopt it when running, end it when gone) before any new one starts.
739
- if (error instanceof MachineLaunchUncertainError)
737
+ // A start sent to the Mac and unanswered leaves its execution launching: the Mac may have spawned the broker, and the lifecycle
738
+ // tick's `recoverLaunching` asks `status` of it once the link is back (running is adopted, gone is ended).
739
+ if (error instanceof MachineOfflineError && error.sent)
740
740
  throw error;
741
741
  await abortExecution(executionId, { reason: 'launch_failed' });
742
742
  // Best effort after the exit transition: a failed diagnostic write must neither leave the row live nor replace the launch error.
@@ -5,6 +5,7 @@ export class MachineOfflineError extends Error {
5
5
  environmentId;
6
6
  sent;
7
7
  code = 'machine_offline';
8
+ status = 503;
8
9
  /** True when the call was written to the link before it dropped: the machine may have run it. False: it ran nowhere. */
9
10
  constructor(environmentId, detail, sent = false) {
10
11
  super(`machine ${environmentId} is offline${detail ? `: ${detail}` : ''}`);
@@ -12,13 +13,7 @@ export class MachineOfflineError extends Error {
12
13
  this.sent = sent;
13
14
  }
14
15
  }
15
- /** A forwarded `start` whose outcome is unknown (link dropped or call lost): the execution stays `launching`, the caller never aborts it
16
- * and never starts another. After the link returns `status` of that execution decides: running is adopted, gone is ended. */
17
- export class MachineLaunchUncertainError extends MachineOfflineError {
18
- uncertain = true;
19
- constructor(environmentId, detail) { super(environmentId, detail, true); }
20
- }
21
- /** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The caller runs `status` before a new `start`. */
16
+ /** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The machine runner reports a lost `start` as offline after send. */
22
17
  export class MachineLostError extends Error {
23
18
  environmentId;
24
19
  callId;
@@ -9,7 +9,7 @@ import { openDb } from '../../../canvas/db.js';
9
9
  import { mintExecutionToken } from '../../../canvas/node-tokens.js';
10
10
  import { callMachine } from './call.js';
11
11
  import { machineEnvironmentOfProfile } from './environment.js';
12
- import { MachineLaunchUncertainError, MachineLostError, MachineOfflineError } from './ops.js';
12
+ import { MachineLostError, MachineOfflineError } from './ops.js';
13
13
  /** The machine environment of a node's profile, or null when the profile points at no machine environment. */
14
14
  export async function machineEnvironmentOfNode(nodeId) {
15
15
  const row = await (await openDb()).prepare('SELECT profile_id FROM nodes WHERE node_id = ?').get(nodeId);
@@ -21,7 +21,6 @@ const defaultEnvironmentOf = async (nodeId) => {
21
21
  throw new Error(`node ${nodeId} has no machine environment`);
22
22
  return environment;
23
23
  };
24
- const defaultTokenMinted = async (executionId) => await (await openDb()).prepare('SELECT 1 AS x FROM node_tokens WHERE broker_process_id = ?').get(executionId) !== undefined;
25
24
  const asError = (error) => error instanceof Error ? error : new Error(String(error));
26
25
  export function createMachineRunner(deps = {}) {
27
26
  const environmentOf = deps.environmentOf ?? defaultEnvironmentOf;
@@ -29,34 +28,15 @@ export function createMachineRunner(deps = {}) {
29
28
  kind: 'machine',
30
29
  async start(input) {
31
30
  const environment = await environmentOf(input.nodeId);
32
- const tokenMinted = deps.tokenMinted ?? defaultTokenMinted;
33
- const uncertain = (why) => new MachineLaunchUncertainError(environment, `the launch of execution ${input.executionId} is unconfirmed: ${why}`);
34
- // `status` of THIS execution decides. A repeated start (a reconciler whose lease was taken, a start whose answer was lost) finds the
35
- // broker of this execution and adopts it. A token is never minted twice for one execution (D75): one that exists means a start was
36
- // already handed over, so what is left to learn is whether its broker exists.
37
- const handedOver = await tokenMinted(input.executionId);
38
- let status;
39
- try {
40
- status = await callMachine(environment, 'status', { execution: input });
41
- }
42
- catch (error) {
43
- if (handedOver && (error instanceof MachineOfflineError || error instanceof MachineLostError))
44
- throw uncertain('the machine could not be asked');
45
- throw error;
46
- }
47
- if (status.state === 'running')
48
- return { pid: status.pid, exited: null };
49
- if (handedOver)
50
- throw uncertain('a start was handed over and no broker is running yet');
51
31
  const nodeToken = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
52
32
  try {
53
33
  const result = await callMachine(environment, 'start', { ...input, nodeToken });
54
34
  return { pid: result.pid, exited: null };
55
35
  }
56
36
  catch (error) {
57
- // Sent and unanswered (the link dropped, or the lease ran out): the Mac may have spawned the broker. The execution stays launching.
58
- if (error instanceof MachineLostError || (error instanceof MachineOfflineError && error.sent))
59
- throw uncertain(error.message);
37
+ // Sent and unanswered (the lease ran out): the Mac may have spawned the broker, so it is offline-after-send and the execution stays launching.
38
+ if (error instanceof MachineLostError)
39
+ throw new MachineOfflineError(environment, error.message, true);
60
40
  throw error;
61
41
  }
62
42
  },
@@ -49,7 +49,7 @@ const LEAF_MENU_ACTIONS = {
49
49
  'crtr.tmux.menu.graph': { description: 'canvas graph', action: { kind: 'keys', keys: '/graph' } },
50
50
  'crtr.tmux.menu.focus-manager': { description: 'go to manager', action: { kind: 'command', run: 'surface node focus {manager}' } },
51
51
  'crtr.tmux.menu.copy-id': { description: 'copy node id', action: { kind: 'direct', run: 'surface node id --pane {pane}' } },
52
- 'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: 'direct', run: 'surface reload --pane {pane}' } },
52
+ 'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: 'literal-input', input: encodeAttachControlInput('crtr.attach.reload-viewer') } },
53
53
  'crtr.tmux.menu.recap': { description: 'generate recap', action: { kind: 'keys', keys: '/recap' } },
54
54
  'crtr.tmux.menu.pin': { description: 'pin conversation', action: { kind: 'direct', run: 'surface node pin --pane {pane}' } },
55
55
  'crtr.tmux.menu.issue.idea': { description: 'idea', action: { kind: 'popup', run: 'canvas issue new --type idea' } },
@@ -624,24 +624,6 @@ export function paneCurrentCommand(pane) {
624
624
  const r = tmux(['display-message', '-p', '-t', pane, '#{pane_current_command}']);
625
625
  return r.ok && r.stdout !== '' ? r.stdout : undefined;
626
626
  }
627
- /** The pane's root process pid (`#{pane_pid}`) — the process tmux launched in
628
- * the pane (the viewer itself, or the login shell hosting it). undefined when
629
- * tmux is unreachable or the pane is gone. */
630
- export function panePid(pane) {
631
- const r = tmux(['display-message', '-p', '-t', pane, '#{pane_pid}']);
632
- if (!r.ok)
633
- return undefined;
634
- const pid = Number.parseInt(r.stdout, 10);
635
- return Number.isInteger(pid) && pid > 0 ? pid : undefined;
636
- }
637
- /** Kill a pane's current process and re-run the SAME command line it was
638
- * started with (`respawn-pane -k` with no command reuses the pane's original
639
- * command). Used to hot-reload a viewer pane in place: the fresh process
640
- * re-resolves `crtr` and picks up the currently selected runtime generation,
641
- * while the pane id, geometry, and the node's broker are untouched. */
642
- export function respawnPaneInPlace(pane) {
643
- return tmux(['respawn-pane', '-k', '-t', pane]).ok;
644
- }
645
627
  // pi command assembly
646
628
  /** Turn a pi argv array into a single shell command string.
647
629
  *
@@ -8,8 +8,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
8
8
  import { monitorEventLoopDelay } from 'node:perf_hooks';
9
9
  const stepTimings = new AsyncLocalStorage();
10
10
  /** Run `fn`, collecting the steps recorded beneath it. */
11
- export async function collectStepTimings(fn) {
12
- const steps = [];
11
+ export async function collectStepTimings(fn, steps = []) {
13
12
  // How long the event loop was blocked while the request ran: a blocked loop delays every await in it, and shows as time no step explains.
14
13
  const loop = monitorEventLoopDelay({ resolution: 5 });
15
14
  loop.enable();
@@ -56,3 +55,9 @@ export async function timedStep(name, fn) {
56
55
  export function serverTimingHeader(steps) {
57
56
  return steps.map(([name, ms]) => `${name};dur=${ms.toFixed(1)}`).join(', ');
58
57
  }
58
+ /** When a request or upgrade arrived (`performance.now()`), and when its authentication finished; set by the listeners before and after they authenticate. */
59
+ const receipts = new WeakMap();
60
+ export function markReceived(req) { receipts.set(req, { receivedAt: performance.now() }); }
61
+ export function markAuthenticated(req) { const r = receipts.get(req); if (r !== undefined)
62
+ r.authenticatedAt = performance.now(); }
63
+ export function receiptOf(req) { return receipts.get(req) ?? { receivedAt: performance.now() }; }
@@ -5,7 +5,6 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
5
5
  import { gitAsync } from './git.js';
6
6
  import { proveBranchContained } from './worktree-containment.js';
7
7
  import { concludeAbsentManagedWorktreeAsync, concludeAbsentManagedWorktreeOnHost } from './worktree-mutation-async.js';
8
- import { parseStatusPorcelain, planLandIntoCheckout } from './worktree-landing.js';
9
8
  import { WORKTREE_LOCK_WAIT_MS, checkoutPathForBranchInList, missingWorktreeRecoveryHint, persistClosedWorktreeState, samePath, worktreeLockPathForCommonDir, WorktreeError } from './worktree.js';
10
9
  import { shellQuote } from '../shared/shell-quote.js';
11
10
  function detailOf(result) {
@@ -62,52 +61,9 @@ function deferredCleanupResult(wt) {
62
61
  branch_delete_error: `cleanup pending: local branch ${wt.branch} remains checked out at ${wt.path}; delete it only after that checkout is removed and its landed commit is still contained in ${wt.base_ref}.`,
63
62
  };
64
63
  }
65
- async function dropStashIfStillTip(cwd, stashSha) {
66
- const tip = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], cwd);
67
- if (tip.status === 0 && tip.stdout.trim() === stashSha)
68
- await gitAsync(['stash', 'drop'], cwd);
69
- }
70
- async function landIntoBaseCheckout(baseCheckout, branch, baseSha, landedSha) {
71
- const status = await gitAsync(['status', '--porcelain'], baseCheckout);
72
- if (status.status !== 0)
73
- return { ok: false, detail: detailOf(status) };
74
- const diff = await gitAsync(['diff', '--name-only', baseSha, landedSha], baseCheckout);
75
- if (diff.status !== 0)
76
- return { ok: false, detail: detailOf(diff) };
77
- const incoming = diff.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '');
78
- const plan = planLandIntoCheckout(parseStatusPorcelain(status.stdout), incoming);
79
- if (plan.kind === 'refuse')
80
- return { ok: false, detail: `untracked files in ${baseCheckout} would be overwritten by the incoming commits: ${plan.collisions.join(', ')}` };
81
- const merge = async () => {
82
- const result = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
83
- return result.status === 0 ? { ok: true } : { ok: false, detail: detailOf(result) };
84
- };
85
- if (plan.kind === 'direct')
86
- return merge();
87
- const before = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
88
- const beforeSha = before.status === 0 ? before.stdout.trim() : null;
89
- const pushed = await gitAsync(['stash', 'push', '--message', `crtr landing ${branch}`], baseCheckout);
90
- if (pushed.status !== 0)
91
- return { ok: false, detail: detailOf(pushed) };
92
- const after = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
93
- const stashSha = after.status === 0 ? after.stdout.trim() : null;
94
- if (stashSha === null || stashSha === beforeSha)
95
- return merge();
96
- const recovery = `local changes from ${baseCheckout} are retained in stash ${stashSha}; recover them with \`git -C ${shellQuote(baseCheckout)} stash apply ${stashSha}\` and resolve any conflict.`;
97
- const landed = await merge();
98
- if (!landed.ok) {
99
- if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0) {
100
- await dropStashIfStillTip(baseCheckout, stashSha);
101
- return landed;
102
- }
103
- return { ok: false, detail: `${landed.detail}\n${recovery}` };
104
- }
105
- if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0) {
106
- await dropStashIfStillTip(baseCheckout, stashSha);
107
- return { ok: true };
108
- }
109
- await gitAsync(['reset', '--hard', landedSha], baseCheckout);
110
- return { ok: true, stash: `the shared base checkout was reset to landed commit ${landedSha} because local changes conflicted with it. ${recovery}` };
64
+ async function landIntoBaseCheckout(baseCheckout, landedSha) {
65
+ const result = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
66
+ return result.status === 0 ? { ok: true } : { ok: false, detail: detailOf(result) };
111
67
  }
112
68
  async function closeLocked(nodeId) {
113
69
  const node = await getNode(nodeId);
@@ -184,22 +140,20 @@ async function closeOutcome(nodeId, wt) {
184
140
  return blocked(`rebased worktree is not a fast-forward of local base branch '${wt.base_ref}'`, 'Ask the user how to land this managed worktree.', detailOf(fastForward));
185
141
  const list = await runGit(wt.path, ['worktree', 'list', '--porcelain'], 'worktree_list_failed', 'Inspect the repository worktrees manually, then retry.');
186
142
  const baseCheckout = checkoutPathForBranchInList(list, wt.base_ref);
187
- let stashNote;
188
143
  if (baseCheckout !== null) {
189
144
  const checkoutHead = await gitAsync(['rev-parse', 'HEAD'], baseCheckout);
190
145
  if (checkoutHead.status !== 0 || checkoutHead.stdout.trim() !== baseSha)
191
146
  return blocked(`local base branch '${wt.base_ref}' changed while this worktree was closing`, `Reconcile the base checkout at ${baseCheckout}, then rerun \`crtr node worktree close\`.`, checkoutHead.status !== 0 ? detailOf(checkoutHead) : `expected ${baseSha}, found ${checkoutHead.stdout.trim()}`);
192
- const landed = await landIntoBaseCheckout(baseCheckout, wt.branch, baseSha, landedSha);
147
+ const landed = await landIntoBaseCheckout(baseCheckout, landedSha);
193
148
  if (!landed.ok)
194
149
  return blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, `Local base branch '${wt.base_ref}' is checked out at ${baseCheckout} in a state that blocks a fast-forward.`, landed.detail);
195
- stashNote = landed.stash;
196
150
  }
197
151
  else {
198
152
  const update = await gitAsync(['update-ref', `refs/heads/${wt.base_ref}`, landedSha, baseSha], wt.path);
199
153
  if (update.status !== 0)
200
154
  return blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, 'Ask the user how to land this managed worktree.', detailOf(update));
201
155
  }
202
- return { kind: 'closed', result: { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: landedSha, ...deferredCleanupResult(wt), ...(stashNote === undefined ? {} : { base_checkout_stash: stashNote }) } };
156
+ return { kind: 'closed', result: { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: landedSha, ...deferredCleanupResult(wt) } };
203
157
  }
204
158
  /** Async daemon executor for explicit close. The lock wait and every Git
205
159
  * subprocess yield to the daemon event loop. */
@@ -1,51 +1,3 @@
1
- // The judgment shared by every path that lands a managed worktree onto its
2
- // base branch. These functions run no subprocesses and touch no filesystem:
3
- // they decide from Git output that the caller already has in hand.
4
- //
5
- // Two callers execute the same decision in two forms — `worktree.ts`'s
6
- // synchronous `close` (an API handler, already blocking) and
7
- // `worktree-sweep.ts`'s asynchronous daemon sweep (which must never block the
8
- // event loop). Only the process plumbing differs; the rules that decide whether
9
- // local work is at risk live here once, so the two can never drift.
10
- /** Split `git status --porcelain` (v1 format) into tracked modifications and
11
- * untracked paths. A rename entry (`R old -> new`) reports the destination:
12
- * that is the path an incoming commit would collide with. */
13
- export function parseStatusPorcelain(porcelain) {
14
- const tracked = [];
15
- const untracked = [];
16
- for (const line of porcelain.split('\n')) {
17
- if (line.length < 4)
18
- continue;
19
- const code = line.slice(0, 2);
20
- const rest = line.slice(3);
21
- const path = rest.includes(' -> ') ? rest.slice(rest.indexOf(' -> ') + 4) : rest;
22
- const unquoted = path.startsWith('"') && path.endsWith('"') ? path.slice(1, -1) : path;
23
- if (code === '??')
24
- untracked.push(unquoted);
25
- else if (code !== '!!')
26
- tracked.push(unquoted);
27
- }
28
- return { tracked, untracked };
29
- }
30
- /** How to fast-forward a base checkout that may hold local changes.
31
- *
32
- * Git is less fragile than it looks here: a fast-forward refuses only when an
33
- * incoming commit touches a file with local modifications, so DISJOINT local
34
- * changes are carried along fine and need no stash at all. Overlap is the
35
- * blocker, not dirt.
36
- *
37
- * Untracked files are different. They also do not block a fast-forward unless
38
- * an incoming commit adds the same path — and that collision is a refusal
39
- * rather than a stash, because sweeping a person's untracked file into a stash
40
- * to make room for a commit is not a trade this code may make on their behalf. */
41
- export function planLandIntoCheckout(status, incoming) {
42
- const arriving = new Set(incoming);
43
- const collisions = status.untracked.filter((path) => arriving.has(path));
44
- if (collisions.length > 0)
45
- return { kind: 'refuse', collisions };
46
- const overlapping = status.tracked.filter((path) => arriving.has(path));
47
- return overlapping.length > 0 ? { kind: 'stash', overlapping } : { kind: 'direct' };
48
- }
49
1
  /** The `git update-ref --stdin` body that deletes a managed branch ONLY while
50
2
  * the ref that proved its content already landed is still at the exact SHA the
51
3
  * proof inspected. Compare-and-delete is the whole ownership guard: a branch
@@ -6,7 +6,7 @@ import { crtrHome } from './canvas/paths.js';
6
6
  import { closeWorktreeAndRepoint, getNode, recordLandIntent } from './canvas/index.js';
7
7
  import { CONFIG_FILE, CRTR_DIR_NAME, STATE_FILE } from '../types.js';
8
8
  import { withExclusiveDirectoryLock, withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
9
- import { parseStatusPorcelain, planLandIntoCheckout, refDeleteTransactionStdin } from './worktree-landing.js';
9
+ import { refDeleteTransactionStdin } from './worktree-landing.js';
10
10
  import { shellQuote } from '../shared/shell-quote.js';
11
11
  export class WorktreeError extends Error {
12
12
  code;
@@ -373,75 +373,13 @@ async function recordBlockedLandIntent(nodeId, blocked) {
373
373
  return;
374
374
  await recordLandIntent(nodeId, { at: new Date().toISOString(), blocked });
375
375
  }
376
- /** Fast-forward a base branch that is CHECKED OUT somewhere, landing underneath
377
- * whatever local changes that checkout holds.
378
- *
379
- * The base checkout is shared by every other node using this repository, and
380
- * its local changes usually have nothing to do with the child that is closing.
381
- * Disjoint changes ride along untouched; overlapping ones are stashed, the
382
- * fast-forward runs underneath them, and they are re-applied. The re-apply is
383
- * `stash apply`, never `stash pop`, so a conflict cannot consume the stash and
384
- * lose the work: on conflict the checkout is reset to the landed commit and the
385
- * stash is deliberately KEPT for a person to apply. Either way this never
386
- * leaves conflict markers behind in a checkout other nodes are using. */
387
- function landIntoBaseCheckout(baseCheckout, branch, baseSha, landedSha) {
388
- const status = gitSync(['status', '--porcelain'], baseCheckout);
389
- if (status.status !== 0)
390
- return { ok: false, detail: (status.stderr.trim() || status.stdout.trim()).trim() };
391
- const diff = gitSync(['diff', '--name-only', baseSha, landedSha], baseCheckout);
392
- if (diff.status !== 0)
393
- return { ok: false, detail: (diff.stderr.trim() || diff.stdout.trim()).trim() };
394
- const incoming = diff.stdout.split('\n').map((l) => l.trim()).filter((l) => l !== '');
395
- const plan = planLandIntoCheckout(parseStatusPorcelain(status.stdout), incoming);
396
- if (plan.kind === 'refuse') {
397
- return { ok: false, detail: `untracked files in ${baseCheckout} would be overwritten by the incoming commits: ${plan.collisions.join(', ')}` };
398
- }
399
- const merge = () => {
400
- const res = gitSync(['merge', '--ff-only', landedSha], baseCheckout);
401
- return res.status === 0 ? { ok: true } : { ok: false, detail: (res.stderr.trim() || res.stdout.trim()).trim() };
402
- };
403
- if (plan.kind === 'direct')
404
- return merge();
405
- // Identify the stash by the exact commit this push created. `refs/stash` can
406
- // already name an UNRELATED stash the user made earlier, and a push that
407
- // saved nothing leaves it untouched — applying or dropping that one would
408
- // destroy work this code never owned.
409
- const before = gitSync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
410
- const beforeSha = before.status === 0 ? before.stdout.trim() : null;
411
- const push = gitSync(['stash', 'push', '--message', `crtr landing ${branch}`], baseCheckout);
412
- if (push.status !== 0)
413
- return { ok: false, detail: (push.stderr.trim() || push.stdout.trim()).trim() };
414
- const after = gitSync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
415
- const stashSha = after.status === 0 ? after.stdout.trim() : null;
416
- if (stashSha === null || stashSha === beforeSha)
417
- return merge(); // nothing was saved
418
- const recovery = `local changes from ${baseCheckout} are retained in stash ${stashSha}; recover them with \`git -C ${shellQuote(baseCheckout)} stash apply ${stashSha}\` and resolve any conflict.`;
419
- const landed = merge();
420
- if (!landed.ok) {
421
- // The failed merge left the tree exactly as the stash found it, so this
422
- // re-apply is clean; restore before surfacing the refusal.
423
- if (gitSync(['stash', 'apply', stashSha], baseCheckout).status === 0) {
424
- dropStashIfStillTip(baseCheckout, stashSha);
425
- return landed;
426
- }
427
- return { ok: false, detail: `${landed.detail}\n${recovery}` };
428
- }
429
- if (gitSync(['stash', 'apply', stashSha], baseCheckout).status === 0) {
430
- dropStashIfStillTip(baseCheckout, stashSha);
431
- return { ok: true };
432
- }
433
- gitSync(['reset', '--hard', landedSha], baseCheckout);
434
- return {
435
- ok: true,
436
- stash: `the shared base checkout was reset to landed commit ${landedSha} because local changes conflicted with it. ${recovery}`,
437
- };
438
- }
439
- /** Drop a stash entry only while it is still the tip `stash@{0}` names, so a
440
- * stash someone else pushed in between is never dropped instead. */
441
- function dropStashIfStillTip(cwd, stashSha) {
442
- const tip = gitSync(['rev-parse', '--verify', '--quiet', 'refs/stash'], cwd);
443
- if (tip.status === 0 && tip.stdout.trim() === stashSha)
444
- gitSync(['stash', 'drop'], cwd);
376
+ /** Fast-forward a base branch that is CHECKED OUT somewhere. Git carries
377
+ * uncommitted changes that do not touch the incoming files and refuses,
378
+ * changing nothing, when they do; that refusal blocks the land. This never
379
+ * stashes or resets a checkout it does not own. */
380
+ function landIntoBaseCheckout(baseCheckout, landedSha) {
381
+ const res = gitSync(['merge', '--ff-only', landedSha], baseCheckout);
382
+ return res.status === 0 ? { ok: true } : { ok: false, detail: (res.stderr.trim() || res.stdout.trim()).trim() };
445
383
  }
446
384
  function deferredCleanupResult(wt) {
447
385
  const remove = `git -C ${shellQuote(wt.repo_root)} worktree remove ${shellQuote(wt.path)}`;
@@ -621,13 +559,11 @@ async function closeManagedWorktreeLocked(nodeId) {
621
559
  throw await blocked(`local base branch '${wt.base_ref}' changed while this worktree was closing`, `Reconcile the base checkout at ${baseCheckout}, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`, detail);
622
560
  }
623
561
  }
624
- let stashNote;
625
562
  if (baseCheckout !== null) {
626
- const landed = landIntoBaseCheckout(baseCheckout, wt.branch, baseSha, landedSha);
563
+ const landed = landIntoBaseCheckout(baseCheckout, landedSha);
627
564
  if (!landed.ok) {
628
565
  throw await blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, `Local base branch '${wt.base_ref}' is checked out at ${baseCheckout} in a state that blocks a fast-forward. Reconcile it there, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`, landed.detail);
629
566
  }
630
- stashNote = landed.stash;
631
567
  }
632
568
  else {
633
569
  const land = gitSync(['update-ref', `refs/heads/${wt.base_ref}`, landedSha, baseSha], wt.path);
@@ -647,7 +583,6 @@ async function closeManagedWorktreeLocked(nodeId) {
647
583
  worktree_path: wt.path,
648
584
  landed_sha: landedSha,
649
585
  ...deferredCleanupResult(wt),
650
- ...(stashNote === undefined ? {} : { base_checkout_stash: stashNote }),
651
586
  };
652
587
  }
653
588
  export async function closeManagedWorktree(nodeId) {
@@ -6,6 +6,7 @@ import { getNode } from '../../core/canvas/canvas.js';
6
6
  import { contextDir } from '../../core/canvas/paths.js';
7
7
  import { appendRunEvent } from '../../core/runs/events.js';
8
8
  import { payerOfGrant } from '../../core/grants/mirror.js';
9
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
9
10
  import { scopeAllowed } from '../../core/scopes.js';
10
11
  import { cronPrincipalOf } from './authority.js';
11
12
  import { personId } from '../../core/canvas/person.js';
@@ -50,11 +51,10 @@ export async function cronBirthPlacement(p, nodeId) {
50
51
  return {
51
52
  root: true, rootLifecycle: 'terminal', ...bounded,
52
53
  run: { grantee: p.grantee, sub: p.sub, grant_id: p.grant_id, client_id: null, metadata_json: JSON.stringify(p.cron_id === null ? { exec: true } : { cron_id: p.cron_id }),
53
- run_id: nodeId, event_cursor: 1,
54
- usage_json: JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) },
54
+ run_id: nodeId, event_cursor: 1 },
55
55
  // A node born with an explicit `run` does not get its `run.started` event from the spawner.
56
56
  withinCreate: async (db, row) => {
57
- await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: await payerOfGrant(p.grant_id), usage: JSON.parse(row.usage_json) });
57
+ await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: await payerOfGrant(p.grant_id), usage: ZERO_RUN_USAGE });
58
58
  },
59
59
  };
60
60
  }
@@ -7,6 +7,9 @@
7
7
  import { EventEmitter } from 'node:events';
8
8
  import { createHmac, timingSafeEqual } from 'node:crypto';
9
9
  import { WebSocket, WebSocketServer } from 'ws';
10
+ import { markAt } from '../../core/logged-step-timings.js';
11
+ import { addStepTiming } from '../../core/step-timings.js';
12
+ import { emitEvent } from '../../core/events/emit.js';
10
13
  import { openDb } from '../../core/canvas/db.js';
11
14
  import { loadSecretsKey } from '../../core/secrets/key.js';
12
15
  import { LINK_MAX_PAYLOAD_BYTES, parseFrame } from './frames.js';
@@ -35,6 +38,8 @@ class ForwardedViewLink extends EventEmitter {
35
38
  super();
36
39
  this.environmentId = environmentId;
37
40
  this.nodeId = nodeId;
41
+ const opened = performance.now();
42
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.forwarded_view_ready', fields: { environment: this.environmentId, node: this.nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
38
43
  this.dial().catch((error) => this.finish(error instanceof Error ? error.message : String(error)));
39
44
  }
40
45
  get destroyed() { return this.ended; }
@@ -125,9 +130,15 @@ export async function waitForMachineView(environmentId, nodeId, exited, waitMs)
125
130
  const deadline = Date.now() + waitMs;
126
131
  let exitSeen = false;
127
132
  void exited?.then(() => { exitSeen = true; });
128
- while (Date.now() <= deadline && !exitSeen) {
129
- if (await probeMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now()))))
133
+ // Each attempt's length and outcome land in the calling request's step timings (`probe_<n>_ready_ms` / `probe_<n>_failed_ms`), and `ready_received_at` marks the first ready.
134
+ for (let attempt = 1; Date.now() <= deadline && !exitSeen; attempt++) {
135
+ const started = performance.now();
136
+ const ready = await probeMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now())));
137
+ addStepTiming(`probe_${attempt}_${ready ? 'ready' : 'failed'}_ms`, performance.now() - started);
138
+ if (ready) {
139
+ markAt('ready_received');
130
140
  return true;
141
+ }
131
142
  await new Promise((resolve) => setTimeout(resolve, 250));
132
143
  }
133
144
  return false;
@@ -252,6 +252,8 @@ export class MachineViewLink extends EventEmitter {
252
252
  super();
253
253
  this.link = link;
254
254
  link.channels.set(this.channel, this);
255
+ const opened = performance.now();
256
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.machine_view_ready', fields: { channel: this.channel, node: nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
255
257
  if (!link.send({ type: 'view.open', channel: this.channel, node: nodeId }))
256
258
  queueMicrotask(() => this.finish('machine link closed'));
257
259
  }
@@ -26,7 +26,7 @@ export function readPidfile() {
26
26
  const p = pidfilePath();
27
27
  if (!existsSync(p))
28
28
  return null;
29
- const raw = readFileSync(p, 'utf8').trim();
29
+ const raw = readFileSync(p, 'utf8').split('\n', 1)[0].trim();
30
30
  const n = Number(raw);
31
31
  return Number.isFinite(n) && n > 0 ? n : null;
32
32
  }
@@ -6,7 +6,6 @@ import { runSchemaRepromptPending } from '../../core/runtime/stop-guard.js';
6
6
  export const TURN_INPUT_TYPE = 'crtr-turn-input';
7
7
  export const SYSTEM_PROMPT_TYPE = 'crtr-system-prompt';
8
8
  export const TURN_END_TYPE = 'crtr-turn-end';
9
- const zero = () => ({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 });
10
9
  function text(content) {
11
10
  if (typeof content === 'string')
12
11
  return content;
@@ -115,13 +114,8 @@ export async function appendConversationEvents(db, runId, nodeId, entries, pendi
115
114
  await doneText();
116
115
  if (message.usage) {
117
116
  const delta = usageParts(message.usage);
118
- const root = await db.prepare('SELECT usage_json, grant_id FROM nodes WHERE node_id = ?').get(runId);
119
- const priorTotal = root.usage_json ? JSON.parse(root.usage_json) : zero();
120
- const total = zero();
121
- for (const key of Object.keys(total))
122
- total[key] = priorTotal[key] + delta[key];
123
- await db.prepare('UPDATE nodes SET usage_json = ? WHERE node_id = ?').run(JSON.stringify(total), runId);
124
- await appendRunEvent(db, runId, nodeId, 'usage', { entry_id: entry.id, served_model: message.model, payer: await payerOfGrant(root.grant_id), ...delta, usage: total });
117
+ const root = await db.prepare('SELECT grant_id FROM nodes WHERE node_id = ?').get(runId);
118
+ await appendRunEvent(db, runId, nodeId, 'usage', { entry_id: entry.id, served_model: message.model, payer: await payerOfGrant(root.grant_id), ...delta, usage: await (await import('../../core/ledger/read.js')).runUsage(runId) });
125
119
  }
126
120
  // The stored message carries the full text in its done events, so the
127
121
  // streamed deltas that previewed it are spent.
@@ -11,10 +11,9 @@ import { ViewLinkTransport } from './view-transport.js';
11
11
  import { emitRunEvent, emitRunSettlement, emitRunStatus } from '../../core/runs/events.js';
12
12
  import { cancelOpenQuestions } from '../../core/runs/questions.js';
13
13
  import { emitEvent } from '../../core/events/emit.js';
14
+ import { runUsage } from '../../core/ledger/index.js';
14
15
  import { toRunOutcomeDTO } from '../api/map.js';
15
16
  import { readOutputResult } from '../../core/runtime/output-result.js';
16
- /** A root row always carries usage; a missing one reads as a run that has used nothing. */
17
- const ZERO_USAGE_JSON = JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 });
18
17
  const observers = new Map();
19
18
  /** One process observes a node at a time: the holder of this lease. A stolen or lapsed lease closes the observer, and the reconcile pass lets another process claim it. */
20
19
  const OBSERVER_LANE = 'run-observer';
@@ -146,8 +145,8 @@ class RunObserver {
146
145
  this.outcomeRevision = outcome.revision;
147
146
  // D2-RES-5: the settlement a result made carries the value `run.get` returns.
148
147
  const result = this.nodeId === this.runId && outcome.kind === 'result' ? await readOutputResult(this.nodeId) : undefined;
149
- const settled = await whileHoldingLease(this.nodeId, this.owner, () => this.nodeId === this.runId
150
- ? emitRunSettlement(this.runId, this.nodeId, 'node.settled', { outcome, usage: JSON.parse(node.usage_json ?? ZERO_USAGE_JSON), ...(result === undefined ? {} : { result }) })
148
+ const settled = await whileHoldingLease(this.nodeId, this.owner, async () => this.nodeId === this.runId
149
+ ? emitRunSettlement(this.runId, this.nodeId, 'node.settled', { outcome, usage: await runUsage(this.runId), ...(result === undefined ? {} : { result }) })
151
150
  : emitRunSettlement(this.runId, this.nodeId, 'child.settled', { child_node_id: this.nodeId, outcome }));
152
151
  if (!settled.held) {
153
152
  this.close();
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.694",
3
+ "version": "0.3.695",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.694",
3
+ "version": "0.3.695",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",