@north-light/cli 0.3.713 → 0.3.715

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +2 -2
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/environments.d.ts +4 -0
  6. package/dist/api/dto/execution-start.d.ts +9 -0
  7. package/dist/api/routes.d.ts +1 -0
  8. package/dist/api/routes.js +1 -1
  9. package/dist/clients/attach/input/controller.d.ts +2 -0
  10. package/dist/clients/attach/input/controller.js +1 -1
  11. package/dist/clients/attach/input/local-files.d.ts +3 -1
  12. package/dist/clients/attach/input/local-files.js +8 -3
  13. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  14. package/dist/clients/attach/render/chat-view.js +2 -2
  15. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  16. package/dist/clients/attach/session/input-wiring.js +1 -1
  17. package/dist/clients/attach/viewer.js +526 -521
  18. package/dist/commands/node/inspect.js +5 -5
  19. package/dist/commands/profile/environment.js +2 -2
  20. package/dist/commands/sys/feedback.js +5 -5
  21. package/dist/core/broker-client/client.js +1 -1
  22. package/dist/core/canvas/canvas.js +1 -1
  23. package/dist/core/canvas/deliveries.js +10 -10
  24. package/dist/core/canvas/executions.d.ts +0 -2
  25. package/dist/core/canvas/executions.js +1 -1
  26. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  27. package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
  28. package/dist/core/canvas/schema-version.d.ts +1 -1
  29. package/dist/core/canvas/schema-version.js +1 -1
  30. package/dist/core/canvas/types.d.ts +1 -0
  31. package/dist/core/checkout-identities.js +1 -1
  32. package/dist/core/environment-recipe.d.ts +1 -0
  33. package/dist/core/environment-recipe.js +1 -1
  34. package/dist/core/import/load/bind.d.ts +8 -0
  35. package/dist/core/import/load/bind.js +15 -15
  36. package/dist/core/import/load/prepare.d.ts +8 -1
  37. package/dist/core/import/load/prepare.js +9 -7
  38. package/dist/core/import/load/run.js +2 -2
  39. package/dist/core/ledger/rates.d.ts +0 -2
  40. package/dist/core/ledger/rates.js +1 -1
  41. package/dist/core/llm/run.d.ts +1 -1
  42. package/dist/core/pool-credential-store.d.ts +5 -5
  43. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  44. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  45. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  46. package/dist/core/runtime/broker-wedge.js +2 -2
  47. package/dist/core/runtime/revive.js +2 -2
  48. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  49. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  50. package/dist/core/runtime/runner/types.d.ts +0 -2
  51. package/dist/core/runtime/spawn.js +1 -1
  52. package/dist/core/subscription-state.d.ts +3 -3
  53. package/dist/core/subscription-state.js +1 -1
  54. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  55. package/dist/daemon/api/handlers/environments.js +1 -1
  56. package/dist/daemon/api/handlers/feedback.d.ts +2 -0
  57. package/dist/daemon/api/handlers/feedback.js +9 -0
  58. package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
  59. package/dist/daemon/api/handlers/git-credential.js +1 -1
  60. package/dist/daemon/api/operations.js +1 -1
  61. package/dist/daemon/api/server.js +1 -1
  62. package/dist/daemon/fleet.d.ts +1 -12
  63. package/dist/daemon/fleet.js +2 -2
  64. package/dist/daemon/machine-daemon.js +1 -1
  65. package/dist/daemon/machine-link/holder.js +1 -1
  66. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  67. package/dist/daemon/reconcilers/ledger-storage.js +2 -4
  68. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  69. package/package.json +3 -3
  70. package/packages/crouter-api/dist/api/client.js +4 -0
  71. package/packages/crouter-api/dist/api/contract.js +1 -1
  72. package/packages/crouter-api/dist/api/routes.js +1 -0
  73. package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
  74. package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
  75. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  76. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  77. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  78. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  79. package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
  80. package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
  81. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  82. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  83. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  84. package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
  85. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  86. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  87. package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
  88. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  89. package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
  90. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  91. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  92. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  93. package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
  94. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
  95. package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
  96. package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
  97. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  98. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
  99. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
  100. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  101. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  102. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/install-runtime.mjs +3 -2
  108. package/scripts/sandbox-start.mjs +1 -1
  109. package/scripts/self-update.mjs +5 -1
@@ -1,17 +1,17 @@
1
- var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as P}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(a=>a.replace(/^user:/,""),"bare"),g=c((a,t)=>`${f(a)}.${f(t)}`,"sq"),N=c(async(a,t,...r)=>await a.prepareUncached(t).all(...r),"all");function I(a,t){return new D("bind","person_mismatch",a,t)}c(I,"mismatch");function te(a,t,r,l){if(a===t||a===r)return r;throw I(`${l} names ${a}, which is neither the bundle's person nor the importing person`,{where:l,value:a})}c(te,"boundSub");async function oe(a,t,r,l){if(!K.test(r))throw I(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===l)return;const u=c(i=>g(t,i),"T"),o=await a.prepareUncached(`SELECT 'identities' AS tbl FROM ${u("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
- UNION ALL SELECT 'grants' FROM ${u("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${u("profiles")} WHERE person = ?
3
- UNION ALL SELECT 'nodes' FROM ${u("nodes")} WHERE sub = ? LIMIT 1`).get(r,r,r,r);if(o!==void 0)throw I(`the bundle's person ${r} is already a person in the target (${o.tbl}), not the importing person ${l}`,{where:`${o.tbl}`,value:r})}c(oe,"checkSourcePerson");const Y=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],B=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:u}=a,o=c(p=>g(r,p),"S"),i=c((p,d)=>{throw I(`${p} names ${d.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${u}`,{where:p,values:d})},"refuse");for(const[p,d]of Y){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,S.map(O=>O.v))}for(const[p,d]of B){const S=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(p)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,l,u);S.length>0&&i(`${p}.${d}`,S.map(O=>O.v))}const h=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,l,u);h.length>0&&i("identities.external_id",h.map(p=>p.v));const _=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
4
- WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,l,u);_.length>0&&i("daemon_actions principal.sub",_.map(p=>p.v));const m=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(l),C(u));m.length>0&&i("relations acts_for subject",m.map(p=>p.v));const $=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return $>0?{relations:$}:{}}c(ne,"checkStagedPersons");async function z(a,t){return(await N(a,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
5
- WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(l=>J(l.inserted_keys).map(u=>u[0]))}c(z,"earlierImportedObjects");async function se(a,t){const{db:r,schema:l,target:u,catalog:o,targetPerson:i}=a,h=c(n=>g(l,n),"S"),_=c(n=>g(u,n),"T"),m=C(i);await r.exec(`CREATE TABLE ${h("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const $=[];for(const[n,b]of P(o))if(!(!o.tables.has(n)||n==="relations"))for(const E of b)!(n==="nodes"&&E==="profile_id")&&!(n==="crons"&&E==="profile")&&$.push([n,E,""]);$.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,b,E]of $)await r.prepareUncached(`INSERT INTO ${h("_refs")} SELECT ?, ?, ${f(b)}::text FROM ${h(n)} ${E===""?"WHERE":`${E} AND`} ${f(b)} IS NOT NULL
6
- AND ${f(b)}::text NOT IN (SELECT id FROM ${h("objects")}) AND ${f(b)}::text IN (SELECT id FROM ${_("objects")})`).run(n,b);const p=await z(r,t),d=await N(r,`WITH RECURSIVE chain(start, id) AS (
7
- SELECT DISTINCT value, value FROM ${h("_refs")}
8
- UNION SELECT c.start, o.owner FROM chain c JOIN ${_("objects")} o ON o.id = c.id JOIN ${_("objects")} up ON up.id = o.owner AND up.type <> 'app'),
1
+ var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as O}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as Y}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(n=>n.replace(/^user:/,""),"bare"),T=c((n,t)=>`${f(n)}.${f(t)}`,"sq"),$=c(async(n,t,...a)=>await n.prepareUncached(t).all(...a),"all");function g(n,t){return new D("bind","person_mismatch",n,t)}c(g,"mismatch");function se(n,t,a,p){if(n===t||n===a)return a;throw g(`${p} names ${n}, which is neither the bundle's person nor the importing person`,{where:p,value:n})}c(se,"boundSub");async function ne(n,t,a,p){if(!K.test(a))throw g(`the bundle's person ${JSON.stringify(a)} is not a user:<id> principal`,{where:"source.json person",value:a});if(a===p)return;const d=c(r=>T(t,r),"T"),o=await n.prepareUncached(`SELECT 'identities' AS tbl FROM ${d("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
+ UNION ALL SELECT 'grants' FROM ${d("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${d("profiles")} WHERE person = ?
3
+ UNION ALL SELECT 'nodes' FROM ${d("nodes")} WHERE sub = ? LIMIT 1`).get(a,a,a,a);if(o!==void 0)throw g(`the bundle's person ${a} is already a person in the target (${o.tbl}), not the importing person ${p}`,{where:`${o.tbl}`,value:a})}c(ne,"checkSourcePerson");const B=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],z=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function re(n){const{db:t,schema:a,sourcePerson:p,targetPerson:d}=n,o=c(s=>T(a,s),"S"),r=c((s,u)=>{throw g(`${s} names ${u.join(", ")}, who is neither the bundle's person ${p} nor the importing person ${d}`,{where:s,values:u})},"refuse");for(const[s,u]of B){const _=await $(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(s)} WHERE ${f(u)} IS NOT NULL AND ${f(u)} <> '' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,p,d);_.length>0&&r(`${s}.${u}`,_.map(N=>N.v))}for(const[s,u]of z){const _=await $(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(s)} WHERE ${f(u)} LIKE 'user:%' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,p,d);_.length>0&&r(`${s}.${u}`,_.map(N=>N.v))}const b=await $(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,p,d);b.length>0&&r("identities.external_id",b.map(s=>s.v));const h=await $(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
4
+ WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,d);h.length>0&&r("daemon_actions principal.sub",h.map(s=>s.v));const l=await $(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(p),C(d));l.length>0&&r("relations acts_for subject",l.map(s=>s.v));const E=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return E>0?{relations:E}:{}}c(re,"checkStagedPersons");async function G(n,t){return(await $(n,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
5
+ WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(d=>d[0]))}c(G,"earlierImportedObjects");async function ae(n,t){const{db:a,schema:p,catalog:d,targetPerson:o}=n,r=await H(n,t);if(r.length>0)throw g(`the bundle refers to objects that are not ${o}'s: ${r.slice(0,10).map(b=>`${b.tbl}.${b.col}=${b.value}`).join(", ")}`,{references:r.slice(0,10)});await V(n)}c(ae,"checkStagedReferences");async function ie(n,t){const{db:a,schema:p,catalog:d}=n;if(!d.tables.has("messages"))return{};const o=c(s=>T(p,s),"S"),r=[...new Set((await H(n,t)).filter(s=>s.tbl==="messages").map(s=>s.value))];if(r.length===0)return{};const b="(object_id = ANY(?::text[]) OR actor_id = ANY(?::text[]))",h=`(SELECT message_id FROM ${o("messages")} WHERE ${b})`,l={};for(const[s,u]of[["deliveries","message_id"],["message_causes","message_id"]]){if(!d.tables.has(s))continue;const _=Number((await a.prepareUncached(`DELETE FROM ${o(s)} WHERE ${u} IN ${h}`).run(r,r)).changes);_>0&&(l[s]=_)}const E=Number((await a.prepareUncached(`DELETE FROM ${o("messages")} WHERE ${b}`).run(r,r)).changes);return E>0&&(l.messages=E),l}c(ie,"dropRefusedMessages");async function H(n,t){const{db:a,schema:p,target:d,catalog:o,targetPerson:r}=n,b=c(_=>T(p,_),"S"),h=c(_=>T(d,_),"T"),l=C(r);await a.exec(`CREATE TABLE ${b("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const E=[];for(const[_,N]of Y(o))if(!(!o.tables.has(_)||_==="relations"))for(const m of N)!(_==="nodes"&&m==="profile_id")&&!(_==="crons"&&m==="profile")&&E.push([_,m,""]);E.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[_,N,m]of E)await a.prepareUncached(`INSERT INTO ${b("_refs")} SELECT ?, ?, ${f(N)}::text FROM ${b(_)} ${m===""?"WHERE":`${m} AND`} ${f(N)} IS NOT NULL
6
+ AND ${f(N)}::text NOT IN (SELECT id FROM ${b("objects")}) AND ${f(N)}::text IN (SELECT id FROM ${h("objects")})`).run(_,N);const s=await G(a,t),u=await $(a,`WITH RECURSIVE chain(start, id) AS (
7
+ SELECT DISTINCT value, value FROM ${b("_refs")}
8
+ UNION SELECT c.start, o.owner FROM chain c JOIN ${h("objects")} o ON o.id = c.id JOIN ${h("objects")} up ON up.id = o.owner AND up.type <> 'app'),
9
9
  ok(id) AS (
10
- SELECT o.id FROM ${_("objects")} o WHERE o.type = 'app'
11
- UNION SELECT d.object FROM ${_("documents")} d WHERE d.source_path IS NOT NULL
12
- UNION SELECT i.object FROM ${_("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
13
- UNION SELECT r.resource_id FROM ${_("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
10
+ SELECT o.id FROM ${h("objects")} o WHERE o.type = 'app'
11
+ UNION SELECT d.object FROM ${h("documents")} d WHERE d.source_path IS NOT NULL
12
+ UNION SELECT i.object FROM ${h("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
13
+ UNION SELECT r.resource_id FROM ${h("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
14
14
  UNION SELECT unnest(?::text[]))
15
- SELECT r.tbl, r.col, r.value FROM ${h("_refs")} r
16
- WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(d.length>0)throw I(`the bundle refers to objects that are not ${i}'s: ${d.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:d});const S=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,b]of S){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("profiles")} p ON p.id = s.${f(b)} WHERE p.person <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names profiles that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}for(const[n,b]of[["nodes","grant_id"],["crons","grant_id"]]){const E=await N(r,`SELECT DISTINCT s.${f(b)} AS v FROM ${h(n)} s JOIN ${_("grants")} g ON g.id = s.${f(b)} WHERE g.sub <> ? LIMIT 5`,i);if(E.length>0)throw I(`${n}.${b} names grants that belong to another person: ${E.map(T=>T.v).join(", ")}`,{where:`${n}.${b}`,values:E.map(T=>T.v)})}const O=await N(r,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${h("daemon_actions")} d
17
- JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:u}=a,o=c(e=>g(r,e),"S"),i=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),h=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),_=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),m=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=c(e=>e.split("/")[1]??"","jobOwner"),p=c((e,s,w,L)=>{const F=R(s);if(F===null||F.kind!==w||L!==void 0&&s!==L)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${L===void 0?"":` of the shape ${L}`}`,{where:e,value:s})},"shaped");for(const e of h)if(p("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of _)p("upload_uses.blob_key",e.blob_key,"attachment");for(const e of m)p("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of h){const s=R(e);s!==null&&s.kind==="conversation"&&!i.has(s.owner)&&d.add(s.owner)}for(const{blob_key:e}of _){const s=R(e);s!==null&&s.kind==="attachment"&&!i.has(s.owner)&&d.add(s.owner)}for(const{output_key:e}of m)i.has($(e))||d.add($(e));const S=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(l,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),O=c(e=>i.has(e)||S.get(e)===u,"held"),n=c(e=>!i.has(e)&&!S.has(e),"gone"),b={},E=c((e,s)=>{s>0&&(b[e]=(b[e]??0)+s)},"count"),T=c(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of h){const w=R(s),L=v.get(e);L!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...L??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(n)).map(([e])=>e);y.length>0&&(E("conversation_parts",await T(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),E("conversation_entries",await T(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=c((e,s)=>{const w=R(s).owner;if(!O(w))throw I(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of h)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=_.filter(e=>{const s=R(e.blob_key);return s!==null&&s.kind==="attachment"&&n(s.owner)&&!i.has(e.run_id)});M.length>0&&E("upload_uses",await T(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of _)U.has(e)||j("upload_uses.blob_key",e.blob_key);const A=m.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&n($(e.output_key)));A.length>0&&E("jobs",await T(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,A.map(e=>e.object)));const x=new Set(A);for(const e of m)x.has(e)||j("jobs.output_key",e.output_key);return b}c(re,"checkStagedBlobKeys");async function ae(a){const{db:t,schema:r}=a;for(const l of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(r,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=l[u];if(o===null||!o.startsWith("requests/"))continue;const i=R(o.includes("/",9)?o:`${o}/x`);if(i===null||i.kind!=="request")throw k(`human_requests.${u} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${u}`,value:o});if(i.owner!==l.request_id)throw I(`human_requests.${u} of ${l.request_id} holds ${o}, which belongs to request ${i.owner}`,{where:`human_requests.${u}`,value:o})}}c(ae,"checkStagedRequestKeys");export{te as boundSub,oe as checkSourcePerson,re as checkStagedBlobKeys,ne as checkStagedPersons,se as checkStagedReferences,ae as checkStagedRequestKeys};
15
+ SELECT r.tbl, r.col, r.value FROM ${b("_refs")} r
16
+ WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),u}c(H,"foreignReferences");async function V(n){const{db:t,schema:a,target:p,targetPerson:d}=n,o=c(l=>T(a,l),"S"),r=c(l=>T(p,l),"T"),b=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[l,E]of b){const s=await $(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,d);if(s.length>0)throw g(`${l}.${E} names profiles that belong to another person: ${s.map(u=>u.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(u=>u.v)})}for(const[l,E]of[["nodes","grant_id"],["crons","grant_id"]]){const s=await $(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,d);if(s.length>0)throw g(`${l}.${E} names grants that belong to another person: ${s.map(u=>u.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(u=>u.v)})}const h=await $(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${o("daemon_actions")} d
17
+ JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,d);if(h.length>0)throw g(`a queued action names grants that belong to another person: ${h.map(l=>l.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:h.map(l=>l.v)})}c(V,"checkStagedProfilesAndGrants");const k=c((n,t)=>new D("bind","bundle_invalid",n,t),"bundleInvalid");async function ce(n){const{db:t,schema:a,target:p,targetPerson:d}=n,o=c(e=>T(a,e),"S"),r=new Set((await $(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),b=await $(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),h=await $(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),l=await $(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),E=c(e=>e.split("/")[1]??"","jobOwner"),s=c((e,i,S,w)=>{const F=O(i);if(F===null||F.kind!==S||w!==void 0&&i!==w)throw k(`${e} holds ${JSON.stringify(i)}, which is not a ${S} blob key${w===void 0?"":` of the shape ${w}`}`,{where:e,value:i})},"shaped");for(const e of b)if(s("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of h)s("upload_uses.blob_key",e.blob_key,"attachment");for(const e of l)s("jobs.output_key",e.output_key,"job",`jobs/${E(e.output_key)}/${e.object}/output`);const u=new Set;for(const{blob_key:e}of b){const i=O(e);i!==null&&i.kind==="conversation"&&!r.has(i.owner)&&u.add(i.owner)}for(const{blob_key:e}of h){const i=O(e);i!==null&&i.kind==="attachment"&&!r.has(i.owner)&&u.add(i.owner)}for(const{output_key:e}of l)r.has(E(e))||u.add(E(e));const _=new Map((u.size===0?[]:await $(t,`SELECT node_id, sub FROM ${T(p,"nodes")} WHERE node_id = ANY(?::text[])`,[...u])).map(e=>[e.node_id,e.sub])),N=c(e=>r.has(e)||_.get(e)===d,"held"),m=c(e=>!r.has(e)&&!_.has(e),"gone"),M={},I=c((e,i)=>{i>0&&(M[e]=(M[e]??0)+i)},"count"),R=c(async(e,...i)=>Number((await t.prepareUncached(e).run(...i)).changes),"drop"),W=new Set((await $(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),L=new Map;for(const{conversation_id:e,blob_key:i}of b){const S=O(i),w=L.get(e);w!==null&&(S===null||S.kind!=="conversation"?L.set(e,null):L.set(e,[...w??[],S.owner]))}const v=[...L].filter(([e,i])=>i!==null&&!W.has(e)&&i.every(m)).map(([e])=>e);v.length>0&&(I("conversation_parts",await R(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,v)),I("conversation_entries",await R(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,v)));const U=new Set(v),A=c((e,i)=>{const S=O(i).owner;if(!N(S))throw g(`${e} holds ${i}, which belongs to node ${S}, who is not in the bundle`,{where:e,value:i})},"owned");for(const e of b)U.has(e.conversation_id)||A("conversation_parts.blob_key",e.blob_key);const y=h.filter(e=>{const i=O(e.blob_key);return i!==null&&i.kind==="attachment"&&m(i.owner)&&!r.has(e.run_id)});y.length>0&&I("upload_uses",await R(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,y.map(e=>e.run_id),y.map(e=>e.path)));const x=new Set(y);for(const e of h)x.has(e)||A("upload_uses.blob_key",e.blob_key);const j=l.filter(e=>e.output_key===`jobs/${E(e.output_key)}/${e.object}/output`&&m(E(e.output_key)));j.length>0&&I("jobs",await R(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,j.map(e=>e.object)));const q=new Set(j);for(const e of l)q.has(e)||A("jobs.output_key",e.output_key);return M}c(ce,"checkStagedBlobKeys");async function de(n){const{db:t,schema:a}=n;for(const p of await $(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${T(a,"human_requests")}`))for(const d of["request_dir","presentation_dir","file"]){const o=p[d];if(o===null||!o.startsWith("requests/"))continue;const r=O(o.includes("/",9)?o:`${o}/x`);if(r===null||r.kind!=="request")throw k(`human_requests.${d} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${d}`,value:o});if(r.owner!==p.request_id)throw g(`human_requests.${d} of ${p.request_id} holds ${o}, which belongs to request ${r.owner}`,{where:`human_requests.${d}`,value:o})}}c(de,"checkStagedRequestKeys");export{se as boundSub,ne as checkSourcePerson,ce as checkStagedBlobKeys,re as checkStagedPersons,ae as checkStagedReferences,de as checkStagedRequestKeys,ie as dropRefusedMessages};
@@ -21,8 +21,15 @@ export declare function rewriteConversationHeaders(db: CanvasDb, schema: string,
21
21
  * prefix; a `file` or `presentation_dir` inside the old dir keeps its relative path, one outside it was uploaded to `source/<basename>`. A path that is not
22
22
  * absolute is already a blob path and stays. */
23
23
  export declare function rewriteRequestPaths(db: CanvasDb, schema: string): Promise<number>;
24
- /** A profile whose name the person already uses for another profile is renamed `<name>-<install id>` (staging only; runs before the pre-check). */
24
+ /** A profile whose name another profile already holds is renamed `<name>-<install id>` (staging only; runs before the pre-check), in its `profiles` row and in its `profile`
25
+ * object's handle. The name clashes when the person already uses it for another profile, or when the object's handle is held by any other live profile object: `objects_handle`
26
+ * is unique per type across the whole fleet, so another person's profile counts. Only a handle that is the profile's name moves (a cloud role's handle is the profile id).
27
+ * The new name is a function of the install, so a second load of the bundle derives the same one. Runs after `mapProfileIds`, which leaves the staged identity at the profile's id. */
25
28
  export declare function renameClashingProfiles(db: CanvasDb, schema: string, target: string, installId: string, person: string): Promise<number>;
29
+ /** A migrated usage charge (`legacy:` id, `importLegacyUsage`) has no install id, so two Macs of one person with usage in the same month and model produce one id with
30
+ * different amounts. A staged one whose id the target holds with a different payer, units or usd is renamed `<id>:install-<install id>`; one the target holds unchanged keeps its
31
+ * id and is skipped by the copy. A second load of the same bundle derives the same id. Runs before the pre-check. */
32
+ export declare function renameClashingLegacyCharges(db: CanvasDb, schema: string, target: string, installId: string): Promise<number>;
26
33
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
27
34
  * absent). Runs in the copy transaction: it writes target objects. */
28
35
  export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<number>;
@@ -1,12 +1,14 @@
1
- var A=Object.defineProperty;var p=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const f=p((n,s)=>`${l(n)}.${l(s)}`,"sq");async function B(n,s,c){if(c.length===0)return 0;const e=p(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=p(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${l(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${l(t)} = ? WHERE ${l(t)}::text = ? AND ${r}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}p(B,"rewritePaths");async function K(n,s,c,e,i){if(c.length===0)return 0;const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
- AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}p(K,"rewriteConversationHeaders");async function J(n,s){const c=f(s,"human_requests"),e=p(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
1
+ var D=Object.defineProperty;var d=(n,o)=>D(n,"name",{value:o,configurable:!0});import{createProfileBlaxelEnvironment as v}from"../../environments.js";import{KEY_MAPPED_TABLES as U,mapPath as N}from"../bundle/layout.js";import{ImportLaneError as S}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const $=d((n,o)=>`${l(n)}.${l(o)}`,"sq");async function K(n,o,c){if(c.length===0)return 0;const e=d(s=>$(o,s),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=d(async(s,r,t,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(s)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?M(m,c):N(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(s)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}d(K,"rewritePaths");async function B(n,o,c,e,i){if(c.length===0)return 0;const a=d(r=>$(o,r),"S"),E=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
+ AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let s=0;for(const{conversation_id:r,blob_key:t}of E){const u=H(i,t),R=await e.get(u);if(R===null)throw new S("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${r} cannot be rewritten`);const m=C(R,r,h=>N(c,h));m!==null&&(await e.put(u,m),s+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,r)}return s}d(B,"rewriteConversationHeaders");async function J(n,o){const c=$(o,"human_requests"),e=d(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
3
3
  WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
4
  WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
5
5
  ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.prepareUncached(`UPDATE ${c} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
6
- request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}p(J,"rewriteRequestPaths");function D(n,s){const c=p(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return S(s,n)}}p(D,"rewriteJsonPaths");async function Y(n,s,c,e,i){const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}p(Y,"renameClashingProfiles");async function X(n,s,c,e,i){const a=p(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}p(X,"fillEnvironments");async function z(n,s,c,e){const i=p(o=>f(s,o),"S"),a={},E=p(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${l(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}p(z,"pruneStaged");async function G(n,s,c){const e=p(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}d(J,"rewriteRequestPaths");function M(n,o){const c=d(e=>typeof e=="string"?N(o,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return N(o,n)}}d(M,"rewriteJsonPaths");async function Y(n,o,c,e,i){const a=d(r=>$(o,r),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let s=0;for(const r of E){const t=await n.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
+ WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),u=await n.prepareUncached(`SELECT 1 AS found FROM ${$(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=t===void 0?void 0:await n.prepareUncached(`SELECT 1 AS found FROM ${$(c,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if(u===void 0&&R===void 0)continue;const m=`${r.name}-${e}`;await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(m,r.id),t!==void 0&&await n.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(m,t.id),s+=1}return s}d(Y,"renameClashingProfiles");async function X(n,o,c,e){const i=await n.prepareUncached(`UPDATE ${$(o,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${$(c,"charges")} t
8
+ WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}d(X,"renameClashingLegacyCharges");async function z(n,o,c,e,i){const a=d(r=>$(o,r),"S");let E=0;const s=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of s){let t=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(t=(await n.prepareUncached(`SELECT environment_id FROM ${$(c,"profiles")} WHERE id = ?`).get(r.id))?.environment_id??await v(n,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i})),t===null)throw new S("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id),E+=1}return E}d(z,"fillEnvironments");async function G(n,o,c,e){const i=d(s=>$(o,s),"S"),a={},E=d(async(s,r,...t)=>{const u=Number((await n.prepareUncached(r).run(...t)).changes);u>0&&(a[s]=(a[s]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[s,r]of Object.entries(U))await E(s,`DELETE FROM ${i(s)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,s);for(const s of c.tables.values())s.columns.includes("claimed_by")&&s.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(s.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}d(G,"pruneStaged");async function Q(n,o,c){const e=d(E=>$(o,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${$(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
7
9
  CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
8
10
  COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
9
- FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}p(G,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function Q(n,s,c,e,i,a,E){const o=p(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(d=>u.identity.includes(d)),h=R.map(d=>`s.${l(d)} = t.${l(d)}`).join(" AND "),I=m?"TRUE":R.map(d=>`s.${l(d)} IS DISTINCT FROM t.${l(d)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const d of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=d.predicate===null?"":` WHERE ${d.predicate}`,T=d.columns.map($=>`s.${l($)} = t.${l($)}`).join(" AND "),L=await n.prepareUncached(`SELECT ${d.columns.map($=>`s.${l($)}::text`).join(" || ',' || ")} AS value
10
- FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:d.name,values:L.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${l($)} IS DISTINCT FROM b.${l($)}`).join(" OR "),O=await n.prepareUncached(`SELECT DISTINCT ${d.columns.map($=>`a.${l($)}::text`).join(" || ',' || ")} AS value
11
- FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${d.columns.map($=>`a.${l($)} = b.${l($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:d.name,values:O.map($=>$.value),staged:!0})}const w=u.columns.filter(d=>!u.identity.includes(d)&&!o(r).includes(d)&&(W[r]?.includes(d)??!0));if(w.length>0&&!m){const d=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
12
- FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${d} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}p(Q,"precheck");export{X as fillEnvironments,Q as precheck,z as pruneStaged,Y as renameClashingProfiles,K as rewriteConversationHeaders,B as rewritePaths,J as rewriteRequestPaths,G as takeRepoSyncedDocuments};
11
+ FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}d(Q,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},F={charges:["payer","units","usd"]};async function V(n,o,c,e,i,a,E){const s=d(t=>[...E.get(t)??[],...t==="profiles"?["environment_id"]:[],...g[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const u=e.tables.get(t);if(u===void 0||a.has(t)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(p=>u.identity.includes(p)),h=R.map(p=>`s.${l(p)} = t.${l(p)}`).join(" AND "),I=m?"TRUE":R.map(p=>`s.${l(p)} IS DISTINCT FROM t.${l(p)}`).join(" OR "),y=new Set([...u.identity,...E.get(t)??[]]);for(const p of e.uniqueKeys.filter(T=>T.table===t&&!T.columns.every(_=>y.has(_)))){const T=p.predicate===null?"":` WHERE ${p.predicate}`,_=p.columns.map(f=>`s.${l(f)} = t.${l(f)}`).join(" AND "),w=await n.prepareUncached(`SELECT ${p.columns.map(f=>`s.${l(f)}::text`).join(" || ',' || ")} AS value
12
+ FROM (SELECT * FROM ${$(o,t)}${T}) s JOIN (SELECT * FROM ${$(c,t)}${T}) t ON ${_} AND (${I}) LIMIT 10`).all();w.length>0&&r.push({table:t,key:p.name,values:w.map(f=>f.value)});const A=m?"TRUE":R.map(f=>`a.${l(f)} IS DISTINCT FROM b.${l(f)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${p.columns.map(f=>`a.${l(f)}::text`).join(" || ',' || ")} AS value
13
+ FROM (SELECT ctid AS row_id, * FROM ${$(o,t)}${T}) a JOIN (SELECT ctid AS row_id, * FROM ${$(o,t)}${T}) b ON ${p.columns.map(f=>`a.${l(f)} = b.${l(f)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:t,key:p.name,values:L.map(f=>f.value),staged:!0})}const O=u.columns.filter(p=>!u.identity.includes(p)&&!s(t).includes(p)&&(F[t]?.includes(p)??!0));if(O.length>0&&!m){const p=O.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),T=await n.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
14
+ FROM ${$(o,t)} s JOIN ${$(c,t)} t ON ${h} WHERE ${p} LIMIT 10`).all();T.length>0&&r.push({table:t,key:"primary key payload",values:T.map(_=>_.value)})}}if(r.length>0){const t=r[0];throw new S("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}d(V,"precheck");export{z as fillEnvironments,V as precheck,G as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Q as takeRepoSyncedDocuments};
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var m=(e,i)=>X(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,checkSourcePerson as _e,checkStagedBlobKeys as we,checkStagedPersons as ge,checkStagedReferences as be,checkStagedRequestKeys as he}from"./bind.js";import{deleteBlobs as ye,deleteRunBlobs as Ee,deleteRunPrefix as Se,moveRunBlobs as ve}from"./blobs.js";import{dropStubRows as Re,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Ie,renameClashingRepos as Te,rewriteIds as je,rewritePerson as ke,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Ae,stagingSchema as Ce,targetSchema as Me}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as Le,writeNodeFiles as Be}from"./path-map.js";import{allStoreKeys as We,readPluginsStore as He,recordImportedActivations as Ke,writeStores as Ue}from"./stores.js";import{publishImportedPlugins as Fe}from"./publish-plugins.js";import{COPIED_TABLES as Je}from"../bundle/layout.js";import{emitEvent as qe}from"../../events/emit.js";import{ClaimLostError as $e}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,Ge=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,i)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Ye(e,i){const t=await e.get(N.source(i));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Ye,"readSource");async function ze(e,i,t,a,n,p){const r=[];for(const c of L(t.run_id,"grants",a)){const f=await e.get(c);if(f===null)throw new g("stage","bundle_invalid",`row file ${c} is missing`);r.push(...ne(f))}const o=[];for(const c of r){const f=me(c.sub,a.person,t.person,"grants.sub");await Oe(i,n,p,f,c.grantee)===void 0&&o.push(c.grantee)}if(o.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Pe(o);return!1}m(ze,"grantsReady");async function Et(e,i,t={}){const a=t.blobs??await x(),n=await v(),p=Ce(e.run_id);let r="start";const o=m(async s=>{r=s,await i.assertOwned(),await O(e.run_id,s),await t.atStep?.(s)},"at");let c=e.state==="committed";const f=[];try{const s=await Ye(a,e.run_id);if(e.source_kind==="machine"&&s.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${s.installId}, the run is for ${e.source_install_id}`);s.installId=e.source_install_id;const l=await Me(n),P=[...Je],b=await se(n,l,[...P,"grants"]);if(!c){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await _e(n,l,s.person,e.person),!await ze(a,n,e,s,l,k)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await o("publish-plugins");const F=await He(a,e.run_id),y=await ee(e.person,()=>Fe(F));if(y.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...y.refused),await o("stage");const J=await Ae(n,e.run_id,s.counts,d=>L(e.run_id,d,s),d=>a.get(d));for(const[d,u]of Object.entries(J))_[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:l,catalog:b,sourcePerson:s.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:s.shippedBodies??{}};await o("bind-staged");for(const[d,u]of Object.entries(await ge(w)))E(_,d,u);for(const[d,u]of Object.entries(await we(w)))E(_,d,u);await o("rewrite-person"),await ke(w),await De(w),await o("prune");const q=await oe(n,p,b,s),S=s.kind==="hosted"?Le(s.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(n,p,S),await ue(n,p,S,a,e.run_id),await le(n,p),await he(w);const $=await Ie(w);await pe(n,p,l,s.installId,e.person),await o("rewrite-ids");const D=await je(w,$);await o("drop");const G=await fe(n,p,l),Y=await Re(w);for(const[d,u]of Object.entries({...q}))E(_,d,u);for(const[d,u]of Object.entries(Y))E(_,d,u);await be(w,{installId:s.installId,person:e.person,runId:e.run_id}),await Te(w),await o("pre-check");const z=new Map([["messages",["seq"]],...ie.map(d=>[d,["seq"]])]);await de(n,p,l,b,P,new Set,z),await o("blobs"),await ve(n,p,l,e.person,a,e.run_id,f),await o("copy"),await M(async d=>{await i.assertOwned({extendLeaseMs:Ge});const u=await re({db:d,runId:e.run_id,schema:p,target:l,catalog:b,source:s,person:e.person,idMap:D,pathMap:S}),A=await Xe(d,e.run_id,G);A>0&&(u.inserted.revisions=(u.inserted.revisions??0)+A),await Be(d,p,e.run_id,s);const C=await Ue({db:d,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(C.inserted))u.inserted[Q]=V.length;return T.push(...C.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ve(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),c=!0,await t.atStep?.("committed")}await o("verify");const h=await Ne(n,e.run_id,p,l,b,s.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(h),e.run_id),!h.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:h.differences,invariants:h.invariants});await o("manifest");const I=N.manifest(e.run_id);await a.put(I,await Ze(e.run_id)),await H(n,e.run_id);for(const _ of We(e.run_id))await a.delete(_);await Ee(a,e.run_id),await M(async _=>{await Ke(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(I,R(),e.run_id)})}catch(s){if(s instanceof $e)throw s;const l=Qe(s,r);qe({level:"error",event:"import.run.failed",error:s,fields:{run_id:e.run_id,step:l.step,code:l.code}}),await H(n,e.run_id).catch(()=>{}),c||await ye(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(l),R(),e.run_id),await Se(a,e.run_id,{keepNodeFiles:c,bestEffort:!0})}}m(Et,"processRun");function Qe(e,i){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:i,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Qe,"failureOf");function E(e,i,t){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(E,"addDropped");function Ve(e,i){for(const[t,a]of Object.entries(i.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(i.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ve,"withInserted");async function Xe(e,i,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(r=>r.rev_id)))).map(r=>r.rev_id)),n=t.filter(r=>!a.has(r.rev_id)),p=new Map;for(const r of t)p.set(r.document,[...p.get(r.document)??[],r]);for(const[r,o]of p){const c=await ae(e,r);c!==null&&await te(e,c,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,i,"revisions",n.map(r=>[r.rev_id])),await U(e,i,"revision_parents",n.flatMap(r=>r.parents.map(o=>[r.rev_id,o]))),n.length}m(Xe,"arrive");async function U(e,i,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),i,t)}m(U,"appendManifest");async function Ze(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
1
+ var X=Object.defineProperty;var m=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ue,rewriteConversationHeaders as ce,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Ee}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Pe,grantMissing as Te,mapProfileIds as je,renameClashingRepos as ke,rewriteIds as De,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Me,stagingSchema as Ne,targetSchema as Le}from"./stage.js";import{verifyRun as Be}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ge}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,ze=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Qe(e,s){const t=await e.get(N.source(s));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Qe,"readSource");async function Ve(e,s,t,a,n,p){const o=[];for(const l of L(t.run_id,"grants",a)){const f=await e.get(l);if(f===null)throw new g("stage","bundle_invalid",`row file ${l} is missing`);o.push(...ne(f))}const d=[];for(const l of o){const f=_e(l.sub,a.person,t.person,"grants.sub");await Pe(s,n,p,f,l.grantee)===void 0&&d.push(l.grantee)}if(d.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Te(d);return!1}m(Ve,"grantsReady");async function vt(e,s,t={}){const a=t.blobs??await x(),n=await v(),p=Ne(e.run_id);let o="start";const d=m(async i=>{o=i,await s.assertOwned(),await O(e.run_id,i),await t.atStep?.(i)},"at");let l=e.state==="committed";const f=[];try{const i=await Qe(a,e.run_id);if(e.source_kind==="machine"&&i.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${i.installId}, the run is for ${e.source_install_id}`);i.installId=e.source_install_id;const c=await Le(n),I=[...$e],b=await se(n,c,[...I,"grants"]);if(!l){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ge(n,c,i.person,e.person),!await Ve(a,n,e,i,c,k)){await s.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await d("publish-plugins");const F=await Ue(a,e.run_id),E=await ee(e.person,()=>qe(F));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...E.refused),await d("stage");const J=await Me(n,e.run_id,i.counts,r=>L(e.run_id,r,i),r=>a.get(r));for(const[r,u]of Object.entries(J))_[r]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:c,catalog:b,sourcePerson:i.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:i.shippedBodies??{}};await d("bind-staged");for(const[r,u]of Object.entries(await he(w)))h(_,r,u);for(const[r,u]of Object.entries(await be(w)))h(_,r,u);await d("rewrite-person"),await Ce(w),await Ae(w),await d("prune");const q=await oe(n,p,b,i),S=i.kind==="hosted"?We(i.pathPrefixes??[]):[];await d("rewrite-paths"),await le(n,p,S),await ce(n,p,S,a,e.run_id),await fe(n,p),await Ee(w);const $=await je(w);await ue(n,p,c,i.installId,e.person),await d("rewrite-ids");const D=await De(w,$);await d("drop");const G=await me(n,p,c),Y=await Ie(w);for(const[r,u]of Object.entries({...q}))h(_,r,u);for(const[r,u]of Object.entries(Y))h(_,r,u);for(const[r,u]of Object.entries(await we(w,{installId:i.installId,person:e.person,runId:e.run_id})))h(_,r,u);await ye(w,{installId:i.installId,person:e.person,runId:e.run_id}),await ke(w),await pe(n,p,c,i.installId),await d("pre-check");const z=new Map([["messages",["seq"]],...ie.map(r=>[r,["seq"]])]);await de(n,p,c,b,I,new Set,z),await d("blobs"),await Oe(n,p,c,e.person,a,e.run_id,f),await d("copy"),await M(async r=>{await s.assertOwned({extendLeaseMs:ze});const u=await re({db:r,runId:e.run_id,schema:p,target:c,catalog:b,source:i,person:e.person,idMap:D,pathMap:S}),C=await xe(r,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,i);const A=await Je({db:r,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.length;return T.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ze(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),l=!0,await t.atStep?.("committed")}await d("verify");const y=await Be(n,e.run_id,p,c,b,i.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const P=N.manifest(e.run_id);await a.put(P,await et(e.run_id)),await H(n,e.run_id);for(const _ of Ke(e.run_id))await a.delete(_);await ve(a,e.run_id),await M(async _=>{await Fe(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,R(),e.run_id)})}catch(i){if(i instanceof Ye)throw i;const c=Xe(i,o);Ge({level:"error",event:"import.run.failed",error:i,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(n,e.run_id).catch(()=>{}),l||await Se(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}m(vt,"processRun");function Xe(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:s,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Xe,"failureOf");function h(e,s,t){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(h,"addDropped");function Ze(e,s){for(const[t,a]of Object.entries(s.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(s.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ze,"withInserted");async function xe(e,s,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(o=>o.rev_id)))).map(o=>o.rev_id)),n=t.filter(o=>!a.has(o.rev_id)),p=new Map;for(const o of t)p.set(o.document,[...p.get(o.document)??[],o]);for(const[o,d]of p){const l=await ae(e,o);l!==null&&await te(e,l,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,s,"revisions",n.map(o=>[o.rev_id])),await U(e,s,"revision_parents",n.flatMap(o=>o.parents.map(d=>[o.rev_id,d]))),n.length}m(xe,"arrive");async function U(e,s,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),s,t)}m(U,"appendManifest");async function et(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(Ze,"manifestFile");export{Ge as COPY_LEASE_MS,K as GRANT_WAIT_MS,Et as processRun};
3
+ `))}m(et,"manifestFile");export{ze as COPY_LEASE_MS,K as GRANT_WAIT_MS,vt as processRun};
@@ -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};
@@ -51,7 +51,7 @@ export interface LlmRequest {
51
51
  stop?: string | string[];
52
52
  seed?: number;
53
53
  }
54
- /** The account's access token, refreshed under the pool's row lock when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
54
+ /** The account's access token, refreshed under the account's refresh claim (no connection held during the vendor call) when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
55
55
  export declare function freshSubscriptionAccess(registry: Awaited<ReturnType<typeof openModelRegistry>>, provider: ManagedProviderId, account: SubscriptionCredential, served: string, signal?: AbortSignal): Promise<string>;
56
56
  export declare function parseLlmRequest(raw: unknown): LlmRequest;
57
57
  export interface LlmResult {
@@ -17,11 +17,11 @@ export declare class PoolCredentialStore implements CredentialStore {
17
17
  read(providerId: string): Promise<Credential | undefined>;
18
18
  list(): Promise<readonly CredentialInfo[]>;
19
19
  /**
20
- * pi's locked read-modify-write, chiefly its OAuth refresh. The whole transaction — electing
21
- * the account, running pi's `fn`, committing the result — happens under the account row locks, because a refresh token is single-use: two brokers electing the same
22
- * expired account outside a lock would both spend it and the loser would get a genuine
23
- * `invalid_grant`. Electing under the lock is also what guarantees the refreshed token lands
24
- * back on exactly the account whose token was spent.
20
+ * pi's read-modify-write, chiefly its OAuth refresh. Running pi's `fn` and committing the result
21
+ * happen under the account's refresh claim, because a refresh token is single-use: two brokers
22
+ * refreshing the same expired account without it would both spend it and the loser would get a
23
+ * genuine `invalid_grant`. The commit is conditional on the spent token, so the refreshed token
24
+ * lands back on exactly the account whose token was spent.
25
25
  *
26
26
  * A managed provider with no pool account is NOT created here — pi must not be able to mint a
27
27
  * managed account behind crouter's login surfaces, which own the account-identity gate.
@@ -59,6 +59,8 @@ export declare function createFrameDispatchContext(deps: FrameDispatchDeps): {
59
59
  notifyTurnAccepted: () => void;
60
60
  pendingPromptDispatches: () => number;
61
61
  resetForSession: () => void;
62
+ /** A correlated request of a type this broker does not know (a newer client's): reject it at once instead of letting it time out. */
63
+ refuseUnknown: (client: BrokerClient, type: string, id: string) => void;
62
64
  /** A new cycle's memory names: the response's, or a fresh read when the cycle-start request gave none. */
63
65
  refreshMemoryNames: (names: import("./frame-memory-refs.js").ComposerNames | undefined) => Promise<void>;
64
66
  };
@@ -1 +1 @@
1
- var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as x}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as U,createPromptDispatchTracker as V,createTurnAcceptanceGate as X}from"./turn-ignition.js";import{prependRunDeferredMail as y}from"./run-deferred-mail.js";function ce(n){const{nodeId:e,registry:s,toolGroups:v,projection:k,rebind:l,boundaryReviewId:u,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:M,broadcastModelChanged:F,registryOf:E,formatModelSpec:R,formatExactModelSpec:S,turnAdmission:m,runNode:h,memoryInventory:H,onKickoffAdmitted:P}=n,t=o(()=>l.session(),"currentSession"),T=o(()=>l.services(),"currentServices"),a=j(s),{notWritable:G}=a,c=B(t,e,H),p=V(t),_=X(),f=U({session:t,dispatches:p,turnAdmission:m,prependDeferred:h?r=>y(e,r):void 0,onAdmitted:P}),g=q({nodeId:e,registry:s,replies:a,session:t,dispatches:p,memoryRefs:c,rebind:l,projection:k,toolGroups:v,turnAdmission:m,prependDeferred:h?r=>y(e,r):void 0}),I=o((r,i)=>{G(r,"drive the engine")||((i.type==="prompt"||i.type==="steer"||i.type==="follow_up")&&x(i.text,{type:"human",channel:{type:"viewer"}}),g(r,i))},"handleDriveFrame"),d=z({registry:s,replies:a,session:t,driveEngine:g,turnAcceptance:_,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,disposeAndExit:C}),W=J({registry:s,replies:a,session:t,services:T,registryOf:E,persistModelChoice:M,broadcastModelChanged:o(async(...r)=>{await F(...r),f.drivePending()},"broadcastModelChanged"),formatModelSpec:R}),K=L({nodeId:e,registry:s,replies:a,session:t,boundaryReviewId:u,memoryRefs:c,formatExactModelSpec:S}),N=Q({registry:s,replies:a,rebind:l,session:t,boundaryReviewId:u,memoryRefs:c,reWelcomeAll:A});return{handlers:{hello:d.hello,drive:I,deliver:d.deliver,dialog:d.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{a.ackTo(r,"reload_auth")},"authentication"),bye:d.bye,shutdown:d.shutdown},kickoff:o((r,i)=>f.kickoff(r,i),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:p.pending,resetForSession:o(()=>{},"resetForSession"),refreshMemoryNames:o(r=>r===void 0?c.invalidate():(c.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(ce,"createFrameDispatchContext");function de(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return}}o(de,"handleFrame");export{ce as createFrameDispatchContext,de as handleFrame};
1
+ var U=Object.defineProperty;var o=(n,e)=>U(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as $}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as V,createPromptDispatchTracker as X,createTurnAcceptanceGate as Y}from"./turn-ignition.js";import{prependRunDeferredMail as v}from"./run-deferred-mail.js";function de(n){const{nodeId:e,registry:s,toolGroups:c,projection:k,rebind:p,boundaryReviewId:m,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:F,broadcastModelChanged:M,registryOf:S,formatModelSpec:E,formatExactModelSpec:R,turnAdmission:h,runNode:f,memoryInventory:H,onKickoffAdmitted:P}=n,a=o(()=>p.session(),"currentSession"),T=o(()=>p.services(),"currentServices"),i=j(s),{notWritable:G}=i,d=B(a,e,H),u=X(a),_=Y(),g=V({session:a,dispatches:u,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0,onAdmitted:P}),y=q({nodeId:e,registry:s,replies:i,session:a,dispatches:u,memoryRefs:d,rebind:p,projection:k,toolGroups:c,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0}),I=o((r,t)=>{G(r,"drive the engine")||((t.type==="prompt"||t.type==="steer"||t.type==="follow_up")&&$(t.text,{type:"human",channel:{type:"viewer"}}),y(r,t))},"handleDriveFrame"),l=z({registry:s,replies:i,session:a,driveEngine:y,turnAcceptance:_,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,disposeAndExit:C}),W=J({registry:s,replies:i,session:a,services:T,registryOf:S,persistModelChoice:F,broadcastModelChanged:o(async(...r)=>{await M(...r),g.drivePending()},"broadcastModelChanged"),formatModelSpec:E}),K=L({nodeId:e,registry:s,replies:i,session:a,boundaryReviewId:m,memoryRefs:d,formatExactModelSpec:R}),N=Q({registry:s,replies:i,rebind:p,session:a,boundaryReviewId:m,memoryRefs:d,reWelcomeAll:A});return{handlers:{hello:l.hello,drive:I,deliver:l.deliver,dialog:l.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{i.ackTo(r,"reload_auth")},"authentication"),bye:l.bye,shutdown:l.shutdown},kickoff:o((r,t)=>g.kickoff(r,t),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:u.pending,resetForSession:o(()=>{},"resetForSession"),refuseUnknown:o((r,t,O)=>s.sendFrame(r,{type:"error",code:"unknown_frame",id:O,message:`this broker does not handle '${t}' frames`}),"refuseUnknown"),refreshMemoryNames:o(r=>r===void 0?d.invalidate():(d.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(de,"createFrameDispatchContext");function le(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return;default:{const c=s;typeof c.id=="string"&&n.refuseUnknown(e,String(c.type),c.id)}}}o(le,"handleFrame");export{de as createFrameDispatchContext,le as handleFrame};
@@ -1,10 +1,9 @@
1
- import type { NodeRow } from '../canvas/index.js';
2
1
  export declare const YIELD_STALL_GRACE_MS: number;
3
2
  export declare const KILL_ESCALATE_MS = 20000;
4
3
  export declare const WEDGE_QUIET_MS: number;
5
4
  export declare const WEDGE_CPU_MAX_PERCENT = 2;
6
5
  export type WedgeVerdict = 'leave' | 'pending' | 'wedged';
7
- export declare function yieldStallVerdict(piPidAlive: boolean | null, intent: NodeRow['intent'], busy: boolean, stalledFor: number | null): 'leave' | 'pending' | 'kill';
6
+ export declare function yieldStallVerdict(piPidAlive: boolean | null, busy: boolean, stalledFor: number | null): 'leave' | 'pending' | 'kill';
8
7
  export declare function wedgeVerdict(input: {
9
8
  busy: boolean;
10
9
  quietForMs: number | null;
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var c=(e,n)=>d(e,"name",{value:n,configurable:!0});import{execFile as a}from"node:child_process";import{promisify as m}from"node:util";const h=m(a),g=3*6e4,N=2e4,_=20*6e4,x=2;function P(e,n,t,r){return e!==!0||n!=="refresh"||t?"leave":r===null||r<g?"pending":"kill"}c(P,"yieldStallVerdict");function S(e){return!e.busy||e.quietForMs===null||e.quietForMs<_?"leave":e.cpuPercent===null||e.hasDescendants!==!1&&e.cpuPercent>x?"pending":"wedged"}c(S,"wedgeVerdict");function p(e){const n=new Map,t=new Map;for(const r of e.split(`
2
- `)){const o=r.trim();if(o==="")continue;const i=o.split(/\s+/);if(i.length<3)continue;const u=Number(i[0]),s=Number(i[1]),l=Number(i[2]);if(!Number.isFinite(u)||!Number.isFinite(s)||!Number.isFinite(l))continue;n.set(u,l);const f=t.get(s);f===void 0?t.set(s,[u]):f.push(u)}return{byPid:n,childrenOf:t}}c(p,"parsePsTree");function b(e,n){const{byPid:t,childrenOf:r}=p(e);if(!t.has(n))return null;let o=0;const i=[n],u=new Set;for(;i.length>0;){const s=i.pop();if(u.has(s))continue;u.add(s),o+=t.get(s)??0;const l=r.get(s);l!==void 0&&i.push(...l)}return o}c(b,"sumTreeCpu");function E(e,n){const{byPid:t,childrenOf:r}=p(e);return t.has(n)?(r.get(n)??[]).length>0:null}c(E,"treeHasDescendants");async function T(e){try{const{stdout:n}=await h("ps",["-ax","-o","pid=,ppid=,pcpu="],{encoding:"utf8",timeout:2e3});if(typeof n!="string")return null;const t=b(n,e),r=E(n,e);return t===null||r===null?null:{cpuPercent:t,hasDescendants:r}}catch{return null}}c(T,"sampleBrokerTree");export{N as KILL_ESCALATE_MS,x as WEDGE_CPU_MAX_PERCENT,_ as WEDGE_QUIET_MS,g as YIELD_STALL_GRACE_MS,T as sampleBrokerTree,b as sumTreeCpu,E as treeHasDescendants,S as wedgeVerdict,P as yieldStallVerdict};
1
+ var d=Object.defineProperty;var u=(e,n)=>d(e,"name",{value:n,configurable:!0});import{execFile as a}from"node:child_process";import{promisify as m}from"node:util";const g=m(a),h=3*6e4,N=2e4,_=20*6e4,x=2;function P(e,n,t){return e!==!0||n?"leave":t===null||t<h?"pending":"kill"}u(P,"yieldStallVerdict");function S(e){return!e.busy||e.quietForMs===null||e.quietForMs<_?"leave":e.cpuPercent===null||e.hasDescendants!==!1&&e.cpuPercent>x?"pending":"wedged"}u(S,"wedgeVerdict");function f(e){const n=new Map,t=new Map;for(const r of e.split(`
2
+ `)){const o=r.trim();if(o==="")continue;const i=o.split(/\s+/);if(i.length<3)continue;const c=Number(i[0]),s=Number(i[1]),l=Number(i[2]);if(!Number.isFinite(c)||!Number.isFinite(s)||!Number.isFinite(l))continue;n.set(c,l);const p=t.get(s);p===void 0?t.set(s,[c]):p.push(c)}return{byPid:n,childrenOf:t}}u(f,"parsePsTree");function b(e,n){const{byPid:t,childrenOf:r}=f(e);if(!t.has(n))return null;let o=0;const i=[n],c=new Set;for(;i.length>0;){const s=i.pop();if(c.has(s))continue;c.add(s),o+=t.get(s)??0;const l=r.get(s);l!==void 0&&i.push(...l)}return o}u(b,"sumTreeCpu");function E(e,n){const{byPid:t,childrenOf:r}=f(e);return t.has(n)?(r.get(n)??[]).length>0:null}u(E,"treeHasDescendants");async function T(e){try{const{stdout:n}=await g("ps",["-ax","-o","pid=,ppid=,pcpu="],{encoding:"utf8",timeout:2e3});if(typeof n!="string")return null;const t=b(n,e),r=E(n,e);return t===null||r===null?null:{cpuPercent:t,hasDescendants:r}}catch{return null}}u(T,"sampleBrokerTree");export{N as KILL_ESCALATE_MS,x as WEDGE_CPU_MAX_PERCENT,_ as WEDGE_QUIET_MS,h as YIELD_STALL_GRACE_MS,T as sampleBrokerTree,b as sumTreeCpu,E as treeHasDescendants,S as wedgeVerdict,P as yieldStallVerdict};
@@ -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 {