@north-light/cli 0.3.708 → 0.3.709

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) 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/pane-tag.d.ts +3 -1
  29. package/dist/clients/attach/session/pane-tag.js +1 -1
  30. package/dist/clients/attach/session/reconnect.js +1 -1
  31. package/dist/clients/attach/session/teardown.d.ts +2 -2
  32. package/dist/clients/attach/session/teardown.js +9 -7
  33. package/dist/clients/attach/viewer.d.ts +7 -5
  34. package/dist/clients/attach/viewer.js +540 -538
  35. package/dist/commands/node/wait.js +2 -6
  36. package/dist/core/broker-client/client.d.ts +6 -3
  37. package/dist/core/broker-client/client.js +1 -1
  38. package/dist/core/canvas/crons.d.ts +11 -1
  39. package/dist/core/canvas/crons.js +14 -14
  40. package/dist/core/canvas/executions.js +1 -1
  41. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  42. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  43. package/dist/core/canvas/schema-version.d.ts +1 -1
  44. package/dist/core/canvas/schema-version.js +1 -1
  45. package/dist/core/command.js +5 -5
  46. package/dist/core/feed/messages.d.ts +5 -0
  47. package/dist/core/feed/messages.js +5 -5
  48. package/dist/core/runtime/bearings.js +4 -4
  49. package/dist/core/runtime/boot-root.js +4 -4
  50. package/dist/core/runtime/lifecycle.js +2 -2
  51. package/dist/core/runtime/revive.js +2 -2
  52. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  53. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  54. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  55. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  56. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  57. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  58. package/dist/core/runtime/runner/types.d.ts +19 -3
  59. package/dist/daemon/api/bridge.d.ts +5 -0
  60. package/dist/daemon/api/bridge.js +3 -3
  61. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  62. package/dist/daemon/api/handlers/crons.js +1 -1
  63. package/dist/daemon/api/handlers/nodes.js +1 -1
  64. package/dist/daemon/api/operations.js +1 -1
  65. package/dist/daemon/cron/ended.d.ts +3 -0
  66. package/dist/daemon/cron/ended.js +2 -2
  67. package/dist/daemon/cron/lease-recovery.js +1 -1
  68. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  69. package/dist/daemon/cron/machine-fire.js +1 -1
  70. package/dist/daemon/cron/passes.js +1 -1
  71. package/dist/daemon/cron-run.js +2 -2
  72. package/dist/daemon/machine-link/client.js +1 -1
  73. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  74. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  75. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  76. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  77. package/package.json +3 -3
  78. package/packages/crouter-api/dist/api/contract.js +1 -1
  79. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  80. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
  81. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
  82. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +2 -1
  83. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
  84. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  85. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  86. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  87. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  88. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  89. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  90. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  91. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
  92. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  93. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  94. package/packages/crouter-api/dist/clients/attach/session/teardown.js +7 -4
  95. package/packages/crouter-api/dist/clients/attach/viewer.js +77 -30
  96. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  97. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  98. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  99. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  100. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  101. package/packages/crouter-api/dist/core/command.js +3 -0
  102. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  103. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  104. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  105. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  106. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  107. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  108. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  109. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  110. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  111. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  112. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  113. package/packages/crouter-api/package.json +1 -1
  114. package/packages/crouter-identity/package.json +1 -1
  115. package/packages/crouter-plugin/package.json +3 -3
  116. package/runtime.lock.json +14 -14
  117. package/dist/core/runtime/starting-screen.d.ts +0 -12
  118. package/dist/core/runtime/starting-screen.js +0 -9
@@ -63,61 +63,61 @@ export async function preWaitForViewSocket(nodeId) {
63
63
  await new Promise((r) => setTimeout(r, 100));
64
64
  }
65
65
  }
66
- /** Resolve the attach target and build the not-yet-connected socket. Rejects with
67
- * a plain `InputError` for an unknown node — no terminal has been taken over yet. */
68
- export async function connectToNode(nodeId, canvasName, wakeParked = true, known) {
66
+ /** Build the not-yet-connected socket and canvas source. No node is resolved or dialed until `bind` names one: a viewer whose root is
67
+ * still being created paints first and binds when the create returns. `bind` rejects with a plain `InputError` for an unknown node. */
68
+ export function connectToNode(canvasName, wakeParked = true) {
69
69
  // An imported Mac has no local canvas API: its canvas and its brokers' viewer channels are reached through the cloud control plane,
70
70
  // so attach without `--canvas` dials the cloud with the person's sign-in. It is still the person's own attach, not a `--canvas` view:
71
71
  // `remote` stays false, so the viewer claims the controller role like any local attach.
72
72
  const remote = canvasName !== undefined;
73
73
  const machine = remote ? undefined : readMachineConfig();
74
- // Attach must NOT silently honor a durable `crtr canvas use` selection: the
75
- // local branch has a hard local-unix-socket assumption baked into its
76
- // not-found and reconnect-give-up handling, so an implicit remote redirect
77
- // (from a `canvas use cloud` some other command left active) would be
78
- // surprising for a command whose whole meaning is "attach to a node on THIS
79
- // canvas". Go remote ONLY when `--canvas` was passed on THIS invocation —
80
- // never fall through to resolveCanvasSource's activeCanvas precedence, which
81
- // is right for `node inspect`/`canvas browse` but not here.
74
+ // Attach must NOT silently honor a durable `crtr canvas use` selection: go remote ONLY when `--canvas` was passed on THIS invocation —
75
+ // never fall through to resolveCanvasSource's activeCanvas precedence, which is right for `node inspect`/`canvas browse` but not here.
82
76
  const canvasSource = canvasName !== undefined ? cliCanvasSource({ canvasName }) : new ApiCanvasSource();
83
- // A remote node id never exists in THIS machine's canvas.db, so the local
84
- // not-found guard is wrong for `--canvas`. Build a minimal local `meta`
85
- // stand-in instead: `meta.cwd` is a legitimately viewer-local concern
86
- // (theming, this pane's own git status) — not a remote-node concern — so
87
- // pointing it at the CLI's own cwd is correct, not a hack. The `getRow`-based
88
- // reconnect give-up is the other local-canvas dependency `--canvas` must skip;
89
- // it gates on `remote` at its own use site, not here.
90
- let meta;
91
- let nodeIdentity;
92
- let transport;
93
- if (canvasName !== undefined) {
94
- meta = { cwd: process.cwd() };
95
- transport = new RelayTransport(nodeId, resolveRemoteCanvasTarget(canvasName));
96
- }
97
- else {
98
- // A caller that just created the node already holds its detail: no second read.
99
- const localMeta = known ?? await canvasSource.getNode(nodeId);
100
- if (localMeta === null) {
101
- throw new InputError({
102
- error: 'not_found',
103
- message: `no node: ${nodeId}`,
104
- received: nodeId,
105
- next: 'List nodes with `crtr node inspect list`.',
106
- });
107
- }
108
- meta = localMeta;
109
- nodeIdentity = localMeta;
110
- if (machine !== undefined) {
111
- // On a Mac the viewer's WebSocket upgrade alone admits the attach: it authorizes, revives and waits for the broker once, and its channel
112
- // is the viewer's. A focus of a parked node dials without waking it; the upgrade's `node_dormant` refusal says the node is parked.
113
- transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl), wakeParked);
77
+ const socket = new BrokerClient(undefined);
78
+ let boundId;
79
+ const nodeId = () => {
80
+ if (boundId === undefined)
81
+ throw new Error('attach has no node yet');
82
+ return boundId;
83
+ };
84
+ /** Build the transport for `id` and give it to the socket. A remote node id never exists in THIS machine's canvas.db, so `--canvas`
85
+ * skips the local lookup and uses the CLI's own cwd as `meta` (theming and this pane's git status are viewer-local concerns). */
86
+ const bind = async (id, known) => {
87
+ boundId = id;
88
+ let transport;
89
+ let meta;
90
+ let nodeIdentity;
91
+ if (canvasName !== undefined) {
92
+ meta = { cwd: process.cwd() };
93
+ transport = new RelayTransport(id, resolveRemoteCanvasTarget(canvasName));
114
94
  }
115
95
  else {
116
- // The attach ensure runs in `dial()`; the viewer connects through crtrd's Unix-socket WebSocket bridge.
117
- transport = new RelayTransport(nodeId, { socketPath: apiSocketPath() });
96
+ // A caller that just created the node already holds its detail: no second read.
97
+ const localMeta = known ?? await canvasSource.getNode(id);
98
+ if (localMeta === null) {
99
+ throw new InputError({
100
+ error: 'not_found',
101
+ message: `no node: ${id}`,
102
+ received: id,
103
+ next: 'List nodes with `crtr node inspect list`.',
104
+ });
105
+ }
106
+ meta = localMeta;
107
+ nodeIdentity = localMeta;
108
+ if (machine !== undefined) {
109
+ // On a Mac the viewer's WebSocket upgrade alone admits the attach: it authorizes, revives and waits for the broker once, and its channel
110
+ // is the viewer's. A focus of a parked node dials without waking it; the upgrade's `node_dormant` refusal says the node is parked.
111
+ transport = new RelayTransport(id, await machineRelayTarget(machine.apiUrl, machine.directoryUrl), wakeParked);
112
+ }
113
+ else {
114
+ // The attach ensure runs in `dial()`; the viewer connects through crtrd's Unix-socket WebSocket bridge.
115
+ transport = new RelayTransport(id, { socketPath: apiSocketPath() });
116
+ }
118
117
  }
119
- }
120
- const socket = new BrokerClient(nodeId, { transport });
118
+ socket.bindTransport(transport);
119
+ return { meta, nodeIdentity };
120
+ };
121
121
  const local = canvasName === undefined && machine === undefined;
122
122
  /** One error shape for a connect-time failure. */
123
123
  const toAttachError = (err) => {
@@ -129,19 +129,19 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
129
129
  return new InputError({
130
130
  error: 'no_broker',
131
131
  message: err.message,
132
- received: nodeId,
132
+ received: nodeId(),
133
133
  next: 'Focus or revive the node first — attach needs a running headless broker.',
134
134
  });
135
135
  }
136
136
  return new InputError({
137
137
  error: 'socket_error',
138
- message: `could not attach to node ${nodeId}: ${String(err?.message ?? err)}`,
139
- received: nodeId,
138
+ message: `could not attach to node ${nodeId()}: ${String(err?.message ?? err)}`,
139
+ received: nodeId(),
140
140
  next: 'Check the node has a running headless broker.',
141
141
  });
142
142
  };
143
143
  const parkedSnapshot = async () => {
144
- const saved = await cliClient().getSnapshot(nodeId);
144
+ const saved = await cliClient().getSnapshot(nodeId());
145
145
  // The API DTO stays dependency-light and structural; this viewer is the
146
146
  // consumer that knows the complete broker snapshot contract.
147
147
  return { snapshot: saved.snapshot, commands: saved.commands };
@@ -151,7 +151,7 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
151
151
  // Attach revives a dormant node (B2 acceptance): the server-side ensureAttach runs reviveNode (the ONE sanctioned launcher)
152
152
  // and waits for the broker's view socket. The daemon, not the broker, owns attending viewer presence.
153
153
  try {
154
- const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
154
+ const attach = await cliClient().ensureAttach(nodeId(), { resume: true, revive: true, wakeParked });
155
155
  // A parked node focused without waking has deliberately no socket to wait for.
156
156
  if (attach.parked)
157
157
  return await parkedSnapshot();
@@ -159,7 +159,7 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
159
159
  catch (err) {
160
160
  rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
161
161
  }
162
- await preWaitForViewSocket(nodeId);
162
+ await preWaitForViewSocket(nodeId());
163
163
  }
164
164
  try {
165
165
  await new Promise((resolve, reject) => {
@@ -181,5 +181,5 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
181
181
  mark('viewer.transport_open');
182
182
  return undefined;
183
183
  };
184
- return { remote, canvasSource, meta, nodeIdentity, socket, dial };
184
+ return { remote, canvasSource, socket, bind, dial };
185
185
  }
@@ -29,7 +29,7 @@ export function createDocumentLinks(opts) {
29
29
  }, () => { rosterLoaded = false; });
30
30
  };
31
31
  const context = {
32
- selfNodeId: opts.selfNodeId,
32
+ get selfNodeId() { return opts.selfNodeId(); },
33
33
  nodeName: (nodeId) => {
34
34
  const name = names.get(nodeId);
35
35
  if (name === undefined)
@@ -11,6 +11,7 @@ export function createNodeIdentity(ctx, initial, hooks) {
11
11
  let identity = initial;
12
12
  return {
13
13
  current: () => identity,
14
+ set: (value) => { identity = value; hooks.onChanged(); },
14
15
  refresh: () => {
15
16
  void ctx.canvasSource
16
17
  .getNode(ctx.nodeId)
@@ -21,7 +21,7 @@ import { defaultAgentDir } from '../config.js';
21
21
  /** Construct the viewer's one capability authority. */
22
22
  export function createViewerCapabilitiesForInput(ctx, isBrokerOffline) {
23
23
  return createViewerCapabilities({
24
- nodeId: ctx.nodeId,
24
+ get nodeId() { return ctx.nodeId; },
25
25
  profileId: ctx.meta.profile_id ?? undefined,
26
26
  remote: ctx.remote,
27
27
  role: ctx.role,
@@ -45,7 +45,7 @@ export function lessDetailNotice(change) {
45
45
  }
46
46
  /** Build the viewer's InputController with every hook answered. */
47
47
  export function createInputController(ctx, km, capabilities, hooks) {
48
- const { nodeId, socket, tui, editor, containers } = ctx;
48
+ const { socket, tui, editor, containers } = ctx;
49
49
  const { setNotice } = hooks;
50
50
  // Auth pickers — viewer-local OAuth/API-key flows against the SAME auth.json
51
51
  // the broker uses (broker + viewer share a filesystem in the tmux-local attach
@@ -129,6 +129,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
129
129
  // broker (it goes to crtrd via `cliClient`), so leaving it wired for an
130
130
  // observer would let a read-only viewer wake and message the node.
131
131
  isDormant: hooks.isDormant,
132
+ isStarting: hooks.isStarting,
132
133
  onDormantSubmit: !capabilities.permits('wake-dormant') ? undefined : (msgText) => {
133
134
  void (async () => {
134
135
  try {
@@ -137,7 +138,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
137
138
  // (verbatim, no "From … — N updates" digest; see coalesce()), exactly
138
139
  // like the live path. NOT `CRTR_NODE_ID`: direct keyboard input is
139
140
  // the human, not whatever node owns the shell that launched us.
140
- const res = await cliClient().sendMessage(nodeId, { body: msgText, from: 'human' });
141
+ const res = await cliClient().sendMessage(ctx.nodeId, { body: msgText, from: 'human' });
141
142
  setNotice(res.revived ? '↻ waking node…' : '✉ delivered — node reads on next wake');
142
143
  }
143
144
  catch (err) {
@@ -16,6 +16,13 @@ const CLEAR_OR_DETACH_MS = 1000;
16
16
  export function installGlobalKeys(ctx, hooks) {
17
17
  const { tui, editor } = ctx;
18
18
  let lastClearOrDetachAt = 0;
19
+ // The one starting check for every node-relative action; detach, clear, help, search, the inbox and the request strip work without a node.
20
+ const needsNode = (run) => () => {
21
+ if (hooks.isStarting())
22
+ hooks.setNotice('The node is starting — try again in a moment');
23
+ else
24
+ run();
25
+ };
19
26
  const actions = {
20
27
  'crtr.attach.detach': hooks.detach,
21
28
  'crtr.attach.clear-or-detach': () => {
@@ -30,17 +37,17 @@ export function installGlobalKeys(ctx, hooks) {
30
37
  hooks.setNotice(`Editor cleared — press ${hooks.detachHint()} again to cancel the agent`);
31
38
  tui.requestRender();
32
39
  },
33
- 'crtr.attach.graph.toggle': hooks.toggleGraph,
40
+ 'crtr.attach.graph.toggle': needsNode(hooks.toggleGraph),
34
41
  'crtr.attach.help.toggle': hooks.toggleHelp,
35
42
  'crtr.attach.inbox.toggle': hooks.toggleInbox,
36
43
  'crtr.attach.inbox-strip': hooks.toggleInboxStrip,
37
44
  // A plain broker frame, so this works locally and remotely alike; the broker gates observers on controller role.
38
45
  'crtr.attach.model-ladder.next': () => hooks.cycleModelLadder('forward'),
39
46
  'crtr.attach.model-ladder.previous': () => hooks.cycleModelLadder('backward'),
40
- 'crtr.attach.command.inspect': hooks.inspectLoadedCommand,
41
- 'crtr.attach.profile-files': hooks.openProfileFiles,
47
+ 'crtr.attach.command.inspect': needsNode(hooks.inspectLoadedCommand),
48
+ 'crtr.attach.profile-files': needsNode(hooks.openProfileFiles),
42
49
  'crtr.attach.search': hooks.openSearch,
43
- 'crtr.attach.whip': hooks.whip,
50
+ 'crtr.attach.whip': needsNode(hooks.whip),
44
51
  'crtr.attach.reload-viewer': hooks.reloadViewer,
45
52
  };
46
53
  return tui.addInputListener((data) => {
@@ -31,10 +31,16 @@ export function createPaneTag(remote, nodeId, io = realPaneTagIo) {
31
31
  set: () => {
32
32
  pane = io.currentPane();
33
33
  claimAttachPane(pane, ownerPid, io.writeOption);
34
- tagAttachPane(remote, pane, nodeId, io.writeOption);
34
+ if (nodeId !== undefined)
35
+ tagAttachPane(remote, pane, nodeId, io.writeOption);
35
36
  tagAttachViewerPane(pane, io.writeOption);
36
37
  stampAttachPane(remote, pane, io.writeOption);
37
38
  },
39
+ bindNode: (id) => {
40
+ nodeId = id;
41
+ if (pane !== undefined)
42
+ tagAttachPane(remote, pane, id, io.writeOption);
43
+ },
38
44
  stamp: () => {
39
45
  if (remote || pane === undefined || pane === '')
40
46
  return;
@@ -13,7 +13,7 @@ const RECONNECT_ACTIVE_DELAY_CAP_MS = 1_000;
13
13
  /** Dormant by choice — low-rate patience. */
14
14
  const RECONNECT_DORMANT_DELAY_MS = 3_000;
15
15
  export function createReconnect(ctx, hooks) {
16
- const { nodeId, socket, canvasSource } = ctx;
16
+ const { socket, canvasSource } = ctx;
17
17
  let lastSocketError;
18
18
  let reconnecting = false;
19
19
  let viewerDormant = false;
@@ -86,7 +86,7 @@ export function createReconnect(ctx, hooks) {
86
86
  // `--canvas`, so `getRow` works for both cases — always attempt it.
87
87
  let row;
88
88
  try {
89
- row = await canvasSource.getRow(nodeId);
89
+ row = await canvasSource.getRow(ctx.nodeId);
90
90
  }
91
91
  catch {
92
92
  row = undefined;
@@ -168,7 +168,7 @@ export function createReconnect(ctx, hooks) {
168
168
  // attach closed that way before the session's first welcome is a refusal,
169
169
  // not a broker to redial; a plain drop or a 1011 "no running broker" is redialed.
170
170
  if (hooks.remote && hooks.role === 'controller' && refusedByRelay && !welcomed) {
171
- lastSocketError = `the remote canvas refused the attach to ${nodeId}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`;
171
+ lastSocketError = `the remote canvas refused the attach to ${ctx.nodeId}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`;
172
172
  hooks.teardown('broker-gone');
173
173
  return;
174
174
  }
@@ -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)
@@ -69,9 +69,12 @@ export function createTeardown(s, hooks) {
69
69
  // buy immediate cleanup (future work).
70
70
  if (reason === 'broker-gone') {
71
71
  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`);
72
+ `broker gone — node ${s.nodeId} is no longer running its engine.`;
73
+ process.stderr.write(`\n${msg}\nReattach with: ${hooks.reattachCommand()}\n`);
74
74
  }
75
+ // No node id exists, so there is nothing to reattach to and nothing to claim about the server's state: print the error alone.
76
+ if (reason === 'create-failed')
77
+ process.stderr.write(`\n${hooks.lastSocketError() ?? 'creating the node failed'}\n`);
75
78
  const unsent = hooks.undelivered();
76
79
  if (unsent.length > 0)
77
80
  process.stderr.write(`\nNot delivered:\n${unsent.join('\n---\n')}\n`);
@@ -80,7 +83,7 @@ export function createTeardown(s, hooks) {
80
83
  // (siblings in a swap-pane window survive); the daemon reconciles the
81
84
  // now-gone viewer row.
82
85
  if (reason === 'node-done') {
83
- process.stderr.write(`\n✓ node ${nodeId} finished — final report submitted.\n`);
86
+ process.stderr.write(`\n✓ node ${s.nodeId} finished — final report submitted.\n`);
84
87
  const pane = hooks.tagPane() ?? process.env['TMUX_PANE'] ?? currentTmux()?.pane;
85
88
  if (!remote && pane !== undefined && inTmux())
86
89
  closePane(pane);
@@ -74,22 +74,16 @@ import { mark } from '../../core/timing.js';
74
74
  function quoteIfNeeded(word) {
75
75
  return /^[A-Za-z0-9._:@/-]+$/.test(word) ? word : shellQuote(word);
76
76
  }
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,
77
+ export async function runAttach(target, observer, canvasName, wakeParked = true,
85
78
  /** Called synchronously just before the viewer takes the terminal. */
86
79
  onConnected) {
87
80
  // The viewer is its own esbuild bundle with its own copy of the settings cache: install the person's settings before anything
88
81
  // calls readConfig (theme, keybindings, ChatView's field initializers all do). A caller that holds them hands them over.
89
- if (held === undefined)
82
+ const pending = typeof target === 'string' ? undefined : target;
83
+ if (pending === undefined)
90
84
  await loadPersonSettingsViaApi();
91
85
  else
92
- installPersonSettingsDto(held.settings);
86
+ installPersonSettingsDto(pending.settings);
93
87
  // 1. Resolve the attach target (session/connection.ts). Nothing here waits for the broker:
94
88
  // the viewer paints first and `connection.dial()` (revive, connect, hello) runs after it, so a
95
89
  // dial failure is shown by the viewer (see `dialBroker` below). An unknown node is still a plain CLI error.
@@ -99,8 +93,14 @@ onConnected) {
99
93
  // and no collaborator may re-derive it.
100
94
  const role = resolveHelloRole(observer);
101
95
  const clientId = randomUUID();
102
- const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
103
- const { remote, canvasSource, meta, socket } = connection;
96
+ const connection = connectToNode(canvasName, wakeParked);
97
+ const { remote, canvasSource, socket } = connection;
98
+ const bound0 = typeof target === 'string'
99
+ ? await connection.bind(target)
100
+ : { meta: { cwd: target.cwd, profile_id: target.profile_id }, nodeIdentity: undefined };
101
+ const meta = bound0.meta;
102
+ /** True until the create request returns and the node is bound. */
103
+ let starting = pending !== undefined;
104
104
  // 2. Theme + keybindings — pi's components throw "Theme not initialized"
105
105
  // otherwise. One KeybindingsManager feeds BOTH editor and input; the
106
106
  // editor may resolve a separate pi-tui instance, so mirror onto it (and
@@ -126,7 +126,7 @@ onConnected) {
126
126
  cwd: meta.cwd,
127
127
  palette: pal,
128
128
  hideThinking: true,
129
- banner: [...croutonBannerLines(buildBannerInfo(meta)), pal.muted(`Older messages: crtr node inspect transcript ${nodeId}`)],
129
+ banner: [...croutonBannerLines(buildBannerInfo(meta)), ...(typeof target === 'string' ? [pal.muted(`Older messages: crtr node inspect transcript ${target}`)] : [])],
130
130
  // Local only: a remote attach cannot read this canvas's ticket dirs, so it
131
131
  // has nothing to render a page block from.
132
132
  inlinePageBlocks: !remote,
@@ -165,7 +165,7 @@ onConnected) {
165
165
  delete process.env['CRTR_ATTACH_DRAFT'];
166
166
  if (restoredDraft !== undefined)
167
167
  editor.setText(restoredDraft);
168
- const ctx = { nodeId, remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
168
+ const ctx = { nodeId: typeof target === 'string' ? target : '', remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
169
169
  // The pending-request strip below the recap goal line. Its hooks close over
170
170
  // collaborators built later (paneFocus, roster, inbox, setNotice) — all are
171
171
  // constructed before any key or refresh can invoke them.
@@ -179,7 +179,7 @@ onConnected) {
179
179
  });
180
180
  containers.header.addChild(strip.component);
181
181
  const userConfig = readConfig('user');
182
- const initialWhip = held?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
182
+ const initialWhip = pending?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
183
183
  delete process.env['CRTR_ATTACH_INITIAL_WHIP'];
184
184
  const startupTicketId = process.env['CRTR_ATTACH_OPEN_TICKET'];
185
185
  if (startupTicketId !== undefined)
@@ -248,7 +248,7 @@ onConnected) {
248
248
  ...(inboxProfile === undefined ? {} : { profile: inboxProfile }),
249
249
  ...(remote ? {} : { scan: async () => {
250
250
  const client = cliClient();
251
- const [inbox, history] = await Promise.all([client.listHumanInbox(), client.getInboxHistory(nodeId, { state: 'pending' })]);
251
+ const [inbox, history] = await Promise.all([client.listHumanInbox(), client.getInboxHistory(ctx.nodeId === '' ? undefined : ctx.nodeId, { state: 'pending' })]);
252
252
  const merged = new Map();
253
253
  for (const item of inbox.tickets) {
254
254
  const row = inboxRowFromDTO(item);
@@ -333,7 +333,7 @@ onConnected) {
333
333
  const inventory = createEditorInventory(ctx, capabilities, { setNotice, bindings: () => crouterBindings, fdPath, frecency });
334
334
  // Canvas identity (kind/mode/lifecycle) behind the context badge. A remote
335
335
  // attach starts without one, so load it as soon as the viewer exists.
336
- const identity = createNodeIdentity(ctx, connection.nodeIdentity, {
336
+ const identity = createNodeIdentity(ctx, bound0.nodeIdentity, {
337
337
  isTornDown: () => lifecycle.isTornDown(),
338
338
  onChanged: () => {
339
339
  editorChrome.syncContextBadge();
@@ -377,6 +377,10 @@ onConnected) {
377
377
  // is a real TTY, so `surface
378
378
  // inspect` hosts in-place inside it.
379
379
  const openInspector = (section) => {
380
+ if (starting) {
381
+ setNotice('The node is starting — try again in a moment');
382
+ return;
383
+ }
380
384
  if (!inTmux()) {
381
385
  setNotice('Inspector requires tmux');
382
386
  return;
@@ -384,7 +388,7 @@ onConnected) {
384
388
  setNotice(`Opening Inspector (${section})…`);
385
389
  const home = envHomeOverride();
386
390
  const prefix = home === undefined ? '' : `CRTR_HOME=${shellQuote(home)} `;
387
- const cmd = `${prefix}crtr surface inspect ${shellQuote(nodeId)} --section ${section}`;
391
+ const cmd = `${prefix}crtr surface inspect ${shellQuote(ctx.nodeId)} --section ${section}`;
388
392
  execFile('tmux', ['display-popup', '-E', '-T', ` inspector · ${section} `, '-w', '90%', '-h', '85%', ...surfaceTmuxStyleArgs(), cmd], () => {
389
393
  chromeRefresh.refresh();
390
394
  });
@@ -424,7 +428,7 @@ onConnected) {
424
428
  const paneFocus = createPaneFocus(editor, [roster.active, strip.active, ticketPanel.active]);
425
429
  // The GRAPH overlay — a bounded, centered modal navigator over the same
426
430
  // 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);
431
+ const graphOverlay = new GraphOverlay(tui, () => ctx.nodeId, () => chromeRefresh.asks(), pal, crouterBindings, canvasSource, role, (cause) => chromeRefresh.reportFailure('canvas graph refresh', cause), setNotice);
428
432
  const helpOverlay = new HelpOverlay(tui, pal);
429
433
  helpOverlay.setBindings(crouterBindings);
430
434
  // The canvas-chrome refresh/poll engine: owns the ask-count map, the
@@ -468,6 +472,7 @@ onConnected) {
468
472
  agentDir: () => sync.state().agentDir,
469
473
  openNodeMetadata: () => openInspector('overview'),
470
474
  isDormant: () => reconnect.isDormant(),
475
+ isStarting: () => starting,
471
476
  copyTarget,
472
477
  moreDetail: () => chatView.moreDetail(),
473
478
  lessDetail: () => chatView.lessDetail(),
@@ -504,7 +509,7 @@ onConnected) {
504
509
  };
505
510
  // `[[…]]` document links: readable names and browser URLs.
506
511
  const documentLinks = createDocumentLinks({
507
- selfNodeId: nodeId,
512
+ selfNodeId: () => ctx.nodeId === '' ? undefined : ctx.nodeId,
508
513
  remote,
509
514
  canvasSource,
510
515
  port: userConfig.document_port,
@@ -523,7 +528,7 @@ onConnected) {
523
528
  }
524
529
  void canvasSource.listNodes()
525
530
  .then((nodes) => {
526
- const family = relatedNodes(nodes, nodeId);
531
+ const family = relatedNodes(nodes, ctx.nodeId);
527
532
  launchProfileFileSearch({
528
533
  cwd: meta.cwd,
529
534
  nodeDirs: family.map((node) => node.cwd),
@@ -582,6 +587,10 @@ onConnected) {
582
587
  // node and flags, through the `crtr` launcher so it loads the selected
583
588
  // release. A shell hosting the viewer stays alive underneath.
584
589
  const restartViewer = (env = {}) => {
590
+ if (starting) {
591
+ setNotice('The node is starting — try again in a moment');
592
+ return;
593
+ }
585
594
  const draft = editor.getText();
586
595
  // Checked before teardown: a failed exec after it would close the pane and lose the draft.
587
596
  if (process.execve === undefined || Buffer.byteLength(draft) > 100_000) {
@@ -589,7 +598,7 @@ onConnected) {
589
598
  return;
590
599
  }
591
600
  teardown('detach');
592
- const args = ['surface', 'attach', 'to', nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
601
+ const args = ['surface', 'attach', 'to', ctx.nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
593
602
  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
603
  };
595
604
  // One automatic restart per daemon release: if the launcher still loads another release, a second try would loop.
@@ -622,7 +631,7 @@ onConnected) {
622
631
  process.on('unhandledRejection', onUnhandledRejection);
623
632
  const removeRejectionGuard = () => { process.off('unhandledRejection', onUnhandledRejection); };
624
633
  // The `@crtr_node` pane tag, claimed after the startup checkpoint below.
625
- const paneTag = createPaneTag(remote, nodeId);
634
+ const paneTag = createPaneTag(remote, ctx.nodeId === '' ? undefined : ctx.nodeId);
626
635
  // Lifecycle / teardown — always restore the terminal, exactly once
627
636
  // (session/teardown.ts owns the ordering rules and the four end reasons).
628
637
  // `stopLocal` is this viewer's own shutdown: every collaborator it built
@@ -658,7 +667,7 @@ onConnected) {
658
667
  // and this is only ever read once teardown actually runs.
659
668
  lastSocketError: () => startupFailure ?? reconnect.lastSocketError(),
660
669
  undelivered: () => (settled ? [] : [...heldFrames.flatMap((f) => ('text' in f ? [f.text] : [])), ...(editor.getText().trim() === '' ? [] : [editor.getText()])]),
661
- reattachCommand: `crtr surface attach to ${quoteIfNeeded(nodeId)}` +
670
+ reattachCommand: () => `crtr surface attach to ${quoteIfNeeded(ctx.nodeId)}` +
662
671
  (observer ? ' --observer' : '') +
663
672
  (canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
664
673
  tagPane: paneTag.pane,
@@ -714,7 +723,7 @@ onConnected) {
714
723
  file,
715
724
  pane: tmux.pane,
716
725
  cwd: meta.cwd,
717
- nodeId,
726
+ nodeId: ctx.nodeId,
718
727
  observer,
719
728
  beforeRespawn: paneTag.clear,
720
729
  });
@@ -840,6 +849,7 @@ onConnected) {
840
849
  },
841
850
  whip,
842
851
  reloadViewer: () => restartViewer(),
852
+ isStarting: () => starting,
843
853
  });
844
854
  // Registered only now: every collaborator `stopLocal` touches (the key
845
855
  // listener included) finally exists, so a signal cannot race a half-built
@@ -858,7 +868,7 @@ onConnected) {
858
868
  // The viewer is painted and interactive: now revive, connect and say hello. A live viewer's tmux binding install waits for the welcome
859
869
  // 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
870
  const dialBroker = async () => {
861
- mark('viewer.connect_start', { node: nodeId });
871
+ mark('viewer.connect_start', { node: ctx.nodeId });
862
872
  let parked;
863
873
  try {
864
874
  parked = await connection.dial();
@@ -892,7 +902,7 @@ onConnected) {
892
902
  if (t.startsWith('/') || t.startsWith('!'))
893
903
  refused.push(frame.text);
894
904
  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)}`));
905
+ 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
906
  }
897
907
  if (refused.length > 0) {
898
908
  editor.setText([...refused, editor.getText()].filter((x) => x.trim() !== '').join('\n'));
@@ -906,12 +916,49 @@ onConnected) {
906
916
  inventory.setCommands(parked.commands);
907
917
  // A parked conversation has no broker, so the attach bridge never sees it shown.
908
918
  if (!remote)
909
- void cliClient().markNodeRead(nodeId).catch(() => undefined);
919
+ void cliClient().markNodeRead(ctx.nodeId).catch(() => undefined);
910
920
  scheduleTmuxBindingInstall();
911
921
  reconnect.startDormant();
912
922
  };
913
- void dialBroker();
914
- chromeRefresh.start();
923
+ if (pending === undefined) {
924
+ void dialBroker();
925
+ chromeRefresh.start();
926
+ }
927
+ else {
928
+ void (async () => {
929
+ let detail;
930
+ try {
931
+ detail = await pending.created;
932
+ }
933
+ catch (err) {
934
+ if (lifecycle.isTornDown())
935
+ return;
936
+ // No node exists: print the create error and anything typed that was never delivered.
937
+ startupFailure = err instanceof Error ? err.message : String(err);
938
+ process.exitCode = 1;
939
+ teardown('create-failed');
940
+ return;
941
+ }
942
+ if (lifecycle.isTornDown())
943
+ return;
944
+ ctx.nodeId = detail.node_id;
945
+ const bound = await connection.bind(detail.node_id, detail);
946
+ starting = false;
947
+ mark('viewer.node_bound', { node: detail.node_id });
948
+ if (bound.nodeIdentity !== undefined)
949
+ identity.set(bound.nodeIdentity);
950
+ paneTag.bindNode(detail.node_id);
951
+ chatView.setBannerHint(pal.muted(`Older messages: crtr node inspect transcript ${detail.node_id}`));
952
+ chromeRefresh.start();
953
+ void dialBroker();
954
+ })().catch((err) => {
955
+ if (lifecycle.isTornDown())
956
+ return;
957
+ startupFailure = err instanceof Error ? err.message : String(err);
958
+ process.exitCode = 1;
959
+ teardown('broker-gone');
960
+ });
961
+ }
915
962
  if (startupTicketId !== undefined && startupTicketId !== '' && !remote) {
916
963
  // The dashboard opened this conversation for its oldest pending ask: show the ask first.
917
964
  // 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,