@north-light/cli 0.3.693 → 0.3.695

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) 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/api/errors.js +1 -1
  10. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  11. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  12. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  14. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  15. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  16. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  17. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  18. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  19. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  20. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  21. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  22. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  23. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  24. package/dist/cli.js +6 -6
  25. package/dist/clients/attach/session/connection.d.ts +11 -2
  26. package/dist/clients/attach/session/connection.js +1 -1
  27. package/dist/clients/attach/session/keys.d.ts +2 -0
  28. package/dist/clients/attach/session/keys.js +1 -1
  29. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  30. package/dist/clients/attach/session/reconnect.js +1 -1
  31. package/dist/clients/attach/viewer.js +538 -537
  32. package/dist/commands/node/inspect.js +9 -9
  33. package/dist/commands/node-worktree.js +1 -1
  34. package/dist/commands/pkg/market-manage.js +1 -1
  35. package/dist/commands/pkg/plugin-manage.js +1 -1
  36. package/dist/commands/surface/node/placement.d.ts +2 -2
  37. package/dist/commands/surface/node/placement.js +1 -1
  38. package/dist/commands/surface.js +1 -1
  39. package/dist/commands/sys/update.js +1 -1
  40. package/dist/core/broker-client/client.d.ts +6 -9
  41. package/dist/core/broker-client/client.js +1 -1
  42. package/dist/core/canvas/canvas.js +7 -7
  43. package/dist/core/canvas/types.d.ts +0 -2
  44. package/dist/core/config.js +1 -1
  45. package/dist/core/conversation-store/row-store.js +10 -10
  46. package/dist/core/graph/exposures.js +1 -1
  47. package/dist/core/graph/names.js +9 -9
  48. package/dist/core/graph/watches.js +1 -1
  49. package/dist/core/installed-plugins.js +1 -1
  50. package/dist/core/keybindings/attach-control.d.ts +3 -0
  51. package/dist/core/keybindings/attach-control.js +1 -1
  52. package/dist/core/keybindings/catalog.js +1 -1
  53. package/dist/core/ledger/chunks.d.ts +3 -1
  54. package/dist/core/ledger/chunks.js +2 -2
  55. package/dist/core/ledger/index.d.ts +1 -1
  56. package/dist/core/ledger/index.js +1 -1
  57. package/dist/core/ledger/read.d.ts +4 -0
  58. package/dist/core/ledger/read.js +2 -2
  59. package/dist/core/llm/run.js +2 -2
  60. package/dist/core/logged-step-timings.d.ts +7 -0
  61. package/dist/core/logged-step-timings.js +1 -0
  62. package/dist/core/permissions/evaluator.d.ts +2 -1
  63. package/dist/core/permissions/evaluator.js +2 -2
  64. package/dist/core/providers/receipts.js +1 -1
  65. package/dist/core/runs/operations.js +8 -8
  66. package/dist/core/runtime/broker/model-adapter.js +3 -3
  67. package/dist/core/runtime/broker.js +1 -1
  68. package/dist/core/runtime/nodes.d.ts +1 -1
  69. package/dist/core/runtime/nodes.js +1 -1
  70. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  71. package/dist/core/runtime/placement-tmux.js +1 -1
  72. package/dist/core/runtime/revive.js +2 -2
  73. package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
  74. package/dist/core/runtime/runner/machine/ops.js +1 -1
  75. package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
  76. package/dist/core/runtime/runner/machine/runner.js +1 -1
  77. package/dist/core/runtime/tmux-bindings.js +3 -3
  78. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  79. package/dist/core/runtime/tmux-driver.js +6 -6
  80. package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
  81. package/dist/core/scoped-state/imported-mac-installs.js +2 -0
  82. package/dist/core/spaces/stop.js +1 -1
  83. package/dist/core/step-timings.d.ts +7 -1
  84. package/dist/core/step-timings.js +1 -1
  85. package/dist/core/worktree-close.js +4 -6
  86. package/dist/core/worktree-landing.d.ts +0 -38
  87. package/dist/core/worktree-landing.js +2 -3
  88. package/dist/core/worktree-sweep.d.ts +0 -1
  89. package/dist/core/worktree-sweep.js +4 -6
  90. package/dist/core/worktree.d.ts +0 -4
  91. package/dist/core/worktree.js +13 -15
  92. package/dist/daemon/api/app-listener.d.ts +1 -0
  93. package/dist/daemon/api/app-listener.js +10 -10
  94. package/dist/daemon/api/bridge.js +4 -4
  95. package/dist/daemon/api/handlers/attach.js +1 -1
  96. package/dist/daemon/api/handlers/conversations.js +3 -3
  97. package/dist/daemon/api/server.d.ts +1 -1
  98. package/dist/daemon/api/server.js +1 -1
  99. package/dist/daemon/cron/armed-context.js +1 -1
  100. package/dist/daemon/crtrd.js +20 -18
  101. package/dist/daemon/machine-link/client.d.ts +5 -1
  102. package/dist/daemon/machine-link/client.js +1 -1
  103. package/dist/daemon/machine-link/forward.js +1 -1
  104. package/dist/daemon/machine-link/holder.js +3 -3
  105. package/dist/daemon/pidfile.js +2 -1
  106. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  107. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  108. package/dist/daemon/runs/append-section.js +2 -2
  109. package/dist/daemon/runs/observer.js +3 -3
  110. package/dist/shared/env.d.ts +8 -3
  111. package/dist/shared/env.js +2 -2
  112. package/dist/types.d.ts +1 -1
  113. package/dist/types.js +1 -1
  114. package/docs/apps/guides/stream-a-run.md +6 -7
  115. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  116. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  117. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  118. package/docs/concepts/scopes-and-trust.md +1 -1
  119. package/docs/concepts/why-a-daemon.md +1 -1
  120. package/docs/sdk/README.md +13 -41
  121. package/docs/sdk/client.md +5 -7
  122. package/docs/sdk/docker.md +1 -1
  123. package/docs/sdk/errors.md +3 -43
  124. package/docs/sdk/getting-started.md +11 -83
  125. package/docs/sdk/release-notes.md +10 -0
  126. package/docs/sdk/resources.md +11 -44
  127. package/package.json +3 -3
  128. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  129. package/packages/crouter-api/dist/api/contract.js +1 -1
  130. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  131. package/packages/crouter-api/dist/api/errors.js +1 -1
  132. package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
  133. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  134. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  135. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  136. package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
  137. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  138. package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
  139. package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
  140. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  141. package/packages/crouter-api/dist/commands/surface.js +2 -3
  142. package/packages/crouter-api/dist/commands/sys/update.js +5 -3
  143. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  144. package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
  145. package/packages/crouter-api/dist/core/config.js +10 -3
  146. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  147. package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
  148. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  149. package/packages/crouter-api/dist/core/graph/watches.js +1 -1
  150. package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
  151. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  152. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  153. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  154. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  155. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  156. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  157. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  158. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  159. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  160. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  161. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  162. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  163. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  164. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  165. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  166. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
  167. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  168. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  169. package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
  170. package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
  171. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  172. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  173. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  174. package/packages/crouter-api/dist/core/worktree.js +9 -74
  175. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  176. package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
  177. package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
  178. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  179. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  180. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  181. package/packages/crouter-api/dist/shared/env.js +15 -4
  182. package/packages/crouter-api/dist/types.js +1 -1
  183. package/packages/crouter-api/package.json +1 -1
  184. package/packages/crouter-identity/package.json +1 -1
  185. package/packages/crouter-plugin/dist/serve.js +1 -1
  186. package/packages/crouter-plugin/package.json +3 -3
  187. package/runtime.lock.json +14 -14
  188. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  189. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  190. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  191. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  192. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  193. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  194. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  195. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  196. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  197. package/dist/commands/surface-reload.d.ts +0 -7
  198. package/dist/commands/surface-reload.js +0 -1
  199. package/docs/sdk/bash.md +0 -39
  200. package/docs/sdk/files.md +0 -49
  201. package/docs/sdk/guides/README.md +0 -17
  202. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  203. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  204. package/docs/sdk/guides/human-approval.md +0 -24
  205. package/docs/sdk/guides/typed-extraction.md +0 -24
  206. package/docs/sdk/nodes.md +0 -194
  207. package/docs/sdk/streaming.md +0 -149
  208. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -1,149 +0,0 @@
1
- ---
2
- title: Streaming
3
- description: Follow assistant text, tool activity, reports, and outcomes as an agent runs.
4
- ---
5
-
6
- # Streaming
7
-
8
- Watch a run as it works: assistant text as it is produced, tool calls as they start and finish, reports as they are pushed, and the settled outcome.
9
-
10
- Streaming a run of an app (forwarding it to a browser, following the reply to one message, `event: idle`, typed run events) is on the SDK docs site: [Stream a run](https://sdk.docs.northlight.ai/docs/guides/stream-a-run).
11
-
12
- ## The SDK surface
13
-
14
- ```ts
15
- const stream = client.nodes.stream({ prompt: 'Fix the failing test', cwd }, { headers: { 'x-trace': 'run-9' } });
16
-
17
- stream.on('node.output_text.delta', (event) => process.stdout.write(event.delta));
18
-
19
- for await (const event of stream) {
20
- // the same events, typed by `type`
21
- }
22
-
23
- const outcome = await stream.finalOutcome(); // resolves on node.settled
24
- stream.abort(); // ends the HTTP response; the node keeps running
25
- ```
26
-
27
- | Member | Behaviour |
28
- |---|---|
29
- | `client.nodes.stream(params, options?)` | Creates the node, then opens its event stream. Returns **synchronously**; `stream.node` is a `Promise<NodeDetailDTO>` for the created node. The request options apply to creation and to opening the stream, except `timeout`, because a stream has no wall-clock timeout. |
30
- | `client.nodes.events(id, options?)` | Validates and retrieves an existing node, then streams it. `options` is `NodeEventsOptions`: `after` plus request `headers`, `signal`, and `maxRetries`; it deliberately has no `timeout`. |
31
- | `.on(type, listener)` / `.off(type, listener)` | Typed event emitter; each returns the `NodeStream`. |
32
- | `[Symbol.asyncIterator]()` | Yields the same `NodeEventDTO` union. |
33
- | `.finalOutcome()` | Returns `Promise<NodeOutcomeDTO>`, resolving on `node.settled` and rejecting on a terminal `error` event or a connection failure. |
34
- | `.abort()` | Aborts the underlying `fetch`. An in-flight iterator and `finalOutcome()` reject with `APIUserAbortError`. Passing your own `signal` in the options aborts the stream the same way; `NodeStream` exposes no `signal` property. |
35
-
36
- The method is called `events`, not `subscribe`: a subscription is already a push-delivery edge between two nodes on the canvas, and one word must not mean two things.
37
-
38
- **A stream is an observer, never a lifecycle hold.** Disconnecting drops your subscriber and leaves the node running. Opening a stream never revives a dormant node — call `client.nodes.revive(id)` first if that is what you want.
39
-
40
- ## Activity helper
41
-
42
- `followActivity(stream, { describe? })` turns streamed tool-call events into immutable `ActivityStep[]` snapshots for a plain activity feed. `describeToolDefault(tool, summary)` names the common tools; pass `describe` to use labels for your application or return `null` to hide a tool call. Tool summaries describe the argument shape, never argument values or raw arguments.
43
-
44
- ```ts
45
- import { followActivity } from '@north-light/sdk';
46
-
47
- for await (const steps of followActivity(stream)) {
48
- render(steps);
49
- }
50
- ```
51
-
52
- A step starts as `running`; a `node.tool_call.completed` event changes it to `done` when `status` is `ok` or `failed` when `status` is `error`.
53
-
54
- ## Events
55
-
56
- Every event except `error` carries `node_id` and `sequence_number` in addition to the fields listed. `error` carries only its error object.
57
-
58
- | Event | `data` |
59
- |---|---|
60
- | `node.output_text.delta` | `{ node_id, sequence_number, delta }` |
61
- | `node.output_text.done` | `{ node_id, sequence_number, text }` |
62
- | `node.tool_call.started` | `{ node_id, sequence_number, tool_call_id, tool, summary }` |
63
- | `node.tool_call.completed` | `{ node_id, sequence_number, tool_call_id, tool, status: 'ok' \| 'error', summary }` |
64
- | `node.turn.started` | `{ node_id, sequence_number }` |
65
- | `node.turn.completed` | `{ node_id, sequence_number }` |
66
- | `node.report.pushed` | `{ node_id, sequence_number, report }` |
67
- | `node.status.changed` | `{ node_id, sequence_number, status }`, where `status` can also be stream-only `'dormant'` |
68
- | `node.settled` | `{ node_id, sequence_number, outcome }` — terminal; the daemon ends the response after it |
69
- | `error` | `{ error: { code: 'stream_gap' \| 'stream_dropped' \| 'stream_error', message, details?: { earliest_sequence?: number } } }` — `stream_gap` is recoverable; the other codes terminate the response |
70
-
71
- A turn can emit more than one `node.turn.started`. A `run.message` sent while the turn is running steers by default, so the agent reads it at its next step and the stream emits another `node.turn.started` whose `input.message_ids` holds the joined message; the turn ends with one `node.turn.completed` whose `message_ids` lists every message that joined it. A reply to one message therefore ends at the turn's completion, not at the next `node.turn.started`; the SDK's `RunReply` stops yielding text once a later message joins. Send `{ steer: false }` to start a separate turn after the current one ends.
72
-
73
- `summary` on a tool-call event states whether arguments are null, an array and its item count, an object and its field count, or a primitive type. It never includes argument values or tool output.
74
-
75
- **Deliberately not carried:** thinking deltas, the model's tool-call construction deltas, raw tool output, and the system prompt. Those belong to the owner's viewer, not to an application's run stream.
76
-
77
- ## The route
78
-
79
- ```
80
- GET /v1/nodes/{id}/events Accept: text/event-stream
81
- ?after=<sequence_number> resume from a cursor (optional)
82
- ```
83
-
84
- Server-sent events: one record per event as `event: <type>`, `data: <JSON>`, blank line, plus `: keepalive` comment lines every 15 s. Authentication is the daemon's existing rule — filesystem permission on the unix socket, bearer token over TCP.
85
-
86
- ### What you get depending on the node's state
87
-
88
- | Node state when you call | What the stream does |
89
- |---|---|
90
- | Already settled | Writes retained events when available, ending in `node.settled`; otherwise writes `node.settled` with the outcome and ends. Nothing is revived. |
91
- | Running | Streams live, seeded as described below. |
92
- | Dormant and not settled | Writes `node.status.changed { status: 'dormant' }` and holds the response open with keepalives. It starts streaming if and when the daemon brings a broker up for that node. |
93
-
94
- A node can settle between your `create` and your `events` call, so both branches are ordinary. Either way the terminal event is `node.settled`, read from the same outcome row `nodes.outcome` reads — a client that joins after settlement and a client that was live at settlement see the same outcome.
95
-
96
- ## Sequence, resume, and failure
97
-
98
- `sequence_number` is monotonic per node while that node's in-memory stream hub exists. The daemon keeps one in-memory ring per streamed node holding the last 512 events or 256 KiB, whichever binds first.
99
-
100
- | Situation | Behaviour |
101
- |---|---|
102
- | You join a run already in progress | First replays already-pushed reports oldest first, then seeds from the broker's snapshot: one `node.output_text.done` per completed assistant message, then one `node.output_text.delta` carrying the accumulated partial, then live. No content is lost — only delta granularity. |
103
- | A second subscriber joins | Seeded from the ring, so both subscribers see the same sequence numbers. |
104
- | `after=N` within the retained range | Replays events after `N`. |
105
- | `after=N` outside the retained range, including a future cursor | An `error` event with code **`stream_gap`** carries the earliest available sequence, then the stream continues from that point. It never silently skips. |
106
- | One event exceeds the 256 KiB replay budget | Live subscribers receive it, but the daemon clears the resume ring. A cursor before that event gets `stream_gap`; a cursor on it resumes at the next retained event. |
107
- | Your HTTP reader is too slow | The daemon ends the response with an `error` event whose code is **`stream_dropped`**. One slow reader cannot stall the engine. |
108
- | The node's broker is replaced or its observer socket closes | The daemon reconnects and emits `node.status.changed`. Sequence continues while the stream hub remains in memory. |
109
- | The daemon restarts | The ring is gone. A resuming client gets `stream_gap` with `earliest_sequence: 1`. There is no durable event log. |
110
- | You disconnect | Your subscriber is dropped. The node keeps running. |
111
-
112
- ### Resuming
113
-
114
- ```ts
115
- import { APIError } from '@north-light/sdk';
116
-
117
- let cursor: number | undefined;
118
-
119
- for (;;) {
120
- const stream = client.nodes.events(id, { after: cursor });
121
- try {
122
- for await (const event of stream) {
123
- if (event.type === 'error') {
124
- if (event.error.code === 'stream_gap') {
125
- console.warn('missed events before', event.error.details?.earliest_sequence);
126
- continue; // the stream continues from the floor
127
- }
128
- throw new APIError(0, event.error.code, event.error.message, event.error.details);
129
- }
130
- cursor = event.sequence_number;
131
- handle(event);
132
- }
133
- return; // ended on node.settled
134
- } catch (error) {
135
- if (error instanceof APIError && error.code === 'stream_dropped') continue;
136
- throw error;
137
- }
138
- }
139
- ```
140
-
141
- `stream_gap` is recoverable and the stream continues after it. `stream_dropped` is terminal for that HTTP response — reconnect with the cursor you last saw.
142
-
143
- ## Identifier validation
144
-
145
- `nodes.events(id, options?)` validates `id` before it requests the node or opens SSE. Because it returns a `NodeStream` synchronously, an invalid node identifier rejects `stream.node`, `stream.finalOutcome()`, and an iteration with `TypeError`; no request is sent. See [Errors](./errors.md#identifier-validation).
146
-
147
- ## Event shapes depend on the pinned pi version
148
-
149
- The delta and tool-call shapes come from the installed `@earendil-works/pi-agent-core` and `pi-ai` packages, not from crouter. The daemon's translator is the one place that depends on them. A pi version bump must be checked against it.
@@ -1,129 +0,0 @@
1
- // `crtr surface reload` — hot-reload a viewer pane in place.
2
- //
3
- // A viewer process loads its runtime generation at startup and never reloads
4
- // it, so after a runtime roll an already-open pane keeps running the old
5
- // generation against the new crtrd. Respawning the pane with the viewer's own
6
- // `crtr surface attach to <id>` command line means the fresh process picks up
7
- // the currently selected generation while the pane and broker are untouched.
8
- import { defineLeaf } from '../core/command.js';
9
- import { InputError } from '../core/io.js';
10
- import { listProcessTable } from '../core/canvas/pid.js';
11
- import { displayMessage } from '../core/runtime/tmux-chrome.js';
12
- import { nodeInPane, paneCurrentPath, panePid, paneStartCommand, respawnPaneInPlace, respawnPaneSync, viewerSplitEnv, } from './surface/node/placement.js';
13
- /** True when `rootPid` (the pane's `#{pane_pid}`) or any descendant of it is a
14
- * live `crtr surface attach to <nodeId>` viewer process. This is how a
15
- * shell-hosted viewer is recognized: older panes were opened as a login shell
16
- * that then ran the viewer, so their `#{pane_start_command}` is `zsh -l` and
17
- * only the live process tree reveals the viewer. One process-table snapshot, walked
18
- * from the pane's root pid. */
19
- function paneTreeHasViewer(rootPid, nodeId) {
20
- const table = listProcessTable();
21
- if (table === null)
22
- return false;
23
- const childrenOf = new Map();
24
- const commandOf = new Map();
25
- for (const { pid, ppid, command } of table) {
26
- commandOf.set(pid, command);
27
- const siblings = childrenOf.get(ppid) ?? [];
28
- siblings.push(pid);
29
- childrenOf.set(ppid, siblings);
30
- }
31
- // Node ids are [a-z0-9-] so splicing one into a regex is safe. The viewer
32
- // shows up as e.g. `node /opt/homebrew/bin/crtr surface attach to <id>`.
33
- const viewer = new RegExp(`(?:^|\\s)surface attach to ${nodeId}(?:\\s|$)`);
34
- const queue = [rootPid];
35
- while (queue.length > 0) {
36
- const pid = queue.pop();
37
- const command = commandOf.get(pid);
38
- if (command !== undefined && viewer.test(command))
39
- return true;
40
- const kids = childrenOf.get(pid);
41
- if (kids !== undefined)
42
- queue.push(...kids);
43
- }
44
- return false;
45
- }
46
- /** The node a `crtr surface attach to <id>` command line targets. Panes opened
47
- * by a respawn path (the Markdown file-open bridge, the review companion) carry
48
- * a shell-quoted id, so the raw command line is not comparable to the canonical
49
- * one — the target node is. */
50
- export function attachTargetNode(command) {
51
- const match = /(?:^|\s)surface attach to\s+(?:'([^']*)'|"([^"]*)"|(\S+))/.exec(command);
52
- return match?.[1] ?? match?.[2] ?? match?.[3];
53
- }
54
- export const surfaceReloadLeaf = defineLeaf({
55
- name: 'reload',
56
- description: 'respawn a viewer pane in place onto the current runtime generation',
57
- whenToUse: 'a viewer pane predates a runtime roll and should be refreshed onto the selected generation without losing the pane or the node it views',
58
- help: {
59
- name: 'surface reload',
60
- summary: 'kill and re-run a viewer pane’s `crtr surface attach to <node>` command line in place, so the fresh viewer picks up the currently selected runtime generation',
61
- params: [
62
- { kind: 'flag', name: 'pane', type: 'string', required: false, constraint: 'tmux pane id hosting the viewer to reload. Defaults to $TMUX_PANE / your current pane. The Alt+C menu passes this for you.' },
63
- ],
64
- output: [
65
- { name: 'pane', type: 'string', required: true, constraint: 'The respawned tmux pane.' },
66
- { name: 'node_id', type: 'string', required: true, constraint: 'The node whose viewer was reloaded.' },
67
- ],
68
- outputKind: 'object',
69
- effects: ['Kills the pane’s viewer process and re-runs the viewer command line in the same pane; the node’s broker engine keeps running untouched.'],
70
- },
71
- run: async (input) => {
72
- const pane = input['pane'] ?? process.env['TMUX_PANE'];
73
- if (pane === undefined || pane === '') {
74
- throw new InputError({ error: 'not_in_tmux', message: 'viewer reload is tmux-only — no tmux pane to target', next: 'Run it inside tmux, or pass --pane <pane-id> of a tmux viewer pane.' });
75
- }
76
- // Only respawn a pane that actually hosts a viewer FOR THE TAGGED NODE. The
77
- // node tag alone is not enough — workspace shell panes carry `@crtr_node`
78
- // too, and respawning one would kill a live shell the user is working in.
79
- // Two shapes qualify:
80
- // 1. The pane's start command IS the viewer (tmux launched `crtr surface
81
- // attach to <id>` as the pane command) → a bare `respawn-pane -k`
82
- // replays that exact line.
83
- // 2. The pane was started as a shell (`zsh -l`) that is now RUNNING the
84
- // viewer as a live child process → respawn with an explicit
85
- // `crtr surface attach to <node>` command, because replaying the
86
- // shell line would leave a bare shell instead of a viewer.
87
- // A tagged pane sitting at a shell prompt with no live viewer matches
88
- // neither and is refused — killing it would lose the user's shell.
89
- const nodeId = nodeInPane(pane);
90
- if (nodeId === undefined) {
91
- displayMessage('crtr: no viewer in pane', pane);
92
- throw new InputError({ error: 'no_viewer', message: 'this pane does not host an attach viewer', next: 'Pass --pane <pane-id> for a pane running `crtr surface attach to <node>`.' });
93
- }
94
- const viewerCommand = `crtr surface attach to ${nodeId}`;
95
- // tmux wraps #{pane_start_command} in literal double quotes.
96
- const startCommand = paneStartCommand(pane)?.replace(/^"|"$/g, '');
97
- if (startCommand !== undefined && startCommand.startsWith('crtr surface attach ')) {
98
- // The start command must target the TAGGED node — a mismatch means the
99
- // tag is stale or the viewer belongs to another node; don't touch it.
100
- if (attachTargetNode(startCommand) !== nodeId) {
101
- displayMessage('crtr: viewer/node mismatch in pane', pane);
102
- throw new InputError({ error: 'no_viewer', message: `this pane's viewer command (${startCommand}) does not match its node tag (${nodeId})`, next: 'Pass --pane <pane-id> for a pane running `crtr surface attach to <node>`.' });
103
- }
104
- if (!respawnPaneInPlace(pane)) {
105
- displayMessage('crtr: viewer reload failed', pane);
106
- throw new InputError({ error: 'respawn_failed', message: `tmux could not respawn pane ${pane}`, next: 'Check the tmux server is reachable, then retry.' });
107
- }
108
- displayMessage('crtr: viewer reloaded', pane);
109
- return { pane, node_id: nodeId };
110
- }
111
- const rootPid = panePid(pane);
112
- if (rootPid === undefined || !paneTreeHasViewer(rootPid, nodeId)) {
113
- displayMessage('crtr: no viewer in pane', pane);
114
- throw new InputError({ error: 'no_viewer', message: 'this pane does not host an attach viewer', next: 'Pass --pane <pane-id> for a pane running `crtr surface attach to <node>`.' });
115
- }
116
- // Shell-hosted viewer: respawn onto the viewer command directly. The pane
117
- // deliberately converges on the viewer-as-pane-command shape every other
118
- // crtr surface uses today, so its start command becomes truthful and the
119
- // next reload takes the replay path.
120
- const cwd = paneCurrentPath(pane) ?? process.cwd();
121
- if (!respawnPaneSync({ pane, cwd, env: viewerSplitEnv(), command: viewerCommand })) {
122
- displayMessage('crtr: viewer reload failed', pane);
123
- throw new InputError({ error: 'respawn_failed', message: `tmux could not respawn pane ${pane}`, next: 'Check the tmux server is reachable, then retry.' });
124
- }
125
- displayMessage('crtr: viewer reloaded', pane);
126
- return { pane, node_id: nodeId };
127
- },
128
- render: (r) => `Reloaded viewer for ${r['node_id']} in pane ${r['pane']}.`,
129
- });