@north-light/cli 0.3.780 → 0.3.782
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 +14 -24
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/charges.d.ts +1 -1
- package/dist/api/dto/charges.js +1 -1
- package/dist/api/dto/inbox.d.ts +2 -0
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +2 -2
- package/dist/builtin-memory/crouter-sdk/README.md +4 -3
- package/dist/builtin-memory/crouter-sdk/client.md +5 -7
- package/dist/builtin-memory/crouter-sdk/docker.md +6 -10
- package/dist/builtin-memory/crouter-sdk/getting-started.md +10 -10
- package/dist/builtin-memory/crouter-sdk/release-notes.md +19 -3
- package/dist/builtin-memory/crouter-sdk/sourcing.md +94 -0
- package/dist/builtin-memory/insights/capture.md +2 -2
- package/dist/builtin-memory/northlight-apps/cli.md +1 -1
- package/dist/builtin-memory/northlight-apps/coding-agents.md +1 -1
- package/dist/builtin-memory/northlight-apps/get-started.md +2 -2
- package/dist/builtin-memory/northlight-apps/guides/watchable-objects.md +1 -1
- package/dist/builtin-memory/northlight-apps/how-it-fits.md +1 -1
- package/dist/builtin-memory/northlight-apps/let-their-ai-use-your-app.md +1 -4
- package/dist/builtin-memory/northlight-apps/quickstart.md +1 -1
- package/dist/cli.js +2 -2
- package/dist/clients/attach/command.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/viewer.js +458 -458
- package/dist/clients/inbox/controller.d.ts +34 -11
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/clients/inbox/dto-adapt.d.ts +1 -0
- package/dist/clients/inbox/dto-adapt.js +1 -1
- package/dist/clients/inbox/surface.js +1 -1
- package/dist/commands/canvas-config.js +2 -2
- package/dist/commands/canvas-use.js +1 -1
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/profile/default.js +1 -1
- package/dist/commands/sys/signin.d.ts +1 -1
- package/dist/commands/sys/signin.js +3 -3
- package/dist/core/command.d.ts +1 -2
- package/dist/core/command.js +6 -6
- package/dist/core/human/requests.d.ts +2 -0
- package/dist/core/human/requests.js +18 -18
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/broker/cli-relay.d.ts +0 -2
- package/dist/core/runtime/broker/cli-relay.js +1 -1
- package/dist/core/runtime/broker/run-turn-queue.js +1 -1
- package/dist/core/runtime/broker/turn-cause.d.ts +2 -0
- package/dist/core/runtime/broker/turn-cause.js +1 -1
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/machine-link/config.d.ts +2 -4
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.js +2 -2
- package/dist/daemon/postgres/cluster.d.ts +3 -3
- package/dist/daemon/postgres/cluster.js +5 -5
- package/dist/daemon/postgres/supervisor.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/apps/cli.md +1 -1
- package/docs/apps/coding-agents.md +1 -1
- package/docs/apps/get-started.md +2 -2
- package/docs/apps/guides/watchable-objects.md +1 -1
- package/docs/apps/how-it-fits.md +1 -1
- package/docs/apps/let-their-ai-use-your-app.md +1 -4
- package/docs/apps/quickstart.md +1 -1
- package/docs/cli/first-session.md +2 -2
- package/docs/concepts/why-a-daemon.md +2 -2
- package/docs/sdk/README.md +4 -3
- package/docs/sdk/client.md +5 -7
- package/docs/sdk/docker.md +5 -9
- package/docs/sdk/getting-started.md +10 -10
- package/docs/sdk/release-notes.md +19 -3
- package/docs/sdk/sourcing.md +91 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/charges.js +1 -1
- package/packages/crouter-api/dist/daemon/machine-link/config.js +3 -5
- package/packages/crouter-api/dist/daemon/manage.js +3 -3
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +1 -1
- package/dist/core/northlight/previews.d.ts +0 -22
- package/dist/core/northlight/previews.js +0 -1
package/README.md
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
<a href="https://discord.gg/txKS3swtWY"><img alt="discord" src="https://img.shields.io/badge/discord-join-5865F2?logo=discord&logoColor=white"></a>
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
|
-
crouter is an agent runtime for Node.js. Each agent is a **node**: a record with a goal, a context directory, and a detached process (its *broker*) that hosts the model session. A daemon, `crtrd`, owns every node's state and lifecycle. You drive it with the `crtr` command line, a terminal viewer, or a typed TypeScript SDK — all three are clients of the same
|
|
11
|
+
crouter is an agent runtime for Node.js. Each agent is a **node**: a record with a goal, a context directory, and a detached process (its *broker*) that hosts the model session. A daemon, `crtrd`, owns every node's state and lifecycle. You drive it with the `crtr` command line, a terminal viewer, or a typed TypeScript SDK — all three are clients of the same `/v1` API. Each model session runs on [pi](https://github.com/earendil-works/pi), the open-source coding-agent harness; crouter adds the daemon, the node graph, the context system and the CLI around it.
|
|
12
12
|
|
|
13
|
-
Closing a terminal does not stop an agent, and an agent that is waiting on something has no process at all. Nodes can spawn children, report to whoever subscribes to them, and share markdown documents that other agents are shown when they become relevant. crouter is not a model and does not bundle one
|
|
13
|
+
Closing a terminal does not stop an agent, and an agent that is waiting on something has no process at all. Nodes can spawn children, report to whoever subscribes to them, and share markdown documents that other agents are shown when they become relevant. crouter is not a model and does not bundle one. The runtime is the Northlight cloud control plane (`api-fleet.northlight.ai`), which owns every node's state and runs the models; a Mac you sign in with `crtr sys signin` is a machine where an agent's commands run. There is no standalone mode.
|
|
14
14
|
|
|
15
|
-
[Docs](https://
|
|
15
|
+
[Docs](https://sdk.docs.northlight.ai) · [Getting started](https://github.com/Northlight-Systems/crouter/blob/main/docs/cli/first-session.md) · [Concepts](https://github.com/Northlight-Systems/crouter/blob/main/docs/concepts/README.md) · [Plugins](https://github.com/Northlight-Systems/crouter/blob/main/docs/plugin/README.md) · [Marketplace](https://github.com/crouton-labs/crouter-official-marketplace) · [Discord](https://discord.gg/txKS3swtWY)
|
|
16
16
|
|
|
17
17
|
## Install
|
|
18
18
|
|
|
@@ -21,13 +21,13 @@ npm install -g @north-light/cli
|
|
|
21
21
|
crtr
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
The first `crtr` on a machine opens the setup installer
|
|
24
|
+
Start by signing in to your Northlight account (`crtr sys signin`; create the account at `https://account.northlight.ai/signup`). The first `crtr` on a machine opens the setup installer, which offers companion packages (including the official plugin marketplace) and system dependencies such as tmux. After setup, `crtr` opens a conversation with an agent, which offers a short tour of how crouter works. `crtr sys setup` reopens the installer later.
|
|
25
25
|
|
|
26
26
|
Requirements:
|
|
27
27
|
|
|
28
|
-
- Node.js 22.19 or later. This is the floor set by the pi packages crouter depends on; CI
|
|
28
|
+
- Node.js 22.19 or later. This is the floor set by the pi packages crouter depends on; CI runs Node 24.
|
|
29
29
|
- tmux, for the in-terminal viewer. The first-run installer offers to install it, and `crtr` started outside tmux opens a `crouter` tmux session for you and runs there.
|
|
30
|
-
- macOS is what CI exercises.
|
|
30
|
+
- macOS is what CI exercises. Linux machines join the Northlight fleet through the sandbox images the fleet builds.
|
|
31
31
|
|
|
32
32
|
## Quick start
|
|
33
33
|
|
|
@@ -62,7 +62,7 @@ crtr canvas browse # interactive navigator with tabs and search
|
|
|
62
62
|
crtr canvas attention list # nodes waiting on you
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
The [first-session guide](https://
|
|
65
|
+
The [first-session guide](https://github.com/Northlight-Systems/crouter/blob/main/docs/cli/first-session.md) walks through this in order.
|
|
66
66
|
|
|
67
67
|
## What it does
|
|
68
68
|
|
|
@@ -97,9 +97,9 @@ flowchart LR
|
|
|
97
97
|
Viewer -. live session .-> Broker
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
-
`crtrd` is the only writer of canvas state and the only launcher of brokers. The CLI, the viewer and SDK applications call its `/v1` API; none of them opens the canvas database or starts an engine of its own.
|
|
100
|
+
`crtrd` is the only writer of canvas state and the only launcher of brokers. The CLI, the viewer and SDK applications call its `/v1` API; none of them opens the canvas database or starts an engine of its own. In production the daemon is the Northlight control plane, reached over HTTPS with a bearer token; a signed-in Mac runs the processes of its nodes and holds an outbound link to the cloud.
|
|
101
101
|
|
|
102
|
-
What this costs:
|
|
102
|
+
What this costs: the runtime has to be reachable, and a network failure on a remote client fails a request loudly rather than replaying it. What it buys is one owner for state, so a node outlives the terminal, the viewer, or the application that created it. [Why a daemon](https://github.com/Northlight-Systems/crouter/blob/main/docs/concepts/why-a-daemon.md) covers the reasoning.
|
|
103
103
|
|
|
104
104
|
## Use crouter from an application
|
|
105
105
|
|
|
@@ -111,7 +111,7 @@ npm install @north-light/sdk zod
|
|
|
111
111
|
import Crouter from '@north-light/sdk';
|
|
112
112
|
import { z } from 'zod';
|
|
113
113
|
|
|
114
|
-
const client = new Crouter(); //
|
|
114
|
+
const client = new Crouter(); // connects to the runtime; pass baseURL and token explicitly outside a signed-in machine
|
|
115
115
|
|
|
116
116
|
const run = await client.runs.parse({
|
|
117
117
|
prompt: 'Report the name and version of the package in your files folder.',
|
|
@@ -120,21 +120,11 @@ const run = await client.runs.parse({
|
|
|
120
120
|
console.log(run);
|
|
121
121
|
```
|
|
122
122
|
|
|
123
|
-
`runs.parse` returns a typed result instead of text you have to parse. A program that drives its owner's own daemon (nodes, bash, crons, the human inbox) uses `CrtrClient` from `@north-light/api` or the `crtr` CLI. See the [SDK docs](https://
|
|
124
|
-
|
|
125
|
-
## Run it in a container
|
|
126
|
-
|
|
127
|
-
```bash
|
|
128
|
-
docker run --cap-add SYS_ADMIN --cap-add NET_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined \
|
|
129
|
-
-e CRTRD_TOKEN=<a-secret-you-choose> -p 7777:7777 ghcr.io/northlight-systems/crtrd
|
|
130
|
-
curl -H "Authorization: Bearer <a-secret-you-choose>" http://localhost:7777/healthz
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
The image runs `crtrd` headless behind TCP; every request needs the bearer token. Its sandbox launcher needs the two capabilities and unconfined seccomp/AppArmor profiles shown. It contains no model credential, so give the agent one before you create a run. Mount a named volume at `/volume` to keep the canvas and installed credentials across restarts. From Node, [`@north-light/env-docker`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-env-docker) starts and stops this container for you. Details are in [`docker/README.md`](https://github.com/Northlight-Systems/crouter/blob/main/docker/README.md).
|
|
123
|
+
`runs.parse` returns a typed result instead of text you have to parse. A program that drives its owner's own daemon (nodes, bash, crons, the human inbox) uses `CrtrClient` from `@north-light/api` or the `crtr` CLI. See the [SDK docs](https://github.com/Northlight-Systems/crouter/blob/main/docs/sdk/README.md).
|
|
134
124
|
|
|
135
125
|
## Extend crouter
|
|
136
126
|
|
|
137
|
-
An application exposes typed operations as native `crtr` commands with [`@north-light/plugin`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-plugin): define a command tree once and it produces the HTTP handler and the archive that `crtr pkg plugin install --endpoint <url> --name <name>` reads. The [plugin docs](https://
|
|
127
|
+
An application exposes typed operations as native `crtr` commands with [`@north-light/plugin`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-plugin): define a command tree once and it produces the HTTP handler and the archive that `crtr pkg plugin install --endpoint <url> --name <name>` reads. The [plugin docs](https://github.com/Northlight-Systems/crouter/blob/main/docs/plugin/README.md) cover commands, parameters, output, errors and deployment.
|
|
138
128
|
|
|
139
129
|
Ready-made plugins live in the [official marketplace](https://github.com/crouton-labs/crouter-official-marketplace): `exa-search`, `capture`, `tsym`, `bird`, `github-asset`, `dev`, `vercel`, `fly`, `railway`, `cloudflare`, and others. The first-run installer offers to register it.
|
|
140
130
|
|
|
@@ -146,10 +136,10 @@ Ready-made plugins live in the [official marketplace](https://github.com/crouton
|
|
|
146
136
|
| [`@north-light/sdk`](https://www.npmjs.com/package/@north-light/sdk) | Typed Node and browser client: runs, streaming, results, files, bash, memory | [`packages/crouter-sdk`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-sdk) |
|
|
147
137
|
| [`@north-light/plugin`](https://www.npmjs.com/package/@north-light/plugin) | Author HTTP plugins from one typed command tree | [`packages/crouter-plugin`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-plugin) |
|
|
148
138
|
| [`@north-light/api`](https://www.npmjs.com/package/@north-light/api) | The `/v1` API contract: `CrtrClient`, DTOs, routes, errors | [`packages/crouter-api`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-api) |
|
|
149
|
-
| [`@north-light/env-docker`](https://www.npmjs.com/package/@north-light/env-docker) |
|
|
139
|
+
| [`@north-light/env-docker`](https://www.npmjs.com/package/@north-light/env-docker) | Northlight-internal: runs the `crtrd` CI image for the pr-review workflow; not a way to run or self-host crtr | [`packages/crouter-env-docker`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-env-docker) |
|
|
150
140
|
| [`@north-light/identity`](https://www.npmjs.com/package/@north-light/identity) | Verify access tokens and evaluate scopes | [`packages/crouter-identity`](https://github.com/Northlight-Systems/crouter/tree/main/packages/crouter-identity) |
|
|
151
141
|
|
|
152
|
-
Most applications need only `@north-light/sdk`. The other repository contents: [`docs/`](https://github.com/Northlight-Systems/crouter/tree/main/docs) is the documentation source, [`apps/docs`](https://github.com/Northlight-Systems/crouter/tree/main/apps/docs) is the TanStack Start site that publishes
|
|
142
|
+
Most applications need only `@north-light/sdk`. The other repository contents: [`docs/`](https://github.com/Northlight-Systems/crouter/tree/main/docs) is the documentation source, [`apps/docs`](https://github.com/Northlight-Systems/crouter/tree/main/apps/docs) is the TanStack Start site that publishes the app-builder pages at sdk.docs.northlight.ai, [`docker/`](https://github.com/Northlight-Systems/crouter/tree/main/docker) builds the `crtrd` image, and [`examples/`](https://github.com/Northlight-Systems/crouter/tree/main/examples) holds the SDK recipes and a localhost demo.
|
|
153
143
|
|
|
154
144
|
## Develop
|
|
155
145
|
|
package/dist/api/client.d.ts
CHANGED
|
@@ -434,7 +434,9 @@ export declare class CrtrClient {
|
|
|
434
434
|
forkReviewComment(commentId: string): Promise<ReviewCommentForkDTO>;
|
|
435
435
|
/** Pending page/review tickets across every available crouter-owned
|
|
436
436
|
* humanloop root. */
|
|
437
|
-
listHumanInbox(
|
|
437
|
+
listHumanInbox(opts?: {
|
|
438
|
+
includePages?: boolean;
|
|
439
|
+
}): Promise<InboxListDTO>;
|
|
438
440
|
/** Read one page ticket by its opaque ticket id (pending, resolved, or canceled). */
|
|
439
441
|
getHumanInboxPage(ticketId: InboxTicketIdDTO): Promise<InboxPageDTO>;
|
|
440
442
|
/** All page tickets, oldest first (pending, resolved, or canceled) —
|
package/dist/api/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
var N=Object.defineProperty;var a=(i,e)=>N(i,"name",{value:e,configurable:!0});import{ApiError as f,isErrorBody as x}from"./errors.js";import{routes as r}from"./routes.js";import{reportServerTiming as B}from"./server-timing.js";import{isSafeNodeId as b}from"./dto/common.js";import{isSafeBashJobId as L}from"./dto/bash-jobs.js";import{isSafeCronId as F}from"./dto/crons.js";const I=3e4,$=3e4,H=Symbol.for("@north-light/api/local-socket-fetch"),U=1e4,j=200;async function J({windowMs:i,probe:e,initialError:t,pollIntervalMs:n=j,retry:s=a(()=>!0,"retry"),now:o=Date.now,sleep:u=M}){const c=o()+i;let l=t;for(;;){const m=c-o();if(m<=0)throw l??new Error("crtrd availability window expired without a probe failure");try{await e(m);return}catch(P){if(l=P,!s(P))throw P}const h=c-o();if(h<=0)throw l;await u(Math.min(n,h))}}a(J,"waitForDaemonAvailability");const v=2147483647;function S(i,e="elapsed",t){const n=e==="retry_after"?`the server asked to retry after ${t}s, which is later than the call's deadline (${new Date(i).toISOString()}); not waiting`:`the call's deadline (${new Date(i).toISOString()}) passed`;return new f(504,"deadline_exceeded",n,{deadline_at:i,reason:e,...t===void 0?{}:{retry_after_s:t}})}a(S,"deadlineExceeded");const p=a(i=>S(i??Date.now()),"budgetExhausted");class oe{static{a(this,"CrtrClient")}baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??I,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[H]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??U}healthz(){return this.request("GET",r.healthz())}async probeHealthz(e){const t=await this.transport("GET",r.healthz(),void 0,{timeout:e});if(t.status===503)try{const n=await t.clone().json();if(typeof n.startup_blocked=="string")return n}catch{}return w(t)}async ready(){const e=await this.transport("GET",r.ready(),void 0,{});if(e.status===503)try{const t=await e.clone().json();if(t.ready===!1)return t}catch{}return w(e)}status(){return this.request("GET",r.status())}due(){return this.request("GET",r.due())}restartDaemon(){return this.request("POST",r.daemonRestart())}drainDaemon(e={}){const t=e.settle_limit_ms??0;return this.request("POST",r.daemonDrain(),e,{timeout:t+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",r.daemonDrain())}admitDaemon(){return this.request("POST",r.daemonAdmit())}appendNodeLog(e,t){return this.request("POST",r.nodeLog(this.nodePath(e)),t)}async putNodeTelemetry(e,t){await this.request("PUT",r.nodeTelemetry(this.nodePath(e)),t)}async putNodeSummaries(e,t){await this.request("PUT",r.nodeSummaries(this.nodePath(e)),t)}async putNodeRecap(e,t){await this.request("PUT",r.nodeRecap(this.nodePath(e)),t)}readNodeInboxReport(e,t,n){return this.request("GET",d(r.nodeInboxReport(this.nodePath(e)),{ref:t,execution_id:n}))}listNodeAttachments(e){return this.request("GET",r.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,t){const n=await this.send("GET",r.nodeAttachment(this.nodePath(e),t));return n.ok||await w(n),new Uint8Array(await n.arrayBuffer())}createNodeFile(e,t){return this.request("POST",r.nodeFiles(this.nodePath(e)),t)}createNodeUpload(e,t){return this.request("POST",r.nodeUploads(this.nodePath(e)),t)}nodeUploadLink(e,t){return this.request("POST",r.nodeUploadLink(this.nodePath(e),t))}completeNodeFile(e,t){return this.request("POST",r.nodeFileComplete(this.nodePath(e),t))}readNodePassiveMessage(e,t){return this.request("GET",d(r.nodePassiveMessage(this.nodePath(e)),{ref:t}))}nodePushedFinal(e,t){return this.request("POST",r.nodePushedFinal(this.nodePath(e)),t)}createNode(e){return this.request("POST",r.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",d(r.nodes(),e))}getNode(e){return this.request("GET",r.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:t}={}){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",d(r.nodeOutcome(this.nodePath(e)),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}getNodeEvents(e,t={},n={}){if(t.after!==void 0&&(!Number.isSafeInteger(t.after)||t.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",d(r.nodeEvents(this.nodePath(e)),t),void 0,{...n,headers:{accept:"text/event-stream",...n.headers??{}},timeout:0})}async*getBrokerSignals(e,t,n={}){const s=await this.send("GET",d(r.nodeBrokerSignals(this.nodePath(e)),{execution_id:t}),void 0,{...n,headers:{accept:"application/x-ndjson",...n.headers??{}},timeout:0});if(!s.ok){await w(s);return}if(s.body===null)throw new f(s.status,"invalid_response","broker signal stream has no body");const o=s.body.getReader(),u=new TextDecoder;let c="";try{for(;;){const{done:l,value:m}=await o.read();if(l)break;c+=u.decode(m,{stream:!0});let h;for(;(h=c.indexOf(`
|
|
2
|
-
`))!==-1;){const P=c.slice(0,h);c=c.slice(h+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new f(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,t){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,t):this.request("POST","/v1/structured-requests",e,t)}getStructuredRequest(e,{wait:t=0,budgetMs:n}={}){if(!Number.isInteger(t)||t<0||t>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",d(`/v1/structured-requests/${this.requestPath(e)}`,{wait:t}),void 0,{budgetMs:n})}cancelStructuredRequest(e,t){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},t)}registerOutcomeDelivery(e,t){return this.request("PUT",r.nodeOutcomeDelivery(this.nodePath(e)),t)}getOutcomeDelivery(e){return this.request("GET",r.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",r.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",r.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,t,n={}){const s=new URLSearchParams;n.tail_lines!==void 0&&s.set("tail_lines",String(n.tail_lines)),n.max_bytes!==void 0&&s.set("max_bytes",String(n.max_bytes));const o=s.size===0?"":`?${s.toString()}`;return this.request("GET",`${r.nodeJobOutput(this.nodePath(e),this.jobPath(t))}${o}`)}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}async patchBashJob(e,t,n){await this.request("PATCH",r.nodeJob(this.nodePath(e),this.jobPath(t)),n)}async reportBashJob(e,t,n){await this.request("POST",r.nodeJobReport(this.nodePath(e),this.jobPath(t)),n)}sendMessage(e,t){return this.request("POST",r.nodeMessages(this.nodePath(e)),t)}interruptNode(e){return this.request("POST",r.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,t){return this.request("POST",r.nodeReports(this.nodePath(e)),t)}submitResult(e,t){return this.request("POST",r.nodeResult(this.nodePath(e)),t)}forkNode(e){return this.request("POST",r.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",r.nodeKick(this.nodePath(e)),{})}reviveNode(e,t){return this.request("POST",r.nodeRevive(this.nodePath(e)),t??{})}relaunchRoot(e){return this.request("POST",r.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,t){return this.request("POST",r.nodeBrokerSessionBound(this.nodePath(e)),t)}cycleStartBroker(e,t,n){return this.request("POST",r.nodeBrokerCycleStart(this.nodePath(e)),t,n)}settleBroker(e,t){return this.request("POST",r.nodeBrokerSettle(this.nodePath(e)),t)}startBrokerCycle(e,t){return this.request("POST",r.nodeBrokerCycle(this.nodePath(e)),t)}async postBrokerIdle(e,t){await this.request("POST",r.nodeBrokerIdle(this.nodePath(e)),t)}completeBrokerPark(e,t){return this.request("POST",r.nodeBrokerParkComplete(this.nodePath(e)),t)}recordBrokerParkActivity(e,t){return this.request("POST",r.nodeBrokerParkActivity(this.nodePath(e)),t)}async recordBrokerTelemetry(e,t){await this.request("POST",r.nodeBrokerTelemetry(this.nodePath(e)),t)}claimNodeMail(e,t){return this.request("POST",r.nodeMailClaim(this.nodePath(e)),t)}acknowledgeNodeMail(e,t){return this.request("POST",r.nodeMailAcknowledge(this.nodePath(e)),t)}recordBrokerTurn(e,t){return this.request("POST",r.brokerTurn(this.nodePath(e)),t)}mutateBrokerProviderRetry(e,t){return this.request("POST",r.brokerProviderRetry(this.nodePath(e)),t)}mutateBrokerFault(e,t){return this.request("POST",r.brokerFault(this.nodePath(e)),t)}getBrokerRecovery(e,t){return this.request("GET",`${r.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(t)}`)}recordNodeFault(e,t){return this.request("POST",r.nodeFault(this.nodePath(e)),t)}clearNodeFault(e,t={}){const n=new URLSearchParams;t.link!==void 0&&n.set("link",t.link),t.preserve_episode!==void 0&&n.set("preserve_episode",String(t.preserve_episode));const s=n.size===0?"":`?${n.toString()}`;return this.request("DELETE",`${r.nodeFault(this.nodePath(e))}${s}`)}commitBrokerModel(e,t){return this.request("POST",r.nodeBrokerModel(this.nodePath(e)),t)}executionStart(e){return this.request("GET",r.executionStart(e))}gitCredential(e,t){return this.request("POST",r.environmentGitCredential(e),t)}postFeedback(e){return this.request("POST",r.feedback(),e)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",r.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,t){return this.request("POST",r.nodeBrokerGoal(this.nodePath(e)),t)}commitBrokerGeneratedName(e,t){return this.request("POST",r.nodeBrokerGeneratedName(this.nodePath(e)),t)}commitBrokerPersonaAck(e,t){return this.request("POST",r.nodeBrokerPersonaAck(this.nodePath(e)),t)}closeNode(e,t){return this.request("POST",r.nodeClose(this.nodePath(e)),t??{})}async markNodeRead(e){await this.request("POST",r.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",r.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",r.nodeDemote(this.nodePath(e)),{})}promoteNode(e,t){return this.request("POST",r.nodePromote(this.nodePath(e)),t)}yieldNode(e,t){return this.request("POST",r.nodeYield(this.nodePath(e)),t)}waitNode(e,t){return this.request("POST",r.nodeWait(this.nodePath(e)),t)}listKinds(){return this.request("GET",r.kinds())}patchConfig(e,t){return this.request("PATCH",r.nodeConfig(this.nodePath(e)),t,t.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",r.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,t){return this.request("POST",r.nodeWorktreeAbandon(this.nodePath(e)),t)}retryDelivery(e){return this.request("POST",r.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",r.quarantinedWorktrees())}showLimits(){return this.request("GET",r.limits())}setAppLimits(e,t){return this.request("PUT",r.limitsApp(e),t)}removeAppLimits(e,t){return this.request("DELETE",d(r.limitsApp(e),{fields:t.join(",")}))}listCharges(e={}){return this.request("GET",d(r.charges(),e))}listSpendLimits(){return this.request("GET",r.spendLimits())}setSpendLimit(e,t){return this.request("PUT",r.spendLimit(e),t)}removeSpendLimit(e){return this.request("DELETE",r.spendLimit(e))}listSpaces(){return this.request("GET",r.spaces())}subscribe(e,t){return this.request("POST",r.nodeSubscriptions(this.nodePath(e)),t)}listFocuses(){return this.request("GET",r.focuses())}focusOf(e){return this.request("GET",d(r.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",d(r.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",r.focuses(),e)}async setFocusPane(e,t){await this.request("PATCH",r.focus(e),t)}async closeFocus(e){await this.request("DELETE",r.focus(e))}async unsubscribe(e,t){await this.request("DELETE",r.nodeSubscription(this.nodePath(e),this.nodePath(t)))}armCron(e){return this.request("POST",r.crons(),e)}listCrons(e){return this.request("GET",d(r.crons(),e))}showCron(e,t){return this.request("GET",d(r.cron(this.cronPath(e)),t))}pauseCron(e,t){return this.request("POST",d(r.cronPause(this.cronPath(e)),t),{})}resumeCron(e,t){return this.request("POST",d(r.cronResume(this.cronPath(e)),t),{})}runCron(e,t){return this.request("POST",d(r.cronRun(this.cronPath(e)),t),{})}async cancelCron(e,t){await this.request("DELETE",d(r.cron(this.cronPath(e)),t))}pokeCrons(){return this.request("POST",r.cronsPoke(),{})}ensureAttach(e,t){return this.request("POST",r.nodeAttach(this.nodePath(e)),t??{},{timeout:$+this.timeoutMs})}getReports(e,t){return this.request("GET",d(r.nodeReports(this.nodePath(e)),t))}getTranscript(e,t){return this.request("GET",d(r.nodeTranscript(this.nodePath(e)),t))}getSnapshot(e){return this.request("GET",r.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",r.nodeSubject(this.nodePath(e)))}getNodeMessages(e,t){return this.request("GET",d(r.nodeMessages(this.nodePath(e)),t))}getSession(e){return this.request("GET",r.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",r.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",d(r.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",r.nodeContext(this.nodePath(e)))}peekFile(e,t,n){return this.request("GET",d(r.filePeek(),{path:e,encoding:t}),void 0,n)}writeFile(e,t,n,s){return this.request("POST",r.fileWrite(),{path:e,content:t,encoding:n},s)}listFiles(e,t,n){return this.request("GET",d(r.fileList(),{path:e,limit:t}),void 0,n)}runBash(e,t){return this.request("POST",r.bash(),e,t)}objects={read:a((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:a(e=>this.request("GET",d(r.objects(),e)),"list"),search:a(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:a((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:a((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:a((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:a(e=>this.request("POST",r.docs(),e),"write"),edit:a((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:a((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:a(e=>this.request("DELETE",r.doc(e)),"delete"),history:a((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:a((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={browserAccess:a(()=>this.request("GET",r.documentsBrowserAccess()),"browserAccess"),reconcilePackages:a(e=>this.request("POST",r.documentsReconcilePackages(),e),"reconcilePackages")};plugins={appToken:a(e=>this.request("GET",r.pluginAppToken(e)),"appToken"),callHeaders:a((e,t)=>this.request("POST",r.pluginCallHeaders(e),t),"callHeaders")};nodeDelivery(e,t){return this.request("POST",r.nodeDelivery(this.nodePath(e)),t)}deliveryDryRun(e){return this.request("POST",r.deliveryDryRun(),e)}recordBackgroundedJob(e,t,n){return this.request("POST",r.nodeJobBackground(this.nodePath(e),this.jobPath(t)),n)}ensureProfile(e,t){return this.request("PUT",r.profile(e),t??{})}createProfile(e){return this.request("POST",r.profiles(),e)}listProfiles(){return this.request("GET",r.profiles())}updateProfile(e,t){return this.request("PATCH",r.profile(e),t)}listAppEnv(){return this.request("GET",r.appEnv())}setAppEnv(e,t){return this.request("PUT",r.appEnvVar(e),{value:t})}removeAppEnv(e){return this.request("DELETE",r.appEnvVar(e))}listProfileEnv(e){return this.request("GET",r.profileEnv(e))}setProfileEnv(e,t,n){return this.request("PUT",r.profileEnvVar(e,t),{value:n})}removeProfileEnv(e,t){return this.request("DELETE",r.profileEnvVar(e,t))}getProfileEnvironment(e){return this.request("GET",r.profileEnvironment(e))}setProfileEnvironment(e,t){return this.request("PUT",r.profileEnvironment(e),t)}getProfile(e){return this.request("GET",r.profile(e))}pauseProfile(e){return this.request("POST",r.profilePause(e),{})}resumeProfile(e){return this.request("POST",r.profileResume(e),{})}updateProfileMetadata(e,t){return this.request("PATCH",r.profileMetadata(e),t)}deleteProfile(e,t){return this.request("DELETE",r.profile(e),t)}getSettings(){return this.request("GET",r.settings())}putSettings(e){return this.request("PUT",r.settings(),e)}listModelAuth(){return this.request("GET",r.modelAuths())}getModelAuthReadiness(e){return this.request("GET",d(r.modelAuthReadiness(),e))}installCredential(e,t){return this.request("PUT",r.modelAuth(e),t)}removeCredential(e){return this.request("DELETE",r.modelAuth(e))}patchModelAuthAccount(e,t,n){return this.request("PATCH",r.modelAuthAccount(e,t),n)}removeModelAuthAccount(e,t){return this.request("DELETE",r.modelAuthAccount(e,t))}startModelAuth(e){return this.request("POST",r.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,t){return this.request("POST",r.modelAuthFlowComplete(e),t,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",r.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,t){return this.request("GET",d(r.modelAuthFlow(e),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",r.humanReviews(),e)}listReviews(e){return this.request("GET",d(r.humanReviews(),e))}getReview(e){return this.request("GET",r.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",r.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,t={}){return this.request("POST",r.humanReviewCancel(this.reviewPath(e)),t)}getReviewDocumentBase(e){return this.request("GET",r.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("POST",r.humanReviewComments(n),t)}listReviewComments(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("GET",d(r.humanReviewComments(n),t))}readReviewCommentEvents(e,t){return this.request("GET",d(r.humanReviewCommentEvents(this.reviewPath(e)),t))}getReviewComment(e){return this.request("GET",r.humanComment(this.commentPath(e)))}editReviewComment(e,t){return this.request("POST",r.humanCommentEdit(this.commentPath(e)),t)}resolveReviewComment(e,t={}){return this.request("POST",r.humanCommentResolve(this.commentPath(e)),t)}reopenReviewComment(e,t={}){return this.request("POST",r.humanCommentReopen(this.commentPath(e)),t)}deleteReviewComment(e,t={}){return this.request("POST",r.humanCommentDelete(this.commentPath(e)),t)}forkReviewComment(e){return this.request("POST",r.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",r.humanInbox())}getHumanInboxPage(e){return this.request("GET",r.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,t={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e,state:t.state}))}respondHumanInboxPage(e,t){return this.request("POST",r.humanInboxRespond(this.ticketId(e)),t)}postInboxProgress(e,t){return this.request("POST",r.humanInboxProgress(this.ticketId(e)),{responses:t})}getInboxResponse(e){return this.request("GET",r.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,t){return this.request("POST",r.humanInboxCancel(this.ticketId(e)),t??{})}createHumanRequest(e){return this.request("POST",r.humanRequests(),e)}listPageComponents(){return this.request("GET",r.humanComponents())}getHumanRequest(e){return this.request("GET",r.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,t){return this.request("POST",r.humanRequestReplace(this.requestPath(e)),t)}respondHumanRequest(e,t){return this.request("POST",r.humanRequestRespond(this.requestPath(e)),t)}dismissHumanRequest(e,t={}){return this.request("POST",r.humanRequestDismiss(this.requestPath(e)),t)}cancelHumanRequest(e,t={}){return this.request("POST",r.humanRequestCancel(this.requestPath(e)),t)}resolvePageFeedbackComment(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(t)}`);return this.request("POST",r.humanInboxFeedbackResolve(this.ticketId(e),t),{node_id:n})}async dashboard(e){const t=e?.under!==void 0?{under:e.under}:void 0,[n,s]=await Promise.all([this.listNodes(t),this.status()]);return{nodes:n,counts:s.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",r.canvasAttention())}attentionCounts(e){const t={node_ids:e};return this.request("POST",r.canvasAttentionCounts(),t)}historySearch(e){return this.request("POST",r.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",r.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",d(r.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",r.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",r.canvasSnapshot())}analytics(e){return this.request("GET",d(r.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,t){await this.request("POST",r.nodeMemoryReads(this.nodePath(e)),t)}liveRoots(e={}){return this.request("GET",d(r.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",r.canvasView(e))}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await w(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(e){return this.request("GET",e===void 0?r.canvasGraph():`${r.canvasGraph()}?root=${encodeURIComponent(e)}`)}prune(e){return this.request("POST",r.canvasPrune(),e)}async request(e,t,n,s){try{const o=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,o);return await w(u,o?.deadlineAt)}catch(o){throw Q(e,q(o,s?.signal))}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw q(s,n?.signal)}}async send(e,t,n,s={}){const o=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=o.maxRetries??this.maxRetries,l=Math.min(o.deadlineAt??1/0,Date.now()+W);for(let m=0;;m++){let h;try{h=await this.transport(e,t,n,o)}catch(P){if(this.isColdSocketError(P)||this.isInterruptedSocketError(P)){const T=this.availabilityFailure?.();if(T!==void 0)throw T}if(this.isColdSocketError(P))try{await this.handleColdSocket(P,o.deadlineAt),h=await this.transport(e,t,n,o)}catch(T){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!A(T,o.signal)?S(o.deadlineAt):q(T,o.signal)}else{if(this.isInterruptedSocketError(P)&&this.localSocketTransport&&(!u||m<c))return await this.rideOutInterruptedRequest(e,t,n,o);if(u&&m<c&&!A(P,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(P))){await R(G(m+1),o);continue}else throw q(P,o.signal)}}if(V(e)&&c>0&&h.status===503&&await z(h,o.deadlineAt)){const P=Math.max(250,(D(h)??0)*1e3)+Math.random()*250;if(Date.now()+P>=l)return h;await g(h,o.deadlineAt),await R(P,{signal:o.signal});continue}if(u&&m<c&&K(h.status)){await g(h,o.deadlineAt),await R(G(m+1),o,D(h));continue}return h}}resolveBudget(e){const{budgetMs:t,deadlineAt:n,...s}=e;if(t===void 0&&n===void 0)return s;if(t!==void 0&&(!Number.isFinite(t)||t<=0||t>v))throw new RangeError(`budgetMs must be a positive finite number of at most ${v}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>v))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${v} ms from now`);return{...s,deadlineAt:Math.min(n??1/0,t===void 0?1/0:Date.now()+t)}}async awaitWithinBudget(e,t){if(t===void 0)return e;const n=t-Date.now();if(n<=0)throw p(t);let s;try{return await Promise.race([e,new Promise((o,u)=>{s=setTimeout(()=>u(p(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const o=this.resolveBudget(s);try{return await w(await this.transport(e,t,n,o))}catch(u){throw q(u,o.signal)}}nodePath(e){if(!b(e))throw new f(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!L(e))throw new f(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!F(e))throw new f(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!b(e))throw new f(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!b(e))throw new f(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new f(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const o=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(p(s.deadlineAt));const u=n===void 0?void 0:JSON.stringify(n),c={accept:"application/json",...this.headers,...s.headers};u!==void 0&&(c["content-type"]="application/json");const l=s.timeout??this.timeoutMs,m=o===void 0?l:l>0?Math.min(l,o):o,h=new AbortController,P=o!==void 0&&(l<=0||o<=l),T=m>0?setTimeout(()=>h.abort(P?p(s.deadlineAt):new DOMException("request timed out","TimeoutError")),m):void 0,E=s.signal,k=a(()=>h.abort(E?.reason),"onExternalAbort");E!==void 0&&(E.aborted?h.abort(E.reason):E.addEventListener("abort",k,{once:!0}));const C=a(()=>{T!==void 0&&clearTimeout(T),E?.removeEventListener("abort",k)},"finish");return Z(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:h.signal}),h.signal).then(y=>(B(y.headers.get("server-timing")),this.retainRequestLifetime(y,C,()=>h.signal.aborted?h.signal.reason:void 0)),y=>{throw C(),y})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let o=!1;const u=a(()=>{o||(o=!0,t())},"close"),c=new ReadableStream({async pull(l){try{const{done:m,value:h}=await s.read();m?(u(),l.close()):l.enqueue(h)}catch(m){u(),l.error(n()??m)}},async cancel(l){u(),await s.cancel(l)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=O(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=O(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(o){throw q(o,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new f(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,t,n,s)}catch(o){throw q(o,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw p(t);let s,o;try{await J({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:a(u=>u!==s&&u!==o,"retry"),probe:a(async u=>{const c=this.availabilityFailure?.();if(c!==void 0)throw o=c,c;const l=this.coldStartFailure?.();if(l!==void 0)throw s=new f(503,"daemon_unavailable",`crtrd failed to start: ${l}`),s;const m=await this.transport("GET",r.healthz(),void 0,{timeout:u});if(m.status>=200&&m.status<300){await g(m);return}const h=await m.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new f(m.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${m.status}: ${h.slice(0,500)}`)},"probe")})}catch(u){throw u===s&&(this.startupFailureReported=!0),u}}async handleColdSocket(e,t){const n=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;n&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),t));try{await this.awaitAvailability(e,t)}catch(s){if(n&&!this.startupFailureReported){const o=X(this.coldStartDiagnostic);if(o!==void 0){const u=q(s);throw new f(u.status,u.code,`${u.message}
|
|
2
|
+
`))!==-1;){const P=c.slice(0,h);c=c.slice(h+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new f(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,t){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,t):this.request("POST","/v1/structured-requests",e,t)}getStructuredRequest(e,{wait:t=0,budgetMs:n}={}){if(!Number.isInteger(t)||t<0||t>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",d(`/v1/structured-requests/${this.requestPath(e)}`,{wait:t}),void 0,{budgetMs:n})}cancelStructuredRequest(e,t){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},t)}registerOutcomeDelivery(e,t){return this.request("PUT",r.nodeOutcomeDelivery(this.nodePath(e)),t)}getOutcomeDelivery(e){return this.request("GET",r.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",r.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",r.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,t,n={}){const s=new URLSearchParams;n.tail_lines!==void 0&&s.set("tail_lines",String(n.tail_lines)),n.max_bytes!==void 0&&s.set("max_bytes",String(n.max_bytes));const o=s.size===0?"":`?${s.toString()}`;return this.request("GET",`${r.nodeJobOutput(this.nodePath(e),this.jobPath(t))}${o}`)}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}async patchBashJob(e,t,n){await this.request("PATCH",r.nodeJob(this.nodePath(e),this.jobPath(t)),n)}async reportBashJob(e,t,n){await this.request("POST",r.nodeJobReport(this.nodePath(e),this.jobPath(t)),n)}sendMessage(e,t){return this.request("POST",r.nodeMessages(this.nodePath(e)),t)}interruptNode(e){return this.request("POST",r.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,t){return this.request("POST",r.nodeReports(this.nodePath(e)),t)}submitResult(e,t){return this.request("POST",r.nodeResult(this.nodePath(e)),t)}forkNode(e){return this.request("POST",r.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",r.nodeKick(this.nodePath(e)),{})}reviveNode(e,t){return this.request("POST",r.nodeRevive(this.nodePath(e)),t??{})}relaunchRoot(e){return this.request("POST",r.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,t){return this.request("POST",r.nodeBrokerSessionBound(this.nodePath(e)),t)}cycleStartBroker(e,t,n){return this.request("POST",r.nodeBrokerCycleStart(this.nodePath(e)),t,n)}settleBroker(e,t){return this.request("POST",r.nodeBrokerSettle(this.nodePath(e)),t)}startBrokerCycle(e,t){return this.request("POST",r.nodeBrokerCycle(this.nodePath(e)),t)}async postBrokerIdle(e,t){await this.request("POST",r.nodeBrokerIdle(this.nodePath(e)),t)}completeBrokerPark(e,t){return this.request("POST",r.nodeBrokerParkComplete(this.nodePath(e)),t)}recordBrokerParkActivity(e,t){return this.request("POST",r.nodeBrokerParkActivity(this.nodePath(e)),t)}async recordBrokerTelemetry(e,t){await this.request("POST",r.nodeBrokerTelemetry(this.nodePath(e)),t)}claimNodeMail(e,t){return this.request("POST",r.nodeMailClaim(this.nodePath(e)),t)}acknowledgeNodeMail(e,t){return this.request("POST",r.nodeMailAcknowledge(this.nodePath(e)),t)}recordBrokerTurn(e,t){return this.request("POST",r.brokerTurn(this.nodePath(e)),t)}mutateBrokerProviderRetry(e,t){return this.request("POST",r.brokerProviderRetry(this.nodePath(e)),t)}mutateBrokerFault(e,t){return this.request("POST",r.brokerFault(this.nodePath(e)),t)}getBrokerRecovery(e,t){return this.request("GET",`${r.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(t)}`)}recordNodeFault(e,t){return this.request("POST",r.nodeFault(this.nodePath(e)),t)}clearNodeFault(e,t={}){const n=new URLSearchParams;t.link!==void 0&&n.set("link",t.link),t.preserve_episode!==void 0&&n.set("preserve_episode",String(t.preserve_episode));const s=n.size===0?"":`?${n.toString()}`;return this.request("DELETE",`${r.nodeFault(this.nodePath(e))}${s}`)}commitBrokerModel(e,t){return this.request("POST",r.nodeBrokerModel(this.nodePath(e)),t)}executionStart(e){return this.request("GET",r.executionStart(e))}gitCredential(e,t){return this.request("POST",r.environmentGitCredential(e),t)}postFeedback(e){return this.request("POST",r.feedback(),e)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",r.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,t){return this.request("POST",r.nodeBrokerGoal(this.nodePath(e)),t)}commitBrokerGeneratedName(e,t){return this.request("POST",r.nodeBrokerGeneratedName(this.nodePath(e)),t)}commitBrokerPersonaAck(e,t){return this.request("POST",r.nodeBrokerPersonaAck(this.nodePath(e)),t)}closeNode(e,t){return this.request("POST",r.nodeClose(this.nodePath(e)),t??{})}async markNodeRead(e){await this.request("POST",r.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",r.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",r.nodeDemote(this.nodePath(e)),{})}promoteNode(e,t){return this.request("POST",r.nodePromote(this.nodePath(e)),t)}yieldNode(e,t){return this.request("POST",r.nodeYield(this.nodePath(e)),t)}waitNode(e,t){return this.request("POST",r.nodeWait(this.nodePath(e)),t)}listKinds(){return this.request("GET",r.kinds())}patchConfig(e,t){return this.request("PATCH",r.nodeConfig(this.nodePath(e)),t,t.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",r.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,t){return this.request("POST",r.nodeWorktreeAbandon(this.nodePath(e)),t)}retryDelivery(e){return this.request("POST",r.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",r.quarantinedWorktrees())}showLimits(){return this.request("GET",r.limits())}setAppLimits(e,t){return this.request("PUT",r.limitsApp(e),t)}removeAppLimits(e,t){return this.request("DELETE",d(r.limitsApp(e),{fields:t.join(",")}))}listCharges(e={}){return this.request("GET",d(r.charges(),e))}listSpendLimits(){return this.request("GET",r.spendLimits())}setSpendLimit(e,t){return this.request("PUT",r.spendLimit(e),t)}removeSpendLimit(e){return this.request("DELETE",r.spendLimit(e))}listSpaces(){return this.request("GET",r.spaces())}subscribe(e,t){return this.request("POST",r.nodeSubscriptions(this.nodePath(e)),t)}listFocuses(){return this.request("GET",r.focuses())}focusOf(e){return this.request("GET",d(r.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",d(r.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",r.focuses(),e)}async setFocusPane(e,t){await this.request("PATCH",r.focus(e),t)}async closeFocus(e){await this.request("DELETE",r.focus(e))}async unsubscribe(e,t){await this.request("DELETE",r.nodeSubscription(this.nodePath(e),this.nodePath(t)))}armCron(e){return this.request("POST",r.crons(),e)}listCrons(e){return this.request("GET",d(r.crons(),e))}showCron(e,t){return this.request("GET",d(r.cron(this.cronPath(e)),t))}pauseCron(e,t){return this.request("POST",d(r.cronPause(this.cronPath(e)),t),{})}resumeCron(e,t){return this.request("POST",d(r.cronResume(this.cronPath(e)),t),{})}runCron(e,t){return this.request("POST",d(r.cronRun(this.cronPath(e)),t),{})}async cancelCron(e,t){await this.request("DELETE",d(r.cron(this.cronPath(e)),t))}pokeCrons(){return this.request("POST",r.cronsPoke(),{})}ensureAttach(e,t){return this.request("POST",r.nodeAttach(this.nodePath(e)),t??{},{timeout:$+this.timeoutMs})}getReports(e,t){return this.request("GET",d(r.nodeReports(this.nodePath(e)),t))}getTranscript(e,t){return this.request("GET",d(r.nodeTranscript(this.nodePath(e)),t))}getSnapshot(e){return this.request("GET",r.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",r.nodeSubject(this.nodePath(e)))}getNodeMessages(e,t){return this.request("GET",d(r.nodeMessages(this.nodePath(e)),t))}getSession(e){return this.request("GET",r.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",r.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",d(r.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",r.nodeContext(this.nodePath(e)))}peekFile(e,t,n){return this.request("GET",d(r.filePeek(),{path:e,encoding:t}),void 0,n)}writeFile(e,t,n,s){return this.request("POST",r.fileWrite(),{path:e,content:t,encoding:n},s)}listFiles(e,t,n){return this.request("GET",d(r.fileList(),{path:e,limit:t}),void 0,n)}runBash(e,t){return this.request("POST",r.bash(),e,t)}objects={read:a((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:a(e=>this.request("GET",d(r.objects(),e)),"list"),search:a(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:a((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:a((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:a((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:a(e=>this.request("POST",r.docs(),e),"write"),edit:a((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:a((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:a(e=>this.request("DELETE",r.doc(e)),"delete"),history:a((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:a((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={browserAccess:a(()=>this.request("GET",r.documentsBrowserAccess()),"browserAccess"),reconcilePackages:a(e=>this.request("POST",r.documentsReconcilePackages(),e),"reconcilePackages")};plugins={appToken:a(e=>this.request("GET",r.pluginAppToken(e)),"appToken"),callHeaders:a((e,t)=>this.request("POST",r.pluginCallHeaders(e),t),"callHeaders")};nodeDelivery(e,t){return this.request("POST",r.nodeDelivery(this.nodePath(e)),t)}deliveryDryRun(e){return this.request("POST",r.deliveryDryRun(),e)}recordBackgroundedJob(e,t,n){return this.request("POST",r.nodeJobBackground(this.nodePath(e),this.jobPath(t)),n)}ensureProfile(e,t){return this.request("PUT",r.profile(e),t??{})}createProfile(e){return this.request("POST",r.profiles(),e)}listProfiles(){return this.request("GET",r.profiles())}updateProfile(e,t){return this.request("PATCH",r.profile(e),t)}listAppEnv(){return this.request("GET",r.appEnv())}setAppEnv(e,t){return this.request("PUT",r.appEnvVar(e),{value:t})}removeAppEnv(e){return this.request("DELETE",r.appEnvVar(e))}listProfileEnv(e){return this.request("GET",r.profileEnv(e))}setProfileEnv(e,t,n){return this.request("PUT",r.profileEnvVar(e,t),{value:n})}removeProfileEnv(e,t){return this.request("DELETE",r.profileEnvVar(e,t))}getProfileEnvironment(e){return this.request("GET",r.profileEnvironment(e))}setProfileEnvironment(e,t){return this.request("PUT",r.profileEnvironment(e),t)}getProfile(e){return this.request("GET",r.profile(e))}pauseProfile(e){return this.request("POST",r.profilePause(e),{})}resumeProfile(e){return this.request("POST",r.profileResume(e),{})}updateProfileMetadata(e,t){return this.request("PATCH",r.profileMetadata(e),t)}deleteProfile(e,t){return this.request("DELETE",r.profile(e),t)}getSettings(){return this.request("GET",r.settings())}putSettings(e){return this.request("PUT",r.settings(),e)}listModelAuth(){return this.request("GET",r.modelAuths())}getModelAuthReadiness(e){return this.request("GET",d(r.modelAuthReadiness(),e))}installCredential(e,t){return this.request("PUT",r.modelAuth(e),t)}removeCredential(e){return this.request("DELETE",r.modelAuth(e))}patchModelAuthAccount(e,t,n){return this.request("PATCH",r.modelAuthAccount(e,t),n)}removeModelAuthAccount(e,t){return this.request("DELETE",r.modelAuthAccount(e,t))}startModelAuth(e){return this.request("POST",r.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,t){return this.request("POST",r.modelAuthFlowComplete(e),t,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",r.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,t){return this.request("GET",d(r.modelAuthFlow(e),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",r.humanReviews(),e)}listReviews(e){return this.request("GET",d(r.humanReviews(),e))}getReview(e){return this.request("GET",r.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",r.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,t={}){return this.request("POST",r.humanReviewCancel(this.reviewPath(e)),t)}getReviewDocumentBase(e){return this.request("GET",r.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("POST",r.humanReviewComments(n),t)}listReviewComments(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("GET",d(r.humanReviewComments(n),t))}readReviewCommentEvents(e,t){return this.request("GET",d(r.humanReviewCommentEvents(this.reviewPath(e)),t))}getReviewComment(e){return this.request("GET",r.humanComment(this.commentPath(e)))}editReviewComment(e,t){return this.request("POST",r.humanCommentEdit(this.commentPath(e)),t)}resolveReviewComment(e,t={}){return this.request("POST",r.humanCommentResolve(this.commentPath(e)),t)}reopenReviewComment(e,t={}){return this.request("POST",r.humanCommentReopen(this.commentPath(e)),t)}deleteReviewComment(e,t={}){return this.request("POST",r.humanCommentDelete(this.commentPath(e)),t)}forkReviewComment(e){return this.request("POST",r.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(e={}){return this.request("GET",e.includePages===!0?d(r.humanInbox(),{include:"page"}):r.humanInbox())}getHumanInboxPage(e){return this.request("GET",r.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,t={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e,state:t.state}))}respondHumanInboxPage(e,t){return this.request("POST",r.humanInboxRespond(this.ticketId(e)),t)}postInboxProgress(e,t){return this.request("POST",r.humanInboxProgress(this.ticketId(e)),{responses:t})}getInboxResponse(e){return this.request("GET",r.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,t){return this.request("POST",r.humanInboxCancel(this.ticketId(e)),t??{})}createHumanRequest(e){return this.request("POST",r.humanRequests(),e)}listPageComponents(){return this.request("GET",r.humanComponents())}getHumanRequest(e){return this.request("GET",r.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,t){return this.request("POST",r.humanRequestReplace(this.requestPath(e)),t)}respondHumanRequest(e,t){return this.request("POST",r.humanRequestRespond(this.requestPath(e)),t)}dismissHumanRequest(e,t={}){return this.request("POST",r.humanRequestDismiss(this.requestPath(e)),t)}cancelHumanRequest(e,t={}){return this.request("POST",r.humanRequestCancel(this.requestPath(e)),t)}resolvePageFeedbackComment(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(t)}`);return this.request("POST",r.humanInboxFeedbackResolve(this.ticketId(e),t),{node_id:n})}async dashboard(e){const t=e?.under!==void 0?{under:e.under}:void 0,[n,s]=await Promise.all([this.listNodes(t),this.status()]);return{nodes:n,counts:s.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",r.canvasAttention())}attentionCounts(e){const t={node_ids:e};return this.request("POST",r.canvasAttentionCounts(),t)}historySearch(e){return this.request("POST",r.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",r.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",d(r.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",r.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",r.canvasSnapshot())}analytics(e){return this.request("GET",d(r.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,t){await this.request("POST",r.nodeMemoryReads(this.nodePath(e)),t)}liveRoots(e={}){return this.request("GET",d(r.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",r.canvasView(e))}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await w(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(e){return this.request("GET",e===void 0?r.canvasGraph():`${r.canvasGraph()}?root=${encodeURIComponent(e)}`)}prune(e){return this.request("POST",r.canvasPrune(),e)}async request(e,t,n,s){try{const o=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,o);return await w(u,o?.deadlineAt)}catch(o){throw Q(e,q(o,s?.signal))}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw q(s,n?.signal)}}async send(e,t,n,s={}){const o=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=o.maxRetries??this.maxRetries,l=Math.min(o.deadlineAt??1/0,Date.now()+W);for(let m=0;;m++){let h;try{h=await this.transport(e,t,n,o)}catch(P){if(this.isColdSocketError(P)||this.isInterruptedSocketError(P)){const T=this.availabilityFailure?.();if(T!==void 0)throw T}if(this.isColdSocketError(P))try{await this.handleColdSocket(P,o.deadlineAt),h=await this.transport(e,t,n,o)}catch(T){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!A(T,o.signal)?S(o.deadlineAt):q(T,o.signal)}else{if(this.isInterruptedSocketError(P)&&this.localSocketTransport&&(!u||m<c))return await this.rideOutInterruptedRequest(e,t,n,o);if(u&&m<c&&!A(P,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(P))){await R(G(m+1),o);continue}else throw q(P,o.signal)}}if(V(e)&&c>0&&h.status===503&&await z(h,o.deadlineAt)){const P=Math.max(250,(D(h)??0)*1e3)+Math.random()*250;if(Date.now()+P>=l)return h;await g(h,o.deadlineAt),await R(P,{signal:o.signal});continue}if(u&&m<c&&K(h.status)){await g(h,o.deadlineAt),await R(G(m+1),o,D(h));continue}return h}}resolveBudget(e){const{budgetMs:t,deadlineAt:n,...s}=e;if(t===void 0&&n===void 0)return s;if(t!==void 0&&(!Number.isFinite(t)||t<=0||t>v))throw new RangeError(`budgetMs must be a positive finite number of at most ${v}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>v))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${v} ms from now`);return{...s,deadlineAt:Math.min(n??1/0,t===void 0?1/0:Date.now()+t)}}async awaitWithinBudget(e,t){if(t===void 0)return e;const n=t-Date.now();if(n<=0)throw p(t);let s;try{return await Promise.race([e,new Promise((o,u)=>{s=setTimeout(()=>u(p(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const o=this.resolveBudget(s);try{return await w(await this.transport(e,t,n,o))}catch(u){throw q(u,o.signal)}}nodePath(e){if(!b(e))throw new f(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!L(e))throw new f(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!F(e))throw new f(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!b(e))throw new f(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!b(e))throw new f(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new f(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const o=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(p(s.deadlineAt));const u=n===void 0?void 0:JSON.stringify(n),c={accept:"application/json",...this.headers,...s.headers};u!==void 0&&(c["content-type"]="application/json");const l=s.timeout??this.timeoutMs,m=o===void 0?l:l>0?Math.min(l,o):o,h=new AbortController,P=o!==void 0&&(l<=0||o<=l),T=m>0?setTimeout(()=>h.abort(P?p(s.deadlineAt):new DOMException("request timed out","TimeoutError")),m):void 0,E=s.signal,k=a(()=>h.abort(E?.reason),"onExternalAbort");E!==void 0&&(E.aborted?h.abort(E.reason):E.addEventListener("abort",k,{once:!0}));const C=a(()=>{T!==void 0&&clearTimeout(T),E?.removeEventListener("abort",k)},"finish");return Z(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:h.signal}),h.signal).then(y=>(B(y.headers.get("server-timing")),this.retainRequestLifetime(y,C,()=>h.signal.aborted?h.signal.reason:void 0)),y=>{throw C(),y})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let o=!1;const u=a(()=>{o||(o=!0,t())},"close"),c=new ReadableStream({async pull(l){try{const{done:m,value:h}=await s.read();m?(u(),l.close()):l.enqueue(h)}catch(m){u(),l.error(n()??m)}},async cancel(l){u(),await s.cancel(l)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=O(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=O(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(o){throw q(o,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new f(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,t,n,s)}catch(o){throw q(o,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw p(t);let s,o;try{await J({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:a(u=>u!==s&&u!==o,"retry"),probe:a(async u=>{const c=this.availabilityFailure?.();if(c!==void 0)throw o=c,c;const l=this.coldStartFailure?.();if(l!==void 0)throw s=new f(503,"daemon_unavailable",`crtrd failed to start: ${l}`),s;const m=await this.transport("GET",r.healthz(),void 0,{timeout:u});if(m.status>=200&&m.status<300){await g(m);return}const h=await m.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new f(m.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${m.status}: ${h.slice(0,500)}`)},"probe")})}catch(u){throw u===s&&(this.startupFailureReported=!0),u}}async handleColdSocket(e,t){const n=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;n&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),t));try{await this.awaitAvailability(e,t)}catch(s){if(n&&!this.startupFailureReported){const o=X(this.coldStartDiagnostic);if(o!==void 0){const u=q(s);throw new f(u.status,u.code,`${u.message}
|
|
3
3
|
${o}`)}}throw s}}}function d(i,e){if(e===void 0)return i;const t=new URLSearchParams;for(const[s,o]of Object.entries(e))o!=null&&t.set(s,String(o));const n=t.toString();return n===""?i:`${i}?${n}`}a(d,"withQuery");async function w(i,e){const t=i.status>=200&&i.status<300,n=(await _(i,e)).trim();let s;if(n!=="")try{s=JSON.parse(n)}catch{if(t)return;throw new f(i.status,"invalid_response",n.slice(0,500),void 0,i.headers)}if(t)return s;throw x(s)?new f(i.status,s.error.code,s.error.message,s.error.details,i.headers,s.error):new f(i.status,"internal",`request failed with status ${i.status}`,void 0,i.headers)}a(w,"parse");const W=6e4;function V(i){return i==="GET"||i==="HEAD"}a(V,"isRead");async function z(i,e){try{if(Number(i.headers.get("content-length")??0)>8192)return!1;const t=await _(i.clone(),Math.min(e??1/0,Date.now()+5e3)),n=JSON.parse(t).error;return n?.origin==="router"&&n.details?.forwarded===!1&&(n.details.runtime_state==="creating"||n.details.runtime_state==="recovering")}catch{return!1}}a(z,"isRefusedBeforeForwarding");function K(i){return i===429||i>=500}a(K,"isRetryableStatus");async function g(i,e){const t=(async()=>{try{await i.body?.cancel()}catch{}})();if(e===void 0)return t;let n;try{await Promise.race([t,new Promise(s=>{n=setTimeout(s,Math.max(0,e-Date.now()))})])}finally{n!==void 0&&clearTimeout(n)}}a(g,"drainResponseBody");async function _(i,e){if(e===void 0)return i.text();const t=e-Date.now(),n=i.text();if(n.catch(()=>{}),t<=0)throw i.body?.cancel().catch(()=>{}),S(e);let s;try{return await Promise.race([n,new Promise((o,u)=>{s=setTimeout(()=>{i.body?.cancel().catch(()=>{}),u(S(e))},t)})])}finally{s!==void 0&&clearTimeout(s)}}a(_,"readTextWithin");function G(i){return Math.min(2e3,250*2**(i-1))}a(G,"retryDelayMs");function O(i){if(typeof i!="object"||i===null)return;const e=i.code;if(typeof e=="string")return e;const t=i.cause;if(typeof t=="object"&&t!==null){const n=t.code;if(typeof n=="string")return n}}a(O,"transportErrorCode");function A(i,e){return e?.aborted?!0:i instanceof DOMException&&(i.name==="AbortError"||i.name==="TimeoutError")}a(A,"isAbortError");function q(i,e){if(e?.aborted)return new f(0,"request_aborted","request aborted by caller signal");if(i instanceof f)return i;if(i instanceof DOMException&&i.name==="TimeoutError")return new f(504,"request_timeout",`crtrd request timed out: ${i.message}`);if(i instanceof DOMException&&i.name==="AbortError")return new f(0,"request_aborted","request aborted by caller signal");const t=O(i),n=i instanceof Error?i.message:String(i);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"?new f(503,"daemon_unavailable",`crtrd is not reachable: ${n}`):t==="ETIMEDOUT"?new f(504,"request_timeout",`crtrd request timed out: ${n}`):new f(503,"transport_error",n)}a(q,"toTransportApiError");function Q(i,e){return i==="GET"||i==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new f(e.status,e.code,`${e.message}; the ${i} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}a(Q,"withUnknownOutcome");function D(i){const e=Number(i.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}a(D,"retryAfterHeaderS");async function R(i,e,t,n){const{deadlineAt:s,signal:o}=e;if(o?.aborted)throw new f(0,"request_aborted","request aborted by caller signal");const u=s!==void 0&&t!==void 0?t*1e3:void 0,c=Math.max(i,u??0);if(s!==void 0&&Date.now()+c>=s){const l=S(s,u!==void 0&&u>=i?"retry_after":"elapsed",u===void 0?void 0:t);throw n!==void 0&&Object.defineProperty(l,"cause",{value:n,configurable:!0,writable:!0}),l}if(o===void 0)return M(c);await new Promise((l,m)=>{const h=a(()=>{clearTimeout(P),o.removeEventListener("abort",h),m(new f(0,"request_aborted","request aborted by caller signal"))},"onAbort"),P=setTimeout(()=>{o.removeEventListener("abort",h),l()},c);o.addEventListener("abort",h,{once:!0})})}a(R,"sleepWithin");function Z(i,e){return new Promise((t,n)=>{const s=a(()=>n(e.reason),"onAbort");e.aborted?s():e.addEventListener("abort",s,{once:!0}),i.then(o=>{e.removeEventListener("abort",s),e.aborted?o.body?.cancel().catch(()=>{}):t(o)},o=>{e.removeEventListener("abort",s),n(o)})})}a(Z,"abortable");function M(i){return new Promise(e=>setTimeout(e,i))}a(M,"sleepMs");function X(i){if(i!==void 0)try{return i()}catch{return}}a(X,"safeColdStartDiagnostic");export{oe as CrtrClient,v as MAX_TIMER_MS,S as deadlineExceeded,X as safeColdStartDiagnostic,R as sleepWithin,J as waitForDaemonAvailability};
|
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.85";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.85",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
|
|
@@ -110,7 +110,7 @@ export interface SpendLimitRemovedDTO {
|
|
|
110
110
|
removed: true;
|
|
111
111
|
}
|
|
112
112
|
/** Why a call was refused for payment. `reason` is what an app branches on; never the message text. */
|
|
113
|
-
export declare const PAYMENT_REFUSAL_REASONS: readonly ["trial_ended", "card_required", "card_limit", "nothing_left", "app_limit", "team_limit", "app_unpaid"];
|
|
113
|
+
export declare const PAYMENT_REFUSAL_REASONS: readonly ["trial_ended", "card_required", "card_limit", "nothing_left", "app_limit", "team_limit", "app_unpaid", "account_held"];
|
|
114
114
|
export type PaymentRefusalReasonDTO = typeof PAYMENT_REFUSAL_REASONS[number];
|
|
115
115
|
/** The structured refusal carried at `error.details.payment` of a `402 payment_refused`, a `402 cap_exhausted` (`app_limit`) and a `429 all_routes_exhausted` (`nothing_left`). */
|
|
116
116
|
export interface PaymentRefusalDTO {
|
package/dist/api/dto/charges.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const i=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid"];export{i as PAYMENT_REFUSAL_REASONS};
|
|
1
|
+
const i=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid","account_held"];export{i as PAYMENT_REFUSAL_REASONS};
|
package/dist/api/dto/inbox.d.ts
CHANGED
|
@@ -63,6 +63,8 @@ export interface PageTicketSummaryDTO {
|
|
|
63
63
|
state: 'pending' | 'resolved' | 'canceled' | 'passive';
|
|
64
64
|
/** Present only on resolved history entries; the stored one-line answer digest. */
|
|
65
65
|
answer_digest?: string;
|
|
66
|
+
/** The full page, present only when the list was read with `?include=page` and the page could be read. */
|
|
67
|
+
page?: InboxPageDTO;
|
|
66
68
|
}
|
|
67
69
|
export type InboxTicketSummaryDTO = PageTicketSummaryDTO | ReviewTicketSummaryDTO;
|
|
68
70
|
export interface InboxListDTO {
|
package/dist/build-root.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var J=Object.defineProperty;var n=(e,t)=>J(e,"name",{value:t,configurable:!0});import{defineBranch as W,defineRoot as b,GLOBAL_TOKENS as k}from"./core/command.js";import{createCoreHookCatalog as E}from"./core/command-hooks/catalog.js";import{composeCoreHooks as N}from"./core/command-hooks/compose.js";import{mark as
|
|
1
|
+
var J=Object.defineProperty;var n=(e,t)=>J(e,"name",{value:t,configurable:!0});import{defineBranch as W,defineRoot as b,GLOBAL_TOKENS as k}from"./core/command.js";import{createCoreHookCatalog as E}from"./core/command-hooks/catalog.js";import{composeCoreHooks as N}from"./core/command-hooks/compose.js";import{mark as g}from"./core/timing.js";import{ApiError as $}from"./api/errors.js";import{CrtrError as K}from"./core/errors.js";import{envNodeId as X,envScopes as Y,isSandboxedNode as x,providerProjectionOverBrokerRelay as Q,scopeAllowed as V}from"./shared/env.js";const P="crtr: agentic runtime.",O=[{name:"--json",desc:"stdout as the leaf's declared outputs in raw JSON instead of prose \u2014 for scripts (a cron's bash, external tooling) that must branch on canvas state; prose stays the contract for what you read yourself."}],R=Object.assign(Object.create(null),{doc:n(async()=>(await import("./commands/doc.js")).registerDoc(),"doc"),"custom-object":n(async()=>(await import("./commands/custom-object.js")).registerCustomObject(),"custom-object"),profile:n(async()=>(await import("./commands/profile.js")).registerProfile(),"profile"),pkg:n(async()=>(await import("./commands/pkg.js")).registerPkg(),"pkg"),human:n(async()=>(await import("./commands/human.js")).registerHuman(),"human"),sys:n(async()=>(await import("./commands/sys.js")).registerSys(),"sys"),node:n(async()=>(await import("./commands/node.js")).registerNode(),"node"),push:n(async()=>(await import("./commands/push.js")).registerPush(),"push"),cron:n(async()=>(await import("./commands/cron.js")).registerCron(),"cron"),canvas:n(async()=>(await import("./commands/canvas.js")).registerCanvas(),"canvas"),surface:n(async()=>(await import("./commands/surface.js")).registerSurface(),"surface")}),m=Object.freeze(Object.keys(R)),Z={human:["crtr:act"],cron:["crtr:schedule"],doc:["crtr:memory:read:user","crtr:memory:rw:user"]};function T(e){const t=Y();return t===null?e:e.filter(r=>{const o=Z[r.name];return o===void 0||o.some(s=>V(t,s))||r.name==="doc"&&process.env.CRTR_GRANTEE?.startsWith("app:")===!0})}n(T,"allowedSubtrees");const A=new Map;function _(e){let t=A.get(e);return t===void 0&&(t=R[e](),A.set(e,t)),t}n(_,"loadSubtree");function v(e){return Promise.all(m.filter(t=>e.has(t)).map(_))}n(v,"loadCoreSubtreesNamed");function S(){return v(new Set(m))}n(S,"loadCoreSubtrees");function j(e){const t=new Set;for(const r of e){const o=r.split(" ")[0];m.includes(o)&&t.add(o)}return t}n(j,"subtreesNamedBy");let L;function he(){return g("cli.hooks.catalog"),L??=S().then(E),L}n(he,"coreHookCatalog");function M(){let e;return()=>(e??=(async()=>{const{compileHookRegistry:t,declaredCommandHookTargets:r,effectiveHookPlugins:o}=await import("./core/command-hooks/discovery.js"),s=o(),a=x()&&X()!==void 0?await(await import("./core/command-hooks/transport/plan.js")).remoteHookPlan(process.cwd()):[];if(g("cli.hooks.effective_plugins",{count:s.length+a.length}),s.length===0&&a.length===0)return g("cli.hooks.empty_registry"),t(E([]),[]);const u=x()?s.filter(l=>l.scope==="project"):s,i=j([...r(u),...a.map(l=>l.target)]);return g("cli.hooks.catalog",{subtrees:[...i].join(",")}),t(E(await v(i)),u,a)})(),e)}n(M,"hookRegistryLoader");function y(e){const t=new Set,r=n((o,s)=>{if(!(o.kind==="branch"&&o.passthrough!==void 0)&&(t.add(s),o.kind==="branch"))for(const a of o.children)r(a,`${s} ${a.name}`)},"visit");for(const o of e)r(o,o.name);return t}n(y,"commandPathsFor");async function we(){return y(await S())}n(we,"coreCommandPaths");async function ye(e){return y(await v(j(e)))}n(ye,"coreCommandPathsCovering");function ee(e){const t=[],r=n((o,s)=>{o.extensible===!0&&t.push(s);for(const a of o.children)a.kind==="branch"&&r(a,[...s,a.name])},"visit");for(const o of e)r(o,[o.name]);return t}n(ee,"extensibleBranchPaths");const te=Object.freeze(["human","sys tutorial"]);async function H(){return new Set(te)}n(H,"extensibleCoreBranches");async function ve(){return new Set(ee(await S()).map(e=>e.join(" ")))}n(ve,"declaredExtensibleCoreBranches");function ne(e,t){const{listing:r,...o}=e.help;return W({name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:o,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,children:t})}n(ne,"rebuildBranch");async function I(e,t,r){if(t.size===0)return e;const[{buildExternalCommandSnapshot:o},{composeCoreBranchMounts:s}]=await Promise.all([import("./core/command-plugins/discovery.js"),import("./core/command-plugins/compose.js")]),a=o(new Set(m),void 0,void 0,r,t),u=n((i,l)=>{let h=!1;const f=i.children.map(d=>{if(d.kind!=="branch")return d;const p=u(d,[...l,d.name]);return p!==d&&(h=!0),p}),w=i.extensible===!0?s(a.coreMounts,l):[];return h||w.length>0?ne(i,[...f,...w]):i},"composeBranch");return e.map(i=>u(i,[i.name]))}n(I,"composeCorePluginMounts");async function oe(e,t){const{validateEffectiveCommandPlugins:r}=await import("./core/command-plugins/discovery.js"),s=r(new Set(m),void 0,void 0,void 0,t).flatMap(u=>u.manifest===void 0?[]:[u.manifest]).filter(u=>u.coreMounts.some(i=>i.parent[0]===e));if(s.length===0)return null;const a=j(s.flatMap(u=>[...u.coreMounts.map(i=>i.parent.join(" ")),...Object.keys(u.helpAddenda??{})]));return a.add(e),y(await v(a))}n(oe,"dispatchCommandPaths");function C(e,t){const r=e.slice(2).filter(o=>!k.has(o));return r[0]==="sys"&&r[1]===t}n(C,"isSysInvocation");const re=[["surface"],["sys"],["pkg"],["profile","default"],["canvas","chord"],["canvas","config"],["canvas","use"],["canvas","browse"],["canvas","issue"]],se=[["sys","feedback"],["pkg","plugin"],["pkg","market"]];function D(e,t){return t.every((r,o)=>e[o]===r)}n(D,"startsWithPath");function Se(e){const t=e.slice(2).filter(o=>!k.has(o));if(se.some(o=>D(t,o)))return null;const r=re.find(o=>D(t,o));return r===void 0?null:r.join(" ")}n(Se,"personOnlyInvocation");function Ce(e){return C(e,"daemon")}n(Ce,"isDaemonControlInvocation");function be(e){const t=e.slice(2).filter(r=>!k.has(r));return t[0]==="pkg"&&(t[1]==="plugin"||t[1]==="market")}n(be,"isPkgInstallInvocation");function ke(e){return C(e,"signin")||C(e,"signout")}n(ke,"isSignInInvocation");function Ee(e){return C(e,"join")}n(Ee,"isJoinInvocation");async function xe(){const{registerDaemonControlSys:e}=await import("./commands/sys/daemon.js");return b({tagline:P,globals:O,subtrees:[e()]})}n(xe,"resolveDaemonControlRoot");async function Pe(e){return(e!==void 0?await ae(e):null)??ie()}n(Pe,"resolveRoot");async function ae(e){if(R[e]===void 0)return null;const t=await _(e),r=await H(),o=[...r].some(a=>a.split(" ")[0]===e)?await oe(e,r):null,s=T(o===null?[t]:await I([t],r,o));return s.length>0?b({tagline:P,globals:O,subtrees:N(s,M())}):null}n(ae,"resolveCoreRoot");async function ie(){const e=await S(),[{buildExternalCommandSnapshot:t},{composeExternalSubtrees:r,composeSandboxProviderSubtrees:o},{qualifiedTopLevelCommandName:s}]=await Promise.all([import("./core/command-plugins/discovery.js"),import("./core/command-plugins/compose.js"),import("./core/command-manifests/registry.js")]),a=await H(),u=await I(e,a,y(e)),i=t(new Set(m),void 0,void 0,y(e),a);let l=r(i);const h=(await import("./daemon/machine-link/config.js")).readMachineConfig()!==void 0;let f;if(x()||Q()||h){const{cliClient:d}=await import("./commands/api-client.js");g("cli.providers.request");let p=[];try{p=(await d().request("GET","/v1/providers/tools")).providers}catch(c){if(!h||!(c instanceof $||c instanceof K))throw c;f=c}g("cli.providers.fetched",{providers:p.length});const B=o(p,new Set(m)),G=new Set(B.map(c=>c.name)),U=new Map(p.map(c=>[c.provider,new Set(c.groups.flatMap(z=>z.leaves.map(F=>F.tool)))])),q=n(async c=>U.get(c)??new Set,"fromCatalog");l=[...B,...r({...i,contributions:i.contributions.map(c=>G.has(c.node.name)?{...c,node:{...c.node,name:s(c.contributor,c.node.name)}}:c)},f===void 0?q:void 0)]}const w=b({tagline:P,globals:O,subtrees:[...N(T(u),M()),...l]});return f===void 0?w:{...w,providerCatalogFailure:f}}n(ie,"buildRoot");export{te as EXTENSIBLE_CORE_BRANCHES,m as SUBTREE_NAMES,ie as buildRoot,we as coreCommandPaths,ye as coreCommandPathsCovering,he as coreHookCatalog,ve as declaredExtensibleCoreBranches,H as extensibleCoreBranches,Ce as isDaemonControlInvocation,Ee as isJoinInvocation,be as isPkgInstallInvocation,ke as isSignInInvocation,Se as personOnlyInvocation,ae as resolveCoreRoot,xe as resolveDaemonControlRoot,Pe as resolveRoot};
|
|
@@ -7,7 +7,7 @@ when-and-why-to-read: When deciding how an application should host or reconnect
|
|
|
7
7
|
|
|
8
8
|
# Why a daemon
|
|
9
9
|
|
|
10
|
-
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd
|
|
10
|
+
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd` (in production the Northlight control plane at `api-fleet.northlight.ai`), owns the durable canvas and starts, stops, and recovers brokers. This separation lets a node continue after the terminal that created or displayed it has gone away.
|
|
11
11
|
|
|
12
12
|
```mermaid
|
|
13
13
|
flowchart LR
|
|
@@ -24,7 +24,7 @@ The broker has one job: host a node’s agent session. The daemon has the broade
|
|
|
24
24
|
|
|
25
25
|
This is why a process crash is recoverable rather than an automatic loss of work. The daemon retains the node row, session information, context directory, documents, waits, and inbox state, then applies recovery to the broker execution. A later wake or explicit revival can continue the node’s saved conversation. The application should create nodes through the daemon (`crtr node new` or `CrtrClient` from `@north-light/api`), not start an LLM process itself, because the daemon is the component that keeps the engine and durable canvas state coordinated.
|
|
26
26
|
|
|
27
|
-
The costs are real.
|
|
27
|
+
The costs are real. The runtime must be reachable, and canvas state has one home — the Northlight control plane — instead of being scattered across terminals and application processes. Clients reach it over HTTPS with a bearer token. A network interruption can therefore fail a mutation loudly rather than encouraging a client to replay it and risk doing the action twice.
|
|
28
28
|
|
|
29
29
|
Those costs buy a simpler model: one state owner, one broker launcher, and clients that can reconnect. A CLI command, an SDK application, and a terminal viewer all use the same API for canvas state. They can come and go without creating competing writers or losing the graph that explains what each agent is doing.
|
|
30
30
|
|
|
@@ -9,7 +9,7 @@ when-and-why-to-read: When you need SDK overview, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
The ESM-only client an application installs to start runs on a person's runtime, read their results, and manage what the app owns there. Apps that sign people in with Northlight are documented on the SDK docs site, which starts at [Quick setup](https://sdk.docs.northlight.ai/docs/quickstart).
|
|
11
11
|
|
|
12
|
-
`new Crouter(
|
|
12
|
+
`new Crouter({ baseURL, token })` talks to the runtime's HTTP listener with a bearer token. On either, the client offers the app routes (`runs`, `uploads`, `docs`, `memory`, …) plus the few owner calls an app setup needs: `models.credentials.install`, `spendLimits` and `customObjects`. crtrd stays the sole owner of canvas state.
|
|
13
13
|
|
|
14
14
|
## Driving nodes, bash, crons or the human inbox
|
|
15
15
|
|
|
@@ -27,11 +27,12 @@ const node = await crtr.createNode({ prompt: 'List the top-level directories her
|
|
|
27
27
|
|
|
28
28
|
| Page | Covers |
|
|
29
29
|
|---|---|
|
|
30
|
-
| [[crouter-sdk/getting-started]] | Install, `new Crouter()` on
|
|
30
|
+
| [[crouter-sdk/getting-started]] | Install, `new Crouter()` on a signed-in machine's socket, `CRTRD_TOKEN` for a browser or remote app, Chrome's local-network prompt |
|
|
31
31
|
| [[crouter-sdk/client]] | Every constructor option and its environment-variable fallback; per-request options |
|
|
32
|
+
| [[crouter-sdk/sourcing]] | `sourcing.read`: Mac first, then hosted search; the route table, the routing rule, `SourcingUnavailableError`, `SOURCING_RUN_RULE` |
|
|
32
33
|
| [[crouter-sdk/resources]] | Every namespace with its routes, and the `client.request()` escape hatch |
|
|
33
34
|
| [[crouter-sdk/errors]] | The daemon's scoped-token and wire errors, and identifier validation |
|
|
34
|
-
| [[crouter-sdk/docker]] |
|
|
35
|
+
| [[crouter-sdk/docker]] | Northlight-internal: `@north-light/env-docker`, the CI image helper used by pr-review |
|
|
35
36
|
| [Release notes](https://sdk.docs.northlight.ai/docs/release-notes) | Behavior changes an existing app must act on, newest first |
|
|
36
37
|
|
|
37
38
|
## Where the agents read this
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
kind: knowledge
|
|
3
3
|
when-and-why-to-read: When you need Client construction, this knowledge should
|
|
4
|
-
be read because Configure
|
|
4
|
+
be read because Configure the HTTP connection to the Northlight runtime,
|
|
5
5
|
authentication, and request options.
|
|
6
6
|
---
|
|
7
7
|
|
|
@@ -10,9 +10,7 @@ when-and-why-to-read: When you need Client construction, this knowledge should
|
|
|
10
10
|
```ts
|
|
11
11
|
import Crouter from '@north-light/sdk';
|
|
12
12
|
|
|
13
|
-
const
|
|
14
|
-
const remoteClient = new Crouter({ baseURL: 'http://localhost:8787', token: 'token' }); // TCP with a bearer token
|
|
15
|
-
const customSocketClient = new Crouter({ socketPath: '/custom/path/crtrd.sock' }); // an explicit socket
|
|
13
|
+
const client = new Crouter({ baseURL: process.env.CRTR_BASE_URL, token: process.env.CRTRD_TOKEN }); // HTTP with a bearer token
|
|
16
14
|
```
|
|
17
15
|
|
|
18
16
|
`Crouter` is the default export and the only class an application constructs. `CrtrClient` from `@north-light/api` is an implementation detail and is not re-exported.
|
|
@@ -26,14 +24,14 @@ An app that signs people in with Northlight uses `OAuth2Client` and `oauth.clien
|
|
|
26
24
|
| Option | Type | Default | Meaning |
|
|
27
25
|
|---|---|---|---|
|
|
28
26
|
| `baseURL` | `string` | `CRTR_BASE_URL`, else unset | `http(s)://host:port` of a daemon TCP listener. |
|
|
29
|
-
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket. Node only; throws in a browser. |
|
|
27
|
+
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket of a signed-in machine's own daemon. Node only; throws in a browser. |
|
|
30
28
|
| `token` | `string` | `CRTRD_TOKEN` | Sent as `Authorization: Bearer <token>`. The token the daemon was started with (`CRTRD_TOKEN`); a scoped token's ceiling is enforced per request (see [[crouter-sdk/getting-started]]). Ignored by a unix-socket daemon, which authenticates by filesystem permission. |
|
|
31
29
|
| `timeout` | `number` (ms) | `30_000` | Per-request wall clock. Does not apply to a stream. |
|
|
32
30
|
| `maxRetries` | `number` | `2` | Transient-failure retries. Never applied to `POST` or `PATCH` — see [[crouter-sdk/errors]]. |
|
|
33
31
|
| `defaultHeaders` | `Record<string, string>` | `{}` | Merged into every request. |
|
|
34
32
|
| `headers` | `Record<string, string>` | unset | Merged after `defaultHeaders`; a matching name wins unless `token` is set, in which case the generated `Authorization` header wins at construction. |
|
|
35
33
|
| `fetch` | `typeof fetch` | global `fetch`, or the socket implementation when `socketPath` is used | Transport override, for proxies and instrumentation. |
|
|
36
|
-
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` |
|
|
34
|
+
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` | For a signed-in machine's own daemon socket: on a cold socket, run `crtr sys daemon start` and retry once. Node only. |
|
|
37
35
|
|
|
38
36
|
### Environment-variable fallbacks
|
|
39
37
|
|
|
@@ -56,7 +54,7 @@ There is one request path. The client issues every request through the Web `fetc
|
|
|
56
54
|
|
|
57
55
|
## Autostart
|
|
58
56
|
|
|
59
|
-
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
57
|
+
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
60
58
|
|
|
61
59
|
Autostart is Node-only and applies only to the socket transport. A `baseURL` client cannot start a daemon it may not even share a machine with, so `autostart` defaults to `false` there; setting it to `true` on a `baseURL` client throws `CrouterError` (`autostart is only valid for the local socket transport`).
|
|
62
60
|
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
---
|
|
2
2
|
kind: knowledge
|
|
3
3
|
when-and-why-to-read: When you need Docker environment, this knowledge should be
|
|
4
|
-
read because
|
|
5
|
-
|
|
4
|
+
read because Northlight-internal helper that runs the crtrd CI image for the
|
|
5
|
+
pr-review workflow.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Docker environment
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
`@north-light/env-docker` runs a crouter daemon in a container and tells you how to reach it. It is a separate package because container lifecycle is real work the SDK does not otherwise do — and it **has no dependencies**, including on the SDK itself.
|
|
10
|
+
`@north-light/env-docker` is Northlight-internal: `Northlight-Systems/shared`'s pr-review workflow uses it to run the `crtrd` CI image (`ghcr.io/northlight-systems/crtrd`) in a container. It is not a way to run or self-host crtr; production is the Northlight control plane at `api-fleet.northlight.ai`. It has no dependencies, including on the SDK itself.
|
|
13
11
|
|
|
14
12
|
```bash
|
|
15
13
|
npm i @north-light/env-docker
|
|
@@ -21,11 +19,9 @@ npm i @north-light/env-docker
|
|
|
21
19
|
import { start } from '@north-light/env-docker';
|
|
22
20
|
import Crouter from '@north-light/sdk';
|
|
23
21
|
|
|
24
|
-
const env = await start({ volume: '
|
|
22
|
+
const env = await start({ volume: 'ci-home' });
|
|
25
23
|
const client = new Crouter(env.connection());
|
|
26
24
|
|
|
27
|
-
await client.runs.start({ prompt: 'Do the thing.' });
|
|
28
|
-
|
|
29
25
|
await env.stop();
|
|
30
26
|
```
|
|
31
27
|
|
|
@@ -65,6 +61,6 @@ const client = new Crouter(env.connection());
|
|
|
65
61
|
|
|
66
62
|
`connection()` is typed structurally — `{ baseURL: string; headers?: Record<string, string> }` — which is how the package stays dependency-free while producing something the SDK accepts directly.
|
|
67
63
|
|
|
68
|
-
## The volume
|
|
64
|
+
## The volume
|
|
69
65
|
|
|
70
|
-
The `volume` you pass is the container's canvas home
|
|
66
|
+
The `volume` you pass is the container's canvas home. Reuse it across `start` calls to keep state; use a fresh one to start from nothing. `start()` mounts an existing named volume unchanged.
|
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
---
|
|
2
2
|
kind: knowledge
|
|
3
3
|
when-and-why-to-read: When you need Getting started, this knowledge should be
|
|
4
|
-
read because Connect to
|
|
4
|
+
read because Connect to the Northlight runtime and start your first run with
|
|
5
5
|
the SDK.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Getting started
|
|
9
9
|
|
|
10
|
-
An agent run needs
|
|
10
|
+
An agent run needs the Northlight runtime (the control plane at `api-fleet.northlight.ai`) to run it. The SDK is a client for it — it never runs an agent itself — and reaches it over HTTP with a bearer token.
|
|
11
11
|
|
|
12
|
-
## 1.
|
|
12
|
+
## 1. Sign in
|
|
13
13
|
|
|
14
14
|
```bash
|
|
15
15
|
npm i -g @north-light/cli
|
|
16
|
+
crtr sys signin
|
|
16
17
|
```
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
The runtime is the Northlight cloud; you do not install or start a daemon. Signing in makes the Mac a machine where your agents' commands run.
|
|
19
20
|
|
|
20
21
|
## 2. Install the SDK in your application
|
|
21
22
|
|
|
@@ -27,22 +28,22 @@ One dependency. It re-exports every data type you need, so you do not also insta
|
|
|
27
28
|
|
|
28
29
|
`@latest` always works against production: a release reaches `latest` only once production serves its contract level. The `next` tag carries every release the moment it is published and may need a newer runtime than production runs (see [[crouter-sdk/errors]] for `RuntimeVersionError`). Keep the exact pin: the compatibility gate protects the wire, not the TypeScript API. To move it, check `npm view @north-light/sdk dist-tags` and read the [release notes](https://sdk.docs.northlight.ai/docs/release-notes) first.
|
|
29
30
|
|
|
30
|
-
## 3. Node
|
|
31
|
+
## 3. Node
|
|
31
32
|
|
|
32
|
-
Pass
|
|
33
|
+
Pass the runtime's URL and a bearer token.
|
|
33
34
|
|
|
34
35
|
```ts
|
|
35
36
|
import Crouter from '@north-light/sdk';
|
|
36
37
|
|
|
37
|
-
const client = new Crouter();
|
|
38
|
+
const client = new Crouter({ baseURL: process.env.CRTR_BASE_URL, token: process.env.CRTRD_TOKEN });
|
|
38
39
|
const { profiles } = await client.profiles.list();
|
|
39
40
|
```
|
|
40
41
|
|
|
41
|
-
The SDK covers the app routes (`runs`, `uploads`, `docs`, `memory`, …). To create nodes, run bash, arm crons or answer the human inbox on
|
|
42
|
+
The SDK covers the app routes (`runs`, `uploads`, `docs`, `memory`, …). To create nodes, run bash, arm crons or answer the human inbox on the runtime, use `CrtrClient` from `@north-light/api` (see the [[crouter-sdk/README]]).
|
|
42
43
|
|
|
43
44
|
## 4. A browser or a remote application
|
|
44
45
|
|
|
45
|
-
A
|
|
46
|
+
A browser page or a remote process reaches the runtime over HTTP with a bearer token. A computer signed in with `crtr sys signin` is a fleet machine: its crtr commands go to the Northlight control plane with the person's bearer.
|
|
46
47
|
|
|
47
48
|
```ts
|
|
48
49
|
import Crouter from '@north-light/sdk';
|
|
@@ -78,4 +79,3 @@ Registering an app, its key pair, the env file and going live are covered for ap
|
|
|
78
79
|
|
|
79
80
|
- Every constructor option and environment-variable fallback: [[crouter-sdk/client]]
|
|
80
81
|
- Every namespace and its routes: [[crouter-sdk/resources]]
|
|
81
|
-
- Running the daemon in a container instead: [[crouter-sdk/docker]]
|