@north-light/cli 0.3.713 → 0.3.715

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 (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +2 -2
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/environments.d.ts +4 -0
  6. package/dist/api/dto/execution-start.d.ts +9 -0
  7. package/dist/api/routes.d.ts +1 -0
  8. package/dist/api/routes.js +1 -1
  9. package/dist/clients/attach/input/controller.d.ts +2 -0
  10. package/dist/clients/attach/input/controller.js +1 -1
  11. package/dist/clients/attach/input/local-files.d.ts +3 -1
  12. package/dist/clients/attach/input/local-files.js +8 -3
  13. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  14. package/dist/clients/attach/render/chat-view.js +2 -2
  15. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  16. package/dist/clients/attach/session/input-wiring.js +1 -1
  17. package/dist/clients/attach/viewer.js +526 -521
  18. package/dist/commands/node/inspect.js +5 -5
  19. package/dist/commands/profile/environment.js +2 -2
  20. package/dist/commands/sys/feedback.js +5 -5
  21. package/dist/core/broker-client/client.js +1 -1
  22. package/dist/core/canvas/canvas.js +1 -1
  23. package/dist/core/canvas/deliveries.js +10 -10
  24. package/dist/core/canvas/executions.d.ts +0 -2
  25. package/dist/core/canvas/executions.js +1 -1
  26. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  27. package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
  28. package/dist/core/canvas/schema-version.d.ts +1 -1
  29. package/dist/core/canvas/schema-version.js +1 -1
  30. package/dist/core/canvas/types.d.ts +1 -0
  31. package/dist/core/checkout-identities.js +1 -1
  32. package/dist/core/environment-recipe.d.ts +1 -0
  33. package/dist/core/environment-recipe.js +1 -1
  34. package/dist/core/import/load/bind.d.ts +8 -0
  35. package/dist/core/import/load/bind.js +15 -15
  36. package/dist/core/import/load/prepare.d.ts +8 -1
  37. package/dist/core/import/load/prepare.js +9 -7
  38. package/dist/core/import/load/run.js +2 -2
  39. package/dist/core/ledger/rates.d.ts +0 -2
  40. package/dist/core/ledger/rates.js +1 -1
  41. package/dist/core/llm/run.d.ts +1 -1
  42. package/dist/core/pool-credential-store.d.ts +5 -5
  43. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  44. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  45. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  46. package/dist/core/runtime/broker-wedge.js +2 -2
  47. package/dist/core/runtime/revive.js +2 -2
  48. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  49. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  50. package/dist/core/runtime/runner/types.d.ts +0 -2
  51. package/dist/core/runtime/spawn.js +1 -1
  52. package/dist/core/subscription-state.d.ts +3 -3
  53. package/dist/core/subscription-state.js +1 -1
  54. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  55. package/dist/daemon/api/handlers/environments.js +1 -1
  56. package/dist/daemon/api/handlers/feedback.d.ts +2 -0
  57. package/dist/daemon/api/handlers/feedback.js +9 -0
  58. package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
  59. package/dist/daemon/api/handlers/git-credential.js +1 -1
  60. package/dist/daemon/api/operations.js +1 -1
  61. package/dist/daemon/api/server.js +1 -1
  62. package/dist/daemon/fleet.d.ts +1 -12
  63. package/dist/daemon/fleet.js +2 -2
  64. package/dist/daemon/machine-daemon.js +1 -1
  65. package/dist/daemon/machine-link/holder.js +1 -1
  66. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  67. package/dist/daemon/reconcilers/ledger-storage.js +2 -4
  68. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  69. package/package.json +3 -3
  70. package/packages/crouter-api/dist/api/client.js +4 -0
  71. package/packages/crouter-api/dist/api/contract.js +1 -1
  72. package/packages/crouter-api/dist/api/routes.js +1 -0
  73. package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
  74. package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
  75. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  76. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  77. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  78. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  79. package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
  80. package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
  81. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  82. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  83. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  84. package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
  85. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  86. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  87. package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
  88. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  89. package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
  90. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  91. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  92. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  93. package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
  94. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
  95. package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
  96. package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
  97. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  98. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
  99. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
  100. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  101. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  102. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/install-runtime.mjs +3 -2
  108. package/scripts/sandbox-start.mjs +1 -1
  109. package/scripts/self-update.mjs +5 -1
@@ -1,12 +1,12 @@
1
1
  var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as I,defineLeaf as _}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as O}from"../../core/errors.js";import{isPidAlive as A}from"../../core/canvas/pid.js";import{fullName as $}from"../../core/canvas/labels.js";import{fuzzyMatch as F}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as L}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as D}from"../../api/index.js";import{cliClient as x,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as E,profilesStateBlock as z,resolveProfileViaDaemon as M}from"../profile/daemon-profiles.js";import{focusViewer as B,nodeInPane as W}from"../surface/node/placement.js";const K=_({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([E(),z()])).join(`
2
- `),"leaf")},run:h(async n=>{const e=h(d=>{const v=n[d];return v!==void 0&&v!==""?v.split(",").map(b=>b.trim()).filter(b=>b!==""):void 0},"csv"),o=e("status"),s=e("kind"),u=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,p=S({canvasName:n.canvas}),a=p instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await p.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await p.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||u!==void 0&&!u.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const u=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(u===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=u,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,p={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),p.session_file&&a.push(`Read the raw conversation transcript: ${p.session_file}`),a.push(`On-disk context dir (ls/read directly): ${p.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:p,follow_up:a.join(`
3
- `)};return i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&t.status===400?!1:w(t))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],p=e.machine;p&&r.push(`- machine: ${p.name??p.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
4
- `));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,v=g.map(b=>`| ${t.map(R=>String(b[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
2
+ `),"leaf")},run:h(async n=>{const e=h(d=>{const b=n[d];return b!==void 0&&b!==""?b.split(",").map(v=>v.trim()).filter(v=>v!==""):void 0},"csv"),o=e("status"),s=e("kind"),p=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,u=S({canvasName:n.canvas}),a=u instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await u.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await u.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||p!==void 0&&!p.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const p=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(p===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=p,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&a.push(`Read the raw conversation transcript: ${u.session_file}`),a.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:u,follow_up:a.join(`
3
+ `)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&(t.status===400||t.status===404)?!1:w(t)))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],u=e.machine;u&&r.push(`- machine: ${u.name??u.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
4
+ `));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
5
5
  `);return`${g.length} ${f}:
6
6
 
7
7
  ${y}
8
8
  ${d}
9
- ${v}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
9
+ ${b}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
10
10
  ${String(n.follow_up)}`),l.join(`
11
11
 
12
- `)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const u=await x().forkNode(s).catch(w),i=await B(u.node_id,{cwd:u.cwd,name:u.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:u.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
12
+ `)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const p=await x().forkNode(s).catch(w),i=await B(p.node_id,{cwd:p.cwd,name:p.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:p.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
@@ -1,2 +1,2 @@
1
- var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{readFileSync as g}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as c}from"../api-client.js";import{resolveProfileViaDaemon as l}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},u=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function f(e){const{environment_id:r,...i}=e;return i}t(f,"output");const w=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...u],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:t(async e=>{const{id:r}=await l(e.profile);return f(await c().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages or memory",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...u],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:t(async e=>{const{id:r}=await l(e.profile),i=e.repo,s=e.setupScriptFile,o=e.piPackage,n=e.memory;if(n!==void 0&&![2,4,8].includes(n))throw m("`--memory` is 2, 4 or 8 (GB).");const a={...i!==void 0&&i.length>0?{repositories:i}:{},...s!==void 0?{setup_script:g(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
- `)}:{},...n!==void 0?{memory_mb:n*1024}:{}};if(Object.keys(a).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`.");return f(await c().setProfileEnvironment(r,a))},"run")}),R=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[w,v]});export{R as environmentBranch};
1
+ var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as w}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as u}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...t}=e;return t}n(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:n(async e=>{const{id:r}=await c(e.profile);return h(await u().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:n(async e=>{const{id:r}=await c(e.profile),t=e.repo,s=e.setupScriptFile,o=e.piPackage,i=e.memory,a=e.allowPullRequestWrite;if(i!==void 0&&![2,4,8].includes(i))throw m("`--memory` is 2, 4 or 8 (GB).");const l={...t!==void 0&&t.length>0?{repositories:t}:{},...s!==void 0?{setup_script:w(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
+ `)}:{},...i!==void 0?{memory_mb:i*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await u().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,v]});export{A as environmentBranch};
@@ -1,7 +1,7 @@
1
- var p=Object.defineProperty;var a=(r,e)=>p(r,"name",{value:e,configurable:!0});import{spawnSync as y}from"node:child_process";import{mkdirSync as g,writeFileSync as w}from"node:fs";import{join as h}from"node:path";import d from"node:os";import{defineLeaf as b}from"../../core/command.js";import{usage as k}from"../../core/errors.js";import{userScopeRoot as v}from"../../core/scope.js";import{readTelemetry as T}from"../../core/canvas/telemetry.js";import{ApiError as $}from"../../api/index.js";import{cliClient as E}from"../api-client.js";import{projectTier1Event as N,readLogSnapshot as _}from"../../core/events/read.js";import{readPackageVersion as O}from"./shared.js";const m="Northlight-Systems/crouter",l="CRTR_FEEDBACK_ENDPOINT",R="CRTR_FEEDBACK_TOKEN",S=15e3;async function C(){const r=process.env,e=r.CRTR_NODE_ID??null;let t=null,n=[];if(e!==null){const s=await D(e);s!==null&&typeof s.cycles=="number"&&(t=s.cycles),n=I(e)}const o=e!==null?T(e).context_tokens??null:null;return{version:O(),platform:`${d.platform()} ${d.release()} (${d.arch()})`,nodeId:e,kind:r.CRTR_KIND??null,mode:r.CRTR_MODE??null,lifecycle:r.CRTR_LIFECYCLE??null,cwd:r.CRTR_NODE_CWD??process.cwd(),cycle:t,contextTokens:o,logTail:n}}a(C,"collectContext");async function D(r){try{return await E().getNode(r)}catch(e){if(e instanceof $)return null;throw e}}a(D,"fetchNodeOrNull");function I(r){try{return _({nodeId:r,component:"broker"},!1).items.filter(e=>e.kind==="event").slice(-15).map(e=>JSON.stringify(N(e.envelope)))}catch{return[]}}a(I,"readRecentActivity");function L(r,e){const n=(r!==void 0&&r.trim()!==""?r.trim():void 0)??e.split(`
2
- `)[0].trim();return`[feedback] ${n.length>80?n.slice(0,79)+"\u2026":n}`}a(L,"deriveTitle");function j(r,e){const t=[`| crtr version | \`${e.version}\` |`,`| platform | ${e.platform} |`];e.nodeId!==null&&(t.push(`| node id | \`${e.nodeId}\` |`),t.push(`| kind / mode / lifecycle | ${e.kind??"?"} / ${e.mode??"?"} / ${e.lifecycle??"?"} |`),e.cycle!==null&&t.push(`| cycle | ${e.cycle} |`),e.contextTokens!==null&&t.push(`| context tokens | ${e.contextTokens.toLocaleString("en-US")} |`)),e.cwd!==null&&t.push(`| working dir | \`${e.cwd}\` |`);const n=[r.trim(),"","---","_Filed via `crtr sys feedback` \u2014 context below auto-attached by the harness._","","### Environment","| | |","|---|---|",...t];return e.logTail.length>0&&n.push("",`### Recent node activity (last ${e.logTail.length} log events)`,"```jsonl",...e.logTail,"```"),n.join(`
1
+ var g=Object.defineProperty;var a=(r,e)=>g(r,"name",{value:e,configurable:!0});import{spawnSync as w}from"node:child_process";import{mkdirSync as k,writeFileSync as b}from"node:fs";import{join as m}from"node:path";import u from"node:os";import{defineLeaf as v}from"../../core/command.js";import{usage as T}from"../../core/errors.js";import{userScopeRoot as $}from"../../core/scope.js";import{readTelemetry as E}from"../../core/canvas/telemetry.js";import{ApiError as R,routes as _}from"../../api/index.js";import{cliClient as p}from"../api-client.js";import{projectTier1Event as N,readLogSnapshot as O}from"../../core/events/read.js";import{readPackageVersion as S}from"./shared.js";const y="Northlight-Systems/crouter",l="CRTR_FEEDBACK_ENDPOINT",C="CRTR_FEEDBACK_TOKEN",D=15e3;async function I(){const r=process.env,e=r.CRTR_NODE_ID??null;let t=null,n=[];if(e!==null){const s=await L(e);s!==null&&typeof s.cycles=="number"&&(t=s.cycles),n=F(e)}const o=e!==null?E(e).context_tokens??null:null;return{version:S(),platform:`${u.platform()} ${u.release()} (${u.arch()})`,nodeId:e,kind:r.CRTR_KIND??null,mode:r.CRTR_MODE??null,lifecycle:r.CRTR_LIFECYCLE??null,cwd:r.CRTR_NODE_CWD??process.cwd(),cycle:t,contextTokens:o,logTail:n}}a(I,"collectContext");async function L(r){try{return await p().getNode(r)}catch(e){if(e instanceof R)return null;throw e}}a(L,"fetchNodeOrNull");function F(r){try{return O({nodeId:r,component:"broker"},!1).items.filter(e=>e.kind==="event").slice(-15).map(e=>JSON.stringify(N(e.envelope)))}catch{return[]}}a(F,"readRecentActivity");function P(r,e){const n=(r!==void 0&&r.trim()!==""?r.trim():void 0)??e.split(`
2
+ `)[0].trim();return`[feedback] ${n.length>80?n.slice(0,79)+"\u2026":n}`}a(P,"deriveTitle");function j(r,e){const t=[`| crtr version | \`${e.version}\` |`,`| platform | ${e.platform} |`];e.nodeId!==null&&(t.push(`| node id | \`${e.nodeId}\` |`),t.push(`| kind / mode / lifecycle | ${e.kind??"?"} / ${e.mode??"?"} / ${e.lifecycle??"?"} |`),e.cycle!==null&&t.push(`| cycle | ${e.cycle} |`),e.contextTokens!==null&&t.push(`| context tokens | ${e.contextTokens.toLocaleString("en-US")} |`)),e.cwd!==null&&t.push(`| working dir | \`${e.cwd}\` |`);const n=[r.trim(),"","---","_Filed via `crtr sys feedback` \u2014 context below auto-attached by the harness._","","### Environment","| | |","|---|---|",...t];return e.logTail.length>0&&n.push("",`### Recent node activity (last ${e.logTail.length} log events)`,"```jsonl",...e.logTail,"```"),n.join(`
3
3
  `)+`
4
- `}a(j,"buildBody");async function q(r,e,t,n,o){const s=process.env[R];try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...s!==void 0&&s!==""?{authorization:`Bearer ${s}`}:{}},body:JSON.stringify({title:e,body:t,message:n,context:o}),signal:AbortSignal.timeout(S)});if(!i.ok){const f=(await i.text().catch(()=>"")).trim().slice(0,400);return{error:`${l} returned HTTP ${i.status}${f===""?"":`: ${f}`}`}}const c=await i.json().catch(()=>null),u=typeof c?.url=="string"?c.url:void 0;return u===void 0?{}:{url:u}}catch(i){return{error:`${l} unreachable: ${i instanceof Error?i.message:String(i)}`}}}a(q,"deliverToEndpoint");function F(r,e){const t=y("gh",["issue","create","--repo",m,"--title",r,"--body-file","-"],{input:e,encoding:"utf8"});return t.error===void 0&&t.status===0?{url:t.stdout.trim().split(`
5
- `).filter(o=>o.startsWith("http")).pop()??t.stdout.trim()}:{error:t.error!==void 0?`gh not available: ${t.error.message}`:t.stderr?.trim()||`gh exited ${t.status}`}}a(F,"deliverToGitHub");function K(r,e){const t=h(v(),"feedback");g(t,{recursive:!0});const n=new Date().toISOString().replace(/[:.]/g,"-"),o=h(t,`${n}.md`);return w(o,`# ${r}
4
+ `}a(j,"buildBody");async function q(r,e,t,n,o){const s=process.env.CRTR_API_URL;if(s!==void 0&&s!==""&&r===`${s.replace(/\/$/,"")}${_.feedback()}`)try{return{url:(await p().postFeedback({title:e,body:t})).url}}catch(i){return{error:`${l} failed: ${i instanceof Error?i.message:String(i)}`}}const c=process.env[C];try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...c!==void 0&&c!==""?{authorization:`Bearer ${c}`}:{}},body:JSON.stringify({title:e,body:t,message:n,context:o}),signal:AbortSignal.timeout(D)});if(!i.ok){const h=(await i.text().catch(()=>"")).trim().slice(0,400);return{error:`${l} returned HTTP ${i.status}${h===""?"":`: ${h}`}`}}const d=await i.json().catch(()=>null),f=typeof d?.url=="string"?d.url:void 0;return f===void 0?{}:{url:f}}catch(i){return{error:`${l} unreachable: ${i instanceof Error?i.message:String(i)}`}}}a(q,"deliverToEndpoint");function A(r,e){const t=w("gh",["issue","create","--repo",y,"--title",r,"--body-file","-"],{input:e,encoding:"utf8"});return t.error===void 0&&t.status===0?{url:t.stdout.trim().split(`
5
+ `).filter(o=>o.startsWith("http")).pop()??t.stdout.trim()}:{error:t.error!==void 0?`gh not available: ${t.error.message}`:t.stderr?.trim()||`gh exited ${t.status}`}}a(A,"deliverToGitHub");function K(r,e){const t=m($(),"feedback");k(t,{recursive:!0});const n=new Date().toISOString().replace(/[:.]/g,"-"),o=m(t,`${n}.md`);return b(o,`# ${r}
6
6
 
7
- ${e}`,"utf8"),o}a(K,"saveLocally");const Q=b({name:"feedback",description:"report a crtr harness bug to whoever maintains this crtr install",whenToUse:"a crtr command itself misbehaves \u2014 it errors unexpectedly, hangs, churns, double-spawns, or acts contrary to its documented contract. NOT for your task work or decisions the user should make (that is `crtr human send`); this reports the TOOL, filing a report with the crtr maintainers with your node context auto-attached.",help:{name:"sys feedback",summary:"file a report describing a crtr harness bug, with node context auto-attached",params:[{kind:"positional",name:"message",required:!0,constraint:"What broke, in your own words: the command you ran, what you expected, what happened instead. Be concrete \u2014 this is the only part you write; everything else is auto-collected."},{kind:"flag",name:"title",type:"string",required:!1,constraint:"Issue title. Default: first line of the message, truncated."}],output:[{name:"status",type:"string",required:!0,constraint:"filed | saved-locally."},{name:"url",type:"string",required:!1,constraint:"Where the report landed, when the sink names a location."},{name:"path",type:"string",required:!1,constraint:"Local report path when status is saved-locally."},{name:"error",type:"string",required:!1,constraint:"Why filing fell back to local save."}],outputKind:"object",effects:[`Sends the report where this install delivers harness feedback: the ${l} endpoint when the deployment sets one, otherwise a public GitHub issue on ${m} via gh.`,"On delivery failure, writes the report to ~/.crouter/feedback/ instead \u2014 never lost."]},run:a(async r=>{const e=r.message?.trim();if(e===void 0||e==="")throw k("feedback message is required: describe what broke. Run `crtr sys feedback -h`.");const t=await C(),n=L(r.title,e),o=j(e,t),s=process.env[l]?.trim(),i=s!==void 0&&s!==""?await q(s,n,o,e,t):F(n,o);return i.error===void 0?i.url===void 0?{status:"filed"}:{status:"filed",url:i.url}:{status:"saved-locally",path:K(n,o),error:i.error}},"run")});export{Q as sysFeedbackLeaf};
7
+ ${e}`,"utf8"),o}a(K,"saveLocally");const Z=v({name:"feedback",description:"report a crtr harness bug to whoever maintains this crtr install",whenToUse:"a crtr command itself misbehaves \u2014 it errors unexpectedly, hangs, churns, double-spawns, or acts contrary to its documented contract. NOT for your task work or decisions the user should make (that is `crtr human send`); this reports the TOOL, filing a report with the crtr maintainers with your node context auto-attached.",help:{name:"sys feedback",summary:"file a report describing a crtr harness bug, with node context auto-attached",params:[{kind:"positional",name:"message",required:!0,constraint:"What broke, in your own words: the command you ran, what you expected, what happened instead. Be concrete \u2014 this is the only part you write; everything else is auto-collected."},{kind:"flag",name:"title",type:"string",required:!1,constraint:"Issue title. Default: first line of the message, truncated."}],output:[{name:"status",type:"string",required:!0,constraint:"filed | saved-locally."},{name:"url",type:"string",required:!1,constraint:"Where the report landed, when the sink names a location."},{name:"path",type:"string",required:!1,constraint:"Local report path when status is saved-locally."},{name:"error",type:"string",required:!1,constraint:"Why filing fell back to local save."}],outputKind:"object",effects:[`Sends the report where this install delivers harness feedback: the ${l} endpoint when the deployment sets one, otherwise a GitHub issue on ${y} via gh.`,"On delivery failure, writes the report to ~/.crouter/feedback/ instead \u2014 never lost."]},run:a(async r=>{const e=r.message?.trim();if(e===void 0||e==="")throw T("feedback message is required: describe what broke. Run `crtr sys feedback -h`.");const t=await I(),n=P(r.title,e),o=j(e,t),s=process.env[l]?.trim(),c=s!==void 0&&s!==""?await q(s,n,o,e,t):A(n,o);return c.error===void 0?c.url===void 0?{status:"filed"}:{status:"filed",url:c.url}:{status:"saved-locally",path:K(n,o),error:c.error}},"run")});export{Z as sysFeedbackLeaf};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as k}from"./transport-socket.js";import{RelayTransport as x}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}probe(e){return this.transport?.probe?.(e)??Promise.resolve(!0)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,x as RelayTransport,k as SocketTransport,E as reconnectShouldGiveUp};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as b}from"./transport.js";import{SocketTransport as k}from"./transport-socket.js";import{RelayTransport as x}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}probe(e){return this.transport?.probe?.(e)??Promise.resolve(!0)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(Object.assign(new Error(e.message||`request failed: ${e.code}`),{code:e.code}));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,b as BrokerUnavailableError,x as RelayTransport,k as SocketTransport,E as reconnectShouldGiveUp};
@@ -1,4 +1,4 @@
1
- var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(r){if(r instanceof Qe&&r.code==="not_found")return null;throw r}}i(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}i(K,"faultFrom");const G=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=i(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}i(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(A,"metaFrom");async function Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}i(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}i(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(r=>`w.${r} AS worktree_${r}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(r=>[r.node_id,r]));return await h(e.map(r=>a.get(r)).filter(r=>r!==void 0),async r=>await A(r,ee(r)))}i(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}i(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),r=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(r.changes)>0}i(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}i(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}i(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}i(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}i(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
1
+ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(r){if(r instanceof Qe&&r.code==="not_found")return null;throw r}}i(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}i(K,"faultFrom");const G=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=i(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,cycle_pending:e.cycle_pending===1,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}i(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(A,"metaFrom");async function Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}i(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}i(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(r=>`w.${r} AS worktree_${r}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(r=>[r.node_id,r]));return await h(e.map(r=>a.get(r)).filter(r=>r!==void 0),async r=>await A(r,ee(r)))}i(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}i(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),r=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(r.changes)>0}i(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}i(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}i(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}i(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}i(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
2
2
  WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
3
3
  AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
4
4
  ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(nt,"dueNodeDeadlines");async function tt(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(tt,"setNodeDeadline");async function at(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
@@ -1,20 +1,20 @@
1
- var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as O}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{CLAIM_OWNER_EXPIRED_SQL as X}from"./reconciler-leases.js";import{inboxPath as w,passivePath as R}from"./paths.js";import{withRetryBudget as M}from"./delivery-contract.js";import{emitEvent as F}from"../events/emit.js";import{mapAsync as H}from"../async-array.js";function D(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(D,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
- WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function y(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
1
+ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as D}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{CLAIM_OWNER_EXPIRED_SQL as X}from"./reconciler-leases.js";import{inboxPath as y,passivePath as R}from"./paths.js";import{withRetryBudget as M}from"./delivery-contract.js";import{emitEvent as F}from"../events/emit.js";import{mapAsync as H}from"../async-array.js";function O(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(O,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
+ WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${d?" AND n.intent IS DISTINCT FROM 'refresh' AND n.cycle_pending = 0":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function w(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
3
3
  m.sender_node_id, m.sender_name, m.kind, m.label, m.body_ref, m.body_json, m.disposition
4
4
  FROM deliveries d JOIN messages m ON m.message_id = d.message_id
5
5
  WHERE d.destination_id = ? AND d.wake = ?
6
6
  ${E?"AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'":d===0?"AND NOT (m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')":""}
7
7
  AND d.canceled_at IS NULL
8
8
  AND d.state = 'handed_off' AND d.claim_owner = ?
9
- ORDER BY m.seq`).all(a,d,r)).map(i=>({...D(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(y,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
9
+ ORDER BY m.seq`).all(a,d,r)).map(i=>({...O(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(w,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
10
10
  WHERE d.destination_id = ? AND d.wake = ? AND d.state = 'pending' AND d.canceled_at IS NULL
11
11
  AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')`,W=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
12
12
  WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function te(e,a,r,d=Date.now()){const s=r==="wake"?1:0;if(r==="deferred_run")return await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=await c.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
13
13
  WHERE d.destination_id = ? AND d.wake = 0 AND d.canceled_at IS NULL
14
14
  AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'
15
15
  AND (d.state = 'pending' OR (d.state = 'handed_off' AND d.claim_owner = ?))`).all(e,a),t=new Set(i.length===0?[]:(await c.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
16
- WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await y(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(W).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,s,i)}})}o(te,"claimNodeMail");async function ae(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
17
- WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await y(d,e,a,1,s)})}o(ae,"claimKickoffMail");function j(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(j,"normalizedSettlement");async function $(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:j(d),l=M(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
16
+ WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await w(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await w(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(W).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await w(c,e,a,s,i)}})}o(te,"claimNodeMail");async function ae(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
17
+ WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await w(d,e,a,1,s)})}o(ae,"claimKickoffMail");function j(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(j,"normalizedSettlement");async function $(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:j(d),l=M(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
18
18
  SET state = ?, next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL,
19
19
  acknowledged_at = ?, failed_at = ?, last_failure_json = ?, updated_at = ?
20
20
  WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,r)).changes)===1;if(f&&l.exhausted&&_.state==="permanent_failed"){const A=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:A.destination_id,messageId:A.message_id})}return f});for(const i of E)F({level:"error",event:"delivery.exhausted",outcome:"failed",attempt:a,fields:{delivery_id:e,destination_id:i.destinationId,message_id:i.messageId,failure:i.failure,retry:`crtr sys retry-delivery ${e}`}});return c}o($,"settleDelivery");async function ne(e,a=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries
@@ -22,13 +22,13 @@ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});i
22
22
  WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}o(ne,"retryFailedDelivery");async function ie(e,a,r,d=Date.now()){return await T(async s=>await L(s,e,a,!1)?{action:"acknowledged",results:await H(r,async c=>{const i=await s.prepare("SELECT 1 FROM deliveries WHERE delivery_id = ? AND destination_id = ?").get(c.deliveryId,e)!==void 0;return{deliveryId:c.deliveryId,outcome:i&&await $(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ie,"acknowledgeNodeMail");async function de(e){const a=await(await N()).prepare(`SELECT m.body_json FROM deliveries d JOIN messages m ON m.message_id = d.message_id
23
23
  WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}o(de,"messageBodyForDelivery");async function se(e){return(await(await N()).prepare(`SELECT * FROM deliveries
24
24
  WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?
25
- ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(D)}o(se,"duePushDeliveries");async function re(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
25
+ ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(O)}o(se,"duePushDeliveries");async function re(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
26
26
  WHERE d.delivery_id = ? AND d.state = 'pending' AND d.canceled_at IS NULL AND d.next_attempt_at <= ?
27
27
  AND NOT EXISTS (SELECT 1 FROM deliveries old JOIN messages prior ON prior.message_id = old.message_id
28
28
  JOIN messages next ON next.message_id = d.message_id
29
29
  WHERE old.destination_id = d.destination_id AND old.delivery_id != d.delivery_id
30
30
  AND old.state = 'handed_off' AND old.canceled_at IS NOT NULL
31
- AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:D(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(re,"claimPushDelivery");async function oe(e,a=!1){return await T(async r=>{const d=a?` AND ${X}`:"",s=a?[new Date(e).toISOString()]:[],E=await r.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
31
+ AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:O(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(re,"claimPushDelivery");async function oe(e,a=!1){return await T(async r=>{const d=a?` AND ${X}`:"",s=a?[new Date(e).toISOString()]:[],E=await r.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
32
32
  claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
33
33
  WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL${d}`).run(e,e,...s),c=await r.prepare(`UPDATE deliveries SET state = 'pending', next_attempt_at = CASE WHEN next_attempt_at IS NOT NULL THEN ?::bigint ELSE NULL END,
34
34
  claimed_at = NULL, claim_owner = NULL, updated_at = ?
@@ -39,8 +39,8 @@ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});i
39
39
  AND NOT EXISTS (
40
40
  SELECT 1 FROM executions e WHERE e.node_id = d.destination_id AND e.execution_id = d.claim_owner AND e.state != 'exited'
41
41
  )`).run(e)).changes)}o(ce,"resetStaleExecutionMail");const b=o((e,a)=>`${e}.wake = 1 AND ${e}.canceled_at IS NULL AND ${e}.urgency != 'deferred' AND ${e}.state IN (${a})`,"WAKE_MAIL_SQL"),q=o(e=>b(e,"'pending', 'handed_off'"),"UNSEEN_WAKE_MAIL_SQL");async function Ee(e){return await(await N()).prepare(`SELECT 1 FROM deliveries d WHERE d.destination_id = ? AND ${q("d")} LIMIT 1`).get(e)!==void 0}o(Ee,"hasUnseenWakeMail");async function me(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE destination_id = ? AND wake = 1
42
- AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(me,"hasWakeMailSince");async function Ne(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ne,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=O(e,"utf8");return a.trim()===""?[]:a.split(`
43
- `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function J(e){return I(e)?new Set(O(e,"utf8").split(`
42
+ AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(me,"hasWakeMailSince");async function Ne(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ne,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=D(e,"utf8");return a.trim()===""?[]:a.split(`
43
+ `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function J(e){return I(e)?new Set(D(e,"utf8").split(`
44
44
  `).map(a=>a.trim()).filter(Boolean)):new Set}o(J,"readCanceled");function pe(e){e.exec(`
45
45
  CREATE TABLE IF NOT EXISTS messages (
46
46
  message_id TEXT PRIMARY KEY,
@@ -95,4 +95,4 @@ CREATE TABLE IF NOT EXISTS waits (
95
95
  );
96
96
  CREATE UNIQUE INDEX IF NOT EXISTS waits_live ON waits(node_id) WHERE satisfied_at IS NULL;
97
97
  CREATE INDEX IF NOT EXISTS waits_node ON waits(node_id);
98
- `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=J(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${R(n)}.draining`],[1,R(n)]])U(f).forEach((A,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:A,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(pe,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{q as UNSEEN_WAKE_MAIL_SQL,b as WAKE_MAIL_SQL,ie as acknowledgeNodeMail,Ne as acknowledgedNodeMailCount,ae as claimKickoffMail,te as claimNodeMail,re as claimPushDelivery,D as deliveryFrom,se as duePushDeliveries,Ee as hasUnseenWakeMail,me as hasWakeMailSince,de as messageBodyForDelivery,pe as migrateMessagingState,j as normalizedSettlement,le as pushDeliveryClaimIsCurrent,_e as releaseExecutionMail,oe as resetHandedOffDeliveries,ce as resetStaleExecutionMail,ne as retryFailedDelivery,$ as settleDelivery};
98
+ `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(y(n)),_=I(`${y(n)}.cursor`)?D(`${y(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=J(`${y(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${R(n)}.draining`],[1,R(n)]])U(f).forEach((A,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:A,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(pe,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{q as UNSEEN_WAKE_MAIL_SQL,b as WAKE_MAIL_SQL,ie as acknowledgeNodeMail,Ne as acknowledgedNodeMailCount,ae as claimKickoffMail,te as claimNodeMail,re as claimPushDelivery,O as deliveryFrom,se as duePushDeliveries,Ee as hasUnseenWakeMail,me as hasWakeMailSince,de as messageBodyForDelivery,pe as migrateMessagingState,j as normalizedSettlement,le as pushDeliveryClaimIsCurrent,_e as releaseExecutionMail,oe as resetHandedOffDeliveries,ce as resetStaleExecutionMail,ne as retryFailedDelivery,$ as settleDelivery};
@@ -9,7 +9,6 @@ export interface Execution {
9
9
  endedAt: string | null;
10
10
  exitReason: string | null;
11
11
  runner: 'process' | 'blaxel' | 'machine';
12
- sandboxName: string | null;
13
12
  attempt: number;
14
13
  /** The release the wake accepted. */
15
14
  release: string | null;
@@ -31,7 +30,6 @@ export interface BeginExecutionInput {
31
30
  runner?: Execution['runner'];
32
31
  /** Defaults to one above the node's highest attempt. */
33
32
  attempt?: number;
34
- sandboxName?: string | null;
35
33
  release?: string | null;
36
34
  launchJson?: string | null;
37
35
  /** The broker cap. The count of other nodes' live rows and this insert are one step under a database-wide lock,
@@ -1 +1 @@
1
- var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as R,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class b extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class F extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new b(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,R())!=="dead"));if(s!==void 0)throw new F(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=R(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{F as ExecutionAlreadyLive,b as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
1
+ var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
@@ -0,0 +1,3 @@
1
+ -- 029-model-accounts-refresh-claim.sql — `model_accounts.refresh_claimed_until`: until when one process holds the right to spend the account's refresh
2
+ -- token (NL-1135), so a refresh holds no row lock or connection across the vendor call. An added column: `schema_min_reader` is not touched.
3
+ ALTER TABLE model_accounts ADD COLUMN IF NOT EXISTS refresh_claimed_until bigint NOT NULL DEFAULT 0;
@@ -0,0 +1,2 @@
1
+ -- 030-environment-pull-request-write.sql — `environments.allow_pull_request_write`: when true, the git credential a cloud environment's nodes receive also carries pull_requests: write (merging). An added column; it is not part of the recipe, so changing it builds no new image.
2
+ ALTER TABLE environments ADD COLUMN IF NOT EXISTS allow_pull_request_write boolean NOT NULL DEFAULT false;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 28;
4
+ export declare const CANVAS_SCHEMA_VERSION = 30;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=28;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=30;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -403,6 +403,7 @@ export interface NodeRow {
403
403
  created: string;
404
404
  /** Authoritative runtime columns (see NodeRuntime). */
405
405
  intent: ExitIntent;
406
+ cycle_pending?: boolean | null;
406
407
  frozen_at?: string | null;
407
408
  respawn_failures?: number;
408
409
  respawn_not_before?: string | null;
@@ -1,3 +1,3 @@
1
- var E=Object.defineProperty;var c=(t,r)=>E(t,"name",{value:r,configurable:!0});import{resolve as l}from"node:path";import{withCanvasWrite as O}from"./canvas/db.js";import{isCloudRole as p,PersonOutsideRequestError as y}from"./canvas/person-state.js";import{emitEvent as h}from"./events/emit.js";import{timedStep as v}from"./step-timings.js";import{realpathOrSelf as d}from"./fs-utils.js";import{checkoutChain as f}from"./graph/repo-sync/identity.js";import{callMachine as C}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as _}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as S,MachineLostError as N,MachineOfflineError as D}from"./runtime/runner/machine/ops.js";const J={"repo.identify":c(async({dirs:t})=>{const r=performance.now(),o=await Promise.all(t.map(async e=>{const a=await f(d(l(e)));return a.every(n=>n.ok)?[e,a]:null}));return h({level:"info",event:"machine.repo_identify.timing",fields:{dirs:t.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(o.filter(e=>e!==null))},"repo.identify")};async function g(t,r){const o=[...new Set(r.map(n=>l(n)))];if(o.length===0)return!0;let e;try{e=await v("repo_identify_call",()=>C(t,"repo.identify",{dirs:o}))}catch(n){if(!(n instanceof D||n instanceof N||n instanceof S))throw n;return h({level:"warn",event:"repo.identify.failed",error:n,fields:{environment:t,dirs:o.length}}),!1}const a=new Date().toISOString();return await O(async n=>{for(const s of o)e[s]!==void 0&&await n.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
1
+ var E=Object.defineProperty;var c=(t,r)=>E(t,"name",{value:r,configurable:!0});import{resolve as l}from"node:path";import{withCanvasWrite as O}from"./canvas/db.js";import{isCloudRole as p,PersonOutsideRequestError as y}from"./canvas/person-state.js";import{emitEvent as h}from"./events/emit.js";import{timedStep as v}from"./step-timings.js";import{realpathOrSelf as d}from"./fs-utils.js";import{checkoutChain as f}from"./graph/repo-sync/identity.js";import{callMachine as C}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as _}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as S,MachineLostError as N,MachineOfflineError as D}from"./runtime/runner/machine/ops.js";const J={"repo.identify":c(async({dirs:t})=>{const r=performance.now(),o=await Promise.all(t.map(async e=>{const a=await f(d(l(e)));return a.every(n=>n.ok)?[e,a]:null}));return h({level:"info",event:"machine.repo_identify.timing",fields:{dirs:t.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(o.filter(e=>e!==null))},"repo.identify")};async function g(t,r){const o=[...new Set(r.map(n=>l(n)))].sort();if(o.length===0)return!0;let e;try{e=await v("repo_identify_call",()=>C(t,"repo.identify",{dirs:o}))}catch(n){if(!(n instanceof D||n instanceof N||n instanceof S))throw n;return h({level:"warn",event:"repo.identify.failed",error:n,fields:{environment:t,dirs:o.length}}),!1}const a=new Date().toISOString();return await O(async n=>{for(const s of o)e[s]!==void 0&&await n.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
2
2
  ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(t,s,JSON.stringify(e[s]),a)}),!0}c(g,"warmMachineCheckouts");function k(t){const r=typeof t=="string"?JSON.parse(t):t;return Array.isArray(r)?r:[]}c(k,"chainOf");async function q(t,r,o){const e=l(r);return(await M(t,[e],o)).get(e)}c(q,"checkoutChainOf");async function M(t,r,o){const e=new Map,a=[...new Set(r)];if(!p()){for(const i of a)e.set(i,await f(i));return e}let n;try{n=await o()}catch(i){if(!(i instanceof y))throw i;for(const m of a)e.set(m,await f(m));return e}const s=n.replace(/^user:/,""),w=a.length===0?[]:await t.prepare(`SELECT DISTINCT ON (c.dir) c.dir, c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
3
3
  WHERE p.person IN (?, ?) AND c.dir = ANY(?::text[]) ORDER BY c.dir, c.observed_at DESC`).all(s,`user:${s}`,a),u=new Map(w.map(i=>[i.dir,i.chain_json]));for(const i of a)e.set(i,u.has(i)?k(u.get(i)):await f(i));return e}c(M,"checkoutChainsOf");async function H(t,r){const o=p()&&t!=null?await _(t):null;if(o!==null){await g(o,r);return}for(const e of r)await f(d(l(e)))}c(H,"warmCheckoutDirs");export{q as checkoutChainOf,M as checkoutChainsOf,J as machineCheckoutHandlers,H as warmCheckoutDirs,g as warmMachineCheckouts};
@@ -22,4 +22,5 @@ export declare function patchEnvironment(environmentId: string, patch: {
22
22
  setup_script?: string | null;
23
23
  pi_packages?: string | null;
24
24
  memory_mb?: number;
25
+ allow_pull_request_write?: boolean;
25
26
  }): Promise<void>;
@@ -1 +1 @@
1
- var f=Object.defineProperty;var s=(i,e)=>f(i,"name",{value:e,configurable:!0});import{usage as l}from"./errors.js";import{withCanvasWrite as m}from"./canvas/db.js";async function d(i,e){return await m(n=>_(n,i,e))}s(d,"setEnvironmentRecipe");async function _(i,e,n){const o=new Set;for(const r of n.repositories){if(!/^[A-Za-z0-9._-]+$/.test(r.name)||r.name==="."||r.name==="..")throw new Error(`repository name ${JSON.stringify(r.name)} is not a plain directory name`);if(o.has(r.name))throw new Error(`repository name ${r.name} appears twice in the recipe`);o.add(r.name)}{const r=await i.prepare("SELECT kind, recipe_revision, setup_script, pi_packages FROM environments WHERE object = ? FOR UPDATE").get(e);if(r===void 0)throw new Error(`no environment ${e}`);if(r.kind!=="blaxel")throw new Error(`environment ${e} is a ${r.kind} environment; only a cloud (blaxel) environment has a recipe image`);const p=await i.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(e);if(r.setup_script===n.setup_script&&r.pi_packages===n.pi_packages&&p.length===n.repositories.length&&p.every((a,t)=>a.name===n.repositories[t].name&&a.github_full_name===n.repositories[t].github_full_name&&a.default_branch===n.repositories[t].default_branch))return{revision:Number(r.recipe_revision),changed:!1};await i.prepare("DELETE FROM environment_repos WHERE environment = ?").run(e);const c=i.prepare("INSERT INTO environment_repos (environment, position, name, github_full_name, default_branch) VALUES (?, ?, ?, ?, ?)");for(const[a,t]of n.repositories.entries())await c.run(e,a,t.name,t.github_full_name,t.default_branch);const E=await i.prepare("UPDATE environments SET setup_script = ?, pi_packages = ?, recipe_revision = recipe_revision + 1 WHERE object = ? RETURNING recipe_revision").get(n.setup_script,n.pi_packages,e);return{revision:Number(E.recipe_revision),changed:!0}}}s(_,"writeEnvironmentRecipe");const u=[2048,4096,8192];async function v(i,e){if(e.memory_mb!==void 0&&!u.includes(e.memory_mb))throw l(`memory_mb must be one of ${u.join(", ")}`,{field:"memory_mb"});await m(async n=>{const o=await n.prepare("SELECT setup_script, pi_packages FROM environments WHERE object = ? AND kind = 'blaxel' FOR UPDATE").get(i);if(o===void 0)throw new Error(`no cloud environment ${i}`);if(e.repositories!==void 0||e.setup_script!==void 0||e.pi_packages!==void 0){const r=e.repositories??await n.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(i);await _(n,i,{repositories:r,setup_script:e.setup_script===void 0?o.setup_script:e.setup_script,pi_packages:e.pi_packages===void 0?o.pi_packages:e.pi_packages})}e.memory_mb!==void 0&&await n.prepare("UPDATE environments SET memory_mb = ? WHERE object = ?").run(e.memory_mb,i)})}s(v,"patchEnvironment");export{u as ENVIRONMENT_MEMORY_MB,v as patchEnvironment,d as setEnvironmentRecipe,_ as writeEnvironmentRecipe};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{usage as f}from"./errors.js";import{withCanvasWrite as _}from"./canvas/db.js";async function d(r,e){return await _(n=>u(n,r,e))}s(d,"setEnvironmentRecipe");async function u(r,e,n){const o=new Set;for(const i of n.repositories){if(!/^[A-Za-z0-9._-]+$/.test(i.name)||i.name==="."||i.name==="..")throw new Error(`repository name ${JSON.stringify(i.name)} is not a plain directory name`);if(o.has(i.name))throw new Error(`repository name ${i.name} appears twice in the recipe`);o.add(i.name)}{const i=await r.prepare("SELECT kind, recipe_revision, setup_script, pi_packages FROM environments WHERE object = ? FOR UPDATE").get(e);if(i===void 0)throw new Error(`no environment ${e}`);if(i.kind!=="blaxel")throw new Error(`environment ${e} is a ${i.kind} environment; only a cloud (blaxel) environment has a recipe image`);const p=await r.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(e);if(i.setup_script===n.setup_script&&i.pi_packages===n.pi_packages&&p.length===n.repositories.length&&p.every((a,t)=>a.name===n.repositories[t].name&&a.github_full_name===n.repositories[t].github_full_name&&a.default_branch===n.repositories[t].default_branch))return{revision:Number(i.recipe_revision),changed:!1};await r.prepare("DELETE FROM environment_repos WHERE environment = ?").run(e);const E=r.prepare("INSERT INTO environment_repos (environment, position, name, github_full_name, default_branch) VALUES (?, ?, ?, ?, ?)");for(const[a,t]of n.repositories.entries())await E.run(e,a,t.name,t.github_full_name,t.default_branch);const l=await r.prepare("UPDATE environments SET setup_script = ?, pi_packages = ?, recipe_revision = recipe_revision + 1 WHERE object = ? RETURNING recipe_revision").get(n.setup_script,n.pi_packages,e);return{revision:Number(l.recipe_revision),changed:!0}}}s(u,"writeEnvironmentRecipe");const m=[2048,4096,8192];async function v(r,e){if(e.memory_mb!==void 0&&!m.includes(e.memory_mb))throw f(`memory_mb must be one of ${m.join(", ")}`,{field:"memory_mb"});await _(async n=>{const o=await n.prepare("SELECT setup_script, pi_packages FROM environments WHERE object = ? AND kind = 'blaxel' FOR UPDATE").get(r);if(o===void 0)throw new Error(`no cloud environment ${r}`);if(e.repositories!==void 0||e.setup_script!==void 0||e.pi_packages!==void 0){const i=e.repositories??await n.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(r);await u(n,r,{repositories:i,setup_script:e.setup_script===void 0?o.setup_script:e.setup_script,pi_packages:e.pi_packages===void 0?o.pi_packages:e.pi_packages})}e.memory_mb!==void 0&&await n.prepare("UPDATE environments SET memory_mb = ? WHERE object = ?").run(e.memory_mb,r),e.allow_pull_request_write!==void 0&&await n.prepare("UPDATE environments SET allow_pull_request_write = ? WHERE object = ?").run(String(e.allow_pull_request_write),r)})}s(v,"patchEnvironment");export{m as ENVIRONMENT_MEMORY_MB,v as patchEnvironment,d as setEnvironmentRecipe,u as writeEnvironmentRecipe};
@@ -18,6 +18,14 @@ export declare function checkStagedReferences(input: RewriteInput, own: {
18
18
  person: string;
19
19
  runId: string;
20
20
  }): Promise<void>;
21
+ /** Before `checkStagedReferences`: a staged `messages` row whose `object_id` or `actor_id` names a target object that check would refuse is dropped, with the
22
+ * `deliveries` and `message_causes` rows of those messages. A message is history, not a binding, and the object it names is another account's (a soft-deleted
23
+ * row of an earlier import from a different install). Ids with no target row keep the stub treatment; every other table still refuses. Returns rows dropped per table. */
24
+ export declare function dropRefusedMessages(input: RewriteInput, own: {
25
+ installId: string;
26
+ person: string;
27
+ runId: string;
28
+ }): Promise<Record<string, number>>;
21
29
  /** After staging, before rewrite 1: every blob key a staged row names has the shape its row would produce and an owner (node) that is in this bundle or is the
22
30
  * importing person's own node in the target. A key naming a node of another person is `person_mismatch`; a key of no known shape is `bundle_invalid`. Without this,
23
31
  * the importer's own node would read, and compaction would delete, a blob of someone else's conversation. (Human requests are checked by `checkStagedRequestKeys`,