@north-light/cli 0.3.731 → 0.3.733
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/dist/api/client.d.ts +3 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/northlight-apps/get-started.md +4 -4
- package/dist/clients/attach/overlays/graph.d.ts +2 -0
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/viewer.js +478 -478
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys/import/move.d.ts +2 -0
- package/dist/commands/sys/import/move.js +9 -7
- package/dist/commands/sys/join.js +1 -1
- package/dist/commands/sys/signin.js +2 -2
- package/dist/core/canvas/canvas.d.ts +1 -1
- package/dist/core/canvas/canvas.js +16 -16
- package/dist/core/canvas/schema-pg/034-authz-epoch-triggers.sql +43 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/tree.d.ts +4 -0
- package/dist/core/canvas/tree.js +6 -6
- package/dist/core/directory/join.d.ts +6 -26
- package/dist/core/directory/join.js +1 -1
- package/dist/core/environment-starter-script.d.ts +1 -1
- package/dist/core/environment-starter-script.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
- package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
- package/dist/core/storage/client.js +2 -2
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/shares.js +1 -1
- package/dist/daemon/crtrd.js +8 -8
- package/dist/daemon/manage.d.ts +2 -7
- package/dist/daemon/manage.js +3 -3
- package/docs/apps/get-started.md +4 -4
- package/docs/cli/join-northlight.md +16 -22
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +18 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -3
- package/packages/crouter-api/dist/commands/sys/import/move.js +12 -0
- package/packages/crouter-api/dist/commands/sys/join.js +5 -37
- package/packages/crouter-api/dist/commands/sys/signin.js +6 -4
- package/packages/crouter-api/dist/core/canvas/canvas.js +7 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/canvas/tree.js +20 -0
- package/packages/crouter-api/dist/core/directory/join.js +35 -86
- package/packages/crouter-api/dist/core/environment-starter-script.js +1 -1
- package/packages/crouter-api/dist/core/grants/sync.js +1 -1
- package/packages/crouter-api/dist/core/providers/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -1
- package/packages/crouter-api/dist/core/storage/client.js +1 -1
- package/packages/crouter-api/dist/daemon/manage.js +2 -16
- 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/dist/core/directory/join-lock.d.ts +0 -13
- package/dist/core/directory/join-lock.js +0 -1
- package/packages/crouter-api/dist/core/directory/join-lock.js +0 -61
package/dist/core/canvas/tree.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var O=Object.defineProperty;var i=(o,t)=>O(o,"name",{value:t,configurable:!0});import{openDb as
|
|
1
|
+
var O=Object.defineProperty;var i=(o,t)=>O(o,"name",{value:t,configurable:!0});import{openDb as r,withCanvasWrite as u}from"./db.js";import{getById as N,nodeObject as w}from"../graph/objects.js";import{recordWatch as b,unwatch as I,configFromJson as E,configToJson as D}from"../graph/watches.js";import{publish as T}from"../graph/events.js";import{DEFAULT_LISTEN as v}from"../graph/types.js";const R=["spawn","job-start","ask"],S="('spawn','job-start','ask')",j=[{threshold:3,delivery:"next-turn"}];function A(o){const t=o.find(e=>e.threshold<=7);return t!==void 0&&t.delivery!=="next-turn"}i(A,"wakesAtSeven");async function d(o,t,...e){const a=await o.prepareUncached(`SELECT wo.id AS from_id, oo.id AS to_id, ws.config_json, ws.created_at,
|
|
2
2
|
wo.listen_json, wn.status AS from_status, onode.status AS to_status
|
|
3
3
|
FROM watches w
|
|
4
4
|
JOIN objects wo ON wo.id = w.watcher AND wo.type = 'node'
|
|
5
5
|
JOIN objects oo ON oo.id = w.object AND oo.type = 'node'
|
|
6
|
-
JOIN watch_subscriptions ws ON ws.watch = w.watch_id AND ws.started_by IN ${
|
|
6
|
+
JOIN watch_subscriptions ws ON ws.watch = w.watch_id AND ws.started_by IN ${S}
|
|
7
7
|
JOIN nodes wn ON wn.node_id = wo.id
|
|
8
8
|
JOIN nodes onode ON onode.node_id = oo.id
|
|
9
9
|
WHERE w.in_tree = 1 ${t}
|
|
10
|
-
ORDER BY ws.created_at, ws.seq`).all(...
|
|
11
|
-
WHERE started_by IN ${
|
|
12
|
-
AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(
|
|
10
|
+
ORDER BY ws.created_at, ws.seq`).all(...e),s=new Map;for(const n of a){const c=n.config_json,f=n.listen_json,_=c!=null?E(c):f!=null?E(f):v,p=`${n.from_id}\0${n.to_id}`,l=s.get(p);if(l){l.active||=A(_);continue}s.set(p,{from_id:n.from_id,to_id:n.to_id,active:A(_),created:n.created_at,from_status:n.from_status??null,to_status:n.to_status??null})}return[...s.values()]}i(d,"treeEdges");async function F(o=null){const t=o===null?null:[...o];return(t===null?await d(await r(),""):await d(await r(),"AND wo.id = ANY(?::text[]) AND oo.id = ANY(?::text[])",t,t)).map(({from_id:a,to_id:s,active:n,created:c})=>({from_id:a,to_id:s,active:n,created:c}))}i(F,"rosterEdges");async function W(o,t,e=!0){await u(async a=>{const s=await w(a,o),n=await w(a,t);await b(a,s,n,"ask"),await x(o,t,e),await T(a,{event:"watched",object:n,actor:s,attrs:{}})})}i(W,"subscribe");async function M(o,t){await u(async e=>{const a=await w(e,o),s=await w(e,t);for(const n of R)await I(e,a,s,{startedBy:n})})}i(M,"unsubscribe");async function x(o,t,e){await u(async a=>{await a.prepareUncached(`UPDATE watch_subscriptions SET config_json = ?
|
|
11
|
+
WHERE started_by IN ${S}
|
|
12
|
+
AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(e?null:D(j),(await w(a,o)).id,(await w(a,t)).id)})}i(x,"setSubscriptionActive");async function $(o){const t=await r(),e=await N(t,o);if(e?.type!=="node")return[];let a=e.id;const s=new Set([a]);for(;;){const c=(await d(t,"AND oo.id = ?",a))[0]?.from_id;if(c===void 0||s.has(c))break;s.add(c),a=c}const n=(await t.prepareUncached(m).all(a,a)).map(c=>c.id);return[a,...n]}i($,"treeContaining");async function B(o){return(await d(await r(),"AND oo.id = ?",o)).map(t=>({node_id:t.from_id,active:t.active,created:t.created}))}i(B,"subscribersOf");async function H(o){return(await d(await r(),"AND wo.id = ?",o)).map(t=>({node_id:t.to_id,active:t.active,created:t.created}))}i(H,"subscriptionsOf");function h(o){return`WITH RECURSIVE walk(id) AS (
|
|
13
13
|
SELECT CAST(? AS text)
|
|
14
14
|
UNION
|
|
15
15
|
SELECT w.object FROM walk
|
|
16
16
|
JOIN watches w ON w.watcher = walk.id AND w.in_tree = 1
|
|
17
17
|
${o?`JOIN objects oo ON oo.id = w.object AND oo.type = 'node' AND oo.kind IS DISTINCT FROM 'human'
|
|
18
18
|
JOIN nodes onode ON onode.node_id = oo.id`:"JOIN nodes onode ON onode.node_id = w.object"}
|
|
19
|
-
) SELECT id FROM walk WHERE id != ?`}i(
|
|
19
|
+
) SELECT id FROM walk WHERE id != ?`}i(h,"subtreeSql");const P=h(!0),m=h(!1);async function Q(o){const t=await r(),e=await N(t,o);return e?.type!=="node"?[]:(await t.prepareUncached(m).all(e.id,e.id)).map(a=>a.id)}i(Q,"view");const y=new Set(["active","idle"]);async function V(o){return(await d(await r(),"AND wo.id = ?",o)).some(t=>t.active&&y.has(t.to_status??""))}i(V,"hasActiveLiveSubscription");async function Y(o){return(await d(await r(),"AND oo.id = ?",o)).some(t=>t.active&&y.has(t.from_status??""))}i(Y,"hasLiveSubscriber");export{m as SUBTREE_ALL_IDS_SQL,P as SUBTREE_IDS_SQL,V as hasActiveLiveSubscription,Y as hasLiveSubscriber,F as rosterEdges,x as setSubscriptionActive,W as subscribe,B as subscribersOf,H as subscriptionsOf,$ as treeContaining,M as unsubscribe,Q as view};
|
|
@@ -18,25 +18,8 @@ interface JoinedClient {
|
|
|
18
18
|
}
|
|
19
19
|
type Registration = Pick<JoinedClient, 'runtime' | 'client_id' | 'issuer' | 'owner' | 'url' | 'machine_id' | 'is_default'>;
|
|
20
20
|
export interface JoinResult extends Registration {
|
|
21
|
-
/** False when the
|
|
21
|
+
/** False when the credential matched the stored successful registration and no directory call was made. */
|
|
22
22
|
registered: boolean;
|
|
23
|
-
/** `restarted`: a daemon was running, join stopped it and started a new one on the joined config. `started`: none was running and join started one, whose first grant sync installs the account's provider plugins (`crtr cloud …`). `not_running`: none was started (a hosted container's launcher owns its daemon). `restart_failed`: the join is committed but the new daemon did not start (see `daemon_error`). */
|
|
24
|
-
daemon: 'restarted' | 'started' | 'not_running' | 'restart_failed';
|
|
25
|
-
daemon_error?: string;
|
|
26
|
-
}
|
|
27
|
-
/** How join takes a running daemon down and brings it back. Absent, join keeps
|
|
28
|
-
* the offline contract and refuses `daemon_running` while a daemon answers. */
|
|
29
|
-
export interface JoinDaemonControl {
|
|
30
|
-
/** Whether a daemon is running or answering on this runtime's socket. */
|
|
31
|
-
running(): Promise<boolean>;
|
|
32
|
-
/** Stop the daemon and every stray; resolves once none remains. */
|
|
33
|
-
stop(): Promise<void>;
|
|
34
|
-
/** Start a daemon on the settings now on disk and wait until it serves. */
|
|
35
|
-
start(): Promise<void>;
|
|
36
|
-
/** Waits, bounded, for a daemon that join started with none running to finish its first grant sync, which installs the account's provider plugins. Best effort: the join is committed either way. */
|
|
37
|
-
firstSync?(): Promise<void>;
|
|
38
|
-
/** Whether this process runs inside a node, whose broker the stop kills. */
|
|
39
|
-
insideNode(): boolean;
|
|
40
23
|
}
|
|
41
24
|
/** Provider plugin ids installed on this machine (reported for display only). */
|
|
42
25
|
export declare function installedPluginIds(): string[];
|
|
@@ -46,12 +29,9 @@ export declare function joinedOwner(): string | null;
|
|
|
46
29
|
export declare function joinedIssuer(): string | null;
|
|
47
30
|
/** The whole registration a successful join recorded, or null; a damaged file throws. */
|
|
48
31
|
export declare function joinedClient(): Registration | null;
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
*
|
|
53
|
-
|
|
54
|
-
* daemon, writes the identity, and starts the daemon again so its start
|
|
55
|
-
* applies the person change to canvas.db. Without it, a running daemon refuses. */
|
|
56
|
-
export declare function joinDirectory(directory: string, token: string, name?: string, daemon?: JoinDaemonControl): Promise<JoinResult>;
|
|
32
|
+
/** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
|
|
33
|
+
export declare function joinDirectory(directory: string, token: string, name?: string): Promise<JoinResult>;
|
|
34
|
+
/** `crtr sys signin`'s registration: the signed-in person's bearer registers this computer as one of the person's runtimes, once. A computer that
|
|
35
|
+
* already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
|
|
36
|
+
export declare function registerSignedInMac(directory: string, bearer: string): Promise<JoinResult | null>;
|
|
57
37
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=Object.defineProperty;var n=(r,e)=>E(r,"name",{value:e,configurable:!0});import{createHash as J,generateKeyPairSync as U,randomUUID as D}from"node:crypto";import{existsSync as I,mkdirSync as R,readdirSync as O,rmSync as x}from"node:fs";import{hostname as S}from"node:os";import{join as _}from"node:path";import{InputError as f}from"../io.js";import{network as d}from"../errors.js";import{secretsDir as g}from"../layout.js";import{apiSocketPath as A}from"../canvas/paths.js";import{daemonAnswers as K}from"../layout-migrate/index.js";import{atomicWriteJson as b,readJsonIfExists as w}from"../fs-utils.js";import{launcherPresent as L}from"../grants/sandboxes.js";import{crtrVersion as N}from"../../shared/crtr-version.js";import{pluginsDir as q}from"../scope.js";function m(){return _(g(),"runtime-client.json")}n(m,"clientPath");function h(r){if(typeof r!="string")return!1;try{const{protocol:e}=new URL(r);return e==="http:"||e==="https:"}catch{return!1}}n(h,"isUrl");function y(r){const e=r??{},{runtime:o,client_id:i,issuer:u,owner:s,url:t}=e;if(typeof o!="string"||!/^runtime:.+/.test(o)||typeof i!="string"||i===""||!h(u)||typeof s!="string"||!/^user:.+/.test(s)||!h(t))throw d("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:c,is_default:a}=e;return{runtime:o,client_id:i,issuer:u,owner:s,url:t,...typeof c=="string"?{machine_id:c}:{},...typeof a=="boolean"?{is_default:a}:{}}}n(y,"registration");function l(){return _(g(),"runtime-client.pending.json")}n(l,"pendingPath");function C(){try{const r=q("user");return!r||!I(r)?[]:O(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")).map(e=>e.name).sort()}catch{return[]}}n(C,"installedPluginIds");async function T(r,e,o,i,u){const s=`${r.replace(/\/$/,"")}/v1/runtimes/registration`;let t;try{t=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({jwk:o,name:i,platform:`${process.platform}-${process.arch}`,crtr_version:N(),plugins:C(),sandboxed:L()}),signal:AbortSignal.timeout(3e4)})}catch(a){throw d(`directory registration request to ${s} failed: ${a instanceof Error?a.message:String(a)}`)}const c=await t.text();if(!t.ok)throw t.status<500&&x(l(),{force:!0}),new f({error:"join_refused",message:`directory refused the registration: ${t.status} ${c.slice(0,500)}`,next:u});try{return y(JSON.parse(c))}catch(a){throw a instanceof SyntaxError?d("directory registration answer is not JSON"):a}}n(T,"register");function p(){const r=w(m());if(r?.token_sha256===void 0)return null;const{owner:e}=r;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${m()} was written by join but has a missing or invalid owner`);return r}n(p,"readJoined");function or(){return p()?.owner??null}n(or,"joinedOwner");function sr(){return p()?.issuer??null}n(sr,"joinedIssuer");function ar(){const r=p();return r===null?null:y(r)}n(ar,"joinedClient");function W(r){return new f({error:"daemon_running",message:`cannot register while a daemon answers on ${r}`,next:"Stop the daemon that owns this volume, then run `crtr sys join` again."})}n(W,"daemonRunningError");async function z(r,e,o,i,u){const s=w(m());if(s?.token_sha256===i)return{joined:y(s),registered:!1};R(g(),{recursive:!0,mode:448});let t=w(l());if(t?.token_sha256!==i||t.directory!==r||!t.jwk||!t.public_jwk){const{privateKey:P,publicKey:$}=U("ec",{namedCurve:"P-256"}),j=D();t={token_sha256:i,directory:r,jwk:{...P.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},b(l(),t,{mode:384})}const{jwk:c,public_jwk:a}=t,k=await T(r,e,a,o,u);return{joined:k,registered:!0,client:{jwk:c,kid:c.kid,alg:"ES256",...k,token_sha256:i}}}n(z,"obtainRegistration");function B(r){if(!h(r))throw new f({error:"invalid_directory",message:"directory must be an http or https URL",received:r,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}n(B,"requireDirectory");async function v(r,e,o,i){if(B(r),e==="")throw new f({error:"invalid_token",message:"credential is empty",field:"token",next:"Pass the enrollment token provisioning supplied."});const{joined:u,registered:s,client:t}=await z(r,e,o,J("sha256").update(e).digest("hex"),i);return t&&(b(m(),t,{mode:384}),x(l(),{force:!0})),{...u,registered:s}}n(v,"registerAndStore");async function ur(r,e,o=S()){const i=A();if(await K(i))throw W(i);return v(r,e,o,"Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.")}n(ur,"joinDirectory");async function cr(r,e){return p()!==null?null:v(r,e,S(),"Run `crtr sys signin` again.")}n(cr,"registerSignedInMac");export{C as installedPluginIds,ur as joinDirectory,ar as joinedClient,sr as joinedIssuer,or as joinedOwner,cr as registerSignedInMac};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\". Files you create for it must be chowned to it. A node runs with HOME set to its app's home\n# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.\n# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,\n# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
|
|
1
|
+
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\". Files you create for it must be chowned to it. A node runs with HOME set to its app's home\n# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.\n# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,\n# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.\n# - Already done for you: git, gh, curl, ripgrep, jq, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
|
|
@@ -8,7 +8,7 @@ const e=`#!/usr/bin/env bash
|
|
|
8
8
|
# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.
|
|
9
9
|
# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,
|
|
10
10
|
# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.
|
|
11
|
-
# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
|
|
11
|
+
# - Already done for you: git, gh, curl, ripgrep, jq, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
|
|
12
12
|
# or install at build time below.
|
|
13
13
|
# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
|
|
14
14
|
# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.
|
package/dist/core/grants/sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var r=(e,n)=>O(e,"name",{value:n,configurable:!0});import{createPrivateKey as P,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,inferenceEndpointOf as B,replaceGrants as C,teamsOf as D}from"./mirror.js";import{onGrantSync as F}from"./on-sync.js";import{hostedEndpointOf as I,paymentSetupUrlOf as M,storeHostedEndpoint as W}from"./hosted-endpoint.js";import{adoptInstallPerson as q}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as L,PersonUnresolvedError as H,personId as z,resolvePerson as K,retireLocalPerson as V,setPersonId as Y}from"../canvas/person.js";const ve=300;function Q(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:P({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Q,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function ke(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(ke,"runtimeId");function X(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(X,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(X(n)),this.name="MachineRevokedError"}}async function Z(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Q(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ee(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:te(a.access_token,a.expires_in)}}r(Z,"mintDirectoryToken");async function ee(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ee,"isInvalidClient");function te(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(te,"tokenExpiry");function ne(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:a==="app"?B(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(ne,"responseGrant");async function re(){try{return{id:z(),late:null}}catch(n){if(n instanceof L)return null;if(!(n instanceof H))throw n}const e=await K();return e===null?null:{id:e.id,late:e}}r(re,"pullPerson");async function oe(e){Y(e.id),await q(e.id);const n=await V();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(oe,"bindLatePerson");let _;function be(e){return _?_(e):Promise.resolve()}r(be,"requestGrantSync");function Ee(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await Z(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:I(s.hosted_endpoint??null),payment_setup_url:M(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(l=>ne(l,d)),w=await v(async()=>{await C(h,j,i,D(s.teams));const l=await re();return g&&l&&await W(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await oe(w.late);try{await F(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(Ee,"createGrantSync");export{ve as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Q as assertion,Ee as createGrantSync,X as machineRevokedMessage,Z as mintDirectoryToken,be as requestGrantSync,y as runtimeClient,ke as runtimeId};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ue=Object.defineProperty;var m=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as G}from"../../api/command-manifest/result.js";import{callerAllows as le,requireGroup as pe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as ce}from"../grants/terminal.js";import{findRefusal as fe,payerOf as me,refusalError as ve,refusedMark as ge,writeCharge as he}from"../ledger/index.js";import{listInstalledPlugins as we}from"../resolver.js";import{emitEvent as ye}from"../events/emit.js";import{ProviderError as c,scopeMissing as be}from"./errors.js";import{parseProviderPayment as _e}from"../provider-failure.js";import{resolveProviderRef as je}from"./roots.js";import{providerToolPath as Ae}from"../plugin-objects-manifest.js";import{ensureProviderBundle as ke,refreshProviderBundle as Y,resolveProviderBundle as S,unavailableProviderError as Pe}from"./bundles.js";import{prepareFileCall as $e,resignForRetry as Z,resolveFileResult as ee}from"./files.js";import{consumeApproval as Ee,requireProviderApproval as qe}from"./approval.js";import{outboundToken as Ce}from"./mint.js";import{discardFile as Re}from"./token-cache.js";import{registerProviderCall as Me}from"./inflight.js";import{buildRequestPlan as Te,paramKey as Ie}from"../command-plugins/transport/http-plan.js";import{newTraceId as Oe}from"../../shared/traceparent.js";import{sendProviderRequest as Be,ProviderTransportError as Ne}from"./request.js";import{acceptProviderReceipt as Se}from"./receipts.js";import{writeProviderAudit as Fe}from"./audit.js";import{selectDevice as De,sendDeviceCall as Ue,deviceFailure as Le,deviceUnreachable as re,DEFAULT_DEVICE_REQUEST_MS as xe}from"./device.js";import{isLibsSearch as te,wantsBundling as Je,callLibsSearch as He,bundleExec as Ge,mapLibOutcome as ze,reportLibCalls as Ke}from"./device-libs.js";import{ownMachineId as Qe}from"../peer/directory.js";import{directoryIssuer as Ve}from"../directory/issuer.js";import{isCloudRole as We}from"../canvas/person-state.js";import{formatCrtrCaller as oe}from"../command-plugins/caller-header.js";import{getNode as Xe}from"../canvas/canvas.js";import{envelopeForProviderCaller as Ye,EnvelopeError as Ze}from"../peer/envelope.js";const er="app:terminal";function ne(e){const t=[],i=m((l,r,n)=>{const p=[...r,l.name],d=n||l.tier==="hidden";if(l.kind==="branch"){for(const b of l.children)i(b,p,d);return}const h=Ae(e.roots.length,p);t.push({tool:h,leaf:l,hidden:d})},"walk");for(const l of e.roots)i(l,[],!1);return t}m(ne,"providerLeaves");function ie(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ie(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:a,description:j,whenToUse:w,tier:y,summary:k,params:P,output:o,effects:u,group:A}=v;t.push({kind:_,name:a,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:k,params:P,output:o,effects:u,group:A})}if(t.length===0)return null;const{kind:i,name:l,description:r,whenToUse:n,tier:p,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:l,description:r,whenToUse:n,...p===void 0?{}:{tier:p},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ie,"providerHelpBranch");async function Dr(e,t){const i=await S(t),l=ne(i.commands),r=we("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>le(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:l.filter(({leaf:p,hidden:d})=>!d&&p.group===n.group).map(({tool:p,leaf:d})=>({tool:p,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const p=ie(n);return p?[p]:[]})}}m(Dr,"providerTools");async function rr(e){return await Se(e.headers["crtr-receipt"],e)}m(rr,"onProviderResponse");async function tr(e){if(e.class==="person"){const t=(await ce())?.sub;if(!t)throw new c("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new c("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(tr,"identity");function or(e,t){return[`${e.id}:${t.group}`]}m(or,"callScope");function nr(e,t){const i=ne(e.commands).find(l=>l.tool===t);if(!i)throw new c("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new c("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(nr,"leafFor");function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(z,"errorBody");function ir(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const l=Date.parse(t);return Number.isFinite(l)?Math.max(0,Math.ceil((l-Date.now())/1e3)):void 0}m(ir,"retryAfter");function F(e,t,i,l=!1){const r=z(t),n=typeof r.code=="string"?r.code:void 0,p=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=_e(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,a={origin:"provider",details:{code:n??null,message:p,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new c("provider_rate_limited",p,{...a,retry_after_s:ir(i["retry-after"])}):e===401||e>=500?new c("provider_unavailable",p,a):e===403&&n==="provider_refused"?new c("provider_refused",p,a):e===403&&n==="approval_required"?new c("provider_error",l?"provider asked for approval again":"provider approval question is invalid",{...a,status:e}):new c("provider_error",p,{...a,status:e})}m(F,"mapProviderResponse");function se(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(se,"approvalShape");async function sr(e){const t=e.origin!==void 0?oe({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):oe({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await Xe(e.node_id))?.profile_id??void 0:void 0,machine:Ve()!==null?Qe():void 0});return t===""?{}:{"Crtr-Caller":t}}m(sr,"crtrCallerHeader");async function Ur(e,t,i){const l=je(t.provider);if(l===null)throw new c("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:l},n=new AbortController,p=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?p():i.signal.addEventListener("abort",p,{once:!0});let d=i.requestId;const h=i.traceId??Oe(),b=Me({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,a,j,w,y,k,P="allowed";try{if(We()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw be(`${r.provider}:*`);try{await ke(r.provider)}catch{throw Pe(r.provider)}let o=await S(r.provider,r.version),u=!1,A=!1,$,D,q,K=!1,Q=!1,U,V=0;for(;;){const g=nr(o,r.tool);if(a=`${o.id}:${g.group}`,pe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new c("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await De(r.machine,void 0,{newest:te(o.major,r.tool)}),V=Date.now()+(o.commands.timeouts?.requestMs??xe));let L=null;if(r.approval&&!K){const s=await Ee(e,r,se(o,g));q=s.option,L=s.prepared,k=r.approval,d=s.requestId,K=!0}const O={params:g.params.filter(s=>"type"in s&&s.type==="file").map(s=>s.name),output:g.output.find(s=>s.type==="file")?.name??null},W=JSON.stringify(O);if(D!==void 0&&D!==W)throw new c("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=W,L&&($=await Z(e,O,r.arguments,L,{signal:n.signal})),$??=await $e(e,O,r.arguments,{signal:n.signal});const{sub:M,grantee:B}=await tr(e);if(o.transport.kind==="machine"){const s=await dr(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:V,signal:n.signal,machine:U});return y=s.responder,v=s.cleanup,{status:200,body:s.result}}const X=o.transport.endpoint;let C;try{C=await Ce({audience:X,sub:M,grantee:B,initiating_app:B,scope:or(o,g)},{signal:n.signal})}catch(s){if(!(s instanceof c)||s.details?.directory_error!=="invalid_target"||A)throw s;A=!0,await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===X)throw s;o=E;continue}j=C.jti;const x=e.class==="person"?er:B,T=me({call:"tool",tokenPayer:C.payer,sub:M}),J=await fe({scope:"call",payer:T.payer,funding:T.funding,sub:M,grantee:x,provider:`app:${o.id}`});if(J!==null)throw await he({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:T.payer,funding:T.funding,sub:M,grantee:x,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ge(J)}),ve(J);const ae={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},de=Te(ae,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await sr(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Be(de,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(s){throw n.signal.aborted?n.signal.reason??s:s instanceof Ne?new c("provider_unavailable",s.message,{origin:"provider",details:{status:null,code:s.kind}}):s}if(w??=await rr({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:B,payer:C.payer,ledger_grantee:x,funding:T.funding,node_id:e.node_id,caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Re(C.key),f.status>=200&&f.status<300){const s=f.body;if(!s||typeof s!="object"||Array.isArray(s))throw new c("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await ee(e,$,s,{signal:n.signal})}catch(I){throw I instanceof c&&I.code==="provider_error"?new c("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}v=E.cleanup;const N=G(g.output,E.result);if(N)throw new c("provider_bad_response",`provider result has an invalid output field "${N.field}"`,{origin:"provider",param:N.field,details:{status:f.status,...N}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=z(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!Q){Q=!0;const s=await qe(e,r,d,R.question,n.signal,se(o,g),$);if(k=s.questionId,q=s.option,$=await Z(e,O,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new c("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const H=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||H)&&!u){u=!0;const s=o.major;await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),ye({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:H?"unsupported_major":"manifest_stale",major_before:s,major_after:o.major,...H&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof c&&o.question_id&&(k=o.question_id),y===void 0&&o instanceof c&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof c?o.code:"server_error"}`,await v?.(),o}finally{try{await Fe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:a,outcome:P,jti:j,receipt_id:w,responder:y,question_id:k})}finally{b()}i.signal.removeEventListener("abort",p)}}m(Ur,"callProvider");function ar(e,t){const i={...t};for(const{name:l}of e.params){const r=Ie(l);r===l||!Object.hasOwn(i,r)||(i[l]=i[r],delete i[r])}return i}m(ar,"declaredNames");async function dr(e,t,i,l,r,n){const{machine:p}=n;let d;try{d=await Ye(e,n.sub)}catch(u){throw u instanceof Ze?new c("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:p,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(te(t.major,i.tool)){const u=await He(h,r.arguments,t.major),A=G(l.output,u);if(A)throw new c("provider_bad_response",`the libraries result has an invalid output field "${A.field}"`,{origin:"provider",param:A.field,details:{status:200,...A}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(Je(t.major,i.tool,r.arguments)){const u=await Ge(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw re(p,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const a=await Ue(p,{tool:i.tool,arguments:ar(l,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in a)throw re(p,a.unreachable.reason,a.unreachable.message);const j=a.headers["crtr-responder"],w=z(a.body);if(a.status<200||a.status>=300){const u=Le(p,a.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,a.body),A=u===null&&a.status>=500&&typeof w.code=="string"?new c("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${a.status}`,{origin:"runtime",status:a.status,details:{code:w.code,status:a.status}}):null;throw Object.assign(u??A??F(a.status,a.body,a.headers),{responder:j})}const y=a.body&&typeof a.body=="object"&&!Array.isArray(a.body)?a.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new c("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:a.status,message:"the device result is not a JSON object"}}),{responder:j});let k=y;if(v!==null){const u=ze(k,v);if(Ke(p,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});k=u.result}let P;try{P=await ee(e,r,k,{signal:n.signal})}catch(u){throw u instanceof c&&u.code==="provider_error"?Object.assign(new c("provider_bad_response",u.message,{origin:"provider",details:{status:a.status,message:u.message}}),{responder:j}):u}const o=G(l.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new c("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:a.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(dr,"callDevice");export{Ur as callProvider,sr as crtrCallerHeader,tr as identity,F as mapProviderResponse,rr as onProviderResponse,ne as providerLeaves,Dr as providerTools};
|
|
1
|
+
var ue=Object.defineProperty;var m=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as G}from"../../api/command-manifest/result.js";import{callerAllows as le,requireGroup as pe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as ce}from"../grants/terminal.js";import{findRefusal as fe,payerOf as me,refusalError as ve,refusedMark as ge,writeCharge as he}from"../ledger/index.js";import{listInstalledPlugins as we}from"../resolver.js";import{emitEvent as ye}from"../events/emit.js";import{ProviderError as c,scopeMissing as be}from"./errors.js";import{parseProviderPayment as _e}from"../provider-failure.js";import{resolveProviderRef as je}from"./roots.js";import{providerToolPath as Ae}from"../plugin-objects-manifest.js";import{ensureProviderBundle as ke,refreshProviderBundle as Y,resolveProviderBundle as S,unavailableProviderError as Pe}from"./bundles.js";import{prepareFileCall as $e,resignForRetry as Z,resolveFileResult as ee}from"./files.js";import{consumeApproval as Ee,requireProviderApproval as qe}from"./approval.js";import{outboundToken as Ce}from"./mint.js";import{discardFile as Re}from"./token-cache.js";import{registerProviderCall as Me}from"./inflight.js";import{buildRequestPlan as Te,paramKey as Ie}from"../command-plugins/transport/http-plan.js";import{newTraceId as Oe}from"../../shared/traceparent.js";import{sendProviderRequest as Be,ProviderTransportError as Ne}from"./request.js";import{acceptProviderReceipt as Se}from"./receipts.js";import{writeProviderAudit as Fe}from"./audit.js";import{selectDevice as De,sendDeviceCall as Ue,deviceFailure as Le,deviceUnreachable as re,DEFAULT_DEVICE_REQUEST_MS as xe}from"./device.js";import{isLibsSearch as te,wantsBundling as Je,callLibsSearch as He,bundleExec as Ge,mapLibOutcome as ze,reportLibCalls as Ke}from"./device-libs.js";import{ownMachineId as Qe}from"../peer/directory.js";import{directoryIssuer as Ve}from"../directory/issuer.js";import{isCloudRole as We}from"../canvas/person-state.js";import{formatCrtrCaller as oe}from"../command-plugins/caller-header.js";import{getNode as Xe}from"../canvas/canvas.js";import{envelopeForProviderCaller as Ye,EnvelopeError as Ze}from"../peer/envelope.js";const er="app:terminal";function ne(e){const t=[],i=m((l,r,n)=>{const p=[...r,l.name],d=n||l.tier==="hidden";if(l.kind==="branch"){for(const b of l.children)i(b,p,d);return}const h=Ae(e.roots.length,p);t.push({tool:h,leaf:l,hidden:d})},"walk");for(const l of e.roots)i(l,[],!1);return t}m(ne,"providerLeaves");function ie(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ie(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:a,description:j,whenToUse:w,tier:y,summary:k,params:P,output:o,effects:u,group:A}=v;t.push({kind:_,name:a,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:k,params:P,output:o,effects:u,group:A})}if(t.length===0)return null;const{kind:i,name:l,description:r,whenToUse:n,tier:p,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:l,description:r,whenToUse:n,...p===void 0?{}:{tier:p},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ie,"providerHelpBranch");async function Dr(e,t){const i=await S(t),l=ne(i.commands),r=we("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>le(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:l.filter(({leaf:p,hidden:d})=>!d&&p.group===n.group).map(({tool:p,leaf:d})=>({tool:p,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const p=ie(n);return p?[p]:[]})}}m(Dr,"providerTools");async function rr(e){return await Se(e.headers["crtr-receipt"],e)}m(rr,"onProviderResponse");async function tr(e){if(e.class==="person"){const t=(await ce())?.sub;if(!t)throw new c("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new c("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(tr,"identity");function or(e,t){return[`${e.id}:${t.group}`]}m(or,"callScope");function nr(e,t){const i=ne(e.commands).find(l=>l.tool===t);if(!i)throw new c("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new c("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(nr,"leafFor");function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(z,"errorBody");function ir(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const l=Date.parse(t);return Number.isFinite(l)?Math.max(0,Math.ceil((l-Date.now())/1e3)):void 0}m(ir,"retryAfter");function F(e,t,i,l=!1){const r=z(t),n=typeof r.code=="string"?r.code:void 0,p=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=_e(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,a={origin:"provider",details:{code:n??null,message:p,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new c("provider_rate_limited",p,{...a,retry_after_s:ir(i["retry-after"])}):e===401||e>=500?new c("provider_unavailable",p,a):e===403&&n==="provider_refused"?new c("provider_refused",p,a):e===403&&n==="approval_required"?new c("provider_error",l?"provider asked for approval again":"provider approval question is invalid",{...a,status:e}):new c("provider_error",p,{...a,status:e})}m(F,"mapProviderResponse");function se(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(se,"approvalShape");async function sr(e){const t=e.origin!==void 0?oe({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):oe({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await Xe(e.node_id))?.profile_id??void 0:void 0,machine:Ve()!==null?Qe():void 0});return t===""?{}:{"Crtr-Caller":t}}m(sr,"crtrCallerHeader");async function Ur(e,t,i){const l=je(t.provider);if(l===null)throw new c("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:l},n=new AbortController,p=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?p():i.signal.addEventListener("abort",p,{once:!0});let d=i.requestId;const h=i.traceId??Oe(),b=Me({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,a,j,w,y,k,P="allowed";try{if(We()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw be(`${r.provider}:*`);try{await ke(r.provider)}catch{throw Pe(r.provider)}let o=await S(r.provider,r.version),u=!1,A=!1,$,D,q,K=!1,Q=!1,U,V=0;for(;;){const g=nr(o,r.tool);if(a=`${o.id}:${g.group}`,pe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new c("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await De(r.machine,void 0,{newest:te(o.major,r.tool)}),V=Date.now()+(o.commands.timeouts?.requestMs??xe));let L=null;if(r.approval&&!K){const s=await Ee(e,r,se(o,g));q=s.option,L=s.prepared,k=r.approval,d=s.requestId,K=!0}const O={params:g.params.filter(s=>"type"in s&&s.type==="file").map(s=>s.name),output:g.output.find(s=>s.type==="file")?.name??null},W=JSON.stringify(O);if(D!==void 0&&D!==W)throw new c("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=W,L&&($=await Z(e,O,r.arguments,L,{signal:n.signal})),$??=await $e(e,O,r.arguments,{signal:n.signal});const{sub:M,grantee:B}=await tr(e);if(o.transport.kind==="machine"){const s=await dr(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:V,signal:n.signal,machine:U});return y=s.responder,v=s.cleanup,{status:200,body:s.result}}const X=o.transport.endpoint;let C;try{C=await Ce({audience:X,sub:M,grantee:B,initiating_app:B,scope:or(o,g)},{signal:n.signal})}catch(s){if(!(s instanceof c)||s.details?.directory_error!=="invalid_target"||A)throw s;A=!0,await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===X)throw s;o=E;continue}j=C.jti;const x=e.class==="person"?er:B,T=me({call:"tool",tokenPayer:C.payer,sub:M}),J=await fe({scope:"call",payer:T.payer,funding:T.funding,sub:M,grantee:x,provider:`app:${o.id}`});if(J!==null)throw await he({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:T.payer,funding:T.funding,sub:M,grantee:x,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ge(J)}),ve(J);const ae={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},de=Te(ae,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await sr(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Be(de,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(s){throw n.signal.aborted?n.signal.reason??s:s instanceof Ne?new c("provider_unavailable",s.message,{origin:"provider",details:{status:null,code:s.kind}}):s}if(w??=await rr({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:B,payer:C.payer,ledger_grantee:x,funding:T.funding,node_id:e.node_id,caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Re(C.key),f.status>=200&&f.status<300){const s=f.body;if(!s||typeof s!="object"||Array.isArray(s))throw new c("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await ee(e,$,s,{signal:n.signal})}catch(I){throw I instanceof c&&I.code==="provider_error"?new c("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}v=E.cleanup;const N=G(g.output,E.result);if(N)throw new c("provider_bad_response",`provider result has an invalid output field "${N.field}"`,{origin:"provider",param:N.field,details:{status:f.status,...N}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=z(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!Q){Q=!0;const s=await qe(e,r,d,R.question,n.signal,se(o,g),$);if(k=s.questionId,q=s.option,$=await Z(e,O,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new c("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const H=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||H)&&!u){u=!0;const s=o.major;await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),ye({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:H?"unsupported_major":"manifest_stale",major_before:s,major_after:o.major,...H&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof c&&o.question_id&&(k=o.question_id),y===void 0&&o instanceof c&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof c?o.code:"server_error"}`,await v?.(),o}finally{try{await Fe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:a,outcome:P,jti:j,receipt_id:w,responder:y,question_id:k})}finally{b()}i.signal.removeEventListener("abort",p)}}m(Ur,"callProvider");function ar(e,t){const i={...t};for(const{name:l}of e.params){const r=Ie(l);r===l||!Object.hasOwn(i,r)||(i[l]=i[r],delete i[r])}return i}m(ar,"declaredNames");async function dr(e,t,i,l,r,n){const{machine:p}=n;let d;try{d=await Ye(e,n.sub)}catch(u){throw u instanceof Ze?new c("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:p,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(te(t.major,i.tool)){const u=await He(h,r.arguments,t.major),A=G(l.output,u);if(A)throw new c("provider_bad_response",`the libraries result has an invalid output field "${A.field}"`,{origin:"provider",param:A.field,details:{status:200,...A}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(Je(t.major,i.tool,r.arguments)){const u=await Ge(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw re(p,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const a=await Ue(p,{tool:i.tool,arguments:ar(l,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in a)throw re(p,a.unreachable.reason,a.unreachable.message);const j=a.headers["crtr-responder"],w=z(a.body);if(a.status<200||a.status>=300){const u=Le(p,a.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,a.body),A=u===null&&a.status>=500&&typeof w.code=="string"?new c("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${a.status}`,{origin:"runtime",status:a.status,details:{code:w.code,status:a.status}}):null;throw Object.assign(u??A??F(a.status,a.body,a.headers),{responder:j})}const y=a.body&&typeof a.body=="object"&&!Array.isArray(a.body)?a.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new c("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:a.status,message:"the device result is not a JSON object"}}),{responder:j});let k=y;if(v!==null){const u=ze(k,v);if(Ke(p,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});k=u.result}let P;try{P=await ee(e,r,k,{signal:n.signal})}catch(u){throw u instanceof c&&u.code==="provider_error"?Object.assign(new c("provider_bad_response",u.message,{origin:"provider",details:{status:a.status,message:u.message}}),{responder:j}):u}const o=G(l.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new c("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:a.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(dr,"callDevice");export{Ur as callProvider,sr as crtrCallerHeader,tr as identity,F as mapProviderResponse,rr as onProviderResponse,ne as providerLeaves,Dr as providerTools};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as v,lstatSync as z,mkdirSync as W,readFileSync as V,readdirSync as J,readlinkSync as X,rmSync as Z,writeFileSync as _}from"node:fs";import{join as E,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",D="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
|
|
2
2
|
slim = false
|
|
3
3
|
`,at="1.1.0",b="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],lt=`ENV NPM_CONFIG_USERCONFIG=/home/${p}/.npmrc`,B=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),N="repos",G="/work/.crtr/setup.log",C="/work/.crtr/setup-failed",M="/usr/local/bin/gh",pt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],L=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ut=c(t=>(t??"").split(`
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${L(t)} "exited $?" >> ${C}`,"guarded");function dt(t,r,i=!1){const s=ut(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${pt.map(L).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${N}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${L(o)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(lt,`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${L(t)} "exited $?" >> ${C}`,"guarded");function dt(t,r,i=!1){const s=ut(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep jq github-cli",`RUN printf '%s\\n' ${pt.map(L).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${N}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${L(o)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(lt,`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
5
5
|
`)}c(dt,"recipeDockerfile");const ht=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function Ut(t){const r=t.git??ht,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(E(t.dir,N),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(N,n.name)],a,t.dir)}_(E(t.dir,st),it),_(E(t.dir,"Dockerfile"),dt(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
6
6
|
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
|
|
7
7
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
8
|
-
`)}c(Ut,"prepareBuildDir");function F(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:V(a),mode:v.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ft,"zipDirectory");async function R(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(R,"api");async function H(t,r){const{status:i,json:s}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function xt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(xt,"deleteImage");const mt=60*6e4;async function Nt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const O=s.timeoutMs??mt,K=e+O;let T=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){T??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-T>=(s.tagGraceMs??6e4),P=(y.length>0?y:A?m:[]).sort((w,
|
|
8
|
+
`)}c(Ut,"prepareBuildDir");function F(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:V(a),mode:v.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ft,"zipDirectory");async function R(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(R,"api");async function H(t,r){const{status:i,json:s}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function xt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(xt,"deleteImage");const mt=60*6e4;async function Nt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const O=s.timeoutMs??mt,K=e+O;let T=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){T??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-T>=(s.tagGraceMs??6e4),P=(y.length>0?y:A?m:[]).sort((w,j)=>(j.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(A)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${O} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(Nt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,mt as BUILD_TIMEOUT_MS,M as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,N as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,lt as RUN_USER_NPMRC_ENV,ot as SANDBOX_API_IMAGE,C as SETUP_FAILED_FILE,G as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,Nt as buildImage,xt as deleteImage,Lt as environmentImageName,H as getImage,Ut as prepareBuildDir,dt as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as E}from"node:crypto";import{copyFileSync as f,mkdtempSync as g,readFileSync as w,writeFileSync as d}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";import{buildImage as S,NODE_BASE_IMAGE as h,removeBuildDir as b,RUN_USER as n,SANDBOX_API_IMAGE as u}from"./image-build.js";const x="/opt/crtr/releases",y=".sha256",I=".complete",i="runtime.tar.gz",A=/^[0-9a-f]{64}$/,O=/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/,l=o(e=>`releases/${e}/sandbox-image.json`,"releaseImageKey");function $(e){if(!O.test(e))throw new Error(`${JSON.stringify(e)} is not a release version`);const r=`crtr-release-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;if(r.length>63)throw new Error(`image name ${r} is longer than 63 characters`);return r}o($,"releaseImageName");function N(e,r){if(!A.test(r))throw new Error("sha256 must be 64 lowercase hex characters");$(e);const a=`${x}/${e}`;return[`FROM ${h} AS release`,`COPY ${i} /tmp/${i}`,`RUN mkdir -p ${a} && tar -xzf /tmp/${i} -C ${a} && echo ${r} > ${a}/${y} && : > ${a}/${I}`,"",`FROM ${h}`,"RUN apk add --no-cache bash git curl ripgrep python3",`COPY --from=${u} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${n} -s /bin/sh ${n} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${n} /run/crtr /var/lib/crtr /work`,"COPY --from=release /opt/crtr /opt/crtr",`USER ${n}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""].join(`
|
|
1
|
+
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as E}from"node:crypto";import{copyFileSync as f,mkdtempSync as g,readFileSync as w,writeFileSync as d}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";import{buildImage as S,NODE_BASE_IMAGE as h,removeBuildDir as b,RUN_USER as n,SANDBOX_API_IMAGE as u}from"./image-build.js";const x="/opt/crtr/releases",y=".sha256",I=".complete",i="runtime.tar.gz",A=/^[0-9a-f]{64}$/,O=/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/,l=o(e=>`releases/${e}/sandbox-image.json`,"releaseImageKey");function $(e){if(!O.test(e))throw new Error(`${JSON.stringify(e)} is not a release version`);const r=`crtr-release-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;if(r.length>63)throw new Error(`image name ${r} is longer than 63 characters`);return r}o($,"releaseImageName");function N(e,r){if(!A.test(r))throw new Error("sha256 must be 64 lowercase hex characters");$(e);const a=`${x}/${e}`;return[`FROM ${h} AS release`,`COPY ${i} /tmp/${i}`,`RUN mkdir -p ${a} && tar -xzf /tmp/${i} -C ${a} && echo ${r} > ${a}/${y} && : > ${a}/${I}`,"",`FROM ${h}`,"RUN apk add --no-cache bash git curl ripgrep jq python3",`COPY --from=${u} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${n} -s /bin/sh ${n} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${n} /run/crtr /var/lib/crtr /work`,"COPY --from=release /opt/crtr /opt/crtr",`USER ${n}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""].join(`
|
|
2
2
|
`)}o(N,"releaseImageDockerfile");function C(e){return`${JSON.stringify(e)}
|
|
3
|
-
`}o(C,"releaseImagePointerText");function U(e,r,a){let s;try{s=JSON.parse(e)}catch{throw new Error(`${l(r)} is not JSON`)}const t=s;if(t===null||typeof t!="object"||typeof t.release!="string"||typeof t.sha256!="string"||typeof t.image!="string"||t.image==="")throw new Error(`${l(r)} must hold {release, sha256, image}`);if(t.release!==r)throw new Error(`${l(r)} names release ${t.release}`);if(t.sha256!==a)throw new Error(`${l(r)} was built from tarball ${t.sha256}, not ${a}`);return t.image}o(U,"parseReleaseImagePointer");async function
|
|
3
|
+
`}o(C,"releaseImagePointerText");function U(e,r,a){let s;try{s=JSON.parse(e)}catch{throw new Error(`${l(r)} is not JSON`)}const t=s;if(t===null||typeof t!="object"||typeof t.release!="string"||typeof t.sha256!="string"||typeof t.image!="string"||t.image==="")throw new Error(`${l(r)} must hold {release, sha256, image}`);if(t.release!==r)throw new Error(`${l(r)} names release ${t.release}`);if(t.sha256!==a)throw new Error(`${l(r)} was built from tarball ${t.sha256}, not ${a}`);return t.image}o(U,"parseReleaseImagePointer");async function j(e,r,a={}){const s=E("sha256").update(w(r.tarball)).digest("hex");if(s!==r.sha256)throw new Error(`${r.tarball} has sha256 ${s}, not ${r.sha256}`);const t=g(c(R(),"crtr-release-image-"));try{f(r.tarball,c(t,i)),d(c(t,"Dockerfile"),N(r.release,r.sha256));const m=await S(e,$(r.release),t,a);return{pointer:{release:r.release,sha256:r.sha256,image:m.ref},built:m}}finally{b(t)}}o(j,"buildReleaseImage");export{x as RELEASES_DIR,I as RELEASE_COMPLETE_FILE,y as RELEASE_SHA_FILE,i as RELEASE_TARBALL_FILE,j as buildReleaseImage,U as parseReleaseImagePointer,N as releaseImageDockerfile,l as releaseImageKey,$ as releaseImageName,C as releaseImagePointerText};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var x=Object.defineProperty;var l=(r,o)=>x(r,"name",{value:o,configurable:!0});import{read as v}from"node:fs";import{Readable as w}from"node:stream";import{promisify as S}from"node:util";import{isCloudRole as $}from"../canvas/person-state.js";import{readConfig as T}from"../config.js";import{directoryIssuer as O}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as E,runtimeId as R}from"../grants/sync.js";const W=104857600;class m extends Error{static{l(this,"StorageRefused")}status;code;constructor(o,u,d){super(d),this.status=o,this.code=u}}const C=S(v);async function*
|
|
1
|
+
var x=Object.defineProperty;var l=(r,o)=>x(r,"name",{value:o,configurable:!0});import{read as v}from"node:fs";import{Readable as w}from"node:stream";import{promisify as S}from"node:util";import{isCloudRole as $}from"../canvas/person-state.js";import{readConfig as T}from"../config.js";import{directoryIssuer as O}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as E,runtimeId as R}from"../grants/sync.js";const W=104857600;class m extends Error{static{l(this,"StorageRefused")}status;code;constructor(o,u,d){super(d),this.status=o,this.code=u}}const C=S(v);async function*U(r,o){let u=0;for(;u<o;){const d=Buffer.allocUnsafe(Math.min(1048576,o-u)),{bytesRead:p}=await C(r,d,0,d.length,u);if(p===0)throw new Error("file shrank while it was being copied");u+=p,yield d.subarray(0,p)}}l(U,"fdChunks");const s=l(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function j(){if($()){const o=process.env.CRTR_BOOT_STORAGE_URL?.replace(/\/$/,"");return o?{service_url:o,base_url:o}:null}const r=T("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}l(j,"storageConfig");let h;function F(){const r=j(),o=O();if(!r||!o)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a registered computer cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${o}
|
|
2
2
|
${r.service_url}
|
|
3
|
-
${r.base_url}`;return h?.key!==u&&(h={key:u,client:A(r,()=>E(o,r.service_url),R())}),h.client}l(F,"storageClient");function J(){h=void 0}l(J,"resetStorageClient");function A(r,o,u){let d,p;const k=l(async()=>{if(d&&d.expires_at-6e4>Date.now())return d.access_token;p??=o().finally(()=>{p=void 0});try{d=await p}catch(t){throw s(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return d.access_token},"bearer"),c=l(async(t,e,i={})=>{const _=[AbortSignal.timeout(i.timeoutMs??1e4),...i.signal?[i.signal]:[]];let n;try{n=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(_),headers:{Authorization:`Bearer ${await k()}`,...i.body===void 0?{}:{"Content-Type":"application/json"}},...i.body===void 0?{}:{body:JSON.stringify(i.body)}})}catch(a){throw a instanceof b?a:s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(n.status===401&&(d=void 0),n.status===404||n.status===409){const a=await n.json().catch(()=>({})),g=a.error?.code??a.code??(n.status===404?"not_found":"not_uploaded");throw new m(n.status,g,a.error?.message??a.message??`storage answered ${n.status}`)}if(!n.ok)throw await n.body?.cancel().catch(()=>{}),s(`storage answered ${n.status} to ${t} ${e.split("?")[0]}`);return n},"call"),f=l(async t=>{try{return await t.json()}catch{throw s("storage answered with an invalid body")}},"json"),y=l(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await f(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const i=await c("GET",`/v1/uploads/${y(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!i.body)throw s("storage answered with no body");const _=i.headers.get("content-length");return{body:w.fromWeb(i.body),size:_===null?null:Number(_),media_type:i.headers.get("content-type")}},async signDownload(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await f(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw s("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async deleteShare(t){try{await c("DELETE",`/v1/shares/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await f(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await f(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await f(await c("POST",`/v1/outbound/${y(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,i,_){const n=w.from(
|
|
3
|
+
${r.base_url}`;return h?.key!==u&&(h={key:u,client:A(r,()=>E(o,r.service_url),R())}),h.client}l(F,"storageClient");function J(){h=void 0}l(J,"resetStorageClient");function A(r,o,u){let d,p;const k=l(async()=>{if(d&&d.expires_at-6e4>Date.now())return d.access_token;p??=o().finally(()=>{p=void 0});try{d=await p}catch(t){throw s(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return d.access_token},"bearer"),c=l(async(t,e,i={})=>{const _=[AbortSignal.timeout(i.timeoutMs??1e4),...i.signal?[i.signal]:[]];let n;try{n=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(_),headers:{Authorization:`Bearer ${await k()}`,...i.body===void 0?{}:{"Content-Type":"application/json"}},...i.body===void 0?{}:{body:JSON.stringify(i.body)}})}catch(a){throw a instanceof b?a:s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(n.status===401&&(d=void 0),n.status===404||n.status===409){const a=await n.json().catch(()=>({})),g=a.error?.code??a.code??(n.status===404?"not_found":"not_uploaded");throw new m(n.status,g,a.error?.message??a.message??`storage answered ${n.status}`)}if(!n.ok)throw await n.body?.cancel().catch(()=>{}),s(`storage answered ${n.status} to ${t} ${e.split("?")[0]}`);return n},"call"),f=l(async t=>{try{return await t.json()}catch{throw s("storage answered with an invalid body")}},"json"),y=l(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await f(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const i=await c("GET",`/v1/uploads/${y(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!i.body)throw s("storage answered with no body");const _=i.headers.get("content-length");return{body:w.fromWeb(i.body),size:_===null?null:Number(_),media_type:i.headers.get("content-type")}},async signDownload(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await f(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw s("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async deleteShare(t){try{await c("DELETE",`/v1/shares/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await f(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await f(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await f(await c("POST",`/v1/outbound/${y(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,i,_){const n=w.from(U(e,i));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":_,"Content-Length":String(i)},body:w.toWeb(n),duplex:"half"})}catch(g){throw s(`storage could not be reached: ${g instanceof Error?g.message:String(g)}`)}finally{n.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw s(`storage answered ${a.status} to the upload`)}}}l(A,"createStorageClient");function X(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}l(X,"invalidStorageName");export{m as StorageRefused,W as UPLOAD_MAX_BYTES,A as createStorageClient,X as invalidStorageName,J as resetStorageClient,F as storageClient,j as storageConfig};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var Q=Object.defineProperty;var u=(t
|
|
2
|
-
`);if(
|
|
3
|
-
`).forEach((
|
|
1
|
+
var Q=Object.defineProperty;var u=(e,t)=>Q(e,"name",{value:t,configurable:!0});import{gzipSync as Y}from"node:zlib";import{browseNodes as D,graphNodes as X,pruneNodes as Z,pruneToLimit as ee,rosterEdges as N,rosterNodes as F}from"../../../core/canvas/canvas.js";import{liveObjectWaitsNamed as B,readControllerWaits as te}from"../../../core/canvas/waits.js";import{runningJobs as ne}from"../../../core/graph/jobs.js";import{nowIso as O}from"../../../core/fs-utils.js";import{isPidPresent as oe}from"../../../core/canvas/pid.js";import{dashboardRowsAllFromSource as se,enrichRowsFromSource as re}from"../../../core/canvas/render-source.js";import{localCanvasSource as G}from"../../../core/canvas/source.js";import{ticketCountsForNodes as M,ticketsAcrossCanvas as ae}from"../../../core/canvas/attention.js";import{buildCorpus as ie,groupCorpus as de,resolveRef as ce}from"../../../core/canvas/history.js";import{listFocuses as q,reapEmptyNodes as le}from"../../../core/runtime/placement.js";import{boundFleet as ue}from"../../../core/runtime/fleet.js";import{retentionHold as fe}from"../../reconcilers/live-obligation.js";import{notFound as me,usage as y}from"../../../core/errors.js";import{openDb as A}from"../../../core/canvas/db.js";import{treeContaining as pe,view as _e}from"../../../core/canvas/tree.js";import{isLiveStatus as he}from"../../../core/canvas/node-order.js";import{readNodeRecap as ye}from"../../../core/canvas/node-recap.js";import{readGoal as be}from"../../../core/runtime/kickoff.js";import{faultSummary as ge}from"../../../core/canvas/status-glyph.js";import{listPendingAsks as we}from"../../../core/human/requests.js";import{toGraphNodeDTO as ve}from"../map.js";import{actsAsPerson as Se,readableAmong as ke,readableNodeIds as P}from"../router.js";import{ApiError as T}from"../../../api/errors.js";import{mapAsync as J}from"../../../core/async-array.js";async function v(e){return await P(e.principal)}u(v,"visibleNodes");async function Ne(e){const t=await v(e);return{status:200,body:{items:(await ae()).filter(o=>t===null||t.has(o.node_id)).map(o=>({node_id:o.node_id,name:o.name,cwd:o.cwd,count:o.count,subjects:o.subjects}))}}}u(Ne,"handleAttention");async function Oe(e){const t=e.body;if(t===null||typeof t!="object"||!Array.isArray(t.node_ids))throw y("attention count request requires node_ids: string[]");const r=t.node_ids;if(!r.every(c=>typeof c=="string"))throw y("attention count request node_ids must contain only strings");const o=await v(e);return{status:200,body:{counts:await M(r.filter(c=>o===null||o.has(c)))}}}u(Oe,"handleAttentionCounts");function x(e){return Buffer.from(String(e),"utf8").toString("base64")}u(x,"encodeCursor");function H(e){const t=Number(Buffer.from(e,"base64").toString("utf8"));if(!Number.isInteger(t)||t<0)throw y(`invalid cursor: ${e}`);return t}u(H,"decodeCursor");function je(e,t,r){const a=e.loadBody().split(`
|
|
2
|
+
`);if(t.length>0){const s=a.findIndex(m=>{const f=m.toLowerCase();return t.some(h=>f.includes(h))});if(s!==-1)return a.slice(s,s+r).map(m=>m.trim()).filter(m=>m!=="").join(" \u23CE ")}const c=a.map(s=>s.trim()).filter(s=>s!=="").slice(0,r).join(" \u23CE ");return c!==""?c:e.title}u(je,"snippet");function Ie(e,t,r){const o=[...e];return t==="relevance"&&r!==void 0?o.sort((a,c)=>(r.get(c.ref)??0)-(r.get(a.ref)??0)||c.tsMs-a.tsMs||a.ref.localeCompare(c.ref)):t==="oldest"?o.sort((a,c)=>a.tsMs-c.tsMs||a.ref.localeCompare(c.ref)):o.sort((a,c)=>c.tsMs-a.tsMs||a.ref.localeCompare(c.ref)),o}u(Ie,"sortArtifacts");function Ce(e){if(e==null)return{};if(typeof e!="object")throw y("history search body must be a JSON object");return e}u(Ce,"parseSearchBody");function Re(e){if(e===null||typeof e!="object")throw y("history grep body must be a JSON object");const t=e;if(typeof t.pattern!="string"||t.pattern==="")throw y("history grep body requires a non-empty pattern");return t}u(Re,"parseGrepBody");async function L(e,t){const r={cwd:e.cwd,allCwds:e.all_cwds===!0,under:e.under,nodes:e.nodes},o={types:e.types,kinds:e.kinds,statuses:e.statuses,sinceMs:e.since_ms,untilMs:e.until_ms,origins:e.origins,roles:e.roles,from:e.from},a=await v(t);return(await ie(r,o)).filter(c=>a===null||a.has(c.nodeId))}u(L,"buildCorpusFromQuery");function Ee(e){if(e==null)return{};if(typeof e!="object")throw y("history stats body must be a JSON object");return e}u(Ee,"parseStatsBody");const z=["origin","node","kind","day","type","role"];async function Me(e){const t=Ee(e.body),r=t.group_by??"type";if(!z.includes(r))throw y(`--group-by must be one of: ${z.join(", ")}; received: ${String(t.group_by)}`);const o=await L(t,e),a=de(o,r);return{status:200,body:{group_by:r,groups:a,total:a.reduce((s,m)=>s+m.count,0),scanned:o.length}}}u(Me,"handleHistoryStats");async function Ae(e){const t=Re(e.body),r=Math.min(100,Math.max(1,t.limit??20)),o=await L(t,e),a=t.cursor!==void 0?H(t.cursor):0;let c;try{c=new RegExp(t.pattern,"i")}catch{throw y(`invalid regex pattern: ${t.pattern}`)}const s=[];for(const p of o)p.loadBody().split(`
|
|
3
|
+
`).forEach((l,b)=>{c.test(l)&&s.push({ref:p.ref,node:`${p.nodeName} (${p.nodeId})`,ts:p.ts,line:b+1,text:l.trim()})});s.sort((p,n)=>p.ref.localeCompare(n.ref)||p.line-n.line);const m=s.slice(a,a+r),f=a+r<s.length?x(a+r):null;return{status:200,body:{hits:m,next_cursor:f,total:s.length}}}u(Ae,"handleHistoryGrep");async function Te(e){const t=Ce(e.body),r=(t.query??"").trim(),o=t.weigh_body===!0,a=t.full===!0,c=Math.max(1,t.snippet_lines??1),s=Math.min(100,Math.max(1,t.limit??20)),m=t.per_node===!0;if(m&&(t.nodes===void 0||t.nodes.length===0))throw new T(400,"invalid_request","`per_node` requires a non-empty `nodes` list",{param:"nodes"});const f=await L(t,e),h=t.cursor!==void 0?H(t.cursor):0,p=r.toLowerCase().split(/\s+/).filter(i=>i.length>0);let n=f,l;const b=t.sort??(p.length>0?"relevance":"recency");if(p.length>0&&b==="relevance"){l=new Map;const i=[];for(const _ of f){const E=_.title.toLowerCase(),K=_.nodeName.toLowerCase(),V=_.nodeDesc.toLowerCase(),$=o?_.loadBody().toLowerCase():null;let k=0;for(const I of p)E.includes(I)&&(k+=10),K.includes(I)&&(k+=5),V.includes(I)&&(k+=3),$!==null&&$.includes(I)&&(k+=1);k>0&&(l.set(_.ref,k),i.push(_))}n=i}else p.length>0&&(n=f.filter(i=>{const _=`${i.title}
|
|
4
4
|
${i.nodeName}
|
|
5
5
|
${i.nodeDesc}${o?`
|
|
6
|
-
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=
|
|
6
|
+
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=Ie(n,b,l);if(m){const i=new Set;d=d.filter(_=>!i.has(_.nodeId)&&i.add(_.nodeId))}const g=m?d:d.slice(h,h+s),w=!m&&h+s<d.length?x(h+s):null;return{status:200,body:{hits:g.map(i=>{const _={ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,kind:i.nodeKind,source:i.source,ts:i.ts,...m?{node_id:i.nodeId}:{}};return b==="relevance"&&l!==void 0&&(_.score=l.get(i.ref)??0),a?_.body=i.loadBody():_.snippet=je(i,p,c),_}),next_cursor:w,total:d.length}}}u(Te,"handleHistorySearch");async function Le(e){const t=(e.query.get("ref")??"").trim();if(!t.includes(":"))throw y(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${t}`,{received:t,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const r=await ce(t);if(r===null)throw me(`no inbox entry or message for ref: ${t}`,{ref:t,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if((await v(e))?.has(r.nodeId)===!1)throw new T(404,"not_found","artifact not found");const o=r.source,c=(e.query.get("format")==="raw"?await r.raw?.():null)??r.body;return{status:200,body:{ref:t,node:`${r.nodeName} (${r.nodeId})`,source:o,ts:r.ts,content:c}}}u(Le,"handleHistoryRead");function $e(e){for(const[o]of e.query)if(o!=="live")throw y(`unknown snapshot query parameter: ${o}`);const t=e.query.getAll("live");if(t.length>1)throw y("live must appear at most once");const r=t[0];if(r===void 0||r==="false"||r==="0")return!1;if(r==="true"||r==="1")return!0;throw y("live must be true or false")}u($e,"snapshotLiveOnly");async function De(e){const t=new Set((await q()).map(n=>n.node_id)),r=await v(e),o=(await se(G,t,$e(e))).filter(n=>r===null||r.has(n.node_id)),a=await M(o.map(n=>n.node_id));await re(G,o,a);const c=await te(o.map(n=>n.node_id)),s=await J(o,async n=>{const l=n.srcRow,b=l?.host_kind??"tmux";return{node_id:n.node_id,name:n.name,title:n.handle??n.name,description:n.description??null,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle??l?.lifecycle,status:n.status,cwd:n.cwd,profile_id:n.profile_id??null,parent:l?.parent??null,created:n.created,host_kind:b,enterable:b==="broker",attention_count:n.asks,...l?.cycles!=null?{cycles:l.cycles}:{},...n.mtimeMs!==void 0?{last_activity:new Date(n.mtimeMs).toISOString()}:{},ctx_tokens:n.ctx_tokens,streaming:n.streaming??!1,jobs_active:l!==void 0&&oe(l.pi_pid)?(await ne(await A(),n.node_id)).length:0,waiting_for:c.get(n.node_id)?.controllerId??null,hanging:n.hanging??null,viewed:n.viewed??!1,final_report:l?.final_report??null,finalized_at:l?.finalized_at??null}}),m=new Map;for(const n of await N(r)){const l=m.get(n.from_id);l===void 0?m.set(n.from_id,[n.to_id]):l.push(n.to_id)}const f=new Set(o.map(n=>n.node_id)),h=Object.fromEntries(o.map(n=>[n.node_id,(m.get(n.node_id)??[]).filter(l=>f.has(l))]));return{status:200,body:{generated_at:O(),nodes:s,subscriptions:h}}}u(De,"handleSnapshot");function U(e){const t=e.host_kind??"tmux";return{node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:t,enterable:t==="broker",parent:e.parent,created:e.created,description:e.description}}u(U,"toRosterNodeDTO");async function Fe(){const e=(await F()).map(U),t=(await N()).map(o=>({from_id:o.from_id,to_id:o.to_id,active:o.active,created:o.created})),r=(await B()).map(o=>({node_id:o.nodeId,object_id:o.objectId,object_type:o.objectType,object_name:o.objectName,created:new Date(o.createdAt).toISOString()}));return{generated_at:O(),nodes:e,edges:t,object_waits:r}}u(Fe,"buildRoster");async function Be(e){const t=e.params.id,o=(await(await A()).prepareUncached(`WITH RECURSIVE up(id) AS (
|
|
7
7
|
SELECT CAST(? AS text)
|
|
8
8
|
UNION
|
|
9
9
|
SELECT w.watcher FROM up JOIN watches w ON w.object = up.id AND w.in_tree = 1
|
|
@@ -13,4 +13,4 @@ ${i.nodeDesc}${o?`
|
|
|
13
13
|
UNION
|
|
14
14
|
SELECT w.object FROM down JOIN watches w ON w.watcher = down.id AND w.in_tree = 1
|
|
15
15
|
JOIN objects oo ON oo.id = w.object AND oo.type = 'node' JOIN nodes onode ON onode.node_id = oo.id
|
|
16
|
-
) SELECT id FROM down`).all(
|
|
16
|
+
) SELECT id FROM down`).all(t)).map(d=>d.id),a=await ke(e.principal,o);if(!a.has(t))return{status:200,body:{generated_at:O(),nodes:[],edges:[],object_waits:[],counts:{}}};const c=await N(a),s=new Map,m=new Map;for(const d of c)(s.get(d.to_id)??s.set(d.to_id,[]).get(d.to_id)).push(d.from_id),(m.get(d.from_id)??m.set(d.from_id,[]).get(d.from_id)).push(d.to_id);let f=t;const h=new Set([f]);for(;;){const d=s.get(f)?.[0];if(d===void 0||h.has(d))break;h.add(d),f=d}const p=new Set([f]),n=[f];for(let d=0;d<n.length;d++)for(const g of m.get(n[d])??[])p.has(g)||(p.add(g),n.push(g));const l=[...p];return{status:200,body:{generated_at:O(),nodes:(await F(l)).map(U),edges:c.filter(d=>p.has(d.from_id)&&p.has(d.to_id)).map(d=>({from_id:d.from_id,to_id:d.to_id,active:d.active,created:d.created})),object_waits:(await B(void 0,l)).map(d=>({node_id:d.nodeId,object_id:d.objectId,object_type:d.objectType,object_name:d.objectName,created:new Date(d.createdAt).toISOString()})),counts:await M(l)}}}u(Be,"handleView");async function Ge(e){const t=await Fe(),r=await v(e);return r===null?{status:200,body:t}:{status:200,body:{...t,nodes:t.nodes.filter(o=>r.has(o.node_id)),edges:t.edges.filter(o=>r.has(o.from_id)&&r.has(o.to_id)),object_waits:(t.object_waits??[]).filter(o=>r.has(o.node_id))}}}u(Ge,"handleRoster");function W(e){if(e.name!==""&&e.name!==e.kind)return e.name;const t=(e.description??"").trim();return t!==""?t:e.name}u(W,"liveRootName");const qe=1440*6e4;async function Pe(){const e=await D(),t=new Map(e.map(n=>[n.node_id,n])),r=new Map((await(await A()).prepare("SELECT node_id, reply_at, read_at, intent FROM nodes WHERE parent IS NULL").all()).map(n=>[n.node_id,n])),o=await we(),a=new Map;for(const n of o)a.set(n.requester_node_id,(a.get(n.requester_node_id)??0)+1);const c=new Date(Date.now()-qe).toISOString(),s=u(n=>{const l=r.get(n.node_id);return l?.reply_at!=null&&(l.read_at==null||l.reply_at>l.read_at)||(a.get(n.node_id)??0)>0?!0:n.status!=="done"||l?.intent!=="parked"?!1:[n.created,n.telemetry_updated_at,l.reply_at].reduce((g,w)=>w!=null&&w>g?w:g,"")>=c},"keepFinished"),m=e.filter(n=>n.parent===null&&n.kind!=="human"&&(he(n.status)||s(n))),f=new Map;for(const n of await N())f.set(n.from_id,[...f.get(n.from_id)??[],n.to_id]);const h=u(n=>{const l=t.get(n)?.fault;return l&&l.link!=="broker\u2194crtrd"?ge(l):null},"faultOf"),p=await J(m,async n=>{const l=[n.node_id,...await _e(n.node_id)].filter(i=>t.get(i)?.kind!=="human"&&t.has(i)),b=new Set(l),d=o.filter(i=>b.has(i.requester_node_id)),g=r.get(n.node_id),w=g?.reply_at??null,R=g?.read_at??null;let S=n.created;for(const i of l){const _=t.get(i).telemetry_updated_at;_!=null&&_>S&&(S=_)}return w!==null&&w>S&&(S=w),{node_id:n.node_id,name:W(n),cwd:n.cwd,profile_id:n.profile_id,status:n.status,state_line:(()=>{const i=ye(n.node_id)?.state.trim();return i||null})(),goal:(await be(n.node_id))?.trim()||null,asks:d.length,first_ask_ticket_id:d[0]?.inbox_ticket_id??null,fault:l.map(h).find(i=>i!==null)??null,running_count:l.filter(i=>t.get(i).streaming===!0).length,unread:w!==null&&(R===null||w>R),last_activity:S,children:(f.get(n.node_id)??[]).filter(i=>t.has(i)&&t.get(i).kind!=="human").map(i=>{const _=t.get(i);return{node_id:i,name:W(_),status:_.status,streaming:_.streaming===!0,asks:a.get(i)??0,fault:h(i)}})}});return{generated_at:O(),rows:p}}u(Pe,"buildLiveRoots");let j=null,C=null;function Je(){const e=u(()=>Promise.resolve().then(Pe),"run");return j===null?(j=e().finally(()=>{j=null}),j):(C===null&&(C=j.then(e).finally(()=>{C=null})),C)}u(Je,"liveRootsCoalesced");async function xe(e){if(!Se(e.principal))throw new T(403,"permission_error","only the person reads the dashboard");const t=await Je(),r=e.query.get("profile");return{status:200,body:r===null?t:{...t,rows:t.rows.filter(o=>o.profile_id===r)}}}u(xe,"handleLiveRoots");async function He(e){const t=await P(e.principal),r=(await D()).filter(s=>t===null||t.has(s.node_id)).map(s=>({node_id:s.node_id,name:s.name,description:s.description,kind:s.kind,mode:s.mode,lifecycle:s.lifecycle,status:s.status,cwd:s.cwd,profile_id:s.profile_id,grantee:s.grantee??"app:terminal",parent:s.parent,created:s.created,frozen_at:s.frozen_at??null,terminal_reason:s.terminal_reason??null,final_report:s.final_report??null,telemetry_tokens_in:s.telemetry_tokens_in??null,telemetry_updated_at:s.telemetry_updated_at??null,fault:s.fault&&s.fault.link!=="broker\u2194crtrd"?{...s.fault,link:s.fault.link}:null,streaming:s.streaming??!1})),o=new Set(r.map(s=>s.node_id)),a=(await N(t)).filter(s=>o.has(s.from_id)&&o.has(s.to_id));return{status:200,rawBody:Y(JSON.stringify({nodes:r,edges:a}),{level:1}),headers:{"content-type":"application/gzip"}}}u(He,"handleBrowse");async function ze(e){const t=await v(e),r=e.query.get("root");let o=t,a;return r!==null&&(a=(await pe(r)).filter(s=>t===null||t.has(s)),o=new Set(a)),{status:200,body:{generated_at:O(),nodes:(await X(a)).filter(s=>o===null||o.has(s.node_id)).map(ve),edges:(await N(o)).filter(s=>o===null||o.has(s.from_id)&&o.has(s.to_id)).map(s=>({from_id:s.from_id,to_id:s.to_id,active:s.active,created:s.created})),focused_node_ids:(await q()).map(s=>s.node_id).filter(s=>o===null||o.has(s))}}}u(ze,"handleGraph");function Ue(e){if(e==null)return{};if(typeof e!="object")throw y("prune body must be a JSON object");const t=e,r=u(p=>{const n=t[p];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw y(`${p} must be a number`);return n}},"num"),o=u(p=>{const n=t[p];if(n!==void 0){if(typeof n!="boolean")throw y(`${p} must be a boolean`);return n}},"bool"),a={},c=r("limit");c!==void 0&&(a.limit=c);const s=r("ttl_days");s!==void 0&&(a.ttl_days=s);const m=o("include_stale");m!==void 0&&(a.include_stale=m);const f=o("empty");f!==void 0&&(a.empty=f);const h=o("dry_run");return h!==void 0&&(a.dry_run=h),a}u(Ue,"parsePruneBody");async function We(e){const t=Ue(e.body),r=t.ttl_days??14,o=t.dry_run??!1,a=await fe(ue());let c;return t.limit!==void 0?c=(await ee({maxNodes:t.limit,held:a,dryRun:o})).pruned.map(f=>({node_id:f.node_id,status:f.status,created:f.created})):t.empty===!0?c=(await le({dryRun:o})).map(f=>({node_id:f,status:"empty",created:""})):c=(await Z({ttlDays:r,held:a,dryRun:o,includeStale:t.include_stale??!1})).pruned.map(f=>({node_id:f.node_id,status:f.status,created:f.created})),{status:200,body:{pruned:c,dry_run:o,ttl_days:r}}}u(We,"handlePrune");const wt=[{method:"GET",pattern:"/v1/canvas/attention",handler:Ne},{method:"POST",pattern:"/v1/canvas/attention/counts",handler:Oe},{method:"POST",pattern:"/v1/canvas/history/search",handler:Te},{method:"POST",pattern:"/v1/canvas/history/grep",handler:Ae},{method:"GET",pattern:"/v1/canvas/history/read",handler:Le},{method:"POST",pattern:"/v1/canvas/history/stats",handler:Me},{method:"GET",pattern:"/v1/canvas/snapshot",handler:De},{method:"GET",pattern:"/v1/canvas/roster",handler:Ge},{method:"GET",pattern:"/v1/canvas/view/:id",handler:Be},{method:"GET",pattern:"/v1/canvas/live-roots",handler:xe},{method:"GET",pattern:"/v1/canvas/browse",handler:He},{method:"GET",pattern:"/v1/canvas/graph",handler:ze},{method:"POST",pattern:"/v1/canvas/prune",ownerOnly:!0,handler:We}];export{wt as canvasRoutes,He as handleBrowse};
|