@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.
- package/README.md +4 -7
- package/dist/api/command-manifest/result.d.ts +5 -5
- package/dist/api/command-manifest/result.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/run-events.d.ts +1 -0
- package/dist/api/dto/run-events.js +1 -0
- package/dist/api/dto/worktree.d.ts +0 -4
- package/dist/api/errors.js +1 -1
- package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
- package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
- package/dist/builtin-memory/crouter-sdk/README.md +14 -42
- package/dist/builtin-memory/crouter-sdk/client.md +5 -7
- package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
- package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
- package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
- package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
- package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
- package/dist/cli.js +6 -6
- package/dist/clients/attach/session/connection.d.ts +11 -2
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/pane-tag.d.ts +3 -3
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/viewer.js +538 -537
- package/dist/commands/node/inspect.js +9 -9
- package/dist/commands/node-worktree.js +1 -1
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/surface/node/placement.d.ts +2 -2
- package/dist/commands/surface/node/placement.js +1 -1
- package/dist/commands/surface.js +1 -1
- package/dist/commands/sys/update.js +1 -1
- package/dist/core/broker-client/client.d.ts +6 -9
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +7 -7
- package/dist/core/canvas/types.d.ts +0 -2
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/row-store.js +10 -10
- package/dist/core/graph/exposures.js +1 -1
- package/dist/core/graph/names.js +9 -9
- package/dist/core/graph/watches.js +1 -1
- package/dist/core/installed-plugins.js +1 -1
- package/dist/core/keybindings/attach-control.d.ts +3 -0
- package/dist/core/keybindings/attach-control.js +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/ledger/chunks.d.ts +3 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/index.d.ts +1 -1
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/read.d.ts +4 -0
- package/dist/core/ledger/read.js +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/logged-step-timings.d.ts +7 -0
- package/dist/core/logged-step-timings.js +1 -0
- package/dist/core/permissions/evaluator.d.ts +2 -1
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runs/operations.js +8 -8
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/nodes.d.ts +1 -1
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/runtime/tmux-driver.d.ts +0 -10
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
- package/dist/core/scoped-state/imported-mac-installs.js +2 -0
- package/dist/core/spaces/stop.js +1 -1
- package/dist/core/step-timings.d.ts +7 -1
- package/dist/core/step-timings.js +1 -1
- package/dist/core/worktree-close.js +4 -6
- package/dist/core/worktree-landing.d.ts +0 -38
- package/dist/core/worktree-landing.js +2 -3
- package/dist/core/worktree-sweep.d.ts +0 -1
- package/dist/core/worktree-sweep.js +4 -6
- package/dist/core/worktree.d.ts +0 -4
- package/dist/core/worktree.js +13 -15
- package/dist/daemon/api/app-listener.d.ts +1 -0
- package/dist/daemon/api/app-listener.js +10 -10
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/daemon/api/server.d.ts +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/crtrd.js +20 -18
- package/dist/daemon/machine-link/client.d.ts +5 -1
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +3 -3
- package/dist/daemon/pidfile.js +2 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/daemon/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.js +3 -3
- package/dist/shared/env.d.ts +8 -3
- package/dist/shared/env.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/docs/apps/guides/stream-a-run.md +6 -7
- package/docs/concepts/lifecycle-and-wakes.md +1 -1
- package/docs/concepts/nodes-and-the-canvas.md +2 -2
- package/docs/concepts/profiles-kinds-and-modes.md +1 -1
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +13 -41
- package/docs/sdk/client.md +5 -7
- package/docs/sdk/docker.md +1 -1
- package/docs/sdk/errors.md +3 -43
- package/docs/sdk/getting-started.md +11 -83
- package/docs/sdk/release-notes.md +10 -0
- package/docs/sdk/resources.md +11 -44
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
- package/packages/crouter-api/dist/api/errors.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
- package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
- package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
- package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
- package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
- package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
- package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
- package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
- package/packages/crouter-api/dist/commands/surface.js +2 -3
- package/packages/crouter-api/dist/commands/sys/update.js +5 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
- package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
- package/packages/crouter-api/dist/core/config.js +10 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
- package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -20
- package/packages/crouter-api/dist/core/graph/watches.js +1 -1
- package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
- package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
- package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
- package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
- package/packages/crouter-api/dist/core/ledger/index.js +1 -1
- package/packages/crouter-api/dist/core/ledger/read.js +18 -1
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
- package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
- package/packages/crouter-api/dist/core/runs/operations.js +5 -4
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
- package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
- package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
- package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
- package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
- package/packages/crouter-api/dist/core/step-timings.js +7 -2
- package/packages/crouter-api/dist/core/worktree-close.js +5 -51
- package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
- package/packages/crouter-api/dist/core/worktree.js +9 -74
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
- package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
- package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
- package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
- package/packages/crouter-api/dist/shared/env.js +15 -4
- package/packages/crouter-api/dist/types.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
- package/dist/builtin-memory/crouter-sdk/files.md +0 -50
- package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
- package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
- package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
- package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
- package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
- package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
- package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
- package/dist/commands/surface-reload.d.ts +0 -7
- package/dist/commands/surface-reload.js +0 -1
- package/docs/sdk/bash.md +0 -39
- package/docs/sdk/files.md +0 -49
- package/docs/sdk/guides/README.md +0 -17
- package/docs/sdk/guides/event-driven-assistant.md +0 -24
- package/docs/sdk/guides/fan-out-pipeline.md +0 -24
- package/docs/sdk/guides/human-approval.md +0 -24
- package/docs/sdk/guides/typed-extraction.md +0 -24
- package/docs/sdk/nodes.md +0 -194
- package/docs/sdk/streaming.md +0 -149
- 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.
|
|
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
|
-
| `
|
|
15
|
-
| `
|
|
16
|
-
| `
|
|
17
|
-
| `
|
|
18
|
-
| `
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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. `
|
|
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
|
-
|
|
77
|
-
|
|
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 `
|
|
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
|
|
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
|
|
3
|
-
`,"utf8"),
|
|
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((
|
|
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(),
|
|
9
|
-
`);return}await
|
|
10
|
-
`),process.exit(130)),(r instanceof y||r instanceof f)&&(G(r),process.exit(typeof process.exitCode=="number"?process.exitCode:1));const
|
|
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
|
|
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
|
|
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
|
|
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
|
|
16
|
-
*
|
|
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`
|
|
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
|
|
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};
|