@north-light/cli 0.3.750 → 0.3.752

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 (70) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/environments.d.ts +37 -0
  4. package/dist/api/routes.d.ts +2 -0
  5. package/dist/api/routes.js +1 -1
  6. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  7. package/dist/clients/attach/viewer.js +1 -1
  8. package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
  9. package/dist/core/canvas/schema-version.d.ts +1 -1
  10. package/dist/core/canvas/schema-version.js +1 -1
  11. package/dist/core/environments.js +1 -1
  12. package/dist/core/grants/local.js +1 -1
  13. package/dist/core/grants/mirror.d.ts +11 -3
  14. package/dist/core/grants/mirror.js +12 -12
  15. package/dist/core/grants/shadow.js +1 -1
  16. package/dist/core/grants/sync.js +1 -1
  17. package/dist/core/graph/objects.d.ts +3 -1
  18. package/dist/core/graph/objects.js +10 -10
  19. package/dist/core/ledger/payer.d.ts +4 -4
  20. package/dist/core/ledger/payer.js +1 -1
  21. package/dist/core/llm/app-rungs.js +1 -1
  22. package/dist/core/llm/run.d.ts +2 -2
  23. package/dist/core/llm/run.js +2 -2
  24. package/dist/core/profiles/manifest.d.ts +5 -0
  25. package/dist/core/profiles/manifest.js +1 -1
  26. package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
  27. package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
  28. package/dist/core/runtime/start-check.js +1 -1
  29. package/dist/daemon/api/app-listener.js +12 -12
  30. package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
  31. package/dist/daemon/api/handlers/app-environments.js +1 -0
  32. package/dist/daemon/api/handlers/git-credential.js +1 -1
  33. package/dist/daemon/api/handlers/runs.js +1 -1
  34. package/dist/daemon/api/operations.js +1 -1
  35. package/dist/daemon/api/principal.d.ts +11 -5
  36. package/dist/daemon/api/principal.js +1 -1
  37. package/dist/daemon/api/server.js +1 -1
  38. package/dist/daemon/crtrd.js +12 -12
  39. package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
  40. package/dist/daemon/reconcilers/recipe-image.js +5 -5
  41. package/docs/ci-runner.md +1 -1
  42. package/docs/sdk/release-notes.md +10 -0
  43. package/package.json +3 -3
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/routes.js +2 -0
  46. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  47. package/packages/crouter-api/dist/core/environments.js +3 -2
  48. package/packages/crouter-api/dist/core/grants/local.js +1 -1
  49. package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
  50. package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
  51. package/packages/crouter-api/dist/core/grants/sync.js +5 -4
  52. package/packages/crouter-api/dist/core/graph/objects.js +2 -2
  53. package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
  54. package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
  55. package/packages/crouter-api/dist/core/llm/run.js +3 -2
  56. package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
  57. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
  58. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  59. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
  60. package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
  61. package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
  62. package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
  63. package/packages/crouter-api/package.json +1 -1
  64. package/packages/crouter-identity/dist/index.d.ts +4 -2
  65. package/packages/crouter-identity/dist/index.js +31 -12
  66. package/packages/crouter-identity/package.json +1 -1
  67. package/packages/crouter-plugin/dist/serve.js +4 -1
  68. package/packages/crouter-plugin/dist/verify.js +36 -8
  69. package/packages/crouter-plugin/package.json +3 -3
  70. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as p,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as d,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const j=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",x="root";function m(e){return e.grantee??"app:terminal"}a(m,"profileApp");function g(e,t){Y(P(m(t),e).dir)}a(g,"scaffoldProfile");function $(e){if(!j.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=p(e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return P(m(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const t=h(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=p(e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(j.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return d(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(h(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(h(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(p(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=h().find(r=>r.manifest.name===x&&m(r.manifest)==="app:terminal");return n!==void 0?(g(n.profileId,n.manifest),n):await q(x,[],{grantee:"app:terminal"})}const e=p(v)??h().find(n=>n.manifest.name===x&&m(n.manifest)==="app:terminal")??null;if(e!==null)return g(e.profileId,e.manifest),e;const t={schema_version:k,name:x,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return g(v,t),await w(n=>n.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:t}}]),p(v)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:y(),last_used_at:null};g(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:m(s),person:te(),...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=h().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),p(e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw d(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:y()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!j.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??y()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=P(m(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw d(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{v as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,h as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
1
+ var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as m,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as p,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const j=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",x="root";function d(e){return e.grantee??"app:terminal"}a(d,"profileApp");function g(e,t){Y(P(d(t),e).dir)}a(g,"scaffoldProfile");function $(e){if(!j.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=m(e);if(t===null)throw p(`profile not found: ${e}`,{received:e});return P(d(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const t=h(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=m(e);if(t!==null)return t;throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(j.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return p(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(h(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(h(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(m(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=h().find(r=>r.manifest.name===x&&d(r.manifest)==="app:terminal");return n!==void 0?(g(n.profileId,n.manifest),n):await q(x,[],{grantee:"app:terminal"})}const e=m(v)??h().find(n=>n.manifest.name===x&&d(n.manifest)==="app:terminal")??null;if(e!==null)return g(e.profileId,e.manifest),e;const t={schema_version:k,name:x,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return g(v,t),await w(n=>n.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:t}}]),m(v)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:y(),last_used_at:null};g(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:d(s),person:n.appEnvironment===!0?d(s):te(),...n.appEnvironment===!0?{payer:n.payer??d(s)}:{},...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=h().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),m(e)===null)throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw p(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:y()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!j.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??y()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw p(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=P(d(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw p(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{v as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,h as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
@@ -28,32 +28,31 @@ export declare const RUN_USER_NPMRC: string[];
28
28
  /** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
29
29
  * this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
30
30
  export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
31
- export declare const REPOS_DIR = "repos";
31
+ /** The build argument that carries the GitHub installation token into the build stage. */
32
+ export declare const GIT_TOKEN_ARG = "CRTR_GIT_TOKEN";
32
33
  /** 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`). */
33
34
  export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
34
35
  export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
35
36
  /** `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
36
37
  * 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. */
37
38
  export declare const GH_WRAPPER_PATH = "/usr/local/bin/gh";
38
- /** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
39
- * Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
40
- * 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. */
41
- export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean): string;
42
- export type GitRunner = (args: string[], env: Record<string, string>, cwd: string) => Promise<void>;
39
+ /** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
40
+ export declare function assertRepositoryShape(repo: RecipeRepository): void;
41
+ /** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
42
+ * only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
43
+ * in the upload) and never in the final stage, so no token is in a layer of the final image. */
44
+ export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean, gitToken?: boolean): string;
43
45
  export interface PrepareBuildDirInput {
44
46
  recipe: Recipe;
45
47
  revision: number;
46
- /** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. */
48
+ /** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. It goes only into `.env.build`. */
47
49
  token: string | null;
48
50
  /** The packages token (`NODE_AUTH_TOKEN`) for the build stage, or null. It goes only into `.env.build` of the upload. */
49
51
  packagesToken?: string | null;
50
52
  /** An empty directory. */
51
53
  dir: string;
52
- git?: GitRunner;
53
- /** The clone URL of a repository; the default is `https://github.com/<full name>.git`. */
54
- cloneUrl?: (githubFullName: string) => string;
55
54
  }
56
- /** Clones each repository into `<dir>/repos/<name>` and writes the Dockerfile and the setup script beside it. */
55
+ /** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
57
56
  export declare function prepareBuildDir(input: PrepareBuildDirInput): Promise<void>;
58
57
  /** A zip of every file under `dir` (deflate, unix modes kept so scripts stay executable). Empty directories are not carried. */
59
58
  export declare function zipDirectory(dir: string): Buffer;
@@ -1,8 +1,9 @@
1
- var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as v,lstatSync as z,mkdirSync as W,readFileSync as V,readdirSync as J,readlinkSync as X,rmSync as Z,writeFileSync as _}from"node:fs";import{join as E,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",D="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
1
+ var z=Object.defineProperty;var c=(t,e)=>z(t,"name",{value:e,configurable:!0});import{constants as v,lstatSync as q,readFileSync as Y,readdirSync as J,readlinkSync as W,rmSync as Z,writeFileSync as I}from"node:fs";import{join as b,relative as V}from"node:path";import{crc32 as X,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as tt}from"./client.js";const et="public.ecr.aws/docker/library/node:24-alpine",nt="ghcr.io/blaxel-ai/sandbox:latest",u="crtr",D="/var/lib/crtr/recipe-pi-agent",rt="blaxel.toml",st=`[build]
2
2
  slim = false
3
- `,at="1.1.0",b="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],lt=`ENV NPM_CONFIG_USERCONFIG=/home/${p}/.npmrc`,B=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),N="repos",G="/work/.crtr/setup.log",C="/work/.crtr/setup-failed",M="/usr/local/bin/gh",pt=["#!/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 "$@"'],L=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ut=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${L(t)} "exited $?" >> ${C}`,"guarded");function dt(t,r,i=!1){const s=ut(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep jq github-cli",`RUN printf '%s\\n' ${pt.map(L).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${N}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${L(o)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${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",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(lt,`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(dt,"recipeDockerfile");const ht=c((t,r,i)=>new Promise((s,a)=>{const n=q("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 Ut(t){const r=t.git??ht,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(E(t.dir,N),{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(N,n.name)],a,t.dir)}_(E(t.dir,st),it),_(E(t.dir,"Dockerfile"),dt(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
3
+ `,ot="1.1.0",x="recipe-setup.sh",it=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${u}/.local/share/pnpm/store`],at=`ENV NPM_CONFIG_USERCONFIG=/home/${u}/.npmrc`,B=c(()=>`printf '%s\\n' ${it.map(t=>`'${t}'`).join(" ")} > /home/${u}/.npmrc`,"writeRunUserNpmrc"),N="CRTR_GIT_TOKEN",M="/work/.crtr/setup.log",G="/work/.crtr/setup-failed",C="/usr/local/bin/gh",ct=["#!/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 "$@"'],w=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),lt=c(t=>(t??"").split(`
4
+ `).map(e=>e.trim()).filter(e=>e!==""),"lines"),E=c((t,e)=>`RUN { ${e}; } >> ${M} 2>&1 || echo ${w(t)} "exited $?" >> ${G}`,"guarded"),pt=c((t,e,i)=>{const o=i?`-c http.https://github.com/.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${N}" | base64 | tr -d '\\n')" `:"";return E(`clone ${t.github_full_name}`,`: r${Math.trunc(e)}; GIT_TERMINAL_PROMPT=0 git ${o}clone --quiet --filter=blob:none --branch ${w(t.default_branch)} ${w(`https://github.com/${t.github_full_name}.git`)} ${w(`/work/${t.name}`)}`)},"cloneStep");function ut(t){if(!/^[A-Za-z0-9._-]+$/.test(t.name)||t.name==="."||t.name==="..")throw new Error(`repository name ${JSON.stringify(t.name)} is not a plain directory name`);if(!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(t.github_full_name))throw new Error(`repository ${JSON.stringify(t.github_full_name)} is not an owner/name pair`);if(t.default_branch===""||/[\s\x00-\x1f'"`$\\]/.test(t.default_branch))throw new Error(`branch ${JSON.stringify(t.default_branch)} of ${t.github_full_name} is not a plain branch name`)}c(ut,"assertRepositoryShape");function ht(t,e,i=!1,o=!1){const l=lt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",r=[`FROM ${et}`,"RUN apk add --no-cache bash git curl ripgrep jq github-cli",`RUN printf '%s\\n' ${ct.map(w).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${nt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${u} -s /bin/sh ${u} && mkdir -p /work/.crtr ${D} && chown -R ${u} /work /var/lib/crtr`];for(const s of t.repositories)ut(s);const n=[`${r[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...o&&t.repositories.length>0?[`ARG ${N}`]:[],...r.slice(1),`RUN rm -f ${G} ${M}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];for(const s of t.repositories)n.push(pt(s,e,o));l.length>0&&n.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${ot}`)),a&&n.push(`COPY ${x} /tmp/${x}`),n.push("WORKDIR /work"),n.push(`RUN ${B()}`);for(const s of l)n.push(E(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${w(s)}`));a&&n.push(E("setup script",`bash /tmp/${x}`)),n.push(E("finalize",`echo ${Math.trunc(e)} > /work/.crtr/recipe-revision`)),n.push("",...r);for(const s of["/work",`/home/${u}`,"/var/lib/crtr"])n.push(`COPY --from=build --chown=${u}:${u} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])n.push(`COPY --from=build ${s} ${s}`);return n.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),n.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&n.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${u}:${u} /home/${u}/.npmrc`),n.push(at,`USER ${u}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),n.join(`
5
+ `)}c(ht,"recipeDockerfile");async function _t(t){const e=t.packagesToken??null,i=t.recipe.repositories.length>0?t.token:null;I(b(t.dir,rt),st),I(b(t.dir,"Dockerfile"),ht(t.recipe,t.revision,e!==null,i!==null));const o=[...e!==null?[`NODE_AUTH_TOKEN=${e}`]:[],...i!==null?[`${N}=${i}`]:[]];o.length>0&&I(b(t.dir,".env.build"),`${o.join(`
6
+ `)}
7
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&I(b(t.dir,x),t.recipe.setup_script.endsWith(`
7
8
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(Ut,"prepareBuildDir");function F(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:V(a),mode:v.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,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+=u.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(ft,"zipDirectory");async function R(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 rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(R,"api");async function H(t,r){const{status:i,json:s}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function xt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(xt,"deleteImage");const mt=60*6e4;async function Nt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await R(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 U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const O=s.timeoutMs??mt,K=e+O;let T=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){T??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-T>=(s.tagGraceMs??6e4),P=(y.length>0?y:A?m:[]).sort((w,j)=>(j.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(A)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${O} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(Nt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,mt as BUILD_TIMEOUT_MS,M as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,N as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,lt as RUN_USER_NPMRC_ENV,ot as SANDBOX_API_IMAGE,C as SETUP_FAILED_FILE,G as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,Nt as buildImage,xt as deleteImage,Lt as environmentImageName,H as getImage,Ut as prepareBuildDir,dt as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
9
+ `)}c(_t,"prepareBuildDir");function F(t,e,i){for(const o of J(e).sort()){const l=b(e,o),a=q(l),r=V(t,l).split("\\").join("/");a.isDirectory()?F(t,l,i):a.isSymbolicLink()?i.push({name:r,data:Buffer.from(W(l)),mode:v.S_IFLNK|511}):a.isFile()&&i.push({name:r,data:Y(l),mode:v.S_IFREG|a.mode&511})}}c(F,"walk");function ft(t){const e=[];F(t,t,e);const i=[],o=[];let l=0;for(const n of e){const s=Buffer.from(n.name),g=Q(n.data),_=X(n.data),h=Buffer.alloc(30);h.writeUInt32LE(67324752,0),h.writeUInt16LE(20,4),h.writeUInt16LE(2048,6),h.writeUInt16LE(8,8),h.writeUInt32LE(33,12),h.writeUInt32LE(_,14),h.writeUInt32LE(g.length,18),h.writeUInt32LE(n.data.length,22),h.writeUInt16LE(s.length,26),i.push(h,s,g);const p=Buffer.alloc(46);p.writeUInt32LE(33639248,0),p.writeUInt16LE(788,4),p.writeUInt16LE(20,6),p.writeUInt16LE(2048,8),p.writeUInt16LE(8,10),p.writeUInt32LE(33,14),p.writeUInt32LE(_,16),p.writeUInt32LE(g.length,20),p.writeUInt32LE(n.data.length,24),p.writeUInt16LE(s.length,28),p.writeUInt32LE(n.mode<<16>>>0,38),p.writeUInt32LE(l,42),o.push(p,s),l+=h.length+s.length+g.length}const a=Buffer.concat(o),r=Buffer.alloc(22);return r.writeUInt32LE(101010256,0),r.writeUInt16LE(e.length,8),r.writeUInt16LE(e.length,10),r.writeUInt32LE(a.length,12),r.writeUInt32LE(l,16),Buffer.concat([...i,a,r])}c(ft,"zipDirectory");async function L(t,e,i,o,l=[]){const a=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,r=await(t.fetch??fetch)(a,{method:e,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),n=await r.text();let s=null;if(n!=="")try{s=JSON.parse(n)}catch{s={raw:n}}if(!r.ok&&!l.includes(r.status))throw new tt(r.status,null,`Blaxel ${e} ${a} failed (${r.status}): ${n.slice(0,300)}`);return{status:r.status,headers:r.headers,json:s}}c(L,"api");async function j(t,e){const{status:i,json:o}=await L(t,"GET",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404]);return i===404?null:o}c(j,"getImage");async function It(t,e){await L(t,"DELETE",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404])}c(It,"deleteImage");const dt=60*6e4;async function xt(t,e,i,o={}){const l=o.sleep??(d=>new Promise(f=>setTimeout(f,d))),a=o.now??Date.now,r=a(),n=await j(t,e),s=new Set((n?.spec?.tags??[]).map(d=>d.name)),g=c(d=>(d?.metadata?.events??[]).map(f=>Date.parse(f.time??"")).filter(f=>!Number.isNaN(f)),"eventTimes"),_=Math.max(-1/0,...g(n)),p=(await L(t,"POST","/images",{resourceType:"sandbox",name:e})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${e}`);const U=await(t.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${e} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const T=o.timeoutMs??dt,K=r+T;let O=null;for(;;){const d=await j(t,e),f=d?.metadata?.status,k=g(d).filter(m=>m>_).sort((m,R)=>m-R);if(f==="BUILT"&&k.length>=2){O??=a();const m=(d?.spec?.tags??[]).filter($=>$.name!==void 0),R=k[0],y=c($=>Date.parse($??"")>=R,"touchedSince"),A=m.filter($=>!s.has($.name)||y($.createdAt)||y($.updatedAt)),S=a()-O>=(o.tagGraceMs??6e4),P=(A.length>0?A:S?m:[]).sort(($,H)=>(H.updatedAt??"").localeCompare($.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${e}:${P}`,buildMs:a()-r};if(S)throw new Error(`Blaxel built image ${e} but no tag appeared`)}if(f==="FAILED"||f==="TERMINATED"){const m=d?.metadata?.events??[];throw new Error(`building image ${e} ${f.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(a()>K)throw new Error(`building image ${e} did not finish within ${T} ms (last status ${f??"none"})`);await l(o.pollMs??3e3)}}c(xt,"buildImage");const Ut=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{st as BLAXEL_TOML,rt as BLAXEL_TOML_FILE,dt as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,N as GIT_TOKEN_ARG,et as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,u as RUN_USER,it as RUN_USER_NPMRC,at as RUN_USER_NPMRC_ENV,nt as SANDBOX_API_IMAGE,G as SETUP_FAILED_FILE,M as SETUP_LOG_FILE,x as SETUP_SCRIPT_FILE,ut as assertRepositoryShape,xt as buildImage,It as deleteImage,Ut as environmentImageName,j as getImage,_t as prepareBuildDir,ht as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as p,payerOf as u}from"../ledger/index.js";import{RunError as r}from"../runs/operations.js";import{grantStanding as f,payerOfGrant as d}from"../grants/mirror.js";import{callerTerminalGrant as m}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",e=t.sub??(a==="app:terminal"?(await m())?.sub:void 0)??null;if(e===null)return null;const c=await d(t.grant_id);return{scope:"start",payer:u({call:"start",grantPayer:c,sub:e,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:e,grantee:a}}n(i,"startCandidateOf");async function w(t){const a=await i(t);a!==null&&await s(a)}n(w,"checkStart");async function O(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new r(401,"grant_revoked","the node's grant is not active")}n(O,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await p(a)}n(P,"startRefusal");function R(t){return t instanceof r&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(R,"isStartRefusal");export{O as checkGrantActive,w as checkStart,R as isStartRefusal,i as startCandidateOf,P as startRefusal};
1
+ var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as u,payerOf as p}from"../ledger/index.js";import{RunError as e}from"../runs/operations.js";import{grantRecord as d,grantStanding as f}from"../grants/mirror.js";import{callerTerminalGrant as g}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",r=t.sub??(a==="app:terminal"?(await g())?.sub:void 0)??null;if(r===null)return null;const c=t.grant_id?(await d(t.grant_id))?.payer:null;return{scope:"start",payer:p({call:"start",grantPayer:c,sub:r,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:r,grantee:a}}n(i,"startCandidateOf");async function R(t){const a=await i(t);a!==null&&await s(a)}n(R,"checkStart");async function w(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new e(401,"grant_revoked","the node's grant is not active")}n(w,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await u(a)}n(P,"startRefusal");function b(t){return t instanceof e&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(b,"isStartRefusal");export{w as checkGrantActive,R as checkStart,b as isStartRefusal,i as startCandidateOf,P as startRefusal};
@@ -1,24 +1,24 @@
1
- var Z=Object.defineProperty;var i=(e,n)=>Z(e,"name",{value:n,configurable:!0});import{AsyncResource as ee}from"node:async_hooks";import{randomUUID as te}from"node:crypto";import{createServer as ne}from"node:http";import{Router as V,causedByOf as re}from"./router.js";import{toErrorBody as ae}from"./map.js";import{objectRoutes as oe}from"./handlers/objects.js";import{customObjectRoutes as ie}from"./handlers/custom-objects.js";import{checkRoutes as se}from"./handlers/check.js";import{chargeRoutes as ue}from"./handlers/charges.js";import{docRoutes as de}from"./handlers/docs.js";import{relationRoutes as ce}from"./handlers/relations.js";import{schemaRoutes as le}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as fe}from"../readiness.js";import{errorCodes as z}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as pe,RUNTIME_VERSION_HEADER as he,minimumRuntimeRefusal as we}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ye,CONTRACT_LEVEL as G,REQUIRED_CONTRACT_HEADER as _e,contractRefusal as ge}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ve,parseTraceparent as Re}from"../../shared/traceparent.js";import{AppPrincipalResolver as Oe}from"./principal.js";import{isDaemonRoute as be,runtimeOwner as Ee,servePeer as Y}from"../peer/ingress.js";import{applySyncNotice as Ae}from"./sync-notice.js";import{ownMachineId as Se}from"../../core/peer/directory.js";import{handleRunOperation as Te,integer as Ne}from"./handlers/runs.js";import{runAnthropicMessages as Ce}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Ie,parseLlmRequest as Pe,runLlm as ke}from"../../core/llm/run.js";import{parseUsageMonth as Me,usageFor as He}from"../../core/ledger/index.js";import{capFields as De}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as F,MODEL_CONTEXT_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{RunError as l,cloudPersonScope as Be,runIsRunning as xe}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as je}from"./deferred-head.js";import{readRunEvents as W,registerGrantStream as Je,subscribeRunEvents as Le}from"../../core/runs/events.js";import{activeGrant as q,payerOfGrant as Ue}from"../../core/grants/mirror.js";async function Xe(e){if(await Ue(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Xe,"appPaidGone");import{releaseGrantWaiters as $e}from"../../core/grants/watch.js";import{emitEvent as Ve}from"../../core/events/emit.js";import{runNotices as ze}from"../run-notices.js";import{handleRuntimeSignIn as Ge,isRuntimeSignInPath as Ye}from"./key-signin.js";import{listAppProfiles as Fe}from"./handlers/app-profiles.js";import{handleTransferOperation as Qe,TRANSFER_OPERATIONS as We}from"./handlers/transfer.js";import{handleQuestionOperation as qe,QUESTION_OPERATIONS as Ke}from"./handlers/questions.js";import{removeVendorAccount as Ze,vendorStatus as et}from"./handlers/vendor-status.js";import{handleMemoryOperation as tt,MEMORY_OPERATIONS as nt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as rt,handleExec as at}from"./handlers/exec.js";import{abortOnClose as U,callerFromApp as ot,handleProviderOperation as it,PROVIDER_OPERATIONS as st,providerFailure as ut}from"./handlers/providers.js";function dt(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(dt,"fixedRow");function ct(e){const n=dt(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(ct,"errorType");function lt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(lt,"appDetails");function x(e,n,o){const m=lt(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:ct(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...De(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,m,d){const y=n instanceof l?n:new l(500,"server_failure","runtime request failed");if(n instanceof l||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
1
+ var ee=Object.defineProperty;var i=(e,n)=>ee(e,"name",{value:n,configurable:!0});import{AsyncResource as te}from"node:async_hooks";import{randomUUID as ne}from"node:crypto";import{createServer as re}from"node:http";import{Router as z,causedByOf as ae}from"./router.js";import{toErrorBody as oe}from"./map.js";import{objectRoutes as ie}from"./handlers/objects.js";import{customObjectRoutes as se}from"./handlers/custom-objects.js";import{checkRoutes as ue}from"./handlers/check.js";import{chargeRoutes as de}from"./handlers/charges.js";import{docRoutes as ce}from"./handlers/docs.js";import{relationRoutes as le}from"./handlers/relations.js";import{schemaRoutes as fe}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as pe}from"../readiness.js";import{errorCodes as G}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as he,RUNTIME_VERSION_HEADER as we,minimumRuntimeRefusal as ye}from"../../api/runtime-version.js";import{CONTRACT_HEADER as _e,CONTRACT_LEVEL as Y,REQUIRED_CONTRACT_HEADER as ge,contractRefusal as ve}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as Re,parseTraceparent as Oe}from"../../shared/traceparent.js";import{AppPrincipalResolver as be,grantIdOf as L}from"./principal.js";import{isDaemonRoute as Ee,runtimeOwner as Ae,servePeer as F}from"../peer/ingress.js";import{applySyncNotice as Se}from"./sync-notice.js";import{ownMachineId as Te}from"../../core/peer/directory.js";import{handleRunOperation as Ne,integer as Ce}from"./handlers/runs.js";import{runAnthropicMessages as Ie}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Pe,parseLlmRequest as ke,runLlm as Me}from"../../core/llm/run.js";import{parseUsageMonth as He,usageFor as De}from"../../core/ledger/index.js";import{capFields as Be}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as Q,MODEL_CONTEXT_BODY_MAX_BYTES as W}from"../../core/llm/body-limits.js";import{RunError as f,cloudPersonScope as xe,runIsRunning as je}from"../../core/runs/operations.js";import{requireRun as U}from"./router.js";import{deferHead as Je}from"./deferred-head.js";import{readRunEvents as q,registerGrantStream as Le,subscribeRunEvents as Ue}from"../../core/runs/events.js";import{activeGrant as K,payerOfGrant as Xe}from"../../core/grants/mirror.js";async function $e(e){if(await Xe(e)==="app")throw new f(401,"grant_revoked","this app-paid grant is no longer active");return null}i($e,"appPaidGone");import{releaseGrantWaiters as Ve}from"../../core/grants/watch.js";import{emitEvent as ze}from"../../core/events/emit.js";import{runNotices as Ge}from"../run-notices.js";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Fe}from"./key-signin.js";import{listAppProfiles as Qe}from"./handlers/app-profiles.js";import{handleTransferOperation as We,TRANSFER_OPERATIONS as qe}from"./handlers/transfer.js";import{handleQuestionOperation as Ke,QUESTION_OPERATIONS as Ze}from"./handlers/questions.js";import{removeVendorAccount as et,vendorStatus as tt}from"./handlers/vendor-status.js";import{handleMemoryOperation as nt,MEMORY_OPERATIONS as rt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as at,handleExec as ot}from"./handlers/exec.js";import{abortOnClose as X,callerFromApp as it,handleProviderOperation as st,PROVIDER_OPERATIONS as ut,providerFailure as dt}from"./handlers/providers.js";function ct(e){return Object.prototype.hasOwnProperty.call(G,e)?G[e]:void 0}i(ct,"fixedRow");function lt(e){const n=ct(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(lt,"errorType");function ft(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(ft,"appDetails");function x(e,n,o){const c=ft(e.details);return{error:{code:e.code,message:e.message,...c===void 0?{}:{details:c},type:lt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...Be(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,c,d){const y=n instanceof f?n:new f(500,"server_failure","runtime request failed");if(n instanceof f||console.error("[app-listener]",`trace_id=${c}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
2
  data: ${JSON.stringify(x(y,o,d))}
3
3
 
4
- `);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(mt,"fail");function X(e){return Array.isArray(e)?e[0]:e}i(X,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function K(e,n=F){const o=[];let m=0;for await(const d of e){if(m+=d.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(K,"rawBodyOf");async function I(e,n=F){const o=await K(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ft(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return Ne(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ft,"cursor");function pt(e){return`id: ${e.sequence_number}
4
+ `);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(mt,"fail");function $(e){return Array.isArray(e)?e[0]:e}i($,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function Z(e,n=Q){const o=[];let c=0;for await(const d of e){if(c+=d.length,c>n)throw new f(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(Z,"rawBodyOf");async function I(e,n=Q){const o=await Z(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new f(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function pt(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new f(400,"invalid_request","invalid cursor","after");return Ce(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(pt,"cursor");function ht(e){return`id: ${e.sequence_number}
5
5
  event: ${e.type}
6
6
  data: ${JSON.stringify(e)}
7
7
 
8
- `}i(pt,"frame");const ht=6e4;async function wt(e,n,o,m,d,y,S,O={},r){await L(m,o);let t=await W(o,d);if(d>t.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":S==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),S==="sse"?n.write(`: connected
8
+ `}i(ht,"frame");const wt=6e4;async function yt(e,n,o,c,d,y,S,O={},r){await U(c,o);let t=await q(o,d);if(d>t.latest_sequence)throw new f(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new f(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":S==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),S==="sse"?n.write(`: connected
9
9
 
10
- `):n.flushHeaders();let p=d;const _=await ze().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(f=>{b=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),b())},"end"),a=i(()=>{N=!1,E()},"onDrain"),H=i(f=>{v||n.write(S==="sse"?`event: error
11
- data: ${JSON.stringify(x(f,y,o))}
10
+ `):n.flushHeaders();let p=d;const _=await Ge().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(m=>{b=m}),R=i(()=>{v||(v=!0,_(p).catch(m=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],m)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),b())},"end"),a=i(()=>{N=!1,E()},"onDrain"),H=i(m=>{v||n.write(S==="sse"?`event: error
11
+ data: ${JSON.stringify(x(m,y,o))}
12
12
 
13
- `:`${JSON.stringify({type:"error",...x(f,y,o)})}
14
- `),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await W(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(S==="sse"?pt(f):`${JSON.stringify(f)}
15
- `),p=f.sequence_number}}catch(f){H(f instanceof l?f:new l(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new l(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await q(m.grant)!==null,"grantActive"),C=await Le(o,ee.bind(E)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
13
+ `:`${JSON.stringify({type:"error",...x(m,y,o)})}
14
+ `),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await U(c,o),t=await q(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new f(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const m of t.events){if(N)break;N=!n.write(S==="sse"?ht(m):`${JSON.stringify(m)}
15
+ `),p=m.sequence_number}}catch(m){H(m instanceof f?m:new f(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new f(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in c||c.grant===null||await K(c.grant)!==null,"grantActive"),C=await Ue(o,te.bind(E)),u="class"in c||c.grant===null?()=>{}:Le(c.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
16
16
 
17
- `)},15e3),s=O.idleMs??ht,w=O.isRunning??xe;let c=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==A){c=f,A=p;return}f-c<s||N||(n.write(`event: idle
17
+ `)},15e3),s=O.idleMs??wt,w=O.isRunning??je;let l=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const m=Date.now();let V=!0;try{V=await w(o)}catch{}if(!v){if(V||p!==A){l=m,A=p;return}m-l<s||N||(n.write(`event: idle
18
18
  data: {}
19
19
 
20
- `),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(wt,"streamRunEvents");function yt(e,n,o,m={}){const d=new V,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const S=new V().registerAll(oe).registerAll(ie).registerAll(de).registerAll(le).registerAll(ce).registerAll(se).registerAll(ue);return i((r,t,p)=>(async()=>{je(r,t,m.deferHead);const _=te();t.setHeader("Request-Id",_);const v=Re(X(r.headers.traceparent))??ve();t.setHeader(he,J()),t.setHeader(ye,G);let T;try{const N=X(r.headers[pe.toLowerCase()]),b=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new l(400,b.code,b.message,b.param):new l(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let E,P;if(p!==void 0)E=p;else if(!H&&r.headers.authorization!==void 0)try{E=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ee,self:Se,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,E);return}if(E===void 0&&a===void 0&&await be(r.method??"GET",h.pathname)){await Y(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await fe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new l(503,"runtime_starting","runtime_starting");if(!R||!a)throw new l(404,"not_found","unknown operation");T=R.params.run_id;const C=re(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Ae(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await et());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await Ze(await I(r)));return}if(E===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await L(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=S.match(a.method,h.pathname);if(!s)throw new l(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let c;try{c=await s.handler(w)}catch(A){const{status:k,body:M}=ae(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream){await wt(r,t,T,u,ft(r,h.searchParams),_,"sse",m.stream,v);return}if(a.name==="llm"){const s=Pe(await I(r,Q)),w=new AbortController,c=i(()=>w.abort(),"abort");t.on("close",c);try{const A=await ke(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
20
+ `),R())}},"checkIdle"),M=setInterval(()=>{k().catch(m=>ze({level:"error",event:"api.run_stream.idle_check_failed",error:m}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(yt,"streamRunEvents");function _t(e,n,o,c={}){const d=new z,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const S=new z().registerAll(ie).registerAll(se).registerAll(ce).registerAll(fe).registerAll(le).registerAll(ue).registerAll(de);return i((r,t,p)=>(async()=>{Je(r,t,c.deferHead);const _=ne();t.setHeader("Request-Id",_);const v=Oe($(r.headers.traceparent))??Re();t.setHeader(we,J()),t.setHeader(_e,Y);let T;try{const N=$(r.headers[he.toLowerCase()]),b=ye(N,J())??ve($(r.headers[ge.toLowerCase()]),Y,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new f(400,b.code,b.message,b.param):new f(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Fe(h.pathname)){await Ye(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let E,P;if(p!==void 0)E=p;else if(!H&&r.headers.authorization!==void 0)try{E=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ae,self:Te,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await F(r,t,D,E);return}if(E===void 0&&a===void 0&&await Ee(r.method??"GET",h.pathname)){await F(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await pe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new f(503,"runtime_starting","runtime_starting");if(!R||!a)throw new f(404,"not_found","unknown operation");T=R.params.run_id;const C=ae(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Se(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await tt());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await et(await I(r)));return}if(E===void 0)throw P??new f(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await U(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=S.match(a.method,h.pathname);if(!s)throw new f(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let l;try{l=await s.handler(w)}catch(A){const{status:k,body:M}=oe(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new f(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(l.rawBody!==void 0||l.status===204||l.body===void 0){t.writeHead(l.status,l.headers??{}),t.end(l.rawBody);return}t.writeHead(l.status,{"Content-Type":"application/json; charset=utf-8",...l.headers??{}}),t.end(JSON.stringify(l.body));return}if(a.stream){await yt(r,t,T,u,pt(r,h.searchParams),_,"sse",c.stream,v);return}if(a.name==="llm"){const s=ke(await I(r,W)),w=new AbortController,l=i(()=>w.abort(),"abort");t.on("close",l);try{const A=await Me(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
21
21
 
22
- `)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},Ie(await q(u.grant)??await Xe(u.grant)),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
22
+ `)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},Pe(await K(L(u))??await $e(L(u))),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
23
23
 
24
- `)):g(t,200,A.completion)}finally{t.off("close",c)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=U(t);try{await Ce(await K(r,Q),r.headers,s,{grant:u.grant,sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=U(t);try{g(t,200,await at(u,await I(r,rt),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await He(u.grantee,Me(h.searchParams.get("month")),Be(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Fe(u));return}if(Ke.has(a.name)){const s=await qe(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(st.has(a.name)){const{signal:s,release:w}=U(t);try{const c=await it(a.name,ot(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,c.status,c.body)}catch(c){const A=ut(c,_,!0);t.writeHead(A.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...A.headers}),t.end(JSON.stringify(A.body))}finally{w()}return}if(nt.has(a.name)){const s=await tt(a.name,{class:"app",app:u.grantee,sub:u.sub,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(We.has(a.name)){const s=await Qe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Te(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){mt(t,N,_,v,T)}})(),"handle")}i(yt,"createAppRequestHandler");async function ln(e,n,o,m={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<0||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new Oe(e.issuer,e.audience,o,e.jwksUrl),S=yt(y,n,o,m),O=ne((t,p)=>{S(t,p)});return{ready:new Promise((t,p)=>{O.once("error",p),O.listen(d.port,d.address,()=>{O.off("error",p),t()})}),port:i(()=>O.address().port,"port"),close:i(async()=>{y.close(),$e(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(ln,"createAppListener");export{ht as RUN_STREAM_IDLE_MS,ln as createAppListener,yt as createAppRequestHandler,ft as cursor,wt as streamRunEvents};
24
+ `)):g(t,200,A.completion)}finally{t.off("close",l)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=X(t);try{await Ie(await Z(r,W),r.headers,s,{grant:L(u),sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=X(t);try{g(t,200,await ot(u,await I(r,at),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await De(u.grantee,He(h.searchParams.get("month")),xe(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Qe(u));return}if(Ze.has(a.name)){const s=await Ke(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(ut.has(a.name)){const{signal:s,release:w}=X(t);try{const l=await st(a.name,it(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,l.status,l.body)}catch(l){const A=dt(l,_,!0);t.writeHead(A.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...A.headers}),t.end(JSON.stringify(A.body))}finally{w()}return}if(rt.has(a.name)){const s=await nt(a.name,{class:"app",app:u.grantee,sub:u.sub,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(qe.has(a.name)){const s=await We(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Ne(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){mt(t,N,_,v,T)}})(),"handle")}i(_t,"createAppRequestHandler");async function fn(e,n,o,c={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<0||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new be(e.issuer,e.audience,o,e.jwksUrl),S=_t(y,n,o,c),O=re((t,p)=>{S(t,p)});return{ready:new Promise((t,p)=>{O.once("error",p),O.listen(d.port,d.address,()=>{O.off("error",p),t()})}),port:i(()=>O.address().port,"port"),close:i(async()=>{y.close(),Ve(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(fn,"createAppListener");export{wt as RUN_STREAM_IDLE_MS,fn as createAppListener,_t as createAppRequestHandler,pt as cursor,yt as streamRunEvents};
@@ -0,0 +1,2 @@
1
+ import { type RouteTable } from '../router.js';
2
+ export declare const appEnvironmentRoutes: RouteTable;
@@ -0,0 +1 @@
1
+ var P=Object.defineProperty;var i=(e,n)=>P(e,"name",{value:n,configurable:!0});import{parsePrincipal as R}from"@north-light/identity";import{grantFor as N}from"../../../core/grants/mirror.js";import{isNamespaceOwner as O}from"../../../core/grants/owner.js";import{openDb as _}from"../../../core/canvas/db.js";import{ApiError as s}from"../../../api/errors.js";import{usage as f}from"../../../core/errors.js";import{isCloudRole as T}from"../../../core/canvas/person-state.js";import{ENVIRONMENT_MEMORY_MB as h,patchEnvironment as M}from"../../../core/environment-recipe.js";import{createProfile as $,listProfiles as b}from"../../../core/profiles/manifest.js";import{check as q}from"../../../core/permissions/evaluator.js";import{requestProfileDeletion as A}from"../../profile-delete.js";import{readerFor as I}from"../reader.js";import{actsAsPerson as C,appOf as g}from"../router.js";async function y(e,n){const r=await _(),t=e.principal.class==="person"?void 0:g(e.principal),o=[];for(const m of b()){const p=m.manifest.environment_id;p===void 0||t!==void 0&&(m.manifest.grantee??"app:terminal")!==t||(await r.prepare("SELECT payer FROM environments WHERE object = ? AND kind = 'blaxel'").get(p))?.payer==null||t===void 0&&!C(e.principal)&&!await q(r,await I(r,e),n,p)||o.push({entry:m,environmentId:p})}return o}i(y,"visible");async function v(e,n){const r=e.params.name,t=(await y(e,n)).filter(({entry:o})=>o.profileId===r||o.manifest.name===r);if(t.length===0)throw new s(404,"not_found","environment not found");if(t.length>1)throw new s(400,"ambiguous","environment name matches several apps; use the profile id");return t[0]}i(v,"find");async function u(e,n){const r=await(await _()).prepare("SELECT payer, setup_script, pi_packages, memory_mb, recipe_revision FROM environments WHERE object = ?").get(n);return{name:e.manifest.name,profile_id:e.profileId,environment_id:n,payer:r.payer,setup_script:r.setup_script,pi_packages:r.pi_packages,memory_mb:Number(r.memory_mb),recipe_revision:Number(r.recipe_revision)}}i(u,"read");function E(e){if(e!==void 0){if(!Array.isArray(e))throw f("repositories must be an array",{field:"repositories"});if(e.length>0)throw new s(400,"repositories_not_supported","an app environment cannot have repositories yet")}}i(E,"assertNoRepositories");function d(e,n){if(e==null)return null;if(typeof e=="string")return e;throw f(`${n} must be a string or null`,{field:n})}i(d,"recipeText");function k(e){const n=e??2048;if(typeof n!="number"||!h.includes(n))throw f(`memory_mb must be one of ${h.join(", ")}`,{field:"memory_mb"});return n}i(k,"memoryOf");async function D(e,n){const r=typeof n=="string"?R(n):null,t=i(()=>new s(400,"invalid_request",`payer must be a principal ${e} speaks for or an owner whose grant to ${e} names itself payer`,{violations:[{field:"payer",problem:"not payable by the caller",received:n}]}),"refuse");if(typeof n!="string"||r===null)throw t();if(O(e,n))return n;const o=await N(e,n);if(o===null||o.payer!==n)throw t();return n}i(D,"validPayer");async function F(e){const n=g(e.principal);if(e.principal.class!=="app"&&e.principal.class!=="broker")throw new s(403,"permission_error","only an app creates an environment");const r=e.body??{};if(typeof r.name!="string"||r.name.trim()==="")throw f("an environment name is required",{field:"name"});if(n===null)throw new s(403,"permission_error","only an app creates an environment");const t=await D(n,r.payer);E(r.recipe?.repositories);const o=d(r.recipe?.setup_script,"setup_script"),m=d(r.recipe?.pi_packages,"pi_packages"),p=k(r.recipe?.memory_mb),c=r.name.trim(),l=(await y(e,"read")).find(({entry:a})=>a.manifest.name===c);if(l!==void 0){const a=await u(l.entry,l.environmentId);if(a.setup_script!==o||a.pi_packages!==m||a.memory_mb!==p)throw new s(409,"conflict",`environment ${c} exists with a different recipe; use patch`);return{status:200,body:a}}if(b().some(a=>a.manifest.name===c&&(a.manifest.grantee??"app:terminal")===n))throw new s(409,"conflict",`${n} already has a profile named ${c} that is not an environment`);if(!T())throw new s(400,"invalid_request","app environments are created on a cloud role");const w=await $(c,[],{grantee:n,appEnvironment:!0,payer:t,memoryMb:p,recipe:{repositories:[],setup_script:o,pi_packages:m}});return{status:201,body:await u(w,w.manifest.environment_id)}}i(F,"handleCreate");async function L(e){const n=await y(e,"read");return{status:200,body:{environments:await Promise.all(n.map(({entry:r,environmentId:t})=>u(r,t)))}}}i(L,"handleList");async function S(e){const{entry:n,environmentId:r}=await v(e,"edit"),t=e.body??{};return E(t.repositories),await M(r,{...t.setup_script!==void 0?{setup_script:d(t.setup_script,"setup_script")}:{},...t.pi_packages!==void 0?{pi_packages:d(t.pi_packages,"pi_packages")}:{},...t.memory_mb!==void 0?{memory_mb:k(t.memory_mb)}:{}}),{status:200,body:await u(n,r)}}i(S,"handlePatch");async function j(e){const{entry:n}=await v(e,"edit"),r=await A(n.profileId,{force:!0});return{status:r.status,body:r.body}}i(j,"handleDelete");const ee=[{method:"POST",pattern:"/v1/environments",handler:F},{method:"GET",pattern:"/v1/environments",handler:L},{method:"PATCH",pattern:"/v1/environments/:name",handler:S},{method:"DELETE",pattern:"/v1/environments/:name",handler:j}];export{ee as appEnvironmentRoutes};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var d=(o,t)=>_(o,"name",{value:t,configurable:!0});import{ApiError as n}from"../../../api/errors.js";import{openDb as f}from"../../../core/canvas/db.js";import{getNode as w}from"../../../core/canvas/canvas.js";import{environmentOfNode as m,recipeOf as g}from"../environment-of.js";import{invalidRequest as b,objectBody as v,optionalString as y,requiredString as k}from"./validate.js";function p(o){const t=process.env[o];if(t===void 0||t==="")throw new n(500,"github_service_unconfigured",`${o} is not set on this control plane`);return t}d(p,"requiredEnv");async function E(o){const{principal:t}=o;if(t.class!=="broker")throw new n(403,"broker_only","git credentials are issued to a node token");const l=o.params.environment_id??"",r=await w(t.node);if(r===null)throw new n(404,"node_not_found",`no node ${t.node}`);if(await m(r.profile_id??null)!==l)throw new n(403,"not_your_environment",`this node does not run in environment ${l}`);const s=[],e=v(o.body,["host","path"],s),i=k(e,"host",s);if(y(e,"path",s),s.length>0&&b("git credential request",s),i!=="github.com")throw new n(400,"unsupported_git_host",`only github.com credentials are issued, not ${i}`);const a=(await g(l))?.repositories.map(h=>h.github_full_name)??[];if(a.length===0)throw new n(409,"no_recipe_repositories",`environment ${l} has no recipe repositories`);const u=await(await f()).prepare("SELECT allow_pull_request_write FROM environments WHERE object = ?").get(l),c=await x(t.sub,a,u?.allow_pull_request_write===!0);return{status:200,body:{username:"x-access-token",password:c.token,expiry:c.expires_at}}}d(E,"handleGitCredential");async function x(o,t,l=!1){const r=await fetch(`${p("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/installation-token`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${p("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({sub:o,repositories:t,allow_pull_request_write:l})}),s=await r.text(),e=s===""?{}:JSON.parse(s);if(!r.ok){const a=typeof e.error=="object"?e.error?.code:e.code,u=(typeof e.error=="object"?e.error?.message:e.message)??`the GitHub service answered ${r.status}`;throw r.status===409&&(a==="repositories_span_installations"||a==="github_not_connected")?new n(409,a,u,{repositories:t}):new n(502,"github_service_failed",u,{status:r.status,...a===void 0?{}:{code:a}})}if(typeof e.token!="string"||typeof e.expires_at!="string")throw new n(502,"github_service_failed","the GitHub service answered without a token and expiry");const i=e.author;if(i===void 0)throw new n(502,"github_service_failed","the GitHub service answered without an author field");if(i!==null&&(typeof i.name!="string"||typeof i.email!="string"))throw new n(502,"github_service_failed","the GitHub service answered a malformed author");return{token:e.token,expires_at:e.expires_at,author:i===null?null:{name:i.name,email:i.email}}}d(x,"mintInstallationToken");const C=[{method:"POST",pattern:"/v1/environments/:environment_id/git-credential",handler:E}];export{C as gitCredentialRoutes,x as mintInstallationToken,p as requiredEnv};
1
+ var f=Object.defineProperty;var p=(o,t)=>f(o,"name",{value:t,configurable:!0});import{ApiError as n}from"../../../api/errors.js";import{openDb as _}from"../../../core/canvas/db.js";import{getNode as w}from"../../../core/canvas/canvas.js";import{environmentOfNode as m,recipeOf as g}from"../environment-of.js";import{invalidRequest as b,objectBody as v,optionalString as y,requiredString as k}from"./validate.js";function h(o){const t=process.env[o];if(t===void 0||t==="")throw new n(500,"github_service_unconfigured",`${o} is not set on this control plane`);return t}p(h,"requiredEnv");async function x(o){const{principal:t}=o;if(t.class!=="broker")throw new n(403,"broker_only","git credentials are issued to a node token");const l=o.params.environment_id??"",s=await w(t.node);if(s===null)throw new n(404,"node_not_found",`no node ${t.node}`);if(await m(s.profile_id??null)!==l)throw new n(403,"not_your_environment",`this node does not run in environment ${l}`);const a=[],e=v(o.body,["host","path"],a),r=k(e,"host",a);if(y(e,"path",a),a.length>0&&b("git credential request",a),r!=="github.com")throw new n(400,"unsupported_git_host",`only github.com credentials are issued, not ${r}`);const i=(await g(l))?.repositories.map(c=>c.github_full_name)??[];if(i.length===0)throw new n(409,"no_recipe_repositories",`environment ${l} has no recipe repositories`);const d=await(await _()).prepare("SELECT allow_pull_request_write FROM environments WHERE object = ?").get(l),u=await E(t.sub,i,d?.allow_pull_request_write===!0);return{status:200,body:{username:"x-access-token",password:u.token,expiry:u.expires_at}}}p(x,"handleGitCredential");async function E(o,t,l=!1){const s=await fetch(`${h("GITHUB_SERVICE_URL").replace(/\/$/,"")}/internal/installation-token`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${h("CROUTER_SERVICE_TOKEN")}`},body:JSON.stringify({sub:o,repositories:t,allow_pull_request_write:l})}),a=await s.text(),e=a===""?{}:JSON.parse(a);if(!s.ok){const i=typeof e.error=="object"?e.error?.code:e.code,d=(typeof e.error=="object"?e.error?.message:e.message)??`the GitHub service answered ${s.status}`,u=typeof e.error=="object"?e.error?.next:e.next;if(s.status===409&&(i==="repositories_span_installations"||i==="github_not_connected")){const c=typeof u=="string"&&u!==""?u:void 0;throw new n(409,i,d,{repositories:t,...c===void 0?{}:{error:i,message:d,next:i==="github_not_connected"?`Ask the person to open ${c}, link GitHub and install the Northlight GitHub App on the account that owns these repositories (choose "All repositories"), then retry.`:`List repositories from one GitHub account only; manage installations at ${c}.`,url:c}})}throw new n(502,"github_service_failed",d,{status:s.status,...i===void 0?{}:{code:i}})}if(typeof e.token!="string"||typeof e.expires_at!="string")throw new n(502,"github_service_failed","the GitHub service answered without a token and expiry");const r=e.author;if(r===void 0)throw new n(502,"github_service_failed","the GitHub service answered without an author field");if(r!==null&&(typeof r.name!="string"||typeof r.email!="string"))throw new n(502,"github_service_failed","the GitHub service answered a malformed author");return{token:e.token,expires_at:e.expires_at,author:r===null?null:{name:r.name,email:r.email}}}p(E,"mintInstallationToken");const q=[{method:"POST",pattern:"/v1/environments/:environment_id/git-credential",handler:x}];export{q as gitCredentialRoutes,E as mintInstallationToken,h as requiredEnv};
@@ -1 +1 @@
1
- var S=Object.defineProperty;var c=(a,t)=>S(a,"name",{value:t,configurable:!0});import{callerGrant as g}from"../principal.js";import{grantVersion as b,payerOfGrant as O}from"../../../core/grants/mirror.js";import{holdGrant as $}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as v,cancelRun as N,cloudPersonScope as A,deleteRun as j,interruptRun as x,listRuns as B,messageRun as J,renameRun as z,requestedScopes as D,startRun as E,traceRun as G,waitRun as K}from"../../../core/runs/operations.js";import{canReadRun as y,requireRun as w,runCallerApp as M}from"../router.js";import{waitSeconds as q}from"../long-poll-wait.js";import{outputSchemaProblem as P}from"../../../core/runtime/structured-output.js";function m(a){if(!a||typeof a!="object"||Array.isArray(a))throw new n(400,"invalid_request","a JSON object is required");return a}c(m,"object");function k(a,t,i,u,l){if(a===null)return l;if(!/^(0|[1-9]\d*)$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<i||Number(a)>u)throw new n(400,"invalid_request",`invalid ${t}`,t);return Number(a)}c(k,"integer");const T=256*1024;async function Y(a,t,i,u,l,_,h){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=q("grant.get",u),s=u.get("since");if(s!==null&&!/^[A-Za-z0-9_-]{1,64}$/.test(s))throw new n(400,"invalid_request","invalid since","since");const d=e&&s!==null?$(t.grant):void 0;let o;try{if(o=await g(t),d){const f=Date.now()+e*1e3;for(;b(o)===s&&Date.now()<f;)await d.changed(Math.max(0,(f-Date.now())/1e3)),o=await g(t)}}finally{d?.release()}return{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:t.grant,rev:o.rev,resolved_scopes:o.resolved_scopes,spend_cap:o.spend_cap,exp:t.exp,payer:await O(t.grant),dependencies:o.dependencies??{},version:b(o)}}}case"run.start":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=m(l),s=["mode","parent","fork_from","node_id","env","tools","system_prompt"];for(const r of s)if(e[r]!==void 0)throw new n(403,"owner_only",`${r} is owner-only`,r);const d=["payer","model_policy","kind"];for(const r of d)if(e[r]!==void 0)throw new n(400,"invalid_request",`${r} is not available`,r);for(const r of Object.keys(e))if(!["prompt","scopes","metadata","profile","isolated","cwd","worktree","output_schema","message","model","deadline"].includes(r))throw new n(400,"invalid_request",`unknown field ${r}`,r);if(e.model!==void 0&&(typeof e.model!="string"||!e.model.trim()))throw new n(400,"invalid_request","model must be a non-empty string","model");if(e.deadline!==void 0&&(typeof e.deadline!="string"||!e.deadline.trim()))throw new n(400,"invalid_request","deadline must be a duration string such as 10m","deadline");if(e.profile!==void 0&&(typeof e.profile!="string"||!e.profile))throw new n(400,"invalid_request","profile must be a profile id","profile");if(e.isolated!==void 0&&typeof e.isolated!="boolean")throw new n(400,"invalid_request","isolated must be a boolean","isolated");if(e.cwd!==void 0&&(e.isolated!==!0||typeof e.cwd!="string"||!e.cwd))throw new n(400,"invalid_request","cwd is available only for an isolated run and must be an absolute path inside its root folder","cwd");if(e.worktree!==void 0&&e.isolated!==!0)throw new n(400,"invalid_request","worktree is not available","worktree");if(e.isolated===!0&&e.worktree!==void 0)throw new n(400,"invalid_request","worktree is unavailable for an isolated run","worktree");if(typeof e.prompt!="string"||!e.prompt.trim())throw new n(400,"invalid_request","prompt is required","prompt");if(e.message!==void 0&&(typeof e.message!="string"||!e.message.trim()))throw new n(400,"invalid_request","message must be a non-empty string","message");const o=e.metadata===void 0?{}:m(e.metadata);if(Buffer.byteLength(JSON.stringify(o))>4096)throw new n(400,"invalid_request","metadata exceeds 4 KB","metadata");let f;if(e.output_schema!==void 0){const r=e.output_schema;if(!r||typeof r!="object"||Array.isArray(r))throw new n(400,"invalid_request","output_schema must be a JSON Schema object","output_schema");if(Buffer.byteLength(JSON.stringify(r))>T)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");const p=await P(r);if(p!==null)throw new n(400,"invalid_request",`output_schema is not usable: ${p}`,"output_schema");f=r}const R=D(t.resolved,e.scopes,t.grantee);return{status:201,body:await E(t,{prompt:e.prompt,scopes:R,metadata:o,profile:e.profile,isolated:e.isolated,cwd:e.cwd,...e.model===void 0?{}:{model:e.model},...e.deadline===void 0?{}:{deadline:e.deadline},...f===void 0?{}:{output_schema:f},...e.message===void 0?{}:{message:e.message},...h===void 0?{}:{causedBy:h}},v(_))}}case"run.list":{const e=u.get("status")??void 0;if(e&&!["running","waiting_on_user","idle","settled"].includes(e))throw new n(400,"invalid_request","invalid status","status");const s=u.get("app");if(s!==null&&!/^(?:app:)?[a-z0-9][a-z0-9-]*$/.test(s))throw new n(400,"invalid_request","invalid app","app");const d=s===null?M(t):s.startsWith("app:")?s:`app:${s}`;if(d!==null&&!await y(t,d))throw new n(404,"not_found","run not found");const o=A("sub"in t?t.sub:void 0);return{status:200,body:await B(d,{status:e,...o===void 0?{}:{sub:o},after:u.get("after")??void 0,limit:k(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&d!==null?{visible:c(async f=>await y(t,d,f),"visible")}:{}})}}case"run.get":{const e=q("run.get",u),s=await w(t,i),d=await K(i,s.grantee,e);return await w(t,i),{status:200,body:d}}case"run.message":{const e=m(l);if(typeof e.message!="string"||!e.message.trim())throw new n(400,"invalid_request","message is required","message");if(e.start_turn!==void 0&&typeof e.start_turn!="boolean")throw new n(400,"invalid_request","start_turn must be a boolean","start_turn");if(e.steer!==void 0&&typeof e.steer!="boolean")throw new n(400,"invalid_request","steer must be a boolean","steer");if(e.start_turn===!1&&e.steer===!0)throw new n(400,"invalid_request","steer requires start_turn","steer");return{status:202,body:await J(await w(t,i,!0),e.message,void 0,e.start_turn,v(_),e.steer)}}case"run.interrupt":{const e=m(l===void 0?{}:l);if(e.children!==void 0&&e.children!=="stop"&&e.children!=="continue")throw new n(400,"invalid_request","invalid children","children");return{status:200,body:await x(await w(t,i,!0),e.children)}}case"run.cancel":{const e=m(l===void 0?{}:l);if(e.keep_schedules!==void 0&&typeof e.keep_schedules!="boolean")throw new n(400,"invalid_request","invalid keep_schedules","keep_schedules");return{status:200,body:await N(await w(t,i,!0),{keepSchedules:e.keep_schedules})}}case"run.rename":{const e=m(l);for(const s of Object.keys(e))if(s!=="name")throw new n(400,"invalid_request",`unknown field ${s}`,s);return{status:200,body:await z(await w(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await j(await w(t,i,!0,!0));return{status:200,body:{run_id:i,uploads_pending:e}}}case"trace.get":{const e=u.get("format")??void 0;if(e&&e!=="entries")throw new n(400,"invalid_request","unknown trace format","format");const s=await w(t,i);return{status:200,body:await G(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}c(Y,"handleRunOperation");export{Y as handleRunOperation,k as integer};
1
+ var O=Object.defineProperty;var c=(a,t)=>O(a,"name",{value:t,configurable:!0});import{callerGrant as b,grantIdOf as _}from"../principal.js";import{grantVersion as v,payerOfGrant as $}from"../../../core/grants/mirror.js";import{holdGrant as N}from"../../../core/grants/watch.js";import{RunError as n,idempotencyKeyOf as y,cancelRun as A,cloudPersonScope as j,deleteRun as x,interruptRun as B,listRuns as J,messageRun as z,renameRun as D,requestedScopes as E,startRun as G,traceRun as K,waitRun as M}from"../../../core/runs/operations.js";import{canReadRun as q,requireRun as w,runCallerApp as P}from"../router.js";import{waitSeconds as k}from"../long-poll-wait.js";import{outputSchemaProblem as T}from"../../../core/runtime/structured-output.js";function m(a){if(!a||typeof a!="object"||Array.isArray(a))throw new n(400,"invalid_request","a JSON object is required");return a}c(m,"object");function R(a,t,i,u,l){if(a===null)return l;if(!/^(0|[1-9]\d*)$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<i||Number(a)>u)throw new n(400,"invalid_request",`invalid ${t}`,t);return Number(a)}c(R,"integer");const C=256*1024;async function Z(a,t,i,u,l,h,p){switch(a.name){case"grant.get":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=k("grant.get",u),s=u.get("since");if(s!==null&&!/^[A-Za-z0-9_-]{1,64}$/.test(s))throw new n(400,"invalid_request","invalid since","since");const d=e&&s!==null?N(_(t)):void 0;let o;try{if(o=await b(t),d){const f=Date.now()+e*1e3;for(;v(o)===s&&Date.now()<f;)await d.changed(Math.max(0,(f-Date.now())/1e3)),o=await b(t)}}finally{d?.release()}return{status:200,body:{sub:t.sub,grantee:t.grantee,client_id:t.client_id,grant:_(t),rev:o.rev,resolved_scopes:o.resolved_scopes,spend_cap:o.spend_cap,exp:t.exp,payer:await $(_(t)),dependencies:o.dependencies??{},version:v(o)}}}case"run.start":{if("class"in t)throw new n(403,"permission_error","an app token is required");const e=m(l),s=["mode","parent","fork_from","node_id","env","tools","system_prompt"];for(const r of s)if(e[r]!==void 0)throw new n(403,"owner_only",`${r} is owner-only`,r);const d=["payer","model_policy","kind"];for(const r of d)if(e[r]!==void 0)throw new n(400,"invalid_request",`${r} is not available`,r);for(const r of Object.keys(e))if(!["prompt","scopes","metadata","profile","isolated","cwd","worktree","output_schema","message","model","deadline"].includes(r))throw new n(400,"invalid_request",`unknown field ${r}`,r);if(e.model!==void 0&&(typeof e.model!="string"||!e.model.trim()))throw new n(400,"invalid_request","model must be a non-empty string","model");if(e.deadline!==void 0&&(typeof e.deadline!="string"||!e.deadline.trim()))throw new n(400,"invalid_request","deadline must be a duration string such as 10m","deadline");if(e.profile!==void 0&&(typeof e.profile!="string"||!e.profile))throw new n(400,"invalid_request","profile must be a profile id","profile");if(e.isolated!==void 0&&typeof e.isolated!="boolean")throw new n(400,"invalid_request","isolated must be a boolean","isolated");if(e.cwd!==void 0&&(e.isolated!==!0||typeof e.cwd!="string"||!e.cwd))throw new n(400,"invalid_request","cwd is available only for an isolated run and must be an absolute path inside its root folder","cwd");if(e.worktree!==void 0&&e.isolated!==!0)throw new n(400,"invalid_request","worktree is not available","worktree");if(e.isolated===!0&&e.worktree!==void 0)throw new n(400,"invalid_request","worktree is unavailable for an isolated run","worktree");if(typeof e.prompt!="string"||!e.prompt.trim())throw new n(400,"invalid_request","prompt is required","prompt");if(e.message!==void 0&&(typeof e.message!="string"||!e.message.trim()))throw new n(400,"invalid_request","message must be a non-empty string","message");const o=e.metadata===void 0?{}:m(e.metadata);if(Buffer.byteLength(JSON.stringify(o))>4096)throw new n(400,"invalid_request","metadata exceeds 4 KB","metadata");let f;if(e.output_schema!==void 0){const r=e.output_schema;if(!r||typeof r!="object"||Array.isArray(r))throw new n(400,"invalid_request","output_schema must be a JSON Schema object","output_schema");if(Buffer.byteLength(JSON.stringify(r))>C)throw new n(400,"invalid_request","output_schema exceeds 256 KB","output_schema");const g=await T(r);if(g!==null)throw new n(400,"invalid_request",`output_schema is not usable: ${g}`,"output_schema");f=r}const S=E(t.resolved,e.scopes,t.grantee);return{status:201,body:await G(t,{prompt:e.prompt,scopes:S,metadata:o,profile:e.profile,isolated:e.isolated,cwd:e.cwd,...e.model===void 0?{}:{model:e.model},...e.deadline===void 0?{}:{deadline:e.deadline},...f===void 0?{}:{output_schema:f},...e.message===void 0?{}:{message:e.message},...p===void 0?{}:{causedBy:p}},y(h))}}case"run.list":{const e=u.get("status")??void 0;if(e&&!["running","waiting_on_user","idle","settled"].includes(e))throw new n(400,"invalid_request","invalid status","status");const s=u.get("app");if(s!==null&&!/^(?:app:)?[a-z0-9][a-z0-9-]*$/.test(s))throw new n(400,"invalid_request","invalid app","app");const d=s===null?P(t):s.startsWith("app:")?s:`app:${s}`;if(d!==null&&!await q(t,d))throw new n(404,"not_found","run not found");const o=j("sub"in t?t.sub:void 0);return{status:200,body:await J(d,{status:e,...o===void 0?{}:{sub:o},after:u.get("after")??void 0,limit:R(u.get("limit"),"limit",1,100,50),..."class"in t&&(t.class==="broker"||t.class==="cron")&&d!==null?{visible:c(async f=>await q(t,d,f),"visible")}:{}})}}case"run.get":{const e=k("run.get",u),s=await w(t,i),d=await M(i,s.grantee,e);return await w(t,i),{status:200,body:d}}case"run.message":{const e=m(l);if(typeof e.message!="string"||!e.message.trim())throw new n(400,"invalid_request","message is required","message");if(e.start_turn!==void 0&&typeof e.start_turn!="boolean")throw new n(400,"invalid_request","start_turn must be a boolean","start_turn");if(e.steer!==void 0&&typeof e.steer!="boolean")throw new n(400,"invalid_request","steer must be a boolean","steer");if(e.start_turn===!1&&e.steer===!0)throw new n(400,"invalid_request","steer requires start_turn","steer");return{status:202,body:await z(await w(t,i,!0),e.message,void 0,e.start_turn,y(h),e.steer)}}case"run.interrupt":{const e=m(l===void 0?{}:l);if(e.children!==void 0&&e.children!=="stop"&&e.children!=="continue")throw new n(400,"invalid_request","invalid children","children");return{status:200,body:await B(await w(t,i,!0),e.children)}}case"run.cancel":{const e=m(l===void 0?{}:l);if(e.keep_schedules!==void 0&&typeof e.keep_schedules!="boolean")throw new n(400,"invalid_request","invalid keep_schedules","keep_schedules");return{status:200,body:await A(await w(t,i,!0),{keepSchedules:e.keep_schedules})}}case"run.rename":{const e=m(l);for(const s of Object.keys(e))if(s!=="name")throw new n(400,"invalid_request",`unknown field ${s}`,s);return{status:200,body:await D(await w(t,i,!0),e.name)}}case"run.delete":{const{uploads_pending:e}=await x(await w(t,i,!0,!0));return{status:200,body:{run_id:i,uploads_pending:e}}}case"trace.get":{const e=u.get("format")??void 0;if(e&&e!=="entries")throw new n(400,"invalid_request","unknown trace format","format");const s=await w(t,i);return{status:200,body:await K(i,s.grantee,e)}}default:throw new n(404,"not_found","unknown operation")}}c(Z,"handleRunOperation");export{Z as handleRunOperation,R as integer};