@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
@@ -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.
@@ -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 M=Object.defineProperty;var r=(e,s)=>M(e,"name",{value:s,configurable:!0});import{createConnection as B}from"node:net";import{apiSocketPath as $,viewSocketPath as z}from"../../../core/canvas/paths.js";import{BrokerClient as H,BrokerUnavailableError as F,RelayTransport as T}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 _,rethrowAsCliError as x}from"../../../commands/api-client.js";import{InputError as R,apiErrorToCliError as L}from"../../../core/io.js";import{ApiError as V}from"../../../api/index.js";import{readMachineConfig as q}from"../../../daemon/machine-link/config.js";import{personBearer as P}from"../../../core/directory/person-credential.js";const G=15e3;async function J(e,s){let a=await P(s);return setInterval(()=>{P(s).then(l=>{a=l},()=>{})},G).unref(),{previewEndpoint:e,get relayToken(){return a}}}r(J,"machineRelayTarget");function re(e){return e?"observer":"controller"}r(re,"resolveHelloRole");async function K(e){const s=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(s)||s<=0)return;const a=z(e),g=Date.now()+s;for(;Date.now()<g;){if(await new Promise(u=>{const c=B(a),d=r(h=>{c.destroy(),u(h)},"settle");c.once("connect",()=>d(!0)),c.once("error",()=>d(!1))}))return;await new Promise(u=>setTimeout(u,100))}}r(K,"preWaitForViewSocket");async function oe(e,s,a=!0,g,l){const u=s!==void 0,c=u?void 0:q(),d=s!==void 0?W({canvasName:s}):new U;let h,A,b,f,k;if(s!==void 0)h={cwd:process.cwd()},b=new T(e,D(s));else{const t=g??await d.getNode(e);if(t===null)throw new R({error:"not_found",message:`no node: ${e}`,received:e,next:"List nodes with `crtr node inspect list`."});if(h=t,A=t,c!==void 0)b=new T(e,await J(c.apiUrl,c.directoryUrl),a);else{try{if((await _().ensureAttach(e,{resume:!0,revive:!0,wakeParked:a})).parked){const i=await _().getSnapshot(e);f=i.snapshot,k=i.commands}}catch(n){x(n,"The node may be finalized or otherwise not attachable.")}f===void 0&&await K(e),b=new T(e,{socketPath:$()})}}const o=new H(e,{transport:b}),v=[];let C;const S=r(t=>{const n=t?.refusal;return n!==void 0?L(new V(n.status,n.code,n.message),"The node may be finalized or otherwise not attachable."):t instanceof F?new R({error:"no_broker",message:t.message,received:e,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new R({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 E;return o.on("error",t=>{E===void 0&&(E=t)}),f===void 0&&(await new Promise(async(t,n)=>{const i=r(()=>{p(),t()},"onConnect"),w=r(y=>{p(),n(y)},"onErr"),p=r(()=>{o.off("connect",i),o.off("error",w)},"cleanup");o.on("connect",i),o.on("error",w),o.connect()}).catch(async t=>{if(c!==void 0&&!a&&String(t?.message).includes("node_dormant")){const n=await _().getSnapshot(e).catch(i=>x(i,"The node may be finalized or otherwise not attachable."));f=n.snapshot,k=n.commands;return}throw S(t)}),l!==void 0&&await new Promise((t,n)=>{const i=r(m=>{v.push(m),m.type==="welcome"&&(y(),t())},"onFrame"),w=r(()=>{y(),n(new F(e,`the broker of node ${e} closed before its session was ready; it did not start`))},"onClose"),p=r(m=>{y(),n(m)},"onErr"),y=r(()=>{o.off("error",p),o.off("close",w),v.some(m=>m.type==="welcome")||o.off("frame",i)},"cleanup");C=i,o.on("frame",i),o.on("close",w),o.on("error",p),o.send({type:"hello",role:l.role,client_id:l.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})}).catch(t=>{throw S(t)})),{remote:u,canvasSource:d,meta:h,nodeIdentity:A,socket:o,...f===void 0?{}:{initialSnapshot:f,initialCommands:k},earlyFrames:v,takeEarlyFrames:r(()=>(C!==void 0&&o.off("frame",C),C=void 0,v.splice(0)),"takeEarlyFrames"),assertConnected:r(()=>{if(f===void 0&&E!==void 0)throw S(E)},"assertConnected")}}r(oe,"connectToNode");export{oe as connectToNode,J as machineRelayTarget,K as preWaitForViewSocket,re 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};