@north-light/cli 0.3.665 → 0.3.667
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/nodes.d.ts +2 -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/02-turn-lifecycle/00-ending-a-turn.md +3 -1
- package/dist/builtin-memory/04-base-worker-exploring.md +2 -2
- 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/chrome/canvas-panels.d.ts +9 -1
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/viewer.js +499 -499
- package/dist/commands/node.js +1 -1
- 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/canvas/canvas.js +18 -18
- 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 +2 -2
- package/dist/daemon/api/operations.d.ts +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +11 -11
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +6 -6
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +18 -0
- package/dist/daemon/reconcilers/idle-sandbox.js +7 -0
- package/dist/daemon/reconcilers/recipe-image.js +4 -4
- package/docs/apps/guides/files-and-documents.md +2 -6
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/dist/core/storage/download.d.ts +0 -23
- package/dist/core/storage/download.js +0 -1
package/dist/commands/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var e=(n
|
|
1
|
+
var t=Object.defineProperty;var e=(o,n)=>t(o,"name",{value:n,configurable:!0});import{defineBranch as a}from"../core/command.js";import{nodeNew as i}from"./node/create.js";import{nodeInspect as r,nodeFork as s}from"./node/inspect.js";import{nodeLifecycle as d,nodeConfig as c,nodePromote as h,nodeYield as m}from"./node/lifecycle.js";import{nodeMessage as l}from"./node/message.js";import{nodeWaitBranch as f}from"./node/wait.js";import{nodeSubscription as p}from"./node/subscription.js";import{nodeBash as w}from"./node/bash.js";import{pyramidSlash as u}from"./node/pyramid.js";import{nodeWorktreeBranch as g}from"./node-worktree.js";import{nodeOutcome as y}from"./node/outcome.js";function C(){return a({name:"node",slash:u,rootEntry:{concept:"a unit of the agent runtime \u2014 an agent on the canvas with its own context dir and pi vehicle. A child node starts with none of your context, spends its own full window of tokens, and you wait for its report",desc:"spawn, inspect, and navigate nodes on the canvas",useWhen:"delegating a genuinely independent subtask, or walking the subscription graph. Delegation pays when the subtask runs in parallel with your own work or would fill your window with material you do not need afterwards; do the work yourself when it is a few files or a few commands. Base nodes work hands-on; orchestrators fan out. Brief each child with the outcome, what you already know, and what to hand back. Give each child a bounded outcome distinct from your whole assignment so delegation moves work toward completion instead of recursively passing it down. Once delegated, do not duplicate the child\u2019s work; its finish wakes you. Use the help surface for the exact node contract before invoking it. For a long-running shell command, `crtr node bash -h`."},help:{name:"node",summary:"create, inspect, message, and change canvas nodes",model:"A node is one agent on the canvas. Immediate actions, durable waits, subscriptions, lifecycle changes, and scheduled crons are separate intent families; choose the family by when the effect happens and what persistent state it changes."},children:[i,s,l,f,p,y,r,d,g,c,h,m,w]})}e(C,"registerNode");export{C as registerNode};
|
|
@@ -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,8 +1,8 @@
|
|
|
1
|
-
var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as de,realpathSync as H,rmdirSync as ue,rmSync as ce,statSync as le}from"node:fs";import{basename as _e,dirname as M,isAbsolute as pe,join as S,relative as fe,resolve as Ee,sep as we}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as ye}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as me,ConversationNotFoundError as Ne}from"../conversation-store/index.js";import{hasUnseenWakeMail as Re,UNSEEN_WAKE_MAIL_SQL as Se}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as he}from"../graph/events.js";import{nodeObject as Oe}from"../graph/objects.js";import{findNodeBySessionFileSql as Te}from"./sessions.js";import{hydrateFault as Le}from"./recovery.js";import{hasUnreconciledWorktree as De,openWorktree as ge,readWorktree as Ae,worktreeFromRow as ve}from"./worktrees.js";import{isPidAlive as ke,isPidPresent as z,recordedPidLiveness as Ue}from"./pid.js";import{ensureHome as xe,jobDir as je,nodeDir as We,nodeRunDir as J}from"./paths.js";import{appForNode as be,ensureNodeDirs as Ie,nodeAgentDir as Fe}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Ce,getById as D,ownerForGrantee as He,setObjectKind as Me,setObjectName as Pe}from"../graph/objects.js";import{profileObject as $e}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as qe}from"../errors.js";import{deleteNodeWithOwned as Be}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as ze,SUBTREE_IDS_SQL as Je}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function kn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(kn,"assertRunNotDeleting");async function Q(e,n,t){try{return await $e(e,n,t)}catch(a){if(a instanceof qe&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ye(e,n){const t=await He(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Ce(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Y(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ye,"seedRow");function V(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return Le(Object.fromEntries(n))}i(V,"faultFrom");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}i(f,"rowFrom");async function g(e,n){return n??=await Ae(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(g,"metaFrom");async function Un(e,n={}){return xe(),await p(async t=>{await Ye(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await ge(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Ie(e.node_id),await O(e.node_id)}i(Un,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}i(O,"getNode");async function xn(e){if(e.length===0)return[];const n=v.map(o=>`w.${o} AS worktree_${o}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,G(o)))}i(xn,"getNodes");const Qe=1440*60*1e3;function K(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(K,"createRequestRecord");async function jn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:K(n)}i(jn,"findCreateRequest");async function Wn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Qe);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return K(a)})}i(Wn,"reserveCreateRequest");async function bn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(bn,"pruneExpiredCreateRequests");async function In(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(In,"recordCreateRequestNode");async function Fn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Fn,"reserveCreateRequestNode");async function Cn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Cn,"completeCreateRequest");async function Hn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Hn,"abandonCreateRequest");function Mn(e){return Ee(e)}i(Mn,"canonicalSessionFile");async function Pn(e){const n=await Te(e);return n===null?null:await O(n)}i(Pn,"findNodeBySessionFile");async function $n(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i($n,"getRow");async function qn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(qn,"getRowByPane");async function Bn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
|
|
1
|
+
var ue=Object.defineProperty;var i=(e,n)=>ue(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as ce,realpathSync as H,rmdirSync as le,rmSync as _e,statSync as pe}from"node:fs";import{basename as fe,dirname as M,isAbsolute as we,join as S,relative as Ee,resolve as ye,sep as me}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as Ne}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as Re,ConversationNotFoundError as Se}from"../conversation-store/index.js";import{hasUnseenWakeMail as he,UNSEEN_WAKE_MAIL_SQL as Oe}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as Te}from"../graph/events.js";import{nodeObject as Le}from"../graph/objects.js";import{findNodeBySessionFileSql as De}from"./sessions.js";import{hydrateFault as ge}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as Ae,readWorktree as ke,worktreeFromRow as Ue}from"./worktrees.js";import{isPidAlive as xe,isPidPresent as z,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as We}from"./person-state.js";import{ensureHome as be,jobDir as Ie,nodeDir as Fe,nodeRunDir as J}from"./paths.js";import{appForNode as Ce,ensureNodeDirs as He,nodeAgentDir as Me}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Pe,getById as D,ownerForGrantee as $e,setObjectKind as qe,setObjectName as Be}from"../graph/objects.js";import{profileObject as ze}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as Je}from"../errors.js";import{deleteNodeWithOwned as Ye}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Qe,SUBTREE_IDS_SQL as Ve}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function w(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(w,"jsonValue");async function Wn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Wn,"assertRunNotDeleting");async function Q(e,n,t){try{return await ze(e,n,t)}catch(a){if(a instanceof Je&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ke(e,n){const t=await $e(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Pe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Y(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,w(e.persona_ack,"persona_ack"),w(e.review_binding,"review_binding"),w(e.launch,"launch"),w(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ke,"seedRow");function V(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ge(Object.fromEntries(n))}i(V,"faultFrom");const K=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),G=i(e=>e||We(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=K(e)&&G(t),n}i(f,"rowFrom");async function g(e,n){return n??=await ke(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(g,"metaFrom");async function bn(e,n={}){return be(),await p(async t=>{await Ke(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await Ae(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await He(e.node_id),await O(e.node_id)}i(bn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}i(O,"getNode");async function In(e){if(e.length===0)return[];const n=A.map(o=>`w.${o} AS worktree_${o}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,Z(o)))}i(In,"getNodes");const Ge=1440*60*1e3;function X(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(X,"createRequestRecord");async function Fn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:X(n)}i(Fn,"findCreateRequest");async function Cn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ge);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return X(a)})}i(Cn,"reserveCreateRequest");async function Hn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(Hn,"pruneExpiredCreateRequests");async function Mn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(Mn,"recordCreateRequestNode");async function Pn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Pn,"reserveCreateRequestNode");async function $n(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i($n,"completeCreateRequest");async function qn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(qn,"abandonCreateRequest");function Bn(e){return ye(e)}i(Bn,"canonicalSessionFile");async function zn(e){const n=await De(e);return n===null?null:await O(n)}i(zn,"findNodeBySessionFile");async function Jn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Jn,"getRow");async function Yn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(Yn,"getRowByPane");async function Qn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
|
|
2
2
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
|
|
3
3
|
AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
|
|
4
|
-
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(
|
|
5
|
-
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(
|
|
4
|
+
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(Qn,"dueNodeDeadlines");async function Vn(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(Vn,"setNodeDeadline");async function Kn(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
|
|
5
|
+
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(Kn,"shiftProfileNodeDeadlines");function v(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}i(v,"sqlInput");async function Gn(e,n){const t=[],a=i((r,s=r)=>{Object.prototype.hasOwnProperty.call(n,r)&&t.push([s,v(n[r],r)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",w(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",w(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",w(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",w(n.launch,"launch")]);const o=i(r=>Object.prototype.hasOwnProperty.call(n,r),"has");return await p(async r=>{const s=await D(r,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await Be(r,s,v(n.name,"name")),o("kind")&&await qe(r,s,v(n.kind,"kind")),t.length===0)return;if(o("profile_id")){const u=await r.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(r,u.app):null;if(_){const E=n.profile_id?await Q(r,n.profile_id,_):null;await r.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((E??_).id,e);const N=(await r.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;E===null&&N&&await Y(r,e,N)}}if((await r.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await O(e)}i(Gn,"updateNode");async function Xn(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(Xn,"setStatus");async function Zn(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(Zn,"setIntent");async function et(e,n,t={}){if(t.outcome===void 0){const o=[],r=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),r.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),r.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),r.push(n.terminal_reason??null));const s=["node_id = ?"];r.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),r.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${s.join(" AND ")}`).run(...r);return Number(c.changes)}const a=t.outcome;return await p(async o=>{const r=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const c=i((N,R)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${R} END`,"outcomeValue");r.push(`outcome_kind = ${c(a.kind,"outcome_kind")}`,`outcome_reason = ${c(a.reason,"outcome_reason")}`,`outcome_detail_json = ${c(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${c(a.at,"outcome_at")}`),s.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await o.prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const E=await o.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||E.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await Te(o,{event:"outcome",object:await Le(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(et,"transitionStatusIntent");async function nt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(nt,"getFinalReport");async function tt(e,n){return(await(await d()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}i(tt,"clearFinalReportIfMatches");async function at(e,n){await(await d()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}i(at,"setPresence");async function it(e,n){await(await d()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}i(it,"recordLaunch");async function ot(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(ot,"recordSettledTurn");async function rt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(rt,"setFrozen");async function st(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(st,"clearFrozen");async function dt(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(dt,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",A=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function Z(e){return e.worktree_state===null?null:Ue(Object.fromEntries(A.map(n=>[n,e[`worktree_${n}`]])))}i(Z,"worktreeFromProjection");async function ut(e){const n=A.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await h(t,async a=>await g(a,Z(a)))}i(ut,"listNodesByProfile");async function ct(){return(await(await d()).prepare(`SELECT
|
|
6
6
|
node_id, name, description, kind, mode, lifecycle, status, cwd, profile_id,
|
|
7
7
|
grantee, parent, created, frozen_at, terminal_reason, final_report,
|
|
8
8
|
telemetry_tokens_in, telemetry_updated_at, pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -10,13 +10,13 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
10
10
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
11
11
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
12
12
|
fault_provider_error_json
|
|
13
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(
|
|
13
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(ct,"browseNodes");async function lt(e,n){await(await d()).prepare(`UPDATE nodes
|
|
14
14
|
SET telemetry_tokens_in = ?,
|
|
15
15
|
telemetry_context_tokens = COALESCE(?, telemetry_context_tokens),
|
|
16
16
|
telemetry_last_activity = COALESCE(?, telemetry_last_activity),
|
|
17
17
|
telemetry_updated_at = ?
|
|
18
18
|
WHERE node_id = ?
|
|
19
|
-
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(
|
|
19
|
+
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(lt,"updateNodeTelemetry");async function _t(){return(await(await d()).prepare(`SELECT
|
|
20
20
|
node_id, name, description, cycles, kind, status, frozen_at,
|
|
21
21
|
telemetry_context_tokens, telemetry_last_activity,
|
|
22
22
|
pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -24,14 +24,14 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
24
24
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
25
25
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
26
26
|
fault_provider_error_json
|
|
27
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=z(t),o=V(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:n
|
|
27
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=z(t),o=V(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:K(n)&&G(a)}})}i(_t,"graphNodes");async function Xe(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Qe}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ve})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,o=>`\\${o}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await d()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}i(Xe,"listNodes");const Ze=`SELECT
|
|
28
28
|
node_id, created, launched_at, last_settled_at, finalized_at,
|
|
29
29
|
outcome_at, last_activity_at, pane, "window", tmux_session
|
|
30
30
|
FROM nodes
|
|
31
31
|
WHERE ${m}
|
|
32
32
|
AND status IN ('done', 'canceled', 'dead')
|
|
33
33
|
AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
|
|
34
|
-
ORDER BY created`;async function
|
|
34
|
+
ORDER BY created`;async function pt(){return await(await d()).prepare(Ze).all()}i(pt,"listTerminalPlacementResidue");const en=`WITH candidates AS MATERIALIZED (
|
|
35
35
|
SELECT node_id FROM nodes WHERE status IN ('active', 'idle')
|
|
36
36
|
UNION
|
|
37
37
|
SELECT node_id FROM nodes
|
|
@@ -45,23 +45,23 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
45
45
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
46
46
|
AND v.kind != 'human'
|
|
47
47
|
AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))
|
|
48
|
-
ORDER BY v.created`;async function
|
|
49
|
-
WHERE ${
|
|
50
|
-
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${
|
|
51
|
-
ORDER BY v.created`).all()).map(f)}i(
|
|
48
|
+
ORDER BY v.created`;async function ft(){return(await(await d()).prepare(en).all()).map(f)}i(ft,"listNodesForSupervision");const ee=i(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),nn=i(e=>`(${e}.status IN ('active', 'idle') OR ${ee(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function wt(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${nn("nodes")} AND node_id != ?`).all(e)}i(wt,"resumableNodeCwds");async function Et(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
|
|
49
|
+
WHERE ${ee("v")}
|
|
50
|
+
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Oe("d")}) AND v.kind != 'human' AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
51
|
+
ORDER BY v.created`).all()).map(f)}i(Et,"listParkedResidentsWithWakeMail");async function yt(e,n){await(await d()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}i(yt,"registerWarmSpare");async function mt(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(mt,"unregisterWarmSpare");async function k(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
|
|
52
52
|
n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
|
|
53
|
-
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function
|
|
54
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(
|
|
53
|
+
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function Nt(){return await k(await d())}i(Nt,"listWarmSpares");async function Rt(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(Rt,"isWarmSpare");function ne(e){return e.status!=="active"&&e.status!=="idle"?!1:je(e.pi_pid,e.pi_pid_identity)==="alive"}i(ne,"spareIsClaimable");async function St(e,n,t={}){return await p(async a=>{const o=(await k(a,e)).find(ne);return o===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await B(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(St,"claimWarmSpare");async function ht(e){return(await k(await d(),e)).filter(ne).length}i(ht,"warmSpareCount");async function Ot(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(Ot,"childrenOf");async function Tt(){return(await(await d()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
|
|
54
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(Tt,"rosterNodes");async function Lt(e){return(await(await d()).prepareUncached(`SELECT * FROM node_rows
|
|
55
55
|
WHERE parent IS NULL AND kind != 'human'
|
|
56
56
|
AND status IN ('active','idle') AND cwd = ?
|
|
57
57
|
AND ${m}
|
|
58
|
-
ORDER BY created DESC`).all(e)).map(f)}i(
|
|
59
|
-
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&
|
|
58
|
+
ORDER BY created DESC`).all(e)).map(f)}i(Lt,"listResumableRoots");export*from"./tree.js";async function Dt(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(Dt,"withFreshTerminalGuard");async function T(e){return await ve(e)}i(T,"hasUnreconciledManagedWorktree");async function te(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await T(e.node_id)||e.node_id===C()||q(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(te,"isCollectible");async function U(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await d()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:S(L(a.grantee).conversations,a.node_id)}])).values()]}i(U,"nodeConversationIds");async function x(e){const n=await d(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
|
|
59
|
+
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&ce(r,{throwIfNoEntry:!1})!==void 0){if(!tn(s,r)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${r}`);continue}try{await Re().delete(o,r)}catch(c){if(!(c instanceof Se))throw c}}}i(x,"deleteNodeConversations");function tn(e,n){try{const t=Ee(H(e),S(H(M(n)),fe(n)));return t!==""&&t!==".."&&!t.startsWith(`..${me}`)&&!we(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(tn,"isBeneath");async function j(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Ye(e,t),!0)}i(j,"deleteNodeObject");async function W(e){return{nodeId:e,app:await O(e)===null?null:await Ce(e)}}i(W,"nodeFiles");async function ae({nodeId:e,app:n}){n!==null&&P(L(n).nodes,await Me(e,n)),P(M(J(e)),J(e))}i(ae,"removeNodeAppTrees");function ie({nodeId:e}){return[Fe(e)]}i(ie,"nodeOwnedDirs");function oe({nodeId:e,app:n}){if(n!==null)try{le(S(L(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(oe,"removeNodeConversationDir");async function b(e){await ae(e);for(const n of ie(e))_e(n,{recursive:!0,force:!0});oe(e)}i(b,"removeNodeFiles");async function re(e){const n=await $(e);if(n.length>0)throw new Error(`the sandbox of node(s) ${n.join(", ")} could not be deleted; the node rows are kept`)}i(re,"requireSandboxesDeleted");async function gt(e){if(await T(e))return{deleted:!1};await re([e]);const n=await W(e),t=await U([e]),a=await p(async o=>(await j(o,e),{deleted:!0}));return await x(t),await b(n),a}i(gt,"deleteNode");async function vt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,T);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await re(n);const a=await h(n,W),o=await U(n),r=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await j(_,u)));await x(o);for(const u of c){const _=a[n.indexOf(u)];await F(_,async()=>await b(_))}return c}i(vt,"deleteNodes");async function At(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),r=C()??"",s=await d(),c=i(l=>de(l)<a,"quiet"),u=i(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await an(),E=(await y((await s.prepare(`SELECT * FROM node_rows
|
|
60
60
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
61
|
-
ORDER BY created`).all(o)).map(f),async l=>await
|
|
61
|
+
ORDER BY created`).all(o)).map(f),async l=>await te(l,{pastTtl:!0})&&c(l)&&!_.has(l.node_id)&&!await e.held(l.node_id))).map(u),N=t?(await y((await s.prepare(`SELECT * FROM node_rows
|
|
62
62
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
63
|
-
ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!
|
|
63
|
+
ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!xe(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!q(l)&&!await he(l.node_id)&&!await T(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await I([...E,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await se(R,e.removeDirs),dryRun:n}}i(At,"pruneNodes");async function an(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
|
|
64
64
|
JOIN objects d ON d.id = w.object AND d.type = 'document' AND d.deleted_at IS NULL
|
|
65
65
|
JOIN objects o ON o.id = w.watcher AND o.deleted_at IS NULL
|
|
66
66
|
LEFT JOIN nodes n ON n.node_id = w.watcher
|
|
67
|
-
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(
|
|
67
|
+
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(an,"ownersOfWatchedDocuments");async function I(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(r=>a.has(r.node_id)))}i(I,"retainRunRootsWithMembers");async function se(e,n){const t=new Set(await $(e.map(s=>s.node_id))),a=t.size===0?e:await I(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const o=await h(a,async s=>await W(s.node_id)),r=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await j(c,s.node_id));if(await x(r),n!==void 0){for(const s of o)await F(s,async()=>{await ae(s),oe(s)});return n(o.flatMap(ie)),a}for(const s of o)await F(s,async()=>await b(s));return a}i(se,"deletePrunedNodes");async function F(e,n){try{await n()}catch(t){Ne({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(F,"eachNodeBestEffort");function de(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=pe(S(Ie(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(de,"lastActivityMs");async function kt(e){const n=e.dryRun??!1,t=await Xe(),a=await y(t,async u=>await te(u)&&!await e.held(u.node_id)),o=t.length-a.length,r=Math.max(0,e.maxNodes-o),s=a.map(u=>({row:u,recency:de(u)})).sort((u,_)=>_.recency-u.recency).slice(r).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await I(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await se(c),dryRun:n}}i(kt,"pruneToLimit");export{ee as PARKED_RESIDENT_SQL,nn as RESUMABLE_NODE_SQL,qn as abandonCreateRequest,Wn as assertRunNotDeleting,ct as browseNodes,Bn as canonicalSessionFile,Ot as childrenOf,St as claimWarmSpare,tt as clearFinalReportIfMatches,st as clearFrozen,$n as completeCreateRequest,bn as createNode,gt as deleteNode,vt as deleteNodes,Qn as dueNodeDeadlines,Fn as findCreateRequest,zn as findNodeBySessionFile,nt as getFinalReport,O as getNode,In as getNodes,Jn as getRow,Yn as getRowByPane,_t as graphNodes,te as isCollectible,Rt as isWarmSpare,de as lastActivityMs,Xe as listNodes,ut as listNodesByProfile,ft as listNodesForSupervision,Et as listParkedResidentsWithWakeMail,Lt as listResumableRoots,pt as listTerminalPlacementResidue,Nt as listWarmSpares,W as nodeFiles,en as nodesForSupervisionSql,Hn as pruneExpiredCreateRequests,At as pruneNodes,kt as pruneToLimit,Mn as recordCreateRequestNode,it as recordLaunch,dt as recordRespawnAttempt,ot as recordSettledTurn,yt as registerWarmSpare,b as removeNodeFiles,Cn as reserveCreateRequest,Pn as reserveCreateRequestNode,wt as resumableNodeCwds,Tt as rosterNodes,rt as setFrozen,Zn as setIntent,Vn as setNodeDeadline,at as setPresence,Xn as setStatus,Kn as shiftProfileNodeDeadlines,Ze as terminalPlacementResidueSql,et as transitionStatusIntent,mt as unregisterWarmSpare,Gn as updateNode,lt as updateNodeTelemetry,ht as warmSpareCount,Dt as withFreshTerminalGuard};
|
|
@@ -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};
|