@north-light/cli 0.3.755 → 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.
- package/dist/api/client.d.ts +1 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/health.d.ts +0 -54
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +3 -3
- package/dist/cli.js +8 -9
- package/dist/clients/attach/viewer.js +474 -474
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile/project.js +1 -1
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/bootstrap.js +1 -1
- package/dist/core/canvas/boot.d.ts +0 -25
- package/dist/core/canvas/boot.js +1 -1
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +5 -5
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +4 -4
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/profiles/project-dir.d.ts +3 -0
- package/dist/core/profiles/project-dir.js +1 -0
- package/dist/core/scoped-state/db.js +2 -2
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/crtrd.js +18 -20
- package/dist/daemon/manage.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +0 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/dist/build-root.js +0 -9
- package/packages/crouter-api/dist/commands/profile/new.js +2 -2
- package/packages/crouter-api/dist/commands/profile/project.js +2 -1
- package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
- package/packages/crouter-api/dist/commands/sys.js +1 -2
- package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
- package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
- package/packages/crouter-api/dist/core/directory/join.js +18 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
- package/packages/crouter-api/dist/core/grants/sync.js +2 -2
- package/packages/crouter-api/dist/core/io.js +0 -5
- package/packages/crouter-api/dist/core/layout.js +2 -19
- package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
- package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
- package/packages/crouter-api/dist/daemon/api/map.js +0 -16
- package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
- package/packages/crouter-api/dist/daemon/manage.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +1 -30
- package/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -1
- package/dist/core/canvas/import-sqlite.d.ts +0 -46
- package/dist/core/canvas/import-sqlite.js +0 -19
- package/dist/core/canvas/migrations.d.ts +0 -16
- package/dist/core/canvas/migrations.js +0 -1073
- package/dist/core/feed/inbox-migrate.d.ts +0 -11
- package/dist/core/feed/inbox-migrate.js +0 -3
- package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
- package/dist/core/graph/bodies-boot-copy.js +0 -1
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -4
- package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
- package/dist/core/layout-migrate/loose-keys.js +0 -1
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -1
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -11
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -3
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -3
- package/dist/daemon/boot-migrations.d.ts +0 -14
- package/dist/daemon/boot-migrations.js +0 -1
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -1
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
- package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
- package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -3
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -4
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -2
- package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
- package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
- package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
- package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
- package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
- package/packages/crouter-api/dist/core/locked-file.js +0 -121
- package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
- package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
- package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
- package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/packages/crouter-api/dist/migrations/activation.js +0 -46
|
@@ -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{
|
|
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
|
|
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 o=Object.defineProperty;var t=(e,n)=>o(e,"name",{value:n,configurable:!0});import{defineBranch as r}from"../../core/command.js";const i={concept:"crtr configuration, diagnostics, and self-management",desc:"settings, config, connect, setup, tutorial, doctor, context, sync,
|
|
1
|
+
var o=Object.defineProperty;var t=(e,n)=>o(e,"name",{value:n,configurable:!0});import{defineBranch as r}from"../../core/command.js";const i={concept:"crtr configuration, diagnostics, and self-management",desc:"settings, config, connect, setup, tutorial, doctor, context, sync, join, update, version, feedback, logs, retry-delivery, support, limits, daemon",useWhen:"managing the crtr installation, inspecting diagnostics, operating the crtrd supervisor process, or registering a hosted runtime with its directory before first boot"},s={name:"sys",summary:"crtr system configuration, settings, diagnostics, and self-management",model:"Configuration and settings own durable behavior; diagnostics and support observe it. Setup, migration, sync, and update change installed or generated state, and join registers a stopped runtime with its directory from an enrollment token, while daemon control owns the supervisor lifecycle."};function d(e){return r({name:"sys",rootEntry:i,help:{...s},children:e})}t(d,"defineSysBranch");export{d as defineSysBranch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as g}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as y}from"../../core/wake.js";import{DaemonNotPreparedError as b,probeDaemonHealth as l,probeErrorMessage as v,spawnDaemon as p,stopDaemonProcess as c,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as h,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{readMachineConfig as q}from"../../daemon/machine-link/config.js";import{apiSocketPath as x}from"../../core/canvas/paths.js";import{localClient as f}from"../../api/node-transport.js";import{defineSysBranch as I}from"./branch.js";import{selectedGeneration as D}from"./shared.js";const S=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await p({targetPhase:n.prepare===!0?"prepared":"ready"})}catch(e){throw e instanceof b?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),P=100;async function E(n,e){const t=Date.now(),r=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const a=await l(Math.min(1e3,Math.max(1,r-Date.now())));if(s=a.startup_phase,i=a.startup_blocked??`daemon is ${a.startup_phase}`,a.startup_phase==="blocked")throw new d({error:"startup_blocked",message:a.startup_blocked??"daemon startup is blocked",received:a.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(a.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&a.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:a.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(a){if(a instanceof d)throw a;i=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,Math.min(P,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(E,"awaitDaemonPhase");const R=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=y(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,t)},"run")}),A=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await f({autostart:!1}).admitDaemon(),"run")});async function M(n){if(n.generation_id!==void 0)return n.generation_id??void 0;try{return(await f({autostart:!1,socketPath:x()}).status()).generation_id??void 0}catch{return}}o(M,"servingGenerationId");const U=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=h();if(!(e!==null&&m(e)))return{running:!1};try{const r=await l(),s=await M(r),i=D().generation?.id;return{running:!0,serving:r.ok,pid:e,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:e,probe_error:v(r)}}},"run")}),K=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await p();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}if(q()!==void 0){const t=h();t!==null&&await c(t);const r=await p(),s=r.pid??r.existing_pid;return{restarted:!0,...s!==void 0?{pid:s}:{},note:"Machine-role daemon replaced on the selected runtime generation. Its brokers kept running; no node was interrupted."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),L=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=h(),t=e!==null&&m(e);try{let r=!1;t&&(r=await c(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),j=g({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[S,R,A,K,U,L]});function Q(){return I([j])}o(Q,"registerDaemonControlSys");export{j as daemonBranch,Q as registerDaemonControlSys};
|
|
1
|
+
var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as g}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as y}from"../../core/wake.js";import{DaemonNotPreparedError as b,probeDaemonHealth as l,probeErrorMessage as v,spawnDaemon as p,stopDaemonProcess as c,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as h,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{readMachineConfig as q}from"../../daemon/machine-link/config.js";import{apiSocketPath as x}from"../../core/canvas/paths.js";import{localClient as f}from"../../api/node-transport.js";import{defineSysBranch as I}from"./branch.js";import{selectedGeneration as D}from"./shared.js";const S=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await p({targetPhase:n.prepare===!0?"prepared":"ready"})}catch(e){throw e instanceof b?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),P=100;async function E(n,e){const t=Date.now(),r=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const a=await l(Math.min(1e3,Math.max(1,r-Date.now())));if(s=a.startup_phase,i=a.startup_blocked??`daemon is ${a.startup_phase}`,a.startup_phase==="blocked")throw new d({error:"startup_blocked",message:a.startup_blocked??"daemon startup is blocked",received:a.startup_phase,field:"phase",next:"Fix the reported blocker, then retry the await."});if(a.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&a.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:a.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(a){if(a instanceof d)throw a;i=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,Math.min(P,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(E,"awaitDaemonPhase");const R=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=y(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,t)},"run")}),A=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await f({autostart:!1}).admitDaemon(),"run")});async function M(n){if(n.generation_id!==void 0)return n.generation_id??void 0;try{return(await f({autostart:!1,socketPath:x()}).status()).generation_id??void 0}catch{return}}o(M,"servingGenerationId");const U=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=h();if(!(e!==null&&m(e)))return{running:!1};try{const r=await l(),s=await M(r),i=D().generation?.id;return{running:!0,serving:r.ok,pid:e,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:e,probe_error:v(r)}}},"run")}),K=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await p();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}if(q()!==void 0){const t=h();t!==null&&await c(t);const r=await p(),s=r.pid??r.existing_pid;return{restarted:!0,...s!==void 0?{pid:s}:{},note:"Machine-role daemon replaced on the selected runtime generation. Its brokers kept running; no node was interrupted."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),L=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=h(),t=e!==null&&m(e);try{let r=!1;t&&(r=await c(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),j=g({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[S,R,A,K,U,L]});function Q(){return I([j])}o(Q,"registerDaemonControlSys");export{j as daemonBranch,Q as registerDaemonControlSys};
|
package/dist/commands/sys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as
|
|
1
|
+
var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as p}from"./sys/doctor.js";import{sysFeedbackLeaf as a}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{sysJoinLeaf as l}from"./sys/join.js";import{sysImportBranch as v}from"./sys/import/start.js";import{sysMachineBranch as x}from"./sys/machine/rotate.js";import{sysDesktopBranch as b}from"./sys/desktop.js";import{sysSigninLeaf as E,sysSignoutLeaf as F}from"./sys/signin.js";import{sysUpdateLeaf as I,sysVersionLeaf as J}from"./sys/update.js";function or(){return t([S,f,i,g,u,p,k,a,n,c,y,L,h,B,d,I,J,l,D,v,x,E,F,b,e])}r(or,"registerSys");export{or as registerSys};
|
package/dist/core/bootstrap.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i=Object.defineProperty;var t=(
|
|
1
|
+
var i=Object.defineProperty;var t=(o,r)=>i(o,"name",{value:r,configurable:!0});import{homedir as s}from"node:os";import{join as c,relative as p,sep as f}from"node:path";import{appsRoot as m}from"./layout.js";import{findProjectScopeRoot as u,userScopeRoot as a}from"./scope.js";import{ensureScopeInitialized as S}from"./config.js";import{CRTR_DIR_NAME as d}from"../types.js";import{envDebug as h}from"../shared/env.js";const l=new Set(["help","--help","-h","--version","-v"]);function R(o){const r=o[2];return r===void 0?!0:l.has(r)}t(R,"shouldSkipForArgv");async function T(o){try{if(process.env.CRTR_NO_AUTO_INIT==="1"||R(o)||u()!==null)return;const r=process.cwd();if(r===s())return;const e=p(m(),r).split(f);if(e.length===2&&e[1]==="home")return;const n=c(r,d);if(n===a())return;await S("project",n)}catch(r){if(h()){const e=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: project-init error: ${e}
|
|
2
2
|
`)}}}t(T,"ensureProjectScope");export{T as ensureProjectScope};
|
|
@@ -65,28 +65,3 @@ export interface BootReconcileResult {
|
|
|
65
65
|
* `current` defaults to the real identity; tests inject a synthetic one against
|
|
66
66
|
* an isolated CRTR_HOME to simulate a boot change without a real reboot. */
|
|
67
67
|
export declare function reconcileBootLiveness(current?: BootIdentity): Promise<BootReconcileResult>;
|
|
68
|
-
/** The one-time execution-identity migration, injected into the startup
|
|
69
|
-
* composition. In production this is `migrateLegacyExecutionIdentities` from
|
|
70
|
-
* executions.ts. It remains injected so tests can exercise this composition
|
|
71
|
-
* without reaching process inspection. */
|
|
72
|
-
export type MigrateLegacyExecutionIdentities = (captureIdentity?: (pid: number) => string | undefined) => Promise<{
|
|
73
|
-
migrated: string[];
|
|
74
|
-
}>;
|
|
75
|
-
export interface BootStartupResult {
|
|
76
|
-
/** The pid-liveness reconciliation result (boot-change sweep + provenance). */
|
|
77
|
-
reconcile: BootReconcileResult;
|
|
78
|
-
/** node_ids whose legacy identity baseline was migrated — empty when the
|
|
79
|
-
* provenance gate skipped the sweep. */
|
|
80
|
-
migrated: string[];
|
|
81
|
-
}
|
|
82
|
-
/** The daemon's one-time startup boot composition, the single source of truth
|
|
83
|
-
* for its ORDERING and GATE: reconcile pid liveness FIRST (clearing any pids
|
|
84
|
-
* recorded before this boot), then run the legacy identity migration ONLY when
|
|
85
|
-
* reconciliation positively PROVED same-boot provenance (`sameBootProven`).
|
|
86
|
-
* Both `runDaemon` and the migration-gate regression tests call this, so a
|
|
87
|
-
* revert that inverts the gate, drops it, or reorders migration ahead of
|
|
88
|
-
* reconciliation is caught here rather than only in a test-side duplicate.
|
|
89
|
-
*
|
|
90
|
-
* `migrate` is injected (see `MigrateLegacyPidIdentities`); `current` and
|
|
91
|
-
* `captureIdentity` pass through to the two steps for test injection. */
|
|
92
|
-
export declare function reconcileAndMigrateBoot(migrate: MigrateLegacyExecutionIdentities, current?: BootIdentity, captureIdentity?: (pid: number) => string | undefined): Promise<BootStartupResult>;
|
package/dist/core/canvas/boot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=Object.defineProperty;var n=(t,o)=>l(t,"name",{value:o,configurable:!0});import{uptime as p}from"node:os";import{withCanvasWrite as
|
|
1
|
+
var l=Object.defineProperty;var n=(t,o)=>l(t,"name",{value:o,configurable:!0});import{uptime as p}from"node:os";import{withCanvasWrite as E}from"./db.js";import{readKernelBootId as f}from"./boot-id.js";import{readKernelBootId as w}from"./boot-id.js";const b=6e4;function I(t=Date.now()){return{bootId:f(),bootEpochMs:t-Math.round(p()*1e3)}}n(I,"currentBootIdentity");function h(t,o){return o===null?!1:t.bootId!==null&&o.bootId!==null?t.bootId!==o.bootId:Math.abs(t.bootEpochMs-o.bootEpochMs)>b}n(h,"bootChanged");function _(t,o){return o!==null&&t.bootId!==null&&o.bootId!==null&&t.bootId===o.bootId}n(_,"bootProvenSame");const i="boot_identity";async function x(t){const o=await t.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(i);if(o===void 0)return null;try{const e=JSON.parse(o.value);return typeof e.bootEpochMs!="number"?null:{bootId:typeof e.bootId=="string"?e.bootId:null,bootEpochMs:e.bootEpochMs}}catch{return null}}n(x,"readBootMarker");async function s(t,o){await t.prepareUncached("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(i,JSON.stringify(o))}n(s,"writeBootMarker");async function v(t=I()){return E(async o=>{const e=await x(o);if(!h(t,e)){e===null&&await s(o,t);const a=_(t,e);return{changed:!1,cleared:[],sameBootProven:a}}const u=await o.prepare("SELECT execution_id, node_id FROM executions WHERE state != 'exited'").all(),c=o.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exit_reason = 'boot-change' WHERE execution_id = ? AND state != 'exited'"),r=[],d=new Date().toISOString();for(const a of u)(await c.run(d,a.execution_id)).changes>0&&r.push(a.node_id);return await s(o,t),{changed:!0,cleared:r,sameBootProven:!1}})}n(v,"reconcileBootLiveness");export{h as bootChanged,_ as bootProvenSame,I as currentBootIdentity,w as readKernelBootId,v as reconcileBootLiveness};
|
|
@@ -77,9 +77,6 @@ export declare function abortExecution(executionId: string, input: {
|
|
|
77
77
|
export declare function endLiveExecution(nodeId: string, input: {
|
|
78
78
|
reason: ExecutionEndReason;
|
|
79
79
|
}): Promise<boolean>;
|
|
80
|
-
export declare function migrateLegacyExecutionIdentities(captureIdentity?: (pid: number) => string | undefined): Promise<{
|
|
81
|
-
migrated: string[];
|
|
82
|
-
}>;
|
|
83
80
|
/** Records a stop request on the node's live execution; the first request's time and reason stand. */
|
|
84
81
|
export declare function requestExecutionStop(nodeId: string, input: {
|
|
85
82
|
afterTurn: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var D=Object.defineProperty;var a=(e,t)=>D(e,"name",{value:t,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as U}from"./pid.js";import{existsSync as P,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const p=g(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!U(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function L(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(L,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await L(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===T}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await L(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,L as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
|
|
1
|
+
var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as p}from"./db.js";import{capturePidIdentities as g,captureLivenessSnapshot as R,recordedPidLiveness as y}from"./pid.js";import{existsSync as C,readFileSync as O}from"node:fs";import{LAUNCHER_SOCKET as P}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as m}from"../runtime/runner/delete-sandboxes.js";function u(){return new Date().toISOString()}a(u,"now");function A(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(A,"hydrate");async function X(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:A(t)}a(X,"liveExecutionForNode");class U extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class W extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const H=7340001;async function Y(e,t){return await p(async n=>{const i=u();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${H})`).get();const s=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(s>=t.cap)throw new U(t.cap,s)}const c=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(s=>s.runner!=="process"||t.daemonEpoch!==null&&s.daemon_epoch===t.daemonEpoch&&(s.state==="launching"||y(s.pid,s.process_identity,R())!=="dead"));if(c!==void 0)throw new W(e,c.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const d=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(d,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),d})}a(Y,"beginExecution");async function j(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(j,"setExecutionLaunchJson");async function J(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(u(),e);return Number(t.changes)===1}a(J,"recordExecutionIdle");async function G(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(u(),e)}a(G,"recordExecutionAwake");async function V(e,t,n){const i=g([n])?.get(n)??null;return await p(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,u(),e,t)).changes>0)return"recorded";const c=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(c?.pid===n)return"recorded";if(process.platform==="linux"&&C(P)&&c?.pid!=null){const S=R(),d=[c.pid];for(let E=0;E<d.length;E++)d.push(...S?.childrenOf.get(d[E])??[]);if(d.includes(n))return"recorded";for(const E of d)try{const s=O(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(s)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(V,"recordExecutionPid");async function F(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),m(o.node_id)),o!==void 0})}a(F,"endExecution");async function z(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(z,"endLaunchingExecution");async function Q(e,t){return await F(e,t)}a(Q,"abortExecution");async function Z(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),m(e)),Number(o.changes)===1})}a(Z,"endLiveExecution");async function ee(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(u(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ee,"requestExecutionStop");async function te(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(A)}a(te,"executionsWithStopRequestedBefore");async function w(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:A(t)}a(w,"latestExecutionForNode");async function ne(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(ne,"hasRunningRemoteExecution");async function ae(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(ae,"hasLaunchingExecution");async function ie(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ie,"liveProcessExecutionNodeIds");async function oe(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(oe,"liveExecutionNodeIds");const N="profile_pause",T="profile_pause_absorbed";async function re(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(u(),N,e)}a(re,"markProfilePauseStop");async function se(e){return(await w(e))?.stopReason===N}a(se,"hasProfilePauseStop");async function ce(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,N);return Number(t.changes)>0}a(ce,"absorbProfilePauseStop");function ue(e){return e.stopReason===T}a(ue,"hasAbsorbedProfilePauseStop");const f="exited:";async function de(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(de,"recordExecutionExit");function Ee(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(Ee,"hasObservedExit");async function pe(e){const t=await w(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[_,c]=n.slice(f.length).split(":");return{code:_===""?null:Number(_),signal:c===""?null:c}}a(pe,"takeObservedExit");export{W as ExecutionAlreadyLive,U as ExecutionCapReached,N as PROFILE_PAUSE_STOP_REASON,Q as abortExecution,ce as absorbProfilePauseStop,Y as beginExecution,F as endExecution,z as endLaunchingExecution,Z as endLiveExecution,te as executionsWithStopRequestedBefore,ue as hasAbsorbedProfilePauseStop,ae as hasLaunchingExecution,Ee as hasObservedExit,se as hasProfilePauseStop,ne as hasRunningRemoteExecution,w as latestExecutionForNode,X as liveExecutionForNode,oe as liveExecutionNodeIds,ie as liveProcessExecutionNodeIds,re as markProfilePauseStop,G as recordExecutionAwake,de as recordExecutionExit,J as recordExecutionIdle,V as recordExecutionPid,ee as requestExecutionStop,j as setExecutionLaunchJson,pe as takeObservedExit};
|
|
@@ -115,16 +115,6 @@ export declare function killProcessGroup(pid: number, signal?: NodeJS.Signals):
|
|
|
115
115
|
* no-boot_id host is not hammered with a synchronous throwing read on every
|
|
116
116
|
* identity composition. `now` is injectable for tests. */
|
|
117
117
|
export declare function makeBootIdCache(read: () => string | null, now?: () => number, negativeTtlMs?: number): () => string | null;
|
|
118
|
-
/** Is `identity` a LEGACY (pre-boot-scoped) baseline — a `<lstart>#<ticks>` row
|
|
119
|
-
* whose base is NOT a boot_id UUID but which DOES carry ticks? These are the
|
|
120
|
-
* rows the one-time startup migration re-records once this platform can
|
|
121
|
-
* compose boot-scoped identities (see `migrateLegacyPidIdentities`). */
|
|
122
|
-
export declare function isLegacyTicksIdentity(identity: string): boolean;
|
|
123
|
-
/** Is `identity` a NEW-format boot-scoped baseline — `<bootId>#<ticks>` with a
|
|
124
|
-
* real boot_id UUID base AND ticks? The startup migration only re-records a
|
|
125
|
-
* legacy row when the pid's CURRENT identity comes out in this shape (i.e. the
|
|
126
|
-
* platform now composes new-format), never otherwise. */
|
|
127
|
-
export declare function isBootScopedIdentity(identity: string): boolean;
|
|
128
118
|
/** Compose the stable, BOOT-SCOPED process-identity fingerprint used
|
|
129
119
|
* everywhere in this module. ALWAYS used to build an identity string, never a
|
|
130
120
|
* raw field directly, so every identity captured anywhere (launch-time
|
package/dist/core/canvas/pid.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var K=Object.defineProperty;var s=(n,e)=>K(n,"name",{value:e,configurable:!0});import{execFile as X,spawn as q,spawnSync as g}from"node:child_process";import{readFileSync as h,readdirSync as W,statSync as Q}from"node:fs";import{readFile as
|
|
2
|
-
`)}s(m,"logPidLivenessDecision");function nn(n,e="SIGTERM"){if(!(!Number.isInteger(n)||n<=0))try{process.kill(-n,e)}catch{}}s(nn,"killProcessGroup");function en(n){try{const e=h(`/proc/${n}/stat`,"utf8"),t=e.lastIndexOf(")");if(t===-1)return null;const o=e.slice(t+2).trim().split(/\s+/)[19];return o!==void 0&&/^\d+$/.test(o)?o:null}catch{return null}}s(en,"procStartTicks");const tn=6e4;function rn(n,e=Date.now,t=tn){let r=null,o=0;return()=>{if(r!==null)return r;const i=e();if(i<o)return null;const u=n();return u!==null?r=u:(o=i+t,null)}}s(rn,"makeBootIdCache");const A=rn(
|
|
3
|
-
`)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}s(Z,"parseProcessTable");async function
|
|
4
|
-
`)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],
|
|
5
|
-
`)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,M(c,l))}return t}catch{return null}}s(V,"capturePidIdentities");function
|
|
1
|
+
var K=Object.defineProperty;var s=(n,e)=>K(n,"name",{value:e,configurable:!0});import{execFile as X,spawn as q,spawnSync as g}from"node:child_process";import{readFileSync as h,readdirSync as W,statSync as Q}from"node:fs";import{readFile as E}from"node:fs/promises";import{readKernelBootId as O}from"./boot-id.js";function Y(n){if(p())return D(n);try{const e=g("ps",["-o","stat=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";const t=e.stdout.trim();return t===""?"gone":t.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}s(Y,"psProcessState");function y(n){if(n==null)return!1;try{process.kill(n,0)}catch(t){return t.code==="EPERM"}const e=Y(n);return e!=="zombie"&&e!=="gone"}s(y,"isPidAlive");function mn(n){if(n==null)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}s(mn,"isPidPresent");const T=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function v(n){const e=n.indexOf("#");if(e===-1)return{base:n,ticks:void 0};const t=n.slice(e+1);return{base:n.slice(0,e),ticks:/^\d+$/.test(t)?t:void 0}}s(v,"splitIdentity");function S(n,e){const t=v(n),r=v(e);return t.ticks!==void 0&&r.ticks!==void 0?T.test(t.base)&&T.test(r.base)?t.base===r.base&&t.ticks===r.ticks:t.ticks===r.ticks:t.base===r.base}s(S,"identitiesMatch");function gn(n,e,t){const r=!!process.env.CRTR_DEBUG_PID_LIVENESS;if(n==null)return"dead";if(t===null)return r&&m(n,!1,e,"probe-null","ps snapshot failed \u2192 indeterminate","indeterminate"),"indeterminate";const o=t?.processes.get(n),i=t===void 0?y(n):o!==void 0&&!o.zombie;if(!i)return r&&m(n,i,e,t===void 0?"no-probe":"no-entry","process absent/zombie \u2192 dead","dead"),"dead";if(e==null)return r&&m(n,i,e,"no-probe","no baseline \u2192 trust process presence","alive"),"alive";let u;if(t===void 0){const l=V([n]);if(l==null)return r&&m(n,i,e,"probe-null","ps probe failed \u2192 indeterminate","indeterminate"),"indeterminate";if(u=l.get(n),u===void 0)return r&&m(n,i,e,"no-entry","no identity row for pid (race) \u2192 dead","dead"),"dead"}else u=o.identity;const c=S(u,e);return r&&m(n,i,e,"value",c?"identity matches expected \u2192 alive":"identity differs from expected \u2192 REUSED \u2192 dead",c?"alive":"dead",u),c?"alive":"dead"}s(gn,"recordedPidLiveness");function m(n,e,t,r,o,i,u){const c=[`pid=${String(n)}`,`isPidAlive=${e}`,`expectedIdentity=${t===void 0?"undefined":t===null?"null":JSON.stringify(t)}`,`capturePidIdentities=${r}${r==="value"?`(${JSON.stringify(u)})`:""}`,`branch=${JSON.stringify(o)}`,`returned=${i}`];process.stderr.write(`[recordedPidLiveness] ${c.join(" ")}
|
|
2
|
+
`)}s(m,"logPidLivenessDecision");function nn(n,e="SIGTERM"){if(!(!Number.isInteger(n)||n<=0))try{process.kill(-n,e)}catch{}}s(nn,"killProcessGroup");function en(n){try{const e=h(`/proc/${n}/stat`,"utf8"),t=e.lastIndexOf(")");if(t===-1)return null;const o=e.slice(t+2).trim().split(/\s+/)[19];return o!==void 0&&/^\d+$/.test(o)?o:null}catch{return null}}s(en,"procStartTicks");const tn=6e4;function rn(n,e=Date.now,t=tn){let r=null,o=0;return()=>{if(r!==null)return r;const i=e();if(i<o)return null;const u=n();return u!==null?r=u:(o=i+t,null)}}s(rn,"makeBootIdCache");const A=rn(O);function M(n,e,t={}){const r=t.ticks!==void 0?t.ticks:en(n);return r===null?e:`${(t.bootId!==void 0?t.bootId:A())??e}#${r}`}s(M,"composeIdentity");const R=["-Ao","pid=,ppid=,pgid=,stat=,lstart=,command="],_=2e3;function w(){if(p())return $();let n;try{const e=g("ps",[...R],{encoding:"utf8",timeout:_,maxBuffer:8388608});if(e.status!==0||typeof e.stdout!="string")return null;n=e.stdout}catch{return null}return J(n)}s(w,"captureLivenessSnapshot");async function bn(){if(p())return j();const n=await new Promise(e=>{let t;try{t=q("ps",[...R])}catch{return e(null)}let r="",o=!1;const i=s(c=>{o||(o=!0,clearTimeout(u),e(c))},"settle"),u=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}i(null)},_);u.unref?.(),t.stdout.on("data",c=>r+=c.toString()),t.stderr.on("data",()=>{}),t.on("error",()=>i(null)),t.on("close",c=>i(c===0?r:null))});return n===null?null:J(n)}s(bn,"captureLivenessSnapshotAsync");function B(n){const e=n.indexOf("("),t=n.lastIndexOf(")");if(e===-1||t===-1||t<e)return null;const r=n.slice(t+2).trim().split(/\s+/),o=r[0],i=Number(r[1]),u=Number(r[2]),c=r[19];return o===void 0||o===""||!Number.isInteger(i)||i<0||!Number.isInteger(u)||u<0||c===void 0||!/^\d+$/.test(c)?null:{comm:n.slice(e+1,t),state:o,ppid:i,pgid:u,starttime:c}}s(B,"parseProcStat");function C(n,e){const t=n.replace(/\0+$/,"").split("\0").join(" ").trim();return t===""?`[${e}]`:t}s(C,"procCommandLine");let k;function p(){return k===void 0&&(k=process.platform==="linux"&&O()!==null&&on(process.pid)!==null),k}s(p,"procfsUsable");const a={root:"/proc",bootId:s(()=>A(),"bootId")};function on(n,e=a){const t=b(n,e);return t==="unreadable"||t==="denied"||t==="gone"?null:t}s(on,"procStatOf");function b(n,e=a){let t;try{t=h(`${e.root}/${n}/stat`,"utf8")}catch(r){return I(r)}return B(t)??"unreadable"}s(b,"readProcStat");function I(n){const e=n.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}s(I,"classifyProcReadError");function sn(n,e){const t=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(t===null)return"own-or-unknown";try{return Q(`${e.root}/${n}`).uid===t?"own-or-unknown":"foreign"}catch(r){return I(r)==="gone"?"gone":"own-or-unknown"}}s(sn,"procOwnership");function L(n,e,t){return n==="gone"?"skip":n==="unreadable"||sn(e,t)==="own-or-unknown"?"fail":"skip"}s(L,"scanDisposition");function z(n,e=a){const t=e.bootId();return t===null?null:`${t}#${n.starttime}`}s(z,"procIdentity");function D(n,e=a){const t=b(n,e);return t==="gone"?"gone":t==="denied"||t==="unreadable"?"unknown":t.state==="Z"||t.state==="X"?"zombie":"live"}s(D,"procProcessState");function G(n,e=a){const t=new Map;for(const r of n){const o=b(r,e);if(o==="gone")continue;if(o==="unreadable"||o==="denied")return null;const i=z(o,e);if(i===null)return null;t.set(r,i)}return t}s(G,"procIdentities");function H(n,e=a){const t=b(n,e);if(t==="gone"||t==="unreadable"||t==="denied")return null;try{const r=C(h(`${e.root}/${n}/cmdline`,"utf8"),t.comm);return r===""?null:r}catch{return null}}s(H,"procCommand");function U(n,e,t,r,o){const i=z(r,n);if(i===null)return!1;e.processes.set(t,{zombie:r.state==="Z"||r.state==="X",pgid:r.pgid,identity:i,command:C(o,r.comm)});const u=e.childrenOf.get(r.ppid);return u===void 0?e.childrenOf.set(r.ppid,[t]):u.push(t),!0}s(U,"addProcfsRow");function F(n){try{return W(n).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}s(F,"procPids");function $(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map};for(const r of e){const o=b(r,n);if(o==="gone"||o==="denied"||o==="unreadable"){if(L(o==="gone"?"gone":o,r,n)==="skip")continue;return null}let i="";try{i=h(`${n.root}/${r}/cmdline`,"utf8")}catch(u){const c=u.code;if(c==="ENOENT"||c==="ESRCH")continue}if(!U(n,t,r,o,i))return null}return t}s($,"readProcfsSnapshot");async function j(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map},r=64;for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),u=await Promise.all(i.map(async c=>{try{const l=B(await E(`${n.root}/${c}/stat`,"utf8"));if(l===null)return"failed";const f=await E(`${n.root}/${c}/cmdline`,"utf8").catch(d=>{if(d.code==="ENOENT"||d.code==="ESRCH")throw d;return""});return{pid:c,stat:l,cmdline:f}}catch(l){return L(I(l),c,n)==="skip"?"gone":"failed"}}));for(const c of u)if(c!=="gone"&&(c==="failed"||!U(n,t,c.pid,c.stat,c.cmdline)))return null}return t}s(j,"readProcfsSnapshotAsync");function un(){if(p()){const n=$();if(n===null)return null;const e=new Map;for(const[t,r]of n.childrenOf)for(const o of r)e.set(o,t);return[...n.processes].map(([t,r])=>({pid:t,ppid:e.get(t)??0,command:r.command}))}try{const n=g("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});return n.status!==0||typeof n.stdout!="string"?null:Z(n.stdout)}catch{return null}}s(un,"listProcessTable");function Z(n){const e=[];for(const t of n.split(`
|
|
3
|
+
`)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}s(Z,"parseProcessTable");async function hn(n=1e4){return p()?un():await new Promise(e=>{try{X("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:n,maxBuffer:8*1024*1024},(t,r)=>{e(t===null&&typeof r=="string"?Z(r):null)})}catch{e(null)}})}s(hn,"listProcessTableAsync");const yn={procIdentities:G,procProcessState:D,procCommand:H,readProcfsSnapshot:$,readProcfsSnapshotAsync:j};function J(n){const e=new Map,t=new Map;for(const r of n.split(`
|
|
4
|
+
`)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],x=i[6].trim();if(!Number.isInteger(u)||u<=0||!Number.isInteger(c)||c<0||x==="")continue;e.set(u,{zombie:f.startsWith("Z"),pgid:l,identity:M(u,d),command:x});const P=t.get(c);P===void 0?t.set(c,[u]):P.push(u)}return{processes:e,childrenOf:t}}s(J,"parseLivenessTable");function N(n,e){const t=[],r=new Set([n]),o=[...e.get(n)??[]];for(;o.length>0;){const i=o.shift();if(r.has(i))continue;r.add(i),t.push(i);const u=e.get(i);u!==void 0&&o.push(...u)}return t}s(N,"descendantPidsFrom");function cn(n){if(!Number.isInteger(n)||n<=0)return[];const e=w();return e===null?[]:N(n,e.childrenOf)}s(cn,"descendantPids");function Sn(n){const e=w();return e===null?null:[...e.processes].filter(([,t])=>t.pgid===n&&!t.zombie).map(([t])=>t)}s(Sn,"pidsInProcessGroup");function V(n){const e=n.filter(r=>Number.isInteger(r)&&r>0),t=new Map;if(e.length===0)return t;if(p())return G(e);try{const r=g("ps",["-o","pid=,lstart=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});if(r.error!=null||r.signal!=null||typeof r.stdout!="string"||typeof r.stderr=="string"&&r.stderr.trim()!=="")return null;for(const o of r.stdout.split(`
|
|
5
|
+
`)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,M(c,l))}return t}catch{return null}}s(V,"capturePidIdentities");function wn(n){if(!Number.isInteger(n)||n<=0)return null;if(p())return H(n);try{const e=g("ps",["-o","command=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.status!==0||typeof e.stdout!="string")return null;const t=e.stdout.trim();return t===""?null:t}catch{return null}}s(wn,"capturePidCommand");function kn(n,e,t){if(!Number.isInteger(n)||n<=0)return{tree:[],identities:null,reused:!1};const r=w();if(r===null)return{tree:[n],identities:null,reused:!1};const o=r.processes.get(n)?.identity;if(e!=null&&o!==void 0&&!S(o,e))return{tree:[],identities:null,reused:!0};const u=t!==void 0&&Number.isInteger(t)&&t>0?new Set([t,...N(t,r.childrenOf)]):void 0,c=[n,...N(n,r.childrenOf)].filter(f=>!u?.has(f)),l=new Map;for(const f of c){const d=r.processes.get(f)?.identity;d!==void 0&&l.set(f,d)}return{tree:c,identities:l,reused:!1}}s(kn,"captureTeardownSnapshot");function In(n,e="SIGTERM",t){const r=t!=null?V(n):void 0;for(const o of n){if(t!=null&&r!=null){const i=t.get(o),u=r.get(o);if(i!==void 0&&u!==void 0&&!S(u,i))continue}if(nn(o,e),!(!Number.isInteger(o)||o<=0))try{process.kill(o,e)}catch{}}}s(In,"killProcessTreePids");function $n(n){return y(n)?!0:cn(n).some(e=>y(e))}s($n,"isProcessTreeAlive");function Nn(n){return n.some(e=>y(e))}s(Nn,"isAnyPidAlive");export{w as captureLivenessSnapshot,bn as captureLivenessSnapshotAsync,wn as capturePidCommand,V as capturePidIdentities,kn as captureTeardownSnapshot,M as composeIdentity,cn as descendantPids,S as identitiesMatch,Nn as isAnyPidAlive,y as isPidAlive,mn as isPidPresent,$n as isProcessTreeAlive,nn as killProcessGroup,In as killProcessTreePids,un as listProcessTable,hn as listProcessTableAsync,rn as makeBootIdCache,B as parseProcStat,Sn as pidsInProcessGroup,C as procCommandLine,yn as procfsBackendForTest,$ as readProcfsSnapshot,j as readProcfsSnapshotAsync,gn as recordedPidLiveness};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var o=(e,r)=>v(e,"name",{value:r,configurable:!0});import{createHash as U,generateKeyPairSync as D,randomUUID as J}from"node:crypto";import{existsSync as N,mkdirSync as R,readdirSync as I,rmSync as x}from"node:fs";import{request as O}from"node:http";import{hostname as S}from"node:os";import{join as _}from"node:path";import{InputError as m}from"../io.js";import{network as l}from"../errors.js";import{secretsDir as g}from"../layout.js";import{apiSocketPath as q}from"../canvas/paths.js";import{atomicWriteJson as b,readJsonIfExists as h}from"../fs-utils.js";import{launcherPresent as T}from"../grants/sandboxes.js";import{crtrVersion as A}from"../../shared/crtr-version.js";import{pluginsDir as C}from"../scope.js";function f(){return _(g(),"runtime-client.json")}o(f,"clientPath");function w(e){if(typeof e!="string")return!1;try{const{protocol:r}=new URL(e);return r==="http:"||r==="https:"}catch{return!1}}o(w,"isUrl");function y(e){const r=e??{},{runtime:i,client_id:t,issuer:u,owner:s,url:n}=r;if(typeof i!="string"||!/^runtime:.+/.test(i)||typeof t!="string"||t===""||!w(u)||typeof s!="string"||!/^user:.+/.test(s)||!w(n))throw l("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:c,is_default:a}=r;return{runtime:i,client_id:t,issuer:u,owner:s,url:n,...typeof c=="string"?{machine_id:c}:{},...typeof a=="boolean"?{is_default:a}:{}}}o(y,"registration");function d(){return _(g(),"runtime-client.pending.json")}o(d,"pendingPath");function K(){try{const e=C("user");return!e||!N(e)?[]:I(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>r.name).sort()}catch{return[]}}o(K,"installedPluginIds");async function L(e,r,i,t,u){const s=`${e.replace(/\/$/,"")}/v1/runtimes/registration`;let n;try{n=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({jwk:i,name:t,platform:`${process.platform}-${process.arch}`,crtr_version:A(),plugins:K(),sandboxed:T()}),signal:AbortSignal.timeout(3e4)})}catch(a){throw l(`directory registration request to ${s} failed: ${a instanceof Error?a.message:String(a)}`)}const c=await n.text();if(!n.ok)throw n.status<500&&x(d(),{force:!0}),new m({error:"join_refused",message:`directory refused the registration: ${n.status} ${c.slice(0,500)}`,next:u});try{return y(JSON.parse(c))}catch(a){throw a instanceof SyntaxError?l("directory registration answer is not JSON"):a}}o(L,"register");function p(){const e=h(f());if(e?.token_sha256===void 0)return null;const{owner:r}=e;if(typeof r!="string"||!/^user:.+/.test(r))throw new Error(`${f()} was written by join but has a missing or invalid owner`);return e}o(p,"readJoined");function se(){return p()?.owner??null}o(se,"joinedOwner");function ae(){return p()?.issuer??null}o(ae,"joinedIssuer");function ue(){const e=p();return e===null?null:y(e)}o(ue,"joinedClient");function z(e){return new m({error:"daemon_running",message:`cannot register while a daemon answers on ${e}`,next:"Stop the daemon that owns this volume, then run `crtr sys join` again."})}o(z,"daemonRunningError");async function F(e,r,i,t,u){const s=h(f());if(s?.token_sha256===t)return{joined:y(s),registered:!1};R(g(),{recursive:!0,mode:448});let n=h(d());if(n?.token_sha256!==t||n.directory!==e||!n.jwk||!n.public_jwk){const{privateKey:P,publicKey:$}=D("ec",{namedCurve:"P-256"}),j=J();n={token_sha256:t,directory:e,jwk:{...P.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},b(d(),n,{mode:384})}const{jwk:c,public_jwk:a}=n,k=await L(e,r,a,i,u);return{joined:k,registered:!0,client:{jwk:c,kid:c.kid,alg:"ES256",...k,token_sha256:t}}}o(F,"obtainRegistration");function W(e){if(!w(e))throw new m({error:"invalid_directory",message:"directory must be an http or https URL",received:e,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}o(W,"requireDirectory");async function E(e,r,i,t){if(W(e),r==="")throw new m({error:"invalid_token",message:"credential is empty",field:"token",next:"Pass the enrollment token provisioning supplied."});const{joined:u,registered:s,client:n}=await F(e,r,i,U("sha256").update(r).digest("hex"),t);return n&&(b(f(),n,{mode:384}),x(d(),{force:!0})),{...u,registered:s}}o(E,"registerAndStore");function B(e){return new Promise(r=>{const i=O({socketPath:e,path:"/healthz",method:"GET",timeout:1e3},t=>{t.resume(),r(!0)});i.on("timeout",()=>i.destroy(new Error("daemon probe timed out"))),i.on("error",t=>{t.code==="ENOENT"||t.code==="ECONNREFUSED"?r(!1):r(!0)}),i.end()})}o(B,"daemonAnswers");async function ce(e,r,i=S()){const t=q();if(await B(t))throw z(t);return E(e,r,i,"Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.")}o(ce,"joinDirectory");async function me(e,r){return p()!==null?null:E(e,r,S(),"Run `crtr sys signin` again.")}o(me,"registerSignedInMac");export{K as installedPluginIds,ce as joinDirectory,ue as joinedClient,ae as joinedIssuer,se as joinedOwner,me as registerSignedInMac};
|
|
@@ -179,11 +179,6 @@ export declare function hasSyncedGrants(source: string): Promise<boolean>;
|
|
|
179
179
|
* the install's person full local scopes and is not the directory's. Delete it so no
|
|
180
180
|
* grant exists until grant sync installs the directory's mirror. */
|
|
181
181
|
export declare function dropLocalGrantMirror(db: CanvasDb): Promise<number>;
|
|
182
|
-
/** Mark rows a build older than C-D2 wrote as computed for their revision. That build computed every column locally in the same
|
|
183
|
-
* write but never set `computed_rev`, so its rows are complete; left NULL they read as no grant until the next successful
|
|
184
|
-
* sync rewrites them, and the terminal grant then refuses every launch (NL-550). A directory-written row with lagging
|
|
185
|
-
* columns has NULL scopes, so it is never matched. Returns the rows changed. */
|
|
186
|
-
export declare function backfillComputedRev(): Promise<number>;
|
|
187
182
|
/** The directory response is complete; commit it or keep the prior snapshot intact. */
|
|
188
183
|
/** A directory team the runtime's owner belongs to: `team` is `team:<id>`, `members` are `user:<id>`. */
|
|
189
184
|
export interface TeamRecord {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var n=(e,r)=>I(e,"name",{value:r,configurable:!0});import{createHash as L}from"node:crypto";import{parsePrincipal as T,parseScope as C}from"@north-light/identity";import{openDb as d,withCanvasWrite as M}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as O,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function c(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(c,"grantRows");async function u(e,r,t=[]){return(await c(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function j(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(j,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function w(e,r,t,s){return r===e&&t&&s}n(w,"computedFor");function _(e){if(!w(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:j(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
2
|
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
3
|
-
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${
|
|
3
|
+
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${S()}${e.sql}) d OFFSET 0) p
|
|
4
4
|
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
5
5
|
CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):${g}$') m
|
|
6
|
-
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${S()} AND EXISTS (
|
|
7
7
|
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
|
-
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function
|
|
8
|
+
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function ge(){return(await c("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return b(e===void 0?await c("*","status = 'active'"):await c("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await c("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return b(await c("*","true"))}n(Y,"allGrants");async function Se(e){return(await c("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!w(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Se,"grantsOfPerson");function b(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(b,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>C(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${N(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function Ne(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return L("sha256").update(N(r)).digest("base64url").slice(0,22)}n(Ne,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await c("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await c("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await c("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await c("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");function Fe(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Fe,"teamsOf");async function $e(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await M(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const h=a.prepare(`INSERT INTO grants
|
|
9
9
|
(id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
10
10
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -19,6 +19,6 @@ var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});i
|
|
|
19
19
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
20
20
|
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
21
21
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
22
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const
|
|
22
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)E+=Number((await h.run(i.id,i.runtime,i.sub,i.grantee,i.grantee_prefix??null,i.rev,JSON.stringify(i.scopes),JSON.stringify(i.resolved_scopes),i.spend_cap,i.expires_at,i.status,i.revoked_at,i.approved_at,G(i.payer,i.sub,i.grantee),JSON.stringify(j(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await O(a,"directory",f,"member",s.flatMap(({team:i,members:R})=>R.map(D=>({resourceId:i,subject:F(D)})))),await te(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n($e,"replaceGrants");const ee=["editor","messenger","user_of"],re="app-admin";async function te(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
|
|
23
23
|
JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
|
|
24
|
-
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await
|
|
24
|
+
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await O(e,re,$,s,t)}n(te,"reconcileAppAdminFacts");async function ke(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(ke,"grantsGeneration");export{re as APP_ADMIN_WRITER,Q as activeGrant,Re as activeGrantForApp,ye as activeGrantNamesApp,Ee as activeGrants,me as activeGrantsOfPerson,fe as activeProviderIds,Z as activeRecord,Y as allGrants,_e as anyActiveGrant,N as canonicalJson,j as dependenciesOf,Me as dropLocalGrantMirror,H as endpointPays,z as grantExpired,he as grantFor,we as grantIdsWhere,K as grantRecord,je as grantStanding,ge as grantSubs,Ae as grantSyncState,Oe as grantSyncStateFor,Ne as grantVersion,ve as grantedProviderIds,ke as grantsGeneration,Se as grantsOfPerson,Le as grantsSource,Te as hasGrant,Ce as hasSyncedGrants,V as inferenceEndpointOf,xe as isProviderBundleRow,de as localGrants,y as mirrorOnly,le as otherLiveGrantOfApp,be as payerOfGrant,G as principalPayer,B as providerIdsFromGrants,te as reconcileAppAdminFacts,$e as replaceGrants,De as runNoticeTarget,x as runtimeScope,Fe as teamsOf,Ie as terminalGrant};
|