@north-light/cli 0.3.665 → 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/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/runs/operations.js +7 -7
- 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/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.js +1 -1
- 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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{readFileSync as g}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as c}from"../api-client.js";import{resolveProfileViaDaemon as l}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},u=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function f(e){const{environment_id:r,...i}=e;return i}t(f,"output");const w=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...u],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:t(async e=>{const{id:r}=await l(e.profile);return f(await c().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages or memory",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...u],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:t(async e=>{const{id:r}=await l(e.profile),i=e.repo,s=e.setupScriptFile,o=e.piPackage,n=e.memory;if(n!==void 0&&![2,4,8].includes(n))throw m("`--memory` is 2, 4 or 8 (GB).");const a={...i!==void 0&&i.length>0?{repositories:i}:{},...s!==void 0?{setup_script:g(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
|
|
2
|
+
`)}:{},...n!==void 0?{memory_mb:n*1024}:{}};if(Object.keys(a).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`.");return f(await c().setProfileEnvironment(r,a))},"run")}),R=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[w,v]});export{R as environmentBranch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var n=(e,t)=>f(e,"name",{value:t,configurable:!0});import{defineLeaf as c}from"../../core/command.js";import{usage as s}from"../../core/errors.js";import{resolve as u}from"node:path";import{cliClient as d}from"../api-client.js";import{resolveMetaPairs as h}from"./meta.js";const k=c({name:"new",description:"create a new profile",whenToUse:"you are establishing a new agent identity \u2014 a stable id, a display name, and its own documents (a profile owns documents like any other owner). Pass at most one initial project directory here (the parser has no repeatable-flag support); use `profile project add` afterward for every additional one. Use `--root` (no name) to provision the canonical stable root profile \u2014 the default identity a home falls back to \u2014 idempotently, without spawning a node.",help:{name:"profile new",summary:"create a profile of the caller's app in the scoped store, with its own app directory",params:[{kind:"flag",name:"name",type:"string",required:!1,constraint:"Display name for the profile. Also slugified into the stable profile id \u2014 the id never changes on later rename. Required unless `--root` is given; mutually exclusive with `--root`."},{kind:"flag",name:"root",type:"bool",required:!1,constraint:"Provision the canonical stable root profile (fixed id `root-00000000`, name `root`) \u2014 the fallback default identity for a home \u2014 instead of a fresh named one. Idempotent: re-running returns the existing root. Node-free (no `node new --root` needed). Mutually exclusive with `--name`/`--project`/`--repo`/`--default-kind`/`--meta`."},{kind:"flag",name:"project",type:"path",required:!1,constraint:"One initial project directory. Must already exist and be a directory; resolved to its absolute real path before storing. Creates a purview relationship: the repos enclosing it join the view of every node of the profile, with no delivery limit (`profile project add` starts them at `preview`). Singular \u2014 add more with `crtr profile project add` after creation."},{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository). Makes a cloud dev profile: a Blaxel sandbox environment with 4096 MB whose recipe checks out these repositories at `/work/<name>`. Cloud only; mutually exclusive with `--project`. The GitHub App must be installed on each repository."},{kind:"flag",name:"default-kind",type:"string",required:!1,constraint:"Installed persona kind for node creates under this profile that omit --kind. Defaults to general when omitted; the daemon validates it against its installed kind registry."},{kind:"flag",name:"meta",type:"string",required:!1,repeatable:!0,constraint:"KEY=VALUE metadata entry (repeat per entry). KEY starts with a letter or digit, followed by letters, digits, `_`, or `-`. Each entry reaches every broker launched under the profile as `CRTR_PROFILE_META_<KEY>` env; readable back via `profile show` \u2014 not for secrets (those go to `profile env`)."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id (`<slug>-<shortid>`). Pass this, or the name, to every other `profile` verb and to `--profile` elsewhere."},{name:"profile_path",type:"string",required:!0,constraint:"Absolute path to the profile directory, `<app space>/profiles/<id>`: its settings root. Documents the profile owns are canvas documents, read with `crtr canvas read`, not files here."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"Explicit `{path}` project relationships in manifest order. `path` defines purview and puts the repos enclosing it in the view of every node of the profile. Empty when --project was omitted."},{name:"app",type:"string",required:!0,constraint:"The app that owns this profile."},{name:"default_kind",type:"string",required:!0,constraint:"Default persona kind for node creates that omit --kind; `general` when none is stored."},{name:"metadata",type:"object",required:!0,constraint:"Stored metadata map; empty when --meta was omitted."},{name:"created_at",type:"string",required:!0,constraint:"ISO 8601 creation timestamp."}],outputKind:"object",effects:["Creates a profile row owned by the caller's app (the terminal app for a person) and its directory under that app's space. A name the caller's app already holds is refused."]},run:n(async e=>{const t=e.name,r=e.project,a=e.defaultKind,i=h(e.meta,"meta"),p=e.root===!0,o=e.repo??[];if(p){if(t!==void 0||r!==void 0||o.length>0||a!==void 0||Object.keys(i).length>0)throw s("`--root` provisions the canonical stable root profile and takes no `--name`/`--project`/`--repo`/`--default-kind`/`--meta`.");return l(await d().ensureProfile("root"))}if(o.length>0&&r!==void 0)throw s("`--repo` and `--project` are mutually exclusive: a dev profile works in sandbox checkouts, not local directories.");if(t===void 0)throw s("provide `--name <name>` to create a profile, or `--root` to provision the stable root profile.");return l(await d().createProfile({name:t,...r!==void 0?{projects:[{path:u(r)}]}:{},...o.length>0?{repositories:o}:{},...a!==void 0?{default_kind:a}:{},...Object.keys(i).length>0?{metadata:i}:{}}))},"run")});function l(e){return{profile_id:e.id,profile_path:e.profile_path,projects:e.projects,app:e.app,default_kind:e.default_kind,metadata:e.metadata,created_at:e.created_at}}n(l,"newProfileOutput");export{k as newLeaf};
|
package/dist/commands/profile.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var e=(r,o)=>t(r,"name",{value:o,configurable:!0});import{defineBranch as n}from"../core/command.js";import{newLeaf as i}from"./profile/new.js";import{listLeaf as a}from"./profile/list.js";import{showLeaf as s}from"./profile/show.js";import{renameLeaf as d}from"./profile/rename.js";import{deleteLeaf as l}from"./profile/delete.js";import{pauseLeaf as p,resumeLeaf as c}from"./profile/pause.js";import{kindLeaf as f}from"./profile/kind.js";import{metaLeaf as m}from"./profile/meta.js";import{projectBranch as h}from"./profile/project.js";import{defaultBranch as u}from"./profile/default.js";import{envBranch as w}from"./profile/env.js";function
|
|
1
|
+
var t=Object.defineProperty;var e=(r,o)=>t(r,"name",{value:o,configurable:!0});import{defineBranch as n}from"../core/command.js";import{newLeaf as i}from"./profile/new.js";import{listLeaf as a}from"./profile/list.js";import{showLeaf as s}from"./profile/show.js";import{renameLeaf as d}from"./profile/rename.js";import{deleteLeaf as l}from"./profile/delete.js";import{pauseLeaf as p,resumeLeaf as c}from"./profile/pause.js";import{kindLeaf as f}from"./profile/kind.js";import{metaLeaf as m}from"./profile/meta.js";import{projectBranch as h}from"./profile/project.js";import{defaultBranch as u}from"./profile/default.js";import{envBranch as w}from"./profile/env.js";import{environmentBranch as g}from"./profile/environment.js";function O(){return n({name:"profile",rootEntry:{concept:"an agent identity defined at the user root \u2014 a scoped-state row naming project directories; it also owns documents",desc:"create, inspect, and manage profiles",useWhen:"creating a new agent identity, inspecting or listing existing ones, changing a profile\u2019s project purview, pinning which profile a directory defaults to at startup, or managing a profile\u2019s stored env vars. Selecting a profile for a one-off run (`--profile`) lives elsewhere."},help:{name:"profile",summary:"create, inspect, and manage profiles \u2014 agent identities that own documents and have their own project purview",model:"A node\u2019s app owns its home; the profile does not select it. A node lands in the directory it was launched from when there is one: `node new --cwd`, an inherited spawner directory (notably inside a managed worktree), or the directory a root was started in. So one profile can cover many working directories \u2014 cwd selects the identity, and the launch decides where the work happens. `new` creates one from a name (+ at most one initial `--project`). `list` inventories every profile as JSONL. `show` prints one profile definition in full. `rename` changes only the profile name \u2014 the profile_id is stable across a rename. `delete --force` removes the profile after cascading through its nodes, matching schedules, originating inbox/review state, and default pins; `--detach --force` instead preserves nodes and human history while clearing the profile identity and globalizing its schedules. Both modes block while a matching node owns an open managed worktree and never touch the project directories the profile pointed at. `project` widens/narrows a profile\u2019s project purview (the dirs it resolves repo documents + config from). `default` pins which profile a directory defaults to at startup so the chooser stops asking \u2014 directory-scoped, independent of purview. `env` manages a profile-scoped 0600 store of env vars injected directly into every broker launched under that profile \u2014 set on stdin, list names only (never values), or remove one; no `spawnEnv.allow` entry needed. `meta` edits the profile\u2019s readable metadata map \u2014 identity facts each broker under the profile sees as `CRTR_PROFILE_META_<KEY>` env (secrets stay in `env`). Every manifest verb but `new`/`list` takes <profile> as an exact id, a profile name, or a close-enough name that resolves to the nearest profile (reported on stderr); a name shared by several profiles, or one equally close to several, fails listing every matching id. `delete` alone never guesses \u2014 an irreversible verb requires an exact id or name."},children:[i,a,s,d,p,c,f,m,l,h,u,w,g]})}e(O,"registerProfile");export{O as registerProfile};
|
|
@@ -1,15 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}>;
|
|
7
|
-
setup_script: string | null;
|
|
8
|
-
/** pi package sources, one per line. */
|
|
9
|
-
pi_packages: string | null;
|
|
10
|
-
}
|
|
1
|
+
/** The writer of an environment's recipe (repositories, pi packages, setup script). A changed recipe raises `recipe_revision` by one, which is
|
|
2
|
+
* what the `recipe-image` lane builds an image for (D25); an unchanged recipe writes nothing and keeps its revision. */
|
|
3
|
+
import type { EnvironmentRecipeInput } from '../api/dto/profiles.js';
|
|
4
|
+
import { type CanvasDb } from './canvas/db.js';
|
|
5
|
+
export type { EnvironmentRecipeInput };
|
|
11
6
|
/** Replaces the recipe of a cloud environment. Returns the recipe revision after the write and whether it changed. */
|
|
12
7
|
export declare function setEnvironmentRecipe(environmentId: string, recipe: EnvironmentRecipeInput): Promise<{
|
|
13
8
|
revision: number;
|
|
14
9
|
changed: boolean;
|
|
15
10
|
}>;
|
|
11
|
+
/** {@link setEnvironmentRecipe} inside a write the caller already holds, so a recipe can commit with the rows it belongs to. */
|
|
12
|
+
export declare function writeEnvironmentRecipe(db: CanvasDb, environmentId: string, recipe: EnvironmentRecipeInput): Promise<{
|
|
13
|
+
revision: number;
|
|
14
|
+
changed: boolean;
|
|
15
|
+
}>;
|
|
16
|
+
/** Memory sizes a cloud environment's sandboxes may have. Billing reads the chosen value (`ledger-sandbox`). */
|
|
17
|
+
export declare const ENVIRONMENT_MEMORY_MB: readonly [2048, 4096, 8192];
|
|
18
|
+
/** Changes the given fields of a cloud environment's recipe and memory in one write; a field left out keeps its value. The row is locked before
|
|
19
|
+
* the current values are read, so concurrent changes to different fields both land. Memory reaches sandboxes created after this call. */
|
|
20
|
+
export declare function patchEnvironment(environmentId: string, patch: {
|
|
21
|
+
repositories?: EnvironmentRecipeInput['repositories'];
|
|
22
|
+
setup_script?: string | null;
|
|
23
|
+
pi_packages?: string | null;
|
|
24
|
+
memory_mb?: number;
|
|
25
|
+
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var s=(i,e)=>f(i,"name",{value:e,configurable:!0});import{usage as l}from"./errors.js";import{withCanvasWrite as m}from"./canvas/db.js";async function d(i,e){return await m(n=>_(n,i,e))}s(d,"setEnvironmentRecipe");async function _(i,e,n){const o=new Set;for(const r of n.repositories){if(!/^[A-Za-z0-9._-]+$/.test(r.name)||r.name==="."||r.name==="..")throw new Error(`repository name ${JSON.stringify(r.name)} is not a plain directory name`);if(o.has(r.name))throw new Error(`repository name ${r.name} appears twice in the recipe`);o.add(r.name)}{const r=await i.prepare("SELECT kind, recipe_revision, setup_script, pi_packages FROM environments WHERE object = ? FOR UPDATE").get(e);if(r===void 0)throw new Error(`no environment ${e}`);if(r.kind!=="blaxel")throw new Error(`environment ${e} is a ${r.kind} environment; only a cloud (blaxel) environment has a recipe image`);const p=await i.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(e);if(r.setup_script===n.setup_script&&r.pi_packages===n.pi_packages&&p.length===n.repositories.length&&p.every((a,t)=>a.name===n.repositories[t].name&&a.github_full_name===n.repositories[t].github_full_name&&a.default_branch===n.repositories[t].default_branch))return{revision:Number(r.recipe_revision),changed:!1};await i.prepare("DELETE FROM environment_repos WHERE environment = ?").run(e);const c=i.prepare("INSERT INTO environment_repos (environment, position, name, github_full_name, default_branch) VALUES (?, ?, ?, ?, ?)");for(const[a,t]of n.repositories.entries())await c.run(e,a,t.name,t.github_full_name,t.default_branch);const E=await i.prepare("UPDATE environments SET setup_script = ?, pi_packages = ?, recipe_revision = recipe_revision + 1 WHERE object = ? RETURNING recipe_revision").get(n.setup_script,n.pi_packages,e);return{revision:Number(E.recipe_revision),changed:!0}}}s(_,"writeEnvironmentRecipe");const u=[2048,4096,8192];async function v(i,e){if(e.memory_mb!==void 0&&!u.includes(e.memory_mb))throw l(`memory_mb must be one of ${u.join(", ")}`,{field:"memory_mb"});await m(async n=>{const o=await n.prepare("SELECT setup_script, pi_packages FROM environments WHERE object = ? AND kind = 'blaxel' FOR UPDATE").get(i);if(o===void 0)throw new Error(`no cloud environment ${i}`);if(e.repositories!==void 0||e.setup_script!==void 0||e.pi_packages!==void 0){const r=e.repositories??await n.prepare("SELECT name, github_full_name, default_branch FROM environment_repos WHERE environment = ? ORDER BY position").all(i);await _(n,i,{repositories:r,setup_script:e.setup_script===void 0?o.setup_script:e.setup_script,pi_packages:e.pi_packages===void 0?o.pi_packages:e.pi_packages})}e.memory_mb!==void 0&&await n.prepare("UPDATE environments SET memory_mb = ? WHERE object = ?").run(e.memory_mb,i)})}s(v,"patchEnvironment");export{u as ENVIRONMENT_MEMORY_MB,v as patchEnvironment,d as setEnvironmentRecipe,_ as writeEnvironmentRecipe};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { EnvironmentRecipeInput } from './environment-recipe.js';
|
|
2
|
+
/** Turns `owner/name` requests into recipe repositories: one token minted for all of them (a repository outside the App, or across installations,
|
|
3
|
+
* is refused with the mint's own 409), then each repository's `default_branch` read from GitHub with it. The mint is write-scoped; this read
|
|
4
|
+
* reuses it on purpose, because the same repositories are minted for at every sandbox start. */
|
|
5
|
+
export declare function resolveRecipeRepositories(sub: string, fullNames: string[]): Promise<EnvironmentRecipeInput['repositories']>;
|
|
6
|
+
/** Recipe repositories (`owner/name`, in position order) of every profile whose environment has any; a profile with none is absent. */
|
|
7
|
+
export declare function repositoriesByProfile(): Promise<Map<string, string[]>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var f=(r,t)=>c(r,"name",{value:t,configurable:!0});import{ApiError as i}from"../api/errors.js";import{openDb as h}from"./canvas/db.js";import{mintInstallationToken as l}from"../daemon/api/handlers/git-credential.js";const w=/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\/[A-Za-z0-9._-]+$/;async function g(r,t){for(const e of t)if(!w.test(e))throw new i(400,"invalid_request",`repository ${JSON.stringify(e)} is not of the form owner/name`);if(new Set(t.map(e=>e.toLowerCase())).size!==t.length)throw new i(400,"invalid_request","a repository is listed twice");const o=t.map(e=>e.split("/")[1]);if(new Set(o).size!==o.length)throw new i(400,"invalid_request","two repositories share a name; each is checked out at /work/<name>");if(t.length===0)return[];const{token:s}=await l(r,t),u=[];for(const[e,a]of t.entries()){const n=await fetch(`https://api.github.com/repos/${a}`,{headers:{authorization:`Bearer ${s}`,accept:"application/vnd.github+json","user-agent":"crouter","x-github-api-version":"2022-11-28"}});if(!n.ok)throw new i(n.status===404?404:502,n.status===404?"repository_not_found":"github_failed",`GitHub answered ${n.status} for repository ${a}`);const p=await n.json();if(typeof p.default_branch!="string"||p.default_branch==="")throw new i(502,"github_failed",`GitHub returned no default branch for ${a}`);u.push({name:o[e],github_full_name:a,default_branch:p.default_branch})}return u}f(g,"resolveRecipeRepositories");async function y(){const r=await(await h()).prepare("SELECT p.id AS profile, r.github_full_name AS full FROM profiles p JOIN environment_repos r ON r.environment = p.environment_id ORDER BY p.id, r.position").all(),t=new Map;for(const{profile:o,full:s}of r)t.set(o,[...t.get(o)??[],s]);return t}f(y,"repositoriesByProfile");export{y as repositoriesByProfile,g as resolveRecipeRepositories};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CanvasDb } from './canvas/db.js';
|
|
2
|
+
import { type EnvironmentRecipeInput } from './environment-recipe.js';
|
|
2
3
|
/** Find the `environments` row for `installId`, or create its object and row; either way set `last_seen_at`, and cache
|
|
3
4
|
* the environment id and install id for {@link machineEnvironmentId} and {@link touchMachineEnvironment}. */
|
|
4
5
|
export declare function registerMachineEnvironment(installId: string): Promise<{
|
|
@@ -6,7 +7,7 @@ export declare function registerMachineEnvironment(installId: string): Promise<{
|
|
|
6
7
|
created: boolean;
|
|
7
8
|
}>;
|
|
8
9
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
9
|
-
* its `environments` row with the
|
|
10
|
+
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
10
11
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
11
12
|
* here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
|
|
12
13
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
@@ -14,6 +15,8 @@ export declare function createProfileBlaxelEnvironment(db: CanvasDb, spec: {
|
|
|
14
15
|
profileId: string;
|
|
15
16
|
grantee: string;
|
|
16
17
|
person: string;
|
|
18
|
+
memoryMb?: number;
|
|
19
|
+
recipe?: EnvironmentRecipeInput;
|
|
17
20
|
}): Promise<string>;
|
|
18
21
|
/** Stamp `last_seen_at` on the machine environment: one statement, no read. A no-op before {@link registerMachineEnvironment}. */
|
|
19
22
|
export declare function touchMachineEnvironment(now: string): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var a=(e,n)=>f(e,"name",{value:n,configurable:!0});import{openDb as l,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as u,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as I}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async i=>{const r=await i.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(r!==void 0)return await i.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:r.object,created:!1};const d=await w(i,"app:terminal"),m=await p(i,{type:"environment",kind:"machine",owner:d.id,privacy:"public",name:e,preview:"machine"});return v()||await s(i,m.id,await E()),await i.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function _(e,n){const t=await w(e,n.grantee),i=await u(e,"profile","profile",n.profileId,n.profileId,t),r=await p(e,{type:"environment",kind:"blaxel",owner:i.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,r.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, last_seen_at) VALUES (?, 'blaxel', NULL, ?, ?)").run(r.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,r.id,n.recipe),r.id}a(_,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await l()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),I((e,n)=>c(async t=>{await n(await _(t,e))}));export{_ as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProfileManifest } from '../../types.js';
|
|
2
|
-
import type { DeliveryLimits, ProfileProject, ProfileProjectMemory } from '../../api/dto/profiles.js';
|
|
2
|
+
import type { DeliveryLimits, EnvironmentRecipeInput, ProfileProject, ProfileProjectMemory } from '../../api/dto/profiles.js';
|
|
3
3
|
export declare const ROOT_PROFILE_ID = "root-00000000";
|
|
4
4
|
export declare function profileDir(profileId: string): string;
|
|
5
5
|
export declare function assertProfileProjects(entries: unknown): asserts entries is ProfileProject[];
|
|
@@ -62,6 +62,8 @@ export type CloudProfileWriter = (spec: {
|
|
|
62
62
|
profileId: string;
|
|
63
63
|
grantee: string;
|
|
64
64
|
person: string;
|
|
65
|
+
memoryMb?: number;
|
|
66
|
+
recipe?: EnvironmentRecipeInput;
|
|
65
67
|
}, insert: (environmentId: string) => Promise<void>) => Promise<void>;
|
|
66
68
|
export declare function setCloudProfileWriter(writer: CloudProfileWriter): void;
|
|
67
69
|
export declare function ensureRootProfile(): Promise<ProfileEntry>;
|
|
@@ -82,6 +84,10 @@ export declare function createProfile(name: string, projects?: ProfileProject[],
|
|
|
82
84
|
defaultKind?: string;
|
|
83
85
|
metadata?: Record<string, string>;
|
|
84
86
|
grantee?: string;
|
|
87
|
+
/** Memory of the cloud environment created with the profile; ignored off a cloud role. */
|
|
88
|
+
memoryMb?: number;
|
|
89
|
+
/** Recipe written with the cloud environment, in the same write as the profile row. */
|
|
90
|
+
recipe?: EnvironmentRecipeInput;
|
|
85
91
|
}): Promise<ProfileEntry>;
|
|
86
92
|
export declare function ensureAppProfile(grantee: string): Promise<ProfileEntry>;
|
|
87
93
|
export declare function updateProfileLastUsed(profileId: string): Promise<ProfileEntry>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var W=Object.defineProperty;var i=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as V,realpathSync as E,rmSync as S,statSync as Y}from"node:fs";import{resolve as O}from"node:path";import{SCHEMA_VERSION as R}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as M}from"../../api/dto/profiles.js";import{ensureDir as G,nowIso as h}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 l,notFound as u,ambiguous as k,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as C,personId as te}from"../canvas/person-state.js";const P=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,m="root-00000000",$="root";function y(e){return e.grantee??"app:terminal"}i(y,"profileApp");function x(e,t){G(g(y(t),e).dir)}i(x,"scaffoldProfile");function _(e){if(!P.test(e))throw l(`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."})}i(_,"assertSafeProfileId");function _e(e){_(e);const t=p(e);if(t===null)throw u(`profile not found: ${e}`,{received:e});return g(y(t.manifest),e).dir}i(_e,"profileDir");function D(e){if(!Array.isArray(e))throw l("projects must be an array of {path} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"}.'});const{path:r}=t;if(typeof r!="string"||r.trim()==="")throw l(`project entry has no path: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a non-empty directory path."})}}i(D,"assertProfileProjects");function re(e){const t=M.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw l("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[r,n]of Object.entries(e)){if(r.trim()==="")throw l("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 n!="string"||!M.includes(n))throw l(`invalid delivery limit for ${r}: ${JSON.stringify(n)}`,{received:String(n),field:"delivery_limits",next:`Set ${r} to one of: ${t}.`})}}i(re,"assertDeliveryLimits");function ne(){return{entries:X(),unreadableIds:[]}}i(ne,"enumerateProfiles");function v(){return ne().entries}i(v,"listProfiles");function ie(e){const t=v(),r=N(t,e,j);return r?{kind:"resolved",entry:r}:{kind:"absent"}}i(ie,"lookupProfile");function L(e){_(e);const t=p(e);if(t!==null)return t;throw u(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}i(L,"loadExactProfileManifest");const j=i(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function N(e,t,r){if(P.test(t)){const o=e.find(a=>r(a).profileId===t);if(o!==void 0)return o}const n=e.filter(o=>r(o).name===t);if(n.length===1)return n[0];if(n.length>1){const o=n.map(a=>r(a).profileId);throw k(`profile name "${t}" matches ${o.length} profiles: ${o.join(", ")}`,{received:t,candidates:o,next:`Re-run with one exact profile id: ${o.join(", ")}.`})}return null}i(N,"findExactProfile");function z(e,t,r){const n=e.map(o=>`${r(o).profileId} (${r(o).name})`);return u(`profile not found: ${t}`,{received:t,available:n,next:n.length>0?`Re-run with one of the profiles on this host: ${n.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>`."})}i(z,"profileNotFound");function oe(e){const t=ie(e);if(t.kind==="resolved")return t.entry;throw z(v(),e,j)}i(oe,"loadProfileManifest");function je(e){return ae(v(),e,j)}i(je,"resolveProfileOperand");function ae(e,t,r){const n=N(e,t,r);if(n!==null)return n;const{match:o,tied:a}=ee(t,e.map(r));if(o!==null){const s=e.find(f=>r(f).profileId===o.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${r(s).name} (${r(s).profileId})`),s}if(a.length>1){const s=a.map(f=>`${f.profileId} (${f.name})`);throw k(`"${t}" is equally close to ${a.length} profiles: ${s.join(", ")}`,{received:t,candidates:a.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw z(e,t,r)}i(ae,"matchProfileOperand");function J(e){const t=O(e);if(!V(t)||!Y(t).isDirectory())throw l(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return E(t)}catch{return t}}i(J,"resolveExistingProjectDir");function T(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}i(T,"dedupeProjects");function se(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"}i(se,"slugify");function fe(e){const t=se(e);for(let r=0;r<20;r++){const n=Z().replace(/-/g,"").slice(0,8),o=`${t}-${n}`;if(p(o)===null)return o}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}i(fe,"generateProfileId");let b=null;function be(e){b=e}i(be,"setCloudProfileWriter");async function Ae(){if(C()){const r=v().find(n=>n.manifest.name===$&&y(n.manifest)==="app:terminal");return r!==void 0?(x(r.profileId,r.manifest),r):await q($,[],{grantee:"app:terminal"})}const e=p(m);if(e!==null)return x(m,e.manifest),e;const t={schema_version:R,name:$,projects:[],grantee:"app:terminal",paused_at:null,created_at:h(),last_used_at:h()};return x(m,t),await w(r=>r.profiles.some(n=>n.profileId===m)?[]:[{op:"profile.insert",profile:{profileId:m,manifest:t}}]),p(m)}i(Ae,"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,"_")}`}i(F,"metadataEnvName");function A(e){if(typeof e!="object"||e===null||Array.isArray(e))throw l("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[r,n]of Object.entries(e)){if(!U.test(r))throw l(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw l(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw l(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const o=F(r),a=t.get(o);if(a!==void 0)throw l(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${o}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(o,r)}}i(A,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,o]of Object.entries(e)){if(typeof o!="string"||!U.test(n)||o.includes("\0"))continue;const a=F(n);r.has(a)||(r.add(a),t[n]=o)}return t}i(K,"sanitizeProfileMetadata");async function q(e,t=[],r={}){const n=e.trim();if(n==="")throw l("profile name must not be empty");r.metadata!==void 0&&A(r.metadata),D(t);const o=T(t.map(d=>({path:J(d.path)}))),a=fe(n),s={schema_version:R,name:n,projects:o,paused_at:null,...r.grantee===void 0?{}:{grantee:r.grantee},...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:h(),last_used_at:null};x(a,s);const f=i(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:a,manifest:s}}])},"insert");if(!C())await f();else{if(b===null)throw new Error("a cloud role has no profile environment writer registered");await b({profileId:a,grantee:y(s),person:te()},async d=>{s.environment_id=d,await f()})}return{profileId:a,manifest:s}}i(q,"createProfile");async function Ee(e){if(!e.startsWith("app:")||e.length<=4)throw l("an app grantee is required");const t=`app-${e.slice(4)}`,r=v().filter(n=>n.manifest.name===t&&n.manifest.grantee===e);if(r.length>1)throw new Error(`duplicate default profile for ${e}`);return r[0]?r[0]:await q(t,[],{grantee:e})}i(Ee,"ensureAppProfile");function H(e){if(_(e),p(e)===null)throw u(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}i(H,"requireExistingProfile");async function c(e,t){H(e);let r;return await w(n=>{const o=n.profiles.find(a=>a.profileId===e);if(o===void 0)throw u(`profile not found: ${e}`,{received:e});return r={profileId:e,manifest:t(structuredClone(o.manifest))},[{op:"profile.update",profile:r}]}),r}i(c,"mutateManifest");async function Se(e){return await c(e,t=>({...t,last_used_at:h()}))}i(Se,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return oe(e)}catch{return null}}i(le,"loadProfileManifestOrNull");function Oe(e){return e==null||e===""||!P.test(e)?!1:Q(e)}i(Oe,"isProfilePaused");function Re(){return B()}i(Re,"pausedCanvasProfiles");function ce(e){if(e.manifest.paused_at!==null)throw l(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}i(ce,"assertProfileEntryActive");function Me(e){const t=le(e);return t===null?null:(ce(t),t)}i(Me,"assertProfileActive");async function ke(e){return await c(e,t=>({...t,paused_at:t.paused_at??h()}))}i(ke,"pauseProfile");async function Ce(e){let t=null;return{...await c(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}i(Ce,"resumeProfile");async function De(e,t){return await c(e,r=>({...r,default_kind:t}))}i(De,"setProfileDefaultKind");async function Le(e,t,r=[]){return A(t),await c(e,n=>{const o={...K(n.metadata),...t};for(const f of r)delete o[f];A(o);const{metadata:a,...s}=n;return{...s,...Object.keys(o).length>0?{metadata:o}:{}}})}i(Le,"updateProfileMetadata");function Ne(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}i(Ne,"readProfileMetadata");async function ze(e,t){const r=t.trim();if(r==="")throw l("profile name must not be empty");return await c(e,o=>({...o,name:r}))}i(ze,"renameProfile");async function Je(e,t){D([{path:t}]);const r=J(t);return await c(e,o=>({...o,projects:T([...o.projects,{path:r}])}))}i(Je,"addProfileProject");async function Te(e,t,r){return re({[t]:r}),await c(e,n=>{const{[t]:o,...a}=n.delivery_limits??{},s=r==="content"?a:{...a,[t]:r},{delivery_limits:f,...d}=n;return Object.keys(s).length===0?d:{...d,delivery_limits:s}})}i(Te,"setProfileDeliveryLimit");async function Ue(e,t){const r=O(t);let n=r;try{n=E(r)}catch{}return await c(e,a=>{const s=a.projects.filter(f=>f.path!==n&&f.path!==r);if(s.length===a.projects.length)throw u(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(f=>f.path).join(", "):"(none)"}.`});return{...a,projects:s}})}i(Ue,"removeProfileProject");async function Fe(e){H(e);const t=g(y(L(e).manifest),e);await w(r=>{if(!r.profiles.some(n=>n.profileId===e))throw u(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),S(t.dir,{recursive:!0,force:!0}),S(t.env,{force:!0})}i(Fe,"deleteProfile");export{m as ROOT_PROFILE_ID,Je as addProfileProject,re as assertDeliveryLimits,Me as assertProfileActive,ce as assertProfileEntryActive,A as assertProfileMetadata,D as assertProfileProjects,q as createProfile,Fe as deleteProfile,Ee as ensureAppProfile,Ae as ensureRootProfile,Oe as isProfilePaused,v as listProfiles,L as loadExactProfileManifest,oe as loadProfileManifest,ie as lookupProfile,ae as matchProfileOperand,F as metadataEnvName,ke as pauseProfile,Re as pausedCanvasProfiles,_e as profileDir,Ne as readProfileMetadata,Ue as removeProfileProject,ze as renameProfile,je as resolveProfileOperand,Ce as resumeProfile,K as sanitizeProfileMetadata,be as setCloudProfileWriter,De as setProfileDefaultKind,Te as setProfileDeliveryLimit,Se as updateProfileLastUsed,Le as updateProfileMetadata};
|
|
1
|
+
var W=Object.defineProperty;var i=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as V,realpathSync as E,rmSync as S,statSync as Y}from"node:fs";import{resolve as O}from"node:path";import{SCHEMA_VERSION as R}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as M}from"../../api/dto/profiles.js";import{ensureDir as G,nowIso as h}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 l,notFound as u,ambiguous as k,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as C,personId as te}from"../canvas/person-state.js";const P=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,m="root-00000000",$="root";function y(e){return e.grantee??"app:terminal"}i(y,"profileApp");function x(e,t){G(g(y(t),e).dir)}i(x,"scaffoldProfile");function _(e){if(!P.test(e))throw l(`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."})}i(_,"assertSafeProfileId");function _e(e){_(e);const t=p(e);if(t===null)throw u(`profile not found: ${e}`,{received:e});return g(y(t.manifest),e).dir}i(_e,"profileDir");function D(e){if(!Array.isArray(e))throw l("projects must be an array of {path} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"}.'});const{path:r}=t;if(typeof r!="string"||r.trim()==="")throw l(`project entry has no path: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a non-empty directory path."})}}i(D,"assertProfileProjects");function re(e){const t=M.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw l("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[r,n]of Object.entries(e)){if(r.trim()==="")throw l("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 n!="string"||!M.includes(n))throw l(`invalid delivery limit for ${r}: ${JSON.stringify(n)}`,{received:String(n),field:"delivery_limits",next:`Set ${r} to one of: ${t}.`})}}i(re,"assertDeliveryLimits");function ne(){return{entries:X(),unreadableIds:[]}}i(ne,"enumerateProfiles");function v(){return ne().entries}i(v,"listProfiles");function ie(e){const t=v(),r=N(t,e,j);return r?{kind:"resolved",entry:r}:{kind:"absent"}}i(ie,"lookupProfile");function L(e){_(e);const t=p(e);if(t!==null)return t;throw u(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}i(L,"loadExactProfileManifest");const j=i(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function N(e,t,r){if(P.test(t)){const o=e.find(a=>r(a).profileId===t);if(o!==void 0)return o}const n=e.filter(o=>r(o).name===t);if(n.length===1)return n[0];if(n.length>1){const o=n.map(a=>r(a).profileId);throw k(`profile name "${t}" matches ${o.length} profiles: ${o.join(", ")}`,{received:t,candidates:o,next:`Re-run with one exact profile id: ${o.join(", ")}.`})}return null}i(N,"findExactProfile");function z(e,t,r){const n=e.map(o=>`${r(o).profileId} (${r(o).name})`);return u(`profile not found: ${t}`,{received:t,available:n,next:n.length>0?`Re-run with one of the profiles on this host: ${n.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>`."})}i(z,"profileNotFound");function oe(e){const t=ie(e);if(t.kind==="resolved")return t.entry;throw z(v(),e,j)}i(oe,"loadProfileManifest");function je(e){return ae(v(),e,j)}i(je,"resolveProfileOperand");function ae(e,t,r){const n=N(e,t,r);if(n!==null)return n;const{match:o,tied:a}=ee(t,e.map(r));if(o!==null){const s=e.find(f=>r(f).profileId===o.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${r(s).name} (${r(s).profileId})`),s}if(a.length>1){const s=a.map(f=>`${f.profileId} (${f.name})`);throw k(`"${t}" is equally close to ${a.length} profiles: ${s.join(", ")}`,{received:t,candidates:a.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw z(e,t,r)}i(ae,"matchProfileOperand");function J(e){const t=O(e);if(!V(t)||!Y(t).isDirectory())throw l(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return E(t)}catch{return t}}i(J,"resolveExistingProjectDir");function T(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}i(T,"dedupeProjects");function se(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"}i(se,"slugify");function fe(e){const t=se(e);for(let r=0;r<20;r++){const n=Z().replace(/-/g,"").slice(0,8),o=`${t}-${n}`;if(p(o)===null)return o}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}i(fe,"generateProfileId");let b=null;function be(e){b=e}i(be,"setCloudProfileWriter");async function Ae(){if(C()){const r=v().find(n=>n.manifest.name===$&&y(n.manifest)==="app:terminal");return r!==void 0?(x(r.profileId,r.manifest),r):await q($,[],{grantee:"app:terminal"})}const e=p(m);if(e!==null)return x(m,e.manifest),e;const t={schema_version:R,name:$,projects:[],grantee:"app:terminal",paused_at:null,created_at:h(),last_used_at:h()};return x(m,t),await w(r=>r.profiles.some(n=>n.profileId===m)?[]:[{op:"profile.insert",profile:{profileId:m,manifest:t}}]),p(m)}i(Ae,"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,"_")}`}i(F,"metadataEnvName");function A(e){if(typeof e!="object"||e===null||Array.isArray(e))throw l("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[r,n]of Object.entries(e)){if(!U.test(r))throw l(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw l(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw l(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const o=F(r),a=t.get(o);if(a!==void 0)throw l(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${o}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(o,r)}}i(A,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,o]of Object.entries(e)){if(typeof o!="string"||!U.test(n)||o.includes("\0"))continue;const a=F(n);r.has(a)||(r.add(a),t[n]=o)}return t}i(K,"sanitizeProfileMetadata");async function q(e,t=[],r={}){const n=e.trim();if(n==="")throw l("profile name must not be empty");r.metadata!==void 0&&A(r.metadata),D(t);const o=T(t.map(d=>({path:J(d.path)}))),a=fe(n),s={schema_version:R,name:n,projects:o,paused_at:null,...r.grantee===void 0?{}:{grantee:r.grantee},...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:h(),last_used_at:null};x(a,s);const f=i(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:a,manifest:s}}])},"insert");if(!C())await f();else{if(b===null)throw new Error("a cloud role has no profile environment writer registered");await b({profileId:a,grantee:y(s),person:te(),...r.memoryMb===void 0?{}:{memoryMb:r.memoryMb},...r.recipe===void 0?{}:{recipe:r.recipe}},async d=>{s.environment_id=d,await f()})}return{profileId:a,manifest:s}}i(q,"createProfile");async function Ee(e){if(!e.startsWith("app:")||e.length<=4)throw l("an app grantee is required");const t=`app-${e.slice(4)}`,r=v().filter(n=>n.manifest.name===t&&n.manifest.grantee===e);if(r.length>1)throw new Error(`duplicate default profile for ${e}`);return r[0]?r[0]:await q(t,[],{grantee:e})}i(Ee,"ensureAppProfile");function H(e){if(_(e),p(e)===null)throw u(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}i(H,"requireExistingProfile");async function c(e,t){H(e);let r;return await w(n=>{const o=n.profiles.find(a=>a.profileId===e);if(o===void 0)throw u(`profile not found: ${e}`,{received:e});return r={profileId:e,manifest:t(structuredClone(o.manifest))},[{op:"profile.update",profile:r}]}),r}i(c,"mutateManifest");async function Se(e){return await c(e,t=>({...t,last_used_at:h()}))}i(Se,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return oe(e)}catch{return null}}i(le,"loadProfileManifestOrNull");function Oe(e){return e==null||e===""||!P.test(e)?!1:Q(e)}i(Oe,"isProfilePaused");function Re(){return B()}i(Re,"pausedCanvasProfiles");function ce(e){if(e.manifest.paused_at!==null)throw l(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}i(ce,"assertProfileEntryActive");function Me(e){const t=le(e);return t===null?null:(ce(t),t)}i(Me,"assertProfileActive");async function ke(e){return await c(e,t=>({...t,paused_at:t.paused_at??h()}))}i(ke,"pauseProfile");async function Ce(e){let t=null;return{...await c(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}i(Ce,"resumeProfile");async function De(e,t){return await c(e,r=>({...r,default_kind:t}))}i(De,"setProfileDefaultKind");async function Le(e,t,r=[]){return A(t),await c(e,n=>{const o={...K(n.metadata),...t};for(const f of r)delete o[f];A(o);const{metadata:a,...s}=n;return{...s,...Object.keys(o).length>0?{metadata:o}:{}}})}i(Le,"updateProfileMetadata");function Ne(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}i(Ne,"readProfileMetadata");async function ze(e,t){const r=t.trim();if(r==="")throw l("profile name must not be empty");return await c(e,o=>({...o,name:r}))}i(ze,"renameProfile");async function Je(e,t){D([{path:t}]);const r=J(t);return await c(e,o=>({...o,projects:T([...o.projects,{path:r}])}))}i(Je,"addProfileProject");async function Te(e,t,r){return re({[t]:r}),await c(e,n=>{const{[t]:o,...a}=n.delivery_limits??{},s=r==="content"?a:{...a,[t]:r},{delivery_limits:f,...d}=n;return Object.keys(s).length===0?d:{...d,delivery_limits:s}})}i(Te,"setProfileDeliveryLimit");async function Ue(e,t){const r=O(t);let n=r;try{n=E(r)}catch{}return await c(e,a=>{const s=a.projects.filter(f=>f.path!==n&&f.path!==r);if(s.length===a.projects.length)throw u(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(f=>f.path).join(", "):"(none)"}.`});return{...a,projects:s}})}i(Ue,"removeProfileProject");async function Fe(e){H(e);const t=g(y(L(e).manifest),e);await w(r=>{if(!r.profiles.some(n=>n.profileId===e))throw u(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),S(t.dir,{recursive:!0,force:!0}),S(t.env,{force:!0})}i(Fe,"deleteProfile");export{m as ROOT_PROFILE_ID,Je as addProfileProject,re as assertDeliveryLimits,Me as assertProfileActive,ce as assertProfileEntryActive,A as assertProfileMetadata,D as assertProfileProjects,q as createProfile,Fe as deleteProfile,Ee as ensureAppProfile,Ae as ensureRootProfile,Oe as isProfilePaused,v as listProfiles,L as loadExactProfileManifest,oe as loadProfileManifest,ie as lookupProfile,ae as matchProfileOperand,F as metadataEnvName,ke as pauseProfile,Re as pausedCanvasProfiles,_e as profileDir,Ne as readProfileMetadata,Ue as removeProfileProject,ze as renameProfile,je as resolveProfileOperand,Ce as resumeProfile,K as sanitizeProfileMetadata,be as setCloudProfileWriter,De as setProfileDefaultKind,Te as setProfileDeliveryLimit,Se as updateProfileLastUsed,Le as updateProfileMetadata};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as oe}from"node:crypto";import{closeSync as D,constants as ne,createWriteStream as ie}from"node:fs";import{basename as re,extname as ae,isAbsolute as se,join as C}from"node:path";import{Transform as de}from"node:stream";import{pipeline as ue}from"node:stream/promises";import{appSpace as M}from"../layout.js";import{RunError as F}from"../runs/operations.js";import{createFileBeneath as le,existsBeneath as q,openBeneath as ce,removeTreeBeneath as I,setModeBeneath as fe,unlinkBeneath as pe,withDirBeneath as he}from"../spaces/open-beneath.js";import{ensureAppSpace as we}from"../spaces/space.js";import{isCloudRole as me}from"../canvas/person-state.js";import{invalidStorageName as N,storageClient as T,StorageRefused as U,UPLOAD_MAX_BYTES as B}from"../storage/client.js";import{openCallerFile as _e}from"../storage/
|
|
1
|
+
var te=Object.defineProperty;var u=(e,t)=>te(e,"name",{value:t,configurable:!0});import{createHash as oe}from"node:crypto";import{closeSync as D,constants as ne,createWriteStream as ie}from"node:fs";import{basename as re,extname as ae,isAbsolute as se,join as C}from"node:path";import{Transform as de}from"node:stream";import{pipeline as ue}from"node:stream/promises";import{appSpace as M}from"../layout.js";import{RunError as F}from"../runs/operations.js";import{createFileBeneath as le,existsBeneath as q,openBeneath as ce,removeTreeBeneath as I,setModeBeneath as fe,unlinkBeneath as pe,withDirBeneath as he}from"../spaces/open-beneath.js";import{ensureAppSpace as we}from"../spaces/space.js";import{isCloudRole as me}from"../canvas/person-state.js";import{invalidStorageName as N,storageClient as T,StorageRefused as U,UPLOAD_MAX_BYTES as B}from"../storage/client.js";import{openCallerFile as _e}from"../storage/caller-file.js";import{contentTypeFor as ge}from"../storage/media-types.js";import{withCanvasWrite as ye}from"../canvas/db.js";import{deleteUploadUse as be,getUpload as $e,insertUpload as ve,insertUploadUses as Se,setUploadSize as Ue,uploadUseAt as ze}from"../storage/tables.js";import{ProviderError as d}from"./errors.js";const Ee=11e4,Ae="app:terminal";function H(e){if(e.class==="person")return e.grantee??Ae;if(!e.grantee)throw new d("server_error","provider caller has no grantee");return e.grantee}u(H,"grantee");function Ce(e){if(e.class==="person"&&e.sub)throw new d("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:H(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Ce,"fileCaller");function y(e){return e instanceof d?e:e instanceof U?new d("storage_unavailable",`storage refused: ${e.message}`):e instanceof F&&e.code==="storage_unavailable"&&e.retryable?new d("storage_unavailable",e.message):e}u(y,"storageFailure");const b=u(e=>new d("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!se(n)||n.includes("\0"))throw new d("invalid_request",`${t} must be an absolute runtime path`,{param:t});let r;try{r=_e(Ce(e),n)}catch(i){throw i instanceof F?i.code==="scope_missing"?new d("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new d("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(r.size>B)throw new d("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=re(r.path),o=N(i);if(o)throw new d("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:r,name:i,mediaType:ge(r.path)}}catch(i){throw D(r.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const r=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:r.url}}catch(n){throw y(n)}}u(Te,"copyOutbound");async function P(e,t,n,r){const i=[];try{for(const a of t)n[a]===void 0||n[a]===null||i.push(Fe(e,a,n[a]));if(!i.length)return[];let o;try{o=r()}catch(a){throw y(a)}const c=[];for(const a of i)c.push(await Te(o,a));return c}finally{for(const o of i)D(o.file.fd)}}u(P,"copyArguments");function k(e){const t=N(e);if(t)throw new d("server_error",`file output ${e} cannot name an upload: ${t}`)}u(k,"checkOutputField");async function W(e,t,n){k(t);const r=H(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:B})}catch(c){throw y(c)}return await ve({upload_id:o.upload_id,grantee:r,name:t,media_type:i,size:B,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:r}}u(W,"createResultUpload");function X(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(X,"uploadHeaders");function Y(e,t){const n={...e};for(const r of t)n[r.param]=r.url;return n}u(Y,"withUrls");async function Ke(e,t,n,r={}){const i=r.storage??T;if(t.output&&(k(t.output),me()))throw new d("invalid_request","this command returns a file, which cannot be delivered to your computer from here yet, so it is not available from a moved Mac");const o=await P(e,t.params,n,i),c=t.output?await W(e,t.output,i):null;return{arguments:Y(n,o),copies:o,upload:c,headers:X(c)}}u(Ke,"prepareFileCall");async function Qe(e,t,n,r,i={}){const o=i.storage??T,c=[];for(const s of r.copies)try{const p=await o().signOutbound(s.object_id);c.push({...s,url:p.url})}catch(p){if(!(p instanceof U))throw y(p);c.push(...await P(e,[s.param],n,o))}let a=r.upload;if(a)try{const s=await o().signUploadLink(a.upload_id);a={...a,upload_link:s.upload_link}}catch(s){if(!(s instanceof U))throw y(s);s.status===404&&(a=await W(e,t.output??a.field,o))}return{arguments:Y(n,c),copies:c,upload:a,headers:X(a)}}u(Qe,"resignForRetry");const Be=/^[0-9a-f]{64}$/i;function Re(e,t){if(t===1)return e;const n=ae(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Re,"candidate");async function Ve(e,t,n,r={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,a=c[o.field];if(a==null)return i;if(typeof a!="object"||Array.isArray(a))throw b(`${o.field} must be {upload_id, size, sha256}`);const s=a;if(typeof s.upload_id!="string"||typeof s.size!="number"||!Number.isSafeInteger(s.size)||s.size<0||typeof s.sha256!="string"||!Be.test(s.sha256))throw b(`${o.field} must be {upload_id, size, sha256}`);if(s.upload_id!==o.upload_id)throw b(`${o.field} names an upload other than Crtr-Upload-Id`);const p=s.size,G=s.sha256.toLowerCase(),z=AbortSignal.timeout(r.budgetMs??Ee),R=r.signal?AbortSignal.any([z,r.signal]):z;let h;try{h=await(r.storage??T)().fetchUpload(o.upload_id,R)}catch(m){throw m instanceof U?b(`${o.field} names an upload with nothing stored`):y(m)}if(h.size===null)throw h.body.destroy(),new d("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(h.size!==p)throw h.body.destroy(),b(`${o.field} claims ${p} bytes; storage holds ${h.size}`);const E=o.grantee,$=e.node_id!==null,J=await we(E),f=$?M(E).nodes:M(E).files,A=$?C(f,e.node_id):f,v=$?C(A,"attachments"):f,K={uid:process.getuid?.()??0,gid:J.gid},O=$&&!q(f,A),Q=$&&!O&&!q(f,v);let w=null,S=null,x=!1;const L=u(async()=>{if(!x){if(x=!0,S)try{await be(S)}catch{}if(w)try{pe(f,w)}catch{}try{O?I(f,A):Q&&I(f,v)}catch{}}},"cleanup");try{he(f,v,()=>{},!0);for(let l=1;;l++){const _=C(v,Re(o.field,l));if(!await ze(_))try{le(f,_,Buffer.alloc(0),432),w=_;break}catch(g){if(g.code!=="EEXIST")throw g}}let m=0;const j=oe("sha256"),V=new de({transform(l,_,g){m+=l.length,j.update(l),g(null,l)}}),Z=ce(f,w,ne.O_WRONLY);try{await ue(h.body,V,ie("",{fd:Z,autoClose:!0}),{signal:R})}catch(l){throw z.aborted?new d("storage_unavailable","the file result could not be fetched within 110 s"):l instanceof F?y(l):new d("storage_unavailable",`storage stopped sending ${o.field}: ${l instanceof Error?l.message:String(l)}`)}if(m!==p)throw new d("storage_unavailable",`storage sent ${m} of ${p} bytes of ${o.field}`);if(j.digest("hex")!==G)throw b(`${o.field}: the stored bytes do not match sha256`);fe(f,w,432,K);const ee=w;await ye(async l=>{const _=await $e(o.upload_id,l);if(!_||_.delete_pending_since)throw new d("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await Ue(o.upload_id,p,l),!e.run_id)return;const g=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!g||g.deleting_at)throw new d("not_found",`run ${e.run_id} was deleted while its file result was fetched`);S={upload_id:o.upload_id,run_id:e.run_id,path:ee},await Se([S],l)})}catch(m){throw h.body.destroy(),await L(),m}return{result:{...c,[o.field]:w},file:{path:w,upload_id:o.upload_id},cleanup:L}}u(Ve,"resolveFileResult");export{Ee as FILE_RESULT_FETCH_BUDGET_MS,Ke as prepareFileCall,Qe as resignForRetry,Ve as resolveFileResult};
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var Ie=Object.defineProperty;var c=(e,t)=>Ie(e,"name",{value:t,configurable:!0});import{coveredByAny as Te}from"../../shared/env.js";import{createHash as K}from"node:crypto";import{ApiError as Le}from"../../api/errors.js";import{CrtrError as
|
|
1
|
+
var Ie=Object.defineProperty;var c=(e,t)=>Ie(e,"name",{value:t,configurable:!0});import{coveredByAny as Te}from"../../shared/env.js";import{createHash as K}from"node:crypto";import{ApiError as Le}from"../../api/errors.js";import{CrtrError as ke}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as ee,relative as xe,resolve as We,sep as Fe,join as qe}from"node:path";import{SessionManager as He}from"@earendil-works/pi-coding-agent";import{covers as j}from"@north-light/identity";import{openDb as Y,withCanvasWrite as U}from"../canvas/db.js";import{deleteNodeWithOwned as Ue}from"../graph/deletion.js";import{getById as $e}from"../graph/objects.js";import{repairRunConversations as te}from"../canvas/sessions.js";import{getNode as v,nodeFiles as Pe,removeNodeFiles as Be,updateNode as Je}from"../canvas/canvas.js";import{fullName as je}from"../canvas/labels.js";import{renameWindow as Ye}from"../runtime/placement.js";import{latestExecutionForNode as Ge,liveExecutionForNode as ne}from"../canvas/executions.js";import{conversationStore as se,isConversationNotFound as Xe}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as ze}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Qe}from"../canvas/deliveries.js";import{readNodeRecap as Ve}from"../canvas/node-recap.js";import{enqueueNodeMail as Ze}from"../feed/messages.js";import{recordInitialInput as Ke}from"./initial-input.js";import{newestReportBody as et}from"../feed/reports.js";import{ensureAppProfile as ae,loadExactProfileManifest as ie}from"../profiles/manifest.js";import{stopNodeSandboxes as re}from"../spaces/stop.js";import{deleteNodeSandboxes as tt}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as nt}from"../runtime/broker-request.js";import{interruptLive as st}from"../runtime/interactive-deliver.js";import{isBrokerLive as oe}from"../runtime/model-swap.js";import{newNodeId as at}from"../runtime/nodes.js";import{reviveNode as G}from"../runtime/revive.js";import{spawnChildPrepared as it}from"../runtime/spawn.js";import{isPortableModelToken as rt}from"../runtime/launch.js";import{parseDurationMs as ot}from"../wake.js";import{expandModelCandidates as dt,parseModelSpec as ct}from"../model-routes.js";import{payerOfGrant as X}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as ut}from"../runtime/host.js";import{blaxelEnvironmentOf as mt}from"../runtime/blaxel-environment.js";import{resolveRunKind as lt,resolveRunModel as ft}from"../runtime/launch-target.js";import{cycleAwareMessages as pt}from"../runtime/session-cycles.js";import{originFor as de}from"../runtime/stamp/protocol.js";import{readOutputRequest as _t,readOutputResult as ce}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as ue}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as wt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as gt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as Et}from"../../daemon/runs/observer.js";import{closeNode as me}from"../runtime/close.js";import{parseScope as yt}from"@north-light/identity";import{appendRunEvent as le,lockRunRoot as ht,subscribeRunEvents as Rt}from"./events.js";import{runActivity as St}from"./activity.js";import{cancelOpenQuestions as fe,openNoticeIds as Nt,openQuestionIds as pe}from"./questions.js";import{appSpace as z}from"../layout.js";import{ensureAppSpace as bt}from"../spaces/space.js";import{assertUploadsUsable as _e,resolveStorageUrls as vt}from"../storage/attachments.js";import{storageClient as Ot,storageConfig as Dt}from"../storage/client.js";import{deleteRunFiles as Mt,deleteUploadRow as At,insertUploadUses as we,releaseRunUploads as It,runUsesPath as Tt}from"../storage/tables.js";import{abortProviderCalls as ge}from"../providers/inflight.js";import{filterAsync as Ee,mapAsync as q}from"../async-array.js";import{blobStore as Lt}from"../blobs/index.js";import{emitEvent as kt}from"../events/emit.js";const ye=c((e,t,s,n,d)=>vt(t,d,e,s,n?{taken:n}:{}),"defaultResolver"),Ct=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,s,n,d,f,r,i=t===503){super(n),this.status=t,this.code=s,this.param=d,this.details=f,this.scope=r,this.retryable=i}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),Q=c(()=>new R(404,"not_found","run not found"),"missing"),V=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),I=c(async()=>await Y(),"db");async function $(e,t,s=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!s&&n.deleting_at)throw Q();return n}c($,"ownedRun");const he=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await I()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
|
|
2
2
|
(n.last_settled_at IS NULL OR EXISTS (
|
|
3
3
|
SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
|
|
4
4
|
AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
|
|
5
5
|
WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
|
|
6
|
-
)) LIMIT 1`).get(e.node_id,e.node_id),s=!e.last_settled_at&&e.status!=="done";return t||s||await
|
|
7
|
-
WHERE n.run_id = ? AND ${
|
|
8
|
-
AND (n.status IN ('active', 'idle') OR ${
|
|
6
|
+
)) LIMIT 1`).get(e.node_id,e.node_id),s=!e.last_settled_at&&e.status!=="done";return t||s||await wt(e)?"running":(await pe(e.node_id)).length?"waiting_on_user":await(await I()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
|
|
7
|
+
WHERE n.run_id = ? AND ${Qe("d","'armed', 'pending', 'handed_off'")}
|
|
8
|
+
AND (n.status IN ('active', 'idle') OR ${ze("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function zn(e){const t=await v(e);return t!==null&&await C(t)==="running"}c(zn,"runIsRunning");async function H(e){await te(e.node_id),e=await v(e.node_id)??e;const t=await C(e),s=t==="settled"?[]:await pe(e.node_id),n=await et(e.node_id)||void 0,d=t==="settled"?await gt(e):null,f=d?.kind==="result"?await ce(e.node_id):void 0,r=Ve(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...r?{recap:r}:{},pending_question_ids:s,open_notice_ids:t==="settled"?[]:await Nt(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(V())),payer:await X(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await St(e.node_id,t),worktree:await xt(e.node_id)}}c(H,"runObject");async function xt(e){const t=await Ge(e);if(t===null||t.runner!=="blaxel"||t.launchJson===null)return null;const s=JSON.parse(t.launchJson).worktree;return typeof s?.repository=="string"&&typeof s.branch=="string"?{repository:s.repository,branch:s.branch}:null}c(xt,"runWorktree");const Z=864e5,Re=255;function Qn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>Re)throw S(`Idempotency-Key must be 1-${Re} characters`);return e}}c(Qn,"idempotencyKeyOf");function x(e){if(Ce()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(x,"cloudPersonScope");function W(e,t){const s=x(e);return s===void 0?t:`${s}:${t}`}c(W,"personKey");async function P(e,t,s,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await Y();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=Z)){if(d.body_hash!==s)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(P,"findIdempotent");async function Se(e,t,s,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,s,new Date(Date.now()-Z).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,s,n,d,JSON.stringify(f),r)}c(Se,"recordIdempotent");async function Vn(e=Date.now()){return Number((await(await Y()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-Z).toISOString())).changes)}c(Vn,"pruneExpiredIdempotencyKeys");async function Ne(e,t,s,n,d,f,r=!1){const i=d.text;let u=0;return{messageId:(await Ze(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:s,bodyJson:f?{body:i,...r?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await _e(s,x(n),d.uses,h),await we(d.uses.map(({upload_id:m,path:y,blob_key:a})=>({upload_id:m,path:y,blob_key:a,run_id:t})),h)),u=(await le(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Ne,"acceptRunMessage");class be extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Wt=1440*60*1e3;function ve(e){const t=typeof e=="string"?ot(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Wt)throw S("deadline must be at most 24h","deadline");return t}c(ve,"parseRunDeadlineMs");async function Zn(e,t,s,n=ye){if(t.isolated&&!ut()&&await mt((t.profile===void 0?await ae(e.grantee):ie(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&ve(t.deadline);const{causedBy:d,...f}=t,r=K("sha256").update(JSON.stringify(f)).digest("hex");if(s){const o=await P(e.grantee,W(e.sub,s),r);if(o){const m=await $(o.run_id,e.grantee);return!m.pi_pid&&await C(m)==="running"&&(t.output_schema!==void 0&&!m.outcome_at&&await _t(m.node_id)===null&&await ce(m.node_id)===void 0&&await ue(m.node_id,"terminal",t.output_schema),await G(m.node_id,{resume:!0,capacity:"freeze"})),o.response}}await bt(e.grantee);const i=t.profile===void 0?await ae(e.grantee):ie(t.profile),u=i.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${i.profileId}`;if(!e.resolved.some(m=>j(m,o))||t.scopes!==null&&!t.scopes.some(m=>j(m,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(rt(o)){if(o.includes("/")&&await X(e.grant)!=="app"){const m=o.lastIndexOf("/"),y=o.slice(0,m),a=o.slice(m+1);if(["ultra","strong","medium","light"].includes(a)&&(await dt({kind:"logical",family:y,strength:a,spec:o},z(e.grantee).files,i.profileId)).every(E=>E.family!==y))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(ct(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const _=await at(),h=qe(z(e.grantee).nodes,_);if(t.isolated&&t.cwd!==void 0){const o=xe(h,We(t.cwd));if(!ee(t.cwd)||o===".."||o.startsWith(`..${Fe}`)||ee(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(_,e.grantee,t.prompt,void 0,x(e.sub)),m=o.text,y=t.message===void 0?void 0:await n(_,e.grantee,t.message,o.uses.map(p=>p.path),x(e.sub)),a=await X(e.grant);let E;try{const p=ft(i,t.model);await it({kind:lt(i),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:z(e.grantee).files,profile:i.profileId,prompt:m,nodeId:_,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...p===void 0?{}:{model:p},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+ve(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:_,event_cursor:1,usage_json:JSON.stringify(V())},withinCreate:c(async(g,D)=>{if(s){const N=await P(e.grantee,W(e.sub,s),r,g);if(N)throw new be(N)}const A=o.uses;if(A.length&&(await _e(e.grantee,x(e.sub),A,g),await we(A.map(({upload_id:N,path:F,blob_key:T})=>({upload_id:N,path:F,blob_key:T,run_id:_})),g)),E={run_id:_,node_id:_,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:a,status:"running",created_at:D.created,metadata:t.metadata,sequence_number:0},await le(g,_,_,"run.started",{scopes:t.scopes,payer:a,usage:V()}),y){const N=await Ne(g,_,e.grantee,e.sub,y,!1);E.message={run_id:_,message_id:N.messageId,sequence_number:N.sequence}}else await Ke(_,e.grantee,m);s&&await Se(g,e.grantee,W(e.sub,s),r,_,E,D.created)},"withinCreate")},t.output_schema===void 0?void 0:async g=>{await ue(g,"terminal",t.output_schema)})}catch(p){if(p instanceof be)return p.winner.response;if(t.model!==void 0&&p instanceof ke&&p.code==="usage")throw S(p.message,"model");if(p instanceof Le&&(p.code==="isolated_run"||p.code==="invalid_request")){const g=p.details&&typeof p.details=="object"&&"param"in p.details&&typeof p.details.param=="string"?p.details.param:void 0;throw new R(p.status,p.code,p.message,g)}throw p}if(!E)throw new Error("run creation did not commit");return E}finally{await Ft(_)}}c(Zn,"startRun");async function Ft(e){try{if(await v(e)!==null)return;const t=await Lt();for(const s of await t.list(`attachments/${e}/`))await t.delete(s)}catch(t){kt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(Ft,"discardUncommittedAttachments");async function Kn(e,t){let s;if(t.after)try{const i=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!i||typeof i!="object"||!("activity"in i)||typeof i.activity!="string"||!("id"in i)||typeof i.id!="string")throw new Error("invalid cursor");s={activity:i.activity,id:i.id}}catch{throw S("invalid list cursor","after")}const n=await(await I()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
|
|
9
9
|
WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}${t.sub===void 0?"":" AND sub = ?"}
|
|
10
|
-
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await Ee(await
|
|
10
|
+
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await Ee(await q((await Ee(n,async({node_id:i})=>!t.visible||await t.visible(i))).filter(({activity:i,node_id:u})=>!s||i<s.activity||i===s.activity&&u<s.id),async i=>({root:await v(i.node_id),activity:i.activity})),async({root:i})=>!t.status||await C(i)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await q(f,async({root:i})=>await H(i)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(Kn,"listRuns");async function es(e,t,s){const n=await $(e,t),d=c(async()=>await H(await $(e,t)),"read");return!s||he.includes(await C(n))?await d():new Promise((f,r)=>{let i=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(y),clearInterval(m),i()},"settle"),_=c(async()=>{u();try{f(await d())}catch(a){r(a)}},"finish"),h=c(async()=>{he.includes(String((await d()).status))&&await _()},"check"),o=c(()=>{h().catch(a=>{u(),r(a)})},"run"),m=setInterval(o,250),y=setTimeout(()=>{_()},s*1e3);Rt(e,o).then(a=>{i=a},a=>{u(),r(a)})})}c(es,"waitRun");const qt=5;async function ts(e,t,s=ye,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",i=e.grantee??"app:terminal",u=K("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),_=c(async o=>{const m=await v(e.node_id),y=await(await I()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return m&&!r&&n&&!m.pi_pid&&y&&await G(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await P(i,W(e.sub,d),u);if(o)return _(o.response)}if(r)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const m=await s(e.node_id,i,t,void 0,x(e.sub)),y=await U(async a=>{if(d){const g=await P(i,W(e.sub,d),u,a);if(g)return{replayed:g.response}}if(m.uses.length){await ht(a,e.node_id);for(const g of m.uses)if(await Tt(e.node_id,g.path,a))return"path_taken"}await h?.(e.node_id);const E=await Ne(a,e.node_id,i,e.sub,m,n,n&&f),p={run_id:e.node_id,message_id:E.messageId,sequence_number:E.sequence};return d&&await Se(a,i,W(e.sub,d),u,e.node_id,p,new Date().toISOString()),{result:p}});if(y==="path_taken"){if(o>=qt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in y?_(y.replayed):(n&&!e.pi_pid&&await G(e.node_id,{resume:!0,capacity:"freeze"}),y.result)}}c(ts,"messageRun");async function Ht(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let s=0;s<2;s++){const n=await v(e);if(!n)throw Q();if(!oe(n)){if(n.streaming)throw t();return}const d=(await ne(e))?.executionId;try{await st(e)==="turn"&&ge({nodes:[e]});return}catch(f){if(!(f instanceof nt))throw f;const r=await v(e);if(!r)throw Q();if(!r.streaming)return;if(s===0&&oe(r)&&(await ne(e))?.executionId!==d)continue;throw t()}}throw t()}c(Ht,"interruptNode");async function ns(e,t="stop"){const s=t==="stop"?(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(s.map(n=>Ht(n))),await H(await v(e.node_id)??e)}c(ns,"interruptRun");async function ss(e,t={}){const s=(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);ge({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await me(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of s){if(r===e.node_id)continue;const i=await v(r);i&&i.status!=="done"&&i.status!=="canceled"&&i.status!=="dead"&&n.push(...(await me(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await fe({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>re(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await v(e.node_id);return await H(f??e)}c(ss,"cancelRun");const Oe=200;async function as(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const s=t.trim();if(s.length>Oe)throw S(`name exceeds ${Oe} characters`,"name");const n=await Je(e.node_id,{name:s});return n.window&&Ye(n.window,je(n)),await H(n)}c(as,"renameRun");async function is(e,t={config:Dt,client:Ot}){await fe({run_id:e.node_id},"the run was deleted");const s=await U(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(_=>_.node_id)));if((await Promise.all(s.map(u=>re(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await tt(s)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await q(s,async u=>{const _=await Pe(u);if(_.app===null)throw new Error(`run node missing during deletion: ${u}`);return _}),f=await(await I()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of f)try{await se().delete(u)}catch(_){if(!Xe(_))throw _}const r=await U(async u=>{for(const m of s){const y=await $e(u,m);y!==null&&y.deleted_at===null&&await Ue(u,y)}const _=await It([e.node_id],u);await Mt([e.node_id],u),await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=s.map(()=>"?").join(","),o=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...s,...s);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...s);for(const{message_id:m}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(m,m);return _});for(const u of d)await Be(u);const{notifyRunDeleted:i}=await import("./events.js");return i(e.node_id),{uploads_pending:await Ut(r,t)}}c(is,"deleteRun");async function Ut(e,t){if(!e.length||!t.config())return e.length;let s;try{s=t.client()}catch{return e.length}const n=new Set,d=e.map(r=>s.deleteUpload(r).then(async()=>{await At(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??Ct),f.unref?.()})]),clearTimeout(f),e.length-n.size}c(Ut,"deleteReleasedUploads");async function rs(e,t,s){await $(e,t),await te(e);const n=await U(async a=>{const E=await a.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),p=new Map;for(const b of E)p.set(b.node_id,(await a.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(b.node_id)).map(l=>l.session_id));const D=(await a.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await a.prepare(`SELECT node_id, sequence_number FROM run_events
|
|
11
11
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
|
|
12
12
|
ORDER BY sequence_number`).all(e,D),N=await a.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
|
|
13
13
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
|
|
14
|
-
ORDER BY sequence_number`).all(e,D),
|
|
14
|
+
ORDER BY sequence_number`).all(e,D),F=await a.prepare(`SELECT node_id, sequence_number, ts, body_json FROM run_events
|
|
15
15
|
WHERE run_id = ? AND sequence_number <= ? AND type = 'file.sent'
|
|
16
|
-
ORDER BY sequence_number`).all(e,D),T=new Set((await a.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=
|
|
16
|
+
ORDER BY sequence_number`).all(e,D),T=new Set((await a.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=F.flatMap(b=>{const l=JSON.parse(b.body_json);return T.has(l.file_id)?[{file_id:l.file_id,node_id:b.node_id,name:l.name,media_type:l.media_type,size:l.size,sequence_number:Number(b.sequence_number),ts:b.ts}]:[]});return{nodes:E,sessionIds:p,latestSequence:D,completed:A,deltas:N,files:B}}),{nodes:d,sessionIds:f,latestSequence:r,completed:i,deltas:u,files:_}=n,h=await q(d,async a=>({node_id:a.node_id,parent_node_id:a.parent,conversations:await q(f.get(a.node_id)??[],async E=>{const{header:p,entries:g}=await se().read(E);if(s==="entries")return{conversation_id:E,header:p,entries:g};const D=He.inMemory(p.cwd,void 0,[p,...g]),A=pt(D)??[],N=new Map(g.map((l,O)=>[l.id,O])),F=g.filter(l=>l.type==="custom"&&l.customType==="crtr-system-prompt").map(l=>({id:l.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in l?l.data:void 0,timestamp:l.timestamp}})),T=g.filter(l=>l.type==="custom_message"&&l.customType==="app_message").map(l=>({id:l.id,message:{role:"custom",customType:"app_message",content:"content"in l?l.content:"",timestamp:l.timestamp}})),B=a.node_id===e?g.find(l=>{if(l.type!=="message"||l.message.role!=="user")return!1;const O=de(g,l.message.timestamp);return O?.type==="runtime"&&O.kind==="kickoff"})?.id:void 0,b=[...A.filter(({id:l})=>!T.some(O=>O.id===l)),...F,...T].sort((l,O)=>(N.get(l.id)??Number.MAX_SAFE_INTEGER)-(N.get(O.id)??Number.MAX_SAFE_INTEGER)).map(({id:l,message:O})=>{const w=O,L=w.usage,J=w.role==="user"?de(g,Number(w.timestamp)):null,De=J?.type==="human"||l===B,k=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?De?"user":"custom":w.role,Me=k==="custom"?w.role==="custom"?w.customType:J?.type==="runtime"?J.kind:"unknown":void 0,Ae=k==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(M=>M.type==="toolCall"?{type:"tool_call",tool_call_id:M.id,name:M.name,arguments:M.arguments}:M.type==="image"?{type:"image",mime_type:M.mimeType}:M.type==="thinking"?{type:"thinking",text:M.thinking}:M):[];return{entry_id:l,role:k,...k==="custom"?{custom_type:Me}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Ae,...k==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...L?{usage:{input_tokens:L.input??0,output_tokens:L.output??0,cache_read_tokens:L.cacheRead??0,cache_write_tokens:L.cacheWrite??0,cost_usd:L.cost?.total??0}}:{}}:{},...k==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:E,messages:b}})})),o=new Map(await Promise.all(h.map(async a=>[a.node_id,await Et(a.node_id)])));for(const a of i){const E=o.get(a.node_id);E!=null&&a.sequence_number>=E&&o.set(a.node_id,null)}const m=new Map;for(const a of u){const E=o.get(a.node_id);if(E==null||a.sequence_number<E)continue;const p=JSON.parse(a.body_json),g=m.get(a.node_id)??{thinking:"",text:""};a.type==="node.thinking.delta"?g.thinking+=p.delta:g.text+=p.delta,m.set(a.node_id,g)}const y=h.map(a=>({...a,in_progress_message:o.get(a.node_id)==null?null:m.get(a.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:y,files:_}}c(rs,"traceRun");function os(e,t,s){if(t===void 0){if(!e.some(n=>j(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{yt(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===s.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===s.slice(4))&&!Te(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(os,"requestedScopes");export{Z as IDEMPOTENCY_WINDOW_MS,Wt as RUN_DEADLINE_MAX_MS,Ct as RUN_DELETE_STORAGE_BUDGET_MS,Oe as RUN_NAME_MAX,R as RunError,ss as cancelRun,x as cloudPersonScope,is as deleteRun,Qn as idempotencyKeyOf,ns as interruptRun,Kn as listRuns,ts as messageRun,$ as ownedRun,ve as parseRunDeadlineMs,Vn as pruneExpiredIdempotencyKeys,as as renameRun,os as requestedScopes,zn as runIsRunning,H as runObject,Zn as startRun,rs as traceRun,es as waitRun};
|
|
@@ -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};
|