@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
@@ -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; }
@@ -110,27 +115,34 @@ class ForwardedViewLink extends EventEmitter {
110
115
  this.emit('close', this.failed);
111
116
  }
112
117
  }
113
- /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. */
114
- export function probeMachineView(environmentId, nodeId, timeoutMs) {
118
+ /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. The channel that connected is returned open, for the caller to use or destroy; null when it did not connect. */
119
+ function openReadyMachineView(environmentId, nodeId, timeoutMs) {
115
120
  return new Promise((resolve) => {
116
121
  const view = openMachineView(environmentId, nodeId);
117
- const timer = setTimeout(() => { resolve(false); view.destroy(); }, timeoutMs);
118
- view.on('connect', () => { clearTimeout(timer); resolve(true); view.destroy(); });
122
+ const timer = setTimeout(() => { resolve(null); view.destroy(); }, timeoutMs);
123
+ // The no-op error listener stays on the returned channel until its user attaches its own: an error before then must not throw.
119
124
  view.on('error', () => { });
120
- view.on('close', () => { clearTimeout(timer); resolve(false); });
125
+ view.on('connect', () => { clearTimeout(timer); resolve(view); });
126
+ view.on('close', () => { clearTimeout(timer); resolve(null); });
121
127
  });
122
128
  }
123
- /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; false on the deadline or when the launch exits. */
129
+ /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; the accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
124
130
  export async function waitForMachineView(environmentId, nodeId, exited, waitMs) {
125
131
  const deadline = Date.now() + waitMs;
126
132
  let exitSeen = false;
127
133
  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()))))
130
- return true;
134
+ // 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.
135
+ for (let attempt = 1; Date.now() <= deadline && !exitSeen; attempt++) {
136
+ const started = performance.now();
137
+ const ready = await openReadyMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now())));
138
+ addStepTiming(`probe_${attempt}_${ready !== null ? 'ready' : 'failed'}_ms`, performance.now() - started);
139
+ if (ready !== null) {
140
+ markAt('ready_received');
141
+ return ready;
142
+ }
131
143
  await new Promise((resolve) => setTimeout(resolve, 250));
132
144
  }
133
- return false;
145
+ return null;
134
146
  }
135
147
  /** The environment id of a forwarded viewer upgrade path, or null for any other path. */
136
148
  export function machineViewEnvironment(req) {
@@ -18,6 +18,8 @@ import { storeJobReport } from '../api/handlers/bash-jobs.js';
18
18
  import { APIError } from '../../api/errors.js';
19
19
  import { brokerSignalBus } from '../broker-signals/bus.js';
20
20
  import { verifyMachineCredential } from './credential.js';
21
+ import { compareReleaseVersions, RUNTIME_VERSION_HEADER } from '../../api/runtime-version.js';
22
+ import { crtrVersion } from '../../shared/crtr-version.js';
21
23
  import { CLOSE_REVOKED, CLOSE_SUPERSEDED, LINK_MAX_PAYLOAD_BYTES, parseFrame } from './frames.js';
22
24
  export const LINK_LEASE_MS = 45_000;
23
25
  export const LINK_RENEW_MS = 15_000;
@@ -252,6 +254,8 @@ export class MachineViewLink extends EventEmitter {
252
254
  super();
253
255
  this.link = link;
254
256
  link.channels.set(this.channel, this);
257
+ const opened = performance.now();
258
+ 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
259
  if (!link.send({ type: 'view.open', channel: this.channel, node: nodeId }))
256
260
  queueMicrotask(() => this.finish('machine link closed'));
257
261
  }
@@ -293,6 +297,9 @@ export async function handleMachineLinkUpgrade(req, socket, head, environmentId)
293
297
  const token = /^Bearer (\S+)$/.exec(Array.isArray(header) ? header[0] ?? '' : header ?? '')?.[1];
294
298
  if (token === undefined || !await verifyMachineCredential(environmentId, token))
295
299
  return { status: 401, text: 'Unauthorized', code: 'unauthorized', message: 'machine credential refused' };
300
+ // A Mac older than this control plane (or naming no release) may lack an op it would be sent: it installs crtrVersion() and links again. A newer one links.
301
+ if (compareReleaseVersions(String(req.headers[RUNTIME_VERSION_HEADER.toLowerCase()] ?? ''), crtrVersion()) < 0)
302
+ return { status: 426, text: 'Upgrade Required', code: 'machine_release_behind', message: crtrVersion() };
296
303
  const now = new Date().toISOString();
297
304
  const db = await openDb();
298
305
  const row = await db.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
@@ -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.696",
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.696",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -527,7 +527,7 @@ function resultResponse(result, leaf) {
527
527
  }
528
528
  if (!isRecord(wireResult))
529
529
  throw outputInvalid('result');
530
- const invalid = validateDeclaredResult(leaf.output, wireResult);
530
+ const invalid = validateDeclaredResult(leaf.output, wireResult, true);
531
531
  if (invalid !== null)
532
532
  throw outputInvalid(invalid.field, invalid.receivedType);
533
533
  for (const key of Object.keys(wireResult)) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.694",
3
+ "version": "0.3.696",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.694",
31
- "@north-light/identity": "0.3.694"
30
+ "@north-light/api": "0.3.696",
31
+ "@north-light/identity": "0.3.696"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.694",
3
+ "version": "0.3.696",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.694",
9
+ "version": "0.3.696",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.694",
32
- "@north-light/plugin": "0.3.694",
31
+ "@north-light/identity": "0.3.696",
32
+ "@north-light/plugin": "0.3.696",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.694",
10670
+ "version": "0.3.696",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.694",
10675
+ "version": "0.3.696",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.694",
10680
+ "version": "0.3.696",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.694",
10688
+ "version": "0.3.696",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.694",
10692
- "@north-light/identity": "0.3.694"
10691
+ "@north-light/api": "0.3.696",
10692
+ "@north-light/identity": "0.3.696"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.694",
10697
+ "version": "0.3.696",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.694",
10701
- "@north-light/identity": "0.3.694",
10702
- "@north-light/plugin": "0.3.694",
10700
+ "@north-light/api": "0.3.696",
10701
+ "@north-light/identity": "0.3.696",
10702
+ "@north-light/plugin": "0.3.696",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {
@@ -26,8 +26,12 @@ function run(command, args, options) {
26
26
  return result;
27
27
  }
28
28
 
29
- function latestArchive(directory) {
30
- const result = run('npm', ['pack', `${PACKAGE_NAME}@latest`, '--json', '--pack-destination', directory], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
29
+ // `--version <x.y.z>` installs that exact release (an imported Mac's machine daemon matching its control plane); otherwise `latest`.
30
+ const versionAt = process.argv.indexOf('--version');
31
+ const wanted = versionAt === -1 ? 'latest' : process.argv[versionAt + 1];
32
+
33
+ function releaseArchive(directory) {
34
+ const result = run('npm', ['pack', `${PACKAGE_NAME}@${wanted}`, '--json', '--pack-destination', directory], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
31
35
  const packed = JSON.parse(result.stdout);
32
36
  if (!Array.isArray(packed) || typeof packed[0]?.filename !== 'string') throw new Error('npm pack did not report an archive');
33
37
  return join(directory, packed[0].filename);
@@ -35,7 +39,7 @@ function latestArchive(directory) {
35
39
 
36
40
  const temporary = mkdtempSync(join(tmpdir(), 'crtr-self-update-'));
37
41
  try {
38
- const archive = latestArchive(temporary);
42
+ const archive = releaseArchive(temporary);
39
43
  const release = join(temporary, 'package');
40
44
  mkdirSync(release);
41
45
  run('tar', ['-xzf', archive, '--strip-components=1', '-C', release]);
@@ -1,40 +0,0 @@
1
- ---
2
- kind: knowledge
3
- when-and-why-to-read: When you need Bash, this knowledge should be read because
4
- Execute bounded shell commands through the daemon.
5
- ---
6
-
7
- # `client.bash`
8
-
9
- `client.bash.run` executes one bounded `bash -c` command through the daemon.
10
-
11
- ```ts
12
- const result = await client.bash.run({
13
- command: 'printf "%s\\n" "$MESSAGE"',
14
- cwd: '/absolute/path/to/project',
15
- env: { MESSAGE: 'hello' },
16
- timeout_s: 30,
17
- profile: 'my-app',
18
- });
19
-
20
- if (result.exit_code !== 0) console.error(result.stderr);
21
- ```
22
-
23
- `run(params, options?)` returns `Promise<BashRunDTO>`. Its final `options` object is the normal request-options object: `headers`, `signal`, `timeout`, and `maxRetries`.
24
-
25
- | Result field | Type | Meaning |
26
- |---|---|---|
27
- | `exit_code` | `number \| null` | Process exit code, or `null` after a timeout. A non-zero code is returned, not thrown. |
28
- | `signal` | `string \| null` | Signal that ended the process, when one did. |
29
- | `stdout` / `stderr` | `string` | Captured output prefix. |
30
- | `stdout_truncated` / `stderr_truncated` | `boolean` | Whether that output stream exceeded its 256 KiB capture limit. |
31
- | `timed_out` | `boolean` | `true` after the daemon terminates the process group for a timeout. |
32
- | `duration_ms` | `number` | Command duration in milliseconds. |
33
-
34
- `cwd` is required, absolute, and must name an existing directory. The daemon never uses its own working directory as a fallback. `timeout_s` defaults to 60, must be greater than 0, and cannot exceed 600. The SDK keeps the HTTP request open for the command timeout plus 15 seconds, unless its configured request timeout is already longer.
35
-
36
- Pass dynamic values through `env` and reference them from the command as `"$NAME"`, rather than interpolating them into shell source. The command receives the daemon's default-deny operational environment, selected profile environment, then your `env` values.
37
-
38
- ## Authority
39
-
40
- The token is the owner credential. Anyone holding it can already create an agent with a bash tool, so this command runs with the daemon user's authority and does not provide a restricted command area.
@@ -1,50 +0,0 @@
1
- ---
2
- kind: knowledge
3
- when-and-why-to-read: When you need Files, this knowledge should be read because
4
- Read, write, and list host files through the daemon.
5
- ---
6
-
7
- # `client.files`
8
-
9
- `client.files` reads, writes, and lists host files through the daemon.
10
-
11
- ```ts
12
- const source = await client.files.read('/absolute/path/to/input.txt');
13
- const written = await client.files.write('/absolute/path/to/output.txt', source.content);
14
- const directory = await client.files.list('/absolute/path/to');
15
- ```
16
-
17
- Every `path` is absolute. Relative paths and `~` are not expanded. File paths are sent to the daemon unchanged; the daemon checks that they are absolute and returns a mapped API error when they are not.
18
-
19
- Every method accepts ordinary request options in its final object: `headers`, `signal`, `timeout`, and `maxRetries`. `read` and `write` add `encoding`; `list` adds `limit`.
20
-
21
- ## Read
22
-
23
- ```ts
24
- await client.files.read(path, { encoding: 'utf8', timeout: 5_000 });
25
- await client.files.read(path, { encoding: 'base64' });
26
- ```
27
-
28
- `read(path, options?)` returns `Promise<FilePeekDTO>`, `{ path, content, truncated }`, through `GET /v1/files/peek`. It captures at most 512 KiB of file bytes. `truncated: true` means `content` is only the prefix. Request `base64` for binary content.
29
-
30
- ## Write
31
-
32
- ```ts
33
- const result = await client.files.write(path, content, { encoding: 'utf8' });
34
- // result is { path, bytes_written }
35
- await client.files.write(path, bytes.toString('base64'), { encoding: 'base64' });
36
- ```
37
-
38
- `write(path, content, options?)` returns `Promise<FileWriteDTO>`, `{ path, bytes_written }`. Writes create parent directories and atomically replace the target. If `path` is an existing symlink, the daemon resolves it and atomically replaces its destination; the symlink remains. Decoded content above 1 MiB is refused with `UnprocessableEntityError` carrying `status: 413` and `code: 'file_too_large'`; it is never truncated or partially written.
39
-
40
- ## List
41
-
42
- ```ts
43
- const result = await client.files.list(path, { limit: 100 });
44
- ```
45
-
46
- `list(path, options?)` returns `Promise<FileListDTO>`, `{ path, entries, truncated }`, for one directory level. Each entry has `name`, `type: 'file' | 'dir' | 'other'`, `size`, and ISO-8601 `modified`. `limit` must be a positive integer; the default is 1000. `truncated: true` means the directory had more entries than the requested limit.
47
-
48
- ## Authority
49
-
50
- The token is the owner credential. Anyone holding it can already create an agent with a bash tool, so these methods run with the daemon user's authority and do not provide a restricted file area.
@@ -1,18 +0,0 @@
1
- ---
2
- kind: knowledge
3
- when-and-why-to-read: When composing crouter SDK namespaces into an application,
4
- read this because it helps you choose a complete runnable starting point.
5
- ---
6
-
7
- # SDK recipes
8
-
9
- These recipes turn the SDK namespaces into complete applications: a bounded extraction, an assistant that waits for events, a research pipeline, and a human approval step.
10
-
11
- | Recipe | Use it when | It ends with |
12
- |---|---|---|
13
- | [[crouter-sdk/guides/typed-extraction]] | You need one structured answer and no follow-up. | A typed object or an explicit failure. |
14
- | [[crouter-sdk/guides/event-driven-assistant]] | Events arrive over time from a webhook, queue, or watcher. | A resident node that wakes for each event. |
15
- | [[crouter-sdk/guides/fan-out-pipeline]] | One task needs independent research before a synthesis. | An orchestrator's final report. |
16
- | [[crouter-sdk/guides/human-approval]] | A person must decide before work continues. | A node resumed by an inbox answer. |
17
-
18
- Start with typed extraction for a request/response job. Use a resident node when the same assistant should react again later. Use an orchestrator only when child work can proceed independently; otherwise keep the composition in your application.