@north-light/cli 0.3.661 → 0.3.663

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.
Files changed (35) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/run-events.d.ts +13 -0
  4. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +2 -0
  5. package/dist/clients/attach/viewer.js +1 -1
  6. package/dist/core/canvas/schema-pg/020-machine-calls-status-all.sql +8 -0
  7. package/dist/core/canvas/schema-version.d.ts +1 -1
  8. package/dist/core/canvas/schema-version.js +1 -1
  9. package/dist/core/runs/operations.js +9 -7
  10. package/dist/core/runtime/runner/machine/call.js +2 -2
  11. package/dist/core/runtime/runner/machine/executor.d.ts +7 -0
  12. package/dist/core/runtime/runner/machine/executor.js +1 -1
  13. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  14. package/dist/core/runtime/runner/machine/ops.d.ts +14 -1
  15. package/dist/core/runtime/runner/machine/ops.js +1 -1
  16. package/dist/daemon/broker-signals/bus.d.ts +3 -2
  17. package/dist/daemon/broker-signals/bus.js +1 -1
  18. package/dist/daemon/crtrd.d.ts +4 -0
  19. package/dist/daemon/crtrd.js +12 -12
  20. package/dist/daemon/machine-daemon.js +1 -1
  21. package/dist/daemon/machine-link/client.d.ts +9 -0
  22. package/dist/daemon/machine-link/client.js +1 -1
  23. package/dist/daemon/machine-link/frames.d.ts +8 -0
  24. package/dist/daemon/machine-link/frames.js +1 -1
  25. package/dist/daemon/machine-link/holder.d.ts +11 -0
  26. package/dist/daemon/machine-link/holder.js +4 -4
  27. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  28. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +5 -0
  29. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +4 -0
  30. package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +3 -0
  31. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  32. package/docs/apps/guides/stream-a-run.md +2 -0
  33. package/package.json +2 -2
  34. package/packages/crouter-identity/package.json +1 -1
  35. package/runtime.lock.json +13 -13
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=19;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=20;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1,14 +1,16 @@
1
- var Ae=Object.defineProperty;var c=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as V}from"node:crypto";import{ApiError as Te}from"../../api/errors.js";import{CrtrError as Le}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as Z,relative as ke,resolve as xe,sep as We,join as Fe}from"node:path";import{SessionManager as qe}from"@earendil-works/pi-coding-agent";import{covers as B}from"@north-light/identity";import{openDb as j,withCanvasWrite as q}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as K}from"../canvas/sessions.js";import{getNode as b,nodeFiles as $e,removeNodeFiles as Pe,updateNode as Be}from"../canvas/canvas.js";import{fullName as je}from"../canvas/labels.js";import{renameWindow as Je}from"../runtime/placement.js";import{liveExecutionForNode as ee}from"../canvas/executions.js";import{conversationStore as te,isConversationNotFound as Ye}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ge}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Xe}from"../canvas/deliveries.js";import{readNodeRecap as ze}from"../canvas/node-recap.js";import{enqueueNodeMail as Qe}from"../feed/messages.js";import{recordInitialInput as Ve}from"./initial-input.js";import{newestReportBody as Ze}from"../feed/reports.js";import{ensureAppProfile as ne,loadExactProfileManifest as ae}from"../profiles/manifest.js";import{stopNodeSandboxes as se}from"../spaces/stop.js";import{deleteNodeSandboxes as Ke}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as et}from"../runtime/broker-request.js";import{interruptLive as tt}from"../runtime/interactive-deliver.js";import{isBrokerLive as ie}from"../runtime/model-swap.js";import{newNodeId as nt}from"../runtime/nodes.js";import{reviveNode as J}from"../runtime/revive.js";import{spawnChildPrepared as at}from"../runtime/spawn.js";import{isPortableModelToken as st}from"../runtime/launch.js";import{parseDurationMs as it}from"../wake.js";import{expandModelCandidates as rt,parseModelSpec as ot}from"../model-routes.js";import{payerOfGrant as Y}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as dt}from"../runtime/host.js";import{blaxelEnvironmentOf as ct}from"../runtime/blaxel-environment.js";import{resolveRunKind as ut,resolveRunModel as mt}from"../runtime/launch-target.js";import{cycleAwareMessages as lt}from"../runtime/session-cycles.js";import{originFor as re}from"../runtime/stamp/protocol.js";import{readOutputRequest as ft,readOutputResult as oe}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as de}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as pt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as _t}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as wt}from"../../daemon/runs/observer.js";import{closeNode as ce}from"../runtime/close.js";import{parseScope as gt}from"@north-light/identity";import{appendRunEvent as ue,lockRunRoot as Et,subscribeRunEvents as yt}from"./events.js";import{runActivity as ht}from"./activity.js";import{cancelOpenQuestions as me,openNoticeIds as Rt,openQuestionIds as le}from"./questions.js";import{appSpace as G}from"../layout.js";import{ensureAppSpace as St}from"../spaces/space.js";import{assertUploadsUsable as fe,resolveStorageUrls as Nt}from"../storage/attachments.js";import{storageClient as bt,storageConfig as vt}from"../storage/client.js";import{deleteRunFiles as Ot,deleteUploadRow as Dt,insertUploadUses as pe,releaseRunUploads as Mt,runUsesPath as At}from"../storage/tables.js";import{abortProviderCalls as _e}from"../providers/inflight.js";import{filterAsync as we,mapAsync as W}from"../async-array.js";import{blobStore as It}from"../blobs/index.js";import{emitEvent as Tt}from"../events/emit.js";const ge=c((e,t,a,n,d)=>Nt(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),Lt=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,f,r,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=f,this.scope=r,this.retryable=s}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),X=c(()=>new R(404,"not_found","run not found"),"missing"),z=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),M=c(async()=>await j(),"db");async function H(e,t,a=!1){const n=await b(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw X();return n}c(H,"ownedRun");const Ee=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await M()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var Ie=Object.defineProperty;var c=(e,t)=>Ie(e,"name",{value:t,configurable:!0});import{coveredByAny as Te}from"../../shared/env.js";import{createHash as K}from"node:crypto";import{ApiError as Le}from"../../api/errors.js";import{CrtrError as Ce}from"../errors.js";import{isCloudRole as ke}from"../canvas/person.js";import{isAbsolute as ee,relative as xe,resolve as We,sep as qe,join as Fe}from"node:path";import{SessionManager as He}from"@earendil-works/pi-coding-agent";import{covers as J}from"@north-light/identity";import{openDb as Y,withCanvasWrite as U}from"../canvas/db.js";import{deleteNodeWithOwned as Ue}from"../graph/deletion.js";import{getById as $e}from"../graph/objects.js";import{repairRunConversations as te}from"../canvas/sessions.js";import{getNode as v,nodeFiles as Pe,removeNodeFiles as Be,updateNode as je}from"../canvas/canvas.js";import{fullName as Je}from"../canvas/labels.js";import{renameWindow as Ye}from"../runtime/placement.js";import{liveExecutionForNode as ne}from"../canvas/executions.js";import{conversationStore as se,isConversationNotFound as Ge}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Xe}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as ze}from"../canvas/deliveries.js";import{readNodeRecap as Qe}from"../canvas/node-recap.js";import{enqueueNodeMail as Ve}from"../feed/messages.js";import{recordInitialInput as Ze}from"./initial-input.js";import{newestReportBody as Ke}from"../feed/reports.js";import{ensureAppProfile as ae,loadExactProfileManifest as ie}from"../profiles/manifest.js";import{stopNodeSandboxes as re}from"../spaces/stop.js";import{deleteNodeSandboxes as et}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as tt}from"../runtime/broker-request.js";import{interruptLive as nt}from"../runtime/interactive-deliver.js";import{isBrokerLive as oe}from"../runtime/model-swap.js";import{newNodeId as st}from"../runtime/nodes.js";import{reviveNode as G}from"../runtime/revive.js";import{spawnChildPrepared as at}from"../runtime/spawn.js";import{isPortableModelToken as it}from"../runtime/launch.js";import{parseDurationMs as rt}from"../wake.js";import{expandModelCandidates as ot,parseModelSpec as dt}from"../model-routes.js";import{payerOfGrant as X}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as ct}from"../runtime/host.js";import{blaxelEnvironmentOf as ut}from"../runtime/blaxel-environment.js";import{resolveRunKind as mt,resolveRunModel as lt}from"../runtime/launch-target.js";import{cycleAwareMessages as ft}from"../runtime/session-cycles.js";import{originFor as de}from"../runtime/stamp/protocol.js";import{readOutputRequest as _t,readOutputResult as ce}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as ue}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as pt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as wt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as gt}from"../../daemon/runs/observer.js";import{closeNode as me}from"../runtime/close.js";import{parseScope as Et}from"@north-light/identity";import{appendRunEvent as le,lockRunRoot as yt,subscribeRunEvents as ht}from"./events.js";import{runActivity as Rt}from"./activity.js";import{cancelOpenQuestions as fe,openNoticeIds as St,openQuestionIds as _e}from"./questions.js";import{appSpace as z}from"../layout.js";import{ensureAppSpace as Nt}from"../spaces/space.js";import{assertUploadsUsable as pe,resolveStorageUrls as bt}from"../storage/attachments.js";import{storageClient as vt,storageConfig as Ot}from"../storage/client.js";import{deleteRunFiles as Dt,deleteUploadRow as Mt,insertUploadUses as we,releaseRunUploads as At,runUsesPath as It}from"../storage/tables.js";import{abortProviderCalls as ge}from"../providers/inflight.js";import{filterAsync as Ee,mapAsync as F}from"../async-array.js";import{blobStore as Tt}from"../blobs/index.js";import{emitEvent as Lt}from"../events/emit.js";const ye=c((e,t,s,n,d)=>bt(t,d,e,s,n?{taken:n}:{}),"defaultResolver"),Ct=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,s,n,d,f,r,i=t===503){super(n),this.status=t,this.code=s,this.param=d,this.details=f,this.scope=r,this.retryable=i}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),Q=c(()=>new R(404,"not_found","run not found"),"missing"),V=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),I=c(async()=>await Y(),"db");async function $(e,t,s=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!s&&n.deleting_at)throw Q();return n}c($,"ownedRun");const he=["waiting_on_user","idle","settled"];async function k(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await I()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
2
2
  (n.last_settled_at IS NULL OR EXISTS (
3
3
  SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
4
4
  AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
5
5
  WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
6
- )) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await pt(e)?"running":(await le(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
- WHERE n.run_id = ? AND ${Xe("d","'armed', 'pending', 'handed_off'")}
8
- AND (n.status IN ('active', 'idle') OR ${Ge("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Yn(e){const t=await b(e);return t!==null&&await C(t)==="running"}c(Yn,"runIsRunning");async function F(e){await K(e.node_id),e=await b(e.node_id)??e;const t=await C(e),a=t==="settled"?[]:await le(e.node_id),n=await Ze(e.node_id)||void 0,d=t==="settled"?await _t(e):null,f=d?.kind==="result"?await oe(e.node_id):void 0,r=ze(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...r?{recap:r}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await Rt(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(z())),payer:await Y(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await ht(e.node_id,t)}}c(F,"runObject");const Q=864e5,ye=255;function Gn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>ye)throw S(`Idempotency-Key must be 1-${ye} characters`);return e}}c(Gn,"idempotencyKeyOf");function k(e){if(Ce()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(k,"cloudPersonScope");function x(e,t){const a=k(e);return a===void 0?t:`${a}:${t}`}c(x,"personKey");async function U(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await j();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=Q)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(U,"findIdempotent");async function he(e,t,a,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-Q).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(f),r)}c(he,"recordIdempotent");async function Xn(e=Date.now()){return Number((await(await j()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-Q).toISOString())).changes)}c(Xn,"pruneExpiredIdempotencyKeys");async function Re(e,t,a,n,d,f,r=!1){const s=d.text;let u=0;return{messageId:(await Qe(t,{kind:"message",label:s.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:f?{body:s,...r?{steer:!0}:{}}:{body:s,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await fe(a,k(n),d.uses,h),await pe(d.uses.map(({upload_id:_,path:i,blob_key:l})=>({upload_id:_,path:i,blob_key:l,run_id:t})),h)),u=(await ue(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Re,"acceptRunMessage");class Se extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Ct=1440*60*1e3;function Ne(e){const t=typeof e=="string"?it(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Ct)throw S("deadline must be at most 24h","deadline");return t}c(Ne,"parseRunDeadlineMs");async function zn(e,t,a,n=ge){if(t.isolated&&!dt()&&await ct((t.profile===void 0?await ne(e.grantee):ae(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Ne(t.deadline);const{causedBy:d,...f}=t,r=V("sha256").update(JSON.stringify(f)).digest("hex");if(a){const o=await U(e.grantee,x(e.sub,a),r);if(o){const _=await H(o.run_id,e.grantee);return!_.pi_pid&&await C(_)==="running"&&(t.output_schema!==void 0&&!_.outcome_at&&await ft(_.node_id)===null&&await oe(_.node_id)===void 0&&await de(_.node_id,"terminal",t.output_schema),await J(_.node_id,{resume:!0,capacity:"freeze"})),o.response}}await St(e.grantee);const s=t.profile===void 0?await ne(e.grantee):ae(t.profile),u=s.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${s.profileId}`;if(!e.resolved.some(_=>B(_,o))||t.scopes!==null&&!t.scopes.some(_=>B(_,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(st(o)){if(o.includes("/")&&await Y(e.grant)!=="app"){const _=o.lastIndexOf("/"),i=o.slice(0,_),l=o.slice(_+1);if(["ultra","strong","medium","light"].includes(l)&&(await rt({kind:"logical",family:i,strength:l,spec:o},G(e.grantee).files,s.profileId)).every(y=>y.family!==i))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(ot(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const p=await nt(),h=Fe(G(e.grantee).nodes,p);if(t.isolated&&t.cwd!==void 0){const o=ke(h,xe(t.cwd));if(!Z(t.cwd)||o===".."||o.startsWith(`..${We}`)||Z(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(p,e.grantee,t.prompt,void 0,k(e.sub)),_=o.text,i=t.message===void 0?void 0:await n(p,e.grantee,t.message,o.uses.map(m=>m.path),k(e.sub)),l=await Y(e.grant);let y;try{const m=mt(s,t.model);await at({kind:ut(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:G(e.grantee).files,profile:s.profileId,prompt:_,nodeId:p,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...m===void 0?{}:{model:m},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Ne(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:p,event_cursor:1,usage_json:JSON.stringify(z())},withinCreate:c(async(E,A)=>{if(a){const N=await U(e.grantee,x(e.sub,a),r,E);if(N)throw new Se(N)}const D=o.uses;if(D.length&&(await fe(e.grantee,k(e.sub),D,E),await pe(D.map(({upload_id:N,path:I,blob_key:$})=>({upload_id:N,path:I,blob_key:$,run_id:p})),E)),y={run_id:p,node_id:p,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:l,status:"running",created_at:A.created,metadata:t.metadata,sequence_number:0},await ue(E,p,p,"run.started",{scopes:t.scopes,payer:l,usage:z()}),i){const N=await Re(E,p,e.grantee,e.sub,i,!1);y.message={run_id:p,message_id:N.messageId,sequence_number:N.sequence}}else await Ve(p,e.grantee,_);a&&await he(E,e.grantee,x(e.sub,a),r,p,y,A.created)},"withinCreate")},t.output_schema===void 0?void 0:async E=>{await de(E,"terminal",t.output_schema)})}catch(m){if(m instanceof Se)return m.winner.response;if(t.model!==void 0&&m instanceof Le&&m.code==="usage")throw S(m.message,"model");if(m instanceof Te&&(m.code==="isolated_run"||m.code==="invalid_request")){const E=m.details&&typeof m.details=="object"&&"param"in m.details&&typeof m.details.param=="string"?m.details.param:void 0;throw new R(m.status,m.code,m.message,E)}throw m}if(!y)throw new Error("run creation did not commit");return y}finally{await kt(p)}}c(zn,"startRun");async function kt(e){try{if(await b(e)!==null)return;const t=await It();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){Tt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(kt,"discardUncommittedAttachments");async function Qn(e,t){let a;if(t.after)try{const s=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!s||typeof s!="object"||!("activity"in s)||typeof s.activity!="string"||!("id"in s)||typeof s.id!="string")throw new Error("invalid cursor");a={activity:s.activity,id:s.id}}catch{throw S("invalid list cursor","after")}const n=await(await M()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),s=!e.last_settled_at&&e.status!=="done";return t||s||await pt(e)?"running":(await _e(e.node_id)).length?"waiting_on_user":await(await I()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
+ WHERE n.run_id = ? AND ${ze("d","'armed', 'pending', 'handed_off'")}
8
+ AND (n.status IN ('active', 'idle') OR ${Xe("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(k,"runStatus");async function Gn(e){const t=await v(e);return t!==null&&await k(t)==="running"}c(Gn,"runIsRunning");async function H(e){await te(e.node_id),e=await v(e.node_id)??e;const t=await k(e),s=t==="settled"?[]:await _e(e.node_id),n=await Ke(e.node_id)||void 0,d=t==="settled"?await wt(e):null,f=d?.kind==="result"?await ce(e.node_id):void 0,r=Qe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...r?{recap:r}:{},pending_question_ids:s,open_notice_ids:t==="settled"?[]:await St(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(V())),payer:await X(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await Rt(e.node_id,t)}}c(H,"runObject");const Z=864e5,Re=255;function Xn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>Re)throw S(`Idempotency-Key must be 1-${Re} characters`);return e}}c(Xn,"idempotencyKeyOf");function x(e){if(ke()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(x,"cloudPersonScope");function W(e,t){const s=x(e);return s===void 0?t:`${s}:${t}`}c(W,"personKey");async function P(e,t,s,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await Y();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=Z)){if(d.body_hash!==s)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(P,"findIdempotent");async function Se(e,t,s,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,s,new Date(Date.now()-Z).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,s,n,d,JSON.stringify(f),r)}c(Se,"recordIdempotent");async function zn(e=Date.now()){return Number((await(await Y()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-Z).toISOString())).changes)}c(zn,"pruneExpiredIdempotencyKeys");async function Ne(e,t,s,n,d,f,r=!1){const i=d.text;let u=0;return{messageId:(await Ve(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:s,bodyJson:f?{body:i,...r?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await pe(s,x(n),d.uses,h),await we(d.uses.map(({upload_id:m,path:y,blob_key:a})=>({upload_id:m,path:y,blob_key:a,run_id:t})),h)),u=(await le(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Ne,"acceptRunMessage");class be extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const kt=1440*60*1e3;function ve(e){const t=typeof e=="string"?rt(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>kt)throw S("deadline must be at most 24h","deadline");return t}c(ve,"parseRunDeadlineMs");async function Qn(e,t,s,n=ye){if(t.isolated&&!ct()&&await ut((t.profile===void 0?await ae(e.grantee):ie(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&ve(t.deadline);const{causedBy:d,...f}=t,r=K("sha256").update(JSON.stringify(f)).digest("hex");if(s){const o=await P(e.grantee,W(e.sub,s),r);if(o){const m=await $(o.run_id,e.grantee);return!m.pi_pid&&await k(m)==="running"&&(t.output_schema!==void 0&&!m.outcome_at&&await _t(m.node_id)===null&&await ce(m.node_id)===void 0&&await ue(m.node_id,"terminal",t.output_schema),await G(m.node_id,{resume:!0,capacity:"freeze"})),o.response}}await Nt(e.grantee);const i=t.profile===void 0?await ae(e.grantee):ie(t.profile),u=i.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${i.profileId}`;if(!e.resolved.some(m=>J(m,o))||t.scopes!==null&&!t.scopes.some(m=>J(m,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(it(o)){if(o.includes("/")&&await X(e.grant)!=="app"){const m=o.lastIndexOf("/"),y=o.slice(0,m),a=o.slice(m+1);if(["ultra","strong","medium","light"].includes(a)&&(await ot({kind:"logical",family:y,strength:a,spec:o},z(e.grantee).files,i.profileId)).every(E=>E.family!==y))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(dt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const p=await st(),h=Fe(z(e.grantee).nodes,p);if(t.isolated&&t.cwd!==void 0){const o=xe(h,We(t.cwd));if(!ee(t.cwd)||o===".."||o.startsWith(`..${qe}`)||ee(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(p,e.grantee,t.prompt,void 0,x(e.sub)),m=o.text,y=t.message===void 0?void 0:await n(p,e.grantee,t.message,o.uses.map(_=>_.path),x(e.sub)),a=await X(e.grant);let E;try{const _=lt(i,t.model);await at({kind:mt(i),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:z(e.grantee).files,profile:i.profileId,prompt:m,nodeId:p,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},..._===void 0?{}:{model:_},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+ve(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:p,event_cursor:1,usage_json:JSON.stringify(V())},withinCreate:c(async(g,D)=>{if(s){const N=await P(e.grantee,W(e.sub,s),r,g);if(N)throw new be(N)}const A=o.uses;if(A.length&&(await pe(e.grantee,x(e.sub),A,g),await we(A.map(({upload_id:N,path:q,blob_key:T})=>({upload_id:N,path:q,blob_key:T,run_id:p})),g)),E={run_id:p,node_id:p,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:a,status:"running",created_at:D.created,metadata:t.metadata,sequence_number:0},await le(g,p,p,"run.started",{scopes:t.scopes,payer:a,usage:V()}),y){const N=await Ne(g,p,e.grantee,e.sub,y,!1);E.message={run_id:p,message_id:N.messageId,sequence_number:N.sequence}}else await Ze(p,e.grantee,m);s&&await Se(g,e.grantee,W(e.sub,s),r,p,E,D.created)},"withinCreate")},t.output_schema===void 0?void 0:async g=>{await ue(g,"terminal",t.output_schema)})}catch(_){if(_ instanceof be)return _.winner.response;if(t.model!==void 0&&_ instanceof Ce&&_.code==="usage")throw S(_.message,"model");if(_ instanceof Le&&(_.code==="isolated_run"||_.code==="invalid_request")){const g=_.details&&typeof _.details=="object"&&"param"in _.details&&typeof _.details.param=="string"?_.details.param:void 0;throw new R(_.status,_.code,_.message,g)}throw _}if(!E)throw new Error("run creation did not commit");return E}finally{await xt(p)}}c(Qn,"startRun");async function xt(e){try{if(await v(e)!==null)return;const t=await Tt();for(const s of await t.list(`attachments/${e}/`))await t.delete(s)}catch(t){Lt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(xt,"discardUncommittedAttachments");async function Vn(e,t){let s;if(t.after)try{const i=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!i||typeof i!="object"||!("activity"in i)||typeof i.activity!="string"||!("id"in i)||typeof i.id!="string")throw new Error("invalid cursor");s={activity:i.activity,id:i.id}}catch{throw S("invalid list cursor","after")}const n=await(await I()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
9
9
  WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}${t.sub===void 0?"":" AND sub = ?"}
10
- ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await we(await W((await we(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:u})=>!a||s<a.activity||s===a.activity&&u<a.id),async s=>({root:await b(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await W(f,async({root:s})=>await F(s)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(Qn,"listRuns");async function Vn(e,t,a){const n=await H(e,t),d=c(async()=>await F(await H(e,t)),"read");return!a||Ee.includes(await C(n))?await d():new Promise((f,r)=>{let s=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(i),clearInterval(_),s()},"settle"),p=c(async()=>{u();try{f(await d())}catch(l){r(l)}},"finish"),h=c(async()=>{Ee.includes(String((await d()).status))&&await p()},"check"),o=c(()=>{h().catch(l=>{u(),r(l)})},"run"),_=setInterval(o,250),i=setTimeout(()=>{p()},a*1e3);yt(e,o).then(l=>{s=l},l=>{u(),r(l)})})}c(Vn,"waitRun");const xt=5;async function Zn(e,t,a=ge,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",u=V("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),p=c(async o=>{const _=await b(e.node_id),i=await(await M()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return _&&!r&&n&&!_.pi_pid&&i&&await J(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await U(s,x(e.sub,d),u);if(o)return p(o.response)}if(r)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const _=await a(e.node_id,s,t,void 0,k(e.sub)),i=await q(async l=>{if(d){const E=await U(s,x(e.sub,d),u,l);if(E)return{replayed:E.response}}if(_.uses.length){await Et(l,e.node_id);for(const E of _.uses)if(await At(e.node_id,E.path,l))return"path_taken"}await h?.(e.node_id);const y=await Re(l,e.node_id,s,e.sub,_,n,n&&f),m={run_id:e.node_id,message_id:y.messageId,sequence_number:y.sequence};return d&&await he(l,s,x(e.sub,d),u,e.node_id,m,new Date().toISOString()),{result:m}});if(i==="path_taken"){if(o>=xt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in i?p(i.replayed):(n&&!e.pi_pid&&await J(e.node_id,{resume:!0,capacity:"freeze"}),i.result)}}c(Zn,"messageRun");async function Wt(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await b(e);if(!n)throw X();if(!ie(n)){if(n.streaming)throw t();return}const d=(await ee(e))?.executionId;try{await tt(e)==="turn"&&_e({nodes:[e]});return}catch(f){if(!(f instanceof et))throw f;const r=await b(e);if(!r)throw X();if(!r.streaming)return;if(a===0&&ie(r)&&(await ee(e))?.executionId!==d)continue;throw t()}}throw t()}c(Wt,"interruptNode");async function Kn(e,t="stop"){const a=t==="stop"?(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>Wt(n))),await F(await b(e.node_id)??e)}c(Kn,"interruptRun");async function ea(e,t={}){const a=(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);_e({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await ce(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of a){if(r===e.node_id)continue;const s=await b(r);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...(await ce(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await me({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>se(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await b(e.node_id);return await F(f??e)}c(ea,"cancelRun");const be=200;async function ta(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>be)throw S(`name exceeds ${be} characters`,"name");const n=await Be(e.node_id,{name:a});return n.window&&Je(n.window,je(n)),await F(n)}c(ta,"renameRun");async function na(e,t={config:vt,client:bt}){await me({run_id:e.node_id},"the run was deleted");const a=await q(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(p=>p.node_id)));if((await Promise.all(a.map(u=>se(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await Ke(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await W(a,async u=>{const p=await $e(u);if(p.app===null)throw new Error(`run node missing during deletion: ${u}`);return p}),f=await(await M()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of f)try{await te().delete(u)}catch(p){if(!Ye(p))throw p}const r=await q(async u=>{for(const _ of a){const i=await Ue(u,_);i!==null&&i.deleted_at===null&&await He(u,i)}const p=await Mt([e.node_id],u);await Ot([e.node_id],u),await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:_}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(_,_);return p});for(const u of d)await Pe(u);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Ft(r,t)}}c(na,"deleteRun");async function Ft(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(r=>a.deleteUpload(r).then(async()=>{await Dt(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??Lt),f.unref?.()})]),clearTimeout(f),e.length-n.size}c(Ft,"deleteReleasedUploads");async function aa(e,t,a){await H(e,t),await K(e);const n=await q(async i=>{const l=await i.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),y=new Map;for(const N of l)y.set(N.node_id,(await i.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(N.node_id)).map(I=>I.session_id));const E=(await i.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await i.prepare(`SELECT node_id, sequence_number FROM run_events
10
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await Ee(await F((await Ee(n,async({node_id:i})=>!t.visible||await t.visible(i))).filter(({activity:i,node_id:u})=>!s||i<s.activity||i===s.activity&&u<s.id),async i=>({root:await v(i.node_id),activity:i.activity})),async({root:i})=>!t.status||await k(i)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await F(f,async({root:i})=>await H(i)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(Vn,"listRuns");async function Zn(e,t,s){const n=await $(e,t),d=c(async()=>await H(await $(e,t)),"read");return!s||he.includes(await k(n))?await d():new Promise((f,r)=>{let i=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(y),clearInterval(m),i()},"settle"),p=c(async()=>{u();try{f(await d())}catch(a){r(a)}},"finish"),h=c(async()=>{he.includes(String((await d()).status))&&await p()},"check"),o=c(()=>{h().catch(a=>{u(),r(a)})},"run"),m=setInterval(o,250),y=setTimeout(()=>{p()},s*1e3);ht(e,o).then(a=>{i=a},a=>{u(),r(a)})})}c(Zn,"waitRun");const Wt=5;async function Kn(e,t,s=ye,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",i=e.grantee??"app:terminal",u=K("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),p=c(async o=>{const m=await v(e.node_id),y=await(await I()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return m&&!r&&n&&!m.pi_pid&&y&&await G(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await P(i,W(e.sub,d),u);if(o)return p(o.response)}if(r)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const m=await s(e.node_id,i,t,void 0,x(e.sub)),y=await U(async a=>{if(d){const g=await P(i,W(e.sub,d),u,a);if(g)return{replayed:g.response}}if(m.uses.length){await yt(a,e.node_id);for(const g of m.uses)if(await It(e.node_id,g.path,a))return"path_taken"}await h?.(e.node_id);const E=await Ne(a,e.node_id,i,e.sub,m,n,n&&f),_={run_id:e.node_id,message_id:E.messageId,sequence_number:E.sequence};return d&&await Se(a,i,W(e.sub,d),u,e.node_id,_,new Date().toISOString()),{result:_}});if(y==="path_taken"){if(o>=Wt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in y?p(y.replayed):(n&&!e.pi_pid&&await G(e.node_id,{resume:!0,capacity:"freeze"}),y.result)}}c(Kn,"messageRun");async function qt(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let s=0;s<2;s++){const n=await v(e);if(!n)throw Q();if(!oe(n)){if(n.streaming)throw t();return}const d=(await ne(e))?.executionId;try{await nt(e)==="turn"&&ge({nodes:[e]});return}catch(f){if(!(f instanceof tt))throw f;const r=await v(e);if(!r)throw Q();if(!r.streaming)return;if(s===0&&oe(r)&&(await ne(e))?.executionId!==d)continue;throw t()}}throw t()}c(qt,"interruptNode");async function es(e,t="stop"){const s=t==="stop"?(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(s.map(n=>qt(n))),await H(await v(e.node_id)??e)}c(es,"interruptRun");async function ts(e,t={}){const s=(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);ge({run:e.node_id});const n=[];if(await k(e)!=="settled")n.push(...(await me(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of s){if(r===e.node_id)continue;const i=await v(r);i&&i.status!=="done"&&i.status!=="canceled"&&i.status!=="dead"&&n.push(...(await me(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await fe({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>re(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await v(e.node_id);return await H(f??e)}c(ts,"cancelRun");const Oe=200;async function ns(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const s=t.trim();if(s.length>Oe)throw S(`name exceeds ${Oe} characters`,"name");const n=await je(e.node_id,{name:s});return n.window&&Ye(n.window,Je(n)),await H(n)}c(ns,"renameRun");async function ss(e,t={config:Ot,client:vt}){await fe({run_id:e.node_id},"the run was deleted");const s=await U(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(p=>p.node_id)));if((await Promise.all(s.map(u=>re(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await et(s)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await F(s,async u=>{const p=await Pe(u);if(p.app===null)throw new Error(`run node missing during deletion: ${u}`);return p}),f=await(await I()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of f)try{await se().delete(u)}catch(p){if(!Ge(p))throw p}const r=await U(async u=>{for(const m of s){const y=await $e(u,m);y!==null&&y.deleted_at===null&&await Ue(u,y)}const p=await At([e.node_id],u);await Dt([e.node_id],u),await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=s.map(()=>"?").join(","),o=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...s,...s);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...s);for(const{message_id:m}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(m,m);return p});for(const u of d)await Be(u);const{notifyRunDeleted:i}=await import("./events.js");return i(e.node_id),{uploads_pending:await Ft(r,t)}}c(ss,"deleteRun");async function Ft(e,t){if(!e.length||!t.config())return e.length;let s;try{s=t.client()}catch{return e.length}const n=new Set,d=e.map(r=>s.deleteUpload(r).then(async()=>{await Mt(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??Ct),f.unref?.()})]),clearTimeout(f),e.length-n.size}c(Ft,"deleteReleasedUploads");async function as(e,t,s){await $(e,t),await te(e);const n=await U(async a=>{const E=await a.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),_=new Map;for(const b of E)_.set(b.node_id,(await a.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(b.node_id)).map(l=>l.session_id));const D=(await a.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await a.prepare(`SELECT node_id, sequence_number FROM run_events
11
11
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
12
- ORDER BY sequence_number`).all(e,E),D=await i.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
12
+ ORDER BY sequence_number`).all(e,D),N=await a.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
13
13
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
14
- ORDER BY sequence_number`).all(e,E);return{nodes:l,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:f,latestSequence:r,completed:s,deltas:u}=n,p=await W(d,async i=>({node_id:i.node_id,parent_node_id:i.parent,conversations:await W(f.get(i.node_id)??[],async l=>{const{header:y,entries:m}=await te().read(l);if(a==="entries")return{conversation_id:l,header:y,entries:m};const E=qe.inMemory(y.cwd,void 0,[y,...m]),A=lt(E)??[],D=new Map(m.map((g,v)=>[g.id,v])),N=m.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=m.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),$=i.node_id===e?m.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const v=re(m,g.message.timestamp);return v?.type==="runtime"&&v.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(v=>v.id===g)),...N,...I].sort((g,v)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(v.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:v})=>{const w=v,T=w.usage,P=w.role==="user"?re(m,Number(w.timestamp)):null,Oe=P?.type==="human"||g===$,L=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?Oe?"user":"custom":w.role,De=L==="custom"?w.role==="custom"?w.customType:P?.type==="runtime"?P.kind:"unknown":void 0,Me=L==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:l,messages:ve}})})),h=new Map(await Promise.all(p.map(async i=>[i.node_id,await wt(i.node_id)])));for(const i of s){const l=h.get(i.node_id);l!=null&&i.sequence_number>=l&&h.set(i.node_id,null)}const o=new Map;for(const i of u){const l=h.get(i.node_id);if(l==null||i.sequence_number<l)continue;const y=JSON.parse(i.body_json),m=o.get(i.node_id)??{thinking:"",text:""};i.type==="node.thinking.delta"?m.thinking+=y.delta:m.text+=y.delta,o.set(i.node_id,m)}const _=p.map(i=>({...i,in_progress_message:h.get(i.node_id)==null?null:o.get(i.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:_}}c(aa,"traceRun");function sa(e,t,a){if(t===void 0){if(!e.some(n=>B(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{gt(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ie(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(sa,"requestedScopes");export{Q as IDEMPOTENCY_WINDOW_MS,Ct as RUN_DEADLINE_MAX_MS,Lt as RUN_DELETE_STORAGE_BUDGET_MS,be as RUN_NAME_MAX,R as RunError,ea as cancelRun,k as cloudPersonScope,na as deleteRun,Gn as idempotencyKeyOf,Kn as interruptRun,Qn as listRuns,Zn as messageRun,H as ownedRun,Ne as parseRunDeadlineMs,Xn as pruneExpiredIdempotencyKeys,ta as renameRun,sa as requestedScopes,Yn as runIsRunning,F as runObject,zn as startRun,aa as traceRun,Vn as waitRun};
14
+ ORDER BY sequence_number`).all(e,D),q=await a.prepare(`SELECT node_id, sequence_number, ts, body_json FROM run_events
15
+ WHERE run_id = ? AND sequence_number <= ? AND type = 'file.sent'
16
+ ORDER BY sequence_number`).all(e,D),T=new Set((await a.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=q.flatMap(b=>{const l=JSON.parse(b.body_json);return T.has(l.file_id)?[{file_id:l.file_id,node_id:b.node_id,name:l.name,media_type:l.media_type,size:l.size,sequence_number:Number(b.sequence_number),ts:b.ts}]:[]});return{nodes:E,sessionIds:_,latestSequence:D,completed:A,deltas:N,files:B}}),{nodes:d,sessionIds:f,latestSequence:r,completed:i,deltas:u,files:p}=n,h=await F(d,async a=>({node_id:a.node_id,parent_node_id:a.parent,conversations:await F(f.get(a.node_id)??[],async E=>{const{header:_,entries:g}=await se().read(E);if(s==="entries")return{conversation_id:E,header:_,entries:g};const D=He.inMemory(_.cwd,void 0,[_,...g]),A=ft(D)??[],N=new Map(g.map((l,O)=>[l.id,O])),q=g.filter(l=>l.type==="custom"&&l.customType==="crtr-system-prompt").map(l=>({id:l.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in l?l.data:void 0,timestamp:l.timestamp}})),T=g.filter(l=>l.type==="custom_message"&&l.customType==="app_message").map(l=>({id:l.id,message:{role:"custom",customType:"app_message",content:"content"in l?l.content:"",timestamp:l.timestamp}})),B=a.node_id===e?g.find(l=>{if(l.type!=="message"||l.message.role!=="user")return!1;const O=de(g,l.message.timestamp);return O?.type==="runtime"&&O.kind==="kickoff"})?.id:void 0,b=[...A.filter(({id:l})=>!T.some(O=>O.id===l)),...q,...T].sort((l,O)=>(N.get(l.id)??Number.MAX_SAFE_INTEGER)-(N.get(O.id)??Number.MAX_SAFE_INTEGER)).map(({id:l,message:O})=>{const w=O,L=w.usage,j=w.role==="user"?de(g,Number(w.timestamp)):null,De=j?.type==="human"||l===B,C=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?De?"user":"custom":w.role,Me=C==="custom"?w.role==="custom"?w.customType:j?.type==="runtime"?j.kind:"unknown":void 0,Ae=C==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(M=>M.type==="toolCall"?{type:"tool_call",tool_call_id:M.id,name:M.name,arguments:M.arguments}:M.type==="image"?{type:"image",mime_type:M.mimeType}:M.type==="thinking"?{type:"thinking",text:M.thinking}:M):[];return{entry_id:l,role:C,...C==="custom"?{custom_type:Me}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Ae,...C==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...L?{usage:{input_tokens:L.input??0,output_tokens:L.output??0,cache_read_tokens:L.cacheRead??0,cache_write_tokens:L.cacheWrite??0,cost_usd:L.cost?.total??0}}:{}}:{},...C==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:E,messages:b}})})),o=new Map(await Promise.all(h.map(async a=>[a.node_id,await gt(a.node_id)])));for(const a of i){const E=o.get(a.node_id);E!=null&&a.sequence_number>=E&&o.set(a.node_id,null)}const m=new Map;for(const a of u){const E=o.get(a.node_id);if(E==null||a.sequence_number<E)continue;const _=JSON.parse(a.body_json),g=m.get(a.node_id)??{thinking:"",text:""};a.type==="node.thinking.delta"?g.thinking+=_.delta:g.text+=_.delta,m.set(a.node_id,g)}const y=h.map(a=>({...a,in_progress_message:o.get(a.node_id)==null?null:m.get(a.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:y,files:p}}c(as,"traceRun");function is(e,t,s){if(t===void 0){if(!e.some(n=>J(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{Et(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===s.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===s.slice(4))&&!Te(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(is,"requestedScopes");export{Z as IDEMPOTENCY_WINDOW_MS,kt as RUN_DEADLINE_MAX_MS,Ct as RUN_DELETE_STORAGE_BUDGET_MS,Oe as RUN_NAME_MAX,R as RunError,ts as cancelRun,x as cloudPersonScope,ss as deleteRun,Xn as idempotencyKeyOf,es as interruptRun,Vn as listRuns,Kn as messageRun,$ as ownedRun,ve as parseRunDeadlineMs,zn as pruneExpiredIdempotencyKeys,ns as renameRun,is as requestedScopes,Gn as runIsRunning,H as runObject,Qn as startRun,as as traceRun,Zn as waitRun};
@@ -1,3 +1,3 @@
1
- var d=Object.defineProperty;var o=(e,n)=>d(e,"name",{value:n,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as f,withCanvasWrite as h}from"../../../canvas/db.js";import{MachineCallFailedError as p,MachineLostError as l,MachineOfflineError as s}from"./ops.js";const S={start:60,wake:15,stop:15,status:15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60},m=1e3;async function T(e,n,r,c={}){const i=E(),w=new Date().toISOString();if(!await h(async a=>await a.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,w)===void 0?!1:(await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(i,e,n,JSON.stringify(r),w),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new s(e,"no live link");const _=Date.now()+(c.timeoutMs??S[n]*1e3);for(;;){const a=await(await f()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(i);if(a===void 0)throw new l(e,i);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const t=a.result_json===null?{}:JSON.parse(a.result_json);throw t.code==="machine_offline"?new s(e,t.message,t.sent===!0):t.code==="machine_lost"?new l(e,i):new p(e,n,t.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await u(i,"lease expired")===void 0)continue;throw new l(e,i)}if(Date.now()>=_){const t=await u(i,"timed out");if(t===void 0)continue;throw t===null?new s(e,"no holder claimed the call"):new l(e,i)}await new Promise(t=>setTimeout(t,c.rereadMs??m))}}o(T,"callMachine");async function u(e,n){const r=await(await f()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
1
+ var S=Object.defineProperty;var o=(e,n)=>S(e,"name",{value:n,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as E,withCanvasWrite as N}from"../../../canvas/db.js";import{brokerSignalBus as k}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as O,MachineLostError as _,MachineOfflineError as d}from"./ops.js";const D={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60},M=1e3;async function x(e,n,a,l={}){const s=g(),c=new Date().toISOString();if(!await N(async r=>await r.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,c)===void 0?!1:(await r.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(s,e,n,JSON.stringify(a),c),await r.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new d(e,"no live link");const i=Date.now()+(l.timeoutMs??D[n]*1e3);let u,f=!1;const h=await k.subscribe(r=>{r===s&&(f=!0,u?.())},{kinds:["machine_call"]});try{return await T(e,n,s,i,l.rereadMs??M,r=>new Promise(w=>{if(f){f=!1,w();return}const p=setTimeout(()=>{u=void 0,w()},r);u=o(()=>{clearTimeout(p),u=void 0,f=!1,w()},"wake")}))}finally{h()}}o(x,"callMachine");async function T(e,n,a,l,s,c){for(;;){const t=await(await E()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(a);if(t===void 0)throw new _(e,a);if(t.state==="done")return t.result_json===null?null:JSON.parse(t.result_json);if(t.state==="failed"){const i=t.result_json===null?{}:JSON.parse(t.result_json);throw i.code==="machine_offline"?new d(e,i.message,i.sent===!0):i.code==="machine_lost"?new _(e,a):new O(e,n,i.message??"unknown")}if(t.claimed_generation!==null&&t.lease_expires_at!==null&&t.lease_expires_at<=new Date().toISOString()){if(await m(a,"lease expired")===void 0)continue;throw new _(e,a)}if(Date.now()>=l){const i=await m(a,"timed out");if(i===void 0)continue;throw i===null?new d(e,"no holder claimed the call"):new _(e,a)}await c(Math.min(s,Math.max(0,l-Date.now())))}}o(T,"waitForCall");async function m(e,n){const a=await(await E()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
2
2
  result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
3
- WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return r===void 0?void 0:r.claimed_generation===null?null:Number(r.claimed_generation)}o(u,"failOpenCall");export{S as MACHINE_CALL_TIMEOUT_S,T as callMachine};
3
+ WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return a===void 0?void 0:a.claimed_generation===null?null:Number(a.claimed_generation)}o(m,"failOpenCall");export{D as MACHINE_CALL_TIMEOUT_S,x as callMachine};
@@ -7,6 +7,13 @@ export interface MachineExecutorDeps {
7
7
  environmentId: string;
8
8
  /** Seconds `stop` waits after SIGTERM before SIGKILL. */
9
9
  stopGraceS?: number;
10
+ /** Called when a broker this executor spawned exits. */
11
+ onExit?: (exit: {
12
+ execution: string;
13
+ node: string;
14
+ code: number | null;
15
+ signal: string | null;
16
+ }) => void;
10
17
  }
11
18
  /** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
12
19
  * be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
@@ -1 +1 @@
1
- var P=Object.defineProperty;var s=(o,n)=>P(o,"name",{value:n,configurable:!0});import{spawn as U}from"node:child_process";import{closeSync as $,existsSync as E,mkdirSync as _,openSync as B,statSync as G}from"node:fs";import{rm as H}from"node:fs/promises";import{basename as S,dirname as I,join as R}from"node:path";import{fileURLToPath as F}from"node:url";import{contextDir as j,jobDir as K,nodeRunDir as k,crtrHome as b,viewSocketPath as X}from"../../../canvas/paths.js";import{captureTeardownSnapshot as J,isAnyPidAlive as V,killProcessTreePids as y,listProcessTableAsync as Y}from"../../../canvas/pid.js";import{scopesFilePath as v}from"../../../canvas/paths.js";import{writeFileBeneath as x}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as W}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as z}from"../../broker-ownership.js";import{isShippedCanvasExtension as Q}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as q,mergeCanvasExtensions as Z}from"../../canvas-extensions.js";import{layoutRoot as g,runtimeRoot as ee}from"../../../layout.js";import{composeAppProcessEnv as oe,overlayBrokerEnv as te}from"../../spawn-env.js";const T=s(()=>R(I(F(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),C=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),re=s(o=>new Promise(n=>setTimeout(n,o)),"sleep");async function N(){const o=[],n=await Y();if(n===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:r,command:e}of n){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:r,execution:t[1],node:t[2],command:e})}return o}s(N,"findBrokers");const ne=new Set([502,503,504]),ie=1e3,ce=3e4,se=3e4,A=9e4;async function ae(o,n,r,e){const t=Date.now()+A;for(let c=ie;;c=Math.min(c*2,ce)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(se,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${n}/start`,{headers:{authorization:`Bearer ${r}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${n}`}catch(u){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${n}: ${u instanceof Error?u.message:String(u)}`}if(a?.ok)return await a.json();if(a!==void 0&&!ne.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${A/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(u=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),u()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(ae,"fetchBundle");const de=["CRTR_HOME","CRTR_RUNTIME_HOME"];function O(o,n){const r={...o};for(const e of de)delete r[e];return r.CRTR_CONTEXT_DIR!==void 0&&(r.CRTR_CONTEXT_DIR=j(n.id,r.CRTR_GRANTEE??n.app)),r.CRTR_SCOPES_FILE!==void 0&&(r.CRTR_SCOPES_FILE=v(n.id)),r}s(O,"localLaunchEnv");function ue(o){const n=s(i=>S(i).replace(/\.[jt]s$/,""),"stem"),r=new Set(q.map(n)),e=s(i=>Q(i)||S(I(i))==="pi-extensions"&&(r.has(n(i))||n(i).startsWith("canvas-")&&!E(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!E(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...Z(c).flatMap(i=>["-e",i]),...t]}s(ue,"localExtensionArgv");function fe(o,n){const r=JSON.parse(o);return JSON.stringify({...r,argv:ue(r.argv),env:O(r.env??{},n)})}s(fe,"machineLaunchRecipe");function le(o,n,r){const e=o.launch,t=te({argv:[],env:O(e.env??{},o.node)},oe(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:g(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ee(),CRTR_API_URL:n.apiUrl,CRTR_EXECUTION_ID:r,CRTR_ENVIRONMENT_ID:n.environmentId,CRTR_VIEW_WSS:"0",[W]:"1"})}s(le,"machineBrokerEnv");async function M(o,n,r){const{tree:e,identities:t}=J(o,null,r);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let d=0;V(i);d+=100){if(d>=a)return!1;await re(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],n),y(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(y(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(M,"stopBroker");async function Ne(o=1e4){const r=(await Promise.all((await N()).filter(e=>z(e.command,b())).map(e=>M(e.pid,o)))).filter(e=>!e.confirmed);if(r.length>0)throw new Error(r.map(e=>e.error??"a broker did not stop").join("; "))}s(Ne,"stopAllBrokers");function Ae(o){const n=(o.stopGraceS??10)*1e3,r=s(async e=>(await N()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=await r(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!E(e.cwd)||!G(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(T()))throw new Error(`the broker entry ${T()} does not exist`);const i=await ae(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=k(e.nodeId);_(d,{recursive:!0}),x(d,R(d,"broker-launch.json"),fe(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&x(d,v(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const u=K(e.nodeId);_(u,{recursive:!0});const m=B(R(u,"broker.log"),"a"),l=le(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const f=U(process.execPath,[T(),"--canvas-home",b(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l}),p=f.stdio[3];if(p==null||!("end"in p))throw C(f.pid),new Error("broker token pipe did not open");const D=await new Promise((L,h)=>{f.once("error",h),f.once("spawn",()=>{f.off("error",h),p.once("error",w=>{C(f.pid),h(w)}),p.end(e.nodeToken,w=>{w?h(w):L(f.pid)})})});return f.unref(),{pid:D}}finally{$(m)}},async wake({execution:e}){const t=await r(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=await r(e.executionId);return c===void 0?{confirmed:!0}:await M(c.pid,n,t.excludePid)},async status({execution:e}){const t=await r(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async delete({nodeId:e}){return await H(k(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:X(e.nodeId)}}}}s(Ae,"createMachineExecutor");export{Ae as createMachineExecutor,ae as fetchBundle,N as findBrokers,ue as localExtensionArgv,le as machineBrokerEnv,fe as machineLaunchRecipe,Ne as stopAllBrokers};
1
+ var B=Object.defineProperty;var s=(o,r)=>B(o,"name",{value:r,configurable:!0});import{spawn as G}from"node:child_process";import{closeSync as H,existsSync as E,mkdirSync as y,openSync as F,statSync as j}from"node:fs";import{rm as K}from"node:fs/promises";import{basename as b,dirname as v,join as T}from"node:path";import{fileURLToPath as X}from"node:url";import{contextDir as J,jobDir as V,nodeRunDir as C,crtrHome as N,viewSocketPath as Y}from"../../../canvas/paths.js";import{captureTeardownSnapshot as W,isAnyPidAlive as z,killProcessTreePids as A,listProcessTableAsync as Q}from"../../../canvas/pid.js";import{scopesFilePath as O}from"../../../canvas/paths.js";import{writeFileBeneath as M}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as q}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as Z}from"../../broker-ownership.js";import{isShippedCanvasExtension as g}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ee,mergeCanvasExtensions as oe}from"../../canvas-extensions.js";import{layoutRoot as te,runtimeRoot as ne}from"../../../layout.js";import{composeAppProcessEnv as re,overlayBrokerEnv as ie}from"../../spawn-env.js";const S=s(()=>T(v(X(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),D=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),ce=s(o=>new Promise(r=>setTimeout(r,o)),"sleep");async function I(){const o=[],r=await Q();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:n,command:e}of r){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:n,execution:t[1],node:t[2],command:e})}return o}s(I,"findBrokers");const se=new Set([502,503,504]),ae=1e3,de=3e4,ue=3e4,L=9e4;async function fe(o,r,n,e){const t=Date.now()+L;for(let c=ae;;c=Math.min(c*2,de)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(ue,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${r}/start`,{headers:{authorization:`Bearer ${n}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${r}`}catch(f){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${r}: ${f instanceof Error?f.message:String(f)}`}if(a?.ok)return await a.json();if(a!==void 0&&!se.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${L/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(f=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),f()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(fe,"fetchBundle");const le=["CRTR_HOME","CRTR_RUNTIME_HOME"];function P(o,r){const n={...o};for(const e of le)delete n[e];return n.CRTR_CONTEXT_DIR!==void 0&&(n.CRTR_CONTEXT_DIR=J(r.id,n.CRTR_GRANTEE??r.app)),n.CRTR_SCOPES_FILE!==void 0&&(n.CRTR_SCOPES_FILE=O(r.id)),n}s(P,"localLaunchEnv");function pe(o){const r=s(i=>b(i).replace(/\.[jt]s$/,""),"stem"),n=new Set(ee.map(r)),e=s(i=>g(i)||b(v(i))==="pi-extensions"&&(n.has(r(i))||r(i).startsWith("canvas-")&&!E(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!E(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...oe(c).flatMap(i=>["-e",i]),...t]}s(pe,"localExtensionArgv");function me(o,r){const n=JSON.parse(o);return JSON.stringify({...n,argv:pe(n.argv),env:P(n.env??{},r)})}s(me,"machineLaunchRecipe");function he(o,r,n){const e=o.launch,t=ie({argv:[],env:P(e.env??{},o.node)},re(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:te(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ne(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:n,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[q]:"1"})}s(he,"machineBrokerEnv");async function U(o,r,n){const{tree:e,identities:t}=W(o,null,n);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let d=0;z(i);d+=100){if(d>=a)return!1;await ce(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],r),A(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(A(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(U,"stopBroker");async function Me(o=1e4){const n=(await Promise.all((await I()).filter(e=>Z(e.command,N())).map(e=>U(e.pid,o)))).filter(e=>!e.confirmed);if(n.length>0)throw new Error(n.map(e=>e.error??"a broker did not stop").join("; "))}s(Me,"stopAllBrokers");function De(o){const r=(o.stopGraceS??10)*1e3,n=s(async e=>(await I()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=await n(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!E(e.cwd)||!j(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(S()))throw new Error(`the broker entry ${S()} does not exist`);const i=await fe(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=C(e.nodeId);y(d,{recursive:!0}),M(d,T(d,"broker-launch.json"),me(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&M(d,O(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const f=V(e.nodeId);y(f,{recursive:!0});const m=F(T(f,"broker.log"),"a"),l=he(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const u=G(process.execPath,[S(),"--canvas-home",N(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l});let R,k=!1;const x=s(()=>{R!==void 0&&o.onExit?.({execution:e.executionId,node:e.nodeId,...R})},"report");u.once("exit",(_,p)=>{R={code:_,signal:p},k&&x()});const h=u.stdio[3];if(h==null||!("end"in h))throw D(u.pid),new Error("broker token pipe did not open");const $=await new Promise((_,p)=>{u.once("error",p),u.once("spawn",()=>{u.off("error",p),h.once("error",w=>{D(u.pid),p(w)}),h.end(e.nodeToken,w=>{w?p(w):_(u.pid)})})});return k=!0,x(),u.unref(),{pid:$}}finally{H(m)}},async wake({execution:e}){const t=await n(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=await n(e.executionId);return c===void 0?{confirmed:!0}:await U(c.pid,r,t.excludePid)},async status({execution:e}){const t=await n(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async"status.all"(e){return{running:(await I()).map(t=>({execution:t.execution,pid:t.pid}))}},async delete({nodeId:e}){return await K(C(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Y(e.nodeId)}}}}s(De,"createMachineExecutor");export{De as createMachineExecutor,fe as fetchBundle,I as findBrokers,pe as localExtensionArgv,he as machineBrokerEnv,me as machineLaunchRecipe,Me as stopAllBrokers};
@@ -1,4 +1,4 @@
1
- var N=Object.defineProperty;var m=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as c}from"node:test";import e from"node:assert/strict";import{spawn as P}from"node:child_process";import{mkdirSync as R,mkdtempSync as E,readFileSync as A,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as l}from"node:path";import{EventEmitter as k}from"node:events";import{Readable as D}from"node:stream";import{createServer as H}from"node:http";import{createNode as M}from"../../../canvas/canvas.js";import{closeDb as L,openDb as T}from"../../../canvas/db.js";import{isPidAlive as u}from"../../../canvas/pid.js";import{bindPerson as F,installTerminalGrant as j,useEmptyPersonSettings as U}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as O}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as g}from"../../../profiles/env-store.js";import{createProfile as V}from"../../../profiles/manifest.js";import{putEnvRow as G}from"../../../secrets/env-rows.js";import{appSpace as J}from"../../../layout.js";import{executionStartRoutes as $}from"../../../../daemon/api/handlers/execution-start.js";import{Router as X}from"../../../../daemon/api/router.js";import{contextDir as S,scopesFilePath as C}from"../../../canvas/paths.js";import{layoutRoot as B,runtimeRoot as K}from"../../../layout.js";import{CANVAS_EXTENSIONS as d}from"../../canvas-extensions.js";import{createMachineExecutor as Y,fetchBundle as I,localExtensionArgv as z,machineBrokerEnv as h,machineLaunchRecipe as b}from"./executor.js";let p;const Q={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=p=E(l(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=l(p,".crouter"),R(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await L(),v(p,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Q))o===void 0?delete process.env[n]:process.env[n]=o});async function W(n,o){const a=new X().registerAll($),i=Object.assign(D.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const t=Object.assign(new k,{headersSent:!1,writableEnded:!1,writableFinished:!1});return t.setHeader=()=>t,t.writeHead=()=>(t.headersSent=!0,t),t.end=s=>(s&&(r+=s),t.writableEnded=!0,t.writableFinished=!0,t),await a.handle(i,t,null,n),JSON.parse(r)}m(W,"bundleFor"),c("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await U(),await T();const n=await j(),o=(await V("machine-env")).profileId;await O("app:terminal","SHARED","from-app",n),await O("app:terminal","APP_SECRET","app-secret",n),await g(o,"SHARED","from-profile",n),await g(o,"PROFILE_VAR","profile-value",n),await G({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const a=l(p,"work");R(a,{recursive:!0}),await M({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:a,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const i={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await F(),grant:null,client_id:null,scopes:null},r=await W(i,"em1");e.equal(r.machine_env?.APP_SECRET,"app-secret");const t=h(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");e.equal(t.APP_SECRET,"app-secret"),e.equal(t.PROFILE_VAR,"profile-value"),e.equal(t.DEPLOY_VAR,"deploy-value"),e.equal(t.SHARED,"from-profile","the profile's row wins over the app's"),e.equal(t.LAUNCH_VAR,"launch"),e.equal(t.PI_CODING_AGENT_DIR,l(J("app:terminal").home,".pi","agent")),e.equal(t.CRTR_API_URL,"http://cloud.invalid"),e.equal(t.CRTR_EXECUTION_ID,"em1"),e.doesNotThrow(()=>h({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),e.equal(t.GITHUB_TOKEN,void 0)}),c("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(l(w(),"crtr-machine-stop-")),o=l(n,"child.pid"),a=l(n,"broker-cli.js");_(a,`const { spawn } = require('node:child_process');
1
+ var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as d}from"node:test";import e from"node:assert/strict";import{spawn as P}from"node:child_process";import{mkdirSync as R,mkdtempSync as E,readFileSync as k,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as l}from"node:path";import{EventEmitter as A}from"node:events";import{Readable as D}from"node:stream";import{createServer as H}from"node:http";import{createNode as M}from"../../../canvas/canvas.js";import{closeDb as L,openDb as T}from"../../../canvas/db.js";import{isPidAlive as h}from"../../../canvas/pid.js";import{bindPerson as F,installTerminalGrant as j,useEmptyPersonSettings as U}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as g}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as O}from"../../../profiles/env-store.js";import{createProfile as V}from"../../../profiles/manifest.js";import{putEnvRow as G}from"../../../secrets/env-rows.js";import{appSpace as J}from"../../../layout.js";import{executionStartRoutes as $}from"../../../../daemon/api/handlers/execution-start.js";import{Router as X}from"../../../../daemon/api/router.js";import{contextDir as S,scopesFilePath as C}from"../../../canvas/paths.js";import{layoutRoot as B,runtimeRoot as K}from"../../../layout.js";import{CANVAS_EXTENSIONS as m}from"../../canvas-extensions.js";import{createMachineExecutor as Y,fetchBundle as I,localExtensionArgv as z,machineBrokerEnv as f,machineLaunchRecipe as b}from"./executor.js";let p;const Q={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=p=E(l(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=l(p,".crouter"),R(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await L(),v(p,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Q))o===void 0?delete process.env[n]:process.env[n]=o});async function W(n,o){const i=new X().registerAll($),a=Object.assign(D.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const t=Object.assign(new A,{headersSent:!1,writableEnded:!1,writableFinished:!1});return t.setHeader=()=>t,t.writeHead=()=>(t.headersSent=!0,t),t.end=s=>(s&&(r+=s),t.writableEnded=!0,t.writableFinished=!0,t),await i.handle(a,t,null,n),JSON.parse(r)}u(W,"bundleFor"),d("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await U(),await T();const n=await j(),o=(await V("machine-env")).profileId;await g("app:terminal","SHARED","from-app",n),await g("app:terminal","APP_SECRET","app-secret",n),await O(o,"SHARED","from-profile",n),await O(o,"PROFILE_VAR","profile-value",n),await G({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const i=l(p,"work");R(i,{recursive:!0}),await M({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:i,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const a={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await F(),grant:null,client_id:null,scopes:null},r=await W(a,"em1");e.equal(r.machine_env?.APP_SECRET,"app-secret");const t=f(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");e.equal(t.APP_SECRET,"app-secret"),e.equal(t.PROFILE_VAR,"profile-value"),e.equal(t.DEPLOY_VAR,"deploy-value"),e.equal(t.SHARED,"from-profile","the profile's row wins over the app's"),e.equal(t.LAUNCH_VAR,"launch"),e.equal(t.PI_CODING_AGENT_DIR,l(J("app:terminal").home,".pi","agent")),e.equal(t.CRTR_API_URL,"http://cloud.invalid"),e.equal(t.CRTR_EXECUTION_ID,"em1"),e.doesNotThrow(()=>f({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),e.equal(t.GITHUB_TOKEN,void 0)}),d("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(l(w(),"crtr-machine-stop-")),o=l(n,"child.pid"),i=l(n,"broker-cli.js");_(i,`const { spawn } = require('node:child_process');
2
2
  const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
3
3
  require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
4
- setInterval(() => {}, 1000);`);const i=P(process.execPath,[a,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});i.unref();try{let r=0;for(let f=0;f<100&&r===0;f++)try{r=Number(A(o,"utf8"))}catch{await new Promise(y=>setTimeout(y,50))}e.ok(r>0&&u(r),"the detached child is running");const s=await Y({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3}).stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});e.deepEqual(s,{confirmed:!0}),e.equal(u(i.pid),!1,"the broker is gone"),e.equal(u(r),!1,"the detached child is gone")}finally{try{process.kill(-i.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),c("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},a={launch:{argv:[...d.flatMap(t=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${t.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:p,profile:null},machine_env:{APP_SECRET:"s"}},i=h(a,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");e.equal(i.CRTR_HOME,B()),e.equal(i.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??K()),e.equal(i.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(i.CRTR_SCOPES_FILE,C("m2")),e.equal(i.CRTR_NODE_ID,"m2"),e.equal(i.CRTR_PROFILE_ID,"p-1"),e.equal(i.APP_SECRET,"s");for(const[t,s]of Object.entries(i))e.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${t} names a control plane path: ${s}`);const r=JSON.parse(b(JSON.stringify(a.launch),a.node));e.deepEqual(r.argv.filter((t,s)=>r.argv[s-1]==="-e"),d),e.equal(r.argv.at(-1),"m2"),e.equal(r.env.CRTR_HOME,void 0),e.equal(r.env.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(r.env.CRTR_SCOPES_FILE,C("m2")),e.deepEqual(r.scopes,["a:b"]),e.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),e.throws(()=>b(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),c("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=m(t=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${t}.js`],"server"),o=l(p,"custom-ext.js");_(o,"");const a=[...d,o].flatMap(t=>["-e",t]),r=[...d.map(t=>t.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];e.deepEqual(z(r),[...a,"-n","label","prompt text"])}),c("a control plane that answers 502 and then 200 still gives the start bundle, while a 404 fails at once with its status",async()=>{const n=[502,200],o=H((a,i)=>{const r=a.url?.includes("/gone/")?404:n.shift()??200;i.writeHead(r,{"content-type":"application/json"}),i.end(JSON.stringify(r===200?{launch:{argv:[]},node:{id:"n"}}:{error:"x"}))});await new Promise(a=>o.listen(0,"127.0.0.1",a));try{const a=`http://127.0.0.1:${o.address().port}`;e.deepEqual((await I(a,"exec-502","token")).node,{id:"n"}),e.deepEqual(n,[],"the 502 was asked again"),await e.rejects(I(a,"gone","token"),/answered 404/)}finally{o.close()}});
4
+ setInterval(() => {}, 1000);`);const a=P(process.execPath,[i,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});a.unref();try{let r=0;for(let c=0;c<100&&r===0;c++)try{r=Number(k(o,"utf8"))}catch{await new Promise(y=>setTimeout(y,50))}e.ok(r>0&&h(r),"the detached child is running");const t=Y({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3});e.ok((await t["status.all"]({})).running.some(c=>c.execution==="exec-stop-1"&&c.pid===a.pid),"status.all lists the running broker");const s=await t.stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});e.deepEqual(s,{confirmed:!0}),e.equal(h(a.pid),!1,"the broker is gone"),e.equal(h(r),!1,"the detached child is gone")}finally{try{process.kill(-a.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),d("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},i={launch:{argv:[...m.flatMap(t=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${t.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:p,profile:null},machine_env:{APP_SECRET:"s"}},a=f(i,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");e.equal(a.CRTR_HOME,B()),e.equal(a.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??K()),e.equal(a.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(a.CRTR_SCOPES_FILE,C("m2")),e.equal(a.CRTR_NODE_ID,"m2"),e.equal(a.CRTR_PROFILE_ID,"p-1"),e.equal(a.APP_SECRET,"s");for(const[t,s]of Object.entries(a))e.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${t} names a control plane path: ${s}`);const r=JSON.parse(b(JSON.stringify(i.launch),i.node));e.deepEqual(r.argv.filter((t,s)=>r.argv[s-1]==="-e"),m),e.equal(r.argv.at(-1),"m2"),e.equal(r.env.CRTR_HOME,void 0),e.equal(r.env.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(r.env.CRTR_SCOPES_FILE,C("m2")),e.deepEqual(r.scopes,["a:b"]),e.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),e.throws(()=>b(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),d("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=u(t=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${t}.js`],"server"),o=l(p,"custom-ext.js");_(o,"");const i=[...m,o].flatMap(t=>["-e",t]),r=[...m.map(t=>t.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];e.deepEqual(z(r),[...i,"-n","label","prompt text"])}),d("a control plane that answers 502 and then 200 still gives the start bundle, while a 404 fails at once with its status",async()=>{const n=[502,200],o=H((i,a)=>{const r=i.url?.includes("/gone/")?404:n.shift()??200;a.writeHead(r,{"content-type":"application/json"}),a.end(JSON.stringify(r===200?{launch:{argv:[]},node:{id:"n"}}:{error:"x"}))});await new Promise(i=>o.listen(0,"127.0.0.1",i));try{const i=`http://127.0.0.1:${o.address().port}`;e.deepEqual((await I(i,"exec-502","token")).node,{id:"n"}),e.deepEqual(n,[],"the 502 was asked again"),await e.rejects(I(i,"gone","token"),/answered 404/)}finally{o.close()}});
@@ -3,7 +3,7 @@ import type { AutoDroppedWorktree, AbandonManagedWorktreeResult } from '../../..
3
3
  import type { CloseOnHostOutcome } from '../../../worktree-close.js';
4
4
  import type { AbandonOutcome, FinalizeWorktreeOutcome } from '../../../worktree-mutation-async.js';
5
5
  import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions, RunnerStopResult, RunnerViewerAddress, RunnerWakeResult } from '../types.js';
6
- export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
6
+ export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "status.all", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
7
7
  export type MachineOp = (typeof MACHINE_OPS)[number];
8
8
  /** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
9
9
  * The token sits in `machine_calls.args_json` until the row is deleted a day after it finishes; the execution's token row holds its hash. */
@@ -23,6 +23,15 @@ export interface MachineStopArgs {
23
23
  export interface MachineStatusArgs {
24
24
  execution: RunnerExecution;
25
25
  }
26
+ /** Every broker running on the machine, from one scan of its process table: the control plane's timed check of all its executions
27
+ * there in one call. A machine on a release before this op answers `this machine does not execute status.all`. */
28
+ export type MachineStatusAllArgs = Record<string, never>;
29
+ export interface MachineStatusAllResult {
30
+ running: Array<{
31
+ execution: string;
32
+ pid: number;
33
+ }>;
34
+ }
26
35
  export interface MachineDeleteArgs {
27
36
  nodeId: string;
28
37
  }
@@ -118,6 +127,10 @@ export interface MachineOpTable {
118
127
  args: MachineStatusArgs;
119
128
  result: RunnerStatus;
120
129
  };
130
+ 'status.all': {
131
+ args: MachineStatusAllArgs;
132
+ result: MachineStatusAllResult;
133
+ };
121
134
  delete: {
122
135
  args: MachineDeleteArgs;
123
136
  result: null;
@@ -1 +1 @@
1
- var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
1
+ var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","status.all","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
@@ -11,10 +11,11 @@ export declare function cachedBrokerNodeFields(node: BrokerExtensionNodeDTO): Br
11
11
  * (D39): a grant id, run or node id, structured request, queue, limit, or environment object. `fault_retry` carries a node id: the
12
12
  * fault-retry backstop publishes it in the commit that claims the nudge, and the API process holding that node's stream turns it
13
13
  * into a `fault-retry` line. `machine` carries a machine environment object id (a call is pending for the API process holding its link);
14
- * `machine_call` carries a call id (the caller waiting on it re-reads the row). `document` carries a document object id: it was edited or
14
+ * `machine_call` carries a call id (the caller waiting on it re-reads the row); `execution_exit` carries a node id whose machine broker
15
+ * exited (the lane processes run that node's lifecycle pass). `document` carries a document object id: it was edited or
15
16
  * deleted, and a browser document stream re-reads it. The writers fire them (the
16
17
  * schema's triggers, or the unit that owns the writer); the bus only delivers. */
17
- export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document"];
18
+ export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document", "execution_exit"];
18
19
  export type BrokerSignalKind = (typeof BROKER_SIGNAL_KINDS)[number];
19
20
  export type BrokerSignalSubscriber = (id: string, kind: BrokerSignalKind) => void;
20
21
  export interface BrokerSignalSubscription {
@@ -1 +1 @@
1
- var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
1
+ var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","execution_exit"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
@@ -9,6 +9,10 @@ interface DaemonTickLifecycle extends DetachedWorkLifecycle {
9
9
  }
10
10
  /** Supervision tick over the daemon's current live set. */
11
11
  export declare function superviseTick(now?: number, lifecycle?: DaemonTickLifecycle): Promise<void>;
12
+ /** The node-lifecycle pass for one node whose machine broker exit was just reported (`execution_exit`), as the tick would run it.
13
+ * Every lane process hears the signal; only a pass that still finds the exit unconsumed runs, because the one that consumed it already
14
+ * decided (a later one would read the cleared pid as a stranded launch). A node whose stop is held is left to its stopper by the pass. */
15
+ export declare function exitedNodePass(nodeId: string, now?: number): Promise<void>;
12
16
  export interface DaemonOpts {
13
17
  /** Milliseconds between supervision polls. Default 2000. */
14
18
  intervalMs?: number;