@north-light/cli 0.3.694 → 0.3.696

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/README.md +4 -7
  2. package/dist/api/command-manifest/result.d.ts +5 -5
  3. package/dist/api/command-manifest/result.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -0
  7. package/dist/api/dto/run-events.js +1 -0
  8. package/dist/api/dto/worktree.d.ts +0 -4
  9. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  10. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  11. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  12. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  14. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  15. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  16. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  17. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  18. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  19. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  20. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  21. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  22. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  23. package/dist/clients/attach/session/connection.d.ts +11 -2
  24. package/dist/clients/attach/session/connection.js +1 -1
  25. package/dist/clients/attach/session/keys.d.ts +2 -0
  26. package/dist/clients/attach/session/keys.js +1 -1
  27. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  28. package/dist/clients/attach/session/reconnect.js +1 -1
  29. package/dist/clients/attach/viewer.js +539 -538
  30. package/dist/commands/node-worktree.js +1 -1
  31. package/dist/commands/surface/node/placement.d.ts +2 -2
  32. package/dist/commands/surface/node/placement.js +1 -1
  33. package/dist/commands/surface.js +1 -1
  34. package/dist/core/broker-client/client.d.ts +6 -9
  35. package/dist/core/broker-client/client.js +1 -1
  36. package/dist/core/broker-client/transport-relay.d.ts +12 -1
  37. package/dist/core/broker-client/transport-relay.js +1 -1
  38. package/dist/core/canvas/canvas.js +5 -5
  39. package/dist/core/canvas/types.d.ts +0 -2
  40. package/dist/core/conversation-store/row-store.js +10 -10
  41. package/dist/core/graph/names.js +9 -9
  42. package/dist/core/keybindings/attach-control.d.ts +3 -0
  43. package/dist/core/keybindings/attach-control.js +1 -1
  44. package/dist/core/keybindings/catalog.js +1 -1
  45. package/dist/core/ledger/chunks.d.ts +3 -1
  46. package/dist/core/ledger/chunks.js +2 -2
  47. package/dist/core/ledger/index.d.ts +1 -1
  48. package/dist/core/ledger/index.js +1 -1
  49. package/dist/core/ledger/read.d.ts +4 -0
  50. package/dist/core/ledger/read.js +2 -2
  51. package/dist/core/llm/run.js +2 -2
  52. package/dist/core/logged-step-timings.d.ts +7 -0
  53. package/dist/core/logged-step-timings.js +1 -0
  54. package/dist/core/permissions/evaluator.d.ts +2 -1
  55. package/dist/core/permissions/evaluator.js +2 -2
  56. package/dist/core/providers/receipts.js +1 -1
  57. package/dist/core/runs/operations.js +8 -8
  58. package/dist/core/runtime/broker/model-adapter.js +3 -3
  59. package/dist/core/runtime/broker.js +1 -1
  60. package/dist/core/runtime/nodes.d.ts +1 -1
  61. package/dist/core/runtime/nodes.js +1 -1
  62. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  63. package/dist/core/runtime/placement-tmux.js +1 -1
  64. package/dist/core/runtime/revive.js +2 -2
  65. package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
  66. package/dist/core/runtime/runner/machine/executor.js +1 -1
  67. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  68. package/dist/core/runtime/runner/machine/ops.d.ts +7 -13
  69. package/dist/core/runtime/runner/machine/ops.js +1 -1
  70. package/dist/core/runtime/runner/machine/runner.d.ts +3 -2
  71. package/dist/core/runtime/runner/machine/runner.js +1 -1
  72. package/dist/core/runtime/tmux-bindings.js +3 -3
  73. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  74. package/dist/core/runtime/tmux-driver.js +6 -6
  75. package/dist/core/step-timings.d.ts +7 -1
  76. package/dist/core/step-timings.js +1 -1
  77. package/dist/core/worktree-close.js +4 -6
  78. package/dist/core/worktree-landing.d.ts +0 -38
  79. package/dist/core/worktree-landing.js +2 -3
  80. package/dist/core/worktree-sweep.d.ts +0 -1
  81. package/dist/core/worktree-sweep.js +4 -6
  82. package/dist/core/worktree.d.ts +0 -4
  83. package/dist/core/worktree.js +13 -15
  84. package/dist/daemon/api/app-listener.d.ts +1 -0
  85. package/dist/daemon/api/app-listener.js +10 -10
  86. package/dist/daemon/api/bridge.js +5 -5
  87. package/dist/daemon/api/handlers/attach.js +1 -1
  88. package/dist/daemon/api/handlers/conversations.js +3 -3
  89. package/dist/daemon/api/server.d.ts +1 -1
  90. package/dist/daemon/api/server.js +1 -1
  91. package/dist/daemon/cron/armed-context.js +1 -1
  92. package/dist/daemon/crtrd.js +20 -18
  93. package/dist/daemon/machine-daemon.js +1 -1
  94. package/dist/daemon/machine-link/client.d.ts +7 -1
  95. package/dist/daemon/machine-link/client.js +1 -1
  96. package/dist/daemon/machine-link/forward.d.ts +2 -4
  97. package/dist/daemon/machine-link/forward.js +1 -1
  98. package/dist/daemon/machine-link/holder.js +5 -5
  99. package/dist/daemon/pidfile.js +2 -1
  100. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  101. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  102. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
  104. package/dist/daemon/runs/append-section.js +2 -2
  105. package/dist/daemon/runs/observer.js +3 -3
  106. package/docs/apps/guides/stream-a-run.md +6 -7
  107. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  108. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  109. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  110. package/docs/concepts/scopes-and-trust.md +1 -1
  111. package/docs/concepts/why-a-daemon.md +1 -1
  112. package/docs/sdk/README.md +13 -41
  113. package/docs/sdk/client.md +5 -7
  114. package/docs/sdk/docker.md +1 -1
  115. package/docs/sdk/errors.md +3 -43
  116. package/docs/sdk/getting-started.md +11 -83
  117. package/docs/sdk/release-notes.md +10 -0
  118. package/docs/sdk/resources.md +11 -44
  119. package/package.json +3 -3
  120. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  121. package/packages/crouter-api/dist/api/contract.js +1 -1
  122. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  123. package/packages/crouter-api/dist/clients/attach/session/connection.js +73 -25
  124. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  125. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  126. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  127. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  128. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  129. package/packages/crouter-api/dist/commands/surface.js +2 -3
  130. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  131. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
  132. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
  133. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  134. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  135. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  136. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  137. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  138. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  139. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  140. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  141. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  142. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  143. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  144. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  145. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  146. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  147. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  148. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  149. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  150. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +14 -32
  151. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  152. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  153. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  154. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  155. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  156. package/packages/crouter-api/dist/core/worktree.js +9 -74
  157. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  158. package/packages/crouter-api/dist/daemon/machine-link/forward.js +22 -10
  159. package/packages/crouter-api/dist/daemon/machine-link/holder.js +7 -0
  160. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  161. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  162. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  163. package/packages/crouter-api/package.json +1 -1
  164. package/packages/crouter-identity/package.json +1 -1
  165. package/packages/crouter-plugin/dist/serve.js +1 -1
  166. package/packages/crouter-plugin/package.json +3 -3
  167. package/runtime.lock.json +14 -14
  168. package/scripts/self-update.mjs +7 -3
  169. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  170. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  171. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  172. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  173. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  174. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  175. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  176. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  177. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  178. package/dist/commands/surface-reload.d.ts +0 -7
  179. package/dist/commands/surface-reload.js +0 -1
  180. package/docs/sdk/bash.md +0 -39
  181. package/docs/sdk/files.md +0 -49
  182. package/docs/sdk/guides/README.md +0 -17
  183. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  184. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  185. package/docs/sdk/guides/human-approval.md +0 -24
  186. package/docs/sdk/guides/typed-extraction.md +0 -24
  187. package/docs/sdk/nodes.md +0 -194
  188. package/docs/sdk/streaming.md +0 -149
  189. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -1,43 +1,21 @@
1
1
  ---
2
2
  title: Errors
3
- description: What the crouter daemon refuses, how scoped tokens are limited, the socket wire body, and how node creation survives a retry.
3
+ description: What the crouter daemon refuses, how scoped tokens are limited, and the socket wire body.
4
4
  ---
5
5
 
6
6
  # Errors
7
7
 
8
8
  The error classes, the settled-outcome rule, retries and the app-facing error envelope are the same for every use of `@north-light/sdk`, and they are documented for app builders on the SDK docs site: [Errors](https://sdk.docs.northlight.ai/docs/errors). This page covers what is specific to driving a crouter daemon with `new Crouter()`.
9
9
 
10
- **An agent's own outcome is returned, never thrown.** A node that declined the schema, hit its deadline, or crashed comes back as a settled `NodeOutcome` from `waitForOutcome`, `createAndWait`, or `parse`. Narrow on it — see [Nodes](./nodes.md#outcomes).
11
-
12
- ## Daemon error codes
13
-
14
- A terminal SSE `error` event other than `stream_gap` rejects `NodeStream.finalOutcome()` and the iterator with `APIError` carrying that event's code, message, and details. `stream_gap` is delivered as an event and the stream continues. See [Streaming](./streaming.md).
15
-
16
- ```ts
17
- import { ConflictError, NotFoundError, APIConnectionError } from '@north-light/sdk';
18
-
19
- try {
20
- await client.nodes.create({ prompt, node_id: 'my-run-42' });
21
- } catch (error) {
22
- if (error instanceof ConflictError && error.code === 'node_id_exists') {
23
- // the run already exists — attach to it instead of spawning a second one
24
- return client.nodes.waitForOutcome('my-run-42');
25
- }
26
- if (error instanceof NotFoundError) throw new Error('no such node');
27
- if (error instanceof APIConnectionError) throw new Error('the daemon is not reachable');
28
- throw error;
29
- }
30
- ```
31
-
32
10
  ## Identifier validation
33
11
 
34
- The SDK validates path-segment identifiers before it makes a request. Invalid node ids, cron ids, bash-job ids, human-request ids, inbox ticket ids, provider names, and profile names throw `TypeError` locally. Node ids apply to core node calls, lifecycle calls, and nested node resources. `nodes.events()` returns a `NodeStream` synchronously, so its invalid-id `TypeError` rejects `stream.node`, `stream.finalOutcome()`, and iteration instead. File paths are not identifiers; invalid or relative file paths reach the daemon and return its mapped API error. `nodes.outcome(id, { wait })` separately throws `RangeError` when `wait` is not an integer from 0 through 25.
12
+ The SDK validates path-segment identifiers (provider names, file ids, share and question ids) before it makes a request. An empty value, `.` or `..`, or one holding `/`, `\`, whitespace, `?`, `#` or `%` throws `TypeError` locally and sends no request.
35
13
 
36
14
  ## Scoped tokens
37
15
 
38
16
  | Condition | Class, status, and code |
39
17
  |---|---|
40
- | The bearer token's ceiling lacks the scope a route needs, or `nodes.create` asks for `scopes` outside it (`details.scopes` lists them) | `PermissionDeniedError`, 403 `scope_denied` |
18
+ | The bearer token's ceiling lacks the scope a route needs, or a run asks for `scopes` outside it (`details.scopes` lists them) | `PermissionDeniedError`, 403 `scope_denied` |
41
19
  | A scoped token reaches an owner-only route (daemon restart, attach, broker internals, canvas prune, profile pause/resume/delete, model credential install) | `PermissionDeniedError`, 403 `owner_only` |
42
20
 
43
21
  ## The wire body
@@ -50,24 +28,6 @@ The daemon answers an error with:
50
28
 
51
29
  `code` is the stable, machine-readable identity — `node_id_exists`, `daemon_unavailable`, `request_timeout`, `node_dormant`. Branch on it. There is no separate `type` field and no `param` field. Northlight's app-facing endpoints answer with a fuller body; see the [error envelope](https://sdk.docs.northlight.ai/docs/errors#the-error-envelope).
52
30
 
53
- ## Creating a node that survives a retry
54
-
55
- `nodes.create` is a `POST` and is not retried automatically, because replaying it would spawn a second agent. Pass `node_id` so a duplicate fails loudly with `409 node_id_exists` instead of quietly running twice:
56
-
57
- ```ts
58
- const runId = `invoice-${invoice.id}`;
59
-
60
- try {
61
- await client.nodes.create({ prompt, node_id: runId, root: true });
62
- } catch (error) {
63
- if (!(error instanceof ConflictError && error.code === 'node_id_exists')) throw error;
64
- }
65
-
66
- const outcome = await client.nodes.waitForOutcome(runId);
67
- ```
68
-
69
- Which calls the SDK retries, and `runs.start` / `runs.message` idempotency keys, are in [Retries](https://sdk.docs.northlight.ai/docs/errors#retries).
70
-
71
31
  ## In-repo callers
72
32
 
73
33
  `ApiError` from `@north-light/api` is an alias of `APIError`, so existing crouter code and its transport checks keep working unchanged. Daemon handlers keep throwing `{ status, code, message }` and never name an SDK class — the hierarchy is one `status → constructor` table on the client side and nothing else depends on it.
@@ -1,12 +1,10 @@
1
1
  ---
2
2
  title: Getting started
3
- description: Connect to a local or remote daemon and run your first agent with the SDK.
3
+ description: Connect to a local or remote daemon and start your first run with the SDK.
4
4
  ---
5
5
 
6
6
  # Getting started
7
7
 
8
- Phase 1.
9
-
10
8
  An agent run needs a crouter daemon (`crtrd`) to run it. The SDK is a client for that daemon — it never runs an agent itself. There are two ways to reach one: the unix socket on the machine you are running on, or a TCP listener with a bearer token.
11
9
 
12
10
  ## 1. Install the runtime
@@ -35,19 +33,10 @@ Pass nothing. The client resolves the same socket path the `crtr` CLI does, and
35
33
  import Crouter from '@north-light/sdk';
36
34
 
37
35
  const client = new Crouter();
38
-
39
- const node = await client.nodes.create({
40
- prompt: 'List the top-level directories here and say what each one is for.',
41
- cwd: process.cwd(),
42
- root: true,
43
- root_lifecycle: 'terminal',
44
- });
45
-
46
- const outcome = await client.nodes.waitForOutcome(node.node_id);
47
- if (outcome.kind === 'result') console.log(outcome.final_report_path);
36
+ const { profiles } = await client.profiles.list();
48
37
  ```
49
38
 
50
- `root: true` says this run has no parent node and reports to nobody — which is what an application's run is. `root_lifecycle: 'terminal'` says it finishes and reaps; use `'resident'` for a run a person will open and keep talking to.
39
+ The SDK covers the app routes (`runs`, `uploads`, `docs`, `memory`, …). To create nodes, run bash, arm crons or answer the human inbox on your own daemon, use `CrtrClient` from `@north-light/api` (see the [SDK overview](./README.md#driving-nodes-bash-crons-or-the-human-inbox)).
51
40
 
52
41
  ## 4. A browser or a remote application
53
42
 
@@ -78,59 +67,23 @@ crtr sys connect --app my-app --scopes crtr:llm,crtr:act,crtr:memory:read:user
78
67
 
79
68
  `--scopes` requires `--app` (the app id, without the `app:` prefix) and accepts only `crtr:llm`, `crtr:act`, `crtr:schedule`, `crtr:memory:read:user`, `crtr:memory:read:app`, `crtr:memory:rw:app`, `crtr:files:read:user:.` and `crtr:files:rw:user:.`. This mints a new token for that app whose scope list is a ceiling, appends it to the same secrets store, prints it in place of the owner token, and always hands the daemon over (it reads tokens once, at boot). The ceiling is checked on every request that carries the token:
80
69
 
81
- - A scope-gated operation the ceiling lacks answers `403 scope_denied`. Creating, reviving, forking, messaging, or yielding a node needs `crtr:act`, as do `bash`, `files`, and creating a human request or review (there is no separate scope for human requests); arming or running a cron needs `crtr:schedule`; `/v1/llm` needs `crtr:llm`. `client.memory` has no scope of its own: it reads the person's documents filtered by privacy, and a grant holding `crtr:memory:read_private:user` also sees `private` documents, and one holding `crtr:memory:manage:user` sees every level.
82
- - `nodes.create` with `scopes` outside the ceiling answers `403 scope_denied`; `details.scopes` lists the offending scopes. Omit `scopes` and the run gets the ceiling.
70
+ - A scope-gated operation the ceiling lacks answers `403 scope_denied`. Starting or messaging a run, and creating, reviving, forking, messaging, or yielding a node, needs `crtr:act`, as do `bash`, `files`, and creating a human request or review (there is no separate scope for human requests); arming or running a cron needs `crtr:schedule`; `/v1/llm` needs `crtr:llm`. `client.memory` has no scope of its own: it reads the person's documents filtered by privacy, and a grant holding `crtr:memory:read_private:user` also sees `private` documents, and one holding `crtr:memory:manage:user` sees every level.
71
+ - A run started with `scopes` outside the ceiling answers `403 scope_denied`; `details.scopes` lists the offending scopes. Omit `scopes` and the run gets the ceiling.
83
72
  - Owner-only operations — daemon restart, the attach viewer, broker internals, canvas prune, profile pause/resume/delete, model credential install — answer `403 owner_only` to any scoped token.
84
73
 
85
74
  What a scope does **not** do on a developer's machine: there is no OS sandbox. Scopes gate the daemon and the CLI; a run's own bash tool is ungated, and the daemon identifies a calling node by a field the caller declares, so a scope check bounds a well-behaved agent, not a hostile one. A scope the daemon does not check at any route is recorded on the run but not enforced; `sys connect` mints only the scopes listed above. There is no list or revoke verb yet; to retire a scoped token, remove it from the 0600 user secrets store and restart the daemon.
86
75
 
87
- ### Check setup before generating
76
+ ### Connect with the saved values
88
77
 
89
- Construct the client from the application's saved connection. On the first visit that value is absent, and `client.auth.status()` returns `'connect'` without a request. Once the user pastes the base URL and token printed by `crtr sys connect`, construct it again and call `status()` to check the selected provider.
78
+ Construct the client from the base URL and token the user pasted from `crtr sys connect`:
90
79
 
91
80
  ```ts
92
81
  import Crouter from '@north-light/sdk';
93
82
 
94
- const saved = loadConnection(); // { baseURL: string; token: string } | null
95
- const client = new Crouter(saved ?? {});
96
- const status = await client.auth.status({ profile: 'my-app', cwd: '/path/to/repo' });
97
-
98
- if (status.next_step !== null) {
99
- showSetupPanel({ step: status.next_step, instructions: status.instructions! });
100
- return;
101
- }
102
-
103
- const run = await client.nodes.createAndWait({
104
- prompt: 'What changed in this repo today?',
105
- cwd: '/path/to/repo',
106
- profile: 'my-app',
107
- root: true,
108
- });
83
+ const client = new Crouter({ baseURL: saved.baseURL, token: saved.token });
109
84
  ```
110
85
 
111
- `status()` returns `next_step: 'connect'` when the application has no daemon transport, when the saved bearer token is rejected, or when the saved base URL cannot be reached. It returns `next_step: 'login'` when the daemon resolves the selected run to a provider without a ready credential. In both cases, display `instructions`: it names the exact `crtr sys connect` action and, for a login, the provider. When `status()` receives `profile`, `cwd`, `kind`, or `model`, the login instruction passes those selectors to `crtr sys connect`; use the text unchanged. A daemon that is still starting is connected with `next_step: null`; inspect `status.daemon.startup_phase` and wait for it to become `ready` before starting a run.
112
-
113
- An isolated auth-status probe returned:
114
-
115
- ```json
116
- {
117
- "no_request": {
118
- "next_step": "connect",
119
- "requests": 0
120
- },
121
- "missing": {
122
- "provider": "anthropic",
123
- "credential": "missing",
124
- "next_step": "login",
125
- "instructions": "Run `crtr sys connect --cwd /private/tmp/crouter-sdk-auth-proof.P3fSWg/empty --model anthropic/claude-opus-5` to log in to anthropic."
126
- },
127
- "ready": {
128
- "provider": "anthropic",
129
- "credential": "ready",
130
- "next_step": null
131
- }
132
- }
133
- ```
86
+ A rejected token raises `AuthenticationError` and an unreachable listener raises `APIConnectionError`; in both cases ask the user to run `crtr sys connect` again and paste what it prints.
134
87
 
135
88
  The root entry of the SDK is browser-safe: it imports nothing from `node:*`. The unix-socket code is reached only through a dynamic import taken when `socketPath` is set, so a browser bundle never resolves it.
136
89
 
@@ -148,29 +101,7 @@ Tell your users what the prompt is for. A prompt that appears with no explanatio
148
101
 
149
102
  ## 5. A typed result
150
103
 
151
- `parse()` creates the run, waits for it to settle, and types the structured result against the schema you gave it.
152
-
153
- ```ts
154
- import { z } from 'zod';
155
-
156
- const run = await client.nodes.parse({
157
- prompt: 'Read package.json here and report its name and version.',
158
- cwd: '/path/to/repo',
159
- output_schema: z.object({ name: z.string(), version: z.string() }),
160
- });
161
-
162
- if (run.kind === 'result') {
163
- console.log(run.output_parsed.name, run.output_parsed.version);
164
- } else if (run.reason === 'declined') {
165
- console.warn('the agent refused the schema:', run.declined?.reason);
166
- } else {
167
- console.error('the run failed:', run.reason, run.detail);
168
- }
169
- ```
170
-
171
- `output_parsed` is non-null on a result. A Zod schema supplies its inferred output type; a Standard Schema supplies `~standard.types.output`. A JSON-Schema literal or any other `{ toJSONSchema() }` object is accepted but makes `output_parsed` `unknown`.
172
-
173
- An outcome is returned, never thrown — including a decline and a failure. Only transport faults, daemon errors, and your own abort throw. See [Errors](./errors.md).
104
+ `client.runs.parse()` starts a run, waits for it to end, and types its structured result against the schema you gave it. See [Typed results](https://sdk.docs.northlight.ai/docs/guides/typed-results) on the SDK docs site.
174
105
 
175
106
  ## Build an app for other people
176
107
 
@@ -178,9 +109,6 @@ Registering an app, its key pair, the env file and going live are covered for ap
178
109
 
179
110
  ## Where to go next
180
111
 
181
- - A complete local page that demonstrates streaming, structured output, and a plugin: localhost SDK demo (`examples/localhost-demo` in the crouter repository)
182
112
  - Every constructor option and environment-variable fallback: [Client construction](./client.md)
183
- - Checking the daemon connection and selected provider before a run: `client.auth.status()` above
184
- - The full create-parameter table and the outcome union: [Nodes](./nodes.md)
185
- - Watching a run as it works: [Streaming](./streaming.md)
113
+ - Every namespace and its routes: [Resource map](./resources.md)
186
114
  - Running the daemon in a container instead: [Docker environment](./docker.md)
@@ -7,6 +7,16 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
7
7
 
8
8
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
9
9
 
10
+ ## 0.3.694
11
+
12
+ ### The owner's daemon routes are no longer wrapped (breaking for code that calls them)
13
+
14
+ No Northlight app called these, so they are gone from `Crouter`: `client.nodes` (with `parse`, `create`, `stream`, `events`, `message`, `NodeStream` and their types), `client.bash`, `client.crons`, `client.structuredRequests`, `client.human`, `client.system`, `client.auth`, `profiles` other than `list`, `files` other than `link`, `canvas` other than `watch` and `unwatch`, and `models.credentials` other than `install`. A program that drives its owner's own daemon uses `CrtrClient` from `@north-light/api` (the typed client the `crtr` CLI uses) or the `crtr` CLI; a one-shot typed run from an app uses `runs.parse`. `client.request(method, path, body?, options?)` still reaches any `/v1` route. No runtime route changes.
15
+
16
+ ### Unused run-stream methods and helpers are removed (breaking for code that calls them)
17
+
18
+ No Northlight app called these, so they are gone: `RunStream.finalOutcome()`, `whenEnded()`, `waitingOnUser()`, `on()` and `off()` (with the types `RunStreamEnd` and `RunEventListener`); `runs.stream()`; `health.get()`; `followActivity`, `describeToolDefault`, `ActivityStep` and `DescribeTool`; and the constant `DEFAULT_DIRECTORY_TIMEOUT_MS`. Read a run by iterating `runs.events(runId, {after})`: when iteration ends, `stream.idle` says whether the runtime closed a quiet stream, and `stream.position` is where to reopen. Start a run with `runs.start` and then open `runs.events`. No runtime route changes.
19
+
10
20
  ## 0.3.691
11
21
 
12
22
  A node whose commands run on the shared control plane passes provider file arguments, receives file results and files for review by upload id instead of by path. New optional `file_upload_id` on `POST /v1/human/reviews` and routes `POST /v1/nodes/:id/uploads` and `/uploads/:uploadId/link`; nothing existing changes.
@@ -5,27 +5,15 @@ description: Find client namespaces, their daemon routes, and the raw request es
5
5
 
6
6
  # Resource map
7
7
 
8
- Every namespace exported by the client. Namespaces are camelCase. Verbs are `create`, `retrieve`, `list`, `update`, `delete`, and `cancel`, except where the product already has a literal name for the action (`fork`, `revive`, `promote`, `pause`, `poke`) — in which case the SDK uses that name.
8
+ Every namespace exported by the client. Namespaces are camelCase. The owner's node, bash, cron, human-inbox, canvas-view, file and system routes have no namespace here: a program driving the owner's own daemon uses `CrtrClient` from `@north-light/api` or the `crtr` CLI, and `client.request()` reaches any of them.
9
9
 
10
10
  | Namespace | Methods | Routes |
11
11
  |---|---|---|
12
- | `nodes` | `create`, `retrieve`, `list`, `update`, `cancel`, `interrupt`, `message`, `outcome`, `waitForOutcome`, `createAndWait`, `parse`, `stream`, `events`, `fork`, `revive`, `reviveAll`, `promote`, `demote`, `recycle`, `yield`, `wait`, `relaunchRoot` | `/v1/nodes…` |
13
- | `nodes.reports` | `list` | `/v1/nodes/{id}/reports` |
14
- | `nodes.jobs` | `list`, `cancel` | `/v1/nodes/{id}/jobs` |
15
- | `nodes.worktree` | `close`, `abandon` | `/v1/nodes/{id}/worktree/…` |
16
- | `nodes.result` | `submit` | `POST /v1/nodes/{id}/result` |
17
- | `profiles` | `ensure`, `retrieve` | `/v1/profiles…` |
18
- | `auth` | `status` | `GET /v1/status`, then `GET /v1/model-auth/readiness` once the daemon is ready |
19
- | `system` | `status`, `health` | `/v1/status`, `/healthz` |
20
- | `files` | `read`, `write`, `list` | `/v1/files/peek`, `/v1/files/write`, `/v1/files/list` |
21
- | `bash` | `run` | `/v1/bash` |
22
- | `canvas` | `attention`, `attentionCounts`, `snapshot`, `roster`, `dashboard`, `prune` | `/v1/canvas…` and composed node/status requests for `dashboard` |
23
- | `canvas.history` | `search`, `grep`, `read`, `stats` | `/v1/canvas/history/…` |
24
- | `crons` | `create`, `retrieve`, `list`, `pause`, `resume`, `run`, `delete`, `poke` | `/v1/crons…` |
25
- | `human.requests` | `create`, `retrieve`, `replace`, `respond`, `dismiss`, `cancel` | `/v1/human/requests…` |
26
- | `human.inbox` | `list`, `retrieve`, `respond`, `progress`, `cancel`, `history`, `response` | `/v1/human/inbox…` |
27
- | `models.credentials` | `list`, `install`, `remove` | `/v1/model-auth…` |
28
- | `models.config` | `update` | `PUT /v1/model-config` |
12
+ | `profiles` | `list` | `GET /v1/profiles` |
13
+ | `files` | `link` | `GET /v1/files/{id}/link` |
14
+ | `canvas` | `watch`, `unwatch` | `POST`/`DELETE /v1/objects/{ref}/watch` |
15
+ | `models.credentials` | `install` | `PUT /v1/model-auth/{provider}` |
16
+ | `spendLimits` | `list`, `set`, `remove` | `/v1/spend-limits` |
29
17
  | `customObjects` | `register`, `publish`, `unregister`, `ack`, `receive` | `/v1/custom-objects…` |
30
18
  | `memory` | `list`, `listAll`, `get` | `GET /v1/memory`, `GET /v1/memory/document` |
31
19
  | `docs` | `write`, `edit`, `get` | `POST /v1/docs`, `PATCH /v1/docs/:ref`, `GET /v1/objects/:ref?fields=1` |
@@ -36,49 +24,28 @@ Every namespace exported by the client. Namespaces are camelCase. Verbs are `cre
36
24
  | `questions` | `get`, `answer` | `/v1/questions/{id}…` |
37
25
  | `providers` | `tools`, `call` | `/v1/providers/tools`, `POST /v1/provider/call` |
38
26
  | `grant` | `get` (`wait`, `since`: hold until `version` changes) | `GET /v1/grant` |
39
- | `health` | `get` | `GET /v1/health` |
40
27
 
41
- `runs`, `uploads`, `attachments`, `shares`, `questions`, `docs` and the app side of `grant` and `providers` are the application-facing API an app reaches through the app listener; `oauth.client(userId)` returns a client typed to exactly that set (`AppClient`); `customObjects` (`register`, `publish`, `unregister`) and `canvas` (`watch`, `unwatch`) are served too, for the custom objects your app owns; `oauth.appClient(userId)` returns the same `AppClient` type without a stored sign-in ([Connections](https://sdk.docs.northlight.ai/docs/concepts/connections#acting-without-a-sign-in)). Both return a `ConnectedCrouter`, which also has `exec(argv, { timeoutS? })` (`POST /v1/exec`, scopes `crtr:act` and `crtr:schedule`): it runs `crtr <argv>` with no shell in the app's sandbox on the person's runtime and returns the same result shape as `bash.run`; at most 4 run at once per app (`429 busy`). `nodes`, `bash`, `crons`, `human`, `models`, `structuredRequests`, `system`, `auth`, the rest of `canvas` and `customObjects` (`receive`, `ack`), `files.read/write/list` and `profiles.ensure/retrieve` are the owner's own daemon and are not served to an app. An app schedules work with its own timer calling `runs.start`, or a run's agent runs `crtr cron add` under `crtr:schedule`. See [Apps on Northlight](./guides/apps-on-northlight.md) and [Apps with many users](./guides/apps-with-many-users.md). `memory` is the person's `public` documents ([Memory](./memory.md)). `docs` writes, reads and edits documents the calling app owns: `docs.write({name, body, preview, kind?, rules?})` returns the canonical `name`; `docs.get(name)` returns `body`, `revision`, `rules` and the edit `base`; `docs.edit(name, {body, rationale, base?})` changes it in place and refuses a stale `base` with `ConflictError` (`stale_revision`). To keep one document current, `get` it (catch `NotFoundError` on first run to `write`), compare `body` to your text, and `edit` only when they differ. `system.health` (`/healthz`) is the daemon's liveness check; `health.get` is the app listener's.
28
+ `runs`, `uploads`, `attachments`, `shares`, `questions`, `docs` and the app side of `grant` and `providers` are the application-facing API an app reaches through the app listener; `oauth.client(userId)` returns a client typed to exactly that set (`AppClient`); `customObjects` (`register`, `publish`, `unregister`) and `canvas` (`watch`, `unwatch`) are served too, for the custom objects your app owns; `oauth.appClient(userId)` returns the same `AppClient` type without a stored sign-in ([Connections](https://sdk.docs.northlight.ai/docs/concepts/connections#acting-without-a-sign-in)). Both return a `ConnectedCrouter`, which also has `exec(argv, { timeoutS? })` (`POST /v1/exec`, scopes `crtr:act` and `crtr:schedule`): it runs `crtr <argv>` with no shell in the app's sandbox on the person's runtime and returns `{ exit_code, stdout, stderr, … }`; at most 4 run at once per app (`429 busy`). `models`, `spendLimits` and `customObjects` `receive` and `ack` are the owner's own daemon and are not served to an app. An app schedules work with its own timer calling `runs.start`, or a run's agent runs `crtr cron add` under `crtr:schedule`. See [Many users](https://sdk.docs.northlight.ai/docs/guides/many-users). `memory` is the person's `public` documents. `docs` writes, reads and edits documents the calling app owns: `docs.write({name, body, preview, kind?, rules?})` returns the canonical `name`; `docs.get(name)` returns `body`, `revision`, `rules` and the edit `base`; `docs.edit(name, {body, rationale, base?})` changes it in place and refuses a stale `base` with `ConflictError` (`stale_revision`). To keep one document current, `get` it (catch `NotFoundError` on first run to `write`), compare `body` to your text, and `edit` only when they differ.
42
29
 
43
- Action methods keep the product's literal name (`fork`, `revive`, `promote`, `yield`) rather than being renamed into a generic verb. Every request-capable method takes `RequestOptions` as its final argument after its path, body, or query arguments. `RequestOptions` is `{ headers?, signal?, timeout?, maxRetries? }`; stream event options exclude `timeout` and add `after`.
30
+ Every request-capable method takes `RequestOptions` as its final argument after its path, body, or query arguments. `RequestOptions` is `{ headers?, signal?, timeout?, maxRetries?, budgetMs?, deadlineAt? }`.
44
31
 
45
32
  ## Custom objects
46
33
 
47
34
  `client.customObjects` registers an external service or script as an object on the canvas, with a declared event catalog and a queue, URL or argv receiver, and publishes its events to the objects watching it. `register(body)` returns the object and, once, its publish token; `publish(ref, body)` sends one declared event (a custom object may publish with that token alone); `receive(ref, { after?, signal? })` is an async iterator over a queue receiver's deliveries and replays every unacknowledged delivery on each connect; `ack(ref, deliveryIds)` acknowledges them; `unregister(ref)` deletes the object. An app reaches `register`, `publish` and `unregister` on its own objects through `oauth.client(userId)` or `oauth.appClient(userId)`, and links a node to one with `client.canvas.watch(ref, { watcher, watcher_machine? })` and `client.canvas.unwatch(ref, { watcher, watcher_machine? })` under `crtr:objects:link:node` (without `watcher`, `unwatch` removes the app's own watch). The same objects are managed from a terminal with `crtr custom-object` and watched with `crtr canvas watch`.
48
35
 
49
- ## Files and bash
50
-
51
- [`client.files`](./files.md) reads through `GET /v1/files/peek`, atomically writes, and lists absolute host paths. Reads and lists report `truncated`; writes over 1 MiB are refused instead of truncated. [`client.bash`](./bash.md) runs one command in a required absolute working directory and returns non-zero exits as values.
52
-
53
- ## Canvas
54
-
55
- `client.canvas.attention()`, `attentionCounts(body)`, `snapshot()`, `roster()`, and `prune(body)` each send their matching canvas route. `dashboard(query?)` composes `GET /v1/nodes` and `GET /v1/status`, because the daemon deliberately has no dashboard route. `client.canvas.history.search(body)`, `grep(body)`, `read(query)`, and `stats(body)` wrap the four history routes.
56
-
57
- ## Crons
58
-
59
- `client.crons.create(body)`, `retrieve(id, query?)`, `list(query?)`, `pause(id, query?)`, `resume(id, query?)`, `run(id, query?)`, `delete(id, query?)`, and `poke()` retain the daemon's cron DTOs and snake_case query fields. `delete` is the SDK verb for the daemon's `DELETE /v1/crons/{id}` route.
60
-
61
- ## Human requests and inbox
62
-
63
- `client.human.requests` exposes `create`, `retrieve`, `replace`, `respond`, `dismiss`, and `cancel`. `client.human.inbox` exposes `list`, `retrieve`, `respond`, `progress`, `cancel`, `history`, and `response`. The inbox methods preserve the page protocol's nested camelCase fields and the daemon envelope's snake_case fields.
64
-
65
- ## Models
66
-
67
- `client.models.credentials.list()`, `install(provider, body)`, and `remove(provider)` wrap `/v1/model-auth`. `client.models.config.update(body)` sends `PUT /v1/model-config`. Credential material is accepted only by `install`; list responses remain sanitized daemon DTOs.
68
-
69
36
  ## Identifier validation
70
37
 
71
- Methods with node, cron, bash-job, human-request, inbox-ticket, provider, or profile identifiers validate them before calling the daemon. Invalid values throw `TypeError` locally and send no request. This applies to node action methods and nested node resources, cron methods that take an id, `human.requests` methods that take an id, `human.inbox` methods that take a ticket id, `models.credentials.install` and `remove`, and profile `ensure` and `retrieve`. File paths are not subject to this identifier check; the daemon validates their absolute-path contract.
38
+ Methods that take a provider name, file id, share id or question id validate it before calling the daemon. An invalid value throws `TypeError` locally and sends no request.
72
39
 
73
40
  ## Excluded from the typed surface
74
41
 
75
- These `/v1` routes get no SDK method, with the reason. They are still reachable through `client.request()`.
42
+ Besides the owner routes above, these `/v1` routes get no SDK method on purpose, with the reason. They are still reachable through `client.request()`.
76
43
 
77
44
  | Routes | Why |
78
45
  |---|---|
79
46
  | `/v1/focuses…` | A focus maps a node to a tmux pane. An SDK caller has no tmux. It stays on `/v1` for the viewer. |
80
47
  | `POST /v1/nodes/{id}/mail/claim`, `…/mail/acknowledge` | These are how a node's own broker takes delivery of its inbox. An external caller claiming another node's mail would consume deliveries that node then never sees. |
81
- | `POST /v1/nodes/{id}/attach` | Returns the host-local path to a broker's viewer socket. A remote or browser caller cannot open that path, and [Streaming](./streaming.md) is the application-facing way to watch a node. |
48
+ | `POST /v1/nodes/{id}/attach` | Returns the host-local path to a broker's viewer socket. A remote or browser caller cannot open that path, and `runs.events` is the application-facing way to watch a run. |
82
49
  | Broker operations, broker recovery, node faults | The broker's own control plane — session binding, settle directives, park completion, turn recording, provider-retry mutation, fault recording, model commit. They exist so the one process hosting a node can coordinate with crtrd about that node's runtime. An external caller invoking them introduces a second writer to state the broker and the daemon coordinate between themselves. |
83
50
 
84
51
  ## The escape hatch
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.694",
3
+ "version": "0.3.696",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.694",
160
- "@north-light/plugin": "0.3.694",
159
+ "@north-light/identity": "0.3.696",
160
+ "@north-light/plugin": "0.3.696",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -1,8 +1,8 @@
1
1
  import { isRecord } from '../../shared/predicates.js';
2
2
  /** Validates a result object against declared output field descriptors.
3
3
  * Returns null if valid; otherwise returns a { field, receivedType } error
4
- * where `field` is the full path of the first mismatch. */
5
- export function validateDeclaredResult(output, result) {
4
+ * where `field` is the full path of the first mismatch. A client ignores object members it does not know; `closed` makes them a mismatch. */
5
+ export function validateDeclaredResult(output, result, closed = false) {
6
6
  for (const f of output) {
7
7
  const value = result[f.name];
8
8
  const present = Object.prototype.hasOwnProperty.call(result, f.name) && value !== undefined;
@@ -11,7 +11,7 @@ export function validateDeclaredResult(output, result) {
11
11
  return { field: f.name };
12
12
  continue;
13
13
  }
14
- const mismatch = validateValue(f, value, f.name);
14
+ const mismatch = validateValue(f, value, f.name, closed);
15
15
  if (mismatch !== null)
16
16
  return { field: mismatch.path, receivedType: mismatch.receivedType, expected: mismatch.expected };
17
17
  }
@@ -20,9 +20,9 @@ export function validateDeclaredResult(output, result) {
20
20
  /** Checks one JSON value against one shape, recursively: object members, array
21
21
  * items, map values, union variants, enum values and nullability. An object that
22
22
  * declares `children` is closed unless it carries `extra`: an undeclared
23
- * member is a mismatch at any depth, or must fit `extra`. Returns null, or the first mismatch with its full path from `path`.
23
+ * member is a mismatch at any depth (ignored when `closed` is false), or must fit `extra`. Returns null, or the first mismatch with its full path from `path`.
24
24
  * A declared type that is not recognized is accepted. */
25
- export function validateValue(shape, value, path) {
25
+ export function validateValue(shape, value, path, closed = true) {
26
26
  const atoms = shape.type.split('|').map((part) => part.trim()).filter(Boolean);
27
27
  const bases = atoms.filter((part) => part.toLowerCase() !== 'null');
28
28
  if (value === null && bases.length < atoms.length)
@@ -32,9 +32,9 @@ export function validateValue(shape, value, path) {
32
32
  if (!atoms.every((part) => knownType(part) || /^[a-z][a-z0-9_-]*$/.test(part)))
33
33
  return null;
34
34
  if (bases.length === 1)
35
- return atomMismatch(bases[0], shape, value, path);
35
+ return atomMismatch(bases[0], shape, value, path, closed);
36
36
  for (const atom of bases) {
37
- if (atomMismatch(atom, shape, value, path) === null)
37
+ if (atomMismatch(atom, shape, value, path, closed) === null)
38
38
  return null;
39
39
  }
40
40
  return mismatch(path, shape.type, value);
@@ -64,7 +64,7 @@ function knownType(type) {
64
64
  || t === 'enum'
65
65
  || t === 'file';
66
66
  }
67
- function atomMismatch(type, shape, v, path) {
67
+ function atomMismatch(type, shape, v, path, closed) {
68
68
  const t = type.toLowerCase();
69
69
  const fail = (expected) => mismatch(path, expected, v);
70
70
  if (t === 'null')
@@ -96,7 +96,7 @@ function atomMismatch(type, shape, v, path) {
96
96
  if (shape.items === undefined)
97
97
  return null;
98
98
  for (let i = 0; i < v.length; i++) {
99
- const inner = validateValue(shape.items, v[i], `${path}[${i}]`);
99
+ const inner = validateValue(shape.items, v[i], `${path}[${i}]`, closed);
100
100
  if (inner !== null)
101
101
  return inner;
102
102
  }
@@ -110,7 +110,7 @@ function atomMismatch(type, shape, v, path) {
110
110
  if (shape.items === undefined)
111
111
  return null;
112
112
  for (const [key, entry] of Object.entries(v)) {
113
- const inner = validateValue(shape.items, entry, `${path}[${JSON.stringify(key)}]`);
113
+ const inner = validateValue(shape.items, entry, `${path}[${JSON.stringify(key)}]`, closed);
114
114
  if (inner !== null)
115
115
  return inner;
116
116
  }
@@ -129,7 +129,7 @@ function atomMismatch(type, shape, v, path) {
129
129
  return { path: `${path}.${member.name}`, expected: `${member.type} (required)`, receivedType: 'undefined' };
130
130
  continue;
131
131
  }
132
- const inner = validateValue(member, memberValue, `${path}.${member.name}`);
132
+ const inner = validateValue(member, memberValue, `${path}.${member.name}`, closed);
133
133
  if (inner !== null)
134
134
  return inner;
135
135
  }
@@ -137,11 +137,11 @@ function atomMismatch(type, shape, v, path) {
137
137
  for (const key of Object.keys(v)) {
138
138
  if (declared.has(key))
139
139
  continue;
140
- if (shape.extra === undefined)
140
+ if (shape.extra === undefined && closed)
141
141
  return mismatch(`${path}.${key}`, 'no such member (the object is closed)', v[key]);
142
- if (v[key] === undefined)
142
+ if (shape.extra === undefined || v[key] === undefined)
143
143
  continue;
144
- const inner = validateValue(shape.extra, v[key], `${path}.${key}`);
144
+ const inner = validateValue(shape.extra, v[key], `${path}.${key}`, closed);
145
145
  if (inner !== null)
146
146
  return inner;
147
147
  }
@@ -150,7 +150,7 @@ function atomMismatch(type, shape, v, path) {
150
150
  if (t === 'union') {
151
151
  const failures = [];
152
152
  for (const variant of shape.variants ?? []) {
153
- const inner = validateValue(variant, v, path);
153
+ const inner = validateValue(variant, v, path, closed);
154
154
  if (inner === null)
155
155
  return null;
156
156
  failures.push(inner);
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.64';
15
+ export const CONTRACT_LEVEL = '1.65';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -3,4 +3,4 @@
3
3
  // it and the SDK exports it, so a new event or field is added here once.
4
4
  //
5
5
  // PURITY (spec §3.1): imports only other `src/api/*` modules.
6
- export {};
6
+ export const ZERO_RUN_USAGE = { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 };
@@ -12,7 +12,8 @@ import { apiSocketPath, viewSocketPath } from '../../../core/canvas/paths.js';
12
12
  import { BrokerClient, BrokerUnavailableError, RelayTransport } from '../../../core/broker-client/index.js';
13
13
  import { resolveRemoteCanvasTarget } from '../../../core/remote-canvas-target.js';
14
14
  import { ApiCanvasSource, cliCanvasSource, cliClient, rethrowAsCliError } from '../../../commands/api-client.js';
15
- import { InputError } from '../../../core/io.js';
15
+ import { InputError, apiErrorToCliError } from '../../../core/io.js';
16
+ import { ApiError } from '../../../api/index.js';
16
17
  import { readMachineConfig } from '../../../daemon/machine-link/config.js';
17
18
  import { personBearer } from '../../../core/directory/person-credential.js';
18
19
  /** The person bearer is cached until 30 s before it ends; a viewer redials with whatever the target holds at that moment, so a shorter timer keeps it fresh. */
@@ -63,7 +64,9 @@ export async function preWaitForViewSocket(nodeId) {
63
64
  /** Resolve the target, revive the node if it is dormant (server-side), and dial
64
65
  * the broker. Rejects with a plain `InputError` — no terminal has been taken
65
66
  * over at this point, so a failure here is an ordinary non-zero CLI exit. */
66
- export async function connectToNode(nodeId, canvasName, wakeParked = true, known) {
67
+ export async function connectToNode(nodeId, canvasName, wakeParked = true, known,
68
+ /** The viewer's identity for the `hello` sent right after the connect. A live attach stays on the caller's screen until the broker's `welcome` answers it. */
69
+ hello) {
67
70
  // An imported Mac has no local canvas API: its canvas and its brokers' viewer channels are reached through the cloud control plane,
68
71
  // 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:
69
72
  // `remote` stays false, so the viewer claims the controller role like any local attach.
@@ -107,39 +110,46 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
107
110
  }
108
111
  meta = localMeta;
109
112
  nodeIdentity = localMeta;
110
- // Attach revives a dormant node (B2 acceptance): the server-side
111
- // ensureAttach runs reviveNode (the ONE sanctioned launcher) and waits for
112
- // the broker's view socket, returning socket_path === viewSocketPath(nodeId).
113
- // The viewer connects through crtrd's Unix-socket WebSocket bridge after
114
- // this ensure. The daemon, not the broker, owns attending viewer presence.
115
- try {
116
- const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
117
- if (attach.parked) {
118
- const saved = await cliClient().getSnapshot(nodeId);
119
- // The API DTO stays dependency-light and structural; this viewer is the
120
- // consumer that knows the complete broker snapshot contract.
121
- initialSnapshot = saved.snapshot;
122
- initialCommands = saved.commands;
123
- }
113
+ if (machine !== undefined) {
114
+ // On a Mac the viewer's WebSocket upgrade alone admits the attach: it authorizes, revives and waits for the broker once, and its channel
115
+ // 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.
116
+ transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl), wakeParked);
124
117
  }
125
- catch (err) {
126
- rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
127
- }
128
- // Local only: remote attach reaches crtrd over WebSocket rather than a
129
- // local socket file, so `--canvas` has nothing to pre-wait on. An offline
130
- // parked focus has deliberately no socket to wait for.
131
- if (machine !== undefined)
132
- transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl));
133
118
  else {
119
+ // Attach revives a dormant node (B2 acceptance): the server-side
120
+ // ensureAttach runs reviveNode (the ONE sanctioned launcher) and waits for
121
+ // the broker's view socket, returning socket_path === viewSocketPath(nodeId).
122
+ // The viewer connects through crtrd's Unix-socket WebSocket bridge after
123
+ // this ensure. The daemon, not the broker, owns attending viewer presence.
124
+ try {
125
+ const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
126
+ if (attach.parked) {
127
+ const saved = await cliClient().getSnapshot(nodeId);
128
+ // The API DTO stays dependency-light and structural; this viewer is the
129
+ // consumer that knows the complete broker snapshot contract.
130
+ initialSnapshot = saved.snapshot;
131
+ initialCommands = saved.commands;
132
+ }
133
+ }
134
+ catch (err) {
135
+ rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
136
+ }
137
+ // An offline parked focus has deliberately no socket to wait for.
134
138
  if (initialSnapshot === undefined)
135
139
  await preWaitForViewSocket(nodeId);
136
140
  transport = new RelayTransport(nodeId, { socketPath: apiSocketPath() });
137
141
  }
138
142
  }
139
143
  const socket = new BrokerClient(nodeId, { transport });
144
+ const earlyFrames = [];
145
+ let collectFrame;
140
146
  /** One error shape for a connect-time failure, whether the connect race below
141
147
  * caught it or the deferred `assertConnected` checkpoint did. */
142
148
  const toAttachError = (err) => {
149
+ // An upgrade the daemon refused with an API error shows as that error, as the attach ensure it replaced did.
150
+ const refusal = err?.refusal;
151
+ if (refusal !== undefined)
152
+ return apiErrorToCliError(new ApiError(refusal.status, refusal.code, refusal.message), 'The node may be finalized or otherwise not attachable.');
143
153
  if (err instanceof BrokerUnavailableError) {
144
154
  return new InputError({
145
155
  error: 'no_broker',
@@ -186,9 +196,40 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
186
196
  socket.on('connect', onConnect);
187
197
  socket.on('error', onErr);
188
198
  socket.connect();
189
- }).catch((err) => {
199
+ }).catch(async (err) => {
200
+ // A Mac's upgrade refuses a parked node it was told not to wake: show its saved snapshot, offline, as a local parked focus does.
201
+ if (machine !== undefined && !wakeParked && String(err?.message).includes('node_dormant')) {
202
+ const saved = await cliClient().getSnapshot(nodeId).catch((e) => rethrowAsCliError(e, 'The node may be finalized or otherwise not attachable.'));
203
+ initialSnapshot = saved.snapshot;
204
+ initialCommands = saved.commands;
205
+ return;
206
+ }
190
207
  throw toAttachError(err);
191
208
  });
209
+ // A broker listens before its session exists and answers `hello` only once it does. Wait for that answer here, so the caller's screen stays up and
210
+ // no input is accepted until the session is real. Every frame from the welcome on is kept for the viewer to replay once its handlers exist.
211
+ if (hello !== undefined) {
212
+ await new Promise((resolve, reject) => {
213
+ const onFrame = (frame) => {
214
+ earlyFrames.push(frame);
215
+ if (frame.type === 'welcome') {
216
+ cleanup();
217
+ resolve();
218
+ }
219
+ };
220
+ const onClose = () => { cleanup(); reject(new BrokerUnavailableError(nodeId, `the broker of node ${nodeId} closed before its session was ready; it did not start`)); };
221
+ const onErr = (err) => { cleanup(); reject(err); };
222
+ const cleanup = () => { socket.off('error', onErr); socket.off('close', onClose); if (!earlyFrames.some((f) => f.type === 'welcome'))
223
+ socket.off('frame', onFrame); };
224
+ collectFrame = onFrame;
225
+ socket.on('frame', onFrame);
226
+ socket.on('close', onClose);
227
+ socket.on('error', onErr);
228
+ socket.send({ type: 'hello', role: hello.role, client_id: hello.clientId, term: { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 } });
229
+ }).catch((err) => {
230
+ throw toAttachError(err);
231
+ });
232
+ }
192
233
  }
193
234
  return {
194
235
  remote,
@@ -197,6 +238,13 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true, known
197
238
  nodeIdentity,
198
239
  socket,
199
240
  ...(initialSnapshot === undefined ? {} : { initialSnapshot, initialCommands }),
241
+ earlyFrames,
242
+ takeEarlyFrames: () => {
243
+ if (collectFrame !== undefined)
244
+ socket.off('frame', collectFrame);
245
+ collectFrame = undefined;
246
+ return earlyFrames.splice(0);
247
+ },
200
248
  assertConnected: () => {
201
249
  if (initialSnapshot === undefined && terminalStartupError !== undefined)
202
250
  throw toAttachError(terminalStartupError);