@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
@@ -9,6 +9,16 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
9
9
 
10
10
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
11
11
 
12
+ ## 0.3.694
13
+
14
+ ### The owner's daemon routes are no longer wrapped (breaking for code that calls them)
15
+
16
+ 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.
17
+
18
+ ### Unused run-stream methods and helpers are removed (breaking for code that calls them)
19
+
20
+ 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.
21
+
12
22
  ## 0.3.691
13
23
 
14
24
  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.
@@ -7,27 +7,15 @@ when-and-why-to-read: When you need Resource map, this knowledge should be read
7
7
 
8
8
  # Resource map
9
9
 
10
- 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.
10
+ 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.
11
11
 
12
12
  | Namespace | Methods | Routes |
13
13
  |---|---|---|
14
- | `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…` |
15
- | `nodes.reports` | `list` | `/v1/nodes/{id}/reports` |
16
- | `nodes.jobs` | `list`, `cancel` | `/v1/nodes/{id}/jobs` |
17
- | `nodes.worktree` | `close`, `abandon` | `/v1/nodes/{id}/worktree/…` |
18
- | `nodes.result` | `submit` | `POST /v1/nodes/{id}/result` |
19
- | `profiles` | `ensure`, `retrieve` | `/v1/profiles…` |
20
- | `auth` | `status` | `GET /v1/status`, then `GET /v1/model-auth/readiness` once the daemon is ready |
21
- | `system` | `status`, `health` | `/v1/status`, `/healthz` |
22
- | `files` | `read`, `write`, `list` | `/v1/files/peek`, `/v1/files/write`, `/v1/files/list` |
23
- | `bash` | `run` | `/v1/bash` |
24
- | `canvas` | `attention`, `attentionCounts`, `snapshot`, `roster`, `dashboard`, `prune` | `/v1/canvas…` and composed node/status requests for `dashboard` |
25
- | `canvas.history` | `search`, `grep`, `read`, `stats` | `/v1/canvas/history/…` |
26
- | `crons` | `create`, `retrieve`, `list`, `pause`, `resume`, `run`, `delete`, `poke` | `/v1/crons…` |
27
- | `human.requests` | `create`, `retrieve`, `replace`, `respond`, `dismiss`, `cancel` | `/v1/human/requests…` |
28
- | `human.inbox` | `list`, `retrieve`, `respond`, `progress`, `cancel`, `history`, `response` | `/v1/human/inbox…` |
29
- | `models.credentials` | `list`, `install`, `remove` | `/v1/model-auth…` |
30
- | `models.config` | `update` | `PUT /v1/model-config` |
14
+ | `profiles` | `list` | `GET /v1/profiles` |
15
+ | `files` | `link` | `GET /v1/files/{id}/link` |
16
+ | `canvas` | `watch`, `unwatch` | `POST`/`DELETE /v1/objects/{ref}/watch` |
17
+ | `models.credentials` | `install` | `PUT /v1/model-auth/{provider}` |
18
+ | `spendLimits` | `list`, `set`, `remove` | `/v1/spend-limits` |
31
19
  | `customObjects` | `register`, `publish`, `unregister`, `ack`, `receive` | `/v1/custom-objects…` |
32
20
  | `memory` | `list`, `listAll`, `get` | `GET /v1/memory`, `GET /v1/memory/document` |
33
21
  | `docs` | `write`, `edit`, `get` | `POST /v1/docs`, `PATCH /v1/docs/:ref`, `GET /v1/objects/:ref?fields=1` |
@@ -38,49 +26,28 @@ Every namespace exported by the client. Namespaces are camelCase. Verbs are `cre
38
26
  | `questions` | `get`, `answer` | `/v1/questions/{id}…` |
39
27
  | `providers` | `tools`, `call` | `/v1/providers/tools`, `POST /v1/provider/call` |
40
28
  | `grant` | `get` (`wait`, `since`: hold until `version` changes) | `GET /v1/grant` |
41
- | `health` | `get` | `GET /v1/health` |
42
29
 
43
- `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 [[crouter-sdk/guides/apps-on-northlight]] and [[crouter-sdk/guides/apps-with-many-users]]. `memory` is the person's `public` documents ([[crouter-sdk/memory]]). `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.
30
+ `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.
44
31
 
45
- 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`.
32
+ 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? }`.
46
33
 
47
34
  ## Custom objects
48
35
 
49
36
  `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`.
50
37
 
51
- ## Files and bash
52
-
53
- [[crouter-sdk/files]] 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. [[crouter-sdk/bash]] runs one command in a required absolute working directory and returns non-zero exits as values.
54
-
55
- ## Canvas
56
-
57
- `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.
58
-
59
- ## Crons
60
-
61
- `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.
62
-
63
- ## Human requests and inbox
64
-
65
- `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.
66
-
67
- ## Models
68
-
69
- `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.
70
-
71
38
  ## Identifier validation
72
39
 
73
- 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.
40
+ 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.
74
41
 
75
42
  ## Excluded from the typed surface
76
43
 
77
- These `/v1` routes get no SDK method, with the reason. They are still reachable through `client.request()`.
44
+ Besides the owner routes above, these `/v1` routes get no SDK method on purpose, with the reason. They are still reachable through `client.request()`.
78
45
 
79
46
  | Routes | Why |
80
47
  |---|---|
81
48
  | `/v1/focuses…` | A focus maps a node to a tmux pane. An SDK caller has no tmux. It stays on `/v1` for the viewer. |
82
49
  | `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. |
83
- | `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 [[crouter-sdk/streaming]] is the application-facing way to watch a node. |
50
+ | `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. |
84
51
  | 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. |
85
52
 
86
53
  ## The escape hatch
@@ -68,19 +68,18 @@ A refused or failed model call ends the turn with an empty `message.done` (`stop
68
68
 
69
69
  ## A quiet run
70
70
 
71
- A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. `RunStream` reports that and does not reconnect:
71
+ A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. Iteration then ends normally, `stream.idle` is `true` and the stream does not reconnect; reopen from `stream.position` when you want more:
72
72
 
73
73
  ```ts
74
74
  const stream = runtime.runs.events(runId, {after: cursor});
75
- for await (const event of stream) handle(event);
76
- const end = await stream.whenEnded(); // rejects on a transport failure or abort()
77
- if (end.reason === 'idle') {
78
- // the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: end.cursor})
75
+ for await (const event of stream) handle(event); // throws on a transport failure or abort()
76
+ if (stream.idle) {
77
+ // the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: stream.position})
79
78
  }
80
79
  ```
81
80
 
82
- A settled run ends with `reason: 'settled'`. `runs.reply` reopens through an idle close on its own.
81
+ A settled run ends iteration after `node.settled` with `idle` false. `runs.reply` reopens through an idle close on its own.
83
82
 
84
83
  ## Typed events
85
84
 
86
- `RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one, and `RunStream.on(type, listener)` passes the listener that event. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
85
+ `RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one; narrow on `event.type` inside the loop. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- var R=Object.defineProperty;var s=(r,o)=>R(r,"name",{value:o,configurable:!0});import"./suppress-experimental-warnings.js";import{mkdirSync as S,openSync as b,readFileSync as E,renameSync as I,rmSync as C,statSync as g,writeFileSync as O}from"node:fs";import{dirname as h,join as a}from"node:path";import{enableCompileCache as k}from"node:module";import{fileURLToPath as v}from"node:url";import{isDaemonControlInvocation as m,isJoinInvocation as A,isLayoutMigrationInvocation as N,isPkgInstallInvocation as x,isSignInInvocation as $,personOnlyInvocation as P,resolveDaemonControlRoot as T,resolveLayoutMigrationRoot as F,resolveRoot as M}from"./build-root.js";import{maybeBootRoot as D}from"./core/runtime/front-door.js";import{maybeAutoUpdate as L}from"./core/auto-update.js";import{ensureProjectScope as j}from"./core/bootstrap.js";import{provisionExports as U,pruneLegacyExports as B}from"./core/host-exports/export.js";import{revalidateBundlePlugins as K}from"./core/command-plugins/revalidate.js";import{renderNode as J,runCli as w,walk as V}from"./core/command.js";import{dispatchWithStaleRecovery as W}from"./core/manifest-recovery.js";import{installStdoutErrorPolicy as q}from"./core/stdout-errors.js";import{handle as G}from"./core/io.js";import{CrtrError as f,ownerOnly as z}from"./core/errors.js";import{ExitCode as H}from"./types.js";import{layoutNeedsMigration as Q,runtimeRoot as X}from"./core/layout.js";import{ApiError as y}from"./api/index.js";import{mark as i}from"./core/timing.js";import{launchSnapshotFile as Y,providerProjectionOverBrokerRelay as Z,sandboxCliNodeId as rr}from"./shared/env.js";import{nodeRunDir as d}from"./core/canvas/paths.js";import{installBrokerConfigSnapshot as or}from"./core/config.js";b(v(import.meta.url),"r"),q(),i("cli.entry",{cmd:process.argv[2]??"(bare)"});try{k()}catch{}i("cli.compile_cache");const er=a(h(v(import.meta.url)),".."),l=a(X(),"first-run.json");function c(r){return(r instanceof Error?r.message:String(r)).split(/\r?\n/,1)[0]??""}s(c,"errorMessage");function tr(r){const o=h(l);S(o,{recursive:!0});const t=`${l}.${process.pid}.${Date.now()}.tmp`;try{O(t,JSON.stringify({packageVersion:r,completedAt:new Date().toISOString()})+`
3
- `,"utf8"),I(t,l)}finally{C(t,{force:!0})}}s(tr,"writeFirstRunMarker");async function ir(){if(process.env.CRTR_NO_AUTO_INIT==="1")return;try{if(g(l,{throwIfNoEntry:!1})!==void 0)return}catch(o){process.stderr.write(`crtr: first-run reconcile marker check failed: ${c(o)}
2
+ var R=Object.defineProperty;var s=(r,o)=>R(r,"name",{value:o,configurable:!0});import"./suppress-experimental-warnings.js";import{mkdirSync as S,openSync as b,readFileSync as I,renameSync as E,rmSync as C,statSync as g,writeFileSync as O}from"node:fs";import{dirname as h,join as a}from"node:path";import{enableCompileCache as k}from"node:module";import{fileURLToPath as w}from"node:url";import{isDaemonControlInvocation as m,isJoinInvocation as A,isLayoutMigrationInvocation as N,isPkgInstallInvocation as x,isSignInInvocation as $,personOnlyInvocation as P,resolveDaemonControlRoot as T,resolveLayoutMigrationRoot as F,resolveRoot as L}from"./build-root.js";import{maybeBootRoot as M}from"./core/runtime/front-door.js";import{maybeAutoUpdate as D}from"./core/auto-update.js";import{ensureProjectScope as j}from"./core/bootstrap.js";import{provisionExports as U,pruneLegacyExports as B}from"./core/host-exports/export.js";import{revalidateBundlePlugins as K}from"./core/command-plugins/revalidate.js";import{renderNode as J,runCli as v,walk as V}from"./core/command.js";import{dispatchWithStaleRecovery as W}from"./core/manifest-recovery.js";import{installStdoutErrorPolicy as q}from"./core/stdout-errors.js";import{handle as G}from"./core/io.js";import{CrtrError as f,ownerOnly as z}from"./core/errors.js";import{ExitCode as H}from"./types.js";import{layoutNeedsMigration as Q,runtimeRoot as X}from"./core/layout.js";import{ApiError as y}from"./api/index.js";import{mark as i}from"./core/timing.js";import{launchSnapshotFile as Y,providerProjectionOverBrokerRelay as Z,sandboxCliNodeId as rr}from"./shared/env.js";import{nodeRunDir as d}from"./core/canvas/paths.js";import{installBrokerConfigSnapshot as or}from"./core/config.js";b(w(import.meta.url),"r"),q(),i("cli.entry",{cmd:process.argv[2]??"(bare)"});try{k()}catch{}i("cli.compile_cache");const er=a(h(w(import.meta.url)),".."),l=a(X(),"first-run.json");function c(r){return(r instanceof Error?r.message:String(r)).split(/\r?\n/,1)[0]??""}s(c,"errorMessage");function tr(r){const o=h(l);S(o,{recursive:!0});const e=`${l}.${process.pid}.${Date.now()}.tmp`;try{O(e,JSON.stringify({packageVersion:r,completedAt:new Date().toISOString()})+`
3
+ `,"utf8"),E(e,l)}finally{C(e,{force:!0})}}s(tr,"writeFirstRunMarker");async function ir(){if(process.env.CRTR_NO_AUTO_INIT==="1")return;try{if(g(l,{throwIfNoEntry:!1})!==void 0)return}catch(o){process.stderr.write(`crtr: first-run reconcile marker check failed: ${c(o)}
4
4
  `);return}try{if(g(a(er,".git"),{throwIfNoEntry:!1})!==void 0)return}catch(o){process.stderr.write(`crtr: first-run reconcile source check failed: ${c(o)}
5
- `);return}let r;try{const{reconcileFirstRun:o}=await import("./commands/sys/setup-core.js");r=await o((t,p)=>{process.stderr.write(`crtr: first-run reconcile ${t} failed: ${c(p)}
5
+ `);return}let r;try{const{reconcileFirstRun:o}=await import("./commands/sys/setup-core.js");r=await o((e,p)=>{process.stderr.write(`crtr: first-run reconcile ${e} failed: ${c(p)}
6
6
  `)})}catch(o){process.stderr.write(`crtr: first-run reconcile failed: ${c(o)}
7
7
  `)}finally{if(r!==void 0)try{tr(r)}catch(o){process.stderr.write(`crtr: first-run reconcile marker failed: ${c(o)}
8
- `)}}}s(ir,"maybeReconcileFirstRun");async function nr(){const r=N(process.argv),o=rr(),t=o!==void 0;if(o!==void 0){process.env.CRTR_API_SOCKET=a(d(o),"cli.sock");const e=P(process.argv);if(e!==null)throw z(`crtr ${e} is not available to an app's node`,"Run this command from the person's terminal.");const n=JSON.parse(E(Y(d(o))??a(d(o),"broker-launch.json"),"utf8"));if(!n.configSnapshot)throw new Error("node launch is missing its config snapshot");or(n.configSnapshot)}if(!t&&Q()&&!m(process.argv)&&!r)throw new f("layout_migration_required","run crtr sys migrate while the runtime is offline",H.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(r){const e=await F();if(process.argv.slice(4).some(n=>n==="-h"||n==="--help")){process.stdout.write(J(V(e,["sys","migrate"]).node)+`
9
- `);return}await w(e,process.argv);return}if((!t||x(process.argv))&&!m(process.argv)&&!A(process.argv)&&!$(process.argv)){try{t||await(await import("./commands/daemon-generation.js")).assertLocalDaemonMatchesCli(),await(await import("./commands/person-settings.js")).loadPersonSettingsViaApi()}catch(e){const n=process.argv.slice(2).some(u=>u==="-h"||u==="--help"),_=e instanceof y&&(e.code==="daemon_unavailable"||e.code==="northlight_unreachable")||e instanceof f&&(e.code==="daemon_generation_mismatch"||e.code==="not_signed_in"||e.code==="move_unfinished"||e.code==="northlight_unreachable");if(!(n&&_))throw e;(await import("./core/scoped-state/person-store.js")).installPreludeSnapshot({profiles:[],defaults:{},settings:{},state:{},apps:{}})}i("cli.settings_loaded")}if(t||(B(process.argv),Z()||await ir()),await D(process.argv),i("cli.front_door_passed"),m(process.argv)){await w(await T(),process.argv);return}t||await K(process.argv),i("cli.plugins_revalidated");const p=await M(process.argv[2]);i("cli.root_resolved"),t||(U(p,process.argv),await j(process.argv),await L(process.argv)),i("cli.dispatch_start"),await W(p,process.argv),i("cli.dispatch_done")}s(nr,"main"),nr().catch(r=>{(r instanceof Error&&r.name==="AbortError"||r instanceof Error&&/operation was aborted/i.test(r.message))&&(process.stderr.write(`crtr: Interrupted
10
- `),process.exit(130)),(r instanceof y||r instanceof f)&&(G(r),process.exit(typeof process.exitCode=="number"?process.exitCode:1));const t=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: ${t}
8
+ `)}}}s(ir,"maybeReconcileFirstRun");async function nr(){const r=N(process.argv),o=rr(),e=o!==void 0;if(o!==void 0){process.env.CRTR_API_SOCKET=a(d(o),"cli.sock");const t=P(process.argv);if(t!==null)throw z(`crtr ${t} is not available to an app's node`,"Run this command from the person's terminal.");const n=JSON.parse(I(Y(d(o))??a(d(o),"broker-launch.json"),"utf8"));if(!n.configSnapshot)throw new Error("node launch is missing its config snapshot");or(n.configSnapshot)}if(!e&&Q()&&!m(process.argv)&&!r)throw new f("layout_migration_required","run crtr sys migrate while the runtime is offline",H.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(r){const t=await F();if(process.argv.slice(4).some(n=>n==="-h"||n==="--help")){process.stdout.write(J(V(t,["sys","migrate"]).node)+`
9
+ `);return}await v(t,process.argv);return}if((!e||x(process.argv))&&!m(process.argv)&&!A(process.argv)&&!$(process.argv)){try{e||await(await import("./commands/daemon-generation.js")).assertLocalDaemonMatchesCli(),await(await import("./commands/person-settings.js")).loadPersonSettingsViaApi(),e||await(await import("./core/scoped-state/imported-mac-installs.js")).migrateLegacyInstallsOnce()}catch(t){const n=process.argv.slice(2).some(u=>u==="-h"||u==="--help"),_=t instanceof y&&(t.code==="daemon_unavailable"||t.code==="northlight_unreachable")||t instanceof f&&(t.code==="daemon_generation_mismatch"||t.code==="not_signed_in"||t.code==="move_unfinished"||t.code==="northlight_unreachable");if(!(n&&_))throw t;(await import("./core/scoped-state/person-store.js")).installPreludeSnapshot({profiles:[],defaults:{},settings:{},state:{},apps:{}})}i("cli.settings_loaded")}if(e||(B(process.argv),Z()||await ir()),await M(process.argv),i("cli.front_door_passed"),m(process.argv)){await v(await T(),process.argv);return}e||await K(process.argv),i("cli.plugins_revalidated");const p=await L(process.argv[2]);i("cli.root_resolved"),e||(U(p,process.argv),await j(process.argv),await D(process.argv)),i("cli.dispatch_start"),await W(p,process.argv),i("cli.dispatch_done")}s(nr,"main"),nr().catch(r=>{(r instanceof Error&&r.name==="AbortError"||r instanceof Error&&/operation was aborted/i.test(r.message))&&(process.stderr.write(`crtr: Interrupted
10
+ `),process.exit(130)),(r instanceof y||r instanceof f)&&(G(r),process.exit(typeof process.exitCode=="number"?process.exitCode:1));const e=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: ${e}
11
11
  `),process.exit(1)});
@@ -1,4 +1,4 @@
1
- import type { BrokerSnapshot, ClientRole } from '../../../core/runtime/broker-protocol.js';
1
+ import type { BrokerSnapshot, BrokerToClient, ClientRole } from '../../../core/runtime/broker-protocol.js';
2
2
  import type { CanvasSource } from '../../../core/canvas/source.js';
3
3
  import type { NodeDetailDTO } from '../../../api/dto/nodes.js';
4
4
  import type { NodeMeta } from '../../../core/canvas/types.js';
@@ -39,6 +39,10 @@ export interface AttachConnection {
39
39
  /** Saved snapshot used to seed an offline parked viewer. Absent for direct
40
40
  * attach and for focus paths whose broker was live or legitimately woke. */
41
41
  readonly initialSnapshot?: BrokerSnapshot;
42
+ /** Frames the broker sent from its `welcome` on, received before the viewer's handlers existed. Empty when no `hello` was sent during the connect. */
43
+ readonly earlyFrames: BrokerToClient[];
44
+ /** Stop collecting and hand over every frame collected so far, once. */
45
+ takeEarlyFrames(): BrokerToClient[];
42
46
  readonly initialCommands?: ReadonlyArray<{
43
47
  name: string;
44
48
  description: string;
@@ -52,4 +56,9 @@ export interface AttachConnection {
52
56
  /** Resolve the target, revive the node if it is dormant (server-side), and dial
53
57
  * the broker. Rejects with a plain `InputError` — no terminal has been taken
54
58
  * over at this point, so a failure here is an ordinary non-zero CLI exit. */
55
- export declare function connectToNode(nodeId: string, canvasName?: string, wakeParked?: boolean, known?: NodeDetailDTO): Promise<AttachConnection>;
59
+ export declare function connectToNode(nodeId: string, canvasName?: string, wakeParked?: boolean, known?: NodeDetailDTO,
60
+ /** 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. */
61
+ hello?: {
62
+ role: 'controller' | 'observer';
63
+ clientId: string;
64
+ }): Promise<AttachConnection>;
@@ -1 +1 @@
1
- var R=Object.defineProperty;var n=(e,t)=>R(e,"name",{value:t,configurable:!0});import{createConnection as _}from"node:net";import{apiSocketPath as A,viewSocketPath as x}from"../../../core/canvas/paths.js";import{BrokerClient as P,BrokerUnavailableError as M,RelayTransport as k}from"../../../core/broker-client/index.js";import{resolveRemoteCanvasTarget as B}from"../../../core/remote-canvas-target.js";import{ApiCanvasSource as F,cliCanvasSource as H,cliClient as y,rethrowAsCliError as $}from"../../../commands/api-client.js";import{InputError as v}from"../../../core/io.js";import{readMachineConfig as D}from"../../../daemon/machine-link/config.js";import{personBearer as E}from"../../../core/directory/person-credential.js";const U=15e3;async function W(e,t){let a=await E(t);return setInterval(()=>{E(t).then(f=>{a=f},()=>{})},U).unref(),{previewEndpoint:e,get relayToken(){return a}}}n(W,"machineRelayTarget");function Q(e){return e?"observer":"controller"}n(Q,"resolveHelloRole");async function z(e){const t=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(t)||t<=0)return;const a=x(e),m=Date.now()+t;for(;Date.now()<m;){if(await new Promise(o=>{const s=_(a),c=n(w=>{s.destroy(),o(w)},"settle");s.once("connect",()=>c(!0)),s.once("error",()=>c(!1))}))return;await new Promise(o=>setTimeout(o,100))}}n(z,"preWaitForViewSocket");async function X(e,t,a=!0,m){const f=t!==void 0,o=f?void 0:D(),s=t!==void 0?H({canvasName:t}):new F;let c,w,h,l,g;if(t!==void 0)c={cwd:process.cwd()},h=new k(e,B(t));else{const r=m??await s.getNode(e);if(r===null)throw new v({error:"not_found",message:`no node: ${e}`,received:e,next:"List nodes with `crtr node inspect list`."});c=r,w=r;try{if((await y().ensureAttach(e,{resume:!0,revive:!0,wakeParked:a})).parked){const u=await y().getSnapshot(e);l=u.snapshot,g=u.commands}}catch(d){$(d,"The node may be finalized or otherwise not attachable.")}o!==void 0?h=new k(e,await W(o.apiUrl,o.directoryUrl)):(l===void 0&&await z(e),h=new k(e,{socketPath:A()}))}const i=new P(e,{transport:h}),C=n(r=>r instanceof M?new v({error:"no_broker",message:r.message,received:e,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new v({error:"socket_error",message:`could not attach to node ${e}: ${String(r?.message??r)}`,received:e,next:"Check the node has a running headless broker."}),"toAttachError");let p;return i.on("error",r=>{p===void 0&&(p=r)}),l===void 0&&await new Promise(async(r,d)=>{const u=n(()=>{b(),r()},"onConnect"),S=n(T=>{b(),d(T)},"onErr"),b=n(()=>{i.off("connect",u),i.off("error",S)},"cleanup");i.on("connect",u),i.on("error",S),i.connect()}).catch(r=>{throw C(r)}),{remote:f,canvasSource:s,meta:c,nodeIdentity:w,socket:i,...l===void 0?{}:{initialSnapshot:l,initialCommands:g},assertConnected:n(()=>{if(l===void 0&&p!==void 0)throw C(p)},"assertConnected")}}n(X,"connectToNode");export{X as connectToNode,W as machineRelayTarget,z as preWaitForViewSocket,Q as resolveHelloRole};
1
+ var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{createConnection as M}from"node:net";import{apiSocketPath as B,viewSocketPath as $}from"../../../core/canvas/paths.js";import{BrokerClient as H,BrokerUnavailableError as A,RelayTransport as S}from"../../../core/broker-client/index.js";import{resolveRemoteCanvasTarget as D}from"../../../core/remote-canvas-target.js";import{ApiCanvasSource as U,cliCanvasSource as W,cliClient as F,rethrowAsCliError as z}from"../../../commands/api-client.js";import{InputError as T}from"../../../core/io.js";import{readMachineConfig as L}from"../../../daemon/machine-link/config.js";import{personBearer as P}from"../../../core/directory/person-credential.js";const V=15e3;async function q(e,n){let c=await P(n);return setInterval(()=>{P(n).then(f=>{c=f},()=>{})},V).unref(),{previewEndpoint:e,get relayToken(){return c}}}r(q,"machineRelayTarget");function I(e){return e?"observer":"controller"}r(I,"resolveHelloRole");async function G(e){const n=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(n)||n<=0)return;const c=$(e),y=Date.now()+n;for(;Date.now()<y;){if(await new Promise(l=>{const i=M(c),w=r(d=>{i.destroy(),l(d)},"settle");i.once("connect",()=>w(!0)),i.once("error",()=>w(!1))}))return;await new Promise(l=>setTimeout(l,100))}}r(G,"preWaitForViewSocket");async function ee(e,n,c=!0,y,f){const l=n!==void 0,i=l?void 0:L(),w=n!==void 0?W({canvasName:n}):new U;let d,R,v,u,_;if(n!==void 0)d={cwd:process.cwd()},v=new S(e,D(n));else{const t=y??await w.getNode(e);if(t===null)throw new T({error:"not_found",message:`no node: ${e}`,received:e,next:"List nodes with `crtr node inspect list`."});d=t,R=t;try{if((await F().ensureAttach(e,{resume:!0,revive:!0,wakeParked:c})).parked){const s=await F().getSnapshot(e);u=s.snapshot,_=s.commands}}catch(a){z(a,"The node may be finalized or otherwise not attachable.")}i!==void 0?v=new S(e,await q(i.apiUrl,i.directoryUrl)):(u===void 0&&await G(e),v=new S(e,{socketPath:B()}))}const o=new H(e,{transport:v}),C=[];let g;const E=r(t=>t instanceof A?new T({error:"no_broker",message:t.message,received:e,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new T({error:"socket_error",message:`could not attach to node ${e}: ${String(t?.message??t)}`,received:e,next:"Check the node has a running headless broker."}),"toAttachError");let b;return o.on("error",t=>{b===void 0&&(b=t)}),u===void 0&&(await new Promise(async(t,a)=>{const s=r(()=>{h(),t()},"onConnect"),p=r(k=>{h(),a(k)},"onErr"),h=r(()=>{o.off("connect",s),o.off("error",p)},"cleanup");o.on("connect",s),o.on("error",p),o.connect()}).catch(t=>{throw E(t)}),f!==void 0&&await new Promise((t,a)=>{const s=r(m=>{C.push(m),m.type==="welcome"&&(k(),t())},"onFrame"),p=r(()=>{k(),a(new A(e,`the broker of node ${e} closed before its session was ready; it did not start`))},"onClose"),h=r(m=>{k(),a(m)},"onErr"),k=r(()=>{o.off("error",h),o.off("close",p),C.some(m=>m.type==="welcome")||o.off("frame",s)},"cleanup");g=s,o.on("frame",s),o.on("close",p),o.on("error",h),o.send({type:"hello",role:f.role,client_id:f.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})}).catch(t=>{throw E(t)})),{remote:l,canvasSource:w,meta:d,nodeIdentity:R,socket:o,...u===void 0?{}:{initialSnapshot:u,initialCommands:_},earlyFrames:C,takeEarlyFrames:r(()=>(g!==void 0&&o.off("frame",g),g=void 0,C.splice(0)),"takeEarlyFrames"),assertConnected:r(()=>{if(u===void 0&&b!==void 0)throw E(b)},"assertConnected")}}r(ee,"connectToNode");export{ee as connectToNode,q as machineRelayTarget,G as preWaitForViewSocket,I as resolveHelloRole};
@@ -41,6 +41,8 @@ export interface KeyHooks {
41
41
  openSearch: () => void;
42
42
  /** Play the whip animation and interrupt the focused agent with a command. */
43
43
  whip: () => void;
44
+ /** Restart this viewer process in place (the Alt+C "reload viewer" entry). */
45
+ reloadViewer: () => void;
44
46
  }
45
47
  /** Install the listener; returns the remover, which teardown MUST call. */
46
48
  export declare function installGlobalKeys(ctx: Pick<AttachSession, 'tui' | 'editor'>, hooks: KeyHooks): () => void;
@@ -1 +1 @@
1
- var f=Object.defineProperty;var r=(c,e)=>f(c,"name",{value:e,configurable:!0});import{extractAttachControlInput as g}from"../../../core/keybindings/index.js";import{dispatchAttachAction as m,dispatchAttachBinding as o,dispatchAttachViewportBinding as h}from"./bindings.js";import{FOCUS_IN as l,FOCUS_OUT as d}from"./focus-events.js";const x=1e3;function y(c,e){const{tui:i,editor:u}=c;let a=0;const p={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":r(()=>{const t=Date.now();if(t-a<x){a=0,e.cancelTurn();return}a=t,u.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),i.requestRender()},"crtr.attach.clear-or-detach"),"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":r(()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.next"),"crtr.attach.model-ladder.previous":r(()=>e.cycleModelLadder("backward"),"crtr.attach.model-ladder.previous"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip};return i.addInputListener(t=>{if(t.includes(l)||t.includes(d)){e.setPaneFocused(t.lastIndexOf(l)>t.lastIndexOf(d)),i.requestRender();const s=t.replaceAll(l,"").replaceAll(d,"");return s.length>0?{data:s}:{consume:!0}}const n=g(t);if(n!==void 0)return m(n.actionId,p),n.remaining.length>0?{data:n.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(t)?{consume:!0}:e.searchHandleKey(t)?{consume:!0}:u.focused&&h(e.bindings(),t,e.viewportActions())?{consume:!0}:e.stripHandleKey(t)?{consume:!0}:e.rosterHandleKey(t)?{consume:!0}:o(e.bindings(),t,p)?{consume:!0}:void 0})}r(y,"installGlobalKeys");export{y as installGlobalKeys};
1
+ var f=Object.defineProperty;var r=(c,e)=>f(c,"name",{value:e,configurable:!0});import{extractAttachControlInput as g}from"../../../core/keybindings/index.js";import{dispatchAttachAction as m,dispatchAttachBinding as o,dispatchAttachViewportBinding as h}from"./bindings.js";import{FOCUS_IN as l,FOCUS_OUT as d}from"./focus-events.js";const w=1e3;function y(c,e){const{tui:a,editor:u}=c;let i=0;const p={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":r(()=>{const t=Date.now();if(t-i<w){i=0,e.cancelTurn();return}i=t,u.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),a.requestRender()},"crtr.attach.clear-or-detach"),"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":r(()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.next"),"crtr.attach.model-ladder.previous":r(()=>e.cycleModelLadder("backward"),"crtr.attach.model-ladder.previous"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip,"crtr.attach.reload-viewer":e.reloadViewer};return a.addInputListener(t=>{if(t.includes(l)||t.includes(d)){e.setPaneFocused(t.lastIndexOf(l)>t.lastIndexOf(d)),a.requestRender();const s=t.replaceAll(l,"").replaceAll(d,"");return s.length>0?{data:s}:{consume:!0}}const n=g(t);if(n!==void 0)return m(n.actionId,p),n.remaining.length>0?{data:n.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(t)?{consume:!0}:e.searchHandleKey(t)?{consume:!0}:u.focused&&h(e.bindings(),t,e.viewportActions())?{consume:!0}:e.stripHandleKey(t)?{consume:!0}:e.rosterHandleKey(t)?{consume:!0}:o(e.bindings(),t,p)?{consume:!0}:void 0})}r(y,"installGlobalKeys");export{y as installGlobalKeys};
@@ -12,12 +12,12 @@
12
12
  * the replacement is running ~50ms later. A departing viewer whose event loop
13
13
  * was busy when the signal arrived therefore runs its teardown after the
14
14
  * replacement has claimed the pane, and an unconditional clear then wipes the
15
- * LIVE viewer's identity: `nodeInPane()` returns nothing, so `surface reload`
16
- * and viewer focus refuse the pane until someone re-tags it by hand. So the
15
+ * LIVE viewer's identity: `nodeInPane()` returns nothing, so viewer focus
16
+ * refuses the pane until someone re-tags it by hand. So the
17
17
  * clear is conditional on still owning the pane, decided by `@crtr_viewer_pid`:
18
18
  * a pane carrying someone else's pid has a successor, and its tags are not
19
19
  * ours to remove. Skipping leaves at worst a stale tag on a dead pane, which
20
- * `liveViewerPanes` and `surface reload` already validate against the live
20
+ * `liveViewerPanes` already validates against the live
21
21
  * process; wiping a live viewer's tag has no such defense. */
22
22
  /** The tmux reads and writes the tag lifecycle makes, injectable so the
23
23
  * successor race is testable without a live tmux server. */
@@ -1 +1 @@
1
- var S=Object.defineProperty;var n=(d,e)=>S(d,"name",{value:e,configurable:!0});import{AttachRefusedError as b,reconnectShouldGiveUp as A}from"../../../core/broker-client/index.js";const C=1e3,P=3e3;function h(d,e){const{nodeId:p,socket:a,canvasSource:_}=d;let f,s=!1,l=e.initialDormant===!0,y=!1,i=!1,D=n(()=>{},"resolveStopped"),c,u;const v=new Promise(r=>{D=r}),R=n(r=>i?Promise.resolve(!1):new Promise(t=>{const o=n(w=>{c=void 0,u=void 0,t(w)},"settle");c=setTimeout(()=>o(!0),r),u=n(()=>{c!==void 0&&clearTimeout(c),o(!1)},"cancelRetry")}),"waitForRetry");let E=!1,m=!1;const T=n(()=>{m=!1,a.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},"sendHello"),g=n(async()=>{s=!0,e.setNotice("\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!0});let r=200;try{for(;!i&&!e.isTornDown();){let t;try{t=await _.getRow(p)}catch{t=void 0}if(t!==void 0&&A(t)){y=t?.status==="done";break}const o=t?.status==="idle"||t?.intent==="idle-release"||t?.lifecycle==="resident"&&t.status==="done"&&t.intent==="parked"&&t.final_report==null,w=o&&!l;l=o,w&&e.onEnterDormancy(),e.setNotice(o?"":"\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!o});try{if(!await Promise.race([a.redial({brokerUnavailableIsExpected:o}).then(()=>!0),v.then(()=>!1)])||i||e.isTornDown())return;T(),l=!1,e.setNotice("");return}catch{if(!await R(o?P:Math.min(r,C)))return;r*=2}}}finally{s=!1}!i&&!e.isTornDown()&&e.teardown(y?"node-done":"broker-gone")},"attemptReconnect");return{sendHello:T,startDormant:n(()=>{s||i||e.isTornDown()||(e.onEnterDormancy(),g())},"startDormant"),isDormant:n(()=>l,"isDormant"),lastSocketError:n(()=>f,"lastSocketError"),install:n(async()=>{a.on("frame",r=>{r.type==="welcome"&&(E=!0),e.onFrame(r)}),a.on("error",r=>{f=r.message,r instanceof b&&(m=!0)}),a.on("close",()=>{if(!e.isTornDown()&&!s){if(e.remote&&e.role==="controller"&&m&&!E){f=`the remote canvas refused the attach to ${p}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`,e.teardown("broker-gone");return}g()}})},"install"),stop:n(()=>{i||(i=!0,u?.(),D())},"stop")}}n(h,"createReconnect");export{h as createReconnect};
1
+ var b=Object.defineProperty;var n=(f,e)=>b(f,"name",{value:e,configurable:!0});import{AttachRefusedError as A,reconnectShouldGiveUp as C}from"../../../core/broker-client/index.js";const P=1e3,I=3e3;function x(f,e){const{nodeId:p,socket:s,canvasSource:T}=f;let u,l=!1,c=e.initialDormant===!0,y=!1,o=!1,D=n(()=>{},"resolveStopped"),d,m;const R=new Promise(r=>{D=r}),_=n(r=>o?Promise.resolve(!1):new Promise(t=>{const i=n(a=>{d=void 0,m=void 0,t(a)},"settle");d=setTimeout(()=>i(!0),r),m=n(()=>{d!==void 0&&clearTimeout(d),i(!1)},"cancelRetry")}),"waitForRetry");let E=!1,w=!1;const g=n(()=>{w=!1,s.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},"sendHello"),v=n(async()=>{l=!0,e.setNotice("\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!0});let r=200;try{for(;!o&&!e.isTornDown();){let t;try{t=await T.getRow(p)}catch{t=void 0}if(t!==void 0&&C(t)){y=t!==null;break}const i=t?.status==="dead"||t?.status==="canceled",a=t?.status==="idle"||t?.intent==="idle-release"||t?.status==="done",N=a&&!c;c=a,N&&e.onEnterDormancy(),e.setNotice(i?`node is ${t?.status} \u2014 waiting for a revive`:a?"":"\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!a});try{if(!await Promise.race([s.redial({brokerUnavailableIsExpected:a||i}).then(()=>!0),R.then(()=>!1)])||o||e.isTornDown())return;g(),c=!1,e.setNotice("");return}catch{if(!await _(a||i?I:Math.min(r,P)))return;r*=2}}}finally{l=!1}!o&&!e.isTornDown()&&e.teardown(y?"node-done":"broker-gone")},"attemptReconnect");return{sendHello:g,startDormant:n(()=>{l||o||e.isTornDown()||(e.onEnterDormancy(),v())},"startDormant"),isDormant:n(()=>c,"isDormant"),lastSocketError:n(()=>u,"lastSocketError"),install:n(async()=>{s.on("frame",r=>{r.type==="welcome"&&(E=!0),e.onFrame(r)}),s.on("error",r=>{u=r.message,r instanceof A&&(w=!0)}),s.on("close",()=>{if(!e.isTornDown()&&!l){if(e.remote&&e.role==="controller"&&w&&!E){u=`the remote canvas refused the attach to ${p}. A writable attach needs message permission on the node; with read permission only, attach with --observer.`,e.teardown("broker-gone");return}v()}})},"install"),stop:n(()=>{o||(o=!0,m?.(),D())},"stop")}}n(x,"createReconnect");export{x as createReconnect};