@north-light/cli 0.3.699 → 0.3.700
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +4 -0
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +4 -4
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/node-lifecycle-revive.d.ts +2 -10
- package/dist/commands/node-lifecycle-revive.js +1 -1
- package/dist/core/canvas/status-glyph.d.ts +9 -0
- package/dist/core/canvas/status-glyph.js +1 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.js +8 -8
- package/dist/core/graph/names.d.ts +1 -1
- package/dist/core/graph/names.js +10 -10
- package/dist/core/help.js +2 -2
- package/dist/core/permissions/ceiling.d.ts +1 -1
- package/dist/core/permissions/evaluator.d.ts +4 -6
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +2 -2
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +8 -10
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-wedge.d.ts +20 -0
- package/dist/core/runtime/broker-wedge.js +2 -0
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/runner/machine/call.js +1 -1
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +1 -14
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +14 -2
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +38 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +8 -0
- package/dist/daemon/machine-link/holder.js +5 -4
- package/dist/daemon/machine-supervision.d.ts +17 -0
- package/dist/daemon/machine-supervision.js +1 -0
- package/dist/daemon/reconcilers/broker-supervision.d.ts +11 -14
- package/dist/daemon/reconcilers/broker-supervision.js +3 -4
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +1 -1
- package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
- package/packages/crouter-api/dist/commands/node-lifecycle-revive.js +14 -16
- package/packages/crouter-api/dist/core/canvas/status-glyph.js +15 -0
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -0
- package/packages/crouter-api/dist/core/command.js +13 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -8
- package/packages/crouter-api/dist/core/help.js +1 -1
- package/packages/crouter-api/dist/core/permissions/ceiling.js +1 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +20 -12
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +26 -12
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +99 -0
- package/packages/crouter-api/dist/core/runtime/host.js +10 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +3 -3
- package/packages/crouter-api/dist/daemon/api/map.js +2 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/dist/daemon/machine-link/frames.js +4 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +63 -1
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +61 -163
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +0 -5
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +0 -4
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as I,defineLeaf as _}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as O}from"../../core/errors.js";import{isPidAlive as A}from"../../core/canvas/pid.js";import{fullName as $}from"../../core/canvas/labels.js";import{fuzzyMatch as F}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as L}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as D}from"../../api/index.js";import{cliClient as x,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as E,profilesStateBlock as z,resolveProfileViaDaemon as
|
|
2
|
-
`),"leaf")},run:h(async n=>{const e=h(d=>{const
|
|
3
|
-
`)};return i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&t.status===400?!1:w(t))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],p=e.machine;p&&r.push(`- machine: ${p.name??p.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
|
|
4
|
-
`));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,
|
|
1
|
+
var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as I,defineLeaf as _}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as O}from"../../core/errors.js";import{isPidAlive as A}from"../../core/canvas/pid.js";import{fullName as $}from"../../core/canvas/labels.js";import{fuzzyMatch as F}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as L}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as D}from"../../api/index.js";import{cliClient as x,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as E,profilesStateBlock as z,resolveProfileViaDaemon as M}from"../profile/daemon-profiles.js";import{focusViewer as B,nodeInPane as W}from"../surface/node/placement.js";const K=_({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([E(),z()])).join(`
|
|
2
|
+
`),"leaf")},run:h(async n=>{const e=h(d=>{const v=n[d];return v!==void 0&&v!==""?v.split(",").map(b=>b.trim()).filter(b=>b!==""):void 0},"csv"),o=e("status"),s=e("kind"),u=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,p=S({canvasName:n.canvas}),a=p instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await p.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await p.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||u!==void 0&&!u.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const u=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(u===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=u,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,p={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),p.session_file&&a.push(`Read the raw conversation transcript: ${p.session_file}`),a.push(`On-disk context dir (ls/read directly): ${p.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:p,follow_up:a.join(`
|
|
3
|
+
`)};return i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&t.status===400?!1:w(t))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],p=e.machine;p&&r.push(`- machine: ${p.name??p.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
|
|
4
|
+
`));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,v=g.map(b=>`| ${t.map(R=>String(b[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
|
|
5
5
|
`);return`${g.length} ${f}:
|
|
6
6
|
|
|
7
7
|
${y}
|
|
8
8
|
${d}
|
|
9
|
-
${
|
|
9
|
+
${v}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
|
|
10
10
|
${String(n.follow_up)}`),l.join(`
|
|
11
11
|
|
|
12
|
-
`)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const u=await x().forkNode(s).catch(w),i=await
|
|
12
|
+
`)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const u=await x().forkNode(s).catch(w),i=await B(u.node_id,{cwd:u.cwd,name:u.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:u.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
|
|
@@ -1,14 +1,6 @@
|
|
|
1
1
|
import type { LeafDef } from '../core/command.js';
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
* (kick it early instead of waiting out the schedule), or any fault the
|
|
5
|
-
* canvas dashboard flags "needs you" (`faultNeedsYou`, status-glyph.ts) — the
|
|
6
|
-
* disposition that otherwise has NO sanctioned recovery verb.
|
|
7
|
-
* Both are scoped to `pi→provider`: refuses a client-owned auto retry
|
|
8
|
-
* (redialing) already in flight, and refuses any OTHER link — notably a
|
|
9
|
-
* `daemon→node` wedge fault, which --now can't clear (SIGTERM doesn't touch
|
|
10
|
-
* the runaway subprocess; see `wedged-child-on-runaway-bash`). */
|
|
11
|
-
export declare function isNowEligibleFault(fault: NodeFaultDTO | null): boolean;
|
|
2
|
+
import { isNowEligibleFault } from '../core/canvas/status-glyph.js';
|
|
3
|
+
export { isNowEligibleFault };
|
|
12
4
|
export declare const nodeReviveLeaf: LeafDef;
|
|
13
5
|
/** The leaf's output. `ready:false` after a launch is only the daemon's ~10 s wait running out, so say the broker was launched and is still starting. */
|
|
14
6
|
export declare function reviveReport(result: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var l=(e,r)=>g(e,"name",{value:r,configurable:!0});import{defineLeaf as p}from"../core/command.js";import{InputError as a}from"../core/io.js";import{requireScope as k}from"../core/errors.js";import{cliClient as y,rethrowAsCliError as c}from"./api-client.js";import{recordedPidLiveness as b}from"../core/canvas/pid.js";import{fullName as m}from"../core/canvas/labels.js";import{isNowEligibleFault as v}from"../core/canvas/status-glyph.js";const G=p({name:"revive",description:"reopen a window for a done/idle/dead/canceled node",whenToUse:"you want to bring a dormant node back yourself \u2014 reopen a window for one that is done, idle, dead, or canceled: resume a node you closed with `node lifecycle close`, reopen a finished worker for a follow-up, or restart a crashed one now instead of waiting. It resumes the saved conversation by default, or can restart the node clean. You rarely need this for crashes \u2014 the daemon auto-revives those; reach for it to bring a node back on demand, to revive a canceled node the daemon will never touch on its own, or to kick a hanging one early (--now). To mass-reconnect EVERY disconnected node at once (after a reboot, a killed login/tmux session, or the daemon being down a while), use `canvas revive --all` instead",help:{name:"node lifecycle revive",summary:"relaunch a node's broker engine (resuming its saved conversation), or kick a hanging one (--now)",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id to revive."},{kind:"flag",name:"fresh",type:"bool",required:!1,default:!1,constraint:"When set, do NOT do a true resume. If the node already has a session `.jsonl`, this instead CYCLES it in place \u2014 reuses that SAME file, resets the tree leaf, and roots a fresh `crtr-cycle` branch (a clean-context restart that still carries the file's history, output `resumed:false`). Only when no `.jsonl` exists yet does this start a genuinely brand-new session (also `resumed:false`). Default (no --fresh): a true resume \u2014 replays the existing `.jsonl` as-is (`resumed:true`)."},{kind:"flag",name:"now",type:"bool",required:!1,default:!1,constraint:'On-demand kick of an active-fault node (parked on a `pi\u2192provider` fault, broker still alive). Its broker pid is alive, so an ordinary revive no-ops (double-launch guard) \u2014 --now SIGTERMs the live broker instead, so the daemon\'s crash\u2192grace\u2192resume path brings it back in ~20s. Valid for a live `pi\u2192provider` fault that is either a daemon-owned auto retry (kicks it early), or ANY fault the canvas dashboard flags "needs you" (e.g. exhausted retries, an auth fault you just fixed) \u2014 that disposition otherwise has no recovery verb. Mutually exclusive with --fresh.'},{kind:"flag",name:"reopen",type:"bool",required:!1,default:!1,constraint:"Clear a latched node's finalization latch (final_report/finalized_at only \u2014 the old report file and every delivered feed event are untouched) before reviving it. Rejected against a node that is not finalized. Mutually exclusive with --now."}],output:[{name:"resumed",type:"boolean",required:!1,constraint:"True ONLY for a true resume (the existing `.jsonl` replayed as-is). False for a --fresh revive, whether that landed as an in-place CYCLE (an existing `.jsonl` reused with a fresh `crtr-cycle` branch \u2014 pi is still told --session, but this is not a resume) or a genuinely fresh launch (no `.jsonl` existed). Absent for a --now kick."},{name:"ready",type:"boolean",required:!1,constraint:"True when the daemon saw the node's view.sock accept a connection within ~10s of the revive \u2014 the node is attachable. It does not show the task was delivered or the model is making progress. False when it did not (still starting \u2014 a launch with `ready:false` carries a `message` saying so \u2014 broker exited, or no free broker slot). Absent for a --now kick, and when the daemon predates this field (readiness unknown)."},{name:"kicked",type:"boolean",required:!1,constraint:"True when --now SIGTERM'd the hanging node's live broker (the daemon resumes it on the saved session within ~20s). Absent for an ordinary revive."},{name:"message",type:"string",required:!1,constraint:"Kick confirmation naming the signalled node, pid, and the daemon's ~20s resume handoff. Present for --now, and for a launch whose broker is still starting."}],outputKind:"object",effects:["Launches the node's detached headless broker engine (no tmux window).","Updates the node's canvas record: status=active, intent=null.","Waits up to ~10s for the daemon to see the broker's view.sock accept a connection, so `ready:true` means a caller can attach on return.","--now: SIGTERMs the live broker instead of launching anything (the daemon's own crash-grace path resumes it)."]},run:l(async e=>{k("crtr:act","crtr node lifecycle revive");const r=e.now??!1,o=e.node,h=e.fresh??!1,u=e.reopen??!1;if(r&&u)throw new a({error:"conflicting_args",message:"`--now` kicks a LIVE broker (nothing to reopen \u2014 a finalized node has no live broker); `--reopen` is meaningless there.",next:"Run `crtr node lifecycle revive <node> --now` on a hanging node, or `crtr node lifecycle revive <node> --reopen` (no --now) to re-task a finalized one."});if(r&&h)throw new a({error:"conflicting_args",message:"`--now` kicks a live hanging broker (SIGTERM \u2192 daemon resumes the SAVED session); `--fresh` is meaningless there.",next:"Run `crtr node lifecycle revive <node> --now` (resumes), or `crtr node lifecycle revive <node> --fresh` (no --now) to relaunch clean."});const i=y();if(r){let n;try{n=await i.getNode(o)}catch(d){c(d)}if(n.runner==="machine"){try{await i.kickNode(o)}catch(d){c(d)}return{kicked:!0,message:`Stopped ${m(n)} (${o}) on its Mac. The daemon relaunched it on the saved session.`}}const t=n.pi_pid,w=n.fault??null;if(t==null||b(t,n.pi_pid_identity??null)!=="alive")throw new a({error:"not_hanging",message:`${o} has no live broker \u2014 nothing to kick. --now is for a HANGING node (live broker parked on an active fault).`,next:"Revive a dormant node with `crtr node lifecycle revive "+o+"` (no --now)."});if(!v(w))throw new a({error:"not_hanging",message:`${o} is live but has no pi\u2192provider fault eligible for --now (either healthy, or a client-owned retry / non-provider fault already being handled elsewhere) \u2014 --now refuses to SIGTERM a node that isn't stuck on a kickable provider fault.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault. For a routine relaunch, omit --now."});if(n.streaming===!0)throw new a({error:"busy",message:`${o} is mid-turn right now (busy) \u2014 --now refuses to SIGTERM a working engine; it has recovered on its own.`,next:"Re-check the canvas \u2014 if it's no longer marked hanging (\u26A0), nothing to do."});try{process.kill(t,"SIGTERM")}catch{}return{kicked:!0,message:`Sent SIGTERM to ${m(n)} (${o}, pid ${t}). The daemon will resume it on the saved session within ~20s (crash\u2192grace\u2192resume).`}}const s=process.env.CRTR_CRON_ID;let f;try{f=await i.reviveNode(o,{resume:!h,reopen:u,...s!==void 0&&s!==""?{cron_id:s}:{}})}catch(n){c(n)}return x(f)},"run")});function x(e){return{resumed:e.resumed,...e.ready!==void 0?{ready:e.ready}:{},...e.ready===!1&&e.revived?{message:"Launched; the broker is still starting (not failed). Attaching waits for it."}:{}}}l(x,"reviveReport");export{v as isNowEligibleFault,G as nodeReviveLeaf,x as reviveReport};
|
|
@@ -50,3 +50,12 @@ export declare function faultSummary(fault: Fault, now?: number): string;
|
|
|
50
50
|
/** Elapsed counter used by the browse rail's countdown slot. `faultSummary`
|
|
51
51
|
* covers the presenter surfaces; this stays for the rail's existing time text. */
|
|
52
52
|
export declare function hangingCountdown(since: string, now?: number): string;
|
|
53
|
+
/** --now eligibility for a live, non-busy fault: a daemon-owned AUTO retry
|
|
54
|
+
* (kick it early instead of waiting out the schedule), or any fault the
|
|
55
|
+
* canvas dashboard flags "needs you" (`faultNeedsYou`, status-glyph.ts) — the
|
|
56
|
+
* disposition that otherwise has NO sanctioned recovery verb.
|
|
57
|
+
* Both are scoped to `pi→provider`: refuses a client-owned auto retry
|
|
58
|
+
* (redialing) already in flight, and refuses any OTHER link — notably a
|
|
59
|
+
* `daemon→node` wedge fault, which --now can't clear (SIGTERM doesn't touch
|
|
60
|
+
* the runaway subprocess; see `wedged-child-on-runaway-bash`). */
|
|
61
|
+
export declare function isNowEligibleFault(fault: Pick<Fault, 'link' | 'retry'> | null): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var o=(e,r)=>a(e,"name",{value:r,configurable:!0});import{RECESSIVE_FG as c}from"../tui/draw.js";import{FAULT_QUIET_MS as d}from"../runtime/fault.js";const l={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},s={active:"32",idle:"33",done:"36",dead:"31",canceled:c},f="\u27F3",p="92",m="\u25CC",g="94",x="\u26A0",y="33";function i(e){switch(e){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}o(i,"hangingLabel");function $(e){return e.frozen_at!=null&&e.pi_pid==null}o($,"isFrozenRow");function b(e,r){return r.hanging!=null?{glyph:x,color:y,word:i(r.hanging.kind),bold:!0}:r.frozen===!0?{glyph:m,color:g,word:"frozen"}:r.streaming===!0?{glyph:f,color:p,word:"live",bold:!0}:{glyph:l[e]??"?",color:s[e]}}o(b,"resolveNodeVisual");function h(e,r){const t=Date.parse(e);if(Number.isNaN(t))return"now";const n=t-r;return n<=0?"now":n>=6e4?`${Math.max(1,Math.round(n/6e4))}m`:`${Math.max(1,Math.ceil(n/1e3))}s`}o(h,"retryCountdown");function u(e){return e.retry.disposition!=="auto"}o(u,"faultNeedsYou");function w(e,r=Date.now()){const t=e.retry;if(!u(e)){if(t.by==="client")return"redialing";const n=typeof t.attempt=="number"&&typeof t.max=="number"?`auto-retry ${t.attempt}/${t.max}`:"auto-retrying";return t.nextAt?`${n}, next ${h(t.nextAt,r)}`:n}return"needs you"}o(w,"faultDispositionText");function L(e,r=Date.now()){return`${e.link} ${i(e.kind)} \xB7 ${w(e,r)}`}o(L,"faultSummary");function M(e,r=Date.now()){const t=Date.parse(e);if(Number.isNaN(t))return"retrying\u2026";const n=d-(r-t);return n<=0?"retrying\u2026":n>=6e4?`retry in ~${Math.max(1,Math.round(n/6e4))}m`:`retry in ~${Math.ceil(n/1e3)}s`}o(M,"hangingCountdown");function O(e){return e===null||e.link!=="pi\u2192provider"?!1:u(e)?!0:e.retry.by==="daemon"}o(O,"isNowEligibleFault");export{y as HANGING_COLOR,x as HANGING_GLYPH,s as STATUS_COLOR,l as STATUS_GLYPH,w as faultDispositionText,u as faultNeedsYou,L as faultSummary,M as hangingCountdown,i as hangingLabel,$ as isFrozenRow,O as isNowEligibleFault,b as resolveNodeVisual};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var
|
|
1
|
+
var j=Object.defineProperty;var d=(n,e)=>j(n,"name",{value:e,configurable:!0});import{resolve as w}from"node:path";import{ExitCode as U}from"../../types.js";import{envNodeId as A}from"../../shared/env.js";import{cliClient as c}from"../../commands/api-client.js";import{apiErrorToCliError as g}from"../io.js";import{ApiError as m}from"../../api/index.js";import{defineBranch as E,defineLeaf as L}from"../command.js";import{qualifiedTopLevelCommandName as M,resolveCommandRegistry as P}from"../command-manifests/registry.js";import{executeExternalLeaf as S}from"./transport/exec-invoke.js";import{invokeHttpLeaf as H}from"./transport/http-invoke.js";import{downloadNodeUpload as R,filesCrossByUpload as k,uploadNodeFile as K}from"../storage/node-transfer.js";import{readPathParam as $}from"./transport/http-plan.js";import{sha256Hex as I,signedHeaderDigest as O}from"./transport/sign.js";import{needsAppToken as q}from"../plugin-objects-manifest.js";async function C(n){const e=await c().request("GET",`/v1/providers/${encodeURIComponent(n)}/tools`);return new Set(e.groups.flatMap(a=>a.leaves.map(i=>i.tool)))}d(C,"allowedProviderTools");function v(n,e,a){return n.children.some(i=>i.kind==="leaf"?a.has([...e,i.name].join(" ")):v(i,[...e,i.name],a))}d(v,"hasAllowedLeaf");function B(n,e,a){return n.children.filter(i=>i.tier!=="hidden"&&(i.kind==="leaf"?a.has([...e,i.name].join(" ")):v(i,[...e,i.name],a))).length}d(B,"visibleChildCount");function T(n,e,a){return async()=>{if(!A())return n.help;const i=await a();return{...n.help,listing:n.help.listing?.flatMap(f=>{const o=n.children.find(p=>p.name===f.name);if(o?.kind==="leaf")return i.has([...e,o.name].join(" "))?[f]:[];if(o?.kind!=="branch")return[];const s=[...e,o.name];if(!v(o,s,i))return[];const t=B(o,s,i);return[{...f,...f.subCount!==void 0?{subCount:t}:{}}]})}}}d(T,"providerHelp");const D="Runs on one of your devices. Add `--machine <machine_id>` to pick which; without it the call goes to your only device, and with several the answer is `machine_required` listing each one's machine_id. The `runtime:` prefix on the id is optional.";function x(n,e,a,i=!1){return{outputKind:"object",...i?{machineSelector:!0}:{},run:d(async(f,o)=>{const s={...f};for(const t of a.params){if(!("type"in t))continue;const p=t.name.replace(/-([a-z])/g,(u,l)=>l.toUpperCase());if(t.type==="bool"&&t.default===void 0&&o!==void 0&&!o.providedParams.has(p)){delete s[p];continue}const r=s[p];t.type==="file"&&typeof r=="string"?s[p]=k()?{upload_id:await K(w(r))}:w(r):t.type==="path"&&r!==void 0&&(s[p]=$(`provider command \`${n} ${e}\``,t,r))}try{const t=await c({timeoutMs:0}).request("POST","/v1/provider/call",{provider:n,tool:e,arguments:s,...o?.machine===void 0?{}:{machine:o.machine}},{timeout:0});if(k())for(const p of a.output??[]){const r=t[p.name];if(p.type==="file"&&r&&typeof r=="object"&&typeof r.upload_id=="string"){const{upload_id:u,size:l,sha256:h}=r;t[p.name]=await R(u,p.name,l,h)}}return t}catch(t){throw t instanceof m?g(t,void 0,{providerCall:!0}):t}},"run")}}d(x,"providerLeafAdapter");function _(n,e){return/^[A-Za-z0-9_-]{1,64}$/.test(n)&&n!=="crtr"&&!e.has(n)}d(_,"validRootName");function se(n,e){const a=[],i=[];for(const o of n){const{provider:s,commands:t}=o;if(!Array.isArray(t)||o.status!=="available"&&!_(s,e))continue;if(o.status!=="available"){const r=o.error??"bundle installation pending",u=`Unavailable (${o.status}): ${r}`,l=E({name:s,rootEntry:{concept:o.display_name,desc:u,useWhen:u},help:{name:s,summary:u},children:[],refusal:{code:"provider_unavailable",message:u,exit:U.NETWORK,next:"The daemon retries bundle installation on grant sync; retry after the provider becomes available."}});i.push(l);continue}const p=d(r=>r.kind==="branch"?{...r,children:r.children.map(p)}:{...r,rest:{method:"GET",path:"/",params:{}}},"helpNode");for(const r of t){if(r.kind!=="branch"||!Array.isArray(r.children)||!_(r.name,e))continue;const u=p(r);a.push({contributor:{name:s,scope:"user"},manifestName:r.name,node:o.groups.length===0?{...u,rootEntry:void 0}:u,adaptLeaf:d((l,h)=>x(s,h.slice(1).join(" "),l,o.transport==="machine"),"adaptLeaf")})}}const f=F(P(a,e));for(const o of f){const s=n.find(r=>r.status==="available"&&r.commands.some(u=>u.name===o.name||M({name:r.provider},u.name)===o.name));if(s?.status!=="available")continue;const t=new Set(s.groups.flatMap(r=>r.leaves.map(u=>u.tool))),p=d((r,u)=>{r.effectiveHelp=T(r,u,async()=>t);for(const l of r.children)l.kind==="branch"&&p(l,[...u,l.name])},"attachHelp");p(o,[])}return[...f,...i]}d(se,"composeSandboxProviderSubtrees");async function z(n){try{const{token:e,socket:a}=await c().plugins.appToken(n);return{CRTR_APP_TOKEN:e,CRTR_DAEMON_SOCKET:a}}catch(e){if(e instanceof m&&(e.status===404||e.status===403))return;throw e instanceof m?g(e):e}}d(z,"appEnvFor");function b(n,e){return(a,i)=>{const f=n.transport,o=e(i);if(n.provider!==void 0)return x(n.provider.id,o.slice(1).join(" "),a,f.kind==="machine");if(f.kind==="exec"){const t=f.executable;if(t===void 0)throw new Error(`exec plugin "${n.plugin.name}" has an executable leaf without transport.executable`);return{outputKind:"object",run:d(async p=>{const r=q(n.plugin.manifest)?await z(n.plugin.name):void 0;return S({plugin:n.plugin,executable:t,commandPath:o,output:a.output,...r!==void 0?{appEnv:r}:{}},p)},"run")}}if(f.kind==="machine")throw new Error(`machine plugin "${n.plugin.name}" is not a capability provider`);const s=a;return{outputKind:s.rest.streaming===!0?"jsonl":"object",run:d((t,p)=>H({registration:{name:n.plugin.name,endpoint:f.endpoint,...f.authEnv!==void 0?{authEnv:f.authEnv}:{}},...n.manifest?.baseUrl!==void 0?{baseUrl:n.manifest.baseUrl}:{},...n.manifest?.timeouts!==void 0?{timeouts:n.manifest.timeouts}:{},params:s.params,rest:s.rest,output:s.output,commandPath:o},t,p,{callHeaders:d(r=>c().plugins.callHeaders(n.plugin.name,{method:r.method,url:r.url.href,body_sha256:I(r.body),...O(r.headers)}).then(u=>u.headers,u=>{throw u instanceof m?g(u):u}),"callHeaders")}),"run")}}}d(b,"adaptLeaf");function ue(n){return{contributions:n.map(e=>({contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,manifestName:e.manifestName,adaptLeaf:b(e,a=>[e.manifestName,...a.slice(1)]),...e.provider!==void 0?{provider:e.provider}:{}})),coreMounts:[],issues:[]}}d(ue,"adaptPluginContributions");function de(n){return n.map(e=>({parent:e.parent,plugin:e.plugin.name,contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,...e.provider!==void 0?{provider:e.provider}:{},adaptLeaf:b({...e,manifestName:e.node.name},a=>e.provider===void 0?[...a]:[e.provider.id,...a.slice(e.parent.length)])}))}d(de,"adaptPluginCoreMounts");function F(n,e=C){return n.contributions.map(a=>y(a,a.node,[a.node.name],1,e))}d(F,"composeExternalSubtrees");function pe(n,e){return n.filter(a=>a.parent.join("\0")===e.join("\0")).map(a=>a.node.kind==="branch"?y(a,a.node,[...e,a.node.name],a.provider===void 0?1:e.length):N(a,a.node,[...e,a.node.name]))}d(pe,"composeCoreBranchMounts");function y(n,e,a,i=1,f=C){const o=e.rootEntry===void 0?void 0:{concept:e.rootEntry.concept,desc:e.rootEntry.description,useWhen:e.rootEntry.whenToUse},s=E({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...o!==void 0?{rootEntry:o}:{},help:{name:a.join(" "),summary:e.summary,...e.model!==void 0?{model:e.model}:{},...a.length===1&&n.extensionIssue!==void 0?{extensionIssue:n.extensionIssue}:{}},...e.passthrough!==void 0?{passthrough:e.passthrough}:{},children:e.children.map(t=>t.kind==="branch"?y(n,t,[...a,t.name],i,f):N(n,t,[...a,t.name]))});return n.provider!==void 0&&(s.effectiveHelp=T(s,a.slice(i),()=>f(n.provider.id))),s}d(y,"buildBranch");function N(n,e,a){const i=n.adaptLeaf(e,a);return L({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...i.machineSelector===!0?{machineSelector:!0}:{},help:{name:a.join(" "),summary:e.summary,...i.machineSelector===!0?{guide:D}:{},params:e.params,output:e.output,outputKind:i.outputKind,effects:[...e.effects]},run:i.run})}d(N,"buildLeaf");export{ue as adaptPluginContributions,de as adaptPluginCoreMounts,pe as composeCoreBranchMounts,F as composeExternalSubtrees,se as composeSandboxProviderSubtrees};
|
package/dist/core/command.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var G=Object.defineProperty;var c=(e,i)=>G(e,"name",{value:i,configurable:!0});import{renderRoot as V,renderBranch as B,renderLeafArgv as W,withAsyncHelpState as K,collapseWideChildren as L,rootPromotedChildren as J}from"./help.js";import{beginPreview as D,publishPreviewResult as Q,readStdinRaw as M,peekStdinRaw as X,emit as Y,handle as Z,setJsonOutput as ee,isJsonOutput as ne}from"./io.js";import{renderResult as te}from"./render.js";import{CrtrError as R}from"./errors.js";import{validateValue as ie}from"../api/command-manifest/result.js";import{isManifestStaleError as re}from"./manifest-stale.js";import{operationIdContext as ae}from"./events/operation-id.js";import{ExitCode as _}from"../types.js";import{envNodeId as oe,providerProjectionOverBrokerRelay as se}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as le}from"node:child_process";import{constants as fe}from"node:os";import{resolve as ce}from"node:path";function F(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const i of Object.values(e))F(i);return Object.freeze(e)}c(F,"freezeCommandMetadata");function Ve(e){const i=F(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:i,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>K(i,r,n)),slash:e.slash===void 0?void 0:F(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}c(Ve,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}c(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(i=>i.tier!=="hidden").length}c(I,"visibleSubCount");function Be(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(i=>{const r=I(i);return{name:i.name,description:i.description??"",whenToUse:i.whenToUse??"",tier:O(i),kind:i.kind,...i.plugin!==void 0?{plugin:i.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}c(Be,"defineBranch");function Je(e){const i=[],r=c(n=>{if(n.slash!==void 0&&i.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return i}c(Je,"collectSlashSpecs");function Me(e){const i=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(s=>s.tier!=="hidden"),l=J(a).map(s=>({path:`${n.name} ${s.name}`,desc:s.tier==="important"?s.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:l.length>0?l:void 0,otherSubcommandCount:a.length-l.length}});return{kind:"root",help:{tagline:e.tagline,commands:i,globals:e.globals},subtrees:e.subtrees}}c(Me,"defineRoot");function ue(e){if(e.kind==="root")return e.subtrees.filter(i=>O(i)!=="hidden").map(i=>i.name);if(e.kind==="branch"){const{listed:i,unlisted:r}=L(e.children.filter(n=>O(n)!=="hidden"));return[...i.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}c(ue,"childNames");function he(e,i){let r=e;const n=[];let a=0;for(;a<i.length;){const l=i[a];if(l==="-h"||l==="--help")break;if(r.kind==="root"){const s=r.subtrees.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else if(r.kind==="branch"){const s=r.children.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else break}return{node:r,path:n,remaining:i.slice(a)}}c(he,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):W(e.help)}c(me,"renderNode");async function z(e,i,r){if(r!==void 0&&e.kind==="leaf")return W(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?W(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(i.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:l},{SUBTREE_NAMES:s,coreCommandPathsCovering:o,extensibleCoreBranches:$}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),v=await l(i.join(" "),{reservedCoreNames:new Set(s),coreCommandPaths:o,extensibleCoreBranches:$});return n+v.map(S=>`
|
|
2
2
|
|
|
3
|
-
<plugin-help plugin="${
|
|
4
|
-
${
|
|
5
|
-
</plugin-help>`).join("")}
|
|
3
|
+
<plugin-help plugin="${S.plugin}">
|
|
4
|
+
${S.text}
|
|
5
|
+
</plugin-help>`).join("")}c(z,"renderNodeWithAddenda");function pe(e){return e.some(i=>i==="-h"||i==="--help")}c(pe,"helpRequested");function ge(e,i){if(e.kind!=="leaf"||i.length!==2)return;const[r,n]=i;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(s=>s.kind==="flag"&&s.name===a)?.focusedHelp!==void 0?a:void 0}c(ge,"focusedHelpFlag");function we(e,i){let r=0;for(let n=0;n<e.length;n++){if(r===i.length)return e.slice(n);e[n]!=="--json"&&e[n]===i[r]&&r++}return[]}c(we,"rawArgsAfterPath");function ve(e,i){const r=le(e.bin,i,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new R("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,_.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=fe.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}c(ve,"runPassthrough");function be(e,i,r){const n=ue(e),a=n.length>0?n.join(", "):"(none)",l=i.length>0?`crtr ${i.join(" ")} -h`:"crtr -h",s=n.some(o=>o.startsWith("(and "));return new R("unknown_path",`unknown subcommand: ${r}`,_.USAGE,{received:r,next:s?`Valid children include: ${a}. Run \`${l}\` for how to find the rest.`:`Valid children: ${a}. Run \`${l}\` for the full list.`})}c(be,"unknownPathError");function xe(e){const i="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new R("not_joined",`\`crtr ${e}\` isn't a command here. ${i}`,_.USAGE,{received:e,next:i})}c(xe,"notJoinedError");async function ke(){if(se())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:i}=await import("../daemon/machine-link/config.js");return i()===void 0&&!e("user").runtime?.issuer}catch{return!1}}c(ke,"runtimeUnjoined");function m(e,i,r,n,a){return new R(e,i,_.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}c(m,"parseArgvError");function k(e){return e.replace(/-([a-z])/g,(i,r)=>r.toUpperCase())}c(k,"flagNameToKey");async function $e(e,i,r){const n={},a=new Set,l=new Map,s=e.filter(t=>t.kind==="positional"),o=e.find(t=>t.kind==="stdin"),$=e.find(t=>t.kind==="context-file"),v=e.filter(t=>t.kind==="flag"),S=new Map(v.map(t=>[t.name,t])),P=v.some(t=>t.sensitive===!0);for(const t of v)t.type==="bool"?n[k(t.name)]=t.default!==void 0?t.default:!1:t.default!==void 0&&(n[k(t.name)]=t.default);const w=[];let b=0,N=!1,u=0;for(;u<i.length;){const t=i[u];if(t==="--"&&!N){N=!0,u++;continue}if(!N&&t.startsWith("--")){const h=t.indexOf("=");let d,C;if(h!==-1?(d=t.slice(2,h),C=t.slice(h+1)):d=t.slice(2),d==="context-file"){if($===void 0)throw m("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const f=C!==void 0?C:i[++u];if(f===void 0)throw m("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let x;try{x=de(f,"utf8")}catch{throw m("invalid_type",`--context-file: cannot read file: ${f}`,f,"context-file","Provide a readable file path.")}let q;try{q=JSON.parse(x)}catch{throw m("invalid_type",`--context-file: file is not valid JSON: ${f}`,f,"context-file","Ensure the file contains a valid JSON object.")}const T=k($.name);n[T]=q,l.set(T,ce(f)),a.add(T),u++;continue}const A=S.has(d)||!d.startsWith("no-")?void 0:S.get(d.slice(3));if(A!==void 0&&A.type==="bool"){if(C!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${C}`,A.name,`Use --${d} (presence = false) with no value.`);const f=k(A.name);a.add(f),n[f]=!1,u++;continue}const E=S.get(d);if(E===void 0)throw m("unknown_flag",`unknown flag: --${d}`,`--${d}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const H=k(d);if(a.add(H),E.type==="bool"){if(C!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${C}`,d,`Use --${d} (presence = true) or --no-${d} (false), with no value.`);n[H]=!0,u++;continue}const y=C!==void 0?C:i[++u];if(y===void 0||C===void 0&&y.startsWith("--")){const f=E.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${d} -h\` and read the focused value contract before retrying.`:void 0;throw m("missing_parameter",`--${d} requires a value`,`--${d}`,d,f)}let j;if(E.type==="int"){const f=Number(y);if(!Number.isInteger(f))throw m("invalid_type",`--${d} must be an integer`,y,d,`Provide an integer value for --${d}.`);j=f}else if(E.type==="enum"){const f=E.choices;if(f!==void 0&&!f.includes(y))throw m("invalid_type",`--${d} must be one of: ${f.join(", ")}`,y,d,`Retry with one of: ${f.join(", ")}.`);j=y}else if(E.type==="json"){let f;try{f=JSON.parse(y)}catch{throw m("invalid_type",`--${d} is not valid JSON`,y,d,`Pass one JSON value for --${d}; run -h for its shape.`)}const x=E.shape===void 0?null:ie(E.shape,f,`--${d}`);if(x!==null)throw m("invalid_type",`${x.path} must be ${x.expected}, got ${x.receivedType}`,y,x.path,`Fix ${x.path}; run -h for the shape of --${d}.`);j=f}else j=y;if(E.repeatable===!0){const f=n[H],x=Array.isArray(f)?f:[];x.push(j),n[H]=x}else n[H]=j;u++;continue}const p=s[b];if(p!==void 0){const h=k(p.name);if(p.repeatable===!0){const d=n[h]??[];d.push(t),n[h]=d}else n[h]=t,b++;w.push(t),a.add(h),u++;continue}if(w.length>0){if(o!==void 0&&s.length===0){w.push(t),u++;continue}throw o!==void 0?m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):m("bad_invocation",P?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${t}`,P?void 0:i.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(s.length===0&&(o===void 0||o.allowPositional===!1))throw m("bad_invocation",P?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${t}`,P?void 0:t,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(t),u++}let g=!1;if(o!==void 0){if(w.length>1&&s.length===0){const t=o.positionalStdinConflict?.(n);throw t!==void 0?m("bad_invocation",t.message,void 0,t.field,t.next):m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&s.length===0&&o.allowPositional!==!1){const t=w[0];if(t==="-"){const p=await M();(p.trim()!==""||!o.required)&&(n[k(o.name)]=p),g=!0}else{if((await X()).trim()!==""){const h=o.positionalStdinConflict?.(n);throw m("bad_invocation",h?.message??`both a positional argument ("${t}") and piped stdin were provided for ${o.name}`,t,h?.field??o.name,h?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[k(o.name)]=t,g=!0}}else{const t=await M();t!==""&&(t.trim()!==""||!o.required)&&(n[k(o.name)]=t,g=!0)}}g&&o!==void 0&&a.add(k(o.name));for(const t of e){if(t.kind!=="flag"&&t.kind!=="positional"||t.defaultFromEnv===void 0)continue;const p=k(t.name);if(a.has(p))continue;const h=process.env[t.defaultFromEnv];h===void 0||h===""||(n[p]=t.kind==="positional"&&t.repeatable===!0?[h]:h,a.add(p))}const U=[];for(const t of e){const p=k(t.name),h=t.kind==="flag"&&t.type==="bool"&&!a.has(p);if(t.required&&(h||n[p]===void 0||n[p]===null)){const d=t.kind==="positional"?`positional ${t.name.toUpperCase()}`:t.kind==="flag"?`--${t.name}`:t.kind==="context-file"?"--context-file":"stdin";U.push({display:d,name:t.name})}}if(U.length>0){const t=U.map(d=>d.display).join(", "),p=r?.leafPath,h=p!==void 0&&p.length>0?`\`crtr ${p.join(" ")} -h\``:"this command with -h";throw m("missing_parameter",U.length===1?`required parameter is missing: ${t}`:`required parameters are missing: ${t}`,void 0,U.map(d=>d.name).join(", "),`Run ${h} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(l),n}c($e,"parseArgv");function ye(e){const i=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){i.push(...e.slice(n));break}const l=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&l===void 0){i.push(a);continue}const s=l??e[n+1];if(s===void 0||s===""||l===void 0&&s.startsWith("-"))throw m("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");l===void 0&&n++,r=s}return r===void 0?{rest:i}:{rest:i,machine:r}}c(ye,"takeMachineSelector");const Se=new Set(["--json","--no-autostart"]);async function Ie(e,i){const r=i.slice(2);r.includes("--json")&&ee(!0);const n=r.filter(o=>!Se.has(o));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const o=oe()?{...e.help,commands:await Promise.all(e.help.commands.map(async $=>{const v=e.subtrees.find(b=>b.name===$.name);if(v?.effectiveHelp===void 0)return $;const P=((await v.effectiveHelp()).listing??[]).filter(b=>b.tier!=="hidden"),w=J(P).map(b=>({path:`${v.name} ${b.name}`,desc:b.tier==="important"?b.description:void 0}));return{...$,subcommands:w.length?w:void 0,otherSubcommandCount:P.length-w.length}}))}:e.help;process.stdout.write(V(o)+`
|
|
6
6
|
`),process.exitCode=_.SUCCESS;return}if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){const{readPackageVersion:o}=await import("../commands/sys/shared.js");process.stdout.write(o()+`
|
|
7
|
-
`),process.exitCode=_.SUCCESS;return}let{node:a,path:l,remaining:s}=
|
|
8
|
-
`),process.exitCode=_.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await
|
|
9
|
-
`),process.exitCode=_.SUCCESS;return}const o=a;
|
|
10
|
-
`))}}catch(o){if(
|
|
7
|
+
`),process.exitCode=_.SUCCESS;return}let{node:a,path:l,remaining:s}=he(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&ve(a.passthrough,we(r,l)),a.kind==="branch"&&a.refusal!==void 0&&s[0]!=="-h"&&s[0]!=="--help")throw new R(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&s.length>0&&s[0]!=="-h"&&s[0]!=="--help")throw a.kind==="root"&&!s[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!s[0].startsWith("-")&&await ke()?xe(s[0]):be(a,l,s[0]);if(pe(s)){process.stdout.write(await z(a,l,ge(a,s))+`
|
|
8
|
+
`),process.exitCode=_.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await z(a,l)+`
|
|
9
|
+
`),process.exitCode=_.SUCCESS;return}const o=a;D(l.join(" "));const $=o.help.params!==void 0?o.help.params:[];let v=new Set,S=new Map,P=s,w;if(o.machineSelector===!0&&!$.some(g=>g.kind==="flag"&&g.name==="machine")){const g=ye(s);P=g.rest,w=g.machine}const b=await $e($,P,{leafPath:l,onProvidedParams:c(g=>{v=g},"onProvidedParams"),onContextFilePaths:c(g=>{S=g},"onContextFilePaths")}),N={providedParams:v,contextFilePaths:S,...w===void 0?{}:{machine:w}},u=await ae.fresh(()=>o.run(b,N));if(Q(u==null?u:o.preview?.(u)??u),u!=null)if(ne())Y(u);else{const g=o.render!==void 0?o.render(u):te(u,o.help);process.stdout.write(g+(o.stdoutExact?.(u)?"":`
|
|
10
|
+
`))}}catch(o){if(re(o))throw o;Z(o)}}c(Ie,"runCli");export{Se as GLOBAL_TOKENS,Je as collectSlashSpecs,Be as defineBranch,Ve as defineLeaf,Me as defineRoot,xe as notJoinedError,$e as parseArgv,me as renderNode,Ie as runCli,ye as takeMachineSelector,be as unknownPathError,he as walk};
|
|
@@ -16,7 +16,7 @@ export type Resolution = {
|
|
|
16
16
|
/** The owners a bare name is looked up under, in order: own node, repos nearest
|
|
17
17
|
* first (each checkout's own repo object first, then others oldest first), the profile's project repos, profile, app, you, your groups, then the apps whose tools the run may use (installed
|
|
18
18
|
* plugins) with `crtr` last. */
|
|
19
|
-
export declare function viewOf(db: CanvasDb, reader: Reader): Promise<ObjectRow[]>;
|
|
19
|
+
export declare function viewOf(db: CanvasDb, reader: Reader, ev?: EvalReader): Promise<ObjectRow[]>;
|
|
20
20
|
/** SQL true when the reader may read the candidate `alias`, live or deleted. A live object is `permits(read)`. A deleted object other than a node
|
|
21
21
|
* has lost its parent in the evaluator's `relation_source` (a reaped node keeps it, so its live documents stay readable), so a deleted one without a schema type is read through the facts on itself and on each owner up its
|
|
22
22
|
* chain (the authority it held before deletion), within the reader's ceiling. The "every app is visible" rule is not such a grant. A deleted
|
package/dist/core/graph/names.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var k=Object.defineProperty;var f=(o,t)=>k(o,"name",{value:t,configurable:!0});import{isSafeNodeId as B}from"../canvas/paths.js";import{OBJECT_TYPE as P}from"../permissions/builtin.js";import{ceilingFrag as J,readablePackageApps as V}from"../permissions/ceiling.js";import{compilePermission as X}from"../permissions/compile.js";import{ceilingOf as z,permits as G,
|
|
2
|
-
WHERE o.type = 'person' AND o.home_machine IS NULL AND regexp_replace(i.external_id, '^user:', '') = ?`).get(
|
|
1
|
+
var k=Object.defineProperty;var f=(o,t)=>k(o,"name",{value:t,configurable:!0});import{isSafeNodeId as B}from"../canvas/paths.js";import{OBJECT_TYPE as P}from"../permissions/builtin.js";import{ceilingFrag as J,readablePackageApps as V}from"../permissions/ceiling.js";import{compilePermission as X}from"../permissions/compile.js";import{ceilingOf as z,permits as G,resolveReader as y}from"../permissions/evaluator.js";import{and as K,or as Q,raw as x}from"../permissions/sql.js";import{flatMapAsync as Z}from"../async-array.js";async function C(o,t,s){const{userId:i,subjects:c}=s??await y(o,t),u=i===null?void 0:await o.prepare(`SELECT o.* FROM objects o JOIN identities i ON i.object = o.id AND i.scheme = 'user'
|
|
2
|
+
WHERE o.type = 'person' AND o.home_machine IS NULL AND regexp_replace(i.external_id, '^user:', '') = ?`).get(i),p=await V(o,t,i),m=await o.prepare(`SELECT a.* FROM objects a WHERE a.type = 'app' AND a.deleted_at IS NULL AND ${p===null?`EXISTS (
|
|
3
3
|
SELECT 1 FROM objects o JOIN documents d ON d.object = o.id
|
|
4
4
|
WHERE o.owner = a.id AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL)`:"a.id = ANY(?::text[])"}
|
|
5
|
-
ORDER BY a.name = 'crtr', a.name`).all(...
|
|
6
|
-
SELECT ${
|
|
5
|
+
ORDER BY a.name = 'crtr', a.name`).all(...p===null?[]:[p]),l=t.class==="node"?[t.node,...t.repos,...t.projectRepos,t.profile,t.app]:t.class==="app"?[t.app]:t.class==="object"?[t.owner,...t.repos,t.app]:[],w=c.groupIds.filter(r=>r.startsWith("group:")).map(r=>r.slice(6)),E=w.length===0?[]:await o.prepare("SELECT * FROM objects WHERE type = 'group' AND deleted_at IS NULL AND id = ANY(?::text[]) ORDER BY created_at, seq").all(w),n=new Set;return[...l,u,...E,...m].filter(r=>!!r&&!n.has(r.id)&&!!n.add(r.id))}f(C,"viewOf");async function D(o,t,s){const i=await G(o,t,"read",s),c=await z(o,t,"read"),u=X(t.defs,t.subjects,P,"read",x("gr.id")),p={sql:`EXISTS (WITH RECURSIVE up(id, depth) AS (
|
|
6
|
+
SELECT ${s}.id, 0
|
|
7
7
|
UNION ALL SELECT p.owner, up.depth + 1 FROM up JOIN objects p ON p.id = up.id WHERE p.owner IS NOT NULL AND up.depth < 12)
|
|
8
|
-
SELECT 1 FROM up gr WHERE ${u.sql})`,params:u.params},
|
|
9
|
-
AND o.deleted_at IS ${
|
|
10
|
-
OR (type IN ('person','app','repo','profile','group') AND (name = ? OR id = ?) AND home_machine IS NULL)`).all(t,t,t)}f(
|
|
11
|
-
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${
|
|
12
|
-
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${
|
|
13
|
-
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NOT NULL AND ${
|
|
8
|
+
SELECT 1 FROM up gr WHERE ${u.sql})`,params:u.params},m=K([x(`${s}.deleted_at IS NOT NULL AND ${s}.schema_type IS NULL`),...c===null?[]:[J(c,s)],p]);return Q([i,m])}f(D,"readableOrDeleted");async function le(o,t,s){const i=await D(o,t,"o");return(await o.prepareUncached(`SELECT ${i.sql} AS ok FROM objects o WHERE o.id = ?`).get(...i.params,s))?.ok===!0}f(le,"canReadOrDeleted");async function ee(o,t,s,i,c,u=!1){const p=await D(o,t,"o");return await o.prepareUncached(`SELECT o.* FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0) AND o.owner = ? AND o.name = ? AND o.home_machine IS ${u?"NOT NULL":"NULL"}
|
|
9
|
+
AND o.deleted_at IS ${c?"NOT NULL":"NULL"} AND ${p.sql}${c?" ORDER BY o.deleted_at DESC":""}`).all(s.id,i,...p.params)}f(ee,"namedObjects");const de=["person","app","repo","profile","group"],H=/^(person|app|repo|profile|group|node):([^/]+)\/(.+)$/,I=f(o=>o.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),"unwrapRef");function W(o){const t=H.exec(o);if(t)return{type:t[1],handle:t[2],rest:t[3]};const s=o.indexOf("/");return s>0?{handle:o.slice(0,s),rest:o.slice(s+1)}:null}f(W,"splitOwnerRef");async function v(o,t,s){return s==="node"?await o.prepare("SELECT * FROM objects WHERE type = 'node' AND id = ?").all(t):s?await o.prepare("SELECT * FROM objects WHERE type = ? AND (name = ? OR id = ?) AND home_machine IS NULL").all(s,t,t):await o.prepare(`SELECT * FROM objects WHERE (type = 'node' AND id = ?)
|
|
10
|
+
OR (type IN ('person','app','repo','profile','group') AND (name = ? OR id = ?) AND home_machine IS NULL)`).all(t,t,t)}f(v,"ownersByHandle");const F=/^([^:/]+):reports\/(.+?)(?:\.md)?$/;async function fe(o,t,s){const i=[...new Set(s.filter(n=>I(n)===n&&!F.test(n)))],c=new Map;if(i.length===0||t.view.length===0)return c;const u=new Set((await o.prepare("SELECT id FROM objects WHERE id = ANY(?::text[])").all(i)).map(n=>n.id)),p=i.filter(n=>!u.has(n));for(const n of p)c.set(n,null);const m=await D(o,t.ev,"o"),l=await o.prepareUncached(`SELECT o.id, o.owner, o.name FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0)
|
|
11
|
+
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${m.sql}`).all(t.view.map(n=>n.id),p,...m.params),w=new Map(t.view.map((n,r)=>[n.id,r])),E=new Map;for(const n of l){const r=w.get(n.owner);r<(E.get(n.name)??1/0)&&(E.set(n.name,r),c.set(n.name,n.id))}return c}f(fe,"viewResolutions");async function me(o,t,s,i){return(await te(o,t,[s],i)).get(s)}f(me,"resolveName");async function te(o,t,s,i){const c=[...s];if(c.length===0)return new Map;const u=i?.ev??await y(o,t),p=i?.view??await C(o,t,u),m=new Map;for(const n of c){let r=I(n);const R=F.exec(r);R&&!H.test(r)&&(r=`${R[1]}/reports/${R[2]}`),m.set(n,r)}const l=new Map,w=[...new Set(m.values())];if(w.length>0){const n=await D(o,u,"o"),r=await o.prepareUncached(`SELECT o.*, ${n.sql} AS readable_ok FROM objects o WHERE o.id = ANY(?::text[])`).all(...n.params,w);for(const{readable_ok:e,...a}of r)e===!0&&l.set(a.id,a.deleted_at?{deleted:a}:{object:a});const R=f(async(e,a)=>{if(e.length===0||a.length===0)return new Map;const d=await o.prepareUncached(`SELECT o.* FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0)
|
|
12
|
+
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${n.sql}`).all(e,a,...n.params);return new Map(d.map(N=>[`${N.owner}\0${N.name}`,N]))},"live"),T=w.filter(e=>!l.has(e)),M=await R(p.map(e=>e.id),T);for(const e of T){const a=p.find(d=>M.has(`${d.id}\0${e}`));a&&l.set(e,{object:M.get(`${a.id}\0${e}`)})}const S=w.filter(e=>!l.has(e)).flatMap(e=>{const a=W(e);return a?[{name:e,...a}]:[]}),A=new Map;for(const e of S){const a=`${e.type??""}\0${e.handle}`;A.has(a)||A.set(a,await v(o,e.handle,e.type))}const Y=await R([...new Set([...A.values()].flat().map(e=>e.id))],[...new Set(S.map(e=>e.rest))]),$=f(e=>{const a=p.findIndex(d=>d.id===e.id);return a<0?1/0:a},"rank");for(const e of S){const a=A.get(`${e.type??""}\0${e.handle}`),d=f(h=>Y.get(`${h.id}\0${e.rest}`),"hitOf"),N=a.filter(h=>$(h)<1/0).sort((h,g)=>$(h)-$(g)).find(h=>d(h)!==void 0),L=a.flatMap(h=>{const g=d(h);return g?[g]:[]});N?l.set(e.name,{object:d(N)}):L.length===1?l.set(e.name,{object:L[0]}):L.length>1&&l.set(e.name,{ambiguous:L})}const b=new Set(S.map(e=>e.name)),U=w.filter(e=>!l.has(e)),_=[...new Set([...p.map(e=>e.id),...[...A.values()].flat().map(e=>e.id)])],j=[...new Set(U.map(e=>b.has(e)?S.find(a=>a.name===e).rest:e))],q=_.length===0||j.length===0?[]:await o.prepareUncached(`SELECT o.* FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0)
|
|
13
|
+
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NOT NULL AND ${n.sql} ORDER BY o.deleted_at DESC`).all(_,j,...n.params),O=new Map;for(const e of q)O.has(`${e.owner}\0${e.name}`)||O.set(`${e.owner}\0${e.name}`,e);for(const e of U){const a=S.find(d=>d.name===e);if(a){const d=A.get(`${a.type??""}\0${a.handle}`),N=d.map(L=>O.get(`${L.id}\0${a.rest}`)).find(L=>L!==void 0);N?l.set(e,{deleted:N}):a.type===void 0&&d.length===0&&B(a.handle)&&l.set(e,{remote:e})}else{const d=p.find(N=>O.has(`${N.id}\0${e}`));d&&l.set(e,{deleted:O.get(`${d.id}\0${e}`)})}}}const E=new Map;for(const[n,r]of m)E.set(n,l.get(r)??{missing:!0});return E}f(te,"resolveNames");async function ue(o,t,s){const i=I(s),c=await y(o,t),u=f(async(l,w)=>await Z(l,async E=>await ee(o,c,E,w,!1,!0)),"found"),p=await u(await C(o,t,c),i);if(p.length)return p;const m=W(i);return m?await u(await v(o,m.handle,m.type),m.rest):[]}f(ue,"stubsNamed");export{de as HANDLE_TYPES,le as canReadOrDeleted,v as ownersByHandle,D as readableOrDeleted,me as resolveName,te as resolveNames,ue as stubsNamed,I as unwrapRef,C as viewOf,fe as viewResolutions};
|
package/dist/core/help.js
CHANGED
|
@@ -4,6 +4,6 @@ ${t}
|
|
|
4
4
|
act on directly \u2014 read it as a continuation of your prompt, don't parse it as data.
|
|
5
5
|
Exit 0 on success, non-zero on failure. Schemas appear at leaf -h; a leaf may route an uncommon flag to focused --flag -h guidance.`,j="Before running a crtr command that changes state \u2014 creates, mutates, or deletes anything \u2014 whose exact contract (args, flags, effects) you haven't verified this session, run `-h` on it and read the schema first \u2014 a reliable read beats a guess that wastes a turn or triggers an unintended effect. When a leaf routes a flag to focused help, read that focused help before using the flag; the compact row is discovery, not its invocation contract. Same when the user names a capability you don't fully recognize: `-h` it before acting.";function C(e){const n=e.subcommands??[],t=e.otherSubcommandCount??0;if(n.length===0&&t===0)return[];const o=[];if(n.length>0){const r=$(n.map(a=>a.path));for(const a of n)o.push(a.desc!==void 0&&a.desc!==""?` ${g(a.path,r)} ${a.desc}`:` ${a.path}`)}if(t>0){const r=n.length>0?"other subcommand":"subcommand";o.push(` [+${t} ${r}${t===1?"":"s"} \u2014 \`crtr ${e.name} -h\`]`)}return o}u(C,"rootSubcommandLines");function R(e){const n=[];n.push(`${e.tagline}`),n.push("");for(const t of e.commands){n.push(`<command name="${t.name}">`),n.push(t.concept),n.push(`use when ${t.useWhen}`);for(const r of C(t))n.push(r);const o=h(t.dynamicState);o!==null&&n.push(o),n.push("</command>"),n.push("")}if(e.globals.length>0){n.push("Globals");const t=$(e.globals.map(o=>o.name));for(const o of e.globals)n.push(` ${g(o.name,t)} ${o.desc}`);n.push("")}return n.push(I),n.push(""),n.push(j),n.join(`
|
|
6
6
|
`)}u(R,"renderRoot");function d(e){return e.replace(/"/g,"'")}u(d,"attr");const v=40;function O(e){if(e.length<=v)return{listed:[...e],unlisted:0};const n=e.filter(t=>t.tier==="common"||t.tier==="important");return n.length===0?{listed:[...e],unlisted:0}:{listed:n,unlisted:e.length-n.length}}u(O,"collapseWideChildren");function D(e){const n=e.length>v;return e.filter(t=>(t.tier==="common"||t.tier==="important")&&(!n||t.kind==="leaf"))}u(D,"rootPromotedChildren");function P(e){const n=[];n.push(`<command name="${e.name}" description="${d(e.summary)}">`);const t=h(e.dynamicState);t!==null&&n.push(t),e.model!==void 0&&n.push(e.model);const{listed:o,unlisted:r}=O((e.listing??[]).filter(a=>a.tier!=="hidden"));for(const a of o){const s=a.plugin===void 0?"":` plugin="${d(a.plugin)}"`,i=a.subCount!==void 0&&a.subCount>0?` subcommands="${a.subCount}"`:"";n.length>1&&n.push(""),n.push(`<subcommand name="${a.name}" description="${d(a.description)}" whenToUse="${d(a.whenToUse)}"${s}${i}/>`)}return r>0&&(n.push(""),n.push(`<unlisted-subcommands count="${r}">${r} more subcommands are not listed here. Each one runs by name, and \`crtr ${e.name} <name> -h\` prints its help.</unlisted-subcommands>`)),e.extensionIssue!==void 0&&n.push(`<extension-issue fragment="${d(e.extensionIssue.fragment)}">This repository's contributed commands were rejected: ${e.extensionIssue.message}. Run \`crtr sys doctor\` for the full report.</extension-issue>`),n.push("</command>"),n.join(`
|
|
7
|
-
`)}u(P,"renderBranch");function T(e){if(e.kind==="positional")return`${e.name.toUpperCase()}${e.repeatable===!0?"...":""}`;if(e.kind==="stdin")return"stdin";if(e.kind==="context-file")return"--context-file PATH";const n=e;return n.type==="bool"?`--${n.name}`:`--${n.name} ${n.name.toUpperCase().replace(/-/g,"_")}`}u(T,"paramLabel");function w(e){return e===void 0?"":e==="base64"?" Local file path: the file is read and its raw bytes are base64-encoded into the request; the path itself is never sent.":" Local file path: the file is read as UTF-8 text and its content is sent as the value; the path itself is never sent."}u(w,"fileEncodingNote");function S(e){return e===void 0?"":` Defaults to $${e} when that is set and non-empty in the environment, and counts as supplied.`}u(S,"envDefaultNote");function k(e){return e==="file"?" A file: pass its path.":""}u(k,"fileParamNote");function H(e,n){return e.focusedHelp===void 0?"":` Before using this flag, run \`crtr ${n} --${e.name} -h\` and read its focused guidance.`}u(H,"focusedFlagHelpNote");function L(e,n){const t=e.required?"required":"optional";if(e.kind==="positional"){const c=e.repeatable===!0?" Repeatable \u2014 pass multiple values to accumulate in argv order.":"";return`positional, ${t}.${k(e.type)}${w(e.encoding)}${S(e.defaultFromEnv)} ${e.constraint}${c}`}if(e.kind==="stdin")return`${t}. ${e.constraint}`;if(e.kind==="context-file"){const c=e.shape!==void 0?` Shape: ${e.shape}`:"";return`${t}. Path to a JSON file.${c} ${e.constraint}`.trim()}const o=e,r=H(o,n);if(o.type==="bool")return`${t} boolean. Presence means true. ${o.constraint}${r}`.trim();const a=o.default!==void 0?` Default: ${String(o.default)}.`:"",s=o.type==="enum"&&o.choices!==void 0?` One of: ${o.choices.join(", ")}.`:"",i=o.repeatable===!0?" Repeatable \u2014 pass multiple times to accumulate.":"";return o.type==="json"?`json, ${t}. One JSON value: ${f(o.shape??{type:"unknown",constraint:""})}. ${o.constraint}${r}`.trim():`${o.type}, ${t}.${s}${a}${k(o.type)}${w(o.encoding)}${S(o.defaultFromEnv)} ${o.constraint}${i}${r}`.trim()}u(L,"paramDesc");function f(e){const n=/\|\s*null\s*$/i.test(e.type),t=y(e.type);return t==="union"&&e.variants!==void 0?`${e.variants.map(f).join(" | ")}${n?" | null":""}`:t==="map"&&e.items!==void 0?`{ [key: string]: ${f(e.items)} }${n?" | null":""}`:e.items===void 0?e.type:`array of ${f(e.items)}${n?", or null":""}`}u(f,"outputTypePhrase");function l(e){return e.values!==void 0?` One of: ${e.values.join(", ")}.`:""}u(l,"outputValuesNote");function b(e,n,t){const o=$(e.map(r=>r.name));for(const r of e){const a=r.constraint.length>0?` ${r.constraint}`:"";t.push(`${n}${g(r.name,o)} ${f(r)}.${l(r)}${a}`),
|
|
8
|
-
`)}if(e.guide!==void 0&&(t.push(""),t.push(e.guide)),t.push(""),o.length>0){t.push("Input");const s=o.map(T),i=$(s);for(let c=0;c<o.length;c++){t.push(` ${g(s[c],i)} ${L(o[c],e.name)}`);const
|
|
7
|
+
`)}u(P,"renderBranch");function T(e){if(e.kind==="positional")return`${e.name.toUpperCase()}${e.repeatable===!0?"...":""}`;if(e.kind==="stdin")return"stdin";if(e.kind==="context-file")return"--context-file PATH";const n=e;return n.type==="bool"?`--${n.name}`:`--${n.name} ${n.name.toUpperCase().replace(/-/g,"_")}`}u(T,"paramLabel");function w(e){return e===void 0?"":e==="base64"?" Local file path: the file is read and its raw bytes are base64-encoded into the request; the path itself is never sent.":" Local file path: the file is read as UTF-8 text and its content is sent as the value; the path itself is never sent."}u(w,"fileEncodingNote");function S(e){return e===void 0?"":` Defaults to $${e} when that is set and non-empty in the environment, and counts as supplied.`}u(S,"envDefaultNote");function k(e){return e==="file"?" A file: pass its path.":""}u(k,"fileParamNote");function H(e,n){return e.focusedHelp===void 0?"":` Before using this flag, run \`crtr ${n} --${e.name} -h\` and read its focused guidance.`}u(H,"focusedFlagHelpNote");function L(e,n){const t=e.required?"required":"optional";if(e.kind==="positional"){const c=e.repeatable===!0?" Repeatable \u2014 pass multiple values to accumulate in argv order.":"";return`positional, ${t}.${k(e.type)}${w(e.encoding)}${S(e.defaultFromEnv)} ${e.constraint}${c}`}if(e.kind==="stdin")return`${t}. ${e.constraint}`;if(e.kind==="context-file"){const c=e.shape!==void 0?` Shape: ${e.shape}`:"";return`${t}. Path to a JSON file.${c} ${e.constraint}`.trim()}const o=e,r=H(o,n);if(o.type==="bool")return`${t} boolean. Presence means true; \`--no-${o.name}\` means false. ${o.constraint}${r}`.trim();const a=o.default!==void 0?` Default: ${String(o.default)}.`:"",s=o.type==="enum"&&o.choices!==void 0?` One of: ${o.choices.join(", ")}.`:"",i=o.repeatable===!0?" Repeatable \u2014 pass multiple times to accumulate.":"";return o.type==="json"?`json, ${t}. One JSON value: ${f(o.shape??{type:"unknown",constraint:""})}. ${o.constraint}${r}`.trim():`${o.type}, ${t}.${s}${a}${k(o.type)}${w(o.encoding)}${S(o.defaultFromEnv)} ${o.constraint}${i}${r}`.trim()}u(L,"paramDesc");function f(e){const n=/\|\s*null\s*$/i.test(e.type),t=y(e.type);return t==="union"&&e.variants!==void 0?`${e.variants.map(f).join(" | ")}${n?" | null":""}`:t==="map"&&e.items!==void 0?`{ [key: string]: ${f(e.items)} }${n?" | null":""}`:e.items===void 0?e.type:`array of ${f(e.items)}${n?", or null":""}`}u(f,"outputTypePhrase");function l(e){return e.values!==void 0?` One of: ${e.values.join(", ")}.`:""}u(l,"outputValuesNote");function b(e,n,t){const o=$(e.map(r=>r.name));for(const r of e){const a=r.constraint.length>0?` ${r.constraint}`:"";t.push(`${n}${g(r.name,o)} ${f(r)}.${l(r)}${a}`),m(r,`${n} `,t)}}u(b,"renderOutputFields");function x(e,n,t){const o=e.extra;o!==void 0&&(t.push(`${n}other members: ${f(o)}.${l(o)}${o.constraint.length>0?` ${o.constraint}`:""}`),m(o,`${n} `,t))}u(x,"renderExtraRow");function m(e,n,t){e.children!==void 0&&e.children.length>0&&b(e.children,n,t),x(e,n,t);for(const a of e.variants??[]){const s=l(a);t.push(`${n}variant: ${f(a)}.${s}${a.constraint.length>0?` ${a.constraint}`:""}`),m(a,`${n} `,t)}let o=e.items,r=y(e.type)==="map"?"each value":"each element";for(;o!==void 0;){const a=l(o);(o.constraint.length>0||a.length>0)&&t.push(`${n}${r}: ${f(o)}.${a}${o.constraint.length>0?` ${o.constraint}`:""}`);for(const s of o.variants??[])t.push(`${n}variant: ${f(s)}.${l(s)}${s.constraint.length>0?` ${s.constraint}`:""}`),m(s,`${n} `,t);if(o.children!==void 0&&o.children.length>0){b(o.children,n,t),x(o,n,t);return}if(o.extra!==void 0){x(o,n,t);return}r=y(o.type)==="map"?"each value":"each element",o=o.items}}u(m,"renderOutputShapeBody");function U(e,n){const t=[`${e.name}: ${e.summary}.`],o=(e.params??[]).filter(s=>!(s.kind==="flag"&&s.hidden===!0)),r=n===void 0?void 0:o.find(s=>s.kind==="flag"&&s.name===n&&s.focusedHelp!==void 0);if(r?.focusedHelp!==void 0){const s=r.focusedHelp;if(t.push(""),t.push(`<parameter name="${r.name}">`),t.push("When to use"),t.push(` ${s.whenToUse}`),t.push(""),t.push("Value"),t.push(` ${s.value}`),(s.effects??[]).length>0){t.push(""),t.push("Effects");for(const c of s.effects??[])t.push(` ${c}`)}const i=h(s.dynamicState);return i!==null&&(t.push(""),t.push(i)),t.push("</parameter>"),t.join(`
|
|
8
|
+
`)}if(e.guide!==void 0&&(t.push(""),t.push(e.guide)),t.push(""),o.length>0){t.push("Input");const s=o.map(T),i=$(s);for(let c=0;c<o.length;c++){t.push(` ${g(s[c],i)} ${L(o[c],e.name)}`);const p=o[c];p.kind==="flag"&&p.type==="json"&&p.shape!==void 0&&m(p.shape,` ${" ".repeat(i)} `,t)}}else t.push(e.inputNote!==void 0?e.inputNote:"No input parameters.");t.push(""),t.push("Output (fields carried in the rendered result)"),b(e.output," ",t),t.push(""),t.push("Effects");for(const s of e.effects)t.push(` ${s}`);const a=h(e.dynamicState);return a!==null&&(t.push(""),t.push(a)),t.join(`
|
|
9
9
|
`)}u(U,"renderLeafArgv");export{v as WIDE_BRANCH_LISTING_LIMIT,O as collapseWideChildren,P as renderBranch,U as renderLeafArgv,R as renderRoot,D as rootPromotedChildren,B as stateBlock,A as withAsyncHelpState};
|
|
@@ -44,7 +44,7 @@ export declare function holdsProviderGroup(scopes: readonly string[], appExt: st
|
|
|
44
44
|
/** The published package apps whose shipped documents `reader` may read (the read rule); null for a person reader, who reads every package. `user` is the
|
|
45
45
|
* bare user id the reader acts for, null for a reader that acts for no person. A revoked grant (null scopes) holds no provider scope. */
|
|
46
46
|
export declare function readablePackageApps(db: CanvasDb, reader: Reader, user: string | null): Promise<string[] | null>;
|
|
47
|
-
/** The ceiling of `reader` for `access`; null for a person reader (no ceiling). `user` is the bare user id the reader acts for (`
|
|
47
|
+
/** The ceiling of `reader` for `access`; null for a person reader (no ceiling). `user` is the bare user id the reader acts for (`resolveReader`), null for a
|
|
48
48
|
* reader that acts for no person: it reads the package apps every reader reads and the providers its scopes hold, never a plugin. */
|
|
49
49
|
export declare function resolveCeiling(db: CanvasDb, reader: Reader, user: string | null, access: Access, options?: CeilingOptions): Promise<Ceiling | null>;
|
|
50
50
|
export interface RunPlace {
|
|
@@ -2,24 +2,22 @@ import type { CanvasDb } from '../canvas/db.js';
|
|
|
2
2
|
import type { Reader } from '../graph/types.js';
|
|
3
3
|
import { type Access, type Ceiling, type CeilingOptions } from './ceiling.js';
|
|
4
4
|
import { type SubjectSet } from './compile.js';
|
|
5
|
+
import type { Definition } from './schema-parser.js';
|
|
5
6
|
import { type Frag } from './sql.js';
|
|
6
7
|
export type Permission = 'read' | 'edit' | 'message' | 'use' | 'share';
|
|
7
8
|
export declare const PERMISSIONS: readonly Permission[];
|
|
8
|
-
/** A reader with its user and
|
|
9
|
-
* that acts for no person (see `readerUser`): its subjects are `*` alone. */
|
|
9
|
+
/** A reader with its user, subjects and schema definitions resolved, for many `permits`/`check` calls. `userId` null: acts for no person, subjects `*` alone. */
|
|
10
10
|
export interface EvalReader {
|
|
11
11
|
reader: Reader;
|
|
12
12
|
userId: string | null;
|
|
13
13
|
subjects: SubjectSet;
|
|
14
|
+
defs: Map<string, Definition>;
|
|
14
15
|
}
|
|
15
16
|
/** The user a reader acts for: a person's own identity; an app call's `sub`; a node's `sub`; otherwise the install's person. */
|
|
16
17
|
export declare function userOf(db: CanvasDb, reader: Reader): Promise<string>;
|
|
17
|
-
/** The user a reader reads as: `userOf`, except that on a cloud role an app reader with no `sub` (a runtime-owned call, such as
|
|
18
|
-
* package link derivation at boot) acts for no person and answers null. `userOf` itself keeps throwing there, so no write path
|
|
19
|
-
* records an object as kept for a person that is not there. */
|
|
20
|
-
export declare function readerUser(db: CanvasDb, reader: Reader): Promise<string | null>;
|
|
21
18
|
/** The user ids a subject stands for (the user and `*`) and every group it reaches, directly or through nested groups. */
|
|
22
19
|
export declare function subjectSet(db: CanvasDb, userId: string): Promise<SubjectSet>;
|
|
20
|
+
export declare const shareReads: <R extends Reader>(reader: R) => R;
|
|
23
21
|
export declare function resolveReader(db: CanvasDb, reader: Reader): Promise<EvalReader>;
|
|
24
22
|
/** SQL true when `reader` holds `permission` on the object `alias` (a row of `objects` in the caller's SELECT): schema within the ceiling.
|
|
25
23
|
* Bare `?` placeholders in textual order: embed `sql` and append `params` at the same position in the caller's parameter list. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var c=(t,e)=>O(t,"name",{value:e,configurable:!0});import{isCloudRole as T,personIdAsync as m}from"../canvas/person.js";import{OBJECT_TYPE as C,GROUP_TYPE as w}from"./builtin.js";import{ceilingFrag as L,resolveCeiling as x}from"./ceiling.js";import{compilePermission as N}from"./compile.js";import{PermissionError as H}from"./errors.js";import{loadDefinitions as A}from"./schemas.js";import{TRUE as W,and as M,f as d,or as k,raw as u}from"./sql.js";const D=["read","edit","message","use","share"],U={read:"read",use:"read",edit:"write",share:"write",message:"message"},p=c(t=>t.replace(/^user:/,""),"bareUser");async function F(t,e){if(e.class==="person"){const r=await t.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(e.person.id);return p(r?.external_id??await m())}if(e.class==="app")return p(e.sub??await m());if(e.class==="object"&&e.sub!==void 0)return p(e.sub);const s=e.class==="node"?e.node.id:e.object.id,n=await t.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(s);return p(n?.sub??await m())}c(F,"userOf");async function I(t,e){const s=[e,"*"],n=await t.prepareUncached(`WITH RECURSIVE g(id) AS (
|
|
2
2
|
SELECT resource_id FROM relations WHERE resource_type = ? AND relation = 'member' AND subject_type = 'user' AND subject_id = ANY(?::text[])
|
|
3
3
|
UNION
|
|
4
4
|
SELECT r.resource_id FROM relations r JOIN g ON r.subject_type = ? AND r.subject_id = g.id AND r.subject_relation = 'member'
|
|
5
5
|
WHERE r.resource_type = ? AND r.relation = 'member')
|
|
6
|
-
SELECT id FROM g`).all(
|
|
6
|
+
SELECT id FROM g`).all(w,s,w,w);return{userIds:s,groupIds:n.map(r=>r.id)}}c(I,"subjectSet");const l=new WeakMap,te=c(t=>(l.has(t)||l.set(t,null),t),"shareReads");function P(t,e){const s=l.get(e);if(s)return s;const n=(async()=>{const r=e.class==="app"&&e.sub===void 0&&T()?null:await F(t,e);return{reader:e,userId:r,subjects:r===null?{userIds:["*"],groupIds:[]}:await I(t,r),defs:await A(t)}})();return s===null&&(l.set(e,n),n.catch(()=>l.set(e,null))),n}c(P,"resolveReader");const q=c(t=>"subjects"in t,"isEval");async function v(t,e,s,n="o",r={}){if(!D.includes(s))throw new H(400,"unknown_permission",`unknown permission ${s}`);const o=q(e)?e:await P(t,e),{defs:a}=o,f=u(`${n}.id`),S=N(a,o.subjects,C,s,f),g=s==="read"?k([S,u(`${n}.type = 'app'`)]):S,h=o.reader.class==="person"?null:o.reader.app.id,y=o.reader.class==="app"&&o.reader.place===void 0&&h!==null?await Y(t,h):new Set,E=[];for(const[i,j]of a){if(i.startsWith("crtr/")||i==="user"||i==="app"||!(s in j.permissions)&&!(s in j.relations))continue;const $=i.split("/")[0];E.push(d`WHEN ${u(n)}.schema_type = ${i} THEN ${y.has($)?W:N(a,o.subjects,i,s,f)}`)}const R=E.length===0?d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${g} ELSE FALSE END)`:d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${g} ${{sql:E.map(i=>i.sql).join(" "),params:E.flatMap(i=>i.params)}} ELSE FALSE END)`,b=await J(t,o,U[s],r);return b===null?R:M([L(b,n),R])}c(v,"permits");const _=new WeakMap;function J(t,e,s,n={}){let r=_.get(e.reader);r===void 0&&_.set(e.reader,r=new Map);const o=`${s} ${n.verb??""} ${e.userId} ${e.subjects.groupIds.join(",")}`;let a=r.get(o);return a===void 0&&(a=x(t,e.reader,e.userId,s,n),r.set(o,a),a.catch(()=>r.delete(o))),a}c(J,"ceilingOf");async function Y(t,e){const s=await t.prepare("SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?").all(e);return new Set(s.map(n=>n.namespace))}c(Y,"ownNamespaceTypes");async function se(t,e,s,n,r={}){const o=await v(t,e,s,"o",r);return(await t.prepareUncached(`SELECT ${o.sql} AS ok FROM objects o WHERE o.id = ?`).get(...o.params,n))?.ok===!0}c(se,"check");async function ne(t,e,s,n){const r=await I(t,p(e)),o=await A(t),a=N(o,r,n.type,s,d`${n.id}::text`);return(await t.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}c(ne,"checkUser");export{D as PERMISSIONS,J as ceilingOf,se as check,ne as checkUser,v as permits,P as resolveReader,te as shareReads,I as subjectSet,F as userOf};
|