@north-light/cli 0.3.664 → 0.3.666
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.
- package/dist/api/client.d.ts +5 -0
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +25 -0
- package/dist/api/dto/environments.js +0 -0
- package/dist/api/dto/profiles.d.ts +15 -0
- package/dist/api/index.d.ts +1 -0
- package/dist/api/index.js +1 -1
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +4 -8
- package/dist/clients/attach/viewer.js +10 -10
- package/dist/commands/profile/environment.d.ts +2 -0
- package/dist/commands/profile/environment.js +2 -0
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile.js +1 -1
- package/dist/core/environment-recipe.d.ts +20 -10
- package/dist/core/environment-recipe.js +1 -1
- package/dist/core/environment-repos.d.ts +7 -0
- package/dist/core/environment-repos.js +1 -0
- package/dist/core/environments.d.ts +4 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/model-auth/api-credential-store.d.ts +5 -1
- package/dist/core/model-auth/api-credential-store.js +1 -1
- package/dist/core/profiles/manifest.d.ts +7 -1
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/providers/files.js +1 -1
- package/dist/core/review/companion.js +1 -1
- package/dist/core/runs/operations.js +7 -7
- package/dist/core/runtime/provider-credential-gate.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +6 -2
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -5
- package/dist/core/secrets/blaxel-launch.js +3 -3
- package/dist/core/storage/caller-file.d.ts +12 -0
- package/dist/core/storage/caller-file.js +1 -0
- package/dist/core/storage/client.d.ts +0 -1
- package/dist/core/storage/client.js +2 -2
- package/dist/core/storage/shares.d.ts +0 -12
- package/dist/core/storage/shares.js +1 -1
- package/dist/daemon/api/app-listener.js +9 -9
- package/dist/daemon/api/environment-of.d.ts +2 -0
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/app-profiles.d.ts +1 -0
- package/dist/daemon/api/handlers/app-profiles.js +1 -1
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/environments.d.ts +2 -0
- package/dist/daemon/api/handlers/environments.js +1 -0
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/handlers/transfer.d.ts +0 -6
- package/dist/daemon/api/handlers/transfer.js +1 -1
- package/dist/daemon/api/map.d.ts +2 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.d.ts +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +11 -11
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +6 -6
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +18 -0
- package/dist/daemon/reconcilers/idle-sandbox.js +7 -0
- package/dist/daemon/reconcilers/recipe-image.js +4 -4
- package/docs/apps/guides/files-and-documents.md +2 -6
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/dist/core/storage/download.d.ts +0 -23
- package/dist/core/storage/download.js +0 -1
|
@@ -16,14 +16,18 @@ export declare const NODE_BASE_IMAGE = "public.ecr.aws/docker/library/node:24-al
|
|
|
16
16
|
export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
|
|
17
17
|
export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
|
|
18
18
|
export declare const REPOS_DIR = "repos";
|
|
19
|
-
/** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a token cannot appear here.
|
|
20
|
-
|
|
19
|
+
/** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
|
|
20
|
+
* Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
|
|
21
|
+
* 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. */
|
|
22
|
+
export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean): string;
|
|
21
23
|
export type GitRunner = (args: string[], env: Record<string, string>, cwd: string) => Promise<void>;
|
|
22
24
|
export interface PrepareBuildDirInput {
|
|
23
25
|
recipe: Recipe;
|
|
24
26
|
revision: number;
|
|
25
27
|
/** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. */
|
|
26
28
|
token: string | null;
|
|
29
|
+
/** The packages token (`NODE_AUTH_TOKEN`) for the build stage, or null. It goes only into `.env.build` of the upload. */
|
|
30
|
+
packagesToken?: string | null;
|
|
27
31
|
/** An empty directory. */
|
|
28
32
|
dir: string;
|
|
29
33
|
git?: GitRunner;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(
|
|
3
|
-
`)}l(X,"recipeDockerfile");const
|
|
4
|
-
|
|
5
|
-
`)
|
|
1
|
+
var B=Object.defineProperty;var l=(e,r)=>B(e,"name",{value:r,configurable:!0});import{spawn as P}from"node:child_process";import{constants as y,lstatSync as C,mkdirSync as G,readFileSync as M,readdirSync as F,readlinkSync as K,rmSync as Y,writeFileSync as b}from"node:fs";import{join as g,relative as j}from"node:path";import{crc32 as q,deflateRawSync as z}from"node:zlib";import{BlaxelApiError as H}from"./client.js";const J="public.ecr.aws/docker/library/node:24-alpine",W="ghcr.io/blaxel-ai/sandbox:latest",h="crtr",T="/var/lib/crtr/recipe-pi-agent",V="1.1.0",I="recipe-setup.sh",U="repos",Z=l(e=>`'${e.replace(/'/g,"'\\''")}'`,"shellQuote"),Q=l(e=>(e??"").split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines");function X(e,r,a=!1){const o=Q(e.pi_packages),i=e.setup_script!==null&&e.setup_script.trim()!=="",n=[`FROM ${J}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${W} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${h} -s /bin/sh ${h} && mkdir -p /work/.crtr ${T} && chown -R ${h} /work /var/lib/crtr`],t=[`${n[0]} AS build`,...a?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),"RUN npm install -g pnpm && mkdir -p /var/lib/postgresql"];e.repositories.length>0&&t.push(`COPY --chown=${h} ${U}/ /work/`),o.length>0&&t.push(`RUN npm install -g @earendil-works/pi-coding-agent@${V}`),i&&t.push(`COPY ${I} /tmp/${I}`),t.push("WORKDIR /work");for(const s of o)t.push(`RUN HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${T} pi install ${Z(s)}`);i&&t.push(`RUN bash /tmp/${I}`),t.push(`RUN echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${h} /work /home/${h} /var/lib/crtr`),t.push("",...n);for(const s of["/work",`/home/${h}`,"/usr/local","/var/lib/crtr","/usr","/etc","/lib"])t.push(`COPY --from=build ${s} ${s}`);return t.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),a&&t.push(`RUN rm -f /work/.npmrc /home/${h}/.npmrc`),t.push("WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),t.join(`
|
|
3
|
+
`)}l(X,"recipeDockerfile");const ee=l((e,r,a)=>new Promise((o,i)=>{const n=P("git",e,{cwd:a,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let t="";n.stderr.on("data",s=>{t+=s.toString()}),n.on("error",i),n.on("close",s=>{s===0?o():i(new Error(`git ${e[0]} failed (${s}): ${t.slice(0,300)}`))})}),"runGit");async function le(e){const r=e.git??ee,a=e.packagesToken??null,o=e.cloneUrl??(n=>`https://github.com/${n}.git`);G(g(e.dir,U),{recursive:!0});const i=e.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:${e.token}`).toString("base64")}`};for(const n of e.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),g(U,n.name)],i,e.dir)}b(g(e.dir,"Dockerfile"),X(e.recipe,e.revision,a!==null)),a!==null&&b(g(e.dir,".env.build"),`NODE_AUTH_TOKEN=${a}
|
|
4
|
+
`,{mode:384}),e.recipe.setup_script!==null&&e.recipe.setup_script.trim()!==""&&b(g(e.dir,I),e.recipe.setup_script.endsWith(`
|
|
5
|
+
`)?e.recipe.setup_script:`${e.recipe.setup_script}
|
|
6
|
+
`)}l(le,"prepareBuildDir");function v(e,r,a){for(const o of F(r).sort()){const i=g(r,o),n=C(i),t=j(e,i).split("\\").join("/");n.isDirectory()?v(e,i,a):n.isSymbolicLink()?a.push({name:t,data:Buffer.from(K(i)),mode:y.S_IFLNK|511}):n.isFile()&&a.push({name:t,data:M(i),mode:y.S_IFREG|n.mode&511})}}l(v,"walk");function te(e){const r=[];v(e,e,r);const a=[],o=[];let i=0;for(const s of r){const u=Buffer.from(s.name),m=z(s.data),$=q(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE($,14),p.writeUInt32LE(m.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,m);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE($,16),c.writeUInt32LE(m.length,20),c.writeUInt32LE(s.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(s.mode<<16>>>0,38),c.writeUInt32LE(i,42),o.push(c,u),i+=p.length+u.length+m.length}const n=Buffer.concat(o),t=Buffer.alloc(22);return t.writeUInt32LE(101010256,0),t.writeUInt16LE(r.length,8),t.writeUInt16LE(r.length,10),t.writeUInt32LE(n.length,12),t.writeUInt32LE(i,16),Buffer.concat([...a,n,t])}l(te,"zipDirectory");async function _(e,r,a,o,i=[]){const n=`${e.controlUrl??"https://api.blaxel.ai/v0"}${a}`,t=await(e.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${e.apiKey}`,"x-blaxel-workspace":e.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await t.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!t.ok&&!i.includes(t.status))throw new H(t.status,null,`Blaxel ${r} ${n} failed (${t.status}): ${s.slice(0,300)}`);return{status:t.status,headers:t.headers,json:u}}l(_,"api");async function S(e,r){const{status:a,json:o}=await _(e,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return a===404?null:o}l(S,"getImage");async function pe(e,r){await _(e,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}l(pe,"deleteImage");async function de(e,r,a,o={}){const i=o.sleep??(f=>new Promise(w=>setTimeout(w,f))),n=o.now??Date.now,t=n(),s=await S(e,r),u=new Set((s?.spec?.tags??[]).map(f=>f.name)),m=s?.metadata?.events?.length??0,p=(await _(e,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const c=await(e.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(te(a))});if(!c.ok)throw new Error(`uploading the build context of image ${r} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const A=t+(o.timeoutMs??20*6e4);let x=null;for(;;){const f=await S(e,r),w=f?.metadata?.status;if(w==="BUILT"&&(f?.metadata?.events?.length??0)>=m+2){x??=n();const E=(f?.spec?.tags??[]).filter(d=>d.name!==void 0),L=(f?.metadata?.events??[]).slice(m).map(d=>d.time??"").filter(d=>d!=="").sort()[0],R=l(d=>L!==void 0&&Date.parse(d??"")>=Date.parse(L),"touchedSince"),N=E.filter(d=>!u.has(d.name)||R(d.createdAt)||R(d.updatedAt)),k=n()-x>=(o.tagGraceMs??6e4),O=(N.length>0?N:k?E:[]).sort((d,D)=>(D.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.name;if(O!==void 0)return{ref:`sandbox/${r}:${O}`,buildMs:n()-t};if(k)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(w==="FAILED"||w==="TERMINATED"){const E=f?.metadata?.events??[];throw new Error(`building image ${r} ${w.toLowerCase()}: ${E[E.length-1]?.message??"no message"}`)}if(n()>A)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${w??"none"})`);await i(o.pollMs??3e3)}}l(de,"buildImage");const ue=l(e=>`env-${e}`,"environmentImageName");function fe(e){Y(e,{recursive:!0,force:!0})}l(fe,"removeBuildDir");export{J as NODE_BASE_IMAGE,T as RECIPE_PI_AGENT_DIR,U as REPOS_DIR,I as SETUP_SCRIPT_FILE,de as buildImage,pe as deleteImage,ue as environmentImageName,S as getImage,le as prepareBuildDir,X as recipeDockerfile,fe as removeBuildDir,te as zipDirectory};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var S=Object.defineProperty;var t=(r,e)=>S(r,"name",{value:e,configurable:!0});import{createHash as A,createHmac as
|
|
1
|
+
var S=Object.defineProperty;var t=(r,e)=>S(r,"name",{value:e,configurable:!0});import{createHash as A,createHmac as _}from"node:crypto";import{openDb as C}from"../canvas/db.js";import{blobStore as $}from"../blobs/index.js";import{environmentOfNode as I,packagesTokenFor as T}from"../../daemon/api/environment-of.js";import{EnvironmentImagePending as b}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{resolveEnvironmentImage as U}from"../../daemon/reconcilers/recipe-image.js";import{environmentSecrets as L}from"./environment-secrets.js";import{environmentOwnerProfile as x,profileInApp as y}from"./environment-owner.js";const v="blaxel/base-image:latest",D=900;function H(r=process.env){const e=t(s=>{const n=r[s];if(!n)throw new Error(`${s} is required to sign release URLs`);return n},"need");return{bucket:e("CRTR_R2_BUCKET"),endpoint:e("CRTR_R2_ENDPOINT"),accessKeyId:e("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:e("CRTR_R2_SECRET_ACCESS_KEY")}}t(H,"releaseSignerFromEnv");const z=t(r=>A("sha256").update(r).digest("hex"),"sha256hex"),E=t((r,e)=>_("sha256",r).update(e).digest(),"hmac"),h=t(r=>encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),"encode");function O(r,e,s,n=new Date){const c=new URL(r.endpoint),i=n.toISOString().replace(/[:-]|\.\d{3}/g,""),o=i.slice(0,8),a=`${o}/auto/s3/aws4_request`,p=`/${h(r.bucket)}/${e.split("/").map(h).join("/")}`,m=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${r.accessKeyId}/${a}`],["X-Amz-Date",i],["X-Amz-Expires",String(s)],["X-Amz-SignedHeaders","host"]].sort(([w],[g])=>w<g?-1:1).map(([w,g])=>`${h(w)}=${h(g)}`).join("&"),d=["GET",p,m,`host:${c.host}
|
|
2
2
|
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
3
|
+
`),f=["AWS4-HMAC-SHA256",i,a,z(d)].join(`
|
|
4
|
+
`),u=E(E(E(E(`AWS4${r.secretAccessKey}`,o),"auto"),"s3"),"aws4_request"),R=_("sha256",u).update(f).digest("hex");return`${c.origin}${p}?${m}&X-Amz-Signature=${R}`}t(O,"presignGet");function X(r=process.env){const e=r.CRTR_PUBLIC_API_URL;if(!e||!/^https?:\/\//.test(e))throw new Error("CRTR_PUBLIC_API_URL must be an http(s) URL for the Blaxel runner");return{apiUrl:e,signer:H(r)}}t(X,"blaxelLaunchDepsFromEnv");async function P(r){const e=await(await $()).get(`releases/${r}/runtime.tar.gz.sha256`);return e===null?null:e.toString("utf8")}t(P,"defaultReleaseSha");function G(r){return async e=>{const s=await C(),n=await s.prepare("SELECT profile_id, grantee FROM node_rows WHERE node_id = ?").get(e.nodeId);if(n===void 0)throw new Error(`no node ${e.nodeId}`);if(n.profile_id===null)throw new Error(`node ${e.nodeId} has no profile, so it has no person`);const c=await s.prepare("SELECT person FROM profiles WHERE id = ?").get(n.profile_id);if(c===void 0)throw new Error(`profile ${n.profile_id} has no row`);const i=n.grantee??"app:terminal",o=await I(n.profile_id),a=await U(o);if(a.state==="pending")throw new b(o,a.error);const p=await s.prepare("SELECT memory_mb FROM environments WHERE object = ?").get(o);if(p===void 0)throw new Error(`no environment ${o}`);const l=await x(o),m=l!==null&&await y(l,i),d=(await(r.releaseSha??P)(e.release)??"").trim().split(/\s+/)[0]??"";if(!/^[0-9a-f]{64}$/.test(d))throw new Error(`release ${e.release} has no sha256 object (releases/${e.release}/runtime.tar.gz.sha256)`);const f=await T(o),u=await L({person:c.person,app:i,ownerProfile:l,ownerProfileInApp:m,includeDeployment:!1});return{image:a.state==="image"?a.ref:v,memoryMb:Number(p.memory_mb),apiUrl:r.apiUrl,releaseUrl:O(r.signer,`releases/${e.release}/runtime.tar.gz`,D,r.now?.()),releaseSha256:d,secrets:f!==null?{NODE_AUTH_TOKEN:f,...u}:u}}}t(G,"createBlaxelLaunchContext");export{v as BASE_IMAGE,D as RELEASE_URL_TTL_S,X as blaxelLaunchDepsFromEnv,G as createBlaxelLaunchContext,O as presignGet,H as releaseSignerFromEnv};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type FileCaller } from '../spaces/permissions.js';
|
|
2
|
+
/** An open regular file the caller may read. The caller closes `fd`. */
|
|
3
|
+
export interface CallerFile {
|
|
4
|
+
fd: number;
|
|
5
|
+
path: string;
|
|
6
|
+
size: number;
|
|
7
|
+
}
|
|
8
|
+
/** Open `raw` for `caller` (`null` = the person) beneath the root its
|
|
9
|
+
* permission names: absent or withheld → `not_found`; unpermitted →
|
|
10
|
+
* `scope_missing`; a symlink on the way → `invalid_request` `param: path`; not
|
|
11
|
+
* a regular file → `not_found`. */
|
|
12
|
+
export declare function openCallerFile(caller: FileCaller | null, raw: string | null | undefined): CallerFile;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=Object.defineProperty;var a=(s,o)=>y(s,"name",{value:o,configurable:!0});import{closeSync as E,constants as u,fstatSync as R,realpathSync as d}from"node:fs";import{isAbsolute as O,join as w,relative as p,resolve as g,sep as h}from"node:path";import{appsRoot as v,runtimeRoot as N,userRoot as _}from"../layout.js";import{RunError as c}from"../runs/operations.js";import{isBeneathRefusal as C,openBeneath as S}from"../spaces/open-beneath.js";import{fileRoot as $}from"../spaces/permissions.js";function m(s,o){const t=p(s,o);return t===""||t!==".."&&!t.startsWith(`..${h}`)&&!t.startsWith(h)}a(m,"contains");function q(s){const o=a(f=>process.platform==="darwin"?f.toLowerCase():f,"fold"),t=o(s),r=o(v());if(m(o(N()),t)||m(o(w(_(),"memory")),t))return!0;if(!m(r,t))return!1;const e=p(r,t).split(h)[1];return e==="memory"||e==="profiles"||e==="conversations"}a(q,"withheld");function x(s,o){if(typeof o!="string"||!o)throw new c(400,"invalid_request","path is required","path");if(!O(o)||o.includes("\0"))throw new c(400,"invalid_request","path must be absolute","path");const t=g(o),r=a(()=>new c(404,"not_found",`no such file: ${t}`),"notFound");if(q(t))throw r();const e=$(s,t,"read");if("hidden"in e)throw r();if(!("root"in e))throw new c(403,"scope_missing",e.missing?`missing scope ${e.missing}`:`no permission names ${t}`,void 0,void 0,e.missing??void 0);const f=a(()=>new c(400,"invalid_request",`${t} meets a symlink, leaves its permitted root, or is not a regular file`,"path"),"symlink");let l;try{l=S(e.root,t,u.O_RDONLY|u.O_NONBLOCK)}catch(n){if(C(n))throw f();const i=n.code;throw i==="ENOENT"||i==="ENOTDIR"||i==="EISDIR"||i==="ENXIO"||i==="EACCES"||i==="EPERM"?r():n}try{if(process.platform!=="linux"){let i;try{i=d(t)}catch{throw r()}if(i!==w(d(e.root),p(e.root,t)))throw f()}const n=R(l);if(!n.isFile())throw r();return{fd:l,path:t,size:n.size}}catch(n){throw E(l),n}}a(x,"openCallerFile");export{x as openCallerFile};
|
|
@@ -70,7 +70,6 @@ export interface StorageClient {
|
|
|
70
70
|
size: number;
|
|
71
71
|
expires_at?: string;
|
|
72
72
|
}): Promise<CreatedShare>;
|
|
73
|
-
putShareBytes(uploadLink: string, file: string, size: number, mediaType: string): Promise<void>;
|
|
74
73
|
deleteShare(shareId: string): Promise<void>;
|
|
75
74
|
/** A provider file result's upload: the PUT accepts any length up to
|
|
76
75
|
* `max_size` and storage records the size stored (the one call to change if
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var x=Object.defineProperty;var l=(r,
|
|
1
|
+
var x=Object.defineProperty;var l=(r,o)=>x(r,"name",{value:o,configurable:!0});import{read as v}from"node:fs";import{Readable as w}from"node:stream";import{promisify as S}from"node:util";import{isCloudRole as $}from"../canvas/person-state.js";import{readConfig as T}from"../config.js";import{directoryIssuer as O}from"../directory/issuer.js";import{RunError as b}from"../runs/operations.js";import{mintDirectoryToken as E,runtimeId as R}from"../grants/sync.js";const W=104857600;class m extends Error{static{l(this,"StorageRefused")}status;code;constructor(o,u,d){super(d),this.status=o,this.code=u}}const C=S(v);async function*j(r,o){let u=0;for(;u<o;){const d=Buffer.allocUnsafe(Math.min(1048576,o-u)),{bytesRead:p}=await C(r,d,0,d.length,u);if(p===0)throw new Error("file shrank while it was being copied");u+=p,yield d.subarray(0,p)}}l(j,"fdChunks");const s=l(r=>new b(503,"storage_unavailable",r,void 0,void 0,void 0,!0),"unavailable");function U(){if($()){const o=process.env.CRTR_BOOT_STORAGE_URL?.replace(/\/$/,"");return o?{service_url:o,base_url:o}:null}const r=T("user").runtime?.storage;return!r?.service_url||!r.base_url?null:{service_url:r.service_url.replace(/\/$/,""),base_url:r.base_url.replace(/\/$/,"")}}l(U,"storageConfig");let h;function F(){const r=U(),o=O();if(!r||!o)throw new b(503,"storage_unavailable","file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.",void 0,void 0,void 0,!1);const u=`${o}
|
|
2
2
|
${r.service_url}
|
|
3
|
-
${r.base_url}`;return
|
|
3
|
+
${r.base_url}`;return h?.key!==u&&(h={key:u,client:A(r,()=>E(o,r.service_url),R())}),h.client}l(F,"storageClient");function J(){h=void 0}l(J,"resetStorageClient");function A(r,o,u){let d,p;const k=l(async()=>{if(d&&d.expires_at-6e4>Date.now())return d.access_token;p??=o().finally(()=>{p=void 0});try{d=await p}catch(t){throw s(`storage token could not be minted: ${t instanceof Error?t.message:String(t)}`)}return d.access_token},"bearer"),c=l(async(t,e,i={})=>{const _=[AbortSignal.timeout(i.timeoutMs??1e4),...i.signal?[i.signal]:[]];let n;try{n=await fetch(`${r.service_url}${e}`,{method:t,signal:AbortSignal.any(_),headers:{Authorization:`Bearer ${await k()}`,...i.body===void 0?{}:{"Content-Type":"application/json"}},...i.body===void 0?{}:{body:JSON.stringify(i.body)}})}catch(a){throw a instanceof b?a:s(`storage could not be reached: ${a instanceof Error?a.message:String(a)}`)}if(n.status===401&&(d=void 0),n.status===404||n.status===409){const a=await n.json().catch(()=>({})),g=a.error?.code??a.code??(n.status===404?"not_found":"not_uploaded");throw new m(n.status,g,a.error?.message??a.message??`storage answered ${n.status}`)}if(!n.ok)throw await n.body?.cancel().catch(()=>{}),s(`storage answered ${n.status} to ${t} ${e.split("?")[0]}`);return n},"call"),f=l(async t=>{try{return await t.json()}catch{throw s("storage answered with an invalid body")}},"json"),y=l(t=>encodeURIComponent(t),"id");return{config:r,runtimeId:u,async createUpload(t){const e=await f(await c("POST","/v1/uploads",{body:t}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async fetchUpload(t,e){const i=await c("GET",`/v1/uploads/${y(t)}/content`,{...e?{signal:e}:{},timeoutMs:11e4});if(!i.body)throw s("storage answered with no body");const _=i.headers.get("content-length");return{body:w.fromWeb(i.body),size:_===null?null:Number(_),media_type:i.headers.get("content-type")}},async signDownload(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/download-link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,expires_at:e.expires_at}},async deleteUpload(t){try{await c("DELETE",`/v1/uploads/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createShare(t){const e=await f(await c("POST","/v1/shares",{body:t}));if(typeof e.share_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string")throw s("storage answered with an invalid share");return{share_id:e.share_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at??null}},async deleteShare(t){try{await c("DELETE",`/v1/shares/${y(t)}`)}catch(e){if(!(e instanceof m&&e.status===404))throw e}},async createResultUpload(t){const e=await f(await c("POST","/v1/uploads",{body:{name:t.name,media_type:t.media_type,max_size:t.max_size}}));if(typeof e.upload_id!="string"||typeof e.url!="string"||typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload");return{upload_id:e.upload_id,url:e.url,upload_link:e.upload_link,expires_at:e.expires_at}},async signUploadLink(t){const e=await f(await c("POST",`/v1/uploads/${y(t)}/upload-link`));if(typeof e.upload_link!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid upload link");return{upload_link:e.upload_link,expires_at:e.expires_at}},async createOutbound(t){const e=await f(await c("POST","/v1/outbound",{body:t}));if(typeof e.object_id!="string"||typeof e.upload_link!="string"||typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid outbound object");return{object_id:e.object_id,upload_link:e.upload_link,url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async signOutbound(t){const e=await f(await c("POST",`/v1/outbound/${y(t)}/link`));if(typeof e.url!="string"||typeof e.expires_at!="string")throw s("storage answered with an invalid link");return{url:e.url,link_expires_at:e.link_expires_at,expires_at:e.expires_at}},async putFileBytes(t,e,i,_){const n=w.from(j(e,i));let a;try{a=await fetch(t,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":_,"Content-Length":String(i)},body:w.toWeb(n),duplex:"half"})}catch(g){throw s(`storage could not be reached: ${g instanceof Error?g.message:String(g)}`)}finally{n.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw s(`storage answered ${a.status} to the upload`)}}}l(A,"createStorageClient");function X(r){return!r||Buffer.byteLength(r,"utf8")>255?"name must be 1-255 bytes":r==="."||r===".."?"name must not be . or ..":/[/\\\u0000-\u001f\u007f]/.test(r)?"name must not contain /, \\, or control characters":null}l(X,"invalidStorageName");export{m as StorageRefused,W as UPLOAD_MAX_BYTES,A as createStorageClient,X as invalidStorageName,J as resetStorageClient,F as storageClient,U as storageConfig};
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import type { FileCaller } from '../spaces/permissions.js';
|
|
2
1
|
import { type FileRow } from './tables.js';
|
|
3
|
-
export declare const SHARE_SCOPE = "crtr:files:share";
|
|
4
2
|
export interface ShareView {
|
|
5
3
|
share_id: string;
|
|
6
4
|
url: string;
|
|
@@ -10,16 +8,6 @@ export interface ShareView {
|
|
|
10
8
|
expires_at: string | null;
|
|
11
9
|
status: 'on' | 'off';
|
|
12
10
|
}
|
|
13
|
-
/** `share.create {path}`: freeze a copy of a file the caller may read at a public URL. Without `crtr:files:share` only the caller's own app
|
|
14
|
-
* space may be shared. The row is inserted only once storage holds the bytes. */
|
|
15
|
-
export declare function createShare(caller: FileCaller, input: {
|
|
16
|
-
path: unknown;
|
|
17
|
-
expires_at?: unknown;
|
|
18
|
-
}): Promise<{
|
|
19
|
-
share_id: string;
|
|
20
|
-
url: string;
|
|
21
|
-
expires_at: string | null;
|
|
22
|
-
}>;
|
|
23
11
|
/** `share.create {file_id}` for a handed-over file: copy the stored object into a new share object, streaming it through this server without touching
|
|
24
12
|
* its disk. The caller has already checked the file is its own and complete. The row is inserted only once storage holds the bytes. */
|
|
25
13
|
export declare function createShareFromFile(file: FileRow, person: string | undefined, input: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var s=(e,t)=>h(e,"name",{value:t,configurable:!0});import{Readable as f}from"node:stream";import{RunError as o}from"../runs/operations.js";import{storageClient as c,StorageRefused as p}from"./client.js";import{getShare as l,insertShare as m,listShares as w,markShareObjectDeleted as b,turnShareOff as y}from"./tables.js";const _=s(e=>new o(503,"storage_unavailable",e,void 0,void 0,void 0,!0),"unavailable");async function S(e,t,i,n){let a;try{a=await fetch(e,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":n,"Content-Length":String(i)},body:f.toWeb(t),duplex:"half"})}catch(r){throw _(`storage could not be reached: ${r instanceof Error?r.message:String(r)}`)}finally{t.destroy()}if(await a.body?.cancel().catch(()=>{}),!a.ok)throw _(`storage answered ${a.status} to the share upload`)}s(S,"putStream");const g=s(e=>{if(e==null)return;const t=typeof e=="string"?Date.parse(e):NaN;if(!Number.isFinite(t))throw new o(400,"invalid_request","expires_at must be an ISO 8601 time","expires_at");if(t<=Date.now())throw new o(400,"invalid_request","expires_at must be in the future","expires_at");return new Date(t).toISOString()},"parseExpiry");async function z(e,t,i){const n=g(i.expires_at),a=c(),r=await a.createShare({name:e.name,media_type:e.media_type,size:e.size,...n?{expires_at:n}:{}});try{const d=await a.fetchUpload(e.file_id,AbortSignal.timeout(11e4));await S(r.upload_link,d.body,e.size,e.media_type)}catch(d){throw await a.deleteShare(r.share_id).catch(()=>{}),d instanceof p?new o(404,"not_found","file not found"):d}const u=r.expires_at??n??null;return await m({share_id:r.share_id,source_space:`file:${e.file_id}`,source_path:e.name,storage_key:`${a.runtimeId}/shares/${r.share_id}/${e.name}`,url:r.url,created_by:e.grantee,...t===void 0?{}:{sub:t},created_at:new Date().toISOString(),expires_at:u}),{share_id:r.share_id,url:r.url,expires_at:u}}s(z,"createShareFromFile");function x(e){return{share_id:e.share_id,url:e.url,source_path:e.source_path,created_by:e.created_by,created_at:e.created_at,expires_at:e.expires_at,status:e.status}}s(x,"view");async function A(e,t){return{shares:(await w(e)).filter(i=>t===void 0||i.sub===t).map(x)}}s(A,"listOwnShares");async function C(e,t,i){const n=await l(t);if(!n||n.created_by!==e||i!==void 0&&n.sub!==i)throw new o(404,"not_found","share not found");if(await y(t),!n.object_deleted_at)try{await c().deleteShare(t),await b(t)}catch(a){if(!(a instanceof o&&a.code==="storage_unavailable"))throw a}return{share_id:t,status:"off"}}s(C,"deleteOwnShare");export{z as createShareFromFile,C as deleteOwnShare,A as listOwnShares};
|
|
@@ -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
|
|
2
|
-
data: ${JSON.stringify(x(y,o,
|
|
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 ce}from"./handlers/docs.js";import{relationRoutes as de}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 ct(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(ct,"fixedRow");function dt(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(dt,"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:dt(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,c){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
|
|
2
|
+
data: ${JSON.stringify(x(y,o,c))}
|
|
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,
|
|
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,c)))}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 c of e){if(m+=c.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(c)}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}
|
|
5
5
|
event: ${e.type}
|
|
6
6
|
data: ${JSON.stringify(e)}
|
|
7
7
|
|
|
8
|
-
`}i(
|
|
8
|
+
`}i(pt,"frame");const ht=6e4;async function wt(e,n,o,m,c,y,A,S={},r){await L(m,o);let t=await W(o,c);if(c>t.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(c<t.latest_sequence&&(t.earliest_sequence===null||c<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":A==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),A==="sse"?n.write(`: connected
|
|
9
9
|
|
|
10
|
-
`):n.flushHeaders();let p=
|
|
10
|
+
`):n.flushHeaders();let p=c;const _=await ze().streamOpened(o);let v=!1,T=!1,N=!1,O;const h=new Promise(f=>{O=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(),O())},"end"),a=i(()=>{N=!1,b()},"onDrain"),H=i(f=>{v||n.write(A==="sse"?`event: error
|
|
11
11
|
data: ${JSON.stringify(x(f,y,o))}
|
|
12
12
|
|
|
13
13
|
`:`${JSON.stringify({type:"error",...x(f,y,o)})}
|
|
14
|
-
`),R()},"error"),b=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(A==="sse"?
|
|
14
|
+
`),R()},"error"),b=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(A==="sse"?pt(f):`${JSON.stringify(f)}
|
|
15
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(b)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&A==="sse"&&n.write(`: keepalive
|
|
16
16
|
|
|
17
|
-
`)},15e3),s=S.idleMs??
|
|
17
|
+
`)},15e3),s=S.idleMs??ht,w=S.isRunning??xe;let d=Date.now(),E=p;const k=i(async()=>{if(v||A!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==E){d=f,E=p;return}f-d<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}))},S.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(
|
|
20
|
+
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},S.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(wt,"streamRunEvents");function yt(e,n,o,m={}){const c=new V,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");c.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const A=new V().registerAll(oe).registerAll(ie).registerAll(ce).registerAll(le).registerAll(de).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()]),O=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(O!==null)throw O.status===400?new l(400,O.code,O.message,O.param):new l(426,O.code,O.message,void 0,O.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(r,t,h,e);return}const R=c.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 b,P;if(p!==void 0)b=p;else if(!H&&r.headers.authorization!==void 0)try{b=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(b?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,b);return}if(b===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(b===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(b,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=A.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 d;try{d=await s.handler(w)}catch(E){const{status:k,body:M}=ae(E);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,E),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(d.rawBody!==void 0||d.status===204||d.body===void 0){t.writeHead(d.status,d.headers??{}),t.end(d.rawBody);return}t.writeHead(d.status,{"Content-Type":"application/json; charset=utf-8",...d.headers??{}}),t.end(JSON.stringify(d.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,d=i(()=>w.abort(),"abort");t.on("close",d);try{const E=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)}
|
|
21
21
|
|
|
22
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]
|
|
23
23
|
|
|
24
|
-
`)):g(t,200,E.completion)}finally{t.off("close",
|
|
24
|
+
`)):g(t,200,E.completion)}finally{t.off("close",d)}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 d=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,d.status,d.body)}catch(d){const E=ut(d,_,!0);t.writeHead(E.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...E.headers}),t.end(JSON.stringify(E.body))}finally{w()}return}if(nt.has(a.name)){const s=await tt(a.name,{class:"app",app:u.grantee,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 c=e.listener;if(!e.issuer||!e.audience||!c?.address||!Number.isInteger(c.port)||c.port<1||c.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(c.address))throw new Error("runtime listener must bind a specific address");const y=new Oe(e.issuer,e.audience,o,e.jwksUrl),A=yt(y,n,o,m),S=ne((t,p)=>{A(t,p)});return{ready:new Promise((t,p)=>{S.once("error",p),S.listen(c.port,c.address,()=>{S.off("error",p),t()})}),close:i(async()=>{y.close(),$e(),S.closeAllConnections(),await new Promise((t,p)=>S.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};
|
|
@@ -4,6 +4,8 @@ export declare function environmentOfNode(profileId: string | null): Promise<str
|
|
|
4
4
|
/** SQL predicate over `environments`: the recipe has content (a repository, a setup script or pi packages). A recipe cleared back to nothing
|
|
5
5
|
* has none, whatever its `recipe_revision` counter says: the counter only orders edits, it does not say whether a recipe exists. */
|
|
6
6
|
export declare const RECIPE_HAS_CONTENT_SQL = "(btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''\n OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object))";
|
|
7
|
+
/** The packages token (`CRTR_PACKAGES_TOKEN`) when `environmentId` is a dev environment whose every repository is under Northlight-Systems and the process holds the token; else null. */
|
|
8
|
+
export declare function packagesTokenFor(environmentId: string): Promise<string | null>;
|
|
7
9
|
/** The environment's recipe; null when it has no content (no repositories, no setup script, no packages). One statement, so the revision,
|
|
8
10
|
* script, packages and repositories all come from one snapshot, never from either side of a concurrent `setEnvironmentRecipe`. */
|
|
9
11
|
export declare function recipeOf(environmentId: string): Promise<StartBundleRecipeDTO | null>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object))
|
|
1
|
+
var E=Object.defineProperty;var r=(n,e)=>E(n,"name",{value:e,configurable:!0});import{ApiError as u}from"../../api/errors.js";import{openDb as o}from"../../core/canvas/db.js";import{machineEnvironmentId as p}from"../../core/environments.js";async function c(n){return n===null?p():(await(await o()).prepare("SELECT environment_id FROM profiles WHERE id = ?").get(n))?.environment_id??p()}r(c,"environmentOfNode");const _=`(btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''
|
|
2
|
+
OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object))`,m="northlight-systems/";async function R(n){const e=process.env.CRTR_PACKAGES_TOKEN;if(e===void 0||e==="")return null;const t=await(await o()).prepare("SELECT github_full_name FROM environment_repos WHERE environment = ?").all(n);return t.length>0&&t.every(i=>i.github_full_name.toLowerCase().startsWith(m))?e:null}r(R,"packagesTokenFor");async function l(n){const e=await(await o()).prepare(`SELECT recipe_revision, setup_script, pi_packages, ${_} AS has_content,
|
|
3
3
|
(SELECT COALESCE(json_agg(json_build_object('name', r.name, 'github_full_name', r.github_full_name, 'default_branch', r.default_branch) ORDER BY r.position), '[]'::json)
|
|
4
4
|
FROM environment_repos r WHERE r.environment = environments.object) AS repositories
|
|
5
|
-
FROM environments WHERE object = ?`).get(n);return e===void 0||!e.has_content?null:{revision:Number(e.recipe_revision),repositories:JSON.parse(e.repositories),setup_script:e.setup_script,pi_packages:e.pi_packages}}r(
|
|
5
|
+
FROM environments WHERE object = ?`).get(n);return e===void 0||!e.has_content?null:{revision:Number(e.recipe_revision),repositories:JSON.parse(e.repositories),setup_script:e.setup_script,pi_packages:e.pi_packages}}r(l,"recipeOf");async function O(n){return(await(await o()).prepare("SELECT kind FROM environments WHERE object = ?").get(await c(n)))?.kind==="blaxel"}r(O,"runsOnBlaxel");async function h(n,e,t,i){const s=((await l(await c(n)))?.repositories??[]).find(a=>e===`/work/${a.name}`||e.startsWith(`/work/${a.name}/`));if(s===void 0)throw new u(400,"invalid_request",`--worktree needs a cwd inside one of the environment's repositories under /work, not ${e}`,{param:"worktree"});return{repository:s.name,branch:`crtr/${t}`,base:i??s.default_branch}}r(h,"sandboxWorktreeRequest");export{_ as RECIPE_HAS_CONTENT_SQL,c as environmentOfNode,R as packagesTokenFor,l as recipeOf,O as runsOnBlaxel,h as sandboxWorktreeRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var t=(r,o)=>a(r,"name",{value:o,configurable:!0});import{covers as m}from"@north-light/identity";import{ensureAppProfile as l,listProfiles as d}from"../../../core/profiles/manifest.js";import{resolveRunKind as u}from"../../../core/runtime/launch-target.js";import{repositoriesByProfile as c}from"../../../core/environment-repos.js";async function _(r){const o=await c(),p=(await l(r.grantee)).profileId;return{profiles:d().filter(({profileId:e,manifest:s})=>{const i=s.grantee??"app:terminal";if(i===r.grantee)return!0;const f=`crtr:memory:rw:${i}:profile:${e}`;return r.resolved.some(n=>m(n,f))}).map(e=>({profile_id:e.profileId,name:e.manifest.name,grantee:e.manifest.grantee??"app:terminal",default_kind:u(e),default:e.profileId===p,repositories:o.get(e.profileId)??[]}))}}t(_,"listAppProfiles");export{_ as listAppProfiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var n=(t,e)=>k(t,"name",{value:e,configurable:!0});import{getNode as p}from"../../../core/canvas/canvas.js";import{decideAttachRevive as b}from"../../../core/runtime/revive.js";import{viewSocketPath as y}from"../../../core/canvas/paths.js";import{waitForBrokerViewSocket as P}from"../../../core/runtime/placement-tmux.js";import{waitForWssView as x}from"../../../core/runtime/view-socket.js";import{liveExecutionForNode as A}from"../../../core/canvas/executions.js";import{runnerForExecution as F}from"../../../core/runtime/runner/index.js";import{waitForMachineView as N}from"../../machine-link/forward.js";import{general as w,notFound as l,usage as u}from"../../../core/errors.js";import{mayOnNode as d,ownerOnly as _}from"../router.js";const h=3e4;function g(t){if(t==null)return{resume:!0,revive:!0,wakeParked:!0};if(typeof t!="object")throw u("attach body must be a JSON object { resume?, revive?, wakeParked? }");const e=t.resume,r=t.revive,i=t.wakeParked;if(e!==void 0&&typeof e!="boolean")throw u("resume must be a boolean");if(r!==void 0&&typeof r!="boolean")throw u("revive must be a boolean");if(i!==void 0&&typeof i!="boolean")throw u("wakeParked must be a boolean");return{resume:e??!0,revive:r??!0,wakeParked:i??!0}}n(g,"parseAttachBody");async function S(t,e,r){return e==="controller"?await d(t,"message",r):await d(t,"read",r)?!0:e==="either"&&await d(t,"message",r)}n(S,"mayAttachNode");async function E(t){const e=t.params.id;if(await p(e)===null)throw l(`unknown node: ${e}`,{received:e});if(!await S(t.principal,"either",e))throw l(`unknown node: ${e}`,{received:e});const{resume:r,revive:i,wakeParked:v}=g(t.body);let c=!1,f=!1,m=!1;if(i){const a=await b(e,{resume:r,capacity:"refuse"},v);if(m=a.parked,!a.parked){c=a.result.launch!==void 0,f=a.result.resumed;const s=await A(e),o=s===null?null:await F(s.runner).viewerAddress(s);if(o===null||o.kind==="unix")await P(e);else if(o.kind==="machine"){if(!await N(o.environmentId,e,a.result.launch?.exited,h))throw w(`the broker for ${e} on its machine did not accept a viewer after revive`)}else if(!await x(o.url,o.headers,a.result.launch?.exited,h))throw w(`the sandboxed broker for ${e} did not accept a viewer after revive`)}}return{status:200,body:{node_id:e,socket_path:y(e),revived:c,resumed:f,parked:m}}}n(E,"handleAttach");const J=_([{method:"POST",pattern:"/v1/nodes/:id/attach",handler:E}]);export{J as attachRoutes,S as mayAttachNode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var _=Object.defineProperty;var t=(r,i)=>_(r,"name",{value:i,configurable:!0});import{openDb as p}from"../../../core/canvas/db.js";import{ApiError as l}from"../../../api/errors.js";import{usage as m}from"../../../core/errors.js";import{personId as v}from"../../../core/canvas/person-state.js";import{patchEnvironment as g}from"../../../core/environment-recipe.js";import{resolveRecipeRepositories as b}from"../../../core/environment-repos.js";import{requireUsableProfile as w}from"./profiles.js";async function u(r){const{profileId:i,manifest:n}=await w(r,r.params.name),e=n.environment_id,o=e===void 0?void 0:await(await p()).prepare("SELECT kind FROM environments WHERE object = ?").get(e);if(e===void 0||o?.kind!=="blaxel")throw new l(400,"invalid_request",`profile ${i} does not run in a cloud environment`);return{profileId:i,environmentId:e}}t(u,"requireBlaxelEnvironment");async function d(r,i){const n=await p(),e=await n.prepare("SELECT setup_script, pi_packages, memory_mb, recipe_revision, image_revision, image_error FROM environments WHERE object = ?").get(i),o=await n.prepare("SELECT github_full_name AS full FROM environment_repos WHERE environment = ? ORDER BY position").all(i);return{profile_id:r,environment_id:i,repositories:o.map(s=>s.full),setup_script:e.setup_script,pi_packages:e.pi_packages,memory_mb:Number(e.memory_mb),recipe_revision:Number(e.recipe_revision),image_revision:e.image_revision===null?null:Number(e.image_revision),image_error:e.image_error}}t(d,"readEnvironment");async function y(r){const{profileId:i,environmentId:n}=await u(r);return{status:200,body:await d(i,n)}}t(y,"handleGet");function c(r,i){if(r==null||typeof r=="string")return r;throw m(`${i} must be a string or null`,{field:i})}t(c,"optionalText");async function E(r){const{profileId:i,environmentId:n}=await u(r),e=r.body??{};if(e.repositories!==void 0&&(!Array.isArray(e.repositories)||e.repositories.some(f=>typeof f!="string")))throw m("repositories must be an array of owner/name strings",{field:"repositories"});const o=c(e.setup_script,"setup_script"),s=c(e.pi_packages,"pi_packages"),a=e.repositories===void 0?void 0:await b(v(),e.repositories);return await g(n,{...a!==void 0?{repositories:a}:{},...o!==void 0?{setup_script:o}:{},...s!==void 0?{pi_packages:s}:{},...e.memory_mb!==void 0?{memory_mb:e.memory_mb}:{}}),{status:200,body:await d(i,n)}}t(E,"handleSet");const O=[{method:"GET",pattern:"/v1/profiles/:name/environment",handler:y},{method:"PUT",pattern:"/v1/profiles/:name/environment",handler:E}];export{O as environmentRoutes};
|