@north-light/cli 0.3.708 → 0.3.710

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 (162) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/crons.d.ts +3 -0
  4. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  5. package/dist/clients/attach/chrome/roster.js +6 -6
  6. package/dist/clients/attach/chrome/status-line.d.ts +1 -1
  7. package/dist/clients/attach/chrome/status-line.js +1 -1
  8. package/dist/clients/attach/input/capabilities.js +1 -1
  9. package/dist/clients/attach/input/controller.d.ts +4 -0
  10. package/dist/clients/attach/input/controller.js +3 -3
  11. package/dist/clients/attach/overlays/graph.d.ts +3 -2
  12. package/dist/clients/attach/overlays/graph.js +1 -1
  13. package/dist/clients/attach/render/chat-view.d.ts +2 -0
  14. package/dist/clients/attach/render/chat-view.js +1 -1
  15. package/dist/clients/attach/render/doc-links.d.ts +1 -1
  16. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  17. package/dist/clients/attach/session/connection.d.ts +10 -9
  18. package/dist/clients/attach/session/connection.js +1 -1
  19. package/dist/clients/attach/session/context.d.ts +1 -1
  20. package/dist/clients/attach/session/document-links.d.ts +1 -1
  21. package/dist/clients/attach/session/document-links.js +1 -1
  22. package/dist/clients/attach/session/identity.d.ts +2 -0
  23. package/dist/clients/attach/session/identity.js +1 -1
  24. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  25. package/dist/clients/attach/session/input-wiring.js +1 -1
  26. package/dist/clients/attach/session/keys.d.ts +2 -0
  27. package/dist/clients/attach/session/keys.js +1 -1
  28. package/dist/clients/attach/session/layout-record.d.ts +13 -0
  29. package/dist/clients/attach/session/layout-record.js +1 -0
  30. package/dist/clients/attach/session/pane-tag.d.ts +3 -1
  31. package/dist/clients/attach/session/pane-tag.js +1 -1
  32. package/dist/clients/attach/session/reconnect.js +1 -1
  33. package/dist/clients/attach/session/teardown.d.ts +4 -2
  34. package/dist/clients/attach/session/teardown.js +9 -7
  35. package/dist/clients/attach/slash/dispatch.js +2 -2
  36. package/dist/clients/attach/slash/recover.d.ts +10 -0
  37. package/dist/clients/attach/slash/recover.js +2 -0
  38. package/dist/clients/attach/viewer.d.ts +7 -5
  39. package/dist/clients/attach/viewer.js +563 -558
  40. package/dist/commands/node/wait.js +2 -6
  41. package/dist/core/broker-client/client.d.ts +6 -3
  42. package/dist/core/broker-client/client.js +1 -1
  43. package/dist/core/canvas/crons.d.ts +11 -1
  44. package/dist/core/canvas/crons.js +14 -14
  45. package/dist/core/canvas/executions.js +1 -1
  46. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
  47. package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
  48. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  49. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  50. package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
  51. package/dist/core/canvas/schema-version.d.ts +1 -1
  52. package/dist/core/canvas/schema-version.js +1 -1
  53. package/dist/core/command.js +5 -5
  54. package/dist/core/feed/messages.d.ts +5 -0
  55. package/dist/core/feed/messages.js +5 -5
  56. package/dist/core/runtime/bearings.js +4 -4
  57. package/dist/core/runtime/boot-root.js +4 -4
  58. package/dist/core/runtime/broker-request.d.ts +2 -0
  59. package/dist/core/runtime/broker-request.js +1 -1
  60. package/dist/core/runtime/broker.js +1 -1
  61. package/dist/core/runtime/lifecycle.js +2 -2
  62. package/dist/core/runtime/model-swap.d.ts +2 -1
  63. package/dist/core/runtime/model-swap.js +1 -1
  64. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  65. package/dist/core/runtime/placement-tmux.js +1 -1
  66. package/dist/core/runtime/revive.js +2 -2
  67. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  68. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  69. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  70. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  71. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  72. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  73. package/dist/core/runtime/runner/machine/call.js +2 -2
  74. package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
  75. package/dist/core/runtime/runner/machine/ops.js +1 -1
  76. package/dist/core/runtime/runner/types.d.ts +19 -3
  77. package/dist/core/runtime/tmux-driver.d.ts +7 -0
  78. package/dist/core/runtime/tmux-driver.js +6 -6
  79. package/dist/core/worktree-machine.d.ts +4 -1
  80. package/dist/core/worktree-machine.js +1 -1
  81. package/dist/core/worktree-sweep.d.ts +14 -3
  82. package/dist/core/worktree-sweep.js +4 -4
  83. package/dist/daemon/api/bridge.d.ts +5 -0
  84. package/dist/daemon/api/bridge.js +3 -3
  85. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  86. package/dist/daemon/api/handlers/crons.js +1 -1
  87. package/dist/daemon/api/handlers/nodes.js +1 -1
  88. package/dist/daemon/api/operations.js +1 -1
  89. package/dist/daemon/cron/ended.d.ts +3 -0
  90. package/dist/daemon/cron/ended.js +2 -2
  91. package/dist/daemon/cron/lease-recovery.js +1 -1
  92. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  93. package/dist/daemon/cron/machine-fire.js +1 -1
  94. package/dist/daemon/cron/passes.js +1 -1
  95. package/dist/daemon/cron-run.js +2 -2
  96. package/dist/daemon/fleet.d.ts +1 -1
  97. package/dist/daemon/fleet.js +4 -4
  98. package/dist/daemon/machine-link/client.js +1 -1
  99. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  100. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  101. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  102. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  104. package/dist/daemon/runs/observer.d.ts +4 -0
  105. package/dist/daemon/runs/observer.js +1 -1
  106. package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
  107. package/package.json +3 -3
  108. package/packages/crouter-api/dist/api/contract.js +1 -1
  109. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  110. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
  111. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
  112. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +3 -1
  113. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
  114. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  115. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  116. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  117. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  118. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  119. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  120. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  121. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
  122. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
  123. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  124. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  125. package/packages/crouter-api/dist/clients/attach/session/teardown.js +9 -4
  126. package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
  127. package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
  128. package/packages/crouter-api/dist/clients/attach/viewer.js +86 -31
  129. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  130. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  131. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  132. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  133. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  134. package/packages/crouter-api/dist/core/command.js +3 -0
  135. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  136. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  137. package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
  138. package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
  139. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  140. package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
  141. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  142. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  143. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  144. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  145. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  146. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  147. package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
  148. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  149. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
  150. package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
  151. package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
  152. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  153. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  154. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  155. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  156. package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
  157. package/packages/crouter-api/package.json +1 -1
  158. package/packages/crouter-identity/package.json +1 -1
  159. package/packages/crouter-plugin/package.json +3 -3
  160. package/runtime.lock.json +14 -14
  161. package/dist/core/runtime/starting-screen.d.ts +0 -12
  162. package/dist/core/runtime/starting-screen.js +0 -9
@@ -25,7 +25,7 @@
25
25
  import { closePane, currentTmux, inTmux } from '../../../core/runtime/placement-tmux.js';
26
26
  import { FOCUS_REPORTING_OFF } from './focus-events.js';
27
27
  export function createTeardown(s, hooks) {
28
- const { tui, socket, nodeId, remote } = s;
28
+ const { tui, socket, remote } = s;
29
29
  let restored = false;
30
30
  const restore = () => {
31
31
  if (restored)
@@ -55,6 +55,8 @@ export function createTeardown(s, hooks) {
55
55
  if (reason === 'detach')
56
56
  socket.send({ type: 'bye' });
57
57
  socket.close();
58
+ if (reason === 'detach' || reason === 'node-done')
59
+ hooks.forgetLayout();
58
60
  restore();
59
61
  // A clean detach leaves the broker running (the engine runs on) — the
60
62
  // documented "detach leaves the broker running" contract. Teardown reaps
@@ -69,9 +71,12 @@ export function createTeardown(s, hooks) {
69
71
  // buy immediate cleanup (future work).
70
72
  if (reason === 'broker-gone') {
71
73
  const msg = hooks.lastSocketError() ??
72
- `broker gone — node ${nodeId} is no longer running its engine.`;
73
- process.stderr.write(`\n${msg}\nReattach with: ${hooks.reattachCommand}\n`);
74
+ `broker gone — node ${s.nodeId} is no longer running its engine.`;
75
+ process.stderr.write(`\n${msg}\nReattach with: ${hooks.reattachCommand()}\n`);
74
76
  }
77
+ // No node id exists, so there is nothing to reattach to and nothing to claim about the server's state: print the error alone.
78
+ if (reason === 'create-failed')
79
+ process.stderr.write(`\n${hooks.lastSocketError() ?? 'creating the node failed'}\n`);
75
80
  const unsent = hooks.undelivered();
76
81
  if (unsent.length > 0)
77
82
  process.stderr.write(`\nNot delivered:\n${unsent.join('\n---\n')}\n`);
@@ -80,7 +85,7 @@ export function createTeardown(s, hooks) {
80
85
  // (siblings in a swap-pane window survive); the daemon reconciles the
81
86
  // now-gone viewer row.
82
87
  if (reason === 'node-done') {
83
- process.stderr.write(`\n✓ node ${nodeId} finished — final report submitted.\n`);
88
+ process.stderr.write(`\n✓ node ${s.nodeId} finished — final report submitted.\n`);
84
89
  const pane = hooks.tagPane() ?? process.env['TMUX_PANE'] ?? currentTmux()?.pane;
85
90
  if (!remote && pane !== undefined && inTmux())
86
91
  closePane(pane);
@@ -26,6 +26,7 @@ import { BUILTIN_SLASH_COMMANDS } from '../../../core/runtime/pi-vendored.js';
26
26
  import { surfaceTmuxStyleArgs } from '../../../core/runtime/surface-bg.js';
27
27
  import { crouterMenuTmuxArgs } from '../../../core/runtime/tmux-bindings.js';
28
28
  import { viewerOperationForSlash } from '../input/capabilities.js';
29
+ import { formatReport, recover } from './recover.js';
29
30
  import { shellQuote } from '../../../shared/shell-quote.js';
30
31
  /** Canvas slash-commands — implemented NATIVE in the viewer, the ONLY live host:
31
32
  * the broker binds mode:'rpc', so broker pi-extensions never run their
@@ -49,6 +50,7 @@ export const CANVAS_SLASH_COMMANDS = [
49
50
  { name: 'mcp', description: 'MCP servers — status from the adapter’s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths' },
50
51
  { name: 'rename', description: 'Rename this node everywhere — node row, viewer window, session chip, tmux pane: /rename <name>' },
51
52
  { name: 'color', description: 'Color this node — tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, …) or /color none' },
53
+ { name: 'recover', description: 'After a crash or reboot: revive every disconnected node and rebuild the tmux viewer panes that were open' },
52
54
  { name: 'mouse', description: 'Toggle mouse wheel scrolling and drag-select — off restores tmux drag-select and copy-mode mouse' },
53
55
  { name: 'copy-message', description: 'Copy the newest message visible in the transcript viewport' },
54
56
  { name: 'copy-tool', description: 'Copy the newest tool call output' },
@@ -407,6 +409,16 @@ function dispatchCanvasCommand(name, arg, ctx) {
407
409
  else
408
410
  ctx.notify('Verbosity is not wired into this viewer');
409
411
  return true;
412
+ case 'recover':
413
+ if (arg)
414
+ return usage(ctx, '/recover — no argument');
415
+ if (process.env['TMUX'] === undefined) {
416
+ ctx.notify('/recover needs tmux');
417
+ return true;
418
+ }
419
+ ctx.notify('Recovering — reviving nodes and rebuilding panes…');
420
+ recover().then((report) => ctx.notify(formatReport(report)), (err) => ctx.notify(`recover failed: ${err instanceof Error ? err.message : String(err)}`));
421
+ return true;
410
422
  case 'mouse':
411
423
  // Viewer-local render state only — no frame, no CLI, no node mutation.
412
424
  if (ctx.onToggleMouse)
@@ -0,0 +1,111 @@
1
+ // slash/recover.ts — `/recover`: after a crash or reboot, revive every disconnected node and rebuild the
2
+ // tmux viewer layout. The layout comes from the per-viewer records in session/layout-record.ts; when none
3
+ // exist it falls back to the nodes whose viewers the daemon logged opening in the last hour.
4
+ import { existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { routes } from '../../../api/index.js';
7
+ import { cliClient } from '../../../commands/api-client.js';
8
+ import { runtimeRoot } from '../../../core/layout.js';
9
+ import { liveViewerPanes } from '../../../core/runtime/tmux-driver.js';
10
+ import { openViewerPane, selectLayout } from '../../../core/runtime/placement-tmux.js';
11
+ import { readLayoutRecords } from '../session/layout-record.js';
12
+ const LOG_TAIL_BYTES = 8 * 1024 * 1024;
13
+ const FALLBACK_WINDOW_MS = 60 * 60_000;
14
+ /** Node ids of viewers the daemon logged opening within the last hour, oldest first. */
15
+ function recentViewOpens(now) {
16
+ const path = join(runtimeRoot(), 'crtrd.log');
17
+ if (!existsSync(path))
18
+ return [];
19
+ const size = statSync(path).size;
20
+ const start = Math.max(0, size - LOG_TAIL_BYTES);
21
+ const buf = Buffer.alloc(size - start);
22
+ const fd = openSync(path, 'r');
23
+ try {
24
+ readSync(fd, buf, 0, buf.length, start);
25
+ }
26
+ finally {
27
+ closeSync(fd);
28
+ }
29
+ const ids = [];
30
+ for (const line of buf.toString('utf8').split('\n')) {
31
+ if (!line.includes('daemon.timing.view_open_received'))
32
+ continue;
33
+ try {
34
+ const e = JSON.parse(line);
35
+ if (e.event === 'daemon.timing.view_open_received' && e.node_id !== undefined && now - Date.parse(e.ts) <= FALLBACK_WINDOW_MS && !ids.includes(e.node_id))
36
+ ids.push(e.node_id);
37
+ }
38
+ catch { /* partial first line of the tail */ }
39
+ }
40
+ return ids;
41
+ }
42
+ export async function recover(now = Date.now()) {
43
+ const client = cliClient();
44
+ const result = await client.request('POST', routes.reviveAll());
45
+ const failedIds = new Set(result.failed.map((f) => f.node_id));
46
+ const report = {
47
+ revived: result.revived.length,
48
+ failed: result.failed.map((f) => `${f.node_id}: ${f.error}`),
49
+ frozen: result.frozen.length, panes: 0, skipped: 0, source: 'none',
50
+ };
51
+ let records = readLayoutRecords();
52
+ if (records.length > 0)
53
+ report.source = 'snapshot';
54
+ else {
55
+ const nodes = recentViewOpens(now);
56
+ if (nodes.length > 0)
57
+ report.source = 'recent views';
58
+ // One session per project directory, one window per node.
59
+ records = [];
60
+ for (const nodeId of nodes)
61
+ records.push({ nodeId, session: '', windowIndex: records.length, windowName: '', paneIndex: 0, cwd: '', pane: '' });
62
+ }
63
+ const viewed = new Set(liveViewerPanes().map((p) => p.nodeId));
64
+ const targets = [];
65
+ for (const rec of records) {
66
+ if (viewed.has(rec.nodeId) || failedIds.has(rec.nodeId)) {
67
+ report.skipped++;
68
+ continue;
69
+ }
70
+ try {
71
+ const node = await client.getNode(rec.nodeId);
72
+ if (node.status === 'done' || node.status === 'canceled' || node.final_report != null) {
73
+ report.skipped++;
74
+ continue;
75
+ }
76
+ const cwd = rec.cwd === '' ? node.cwd : rec.cwd;
77
+ const session = rec.session === '' ? (cwd.split('/').filter(Boolean).pop() ?? 'crtr') : rec.session;
78
+ targets.push({ ...rec, cwd, session, windowName: rec.windowName === '' ? node.name : rec.windowName });
79
+ }
80
+ catch {
81
+ report.skipped++;
82
+ }
83
+ }
84
+ targets.sort((a, b) => a.session.localeCompare(b.session) || a.windowIndex - b.windowIndex || a.paneIndex - b.paneIndex);
85
+ const firstPane = new Map();
86
+ for (const t of targets) {
87
+ const key = `${t.session}\t${t.windowIndex}`;
88
+ const beside = firstPane.get(key);
89
+ const opened = openViewerPane(t.nodeId, t.session, { name: t.windowName, cwd: t.cwd, waitForBroker: true, ...(beside === undefined ? {} : { besidePane: beside }) });
90
+ if (opened === null) {
91
+ report.failed.push(`${t.nodeId}: tmux refused to open a pane`);
92
+ continue;
93
+ }
94
+ if (beside === undefined)
95
+ firstPane.set(key, opened.pane);
96
+ else if (opened.window !== null)
97
+ selectLayout(opened.window, 'even-horizontal');
98
+ report.panes++;
99
+ }
100
+ return report;
101
+ }
102
+ export function formatReport(r) {
103
+ const parts = [`revived ${r.revived}`, `${r.panes} pane${r.panes === 1 ? '' : 's'} recreated (${r.source})`];
104
+ if (r.frozen > 0)
105
+ parts.push(`${r.frozen} waiting for broker slots`);
106
+ if (r.skipped > 0)
107
+ parts.push(`${r.skipped} skipped (already viewed, finished, or not revivable)`);
108
+ if (r.failed.length > 0)
109
+ parts.push(`${r.failed.length} failed: ${r.failed.join('; ')}`);
110
+ return `Recovered — ${parts.join(', ')}`;
111
+ }
@@ -63,6 +63,7 @@ import { createLayout } from './session/layout.js';
63
63
  import { createEditorInventory } from './session/editor-inventory.js';
64
64
  import { createFrecencyStore } from './input/completion-frecency.js';
65
65
  import { createNodeIdentity } from './session/identity.js';
66
+ import { removeLayoutRecord, writeLayoutRecord } from './session/layout-record.js';
66
67
  import { createPaneTag } from './session/pane-tag.js';
67
68
  import { launchProfileFileSearch, relatedNodes } from './session/profile-files.js';
68
69
  import { createSessionStateSync } from './session/state-sync.js';
@@ -74,22 +75,16 @@ import { mark } from '../../core/timing.js';
74
75
  function quoteIfNeeded(word) {
75
76
  return /^[A-Za-z0-9._:@/-]+$/.test(word) ? word : shellQuote(word);
76
77
  }
77
- /** Run the interactive attach session against `nodeId`. Resolves when the
78
- * viewer detaches, the broker goes away, or a signal lands —
79
- * always restoring the terminal first. `canvasName`, when set, attaches over
80
- * a relayed WebSocket to that `remoteCanvas.targets.<name>` instead of the
81
- * local unix socket — see the `--canvas` flag on `attachToLeaf`. */
82
- export async function runAttach(nodeId, observer, canvasName, wakeParked = true,
83
- /** What a caller that just created the node already holds: the node's detail, the person's settings answer, and whether to play the first-prompt animation. */
84
- held,
78
+ export async function runAttach(target, observer, canvasName, wakeParked = true,
85
79
  /** Called synchronously just before the viewer takes the terminal. */
86
80
  onConnected) {
87
81
  // The viewer is its own esbuild bundle with its own copy of the settings cache: install the person's settings before anything
88
82
  // calls readConfig (theme, keybindings, ChatView's field initializers all do). A caller that holds them hands them over.
89
- if (held === undefined)
83
+ const pending = typeof target === 'string' ? undefined : target;
84
+ if (pending === undefined)
90
85
  await loadPersonSettingsViaApi();
91
86
  else
92
- installPersonSettingsDto(held.settings);
87
+ installPersonSettingsDto(pending.settings);
93
88
  // 1. Resolve the attach target (session/connection.ts). Nothing here waits for the broker:
94
89
  // the viewer paints first and `connection.dial()` (revive, connect, hello) runs after it, so a
95
90
  // dial failure is shown by the viewer (see `dialBroker` below). An unknown node is still a plain CLI error.
@@ -99,8 +94,14 @@ onConnected) {
99
94
  // and no collaborator may re-derive it.
100
95
  const role = resolveHelloRole(observer);
101
96
  const clientId = randomUUID();
102
- const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
103
- const { remote, canvasSource, meta, socket } = connection;
97
+ const connection = connectToNode(canvasName, wakeParked);
98
+ const { remote, canvasSource, socket } = connection;
99
+ const bound0 = typeof target === 'string'
100
+ ? await connection.bind(target)
101
+ : { meta: { cwd: target.cwd, profile_id: target.profile_id }, nodeIdentity: undefined };
102
+ const meta = bound0.meta;
103
+ /** True until the create request returns and the node is bound. */
104
+ let starting = pending !== undefined;
104
105
  // 2. Theme + keybindings — pi's components throw "Theme not initialized"
105
106
  // otherwise. One KeybindingsManager feeds BOTH editor and input; the
106
107
  // editor may resolve a separate pi-tui instance, so mirror onto it (and
@@ -126,7 +127,7 @@ onConnected) {
126
127
  cwd: meta.cwd,
127
128
  palette: pal,
128
129
  hideThinking: true,
129
- banner: [...croutonBannerLines(buildBannerInfo(meta)), pal.muted(`Older messages: crtr node inspect transcript ${nodeId}`)],
130
+ banner: [...croutonBannerLines(buildBannerInfo(meta)), ...(typeof target === 'string' ? [pal.muted(`Older messages: crtr node inspect transcript ${target}`)] : [])],
130
131
  // Local only: a remote attach cannot read this canvas's ticket dirs, so it
131
132
  // has nothing to render a page block from.
132
133
  inlinePageBlocks: !remote,
@@ -165,7 +166,7 @@ onConnected) {
165
166
  delete process.env['CRTR_ATTACH_DRAFT'];
166
167
  if (restoredDraft !== undefined)
167
168
  editor.setText(restoredDraft);
168
- const ctx = { nodeId, remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
169
+ const ctx = { nodeId: typeof target === 'string' ? target : '', remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
169
170
  // The pending-request strip below the recap goal line. Its hooks close over
170
171
  // collaborators built later (paneFocus, roster, inbox, setNotice) — all are
171
172
  // constructed before any key or refresh can invoke them.
@@ -179,7 +180,7 @@ onConnected) {
179
180
  });
180
181
  containers.header.addChild(strip.component);
181
182
  const userConfig = readConfig('user');
182
- const initialWhip = held?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
183
+ const initialWhip = pending?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
183
184
  delete process.env['CRTR_ATTACH_INITIAL_WHIP'];
184
185
  const startupTicketId = process.env['CRTR_ATTACH_OPEN_TICKET'];
185
186
  if (startupTicketId !== undefined)
@@ -248,7 +249,7 @@ onConnected) {
248
249
  ...(inboxProfile === undefined ? {} : { profile: inboxProfile }),
249
250
  ...(remote ? {} : { scan: async () => {
250
251
  const client = cliClient();
251
- const [inbox, history] = await Promise.all([client.listHumanInbox(), client.getInboxHistory(nodeId, { state: 'pending' })]);
252
+ const [inbox, history] = await Promise.all([client.listHumanInbox(), client.getInboxHistory(ctx.nodeId === '' ? undefined : ctx.nodeId, { state: 'pending' })]);
252
253
  const merged = new Map();
253
254
  for (const item of inbox.tickets) {
254
255
  const row = inboxRowFromDTO(item);
@@ -333,7 +334,7 @@ onConnected) {
333
334
  const inventory = createEditorInventory(ctx, capabilities, { setNotice, bindings: () => crouterBindings, fdPath, frecency });
334
335
  // Canvas identity (kind/mode/lifecycle) behind the context badge. A remote
335
336
  // attach starts without one, so load it as soon as the viewer exists.
336
- const identity = createNodeIdentity(ctx, connection.nodeIdentity, {
337
+ const identity = createNodeIdentity(ctx, bound0.nodeIdentity, {
337
338
  isTornDown: () => lifecycle.isTornDown(),
338
339
  onChanged: () => {
339
340
  editorChrome.syncContextBadge();
@@ -377,6 +378,10 @@ onConnected) {
377
378
  // is a real TTY, so `surface
378
379
  // inspect` hosts in-place inside it.
379
380
  const openInspector = (section) => {
381
+ if (starting) {
382
+ setNotice('The node is starting — try again in a moment');
383
+ return;
384
+ }
380
385
  if (!inTmux()) {
381
386
  setNotice('Inspector requires tmux');
382
387
  return;
@@ -384,7 +389,7 @@ onConnected) {
384
389
  setNotice(`Opening Inspector (${section})…`);
385
390
  const home = envHomeOverride();
386
391
  const prefix = home === undefined ? '' : `CRTR_HOME=${shellQuote(home)} `;
387
- const cmd = `${prefix}crtr surface inspect ${shellQuote(nodeId)} --section ${section}`;
392
+ const cmd = `${prefix}crtr surface inspect ${shellQuote(ctx.nodeId)} --section ${section}`;
388
393
  execFile('tmux', ['display-popup', '-E', '-T', ` inspector · ${section} `, '-w', '90%', '-h', '85%', ...surfaceTmuxStyleArgs(), cmd], () => {
389
394
  chromeRefresh.refresh();
390
395
  });
@@ -424,7 +429,7 @@ onConnected) {
424
429
  const paneFocus = createPaneFocus(editor, [roster.active, strip.active, ticketPanel.active]);
425
430
  // The GRAPH overlay — a bounded, centered modal navigator over the same
426
431
  // nav-model graph, reading the live ask counts.
427
- const graphOverlay = new GraphOverlay(tui, nodeId, () => chromeRefresh.asks(), pal, crouterBindings, canvasSource, role, (cause) => chromeRefresh.reportFailure('canvas graph refresh', cause), setNotice);
432
+ const graphOverlay = new GraphOverlay(tui, () => ctx.nodeId, () => chromeRefresh.asks(), pal, crouterBindings, canvasSource, role, (cause) => chromeRefresh.reportFailure('canvas graph refresh', cause), setNotice);
428
433
  const helpOverlay = new HelpOverlay(tui, pal);
429
434
  helpOverlay.setBindings(crouterBindings);
430
435
  // The canvas-chrome refresh/poll engine: owns the ask-count map, the
@@ -468,6 +473,7 @@ onConnected) {
468
473
  agentDir: () => sync.state().agentDir,
469
474
  openNodeMetadata: () => openInspector('overview'),
470
475
  isDormant: () => reconnect.isDormant(),
476
+ isStarting: () => starting,
471
477
  copyTarget,
472
478
  moreDetail: () => chatView.moreDetail(),
473
479
  lessDetail: () => chatView.lessDetail(),
@@ -504,7 +510,7 @@ onConnected) {
504
510
  };
505
511
  // `[[…]]` document links: readable names and browser URLs.
506
512
  const documentLinks = createDocumentLinks({
507
- selfNodeId: nodeId,
513
+ selfNodeId: () => ctx.nodeId === '' ? undefined : ctx.nodeId,
508
514
  remote,
509
515
  canvasSource,
510
516
  port: userConfig.document_port,
@@ -523,7 +529,7 @@ onConnected) {
523
529
  }
524
530
  void canvasSource.listNodes()
525
531
  .then((nodes) => {
526
- const family = relatedNodes(nodes, nodeId);
532
+ const family = relatedNodes(nodes, ctx.nodeId);
527
533
  launchProfileFileSearch({
528
534
  cwd: meta.cwd,
529
535
  nodeDirs: family.map((node) => node.cwd),
@@ -582,6 +588,10 @@ onConnected) {
582
588
  // node and flags, through the `crtr` launcher so it loads the selected
583
589
  // release. A shell hosting the viewer stays alive underneath.
584
590
  const restartViewer = (env = {}) => {
591
+ if (starting) {
592
+ setNotice('The node is starting — try again in a moment');
593
+ return;
594
+ }
585
595
  const draft = editor.getText();
586
596
  // Checked before teardown: a failed exec after it would close the pane and lose the draft.
587
597
  if (process.execve === undefined || Buffer.byteLength(draft) > 100_000) {
@@ -589,7 +599,7 @@ onConnected) {
589
599
  return;
590
600
  }
591
601
  teardown('detach');
592
- const args = ['surface', 'attach', 'to', nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
602
+ const args = ['surface', 'attach', 'to', ctx.nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
593
603
  process.execve(process.execPath, [process.execPath, ...process.execArgv, process.argv[1], ...args], { ...process.env, ...env, CRTR_ATTACH_DRAFT: draft, CRTR_ATTACH_WAKE_PARKED: '0' });
594
604
  };
595
605
  // One automatic restart per daemon release: if the launcher still loads another release, a second try would loop.
@@ -622,7 +632,7 @@ onConnected) {
622
632
  process.on('unhandledRejection', onUnhandledRejection);
623
633
  const removeRejectionGuard = () => { process.off('unhandledRejection', onUnhandledRejection); };
624
634
  // The `@crtr_node` pane tag, claimed after the startup checkpoint below.
625
- const paneTag = createPaneTag(remote, nodeId);
635
+ const paneTag = createPaneTag(remote, ctx.nodeId === '' ? undefined : ctx.nodeId);
626
636
  // Lifecycle / teardown — always restore the terminal, exactly once
627
637
  // (session/teardown.ts owns the ordering rules and the four end reasons).
628
638
  // `stopLocal` is this viewer's own shutdown: every collaborator it built
@@ -658,10 +668,12 @@ onConnected) {
658
668
  // and this is only ever read once teardown actually runs.
659
669
  lastSocketError: () => startupFailure ?? reconnect.lastSocketError(),
660
670
  undelivered: () => (settled ? [] : [...heldFrames.flatMap((f) => ('text' in f ? [f.text] : [])), ...(editor.getText().trim() === '' ? [] : [editor.getText()])]),
661
- reattachCommand: `crtr surface attach to ${quoteIfNeeded(nodeId)}` +
671
+ reattachCommand: () => `crtr surface attach to ${quoteIfNeeded(ctx.nodeId)}` +
662
672
  (observer ? ' --observer' : '') +
663
673
  (canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
664
674
  tagPane: paneTag.pane,
675
+ forgetLayout: () => { if (!remote && ctx.nodeId !== '')
676
+ removeLayoutRecord(ctx.nodeId, paneTag.pane()); },
665
677
  });
666
678
  const teardown = lifecycle.teardown;
667
679
  let startupFailure;
@@ -691,6 +703,8 @@ onConnected) {
691
703
  },
692
704
  });
693
705
  paneTag.set();
706
+ if (!remote && ctx.nodeId !== '')
707
+ writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
694
708
  // 5. Lay out and paint; the broker connection follows (`dialBroker`).
695
709
  layout.mount();
696
710
  // Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
@@ -714,7 +728,7 @@ onConnected) {
714
728
  file,
715
729
  pane: tmux.pane,
716
730
  cwd: meta.cwd,
717
- nodeId,
731
+ nodeId: ctx.nodeId,
718
732
  observer,
719
733
  beforeRespawn: paneTag.clear,
720
734
  });
@@ -795,8 +809,11 @@ onConnected) {
795
809
  detachHint: () => detachHint(crouterBindings),
796
810
  hasExclusiveSurface: () => surfaceHost.hasFullPaneSurface(),
797
811
  setPaneFocused: (focused) => {
798
- if (focused)
812
+ if (focused) {
799
813
  paneTag.stamp();
814
+ if (!remote && ctx.nodeId !== '')
815
+ writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
816
+ }
800
817
  paneFocus.setPaneFocused(focused);
801
818
  tui.requestRender();
802
819
  },
@@ -840,6 +857,7 @@ onConnected) {
840
857
  },
841
858
  whip,
842
859
  reloadViewer: () => restartViewer(),
860
+ isStarting: () => starting,
843
861
  });
844
862
  // Registered only now: every collaborator `stopLocal` touches (the key
845
863
  // listener included) finally exists, so a signal cannot race a half-built
@@ -858,7 +876,7 @@ onConnected) {
858
876
  // The viewer is painted and interactive: now revive, connect and say hello. A live viewer's tmux binding install waits for the welcome
859
877
  // so the synchronous tmux sweep cannot block that frame; a parked one installs below, and reconnect's dormancy callback covers a broker that vanishes.
860
878
  const dialBroker = async () => {
861
- mark('viewer.connect_start', { node: nodeId });
879
+ mark('viewer.connect_start', { node: ctx.nodeId });
862
880
  let parked;
863
881
  try {
864
882
  parked = await connection.dial();
@@ -892,7 +910,7 @@ onConnected) {
892
910
  if (t.startsWith('/') || t.startsWith('!'))
893
911
  refused.push(frame.text);
894
912
  else
895
- void cliClient().sendMessage(nodeId, { body: frame.text, from: 'human' }).catch((e) => setNotice(`Couldn't wake node: ${e instanceof Error ? e.message : String(e)}`));
913
+ void cliClient().sendMessage(ctx.nodeId, { body: frame.text, from: 'human' }).catch((e) => setNotice(`Couldn't wake node: ${e instanceof Error ? e.message : String(e)}`));
896
914
  }
897
915
  if (refused.length > 0) {
898
916
  editor.setText([...refused, editor.getText()].filter((x) => x.trim() !== '').join('\n'));
@@ -906,12 +924,49 @@ onConnected) {
906
924
  inventory.setCommands(parked.commands);
907
925
  // A parked conversation has no broker, so the attach bridge never sees it shown.
908
926
  if (!remote)
909
- void cliClient().markNodeRead(nodeId).catch(() => undefined);
927
+ void cliClient().markNodeRead(ctx.nodeId).catch(() => undefined);
910
928
  scheduleTmuxBindingInstall();
911
929
  reconnect.startDormant();
912
930
  };
913
- void dialBroker();
914
- chromeRefresh.start();
931
+ if (pending === undefined) {
932
+ void dialBroker();
933
+ chromeRefresh.start();
934
+ }
935
+ else {
936
+ void (async () => {
937
+ let detail;
938
+ try {
939
+ detail = await pending.created;
940
+ }
941
+ catch (err) {
942
+ if (lifecycle.isTornDown())
943
+ return;
944
+ // No node exists: print the create error and anything typed that was never delivered.
945
+ startupFailure = err instanceof Error ? err.message : String(err);
946
+ process.exitCode = 1;
947
+ teardown('create-failed');
948
+ return;
949
+ }
950
+ if (lifecycle.isTornDown())
951
+ return;
952
+ ctx.nodeId = detail.node_id;
953
+ const bound = await connection.bind(detail.node_id, detail);
954
+ starting = false;
955
+ mark('viewer.node_bound', { node: detail.node_id });
956
+ if (bound.nodeIdentity !== undefined)
957
+ identity.set(bound.nodeIdentity);
958
+ paneTag.bindNode(detail.node_id);
959
+ chatView.setBannerHint(pal.muted(`Older messages: crtr node inspect transcript ${detail.node_id}`));
960
+ chromeRefresh.start();
961
+ void dialBroker();
962
+ })().catch((err) => {
963
+ if (lifecycle.isTornDown())
964
+ return;
965
+ startupFailure = err instanceof Error ? err.message : String(err);
966
+ process.exitCode = 1;
967
+ teardown('broker-gone');
968
+ });
969
+ }
915
970
  if (startupTicketId !== undefined && startupTicketId !== '' && !remote) {
916
971
  // The dashboard opened this conversation for its oldest pending ask: show the ask first.
917
972
  // Resolve it from the same two reads the inbox strip makes (listed tickets, plus pending unlisted pages).
@@ -5,7 +5,6 @@ import { InputError } from '../../core/io.js';
5
5
  import { requireScope } from '../../core/errors.js';
6
6
  import { parseWhen } from '../../core/wake.js';
7
7
  import { cliClient, getNodeOrNull, rethrowAsCliError } from '../api-client.js';
8
- import { shellQuote } from '../surface/node/placement.js';
9
8
  function armerId() {
10
9
  const id = envNodeId();
11
10
  if (id === undefined || id === '') {
@@ -41,14 +40,6 @@ function etaHint(fireAt, now) {
41
40
  return ` (~${hrs}h)`;
42
41
  return ` (~${Math.round(ms / 86_400_000)}d)`;
43
42
  }
44
- function deadlineHeredoc(body, nodeId) {
45
- let delimiter = 'CRTR_DEADLINE';
46
- let suffix = 0;
47
- const lines = new Set(body.split('\n'));
48
- while (lines.has(delimiter))
49
- delimiter = `CRTR_DEADLINE_${++suffix}`;
50
- return `crtr cron cancel "$CRTR_CRON_ID"\ncrtr node message send --to ${shellQuote(nodeId)} --tier urgent <<'${delimiter}'\n${body}\n${delimiter}`;
51
- }
52
43
  const nodeWaitDeadline = defineLeaf({
53
44
  name: 'deadline',
54
45
  description: 'race this node’s next wake against one urgent deadline cron',
@@ -93,7 +84,8 @@ const nodeWaitDeadline = defineLeaf({
93
84
  // core/canvas/crons.ts, where the invariant is enforced for every caller).
94
85
  const cron = await cliClient().armCron({
95
86
  name: `deadline:${self}`,
96
- command: deadlineHeredoc(body, self),
87
+ command: '',
88
+ deadline_body: body,
97
89
  fire_at: parsed.fireAt,
98
90
  recur: null,
99
91
  tz: tz ?? null,
@@ -44,7 +44,6 @@ export function reconnectShouldGiveUp(row) {
44
44
  return row === null || (row.status === 'done' && row.final_report != null);
45
45
  }
46
46
  export class BrokerClient extends EventEmitter {
47
- nodeId;
48
47
  transport;
49
48
  closeEmitted = false;
50
49
  /** Tracks live connect↔close state so {@link request} can fail fast on a
@@ -61,22 +60,31 @@ export class BrokerClient extends EventEmitter {
61
60
  * Resolved by the matching `data` frame / rejected by the matching `error`
62
61
  * frame in {@link onFrame}, the request's timeout, or transport teardown. */
63
62
  pending = new Map();
63
+ /** `nodeId` is undefined only for a viewer whose node is still being created: it holds no transport until {@link bindTransport}, so
64
+ * every send is a no-op and every request rejects until then. */
64
65
  constructor(nodeId, options = {}) {
65
66
  super();
66
- this.nodeId = nodeId;
67
- this.transport = options.transport ?? new SocketTransport(nodeId);
68
- this.transport.on('connect', () => {
67
+ const transport = options.transport ?? (nodeId === undefined ? undefined : new SocketTransport(nodeId));
68
+ if (transport !== undefined)
69
+ this.bindTransport(transport);
70
+ }
71
+ /** Wire the transport once the node it reaches is known. */
72
+ bindTransport(transport) {
73
+ if (this.transport !== undefined)
74
+ throw new Error('BrokerClient already has a transport');
75
+ this.transport = transport;
76
+ transport.on('connect', () => {
69
77
  this.closeEmitted = false;
70
78
  this.connected = true;
71
79
  this.lastTransportError = undefined;
72
80
  this.emit('connect');
73
81
  });
74
- this.transport.on('frame', (frame) => this.onFrame(frame));
75
- this.transport.on('error', (err) => {
82
+ transport.on('frame', (frame) => this.onFrame(frame));
83
+ transport.on('error', (err) => {
76
84
  this.lastTransportError = err.message;
77
85
  this.emitError(err);
78
86
  });
79
- this.transport.on('close', () => this.onClose());
87
+ transport.on('close', () => this.onClose());
80
88
  }
81
89
  /** Issue a correlated read-op and resolve with the broker's `data` reply (or
82
90
  * reject on the correlated `error`, a timeout, or transport teardown). Mints
@@ -112,22 +120,24 @@ export class BrokerClient extends EventEmitter {
112
120
  * {@link BrokerUnavailableError} when the target has no reachable broker)
113
121
  * on failure. Idempotent guard is the caller's job — call once. */
114
122
  connect() {
115
- this.transport.connect();
123
+ this.transport?.connect();
116
124
  }
117
125
  /** Re-establish the connection after a broker exit (a yield→revive cycle),
118
126
  * to the SAME target. Resolves on `connect` (caller re-sends `hello`);
119
127
  * rejects on a retryable dial failure. */
120
128
  redial(options) {
129
+ if (this.transport === undefined)
130
+ return Promise.reject(new Error('no node to redial yet'));
121
131
  return this.transport.redial(options);
122
132
  }
123
133
  /** Encode + send one client→broker frame. No-op on a dead/absent
124
134
  * connection; never throws. */
125
135
  send(frame) {
126
- this.transport.send(frame);
136
+ this.transport?.send(frame);
127
137
  }
128
138
  /** Detach: tear down the transport. `close` fires → the caller tears down. */
129
139
  close() {
130
- this.transport.destroy();
140
+ this.transport?.destroy();
131
141
  }
132
142
  onFrame(frame) {
133
143
  // Correlated replies (read-ops + dequeue) are consumed by the pending-by-id