@north-light/cli 0.3.659 → 0.3.661
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 +5 -1
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/broker-ops.d.ts +33 -1
- package/dist/api/dto/files.d.ts +20 -0
- package/dist/api/dto/run-events.d.ts +9 -1
- package/dist/api/routes.d.ts +3 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +12 -6
- package/dist/clients/attach/viewer.js +471 -471
- package/dist/commands/push.js +6 -4
- package/dist/core/canvas/deliveries.d.ts +2 -0
- package/dist/core/canvas/deliveries.js +19 -18
- package/dist/core/canvas/export-sqlite.js +1 -1
- package/dist/core/canvas/migrations.js +1 -1
- package/dist/core/canvas/person.js +3 -3
- package/dist/core/canvas/schema-pg/019-outbound-files.sql +26 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/remove.js +1 -1
- package/dist/core/import/bundle/layout.d.ts +1 -1
- package/dist/core/import/bundle/layout.js +3 -3
- package/dist/core/import/load/bind.js +8 -8
- package/dist/core/providers/files.js +1 -1
- package/dist/core/runs/operations.js +4 -4
- package/dist/core/runtime/broker/daemon-ops.d.ts +2 -1
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/broker/frame-session.js +3 -3
- package/dist/core/runtime/broker/held-deferred-inbox.d.ts +6 -0
- package/dist/core/runtime/broker/held-deferred-inbox.js +1 -1
- package/dist/core/runtime/broker/rebind.d.ts +5 -2
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/launch-recipe.d.ts +13 -0
- package/dist/core/runtime/launch-recipe.js +1 -0
- package/dist/core/runtime/revive.d.ts +2 -0
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/storage/download.d.ts +0 -1
- package/dist/core/storage/download.js +1 -1
- package/dist/core/storage/media-types.d.ts +1 -0
- package/dist/core/storage/media-types.js +1 -0
- package/dist/core/storage/shares.d.ts +15 -6
- package/dist/core/storage/shares.js +1 -1
- package/dist/core/storage/tables.d.ts +31 -1
- package/dist/core/storage/tables.js +4 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/node-files.d.ts +2 -0
- package/dist/daemon/api/handlers/node-files.js +1 -0
- package/dist/daemon/api/handlers/transfer.d.ts +2 -2
- package/dist/daemon/api/handlers/transfer.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/reconcilers/ledger-storage.js +3 -3
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/docs/apps/guides/files-and-documents.md +11 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,credentialed:JSON.stringify(
|
|
3
|
-
`,{atomic:!0,mode:432}),b(S,
|
|
1
|
+
var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Ce}from"node:child_process";import{mkdirSync as fe,existsSync as j,unlinkSync as de,openSync as G,closeSync as L,writeSync as Le,chmodSync as Ae,lstatSync as Be}from"node:fs";import{ensureAppSpace as $e}from"../spaces/space.js";import{sandboxCacheEnv as je}from"../spaces/cache-env.js";import{compileLaunch as Ge,launchStillGranted as Fe}from"../spaces/mounts.js";import{grantsGeneration as me}from"../grants/mirror.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{launcherRequest as F}from"../../launcher/client.js";import{piAgentDir as he}from"./package-health.js";import{existsBeneath as z,readFileBeneath as Me,readTextBeneathIfExists as Ke,setModeBeneath as b,withDirBeneath as V,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Q,join as m,resolve as Je,isAbsolute as Ue}from"node:path";import{fileURLToPath as pe}from"node:url";import{connectViewSocket as He}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as We,readMergedLaunchConfig as qe}from"../config.js";import{loadRotationConfig as Xe}from"../subscription-state.js";import{getNode as E}from"../canvas/index.js";import{withCanvasWrite as ze}from"../canvas/db.js";import{requestExecutionStop as Ve,setExecutionLaunchJson as Qe}from"../canvas/executions.js";import{scopesFilePath as Y,crtrHome as we,nodeRunDir as Z,nodeRunJobDir as Ye,jobDir as Ze,viewSocketPath as Ie,nodeAgentDir as er,contextDir as rr,nodeHome as tr}from"../canvas/paths.js";import{encodeFrame as ge}from"./broker-protocol.js";import{buildBrokerEnv as nr}from"./spawn-env-rows.js";import{hostExecPathFresh as or}from"./branded-host.js";import{isPidAlive as I,killProcessTreePids as Ee,isAnyPidAlive as ir,captureTeardownSnapshot as sr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ar}from"./canvas-extensions.js";import{appMemoryFull as cr,appMemoryTooSmall as lr,boundFleet as ur,brokerCapReached as fr,brokerThresholdsForDaemon as dr}from"./fleet.js";import{admitBrokerMemory as mr}from"./memory-admission.js";import{emitEvent as _}from"../events/emit.js";import{bindBrokerEventSource as hr,eventSource as pr}from"../events/source.js";import{envBrokerEngine as wr}from"../../shared/env.js";import{conversationIdFromPath as gr,conversationStore as Er,ConversationNotFoundError as _e}from"../conversation-store/index.js";import{mintNodeToken as _r}from"../canvas/node-tokens.js";import{personId as kr}from"../canvas/person.js";function J(){const e=Q(pe(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const vr="@earendil-works/pi-coding-agent";function ke(){const e=m(he(),"models.json"),r=Ke(Q(e),e);if(r===null)return null;const n=JSON.parse(r),o=c(t=>Array.isArray(t)?t.map(o):t===null||typeof t!="object"?t:Object.fromEntries(Object.entries(t).filter(([i])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(i)).map(([i,s])=>[i,o(s)])),"scrub");return{text:r,clean:`${JSON.stringify(o(n),null,2)}
|
|
2
|
+
`,credentialed:JSON.stringify(n)!==JSON.stringify(o(n))}}c(ke,"scrubbedBrokerModels");function yr(e,r){const n=m(he(),"models.json"),o=m(r,"models.json"),t=ke();if(t!==null){if(n===o&&t.text!==t.clean){if(t.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");b(e,o,432);return}M(e,o,t.clean,{atomic:!0,mode:432}),b(e,o,432)}}c(yr,"writeBrokerModels");function ve(e){return e.env.CRTR_BROKER_ENGINE??wr()}c(ve,"resolveEngineSpec");function ye(e){return e.includes("/")||e.endsWith(".jsonl")}c(ye,"isPlainLaunchSessionPath");function Sr(e,r){return Ue(e)?e:Je(r,e)}c(Sr,"resolvePlainLaunchPath");async function br(e,r,n,o){if(n==="--session"&&!ye(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!ye(o))return;const t=Sr(o,r),i=gr(t);try{if(i===null)throw new _e(t);await Er().header(i)}catch(s){if(!(s instanceof _e))throw s;const u=n==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${t})`)}}c(br,"preflightLaunchSessionArg");async function Se(e,r,n){const o=ke();return JSON.stringify({...r,configSnapshot:{user:We("user"),launch:qe(n,r.env.CRTR_PROFILE_ID||null),rotation:await Xe()},scopes:(await E(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Se,"brokerLaunchJson");async function Rr(e,r,n,o){const t=Z(e);fe(t,{recursive:!0}),process.platform==="linux"&&j(X)&&Be(t).uid===process.getuid()&&Ae(t,504);const i=m(t,"broker-launch.json");M(t,i,o??await Se(e,r,n),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(t,Y(e),JSON.stringify((await E(e))?.scopes??[]),{atomic:!0});const s=Me(t,i).toString("utf8"),u=JSON.parse(s);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const w=ve(r);try{const l=import.meta.resolve(w);if(l.startsWith("file:")&&!j(pe(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${w}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,N=[];for(let l=0;l<h.length;l++){const x=h[l];if(x==="-e"){const D=h[++l];D!==void 0&&N.push(D);continue}if(x!=="--session"&&x!=="--fork")continue;const R=h[++l];R!==void 0&&await br(e,n,x,R)}try{ar(N)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Rr,"preflightBrokerLaunch");const Pr=2e3,xr=2e3,Tr=150;async function U(e,r){const n=Date.now()+r;for(;ir(e);){const o=n-Date.now();if(o<=0)return!1;await new Promise(t=>setTimeout(t,Math.min(Tr,o)))}return!0}c(U,"waitForTreeExit");async function Or(e,r,n){return e.length===0?{confirmed:!0}:n&&await U(e,Pr)?{confirmed:!0}:(Ee(e,"SIGTERM",r),await U(e,xr)?{confirmed:!0}:(Ee(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Or,"terminateBrokerTree");async function be(e,r){const n=await E(e),o=n?.pi_pid,t=o!=null?sr(o,n?.pi_pid_identity??null,r.excludePid):null;return t?.reused===!0&&_({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:n?.pi_pid_identity??null}}),{tree:t?.tree??[],identities:t?.identities??null,nodeId:e,launcherPid:j(X)&&t?.tree.includes(o)?o:null}}c(be,"prepareBrokerTeardown");async function Re(e){if(e.launcherPid!==null){try{await F({operation:"stop",pid:e.launcherPid})}catch(r){return I(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let n=!1,o=!1;const t=c(w=>{o||(o=!0,r(w))},"settle"),i=c(()=>{try{de(Ie(e.nodeId))}catch{}},"cleanupSocket"),s=c(w=>{Or(e.tree,e.identities,w).then(t,h=>t({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=He(e.nodeId);u.once("error",()=>{n||(i(),s(!1))}),u.once("connect",()=>{n=!0;try{u.write(ge({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(ge({type:"shutdown"}))}catch{}u.end(),i(),s(!0)})})}c(Re,"runPreparedBrokerTeardown");async function ft(e,r={},n){let o;try{await Ve(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"}),o=await be(e,r)}catch(t){const i={confirmed:!1,error:t instanceof Error?t:new Error(String(t))};return _({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:i.error}),i}return await new Promise(t=>{const i=c(()=>{Re(o).then(async s=>{if(s.confirmed){if(n!==void 0)try{await n()}catch(u){_({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else _({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error});t(s)},s=>{const u={confirmed:!1,error:s instanceof Error?s:new Error(String(s))};_({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),t(u)})},"run");r.startAfter===void 0?setImmediate(i):r.startAfter.then(i,i)})}c(ft,"requestBrokerTeardown");function Pe(){return process.platform==="linux"&&j(X)}c(Pe,"isolatedBrokerLauncherAvailable");const dt={async launch(e,r,n){if(De((await E(e))?.grantee),(await E(e))?.isolated===!0&&!Pe())throw new Error("isolated broker requires the Linux root launcher");const o=n.launchJson??await Se(e,r,n.cwd);await Rr(e,r,n.cwd,o);const t=r.env.CRTR_EXECUTION_ID;n.launchJson===void 0&&t!==void 0&&await Qe(t,o);const i=ur();if(!await i.reserveSlot(e))throw fr(dr().automaticReviveCap,await i.occupancy());let s=null,u,w=!1;try{const h=Ze(e);fe(h,{recursive:!0}),s=G(m(h,"broker.log"),"a");const N=ve(r),l={...await nr(r),CRTR_BROKER_ENGINE:N};if(N!==vr){const a=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;a!==void 0&&(l.NODE_OPTIONS=a);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}pr()===void 0&&hr(e);const x=(await E(e))?.run_id;if(x){const a=await E(x);if(!a||a.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const D=await ze(a=>_r(a,R,e,new Date().toISOString())),H=Pe();if((await E(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const a=await E(e);if(!a)throw new Error(`missing node ${e}`);const f=a.grantee??"app:terminal",T=await mr(e,{useMemo:!1});if(T.verdict==="denied")throw cr(T);if(T.verdict==="too_small")throw lr(T);const v=await $e(f);Object.assign(l,je(f));const y={uid:process.getuid(),gid:v.gid},g=Z(e);for(const[d,k]of[[K(f).nodes,er(e,f)],[K(f).nodes,rr(e,f)],[g,Ye(e)]])V(d,k,()=>{},!0),b(d,k,1528,y);b(g,m(g,"broker-launch.json"),416,y),z(g,Y(e))&&b(g,Y(e),416,y);const te=m(g,"system-prompt.md");z(g,te)&&b(g,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(g,d);z(g,k)&&b(g,k,432,y)}const ne=a.isolated===!0,S=tr(e,f,ne);ne&&(V(K(f).nodes,S,()=>{},!0),b(K(f).nodes,S,1528,y),l.HOME=S,l.PI_CODING_AGENT_DIR=m(S,".pi","agent"));const q=m(S,".pi","agent");V(S,q,()=>{},!0),yr(S,q);const oe=m(q,"settings.json"),Te=m(Q(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(S,oe,`${JSON.stringify({packages:[Te]})}
|
|
3
|
+
`,{atomic:!0,mode:432}),b(S,oe,432);const ie=m(Z(e),`token-${R}`),B=G(ie,"wx+",384);de(ie),Le(B,D);const se=[G(`/proc/self/fd/${B}`,"r"),G(`/proc/self/fd/${B}`,"r")];L(B);const ae={nodeId:e,app:f,sub:a.sub??kr(),grantId:a.grant_id??null,scopes:a.scopes??null,isolated:a.isolated===!0,...a.isolated===!0?{cwd:a.cwd}:{},command:[process.execPath,J(),"--canvas-home",we(),"--epoch",i.epoch(),e],env:Object.fromEntries(Object.entries({...l,...a.isolated===!0?{PWD:a.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>_({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const C of se){const $=await me(),p=await Ge(ae);p.broker=!0;const P=await F({operation:"launch",spec:p},[C]);if(!("pid"in P))throw new Error("launcher did not return a pid");if(await me()===$||await Fe(ae,p)){d=P.pid;break}_({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:P.pid}}),await F({operation:"stop",pid:P.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Oe=Date.now(),ce=new Promise(C=>{const $=setInterval(()=>{I(k)||(clearInterval($),F({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:P,signal:ue})=>{_({level:p||P!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:P,signal:ue,uptime_ms:Date.now()-Oe,oom_killed:p}}),C({code:P,signal:ue,...p?{oomKilled:!0}:{}})}))},250);$.unref()});L(s),s=null;const le={pid:k,exited:ce};return i.register(e,le),w=!0,ce.then(async C=>await i.onChildExit(e,C,R)),le}finally{for(const d of se)L(d)}}const xe=await or(),O=Ce(xe,[J(),"--canvas-home",we(),"--epoch",i.epoch(),e],{cwd:n.cwd,detached:!0,stdio:["ignore",s,s,"pipe"],env:l});u=O;const A=O.stdio[3];if(!A||!("end"in A))throw new Error("broker token pipe did not open");A.on("error",a=>_({event:"broker.token_pipe.failed",level:"error",node_id:e,error:a})),A.end(D),L(s),s=null;const ee=Date.now(),re=new Promise(a=>{let f=!1;const T=c(v=>{f||(f=!0,a(v))},"finish");O.once("exit",(v,y)=>{_({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-ee}}),T({code:v,signal:y})}),O.once("error",v=>{_({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-ee}}),T({code:null,signal:null})})});O.unref();const W={pid:O.pid??null,exited:re};return W.pid!==null&&(i.register(e,W),w=!0,re.then(async a=>await i.onChildExit(e,a,R))),W}catch(h){if(!w&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{w||i.releaseReservation(e),s!==null&&L(s)}},async isAlive(e){return I((typeof e=="string"?await E(e):e)?.pi_pid)},async teardown(e,r={}){try{return Re(await be(e,r))}catch(n){return Promise.resolve({confirmed:!1,error:n instanceof Error?n:new Error(String(n))})}},async signal(e,r){const n=(await E(e))?.pi_pid;if(n!=null)try{process.kill(n,r)}catch{}}};export{Se as brokerLaunchJson,dt as headlessBrokerHost,Pe as isolatedBrokerLauncherAvailable,Rr as preflightBrokerLaunch,ft as requestBrokerTeardown};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PiInvocation } from './invocation.js';
|
|
2
|
+
/** The env a running broker re-applies at the start of each cycle (and deletes when the next launch spec no longer carries it). */
|
|
3
|
+
export declare const CYCLE_APPLIED_ENV: readonly ["CRTR_KIND", "CRTR_MODE", "CRTR_LIFECYCLE", "CRTR_CYCLES", "CRTR_MODEL_INTENT", "CRTR_NODE_DEADLINE_AT"];
|
|
4
|
+
/** A launch invocation, optionally with the stored recipe's config snapshot and scopes (`brokerLaunchJson`): the broker reads both once at boot. */
|
|
5
|
+
type RecipeInput = Pick<PiInvocation, 'argv' | 'env'> & {
|
|
6
|
+
configSnapshot?: unknown;
|
|
7
|
+
scopes?: unknown;
|
|
8
|
+
};
|
|
9
|
+
/** Digest of everything in a launch invocation that a running broker cannot change in place. */
|
|
10
|
+
export declare function launchRecipeKey(inv: RecipeInput): string;
|
|
11
|
+
/** Whether the process launched from `runningLaunchJson` can start a cycle for `next` without restarting. */
|
|
12
|
+
export declare function cycleCompatible(runningLaunchJson: string | null, nextLaunchJson: string): boolean;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s=Object.defineProperty;var n=(e,r)=>s(e,"name",{value:r,configurable:!0});import{createHash as T}from"node:crypto";import{KICKOFF_ORIGIN_ENV as o}from"./stamp/protocol.js";const l=new Set(["CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_CYCLES","CRTR_MODEL_INTENT","CRTR_MODEL_EXACT","CRTR_EXECUTION_ID","CRTR_SUBTREE","CRTR_KICKOFF_MESSAGE_IDS","CRTR_NODE_DEADLINE_AT",o]),D=["CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_CYCLES","CRTR_MODEL_INTENT","CRTR_NODE_DEADLINE_AT"];function C(e,r){const t=[];for(let R=0;R<e.length;R++)e[R]===r&&R+1<e.length&&t.push(e[++R]);return t}n(C,"argvValues");function E(e){const r=Object.entries(e.env).filter(([R])=>!l.has(R)).sort(([R],[_])=>R<_?-1:R>_?1:0),t=JSON.stringify([e.env.CRTR_NODE_CWD??null,e.env.CRTR_PROFILE_ID??null,C(e.argv,"--tools"),C(e.argv,"-e"),C(e.argv,"--append-system-prompt"),r,e.configSnapshot??null,e.scopes??null]);return T("sha256").update(t).digest("hex").slice(0,32)}n(E,"launchRecipeKey");function N(e,r){if(e===null)return!1;const t=JSON.parse(e),R=JSON.parse(r);return!Array.isArray(t.argv)||t.env===void 0||!Array.isArray(R.argv)||R.env===void 0?!1:E(t)===E(R)}n(N,"cycleCompatible");export{D as CYCLE_APPLIED_ENV,N as cycleCompatible,E as launchRecipeKey};
|
|
@@ -111,4 +111,6 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
|
|
|
111
111
|
blaxelEnvironment: string | null;
|
|
112
112
|
remoteMachine: boolean;
|
|
113
113
|
}>;
|
|
114
|
+
/** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
|
|
115
|
+
export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
|
|
114
116
|
export {};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as U}from"node:fs";import{conversationIdFromPath as _,conversationStore as h,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as he,abortExecution as F,endLiveExecution as pe,unbindSession as H,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineLaunchUncertainError as Be,MachineOfflineError as De}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as Y}from"./blaxel-environment.js";import{recordLaunchFailure as Me}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as q,remoteMachineEnvironmentOf as Te,checkBilledWake as Le,EnvironmentImagePending as ze,imageForWake as Ue}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as Ge,liveExecutionForNode as He,setExecutionLaunchJson as Ke}from"../canvas/executions.js";import{isDrained as We}from"../../daemon/drain.js";import{appMemoryFull as Je,appMemoryTooSmall as je,boundFleet as Q,brokerCapReached as Z,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Ve}from"./memory-admission.js";import{beginBootFaultAttempt as Xe,clearFault as Ye,hasAdmittedTurn as qe,readFault as Qe}from"../canvas/recovery.js";import{clearNodeLedger as I,forkNodeLedger as Ze,noticeChangedWhileDone as Ie}from"./ledger.js";import{forkSourceNode as er,rootOfSpine as rr}from"./nodes.js";import{ApiError as ir}from"../../api/errors.js";import{grantSnapshotMissing as tr}from"../../daemon/readiness.js";import{checkGrantActive as nr,checkStart as ar}from"./start-check.js";import{isReviewCompanionBound as or}from"../review/companion.js";import{assertProfileActive as sr}from"../profiles/manifest.js";import{isPidAlive as lr}from"../canvas/pid.js";import{crtrHome as cr,jobDir as ur}from"../canvas/paths.js";import{contextDir as fr,ensureNodeDirs as wr,nodeAgentDir as mr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as dr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await h().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(pr,"resumeArgs");async function ee(e){const r=_(e);if(r===null)return!1;try{return await h().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(ee,"conversationExists");async function vr(e){const r=_(e);return r===null?!0:(await h().read(r)).entries.some(i=>i.type==="message")}s(vr,"sessionHasConversation");async function _r(e){const r=_(e);if(r===null)return!0;const i=(await h().header(r)).header.cwd;return typeof i!="string"||U(i)}s(_r,"sessionCwdExists");async function yr(e,r,i,t){const a=r.pi_session_file;if(!a||!await ee(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&lr(u.pi_pid)?{}:t&&!await _r(a)?{}:await pr(r,i)}s(yr,"resumableSessionArgs");async function kr(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(kr,"isUnstartedBirth");async function wi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(wi,"hasFreshGroundState");async function mi(e,r){const i=await re(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function di(e,r,i){return re(e,{...r,viewerAttach:!0},i)}s(di,"decideAttachRevive");async function re(e,r,i){const t=Ae()?await R(e):null;return t===null?await ie(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ie(e,r,i))}s(re,"decideRevive");async function ie(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);sr(t.profile_id),ue(t.grantee);const a=Q(),u=t.grantee==="app:terminal"&&await tr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await nr(t),await ar(t),await Y(t.profile_id??null)!==null&&await Le(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new ir(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await te(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await We();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const p=!k&&await a.reserveSlot(e);let o=null;if(p){try{o=await Ve(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw je(o);if(!p||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Je(o):Z(P().automaticReviveCap,await a.occupancy());return await te(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await br(e,t,r)}}finally{a.releaseReservation(e)}}s(ie,"decideReviveAsCaller");async function te(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await pe(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(te,"freezeForWait");async function gr(e,r){const i=await Y(r.profile_id??null),t=await Te(r.profile_id??null)!==null;if(!(i!==null||t)&&!U(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(gr,"assertRecordedCwdExists");async function br(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await gr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await or(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await H(e),r.pi_session_id=null,r.pi_session_file=null);const p=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(p&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=p&&typeof o=="string";if(w&&!await ee(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ne}=P();if(t!==null){const l=await Ue(t);if(l.state==="pending")throw new ze(t,l.error)}const ae=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Q().epoch(),cap:ne,...t!==null?{runner:"blaxel",release:q()}:a?{runner:"machine",release:q()}:{}})}catch(l){if(l instanceof Ge)throw Z(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await yr(e,r,x,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await kr(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await qe(e)&&!await vr(d.resumeSessionPath)?(await E(e))?.trim():void 0,M=S!==void 0&&S!=="",oe=w||D||M,T=r.cycle_pending===!0||B;await N(e,{cycle_pending:T}),r.cycle_pending=T,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await H(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await h().header(await h().fork($,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await Ze(e,(await er(o))?.node_id??null)}else if(M)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await I(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await I(e)}c.env={...c.env,CRTR_SUBTREE:await rr(e)},m!==null&&(c.env[$e]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Ie(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Qe(e))?.op!=="conversation_write_failed"&&await Ye(e,{preserveEpisode:!0});const L=await Xe(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await wr(e,r.grantee);const se=dr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(se,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await mr(e),contextDir:await fr(e),jobDir:ur(e)},runtime:{isBirth:oe,canvasHome:cr(),profile:r.profile_id??null}}),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ke(f,z);let b;try{const n=await He(e);if(b=await ae.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof De)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
|
|
1
|
+
var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ce}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as h,ConversationNotFoundError as U}from"../conversation-store/index.js";import{isAbsolute as ue}from"node:path";import{findNodeBySessionFile as fe,getNode as R,updateNode as $,beginExecution as we,ExecutionAlreadyLive as me,recordExecutionPid as de,abortExecution as F,endLiveExecution as he,unbindSession as G,recordLaunch as pe,setFrozen as ve,clearFrozen as K,fullName as _e}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ye}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ke}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as ge,drainBearings as be,hasRetainedReports as Re,readGoal as E,readYieldMessage as Ee,RUNTIME_RESTART_CONTINUATION as xe}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Se,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as $e}from"./host.js";import{isCloudRole as Fe}from"../canvas/person.js";import{asNodePerson as Ae}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Oe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineLaunchUncertainError as Pe,MachineOfflineError as Be}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as Y}from"./blaxel-environment.js";import{recordLaunchFailure as De}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as q,remoteMachineEnvironmentOf as Me,checkBilledWake as Te,EnvironmentImagePending as Le,imageForWake as ze}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as He,liveExecutionForNode as Ue,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ke}from"../../daemon/drain.js";import{appMemoryFull as We,appMemoryTooSmall as Je,boundFleet as Q,brokerCapReached as Z,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as je}from"./memory-admission.js";import{beginBootFaultAttempt as Ve,clearFault as Xe,hasAdmittedTurn as Ye,readFault as qe}from"../canvas/recovery.js";import{clearNodeLedger as I,forkNodeLedger as Qe,noticeChangedWhileDone as Ze}from"./ledger.js";import{forkSourceNode as Ie,rootOfSpine as er}from"./nodes.js";import{ApiError as rr}from"../../api/errors.js";import{grantSnapshotMissing as ir}from"../../daemon/readiness.js";import{checkGrantActive as tr,checkStart as nr}from"./start-check.js";import{isReviewCompanionBound as ar}from"../review/companion.js";import{assertProfileActive as or}from"../profiles/manifest.js";import{isPidAlive as sr}from"../canvas/pid.js";import{crtrHome as lr,jobDir as cr}from"../canvas/paths.js";import{contextDir as ur,ensureNodeDirs as fr,nodeAgentDir as wr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as mr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as dr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await h().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof U)return{};throw a}}s(hr,"resumeArgs");async function ee(e){const r=_(e);if(r===null)return!1;try{return await h().header(r),!0}catch(i){if(i instanceof U)return!1;throw i}}s(ee,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await h().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function vr(e){const r=_(e);if(r===null)return!0;const i=(await h().header(r)).header.cwd;return typeof i!="string"||H(i)}s(vr,"sessionCwdExists");async function _r(e,r,i,t){const a=r.pi_session_file;if(!a||!await ee(a))return{};const u=await fe(a);return u!==null&&u.node_id!==e&&sr(u.pi_pid)?{}:t&&!await vr(a)?{}:await hr(r,i)}s(_r,"resumableSessionArgs");async function yr(e){return await j(e)===null&&await Ee(e)===null&&!await Re(e)}s(yr,"isUnstartedBirth");async function wi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(wi,"hasFreshGroundState");async function mi(e,r){const i=await re(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function di(e,r,i){return re(e,{...r,viewerAttach:!0},i)}s(di,"decideAttachRevive");async function re(e,r,i){const t=Fe()?await R(e):null;return t===null?await ie(e,r,i):await Ae({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ie(e,r,i))}s(re,"decideRevive");async function ie(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);or(t.profile_id),ce(t.grantee);const a=Q(),u=t.grantee==="app:terminal"&&await ir();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await tr(t),await nr(t),await Y(t.profile_id??null)!==null&&await Te(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new rr(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await te(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ke();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const p=!k&&await a.reserveSlot(e);let o=null;if(p){try{o=await je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw Je(o);if(!p||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?We(o):Z(P().automaticReviveCap,await a.occupancy());return await te(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await br(e,t,r)}}finally{a.releaseReservation(e)}}s(ie,"decideReviveAsCaller");async function te(e,r,i){r.frozen_at==null&&(await ve(e,new Date().toISOString()),await he(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(te,"freezeForWait");async function kr(e,r){const i=await Y(r.profile_id??null),t=await Me(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(kr,"assertRecordedCwdExists");async function gr(e,r,i){const t=mr(r.cwd,r.profile_id).plans.get("node:start")??[];await dr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await wr(e),contextDir:await ur(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:lr(),profile:r.profile_id??null}})}s(gr,"runNodeStartHooks");async function br(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await kr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await ar(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);const p=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(p&&(typeof o!="string"||!ue(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=p&&typeof o=="string";if(w&&!await ee(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ne}=P();if(t!==null){const l=await ze(t);if(l.state==="pending")throw new Le(t,l.error)}const ae=t!==null?X("blaxel"):a?X("machine"):Oe;let f;try{f=await we(e,{daemonEpoch:Q().epoch(),cap:ne,...t!==null?{runner:"blaxel",release:q()}:a?{runner:"machine",release:q()}:{}})}catch(l){if(l instanceof He)throw Z(l.cap,l.live);if(l instanceof me)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await _r(e,r,x,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await yr(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Ye(e)&&!await pr(d.resumeSessionPath)?(await E(e))?.trim():void 0,M=S!==void 0&&S!=="",oe=w||D||M,T=r.cycle_pending===!0||B;await $(e,{cycle_pending:T}),r.cycle_pending=T,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const se=(await h().header(await h().fork(N,e))).path;c=y(r,{resumeSessionPath:se,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await Qe(e,(await Ie(o))?.node_id??null)}else if(M)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:xe}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await I(e)}else{const n=await be(r,f);c=y(r,{...d,prompt:await ge(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await I(e)}c.env={...c.env,CRTR_SUBTREE:await er(e)},m!==null&&(c.env[Ce]=Se(m)),r.status==="done"&&r.last_settled_at!=null&&await Ze(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await qe(e))?.op!=="conversation_write_failed"&&await Xe(e,{preserveEpisode:!0});const L=await Ve(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ye(e),await fr(e,r.grantee),await gr(e,r,oe),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await $e(e,c,r.cwd);await Ge(f,z);let b;try{const n=await Ue(e);if(b=await ae.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Be)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ke(e,"notice.crash",`Child crashed \u2014 ${_e(r)} (${e}) failed to relaunch and is now dead: ${n.message}
|
|
2
2
|
|
|
3
|
-
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await
|
|
3
|
+
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await pe(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Pe||(await F(f,{reason:"launch_failed"}),await De(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(br,"launchRevive");export{kr as assertRecordedCwdExists,di as decideAttachRevive,wi as hasFreshGroundState,hr as resumeArgs,mi as reviveNode,gr as runNodeStartHooks};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import { type FileCaller } from '../spaces/permissions.js';
|
|
3
|
-
export declare function contentTypeFor(path: string): string;
|
|
4
3
|
/** An open regular file the caller may read. The caller closes `fd`. */
|
|
5
4
|
export interface CallerFile {
|
|
6
5
|
fd: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var c=(a,e)=>b(a,"name",{value:e,configurable:!0});import{closeSync as u,constants as p,createReadStream as C,fstatSync as R,realpathSync as y}from"node:fs";import{isAbsolute as N,join as w,relative as l,resolve as S,sep as h}from"node:path";import{pipeline as $}from"node:stream/promises";import{appsRoot as E,runtimeRoot as x,userRoot as O}from"../layout.js";import{RunError as d}from"../runs/operations.js";import{isBeneathRefusal as _,openBeneath as v}from"../spaces/open-beneath.js";import{fileRoot as I}from"../spaces/permissions.js";import{contentTypeFor as A}from"./media-types.js";function m(a,e){const r=l(a,e);return r===""||r!==".."&&!r.startsWith(`..${h}`)&&!r.startsWith(h)}c(m,"contains");function L(a){const e=c(n=>process.platform==="darwin"?n.toLowerCase():n,"fold"),r=e(a),o=e(E());if(m(e(x()),r)||m(e(w(O(),"memory")),r))return!0;if(!m(o,r))return!1;const t=l(o,r).split(h)[1];return t==="memory"||t==="profiles"||t==="conversations"}c(L,"withheld");function T(a,e){if(typeof e!="string"||!e)throw new d(400,"invalid_request","path is required","path");if(!N(e)||e.includes("\0"))throw new d(400,"invalid_request","path must be absolute","path");const r=S(e),o=c(()=>new d(404,"not_found",`no such file: ${r}`),"notFound");if(L(r))throw o();const t=I(a,r,"read");if("hidden"in t)throw o();if(!("root"in t))throw new d(403,"scope_missing",t.missing?`missing scope ${t.missing}`:`no permission names ${r}`,void 0,void 0,t.missing??void 0);const n=c(()=>new d(400,"invalid_request",`${r} meets a symlink, leaves its permitted root, or is not a regular file`,"path"),"symlink");let f;try{f=v(t.root,r,p.O_RDONLY|p.O_NONBLOCK)}catch(s){if(_(s))throw n();const i=s.code;throw i==="ENOENT"||i==="ENOTDIR"||i==="EISDIR"||i==="ENXIO"||i==="EACCES"||i==="EPERM"?o():s}try{if(process.platform!=="linux"){let i;try{i=y(r)}catch{throw o()}if(i!==w(y(t.root),l(t.root,r)))throw n()}const s=R(f);if(!s.isFile())throw o();return{fd:f,path:r,size:s.size}}catch(s){throw u(f),s}}c(T,"openCallerFile");function D(a,e){if(a===void 0)return null;const r=c(()=>new d(416,"range_not_satisfiable","range not satisfiable","range",{size:e}),"refuse"),o=/^bytes=(.+)$/i.exec(a.trim());if(!o)throw r();if(o[1].includes(","))return null;const t=/^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(o[1]);if(!t||t[1]===""&&t[2]==="")throw r();let n,f;if(t[1]===""){const s=Number(t[2]);if(!Number.isSafeInteger(s)||s===0||e===0)throw r();n=Math.max(0,e-s),f=e-1}else if(n=Number(t[1]),f=t[2]===""?e-1:Math.min(Number(t[2]),e-1),!Number.isSafeInteger(n)||!Number.isSafeInteger(f)||n>=e||t[2]!==""&&Number(t[2])<n)throw r();return{start:n,end:f}}c(D,"parseRange");async function j(a,e,r,o){const t=T(r,o);let n;try{const i=a.headers.range;try{n=D(Array.isArray(i)?i[0]:i,t.size)}catch(g){throw e.setHeader("Content-Range",`bytes */${t.size}`),g}}catch(i){throw u(t.fd),i}const f={"Content-Type":A(t.path),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox; default-src 'none'","Accept-Ranges":"bytes","Cache-Control":"no-store"};if(a.destroyed||e.destroyed){u(t.fd);return}if(n?e.writeHead(206,{...f,"Content-Length":String(n.end-n.start+1),"Content-Range":`bytes ${n.start}-${n.end}/${t.size}`}):e.writeHead(200,{...f,"Content-Length":String(t.size)}),t.size===0||n&&n.end<n.start){u(t.fd),e.end();return}const s=C("",{fd:t.fd,autoClose:!0,...n?{start:n.start,end:n.end}:{start:0}});try{await $(s,e)}catch{s.destroy(),e.destroy()}}c(j,"serveDownload");export{T as openCallerFile,D as parseRange,j as serveDownload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function contentTypeFor(path: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var i=(e,t)=>a(e,"name",{value:t,configurable:!0});import{extname as p}from"node:path";const o={".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".tsv":"text/tab-separated-values; charset=utf-8",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".bmp":"image/bmp",".tif":"image/tiff",".tiff":"image/tiff",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav",".ogg":"audio/ogg",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},m=new Set(["text/html","image/svg+xml","application/xhtml+xml"]);function s(e){const t=o[p(e).toLowerCase()]??"application/octet-stream";return m.has(t.split(";")[0].trim().toLowerCase())?"application/octet-stream":t}i(s,"contentTypeFor");export{s as contentTypeFor};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { FileCaller } from '../spaces/permissions.js';
|
|
2
|
+
import { type FileRow } from './tables.js';
|
|
2
3
|
export declare const SHARE_SCOPE = "crtr:files:share";
|
|
3
4
|
export interface ShareView {
|
|
4
5
|
share_id: string;
|
|
@@ -9,9 +10,8 @@ export interface ShareView {
|
|
|
9
10
|
expires_at: string | null;
|
|
10
11
|
status: 'on' | 'off';
|
|
11
12
|
}
|
|
12
|
-
/** `share.create`: freeze a copy of a file the caller may read at a public URL.
|
|
13
|
-
*
|
|
14
|
-
* row is inserted only once storage holds the bytes. */
|
|
13
|
+
/** `share.create {path}`: freeze a copy of a file the caller may read at a public URL. Without `crtr:files:share` only the caller's own app
|
|
14
|
+
* space may be shared. The row is inserted only once storage holds the bytes. */
|
|
15
15
|
export declare function createShare(caller: FileCaller, input: {
|
|
16
16
|
path: unknown;
|
|
17
17
|
expires_at?: unknown;
|
|
@@ -20,13 +20,22 @@ export declare function createShare(caller: FileCaller, input: {
|
|
|
20
20
|
url: string;
|
|
21
21
|
expires_at: string | null;
|
|
22
22
|
}>;
|
|
23
|
-
/** `share.
|
|
24
|
-
|
|
23
|
+
/** `share.create {file_id}` for a handed-over file: copy the stored object into a new share object, streaming it through this server without touching
|
|
24
|
+
* its disk. The caller has already checked the file is its own and complete. The row is inserted only once storage holds the bytes. */
|
|
25
|
+
export declare function createShareFromFile(file: FileRow, person: string | undefined, input: {
|
|
26
|
+
expires_at?: unknown;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
share_id: string;
|
|
29
|
+
url: string;
|
|
30
|
+
expires_at: string | null;
|
|
31
|
+
}>;
|
|
32
|
+
/** `share.list`: the shares `createdBy` created; on a cloud role only those of `person`. */
|
|
33
|
+
export declare function listOwnShares(createdBy: string, person?: string): Promise<{
|
|
25
34
|
shares: ShareView[];
|
|
26
35
|
}>;
|
|
27
36
|
/** `share.delete`: turn the share off, then delete its stored copy. A storage
|
|
28
37
|
* failure leaves `object_deleted_at` unset for the due-work tick to retry. */
|
|
29
|
-
export declare function deleteOwnShare(createdBy: string, shareId: string): Promise<{
|
|
38
|
+
export declare function deleteOwnShare(createdBy: string, shareId: string, person?: string): Promise<{
|
|
30
39
|
share_id: string;
|
|
31
40
|
status: 'off';
|
|
32
41
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var s=(e,t)=>O(e,"name",{value:t,configurable:!0});import{closeSync as v,read as A}from"node:fs";import{promisify as k}from"node:util";import{basename as z,relative as l,sep as h}from"node:path";import{Readable as m}from"node:stream";import{appsRoot as w,appSpace as D}from"../layout.js";import{RunError as o}from"../runs/operations.js";import{scopeAllowed as E}from"../scopes.js";import{invalidStorageName as q,storageClient as u,StorageRefused as R,UPLOAD_MAX_BYTES as C}from"./client.js";import{contentTypeFor as F}from"./media-types.js";import{openCallerFile as T}from"./download.js";import{getShare as N,insertShare as y,listShares as U,markShareObjectDeleted as B,turnShareOff as M}from"./tables.js";const f="crtr:files:share";function S(e,t){const r=l(e,t);return r===""||r!==".."&&!r.startsWith(`..${h}`)&&!r.startsWith(h)}s(S,"contains");function P(e){if(S(w(),e)){const t=l(w(),e).split(h)[0];if(t)return`app:${t}`}return"user"}s(P,"spaceOf");const b=s(e=>new o(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable"),W=k(A);async function*j(e,t){let r=0;for(;r<t;){const a=Buffer.allocUnsafe(Math.min(1048576,t-r)),{bytesRead:i}=await W(e,a,0,a.length,r);if(i===0)throw new Error("shared file shrank while it was being copied");r+=i,yield a.subarray(0,i)}}s(j,"chunks");async function g(e,t,r,a){let i;try{i=await fetch(e,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":a,"Content-Length":String(r)},body:m.toWeb(t),duplex:"half"})}catch(n){throw b(`storage could not be reached: ${n instanceof Error?n.message:String(n)}`)}finally{t.destroy()}if(await i.body?.cancel().catch(()=>{}),!i.ok)throw b(`storage answered ${i.status} to the share upload`)}s(g,"putStream");const x=s(e=>{if(e==null)return;const t=typeof e=="string"?Date.parse(e):NaN;if(!Number.isFinite(t))throw new o(400,"invalid_request","expires_at must be an ISO 8601 time","expires_at");if(t<=Date.now())throw new o(400,"invalid_request","expires_at must be in the future","expires_at");return new Date(t).toISOString()},"parseExpiry");async function ae(e,t){if(typeof t.path!="string"||!t.path)throw new o(400,"invalid_request","path is required","path");const r=x(t.expires_at),a=T(e,t.path);try{if(!E(e.resolved,f)&&!S(D(e.app).root,a.path))throw new o(403,"scope_missing",`missing scope ${f}: without it only files in the app's own space can be shared`,void 0,void 0,f);if(a.size>C)throw new o(400,"invalid_request","file exceeds 100 MiB","path");const i=z(a.path),n=q(i);if(n)throw new o(400,"invalid_request",`file name cannot be shared: ${n}`,"path");const p=F(a.path),c=u(),d=await c.createShare({name:i,media_type:p,size:a.size,...r?{expires_at:r}:{}});try{await g(d.upload_link,m.from(j(a.fd,a.size)),a.size,p)}catch($){throw await c.deleteShare(d.share_id).catch(()=>{}),$}const _=d.expires_at??r??null;return await y({share_id:d.share_id,source_space:P(a.path),source_path:a.path,storage_key:`${c.runtimeId}/shares/${d.share_id}/${i}`,url:d.url,created_by:e.app,created_at:new Date().toISOString(),expires_at:_}),{share_id:d.share_id,url:d.url,expires_at:_}}finally{v(a.fd)}}s(ae,"createShare");async function re(e,t,r){const a=x(r.expires_at),i=u(),n=await i.createShare({name:e.name,media_type:e.media_type,size:e.size,...a?{expires_at:a}:{}});try{const c=await i.fetchUpload(e.file_id,AbortSignal.timeout(11e4));await g(n.upload_link,c.body,e.size,e.media_type)}catch(c){throw await i.deleteShare(n.share_id).catch(()=>{}),c instanceof R?new o(404,"not_found","file not found"):c}const p=n.expires_at??a??null;return await y({share_id:n.share_id,source_space:`file:${e.file_id}`,source_path:e.name,storage_key:`${i.runtimeId}/shares/${n.share_id}/${e.name}`,url:n.url,created_by:e.grantee,...t===void 0?{}:{sub:t},created_at:new Date().toISOString(),expires_at:p}),{share_id:n.share_id,url:n.url,expires_at:p}}s(re,"createShareFromFile");function I(e){return{share_id:e.share_id,url:e.url,source_path:e.source_path,created_by:e.created_by,created_at:e.created_at,expires_at:e.expires_at,status:e.status}}s(I,"view");async function ie(e,t){return{shares:(await U(e)).filter(r=>t===void 0||r.sub===t).map(I)}}s(ie,"listOwnShares");async function ne(e,t,r){const a=await N(t);if(!a||a.created_by!==e||r!==void 0&&a.sub!==r)throw new o(404,"not_found","share not found");if(await M(t),!a.object_deleted_at)try{await u().deleteShare(t),await B(t)}catch(i){if(!(i instanceof o&&i.code==="storage_unavailable"))throw i}return{share_id:t,status:"off"}}s(ne,"deleteOwnShare");export{f as SHARE_SCOPE,ae as createShare,re as createShareFromFile,ne as deleteOwnShare,ie as listOwnShares};
|
|
@@ -19,6 +19,7 @@ export interface UploadUseRow {
|
|
|
19
19
|
path: string;
|
|
20
20
|
blob_key?: string | null;
|
|
21
21
|
}
|
|
22
|
+
/** `sub` is the person a cloud role's share was made for; null on a Mac and on every row written before the column existed. */
|
|
22
23
|
export interface ShareRow {
|
|
23
24
|
share_id: string;
|
|
24
25
|
source_space: string;
|
|
@@ -26,11 +27,30 @@ export interface ShareRow {
|
|
|
26
27
|
storage_key: string;
|
|
27
28
|
url: string;
|
|
28
29
|
created_by: string;
|
|
30
|
+
sub: string | null;
|
|
29
31
|
created_at: string;
|
|
30
32
|
expires_at: string | null;
|
|
31
33
|
status: 'on' | 'off';
|
|
32
34
|
object_deleted_at: string | null;
|
|
33
35
|
}
|
|
36
|
+
/** A file an agent handed to the person. Its bytes are the storage upload with the same id as `file_id`; `completed_at` is set once the API
|
|
37
|
+
* has read them back and found the declared size and sha256. `sub` is the person of a cloud role's run, null on a Mac. */
|
|
38
|
+
export interface FileRow {
|
|
39
|
+
file_id: string;
|
|
40
|
+
run_id: string;
|
|
41
|
+
node_id: string;
|
|
42
|
+
grantee: string;
|
|
43
|
+
sub: string | null;
|
|
44
|
+
name: string;
|
|
45
|
+
media_type: string;
|
|
46
|
+
size: number;
|
|
47
|
+
sha256: string;
|
|
48
|
+
created_at: string;
|
|
49
|
+
completed_at: string | null;
|
|
50
|
+
}
|
|
51
|
+
/** The `upload_uses.path` a handed-over file is recorded under: it ties the file's upload to its run, so deleting the run or removing the
|
|
52
|
+
* app releases the upload and the 24 h unused-upload sweep leaves it alone. It is not absolute, so `attachment.link` never resolves it. */
|
|
53
|
+
export declare const fileUsePath: (fileId: string) => string;
|
|
34
54
|
export declare function insertUpload(row: Omit<UploadRow, 'delete_pending_since' | 'sub'> & {
|
|
35
55
|
sub?: string;
|
|
36
56
|
}, db?: CanvasDb): Promise<void>;
|
|
@@ -54,7 +74,17 @@ export declare function uploadUseAt(path: string, db?: CanvasDb): Promise<Upload
|
|
|
54
74
|
export declare function releaseRunUploads(runIds: readonly string[], db?: CanvasDb): Promise<string[]>;
|
|
55
75
|
/** Uploads never used 24 h after creation (the tick marks them for deletion). */
|
|
56
76
|
export declare function staleUnusedUploads(before: string, db?: CanvasDb): Promise<string[]>;
|
|
57
|
-
export declare function insertShare(row: Omit<ShareRow, 'status' | 'object_deleted_at'
|
|
77
|
+
export declare function insertShare(row: Omit<ShareRow, 'status' | 'object_deleted_at' | 'sub'> & {
|
|
78
|
+
sub?: string;
|
|
79
|
+
}, db?: CanvasDb): Promise<void>;
|
|
80
|
+
export declare function insertFile(row: Omit<FileRow, 'sub' | 'completed_at'> & {
|
|
81
|
+
sub?: string;
|
|
82
|
+
}, db?: CanvasDb): Promise<void>;
|
|
83
|
+
export declare function getFile(fileId: string, db?: CanvasDb): Promise<FileRow | null>;
|
|
84
|
+
/** Mark a file complete; false when it already was (a repeated completion). */
|
|
85
|
+
export declare function completeFile(fileId: string, at?: string, db?: CanvasDb): Promise<boolean>;
|
|
86
|
+
/** Drop the file rows of the given runs (their uploads are released by `releaseRunUploads`). */
|
|
87
|
+
export declare function deleteRunFiles(runIds: readonly string[], db?: CanvasDb): Promise<void>;
|
|
58
88
|
export declare function getShare(shareId: string, db?: CanvasDb): Promise<ShareRow | null>;
|
|
59
89
|
/** Shares `created_by` owns; `null` (the person) lists every share. */
|
|
60
90
|
export declare function listShares(createdBy: string | null, db?: CanvasDb): Promise<ShareRow[]>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`).all(
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(
|
|
1
|
+
var l=Object.defineProperty;var t=(e,a)=>l(e,"name",{value:a,configurable:!0});import{openDb as E}from"../canvas/db.js";import{filterAsync as _}from"../async-array.js";const h=t(e=>`file:${e}`,"fileUsePath"),i=t(async e=>e??await E(),"handle"),p=t(()=>new Date().toISOString(),"now");async function T(e,a){await(await i(a)).prepare("INSERT INTO uploads (upload_id, grantee, sub, name, media_type, size, created_at, delete_pending_since) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)").run(e.upload_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.created_at)}t(T,"insertUpload");async function L(e,a){return await(await i(a)).prepare("SELECT * FROM uploads WHERE upload_id = ?").get(e)??null}t(L,"getUpload");async function w(e,a){await(await i(a)).prepare("DELETE FROM uploads WHERE upload_id = ?").run(e)}t(w,"deleteUploadRow");async function O(e){return await(await i(e)).prepare("SELECT * FROM uploads WHERE delete_pending_since IS NOT NULL ORDER BY delete_pending_since, upload_id").all()}t(O,"pendingUploadDeletes");async function o(e,a,n=p()){const r=(await i(a)).prepare("UPDATE uploads SET delete_pending_since = COALESCE(delete_pending_since, ?) WHERE upload_id = ?");for(const s of e)await r.run(n,s)}t(o,"markUploadsDeletePending");async function y(e,a){const n=(await i(a)).prepare("INSERT INTO upload_uses (upload_id, run_id, path, blob_key) VALUES (?, ?, ?, ?)");for(const r of e)await n.run(r.upload_id,r.run_id,r.path,r.blob_key??null)}t(y,"insertUploadUses");async function U(e,a,n){return await(await i(n)).prepare("SELECT 1 AS used FROM upload_uses WHERE run_id = ? AND path = ?").get(e,a)!==void 0}t(U,"runUsesPath");async function x(e,a){await(await i(a)).prepare("DELETE FROM upload_uses WHERE upload_id = ? AND run_id = ? AND path = ?").run(e.upload_id,e.run_id,e.path)}t(x,"deleteUploadUse");async function D(e,a,n){await(await i(n)).prepare("UPDATE uploads SET size = ? WHERE upload_id = ?").run(a,e)}t(D,"setUploadSize");async function N(e,a){return await(await i(a)).prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE path = ? ORDER BY run_id LIMIT 1").get(e)??null}t(N,"uploadUseAt");async function g(e,a){const n=await i(a);if(!e.length)return[];const r=e.map(()=>"?").join(","),s=(await n.prepareUncached(`SELECT DISTINCT upload_id FROM upload_uses WHERE run_id IN (${r})`).all(...e)).map(u=>u.upload_id);await n.prepareUncached(`DELETE FROM upload_uses WHERE run_id IN (${r})`).run(...e);const d=await _(s,async u=>!await n.prepare("SELECT 1 FROM upload_uses WHERE upload_id = ? LIMIT 1").get(u));return await o(d,n),d}t(g,"releaseRunUploads");async function m(e,a){return(await(await i(a)).prepare(`SELECT upload_id FROM uploads u WHERE delete_pending_since IS NULL AND created_at <= ?
|
|
2
|
+
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`).all(e)).map(n=>n.upload_id)}t(m,"staleUnusedUploads");async function A(e,a){await(await i(a)).prepare(`INSERT INTO shares (share_id, source_space, source_path, storage_key, url, created_by, sub, created_at, expires_at, status, object_deleted_at)
|
|
3
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(e.share_id,e.source_space,e.source_path,e.storage_key,e.url,e.created_by,e.sub??null,e.created_at,e.expires_at)}t(A,"insertShare");async function F(e,a){await(await i(a)).prepare(`INSERT INTO files (file_id, run_id, node_id, grantee, sub, name, media_type, size, sha256, created_at, completed_at)
|
|
4
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).run(e.file_id,e.run_id,e.node_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.sha256,e.created_at)}t(F,"insertFile");async function H(e,a){return await(await i(a)).prepare("SELECT * FROM files WHERE file_id = ?").get(e)??null}t(H,"getFile");async function W(e,a=p(),n){return Number((await(await i(n)).prepare("UPDATE files SET completed_at = ? WHERE file_id = ? AND completed_at IS NULL").run(a,e)).changes)>0}t(W,"completeFile");async function C(e,a){e.length&&await(await i(a)).prepareUncached(`DELETE FROM files WHERE run_id IN (${e.map(()=>"?").join(",")})`).run(...e)}t(C,"deleteRunFiles");async function b(e,a){return await(await i(a)).prepare("SELECT * FROM shares WHERE share_id = ?").get(e)??null}t(b,"getShare");async function M(e,a){return e===null?await(await i(a)).prepare("SELECT * FROM shares ORDER BY created_at DESC, share_id").all():await(await i(a)).prepare("SELECT * FROM shares WHERE created_by = ? ORDER BY created_at DESC, share_id").all(e)}t(M,"listShares");async function c(e,a){await(await i(a)).prepare("UPDATE shares SET status = 'off' WHERE share_id = ?").run(e)}t(c,"turnShareOff");async function I(e,a){const n=await i(a),r=(await n.prepare("SELECT share_id FROM shares WHERE created_by = ? AND status = 'on'").all(e)).map(s=>s.share_id);return await n.prepare("UPDATE shares SET status = 'off' WHERE created_by = ? AND status = 'on'").run(e),r}t(I,"turnSharesOffFor");async function P(e=p(),a){const n=await i(a),r=(await n.prepare("SELECT share_id FROM shares WHERE status = 'on' AND expires_at IS NOT NULL AND expires_at <= ?").all(e)).map(s=>s.share_id);for(const s of r)await c(s,n);return r}t(P,"expireShares");async function j(e){return await(await i(e)).prepare("SELECT * FROM shares WHERE status = 'off' AND object_deleted_at IS NULL ORDER BY created_at, share_id").all()}t(j,"sharesOwingObjectDelete");async function k(e,a,n=p()){await(await i(a)).prepare("UPDATE shares SET object_deleted_at = COALESCE(object_deleted_at, ?) WHERE share_id = ?").run(n,e)}t(k,"markShareObjectDeleted");async function z(e,a,n=p()){const r=await i(a),s=(await r.prepare("SELECT upload_id FROM uploads WHERE grantee = ? AND delete_pending_since IS NULL").all(e)).map(d=>d.upload_id);return await o(s,r,n),s}t(z,"markGranteeUploadsDeletePending");export{W as completeFile,C as deleteRunFiles,w as deleteUploadRow,x as deleteUploadUse,P as expireShares,h as fileUsePath,H as getFile,b as getShare,L as getUpload,F as insertFile,A as insertShare,T as insertUpload,y as insertUploadUses,M as listShares,z as markGranteeUploadsDeletePending,k as markShareObjectDeleted,o as markUploadsDeletePending,O as pendingUploadDeletes,g as releaseRunUploads,U as runUsesPath,D as setUploadSize,j as sharesOwingObjectDelete,m as staleUnusedUploads,c as turnShareOff,I as turnSharesOffFor,N as uploadUseAt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var C=Object.defineProperty;var o=(e,t)=>C(e,"name",{value:t,configurable:!0});import{canonicalSessionFile as I,findNodeBySessionFile as q,getNode as b,getNodes as M,isWarmSpare as $,recordRespawnAttempt as j,recordSettledTurn as D,setPresence as k,subscriptionsOf as L,updateNode as g,updateNodeTelemetry as U}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as x,recordExecutionIdle as W,recordExecutionPid as H}from"../../../core/canvas/executions.js";import{bindSession as G,readLiveSession as V,transferSession as J}from"../../../core/canvas/sessions.js";import{isSafeNodeId as Y}from"../../../core/canvas/paths.js";import{isPidAlive as z}from"../../../core/canvas/pid.js";import{editorLabel as S}from"../../../core/canvas/labels.js";import{assembleNodeSubject as K}from"../../../core/substrate/subject.js";import{openDb as Q,withCanvasWrite as p}from"../../../core/canvas/db.js";import{runningJobs as X}from"../../../core/graph/jobs.js";import{notFound as v,usage as u}from"../../../core/errors.js";import{hasUnseenWakeMail as P}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as Z}from"../../../core/runtime/kickoff.js";import{readRoadmap as ee}from"../../../core/runtime/roadmap.js";import{forkSourceNode as te}from"../../../core/runtime/nodes.js";import{transition as h}from"../../../core/runtime/lifecycle.js";import{confirmViewer as R,probeViewer as O,tearDownNode as F}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ne}from"../viewer-presence.js";import{evaluateStop as ie}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as re}from"../../../core/runtime/output-result.js";import{clearFault as w,readFault as oe,recordFault as ae}from"../../../core/canvas/recovery.js";import{updateModelRecipe as se}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as de}from"../../review/finish.js";import{emitEvent as A}from"../../../core/events/emit.js";import{consumePendingPark as ce,recordPendingParkActivity as ue}from"../../park-pending.js";import{shouldParkAfterSummary as le}from"../../park-activity.js";import{ownerOnly as pe}from"../router.js";import{situationalContextEnvelope as fe}from"../../../core/runtime/situational-context.js";import{requireCurrentExecution as f}from"./broker-recovery.js";import{ensureRunObserver as me}from"../../runs/observer.js";import{parseNodeTelemetryRecord as we,writeNodeTelemetryRecord as ye}from"./telemetry-record.js";import{mapAsync as he}from"../../../core/async-array.js";function l(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw u(`${t} requires a JSON body`);return e}o(l,"objectBody");function _e(e){const t=l(e,"broker session-bound");if(typeof t.executionId!="string"||t.executionId==="")throw u("executionId must be a non-empty string");if(typeof t.piSessionId!="string"||t.piSessionId==="")throw u("piSessionId must be a non-empty string");if(t.sessionFile!==null&&typeof t.sessionFile!="string")throw u("sessionFile must be a string or null");if(!Number.isSafeInteger(t.pid)||t.pid<=0)throw u("pid must be a positive safe integer");if(t.reason!==null&&typeof t.reason!="string")throw u("reason must be a string or null");if(!Array.isArray(t.reviewBoundaryIds)||!t.reviewBoundaryIds.every(n=>typeof n=="string"))throw u("reviewBoundaryIds must be an array of strings");return t}o(_e,"parseSessionBoundBody");function be(e){const t=l(e,"broker settle");if(typeof t.stopReason!="string")throw u("stopReason must be a string");for(const n of["pushedFinal"])if(typeof t[n]!="boolean")throw u(`${n} must be a boolean`);return t}o(be,"parseSettleBody");function ke(e){const t=l(e,"broker park-complete");if(t.outcome!=="completed"&&t.outcome!=="failed")throw u("outcome must be completed or failed");return t}o(ke,"parseParkCompleteBody");function ge(e){const t=l(e,"broker telemetry");if(typeof t.expected_execution_id!="string"||t.expected_execution_id==="")throw u("expected_execution_id must be a non-empty string");const n=we(t);return{...n,expected_execution_id:t.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}o(ge,"parseTelemetryBody");function ve(e){const t=l(e,"broker model");if(typeof t.spec!="string"||t.spec.trim()==="")throw u("spec must be a non-empty string");const n=t.intent;if(n!==void 0){const i=n!==null&&typeof n=="object"?n:void 0;if(i===void 0||typeof i.family!="string"||i.family===""||!["ultra","strong","medium","light"].includes(i.strength))throw u("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof t.userSelected!="boolean")throw u("userSelected must be a boolean");return t}o(ve,"parseModelCommitBody");async function m(e){const t=await b(e);if(t===null)throw v(`unknown node: ${e}`,{received:e});return t}o(m,"requireNode");async function _(e){return{node_id:e.node_id,grantee:e.grantee,name:e.name,...e.description===void 0?{}:{description:e.description},...e.title===void 0?{}:{title:e.title},...e.icon===void 0?{}:{icon:e.icon},kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,parent:e.parent??null,fork_from:e.fork_from??null,profile_id:e.profile_id??null,...e.managed_worktree===void 0?{}:{managed_worktree:e.managed_worktree===null?null:{state:e.managed_worktree.state,...e.managed_worktree.cleanup===void 0?{}:{cleanup:e.managed_worktree.cleanup},path:e.managed_worktree.path,branch:e.managed_worktree.branch,base_ref:e.managed_worktree.base_ref,base_sha:e.managed_worktree.base_sha}},...e.review_binding===void 0?{}:{review_binding:e.review_binding??null},intent:e.intent??null,...e.persona_ack===void 0?{}:{persona_ack:e.persona_ack},created:e.created}}o(_,"extensionNode");async function xe(e){const t=await m(e),n=[],i=new Set([e]);let r=t.parent??null;for(;r!==null&&r!==""&&!i.has(r);){i.add(r);const s=await b(r);if(s===null)break;n.unshift(await _(s)),r=s.parent??null}const a=await he((await M((await L(e)).map(s=>s.node_id))).filter(s=>s.kind!=="human").sort((s,y)=>s.status===y.status?0:s.status==="active"?-1:y.status==="active"?1:0),_),d=typeof t.fork_source_file=="string"?await te(t.fork_source_file):null,c=await K(e);if(c===null)throw v(`unknown node: ${e}`,{received:e});return{node:await _(t),warm_spare:await $(e),situational_card:await fe(e),ancestors:n,children:a,fork_source:d===null?null:await _(d),subject:c,roadmap:await ee(e)}}o(xe,"extensionState");function E(e,t){return e?.kind===t.kind&&e?.mode===t.mode&&e?.lifecycle===t.lifecycle}o(E,"samePersona");function Se(e){const t=l(e,"broker generated-name");if(t.kind!=="initial"&&t.kind!=="recap")throw u("kind must be initial or recap");if(typeof t.description!="string"||typeof t.title!="string"||typeof t.icon!="string")throw u("description, title, and icon must be strings");if(t.kind==="initial")return t;const n=t.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(i=>typeof n[i]!="string"))throw u("recap expected must contain name, description, title, icon, and kind strings");return t}o(Se,"parseGeneratedNameBody");function Pe(e){const t=l(e,"broker persona-ack"),n=o(i=>{const r=t[i];if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.kind!="string"||r.mode!=="base"&&r.mode!=="orchestrator"||r.lifecycle!=="terminal"&&r.lifecycle!=="resident")throw u(`${i} must be a persona state`);return r},"parse");return{expected_execution_id:t.expected_execution_id,from:n("from"),to:n("to")}}o(Pe,"parsePersonaAckBody");async function Re(e){const t=e.params.id,n=_e(e.body),i=n.sessionFile===null?null:I(n.sessionFile);return{status:200,body:await p(async a=>{await a.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const d=await m(t);if(await H(n.executionId,t,n.pid)==="shutdown")return{action:"shutdown"};const c=d.review_binding?.review_id;if(c!==void 0&&!n.reviewBoundaryIds.includes(c))return{action:"shutdown"};if(n.reason==="new"&&d.parent==null)return{action:"relaunch_root"};if(n.reason!=="new"&&d.fork_from!=null&&d.pi_session_id==null&&i===null)return{action:"shutdown"};const s=i===null?null:await q(i);if(s!==null&&s.node_id!==t){if(z(s.pi_pid))return await ae(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${i}: it is owned by live node ${s.node_id}`}),{action:"shutdown"};const y=await V(s.node_id);if(y===null||await J({fromNodeId:s.node_id,fromBindingId:y.bindingId,toNodeId:t,executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})!=="transferred")return{action:"shutdown"}}else if(await G(t,{executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})==="shutdown")return{action:"shutdown"};return n.reason!=="new"&&(await Z(t),d.intent==="refresh"&&await h(t,"revive")),{action:"none"}})}}o(Re,"handleSessionBound");async function T(e,t){return t.live!==null||await ne(e)||await P(e)}o(T,"isHeldAwake");async function B(e,t){return(await x(e))?.runner==="blaxel"&&!await T(e,t)&&(await X(await Q(),e)).length===0}o(B,"residentBlaxelCanIdle");async function Oe(e,t,n){const i=await b(e);if(i===null){if(t.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw v(`unknown node: ${e}`,{received:e})}if(await D(e,new Date().toISOString()),(t.stopReason==="stop"||t.stopReason==="length")&&await j(e,{failures:0,notBefore:null}),t.stopReason==="quit"){let c=!1;return(i.status==="active"||i.status==="idle")&&i.intent===null&&(await h(e,"finish"),await w(e),await k(e,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(t.stopReason!=="stop"&&t.stopReason!=="length")return await w(e,{link:"daemon\u2192node"}),i.intent==="refresh"?{directive:{action:"shutdown"},closePane:!1}:t.stopReason==="error"&&t.faultSettled===!0&&(await oe(e))?.retry.disposition==="fatal"&&await re(e)===null&&await B(e,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const r={pushedFinal:t.pushedFinal};if(r.pushedFinal||i.status==="done")return await w(e),await k(e,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(i.intent==="refresh")return await w(e),{directive:{action:"shutdown"},closePane:!1};const a=await ie(e,r);if(await w(e),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await P(e)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const d=await T(e,n);return(await x(e))?.runner==="blaxel"?{directive:await B(e,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:d?{directive:{action:"stay_dormant"},closePane:!1}:(await h(e,"release"),{directive:{action:"shutdown"},closePane:!1})}o(Oe,"settleBroker");async function Fe(e){const t=e.params.id,n=l(e.body,"broker idle");return await f(t,n.expected_execution_id),await W(n.expected_execution_id),{status:204}}o(Fe,"handleIdle");async function Ae(e){const t=e.params.id,n=be(e.body);await f(t,n.expected_execution_id);const i=await O(t),{directive:r,closePane:a}=await p(async()=>await Oe(t,n,await R(i)));return a&&await F(t),r.action!=="reprompt"&&de(t).catch(d=>A({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:t,error:d})),{status:200,body:r}}o(Ae,"handleSettle");async function Ee(e){const t=e.params.id,n=ke(e.body);await f(t,n.expected_execution_id);const i=await O(t),r=await p(async()=>{const a=await ce(t);if(a===void 0)return{action:"stay_dormant"};const d=await m(t);return await le(t,d,a,await R(i))?(await w(t),await h(t,"park"),await k(t,{pane:null,tmux_session:null,window:null}),A({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...Y(t)?{node_id:t}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return r.action==="shutdown"&&await F(t),{status:200,body:r}}o(Ee,"handleParkComplete");async function Te(e){const t=e.params.id;return await f(t,l(e.body,"broker park-activity").expected_execution_id),{status:200,body:await p(async()=>({activity:await ue(t)?"recorded":"none"}))}}o(Te,"handleParkActivity");async function Be(e){const t=e.params.id,n=ge(e.body);return await f(t,n.expected_execution_id),await p(async()=>{await U(t,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),ye(t,n)}),{status:204}}o(Be,"handleTelemetry");async function Ne(e){const t=e.params.id,n=ve(e.body);return await f(t,n.expected_execution_id),{status:200,body:{modelOverride:(await p(async()=>await se(await m(t),n.spec,n.intent,n.userSelected))).model_override}}}o(Ne,"handleModelCommit");let N=!0;function wt(e){N=e}o(wt,"setRequestsStartRunObservers");async function Ce(e){const t=e.params.id,n=await m(t);return n.run_id&&N&&await me(t,n.run_id),{status:200,body:await xe(t)}}o(Ce,"handleExtensionState");async function Ie(e){const t=e.params.id,n=Se(e.body);return await f(t,n.expected_execution_id),{status:200,body:await p(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const a=await m(t);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const s=await g(t,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:S(s),description:s.description??"",title:s.title??"",icon:s.icon??""}}const d=n.expected;if(a.name!==d.name||(a.description??"")!==d.description||(a.title??"")!==d.title||(a.icon??"")!==d.icon||a.kind!==d.kind)return{applied:!1};const c=await g(t,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:S(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}o(Ie,"handleGeneratedName");async function qe(e){const t=e.params.id,n=Pe(e.body);return await f(t,n.expected_execution_id),{status:200,body:await p(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const a=await m(t),d={kind:a.kind,mode:a.mode,lifecycle:a.lifecycle},c=a.persona_ack,s=c===void 0?d:{kind:c.kind??a.kind,mode:c.mode,lifecycle:c.lifecycle};return!E(d,n.to)||!E(s,n.from)?{applied:!1}:(await g(t,{persona_ack:n.to}),{applied:!0})})}}o(qe,"handlePersonaAck");const yt=pe([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:Re},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:Ae},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:Fe},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:Ee},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:Te},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:Be},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:Ne},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:Ce},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:Ie},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:qe}]);export{yt as brokerOperationRoutes,_ as extensionNode,wt as setRequestsStartRunObservers};
|
|
1
|
+
var D=Object.defineProperty;var a=(t,e)=>D(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as M,findNodeBySessionFile as V,getNode as k,getNodes as $,isWarmSpare as I,recordLaunch as j,recordRespawnAttempt as q,recordSettledTurn as U,setPresence as g,subscriptionsOf as W,updateNode as h,updateNodeTelemetry as H}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as v,recordExecutionIdle as J,recordExecutionPid as G}from"../../../core/canvas/executions.js";import{bindSession as Y,readLiveSession as K,transferSession as z}from"../../../core/canvas/sessions.js";import{isSafeNodeId as Q}from"../../../core/canvas/paths.js";import{isPidAlive as X}from"../../../core/canvas/pid.js";import{editorLabel as x}from"../../../core/canvas/labels.js";import{assembleNodeSubject as Z}from"../../../core/substrate/subject.js";import{openDb as ee,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as te}from"../../../core/graph/jobs.js";import{notFound as S,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as P,releaseExecutionMail as ne}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ie}from"../../../core/runtime/kickoff.js";import{readRoadmap as re}from"../../../core/runtime/roadmap.js";import{forkSourceNode as oe}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as R,probeViewer as E,tearDownNode as O}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ae}from"../viewer-presence.js";import{evaluateStop as se}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as ce}from"../../../core/runtime/output-result.js";import{clearFault as w,readFault as de,recordFault as le}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ue}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as pe}from"../../review/finish.js";import{emitEvent as A}from"../../../core/events/emit.js";import{consumePendingPark as fe,recordPendingParkActivity as me}from"../../park-pending.js";import{shouldParkAfterSummary as we}from"../../park-activity.js";import{ownerOnly as ye}from"../router.js";import{situationalContextEnvelope as he}from"../../../core/runtime/situational-context.js";import{requireCurrentExecution as p}from"./broker-recovery.js";import{ensureRunObserver as _e}from"../../runs/observer.js";import{parseNodeTelemetryRecord as be,writeNodeTelemetryRecord as ke}from"./telemetry-record.js";import{mapAsync as ge}from"../../../core/async-array.js";import{crtrVersion as T}from"../../../shared/crtr-version.js";import{buildPiArgv as ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as xe}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as Se,cycleCompatible as Pe}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Re,drainBearings as Ee}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Oe}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ae}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Te}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Fe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Ne}from"../../../api/errors.js";function u(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}a(u,"objectBody");function Be(t){const e=u(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}a(Be,"parseSessionBoundBody");function Ce(t){const e=u(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}a(Ce,"parseSettleBody");function Le(t){const e=u(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}a(Le,"parseCycleBody");function De(t){const e=u(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}a(De,"parseParkCompleteBody");function Me(t){const e=u(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=be(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}a(Me,"parseTelemetryBody");function Ve(t){const e=u(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const i=n!==null&&typeof n=="object"?n:void 0;if(i===void 0||typeof i.family!="string"||i.family===""||!["ultra","strong","medium","light"].includes(i.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}a(Ve,"parseModelCommitBody");async function m(t){const e=await k(t);if(e===null)throw S(`unknown node: ${t}`,{received:t});return e}a(m,"requireNode");async function b(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}a(b,"extensionNode");async function $e(t){const e=await m(t),n=[],i=new Set([t]);let r=e.parent??null;for(;r!==null&&r!==""&&!i.has(r);){i.add(r);const c=await k(r);if(c===null)break;n.unshift(await b(c)),r=c.parent??null}const o=await ge((await $((await W(t)).map(c=>c.node_id))).filter(c=>c.kind!=="human").sort((c,y)=>c.status===y.status?0:c.status==="active"?-1:y.status==="active"?1:0),b),s=typeof e.fork_source_file=="string"?await oe(e.fork_source_file):null,d=await Z(t);if(d===null)throw S(`unknown node: ${t}`,{received:t});return{node:await b(e),warm_spare:await I(t),situational_card:await he(t),ancestors:n,children:o,fork_source:s===null?null:await b(s),subject:d,roadmap:await re(t)}}a($e,"extensionState");function F(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}a(F,"samePersona");function Ie(t){const e=u(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(i=>typeof n[i]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}a(Ie,"parseGeneratedNameBody");function je(t){const e=u(t,"broker persona-ack"),n=a(i=>{const r=e[i];if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.kind!="string"||r.mode!=="base"&&r.mode!=="orchestrator"||r.lifecycle!=="terminal"&&r.lifecycle!=="resident")throw l(`${i} must be a persona state`);return r},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}a(je,"parsePersonaAckBody");async function qe(t){const e=t.params.id,n=Be(t.body),i=n.sessionFile===null?null:M(n.sessionFile);return{status:200,body:await f(async o=>{await o.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const s=await m(e);if(await G(n.executionId,e,n.pid)==="shutdown")return{action:"shutdown"};const d=s.review_binding?.review_id;if(d!==void 0&&!n.reviewBoundaryIds.includes(d))return{action:"shutdown"};if(n.reason==="new"&&s.parent==null)return{action:"relaunch_root"};if(n.reason!=="new"&&s.fork_from!=null&&s.pi_session_id==null&&i===null)return{action:"shutdown"};const c=i===null?null:await V(i);if(c!==null&&c.node_id!==e){if(X(c.pi_pid))return await le(e,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${i}: it is owned by live node ${c.node_id}`}),{action:"shutdown"};const y=await K(c.node_id);if(y===null||await z({fromNodeId:c.node_id,fromBindingId:y.bindingId,toNodeId:e,executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})!=="transferred")return{action:"shutdown"}}else if(await Y(e,{executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})==="shutdown")return{action:"shutdown"};return n.reason!=="new"&&(await ie(e),s.intent==="refresh"&&await _(e,"revive")),{action:"none"}})}}a(qe,"handleSessionBound");async function N(t,e){return e.live!==null||await ae(t)||await P(t)}a(N,"isHeldAwake");async function B(t,e){return(await v(t))?.runner==="blaxel"&&!await N(t,e)&&(await te(await ee(),t)).length===0}a(B,"residentBlaxelCanIdle");function C(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}a(C,"refreshDirective");async function Ue(t,e,n){const i=await k(t);if(i===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw S(`unknown node: ${t}`,{received:t})}if(await U(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let d=!1;return(i.status==="active"||i.status==="idle")&&i.intent===null&&(await _(t,"finish"),await w(t),await g(t,{pane:null,tmux_session:null,window:null}),d=!0),{directive:{action:"shutdown"},closePane:d}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await w(t,{link:"daemon\u2192node"}),i.intent==="refresh"?{directive:C(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await de(t))?.retry.disposition==="fatal"&&await ce(t)===null&&await B(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const r={pushedFinal:e.pushedFinal};if(r.pushedFinal||i.status==="done")return await w(t),await g(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(i.intent==="refresh")return await w(t),{directive:C(e),closePane:!1};const o=await se(t,r);if(await w(t),o.action==="reprompt")return{directive:{action:"reprompt",prompt:o.message},closePane:!1};if(o.reason==="finished")return{directive:await P(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const s=await N(t,n);return(await v(t))?.runner==="blaxel"?{directive:await B(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:o.reason!=="awaiting"&&o.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:s?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}a(Ue,"settleBroker");async function We(t){const e=t.params.id,n=Le(t.body);await p(e,n.expected_execution_id);const i=await m(e);if(i.intent!=="refresh")throw new Ne(409,"not_yielding",`${e} has no pending yield`);const r=await v(e),o=ve(i);return n.brokerVersion===T()&&(r.release===null||r.release===T())&&Pe(r.launchJson,await xe(e,o,i.cwd))?{status:200,body:await He(e,i,r.executionId,o.env)}:{status:200,body:{action:"restart"}}}a(We,"handleCycle");async function He(t,e,n,i){e.cycles=(e.cycles??0)+1,await ne(t,n);const r=await Ee(e,n),o=await Re(e,r);await Oe(t),await Ae(t,e,!1),await Te(t),await w(t,{preserveEpisode:!0}),await j(t,new Date().toISOString()),await h(t,{cycles:e.cycles,cycle_pending:!0});const s={};for(const d of Se)i[d]!==void 0&&(s[d]=i[d]);return s.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:o,origin:Fe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?r.unreadMessageIds??[]:[],env:s,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:x(e)}}a(He,"startCycleRecord");async function Je(t){const e=t.params.id,n=u(t.body,"broker idle");return await p(e,n.expected_execution_id),await J(n.expected_execution_id),{status:204}}a(Je,"handleIdle");async function Ge(t){const e=t.params.id,n=Ce(t.body);await p(e,n.expected_execution_id);const i=await E(e),{directive:r,closePane:o}=await f(async()=>await Ue(e,n,await R(i)));return o&&await O(e),r.action!=="reprompt"&&pe(e).catch(s=>A({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:s})),{status:200,body:r}}a(Ge,"handleSettle");async function Ye(t){const e=t.params.id,n=De(t.body);await p(e,n.expected_execution_id);const i=await E(e),r=await f(async()=>{const o=await fe(e);if(o===void 0)return{action:"stay_dormant"};const s=await m(e);return await we(e,s,o,await R(i))?(await w(e),await _(e,"park"),await g(e,{pane:null,tmux_session:null,window:null}),A({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...Q(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return r.action==="shutdown"&&await O(e),{status:200,body:r}}a(Ye,"handleParkComplete");async function Ke(t){const e=t.params.id;return await p(e,u(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await me(e)?"recorded":"none"}))}}a(Ke,"handleParkActivity");async function ze(t){const e=t.params.id,n=Me(t.body);return await p(e,n.expected_execution_id),await f(async()=>{await H(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),ke(e,n)}),{status:204}}a(ze,"handleTelemetry");async function Qe(t){const e=t.params.id,n=Ve(t.body);return await p(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await ue(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}a(Qe,"handleModelCommit");let L=!0;function Ut(t){L=t}a(Ut,"setRequestsStartRunObservers");async function Xe(t){const e=t.params.id,n=await m(e);return n.run_id&&L&&await _e(e,n.run_id),{status:200,body:await $e(e)}}a(Xe,"handleExtensionState");async function Ze(t){const e=t.params.id,n=Ie(t.body);return await p(e,n.expected_execution_id),{status:200,body:await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const o=await m(e);if(n.kind==="initial"){if((o.description??"").trim()!=="")return{applied:!1};const c=await h(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:x(c),description:c.description??"",title:c.title??"",icon:c.icon??""}}const s=n.expected;if(o.name!==s.name||(o.description??"")!==s.description||(o.title??"")!==s.title||(o.icon??"")!==s.icon||o.kind!==s.kind)return{applied:!1};const d=await h(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:x(d),description:d.description??"",title:d.title??"",icon:d.icon??""}})}}a(Ze,"handleGeneratedName");async function et(t){const e=t.params.id,n=je(t.body);return await p(e,n.expected_execution_id),{status:200,body:await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const o=await m(e),s={kind:o.kind,mode:o.mode,lifecycle:o.lifecycle},d=o.persona_ack,c=d===void 0?s:{kind:d.kind??o.kind,mode:d.mode,lifecycle:d.lifecycle};return!F(s,n.to)||!F(c,n.from)?{applied:!1}:(await h(e,{persona_ack:n.to}),{applied:!0})})}}a(et,"handlePersonaAck");const Wt=ye([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:qe},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:Ge},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:We},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:Je},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:Ye},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:Ke},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ze},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:Qe},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:Xe},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:et}]);export{Wt as brokerOperationRoutes,b as extensionNode,Ut as setRequestsStartRunObservers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var w=Object.defineProperty;var p=(i,n)=>w(i,"name",{value:n,configurable:!0});import{createHash as y}from"node:crypto";import{Writable as g}from"node:stream";import{pipeline as b}from"node:stream/promises";import{ApiError as a}from"../../../api/index.js";import{withCanvasWrite as _}from"../../../core/canvas/db.js";import{getNode as m}from"../../../core/canvas/canvas.js";import{RunError as v,cloudPersonScope as S}from"../../../core/runs/operations.js";import{appendRunEvent as z}from"../../../core/runs/events.js";import{invalidStorageName as q,storageClient as c,StorageRefused as A,UPLOAD_MAX_BYTES as I}from"../../../core/storage/client.js";import{completeFile as E,fileUsePath as U,getFile as O,insertFile as P,insertUploadUses as T,insertUpload as $}from"../../../core/storage/tables.js";const k=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(?:\s*;.{0,200})?$/,C=/^[0-9a-f]{64}$/,M=11e4;async function h(i){const n=i.params.id;if(i.principal.class!=="broker"||i.principal.node!==n)throw new a(403,"permission_error","only this node\u2019s broker may hand over a file");const e=await m(n),o=i.principal.run;if(e===null||o===null||e.run_id!==o||!e.grantee)throw new a(400,"invalid_request","this node belongs to no app run, so there is no one to hand a file to");const r=await m(o);if(r===null||r.event_cursor===null||r.event_cursor===void 0)throw new a(400,"invalid_request","this node\u2019s run has no event stream, so there is no app to hand a file to");return{nodeId:n,runId:o,grantee:e.grantee,person:S(i.principal.sub)}}p(h,"callerRun");function R(i){if(!i||typeof i!="object"||Array.isArray(i))throw new a(400,"invalid_request","a JSON object is required");return i}p(R,"object");async function j(i){const n=await h(i),e=R(i.body);for(const s of Object.keys(e))if(!["name","media_type","size","sha256"].includes(s))throw new a(400,"invalid_request",`unknown field ${s}`);const{name:o,media_type:r,size:d,sha256:l}=e;if(typeof o!="string")throw new a(400,"invalid_request","name is required");const f=q(o);if(f)throw new a(400,"invalid_request",f);if(typeof r!="string"||!k.test(r))throw new a(400,"invalid_request","media_type must be a media type");if(typeof d!="number"||!Number.isSafeInteger(d)||d<0)throw new a(400,"invalid_request","size must be a non-negative integer");if(d>I)throw new a(400,"invalid_request","file exceeds 100 MiB");if(typeof l!="string"||!C.test(l))throw new a(400,"invalid_request","sha256 must be 64 lowercase hex digits");const t=await c().createUpload({name:o,media_type:r,size:d}),u=new Date().toISOString();return await _(async s=>{await $({upload_id:t.upload_id,grantee:n.grantee,...n.person===void 0?{}:{sub:n.person},name:o,media_type:r,size:d,created_at:u},s),await T([{upload_id:t.upload_id,run_id:n.runId,path:U(t.upload_id)}],s),await P({file_id:t.upload_id,run_id:n.runId,node_id:n.nodeId,grantee:n.grantee,...n.person===void 0?{}:{sub:n.person},name:o,media_type:r,size:d,sha256:l,created_at:u},s)}),{status:201,body:{file_id:t.upload_id,upload_link:t.upload_link,expires_at:t.expires_at}}}p(j,"handleCreate");async function D(i){const n=await h(i),e=await O(i.params.fileId);if(!e||e.node_id!==n.nodeId)throw new a(404,"not_found","file not found");const o=p(()=>({status:200,body:{file_id:e.file_id,name:e.name,media_type:e.media_type,size:e.size}}),"done");if(e.completed_at)return o();const r=AbortSignal.timeout(M);let d;try{d=await c().fetchUpload(e.file_id,r)}catch(t){throw t instanceof A?new a(409,"file_not_uploaded","the file bytes have not been uploaded"):t}const l=y("sha256");let f=0;try{await b(d.body,new g({write(t,u,s){l.update(t),f+=t.length,s()}}),{signal:r})}catch(t){throw new v(503,"storage_unavailable",`storage stopped sending the file: ${t instanceof Error?t.message:String(t)}`,void 0,void 0,void 0,!0)}if(f!==e.size||l.digest("hex")!==e.sha256)throw new a(409,"file_mismatch","the stored bytes do not match the declared size and sha256; hand the file over again");return await _(async t=>{await E(e.file_id,void 0,t)&&await z(t,e.run_id,e.node_id,"file.sent",{file_id:e.file_id,name:e.name,media_type:e.media_type,size:e.size})}),o()}p(D,"handleComplete");const K=[{method:"POST",pattern:"/v1/nodes/:id/files",handler:j},{method:"POST",pattern:"/v1/nodes/:id/files/:fileId/complete",handler:D}];export{K as nodeFileRoutes};
|
|
@@ -6,10 +6,10 @@ import type { AppPrincipal } from '../principal.js';
|
|
|
6
6
|
export declare const TRANSFER_OPERATIONS: Set<string>;
|
|
7
7
|
/** An app caller's file permission: its grant, with no narrower launched list. */
|
|
8
8
|
export declare function fileCaller(caller: AppPrincipal): FileCaller;
|
|
9
|
-
/** JSON rows. `
|
|
9
|
+
/** JSON rows. A person's rows are cut by `AppPrincipal.sub` on a cloud role (`cloudPersonScope`); a Mac holds one person. */
|
|
10
10
|
export declare function handleTransferOperation(operation: AppOperation, caller: AppPrincipal, params: Record<string, string>, query: URLSearchParams, body: unknown): Promise<{
|
|
11
11
|
status: number;
|
|
12
12
|
body: unknown;
|
|
13
13
|
}>;
|
|
14
|
-
/** `file.download` (`stream: 'bytes'`): raw bytes with `Range` support. */
|
|
14
|
+
/** `file.download` (`stream: 'bytes'`): raw bytes with `Range` support, by path. */
|
|
15
15
|
export declare function handleTransferDownload(req: IncomingMessage, res: ServerResponse, caller: AppPrincipal, query: URLSearchParams): Promise<void>;
|