@north-light/cli 0.3.756 → 0.3.757

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.
@@ -1 +1 @@
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};
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{resolveExistingProjectDir as u}from"../../core/profiles/project-dir.js";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};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(e,r)=>l(e,"name",{value:r,configurable:!0});import{defineLeaf as i,defineBranch as c}from"../../core/command.js";import{resolve as p}from"node:path";import{usage as h}from"../../core/errors.js";import{cliClient as n}from"../api-client.js";import{resolveProfileViaDaemon as a}from"./daemon-profiles.js";import{PROFILE_PROJECT_MEMORY_VALUES as f}from"../../api/dto/profiles.js";const m=i({name:"add",description:"add a project to a profile's purview",whenToUse:"a profile needs purview over another project directory \u2014 extend it after creation.",help:{name:"profile project add",summary:"add a project relationship to a profile, deduped by real path",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!1,constraint:"Directory to add; exactly one of `--dir` and `--repo`. Must exist and be a directory; resolved to its absolute real path before storing. The repo its checkout identifies as is stored with it; a folder no repo identifies keeps the path only. A path already on the profile keeps its position and nothing changes."},{kind:"flag",name:"repo",type:"string",required:!1,constraint:"Repo handle to add with no folder; exactly one of `--dir` and `--repo`. Must name a repo you may read. A node with no checkout (a sandbox) still gets that repo's documents."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{repo?, path?}` entries in profile order. `path` defines purview for config; `repo` is the repo object id whose documents join the view."}],outputKind:"object",effects:["Appends a new project relationship (a folder, with the repo it identifies as, or a repo alone) to the profile row. Purview follows `path` for config, and every repo enclosing `path` joins the view of every node of the profile: its documents are readable, listed, and delivered at boot and workspace-open. Each such repo starts at a `preview` delivery limit unless the profile already limits that handle (change it with `profile project limit`). Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=e.dir,s=e.repo;if(o===void 0==(s===void 0))throw h("pass exactly one of --dir and --repo",{next:"Use --dir <directory> for a folder or --repo <handle> for a repo with no folder."});const d=await n().updateProfile(r,{add_project:o!==void 0?{path:p(o)}:{repo:s}});return{profile_id:d.id,projects:d.projects}},"run")}),u=i({name:"remove",description:"remove a project relationship from a profile's purview",whenToUse:"a profile no longer needs purview over one of its listed project directories \u2014 narrow it back. Works even if the directory itself was since deleted.",help:{name:"profile project remove",summary:"remove a project directory from a profile's manifest",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!0,constraint:"Directory to remove, matched against the stored project `path`. Does not require the directory to still exist on disk. The profile's app home does not change."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{path}` relationships in profile order."}],outputKind:"object",effects:["Removes a project relationship from the profile row. This narrows purview and drops the path's repos from the view of the profile's nodes (unless a node's cwd is inside them); delivery limits are left in place. Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{remove_project:p(e.dir)});return{profile_id:o.id,projects:o.projects}},"run")}),w=i({name:"limit",description:"set how much of one owner's documents automatic delivery may disclose",whenToUse:"a profile's nodes should get less of one owner's documents (a repo, `user`, an app, a plugin) at boot and workspace-open \u2014 or that limit should be lifted.",help:{name:"profile project limit",summary:"set a profile's automatic delivery limit for one owner handle",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"owner",type:"string",required:!0,constraint:"Owner the limit applies to. A bare handle (`crouter`, `user`) matches an owner of any type holding that handle. `<type>:<handle>` names one owner exactly \u2014 `repo:crouter`, `profile:work`, `app:terminal`, `person:user` \u2014 and wins over a bare key; use it when a repo and another owner share a handle. A profile's own documents are never capped, whichever key matches."},{kind:"flag",name:"level",type:"enum",choices:[...f],required:!0,constraint:"Maximum automatic delivery of this owner's documents at boot and workspace-open: `none`, `name`, `preview`, or `content`. `content` is no limit and removes the entry. Does not change explicit `crtr canvas read` access."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"delivery_limits",type:"object",required:!0,constraint:"The profile\u2019s limits after the change, keyed by owner handle or `<type>:<handle>`; an owner not listed is not limited."}],outputKind:"object",effects:["Sets or removes one entry in the profile's `delivery_limits`. It caps only automatic `boot` and `workspace-open` delivery; a node's own documents and its own profile's documents are never capped. A `<type>:<handle>` key (for example `repo:crouter`) names one owner exactly and wins over a bare handle key."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{set_delivery_limit:{owner:e.owner,level:e.level}});return{profile_id:o.id,delivery_limits:o.delivery_limits}},"run")}),x=c({name:"project",description:"manage a profile's project purview and automatic delivery limits",whenToUse:"changing a profile\u2019s project purview after creation, or limiting how much of one owner's documents its nodes get automatically.",help:{name:"profile project",summary:"manage project purview and per-owner automatic delivery limits",model:"Each `{path}` relationship widens purview: the profile resolves config from `path`, and every node of the profile sees the repos enclosing `path` in addition to the repos enclosing its own cwd (cwd repos first, then projects in manifest order). Rule `if: {repo}` conditions hold for any of those repos (cwd repos and project repos); `--owner repo` stays with the cwd's repos, while a node may change a project repo's documents when its file permissions allow writing that checkout. `add` appends a new real path and starts its repos at a `preview` limit; `remove` narrows purview. `limit` sets the profile's `delivery_limits` entry for one owner handle, which caps automatic boot and workspace-open delivery of that owner's documents, whether the repo is in view through the cwd or the project list; explicit reads are not capped. Purview and delivery limits are both independent of a per-cwd default pin (`crtr profile default`)."},children:[m,u,w]});export{x as projectBranch};
1
+ var p=Object.defineProperty;var t=(e,r)=>p(e,"name",{value:r,configurable:!0});import{defineLeaf as i,defineBranch as l}from"../../core/command.js";import{resolve as c}from"node:path";import{resolveExistingProjectDir as h}from"../../core/profiles/project-dir.js";import{usage as f}from"../../core/errors.js";import{cliClient as n}from"../api-client.js";import{resolveProfileViaDaemon as a}from"./daemon-profiles.js";import{PROFILE_PROJECT_MEMORY_VALUES as m}from"../../api/dto/profiles.js";const u=i({name:"add",description:"add a project to a profile's purview",whenToUse:"a profile needs purview over another project directory \u2014 extend it after creation.",help:{name:"profile project add",summary:"add a project relationship to a profile, deduped by real path",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!1,constraint:"Directory to add; exactly one of `--dir` and `--repo`. Must exist and be a directory; resolved to its absolute real path before storing. The repo its checkout identifies as is stored with it; a folder no repo identifies keeps the path only. A path already on the profile keeps its position and nothing changes."},{kind:"flag",name:"repo",type:"string",required:!1,constraint:"Repo handle to add with no folder; exactly one of `--dir` and `--repo`. Must name a repo you may read. A node with no checkout (a sandbox) still gets that repo's documents."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{repo?, path?}` entries in profile order. `path` defines purview for config; `repo` is the repo object id whose documents join the view."}],outputKind:"object",effects:["Appends a new project relationship (a folder, with the repo it identifies as, or a repo alone) to the profile row. Purview follows `path` for config, and every repo enclosing `path` joins the view of every node of the profile: its documents are readable, listed, and delivered at boot and workspace-open. Each such repo starts at a `preview` delivery limit unless the profile already limits that handle (change it with `profile project limit`). Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=e.dir,s=e.repo;if(o===void 0==(s===void 0))throw f("pass exactly one of --dir and --repo",{next:"Use --dir <directory> for a folder or --repo <handle> for a repo with no folder."});const d=await n().updateProfile(r,{add_project:o!==void 0?{path:h(o)}:{repo:s}});return{profile_id:d.id,projects:d.projects}},"run")}),w=i({name:"remove",description:"remove a project relationship from a profile's purview",whenToUse:"a profile no longer needs purview over one of its listed project directories \u2014 narrow it back. Works even if the directory itself was since deleted.",help:{name:"profile project remove",summary:"remove a project directory from a profile's manifest",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!0,constraint:"Directory to remove, matched against the stored project `path`. Does not require the directory to still exist on disk. The profile's app home does not change."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{path}` relationships in profile order."}],outputKind:"object",effects:["Removes a project relationship from the profile row. This narrows purview and drops the path's repos from the view of the profile's nodes (unless a node's cwd is inside them); delivery limits are left in place. Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{remove_project:c(e.dir)});return{profile_id:o.id,projects:o.projects}},"run")}),y=i({name:"limit",description:"set how much of one owner's documents automatic delivery may disclose",whenToUse:"a profile's nodes should get less of one owner's documents (a repo, `user`, an app, a plugin) at boot and workspace-open \u2014 or that limit should be lifted.",help:{name:"profile project limit",summary:"set a profile's automatic delivery limit for one owner handle",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"owner",type:"string",required:!0,constraint:"Owner the limit applies to. A bare handle (`crouter`, `user`) matches an owner of any type holding that handle. `<type>:<handle>` names one owner exactly \u2014 `repo:crouter`, `profile:work`, `app:terminal`, `person:user` \u2014 and wins over a bare key; use it when a repo and another owner share a handle. A profile's own documents are never capped, whichever key matches."},{kind:"flag",name:"level",type:"enum",choices:[...m],required:!0,constraint:"Maximum automatic delivery of this owner's documents at boot and workspace-open: `none`, `name`, `preview`, or `content`. `content` is no limit and removes the entry. Does not change explicit `crtr canvas read` access."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"delivery_limits",type:"object",required:!0,constraint:"The profile\u2019s limits after the change, keyed by owner handle or `<type>:<handle>`; an owner not listed is not limited."}],outputKind:"object",effects:["Sets or removes one entry in the profile's `delivery_limits`. It caps only automatic `boot` and `workspace-open` delivery; a node's own documents and its own profile's documents are never capped. A `<type>:<handle>` key (for example `repo:crouter`) names one owner exactly and wins over a bare handle key."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{set_delivery_limit:{owner:e.owner,level:e.level}});return{profile_id:o.id,delivery_limits:o.delivery_limits}},"run")}),q=l({name:"project",description:"manage a profile's project purview and automatic delivery limits",whenToUse:"changing a profile\u2019s project purview after creation, or limiting how much of one owner's documents its nodes get automatically.",help:{name:"profile project",summary:"manage project purview and per-owner automatic delivery limits",model:"Each `{path}` relationship widens purview: the profile resolves config from `path`, and every node of the profile sees the repos enclosing `path` in addition to the repos enclosing its own cwd (cwd repos first, then projects in manifest order). Rule `if: {repo}` conditions hold for any of those repos (cwd repos and project repos); `--owner repo` stays with the cwd's repos, while a node may change a project repo's documents when its file permissions allow writing that checkout. `add` appends a new real path and starts its repos at a `preview` limit; `remove` narrows purview. `limit` sets the profile's `delivery_limits` entry for one owner handle, which caps automatic boot and workspace-open delivery of that owner's documents, whether the repo is in view through the cwd or the project list; explicit reads are not capped. Purview and delivery limits are both independent of a per-cwd default pin (`crtr profile default`)."},children:[u,w,y]});export{q as projectBranch};
@@ -1 +1 @@
1
- var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as m,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as p,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const j=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",x="root";function d(e){return e.grantee??"app:terminal"}a(d,"profileApp");function g(e,t){Y(P(d(t),e).dir)}a(g,"scaffoldProfile");function $(e){if(!j.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=m(e);if(t===null)throw p(`profile not found: ${e}`,{received:e});return P(d(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const t=h(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=m(e);if(t!==null)return t;throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(j.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return p(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(h(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(h(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(m(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=h().find(r=>r.manifest.name===x&&d(r.manifest)==="app:terminal");return n!==void 0?(g(n.profileId,n.manifest),n):await q(x,[],{grantee:"app:terminal"})}const e=m(v)??h().find(n=>n.manifest.name===x&&d(n.manifest)==="app:terminal")??null;if(e!==null)return g(e.profileId,e.manifest),e;const t={schema_version:k,name:x,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return g(v,t),await w(n=>n.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:t}}]),m(v)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:y(),last_used_at:null};g(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:d(s),person:n.appEnvironment===!0?d(s):te(),...n.appEnvironment===!0?{payer:n.payer??d(s)}:{},...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=h().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),m(e)===null)throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw p(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:y()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!j.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??y()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw p(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=P(d(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw p(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{v as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,h as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
1
+ var q=Object.defineProperty;var a=(e,n)=>q(e,"name",{value:n,configurable:!0});import{randomUUID as H}from"node:crypto";import{realpathSync as W,rmSync as S}from"node:fs";import{isAbsolute as Z,resolve as G}from"node:path";import{resolveExistingProjectDir as V}from"./project-dir.js";import{SCHEMA_VERSION as M}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as k}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as m,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as l,notFound as p,ambiguous as C,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as j,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const $=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",g="root";function d(e){return e.grantee??"app:terminal"}a(d,"profileApp");function x(e,n){Y(P(d(n),e).dir)}a(x,"scaffoldProfile");function _(e){if(!$.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."})}a(_,"assertSafeProfileId");function Ae(e){_(e);const n=m(e);if(n===null)throw p(`profile not found: ${e}`,{received:e});return P(d(n.manifest),e).dir}a(Ae,"profileDir");function b(e){if(!Array.isArray(e))throw l("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const n of e){if(typeof n!="object"||n===null||Array.isArray(n))throw l(`invalid project entry: ${JSON.stringify(n)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:t,repo:r}=n;for(const[i,o]of[["path",t],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw l(`project entry has an invalid ${i}: ${JSON.stringify(n)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(t===void 0&&r===void 0)throw l(`project entry has neither path nor repo: ${JSON.stringify(n)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(b,"assertProfileProjects");function re(e){const n=k.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: ${n}.`});for(const[t,r]of Object.entries(e)){if(t.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 r!="string"||!k.includes(r))throw l(`invalid delivery limit for ${t}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${t} to one of: ${n}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const n=h(),t=D(n,e,A);return t?{kind:"resolved",entry:t}:{kind:"absent"}}a(oe,"lookupProfile");function N(e){_(e);const n=m(e);if(n!==null)return n;throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(N,"loadExactProfileManifest");const A=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function D(e,n,t){if($.test(n)){const i=e.find(o=>t(o).profileId===n);if(i!==void 0)return i}const r=e.filter(i=>t(i).name===n);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>t(o).profileId);throw C(`profile name "${n}" matches ${i.length} profiles: ${i.join(", ")}`,{received:n,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(D,"findExactProfile");function L(e,n,t){const r=e.map(i=>`${t(i).profileId} (${t(i).name})`);return p(`profile not found: ${n}`,{received:n,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(L,"profileNotFound");function ae(e){const n=oe(e);if(n.kind==="resolved")return n.entry;throw L(h(),e,A)}a(ae,"loadProfileManifest");function Ee(e){return se(h(),e,A)}a(Ee,"resolveProfileOperand");function se(e,n,t){const r=D(e,n,t);if(r!==null)return r;const{match:i,tied:o}=ee(n,e.map(t));if(i!==null){const s=e.find(f=>t(f).profileId===i.profileId);return console.error(`crtr: no profile named "${n}" \u2014 using the closest match: ${t(s).name} (${t(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw C(`"${n}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:n,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw L(e,n,t)}a(se,"matchProfileOperand");function z(e){if(!j())return V(e);if(!Z(e))throw l(`project directory must be an absolute path: ${e}`,{received:e});return e}a(z,"storedProjectDir");function E(e){const n=new Set,t=new Map,r=[];for(const i of e)if(i.path!==void 0){if(n.has(i.path))continue;n.add(i.path);const o=i.repo===void 0?void 0:t.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(t.has(i.repo))continue;t.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(E,"dedupeProjects");function fe(e){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return n.length>40&&(n=n.slice(0,40).replace(/-+$/g,"")),n.length>0?n:"profile"}a(fe,"slugify");function le(e){const n=fe(e);for(let t=0;t<20;t++){const r=H().replace(/-/g,"").slice(0,8),i=`${n}-${r}`;if(m(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(le,"generateProfileId");let O=null;function Oe(e){O=e}a(Oe,"setCloudProfileWriter");async function Re(){if(j()){const t=h().find(r=>r.manifest.name===g&&d(r.manifest)==="app:terminal");return t!==void 0?(x(t.profileId,t.manifest),t):await F(g,[],{grantee:"app:terminal"})}const e=m(v)??h().find(t=>t.manifest.name===g&&d(t.manifest)==="app:terminal")??null;if(e!==null)return x(e.profileId,e.manifest),e;const n={schema_version:M,name:g,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return x(v,n),await w(t=>t.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:n}}]),m(v)}a(Re,"ensureRootProfile");const J=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function T(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(T,"metadataEnvName");function R(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 n=new Map;for(const[t,r]of Object.entries(e)){if(!J.test(t))throw l(`invalid metadata key: ${JSON.stringify(t)}`,{received:t,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw l(`metadata value for ${t} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw l(`metadata value for ${t} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=T(t),o=n.get(i);if(o!==void 0)throw l(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(t)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});n.set(i,t)}}a(R,"assertProfileMetadata");function U(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const n={},t=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!J.test(r)||i.includes("\0"))continue;const o=T(r);t.has(o)||(t.add(o),n[r]=i)}return n}a(U,"sanitizeProfileMetadata");async function F(e,n=[],t={}){const r=e.trim();if(r==="")throw l("profile name must not be empty");t.metadata!==void 0&&R(t.metadata),b(n);const i=E(n.map(c=>({...c.repo===void 0?{}:{repo:c.repo},...c.path===void 0?{}:{path:z(c.path)}}))),o=le(r),s={schema_version:M,name:r,projects:i,paused_at:null,...t.grantee===void 0?{}:{grantee:t.grantee},...t.defaultKind!==void 0?{default_kind:t.defaultKind}:{},...t.metadata!==void 0&&Object.keys(t.metadata).length>0?{metadata:{...t.metadata}}:{},created_at:y(),last_used_at:null};x(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(j()){if(O===null)throw new Error("a cloud role has no profile environment writer registered");await O({profileId:o,grantee:d(s),person:t.appEnvironment===!0?d(s):te(),...t.appEnvironment===!0?{payer:t.payer??d(s)}:{},...t.memoryMb===void 0?{}:{memoryMb:t.memoryMb},...t.recipe===void 0?{}:{recipe:t.recipe}},async c=>{s.environment_id=c,await f()})}else{const c=ne();c!==void 0&&(s.environment_id=c.environmentId),await f()}return{profileId:o,manifest:s}}a(F,"createProfile");async function Se(e){if(!e.startsWith("app:")||e.length<=4)throw l("an app grantee is required");const n=`app-${e.slice(4)}`,t=h().filter(r=>r.manifest.name===n&&r.manifest.grantee===e);if(t.length>1)throw new Error(`duplicate default profile for ${e}`);return t[0]?t[0]:await F(n,[],{grantee:e})}a(Se,"ensureAppProfile");function K(e){if(_(e),m(e)===null)throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(K,"requireExistingProfile");async function u(e,n){K(e);let t;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw p(`profile not found: ${e}`,{received:e});return t={profileId:e,manifest:n(structuredClone(i.manifest))},[{op:"profile.update",profile:t}]}),t}a(u,"mutateManifest");async function Me(e){return await u(e,n=>({...n,last_used_at:y()}))}a(Me,"updateProfileLastUsed");function ce(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(ce,"loadProfileManifestOrNull");function ke(e){return e==null||e===""||!$.test(e)?!1:Q(e)}a(ke,"isProfilePaused");function Ce(){return B()}a(Ce,"pausedCanvasProfiles");function ue(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}\`.`})}a(ue,"assertProfileEntryActive");function Ne(e){const n=ce(e);return n===null?null:(ue(n),n)}a(Ne,"assertProfileActive");async function De(e){return await u(e,n=>({...n,paused_at:n.paused_at??y()}))}a(De,"pauseProfile");async function Le(e){let n=null;return{...await u(e,r=>(n=r.paused_at,{...r,paused_at:null})),pausedAt:n}}a(Le,"resumeProfile");async function ze(e,n){return await u(e,t=>({...t,default_kind:n}))}a(ze,"setProfileDefaultKind");async function Je(e,n,t=[]){return R(n),await u(e,r=>{const i={...U(r.metadata),...n};for(const f of t)delete i[f];R(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(Je,"updateProfileMetadata");function Te(e){if(e===null||e==="")return{};try{return U(N(e).manifest.metadata)}catch{return{}}}a(Te,"readProfileMetadata");async function Ue(e,n){const t=n.trim();if(t==="")throw l("profile name must not be empty");return await u(e,i=>({...i,name:t}))}a(Ue,"renameProfile");async function Fe(e,n,t){b([{path:n,...t===void 0?{}:{repo:t}}]);const r=z(n);return await u(e,i=>({...i,projects:E(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&t!==void 0?{...o,repo:t}:o):[...i.projects,{path:r,...t===void 0?{}:{repo:t}}])}))}a(Fe,"addProfileProject");async function Ke(e,n){return b([{repo:n}]),await u(e,t=>({...t,projects:t.projects.some(r=>r.repo===n)?t.projects:E([...t.projects,{repo:n}])}))}a(Ke,"addProfileRepo");async function qe(e,n,t){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===t))return i;const o=i.projects.map(s=>s.path!==n||s.repo!==void 0?s:(r=!0,{...s,repo:t}));return r?{...i,projects:o}:i}),r}a(qe,"fillProfileProjectRepo");async function He(e,n,t){return re({[n]:t}),await u(e,r=>{const{[n]:i,...o}=r.delivery_limits??{},s=t==="content"?o:{...o,[n]:t},{delivery_limits:f,...c}=r;return Object.keys(s).length===0?c:{...c,delivery_limits:s}})}a(He,"setProfileDeliveryLimit");async function We(e,n){const t=G(n);let r=t;try{r=W(t)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==t);if(s.length===o.projects.length)throw p(`project not found on profile: ${n}`,{received:n,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(We,"removeProfileProject");async function Ze(e){K(e);const n=P(d(N(e).manifest),e);await w(t=>{if(!t.profiles.some(r=>r.profileId===e))throw p(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),S(n.dir,{recursive:!0,force:!0}),S(n.env,{force:!0})}a(Ze,"deleteProfile");export{v as ROOT_PROFILE_ID,Fe as addProfileProject,Ke as addProfileRepo,re as assertDeliveryLimits,Ne as assertProfileActive,ue as assertProfileEntryActive,R as assertProfileMetadata,b as assertProfileProjects,F as createProfile,Ze as deleteProfile,Se as ensureAppProfile,Re as ensureRootProfile,qe as fillProfileProjectRepo,ke as isProfilePaused,h as listProfiles,N as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,T as metadataEnvName,De as pauseProfile,Ce as pausedCanvasProfiles,Ae as profileDir,Te as readProfileMetadata,We as removeProfileProject,Ue as renameProfile,Ee as resolveProfileOperand,Le as resumeProfile,U as sanitizeProfileMetadata,Oe as setCloudProfileWriter,ze as setProfileDefaultKind,He as setProfileDeliveryLimit,Me as updateProfileLastUsed,Je as updateProfileMetadata};
@@ -0,0 +1,3 @@
1
+ /** A project directory as an absolute real path; it must exist and be a directory on THIS machine's disk.
2
+ * The CLI runs this on the caller's machine before sending a path to a canvas that may live in the cloud. */
3
+ export declare function resolveExistingProjectDir(dir: string): string;
@@ -0,0 +1 @@
1
+ var o=Object.defineProperty;var e=(r,t)=>o(r,"name",{value:t,configurable:!0});import{existsSync as s,realpathSync as i,statSync as c}from"node:fs";import{resolve as n}from"node:path";import{usage as a}from"../errors.js";function f(r){const t=n(r);if(!s(t)||!c(t).isDirectory())throw a(`project directory does not exist or is not a directory: ${r}`,{received:r,next:"Pass an existing directory path."});try{return i(t)}catch{return t}}e(f,"resolveExistingProjectDir");export{f as resolveExistingProjectDir};
@@ -1 +1 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as $}from"../../../core/graph/jobs.js";import{boundFleet as F}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const I="root",ye=4096;function v(t,e=[]){return{...me(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();k(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new p(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await z(e,r,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ie(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=F();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&V(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await S(a.node_id)!==null)&&le.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>$(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await he(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(!ve(e)||T(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Re(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await q(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await X(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=O(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,q as requireUsableProfile};
1
+ var M=Object.defineProperty;var o=(t,e)=>M(t,"name",{value:e,configurable:!0});import{openDb as S}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as $}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as F}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as V}from"../../../core/graph/jobs.js";import{boundFleet as C}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as B}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as G}from"../reader.js";import{canRead as H}from"../../../core/graph/access.js";import{ownersByHandle as K}from"../../../core/graph/names.js";import{reposForCwd as U,warmCheckoutIdentities as W}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as J}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as f}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as Y}from"../../../core/env-name.js";import{listProfileEnvNames as z,removeProfileEnvVar as Q,setProfileEnvVar as X}from"../../../core/profiles/env-store.js";import{isDeploymentName as Z,listAppEnvNames as x,removeAppEnvVar as ee,setAppEnvVar as te}from"../../../core/profiles/app-env-store.js";import{addProfileProject as A,addProfileRepo as ae,assertDeliveryLimits as re,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as ie,listProfiles as u,loadProfileManifest as E,pauseProfile as ne,removeProfileProject as oe,renameProfile as se,resumeProfile as de,setProfileDefaultKind as fe,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as le}from"../../profile-delete.js";import{brokerSignalBus as me}from"../../broker-signals/bus.js";import{toProfileDTO as ue}from"../map.js";import{isCloudRole as I,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as k}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const O="root",ye=4096;function v(t,e=[]){return{...ue(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await k()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function R(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new f(400,"invalid_request",`${t} already has a profile named ${e}`)}o(R,"assertNameFree");async function m(t,e){const r=await N(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new f(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();R(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const p=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(p)}}if(!I())throw new f(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new f(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await J(a,t,r),await se(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){if(I()){await A(t,r);return}await W(r);const i=(await w(async n=>await U(n,r)))[0];await A(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await G(n,t);for(const p of await K(n,a,"repo"))if(await H(n,s,p))return p;return null});if(i===null)throw new f(404,"not_found",`no repo you can read is named ${a}`);await ae(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&R(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&re({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await fe(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await oe(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await z(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=Y(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function q(t){const e=D(t);if(Z(e)&&!g(t.principal))throw new f(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(q,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await X(e,r,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Q(e,r)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===O&&a==="app:terminal")return{status:200,body:await l(await ie())};if(e===O)throw new f(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ne(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=C();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&B(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await de(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await F(a.node_id)!==null)&&me.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await $(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>V(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function L(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await S(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await he(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(!ve(e)||T(e.scopes,s))})}o(L,"visibleProfiles");async function N(t,e){const r=await L(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new f(404,"not_found","profile not found");if(i.length>1)throw new f(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(N,"requireUsableProfile");async function Re(t){const e=await k();return{status:200,body:(await L(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await N(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return le((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await x(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=q(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await te(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await ee(c(t),q(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,N as requireUsableProfile};
@@ -1,19 +1,19 @@
1
- var Qe=Object.defineProperty;var a=(e,s)=>Qe(e,"name",{value:s,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as lr}from"node:path";import{envCrtrdTcp as dr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as le}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as lt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as dt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as de}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Ut}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Ht,ensurePostgresHealthy as zt,stopPostgres as Wt,withPostgresStartLock as qt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as Kt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Vt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Yt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Jt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Qt,readBuiltinSnapshot as Xt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Zt,reapStaleSpares as en}from"../core/runtime/warm-pool.js";import{DaemonFleet as rn}from"./fleet.js";import{copyNodeFilesToRows as tn}from"../core/runtime/first-boot-rows.js";import{emitEvent as d}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as nn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as on}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as $i}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const an=5e3,Ge=150;async function sn(e){const s=Ce();if(s===null)throw d({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const m=wr(),c=[];for(const[i,l]of s.processes){const u=l.command;if(l.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const l=xt(i.pid);if(l===null||!l.includes("broker-cli.js")||!me(l,m)||fe(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+an;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(l)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(l,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw d({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const v=[];for(const[i,l]of w.processes){const u=l.command;l.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);d({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(sn,"reapPriorEpochBrokers");const ln=5e3;async function dn(e){const s=Array.from(e.entries());if(s.length===0)return;for(const[o]of s){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=s.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,ln).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of s)await at(o,{reason:"daemon-teardown"});d({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(lr(le()),{recursive:!0}),nr(le(),[process.pid,...e].join(`
2
- `),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function cn(e){const s=le();let m;try{m=or(s,"utf8")}catch(c){if(Fe(c))return;throw c}if(m.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(s)}catch(c){if(Fe(c))return;throw c}}a(cn,"removeOwnedPidfileMirror");const pn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const mn=new et,fn=new Zr,Be=new rt,un=new tt,wn=new nt,hn=new ot,vn=new it,gn=new ct,Sn=new pt,_n=new mt,yn=new ut,kn=new ft,bn=new ht,Rn=new vt,En=new gt,Pn=new St,xn=new _t,Dn=new yt,In=new kt;Rt();const Tn=new bt;async function Cn(e=Date.now(),s=pn){const m=Ne(),c=await Y.runFleetPreamble(m);let h,o,f;try{o=await de();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){d({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:s,held:o}),await mn.run(e,{rows:h,held:o}),await fn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await un.run(e,o),await In.run(e,o),await Tn.run(e,{lifecycle:s}),await wn.run(e,{lifecycle:s,held:o}),await hn.run(e,{lifecycle:s}),await vn.run(e,{lifecycle:s}),await gn.run(e,{lifecycle:s}),await Sn.run(e,{lifecycle:s,fleet:m,held:o}),_n.run(e,{lifecycle:s}),yn.run(e,{lifecycle:s}),kn.run(e,{lifecycle:s}),bn.run(e,{lifecycle:s}),Rn.run(e,{lifecycle:s}),En.run(e,{lifecycle:s}),Pn.run(e,{lifecycle:s}),await fr(),Dn.run(e,{fleet:m,lifecycle:s}),await xn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:s,thresholds:c,frozen:S})}a(Cn,"superviseTick");async function An(e,s=Date.now()){if((await de()).has(e))return;const m=await lt(e);if(m===null||!st(m))return;const c=await br(e);c===null||c.kind==="human"||await Be.runNode(s,c,Ne())}a(An,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const Ln=66e4;function $n(e){const s=new Pr().registerAll(xr(()=>null).filter(l=>l.pattern==="/healthz")),m=a((l,u)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){s.handle(l,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),c=ur();R(c)&&ke(c);const h=be(m),o=new Promise((l,u)=>{h.once("error",u),h.listen(c,()=>{h.off("error",u),sr(c,384),l()})});let f,S=null,w=o;const v=e.tcp??dr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const l=/^(.*):(\d+)$/.exec(v.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>d({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const b=u.address();S=`${b.address}:${b.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([xe(h,new Set,l.graceMs),f===void 0?Promise.resolve():xe(f,new Set,l.graceMs)]);try{R(c)&&ke(c)}catch{}}}}}a($n,"createProbeServer");const Nn="daemon is draining for shutdown and admits no new work";async function Mn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const s=a(n=>{process.stderr.write(`[crtrd] ${n}
4
- `)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);Vt(J(e.role));const h=a(async()=>c?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await qt(async()=>({database:await Ht({log:s,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
1
+ var Qe=Object.defineProperty;var a=(e,d)=>Qe(e,"name",{value:d,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as dr}from"node:path";import{envCrtrdTcp as lr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as de}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as dt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as lt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as le}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{ensurePostgres as Ut,ensurePostgresHealthy as Ht,stopPostgres as zt,withPostgresStartLock as Wt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Kt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Vt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Yt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Jt,readBuiltinSnapshot as Qt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Xt,reapStaleSpares as Zt}from"../core/runtime/warm-pool.js";import{DaemonFleet as en}from"./fleet.js";import{copyNodeFilesToRows as rn}from"../core/runtime/first-boot-rows.js";import{emitEvent as l}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as tn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as nn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Ai}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const on=5e3,Ge=150;async function an(e){const d=Ce();if(d===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const m=wr(),c=[];for(const[i,s]of d.processes){const u=s.command;if(s.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const s=xt(i.pid);if(s===null||!s.includes("broker-cli.js")||!me(s,m)||fe(s)===e||s.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+on;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const s=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(s)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(s,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const v=[];for(const[i,s]of w.processes){const u=s.command;s.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);l({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(an,"reapPriorEpochBrokers");const sn=5e3;async function dn(e){const d=Array.from(e.entries());if(d.length===0)return;for(const[o]of d){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=d.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,sn).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of d)await at(o,{reason:"daemon-teardown"});l({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(dr(de()),{recursive:!0}),nr(de(),[process.pid,...e].join(`
2
+ `),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function ln(e){const d=de();let m;try{m=or(d,"utf8")}catch(c){if(Fe(c))return;throw c}if(m.split(`
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(d)}catch(c){if(Fe(c))return;throw c}}a(ln,"removeOwnedPidfileMirror");const cn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const pn=new et,mn=new Zr,Be=new rt,fn=new tt,un=new nt,wn=new ot,hn=new it,vn=new ct,gn=new pt,Sn=new mt,_n=new ut,yn=new ft,kn=new ht,bn=new vt,Rn=new gt,En=new St,Pn=new _t,xn=new yt,Dn=new kt;Rt();const In=new bt;async function Tn(e=Date.now(),d=cn){const m=Ne(),c=await Y.runFleetPreamble(m);let h,o,f;try{o=await le();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){l({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:d,held:o}),await pn.run(e,{rows:h,held:o}),await mn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await fn.run(e,o),await Dn.run(e,o),await In.run(e,{lifecycle:d}),await un.run(e,{lifecycle:d,held:o}),await wn.run(e,{lifecycle:d}),await hn.run(e,{lifecycle:d}),await vn.run(e,{lifecycle:d}),await gn.run(e,{lifecycle:d,fleet:m,held:o}),Sn.run(e,{lifecycle:d}),_n.run(e,{lifecycle:d}),yn.run(e,{lifecycle:d}),kn.run(e,{lifecycle:d}),bn.run(e,{lifecycle:d}),Rn.run(e,{lifecycle:d}),En.run(e,{lifecycle:d}),await fr(),xn.run(e,{fleet:m,lifecycle:d}),await Pn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:d,thresholds:c,frozen:S})}a(Tn,"superviseTick");async function Cn(e,d=Date.now()){if((await le()).has(e))return;const m=await dt(e);if(m===null||!st(m))return;const c=await br(e);c===null||c.kind==="human"||await Be.runNode(d,c,Ne())}a(Cn,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const An=66e4;function Ln(e){const d=new Pr().registerAll(xr(()=>null).filter(s=>s.pattern==="/healthz")),m=a((s,u)=>{const _=(s.url??"/").split("?")[0];if((s.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){d.handle(s,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),c=ur();R(c)&&ke(c);const h=be(m),o=new Promise((s,u)=>{h.once("error",u),h.listen(c,()=>{h.off("error",u),sr(c,384),s()})});let f,S=null,w=o;const v=e.tcp??lr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const s=/^(.*):(\d+)$/.exec(v.trim());if(s===null||Number(s[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>l({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(s[2]),s[1]===""?"0.0.0.0":s[1],()=>{const b=u.address();S=`${b.address}:${b.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(s={}){if(!i){i=!0,await Promise.all([xe(h,new Set,s.graceMs),f===void 0?Promise.resolve():xe(f,new Set,s.graceMs)]);try{R(c)&&ke(c)}catch{}}}}}a(Ln,"createProbeServer");const $n="daemon is draining for shutdown and admits no new work";async function Nn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const d=a(n=>{process.stderr.write(`[crtrd] ${n}
4
+ `)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);Kt(J(e.role));const h=a(async()=>c?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await Wt(async()=>({database:await Ut({log:d,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
5
5
  `);else{const n=[f.incumbentPid!==void 0?`pid ${f.incumbentPid}`:void 0,f.verdict!==void 0?`verdict ${f.verdict}`:void 0].filter(t=>t!==void 0),r=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${f.reason}${r}
6
- `),f.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,l=null,u,_="";try{c&&await sn(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
7
- `);await jt(),await Ut(o.url,s),e.role===void 0&&on({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>d({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Xt()}catch(p){d({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Qt(p,r,"release")));l=await pe(async p=>await Jt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
8
- `)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Yt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
6
+ `),f.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,s=null,u,_="";try{c&&await an(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
7
+ `);await jt(),e.role===void 0&&nn({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>l({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Qt()}catch(p){l({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Jt(p,r,"release")));s=await pe(async p=>await Yt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
8
+ `)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Vt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
9
9
  `);for(const t of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${t.path}: ${t.error}
10
10
  `);for(const t of r.quarantined)process.stderr.write(`[crtrd] plugin "${t.name}" has a damaged ${t.file} (${t.reason}); ${t.movedTo!==void 0?`moved to ${t.movedTo}`:"left in place and skipped"}
11
11
  `);for(const t of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${t.plugin}" kind ${t.kind} not registered: ${t.message}
12
12
  `);for(const t of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${t.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${t.error}
13
- `)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await dt(S.token);const r=await tn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
- `)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,Kt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(c&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(cn(process.pid),ne=!0),ne&&!we){if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{d({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
13
+ `)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await lt(S.token);const r=await rn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
+ `)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,qt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(c&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(ln(process.pid),ne=!0),ne&&!we){if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{l({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
15
15
  ${r}
16
- `),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{d({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{d({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
17
- `),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:Nn,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:Ln}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await Wt({claimed:a(async()=>{try{return c&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{l({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
17
+ `),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:$n,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:An}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await zt({claimed:a(async()=>{try{return c&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
18
18
  ${t}
19
- `),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{d({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!b||X||(je.check()&&D&&(d({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!b)try{m||await zt({log:s}),await Cn(Date.now(),ze)}catch(n){y.fresh(()=>{d({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new rn({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{d({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{d({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&d({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&d({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await de();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),d({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{d({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{d({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await en(),await Zt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>An(t)))},{kinds:["execution_exit"]}),await K(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!b,p=>d({level:"warn",event:"daemon.move.settle_failed",error:p}))).catch(t=>d({level:"warn",event:"daemon.move.settle_failed",error:t}))}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),nn(),w!==null&&d({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),l!==null&&!l.alreadyDone&&d({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&d({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&d({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):$n(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{d({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{d({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&d({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&R(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Mn,"runDaemon");var Ci=Mn;export{Ln as API_DRAIN_GRACE_MS,$i as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ci as default,An as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Mn as runDaemon,Cn as superviseTick,dn as teardownFleet};
19
+ `),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{l({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!b||X||(je.check()&&D&&(l({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!b)try{m||await Ht({log:d}),await Tn(Date.now(),ze)}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new en({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{l({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{l({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&l({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&l({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await le();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),l({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{l({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{l({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await Zt(),await Xt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>Cn(t)))},{kinds:["execution_exit"]}),await K(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!b,p=>l({level:"warn",event:"daemon.move.settle_failed",error:p}))).catch(t=>l({level:"warn",event:"daemon.move.settle_failed",error:t}))}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),tn(),w!==null&&l({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),s!==null&&!s.alreadyDone&&l({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:s.moved,discarded:s.discarded,people:s.people}}),i!==null&&l({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&l({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):Ln(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{l({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{l({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&l({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&R(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Nn,"runDaemon");var Ii=Nn;export{An as API_DRAIN_GRACE_MS,Ai as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ii as default,Cn as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Nn as runDaemon,Tn as superviseTick,dn as teardownFleet};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.756",
3
+ "version": "0.3.757",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.756",
161
- "@north-light/plugin": "0.3.756",
160
+ "@north-light/identity": "0.3.757",
161
+ "@north-light/plugin": "0.3.757",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -1,6 +1,6 @@
1
1
  import { defineLeaf } from '../../core/command.js';
2
2
  import { usage } from '../../core/errors.js';
3
- import { resolve } from 'node:path';
3
+ import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
4
4
  import { cliClient } from '../api-client.js';
5
5
  import { resolveMetaPairs } from './meta.js';
6
6
  export const newLeaf = defineLeaf({
@@ -87,7 +87,7 @@ export const newLeaf = defineLeaf({
87
87
  throw usage('provide `--name <name>` to create a profile, or `--root` to provision the stable root profile.');
88
88
  return newProfileOutput(await cliClient().createProfile({
89
89
  name,
90
- ...(project !== undefined ? { projects: [{ path: resolve(project) }] } : {}),
90
+ ...(project !== undefined ? { projects: [{ path: resolveExistingProjectDir(project) }] } : {}),
91
91
  ...(repos.length > 0 ? { repositories: repos } : {}),
92
92
  ...(defaultKind !== undefined ? { default_kind: defaultKind } : {}),
93
93
  ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
@@ -1,6 +1,7 @@
1
1
  // `crtr profile project` manages purview relationships and per-owner automatic delivery limits.
2
2
  import { defineLeaf, defineBranch } from '../../core/command.js';
3
3
  import { resolve } from 'node:path';
4
+ import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
4
5
  import { usage } from '../../core/errors.js';
5
6
  import { cliClient } from '../api-client.js';
6
7
  import { resolveProfileViaDaemon } from './daemon-profiles.js';
@@ -48,7 +49,7 @@ const addLeaf = defineLeaf({
48
49
  if ((dir === undefined) === (repo === undefined))
49
50
  throw usage('pass exactly one of --dir and --repo', { next: 'Use --dir <directory> for a folder or --repo <handle> for a repo with no folder.' });
50
51
  const updated = await cliClient().updateProfile(id, {
51
- add_project: dir !== undefined ? { path: resolve(dir) } : { repo: repo },
52
+ add_project: dir !== undefined ? { path: resolveExistingProjectDir(dir) } : { repo: repo },
52
53
  });
53
54
  return { profile_id: updated.id, projects: updated.projects };
54
55
  },
@@ -1,7 +1,8 @@
1
1
  // Profile definitions live in scoped state; memory and environment have separate roots.
2
2
  import { randomUUID } from 'node:crypto';
3
- import { existsSync, realpathSync, rmSync, statSync } from 'node:fs';
4
- import { resolve as resolvePath } from 'node:path';
3
+ import { realpathSync, rmSync } from 'node:fs';
4
+ import { isAbsolute, resolve as resolvePath } from 'node:path';
5
+ import { resolveExistingProjectDir } from './project-dir.js';
5
6
  import { SCHEMA_VERSION } from '../../types.js';
6
7
  import { profileSpace } from '../layout.js';
7
8
  import { PROFILE_PROJECT_MEMORY_VALUES } from '../../api/dto/profiles.js';
@@ -165,20 +166,13 @@ export function matchProfileOperand(all, operand, key) {
165
166
  }
166
167
  // Project dirs — resolved to absolute real paths, must exist + be a directory
167
168
  // on add/create, deduped by real path, stored in manifest order.
168
- function resolveExistingProjectDir(dir) {
169
- const abs = resolvePath(dir);
170
- if (!existsSync(abs) || !statSync(abs).isDirectory()) {
171
- throw usage(`project directory does not exist or is not a directory: ${dir}`, {
172
- received: dir,
173
- next: 'Pass an existing directory path.',
174
- });
175
- }
176
- try {
177
- return realpathSync(abs);
178
- }
179
- catch {
180
- return abs;
181
- }
169
+ /** A cloud role cannot see the caller's disk: the caller's CLI already resolved the path on its own machine, so it is stored as sent. */
170
+ function storedProjectDir(dir) {
171
+ if (!isCloudRole())
172
+ return resolveExistingProjectDir(dir);
173
+ if (!isAbsolute(dir))
174
+ throw usage(`project directory must be an absolute path: ${dir}`, { received: dir });
175
+ return dir;
182
176
  }
183
177
  /** First-wins by resolved path; by repo only among entries with no path. A folder entry for a repo that has a repo-only entry merges into it
184
178
  * (one entry, both fields, the repo-only entry's position). */
@@ -342,7 +336,7 @@ export async function createProfile(name, projects = [], opts = {}) {
342
336
  if (opts.metadata !== undefined)
343
337
  assertProfileMetadata(opts.metadata);
344
338
  assertProfileProjects(projects);
345
- const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path: resolveExistingProjectDir(p.path) }) })));
339
+ const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path: storedProjectDir(p.path) }) })));
346
340
  const profileId = generateProfileId(trimmed);
347
341
  const manifest = {
348
342
  schema_version: SCHEMA_VERSION,
@@ -505,7 +499,7 @@ export async function renameProfile(profileId, name) {
505
499
  * a folder no repo identifies keeps `path` only. A listed entry with that path but no repo gains the repo in place. */
506
500
  export async function addProfileProject(profileId, dir, repo) {
507
501
  assertProfileProjects([{ path: dir, ...(repo === undefined ? {} : { repo }) }]);
508
- const resolved = resolveExistingProjectDir(dir);
502
+ const resolved = storedProjectDir(dir);
509
503
  return await mutateManifest(profileId, (m) => ({
510
504
  ...m,
511
505
  projects: dedupeProjects(m.projects.some((p) => p.path === resolved)
@@ -0,0 +1,20 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { resolve as resolvePath } from 'node:path';
3
+ import { usage } from '../errors.js';
4
+ /** A project directory as an absolute real path; it must exist and be a directory on THIS machine's disk.
5
+ * The CLI runs this on the caller's machine before sending a path to a canvas that may live in the cloud. */
6
+ export function resolveExistingProjectDir(dir) {
7
+ const abs = resolvePath(dir);
8
+ if (!existsSync(abs) || !statSync(abs).isDirectory()) {
9
+ throw usage(`project directory does not exist or is not a directory: ${dir}`, {
10
+ received: dir,
11
+ next: 'Pass an existing directory path.',
12
+ });
13
+ }
14
+ try {
15
+ return realpathSync(abs);
16
+ }
17
+ catch {
18
+ return abs;
19
+ }
20
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.756",
3
+ "version": "0.3.757",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.756",
3
+ "version": "0.3.757",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.756",
3
+ "version": "0.3.757",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.756",
31
- "@north-light/identity": "0.3.756"
30
+ "@north-light/api": "0.3.757",
31
+ "@north-light/identity": "0.3.757"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {