@north-light/cli 0.3.781 → 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 +9 -19
- 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 +1 -1
- package/dist/builtin-memory/crouter-sdk/README.md +3 -2
- package/dist/builtin-memory/crouter-sdk/client.md +3 -3
- package/dist/builtin-memory/crouter-sdk/docker.md +6 -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 +459 -459
- 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/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +3 -2
- package/docs/sdk/client.md +3 -3
- package/docs/sdk/docker.md +5 -9
- 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
|
@@ -12,7 +12,7 @@ crouter is an agent runtime for Node.js. Each agent is a **node**: a record with
|
|
|
12
12
|
|
|
13
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
|
|
|
@@ -25,9 +25,9 @@ Start by signing in to your Northlight account (`crtr sys signin`; create the ac
|
|
|
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
|
|
|
@@ -99,7 +99,7 @@ flowchart LR
|
|
|
99
99
|
|
|
100
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: 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://
|
|
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
|
|
|
@@ -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
|
|
@@ -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
|
|
@@ -24,14 +24,14 @@ An app that signs people in with Northlight uses `OAuth2Client` and `oauth.clien
|
|
|
24
24
|
| Option | Type | Default | Meaning |
|
|
25
25
|
|---|---|---|---|
|
|
26
26
|
| `baseURL` | `string` | `CRTR_BASE_URL`, else unset | `http(s)://host:port` of a daemon TCP listener. |
|
|
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. 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. |
|
|
28
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. |
|
|
29
29
|
| `timeout` | `number` (ms) | `30_000` | Per-request wall clock. Does not apply to a stream. |
|
|
30
30
|
| `maxRetries` | `number` | `2` | Transient-failure retries. Never applied to `POST` or `PATCH` — see [[crouter-sdk/errors]]. |
|
|
31
31
|
| `defaultHeaders` | `Record<string, string>` | `{}` | Merged into every request. |
|
|
32
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. |
|
|
33
33
|
| `fetch` | `typeof fetch` | global `fetch`, or the socket implementation when `socketPath` is used | Transport override, for proxies and instrumentation. |
|
|
34
|
-
| `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. |
|
|
35
35
|
|
|
36
36
|
### Environment-variable fallbacks
|
|
37
37
|
|
|
@@ -54,7 +54,7 @@ There is one request path. The client issues every request through the Web `fetc
|
|
|
54
54
|
|
|
55
55
|
## Autostart
|
|
56
56
|
|
|
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.
|
|
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.
|
|
58
58
|
|
|
59
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`).
|
|
60
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.
|
|
@@ -9,6 +9,22 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.781
|
|
13
|
+
|
|
14
|
+
`sourcing.read` and `SOURCING_RUN_RULE`. Additive: no request or response an existing app sends or reads changes.
|
|
15
|
+
|
|
16
|
+
- `sourcing.read(client, request, options?)` reads from the person's Mac (or their GitHub account) first and Northlight's hosted `search` second, and resolves `{served_by, data, cost_usd?, fallback_reason?}`. LinkedIn reads have no hosted path. See [sourcing](/docs/reference/sourcing).
|
|
17
|
+
- `SourcingUnavailableError` (`code: 'sourcing_unavailable'`, status 503, with `attempts`, `retryAt`, `budget`) is raised when no path can serve the read now.
|
|
18
|
+
- `SOURCING_RUN_RULE` is the same rule as text for run prompts that hold `device:browser`.
|
|
19
|
+
|
|
20
|
+
### `payment.reason` can be `account_held`
|
|
21
|
+
|
|
22
|
+
`PaymentRefusalDTO.reason` now lists `account_held`, which the directory already sent while a new account waits for approval. Treat it like any refusal the person cannot fix by paying: show `message`, no link.
|
|
23
|
+
|
|
24
|
+
`GET /v1/human/inbox?include=page`. Additive: without the query the response is unchanged.
|
|
25
|
+
|
|
26
|
+
- With `include=page`, each page ticket carries an optional `page` field holding the same body `GET /v1/human/inbox/:ticket_id` returns, so a client can open every listed page without a read per page. A page that cannot be read is listed without `page`.
|
|
27
|
+
|
|
12
28
|
## 0.3.759
|
|
13
29
|
|
|
14
30
|
### A grant can hold a whole provider as `<provider>:*`
|
|
@@ -333,7 +349,7 @@ Every other `canvas` method and `customObjects.receive`/`ack` remain absent from
|
|
|
333
349
|
- `definePlugin({objectKinds})` declares canvas object kinds by name relative to the plugin (`repo`), each `{ description, events: { <name>: { level: 1-10, supersedes? } }, read?: { command: [...] } }`. The bundle the kit serves carries them in `bundle.json` `object_kinds`, keyed `<providerId>.<name>`: `providerId` is the `auth.providerId` the handler was given, else the plugin name. `definePlugin` throws `PluginDefinitionError` for a relative name that is not lowercase letters, digits and `-`, a blank description, more than 64 events, a level outside 1-10, and a `read.command` that is not a non-streaming leaf of the plugin. Building the bundle throws if the prefixed kind is not one crouter accepts (a provider id with capitals or `_`, or one of crouter's reserved roots such as `repo` or `report`).
|
|
334
350
|
- `ctx.caller.crtr` carries the calling node: `{ node?, machine?, profile?, run? }`, parsed by the exported `parseCrtrCaller(header)` from the request's `Crtr-Caller`. It is absent when the header names no field. The runtime asserts that header and the bearer token does not cover it, so use it to tell which of the verified `sub`'s nodes called, never to authorize; authorize on `sub`.
|
|
335
351
|
|
|
336
|
-
See
|
|
352
|
+
See Local plugins and Object kinds and the calling node.
|
|
337
353
|
|
|
338
354
|
### `nodes.revive` reports `ready` (additive)
|
|
339
355
|
|
|
@@ -377,7 +393,7 @@ Plugins can now declare canvas object kinds and act on the canvas, and an app to
|
|
|
377
393
|
|
|
378
394
|
### Plugin manifests declare `object_kinds` and `scopes` (additive)
|
|
379
395
|
|
|
380
|
-
`plugin.json` and `bundle.json` take two optional top-level blocks. `object_kinds` maps a kind name (`<plugin>.<name>`, so the first segment is the plugin's own name) to `{ description, events, read? }`: `events` holds up to 64 entries `{ level: 1-10, supersedes?: boolean }`, and `read.command` is a leaf path below the plugin's root command. That leaf must answer once: a leaf declared `rest.streaming: true` is refused as a `read.command`. `scopes` lists the canvas scopes the plugin asks for. A provider bundle may not declare `scopes`: a cloud app's scopes come from directory consent. Install, update and enable refuse an invalid block and keep the installed version; a kind another owner already holds is reported as `kind_owned` and the plugin's other kinds still apply. `crtr pkg plugin install|update|enable` print these as `warnings`, plus `appScopes` (the scopes the plugin's token now carries). Plugin authors: see
|
|
396
|
+
`plugin.json` and `bundle.json` take two optional top-level blocks. `object_kinds` maps a kind name (`<plugin>.<name>`, so the first segment is the plugin's own name) to `{ description, events, read? }`: `events` holds up to 64 entries `{ level: 1-10, supersedes?: boolean }`, and `read.command` is a leaf path below the plugin's root command. That leaf must answer once: a leaf declared `rest.streaming: true` is refused as a `read.command`. `scopes` lists the canvas scopes the plugin asks for. A provider bundle may not declare `scopes`: a cloud app's scopes come from directory consent. Install, update and enable refuse an invalid block and keep the installed version; a kind another owner already holds is reported as `kind_owned` and the plugin's other kinds still apply. `crtr pkg plugin install|update|enable` print these as `warnings`, plus `appScopes` (the scopes the plugin's token now carries). Plugin authors: see Local plugins.
|
|
381
397
|
|
|
382
398
|
`ReconcilePackagesDTO` (the answer of `POST /v1/documents/reconcile-packages`) gains two optional fields: `kinds` (`applied` with `outcome` of `inserted`, `updated` or `unchanged`; `refused` with code `kind_owned`; `invalid` plugins with the reason) and `tokens` (`granted` plugins with their scopes, and `revoked` plugin names).
|
|
383
399
|
|
|
@@ -402,7 +418,7 @@ Each enabled local plugin that declares `object_kinds` or `scopes`, or serves ov
|
|
|
402
418
|
|
|
403
419
|
### `Crtr-Caller` and `Crtr-Signature` on local HTTP calls (additive)
|
|
404
420
|
|
|
405
|
-
Every HTTP call to a plugin carries `Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>` (fields in that order, empty ones left out, header omitted when none). Calls to a local plugin's endpoint origin also carry `Crtr-Signature: v1,t=<unix seconds>,h=<signed header names>,sig=<base64url HMAC-SHA256 keyed by the plugin's token>` plus a fresh `Crtr-Request-Id`. A manifest cannot set these three header names. Provider calls carry `Crtr-Caller` too. Plugin authors: the canonical string and a reference verifier are in
|
|
421
|
+
Every HTTP call to a plugin carries `Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>` (fields in that order, empty ones left out, header omitted when none). Calls to a local plugin's endpoint origin also carry `Crtr-Signature: v1,t=<unix seconds>,h=<signed header names>,sig=<base64url HMAC-SHA256 keyed by the plugin's token>` plus a fresh `Crtr-Request-Id`. A manifest cannot set these three header names. Provider calls carry `Crtr-Caller` too. Plugin authors: the canonical string and a reference verifier are in Local plugins.
|
|
406
422
|
|
|
407
423
|
crtrd signs the call; the CLI never holds the token. `POST /v1/plugins/:name/call-headers` (new operation `plugins.call-headers`, person and broker callers) takes only digests, `{ method, url, body_sha256, header_names, headers_sha256 }`, and answers `{ headers }` (`Crtr-Caller`, and `Crtr-Signature` when the URL is on the installed endpoint's origin and that endpoint is loopback). Any other URL gets `Crtr-Caller` only. An unknown or disabled plugin and a provider plugin answer `404 not_found`; malformed digests answer `400 invalid_request`. SDK: `CrtrClient.plugins.callHeaders(name, request)`, `PluginCallHeadersRequestDTO`, `PluginCallHeadersDTO`, `routes.pluginCallHeaders(name)`.
|
|
408
424
|
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: knowledge
|
|
3
|
+
when-and-why-to-read: When you need Sourcing reads, this knowledge should be
|
|
4
|
+
read because Read a person, company or page from the person's own Mac first,
|
|
5
|
+
then from Northlight's hosted search, with one result shape and one "not now"
|
|
6
|
+
error.
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Sourcing reads
|
|
10
|
+
|
|
11
|
+
`sourcing.read(client, request, options?)` reads one thing about a person, company or page. It tries the person's own Mac (or their linked GitHub account) first. When that path cannot be used now, it tries Northlight's hosted `search` provider, which Northlight pays for up to the app's caps. It never writes, never sleeps and never retries.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { sourcing, SourcingUnavailableError } from '@north-light/sdk';
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
const r = await sourcing.read(runtime, { read: 'github.user', login: 'octocat' }, { scopes: grantedScopes });
|
|
18
|
+
// r.served_by: 'device' | 'integrations' | 'hosted'
|
|
19
|
+
// r.data, r.cost_usd? (hosted only), r.fallback_reason? (hosted only: why path 1 did not serve it)
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (error instanceof SourcingUnavailableError) {
|
|
22
|
+
// error.attempts, error.retryAt (ISO or null), error.budget, error.retryable
|
|
23
|
+
} else throw error;
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`client` is anything with `providers.call`: a `Crouter` or the client from `oauth.appClient(userId)`. The app's grant needs `device:browser` for Mac reads, `integrations:github_read` for GitHub, and the `search` scopes for hosted reads (`search:search`, `search:contents`, `search:answer`, `search:people`).
|
|
28
|
+
|
|
29
|
+
## Route table
|
|
30
|
+
|
|
31
|
+
| `read` | Path 1 | Path 2 (hosted `search`) |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `linkedin.profile`, `linkedin.search`, `linkedin.company` | Mac, `@northlight/linkedin` `getProfile`, `searchPeople`, `getCompany` | **none** |
|
|
34
|
+
| `x.profile` | Mac, `@northlight/x` `getProfile` | `people x-profile` |
|
|
35
|
+
| `x.search` | Mac, `@northlight/x` `searchUsers` | none |
|
|
36
|
+
| `x.posts` | Mac, `@northlight/x` `searchPosts` | `search` with `include-domains x.com` |
|
|
37
|
+
| `github.user` | `integrations` `github read` (the person's own GitHub account) | `people github-user` |
|
|
38
|
+
| `github.repos` | `integrations` `github read` | none (a profile is not a repo list) |
|
|
39
|
+
| `web.search`, `web.contents`, `web.answer` | none | `search`, `contents`, `answer` |
|
|
40
|
+
| `email.work` | none | `people work-email` |
|
|
41
|
+
|
|
42
|
+
There is no hosted LinkedIn path. A LinkedIn read the Mac cannot serve ends in `sourcing_unavailable`; retry at `retryAt` once the Mac is back or the limit window passes.
|
|
43
|
+
|
|
44
|
+
## The rule
|
|
45
|
+
|
|
46
|
+
Path 1 is skipped, with no call, when `options.scopes` is given and lacks the scope for that path, or when `options.browser === false` (the app's last device probe found no Chrome). The attempt is recorded as `skipped:no_scope` or `skipped:no_browser`.
|
|
47
|
+
|
|
48
|
+
| Path 1 returns | Result |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `device_offline`, `device_timeout`, `provider_not_connected`, `machine_required`, `helper_not_installed`, `browser_profile_not_open` | Fall through (the Mac cannot be used now) |
|
|
51
|
+
| `site_signed_out`, `wrong_site` | Fall through (not signed in to the site) |
|
|
52
|
+
| `rate_limited` | Fall through; `retry_after_s` is carried to `retryAt` |
|
|
53
|
+
| `lib_broken` | Fall through |
|
|
54
|
+
| `account_not_linked`, `account_reconnect_required` (GitHub) | Fall through |
|
|
55
|
+
| `js_exception`, `outcome_unknown` | Fall through. Reads never return `outcome_unknown`; it is treated as `js_exception`. A `js_exception` whose message names the site function's `NotFound`, `Validation` or `PermissionDenied` is the answer instead |
|
|
56
|
+
| `not_found`, `invalid_argument`, `permission_error`, `scope_missing`, and any code not listed | **Thrown as is.** The person does not exist, the input is bad, or the grant is wrong |
|
|
57
|
+
|
|
58
|
+
| Hosted returns | Result |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `limit_reached`, `payment_required`, `cap_exhausted` (HTTP 402) | Stop: `SourcingUnavailableError` with `budget: true`; `retryAt` is the refusal's `reset_at` |
|
|
61
|
+
| `provider_rate_limited`, `provider_capacity`, `vendor_unavailable` | `SourcingUnavailableError`, retryable, `retryAt` from `retry_after_s` |
|
|
62
|
+
| `price_over_maximum` | Stop: thrown as is |
|
|
63
|
+
| anything else | Thrown as is |
|
|
64
|
+
|
|
65
|
+
## `SourcingUnavailableError`
|
|
66
|
+
|
|
67
|
+
`code: 'sourcing_unavailable'`, `status: 503`. Retryable when any attempt was transient.
|
|
68
|
+
|
|
69
|
+
| Field | Meaning |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `attempts` | One entry per path tried or skipped: `{path, code, retry_after_s?, reset_at?}` |
|
|
72
|
+
| `retryAt` | ISO time of the earliest `retry_after_s` or `reset_at` across the attempts, or `null` |
|
|
73
|
+
| `budget` | `true` when the hosted refusal was a 402 |
|
|
74
|
+
|
|
75
|
+
The app decides what to do: leave the work queued, show "Mac offline and hosted budget used up", and try again after `retryAt`.
|
|
76
|
+
|
|
77
|
+
## Options
|
|
78
|
+
|
|
79
|
+
| Option | Use |
|
|
80
|
+
|---|---|
|
|
81
|
+
| `scopes` | The scopes the grant holds, so a path without its scope is skipped without a call |
|
|
82
|
+
| `browser` | `false` skips the Mac path (the app's last probe found no Chrome) |
|
|
83
|
+
| `machine` | Which Mac takes the device calls, when the person has more than one |
|
|
84
|
+
| `githubAccount` | The linked GitHub account label, when the person has several |
|
|
85
|
+
| `execTimeoutMs` | The Mac script budget (default 30000) |
|
|
86
|
+
| `signal` | Aborts the read |
|
|
87
|
+
|
|
88
|
+
## Cost and logging
|
|
89
|
+
|
|
90
|
+
Device and integrations reads cost Northlight nothing and are not metered. `served_by` says which path answered; for `hosted`, `cost_usd` is the top-level `cost_usd` of the hosted answer (dollars), when the leaf returns one. Add it to your own per-pass cost.
|
|
91
|
+
|
|
92
|
+
## Rule text for agent runs
|
|
93
|
+
|
|
94
|
+
`SOURCING_RUN_RULE` is the same rule written for an agent. Append it to the prompt of any run that holds `device:browser`, so a run that reads LinkedIn with `crtr device browser` follows the same fall-through, no-hosted-LinkedIn and stop rules.
|