@north-light/cli 0.3.777 → 0.3.779

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.
@@ -65,7 +65,18 @@ A profile is a stable **agent identity** — itself an owner object: a fixed id,
65
65
 
66
66
  Every project path in the purview puts the repos enclosing it into the view of every node under the profile, whatever directory that node works in: their documents are listed and readable, and are delivered at boot and workspace-open when a rule of theirs matches, after the repos enclosing the node's own cwd. A rule's `if: {repo}` holds for any of those repos, so a repo-conditioned rule fires for every node of the profile; use `cwd` to condition on where the node works. `crtr profile project add` starts the added repos at a `preview` limit. The profile's delivery limit per owner caps how much of a repo's documents reach automatic boot and workspace-open context, whether the repo is in view through the cwd or the project list: give `content` to the repos whose front doors the profile's nodes should operate inside, `preview` or `name` to a project the profile must know exists but rarely enters, and `none` to purview held for config, plugins, and deliberate reads alone. Key a limit by repo handle, or `repo:<handle>` when another owner (such as a profile) shares that handle; the profile's own documents are never capped. It is a delivery dial, not an access one: `crtr canvas read` and `file-read`/`command` rules still reach those documents.
67
67
 
68
- Reach for a **new** profile when a distinct body of work has its own set of directories and its own conventions worth dedicated documents — not for every repo. **The profile as owner** is exactly where cross-repo conventions and your stance toward that body of work belong (see the owners below); a profile spanning several related dirs lets one document reach every node working anywhere in that bundle.
68
+ ### Reuse a profile, widen it, or create one
69
+
70
+ Adding a directory to a profile is not free: every node of the profile then carries that repo's documents at boot and fires its repo-conditioned rules, wherever the node works. Decide by asking whose documents should reach whom.
71
+
72
+ | Situation | Do this |
73
+ |---|---|
74
+ | The new directory's work shares the profile's conventions, people, and stance (another repo of the same product, a worktree, a sibling service) | Add it: `crtr profile project add <profile> --dir <path>` |
75
+ | The profile's nodes only occasionally need the repo — to read its docs or resolve its config — but not its front door | Add it, then lower its delivery: `crtr profile project limit` at `name` (knows it exists) or `none` (config and deliberate reads only) |
76
+ | The work has its own conventions, and its documents would be noise to the profile's nodes (or theirs to it) | Create a profile: `crtr profile new --name <name> --project <path>` |
77
+ | One-off work in a directory you will not return to | Run under an existing profile without adding the directory |
78
+
79
+ Do not create one profile per repo: a profile spanning several related directories is what lets one profile-owned document reach every node working anywhere in that bundle. **The profile as owner** is where cross-repo conventions and your stance toward that body of work belong (see the owners below). A cloud dev profile is defined by the repositories its sandbox checks out (`profile new --repo`, `profile environment`) rather than by local folders; the same reuse-or-create rule applies to which repositories belong together.
69
80
 
70
81
  ## Owners — who owns a document sets its reach
71
82
 
@@ -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{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
+ 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 h}from"../../core/profiles/project-dir.js";import{cliClient as d}from"../api-client.js";import{resolveMetaPairs as u}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). Create one only for a distinct body of work whose conventions and documents would be noise to every existing profile; if an existing profile's documents and stance already fit the work, add the directory to it with `profile project add` instead \u2014 not one profile per repo. Use `--repo` for a cloud sandbox profile and `--project` for a folder on this machine. 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=u(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:h(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 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
+ 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. Add a directory when its work shares the profile's conventions and documents; every node of the profile then carries that repo's documents and fires its repo-conditioned rules, so when the profile only needs the repo in reach, follow with `profile project limit` at `name` or `none`, and when the work has its own conventions, create a separate profile with `profile new` instead.",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,3 +1,3 @@
1
- var y=Object.defineProperty;var t=(e,r)=>y(e,"name",{value:r,configurable:!0});import{defineBranch as w,defineLeaf as h}from"../../core/command.js";import{InputError as l}from"../../core/io.js";import{cliClient as m}from"../api-client.js";const d=t(e=>e===null?"unpriced":`$${e.toFixed(e<1?4:2)}`,"usd"),$=t(e=>[e.funding&&`funding ${e.funding}`,e.grantee&&`grantee ${e.grantee}`,e.provider&&`provider ${e.provider}`,e.sub&&`sub ${e.sub}`].filter(Boolean).join(", ")||"everything","filters"),p=t(e=>`- \`${e.id}\` ${e.payer??e.account} ${d(e.usd_per_month)}/month on ${$(e)} (${e.source})`,"limitLine"),b=h({name:"show",description:"show a month's spend by payer and funding, with the limits",whenToUse:"checking what a payer has spent this month and which limits apply",help:{name:"sys spend show",summary:"month totals by payer and by payer and funding from the ledger, then every limit row",params:[{kind:"flag",name:"month",type:"string",required:!1,constraint:"UTC month YYYY-MM. Default: the current month."}],output:[{name:"month",type:"string",required:!0,constraint:"The month shown, YYYY-MM."},{name:"totals",type:"ChargeTotalsDTO",required:!0,constraint:"Record: {month, by_payer, by_funding, limits}. Migrated user-paid model history has funding `legacy`."}],outputKind:"object",effects:["None. Read-only."]},run:t(async e=>{const r=await m().listCharges({limit:1,...e.month===void 0?{}:{month:String(e.month)}});if(r.totals===void 0)throw new l({error:"owner_only",message:"month totals and limits are read by the person; this caller sees only its own app's charges",next:"Run `crtr sys spend show` from the person's own shell, not from inside a node."});return{month:r.month,totals:r.totals}},"run"),render:t(e=>{const r=e.totals;return[`Spend for ${r.month}:`,...r.by_payer.length===0?["- nothing charged"]:r.by_payer.map(i=>`- ${i.payer} ${d(i.usd)}${r.by_funding.filter(s=>s.payer===i.payer).map(s=>` ${s.funding} ${d(s.usd)}`).join("")}`),"Limits:",...r.limits.length===0?["- none"]:r.limits.map(p)].join(`
2
- `)},"render")});function v(e){const r=new Map;for(const n of e)r.set(n.provider??"(none)",(r.get(n.provider??"(none)")??0)+(n.usd??0));const i=new Set(e.map(n=>n.request)),s=t(n=>e.filter(o=>(o.caused_by??null)===n),"children"),a=[],u=new Set,c=t((n,o)=>{if(!u.has(n.id)&&(u.add(n.id),a.push(`${" ".repeat(o)}- ${n.at} ${n.kind} ${n.what} ${d(n.usd)} ${n.payer}/${n.funding}${n.provider?` \u2192 ${n.provider}`:""} vendor_ref ${n.vendor_ref??"none"}${n.refused?` REFUSED by ${n.refused.limit}`:""}`),n.request!==null))for(const g of s(`request:${n.request}`))c(g,o+1)},"print"),f=e.filter(n=>n.caused_by===null||!(n.caused_by.startsWith("request:")&&i.has(n.caused_by.slice(8))));for(const n of f)c(n,0);for(const n of e)c(n,0);return[...a,"Total per provider:",...[...r].map(([n,o])=>`- ${n} ${d(o)}`)].join(`
3
- `)}t(v,"tree");const q=h({name:"chain",description:"list the charge rows under a run, message, request or charge on this runtime",whenToUse:"finding what one run, message or request cost and matching its vendor_ref to a vendor's usage line",help:{name:"sys spend chain",summary:"the rows under a reference as a tree, with each row's vendor_ref and a total per provider",params:[{kind:"positional",name:"reference",type:"string",required:!0,constraint:"`run:<id>`, `message:<id>`, `request:<id>`, `cron_run:<id>` or a charge id. Reads this runtime only."}],output:[{name:"reference",type:"string",required:!0,constraint:"The reference read."},{name:"charges",type:"ChargeDTO[]",required:!0,constraint:"Rows in time order; empty when this runtime holds none under the reference."}],outputKind:"object",effects:["None. Read-only."]},run:t(async e=>{const r=String(e.reference),i=[];for(let s;;){const a=await m().listCharges({under:r,...s===void 0?{}:{after:s}});if(i.push(...a.charges),a.next===null)break;s=a.next}return{reference:r,charges:i}},"run"),render:t(e=>{const r=e.charges;return r.length===0?`No charges under ${String(e.reference)} on this runtime.`:v(r)},"render")}),_=h({name:"limit",description:"set or clear one of the person's dollar limits",whenToUse:"stopping a payer's spend (0 is an emergency stop) or capping it per month; clearing a limit you set",help:{name:"sys spend limit",summary:"write or remove the limit row `person:<name>`; the check refuses calls billed to the payer once the month reaches it",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"A name for the row; the id is `person:<name>`."},{kind:"flag",name:"payer",type:"string",required:!1,constraint:"`user:<id>` (the person) or `app:<id>`. Required unless --clear."},{kind:"flag",name:"usd",type:"string",required:!1,constraint:"Dollars per month, 0 or more; 0 stops the payer. Required unless --clear."},{kind:"flag",name:"funding",type:"enum",choices:["bill","subscription","key","endpoint","take","legacy"],required:!1,constraint:"Limit only this funding. Default: any."},{kind:"flag",name:"grantee",type:"string",required:!1,constraint:"Limit only charges attributed to this app, such as `app:terminal`. Default: any."},{kind:"flag",name:"provider",type:"string",required:!1,constraint:"Limit only money going to this vendor or provider app, such as `anthropic`. Default: any."},{kind:"flag",name:"clear",type:"bool",required:!1,constraint:"Remove the row instead of writing it."}],output:[{name:"limit",type:"LimitDTO",required:!1,constraint:"The row written; absent with --clear."},{name:"removed",type:"string",required:!1,constraint:"The id removed with --clear."}],outputKind:"object",effects:["Writes or deletes one `limits` row with source `person`. Takes effect on the next call."]},run:t(async e=>{const r=`person:${String(e.name)}`;if(e.clear===!0)return{removed:(await m().removeSpendLimit(r)).id};const i=e.usd===void 0?Number.NaN:Number(e.usd);if(typeof e.payer!="string"||!Number.isFinite(i)||i<0)throw new l({error:"nothing_to_set",message:"a limit needs --payer and --usd (0 or more), or --clear",next:"Pass --payer user:<id> --usd 20, or --clear to remove the row."});return{limit:await m().setSpendLimit(r,{payer:e.payer,usd_per_month:i,...e.funding===void 0?{}:{funding:e.funding},...e.grantee===void 0?{}:{grantee:String(e.grantee)},...e.provider===void 0?{}:{provider:String(e.provider)}})}},"run"),render:t(e=>e.removed!==void 0?`Removed ${String(e.removed)}.`:p(e.limit),"render")}),D=w({name:"spend",description:"the money ledger: spend by payer, the chain under a run, and dollar limits",whenToUse:"reading what was spent and why, or stopping or capping a payer's spend",help:{name:"sys spend",summary:"read this runtime's charges and set the person's dollar limits",model:"Every model call and priced tool call is one charge row naming its payer, funding and cause. A limit row bounds a payer's month; the check refuses calls billed to that payer once it is reached. `sys limits` is the unrelated per-app memory and disk cap."},children:[b,q,_]});export{D as sysSpendBranch};
1
+ var y=Object.defineProperty;var t=(e,r)=>y(e,"name",{value:r,configurable:!0});import{defineBranch as w,defineLeaf as h}from"../../core/command.js";import{InputError as u}from"../../core/io.js";import{cliClient as m}from"../api-client.js";const d=t(e=>e===null?"unpriced":`$${e.toFixed(e<1?4:2)}`,"usd"),$=t(e=>[e.funding&&`funding ${e.funding}`,e.grantee&&`grantee ${e.grantee}`,e.provider&&`provider ${e.provider}`,e.sub&&`sub ${e.sub}`].filter(Boolean).join(", ")||"everything","filters"),l=t(e=>`- \`${e.id}\` ${e.payer??e.account} ${d(e.usd_per_month)}/month on ${$(e)} (${e.source})`,"limitLine"),b=h({name:"show",description:"show a month's spend by payer and funding, with the limits",whenToUse:"checking what a payer has spent this month and which limits apply",help:{name:"sys spend show",summary:"month totals by payer and by payer and funding from the ledger, then every limit row",params:[{kind:"flag",name:"month",type:"string",required:!1,constraint:"UTC month YYYY-MM. Default: the current month."}],output:[{name:"month",type:"string",required:!0,constraint:"The month shown, YYYY-MM."},{name:"totals",type:"ChargeTotalsDTO",required:!0,constraint:"Record: {month, by_payer, by_funding, limits}. Migrated user-paid model history has funding `legacy`."}],outputKind:"object",effects:["None. Read-only."]},run:t(async e=>{const r=await m().listCharges({limit:1,...e.month===void 0?{}:{month:String(e.month)}});if(r.totals===void 0)throw new u({error:"owner_only",message:"month totals are read by the person and terminal-app nodes; this caller sees only its own app's charges",next:"Run `crtr sys spend show` from the person's own shell or a terminal-app node."});return{month:r.month,totals:r.totals}},"run"),render:t(e=>{const r=e.totals;return[`Spend for ${r.month}:`,...r.by_payer.length===0?["- nothing charged"]:r.by_payer.map(i=>`- ${i.payer} ${d(i.usd)}${r.by_funding.filter(s=>s.payer===i.payer).map(s=>` ${s.funding} ${d(s.usd)}`).join("")}`),"Limits:",...r.limits.length===0?["- none"]:r.limits.map(l)].join(`
2
+ `)},"render")});function v(e){const r=new Map;for(const n of e)r.set(n.provider??"(none)",(r.get(n.provider??"(none)")??0)+(n.usd??0));const i=new Set(e.map(n=>n.request)),s=t(n=>e.filter(o=>(o.caused_by??null)===n),"children"),a=[],p=new Set,c=t((n,o)=>{if(!p.has(n.id)&&(p.add(n.id),a.push(`${" ".repeat(o)}- ${n.at} ${n.kind} ${n.what} ${d(n.usd)} ${n.payer}/${n.funding}${n.provider?` \u2192 ${n.provider}`:""} vendor_ref ${n.vendor_ref??"none"}${n.refused?` REFUSED by ${n.refused.limit}`:""}`),n.request!==null))for(const g of s(`request:${n.request}`))c(g,o+1)},"print"),f=e.filter(n=>n.caused_by===null||!(n.caused_by.startsWith("request:")&&i.has(n.caused_by.slice(8))));for(const n of f)c(n,0);for(const n of e)c(n,0);return[...a,"Total per provider:",...[...r].map(([n,o])=>`- ${n} ${d(o)}`)].join(`
3
+ `)}t(v,"tree");const q=h({name:"chain",description:"list the charge rows under a run, message, request or charge on this runtime",whenToUse:"finding what one run, message or request cost and matching its vendor_ref to a vendor's usage line",help:{name:"sys spend chain",summary:"the rows under a reference as a tree, with each row's vendor_ref and a total per provider",params:[{kind:"positional",name:"reference",type:"string",required:!0,constraint:"`run:<id>`, `message:<id>`, `request:<id>`, `cron_run:<id>` or a charge id. Reads this runtime only."}],output:[{name:"reference",type:"string",required:!0,constraint:"The reference read."},{name:"charges",type:"ChargeDTO[]",required:!0,constraint:"Rows in time order; empty when this runtime holds none under the reference."}],outputKind:"object",effects:["None. Read-only."]},run:t(async e=>{const r=String(e.reference),i=[];for(let s;;){const a=await m().listCharges({under:r,...s===void 0?{}:{after:s}});if(i.push(...a.charges),a.next===null)break;s=a.next}return{reference:r,charges:i}},"run"),render:t(e=>{const r=e.charges;return r.length===0?`No charges under ${String(e.reference)} on this runtime.`:v(r)},"render")}),_=h({name:"limit",description:"set or clear one of the person's dollar limits",whenToUse:"stopping a payer's spend (0 is an emergency stop) or capping it per month; clearing a limit you set",help:{name:"sys spend limit",summary:"write or remove the limit row `person:<name>`; the check refuses calls billed to the payer once the month reaches it",params:[{kind:"positional",name:"name",type:"string",required:!0,constraint:"A name for the row; the id is `person:<name>`."},{kind:"flag",name:"payer",type:"string",required:!1,constraint:"`user:<id>` (the person) or `app:<id>`. Required unless --clear."},{kind:"flag",name:"usd",type:"string",required:!1,constraint:"Dollars per month, 0 or more; 0 stops the payer. Required unless --clear."},{kind:"flag",name:"funding",type:"enum",choices:["bill","subscription","key","endpoint","take","legacy"],required:!1,constraint:"Limit only this funding. Default: any."},{kind:"flag",name:"grantee",type:"string",required:!1,constraint:"Limit only charges attributed to this app, such as `app:terminal`. Default: any."},{kind:"flag",name:"provider",type:"string",required:!1,constraint:"Limit only money going to this vendor or provider app, such as `anthropic`. Default: any."},{kind:"flag",name:"clear",type:"bool",required:!1,constraint:"Remove the row instead of writing it."}],output:[{name:"limit",type:"LimitDTO",required:!1,constraint:"The row written; absent with --clear."},{name:"removed",type:"string",required:!1,constraint:"The id removed with --clear."}],outputKind:"object",effects:["Writes or deletes one `limits` row with source `person`. Takes effect on the next call."]},run:t(async e=>{const r=`person:${String(e.name)}`;if(e.clear===!0)return{removed:(await m().removeSpendLimit(r)).id};const i=e.usd===void 0?Number.NaN:Number(e.usd);if(typeof e.payer!="string"||!Number.isFinite(i)||i<0)throw new u({error:"nothing_to_set",message:"a limit needs --payer and --usd (0 or more), or --clear",next:"Pass --payer user:<id> --usd 20, or --clear to remove the row."});return{limit:await m().setSpendLimit(r,{payer:e.payer,usd_per_month:i,...e.funding===void 0?{}:{funding:e.funding},...e.grantee===void 0?{}:{grantee:String(e.grantee)},...e.provider===void 0?{}:{provider:String(e.provider)}})}},"run"),render:t(e=>e.removed!==void 0?`Removed ${String(e.removed)}.`:l(e.limit),"render")}),D=w({name:"spend",description:"the money ledger: spend by payer, the chain under a run, and dollar limits",whenToUse:"reading what was spent and why, or stopping or capping a payer's spend",help:{name:"sys spend",summary:"read this runtime's charges and set the person's dollar limits",model:"Every model call and priced tool call is one charge row naming its payer, funding and cause. A limit row bounds a payer's month; the check refuses calls billed to that payer once it is reached. `sys limits` is the unrelated per-app memory and disk cap."},children:[b,q,_]});export{D as sysSpendBranch};
@@ -1,24 +1,25 @@
1
- var se=Object.defineProperty;var l=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as le}from"node:child_process";import{existsSync as ae,realpathSync as ce}from"node:fs";import{basename as fe,join as ue,resolve as pe,sep as A}from"node:path";import{appendRotatingRecord as de}from"../log.js";import{crtrHome as me}from"../canvas/paths.js";import{createInterface as M}from"node:readline/promises";import{emitKeypressEvents as E}from"node:readline";import{listProfiles as D,loadProfileManifest as he,resolveProfileOperand as $e,updateProfileLastUsed as O,createProfile as ge,addProfileProject as j,ensureRootProfile as k,ROOT_PROFILE_ID as L}from"./manifest.js";import{getDefaultProfileId as we,setDefaultProfileId as Ie,clearDefaultProfile as N}from"./default-binding.js";import{tildify as b}from"../fs-utils.js";import{stdoutColor as T}from"../output.js";import{inTmux as ye}from"../runtime/placement-tmux.js";import{surfaceTmuxStyleArgs as xe}from"../runtime/surface-bg.js";import{formatBinding as g,matchesTerminalInput as Pe,resolveUserKeybindings as be}from"../keybindings/index.js";const ve=["crtr.profile.menu.abort","crtr.profile.menu.up","crtr.profile.menu.down","crtr.profile.menu.select","crtr.profile.menu.accept-default","crtr.profile.menu.slot.1","crtr.profile.menu.slot.2","crtr.profile.menu.slot.3","crtr.profile.menu.slot.4","crtr.profile.menu.slot.5","crtr.profile.menu.slot.6","crtr.profile.menu.slot.7","crtr.profile.menu.slot.8","crtr.profile.menu.slot.9","crtr.profile.menu.create","crtr.profile.menu.search-existing","crtr.profile.menu.use-root","crtr.profile.menu.set-default","crtr.profile.menu.add-directory","crtr.profile.menu.unpin","crtr.profile.menu.manage"],Me=["crtr.profile.search.abort","crtr.profile.search.back","crtr.profile.search.pick","crtr.profile.search.up","crtr.profile.search.down","crtr.profile.search.delete"];function Y(t,e){return{input:e.ctrl===!0||e.meta===!0?e.name??t:t,upArrow:e.name==="up",downArrow:e.name==="down",return:e.name==="return"||e.name==="enter",escape:e.name==="escape",backspace:e.name==="backspace",ctrl:e.ctrl,meta:e.meta,shift:e.shift}}l(Y,"profileRawInput");function B(t,e,r){return e.find(n=>Pe(t,n,r))??null}l(B,"firstProfileMatch");function Te(t,e){return B(t,ve,e)}l(Te,"resolveProfileMenuAction");function _e(t,e){return B(t,Me,e)}l(_e,"resolveProfileSearchAction");function W(t){const e=pe(t);if(!ae(e))return e;try{return ce(e)}catch{return e}}l(W,"resolveCwd");function F(t,e){return!!(t===e||t.startsWith(e+A)||e.startsWith(t+A))}l(F,"projectCovers");function H(t,e){return P(t.manifest.projects).some(r=>F(e,r))}l(H,"profileCoversCwd");function _(t,e){return t===null?!1:e===null?!0:t>e}l(_,"isMoreRecent");function U(t){return t.reduce((e,r)=>_(r.manifest.last_used_at,e.manifest.last_used_at)?r:e)}l(U,"pickMostRecent");function K(t){const e=W(t),r=D().filter(o=>H(o,e)),n=r.filter(o=>P(o.manifest.projects).includes(e)),i=we(e),s=i===null?null:r.find(o=>o.profileId===i)??null;return{covering:r,exact:n,pinnedId:i,pinned:s}}l(K,"profileSelectionState");function Ze(t){const{covering:e,exact:r,pinned:n}=K(t);if(n!==null)return n.profileId;if(r.length===1)return r[0].profileId;const i=r.length>0?r:e;return i.length>0?U(i).profileId:L}l(Ze,"selectProfileForCwdReadOnly");function q(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}l(q,"isInteractive");const $=T.dim,x=T.bold,y=T.cyan;function Re(t){return y(x(t))}l(Re,"key");function G(t){if(t===null)return"never used";const e=Date.parse(t);if(Number.isNaN(e))return"used recently";const r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return"used just now";const n=Math.floor(r/60);if(n<60)return`used ${n}m ago`;const i=Math.floor(n/60);if(i<24)return`used ${i}h ago`;const s=Math.floor(i/24);if(s<30)return`used ${s}d ago`;const o=Math.floor(s/30);return o<12?`used ${o}mo ago`:`used ${Math.floor(o/12)}y ago`}l(G,"relativeUsed");function Ce(t,e){const r=e!==void 0?` ${$(e)}
1
+ var se=Object.defineProperty;var a=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as ae}from"node:child_process";import{existsSync as le,realpathSync as ce}from"node:fs";import{basename as fe,join as ue,resolve as pe,sep as A}from"node:path";import{appendRotatingRecord as de}from"../log.js";import{crtrHome as me}from"../canvas/paths.js";import{createInterface as M}from"node:readline/promises";import{emitKeypressEvents as E}from"node:readline";import{listProfiles as k,loadProfileManifest as he,resolveProfileOperand as $e,updateProfileLastUsed as D,createProfile as we,addProfileProject as O,ensureRootProfile as j,ROOT_PROFILE_ID as L}from"./manifest.js";import{getDefaultProfileId as ge,setDefaultProfileId as Ie,clearDefaultProfile as N}from"./default-binding.js";import{tildify as v}from"../fs-utils.js";import{stdoutColor as T}from"../output.js";import{inTmux as ye}from"../runtime/placement-tmux.js";import{surfaceTmuxStyleArgs as xe}from"../runtime/surface-bg.js";import{formatBinding as w,matchesTerminalInput as Pe,resolveUserKeybindings as ve}from"../keybindings/index.js";const be=["crtr.profile.menu.abort","crtr.profile.menu.up","crtr.profile.menu.down","crtr.profile.menu.select","crtr.profile.menu.accept-default","crtr.profile.menu.slot.1","crtr.profile.menu.slot.2","crtr.profile.menu.slot.3","crtr.profile.menu.slot.4","crtr.profile.menu.slot.5","crtr.profile.menu.slot.6","crtr.profile.menu.slot.7","crtr.profile.menu.slot.8","crtr.profile.menu.slot.9","crtr.profile.menu.create","crtr.profile.menu.search-existing","crtr.profile.menu.use-root","crtr.profile.menu.set-default","crtr.profile.menu.add-directory","crtr.profile.menu.unpin","crtr.profile.menu.manage"],Me=["crtr.profile.search.abort","crtr.profile.search.back","crtr.profile.search.pick","crtr.profile.search.up","crtr.profile.search.down","crtr.profile.search.delete"];function Y(t,e){return{input:e.ctrl===!0||e.meta===!0?e.name??t:t,upArrow:e.name==="up",downArrow:e.name==="down",return:e.name==="return"||e.name==="enter",escape:e.name==="escape",backspace:e.name==="backspace",ctrl:e.ctrl,meta:e.meta,shift:e.shift}}a(Y,"profileRawInput");function B(t,e,r){return e.find(n=>Pe(t,n,r))??null}a(B,"firstProfileMatch");function Te(t,e){return B(t,be,e)}a(Te,"resolveProfileMenuAction");function _e(t,e){return B(t,Me,e)}a(_e,"resolveProfileSearchAction");function W(t){const e=pe(t);if(!le(e))return e;try{return ce(e)}catch{return e}}a(W,"resolveCwd");function F(t,e){return!!(t===e||t.startsWith(e+A)||e.startsWith(t+A))}a(F,"projectCovers");function H(t,e){return P(t.manifest.projects).some(r=>F(e,r))}a(H,"profileCoversCwd");function _(t,e){return t===null?!1:e===null?!0:t>e}a(_,"isMoreRecent");function U(t){return t.reduce((e,r)=>_(r.manifest.last_used_at,e.manifest.last_used_at)?r:e)}a(U,"pickMostRecent");function K(t){const e=W(t),r=k().filter(o=>H(o,e)),n=r.filter(o=>P(o.manifest.projects).includes(e)),i=ge(e),s=i===null?null:r.find(o=>o.profileId===i)??null;return{covering:r,exact:n,pinnedId:i,pinned:s}}a(K,"profileSelectionState");function Ze(t){const{covering:e,exact:r,pinned:n}=K(t);if(n!==null)return n.profileId;if(r.length===1)return r[0].profileId;const i=r.length>0?r:e;return i.length>0?U(i).profileId:L}a(Ze,"selectProfileForCwdReadOnly");function q(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}a(q,"isInteractive");const $=T.dim,x=T.bold,y=T.cyan;function Re(t){return y(x(t))}a(Re,"key");function G(t){if(t===null)return"never used";const e=Date.parse(t);if(Number.isNaN(e))return"used recently";const r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return"used just now";const n=Math.floor(r/60);if(n<60)return`used ${n}m ago`;const i=Math.floor(n/60);if(i<24)return`used ${i}h ago`;const s=Math.floor(i/24);if(s<30)return`used ${s}d ago`;const o=Math.floor(s/30);return o<12?`used ${o}mo ago`:`used ${Math.floor(o/12)}y ago`}a(G,"relativeUsed");function Ce(t,e){const r=e!==void 0?` ${$(e)}
2
2
  `:"";process.stdout.write(`
3
3
  ${x(t)}
4
4
  ${r}
5
- `)}l(Ce,"writeHeader");function Se(t){const e=P(t.manifest.projects),r=e.length,n=e[0];return n===void 0?G(t.manifest.last_used_at):r>1?`${b(n)} \xB7 ${r} dirs total`:b(n)}l(Se,"purviewSummary");const J=y("\u25B8"),z=l(t=>t>0?`\x1B[${t}A\r`:"","cursorUp"),Q="\x1B[0J",Ae=/\u001b\[[0-9;]*m/g;function V(t){const e=process.stdout.columns??80,r=t.split(`
6
- `),n=r.length-1;let i=0;for(let s=0;s<n;s++){const o=r[s].replace(Ae,"").length;e>0&&o>e&&(i+=Math.ceil(o/e)-1)}return n+i}l(V,"blockRows");function Ee(t,e,r,n,i,s){let o=`
5
+ `)}a(Ce,"writeHeader");function Se(t){const e=P(t.manifest.projects),r=e.length,n=e[0];return n===void 0?G(t.manifest.last_used_at):r>1?`${v(n)} \xB7 ${r} dirs total`:v(n)}a(Se,"purviewSummary");const J=y("\u25B8"),z=a(t=>t>0?`\x1B[${t}A\r`:"","cursorUp"),Q="\x1B[0J",Ae=/\u001b\[[0-9;]*m/g;function V(t){const e=process.stdout.columns??80,r=t.split(`
6
+ `),n=r.length-1;let i=0;for(let s=0;s<n;s++){const o=r[s].replace(Ae,"").length;e>0&&o>e&&(i+=Math.ceil(o/e)-1)}return n+i}a(V,"blockRows");function Ee(t,e,r,n,i,s){let o=`
7
7
  ${x(e)}
8
8
  `;r!==void 0&&(o+=` ${$(r)}
9
9
  `),o+=`
10
- `;let a=0;for(const[d,h]of n.entries()){const c=h.bindingId===void 0?++a:0,m=h.bindingId!==void 0?g(t,h.bindingId):c<=9?g(t,`crtr.profile.menu.slot.${c}`):"",u=d===i?J:" ",p=h.detail!==""?" "+$(h.detail):"",f=h.isDefault?" "+y("\xB7 "+(h.defaultText??"default")):"";o+=` ${u} ${Re(m)} ${h.label}${p}${f}
10
+ `;let l=0;for(const[d,h]of n.entries()){const c=h.bindingId===void 0?++l:0,m=h.bindingId!==void 0?w(t,h.bindingId):c<=9?w(t,`crtr.profile.menu.slot.${c}`):"",u=d===i?J:" ",p=h.detail!==""?" "+$(h.detail):"",f=h.isDefault?" "+y("\xB7 "+(h.defaultText??"default")):"";o+=` ${u} ${Re(m)} ${h.label}${p}${f}
11
11
  `}return s!==void 0&&(o+=`
12
12
  ${$(s)}
13
13
  `),o+=`
14
- ${$(`${g(t,"crtr.profile.menu.up")}/${g(t,"crtr.profile.menu.down")} move ${g(t,"crtr.profile.menu.select")} select ${g(t,"crtr.profile.menu.accept-default")} default ${g(t,"crtr.profile.menu.abort")} quit`)}
15
- `,o}l(Ee,"renderMenu");function X(t,e,r,n,i={}){const s=[];n.forEach((a,d)=>{a.bindingId===void 0&&s.push(d)});let o=i.initialIndex??0;return new Promise(a=>{let d=0;const h=l(()=>{const u=Ee(t,e,r,n,o,i.hint);process.stdout.write((d>0?z(d)+Q:"")+u),d=V(u)},"draw"),c=l(()=>{process.stdin.off("keypress",m),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),m=l((u,p)=>{const f=Te(t,Y(u,p));if(f==="crtr.profile.menu.abort"&&(c(),process.stdout.write(`
16
- `),process.exit(130)),f==="crtr.profile.menu.up"){o=(o-1+n.length)%n.length,h();return}if(f==="crtr.profile.menu.down"){o=(o+1)%n.length,h();return}if(f==="crtr.profile.menu.select"){c(),a({index:o});return}if(f==="crtr.profile.menu.accept-default"){c(),a({index:i.initialIndex??0});return}if(f?.startsWith("crtr.profile.menu.slot.")){const I=Number.parseInt(f.slice(-1),10);I>=1&&I<=s.length&&(o=s[I-1],h());return}const w=n.findIndex(I=>I.bindingId!==void 0&&I.bindingId===f);if(w>=0){c(),a({index:w});return}f!==null&&i.actionBindingIds?.includes(f)===!0&&(c(),a({index:o,action:f}))},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",m),h()})}l(X,"runMenu");function Z(t){return ye()?(le("tmux",["display-popup","-E","-T"," profiles ","-w","90%","-h","85%","-d",t,...xe(),"crtr sys settings --page profiles"],{stdio:"inherit"}),!0):(process.stdout.write(` ${$("the profile manager needs tmux \u2014 run `crtr sys settings` instead")}
17
- `),!1)}l(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${y("\u203A")} ${$(t)} `}l(ee,"caret");function De(t){return`crtr: no profile covers ${t}, and this session is non-interactive \u2014 using the root profile.
14
+ ${$(`${w(t,"crtr.profile.menu.up")}/${w(t,"crtr.profile.menu.down")} move ${w(t,"crtr.profile.menu.select")} select ${w(t,"crtr.profile.menu.accept-default")} default ${w(t,"crtr.profile.menu.abort")} quit`)}
15
+ `,o}a(Ee,"renderMenu");function X(t,e,r,n,i={}){const s=[];n.forEach((l,d)=>{l.bindingId===void 0&&s.push(d)});let o=i.initialIndex??0;return new Promise(l=>{let d=0;const h=a(()=>{const u=Ee(t,e,r,n,o,i.hint);process.stdout.write((d>0?z(d)+Q:"")+u),d=V(u)},"draw"),c=a(()=>{process.stdin.off("keypress",m),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),m=a((u,p)=>{const f=Te(t,Y(u,p));if(f==="crtr.profile.menu.abort"&&(c(),process.stdout.write(`
16
+ `),process.exit(130)),f==="crtr.profile.menu.up"){o=(o-1+n.length)%n.length,h();return}if(f==="crtr.profile.menu.down"){o=(o+1)%n.length,h();return}if(f==="crtr.profile.menu.select"){c(),l({index:o});return}if(f==="crtr.profile.menu.accept-default"){c(),l({index:i.initialIndex??0});return}if(f?.startsWith("crtr.profile.menu.slot.")){const I=Number.parseInt(f.slice(-1),10);I>=1&&I<=s.length&&(o=s[I-1],h());return}const g=n.findIndex(I=>I.bindingId!==void 0&&I.bindingId===f);if(g>=0){c(),l({index:g});return}f!==null&&i.actionBindingIds?.includes(f)===!0&&(c(),l({index:o,action:f}))},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",m),h()})}a(X,"runMenu");function Z(t){return ye()?(ae("tmux",["display-popup","-E","-T"," profiles ","-w","90%","-h","85%","-d",t,...xe(),"crtr sys settings --page profiles"],{stdio:"inherit"}),!0):(process.stdout.write(` ${$("the profile manager needs tmux \u2014 run `crtr sys settings` instead")}
17
+ `),!1)}a(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${y("\u203A")} ${$(t)} `}a(ee,"caret");function ke(t){return`crtr: no profile covers ${t}, and this session is non-interactive \u2014 using the root profile.
18
18
  Run \`crtr profile new --name <name> --project ${t}\` to create a dedicated profile, or pass --profile <id-or-name> next time.
19
- `}l(De,"rootProfileMessage");async function Oe(t,e){const r=M({input:process.stdin,output:process.stdout});try{Ce(`Profile "${t.manifest.name}" doesn't cover this directory`),await te(r,t,e)}finally{r.close()}}l(Oe,"promptAddDirToProfile");async function te(t,e,r){const n=(await t.question(ee(`add this directory to "${e.manifest.name}"? [Y/n]`))).trim().toLowerCase();n==="n"||n==="no"||(await j(e.profileId,r),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${e.manifest.name}"`)}
20
- `))}l(te,"offerAddDirToProfile");async function je(t){const e=[...D()].filter(s=>s.profileId!==L).sort((s,o)=>_(s.manifest.last_used_at,o.manifest.last_used_at)?-1:1);if(e.length===0)return process.stdout.write(` ${$("no existing profiles to select")}
21
- `),null;let r="",n=0;const i=l(()=>r===""?e:e.filter(s=>s.manifest.name.toLowerCase().includes(r)||P(s.manifest.projects).some(o=>b(o).toLowerCase().includes(r))),"matchesOf");return new Promise(s=>{let o=0;const a=l(()=>{const c=i();n>=c.length&&(n=Math.max(0,c.length-1));let m=`
19
+ `}a(ke,"rootProfileMessage");async function De(t,e){const r=M({input:process.stdin,output:process.stdout});try{Ce(`Profile "${t.manifest.name}" doesn't cover this directory`),await te(r,t,e)}finally{r.close()}}a(De,"promptAddDirToProfile");async function te(t,e,r){process.stdout.write(` ${$(`adding means every "${e.manifest.name}" node also loads this repo's documents; say no for one-off work, or make a separate profile if this work has its own conventions`)}
20
+ `);const n=(await t.question(ee(`add this directory to "${e.manifest.name}"? [Y/n]`))).trim().toLowerCase();n==="n"||n==="no"||(await O(e.profileId,r),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${e.manifest.name}"`)}
21
+ `))}a(te,"offerAddDirToProfile");async function Oe(t){const e=[...k()].filter(s=>s.profileId!==L).sort((s,o)=>_(s.manifest.last_used_at,o.manifest.last_used_at)?-1:1);if(e.length===0)return process.stdout.write(` ${$("no existing profiles to select")}
22
+ `),null;let r="",n=0;const i=a(()=>r===""?e:e.filter(s=>s.manifest.name.toLowerCase().includes(r)||P(s.manifest.projects).some(o=>v(o).toLowerCase().includes(r))),"matchesOf");return new Promise(s=>{let o=0;const l=a(()=>{const c=i();n>=c.length&&(n=Math.max(0,c.length-1));let m=`
22
23
  ${x("Select an existing profile")}
23
24
  `;if(m+=` ${$("across every profile, not just this directory")}
24
25
 
@@ -26,10 +27,10 @@ Run \`crtr profile new --name <name> --project ${t}\` to create a dedicated prof
26
27
  `;else{const u=Math.max(...c.map(p=>p.manifest.name.length));c.forEach((p,f)=>{m+=` ${f===n?J:" "} ${x(p.manifest.name.padEnd(u))} ${$(Se(p))}
27
28
  `})}m+=`
28
29
  ${y("\u203A")} ${r}${$("\u2588")}
29
- `,m+=` ${$(`type to filter ${g(t,"crtr.profile.search.up")}/${g(t,"crtr.profile.search.down")} move ${g(t,"crtr.profile.search.pick")} pick ${g(t,"crtr.profile.search.back")} back`)}
30
- `,process.stdout.write((o>0?z(o)+Q:"")+m),o=V(m)},"draw"),d=l(()=>{process.stdin.off("keypress",h),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),h=l((c,m)=>{const u=_e(t,Y(c,m));if(u==="crtr.profile.search.abort"&&(d(),process.stdout.write(`
31
- `),process.exit(130)),u==="crtr.profile.search.back"){d(),s(null);return}const p=i();if(u==="crtr.profile.search.pick"){p.length>0&&(d(),s(p[n].profileId));return}if(u==="crtr.profile.search.up"){p.length>0&&(n=(n-1+p.length)%p.length,a());return}if(u==="crtr.profile.search.down"){p.length>0&&(n=(n+1)%p.length,a());return}if(u==="crtr.profile.search.delete"){r=r.slice(0,-1),n=0,a();return}c!==void 0&&c.length===1&&c>=" "&&m.ctrl!==!0&&(r+=c.toLowerCase(),n=0,a())},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",h),a()})}l(je,"promptSelectExistingProfile");async function re(t,e){const r=fe(e)||"profile",n=(await t.question(ee(`name the new profile [${r}]`))).trim(),i=n!==""?n:r,s=(await ge(i,[{path:e}])).profileId;return process.stdout.write(` ${y("\u2713")} ${$(`created profile "${i}"`)}
32
- `),s}l(re,"createProfileHere");async function ke(t,e){const r=[{label:"create a profile here",detail:"",bindingId:"crtr.profile.menu.create"},{label:"select an existing profile",detail:"",bindingId:"crtr.profile.menu.search-existing"},{label:$("use the root profile"),detail:"",bindingId:"crtr.profile.menu.use-root",isDefault:!0}];for(;;){const n=await X(e,"No profile covers this directory",void 0,r,{initialIndex:2,actionBindingIds:["crtr.profile.menu.manage"],hint:`${g(e,"crtr.profile.menu.manage")}=manage profiles`});if(n.action==="crtr.profile.menu.manage"){if(Z(t))return R;continue}if(n.index===0){const i=M({input:process.stdin,output:process.stdout});try{return await re(i,t)}finally{i.close()}}if(n.index===1){const i=await je(e);if(i===null)continue;const s=he(i),o=M({input:process.stdin,output:process.stdout});try{await te(o,s,t)}finally{o.close()}return s.profileId}return(await k()).profileId}}l(ke,"promptCreateOrRoot");async function C(t,e,r,n,i){const s=[...t].sort((f,w)=>_(f.manifest.last_used_at,w.manifest.last_used_at)?-1:1),o=n!==null?s.find(f=>f.profileId===n)??null:null,a=o!==null?[o,...s.filter(f=>f!==o)]:s,d=Math.max(...a.map(f=>f.manifest.name.length)),h=a.map((f,w)=>{const I=P(f.manifest.projects),v=I.length,ne=r?`${G(f.manifest.last_used_at)}${v>1?` \xB7 ${v} dirs total`:""}`:(()=>{const S=I.find(ie=>F(e,ie))??I[0];return v>1?`matches ${b(S)} \xB7 ${v} dirs total`:`matches ${b(S)}`})(),oe=o!==null&&a[0]===o?"default (pinned)":"default";return{label:x(f.manifest.name.padEnd(d)),detail:ne,isDefault:w===0,defaultText:oe}});h.push({label:$("create a new profile here"),detail:"",bindingId:"crtr.profile.menu.create"});const c=["crtr.profile.menu.set-default","crtr.profile.menu.manage"];r||c.push("crtr.profile.menu.add-directory"),o!==null&&c.push("crtr.profile.menu.unpin");const m=[`${g(i,"crtr.profile.menu.set-default")}=set default`];r||m.push(`${g(i,"crtr.profile.menu.add-directory")}=add dir here`),o!==null&&m.push(`${g(i,"crtr.profile.menu.unpin")}=unpin`),m.push(`${g(i,"crtr.profile.menu.manage")}=manage profiles`);const u=await X(i,r?"Choose a profile":"Select a profile",r?"Several profiles claim this directory as their project":"This directory falls under existing profile(s)",h,{actionBindingIds:c,hint:m.join(" ")});if(u.action==="crtr.profile.menu.manage")return Z(e)?R:await C(t,e,r,n,i);if(u.index>=a.length){const f=M({input:process.stdin,output:process.stdout});try{return await re(f,e)}finally{f.close()}}const p=a[u.index];return u.action==="crtr.profile.menu.unpin"?(await N(e),process.stdout.write(` ${y("\u2713")} ${$("cleared the default for this directory")}
30
+ `,m+=` ${$(`type to filter ${w(t,"crtr.profile.search.up")}/${w(t,"crtr.profile.search.down")} move ${w(t,"crtr.profile.search.pick")} pick ${w(t,"crtr.profile.search.back")} back`)}
31
+ `,process.stdout.write((o>0?z(o)+Q:"")+m),o=V(m)},"draw"),d=a(()=>{process.stdin.off("keypress",h),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),h=a((c,m)=>{const u=_e(t,Y(c,m));if(u==="crtr.profile.search.abort"&&(d(),process.stdout.write(`
32
+ `),process.exit(130)),u==="crtr.profile.search.back"){d(),s(null);return}const p=i();if(u==="crtr.profile.search.pick"){p.length>0&&(d(),s(p[n].profileId));return}if(u==="crtr.profile.search.up"){p.length>0&&(n=(n-1+p.length)%p.length,l());return}if(u==="crtr.profile.search.down"){p.length>0&&(n=(n+1)%p.length,l());return}if(u==="crtr.profile.search.delete"){r=r.slice(0,-1),n=0,l();return}c!==void 0&&c.length===1&&c>=" "&&m.ctrl!==!0&&(r+=c.toLowerCase(),n=0,l())},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",h),l()})}a(Oe,"promptSelectExistingProfile");async function re(t,e){const r=fe(e)||"profile",n=(await t.question(ee(`name the new profile [${r}]`))).trim(),i=n!==""?n:r,s=(await we(i,[{path:e}])).profileId;return process.stdout.write(` ${y("\u2713")} ${$(`created profile "${i}"`)}
33
+ `),s}a(re,"createProfileHere");async function je(t,e){const r=[{label:"create a profile here",detail:"",bindingId:"crtr.profile.menu.create"},{label:"select an existing profile",detail:"",bindingId:"crtr.profile.menu.search-existing"},{label:$("use the root profile"),detail:"",bindingId:"crtr.profile.menu.use-root",isDefault:!0}];for(;;){const n=await X(e,"No profile covers this directory",void 0,r,{initialIndex:2,actionBindingIds:["crtr.profile.menu.manage"],hint:`${w(e,"crtr.profile.menu.manage")}=manage profiles`});if(n.action==="crtr.profile.menu.manage"){if(Z(t))return R;continue}if(n.index===0){const i=M({input:process.stdin,output:process.stdout});try{return await re(i,t)}finally{i.close()}}if(n.index===1){const i=await Oe(e);if(i===null)continue;const s=he(i),o=M({input:process.stdin,output:process.stdout});try{await te(o,s,t)}finally{o.close()}return s.profileId}return(await j()).profileId}}a(je,"promptCreateOrRoot");async function C(t,e,r,n,i){const s=[...t].sort((f,g)=>_(f.manifest.last_used_at,g.manifest.last_used_at)?-1:1),o=n!==null?s.find(f=>f.profileId===n)??null:null,l=o!==null?[o,...s.filter(f=>f!==o)]:s,d=Math.max(...l.map(f=>f.manifest.name.length)),h=l.map((f,g)=>{const I=P(f.manifest.projects),b=I.length,ne=r?`${G(f.manifest.last_used_at)}${b>1?` \xB7 ${b} dirs total`:""}`:(()=>{const S=I.find(ie=>F(e,ie))??I[0];return b>1?`matches ${v(S)} \xB7 ${b} dirs total`:`matches ${v(S)}`})(),oe=o!==null&&l[0]===o?"default (pinned)":"default";return{label:x(f.manifest.name.padEnd(d)),detail:ne,isDefault:g===0,defaultText:oe}});h.push({label:$("create a new profile here"),detail:"",bindingId:"crtr.profile.menu.create"});const c=["crtr.profile.menu.set-default","crtr.profile.menu.manage"];r||c.push("crtr.profile.menu.add-directory"),o!==null&&c.push("crtr.profile.menu.unpin");const m=[`${w(i,"crtr.profile.menu.set-default")}=set default`];r||m.push(`${w(i,"crtr.profile.menu.add-directory")}=add dir here`),o!==null&&m.push(`${w(i,"crtr.profile.menu.unpin")}=unpin`),m.push(`${w(i,"crtr.profile.menu.manage")}=manage profiles`);const u=await X(i,r?"Choose a profile":"Select a profile",r?"Several profiles claim this directory as their project":"This directory falls under existing profile(s)",h,{actionBindingIds:c,hint:m.join(" ")});if(u.action==="crtr.profile.menu.manage")return Z(e)?R:await C(t,e,r,n,i);if(u.index>=l.length){const f=M({input:process.stdin,output:process.stdout});try{return await re(f,e)}finally{f.close()}}const p=l[u.index];return u.action==="crtr.profile.menu.unpin"?(await N(e),process.stdout.write(` ${y("\u2713")} ${$("cleared the default for this directory")}
33
34
  `),p.profileId):(u.action==="crtr.profile.menu.set-default"?(await Ie(e,p.profileId),process.stdout.write(` ${y("\u2713")} ${$(`"${p.manifest.name}" is now the default here`)}
34
- `)):u.action==="crtr.profile.menu.add-directory"&&(await j(p.profileId,e),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${p.manifest.name}"`)}
35
- `)),p.profileId)}l(C,"promptPickProfileOrCreate");async function et(t,e,r=!1,n=!0){const i=l(async a=>{n?await O(a):O(a).catch(d=>de(ue(me(),"attach-invariants.log"),`${new Date().toISOString()} profile.last_used ${a} ${String(d).replaceAll(/[\r\n]/g," ")}`))},"touch"),s=W(t),o=be();if(e!=null&&e!==""){const a=$e(e);return!H(a,s)&&q()&&await Oe(a,s),await i(a.profileId),a.profileId}for(;;){const{covering:a,exact:d,pinnedId:h,pinned:c}=K(s);if(h!==null&&c===null&&await N(s),c!==null&&!r)return await i(c.profileId),c.profileId;if(!r&&c===null&&d.length===1)return await i(d[0].profileId),d[0].profileId;if(!q()){const p=d.length>0?d:a;if(p.length>0){const w=U(p);return await i(w.profileId),w.profileId}const f=await k();return process.stderr.write(De(s)),f.profileId}const m=c!==null?c.profileId:null,u=d.length>1?await C(d,s,!0,m,o):a.length>0?await C(a,s,!1,m,o):await ke(s,o);if(u!==R)return await i(u),u}}l(et,"selectProfileForCwd");export{H as profileCoversCwd,Te as resolveProfileMenuAction,_e as resolveProfileSearchAction,et as selectProfileForCwd,Ze as selectProfileForCwdReadOnly};
35
+ `)):u.action==="crtr.profile.menu.add-directory"&&(await O(p.profileId,e),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${p.manifest.name}"`)}
36
+ `)),p.profileId)}a(C,"promptPickProfileOrCreate");async function et(t,e,r=!1,n=!0){const i=a(async l=>{n?await D(l):D(l).catch(d=>de(ue(me(),"attach-invariants.log"),`${new Date().toISOString()} profile.last_used ${l} ${String(d).replaceAll(/[\r\n]/g," ")}`))},"touch"),s=W(t),o=ve();if(e!=null&&e!==""){const l=$e(e);return!H(l,s)&&q()&&await De(l,s),await i(l.profileId),l.profileId}for(;;){const{covering:l,exact:d,pinnedId:h,pinned:c}=K(s);if(h!==null&&c===null&&await N(s),c!==null&&!r)return await i(c.profileId),c.profileId;if(!r&&c===null&&d.length===1)return await i(d[0].profileId),d[0].profileId;if(!q()){const p=d.length>0?d:l;if(p.length>0){const g=U(p);return await i(g.profileId),g.profileId}const f=await j();return process.stderr.write(ke(s)),f.profileId}const m=c!==null?c.profileId:null,u=d.length>1?await C(d,s,!0,m,o):l.length>0?await C(l,s,!1,m,o):await je(s,o);if(u!==R)return await i(u),u}}a(et,"selectProfileForCwd");export{H as profileCoversCwd,Te as resolveProfileMenuAction,_e as resolveProfileSearchAction,et as selectProfileForCwd,Ze as selectProfileForCwdReadOnly};
@@ -1 +1 @@
1
- var pe=Object.defineProperty;var m=(e,t)=>pe(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as K}from"../../api/command-manifest/result.js";import{callerAllows as ce,requireGroup as fe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as me}from"../grants/terminal.js";import{environmentPayerOfNode as ve,findRefusal as ge,payerOf as he,refusalError as we,refusedMark as ye,writeCharge as be}from"../ledger/index.js";import{listInstalledPlugins as _e}from"../resolver.js";import{emitEvent as je}from"../events/emit.js";import{ProviderError as l,scopeMissing as ke}from"./errors.js";import{parseProviderPayment as Ae}from"../provider-failure.js";import{resolveProviderRef as Pe}from"./roots.js";import{providerToolPath as $e}from"../plugin-objects-manifest.js";import{ensureProviderBundle as Ee,refreshProviderBundle as Z,resolveProviderBundle as S,unavailableProviderError as qe}from"./bundles.js";import{prepareFileCall as Ce,resignForRetry as ee,resolveFileResult as re}from"./files.js";import{consumeApproval as Re,requireProviderApproval as Te}from"./approval.js";import{actingToken as Me,outboundToken as Oe}from"./mint.js";import{discardFile as Ie}from"./token-cache.js";import{registerProviderCall as Ne}from"./inflight.js";import{buildRequestPlan as Be,paramKey as Se}from"../command-plugins/transport/http-plan.js";import{newTraceId as Fe}from"../../shared/traceparent.js";import{sendProviderRequest as De,ProviderTransportError as Ue}from"./request.js";import{acceptProviderReceipt as Le}from"./receipts.js";import{writeProviderAudit as xe}from"./audit.js";import{selectDevice as Je,sendDeviceCall as He,deviceFailure as Ge,deviceUnreachable as te,DEFAULT_DEVICE_REQUEST_MS as ze}from"./device.js";import{isLibsSearch as oe,wantsBundling as Ke,callLibsSearch as Qe,bundleExec as Ve,mapLibOutcome as We,reportLibCalls as Xe}from"./device-libs.js";import{ownMachineId as Ye}from"../peer/directory.js";import{directoryIssuer as Ze}from"../directory/issuer.js";import{isCloudRole as er}from"../canvas/person-state.js";import{formatCrtrCaller as ne}from"../command-plugins/caller-header.js";import{getNode as rr}from"../canvas/canvas.js";import{envelopeForProviderCaller as tr,EnvelopeError as or}from"../peer/envelope.js";const nr="app:terminal";function ie(e){const t=[],i=m((p,r,n)=>{const c=[...r,p.name],d=n||p.tier==="hidden";if(p.kind==="branch"){for(const b of p.children)i(b,c,d);return}const h=$e(e.roots.length,c);t.push({tool:h,leaf:p,hidden:d})},"walk");for(const p of e.roots)i(p,[],!1);return t}m(ie,"providerLeaves");function ae(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ae(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:s,description:j,whenToUse:w,tier:y,summary:A,params:P,output:o,effects:u,group:k}=v;t.push({kind:_,name:s,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:A,params:P,output:o,effects:u,group:k})}if(t.length===0)return null;const{kind:i,name:p,description:r,whenToUse:n,tier:c,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:p,description:r,whenToUse:n,...c===void 0?{}:{tier:c},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ae,"providerHelpBranch");async function xr(e,t){const i=await S(t),p=ie(i.commands),r=_e("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>ce(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:p.filter(({leaf:c,hidden:d})=>!d&&c.group===n.group).map(({tool:c,leaf:d})=>({tool:c,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const c=ae(n);return c?[c]:[]})}}m(xr,"providerTools");async function ir(e){return await Le(e.headers["crtr-receipt"],e)}m(ir,"onProviderResponse");async function ar(e){if(e.class==="person"){const t=(await me())?.sub;if(!t)throw new l("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new l("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(ar,"identity");function se(e,t){return[`${e.id}:${t.group}`]}m(se,"callScope");function sr(e,t){const i=ie(e.commands).find(p=>p.tool===t);if(!i)throw new l("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new l("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(sr,"leafFor");function Q(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(Q,"errorBody");function dr(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const p=Date.parse(t);return Number.isFinite(p)?Math.max(0,Math.ceil((p-Date.now())/1e3)):void 0}m(dr,"retryAfter");function F(e,t,i,p=!1){const r=Q(t),n=typeof r.code=="string"?r.code:void 0,c=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=Ae(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,s={origin:"provider",details:{code:n??null,message:c,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new l("provider_rate_limited",c,{...s,retry_after_s:dr(i["retry-after"])}):e===401||e>=500?new l("provider_unavailable",c,s):e===403&&n==="provider_refused"?new l("provider_refused",c,s):e===403&&n==="approval_required"?new l("provider_error",p?"provider asked for approval again":"provider approval question is invalid",{...s,status:e}):new l("provider_error",c,{...s,status:e})}m(F,"mapProviderResponse");function de(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(de,"approvalShape");async function ur(e){const t=e.origin!==void 0?ne({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):ne({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await rr(e.node_id))?.profile_id??void 0:void 0,machine:Ze()!==null?Ye():void 0});return t===""?{}:{"Crtr-Caller":t}}m(ur,"crtrCallerHeader");async function Jr(e,t,i){const p=Pe(t.provider);if(p===null)throw new l("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:p},n=new AbortController,c=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?c():i.signal.addEventListener("abort",c,{once:!0});let d=i.requestId;const h=i.traceId??Fe(),b=Ne({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,s,j,w,y,A,P="allowed";try{if(er()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw ke(`${r.provider}:*`);try{await Ee(r.provider)}catch{throw qe(r.provider)}let o=await S(r.provider,r.version),u=!1,k=!1,$,D,q,V=!1,W=!1,U,X=0;for(;;){const g=sr(o,r.tool);if(s=`${o.id}:${g.group}`,fe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new l("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await Je(r.machine,void 0,{newest:oe(o.major,r.tool)}),X=Date.now()+(o.commands.timeouts?.requestMs??ze));let L=null;if(r.approval&&!V){const a=await Re(e,r,de(o,g));q=a.option,L=a.prepared,A=r.approval,d=a.requestId,V=!0}const N={params:g.params.filter(a=>"type"in a&&a.type==="file").map(a=>a.name),output:g.output.find(a=>a.type==="file")?.name??null},Y=JSON.stringify(N);if(D!==void 0&&D!==Y)throw new l("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=Y,L&&($=await ee(e,N,r.arguments,L,{signal:n.signal})),$??=await Ce(e,N,r.arguments,{signal:n.signal});const x=await ar(e),{grantee:T}=x,M=r.as??x.sub;if(o.transport.kind==="machine"){if(r.as!==void 0)throw new l("not_granted","`--as` is not available on a provider served by a device",{param:"as"});const a=await pr(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:X,signal:n.signal,machine:U});return y=a.responder,v=a.cleanup,{status:200,body:a.result}}const J=o.transport.endpoint;let C;try{C=r.as===void 0?await Oe({audience:J,sub:M,grantee:T,initiating_app:T,scope:se(o,g)},{signal:n.signal}):await Me(x,r.as,{audience:J,scope:se(o,g)},{signal:n.signal})}catch(a){if(!(a instanceof l)||a.details?.directory_error!=="invalid_target"||k)throw a;k=!0,await Z(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===J)throw a;o=E;continue}j=C.jti;const H=e.class==="person"?nr:T,O=he({call:"tool",tokenPayer:C.payer,sub:M,environmentPayer:await ve(e.node_id)}),G=await ge({scope:"call",payer:O.payer,funding:O.funding,sub:M,grantee:H,provider:`app:${o.id}`});if(G!==null)throw await be({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:O.payer,funding:O.funding,sub:M,actor:e.actor??(r.as===void 0?null:T),grantee:H,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ye(G)}),we(G);const ue={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},le=Be(ue,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await ur(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await De(le,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(a){throw n.signal.aborted?n.signal.reason??a:a instanceof Ue?new l("provider_unavailable",a.message,{origin:"provider",details:{status:null,code:a.kind}}):a}if(w??=await ir({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:T,payer:C.payer,ledger_grantee:H,funding:O.funding,node_id:e.node_id,actor:e.actor??(r.as===void 0?null:T),caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Ie(C.key),f.status>=200&&f.status<300){const a=f.body;if(!a||typeof a!="object"||Array.isArray(a))throw new l("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await re(e,$,a,{signal:n.signal})}catch(I){throw I instanceof l&&I.code==="provider_error"?new l("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}v=E.cleanup;const B=K(g.output,E.result);if(B)throw new l("provider_bad_response",`provider result has an invalid output field "${B.field}"`,{origin:"provider",param:B.field,details:{status:f.status,...B}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=Q(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!W){W=!0;const a=await Te(e,r,d,R.question,n.signal,de(o,g),$);if(A=a.questionId,q=a.option,$=await ee(e,N,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new l("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const z=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||z)&&!u){u=!0;const a=o.major;await Z(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),je({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:z?"unsupported_major":"manifest_stale",major_before:a,major_after:o.major,...z&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof l&&o.question_id&&(A=o.question_id),y===void 0&&o instanceof l&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof l?o.code:"server_error"}`,await v?.(),o}finally{try{await xe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:s,outcome:P,jti:j,receipt_id:w,responder:y,question_id:A})}finally{b()}i.signal.removeEventListener("abort",c)}}m(Jr,"callProvider");function lr(e,t){const i={...t};for(const{name:p}of e.params){const r=Se(p);r===p||!Object.hasOwn(i,r)||(i[p]=i[r],delete i[r])}return i}m(lr,"declaredNames");async function pr(e,t,i,p,r,n){const{machine:c}=n;let d;try{d=await tr(e,n.sub)}catch(u){throw u instanceof or?new l("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:c,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(oe(t.major,i.tool)){const u=await Qe(h,r.arguments,t.major),k=K(p.output,u);if(k)throw new l("provider_bad_response",`the libraries result has an invalid output field "${k.field}"`,{origin:"provider",param:k.field,details:{status:200,...k}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(Ke(t.major,i.tool,r.arguments)){const u=await Ve(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw te(c,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const s=await He(c,{tool:i.tool,arguments:lr(p,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in s)throw te(c,s.unreachable.reason,s.unreachable.message);const j=s.headers["crtr-responder"],w=Q(s.body);if(s.status<200||s.status>=300){const u=Ge(c,s.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,s.body),k=u===null&&s.status>=500&&typeof w.code=="string"?new l("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${s.status}`,{origin:"runtime",status:s.status,details:{code:w.code,status:s.status}}):null;throw Object.assign(u??k??F(s.status,s.body,s.headers),{responder:j})}const y=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?s.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new l("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:s.status,message:"the device result is not a JSON object"}}),{responder:j});let A=y;if(v!==null){const u=We(A,v);if(Xe(c,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});A=u.result}let P;try{P=await re(e,r,A,{signal:n.signal})}catch(u){throw u instanceof l&&u.code==="provider_error"?Object.assign(new l("provider_bad_response",u.message,{origin:"provider",details:{status:s.status,message:u.message}}),{responder:j}):u}const o=K(p.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new l("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:s.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(pr,"callDevice");export{Jr as callProvider,ur as crtrCallerHeader,ar as identity,F as mapProviderResponse,ir as onProviderResponse,ie as providerLeaves,xr as providerTools};
1
+ var pe=Object.defineProperty;var m=(e,o)=>pe(e,"name",{value:o,configurable:!0});import{validateDeclaredResult as z}from"../../api/command-manifest/result.js";import{callerAllows as ce,requireGroup as fe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as me}from"../grants/terminal.js";import{environmentPayerOfNode as ve,findRefusal as ge,payerOf as he,refusalError as we,refusedMark as ye,writeCharge as be}from"../ledger/index.js";import{listInstalledPlugins as _e}from"../resolver.js";import{emitEvent as je}from"../events/emit.js";import{ProviderError as l,scopeMissing as ke}from"./errors.js";import{parseProviderPayment as Ae}from"../provider-failure.js";import{resolveProviderRef as Pe}from"./roots.js";import{providerToolPath as Ee}from"../plugin-objects-manifest.js";import{ensureProviderBundle as $e,refreshProviderBundle as Z,resolveProviderBundle as S,unavailableProviderError as Re}from"./bundles.js";import{prepareFileCall as qe,resignForRetry as ee,resolveFileResult as re}from"./files.js";import{consumeApproval as Ce,requireProviderApproval as Ie}from"./approval.js";import{actingToken as Te,outboundToken as Me}from"./mint.js";import{discardFile as Oe}from"./token-cache.js";import{registerProviderCall as Ne}from"./inflight.js";import{buildRequestPlan as Be,paramKey as Se}from"../command-plugins/transport/http-plan.js";import{newTraceId as De}from"../../shared/traceparent.js";import{sendProviderRequest as Fe,ProviderTransportError as Ue}from"./request.js";import{acceptProviderReceipt as Le}from"./receipts.js";import{writeProviderAudit as xe}from"./audit.js";import{selectDevice as Je,sendDeviceCall as He,deviceFailure as Ge,deviceUnreachable as te,DEFAULT_DEVICE_REQUEST_MS as Ve}from"./device.js";import{isLibsSearch as oe,wantsBundling as ze,callLibsSearch as Ke,bundleExec as Qe,mapLibOutcome as We,reportLibCalls as Xe}from"./device-libs.js";import{ownMachineId as Ye}from"../peer/directory.js";import{directoryIssuer as Ze}from"../directory/issuer.js";import{isCloudRole as er}from"../canvas/person-state.js";import{formatCrtrCaller as ne}from"../command-plugins/caller-header.js";import{getNode as rr}from"../canvas/canvas.js";import{envelopeForProviderCaller as tr,EnvelopeError as or}from"../peer/envelope.js";const nr="app:terminal",ir="sms";function ie(e){const o=[],i=m((p,r,n)=>{const c=[...r,p.name],d=n||p.tier==="hidden";if(p.kind==="branch"){for(const b of p.children)i(b,c,d);return}const h=Ee(e.roots.length,c);o.push({tool:h,leaf:p,hidden:d})},"walk");for(const p of e.roots)i(p,[],!1);return o}m(ie,"providerLeaves");function ae(e){if(e.kind!=="branch")return null;const o=[];for(const v of e.children)if(v.kind==="branch"){const _=ae(v);_&&o.push(_)}else if("group"in v&&v.group){const{kind:_,name:s,description:j,whenToUse:w,tier:y,summary:A,params:P,output:t,effects:u,group:k}=v;o.push({kind:_,name:s,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:A,params:P,output:t,effects:u,group:k})}if(o.length===0)return null;const{kind:i,name:p,description:r,whenToUse:n,tier:c,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:p,description:r,whenToUse:n,...c===void 0?{}:{tier:c},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:o}}m(ae,"providerHelpBranch");async function Jr(e,o){const i=await S(o),p=ie(i.commands),r=_e("user").find(n=>n.name===o)?.manifest.description??o;return{provider:o,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>ce(e,`${o}:${n.group}`)).map(n=>({group:n.group,leaves:p.filter(({leaf:c,hidden:d})=>!d&&c.group===n.group).map(({tool:c,leaf:d})=>({tool:c,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const c=ae(n);return c?[c]:[]})}}m(Jr,"providerTools");async function ar(e){return await Le(e.headers["crtr-receipt"],e)}m(ar,"onProviderResponse");async function sr(e){if(e.class==="person"){const o=(await me())?.sub;if(!o)throw new l("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.");return{sub:o,grantee:o}}if(!e.sub||!e.grantee)throw new l("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(sr,"identity");function se(e,o){return[`${e.id}:${o.group}`]}m(se,"callScope");function dr(e,o){const i=ie(e.commands).find(p=>p.tool===o);if(!i)throw new l("not_found",`tool "${o}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new l("not_found",`tool "${o}" has no group`,{param:"tool"});return i.leaf}m(dr,"leafFor");function K(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const o=e.error;return!o||typeof o!="object"||Array.isArray(o)?{}:o}m(K,"errorBody");function ur(e){const o=Array.isArray(e)?e[0]:e;if(!o)return;const i=Number(o);if(Number.isFinite(i)&&i>=0)return i;const p=Date.parse(o);return Number.isFinite(p)?Math.max(0,Math.ceil((p-Date.now())/1e3)):void 0}m(ur,"retryAfter");function D(e,o,i,p=!1){const r=K(o),n=typeof r.code=="string"?r.code:void 0,c=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=Ae(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,s={origin:"provider",details:{code:n??null,message:c,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new l("provider_rate_limited",c,{...s,retry_after_s:ur(i["retry-after"])}):e===401||e>=500?new l("provider_unavailable",c,s):e===403&&n==="provider_refused"?new l("provider_refused",c,s):e===403&&n==="approval_required"?new l("provider_error",p?"provider asked for approval again":"provider approval question is invalid",{...s,status:e}):new l("provider_error",c,{...s,status:e})}m(D,"mapProviderResponse");function de(e,o){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:o.rest,params:o.params,output:o.output})}m(de,"approvalShape");async function lr(e){const o=e.origin!==void 0?ne({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):ne({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await rr(e.node_id))?.profile_id??void 0:void 0,machine:Ze()!==null?Ye():void 0});return o===""?{}:{"Crtr-Caller":o}}m(lr,"crtrCallerHeader");async function Hr(e,o,i){const p=Pe(o.provider);if(p===null)throw new l("not_found",`provider "${o.provider}" is not available`,{param:"provider"});const r={...o,provider:p},n=new AbortController,c=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?c():i.signal.addEventListener("abort",c,{once:!0});let d=i.requestId;const h=i.traceId??De(),b=Ne({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,s,j,w,y,A,P="allowed";try{if(er()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw ke(`${r.provider}:*`);try{await $e(r.provider)}catch{throw Re(r.provider)}let t=await S(r.provider,r.version),u=!1,k=!1,E,F,R,Q=!1,W=!1,U,X=0;for(;;){const g=dr(t,r.tool);if(s=`${t.id}:${g.group}`,fe(e,t.id,g.group),t.transport.kind!=="machine"&&r.machine!==void 0)throw new l("invalid_argument",`provider "${t.id}" is not served by a device, so it takes no machine`,{param:"machine"});t.transport.kind==="machine"&&U===void 0&&(U=await Je(r.machine,void 0,{newest:oe(t.major,r.tool)}),X=Date.now()+(t.commands.timeouts?.requestMs??Ve));let L=null;if(r.approval&&!Q){const a=await Ce(e,r,de(t,g));R=a.option,L=a.prepared,A=r.approval,d=a.requestId,Q=!0}const N={params:g.params.filter(a=>"type"in a&&a.type==="file").map(a=>a.name),output:g.output.find(a=>a.type==="file")?.name??null},Y=JSON.stringify(N);if(F!==void 0&&F!==Y)throw new l("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});F=Y,L&&(E=await ee(e,N,r.arguments,L,{signal:n.signal})),E??=await qe(e,N,r.arguments,{signal:n.signal});const x=await sr(e),{grantee:I}=x,T=r.as??x.sub;if(t.transport.kind==="machine"){if(r.as!==void 0)throw new l("not_granted","`--as` is not available on a provider served by a device",{param:"as"});const a=await cr(e,t,r,g,E,{sub:T,requestId:d,deadlineAt:X,signal:n.signal,machine:U});return y=a.responder,v=a.cleanup,{status:200,body:a.result}}const J=t.transport.endpoint;let q;try{q=r.as===void 0?await Me({audience:J,sub:T,grantee:I,initiating_app:I,scope:se(t,g)},{signal:n.signal}):await Te(x,r.as,{audience:J,scope:se(t,g)},{signal:n.signal})}catch(a){if(!(a instanceof l)||a.details?.directory_error!=="invalid_target"||k)throw a;k=!0,await Z(t.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const $=await S(t.id,r.version);if($.transport.kind==="machine"||$.transport.endpoint===J)throw a;t=$;continue}j=q.jti;const H=e.class==="person"?nr:I,M=he({call:"tool",tokenPayer:q.payer,sub:T,environmentPayer:await ve(e.node_id)}),G=t.id===ir?null:await ge({scope:"call",payer:M.payer,funding:M.funding,sub:T,grantee:H,provider:`app:${t.id}`});if(G!==null)throw await be({request:d,kind:"tool",what:`${t.id}:${r.tool}`,usd:0,payer:M.payer,funding:M.funding,sub:T,actor:e.actor??(r.as===void 0?null:I),grantee:H,node:e.node_id,run:e.run_id,provider:`app:${t.id}`,causedBy:i.causedBy??null,refused:ye(G)}),we(G);const ue={registration:{name:t.id,endpoint:t.transport.endpoint},...t.commands.baseUrl?{baseUrl:t.commands.baseUrl}:{},...t.commands.timeouts?{timeouts:t.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[t.id,...r.tool.split(" ")]},le=Be(ue,E.arguments,void 0,{authorization:`Bearer ${q.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await lr(e),...R?{"Crtr-Approval":R}:{},...E.headers}});_??=Date.now()+(t.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Fe(le,{connectMs:t.commands.timeouts?.connectMs,requestMs:t.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(a){throw n.signal.aborted?n.signal.reason??a:a instanceof Ue?new l("provider_unavailable",a.message,{origin:"provider",details:{status:null,code:a.kind}}):a}if(w??=await ar({provider:t.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:T,grantee:I,payer:q.payer,ledger_grantee:H,funding:M.funding,node_id:e.node_id,actor:e.actor??(r.as===void 0?null:I),caused_by:i.causedBy??null,jti:q.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Oe(q.key),f.status>=200&&f.status<300){const a=f.body;if(!a||typeof a!="object"||Array.isArray(a))throw new l("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let $;try{$=await re(e,E,a,{signal:n.signal})}catch(O){throw O instanceof l&&O.code==="provider_error"?new l("provider_bad_response",O.message,{origin:"provider",details:{status:f.status,message:O.message}}):O}v=$.cleanup;const B=z(g.output,$.result);if(B)throw new l("provider_bad_response",`provider result has an invalid output field "${B.field}"`,{origin:"provider",param:B.field,details:{status:f.status,...B}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:$.result}}const C=K(f.body);if(f.status===403&&C.code==="approval_required"&&!R&&!W){W=!0;const a=await Ie(e,r,d,C.question,n.signal,de(t,g),E);if(A=a.questionId,R=a.option,E=await ee(e,N,r.arguments,E,{signal:n.signal}),_=void 0,n.signal.aborted)throw new l("user_denied","the approval wait was canceled");continue}if(f.status===403&&C.code==="approval_required"&&R)throw D(f.status,f.body,f.headers,!0);const V=f.status===410&&C.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(C.manifest_stale===!0||V)&&!u){u=!0;const a=t.major;await Z(t.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),t=await S(t.id,r.version),je({level:"info",event:"daemon.providers.call_retried",fields:{provider:t.id,tool:r.tool,reason:V?"unsupported_major":"manifest_stale",major_before:a,major_after:t.major,...V&&typeof C.received=="number"?{received:C.received}:{}}});continue}throw D(f.status,f.body,f.headers,!!R)}}catch(t){throw t instanceof l&&t.question_id&&(A=t.question_id),y===void 0&&t instanceof l&&typeof t.responder=="string"&&(y=t.responder),P=`refused:${t instanceof l?t.code:"server_error"}`,await v?.(),t}finally{try{await xe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:s,outcome:P,jti:j,receipt_id:w,responder:y,question_id:A})}finally{b()}i.signal.removeEventListener("abort",c)}}m(Hr,"callProvider");function pr(e,o){const i={...o};for(const{name:p}of e.params){const r=Se(p);r===p||!Object.hasOwn(i,r)||(i[p]=i[r],delete i[r])}return i}m(pr,"declaredNames");async function cr(e,o,i,p,r,n){const{machine:c}=n;let d;try{d=await tr(e,n.sub)}catch(u){throw u instanceof or?new l("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:c,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:D};if(oe(o.major,i.tool)){const u=await Ke(h,r.arguments,o.major),k=z(p.output,u);if(k)throw new l("provider_bad_response",`the libraries result has an invalid output field "${k.field}"`,{origin:"provider",param:k.field,details:{status:200,...k}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(ze(o.major,i.tool,r.arguments)){const u=await Qe(h,r.arguments,o.major);if(n.deadlineAt-Date.now()<=0)throw te(c,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const s=await He(c,{tool:i.tool,arguments:pr(p,b),version:o.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in s)throw te(c,s.unreachable.reason,s.unreachable.message);const j=s.headers["crtr-responder"],w=K(s.body);if(s.status<200||s.status>=300){const u=Ge(c,s.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,s.body),k=u===null&&s.status>=500&&typeof w.code=="string"?new l("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${s.status}`,{origin:"runtime",status:s.status,details:{code:w.code,status:s.status}}):null;throw Object.assign(u??k??D(s.status,s.body,s.headers),{responder:j})}const y=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?s.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new l("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:s.status,message:"the device result is not a JSON object"}}),{responder:j});let A=y;if(v!==null){const u=We(A,v);if(Xe(c,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});A=u.result}let P;try{P=await re(e,r,A,{signal:n.signal})}catch(u){throw u instanceof l&&u.code==="provider_error"?Object.assign(new l("provider_bad_response",u.message,{origin:"provider",details:{status:s.status,message:u.message}}),{responder:j}):u}const t=z(p.output,P.result);if(t)throw await P.cleanup?.(),Object.assign(new l("provider_bad_response",`the device result has an invalid output field "${t.field}"`,{origin:"provider",param:t.field,details:{status:s.status,...t}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(cr,"callDevice");export{Hr as callProvider,lr as crtrCallerHeader,sr as identity,D as mapProviderResponse,ar as onProviderResponse,ie as providerLeaves,Jr as providerTools};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var s=(n,e)=>_(n,"name",{value:e,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{personIdAsync as $}from"../../../core/canvas/person.js";import{assertReference as q,deleteLimit as R,listCharges as E,listLimits as m,monthTotals as L,parseUsageMonth as O,upsertLimit as T}from"../../../core/ledger/index.js";import{payersOf as b}from"../../../core/ledger/read.js";import{appOf as k}from"../router.js";import{integer as N}from"./runs.js";import{cloudPersonScope as P}from"../../../core/runs/operations.js";import{invalidRequest as S,objectBody as W}from"./validate.js";function F(n){const{principal:e}=n;if(e.class==="app"||e.class==="broker"){const r=P(e.sub);return r===void 0?{app:e.app}:{app:e.app,sub:r}}if(e.class==="person")return e.sub===void 0?void 0:{person:e.sub};throw new a(403,"owner_only","charges are read by the person, a node or an app")}s(F,"readerOf");async function G(n){const e=F(n),r=n.query.get("under"),t=n.query.get("after"),o=n.query.get("month"),i=r===null||o!==null?O(o):void 0,{charges:d,next:u}=await E({...i===void 0?{}:{month:i},...e===void 0?{}:{reader:e},...r===null?{}:{under:q(r)},...t===null?{}:{after:t},limit:N(n.query.get("limit"),"limit",1,1e4,1e3)}),f=r!==null||e!==void 0&&!("person"in e)?void 0:await L(i,e===void 0?void 0:e.person);return{...i===void 0?{}:{month:i},charges:d,next:u,...f===void 0?{}:{totals:f}}}s(G,"listRoute");const g=["bill","subscription","key","endpoint","take","legacy"],l="person:";function y(n){const{principal:e}=n;if(e.class!=="person")throw new a(403,"owner_only","spend limits are set by a person");return e.sub===void 0?void 0:e.sub.startsWith("user:")?e.sub:`user:${e.sub}`}s(y,"limitOwner");function v(n,e){const r=n.params.id??"";if(!r.startsWith(l)||r.length===l.length||r.length>128)throw new a(400,"invalid_request",`a person limit id starts with \`${l}\`; received ${r}`,{violations:[{field:"id",problem:`must start with ${l}`,received:r}]});if(e===void 0)return r;const t=r.slice(l.length);if(t.includes("/"))throw new a(400,"invalid_request","a person limit name has no `/`",{violations:[{field:"id",problem:"must not contain /",received:r}]});return`${l}${e.slice(5)}/${t}`}s(v,"idOf");function c(n,e,r){const t=n[e];if(t==null)return t;if(typeof t!="string"||t===""){r.push({field:e,problem:"must be a non-empty string or null",received:t});return}return t}s(c,"nullableString");async function I(n){const e=y(n),r=v(n,e),t=[],o=W(n.body,["payer","usd_per_month","funding","grantee","provider","sub"],t),i=o.payer;(typeof i!="string"||!/^(user|app):.+/.test(i))&&t.push({field:"payer",problem:"must be user:<id> or app:<id>",...i===void 0?{}:{received:i}});const d=o.usd_per_month;(typeof d!="number"||!Number.isFinite(d)||d<0)&&t.push({field:"usd_per_month",problem:"must be a number of at least 0",...d===void 0?{}:{received:d}});const u=c(o,"funding",t);typeof u=="string"&&!g.includes(u)&&t.push({field:"funding",problem:`must be one of ${g.join(", ")}`,received:u});const f=c(o,"grantee",t),h=c(o,"provider",t),w=c(o,"sub",t);t.length>0&&S("spend limit request",t);const p=o;if(e===void 0){if(p.payer.startsWith("user:")&&p.payer!==await $())throw new a(403,"owner_only","a person sets limits only on their own payer or on an app",{payer:p.payer})}else if(!(await b(e)).includes(p.payer))throw new a(403,"owner_only","a person sets limits only on their own payer or on an app they hold",{payer:p.payer});return await T({id:r,payer:p.payer,usd_per_month:p.usd_per_month,source:"person",...u===void 0?{}:{funding:u},...f===void 0?{}:{grantee:f},...h===void 0?{}:{provider:h},...w===void 0?{}:{sub:w}})}s(I,"setRoute");async function U(n){if(n.principal.class==="broker"){if(k(n.principal)!=="app:terminal")throw new a(403,"permission_error","only the person and terminal-app agents may read spend limits");return{limits:await m()}}const e=y(n),r=await m();if(e===void 0)return{limits:r};const t=new Set(await b(e)),o=`${l}${e.slice(5)}/`;return{limits:r.filter(i=>i.id.startsWith(o)||i.payer!==null&&t.has(i.payer)||i.account===e)}}s(U,"listLimitsRoute");async function j(n){const e=v(n,y(n));if((await m({source:"person"})).find(t=>t.id===e)===void 0||!await R(e))throw new a(404,"not_found",`no person limit ${e}`);return{id:e,removed:!0}}s(j,"removeRoute");const K=[{method:"GET",pattern:"/v1/charges",handler:s(async n=>({status:200,body:await G(n)}),"handler")}],Q=[{method:"GET",pattern:"/v1/spend-limits",handler:s(async n=>({status:200,body:await U(n)}),"handler")},{method:"PUT",pattern:"/v1/spend-limits/:id",handler:s(async n=>({status:200,body:await I(n)}),"handler")},{method:"DELETE",pattern:"/v1/spend-limits/:id",handler:s(async n=>({status:200,body:await j(n)}),"handler")}];export{K as chargeRoutes,Q as spendLimitRoutes};
1
+ var q=Object.defineProperty;var s=(n,e)=>q(n,"name",{value:e,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{personIdAsync as R}from"../../../core/canvas/person.js";import{assertReference as E,deleteLimit as L,listCharges as O,listLimits as m,monthTotals as k,parseUsageMonth as T,upsertLimit as N}from"../../../core/ledger/index.js";import{payersOf as b}from"../../../core/ledger/read.js";import{appOf as g}from"../router.js";import{integer as P}from"./runs.js";import{cloudPersonScope as v}from"../../../core/runs/operations.js";import{invalidRequest as S,objectBody as W}from"./validate.js";function F(n){const{principal:e}=n;if(e.class==="broker"&&g(e)==="app:terminal"){const r=v(e.sub);return r===void 0?void 0:{person:r}}if(e.class==="app"||e.class==="broker"){const r=v(e.sub);return r===void 0?{app:e.app}:{app:e.app,sub:r}}if(e.class==="person")return e.sub===void 0?void 0:{person:e.sub};throw new a(403,"owner_only","charges are read by the person, a node or an app")}s(F,"readerOf");async function G(n){const e=F(n),r=n.query.get("under"),t=n.query.get("after"),o=n.query.get("month"),i=r===null||o!==null?T(o):void 0,{charges:d,next:u}=await O({...i===void 0?{}:{month:i},...e===void 0?{}:{reader:e},...r===null?{}:{under:E(r)},...t===null?{}:{after:t},limit:P(n.query.get("limit"),"limit",1,1e4,1e3)}),f=r!==null||e!==void 0&&!("person"in e)?void 0:await k(i,e===void 0?void 0:e.person);return{...i===void 0?{}:{month:i},charges:d,next:u,...f===void 0?{}:{totals:f}}}s(G,"listRoute");const _=["bill","subscription","key","endpoint","take","legacy"],l="person:";function y(n){const{principal:e}=n;if(e.class!=="person")throw new a(403,"owner_only","spend limits are set by a person");return e.sub===void 0?void 0:e.sub.startsWith("user:")?e.sub:`user:${e.sub}`}s(y,"limitOwner");function $(n,e){const r=n.params.id??"";if(!r.startsWith(l)||r.length===l.length||r.length>128)throw new a(400,"invalid_request",`a person limit id starts with \`${l}\`; received ${r}`,{violations:[{field:"id",problem:`must start with ${l}`,received:r}]});if(e===void 0)return r;const t=r.slice(l.length);if(t.includes("/"))throw new a(400,"invalid_request","a person limit name has no `/`",{violations:[{field:"id",problem:"must not contain /",received:r}]});return`${l}${e.slice(5)}/${t}`}s($,"idOf");function c(n,e,r){const t=n[e];if(t==null)return t;if(typeof t!="string"||t===""){r.push({field:e,problem:"must be a non-empty string or null",received:t});return}return t}s(c,"nullableString");async function I(n){const e=y(n),r=$(n,e),t=[],o=W(n.body,["payer","usd_per_month","funding","grantee","provider","sub"],t),i=o.payer;(typeof i!="string"||!/^(user|app):.+/.test(i))&&t.push({field:"payer",problem:"must be user:<id> or app:<id>",...i===void 0?{}:{received:i}});const d=o.usd_per_month;(typeof d!="number"||!Number.isFinite(d)||d<0)&&t.push({field:"usd_per_month",problem:"must be a number of at least 0",...d===void 0?{}:{received:d}});const u=c(o,"funding",t);typeof u=="string"&&!_.includes(u)&&t.push({field:"funding",problem:`must be one of ${_.join(", ")}`,received:u});const f=c(o,"grantee",t),h=c(o,"provider",t),w=c(o,"sub",t);t.length>0&&S("spend limit request",t);const p=o;if(e===void 0){if(p.payer.startsWith("user:")&&p.payer!==await R())throw new a(403,"owner_only","a person sets limits only on their own payer or on an app",{payer:p.payer})}else if(!(await b(e)).includes(p.payer))throw new a(403,"owner_only","a person sets limits only on their own payer or on an app they hold",{payer:p.payer});return await N({id:r,payer:p.payer,usd_per_month:p.usd_per_month,source:"person",...u===void 0?{}:{funding:u},...f===void 0?{}:{grantee:f},...h===void 0?{}:{provider:h},...w===void 0?{}:{sub:w}})}s(I,"setRoute");async function U(n){if(n.principal.class==="broker"){if(g(n.principal)!=="app:terminal")throw new a(403,"permission_error","only the person and terminal-app agents may read spend limits");return{limits:await m()}}const e=y(n),r=await m();if(e===void 0)return{limits:r};const t=new Set(await b(e)),o=`${l}${e.slice(5)}/`;return{limits:r.filter(i=>i.id.startsWith(o)||i.payer!==null&&t.has(i.payer)||i.account===e)}}s(U,"listLimitsRoute");async function j(n){const e=$(n,y(n));if((await m({source:"person"})).find(t=>t.id===e)===void 0||!await L(e))throw new a(404,"not_found",`no person limit ${e}`);return{id:e,removed:!0}}s(j,"removeRoute");const K=[{method:"GET",pattern:"/v1/charges",handler:s(async n=>({status:200,body:await G(n)}),"handler")}],Q=[{method:"GET",pattern:"/v1/spend-limits",handler:s(async n=>({status:200,body:await U(n)}),"handler")},{method:"PUT",pattern:"/v1/spend-limits/:id",handler:s(async n=>({status:200,body:await I(n)}),"handler")},{method:"DELETE",pattern:"/v1/spend-limits/:id",handler:s(async n=>({status:200,body:await j(n)}),"handler")}];export{K as chargeRoutes,Q as spendLimitRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.777",
3
+ "version": "0.3.779",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.777",
161
- "@north-light/plugin": "0.3.777",
160
+ "@north-light/identity": "0.3.779",
161
+ "@north-light/plugin": "0.3.779",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.777",
3
+ "version": "0.3.779",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.777",
3
+ "version": "0.3.779",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.777",
3
+ "version": "0.3.779",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.777",
31
- "@north-light/identity": "0.3.777"
30
+ "@north-light/api": "0.3.779",
31
+ "@north-light/identity": "0.3.779"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.777",
3
+ "version": "0.3.779",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.777",
9
+ "version": "0.3.779",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.777",
32
- "@north-light/plugin": "0.3.777",
31
+ "@north-light/identity": "0.3.779",
32
+ "@north-light/plugin": "0.3.779",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.777",
11905
+ "version": "0.3.779",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.777",
11910
+ "version": "0.3.779",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.777",
11915
+ "version": "0.3.779",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.777",
11923
+ "version": "0.3.779",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.777",
11927
- "@north-light/identity": "0.3.777"
11926
+ "@north-light/api": "0.3.779",
11927
+ "@north-light/identity": "0.3.779"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.777",
11932
+ "version": "0.3.779",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.777",
11936
- "@north-light/identity": "0.3.777",
11937
- "@north-light/plugin": "0.3.777",
11935
+ "@north-light/api": "0.3.779",
11936
+ "@north-light/identity": "0.3.779",
11937
+ "@north-light/plugin": "0.3.779",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {