@north-light/cli 0.3.790 → 0.3.791

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 (66) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/nodes.d.ts +0 -12
  4. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  5. package/dist/clients/attach/viewer.js +526 -526
  6. package/dist/commands/node/bash.js +1 -1
  7. package/dist/commands/node/inspect.js +6 -6
  8. package/dist/commands/node/lifecycle.js +4 -4
  9. package/dist/commands/node-context.js +2 -2
  10. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  11. package/dist/core/canvas/node-agent-paths.js +1 -1
  12. package/dist/core/canvas/paths.d.ts +3 -10
  13. package/dist/core/canvas/paths.js +1 -1
  14. package/dist/core/canvas/render-source.js +1 -1
  15. package/dist/core/providers/files.js +1 -1
  16. package/dist/core/runtime/bearings-render.d.ts +2 -2
  17. package/dist/core/runtime/bearings-render.js +11 -11
  18. package/dist/core/runtime/bearings.js +1 -1
  19. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  20. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  21. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  22. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  23. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  24. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  25. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  26. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  27. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  28. package/dist/core/runtime/broker-extension-render.js +2 -2
  29. package/dist/core/runtime/broker.js +1 -1
  30. package/dist/core/runtime/host.js +3 -3
  31. package/dist/core/runtime/kickoff.d.ts +1 -1
  32. package/dist/core/runtime/kickoff.js +12 -12
  33. package/dist/core/runtime/nodes.js +1 -1
  34. package/dist/core/runtime/revive.js +2 -2
  35. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  36. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  37. package/dist/core/runtime/runner/launch-env.js +1 -0
  38. package/dist/core/runtime/runner/machine/executor.js +2 -2
  39. package/dist/core/runtime/runner/types.d.ts +1 -0
  40. package/dist/core/runtime/spawn.js +2 -2
  41. package/dist/core/storage/attachments.d.ts +1 -1
  42. package/dist/core/storage/attachments.js +1 -1
  43. package/dist/core/storage/tables.d.ts +6 -2
  44. package/dist/core/storage/tables.js +4 -4
  45. package/dist/core/substrate/delivery/deliver.js +1 -1
  46. package/dist/core/substrate/delivery/render-boot.js +1 -1
  47. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  48. package/dist/daemon/api/handlers/nodes.js +1 -1
  49. package/dist/daemon/api/map.d.ts +1 -4
  50. package/dist/daemon/api/map.js +2 -2
  51. package/dist/daemon/cron/machine-fire.js +1 -1
  52. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  53. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  54. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  55. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  56. package/package.json +3 -3
  57. package/packages/crouter-api/dist/api/contract.js +1 -1
  58. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  59. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  60. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  61. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  62. package/packages/crouter-api/package.json +1 -1
  63. package/packages/crouter-identity/package.json +1 -1
  64. package/packages/crouter-plugin/package.json +3 -3
  65. package/runtime.lock.json +14 -14
  66. package/scripts/sandbox-start.mjs +5 -3
@@ -1,26 +1,26 @@
1
- var E=Object.defineProperty;var r=(t,e)=>E(t,"name",{value:e,configurable:!0});import{join as _}from"node:path";import{getNode as $,subscriptionsOf as R,subscribersOf as j}from"../canvas/index.js";import{contextDir as w,nodeAgentDir as k}from"../canvas/node-agent-paths.js";import{hasReportDocuments as x}from"../feed/reports.js";import{readdirBeneath as T}from"../spaces/open-beneath.js";import{openDb as c}from"../canvas/db.js";import{bashJobCommandLine as A,bashJobPaths as D,formatBashElapsed as I}from"../bash-jobs.js";import{runningJobs as N}from"../graph/jobs.js";import{readRoadmap as v}from"./roadmap.js";import{buildWakeBearings as M}from"./bearings.js";import{personaDrift as L}from"./persona.js";import{coalesce as O,nodeMailEntry as U}from"../feed/inbox.js";import{claimKickoffMail as B}from"../canvas/deliveries.js";import{formatCard as y}from"../../shared/generated-context.js";import{mapAsync as g}from"../async-array.js";const dt=y("restart-continuation",{},"continue");async function S(t){return _(await w(t),"initial-prompt.md")}r(S,"goalPath");async function G(t){return(await(await c()).prepare("SELECT initial_prompt FROM nodes WHERE node_id = ?").get(t))?.initial_prompt??null}r(G,"readGoal");async function ut(t,e){const n=e.trim();n!==""&&await(await c()).prepare("UPDATE nodes SET initial_prompt = ? WHERE node_id = ?").run(n+`
2
- `,t)}r(ut,"writeGoal");async function ct(t,e){const n=e.trim();return n===""?!1:(await(await c()).prepare("UPDATE nodes SET initial_prompt = ? WHERE node_id = ? AND (initial_prompt IS NULL OR trim(initial_prompt) = '')").run(n+`
3
- `,t)).changes===1}r(ct,"captureGoalIfAbsent");async function lt(t,e){const n=e.trim();n!==""&&await(await c()).prepare("UPDATE nodes SET yield_note = ? WHERE node_id = ?").run(n+`
4
- `,t)}r(lt,"writeYieldMessage");async function W(t){return(await(await c()).prepare("SELECT yield_note FROM nodes WHERE node_id = ?").get(t))?.yield_note?.trim()||null}r(W,"readYieldMessage");async function pt(t){await(await c()).prepare("UPDATE nodes SET yield_note = NULL WHERE node_id = ?").run(t)}r(pt,"clearYieldMessage");async function ft(t){return(await H(t,await w(t))).sort()}r(ft,"listContextDir");async function C(t){return await x(t)}r(C,"hasRetainedReports");async function H(t,e){try{return T(await k(t),e).map(n=>n.name)}catch(n){if(n.code==="ENOENT")return[];throw n}}r(H,"agentDirNames");async function mt(t,e){const n=t.node_id,a=await W(n),o=t.run_id?[]:await B(n,e),s=o.map(f=>f.message.messageId),i=o.map(U);let d=null;if(i.length>0){const f=r(u=>{const h=u.data?.cards;return Array.isArray(h)?h.filter(b=>typeof b=="string"):[]},"cardsFor"),m=[];for(const u of i)(f(u).length>0||m.length===0)&&m.push([]),m.at(-1).push(u);d=(await g(m,async u=>[...f(u[0]),(await O(u)).map(h=>h.text).join(`
1
+ var b=Object.defineProperty;var r=(t,e)=>b(t,"name",{value:e,configurable:!0});import{getNode as E,subscriptionsOf as _,subscribersOf as R}from"../canvas/index.js";import{contextDir as T,nodeAgentDir as $}from"../canvas/node-agent-paths.js";import{hasReportDocuments as j}from"../feed/reports.js";import{readdirBeneath as k}from"../spaces/open-beneath.js";import{openDb as u}from"../canvas/db.js";import{bashJobCommandLine as x,bashJobPaths as I,formatBashElapsed as A}from"../bash-jobs.js";import{runningJobs as D}from"../graph/jobs.js";import{readRoadmap as N}from"./roadmap.js";import{buildWakeBearings as v}from"./bearings.js";import{personaDrift as M}from"./persona.js";import{coalesce as O,nodeMailEntry as L}from"../feed/inbox.js";import{claimKickoffMail as C}from"../canvas/deliveries.js";import{formatCard as w}from"../../shared/generated-context.js";import{mapAsync as y}from"../async-array.js";const it=w("restart-continuation",{},"continue");async function U(t){return"$CRTR_CONTEXT_DIR/initial-prompt.md"}r(U,"goalPath");async function B(t){return(await(await u()).prepare("SELECT initial_prompt FROM nodes WHERE node_id = ?").get(t))?.initial_prompt??null}r(B,"readGoal");async function st(t,e){const n=e.trim();n!==""&&await(await u()).prepare("UPDATE nodes SET initial_prompt = ? WHERE node_id = ?").run(n+`
2
+ `,t)}r(st,"writeGoal");async function dt(t,e){const n=e.trim();return n===""?!1:(await(await u()).prepare("UPDATE nodes SET initial_prompt = ? WHERE node_id = ? AND (initial_prompt IS NULL OR trim(initial_prompt) = '')").run(n+`
3
+ `,t)).changes===1}r(dt,"captureGoalIfAbsent");async function ut(t,e){const n=e.trim();n!==""&&await(await u()).prepare("UPDATE nodes SET yield_note = ? WHERE node_id = ?").run(n+`
4
+ `,t)}r(ut,"writeYieldMessage");async function S(t){return(await(await u()).prepare("SELECT yield_note FROM nodes WHERE node_id = ?").get(t))?.yield_note?.trim()||null}r(S,"readYieldMessage");async function ct(t){await(await u()).prepare("UPDATE nodes SET yield_note = NULL WHERE node_id = ?").run(t)}r(ct,"clearYieldMessage");async function lt(t){return(await W(t,await T(t))).sort()}r(lt,"listContextDir");async function G(t){return await j(t)}r(G,"hasRetainedReports");async function W(t,e){try{return k(await $(t),e).map(n=>n.name)}catch(n){if(n.code==="ENOENT")return[];throw n}}r(W,"agentDirNames");async function pt(t,e){const n=t.node_id,a=await S(n),o=t.run_id?[]:await C(n,e),i=o.map(f=>f.message.messageId),c=o.map(L);let s=null;if(c.length>0){const f=r(d=>{const h=d.data?.cards;return Array.isArray(h)?h.filter(g=>typeof g=="string"):[]},"cardsFor"),m=[];for(const d of c)(f(d).length>0||m.length===0)&&m.push([]),m.at(-1).push(d);s=(await y(m,async d=>[...f(d[0]),(await O(d)).map(h=>h.text).join(`
5
5
 
6
6
  `)].join(`
7
7
 
8
8
  `))).join(`
9
9
 
10
- `)}const l=await L(n),p=l?.guidance===void 0||l.guidance===""?null:l.guidance;return{yieldMsg:a,unreadDigest:d,unreadMessageIds:s,driftGuidance:p}}r(mt,"drainBearings");async function P(t,e){const n=(await g((await R(t)).filter(o=>o.active),async o=>await $(o.node_id))).filter(o=>o!==null&&(o.status==="active"||o.status==="idle")),a=[];if(n.length>0){const o=n.length,s=o===1?"it has":"they have",i=o===1?"Its":"Their";a.push(`Awaiting ${o} node${o===1?"":"s"} \u2014 ${s} not finished. ${i} reports will wake you.`);for(const d of n)a.push(` - ${d.name} (${d.node_id}) \u2014 ${d.status}`);a.push("",e??"(no unread reports)")}else a.push("Awaiting 0 nodes."),a.push("",e??"(no unread reports)");return`<feed>
10
+ `)}const l=await M(n),p=l?.guidance===void 0||l.guidance===""?null:l.guidance;return{yieldMsg:a,unreadDigest:s,unreadMessageIds:i,driftGuidance:p}}r(pt,"drainBearings");async function H(t,e){const n=(await y((await _(t)).filter(o=>o.active),async o=>await E(o.node_id))).filter(o=>o!==null&&(o.status==="active"||o.status==="idle")),a=[];if(n.length>0){const o=n.length,i=o===1?"it has":"they have",c=o===1?"Its":"Their";a.push(`Awaiting ${o} node${o===1?"":"s"} \u2014 ${i} not finished. ${c} reports will wake you.`);for(const s of n)a.push(` - ${s.name} (${s.node_id}) \u2014 ${s.status}`);a.push("",e??"(no unread reports)")}else a.push("Awaiting 0 nodes."),a.push("",e??"(no unread reports)");return`<feed>
11
11
  ${a.join(`
12
12
  `)}
13
- </feed>`}r(P,"feedBlock");function Y(t,e){const n=(t??A(e)).trim()||"(no command)";return n.length>120?`${n.slice(0,117)}\u2026`:n}r(Y,"jobLabel");async function J(t){const e=await w(t),n=await N(await c(),t);if(n.length===0)return null;const a=Date.now(),o=n.length===1,s=[`${n.length} background bash job${o?"":"s"} you started ${o?"is":"are"} STILL RUNNING, detached from any turn and unaffected by your refresh. Each one sends you a message when it exits \u2014 that wake is automatic, so do not poll it and do not relaunch the same command.`];for(const i of n)s.push(` - ${i.jobId} \u2014 ${Y(i.purpose,i.command)} \xB7 running ${I(a-i.startedAtMs)} \xB7 log ${D(e,i.jobId).jobLog}`);return s.push("","Read output so far: `tail -n 50 <log>` (or `crtr node bash list --tail 20`). Abandon one: `crtr node bash kill <job-id>`."),`<background-jobs>
14
- ${s.join(`
13
+ </feed>`}r(H,"feedBlock");function P(t,e){const n=(t??x(e)).trim()||"(no command)";return n.length>120?`${n.slice(0,117)}\u2026`:n}r(P,"jobLabel");async function Y(t){const e=await D(await u(),t);if(e.length===0)return null;const n=Date.now(),a=e.length===1,o=[`${e.length} background bash job${a?"":"s"} you started ${a?"is":"are"} STILL RUNNING, detached from any turn and unaffected by your refresh. Each one sends you a message when it exits \u2014 that wake is automatic, so do not poll it and do not relaunch the same command.`];for(const i of e)o.push(` - ${i.jobId} \u2014 ${P(i.purpose,i.command)} \xB7 running ${A(n-i.startedAtMs)} \xB7 log ${I("$CRTR_CONTEXT_DIR",i.jobId).jobLog}`);return o.push("","Read output so far: `tail -n 50 <log>` (or `crtr node bash list --tail 20`). Abandon one: `crtr node bash kill <job-id>`."),`<background-jobs>
14
+ ${o.join(`
15
15
  `)}
16
- </background-jobs>`}r(J,"backgroundJobsBlock");async function ht(t,e,n){const a=t.node_id,o=["You have been revived fresh after a context refresh \u2014 your previous in-memory context is gone, by design. Everything below was just read from disk; it is your full bearings. Rebuild from it and continue toward your goal."];n!==void 0&&o.push(M(n));const s=await v(a);if(!(s!==null&&s.trim()!=="")&&!await C(a)){const p=await G(a);p!==null&&p.trim()!==""&&o.push(`<goal file="${await S(a)}">
16
+ </background-jobs>`}r(Y,"backgroundJobsBlock");async function ft(t,e,n){const a=t.node_id,o=["You have been revived fresh after a context refresh \u2014 your previous in-memory context is gone, by design. Everything below was just read from disk; it is your full bearings. Rebuild from it and continue toward your goal."];n!==void 0&&o.push(v(n));const i=await N(a);if(!(i!==null&&i.trim()!=="")&&!await G(a)){const p=await B(a);p!==null&&p.trim()!==""&&o.push(`<goal file="${await U(a)}">
17
17
  ${p.trim()}
18
- </goal>`)}const d=await J(a);d!==null&&o.push(d),o.push(await P(a,e.unreadDigest)),o.push(e.yieldMsg!==null?`<yield-message>
18
+ </goal>`)}const s=await Y(a);s!==null&&o.push(s),o.push(await H(a,e.unreadDigest)),o.push(e.yieldMsg!==null?`<yield-message>
19
19
  ${e.yieldMsg.trim()}
20
- </yield-message>`:"<yield-message/>");const l=(await j(a)).length>0;return o.push(l?"If there is work to do, perform it. Otherwise stop \u2014 pipe the result to `crtr push final` through a single-quoted heredoc if the goal is met, or end your turn without a message to stay dormant awaiting your workers.":"If there is work to do, perform it. Otherwise end your turn without writing a message \u2014 the user already has your last reply, and a status recap would only bury it. You are working directly with the user, so stay available and continue when they write back."),e.driftGuidance!==null&&o.push(`<persona-transition>
20
+ </yield-message>`:"<yield-message/>");const l=(await R(a)).length>0;return o.push(l?"If there is work to do, perform it. Otherwise stop \u2014 pipe the result to `crtr push final` through a single-quoted heredoc if the goal is met, or end your turn without a message to stay dormant awaiting your workers.":"If there is work to do, perform it. Otherwise end your turn without writing a message \u2014 the user already has your last reply, and a status recap would only bury it. You are working directly with the user, so stay available and continue when they write back."),e.driftGuidance!==null&&o.push(`<persona-transition>
21
21
  Your role was changed while you were away. ${e.driftGuidance}
22
- </persona-transition>`),y("revive",{},`
22
+ </persona-transition>`),w("revive",{},`
23
23
  ${o.join(`
24
24
 
25
25
  `)}
26
- `)}r(ht,"buildReviveKickoff");export{dt as RUNTIME_RESTART_CONTINUATION,ht as buildReviveKickoff,ct as captureGoalIfAbsent,pt as clearYieldMessage,mt as drainBearings,S as goalPath,C as hasRetainedReports,ft as listContextDir,G as readGoal,W as readYieldMessage,ut as writeGoal,lt as writeYieldMessage};
26
+ `)}r(ft,"buildReviveKickoff");export{it as RUNTIME_RESTART_CONTINUATION,ft as buildReviveKickoff,dt as captureGoalIfAbsent,ct as clearYieldMessage,pt as drainBearings,U as goalPath,G as hasRetainedReports,lt as listContextDir,B as readGoal,S as readYieldMessage,st as writeGoal,ut as writeYieldMessage};
@@ -1 +1 @@
1
- var z=Object.defineProperty;var l=(e,r)=>z(e,"name",{value:r,configurable:!0});import{envHomeOverride as J,envRuntimeHomeOverride as V,INBOX_BETWEEN_TURNS_ENV as Y,SCOPES_FILE_ENV as Z,scopeAllowed as C}from"../../shared/env.js";import{isOwnMemoryScope as Q,validateScopes as ee}from"../scopes.js";import{activeGrant as F,terminalGrant as B}from"../grants/mirror.js";import{callerPerson as ne,nodeTerminalGrant as P}from"../grants/terminal.js";import{grantSnapshotMissing as re}from"../../daemon/readiness.js";import{appendRunEvent as te}from"../runs/events.js";import{ZERO_RUN_USAGE as ie}from"../../api/dto/run-events.js";import{isCloudRole as oe,personId as ae}from"../canvas/person.js";import{InputError as k}from"../io.js";import{ApiError as w}from"../../api/errors.js";import{assertGranteeRunsHere as le}from"./unsandboxed.js";import{randomBytes as se}from"node:crypto";import{existsSync as U}from"node:fs";import{resolve as de,relative as ce,isAbsolute as L,join as ue,sep as fe}from"node:path";import{appSpace as me}from"../layout.js";import{scopesFilePath as pe}from"../canvas/paths.js";import{createNode as _e,assertRunNotDeleting as we,conversationOwner as ge,getNode as u,getRow as he}from"../canvas/index.js";import{ensureAppSpace as Re}from"../spaces/space.js";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{blaxelEnvironmentOf as ve}from"./blaxel-environment.js";import{resolveInstallId as Ee}from"../canvas/install-id.js";import{isAppRun as ye}from"../canvas/app-run.js";import{contextDir as Ie}from"../canvas/paths.js";import{conversationIdFromPath as Ce}from"../conversation-store/index.js";import{usage as q}from"../errors.js";import{assertProfileAvailableForBirth as Ne}from"../profiles/deletion-reservation.js";import{loadExactProfileManifest as Se}from"../profiles/manifest.js";import{admitNodeCreate as ke}from"../command-hooks/lifecycle-create.js";import{getById as Te,nodeObject as N,ownerForGrantee as De}from"../graph/objects.js";import{recordActedOn as Oe}from"../graph/edges.js";import{recordWatch as xe,copyWatchesForFork as be}from"../graph/watches.js";import{publish as Ae}from"../graph/events.js";import{canvasDatabaseUrl as Me}from"../canvas/db.js";import{someAsync as $e}from"../async-array.js";import{admitIntoManagedCheckout as Fe}from"../worktree-mutation-async.js";let T;const G=new Map;function kn(e){T=e}l(kn,"setInstallId");async function Be(){if(T!==void 0)return T;const e=await Me(),r=G.get(e);if(r!==void 0)return r;const o=await Ee();return G.set(e,o),o}l(Be,"installId");function Pe(){return`${Date.now().toString(36)}-${se(4).toString("hex")}`}l(Pe,"newJobId");async function Ue(){return`${await Be()}-${Pe()}`}l(Ue,"newNodeId");const D=128,Le=/^[a-z0-9-]+$/;class W extends Error{static{l(this,"NodeIdConflictError")}nodeId;constructor(r){super(`node already exists: ${r}`),this.nodeId=r,this.name="NodeIdConflictError"}}function O(e){if(e.length===0||e.length>D)throw q(`invalid --node-id '${e}': must be 1-${D} characters`,{next:`Pass an id-safe string (lowercase letters, digits, hyphens) of at most ${D} characters.`});if(!Le.test(e))throw q(`invalid --node-id '${e}': must contain only lowercase letters, digits, and hyphens (e.g. 'remote42', 'my-node-1')`,{next:"Use only lowercase letters, digits, and hyphens."})}l(O,"validateNodeIdFormat");async function Tn(e){if(O(e),await u(e)!==null)throw new W(e)}l(Tn,"preflightNodeId");async function He(e){if(O(e),await u(e)!==null)throw new W(e);return e}l(He,"validatedExplicitNodeId");async function Dn(e){let r=e;const o=new Set;for(;;){if(o.has(r))return r;o.add(r);const s=await he(r);if(s===null||s.parent==null)return r;r=s.parent}}l(Dn,"rootOfSpine");function On(){const e=process.env;return{nodeId:e.CRTR_NODE_ID??null,kind:e.CRTR_KIND??null,mode:e.CRTR_MODE??null}}l(On,"currentNodeContext");function qe(e){return ye(e)}l(qe,"inboxBetweenTurns");function xn(e){const r={CRTR_NODE_ID:e.node_id,CRTR_KIND:e.kind,CRTR_MODE:e.mode,CRTR_LIFECYCLE:e.lifecycle,CRTR_NODE_CWD:e.cwd,CRTR_CONTEXT_DIR:Ie(e.node_id,e.grantee),...e.deadline_at?{CRTR_NODE_DEADLINE_AT:e.deadline_at}:{},CRTR_CYCLES:(e.cycles??0).toString(),CRTR_PROFILE_ID:e.profile_id??"",PI_CLAUDE_OAUTH_REINJECT_SCOPE:"never"};e.parent&&(r.CRTR_PARENT_NODE_ID=e.parent),e.run_id&&(r.CRTR_RUN_ID=e.run_id),qe(e)&&(r[Y]="1"),e.scopes!==null&&e.scopes!==void 0&&(r[Z]=pe(e.node_id)),r.CRTR_GRANTEE=e.grantee??"app:terminal";const o=J();o!==void 0&&o!==""&&(r.CRTR_HOME=o);const s=V();s!==void 0&&s!==""&&(r.CRTR_RUNTIME_HOME=s);const f=process.env.CRTR_SUBTREE;return f!==void 0&&f!==""&&(r.CRTR_SUBTREE=f),{...r,...e.launch?.env??{}}}l(xn,"nodeEnv");async function Ge(e){const r=Ce(e),o=r===null?null:await ge(r);return o===null?null:await u(o)}l(Ge,"forkSourceNode");async function bn(e){const r=e.nodeId!==void 0?(O(e.nodeId),e.nodeId):await Ue(),o=e.parent??null,s=o===null,f=e.spawnedBy??o,p=e.creator??null,x=e.mode??"base",S=e.lifecycle??(s?"resident":"terminal"),E=e.run===void 0?await ne():null;let h=E===null?null:await B(E);const n={node_id:r,name:e.name??e.kind,description:e.description,cycles:0,created:new Date().toISOString(),cwd:e.cwd,host_kind:"broker",profile_id:e.profile_id??null,kind:e.kind,mode:x,lifecycle:S,persona_ack:{kind:e.kind,mode:x,lifecycle:S},status:"active",parent:o,spawned_by:f,creator:p,fork_from:e.forkFrom,fork_source_file:e.forkSourceFile,review_binding:e.reviewBinding,model_override:e.modelOverride??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:e.run?.grantee??"app:terminal",sub:e.run?.sub??h?.sub??null,grant_id:e.run?.grant_id??h?.id??null,client_id:e.run?.client_id??null,metadata_json:s?e.run?.metadata_json??null:null,run_id:s?r:e.run?.run_id??null,event_cursor:s?e.run?.event_cursor??1:null,passive_default:e.passiveDefault??!1,caused_by:e.causedBy??null,...e.managedWorktree!==void 0?{managed_worktree:e.managedWorktree}:{},intent:null,deadline_at:e.deadlineAt??null,pi_session_id:null,pi_session_file:null,launch:e.launch},y=e.scopes===void 0?void 0:ee(e.scopes),R=o===null?null:await u(o);if(o!==null&&R===null)throw new Error(`cannot spawn under unknown parent node: ${o}`);if(R?.run_id&&(await u(R.run_id))?.deleting_at)throw new Error("run is deleting");const c=p===null?null:await u(p);if(p!==null&&c===null)throw new Error(`cannot spawn from unknown creator node: ${p}`);if(c?.run_id&&(await u(c.run_id))?.deleting_at)throw new Error("run is deleting");const b=e.forkSourceFile==null?null:await Ge(e.forkSourceFile),A=e.replaces==null?null:await u(e.replaces),_=R??b??A??c??(f===null?null:await u(f)),j=[R,c,b,A,f===null?null:await u(f)],M=await $e(j,async t=>t?.isolated===!0||t?.run_id!=null&&(await u(t.run_id))?.isolated===!0);if(M&&e.isolated===!1)throw new w(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});if(n.isolated=M||e.isolated===!0,_!==null){const t=c??_;if(c&&_.grantee&&c.grantee&&c.grantee!==_.grantee)throw new w(403,"other_app_run","cannot create under another app's node");const i=c&&c!==_?[_,c]:[_];if(oe()&&E!==null&&i.some(a=>a.sub&&a.sub!==E))throw new w(403,"other_person_run","cannot create under another person's node");const d=[],g=new Set;for(const a of i){a.scopes!==null&&a.scopes!==void 0&&d.push(a.scopes);const m=a.grantee==="app:terminal"?await P(a):a.grant_id?await F(a.grant_id):null;if(m){const v=[...m.resolved];g.add(v),d.push(v)}else{const v=[];g.add(v),d.push(v)}}const I=l(a=>Q(a,t.grantee??"app:terminal"),"ownMemory"),$=l((a,m)=>I(m)&&g.has(a)||C(a,m),"allowed");if(y!==void 0&&!y.every(a=>d.every(m=>$(m,a))))throw new k({error:"unknown_scope",message:"child scopes must be covered by the creating node, its source and their current grants",received:y,field:"scopes",next:"Request only scopes the creating node currently holds."});if(n.scopes=y??(i.every(a=>a.scopes==null)&&i.every(a=>a.grant_id===t.grant_id&&a.sub===t.sub)?null:i.length===1?_.scopes??null:[...new Set(d.flat().filter(a=>d.every(m=>$(m,a))))]),n.scopes?.includes("crtr:act")&&!C(n.scopes,"crtr:llm"))throw new k({error:"invalid_scope",message:"crtr:act requires crtr:llm",received:n.scopes,field:"scopes",next:"Include crtr:llm or omit crtr:act."});n.grantee=t.grantee,n.grantee==="app:terminal"&&t.sub&&(h=await B(t.sub)),n.sub=t.sub??(n.grantee==="app:terminal"?h?.sub:null)??null,n.grant_id=t.grant_id??(n.grantee==="app:terminal"?h?.id:null)??null,n.client_id=t.client_id,n.run_id=s?r:t.run_id??null}if(le(n.grantee),e.run===void 0&&n.grantee==="app:terminal"&&h===null)throw await re()?new w(503,"runtime_starting","the first grant snapshot from the directory has not committed"):new w(403,"scope_missing","terminal grant is not active");if(n.isolated){if((process.platform!=="linux"||!U(H))&&await ve(n.profile_id??null)===null)throw new w(400,"isolated_unavailable","isolated nodes require the Linux root launcher");if(e.managedWorktree!==void 0)throw new w(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const t=ue(me(n.grantee??"app:terminal").nodes,r),i=ce(t,de(n.cwd));if(!L(n.cwd)||i===".."||i.startsWith(`..${fe}`)||L(i))throw new w(400,"invalid_request","isolated node cwd must be inside its own folder",{param:"cwd"})}if(n.profile_id){const t=Se(n.profile_id).manifest.grantee??"app:terminal";if(t!==n.grantee){const i=`crtr:memory:rw:${t}:profile:${n.profile_id}`,d=n.grantee==="app:terminal"?await P(n):n.grant_id?await F(n.grant_id):null;if(!d||d.grantee!==n.grantee||!C(d.resolved,i)||!C(n.scopes,i))throw new k({error:"scope_missing",message:`missing scope ${i}`,received:n.profile_id,field:"profile",next:"Select a profile covered by this run and its current grant."})}}if(Ne(n.profile_id??null),!n.grantee)throw new Error("node creation requires an app");const K=await ke({kind:n.kind,mode:n.mode,cwd:n.cwd,profile:n.profile_id??null,root:s,parentId:o,requestingNodeId:p,lifecycle:S,replaces:e.replaces??null},n.grantee),X=l(async(t,i)=>{const d=await N(t,i.node_id),g=p??o??e.actor??f??null,I=g!==null&&(await Te(t,g))?.type==="node"?await N(t,g):await De(t,e.run===void 0?ae():i.grantee);await Oe(t,I,d),o!==null&&e.subscribe!==!1&&await xe(t,await N(t,o),d,"spawn"),e.forkSourceNode&&await be(t,await N(t,e.forkSourceNode),d),await Ae(t,{event:"created",object:d,actor:I,attrs:{name:i.name,kind:i.kind,creator:p??null}})},"recordBirth");try{e.nodeId!==void 0&&await He(e.nodeId),await e.beforeCreate?.(),(process.platform!=="linux"||U(H))&&await Re(n.grantee??"app:terminal"),await Fe(n.cwd,r,()=>_e(n,{outcomeDelivery:e.outcomeDelivery,withinCreate:l(async(t,i)=>{i.run_id&&i.run_id!==i.node_id&&await we(t,i.run_id),s&&e.run===void 0&&await te(t,r,r,"run.started",{scopes:i.scopes??null,payer:"user",usage:ie}),await e.withinCreate?.(t,i),await X(t,i)},"withinCreate")}))}finally{K()}return n}l(bn,"spawnNode");export{W as NodeIdConflictError,On as currentNodeContext,Ge as forkSourceNode,qe as inboxBetweenTurns,Pe as newJobId,Ue as newNodeId,xn as nodeEnv,Tn as preflightNodeId,Dn as rootOfSpine,kn as setInstallId,bn as spawnNode};
1
+ var J=Object.defineProperty;var l=(e,r)=>J(e,"name",{value:r,configurable:!0});import{envHomeOverride as V,envRuntimeHomeOverride as X,INBOX_BETWEEN_TURNS_ENV as Y,SCOPES_FILE_ENV as Z,scopeAllowed as C}from"../../shared/env.js";import{isOwnMemoryScope as Q,validateScopes as ee}from"../scopes.js";import{activeGrant as F,terminalGrant as B}from"../grants/mirror.js";import{callerPerson as ne,nodeTerminalGrant as P}from"../grants/terminal.js";import{grantSnapshotMissing as re}from"../../daemon/readiness.js";import{appendRunEvent as te}from"../runs/events.js";import{ZERO_RUN_USAGE as ie}from"../../api/dto/run-events.js";import{isCloudRole as oe,personId as ae}from"../canvas/person.js";import{InputError as k}from"../io.js";import{ApiError as _}from"../../api/errors.js";import{assertGranteeRunsHere as le}from"./unsandboxed.js";import{randomBytes as se}from"node:crypto";import{existsSync as U}from"node:fs";import{resolve as de,relative as ce,isAbsolute as L,join as ue,sep as fe}from"node:path";import{appSpace as me}from"../layout.js";import{scopesFilePath as pe}from"../canvas/paths.js";import{createNode as we,assertRunNotDeleting as _e,conversationOwner as ge,getNode as u,getRow as he}from"../canvas/index.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{blaxelEnvironmentOf as Re}from"./blaxel-environment.js";import{resolveInstallId as Ee}from"../canvas/install-id.js";import{isAppRun as ye}from"../canvas/app-run.js";import{conversationIdFromPath as Ie}from"../conversation-store/index.js";import{usage as q}from"../errors.js";import{assertProfileAvailableForBirth as Ce}from"../profiles/deletion-reservation.js";import{loadExactProfileManifest as Ne}from"../profiles/manifest.js";import{admitNodeCreate as Se}from"../command-hooks/lifecycle-create.js";import{getById as ke,nodeObject as N,ownerForGrantee as Te}from"../graph/objects.js";import{recordActedOn as De}from"../graph/edges.js";import{recordWatch as Oe,copyWatchesForFork as xe}from"../graph/watches.js";import{publish as be}from"../graph/events.js";import{canvasDatabaseUrl as Ae}from"../canvas/db.js";import{someAsync as Me}from"../async-array.js";import{admitIntoManagedCheckout as $e}from"../worktree-mutation-async.js";let T;const G=new Map;function Nn(e){T=e}l(Nn,"setInstallId");async function Fe(){if(T!==void 0)return T;const e=await Ae(),r=G.get(e);if(r!==void 0)return r;const o=await Ee();return G.set(e,o),o}l(Fe,"installId");function Be(){return`${Date.now().toString(36)}-${se(4).toString("hex")}`}l(Be,"newJobId");async function Pe(){return`${await Fe()}-${Be()}`}l(Pe,"newNodeId");const D=128,Ue=/^[a-z0-9-]+$/;class W extends Error{static{l(this,"NodeIdConflictError")}nodeId;constructor(r){super(`node already exists: ${r}`),this.nodeId=r,this.name="NodeIdConflictError"}}function O(e){if(e.length===0||e.length>D)throw q(`invalid --node-id '${e}': must be 1-${D} characters`,{next:`Pass an id-safe string (lowercase letters, digits, hyphens) of at most ${D} characters.`});if(!Ue.test(e))throw q(`invalid --node-id '${e}': must contain only lowercase letters, digits, and hyphens (e.g. 'remote42', 'my-node-1')`,{next:"Use only lowercase letters, digits, and hyphens."})}l(O,"validateNodeIdFormat");async function Sn(e){if(O(e),await u(e)!==null)throw new W(e)}l(Sn,"preflightNodeId");async function Le(e){if(O(e),await u(e)!==null)throw new W(e);return e}l(Le,"validatedExplicitNodeId");async function kn(e){let r=e;const o=new Set;for(;;){if(o.has(r))return r;o.add(r);const s=await he(r);if(s===null||s.parent==null)return r;r=s.parent}}l(kn,"rootOfSpine");function Tn(){const e=process.env;return{nodeId:e.CRTR_NODE_ID??null,kind:e.CRTR_KIND??null,mode:e.CRTR_MODE??null}}l(Tn,"currentNodeContext");function He(e){return ye(e)}l(He,"inboxBetweenTurns");function Dn(e){const r={CRTR_NODE_ID:e.node_id,CRTR_KIND:e.kind,CRTR_MODE:e.mode,CRTR_LIFECYCLE:e.lifecycle,CRTR_NODE_CWD:e.cwd,...e.deadline_at?{CRTR_NODE_DEADLINE_AT:e.deadline_at}:{},CRTR_CYCLES:(e.cycles??0).toString(),CRTR_PROFILE_ID:e.profile_id??"",PI_CLAUDE_OAUTH_REINJECT_SCOPE:"never"};e.parent&&(r.CRTR_PARENT_NODE_ID=e.parent),e.run_id&&(r.CRTR_RUN_ID=e.run_id),He(e)&&(r[Y]="1"),e.scopes!==null&&e.scopes!==void 0&&(r[Z]=pe(e.node_id)),r.CRTR_GRANTEE=e.grantee??"app:terminal";const o=V();o!==void 0&&o!==""&&(r.CRTR_HOME=o);const s=X();s!==void 0&&s!==""&&(r.CRTR_RUNTIME_HOME=s);const f=process.env.CRTR_SUBTREE;return f!==void 0&&f!==""&&(r.CRTR_SUBTREE=f),{...r,...e.launch?.env??{}}}l(Dn,"nodeEnv");async function qe(e){const r=Ie(e),o=r===null?null:await ge(r);return o===null?null:await u(o)}l(qe,"forkSourceNode");async function On(e){const r=e.nodeId!==void 0?(O(e.nodeId),e.nodeId):await Pe(),o=e.parent??null,s=o===null,f=e.spawnedBy??o,p=e.creator??null,x=e.mode??"base",S=e.lifecycle??(s?"resident":"terminal"),E=e.run===void 0?await ne():null;let h=E===null?null:await B(E);const n={node_id:r,name:e.name??e.kind,description:e.description,cycles:0,created:new Date().toISOString(),cwd:e.cwd,host_kind:"broker",profile_id:e.profile_id??null,kind:e.kind,mode:x,lifecycle:S,persona_ack:{kind:e.kind,mode:x,lifecycle:S},status:"active",parent:o,spawned_by:f,creator:p,fork_from:e.forkFrom,fork_source_file:e.forkSourceFile,review_binding:e.reviewBinding,model_override:e.modelOverride??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:e.run?.grantee??"app:terminal",sub:e.run?.sub??h?.sub??null,grant_id:e.run?.grant_id??h?.id??null,client_id:e.run?.client_id??null,metadata_json:s?e.run?.metadata_json??null:null,run_id:s?r:e.run?.run_id??null,event_cursor:s?e.run?.event_cursor??1:null,passive_default:e.passiveDefault??!1,caused_by:e.causedBy??null,...e.managedWorktree!==void 0?{managed_worktree:e.managedWorktree}:{},intent:null,deadline_at:e.deadlineAt??null,pi_session_id:null,pi_session_file:null,launch:e.launch},y=e.scopes===void 0?void 0:ee(e.scopes),v=o===null?null:await u(o);if(o!==null&&v===null)throw new Error(`cannot spawn under unknown parent node: ${o}`);if(v?.run_id&&(await u(v.run_id))?.deleting_at)throw new Error("run is deleting");const c=p===null?null:await u(p);if(p!==null&&c===null)throw new Error(`cannot spawn from unknown creator node: ${p}`);if(c?.run_id&&(await u(c.run_id))?.deleting_at)throw new Error("run is deleting");const b=e.forkSourceFile==null?null:await qe(e.forkSourceFile),A=e.replaces==null?null:await u(e.replaces),w=v??b??A??c??(f===null?null:await u(f)),j=[v,c,b,A,f===null?null:await u(f)],M=await Me(j,async t=>t?.isolated===!0||t?.run_id!=null&&(await u(t.run_id))?.isolated===!0);if(M&&e.isolated===!1)throw new _(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});if(n.isolated=M||e.isolated===!0,w!==null){const t=c??w;if(c&&w.grantee&&c.grantee&&c.grantee!==w.grantee)throw new _(403,"other_app_run","cannot create under another app's node");const i=c&&c!==w?[w,c]:[w];if(oe()&&E!==null&&i.some(a=>a.sub&&a.sub!==E))throw new _(403,"other_person_run","cannot create under another person's node");const d=[],g=new Set;for(const a of i){a.scopes!==null&&a.scopes!==void 0&&d.push(a.scopes);const m=a.grantee==="app:terminal"?await P(a):a.grant_id?await F(a.grant_id):null;if(m){const R=[...m.resolved];g.add(R),d.push(R)}else{const R=[];g.add(R),d.push(R)}}const I=l(a=>Q(a,t.grantee??"app:terminal"),"ownMemory"),$=l((a,m)=>I(m)&&g.has(a)||C(a,m),"allowed");if(y!==void 0&&!y.every(a=>d.every(m=>$(m,a))))throw new k({error:"unknown_scope",message:"child scopes must be covered by the creating node, its source and their current grants",received:y,field:"scopes",next:"Request only scopes the creating node currently holds."});if(n.scopes=y??(i.every(a=>a.scopes==null)&&i.every(a=>a.grant_id===t.grant_id&&a.sub===t.sub)?null:i.length===1?w.scopes??null:[...new Set(d.flat().filter(a=>d.every(m=>$(m,a))))]),n.scopes?.includes("crtr:act")&&!C(n.scopes,"crtr:llm"))throw new k({error:"invalid_scope",message:"crtr:act requires crtr:llm",received:n.scopes,field:"scopes",next:"Include crtr:llm or omit crtr:act."});n.grantee=t.grantee,n.grantee==="app:terminal"&&t.sub&&(h=await B(t.sub)),n.sub=t.sub??(n.grantee==="app:terminal"?h?.sub:null)??null,n.grant_id=t.grant_id??(n.grantee==="app:terminal"?h?.id:null)??null,n.client_id=t.client_id,n.run_id=s?r:t.run_id??null}if(le(n.grantee),e.run===void 0&&n.grantee==="app:terminal"&&h===null)throw await re()?new _(503,"runtime_starting","the first grant snapshot from the directory has not committed"):new _(403,"scope_missing","terminal grant is not active");if(n.isolated){if((process.platform!=="linux"||!U(H))&&await Re(n.profile_id??null)===null)throw new _(400,"isolated_unavailable","isolated nodes require the Linux root launcher");if(e.managedWorktree!==void 0)throw new _(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const t=ue(me(n.grantee??"app:terminal").nodes,r),i=ce(t,de(n.cwd));if(!L(n.cwd)||i===".."||i.startsWith(`..${fe}`)||L(i))throw new _(400,"invalid_request","isolated node cwd must be inside its own folder",{param:"cwd"})}if(n.profile_id){const t=Ne(n.profile_id).manifest.grantee??"app:terminal";if(t!==n.grantee){const i=`crtr:memory:rw:${t}:profile:${n.profile_id}`,d=n.grantee==="app:terminal"?await P(n):n.grant_id?await F(n.grant_id):null;if(!d||d.grantee!==n.grantee||!C(d.resolved,i)||!C(n.scopes,i))throw new k({error:"scope_missing",message:`missing scope ${i}`,received:n.profile_id,field:"profile",next:"Select a profile covered by this run and its current grant."})}}if(Ce(n.profile_id??null),!n.grantee)throw new Error("node creation requires an app");const K=await Se({kind:n.kind,mode:n.mode,cwd:n.cwd,profile:n.profile_id??null,root:s,parentId:o,requestingNodeId:p,lifecycle:S,replaces:e.replaces??null},n.grantee),z=l(async(t,i)=>{const d=await N(t,i.node_id),g=p??o??e.actor??f??null,I=g!==null&&(await ke(t,g))?.type==="node"?await N(t,g):await Te(t,e.run===void 0?ae():i.grantee);await De(t,I,d),o!==null&&e.subscribe!==!1&&await Oe(t,await N(t,o),d,"spawn"),e.forkSourceNode&&await xe(t,await N(t,e.forkSourceNode),d),await be(t,{event:"created",object:d,actor:I,attrs:{name:i.name,kind:i.kind,creator:p??null}})},"recordBirth");try{e.nodeId!==void 0&&await Le(e.nodeId),await e.beforeCreate?.(),(process.platform!=="linux"||U(H))&&await ve(n.grantee??"app:terminal"),await $e(n.cwd,r,()=>we(n,{outcomeDelivery:e.outcomeDelivery,withinCreate:l(async(t,i)=>{i.run_id&&i.run_id!==i.node_id&&await _e(t,i.run_id),s&&e.run===void 0&&await te(t,r,r,"run.started",{scopes:i.scopes??null,payer:"user",usage:ie}),await e.withinCreate?.(t,i),await z(t,i)},"withinCreate")}))}finally{K()}return n}l(On,"spawnNode");export{W as NodeIdConflictError,Tn as currentNodeContext,qe as forkSourceNode,He as inboxBetweenTurns,Be as newJobId,Pe as newNodeId,Dn as nodeEnv,Sn as preflightNodeId,kn as rootOfSpine,Nn as setInstallId,On as spawnNode};
@@ -1,3 +1,3 @@
1
- var ue=Object.defineProperty;var o=(e,r)=>ue(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as fe}from"./unsandboxed.js";import{existsSync as W}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as J}from"../conversation-store/index.js";import{isAbsolute as we}from"node:path";import{findNodeBySessionFile as he,getNode as b,updateNode as A,beginExecution as me,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as O,endLiveExecution as ve,unbindSession as j,recordLaunch as _e,setFrozen as ye,clearFrozen as P,fullName as ke}from"../canvas/index.js";import{emitEvent as V}from"../events/emit.js";import{consumeDeadlineOnWake as ge}from"../feed/messages.js";import{isParked as B,transition as R}from"./lifecycle.js";import{publishNotice as be}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as Re,drainBearings as Ee,hasRetainedReports as xe,readGoal as x,readYieldMessage as Se,RUNTIME_RESTART_CONTINUATION as $e}from"./kickoff.js";import{readRoadmap as X}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as Y}from"../runs/initial-input.js";import{headlessBrokerHost as Fe,brokerLaunchJson as Ae}from"./host.js";import{isCloudRole as Oe}from"../canvas/person.js";import{asNodePerson as Pe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Be}from"./runner/process.js";import{runnerForEnvironment as q}from"./runner/index.js";import{MachineOfflineError as Q}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as D}from"./blaxel-environment.js";import{recordLaunchFailure as De}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Z,remoteMachineEnvironmentOf as I,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as ee,brokerCapReached as re,brokerThresholdsForDaemon as T}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ie,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function mr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof J)return{};throw n}}o(mr,"resumeArgs");async function te(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof J)return!1;throw i}}o(te,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}o(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||W(i)}o(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await te(n))return{};const u=await he(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await mr(r,i)}o(vr,"resumableSessionArgs");async function _r(e){return await X(e)===null&&await Se(e)===null&&!await xe(e)}o(_r,"isUnstartedBirth");async function hi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await X(e);return i!==null&&i.trim()!==""}o(hi,"hasFreshGroundState");async function mi(e,r){const i=await ne(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}o(mi,"reviveNode");async function pi(e,r,i){return ne(e,{...r,viewerAttach:!0},i)}o(pi,"decideAttachRevive");async function ne(e,r,i){const t=Oe()?await b(e):null;return t===null?await ae(e,r,i):await Pe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ae(e,r,i))}o(ne,"decideRevive");async function ae(e,r,i){let t=await b(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await b(e)??t,t.run_id&&(await b(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);(i||!(t.lifecycle==="resident"&&B(t)))&&await gr(e,t),ar(t.profile_id),fe(t.grantee);const n=ee(),u=await D(t.profile_id??null)!==null||await I(t.profile_id??null)!==null,M=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&B(t))&&(await ir(t),await tr(t),await D(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await R(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&B(t))return{parked:!0};if(M){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await oe(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const m=await Ue();if(m&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const f=!m&&(u||await n.reserveSlot(e));let s=null;if(f&&!u){try{s=await Je(e)}catch(S){throw n.releaseReservation(e),S}s.verdict!=="admitted"&&n.releaseReservation(e)}if(s?.verdict==="too_small")throw We(s);if(!f||s?.verdict==="denied"){if(r.capacity==="refuse")throw s?.verdict==="denied"?Ke(s):re(T().automaticReviveCap,await n.occupancy());return await oe(e,t,m?{reason:"drain"}:s?.verdict==="denied"?{reason:"app_memory",free_bytes:s.free_bytes,needed_bytes:s.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:T().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await Rr(e,t,r)}}finally{n.releaseReservation(e)}}o(ae,"decideReviveAsCaller");async function oe(e,r,i){r.frozen_at==null&&(await ye(e,new Date().toISOString()),await ve(e,{reason:"frozen"}),V({level:"info",event:"broker.frozen",node_id:e,fields:i}))}o(oe,"freezeForWait");async function yr(e,r){const i=await D(r.profile_id??null),t=await I(r.profile_id??null)!==null;if(!(i!==null||t)&&!W(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}o(yr,"assertRecordedCwdExists");function kr(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}o(kr,"assertCheckoutNotRemoved");async function gr(e,r){try{kr(e,r)}catch(i){throw(r.status==="active"||r.status==="idle")&&(await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:i.message}}}),await P(e)),i}}o(gr,"refuseRemovedCheckout");async function br(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}o(br,"runNodeStartHooks");async function Rr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await A(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await j(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,f=r.fork_source_file;if(m&&(typeof f!="string"||!we(f)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const s=m&&typeof f=="string";if(s&&!await te(f))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${f}`,next:`Restore ${f}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:S}=T();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const se=t!==null?q("blaxel"):n?q("machine"):Be;let w;try{w=await me(e,{daemonEpoch:ee().epoch(),...u?{}:{cap:S},...t!==null?{runner:"blaxel",release:Z()}:n?{runner:"machine",release:Z()}:{}})}catch(l){if(l instanceof ze)throw re(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await A(e,{cycles:r.cycles});const $=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=s?{}:await vr(e,r,$,!u),k=p.resumeSessionPath!==void 0,L=k&&p.newCycle===!0,v=k&&!L,z=!k&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),C=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(p.resumeSessionPath)?(await x(e))?.trim():void 0,H=C!==void 0&&C!=="",le=s||z||H,G=r.cycle_pending===!0||L;await A(e,{cycle_pending:G}),r.cycle_pending=G,!s&&!k&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await j(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const N=o(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(s){const a=await x(e),F=_(f);if(F===null)throw new Error(`invalid fork source ${f}`);const ce=(await d().header(await d().fork(F,e))).path;c=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=N()),await qe(e,(await Ze(f))?.node_id??null)}else if(H)c=y(r,{...p,prompt:C}),h=N(),await Y(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:$e}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(z){const a=(await x(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=N(),await Y(c,r)),await ie(e)}else{const a=await Ee(r,w);c=y(r,{...p,prompt:await Re(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ie(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[Ne]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await R(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const U=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ge(e),await ur(e,r.grantee),await br(e,r,le),c.env={...c.env,CRTR_EXECUTION_ID:w};const K=await Ae(e,c,r.cwd);await Ge(w,K);let g;try{const a=await He(e);if(g=await se.start({executionId:w,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:K,cwd:r.cwd,resuming:v}),!u&&g.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Q)throw a;try{await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await be(e,"notice.crash",`Child crashed \u2014 ${ke(r)} (${e}) failed to relaunch and is now dead: ${a.message}
1
+ var ue=Object.defineProperty;var o=(e,r)=>ue(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as fe}from"./unsandboxed.js";import{existsSync as W}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as J}from"../conversation-store/index.js";import{isAbsolute as we}from"node:path";import{findNodeBySessionFile as he,getNode as b,updateNode as A,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as pe,abortExecution as O,endLiveExecution as ve,unbindSession as j,recordLaunch as _e,setFrozen as ye,clearFrozen as P,fullName as ke}from"../canvas/index.js";import{emitEvent as V}from"../events/emit.js";import{consumeDeadlineOnWake as ge}from"../feed/messages.js";import{isParked as B,transition as R}from"./lifecycle.js";import{publishNotice as be}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as Re,drainBearings as Ee,hasRetainedReports as xe,readGoal as x,readYieldMessage as Se,RUNTIME_RESTART_CONTINUATION as $e}from"./kickoff.js";import{readRoadmap as X}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as Y}from"../runs/initial-input.js";import{headlessBrokerHost as Fe,brokerLaunchJson as Ae}from"./host.js";import{isCloudRole as Oe}from"../canvas/person.js";import{asNodePerson as Pe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Be}from"./runner/process.js";import{runnerForEnvironment as q}from"./runner/index.js";import{MachineOfflineError as Q}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as T}from"./blaxel-environment.js";import{recordLaunchFailure as Te}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Z,remoteMachineEnvironmentOf as I,checkBilledWake as Me,EnvironmentImagePending as De,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as ee,brokerCapReached as re,brokerThresholdsForDaemon as M}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ie,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{hookNodePaths as cr,ensureNodeDirs as ur}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as fr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as wr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await p().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof J)return{};throw n}}o(hr,"resumeArgs");async function te(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof J)return!1;throw i}}o(te,"conversationExists");async function mr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}o(mr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||W(i)}o(dr,"sessionCwdExists");async function pr(e,r,i,t){const n=r.pi_session_file;if(!n||!await te(n))return{};const u=await he(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await hr(r,i)}o(pr,"resumableSessionArgs");async function vr(e){return await X(e)===null&&await Se(e)===null&&!await xe(e)}o(vr,"isUnstartedBirth");async function wi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await X(e);return i!==null&&i.trim()!==""}o(wi,"hasFreshGroundState");async function hi(e,r){const i=await ne(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}o(hi,"reviveNode");async function mi(e,r,i){return ne(e,{...r,viewerAttach:!0},i)}o(mi,"decideAttachRevive");async function ne(e,r,i){const t=Oe()?await b(e):null;return t===null?await ae(e,r,i):await Pe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ae(e,r,i))}o(ne,"decideRevive");async function ae(e,r,i){let t=await b(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await b(e)??t,t.run_id&&(await b(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);(i||!(t.lifecycle==="resident"&&B(t)))&&await kr(e,t),ar(t.profile_id),fe(t.grantee);const n=ee(),u=await T(t.profile_id??null)!==null||await I(t.profile_id??null)!==null,D=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&B(t))&&(await ir(t),await tr(t),await T(t.profile_id??null)!==null&&await Me(t)),await n.isClaimed(e))return await n.has(e)&&await R(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&B(t))return{parked:!0};if(D){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await oe(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const m=await Ue();if(m&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const f=!m&&(u||await n.reserveSlot(e));let s=null;if(f&&!u){try{s=await Je(e)}catch(S){throw n.releaseReservation(e),S}s.verdict!=="admitted"&&n.releaseReservation(e)}if(s?.verdict==="too_small")throw We(s);if(!f||s?.verdict==="denied"){if(r.capacity==="refuse")throw s?.verdict==="denied"?Ke(s):re(M().automaticReviveCap,await n.occupancy());return await oe(e,t,m?{reason:"drain"}:s?.verdict==="denied"?{reason:"app_memory",free_bytes:s.free_bytes,needed_bytes:s.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:M().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await br(e,t,r)}}finally{n.releaseReservation(e)}}o(ae,"decideReviveAsCaller");async function oe(e,r,i){r.frozen_at==null&&(await ye(e,new Date().toISOString()),await ve(e,{reason:"frozen"}),V({level:"info",event:"broker.frozen",node_id:e,fields:i}))}o(oe,"freezeForWait");async function _r(e,r){const i=await T(r.profile_id??null),t=await I(r.profile_id??null)!==null;if(!(i!==null||t)&&!W(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}o(_r,"assertRecordedCwdExists");function yr(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}o(yr,"assertCheckoutNotRemoved");async function kr(e,r){try{yr(e,r)}catch(i){throw(r.status==="active"||r.status==="idle")&&(await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:i.message}}}),await P(e)),i}}o(kr,"refuseRemovedCheckout");async function gr(e,r,i){const t=fr(r.cwd,r.profile_id).plans.get("node:start")??[];await wr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,...await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}o(gr,"runNodeStartHooks");async function br(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await _r(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await A(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await j(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,f=r.fork_source_file;if(m&&(typeof f!="string"||!we(f)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const s=m&&typeof f=="string";if(s&&!await te(f))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${f}`,next:`Restore ${f}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:S}=M();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new De(t,l.error)}const se=t!==null?q("blaxel"):n?q("machine"):Be;let w;try{w=await me(e,{daemonEpoch:ee().epoch(),...u?{}:{cap:S},...t!==null?{runner:"blaxel",release:Z()}:n?{runner:"machine",release:Z()}:{}})}catch(l){if(l instanceof ze)throw re(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await A(e,{cycles:r.cycles});const $=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=s?{}:await pr(e,r,$,!u),k=d.resumeSessionPath!==void 0,L=k&&d.newCycle===!0,v=k&&!L,z=!k&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await vr(e),C=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await mr(d.resumeSessionPath)?(await x(e))?.trim():void 0,H=C!==void 0&&C!=="",le=s||z||H,G=r.cycle_pending===!0||L;await A(e,{cycle_pending:G}),r.cycle_pending=G,!s&&!k&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await j(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const N=o(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(s){const a=await x(e),F=_(f);if(F===null)throw new Error(`invalid fork source ${f}`);const ce=(await p().header(await p().fork(F,e))).path;c=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=N()),await qe(e,(await Ze(f))?.node_id??null)}else if(H)c=y(r,{...d,prompt:C}),h=N(),await Y(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:$e}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(z){const a=(await x(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=N(),await Y(c,r)),await ie(e)}else{const a=await Ee(r,w);c=y(r,{...d,prompt:await Re(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ie(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[Ne]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await R(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const U=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ge(e),await ur(e,r.grantee),await gr(e,r,le),c.env={...c.env,CRTR_EXECUTION_ID:w};const K=await Ae(e,c,r.cwd);await Ge(w,K);let g;try{const a=await He(e);if(g=await se.start({executionId:w,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:K,cwd:r.cwd,resuming:v}),!u&&g.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Q)throw a;try{await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await be(e,"notice.crash",`Child crashed \u2014 ${ke(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await O(w,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await _e(e,new Date().toISOString()),u)return await P(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:U.explanation,outcome:"launched"};if(await de(w,e,g.pid)==="shutdown")throw await O(w,{reason:"superseded"}),Fe.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await P(e),{window:null,session:r.tmux_session??null,resumed:v,launch:g,faultExplanation:U.explanation,outcome:"launched"}}catch(l){throw l instanceof Q&&l.sent||(await O(w,{reason:"launch_failed"}),await De(w,l).catch($=>{V({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:$})})),l}}o(Rr,"launchRevive");export{kr as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,pi as decideAttachRevive,hi as hasFreshGroundState,mr as resumeArgs,mi as reviveNode,br as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await O(w,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await _e(e,new Date().toISOString()),u)return await P(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:U.explanation,outcome:"launched"};if(await pe(w,e,g.pid)==="shutdown")throw await O(w,{reason:"superseded"}),Fe.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await P(e),{window:null,session:r.tmux_session??null,resumed:v,launch:g,faultExplanation:U.explanation,outcome:"launched"}}catch(l){throw l instanceof Q&&l.sent||(await O(w,{reason:"launch_failed"}),await Te(w,l).catch($=>{V({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:$})})),l}}o(br,"launchRevive");export{yr as assertCheckoutNotRemoved,_r as assertRecordedCwdExists,mi as decideAttachRevive,wi as hasFreshGroundState,hr as resumeArgs,hi as reviveNode,gr as runNodeStartHooks};
@@ -1,3 +1,3 @@
1
- var h=Object.defineProperty;var c=(a,n)=>h(a,"name",{value:n,configurable:!0});import{mintExecutionToken as P}from"../../../canvas/node-tokens.js";import{BlaxelApiError as S,isWorkloadUnavailable as R}from"./client.js";const b=4180,u="view",T="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",O=3,A=/^crtr-sandbox-start: failed (\S+)/m,I=2e3,E=c(a=>`broker-${a}`,"brokerProcessName"),l=c(a=>a,"sandboxNameFor"),_=c(a=>`cron-${a}`,"cronProcessName"),y=2e3,$="crtr",v="/opt/crtr/current/bin";function N(a){const n=`${a.logs}
1
+ var h=Object.defineProperty;var c=(a,n)=>h(a,"name",{value:n,configurable:!0});import{mintExecutionToken as P}from"../../../canvas/node-tokens.js";import{sandboxContextDir as T}from"../launch-env.js";import{BlaxelApiError as S,isWorkloadUnavailable as R}from"./client.js";const b=4180,u="view",O="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",A=3,I=/^crtr-sandbox-start: failed (\S+)/m,y=2e3,_=c(a=>`broker-${a}`,"brokerProcessName"),l=c(a=>a,"sandboxNameFor"),E=c(a=>`cron-${a}`,"cronProcessName"),N=2e3,$="crtr",v="/opt/crtr/current/bin";function D(a){const n=`${a.logs}
2
2
  ${a.stderr}
3
- ${a.stdout}`,w=(a.stderr||a.logs||a.stdout||"").trim().slice(-I);return{state:"failed",reason:A.exec(n)?.[1]??"start_failed",code:a.exitCode,...w===""?{}:{output:w}}}c(N,"failureOf");function U(a){const{client:n}=a,w=(a.stopGraceS??10)*1e3,x=new Map;async function m(t){return await n.getSandbox(l(t.nodeId))}c(m,"sandboxOf");async function k(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(w/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await n.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return c(k,"brokerGone"),{kind:"blaxel",async start(t){const r=await a.launchContext(t),e=l(t.nodeId),o={name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:u,target:b}]};let i=await n.createSandbox(o);i.image!==r.image&&(await n.deletePreview(e,u),await n.deleteSandbox(e),x.delete(e),i=await n.createSandbox(o));const d=E(t.executionId);if((await n.getProcess(i,d))?.status==="running")return{pid:null,exited:null};await n.ensurePreview(e,u,b);const g=await(a.mintToken??(p=>P(p.executionId,p.nodeId)))(t),f={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:g,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await n.startProcess(i,{name:d,command:a.bootstrap(),env:f,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await m(t);if(r===null)return"no_broker";try{const e=await n.exec(r,`wake-${t.executionId}-${Date.now()}`,`${T} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===O)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(R(e))return"no_broker";throw e}},async stop(t,r){try{const e=await m(t);if(e===null)return{confirmed:!0};const o=E(t.executionId),i=c(async()=>(await n.getProcess(e,o))?.status==="running","running");if(await i()){await n.stopProcess(e,o);const d=Date.now()+w;for(;Date.now()<d&&await i();)await new Promise(s=>setTimeout(s,250));if(await i()&&await n.killProcess(e,o),await i())return{confirmed:!1}}return{confirmed:await k(e,t.executionId)}}catch(e){return R(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await m(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await n.getProcess(e,E(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?N(o):{state:"gone"}}catch(e){return R(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){await n.deletePreview(l(t),u),await n.deleteSandbox(l(t)),x.delete(l(t))},async viewerAddress(t){const r=l(t.nodeId),e=x.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return C(e.url,e.token);const o=await n.ensurePreview(r,u,b),i=new Date(Date.now()+60*6e4),{token:d}=await n.createPreviewToken(r,u,i);return x.set(r,{url:o,token:d,expiresAt:i.getTime()}),C(o,d)},async cronRun(t,r){const e=await n.getSandbox(l(t));if(e===null)throw new Error(`node ${t} has no sandbox, so the cron cannot run; the scheduler never starts a node to get one`);const o=_(r.runId),i=`exec nsenter -S "$(id -u ${$})" -G "$(id -g ${$})" bash -c "$CRTR_CRON_COMMAND"`,d={...r.env,CRTR_CRON_COMMAND:r.command,PATH:`${v}:/usr/local/bin:/usr/bin:/bin`};let s=await n.getProcess(e,o)??await n.startProcess(e,{name:o,command:i,workingDir:r.cwd,env:d,waitForCompletion:!1});const g=r.startedAtMs+r.timeoutS*1e3;for(;s.status==="running";){if(Date.now()>=g)return await n.killProcess(e,o),{exitCode:null,timedOut:!0,stdout:s.stdout,stderr:s.stderr};await new Promise(p=>setTimeout(p,y));let f;try{f=await n.getProcess(e,o)}catch{continue}if(f===null)return{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} is gone from the sandbox, so its outcome is unknown`};s=f}return s.status==="completed"||s.status==="failed"?{exitCode:s.exitCode,timedOut:!1,stdout:s.stdout,stderr:s.stderr}:{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} was ${s.status} from outside the run`}},async cronCancel(t,r){const e=await n.getSandbox(l(t));e!==null&&await n.killProcess(e,_(r))},async sandboxState(t){return(await m(t))?.state??null}}}c(U,"createBlaxelRunner");function C(a,n){return{kind:"wss",url:`${a.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":n}}}c(C,"viewer");export{b as BROKER_VIEW_PORT,S as BlaxelApiError,O as EXIT_NO_BROKER,A as FAILURE_LINE,T as WAKE_COMMAND,E as brokerProcessName,U as createBlaxelRunner,_ as cronProcessName,l as sandboxNameFor};
3
+ ${a.stdout}`,w=(a.stderr||a.logs||a.stdout||"").trim().slice(-y);return{state:"failed",reason:I.exec(n)?.[1]??"start_failed",code:a.exitCode,...w===""?{}:{output:w}}}c(D,"failureOf");function F(a){const{client:n}=a,w=(a.stopGraceS??10)*1e3,f=new Map;async function m(t){return await n.getSandbox(l(t.nodeId))}c(m,"sandboxOf");async function k(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(w/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await n.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return c(k,"brokerGone"),{kind:"blaxel",async start(t){const r=await a.launchContext(t),e=l(t.nodeId),o={name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:u,target:b}]};let i=await n.createSandbox(o);i.image!==r.image&&(await n.deletePreview(e,u),await n.deleteSandbox(e),f.delete(e),i=await n.createSandbox(o));const d=_(t.executionId);if((await n.getProcess(i,d))?.status==="running")return{pid:null,exited:null};await n.ensurePreview(e,u,b);const g=await(a.mintToken??(p=>P(p.executionId,p.nodeId)))(t),x={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:g,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await n.startProcess(i,{name:d,command:a.bootstrap(),env:x,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await m(t);if(r===null)return"no_broker";try{const e=await n.exec(r,`wake-${t.executionId}-${Date.now()}`,`${O} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===A)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(R(e))return"no_broker";throw e}},async stop(t,r){try{const e=await m(t);if(e===null)return{confirmed:!0};const o=_(t.executionId),i=c(async()=>(await n.getProcess(e,o))?.status==="running","running");if(await i()){await n.stopProcess(e,o);const d=Date.now()+w;for(;Date.now()<d&&await i();)await new Promise(s=>setTimeout(s,250));if(await i()&&await n.killProcess(e,o),await i())return{confirmed:!1}}return{confirmed:await k(e,t.executionId)}}catch(e){return R(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await m(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await n.getProcess(e,_(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?D(o):{state:"gone"}}catch(e){return R(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){await n.deletePreview(l(t),u),await n.deleteSandbox(l(t)),f.delete(l(t))},async viewerAddress(t){const r=l(t.nodeId),e=f.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return C(e.url,e.token);const o=await n.ensurePreview(r,u,b),i=new Date(Date.now()+60*6e4),{token:d}=await n.createPreviewToken(r,u,i);return f.set(r,{url:o,token:d,expiresAt:i.getTime()}),C(o,d)},async cronRun(t,r){const e=await n.getSandbox(l(t));if(e===null)throw new Error(`node ${t} has no sandbox, so the cron cannot run; the scheduler never starts a node to get one`);const o=E(r.runId),i=`exec nsenter -S "$(id -u ${$})" -G "$(id -g ${$})" bash -c "$CRTR_CRON_COMMAND"`,d={...r.env,CRTR_CONTEXT_DIR:T(r.app,t),CRTR_CRON_COMMAND:r.command,PATH:`${v}:/usr/local/bin:/usr/bin:/bin`};let s=await n.getProcess(e,o)??await n.startProcess(e,{name:o,command:i,workingDir:r.cwd,env:d,waitForCompletion:!1});const g=r.startedAtMs+r.timeoutS*1e3;for(;s.status==="running";){if(Date.now()>=g)return await n.killProcess(e,o),{exitCode:null,timedOut:!0,stdout:s.stdout,stderr:s.stderr};await new Promise(p=>setTimeout(p,N));let x;try{x=await n.getProcess(e,o)}catch{continue}if(x===null)return{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} is gone from the sandbox, so its outcome is unknown`};s=x}return s.status==="completed"||s.status==="failed"?{exitCode:s.exitCode,timedOut:!1,stdout:s.stdout,stderr:s.stderr}:{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} was ${s.status} from outside the run`}},async cronCancel(t,r){const e=await n.getSandbox(l(t));e!==null&&await n.killProcess(e,E(r))},async sandboxState(t){return(await m(t))?.state??null}}}c(F,"createBlaxelRunner");function C(a,n){return{kind:"wss",url:`${a.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":n}}}c(C,"viewer");export{b as BROKER_VIEW_PORT,S as BlaxelApiError,A as EXIT_NO_BROKER,I as FAILURE_LINE,O as WAKE_COMMAND,_ as brokerProcessName,F as createBlaxelRunner,E as cronProcessName,l as sandboxNameFor};
@@ -0,0 +1,7 @@
1
+ /** A node's context dir in a sandbox, where the release's data root is `root` (`CRTR_HOME`, default `/var/lib/crtr`). One layout for the sandbox start script and the sandbox cron runner. */
2
+ export declare function sandboxContextDir(app: string, nodeId: string, root?: string): string;
3
+ /** `env` with every control-plane path key removed, `CRTR_CONTEXT_DIR` set to the host's context dir, and `CRTR_SCOPES_FILE` (only when the recipe names one) set to the host's scopes file. */
4
+ export declare function hostLaunchEnv(env: Record<string, string>, host: {
5
+ contextDir: string;
6
+ scopesFile: string;
7
+ }): Record<string, string>;
@@ -0,0 +1 @@
1
+ var R=Object.defineProperty;var o=(t,n)=>R(t,"name",{value:n,configurable:!0});const E=["CRTR_HOME","CRTR_RUNTIME_HOME"];function c(t,n,e="/var/lib/crtr"){return`${e}/apps/${t.replace(/^app:/,"")}/nodes/${n}/context`}o(c,"sandboxContextDir");function C(t,n){const e={...t};for(const r of E)delete e[r];return e.CRTR_CONTEXT_DIR=n.contextDir,e.CRTR_SCOPES_FILE!==void 0&&(e.CRTR_SCOPES_FILE=n.scopesFile),e}o(C,"hostLaunchEnv");export{C as hostLaunchEnv,c as sandboxContextDir};
@@ -1,2 +1,2 @@
1
- var g=Object.defineProperty;var c=(n,r)=>g(n,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{closeSync as J,existsSync as m,mkdirSync as v,openSync as K,readFileSync as V,statSync as X}from"node:fs";import{rm as W}from"node:fs/promises";import{basename as D,dirname as y,join as h}from"node:path";import{fileURLToPath as Y}from"node:url";import{emitEvent as q}from"../../../events/emit.js";import{contextDir as z,jobDir as Q,nodeRunDir as M,crtrHome as L,viewSocketPath as Z}from"../../../canvas/paths.js";import{captureTeardownSnapshot as ee,isAnyPidAlive as ne,killProcessTreePids as A,listProcessTableAsync as oe}from"../../../canvas/pid.js";import{scopesFilePath as G}from"../../../canvas/paths.js";import{writeFileBeneath as b}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as te}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as re}from"../../broker-ownership.js";import{isShippedCanvasExtension as ie}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ce,mergeCanvasExtensions as se}from"../../canvas-extensions.js";import{layoutRoot as ae,runtimeRoot as de}from"../../../layout.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as fe}from"../../spawn-env.js";const R=c(()=>h(y(Y(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry");function le(n){const r=n===void 0?{}:JSON.parse(n),t=h(y(R()),"..","..","builtin-pi-packages","pi-crtr-extensions"),e=(r.packages??[]).filter(o=>!/pi-crtr-extensions/.test(typeof o=="string"?o:String(o.source)));return`${JSON.stringify({...r,packages:[t,...e]},null,2)}
2
- `}c(le,"withBundledExtensions");const H=c(n=>{if(n!==void 0)try{process.kill(-n,"SIGKILL")}catch{}},"killGroup"),pe=c(n=>new Promise(r=>setTimeout(r,n)),"sleep");async function U(){const n=[],r=await oe();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:t,command:e}of r){const o=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);o!==null&&n.push({pid:t,execution:o[1],node:o[2],command:e})}return n}c(U,"findBrokers");const me=["CRTR_HOME","CRTR_RUNTIME_HOME"];function F(n,r){const t={...n};for(const e of me)delete t[e];return t.CRTR_CONTEXT_DIR!==void 0&&(t.CRTR_CONTEXT_DIR=z(r.id,t.CRTR_GRANTEE??r.app)),t.CRTR_SCOPES_FILE!==void 0&&(t.CRTR_SCOPES_FILE=G(r.id)),t}c(F,"localLaunchEnv");function he(n){const r=c(i=>D(i).replace(/\.[jt]s$/,""),"stem"),t=new Set(ce.map(r)),e=c(i=>ie(i)||D(y(i))==="pi-extensions"&&(t.has(r(i))||r(i).startsWith("canvas-")&&!m(i)),"shipped"),o=[],s=[];for(let i=0;i<n.length;i++)if(n[i]==="-e"&&n[i+1]!==void 0){const d=n[++i];if(e(d))continue;if(!m(d))throw new Error(`extension ${d} does not exist on this machine`);s.push(d)}else o.push(n[i]);return[...se(s).flatMap(i=>["-e",i]),...o]}c(he,"localExtensionArgv");function we(n,r,t){const e=JSON.parse(n);return JSON.stringify({...e,argv:he(e.argv),env:F(e.env??{},r),...t===void 0?{}:{start:t}})}c(we,"machineLaunchRecipe");function Ee(n,r,t){const e=n.launch,o=fe({argv:[],env:F(e.env??{},n.node)},ue(n.node.cwd,null,n.node.app,n.machine_env??{},{}));return Object.assign(o,{CRTR_HOME:ae(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??de(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[te]:"1"})}c(Ee,"machineBrokerEnv");async function $(n,r,t){const{tree:e,identities:o}=ee(n,null,t);if(o===null)return{confirmed:!1,error:`the process tree of broker ${n} could not be read, so shutdown cannot be confirmed`};const s=c(async(i,d)=>{for(let l=0;ne(i);l+=100){if(l>=d)return!1;await pe(100)}return!0},"waitUntilDead");try{process.kill(n,"SIGTERM")}catch{}return await s([n],r),A(e,"SIGTERM",o),await s(e,2e3)?{confirmed:!0}:(A(e,"SIGKILL",o),await s(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${n} survived SIGKILL`})}c($,"stopBroker");async function Ae(n=1e4){const t=(await Promise.all((await U()).filter(e=>re(e.command,L())).map(e=>$(e.pid,n)))).filter(e=>!e.confirmed);if(t.length>0)throw new Error(t.map(e=>e.error??"a broker did not stop").join("; "))}c(Ae,"stopAllBrokers");function Ge(n){const r=(n.stopGraceS??10)*1e3,t=c(async e=>(await U()).find(o=>o.execution===e),"brokerOf");return{async start(e,o){const s={};let i=performance.now();const d=c(a=>{const u=performance.now();s[a]=Math.round((u-i)*10)/10,i=u},"stepDone"),l=await t(e.executionId);if(d("process_lookup"),l!==void 0)return{pid:l.pid,timings:s};if(o?.throwIfAborted(),!m(e.cwd)||!X(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!m(R()))throw new Error(`the broker entry ${R()} does not exist`);if(e.bundle===void 0)throw new Error("the control plane carried no start bundle: it runs an older release than this Mac");const{bundle:_}=e,C=_.launch,w=M(e.nodeId);v(w,{recursive:!0}),b(w,h(w,"broker-launch.json"),we(e.launchJson,_.node,e.start),{atomic:!0,mode:384}),C.env?.CRTR_SCOPES_FILE!==void 0&&b(w,G(e.nodeId),JSON.stringify(C.scopes??[]),{atomic:!0});const O=Q(e.nodeId);v(O,{recursive:!0});const I=K(h(O,"broker.log"),"a"),k=Ee(_,n,e.executionId),S=k.PI_CODING_AGENT_DIR,x=h(S,"settings.json");v(S,{recursive:!0}),b(S,x,le(m(x)?V(x,"utf8"):void 0),{atomic:!0}),delete k.CRTR_NODE_TOKEN,d("file_writes");try{o?.throwIfAborted();const a=j(process.execPath,[R(),"--canvas-home",L(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",I,I,"pipe"],env:k});let u,N=!1;const P=c(()=>{u!==void 0&&n.onExit?.({execution:e.executionId,node:e.nodeId,...u})},"report");a.once("exit",(T,f)=>{u={code:T,signal:f},N&&P()});const p=a.stdio[3];if(p==null||!("end"in p))throw H(a.pid),new Error("broker token pipe did not open");const B=await new Promise((T,f)=>{a.once("error",f),a.once("spawn",()=>{a.off("error",f),p.once("error",E=>{H(a.pid),f(E)}),p.end(e.nodeToken,E=>{E?f(E):T(a.pid)})})});return N=!0,P(),a.unref(),d("spawn_and_token_pipe"),q({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...s}}),{pid:B,timings:s}}finally{J(I)}},async wake({execution:e}){const o=await t(e.executionId);if(o===void 0)return"no_broker";try{return process.kill(o.pid,"SIGUSR1"),"signalled"}catch(s){if(s.code==="ESRCH")return"no_broker";throw s}},async stop({execution:e,options:o}){const s=await t(e.executionId);return s===void 0?{confirmed:!0}:await $(s.pid,r,o.excludePid)},async status({execution:e}){const o=await t(e.executionId);return o===void 0?{state:"gone"}:{state:"running",pid:o.pid}},async delete({nodeId:e}){return await W(M(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Z(e.nodeId)}}}}c(Ge,"createMachineExecutor");export{Ge as createMachineExecutor,U as findBrokers,he as localExtensionArgv,Ee as machineBrokerEnv,we as machineLaunchRecipe,Ae as stopAllBrokers,le as withBundledExtensions};
1
+ var j=Object.defineProperty;var c=(n,t)=>j(n,"name",{value:t,configurable:!0});import{spawn as H}from"node:child_process";import{closeSync as J,existsSync as m,mkdirSync as y,openSync as K,readFileSync as V,statSync as W}from"node:fs";import{rm as X}from"node:fs/promises";import{basename as P,dirname as b,join as h}from"node:path";import{fileURLToPath as q}from"node:url";import{emitEvent as z}from"../../../events/emit.js";import{contextDir as Q,jobDir as Y,nodeRunDir as A,crtrHome as M,viewSocketPath as Z}from"../../../canvas/paths.js";import{captureTeardownSnapshot as ee,isAnyPidAlive as ne,killProcessTreePids as G,listProcessTableAsync as oe}from"../../../canvas/pid.js";import{scopesFilePath as L}from"../../../canvas/paths.js";import{writeFileBeneath as T}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as te}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as re}from"../../broker-ownership.js";import{isShippedCanvasExtension as ie}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ce,mergeCanvasExtensions as se}from"../../canvas-extensions.js";import{layoutRoot as ae,runtimeRoot as de}from"../../../layout.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as pe}from"../../spawn-env.js";import{hostLaunchEnv as fe}from"../launch-env.js";const x=c(()=>h(b(q(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry");function le(n){const t=n===void 0?{}:JSON.parse(n),i=h(b(x()),"..","..","builtin-pi-packages","pi-crtr-extensions"),e=(t.packages??[]).filter(o=>!/pi-crtr-extensions/.test(typeof o=="string"?o:String(o.source)));return`${JSON.stringify({...t,packages:[i,...e]},null,2)}
2
+ `}c(le,"withBundledExtensions");const U=c(n=>{if(n!==void 0)try{process.kill(-n,"SIGKILL")}catch{}},"killGroup"),me=c(n=>new Promise(t=>setTimeout(t,n)),"sleep");async function $(){const n=[],t=await oe();if(t===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:i,command:e}of t){const o=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);o!==null&&n.push({pid:i,execution:o[1],node:o[2],command:e})}return n}c($,"findBrokers");function B(n,t){return fe(n,{contextDir:Q(t.id,n.CRTR_GRANTEE??t.app),scopesFile:L(t.id)})}c(B,"localLaunchEnv");function he(n){const t=c(r=>P(r).replace(/\.[jt]s$/,""),"stem"),i=new Set(ce.map(t)),e=c(r=>ie(r)||P(b(r))==="pi-extensions"&&(i.has(t(r))||t(r).startsWith("canvas-")&&!m(r)),"shipped"),o=[],s=[];for(let r=0;r<n.length;r++)if(n[r]==="-e"&&n[r+1]!==void 0){const d=n[++r];if(e(d))continue;if(!m(d))throw new Error(`extension ${d} does not exist on this machine`);s.push(d)}else o.push(n[r]);return[...se(s).flatMap(r=>["-e",r]),...o]}c(he,"localExtensionArgv");function we(n,t,i){const e=JSON.parse(n);return JSON.stringify({...e,argv:he(e.argv),env:B(e.env??{},t),...i===void 0?{}:{start:i}})}c(we,"machineLaunchRecipe");function Ee(n,t,i){const e=n.launch,o=pe({argv:[],env:B(e.env??{},n.node)},ue(n.node.cwd,null,n.node.app,n.machine_env??{},{}));return Object.assign(o,{CRTR_HOME:ae(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??de(),CRTR_API_URL:t.apiUrl,CRTR_EXECUTION_ID:i,CRTR_ENVIRONMENT_ID:t.environmentId,CRTR_VIEW_WSS:"0",[te]:"1"})}c(Ee,"machineBrokerEnv");async function F(n,t,i){const{tree:e,identities:o}=ee(n,null,i);if(o===null)return{confirmed:!1,error:`the process tree of broker ${n} could not be read, so shutdown cannot be confirmed`};const s=c(async(r,d)=>{for(let f=0;ne(r);f+=100){if(f>=d)return!1;await me(100)}return!0},"waitUntilDead");try{process.kill(n,"SIGTERM")}catch{}return await s([n],t),G(e,"SIGTERM",o),await s(e,2e3)?{confirmed:!0}:(G(e,"SIGKILL",o),await s(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${n} survived SIGKILL`})}c(F,"stopBroker");async function Le(n=1e4){const i=(await Promise.all((await $()).filter(e=>re(e.command,M())).map(e=>F(e.pid,n)))).filter(e=>!e.confirmed);if(i.length>0)throw new Error(i.map(e=>e.error??"a broker did not stop").join("; "))}c(Le,"stopAllBrokers");function Ue(n){const t=(n.stopGraceS??10)*1e3,i=c(async e=>(await $()).find(o=>o.execution===e),"brokerOf");return{async start(e,o){const s={};let r=performance.now();const d=c(a=>{const u=performance.now();s[a]=Math.round((u-r)*10)/10,r=u},"stepDone"),f=await i(e.executionId);if(d("process_lookup"),f!==void 0)return{pid:f.pid,timings:s};if(o?.throwIfAborted(),!m(e.cwd)||!W(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!m(x()))throw new Error(`the broker entry ${x()} does not exist`);if(e.bundle===void 0)throw new Error("the control plane carried no start bundle: it runs an older release than this Mac");const{bundle:k}=e,N=k.launch,w=A(e.nodeId);y(w,{recursive:!0}),T(w,h(w,"broker-launch.json"),we(e.launchJson,k.node,e.start),{atomic:!0,mode:384}),N.env?.CRTR_SCOPES_FILE!==void 0&&T(w,L(e.nodeId),JSON.stringify(N.scopes??[]),{atomic:!0});const O=Y(e.nodeId);y(O,{recursive:!0});const I=K(h(O,"broker.log"),"a"),R=Ee(k,n,e.executionId),S=R.PI_CODING_AGENT_DIR,_=h(S,"settings.json");y(S,{recursive:!0}),T(S,_,le(m(_)?V(_,"utf8"):void 0),{atomic:!0}),delete R.CRTR_NODE_TOKEN,d("file_writes");try{o?.throwIfAborted();const a=H(process.execPath,[x(),"--canvas-home",M(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",I,I,"pipe"],env:R});let u,C=!1;const D=c(()=>{u!==void 0&&n.onExit?.({execution:e.executionId,node:e.nodeId,...u})},"report");a.once("exit",(v,p)=>{u={code:v,signal:p},C&&D()});const l=a.stdio[3];if(l==null||!("end"in l))throw U(a.pid),new Error("broker token pipe did not open");const g=await new Promise((v,p)=>{a.once("error",p),a.once("spawn",()=>{a.off("error",p),l.once("error",E=>{U(a.pid),p(E)}),l.end(e.nodeToken,E=>{E?p(E):v(a.pid)})})});return C=!0,D(),a.unref(),d("spawn_and_token_pipe"),z({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...s}}),{pid:g,timings:s}}finally{J(I)}},async wake({execution:e}){const o=await i(e.executionId);if(o===void 0)return"no_broker";try{return process.kill(o.pid,"SIGUSR1"),"signalled"}catch(s){if(s.code==="ESRCH")return"no_broker";throw s}},async stop({execution:e,options:o}){const s=await i(e.executionId);return s===void 0?{confirmed:!0}:await F(s.pid,t,o.excludePid)},async status({execution:e}){const o=await i(e.executionId);return o===void 0?{state:"gone"}:{state:"running",pid:o.pid}},async delete({nodeId:e}){return await X(A(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Z(e.nodeId)}}}}c(Ue,"createMachineExecutor");export{Ue as createMachineExecutor,$ as findBrokers,he as localExtensionArgv,Ee as machineBrokerEnv,we as machineLaunchRecipe,Le as stopAllBrokers,le as withBundledExtensions};
@@ -107,6 +107,7 @@ export interface Runner {
107
107
  runId: string;
108
108
  command: string;
109
109
  cwd: string;
110
+ app: string;
110
111
  env: Record<string, string>;
111
112
  timeoutS: number;
112
113
  startedAtMs: number;
@@ -1,3 +1,3 @@
1
- var Ee=Object.defineProperty;var l=(e,r)=>Ee(e,"name",{value:r,configurable:!0});import{accessSync as Oe,constants as Ie,existsSync as Re}from"node:fs";import{isAbsolute as Me,resolve as De,join as Fe}from"node:path";import{appSpace as Ne}from"../layout.js";import{ApiError as ce}from"../../api/errors.js";import{spawnNode as Be,forkSourceNode as Pe,currentNodeContext as Te,rootOfSpine as Le,newNodeId as ue,preflightNodeId as Ae}from"./nodes.js";import{resolveProfileOperand as ze}from"../profiles/manifest.js";import{selectProfileForCwd as We,selectProfileForCwdReadOnly as je}from"../profiles/select.js";import{buildLaunchSpecAsync as fe,buildPiArgv as He}from"./launch.js";import{devEnvironmentCwd as Ke,runsOnBlaxel as Ue,sandboxWorktreeRequest as Xe}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as qe,rollbackManagedWorktreeAsync as Ge}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ve,rollbackManagedWorktreeOnMachine as Je,worktreeMachineOf as Ye}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as G}from"../errors.js";import{InputError as Qe}from"../io.js";import{isCloudRole as Ze}from"../canvas/person-state.js";import{writeGoal as en}from"./kickoff.js";import{appendSituationalContext as nn,formatSituationalProse as rn}from"./situational-context.js";import{ensureRoadmap as tn}from"./roadmap.js";import{buildWakeBearings as on}from"./bearings.js";import{encodeKickoffOrigin as an,KICKOFF_ORIGIN_ENV as dn}from"./stamp/protocol.js";import{carryInitialInput as sn}from"../runs/initial-input.js";import{ExecutionCapReached as ln,beginExecution as we,crtrHome as cn,getNode as w,fullName as me,jobDir as un,recordExecutionPid as fn,abortExecution as z,setFrozen as Q}from"../canvas/index.js";import{contextDir as Z,nodeAgentDir as ee}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as wn}from"../spaces/open-beneath.js";import{conversationIdFromPath as V,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as mn,boundFleet as he,brokerThresholdsForDaemon as pe}from"./fleet.js";import{admitBrokerMemory as hn}from"./memory-admission.js";import{emitEvent as p}from"../events/emit.js";import{remoteEnvironmentOf as pn}from"./blaxel-environment.js";import{openViewerWindow as _n,focusOf as kn,windowOfPane as vn}from"./placement.js";import{awaitBrokerViewSocket as gn}from"./view-socket.js";import{readLogSnapshot as _e}from"../events/read.js";import{transition as M}from"./lifecycle.js";import{beginBootFaultAttempt as yn}from"../canvas/recovery.js";import{headlessBrokerHost as ne,brokerLaunchJson as bn}from"./host.js";import{openDb as xn,withCanvasWrite as Sn}from"../canvas/db.js";import{warmNodeRepos as Cn}from"../graph/reader.js";import{mintNodeToken as $n}from"../canvas/node-tokens.js";import{recordLaunch as En}from"../canvas/canvas.js";import{setExecutionLaunchJson as On}from"../canvas/executions.js";import{acceptedRelease as ke,remoteMachineEnvironmentOf as In}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as Rn,awaitMachineCall as Mn,callTimes as Dn}from"./runner/machine/call.js";import{addStepTiming as J,timedStep as W}from"../step-timings.js";import{MachineLostError as Fn,MachineOfflineError as Nn}from"./runner/machine/ops.js";import{isDrained as Bn}from"../../daemon/drain.js";import{ensureDaemon as Pn}from"../../daemon/manage.js";import{readConfig as Tn}from"../config.js";import{modelRequestFromConfig as Ln,unregisteredConcreteModel as An,unroutableConcreteModel as zn}from"../model-routes.js";import{openModelRegistry as Wn}from"./model-registry.js";import{MODEL_SPEC_NEXT as jn}from"./model-selection.js";import{forkNodeLedger as Hn}from"./ledger.js";import{appRungForGrant as Kn}from"../llm/app-rungs.js";import{APP_FAMILY as re}from"../model-routes.js";import{discoverLifecycleHookRegistry as Un}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Xn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as qn}from"../async-array.js";import{checkStart as Gn}from"./start-check.js";function D(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(D,"launchFailureOutcome");async function Vn(e,r,o){try{return await ne.launch(e,r,o)}catch(t){try{await M(e,"crash",{reason:"launch_failed",outcome:D(t)})}catch{}const a=t.message;throw G(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}l(Vn,"launchBrokerOrCrash");function Jn(e){return _e({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}l(Jn,"lastStartupStep");function Yn(e,r){return _e({nodeId:e,component:"broker",pattern:"broker.runtime.fatal"},!1).items.flatMap(t=>t.kind==="event"&&t.envelope.event==="broker.runtime.fatal"&&Date.parse(t.envelope.ts)>=r?[t.envelope.error?.message??""]:[]).at(-1)||null}l(Yn,"brokerFatalMessage");function Qn(e,r,o){const t=Jn(e),a=t===null?"it had logged no startup step":`the last startup step it logged was \`${t}\``;if(r.reason==="exited"){const{code:d,signal:s}=r.status,f=Yn(e,o);return{text:`exited (code ${d??"null"}, signal ${s??"null"}) before binding its view socket; ${a}${f===null?"":`: ${f}`}`,fields:{reason:"exited",code:d,signal:s,last_startup_step:t}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${a}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:t}}}l(Qn,"notReadyDescription");async function Zn(e,r){try{await M(e,"crash",{reason:"launch_failed",outcome:D(r)})}catch{}try{ne.teardown(e)}catch{}}l(Zn,"crashAndTearDown");async function er(e){const r=await R().header(e).then(d=>d.path,()=>null);if(r!==null)return r;const o=(await R().list()).map(({conversation_id:d,path:s})=>({id:d,path:s})),t=o.filter(d=>d.id===e),a=t.length>0?t:o.filter(d=>d.id.startsWith(e));if(a.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(a.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${a.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return a[0].path}l(er,"resolveSessionUuid");async function ve(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=V(Me(r)?r:De(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await R().header(t)).path}const o=await w(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=V(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await R().header(a)).path}return await er(r)}l(ve,"resolveForkSource");async function nr(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?ze(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?je(o):We(o)}l(nr,"resolveProfileId");function ge(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Ln(e.model,r,e.modelExact===!0)}l(ge,"requestFromLaunch");async function ye(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await Kn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:d,...s}=e.env??{};return{...e,model:a.model,modelIntent:{family:re,strength:a.strength},modelExact:void 0,env:{...s,CRTR_MODEL_INTENT:`${re}/${a.strength}`}}}l(ye,"appPaidLaunch");async function be(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==re)return;const t=await An(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await Wn(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:jn});const a=await zn(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(be,"assertLaunchModelRegistered");function rr(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}l(rr,"resolveSpawner");async function tr(e,r){const o=await Dn(e);o!==null&&J("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))J(`mac_${t}`,a)}l(tr,"recordStartCallTimings");async function or(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:d}=await import("../../daemon/api/handlers/broker-ops.js");if(await Bn())return"full";let s;try{s=await we(e.node_id,{daemonEpoch:he().epoch(),runner:"machine",release:ke()})}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),"failed"}let f;try{o.env={...o.env,CRTR_EXECUTION_ID:s};const c=await bn(e.node_id,o,e.cwd);await On(s,c);const j=s;J("execution_setup",performance.now()-t);const[x,F]=await W("warm_and_bundle",async()=>await Promise.allSettled([W("warm_repos",async()=>await Cn(await xn(),e.node_id)),W("start_bundle",async()=>{const g=e.sub;if(g==null)throw new Error(`cannot start node ${e.node_id}: its row has no person (null sub)`);return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:g,launchJson:c,runner:"machine"})})]));if(x.status==="rejected")throw x.reason;if(F.status==="rejected")throw F.reason;const v=F.value;f=await W("render_transaction",()=>Sn(async g=>{const T=await d(e.node_id),S=await $n(g,j,e.node_id,new Date().toISOString());return await Rn(r,"start",{executionId:j,nodeId:e.node_id,attempt:1,release:ke(),launchJson:c,cwd:e.cwd,resuming:!1,nodeToken:S,bundle:v,start:T})},{timingName:"render_tx"}))}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),await z(s,{reason:"launch_failed"}),"failed"}let b;try{b=await Mn(r,"start",f)}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),c instanceof Fn||c instanceof Nn&&c.sent?"uncertain":(await z(s,{reason:"launch_failed"}),"failed")}try{await tr(f,b)}catch(c){p({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:c})}try{await W("record_launch",()=>En(e.node_id,new Date().toISOString()))}catch(c){p({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:c})}return"started"}l(or,"startOnMachine");async function xe(e,r,o){const t=performance.now();try{Pn()}catch{}const a=Te(),d=e.root===!0,s=rr(e.parent,a.nodeId??null,d),f=e.mode??"base",b=e.rootLifecycle??(d?"resident":"terminal"),c=d&&b==="resident",j=Date.now(),x=s===null?null:await w(s),F=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Ae(e.nodeId);const v=e.forkFrom!==void 0?await ve(e.forkFrom):void 0,g=v===void 0?null:await Pe(v),T=await qn([x,F,g],async h=>h?.isolated===!0||h?.run_id!=null&&(await w(h.run_id))?.isolated===!0);if(T&&e.isolated===!1)throw new ce(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=T||e.isolated===!0;if(S&&e.worktree===!0)throw new ce(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let _=S||e.worktree===!0?e.nodeId??await ue():e.nodeId,N=S?e.run!==void 0&&d&&!T?e.cwd:Fe(Ne(e.run?.grantee??x?.grantee??"app:terminal").nodes,_):e.cwd;const m=await nr(e.profile,s,N),H=S?null:await Ke(m,e.worktreeCwd??N);H!==null&&(N=H,_??=await ue());const L=e.worktree===!0||H!==null,te=e.run?.grant_id??x?.grant_id??null,A=e.run??F??x??g,oe=await ye((await fe(e.kind,f,{lifecycle:b,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:N,profileId:m,app:A?.grantee??"app:terminal"})).launch,te,e.model);await be(ge(oe),{cwd:N,profileId:m}),await Gn({grantee:A?.grantee??"app:terminal",sub:A?.sub,grant_id:A?.grant_id,profile_id:m});const ie=g?.node_id??null;let C,K=N;const U=L&&await Ue(m)?await Xe(m,H??e.worktreeCwd??e.cwd,_,e.worktreeBase):void 0,X=L&&U===void 0?await Ye(m):null;try{L&&U===void 0&&(C=X!==null?await Ve(X,e.worktreeCwd??e.cwd,_,e.worktreeBase):await qe(e.worktreeCwd??e.cwd,_,e.worktreeBase),K=C.path);const h=L?await ye((await fe(e.kind,f,{lifecycle:b,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:K,profileId:m,app:A?.grantee??"app:terminal"})).launch,te,e.model):oe;U!==void 0&&(h.worktree=U),L&&await be(ge(h),{cwd:K,profileId:m});const n=await Be({kind:e.kind,mode:f,lifecycle:b,cwd:K,name:e.name??e.kind,description:e.description,parent:d?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:ie,spawnedBy:d?s??void 0:void 0,profile_id:m,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:v,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},..._!==void 0?{nodeId:_}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await Hn(n.node_id,ie??null)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:D(i)}),i}if(await en(n.node_id,e.prompt),e.situationalContext!==void 0&&await nn(n.node_id,rn(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:D(i)}),i}const Y=e.prompt!=="",Se=`${Y&&e.wakeOrigin!==void 0?`${on(e.wakeOrigin)}
1
+ var Ee=Object.defineProperty;var l=(e,r)=>Ee(e,"name",{value:r,configurable:!0});import{accessSync as Oe,constants as Ie,existsSync as Re}from"node:fs";import{isAbsolute as Me,resolve as Fe,join as Ne}from"node:path";import{appSpace as De}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Pe,forkSourceNode as Be,currentNodeContext as Te,rootOfSpine as Le,newNodeId as le,preflightNodeId as Ae}from"./nodes.js";import{resolveProfileOperand as ze}from"../profiles/manifest.js";import{selectProfileForCwd as We,selectProfileForCwdReadOnly as je}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as He}from"./launch.js";import{devEnvironmentCwd as Ke,runsOnBlaxel as Ue,sandboxWorktreeRequest as Xe}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as qe,rollbackManagedWorktreeAsync as Ge}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ve,rollbackManagedWorktreeOnMachine as Je,worktreeMachineOf as Ye}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as G}from"../errors.js";import{InputError as Qe}from"../io.js";import{isCloudRole as Ze}from"../canvas/person-state.js";import{writeGoal as en}from"./kickoff.js";import{appendSituationalContext as nn,formatSituationalProse as rn}from"./situational-context.js";import{ensureRoadmap as tn}from"./roadmap.js";import{buildWakeBearings as on}from"./bearings.js";import{encodeKickoffOrigin as an,KICKOFF_ORIGIN_ENV as dn}from"./stamp/protocol.js";import{carryInitialInput as sn}from"../runs/initial-input.js";import{ExecutionCapReached as ln,beginExecution as ue,crtrHome as cn,getNode as w,fullName as fe,jobDir as un,recordExecutionPid as fn,abortExecution as z,setFrozen as Q}from"../canvas/index.js";import{hookNodePaths as wn,contextDir as we,nodeAgentDir as me}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as mn}from"../spaces/open-beneath.js";import{conversationIdFromPath as V,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as hn,boundFleet as he,brokerThresholdsForDaemon as pe}from"./fleet.js";import{admitBrokerMemory as pn}from"./memory-admission.js";import{emitEvent as p}from"../events/emit.js";import{remoteEnvironmentOf as _n}from"./blaxel-environment.js";import{openViewerWindow as kn,focusOf as vn,windowOfPane as gn}from"./placement.js";import{awaitBrokerViewSocket as yn}from"./view-socket.js";import{readLogSnapshot as _e}from"../events/read.js";import{transition as M}from"./lifecycle.js";import{beginBootFaultAttempt as bn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as xn}from"./host.js";import{openDb as Sn,withCanvasWrite as Cn}from"../canvas/db.js";import{warmNodeRepos as $n}from"../graph/reader.js";import{mintNodeToken as En}from"../canvas/node-tokens.js";import{recordLaunch as On}from"../canvas/canvas.js";import{setExecutionLaunchJson as In}from"../canvas/executions.js";import{acceptedRelease as ke,remoteMachineEnvironmentOf as Rn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as Mn,awaitMachineCall as Fn,callTimes as Nn}from"./runner/machine/call.js";import{addStepTiming as J,timedStep as W}from"../step-timings.js";import{MachineLostError as Dn,MachineOfflineError as Pn}from"./runner/machine/ops.js";import{isDrained as Bn}from"../../daemon/drain.js";import{ensureDaemon as Tn}from"../../daemon/manage.js";import{readConfig as Ln}from"../config.js";import{modelRequestFromConfig as An,unregisteredConcreteModel as zn,unroutableConcreteModel as Wn}from"../model-routes.js";import{openModelRegistry as jn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Hn}from"./model-selection.js";import{forkNodeLedger as Kn}from"./ledger.js";import{appRungForGrant as Un}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Xn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as qn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Gn}from"../async-array.js";import{checkStart as Vn}from"./start-check.js";function F(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(F,"launchFailureOutcome");async function Jn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await M(e,"crash",{reason:"launch_failed",outcome:F(t)})}catch{}const a=t.message;throw G(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}l(Jn,"launchBrokerOrCrash");function Yn(e){return _e({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}l(Yn,"lastStartupStep");function Qn(e,r){return _e({nodeId:e,component:"broker",pattern:"broker.runtime.fatal"},!1).items.flatMap(t=>t.kind==="event"&&t.envelope.event==="broker.runtime.fatal"&&Date.parse(t.envelope.ts)>=r?[t.envelope.error?.message??""]:[]).at(-1)||null}l(Qn,"brokerFatalMessage");function Zn(e,r,o){const t=Yn(e),a=t===null?"it had logged no startup step":`the last startup step it logged was \`${t}\``;if(r.reason==="exited"){const{code:d,signal:s}=r.status,f=Qn(e,o);return{text:`exited (code ${d??"null"}, signal ${s??"null"}) before binding its view socket; ${a}${f===null?"":`: ${f}`}`,fields:{reason:"exited",code:d,signal:s,last_startup_step:t}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${a}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:t}}}l(Zn,"notReadyDescription");async function er(e,r){try{await M(e,"crash",{reason:"launch_failed",outcome:F(r)})}catch{}try{Z.teardown(e)}catch{}}l(er,"crashAndTearDown");async function nr(e){const r=await R().header(e).then(d=>d.path,()=>null);if(r!==null)return r;const o=(await R().list()).map(({conversation_id:d,path:s})=>({id:d,path:s})),t=o.filter(d=>d.id===e),a=t.length>0?t:o.filter(d=>d.id.startsWith(e));if(a.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(a.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${a.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return a[0].path}l(nr,"resolveSessionUuid");async function ve(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=V(Me(r)?r:Fe(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await R().header(t)).path}const o=await w(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=V(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await R().header(a)).path}return await nr(r)}l(ve,"resolveForkSource");async function rr(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?ze(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?je(o):We(o)}l(rr,"resolveProfileId");function ge(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return An(e.model,r,e.modelExact===!0)}l(ge,"requestFromLaunch");async function ye(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await Un(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:d,...s}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...s,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}l(ye,"appPaidLaunch");async function be(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await zn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await jn(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Hn});const a=await Wn(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(be,"assertLaunchModelRegistered");function tr(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}l(tr,"resolveSpawner");async function or(e,r){const o=await Nn(e);o!==null&&J("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))J(`mac_${t}`,a)}l(or,"recordStartCallTimings");async function ir(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:d}=await import("../../daemon/api/handlers/broker-ops.js");if(await Bn())return"full";let s;try{s=await ue(e.node_id,{daemonEpoch:he().epoch(),runner:"machine",release:ke()})}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),"failed"}let f;try{o.env={...o.env,CRTR_EXECUTION_ID:s};const c=await xn(e.node_id,o,e.cwd);await In(s,c);const j=s;J("execution_setup",performance.now()-t);const[x,N]=await W("warm_and_bundle",async()=>await Promise.allSettled([W("warm_repos",async()=>await $n(await Sn(),e.node_id)),W("start_bundle",async()=>{const g=e.sub;if(g==null)throw new Error(`cannot start node ${e.node_id}: its row has no person (null sub)`);return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:g,launchJson:c,runner:"machine"})})]));if(x.status==="rejected")throw x.reason;if(N.status==="rejected")throw N.reason;const v=N.value;f=await W("render_transaction",()=>Cn(async g=>{const T=await d(e.node_id),S=await En(g,j,e.node_id,new Date().toISOString());return await Mn(r,"start",{executionId:j,nodeId:e.node_id,attempt:1,release:ke(),launchJson:c,cwd:e.cwd,resuming:!1,nodeToken:S,bundle:v,start:T})},{timingName:"render_tx"}))}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),await z(s,{reason:"launch_failed"}),"failed"}let b;try{b=await Fn(r,"start",f)}catch(c){return p({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),c instanceof Dn||c instanceof Pn&&c.sent?"uncertain":(await z(s,{reason:"launch_failed"}),"failed")}try{await or(f,b)}catch(c){p({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:c})}try{await W("record_launch",()=>On(e.node_id,new Date().toISOString()))}catch(c){p({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:c})}return"started"}l(ir,"startOnMachine");async function xe(e,r,o){const t=performance.now();try{Tn()}catch{}const a=Te(),d=e.root===!0,s=tr(e.parent,a.nodeId??null,d),f=e.mode??"base",b=e.rootLifecycle??(d?"resident":"terminal"),c=d&&b==="resident",j=Date.now(),x=s===null?null:await w(s),N=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Ae(e.nodeId);const v=e.forkFrom!==void 0?await ve(e.forkFrom):void 0,g=v===void 0?null:await Be(v),T=await Gn([x,N,g],async h=>h?.isolated===!0||h?.run_id!=null&&(await w(h.run_id))?.isolated===!0);if(T&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=T||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let _=S||e.worktree===!0?e.nodeId??await le():e.nodeId,D=S?e.run!==void 0&&d&&!T?e.cwd:Ne(De(e.run?.grantee??x?.grantee??"app:terminal").nodes,_):e.cwd;const m=await rr(e.profile,s,D),H=S?null:await Ke(m,e.worktreeCwd??D);H!==null&&(D=H,_??=await le());const L=e.worktree===!0||H!==null,ne=e.run?.grant_id??x?.grant_id??null,A=e.run??N??x??g,re=await ye((await ce(e.kind,f,{lifecycle:b,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:D,profileId:m,app:A?.grantee??"app:terminal"})).launch,ne,e.model);await be(ge(re),{cwd:D,profileId:m}),await Vn({grantee:A?.grantee??"app:terminal",sub:A?.sub,grant_id:A?.grant_id,profile_id:m});const te=g?.node_id??null;let C,K=D;const U=L&&await Ue(m)?await Xe(m,H??e.worktreeCwd??e.cwd,_,e.worktreeBase):void 0,X=L&&U===void 0?await Ye(m):null;try{L&&U===void 0&&(C=X!==null?await Ve(X,e.worktreeCwd??e.cwd,_,e.worktreeBase):await qe(e.worktreeCwd??e.cwd,_,e.worktreeBase),K=C.path);const h=L?await ye((await ce(e.kind,f,{lifecycle:b,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:K,profileId:m,app:A?.grantee??"app:terminal"})).launch,ne,e.model):re;U!==void 0&&(h.worktree=U),L&&await be(ge(h),{cwd:K,profileId:m});const n=await Pe({kind:e.kind,mode:f,lifecycle:b,cwd:K,name:e.name??e.kind,description:e.description,parent:d?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:d?s??void 0:void 0,profile_id:m,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:v,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},..._!==void 0?{nodeId:_}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await Kn(n.node_id,te??null)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}if(await en(n.node_id,e.prompt),e.situationalContext!==void 0&&await nn(n.node_id,rn(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}const Y=e.prompt!=="",Se=`${Y&&e.wakeOrigin!==void 0?`${on(e.wakeOrigin)}
2
2
 
3
- `:""}${e.prompt}`;f==="orchestrator"&&await tn(n.node_id,{goal:e.prompt.trim()}),await ir(n);let ae;if(v!==void 0)try{const i=V(v);if(i===null)throw new Error(`invalid fork source ${v}`);const u=await R().fork(i,n.node_id);ae=(await R().header(u)).path}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:D(i)}),i}const y=He(n,{prompt:Se,resumeSessionPath:ae});if(y.env={...y.env,CRTR_SUBTREE:await Le(n.node_id)},Y){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};y.env[dn]=an(i),await sn(y,n)}const $=he();if(await pn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await In(n.profile_id??null):null;if(u!==null){J("birth",performance.now()-t);const P=await or(n,u,y);if(P==="started"||P==="uncertain")return{node:n,frozen:!1,window:null,session:null}}let O=!1;if(u===null)try{const{reviveNode:P}=await import("./revive.js");O=(await P(n.node_id,{resume:!0,capacity:"freeze",recovery:!0})).outcome!=="frozen"}catch(P){p({level:"warn",event:"broker.create_start_failed",node_id:n.node_id,error:P})}const I=await w(n.node_id);return O?{node:I,frozen:!1,window:null,session:null}:I.frozen_at!=null||I.status!=="active"&&I.status!=="idle"?{node:I,frozen:I.frozen_at!=null,window:null,session:null}:(await Q(n.node_id,i),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...I,frozen_at:i},frozen:!0,window:null,session:null})}if(Ze()&&!Re(n.cwd))throw new Qe({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const de=await $.reserveSlot(n.node_id),E=de?await hn(n.node_id):null;if(E?.verdict==="too_small"){$.releaseReservation(n.node_id);const i=mn(E);throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:D(i)}),i}if(!de||E?.verdict==="denied")return E?.verdict==="denied"&&$.releaseReservation(n.node_id),await Q(n.node_id,new Date().toISOString()),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:E?.verdict==="denied"?{reason:"app_memory",free_bytes:E.free_bytes,needed_bytes:E.needed_bytes}:{reason:"broker_cap",live_count:await $.occupancy(),hard_cap:pe().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const Ce=await yn(n.node_id),{automaticReviveCap:$e}=pe();let B;try{B=await we(n.node_id,{daemonEpoch:$.epoch(),cap:$e})}catch(i){if(!(i instanceof ln))throw i;return $.releaseReservation(n.node_id),await Q(n.node_id,new Date().toISOString()),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}y.env={...y.env,CRTR_EXECUTION_ID:B};let q;try{q=await Vn(n.node_id,y,{cwd:n.cwd,name:me(n),resuming:!1})}catch(i){throw await z(B,{reason:"launch_failed"}),i}finally{$.releaseReservation(n.node_id)}if(q.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await z(B,{reason:"launch_failed"}),await M(n.node_id,"crash",{reason:"launch_failed",outcome:D(i)}),G(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await fn(B,n.node_id,q.pid)==="shutdown")throw await z(B,{reason:"superseded"}),ne.teardown(n.node_id),G(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(c&&e.readiness==="await"){const i=await gn(n.node_id,q.exited);if(!i.ready){const u=Qn(n.node_id,i,j);p({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await Ce.explanation();throw await Zn(n.node_id,new Error(O??u.text)),G(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let se=null,le=null;if(!d&&s!==null&&Tn("user").auto_open_child_viewers)try{const i=await kn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await _n(n.node_id,i.session??"",{name:me(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:Y});u!==null&&u.pane!==null&&u.pane!==""&&(le=u.session,se=vn(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:se,session:le}}catch(h){throw C!==void 0&&_!==void 0&&await w(_)===null&&(X!==null?await Je(X,C):await Ge(C)),h}}l(xe,"spawnChildPrepared");async function ft(e){return xe(e)}l(ft,"spawnChild");async function ir(e){const r=Un(e.cwd,e.profile_id).plans.get("node:start")??[];await Xn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await ee(e.node_id),contextDir:await Z(e.node_id),jobDir:un(e.node_id)},runtime:{isBirth:!0,canvasHome:cn(),profile:e.profile_id??null}})}l(ir,"invokeBirthLifecycleHooks");const ar=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function wt(e,r,o){const t=await w(e);if(t===null)throw k(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await ve(e),d=await Z(e);try{await R().header(V(a)),Oe(d,Ie.R_OK)}catch(s){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${s.message}`)}return xe({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async s=>{const f=await Z(s);wn(await ee(e),d,await ee(s),f,ar)})}l(wt,"forkNode");export{ye as appPaidLaunch,be as assertLaunchModelRegistered,wt as forkNode,ir as invokeBirthLifecycleHooks,ve as resolveForkSource,nr as resolveProfileId,rr as resolveSpawner,ft as spawnChild,xe as spawnChildPrepared};
3
+ `:""}${e.prompt}`;f==="orchestrator"&&await tn(n.node_id,{goal:e.prompt.trim()}),await ar(n);let oe;if(v!==void 0)try{const i=V(v);if(i===null)throw new Error(`invalid fork source ${v}`);const u=await R().fork(i,n.node_id);oe=(await R().header(u)).path}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}const y=He(n,{prompt:Se,resumeSessionPath:oe});if(y.env={...y.env,CRTR_SUBTREE:await Le(n.node_id)},Y){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};y.env[dn]=an(i),await sn(y,n)}const $=he();if(await _n(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await Rn(n.profile_id??null):null;if(u!==null){J("birth",performance.now()-t);const B=await ir(n,u,y);if(B==="started"||B==="uncertain")return{node:n,frozen:!1,window:null,session:null}}let O=!1;if(u===null)try{const{reviveNode:B}=await import("./revive.js");O=(await B(n.node_id,{resume:!0,capacity:"freeze",recovery:!0})).outcome!=="frozen"}catch(B){p({level:"warn",event:"broker.create_start_failed",node_id:n.node_id,error:B})}const I=await w(n.node_id);return O?{node:I,frozen:!1,window:null,session:null}:I.frozen_at!=null||I.status!=="active"&&I.status!=="idle"?{node:I,frozen:I.frozen_at!=null,window:null,session:null}:(await Q(n.node_id,i),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...I,frozen_at:i},frozen:!0,window:null,session:null})}if(Ze()&&!Re(n.cwd))throw new Qe({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await $.reserveSlot(n.node_id),E=ie?await pn(n.node_id):null;if(E?.verdict==="too_small"){$.releaseReservation(n.node_id);const i=hn(E);throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}if(!ie||E?.verdict==="denied")return E?.verdict==="denied"&&$.releaseReservation(n.node_id),await Q(n.node_id,new Date().toISOString()),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:E?.verdict==="denied"?{reason:"app_memory",free_bytes:E.free_bytes,needed_bytes:E.needed_bytes}:{reason:"broker_cap",live_count:await $.occupancy(),hard_cap:pe().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const Ce=await bn(n.node_id),{automaticReviveCap:$e}=pe();let P;try{P=await ue(n.node_id,{daemonEpoch:$.epoch(),cap:$e})}catch(i){if(!(i instanceof ln))throw i;return $.releaseReservation(n.node_id),await Q(n.node_id,new Date().toISOString()),p({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}y.env={...y.env,CRTR_EXECUTION_ID:P};let q;try{q=await Jn(n.node_id,y,{cwd:n.cwd,name:fe(n),resuming:!1})}catch(i){throw await z(P,{reason:"launch_failed"}),i}finally{$.releaseReservation(n.node_id)}if(q.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await z(P,{reason:"launch_failed"}),await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),G(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await fn(P,n.node_id,q.pid)==="shutdown")throw await z(P,{reason:"superseded"}),Z.teardown(n.node_id),G(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(c&&e.readiness==="await"){const i=await yn(n.node_id,q.exited);if(!i.ready){const u=Zn(n.node_id,i,j);p({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await Ce.explanation();throw await er(n.node_id,new Error(O??u.text)),G(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!d&&s!==null&&Ln("user").auto_open_child_viewers)try{const i=await vn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await kn(n.node_id,i.session??"",{name:fe(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:Y});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=gn(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:ae,session:de}}catch(h){throw C!==void 0&&_!==void 0&&await w(_)===null&&(X!==null?await Je(X,C):await Ge(C)),h}}l(xe,"spawnChildPrepared");async function wt(e){return xe(e)}l(wt,"spawnChild");async function ar(e){const r=Xn(e.cwd,e.profile_id).plans.get("node:start")??[];await qn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,...await wn(e.node_id),jobDir:un(e.node_id)},runtime:{isBirth:!0,canvasHome:cn(),profile:e.profile_id??null}})}l(ar,"invokeBirthLifecycleHooks");const dr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function mt(e,r,o){const t=await w(e);if(t===null)throw k(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await ve(e),d=await we(e);try{await R().header(V(a)),Oe(d,Ie.R_OK)}catch(s){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${s.message}`)}return xe({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async s=>{const f=await we(s);mn(await me(e),d,await me(s),f,dr)})}l(mt,"forkNode");export{ye as appPaidLaunch,be as assertLaunchModelRegistered,mt as forkNode,ar as invokeBirthLifecycleHooks,ve as resolveForkSource,rr as resolveProfileId,tr as resolveSpawner,wt as spawnChild,xe as spawnChildPrepared};
@@ -30,7 +30,7 @@ export interface ResolveOptions {
30
30
  * have released it while its bytes were fetched). */
31
31
  export declare function assertUploadsUsable(grantee: string, person: string | undefined, uses: readonly AttachmentUse[], db: CanvasDb): Promise<void>;
32
32
  /** Fetch every upload a storage URL in `text` names into the blob store at `attachments/<rootId>/<sha256>` and replace
33
- * exactly each URL's span with the path the node's broker downloads that file to (`<app space>/nodes/<rootId>/attachments/<name>`).
33
+ * exactly each URL's span with the path the node's broker downloads that file to (`$CRTR_NODE_DIR/attachments/<name>`, which the broker expands to its own node folder; the recorded `upload_uses.path` is the node-relative `attachments/<name>`).
34
34
  * The control plane writes no file there. Without configured storage the text passes through unchanged. A failure leaves
35
35
  * at most content-keyed blobs, which are harmless and are deleted with the node. */
36
36
  export declare function resolveStorageUrls(grantee: string, person: string | undefined, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
@@ -1 +1 @@
1
- var H=Object.defineProperty;var c=(e,t)=>H(e,"name",{value:t,configurable:!0});import{createHash as B}from"node:crypto";import{extname as O,join as A}from"node:path";import{Writable as W}from"node:stream";import{pipeline as Z}from"node:stream/promises";import{blobStore as j}from"../blobs/index.js";import{appSpace as q}from"../layout.js";import{RunError as E}from"../runs/operations.js";import{storageClient as D,storageConfig as F,StorageRefused as G}from"./client.js";import{getUpload as T,runUsesPath as N}from"./tables.js";const P=11e4,g=c((e,t)=>new E(400,"invalid_request",t,void 0,{url:e}),"refused"),_=c(e=>new E(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function C(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}c(C,"shownUrl");function z(e,t,o){return e.grantee===t&&(o===void 0||e.sub===o)}c(z,"ownsUpload");async function I(e,t,o,i,r,d){const l=`${t}/`,$=[];let p=0;for(let u=e.indexOf(l,p);u!==-1;u=e.indexOf(l,p)){const a=C(e,u),w=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(u+l.length));if(!w)throw g(a,`storage URL ${a} does not name an upload`);if(w[1]!==o)throw g(a,`storage URL ${a} names another runtime`);const f=await T(w[2],d);if(!f||!z(f,i,r))throw g(a,`storage URL ${a} names an unknown upload`);if(f.delete_pending_since)throw g(a,`storage URL ${a} names a deleted upload`);const h=u+l.length+w[0].length,m=encodeURIComponent(f.name);if(!e.startsWith(m,h))throw g(a,`storage URL ${a} does not match the upload's name`);$.push({start:u,end:h+m.length,upload:f}),p=h+m.length}return $}c(I,"matchStorageUrls");async function re(e,t,o,i){for(const r of o){const d=await T(r.upload_id,i);if(!d||!z(d,e,t)||d.delete_pending_since)throw g(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}c(re,"assertUploadsUsable");function J(e,t){if(t===1)return e;const o=O(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}c(J,"candidate");async function ie(e,t,o,i,r={}){const d={text:i,uses:[]},l=(r.config??F)();if(!l||!i.includes(`${l.base_url}/`))return d;const $=(r.client??D)(),p=await I(i,l.base_url,$.runtimeId,e,t);if(!p.length)return d;const u=A(q(e).nodes,o,"attachments"),a=AbortSignal.timeout(r.budgetMs??P),w=await(r.blobs??j)(),f=new Set(r.taken),h=new Map;for(const{upload:s,start:M}of p){if(h.has(s.upload_id))continue;const U=C(i,M);let S;try{S=await $.fetchUpload(s.upload_id,a)}catch(n){throw n instanceof G?g(U,n.status===409?`storage URL ${U} names an upload that was never finished`:`storage URL ${U} names an unknown upload`):a.aborted?_("attachments could not be fetched within 110 s"):n}const L=[],k=B("sha256");try{await Z(S.body,new W({write(n,K,x){k.update(n),L.push(n),x()}}),{signal:a})}catch(n){throw a.aborted?_("attachments could not be fetched within 110 s"):_(`storage stopped sending ${s.name}: ${n instanceof Error?n.message:String(n)}`)}const y=Buffer.concat(L);if(y.length!==s.size)throw _(`storage sent ${y.length} of ${s.size} bytes of ${s.name}`);const v=`attachments/${o}/${k.digest("hex")}`;try{await w.put(v,y)}catch(n){throw _(`the attachment ${s.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let b="";for(let n=1;b=A(u,J(s.name,n)),!(!f.has(b)&&!await N(o,b));n++);f.add(b),h.set(s.upload_id,{upload_id:s.upload_id,path:b,url:U,blob_key:v})}let m="",R=0;for(const s of p)m+=i.slice(R,s.start)+h.get(s.upload.upload_id).path,R=s.end;return m+=i.slice(R),{text:m,uses:[...h.values()]}}c(ie,"resolveStorageUrls");export{P as ATTACHMENT_FETCH_BUDGET_MS,re as assertUploadsUsable,ie as resolveStorageUrls};
1
+ var M=Object.defineProperty;var l=(e,t)=>M(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{extname as D}from"node:path";import{Writable as H}from"node:stream";import{pipeline as O}from"node:stream/promises";import{blobStore as B}from"../blobs/index.js";import{RunError as T}from"../runs/operations.js";import{storageClient as I,storageConfig as N,StorageRefused as W}from"./client.js";import{getUpload as k,runUsesPath as Z}from"./tables.js";const q=11e4,w=l((e,t)=>new T(400,"invalid_request",t,void 0,{url:e}),"refused"),b=l(e=>new T(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");function v(e,t){return/^[^\s<>"'`)\]]*/.exec(e.slice(t))[0].replace(/[.,;:!?]+$/,"")}l(v,"shownUrl");function A(e,t,o){return e.grantee===t&&(o===void 0||e.sub===o)}l(A,"ownsUpload");async function F(e,t,o,c,r,u){const f=`${t}/`,$=[];let h=0;for(let i=e.indexOf(f,h);i!==-1;i=e.indexOf(f,h)){const s=v(e,i),g=/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\//.exec(e.slice(i+f.length));if(!g)throw w(s,`storage URL ${s} does not name an upload`);if(g[1]!==o)throw w(s,`storage URL ${s} names another runtime`);const d=await k(g[2],u);if(!d||!A(d,c,r))throw w(s,`storage URL ${s} names an unknown upload`);if(d.delete_pending_since)throw w(s,`storage URL ${s} names a deleted upload`);const m=i+f.length+g[0].length,p=encodeURIComponent(d.name);if(!e.startsWith(p,m))throw w(s,`storage URL ${s} does not match the upload's name`);$.push({start:i,end:m+p.length,upload:d}),h=m+p.length}return $}l(F,"matchStorageUrls");async function ne(e,t,o,c){for(const r of o){const u=await k(r.upload_id,c);if(!u||!A(u,e,t)||u.delete_pending_since)throw w(r.url,`storage URL ${r.url} names an upload deleted while it was fetched`)}}l(ne,"assertUploadsUsable");function G(e,t){if(t===1)return e;const o=D(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}l(G,"candidate");async function oe(e,t,o,c,r={}){const u={text:c,uses:[]},f=(r.config??N)();if(!f||!c.includes(`${f.base_url}/`))return u;const $=(r.client??I)(),h=await F(c,f.base_url,$.runtimeId,e,t);if(!h.length)return u;const i=AbortSignal.timeout(r.budgetMs??q),s=await(r.blobs??B)(),g=new Set(r.taken),d=new Map;for(const{upload:a,start:C}of h){if(d.has(a.upload_id))continue;const U=v(c,C);let y;try{y=await $.fetchUpload(a.upload_id,i)}catch(n){throw n instanceof W?w(U,n.status===409?`storage URL ${U} names an upload that was never finished`:`storage URL ${U} names an unknown upload`):i.aborted?b("attachments could not be fetched within 110 s"):n}const S=[],L=x("sha256");try{await O(y.body,new H({write(n,P,z){L.update(n),S.push(n),z()}}),{signal:i})}catch(n){throw i.aborted?b("attachments could not be fetched within 110 s"):b(`storage stopped sending ${a.name}: ${n instanceof Error?n.message:String(n)}`)}const R=Buffer.concat(S);if(R.length!==a.size)throw b(`storage sent ${R.length} of ${a.size} bytes of ${a.name}`);const E=`attachments/${o}/${L.digest("hex")}`;try{await s.put(E,R)}catch(n){throw b(`the attachment ${a.name} could not be stored: ${n instanceof Error?n.message:String(n)}`)}let _="";for(let n=1;_=`attachments/${G(a.name,n)}`,!(!g.has(_)&&!await Z(o,_));n++);g.add(_),d.set(a.upload_id,{upload_id:a.upload_id,path:_,url:U,blob_key:E})}let m="",p=0;for(const a of h)m+=c.slice(p,a.start)+`$CRTR_NODE_DIR/${d.get(a.upload.upload_id).path}`,p=a.end;return m+=c.slice(p),{text:m,uses:[...d.values()]}}l(oe,"resolveStorageUrls");export{q as ATTACHMENT_FETCH_BUDGET_MS,ne as assertUploadsUsable,oe as resolveStorageUrls};
@@ -67,8 +67,12 @@ export declare function runUsesPath(runId: string, path: string, db?: CanvasDb):
67
67
  export declare function deleteUploadUse(use: UploadUseRow, db?: CanvasDb): Promise<void>;
68
68
  /** Record the size storage actually holds for an upload created with `max_size`. */
69
69
  export declare function setUploadSize(uploadId: string, size: number, db?: CanvasDb): Promise<void>;
70
- /** The use recorded at `path`, if any. */
71
- export declare function uploadUseAt(path: string, db?: CanvasDb): Promise<UploadUseRow | null>;
70
+ /** The use recorded at `path`, if any. A node's folder path (`…/apps/<app>/nodes/<id>/attachments/<name>`, as the broker host names it) is read as the node's
71
+ * relative row `attachments/<name>`; a row recorded before paths were relative holds the absolute path, and is found by it. */
72
+ export declare function uploadUseAt(path: string, db?: CanvasDb, node?: {
73
+ nodeId: string;
74
+ nodeDir: string;
75
+ }): Promise<UploadUseRow | null>;
72
76
  /** Delete a run's uses and mark each of its uploads that no other run uses for
73
77
  * deletion. Returns the upload ids newly owed a storage delete. */
74
78
  export declare function releaseRunUploads(runIds: readonly string[], db?: CanvasDb): Promise<string[]>;
@@ -1,4 +1,4 @@
1
- var l=Object.defineProperty;var t=(e,a)=>l(e,"name",{value:a,configurable:!0});import{openDb as E}from"../canvas/db.js";import{filterAsync as _}from"../async-array.js";const h=t(e=>`file:${e}`,"fileUsePath"),i=t(async e=>e??await E(),"handle"),p=t(()=>new Date().toISOString(),"now");async function T(e,a){await(await i(a)).prepare("INSERT INTO uploads (upload_id, grantee, sub, name, media_type, size, created_at, delete_pending_since) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)").run(e.upload_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.created_at)}t(T,"insertUpload");async function L(e,a){return await(await i(a)).prepare("SELECT * FROM uploads WHERE upload_id = ?").get(e)??null}t(L,"getUpload");async function w(e,a){await(await i(a)).prepare("DELETE FROM uploads WHERE upload_id = ?").run(e)}t(w,"deleteUploadRow");async function O(e){return await(await i(e)).prepare("SELECT * FROM uploads WHERE delete_pending_since IS NOT NULL ORDER BY delete_pending_since, upload_id").all()}t(O,"pendingUploadDeletes");async function o(e,a,n=p()){const r=(await i(a)).prepare("UPDATE uploads SET delete_pending_since = COALESCE(delete_pending_since, ?) WHERE upload_id = ?");for(const s of e)await r.run(n,s)}t(o,"markUploadsDeletePending");async function y(e,a){const n=(await i(a)).prepare("INSERT INTO upload_uses (upload_id, run_id, path, blob_key) VALUES (?, ?, ?, ?)");for(const r of e)await n.run(r.upload_id,r.run_id,r.path,r.blob_key??null)}t(y,"insertUploadUses");async function U(e,a,n){return await(await i(n)).prepare("SELECT 1 AS used FROM upload_uses WHERE run_id = ? AND path = ?").get(e,a)!==void 0}t(U,"runUsesPath");async function x(e,a){await(await i(a)).prepare("DELETE FROM upload_uses WHERE upload_id = ? AND run_id = ? AND path = ?").run(e.upload_id,e.run_id,e.path)}t(x,"deleteUploadUse");async function D(e,a,n){await(await i(n)).prepare("UPDATE uploads SET size = ? WHERE upload_id = ?").run(a,e)}t(D,"setUploadSize");async function N(e,a){return await(await i(a)).prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE path = ? ORDER BY run_id LIMIT 1").get(e)??null}t(N,"uploadUseAt");async function g(e,a){const n=await i(a);if(!e.length)return[];const r=e.map(()=>"?").join(","),s=(await n.prepareUncached(`SELECT DISTINCT upload_id FROM upload_uses WHERE run_id IN (${r})`).all(...e)).map(u=>u.upload_id);await n.prepareUncached(`DELETE FROM upload_uses WHERE run_id IN (${r})`).run(...e);const d=await _(s,async u=>!await n.prepare("SELECT 1 FROM upload_uses WHERE upload_id = ? LIMIT 1").get(u));return await o(d,n),d}t(g,"releaseRunUploads");async function m(e,a){return(await(await i(a)).prepare(`SELECT upload_id FROM uploads u WHERE delete_pending_since IS NULL AND created_at <= ?
2
- AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`).all(e)).map(n=>n.upload_id)}t(m,"staleUnusedUploads");async function A(e,a){await(await i(a)).prepare(`INSERT INTO shares (share_id, source_space, source_path, storage_key, url, created_by, sub, created_at, expires_at, status, object_deleted_at)
3
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(e.share_id,e.source_space,e.source_path,e.storage_key,e.url,e.created_by,e.sub??null,e.created_at,e.expires_at)}t(A,"insertShare");async function F(e,a){await(await i(a)).prepare(`INSERT INTO files (file_id, run_id, node_id, grantee, sub, name, media_type, size, sha256, created_at, completed_at)
4
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).run(e.file_id,e.run_id,e.node_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.sha256,e.created_at)}t(F,"insertFile");async function H(e,a){return await(await i(a)).prepare("SELECT * FROM files WHERE file_id = ?").get(e)??null}t(H,"getFile");async function W(e,a=p(),n){return Number((await(await i(n)).prepare("UPDATE files SET completed_at = ? WHERE file_id = ? AND completed_at IS NULL").run(a,e)).changes)>0}t(W,"completeFile");async function C(e,a){e.length&&await(await i(a)).prepareUncached(`DELETE FROM files WHERE run_id IN (${e.map(()=>"?").join(",")})`).run(...e)}t(C,"deleteRunFiles");async function b(e,a){return await(await i(a)).prepare("SELECT * FROM shares WHERE share_id = ?").get(e)??null}t(b,"getShare");async function M(e,a){return e===null?await(await i(a)).prepare("SELECT * FROM shares ORDER BY created_at DESC, share_id").all():await(await i(a)).prepare("SELECT * FROM shares WHERE created_by = ? ORDER BY created_at DESC, share_id").all(e)}t(M,"listShares");async function c(e,a){await(await i(a)).prepare("UPDATE shares SET status = 'off' WHERE share_id = ?").run(e)}t(c,"turnShareOff");async function I(e,a){const n=await i(a),r=(await n.prepare("SELECT share_id FROM shares WHERE created_by = ? AND status = 'on'").all(e)).map(s=>s.share_id);return await n.prepare("UPDATE shares SET status = 'off' WHERE created_by = ? AND status = 'on'").run(e),r}t(I,"turnSharesOffFor");async function P(e=p(),a){const n=await i(a),r=(await n.prepare("SELECT share_id FROM shares WHERE status = 'on' AND expires_at IS NOT NULL AND expires_at <= ?").all(e)).map(s=>s.share_id);for(const s of r)await c(s,n);return r}t(P,"expireShares");async function j(e){return await(await i(e)).prepare("SELECT * FROM shares WHERE status = 'off' AND object_deleted_at IS NULL ORDER BY created_at, share_id").all()}t(j,"sharesOwingObjectDelete");async function k(e,a,n=p()){await(await i(a)).prepare("UPDATE shares SET object_deleted_at = COALESCE(object_deleted_at, ?) WHERE share_id = ?").run(n,e)}t(k,"markShareObjectDeleted");async function z(e,a,n=p()){const r=await i(a),s=(await r.prepare("SELECT upload_id FROM uploads WHERE grantee = ? AND delete_pending_since IS NULL").all(e)).map(d=>d.upload_id);return await o(s,r,n),s}t(z,"markGranteeUploadsDeletePending");export{W as completeFile,C as deleteRunFiles,w as deleteUploadRow,x as deleteUploadUse,P as expireShares,h as fileUsePath,H as getFile,b as getShare,L as getUpload,F as insertFile,A as insertShare,T as insertUpload,y as insertUploadUses,M as listShares,z as markGranteeUploadsDeletePending,k as markShareObjectDeleted,o as markUploadsDeletePending,O as pendingUploadDeletes,g as releaseRunUploads,U as runUsesPath,D as setUploadSize,j as sharesOwingObjectDelete,m as staleUnusedUploads,c as turnShareOff,I as turnSharesOffFor,N as uploadUseAt};
1
+ var l=Object.defineProperty;var n=(e,a)=>l(e,"name",{value:a,configurable:!0});import{openDb as E}from"../canvas/db.js";import{filterAsync as c}from"../async-array.js";const h=n(e=>`file:${e}`,"fileUsePath"),i=n(async e=>e??await E(),"handle"),d=n(()=>new Date().toISOString(),"now");async function T(e,a){await(await i(a)).prepare("INSERT INTO uploads (upload_id, grantee, sub, name, media_type, size, created_at, delete_pending_since) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)").run(e.upload_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.created_at)}n(T,"insertUpload");async function L(e,a){return await(await i(a)).prepare("SELECT * FROM uploads WHERE upload_id = ?").get(e)??null}n(L,"getUpload");async function w(e,a){await(await i(a)).prepare("DELETE FROM uploads WHERE upload_id = ?").run(e)}n(w,"deleteUploadRow");async function O(e){return await(await i(e)).prepare("SELECT * FROM uploads WHERE delete_pending_since IS NOT NULL ORDER BY delete_pending_since, upload_id").all()}n(O,"pendingUploadDeletes");async function o(e,a,t=d()){const r=(await i(a)).prepare("UPDATE uploads SET delete_pending_since = COALESCE(delete_pending_since, ?) WHERE upload_id = ?");for(const s of e)await r.run(t,s)}n(o,"markUploadsDeletePending");async function D(e,a){const t=(await i(a)).prepare("INSERT INTO upload_uses (upload_id, run_id, path, blob_key) VALUES (?, ?, ?, ?)");for(const r of e)await t.run(r.upload_id,r.run_id,r.path,r.blob_key??null)}n(D,"insertUploadUses");async function y(e,a,t){return await(await i(t)).prepare("SELECT 1 AS used FROM upload_uses WHERE run_id = ? AND path = ?").get(e,a)!==void 0}n(y,"runUsesPath");async function U(e,a){await(await i(a)).prepare("DELETE FROM upload_uses WHERE upload_id = ? AND run_id = ? AND path = ?").run(e.upload_id,e.run_id,e.path)}n(U,"deleteUploadUse");async function x(e,a,t){await(await i(t)).prepare("UPDATE uploads SET size = ? WHERE upload_id = ?").run(a,e)}n(x,"setUploadSize");async function N(e,a,t){const r=await i(a),s=t!==void 0&&e.startsWith(`${t.nodeDir}/attachments/`)?[e,t.nodeId,e.slice(t.nodeDir.length+1)]:/\/apps\/[^/]+\/nodes\/([^/]+)\/(attachments\/.+)$/.exec(e);if(s!==null){const p=await r.prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE run_id = ? AND path = ?").get(s[1],s[2]);if(p!==void 0)return p}return await r.prepare("SELECT upload_id, run_id, path FROM upload_uses WHERE path = ? ORDER BY run_id LIMIT 1").get(e)??null}n(N,"uploadUseAt");async function g(e,a){const t=await i(a);if(!e.length)return[];const r=e.map(()=>"?").join(","),s=(await t.prepareUncached(`SELECT DISTINCT upload_id FROM upload_uses WHERE run_id IN (${r})`).all(...e)).map(u=>u.upload_id);await t.prepareUncached(`DELETE FROM upload_uses WHERE run_id IN (${r})`).run(...e);const p=await c(s,async u=>!await t.prepare("SELECT 1 FROM upload_uses WHERE upload_id = ? LIMIT 1").get(u));return await o(p,t),p}n(g,"releaseRunUploads");async function m(e,a){return(await(await i(a)).prepare(`SELECT upload_id FROM uploads u WHERE delete_pending_since IS NULL AND created_at <= ?
2
+ AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`).all(e)).map(t=>t.upload_id)}n(m,"staleUnusedUploads");async function A(e,a){await(await i(a)).prepare(`INSERT INTO shares (share_id, source_space, source_path, storage_key, url, created_by, sub, created_at, expires_at, status, object_deleted_at)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'on', NULL)`).run(e.share_id,e.source_space,e.source_path,e.storage_key,e.url,e.created_by,e.sub??null,e.created_at,e.expires_at)}n(A,"insertShare");async function W(e,a){await(await i(a)).prepare(`INSERT INTO files (file_id, run_id, node_id, grantee, sub, name, media_type, size, sha256, created_at, completed_at)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`).run(e.file_id,e.run_id,e.node_id,e.grantee,e.sub??null,e.name,e.media_type,e.size,e.sha256,e.created_at)}n(W,"insertFile");async function F(e,a){return await(await i(a)).prepare("SELECT * FROM files WHERE file_id = ?").get(e)??null}n(F,"getFile");async function H(e,a=d(),t){return Number((await(await i(t)).prepare("UPDATE files SET completed_at = ? WHERE file_id = ? AND completed_at IS NULL").run(a,e)).changes)>0}n(H,"completeFile");async function C(e,a){e.length&&await(await i(a)).prepareUncached(`DELETE FROM files WHERE run_id IN (${e.map(()=>"?").join(",")})`).run(...e)}n(C,"deleteRunFiles");async function M(e,a){return await(await i(a)).prepare("SELECT * FROM shares WHERE share_id = ?").get(e)??null}n(M,"getShare");async function b(e,a){return e===null?await(await i(a)).prepare("SELECT * FROM shares ORDER BY created_at DESC, share_id").all():await(await i(a)).prepare("SELECT * FROM shares WHERE created_by = ? ORDER BY created_at DESC, share_id").all(e)}n(b,"listShares");async function _(e,a){await(await i(a)).prepare("UPDATE shares SET status = 'off' WHERE share_id = ?").run(e)}n(_,"turnShareOff");async function I(e,a){const t=await i(a),r=(await t.prepare("SELECT share_id FROM shares WHERE created_by = ? AND status = 'on'").all(e)).map(s=>s.share_id);return await t.prepare("UPDATE shares SET status = 'off' WHERE created_by = ? AND status = 'on'").run(e),r}n(I,"turnSharesOffFor");async function P(e=d(),a){const t=await i(a),r=(await t.prepare("SELECT share_id FROM shares WHERE status = 'on' AND expires_at IS NOT NULL AND expires_at <= ?").all(e)).map(s=>s.share_id);for(const s of r)await _(s,t);return r}n(P,"expireShares");async function j(e){return await(await i(e)).prepare("SELECT * FROM shares WHERE status = 'off' AND object_deleted_at IS NULL ORDER BY created_at, share_id").all()}n(j,"sharesOwingObjectDelete");async function k(e,a,t=d()){await(await i(a)).prepare("UPDATE shares SET object_deleted_at = COALESCE(object_deleted_at, ?) WHERE share_id = ?").run(t,e)}n(k,"markShareObjectDeleted");async function z(e,a,t=d()){const r=await i(a),s=(await r.prepare("SELECT upload_id FROM uploads WHERE grantee = ? AND delete_pending_since IS NULL").all(e)).map(p=>p.upload_id);return await o(s,r,t),s}n(z,"markGranteeUploadsDeletePending");export{H as completeFile,C as deleteRunFiles,w as deleteUploadRow,U as deleteUploadUse,P as expireShares,h as fileUsePath,F as getFile,M as getShare,L as getUpload,W as insertFile,A as insertShare,T as insertUpload,D as insertUploadUses,b as listShares,z as markGranteeUploadsDeletePending,k as markShareObjectDeleted,o as markUploadsDeletePending,O as pendingUploadDeletes,g as releaseRunUploads,y as runUsesPath,x as setUploadSize,j as sharesOwingObjectDelete,m as staleUnusedUploads,_ as turnShareOff,I as turnSharesOffFor,N as uploadUseAt};