@north-light/cli 0.3.714 → 0.3.716

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 (57) 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/viewer.js +222 -222
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/commands/sys/feedback.js +5 -5
  12. package/dist/core/canvas/executions.d.ts +0 -2
  13. package/dist/core/canvas/executions.js +1 -1
  14. package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
  15. package/dist/core/canvas/schema-version.d.ts +1 -1
  16. package/dist/core/canvas/schema-version.js +1 -1
  17. package/dist/core/environment-recipe.d.ts +1 -0
  18. package/dist/core/environment-recipe.js +1 -1
  19. package/dist/core/import/load/rewrite.js +14 -14
  20. package/dist/core/ledger/rates.d.ts +0 -2
  21. package/dist/core/ledger/rates.js +1 -1
  22. package/dist/core/runtime/revive.js +2 -2
  23. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  24. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  25. package/dist/core/runtime/runner/types.d.ts +0 -2
  26. package/dist/core/runtime/spawn.js +1 -1
  27. package/dist/daemon/api/handlers/environments.js +1 -1
  28. package/dist/daemon/api/handlers/feedback.d.ts +2 -0
  29. package/dist/daemon/api/handlers/feedback.js +9 -0
  30. package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
  31. package/dist/daemon/api/handlers/git-credential.js +1 -1
  32. package/dist/daemon/api/operations.js +1 -1
  33. package/dist/daemon/api/server.js +1 -1
  34. package/dist/daemon/machine-daemon.js +1 -1
  35. package/dist/daemon/reconcilers/ledger-storage.js +2 -4
  36. package/package.json +3 -3
  37. package/packages/crouter-api/dist/api/client.js +4 -0
  38. package/packages/crouter-api/dist/api/contract.js +1 -1
  39. package/packages/crouter-api/dist/api/routes.js +1 -0
  40. package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
  41. package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
  42. package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
  43. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  44. package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
  45. package/packages/crouter-api/dist/core/import/load/rewrite.js +8 -4
  46. package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
  47. package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
  48. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
  49. package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
  50. package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
  51. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
  52. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  53. package/packages/crouter-api/package.json +1 -1
  54. package/packages/crouter-identity/package.json +1 -1
  55. package/packages/crouter-plugin/package.json +3 -3
  56. package/runtime.lock.json +14 -14
  57. package/scripts/sandbox-start.mjs +1 -1
@@ -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};
@@ -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,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 = 29;
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=29;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};
@@ -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};
@@ -1,15 +1,15 @@
1
- var I=Object.defineProperty;var E=(t,a)=>I(t,"name",{value:a,configurable:!0});import{createHash as M}from"node:crypto";import{ROOT_PROFILE_ID as h}from"../../profiles/manifest.js";import{substitutePerson as H}from"../../canvas/person.js";import{withCanvasWrite as W}from"../../canvas/db.js";import{ImportLaneError as w}from"./stage.js";import{q as $}from"./catalog.js";const C=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],F=[["nodes","grant_id"],["crons","grant_id"]],g={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},y=["app","person","profile","repo"];function D(t){const a=new Map,o=E((c,s)=>{a.has(c)||a.set(c,new Set),a.get(c).add(s)},"add");for(const c of t.foreignKeys)c.parent==="objects"&&c.columns.length===1&&o(c.table,c.columns[0]);for(const[c,s]of C)o(c,s);return a}E(D,"objectIdColumns");const f=E((t,a)=>`${$(t)}.${$(a)}`,"sq"),p=E(async(t,a,...o)=>Number((await t.prepareUncached(a).run(...o)).changes),"run"),_=E(async(t,a,...o)=>await t.prepareUncached(a).all(...o),"rows");async function q(t){t.sourcePerson!==t.targetPerson&&await W(async a=>{await a.exec(`SET LOCAL search_path TO ${$(t.schema)}`),await H(a,t.sourcePerson,t.targetPerson)})}E(q,"rewritePerson");async function G(t){const a=E(o=>f(t.schema,o),"S");return await p(t.db,`UPDATE ${a("identities")} SET person = '' WHERE person IS NULL`),await p(t.db,`UPDATE ${a("identities")} SET person = ? WHERE object IN (SELECT id FROM ${a("objects")} WHERE type = 'repo')`,t.targetPerson)}E(G,"scopeRepoIdentities");async function V(t){const a=E(s=>f(t.schema,s),"S"),o=E(s=>f(t.target,s),"T");let c=0;for(const s of await _(t.db,`SELECT id, name FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL ORDER BY id`))await t.db.prepareUncached(`SELECT 1 AS found FROM ${o("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id <> ?
2
- UNION ALL SELECT 1 FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id < ? LIMIT 1`).get(s.name,s.id,s.name,s.id)!==void 0&&(await p(t.db,`UPDATE ${a("objects")} SET name = ? WHERE id = ?`,`${s.name}-${s.id}`,s.id),c+=1);return c}E(V,"renameClashingRepos");async function U(t,a,o,c,s){return o===null?void 0:(await t.prepareUncached(`SELECT id FROM ${f(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,c,s))?.id}E(U,"findFleetGrant");function x(t){return new w("id_map","grant_missing",`no grant in the target for: ${t.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...t]})}E(x,"grantMissing");async function P(t,a,o,c,s,n,l,N){const d=a.uniqueKeys.find(r=>r.table==="objects"&&r.name==="objects_named");if(d===void 0||d.predicate===null)throw new w("id_map","import_failed","the target has no objects_named unique index with a predicate");const T=E(r=>`(SELECT * FROM ${r} WHERE ${d.predicate}) o`,"live"),u="o.id <> ? AND o.name = ?";return await t.prepareUncached(`SELECT 1 FROM ${T(o)} WHERE o.owner IN (${s.map(()=>"?").join(", ")}) AND ${u} LIMIT 1`).get(...s,l,N)!==void 0?!0:await t.prepareUncached(`SELECT 1 FROM ${T(c)} WHERE o.owner = ? AND ${u} LIMIT 1`).get(n,l,N)!==void 0}E(P,"usesName");async function z(t,a){const{db:o,schema:c,target:s}=t,n=E(e=>f(c,e),"S"),l=E(e=>f(s,e),"T"),N={object:new Map,grant:new Map,kind:new Map};for(const[e,m]of a)N.object.set(e,m);const d=t.targetPerson.replace(/^user:/,"");for(const e of y){const m=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${l("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,b=await _(o,`SELECT i.object AS src, t.object AS dst FROM ${n("identities")} i
3
- JOIN ${n("objects")} so ON so.id = i.object AND so.type = ?
4
- JOIN ${l("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id${e==="repo"?" AND t.person = ? AND t.scheme = 'git'":""}
5
- JOIN ${l("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
6
- WHERE ${m}`,e,...e==="repo"?[t.targetPerson]:[],e==="person"?t.targetPerson:d);for(const{src:R,dst:O}of b)R!==O&&N.object.set(R,O)}const T=await _(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${n("objects")} o JOIN ${n("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL ORDER BY o.id`);for(const e of T){const m=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("documents")} d ON d.object = o.id
7
- WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(N.object.get(e.owner)??e.owner,e.name);if(m!==void 0){N.object.set(e.id,m.id);continue}const b=t.shippedBodies[e.id];if(b===void 0)throw new w("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("identities")} i ON i.object = o.id
1
+ var I=Object.defineProperty;var E=(o,a)=>I(o,"name",{value:a,configurable:!0});import{createHash as M}from"node:crypto";import{ROOT_PROFILE_ID as h}from"../../profiles/manifest.js";import{substitutePerson as H}from"../../canvas/person.js";import{withCanvasWrite as W}from"../../canvas/db.js";import{ImportLaneError as j}from"./stage.js";import{q as T}from"./catalog.js";const C=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],F=[["nodes","grant_id"],["crons","grant_id"]],g={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},y=["app","person","profile","repo"];function D(o){const a=new Map,n=E((d,i)=>{a.has(d)||a.set(d,new Set),a.get(d).add(i)},"add");for(const d of o.foreignKeys)d.parent==="objects"&&d.columns.length===1&&n(d.table,d.columns[0]);for(const[d,i]of C)n(d,i);return a}E(D,"objectIdColumns");const l=E((o,a)=>`${T(o)}.${T(a)}`,"sq"),p=E(async(o,a,...n)=>Number((await o.prepareUncached(a).run(...n)).changes),"run"),w=E(async(o,a,...n)=>await o.prepareUncached(a).all(...n),"rows");async function X(o){o.sourcePerson!==o.targetPerson&&await W(async a=>{await a.exec(`SET LOCAL search_path TO ${T(o.schema)}`),await H(a,o.sourcePerson,o.targetPerson)})}E(X,"rewritePerson");async function G(o){const a=E(n=>l(o.schema,n),"S");return await p(o.db,`UPDATE ${a("identities")} SET person = '' WHERE person IS NULL`),await p(o.db,`UPDATE ${a("identities")} SET person = ? WHERE object IN (SELECT id FROM ${a("objects")} WHERE type = 'repo')`,o.targetPerson)}E(G,"scopeRepoIdentities");async function V(o){const a=E(i=>l(o.schema,i),"S"),n=E(i=>l(o.target,i),"T");let d=0;for(const i of await w(o.db,`SELECT id, name FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL ORDER BY id`))await o.db.prepareUncached(`SELECT 1 AS found FROM ${n("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id <> ?
2
+ UNION ALL SELECT 1 FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id < ? LIMIT 1`).get(i.name,i.id,i.name,i.id)!==void 0&&(await p(o.db,`UPDATE ${a("objects")} SET name = ? WHERE id = ?`,`${i.name}-${i.id}`,i.id),d+=1);return d}E(V,"renameClashingRepos");async function U(o,a,n,d,i){return n===null?void 0:(await o.prepareUncached(`SELECT id FROM ${l(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(n,d,i))?.id}E(U,"findFleetGrant");function x(o){return new j("id_map","grant_missing",`no grant in the target for: ${o.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...o]})}E(x,"grantMissing");async function P(o,a,n,d,i,t,m,b){const c=a.uniqueKeys.find(s=>s.table==="objects"&&s.name==="objects_named");if(c===void 0||c.predicate===null)throw new j("id_map","import_failed","the target has no objects_named unique index with a predicate");const u=E(s=>`(SELECT * FROM ${s} WHERE ${c.predicate}) o`,"live"),N="o.id <> ? AND o.name = ?";return await o.prepareUncached(`SELECT 1 FROM ${u(n)} WHERE o.owner IN (${i.map(()=>"?").join(", ")}) AND ${N} LIMIT 1`).get(...i,m,b)!==void 0?!0:await o.prepareUncached(`SELECT 1 FROM ${u(d)} WHERE o.owner = ? AND ${N} LIMIT 1`).get(t,m,b)!==void 0}E(P,"usesName");async function z(o,a){const{db:n,schema:d,target:i}=o,t=E(e=>l(d,e),"S"),m=E(e=>l(i,e),"T"),b={object:new Map,grant:new Map,kind:new Map};for(const[e,r]of a)b.object.set(e,r);const c=o.targetPerson.replace(/^user:/,"");for(const e of y){const r=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${m("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,f=await w(n,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
3
+ JOIN ${t("objects")} so ON so.id = i.object AND so.type = ?
4
+ JOIN ${m("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id${e==="repo"?" AND t.person = ? AND t.scheme = 'git'":""}
5
+ JOIN ${m("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
6
+ WHERE ${r}`,e,...e==="repo"?[o.targetPerson]:[],e==="person"?o.targetPerson:c);for(const{src:R,dst:O}of f)R!==O&&b.object.set(R,O)}const u=await w(n,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL ORDER BY o.id`);for(const e of u){const r=await n.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("documents")} d ON d.object = o.id
7
+ WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(b.object.get(e.owner)??e.owner,e.name);if(r!==void 0){b.object.set(e.id,r.id);continue}const f=o.shippedBodies[e.id];if(f===void 0)throw new j("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await n.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("identities")} i ON i.object = o.id
8
8
  WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ?
9
- UNION ALL SELECT o.id FROM ${n("objects")} o JOIN ${n("identities")} i ON i.object = o.id
10
- WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(t.targetPerson,t.targetPerson);if(R===void 0)throw new w("id_map","bundle_invalid",`no person object for ${t.targetPerson}; cannot import shipped document ${e.name}`);const O=[R.id,...[...N.object].filter(([,L])=>L===R.id).map(([L])=>L)],S=E(L=>P(o,t.catalog,n("objects"),l("objects"),O,R.id,e.id,L),"named");let j=e.name;if(await S(j)){const L=await o.prepareUncached(`SELECT name FROM ${n("objects")} WHERE id = ?`).get(e.owner);j=`${e.name}-${L?.name??e.id}`,await S(j)&&(j=`${e.name}-${e.id}`)}await p(o,`UPDATE ${n("objects")} SET owner = ?, name = ? WHERE id = ?`,R.id,j,e.id),await p(o,`UPDATE ${n("rules")} SET owner = ? WHERE object = ?`,R.id,e.id),await p(o,`DELETE FROM ${n("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${n("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
11
- VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,d,e.created_at),await p(o,`UPDATE ${n("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${n("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${n("revision_parents")} p WHERE p.parent = r.rev_id)`,b,e.id)}const u=await _(o,`SELECT id, sub, grantee FROM ${n("grants")} ORDER BY id`),i=[];for(const e of u){const m=await U(o,s,t.fleetRuntime,e.sub,e.grantee);m===void 0?i.push(e.grantee):N.grant.set(e.id,m)}if(i.length>0)throw x(i);await o.exec(`CREATE TABLE ${n("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,m]of[["object",N.object],["grant",N.grant]])for(const[b,R]of m)await p(o,`INSERT INTO ${n("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,b,R);const r=`(SELECT source FROM ${n("_idmap")} WHERE kind = 'object')`;for(const[e,m]of Object.entries(g))await p(o,`DELETE FROM ${n(e)} WHERE ${m} IN ${r}`);await p(o,`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${r})`),await p(o,`DELETE FROM ${n("revisions")} WHERE document IN ${r}`);for(const[e,m]of D(t.catalog))if(t.catalog.tables.has(e))for(const b of m)await A(o,n(e),b,"object",n("_idmap"));for(const[e,m]of F)await A(o,n(e),m,"grant",n("_idmap"));await p(o,`UPDATE ${n("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
12
- FROM ${n("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${n("objects")} WHERE id IN ${r}`),await p(o,`UPDATE ${n("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${n("identities")} WHERE scheme = 'user' AND external_id = ?)`,d,d,t.targetPerson);for(const{name:e}of await _(o,`SELECT k.name FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`))N.kind.set(e,e);return await p(o,`DELETE FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`),N}E(z,"rewriteIds");async function Q(t){const{db:a,schema:o,target:c,targetPerson:s}=t,n=new Map,l=E(async(d,...T)=>await a.prepareUncached(d).get(...T),"row"),N=E(d=>p(a,`DELETE FROM ${f(o,"profiles")} WHERE id = ?`,d),"dropStaged");for(const{id:d}of await _(a,`SELECT id FROM ${f(o,"profiles")} ORDER BY id`)){let T=d===h?await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE person = ? AND name = 'root'`,s):await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ? AND person = ?`,d,s);if(T===void 0){if(await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,d)===void 0&&d!==h)continue;const r=`${d.replace(/-[0-9a-f]{8}$/,"")}-${M("sha256").update(`${s}\0${d}`).digest("hex").slice(0,8)}`,e=await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,r);if(e!==void 0&&e.person!==s)throw new w("id_map","unique_conflict",`profiles ${r} is held by another person in the target`,{table:"profiles",values:[r]});T=e??{id:r,person:s},e===void 0?await p(a,`UPDATE ${f(o,"profiles")} SET id = ? WHERE id = ?`,r,d):await N(d)}else await N(d);const u=T.id;await p(a,`UPDATE ${f(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${f(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
13
- AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${f(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,u,d,u,d),await p(a,`UPDATE ${f(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${f(o,"objects")} WHERE type = 'profile')`,u,d),u!==d&&n.set(d,u)}return n}E(Q,"mapProfileIds");async function A(t,a,o,c,s){await p(t,`UPDATE ${a} t SET ${$(o)} = m.target FROM ${s} m WHERE m.kind = ? AND t.${$(o)} = m.source`,c)}E(A,"remap");async function Z(t){const{db:a,schema:o,target:c,catalog:s}=t,n=E(i=>f(o,i),"S"),l={},N=E((i,r)=>{r>0&&(l[i]=(l[i]??0)+r)},"count");await a.exec(`CREATE TABLE ${n("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const d=`(SELECT id FROM ${n("objects")} WHERE home_machine IS NOT NULL)`;await p(a,`INSERT INTO ${n("_dropped")} SELECT 'objects', id FROM ${n("objects")} WHERE home_machine IS NOT NULL`);for(const[i,r]of Object.entries(g))N(i,await p(a,`DELETE FROM ${n(i)} WHERE ${r} IN ${d}`));N("objects",await p(a,`DELETE FROM ${n("objects")} WHERE home_machine IS NOT NULL`));const T=new Map;for(const[i,r]of D(s))s.tables.has(i)&&i!=="messages"&&T.set(i,[...r]);const u=`(SELECT key FROM ${n("_dropped")} WHERE tbl = 'objects')`;for(;;){let i=0;const r=E(async(e,m,...b)=>{const R=s.tables.get(e).primaryKey.length===1?$(s.tables.get(e).primaryKey[0]):null;R!==null&&await p(a,`INSERT INTO ${n("_dropped")} SELECT ?, ${R}::text FROM ${n(e)} WHERE ${m} ON CONFLICT DO NOTHING`,e,...b);const O=await p(a,`DELETE FROM ${n(e)} WHERE ${m}`,...b);N(e,O),i+=O},"drop");for(const e of s.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!t.catalog.tables.has(e.table)||await r(e.table,`${$(e.columns[0])} IN (SELECT key FROM ${n("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,m]of T)await r(e,m.map(b=>`${$(b)} IN ${u}`).join(" OR "));if(await r("audit_rows",`node_id IN ${u}`),i===0)break}for(const i of s.foreignKeys){if(i.columns.length!==1||!s.tables.has(i.table))continue;const r=$(i.columns[0]),e=$(i.parentColumns[0]),m=await _(a,`SELECT DISTINCT c.${r}::text AS value FROM ${n(i.table)} c
14
- WHERE c.${r} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${n(i.parent)} p WHERE p.${e} = c.${r})
15
- AND NOT EXISTS (SELECT 1 FROM ${f(c,i.parent)} p WHERE p.${e} = c.${r}) LIMIT 10`);if(m.length>0)throw new w("drop","bundle_invalid",`${i.table}.${i.columns[0]} names rows that exist nowhere: ${m.map(b=>b.value).join(", ")}`,{table:i.table,column:i.columns[0],values:m.map(b=>b.value)})}return l}E(Z,"dropStubRows");export{C as OBJECT_ID_COLUMNS,Z as dropStubRows,U as findFleetGrant,x as grantMissing,Q as mapProfileIds,D as objectIdColumns,V as renameClashingRepos,z as rewriteIds,q as rewritePerson,G as scopeRepoIdentities};
9
+ UNION ALL SELECT o.id FROM ${t("objects")} o JOIN ${t("identities")} i ON i.object = o.id
10
+ WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(o.targetPerson,o.targetPerson);if(R===void 0)throw new j("id_map","bundle_invalid",`no person object for ${o.targetPerson}; cannot import shipped document ${e.name}`);const O=[R.id,...[...b.object].filter(([,_])=>_===R.id).map(([_])=>_)],L=E(_=>P(n,o.catalog,t("objects"),m("objects"),O,R.id,e.id,_),"named");let S=e.name;if(await L(S)){const _=await n.prepareUncached(`SELECT name FROM ${t("objects")} WHERE id = ?`).get(e.owner);S=`${e.name}-${_?.name??e.id}`,await L(S)&&(S=`${e.name}-${e.id}`)}await p(n,`UPDATE ${t("objects")} SET owner = ?, name = ? WHERE id = ?`,R.id,S,e.id),await p(n,`UPDATE ${t("rules")} SET owner = ? WHERE object = ?`,R.id,e.id),await p(n,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(n,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
11
+ VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,c,e.created_at),await p(n,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(n,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,f,e.id)}const N=await w(n,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),$=[];for(const e of N){const r=await U(n,i,o.fleetRuntime,e.sub,e.grantee);r===void 0?$.push(e.grantee):b.grant.set(e.id,r)}if($.length>0)throw x($);await n.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,r]of[["object",b.object],["grant",b.grant]])for(const[f,R]of r)await p(n,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,f,R);const s=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,r]of Object.entries(g))await p(n,`DELETE FROM ${t(e)} WHERE ${r} IN ${s}`);await p(n,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${s})`),await p(n,`DELETE FROM ${t("revisions")} WHERE document IN ${s}`);for(const[e,r]of D(o.catalog))if(o.catalog.tables.has(e))for(const f of r)await A(n,t(e),f,"object",t("_idmap"));for(const[e,r]of F)await A(n,t(e),r,"grant",t("_idmap"));await p(n,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
12
+ FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(n,`DELETE FROM ${t("objects")} WHERE id IN ${s}`),await p(n,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,c,c,o.targetPerson);for(const{name:e}of await w(n,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))b.kind.set(e,e);return await p(n,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`),b}E(z,"rewriteIds");async function Q(o){const{db:a,schema:n,target:d,targetPerson:i}=o,t=new Map,m=E(async(c,...u)=>await a.prepareUncached(c).get(...u),"row"),b=E(c=>p(a,`DELETE FROM ${l(n,"profiles")} WHERE id = ?`,c),"dropStaged");for(const{id:c}of await w(a,`SELECT id FROM ${l(n,"profiles")} ORDER BY id`)){let u=c===h?await m(`SELECT id, person FROM ${l(d,"profiles")} WHERE person = ? AND name = 'root'`,i):await m(`SELECT id, person FROM ${l(d,"profiles")} WHERE id = ? AND person = ?`,c,i);if(u===void 0){if(await m(`SELECT id, person FROM ${l(d,"profiles")} WHERE id = ?`,c)===void 0&&c!==h)continue;const s=`${c.replace(/-[0-9a-f]{8}$/,"")}-${M("sha256").update(`${i}\0${c}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${l(d,"profiles")} WHERE id = ?`,s);if(e!==void 0&&e.person!==i)throw new j("id_map","unique_conflict",`profiles ${s} is held by another person in the target`,{table:"profiles",values:[s]});u=e??{id:s,person:i},e===void 0?await p(a,`UPDATE ${l(n,"profiles")} SET id = ? WHERE id = ?`,s,c):await b(c)}else await b(c);const N=u.id;await p(a,`UPDATE ${l(n,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${l(n,"identities")} WHERE scheme = 'profile' AND external_id = ?)
13
+ AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${l(d,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,N,c,N,c),await p(a,`UPDATE ${l(n,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${l(n,"objects")} WHERE type = 'profile')`,N,c),N!==c&&t.set(c,N)}return t}E(Q,"mapProfileIds");async function A(o,a,n,d,i){await p(o,`UPDATE ${a} t SET ${T(n)} = m.target FROM ${i} m WHERE m.kind = ? AND t.${T(n)} = m.source`,d)}E(A,"remap");async function Z(o){const{db:a,schema:n,target:d,catalog:i}=o,t=E(s=>l(n,s),"S"),m={},b=E((s,e)=>{e>0&&(m[s]=(m[s]??0)+e)},"count");await a.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const c=i.uniqueKeys.find(s=>s.table==="objects"&&s.name==="objects_named");if(c===void 0||c.predicate===null)throw new j("drop","import_failed","the target has no objects_named unique index with a predicate");const u=`s.id IN (SELECT s2.id FROM (SELECT * FROM ${t("objects")} WHERE ${c.predicate}) s2 JOIN (SELECT * FROM ${l(d,"objects")} WHERE ${c.predicate}) t ON t.owner = s2.owner AND t.name = s2.name AND t.id <> s2.id)`;await p(a,`INSERT INTO ${t("_dropped")} SELECT 'objects', s.id FROM ${t("objects")} s WHERE s.home_machine IS NOT NULL OR ${u}`);for(const[s,e]of Object.entries(g))b(s,await p(a,`DELETE FROM ${t(s)} WHERE ${e} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`));b("objects",await p(a,`DELETE FROM ${t("objects")} WHERE id IN (SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`));const N=new Map;for(const[s,e]of D(i))i.tables.has(s)&&s!=="messages"&&N.set(s,[...e]);const $=`(SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`;for(;;){let s=0;const e=E(async(r,f,...R)=>{const O=i.tables.get(r).primaryKey.length===1?T(i.tables.get(r).primaryKey[0]):null;O!==null&&await p(a,`INSERT INTO ${t("_dropped")} SELECT ?, ${O}::text FROM ${t(r)} WHERE ${f} ON CONFLICT DO NOTHING`,r,...R);const L=await p(a,`DELETE FROM ${t(r)} WHERE ${f}`,...R);b(r,L),s+=L},"drop");for(const r of i.foreignKeys)r.columns.length!==1||r.parentColumns.length!==1||!o.catalog.tables.has(r.table)||await e(r.table,`${T(r.columns[0])} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,r.parent);for(const[r,f]of N)await e(r,f.map(R=>`${T(R)} IN ${$}`).join(" OR "));if(await e("audit_rows",`node_id IN ${$}`),s===0)break}for(const s of i.foreignKeys){if(s.columns.length!==1||!i.tables.has(s.table))continue;const e=T(s.columns[0]),r=T(s.parentColumns[0]),f=await w(a,`SELECT DISTINCT c.${e}::text AS value FROM ${t(s.table)} c
14
+ WHERE c.${e} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(s.parent)} p WHERE p.${r} = c.${e})
15
+ AND NOT EXISTS (SELECT 1 FROM ${l(d,s.parent)} p WHERE p.${r} = c.${e}) LIMIT 10`);if(f.length>0)throw new j("drop","bundle_invalid",`${s.table}.${s.columns[0]} names rows that exist nowhere: ${f.map(R=>R.value).join(", ")}`,{table:s.table,column:s.columns[0],values:f.map(R=>R.value)})}return m}E(Z,"dropStubRows");export{C as OBJECT_ID_COLUMNS,Z as dropStubRows,U as findFleetGrant,x as grantMissing,Q as mapProfileIds,D as objectIdColumns,V as renameClashingRepos,z as rewriteIds,X as rewritePerson,G as scopeRepoIdentities};
@@ -2,7 +2,6 @@ export declare const LEDGER_ENV: {
2
2
  readonly sandboxUsdPerGbHour: "CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR";
3
3
  readonly sandboxStandbyS: "CRTR_LEDGER_SANDBOX_STANDBY_S";
4
4
  readonly storageUsdPerGbMonth: "CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH";
5
- readonly sandboxDiskUsdPerGbMonth: "CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH";
6
5
  readonly infraFreeUsdPerMonth: "CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH";
7
6
  readonly takePct: "CRTR_LEDGER_TAKE_PCT";
8
7
  readonly r2Move: "CRTR_LEDGER_R2_MOVE";
@@ -12,7 +11,6 @@ export declare const DEFAULT_INFRA_FREE_USD = 50;
12
11
  export declare const sandboxUsdPerGbHour: () => number | null;
13
12
  export declare const sandboxStandbyS: () => number;
14
13
  export declare const storageUsdPerGbMonth: () => number | null;
15
- export declare const sandboxDiskUsdPerGbMonth: () => number | null;
16
14
  export declare const infraFreeUsdPerMonth: () => number;
17
15
  /** Northlight's take on each priced model or tool charge, in percent; 0 (the default) writes no take rows. */
18
16
  export declare const takePercent: () => number;
@@ -1 +1 @@
1
- var E=Object.defineProperty;var t=(r,e)=>E(r,"name",{value:e,configurable:!0});import{emitEvent as a}from"../events/emit.js";const o={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",sandboxDiskUsdPerGbMonth:"CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"},R=30,i=50;function s(r,e=1/0){const n=process.env[r];if(n===void 0||n==="")return null;const _=/^\d+(\.\d+)?$/.test(n)?Number(n):NaN;if(!Number.isFinite(_)||_>e)throw new Error(`${r} must be a number from 0${e===1/0?" up":` to ${e}`}, got ${JSON.stringify(n)}`);return _}t(s,"number");function u(r){const e=process.env[r];if(e===void 0||e==="")return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;throw new Error(`${r} must be true, false, 1 or 0, got ${JSON.stringify(e)}`)}t(u,"flag");const b=t(()=>s(o.sandboxUsdPerGbHour),"sandboxUsdPerGbHour"),f=t(()=>s(o.sandboxStandbyS)??R,"sandboxStandbyS"),c=t(()=>s(o.storageUsdPerGbMonth),"storageUsdPerGbMonth"),D=t(()=>s(o.sandboxDiskUsdPerGbMonth),"sandboxDiskUsdPerGbMonth"),S=t(()=>s(o.infraFreeUsdPerMonth)??i,"infraFreeUsdPerMonth"),G=t(()=>s(o.takePct,100)??0,"takePercent"),U=t(()=>u(o.r2Move),"r2MoveEnabled");function N(){b(),f(),c(),D(),S(),G(),U()}t(N,"assertLedgerEnv");const d=new Set;function T(r,...e){const n=`${r}:${e.join(",")}`;d.has(n)||(d.add(n),a({level:"warn",event:"ledger.rate_unset",fields:{lane:r,unset:e}}))}t(T,"warnRateUnset");export{i as DEFAULT_INFRA_FREE_USD,R as DEFAULT_STANDBY_S,o as LEDGER_ENV,N as assertLedgerEnv,S as infraFreeUsdPerMonth,U as r2MoveEnabled,D as sandboxDiskUsdPerGbMonth,f as sandboxStandbyS,b as sandboxUsdPerGbHour,c as storageUsdPerGbMonth,G as takePercent,T as warnRateUnset};
1
+ var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{emitEvent as d}from"../events/emit.js";const o={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"},i=30,R=50;function s(r,e=1/0){const n=process.env[r];if(n===void 0||n==="")return null;const _=/^\d+(\.\d+)?$/.test(n)?Number(n):NaN;if(!Number.isFinite(_)||_>e)throw new Error(`${r} must be a number from 0${e===1/0?" up":` to ${e}`}, got ${JSON.stringify(n)}`);return _}t(s,"number");function u(r){const e=process.env[r];if(e===void 0||e==="")return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;throw new Error(`${r} must be true, false, 1 or 0, got ${JSON.stringify(e)}`)}t(u,"flag");const f=t(()=>s(o.sandboxUsdPerGbHour),"sandboxUsdPerGbHour"),c=t(()=>s(o.sandboxStandbyS)??i,"sandboxStandbyS"),b=t(()=>s(o.storageUsdPerGbMonth),"storageUsdPerGbMonth"),S=t(()=>s(o.infraFreeUsdPerMonth)??R,"infraFreeUsdPerMonth"),D=t(()=>s(o.takePct,100)??0,"takePercent"),U=t(()=>u(o.r2Move),"r2MoveEnabled");function p(){f(),c(),b(),S(),D(),U()}t(p,"assertLedgerEnv");const E=new Set;function x(r,...e){const n=`${r}:${e.join(",")}`;E.has(n)||(E.add(n),d({level:"warn",event:"ledger.rate_unset",fields:{lane:r,unset:e}}))}t(x,"warnRateUnset");export{R as DEFAULT_INFRA_FREE_USD,i as DEFAULT_STANDBY_S,o as LEDGER_ENV,p as assertLedgerEnv,S as infraFreeUsdPerMonth,U as r2MoveEnabled,c as sandboxStandbyS,f as sandboxUsdPerGbHour,b as storageUsdPerGbMonth,D as takePercent,x as warnRateUnset};
@@ -1,3 +1,3 @@
1
- var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as he,recordExecutionPid as pe,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as mr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(hr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(a)?{}:await hr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.isClaimed(e))return await a.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await a.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await a.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof he)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,h=w?{}:await vr(e,r,x,!u),g=h.resumeSessionPath!==void 0,B=g&&h.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(h.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...h,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...h,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...h,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
1
+ var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as m,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as me,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await m().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await m().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function mr(e){const r=_(e);return r===null?!0:(await m().read(r)).entries.some(i=>i.type==="message")}s(mr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await m().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,x,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await mr(p.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await N(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await m().header(await m().fork($,e))).path;c=y(r,{resumeSessionPath:le,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...p,prompt:S}),h=C(),await V(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await E(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(c,r)),await ee(e)}else{const a=await Re(r,f);c=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[$e]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,hr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await me(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
@@ -26,6 +26,9 @@ export declare const REPOS_DIR = "repos";
26
26
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
27
27
  export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
28
28
  export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
29
+ /** `gh` for a sandbox: /usr/local/bin comes before /usr/bin, so this wrapper runs first. It asks git's credential helper (set at sandbox start, so it reaches the control plane's
30
+ * git-credential route) for a fresh installation token, exports it as GH_TOKEN for this one call and runs the real gh. No token is stored on disk. */
31
+ export declare const GH_WRAPPER_PATH = "/usr/local/bin/gh";
29
32
  /** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
30
33
  * Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
31
34
  * the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
@@ -1,8 +1,8 @@
1
- var K=Object.defineProperty;var c=(t,r)=>K(t,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{constants as A,lstatSync as q,mkdirSync as z,readFileSync as H,readdirSync as J,readlinkSync as W,rmSync as X,writeFileSync as b}from"node:fs";import{join as E,relative as V}from"node:path";import{crc32 as Z,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as tt}from"./client.js";const et="public.ecr.aws/docker/library/node:24-alpine",rt="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",D="/var/lib/crtr/recipe-pi-agent",nt="blaxel.toml",st=`[build]
1
+ var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{constants as P,lstatSync as q,mkdirSync as z,readFileSync as W,readdirSync as J,readlinkSync as X,rmSync as V,writeFileSync as b}from"node:fs";import{join as E,relative as Z}from"node:path";import{crc32 as Q,deflateRawSync as tt}from"node:zlib";import{BlaxelApiError as et}from"./client.js";const rt="public.ecr.aws/docker/library/node:24-alpine",nt="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",D="/var/lib/crtr/recipe-pi-agent",ot="blaxel.toml",st=`[build]
2
2
  slim = false
3
- `,ot="1.1.0",U="recipe-setup.sh",L="repos",B="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",C=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),it=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),I=c((t,r)=>`RUN { ${r}; } >> ${B} 2>&1 || echo ${C(t)} "exited $?" >> ${P}`,"guarded");function at(t,r,i=!1){const o=it(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${et}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${rt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${D} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${B}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),o.length>0&&e.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${ot}`)),a&&e.push(`COPY ${U} /tmp/${U}`),e.push("WORKDIR /work");for(const s of o)e.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${C(s)}`));a&&e.push(I("setup script",`bash /tmp/${U}`)),e.push(I("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(at,"recipeDockerfile");const ct=c((t,r,i)=>new Promise((o,a)=>{const n=j("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function Et(t){const r=t.git??ct,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);z(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,nt),st),b(E(t.dir,"Dockerfile"),at(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,U),t.recipe.setup_script.endsWith(`
3
+ `,it="1.1.0",_="recipe-setup.sh",L="repos",B="/work/.crtr/setup.log",G="/work/.crtr/setup-failed",C="/usr/local/bin/gh",at=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],R=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ct=c(t=>(t??"").split(`
4
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${B} 2>&1 || echo ${R(t)} "exited $?" >> ${G}`,"guarded");function lt(t,r,i=!1){const s=ct(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${rt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${at.map(R).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${nt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${D} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${G} ${B}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${it}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work");for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${R(o)}`));a&&e.push($("setup script",`bash /tmp/${_}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
+ `)}c(lt,"recipeDockerfile");const pt=c((t,r,i)=>new Promise((s,a)=>{const n=j("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function It(t){const r=t.git??pt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);z(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,ot),st),b(E(t.dir,"Dockerfile"),lt(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,_),t.recipe.setup_script.endsWith(`
7
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(Et,"prepareBuildDir");function G(t,r,i){for(const o of J(r).sort()){const a=E(r,o),n=q(a),e=V(t,a).split("\\").join("/");n.isDirectory()?G(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(W(a)),mode:A.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:H(a),mode:A.S_IFREG|n.mode&511})}}c(G,"walk");function lt(t){const r=[];G(t,t,r);const i=[],o=[];let a=0;for(const s of r){const d=Buffer.from(s.name),g=Q(s.data),$=Z(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE($,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE($,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(lt,"zipDirectory");async function O(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let d=null;if(s!=="")try{d=JSON.parse(s)}catch{d={raw:s}}if(!e.ok&&!a.includes(e.status))throw new tt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(O,"api");async function M(t,r){const{status:i,json:o}=await O(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(M,"getImage");async function It(t,r){await O(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(It,"deleteImage");const pt=60*6e4;async function $t(t,r,i,o={}){const a=o.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=o.now??Date.now,e=n(),s=await M(t,r),d=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),$=Math.max(-1/0,...g(s)),l=(await O(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(lt(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=o.timeoutMs??pt,F=e+T;let R=null;for(;;){const h=await M(t,r),u=h?.metadata?.status,N=g(h).filter(m=>m>$).sort((m,_)=>m-_);if(u==="BUILT"&&N.length>=2){R??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),_=N[0],k=c(w=>Date.parse(w??"")>=_,"touchedSince"),S=m.filter(w=>!d.has(w.name)||k(w.createdAt)||k(w.updatedAt)),y=n()-R>=(o.tagGraceMs??6e4),v=(S.length>0?S:y?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(v!==void 0)return{ref:`sandbox/${r}:${v}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${u??"none"})`);await a(o.pollMs??3e3)}}c($t,"buildImage");const bt=c(t=>`env-${t}`,"environmentImageName");function Ut(t){X(t,{recursive:!0,force:!0})}c(Ut,"removeBuildDir");export{st as BLAXEL_TOML,nt as BLAXEL_TOML_FILE,pt as BUILD_TIMEOUT_MS,et as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,rt as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,B as SETUP_LOG_FILE,U as SETUP_SCRIPT_FILE,$t as buildImage,It as deleteImage,bt as environmentImageName,M as getImage,Et as prepareBuildDir,at as recipeDockerfile,Ut as removeBuildDir,lt as zipDirectory};
8
+ `)}c(It,"prepareBuildDir");function M(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=q(a),e=Z(t,a).split("\\").join("/");n.isDirectory()?M(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:P.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:W(a),mode:P.S_IFREG|n.mode&511})}}c(M,"walk");function dt(t){const r=[];M(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=tt(o.data),I=Q(o.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(o.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(dt,"zipDirectory");async function T(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new et(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(T,"api");async function F(t,r){const{status:i,json:s}=await T(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(F,"getImage");async function bt(t,r){await T(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(bt,"deleteImage");const ut=60*6e4;async function _t(t,r,i,s={}){const a=s.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=s.now??Date.now,e=n(),o=await F(t,r),d=new Set((o?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await T(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(dt(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const N=s.timeoutMs??ut,H=e+N;let O=null;for(;;){const h=await F(t,r),u=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,U)=>m-U);if(u==="BUILT"&&k.length>=2){O??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),U=k[0],S=c(w=>Date.parse(w??"")>=U,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),y=(A.length>0?A:v?m:[]).sort((w,K)=>(K.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(y!==void 0)return{ref:`sandbox/${r}:${y}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>H)throw new Error(`building image ${r} did not finish within ${N} ms (last status ${u??"none"})`);await a(s.pollMs??3e3)}}c(_t,"buildImage");const xt=c(t=>`env-${t}`,"environmentImageName");function Ut(t){V(t,{recursive:!0,force:!0})}c(Ut,"removeBuildDir");export{st as BLAXEL_TOML,ot as BLAXEL_TOML_FILE,ut as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,rt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,nt as SANDBOX_API_IMAGE,G as SETUP_FAILED_FILE,B as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,_t as buildImage,bt as deleteImage,xt as environmentImageName,F as getImage,It as prepareBuildDir,lt as recipeDockerfile,Ut as removeBuildDir,dt as zipDirectory};
@@ -5,8 +5,6 @@ export interface RunnerExecution {
5
5
  nodeId: string;
6
6
  /** `executions.attempt`. */
7
7
  attempt: number;
8
- /** `executions.sandbox_name`, null for the process runner. */
9
- sandboxName: string | null;
10
8
  }
11
9
  /** What `start` needs beyond the execution: the execution row's `launch_json` is the launch recipe. */
12
10
  export interface RunnerStartInput extends RunnerExecution {