@north-light/cli 0.3.788 → 0.3.790
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 +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/command-manifest/index.d.ts +1 -0
- package/dist/api/command-manifest/index.js +1 -1
- package/dist/api/command-manifest/memory-extensions.d.ts +34 -0
- package/dist/api/command-manifest/memory-extensions.js +1 -0
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/crouter-plugin/bundles-and-memory.md +16 -1
- package/dist/builtin-memory/internal/INDEX.md +1 -1
- package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
- package/dist/clients/attach/viewer.js +255 -255
- package/dist/commands/canvas-history/shared.js +1 -1
- package/dist/commands/node/create.js +2 -2
- package/dist/commands/person-settings.js +1 -1
- package/dist/commands/profile/daemon-profiles.js +4 -4
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/history.d.ts +2 -8
- package/dist/core/canvas/history.js +9 -9
- package/dist/core/canvas/node-tokens.js +3 -3
- package/dist/core/canvas/person-state.d.ts +5 -7
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +3 -30
- package/dist/core/canvas/person.js +1 -11
- package/dist/core/config.d.ts +4 -1
- package/dist/core/config.js +1 -1
- package/dist/core/directory/join.d.ts +4 -6
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/graph/documents.d.ts +1 -1
- package/dist/core/graph/kinds/document.js +1 -1
- package/dist/core/human/requests.d.ts +11 -1
- package/dist/core/human/requests.js +22 -22
- package/dist/core/plugin-extensions.d.ts +3 -6
- package/dist/core/plugin-extensions.js +1 -1
- package/dist/core/review/store.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/launch-config-worker.js +1 -1
- package/dist/core/runtime/launch-target.d.ts +6 -4
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/launch.d.ts +5 -1
- package/dist/core/runtime/launch.js +2 -2
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +1 -1
- package/dist/core/runtime/runner/delete-sandboxes.js +5 -5
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/spawn-env-rows.js +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/environment-owner.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/human/sweep.js +1 -1
- package/dist/daemon/peer/ingress.d.ts +2 -2
- package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
- package/dist/daemon/runs/observer.js +6 -5
- package/dist/types.d.ts +2 -28
- package/docs/plugin/bundles-and-memory.md +15 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/command-manifest/index.js +1 -0
- package/packages/crouter-api/dist/api/command-manifest/memory-extensions.js +91 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
- package/packages/crouter-api/dist/core/config.js +10 -0
- package/packages/crouter-api/dist/core/directory/join.js +11 -45
- package/packages/crouter-api/dist/core/plugin-extensions.js +2 -86
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/bundle.js +1 -0
- package/packages/crouter-plugin/dist/define.js +10 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/join.d.ts +0 -3
- package/dist/commands/sys/join.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var
|
|
1
|
+
var g=Object.defineProperty;var a=(n,e)=>g(n,"name",{value:e,configurable:!0});import{usage as t}from"../../core/errors.js";import{envNodeId as w}from"../../shared/env.js";const u=["transcript","inbox"],f=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],p=["user","assistant","toolResult"],y=["advisor","developer","spec","design","review","explore","plan","general"],v=["active","idle","done","dead","canceled"],h={s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,mo:2592e6,y:31536e6};function m(n,e){const r=e.match(/^(\d+)(mo|[smhdwy])$/);if(r!==null)return Date.now()-Number(r[1])*h[r[2]];const i=Date.parse(e);if(!Number.isNaN(i))return i;throw t(`--${n} must be ISO 8601 (2026-06-01) or relative (7d, 2w, 1mo); received: ${e}`)}a(m,"parseWhen");function d(n){if(!(n===void 0||n===""))return n.split(",").map(e=>e.trim()).filter(e=>e!=="")}a(d,"splitCsv");const _=[{kind:"flag",name:"cwd",type:"path",required:!1,constraint:"Search another project's record. Default: the calling node's cwd (process cwd when not a node). Mutually exclusive with --all-cwds."},{kind:"flag",name:"all-cwds",type:"bool",required:!1,constraint:"Search every cwd on the canvas. Mutually exclusive with --cwd."},{kind:"flag",name:"under",type:"string",required:!1,constraint:"Restrict to a node and its subscription descendants (one initiative / sub-DAG)."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Restrict to specific node ids. Comma-separated for several."},{kind:"flag",name:"type",type:"string",required:!1,constraint:`Corpus to search; comma-separated for both. One of: ${u.join(", ")}. inbox = every delivery a node received, with un-clipped message bodies; transcript = the conversation itself, message by message. Default: inbox.`},{kind:"flag",name:"kind",type:"string",required:!1,constraint:`Node kind; comma-separated for several. One of: ${y.join(", ")}.`},{kind:"flag",name:"status",type:"string",required:!1,constraint:`Node lifecycle status; comma-separated for several. One of: ${v.join(", ")} (e.g. done = completed work only).`},{kind:"flag",name:"since",type:"string",required:!1,constraint:"Lower bound on artifact timestamp. ISO 8601 (2026-06-01) or relative (7d, 2w, 1mo)."},{kind:"flag",name:"until",type:"string",required:!1,constraint:"Upper bound on artifact timestamp. ISO 8601 or relative."},{kind:"flag",name:"origin",type:"string",required:!1,constraint:`What drove a message to arrive; comma-separated for several. One of: ${f.join(", ")}. Applies to transcript + inbox artifacts, which are the only ones that arrive \u2014 passing it therefore excludes every generated turn on its own. \`unknown\` is a message carrying no stamp, and is its own bucket rather than a fallback.`},{kind:"flag",name:"role",type:"string",required:!1,constraint:`Transcript message role; comma-separated for several. One of: ${p.join(", ")}.`},{kind:"flag",name:"from",type:"string",required:!1,constraint:"Case-insensitive substring against sender attribution \u2014 the node that sent a delivery. Applies to transcript + inbox artifacts."}];function $(n){const e=n.cwd,r=n.allCwds===!0;if(e!==void 0&&r)throw t("--cwd and --all-cwds are mutually exclusive.");const i=d(n.type);if(i!==void 0){const s=i.find(o=>!u.includes(o));if(s!==void 0)throw t(`--type must be one of: ${u.join(", ")}; received: ${s}`)}const c=d(n.origin);if(c!==void 0){const s=c.find(o=>!f.includes(o));if(s!==void 0)throw t(`--origin must be one of: ${f.join(", ")}; received: ${s}`)}const l=d(n.role);if(l!==void 0){const s=l.find(o=>!p.includes(o));if(s!==void 0)throw t(`--role must be one of: ${p.join(", ")}; received: ${s}`)}if(i!==void 0&&i.includes("transcript")&&!(n.node!==void 0||n.under!==void 0||n.since!==void 0))throw t("--type transcript needs a narrowing flag: pass --node, --under, or --since.",{next:"Transcripts are the full conversation corpus \u2014 scanning every node in a cwd reads every session file. Narrow first."});return{cwd:e,allCwds:r,under:n.under,nodes:d(n.node),types:i,kinds:d(n.kind),statuses:d(n.status),sinceMs:n.since!==void 0?m("since",n.since):void 0,untilMs:n.until!==void 0?m("until",n.until):void 0,origins:c,roles:l,from:n.from}}a($,"parseFilters");function S(n,e){const r=e.allCwds||e.under!==void 0||e.nodes!==void 0&&e.nodes.length>0,i=e.cwd??(r||w()!==void 0?void 0:process.cwd());i!==void 0&&(n.cwd=i),e.allCwds&&(n.all_cwds=!0),e.under!==void 0&&(n.under=e.under),e.nodes!==void 0&&(n.nodes=e.nodes),e.types!==void 0&&(n.types=e.types),e.kinds!==void 0&&(n.kinds=e.kinds),e.statuses!==void 0&&(n.statuses=e.statuses),e.sinceMs!==void 0&&(n.since_ms=e.sinceMs),e.untilMs!==void 0&&(n.until_ms=e.untilMs),e.origins!==void 0&&(n.origins=e.origins),e.roles!==void 0&&(n.roles=e.roles),e.from!==void 0&&(n.from=e.from)}a(S,"applyFilters");export{y as NODE_KINDS,f as ORIGINS,p as ROLES,v as STATUSES,u as TYPES,S as applyFilters,_ as filterParams,$ as parseFilters,m as parseWhen,d as splitCsv};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var G=Object.defineProperty;var s=(e,n)=>G(e,"name",{value:n,configurable:!0});import{envNodeId as V}from"../../shared/env.js";import{defineLeaf as X}from"../../core/command.js";import{InputError as o}from"../../core/io.js";import{requireScope as Q}from"../../core/errors.js";import{mark as N}from"../../core/timing.js";import{OUTPUT_SCHEMA_CONSTRAINTS as Z,OUTPUT_SCHEMA_TRANSPORT as ee,parseOutputSchemaValue as te}from"../../core/runtime/structured-output.js";import{MODEL_SPEC_FORMS as oe,MODEL_SPEC_NEXT as ne}from"../../core/runtime/model-selection.js";import{parseDurationMs as re}from"../../core/wake.js";import{kindsStateBlock as ae,profilesStateBlock as ie,resolveProfileViaDaemon as se}from"../profile/daemon-profiles.js";import{cliClient as H,getNodeOrNull as de,rethrowAsCliError as $}from"../api-client.js";import{inTmux as z}from"../../core/runtime/placement-tmux.js";import{openSpawnViewer as ce}from"../surface/node/placement.js";import{randomUUID as le}from"node:crypto";import{resolve as ue}from"node:path";import{isDaemonTransportApiError as W}from"../../api/errors.js";import{ExitCode as he}from"../../types.js";const fe=1e5,B='--output-schema records the accepted result on the node\u2019s structured request and pushes it as the node\u2019s final report; a node that cannot honestly satisfy the schema declines with `crtr push result --decline "<reason>" --code <token>`, which finishes it with a failure outcome (reason `declined`) whose `declined` field carries { reason, code, retryable } and no result. Name the code tokens you accept in the prompt; crouter carries the code verbatim and you validate it.',K=["A resident is told never to push a final, so the spawner gets no report wake when the work is done.","If it stops mid-task, nothing prompts it to continue.","After 15 unattended minutes it is concluded with only a deferred update, which does not wake the spawner."],J="To re-task a terminal child after its final, use `crtr node message send --reopen`; to make an existing node resident later, use `crtr node config --lifecycle resident`.",T="Do not wait, poll, or duplicate this child's assignment in your own context \u2014 there is no result to await, stopping will not strand you, and duplicated work wastes the delegated context. You're auto-subscribed, so its finish wakes you on its own. Two moves only: do other independent work right now, or stop and end your turn \u2014 the wake brings you back.";async function me(e){if(e===void 0||e==="")return T;const n=await de(e);if(n===null||n.mode!=="orchestrator")return T;const t=n.context_tokens??null;return t===null||t<fe?T:`Child spawned \u2014 you're auto-subscribed, so its finish wakes you on its own; never wait, poll, or duplicate the child's assignment in your own context. But you're an orchestrator already carrying ~${Math.round(t/1e3)}k of context: rather than hold this window open for the result, bring your document \`roadmap\` current (\`crtr doc edit roadmap\`) and \`crtr node yield\` now. Yielding ends this turn, and the child's completion then revives you fresh against your roadmap \u2014 let that clean revive absorb the result instead of this bloated context.`}s(me,"childFollowUp");function pe(e,n){throw W(e)||$(e),new o({error:"node_create_effect_unknown",message:`Node creation did not receive an acknowledgement after automatic recovery with request key ${n}; its effect is unknown.`,next:"Do not create a replacement node until the daemon is reachable and this request can be recovered."},he.NETWORK)}s(pe,"createTransportFailure");function we(){return[{kind:"stdin",name:"prompt",required:!1,constraint:"First user message."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Persona kind. Defaults to the profile's default kind; `general` when the profile has none. The <kinds> list below names every top-level installable kind."},{kind:"flag",name:"mode",type:"enum",choices:["base","orchestrator"],required:!1,default:"base",constraint:"Persona mode. base for one hands-on unit; orchestrator when the unit itself needs decomposition across children. When you hold several parallel units of one kind, spawn ONE orchestrator child of that kind to own the fan-out rather than spawning the units yourself \u2014 unless you are already an orchestrator of that kind, whose job is exactly that fan-out."},{kind:"flag",name:"cwd",type:"path",required:!1,constraint:"Pin the node to this directory. Without --worktree, defaults to the spawner\u2019s directory for a managed child and the invocation directory for a root. With --worktree, selects the repository used for creation, defaulting to the invocation directory; the child runs in the new checkout."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Display name."},{kind:"flag",name:"parent",type:"string",required:!1,constraint:"Parent node id. Defaults to the calling node."},{kind:"flag",name:"node-id",type:"string",required:!1,constraint:"Exact id for the new node; lowercase letters, digits, and hyphens only, at most 128 characters. Rejected if already present."},{kind:"flag",name:"root",type:"bool",required:!1,constraint:"Spawn an independent root with no parent or subscription. Mutually exclusive with --worktree."},{kind:"flag",name:"resident",type:"bool",required:!1,constraint:"Birth the node as resident, a conversation partner for a person rather than a worker. Omit unless the user explicitly asks for a node they can talk with back and forth.",focusedHelp:{whenToUse:"Pass it ONLY when the user explicitly asks for a node they can talk with back and forth. Never infer it from task size, from expecting the user to look at the node, or from wanting to follow up later. "+J,value:"Boolean. Roots default to resident, so with --root it changes nothing. Managed children default to terminal; for a managed child the command first refuses, explains the cost, and says how to confirm.",effects:[...K,"It ends by going dormant or by being closed."]}},{kind:"flag",name:"terminal",type:"bool",required:!1,constraint:"Birth the node as terminal: it finalizes when its work is done and leaves nothing wakeable behind. Only meaningful with --root, whose default is resident; managed children are already terminal. Pass it for bounded programmatic work no one will open a viewer on. Mutually exclusive with --resident."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,hidden:!0,constraint:"Confirm a resident managed child (--resident without --root) after the user explicitly asked for one."},{kind:"flag",name:"worktree",type:"string",required:!1,constraint:"Existing local base branch for this child\u2019s managed worktree. When invoking from a managed worktree, also pass --cwd pointing at the repository\u2019s primary checkout; keep --worktree set to the desired parent branch. Mutually exclusive with --root."},{kind:"flag",name:"fork-from",type:"string",required:!1,constraint:"Fork the new node from an existing node id, absolute session path, or partial pi session uuid."},{kind:"flag",name:"model",type:"string",required:!1,constraint:"Durable model override. Omit unless the task or governing guidance requires a specific model.",focusedHelp:{whenToUse:"Use only when the user, task, or governing agent guidance already requires a specific provider, model, capability tier, or family. Omit it for routine delegation: the selected persona kind and profile own normal model selection, and review personas may enforce a quality floor.",value:`Accepted forms: ${oe}. Concrete provider/id requests must be registered. Portable provider/tier, bare-tier, and family-alias requests resolve through the configured model ladders.`,effects:["The resolved concrete model is stored on the node and in its launch recipe.","A concrete provider/id runs exactly that model on every launch and revive. A portable provider/tier, bare tier, or family alias keeps its tier: when that model's provider is rate-limited or rejects its credential, the node moves to the next model in its route: another provider's model at the same tier first, then the configured fallback tier (strong by default).","A persona quality floor may raise a weaker request before its resolved model is stored."]}},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Profile override. Use only when the task needs different project purview, owned documents, or environment; otherwise omit for normal inheritance or selection.",focusedHelp:{whenToUse:"Use only when the work must run under a different profile because it needs that profile\u2019s project purview, owned documents, stored environment, or defaults. Do not use it merely to change the working directory, persona kind, model, or graph ownership; those have separate parameters.",value:"Pass a profile id or name from the <profiles> list below; a close-enough name resolves to the nearest profile and the choice is reported on stderr. Omit it inside a node to inherit the caller\u2019s profile; outside a node, omission runs normal cwd-based profile selection.",effects:["The selected profile id is stored on the node and supplies its profile-scoped config, documents, environment, and injected bearings.","It does not change the parent or subscription; --cwd separately pins the working directory."]}},{kind:"flag",name:"situational-context",type:"string",required:!1,constraint:"Hidden ambient context appended to injected bearings, never visible chat."},{kind:"flag",name:"no-kickoff",type:"bool",required:!1,hidden:!0,constraint:"With --root, start the broker and session idle without a first message or model turn. Mutually exclusive with a prompt and --mode orchestrator."},{kind:"flag",name:"scopes",type:"string",required:!1,constraint:"Comma-separated scope allow-list for the node and every descendant (they inherit it and cannot widen it), e.g. `crtr:llm,crtr:act,device:shell,device:messages_read`. A provider-group call (`crtr device messages send` needs `device:messages_send`) is refused with scope_missing before any request leaves the machine when the group is absent. Must be a subset of what you hold; `crtr:act` requires `crtr:llm`. Enforced on the broker route (the node's own `crtr` calls); on an unsandboxed host a same-UID process can bypass it by calling the daemon socket directly (crouter#146), so it guards against a mistaken call, not a hostile node. Keep the list short: it travels in a request header on every device call (crouter#147)."},{kind:"flag",name:"deadline",type:"string",required:!1,constraint:"Positive, representable wall-clock duration from spawn. Grammar: one or more positive integer-unit parts; units: s, m, h, d; adjacent parts are summed. Omit for no deadline."},{kind:"flag",name:"outcome-action",type:"string",required:!1,constraint:"Declared human-action name that receives the node outcome. Grammar: 1\u2013128 ASCII letters, digits, dots, underscores, or hyphens; starts with a letter or digit. Omit when no external delivery target is needed."},{kind:"flag",name:"outcome-payload",type:"string",required:!1,constraint:"JSON value, serialized at most 64 KiB, frozen and echoed to --outcome-action. Requires --outcome-action."},{kind:"flag",name:"output-schema",type:"string",required:!1,constraint:"Replace prose completion with a schema-constrained final result. Use only when its consumer requires fixed fields.",focusedHelp:{whenToUse:"Use only when the node\u2019s consumer needs a machine-checkable final object with fixed fields. Omit it for ordinary delegation or when a prose report is enough; structured output replaces the completion protocol, and an over-constrained schema can force retries.",value:`Pass the JSON Schema the result must satisfy. ${ee} ${Z}`,effects:["The node must answer with `crtr push result` and cannot finish until the result is accepted; a plain `crtr push final` is blocked while the request is pending.",B,"The managed parent wakes through its existing subscription when the final report arrives; an independent root has no subscriber to wake.","An accepted result, or a decline, removes the request and terminates the node."]}}]}s(we,"nodeNewParams");function ye(){return[{name:"node_id",type:"string",required:!0,constraint:"New node id."},{name:"name",type:"string",required:!0,constraint:"Display name."},{name:"frozen_at",type:"string",required:!1,constraint:"Present when a managed child exists but capacity deferred its broker start."},...z()?[{name:"window",type:"string",required:!1,constraint:"tmux window id when a viewer opens."},{name:"session",type:"string",required:!1,constraint:"tmux session when a viewer opens."}]:[],{name:"follow_up",type:"string",required:!0,constraint:"Managed child: continue unrelated work or stop; its final report wakes you. Root: hand it off; no report wakes you."}]}s(ye,"nodeNewOutput");function ke(){return["Creates nodes/<id>/ in the canvas home, indexes the node in canvas.db, and starts its detached broker engine.","A managed child creates an active parent subscription; its pushes wake the parent. --root creates an independent node with spawned_by provenance and no parent subscription.","--worktree creates a managed worktree at ~/.crouter/canvas/worktrees/<node-id>/ on a new crtr/<node-id> branch.",B,"--deadline persists a wall-clock deadline from spawn; expiry cancels the node and records a failure outcome with reason deadline_exceeded.","--outcome-action registers one resolved local human-action target. When the node settles, crouter retries delivery of its outcome document until the target accepts it or permanently rejects it; --outcome-payload is frozen and echoed in that document.",...z()?["--root opens a viewer for the new node in the current tmux session."]:[]]}s(ke,"nodeNewEffects");async function ge(e){Q("crtr:act","crtr node new");const n=e.prompt??"",t=e.noKickoff===!0;if(!t&&n.trim()==="")throw new o({error:"empty_prompt",message:"a prompt is required (stdin or positional)",next:"Pipe a task on stdin or pass it as an argument, or pass --no-kickoff to spawn an idle node with none."});if(t&&n.trim()!=="")throw new o({error:"no_kickoff_with_prompt",message:"--no-kickoff cannot be combined with a prompt",field:"no-kickoff",next:"Drop --no-kickoff, or drop the prompt."});const l=e.kind,O=e.mode??"base",u=e.cwd?.trim(),h=u!==void 0&&u!==""?ue(u):void 0,S=e.name,Y=e.parent,a=e.root===!0,f=e.resident===!0,P=e.terminal===!0;if(f&&P)throw new o({error:"lifecycle_conflict",message:"--resident and --terminal cannot both be passed",field:"terminal",next:"Pass the one birth lifecycle you want, or neither to take the default (resident for --root, terminal for a managed child)."});if(f&&!a&&e.force!==!0)throw new o({error:"resident_child_requires_force",message:`--resident on a managed child makes it a conversation partner for a person, not a worker that reports back. ${K.join(" ")}`,field:"resident",next:`If the user did not explicitly ask for a node they can talk with back and forth, drop --resident; a terminal child's final report wakes you. ${J} If the user did explicitly ask for one, re-run with --force.`});const m=e.worktree;if(m!==void 0&&m.trim()==="")throw new o({error:"worktree_base_required",message:"--worktree requires a base branch",field:"worktree",next:"Pass an existing local branch that landing can fast-forward."});const p=m?.trim(),E=e.forkFrom,w=e.model?.trim();if(w==="")throw new o({error:"empty_spec",message:"a model spec is required",field:"model",next:`Run \`crtr node new --model -h\` and read the focused contract. ${ne}`});const D=e.profile,C=D===void 0?void 0:(await se(D)).id,y=e.situationalContext?.trim(),A=y!==void 0&&y!==""?y:void 0,U=te(e.outputSchema),I=U!==null?JSON.stringify(U):null,d=e.deadline;if(d!==void 0){const r=re(d),q=r===null?Number.NaN:new Date(Date.now()+r).getTime();if(r===null||!Number.isFinite(r)||r<=0||!Number.isFinite(q))throw new o({error:"invalid_deadline",message:"--deadline must be a positive representable duration",field:"deadline",next:"Pass positive integer-unit parts using s, m, h, or d."})}const k=e.outcomeAction,g=e.outcomePayload;if(g!==void 0&&k===void 0)throw new o({error:"outcome_payload_requires_action",message:"--outcome-payload requires --outcome-action",field:"outcome-payload",next:"Pass the declared delivery action with --outcome-action."});let v;if(g!==void 0)try{v=JSON.parse(g)}catch{throw new o({error:"invalid_outcome_payload",message:"--outcome-payload must be valid JSON",field:"outcome-payload",next:"Pass one valid JSON value."})}const R=e.scopes,c=R===void 0?void 0:R.split(",").map(r=>r.trim()).filter(r=>r!=="");if(c!==void 0&&c.length===0)throw new o({error:"empty_scopes",message:"--scopes names no scope",field:"scopes",next:"Pass a comma-separated list such as crtr:llm,crtr:act, or omit --scopes to inherit."});const b=e.nodeId?.trim();if(a&&p!==void 0)throw new o({error:"worktree_root_conflict",message:"--worktree is mutually exclusive with --root",field:"worktree",next:"Drop either --root or --worktree."});if(t&&!a)throw new o({error:"no_kickoff_requires_root",message:"--no-kickoff is only valid with --root",field:"no-kickoff",next:"Add --root, or drop --no-kickoff and provide a prompt."});if(t&&O==="orchestrator")throw new o({error:"no_kickoff_orchestrator_unsupported",message:"--no-kickoff cannot be combined with --mode orchestrator",field:"no-kickoff",next:"Drop --no-kickoff and provide a prompt, or spawn in base mode."});const _=V(),M=Y??_;N("node_new.create_start",{root:a});const L=le(),j={...l!==void 0?{kind:l}:{},mode:O,cwd:process.cwd(),...h!==void 0&&h!==""?{pin_cwd:h}:{},...S!==void 0?{name:S}:{},prompt:n,...a?{root:!0}:{parent:M??null},..._!==void 0?{creator:_}:{},...f?{root_lifecycle:"resident"}:{},...P?{root_lifecycle:"terminal"}:{},...p!==void 0?{worktree:p}:{},...E!==void 0?{fork_from:E}:{},...w!==void 0?{model:w}:{},...C!==void 0?{profile:C}:{},...A!==void 0?{situational_context:A}:{},...t?{no_kickoff:!0}:{},...I!==null?{output_schema:I}:{},...c!==void 0?{scopes:c}:{},...d!==void 0?{deadline:d}:{},...k!==void 0?{outcome_delivery:{action:k,...v===void 0?{}:{payload:v}}}:{},...b!==void 0&&b!==""?{node_id:b}:{},...a?{prefer_warm:!0}:{},request_key:L};let i;try{i=await H().createNode(j)}catch(r){W(r)||$(r);try{i=await H().createNode(j)}catch(q){pe(q,L)}}N("node_new.node_created",{node:i.node_id});let x={};a&&(x=ce(i.node_id,i.cwd,i.name)),a&&N("node_new.viewer_window_opened");const F=!a&&i.frozen_at!==null;return{node_id:i.node_id,name:i.name,...F?{frozen_at:i.frozen_at}:{},window:x.window,session:x.session,follow_up:a?t?"Independent root spawned idle. No kickoff turn ran; hand it off or attach and prompt it. No report wakes you.":"Independent root spawned. You are not subscribed, so its finish does not wake you; hand it off and move on.":F?"Child row exists and is frozen: its broker has not started yet. A node whose environment is remote (an imported Mac, a Blaxel sandbox) is always born frozen until the cloud launches it; a local node waits here because capacity (broker slots or the app's memory) is full and launches when it frees. Its final report wakes you then.":await me(M)}}s(ge,"runNodeCreation");const Le=X({name:"new",description:"create and start a node immediately",whenToUse:"a unit of work is genuinely separable from what you are doing: a bounded subtask you would otherwise grind out inline, several independent units worth running in parallel (usually via one orchestrator child of the matching kind rather than a flat fan-out from you), a scouting pass over unfamiliar code, a change that wants its own git worktree, or an answer you need in a fixed shape rather than as prose",tier:"important",help:{name:"node new",summary:"create a node immediately and start its detached broker",guide:"The prompt is the child\u2019s entire brief: it wakes with this prompt, its persona, and ambient bearings \u2014 none of your conversation carries over. State the outcome and constraints. Pass an implementation plan only when it is already settled or necessary to preserve an approved decision; otherwise, let the child investigate and choose how. Give the reason along with the request: the larger goal this serves and what the child's output enables, so the child resolves ambiguity toward your intent instead of guessing. Point at every document the task depends on (a spec, an explore map, an earlier child's findings) as `[[<node-id>/<name>]]`, or `[[name]]` for a repo, profile or user document; the child reads each with `crtr canvas read` and receives nothing the prompt does not point at. Name every file or directory as an absolute host path, never `~`-relative: the child's `~` is its own HOME, not yours, and a hook cwd outside its mounts (e.g. `/tmp`) is refused. When the report must carry something specific\u2014findings inline, or pointers to documents it wrote\u2014say so in the prompt.",params:we(),output:ye(),outputKind:"object",effects:ke()},helpState:{leaf:ae,flags:{profile:ie}},run:s(e=>ge(e),"run"),render:s(e=>{const n=e.window?` in window ${e.window}`:"",t=[`Spawned "${e.name}" (${e.node_id})${n}.`];return e.session&&t.push(`- session: ${e.session}`),t.push("",String(e.follow_up)),t.join(`
|
|
2
|
-
`)},"render")});export{
|
|
1
|
+
var X=Object.defineProperty;var s=(e,r)=>X(e,"name",{value:r,configurable:!0});import{envNodeId as Q,envProfileId as Z}from"../../shared/env.js";import{readMergedLaunchConfig as ee}from"../../core/config.js";import{defineLeaf as te}from"../../core/command.js";import{InputError as t}from"../../core/io.js";import{requireScope as oe}from"../../core/errors.js";import{mark as O}from"../../core/timing.js";import{OUTPUT_SCHEMA_CONSTRAINTS as ne,OUTPUT_SCHEMA_TRANSPORT as re,parseOutputSchemaValue as ie}from"../../core/runtime/structured-output.js";import{MODEL_SPEC_FORMS as ae,MODEL_SPEC_NEXT as se}from"../../core/runtime/model-selection.js";import{parseDurationMs as de}from"../../core/wake.js";import{kindsStateBlock as ce,profilesStateBlock as le,resolveProfileViaDaemon as ue}from"../profile/daemon-profiles.js";import{cliClient as S,getNodeOrNull as he,rethrowAsCliError as z}from"../api-client.js";import{inTmux as W}from"../../core/runtime/placement-tmux.js";import{openSpawnViewer as fe}from"../surface/node/placement.js";import{randomUUID as me}from"node:crypto";import{resolve as pe}from"node:path";import{isDaemonTransportApiError as B}from"../../api/errors.js";import{ExitCode as we}from"../../types.js";const ke=1e5,K='--output-schema records the accepted result on the node\u2019s structured request and pushes it as the node\u2019s final report; a node that cannot honestly satisfy the schema declines with `crtr push result --decline "<reason>" --code <token>`, which finishes it with a failure outcome (reason `declined`) whose `declined` field carries { reason, code, retryable } and no result. Name the code tokens you accept in the prompt; crouter carries the code verbatim and you validate it.',J=["A resident is told never to push a final, so the spawner gets no report wake when the work is done.","If it stops mid-task, nothing prompts it to continue.","After 15 unattended minutes it is concluded with only a deferred update, which does not wake the spawner."],V="To re-task a terminal child after its final, use `crtr node message send --reopen`; to make an existing node resident later, use `crtr node config --lifecycle resident`.",T="Do not wait, poll, or duplicate this child's assignment in your own context \u2014 there is no result to await, stopping will not strand you, and duplicated work wastes the delegated context. You're auto-subscribed, so its finish wakes you on its own. Two moves only: do other independent work right now, or stop and end your turn \u2014 the wake brings you back.";async function ye(e){if(e===void 0||e==="")return T;const r=await he(e);if(r===null||r.mode!=="orchestrator")return T;const o=r.context_tokens??null;return o===null||o<ke?T:`Child spawned \u2014 you're auto-subscribed, so its finish wakes you on its own; never wait, poll, or duplicate the child's assignment in your own context. But you're an orchestrator already carrying ~${Math.round(o/1e3)}k of context: rather than hold this window open for the result, bring your document \`roadmap\` current (\`crtr doc edit roadmap\`) and \`crtr node yield\` now. Yielding ends this turn, and the child's completion then revives you fresh against your roadmap \u2014 let that clean revive absorb the result instead of this bloated context.`}s(ye,"childFollowUp");function ge(e,r){throw B(e)||z(e),new t({error:"node_create_effect_unknown",message:`Node creation did not receive an acknowledgement after automatic recovery with request key ${r}; its effect is unknown.`,next:"Do not create a replacement node until the daemon is reachable and this request can be recovered."},we.NETWORK)}s(ge,"createTransportFailure");function ve(){return[{kind:"stdin",name:"prompt",required:!1,constraint:"First user message."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Persona kind. Defaults to the profile's default kind; `general` when the profile has none. The <kinds> list below names every top-level installable kind."},{kind:"flag",name:"mode",type:"enum",choices:["base","orchestrator"],required:!1,default:"base",constraint:"Persona mode. base for one hands-on unit; orchestrator when the unit itself needs decomposition across children. When you hold several parallel units of one kind, spawn ONE orchestrator child of that kind to own the fan-out rather than spawning the units yourself \u2014 unless you are already an orchestrator of that kind, whose job is exactly that fan-out."},{kind:"flag",name:"cwd",type:"path",required:!1,constraint:"Pin the node to this directory. Without --worktree, defaults to the spawner\u2019s directory for a managed child and the invocation directory for a root. With --worktree, selects the repository used for creation, defaulting to the invocation directory; the child runs in the new checkout."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Display name."},{kind:"flag",name:"parent",type:"string",required:!1,constraint:"Parent node id. Defaults to the calling node."},{kind:"flag",name:"node-id",type:"string",required:!1,constraint:"Exact id for the new node; lowercase letters, digits, and hyphens only, at most 128 characters. Rejected if already present."},{kind:"flag",name:"root",type:"bool",required:!1,constraint:"Spawn an independent root with no parent or subscription. Mutually exclusive with --worktree."},{kind:"flag",name:"resident",type:"bool",required:!1,constraint:"Birth the node as resident, a conversation partner for a person rather than a worker. Omit unless the user explicitly asks for a node they can talk with back and forth.",focusedHelp:{whenToUse:"Pass it ONLY when the user explicitly asks for a node they can talk with back and forth. Never infer it from task size, from expecting the user to look at the node, or from wanting to follow up later. "+V,value:"Boolean. Roots default to resident, so with --root it changes nothing. Managed children default to terminal; for a managed child the command first refuses, explains the cost, and says how to confirm.",effects:[...J,"It ends by going dormant or by being closed."]}},{kind:"flag",name:"terminal",type:"bool",required:!1,constraint:"Birth the node as terminal: it finalizes when its work is done and leaves nothing wakeable behind. Only meaningful with --root, whose default is resident; managed children are already terminal. Pass it for bounded programmatic work no one will open a viewer on. Mutually exclusive with --resident."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,hidden:!0,constraint:"Confirm a resident managed child (--resident without --root) after the user explicitly asked for one."},{kind:"flag",name:"worktree",type:"string",required:!1,constraint:"Existing local base branch for this child\u2019s managed worktree. When invoking from a managed worktree, also pass --cwd pointing at the repository\u2019s primary checkout; keep --worktree set to the desired parent branch. Mutually exclusive with --root."},{kind:"flag",name:"fork-from",type:"string",required:!1,constraint:"Fork the new node from an existing node id, absolute session path, or partial pi session uuid."},{kind:"flag",name:"model",type:"string",required:!1,constraint:"Durable model override. Omit unless the task or governing guidance requires a specific model.",focusedHelp:{whenToUse:"Use only when the user, task, or governing agent guidance already requires a specific provider, model, capability tier, or family. Omit it for routine delegation: the selected persona kind and profile own normal model selection, and review personas may enforce a quality floor.",value:`Accepted forms: ${ae}. Concrete provider/id requests must be registered. Portable provider/tier, bare-tier, and family-alias requests resolve through the configured model ladders.`,effects:["The resolved concrete model is stored on the node and in its launch recipe.","A concrete provider/id runs exactly that model on every launch and revive. A portable provider/tier, bare tier, or family alias keeps its tier: when that model's provider is rate-limited or rejects its credential, the node moves to the next model in its route: another provider's model at the same tier first, then the configured fallback tier (strong by default).","A persona quality floor may raise a weaker request before its resolved model is stored."]}},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Profile override. Use only when the task needs different project purview, owned documents, or environment; otherwise omit for normal inheritance or selection.",focusedHelp:{whenToUse:"Use only when the work must run under a different profile because it needs that profile\u2019s project purview, owned documents, stored environment, or defaults. Do not use it merely to change the working directory, persona kind, model, or graph ownership; those have separate parameters.",value:"Pass a profile id or name from the <profiles> list below; a close-enough name resolves to the nearest profile and the choice is reported on stderr. Omit it inside a node to inherit the caller\u2019s profile; outside a node, omission runs normal cwd-based profile selection.",effects:["The selected profile id is stored on the node and supplies its profile-scoped config, documents, environment, and injected bearings.","It does not change the parent or subscription; --cwd separately pins the working directory."]}},{kind:"flag",name:"situational-context",type:"string",required:!1,constraint:"Hidden ambient context appended to injected bearings, never visible chat."},{kind:"flag",name:"no-kickoff",type:"bool",required:!1,hidden:!0,constraint:"With --root, start the broker and session idle without a first message or model turn. Mutually exclusive with a prompt and --mode orchestrator."},{kind:"flag",name:"scopes",type:"string",required:!1,constraint:"Comma-separated scope allow-list for the node and every descendant (they inherit it and cannot widen it), e.g. `crtr:llm,crtr:act,device:shell,device:messages_read`. A provider-group call (`crtr device messages send` needs `device:messages_send`) is refused with scope_missing before any request leaves the machine when the group is absent. Must be a subset of what you hold; `crtr:act` requires `crtr:llm`. Enforced on the broker route (the node's own `crtr` calls); on an unsandboxed host a same-UID process can bypass it by calling the daemon socket directly (crouter#146), so it guards against a mistaken call, not a hostile node. Keep the list short: it travels in a request header on every device call (crouter#147)."},{kind:"flag",name:"deadline",type:"string",required:!1,constraint:"Positive, representable wall-clock duration from spawn. Grammar: one or more positive integer-unit parts; units: s, m, h, d; adjacent parts are summed. Omit for no deadline."},{kind:"flag",name:"outcome-action",type:"string",required:!1,constraint:"Declared human-action name that receives the node outcome. Grammar: 1\u2013128 ASCII letters, digits, dots, underscores, or hyphens; starts with a letter or digit. Omit when no external delivery target is needed."},{kind:"flag",name:"outcome-payload",type:"string",required:!1,constraint:"JSON value, serialized at most 64 KiB, frozen and echoed to --outcome-action. Requires --outcome-action."},{kind:"flag",name:"output-schema",type:"string",required:!1,constraint:"Replace prose completion with a schema-constrained final result. Use only when its consumer requires fixed fields.",focusedHelp:{whenToUse:"Use only when the node\u2019s consumer needs a machine-checkable final object with fixed fields. Omit it for ordinary delegation or when a prose report is enough; structured output replaces the completion protocol, and an over-constrained schema can force retries.",value:`Pass the JSON Schema the result must satisfy. ${re} ${ne}`,effects:["The node must answer with `crtr push result` and cannot finish until the result is accepted; a plain `crtr push final` is blocked while the request is pending.",K,"The managed parent wakes through its existing subscription when the final report arrives; an independent root has no subscriber to wake.","An accepted result, or a decline, removes the request and terminates the node."]}}]}s(ve,"nodeNewParams");function be(){return[{name:"node_id",type:"string",required:!0,constraint:"New node id."},{name:"name",type:"string",required:!0,constraint:"Display name."},{name:"frozen_at",type:"string",required:!1,constraint:"Present when a managed child exists but capacity deferred its broker start."},...W()?[{name:"window",type:"string",required:!1,constraint:"tmux window id when a viewer opens."},{name:"session",type:"string",required:!1,constraint:"tmux session when a viewer opens."}]:[],{name:"follow_up",type:"string",required:!0,constraint:"Managed child: continue unrelated work or stop; its final report wakes you. Root: hand it off; no report wakes you."}]}s(be,"nodeNewOutput");function _e(){return["Creates nodes/<id>/ in the canvas home, indexes the node in canvas.db, and starts its detached broker engine.","A managed child creates an active parent subscription; its pushes wake the parent. --root creates an independent node with spawned_by provenance and no parent subscription.","--worktree creates a managed worktree at ~/.crouter/canvas/worktrees/<node-id>/ on a new crtr/<node-id> branch.",K,"--deadline persists a wall-clock deadline from spawn; expiry cancels the node and records a failure outcome with reason deadline_exceeded.","--outcome-action registers one resolved local human-action target. When the node settles, crouter retries delivery of its outcome document until the target accepts it or permanently rejects it; --outcome-payload is frozen and echoed in that document.",...W()?["--root opens a viewer for the new node in the current tmux session."]:[]]}s(_e,"nodeNewEffects");async function xe(e){oe("crtr:act","crtr node new");const r=e.prompt??"",o=e.noKickoff===!0;if(!o&&r.trim()==="")throw new t({error:"empty_prompt",message:"a prompt is required (stdin or positional)",next:"Pipe a task on stdin or pass it as an argument, or pass --no-kickoff to spawn an idle node with none."});if(o&&r.trim()!=="")throw new t({error:"no_kickoff_with_prompt",message:"--no-kickoff cannot be combined with a prompt",field:"no-kickoff",next:"Drop --no-kickoff, or drop the prompt."});const d=e.kind,P=e.mode??"base",p=e.cwd?.trim(),l=p!==void 0&&p!==""?pe(p):void 0,E=e.name,Y=e.parent,i=e.root===!0,w=e.resident===!0,D=e.terminal===!0;if(w&&D)throw new t({error:"lifecycle_conflict",message:"--resident and --terminal cannot both be passed",field:"terminal",next:"Pass the one birth lifecycle you want, or neither to take the default (resident for --root, terminal for a managed child)."});if(w&&!i&&e.force!==!0)throw new t({error:"resident_child_requires_force",message:`--resident on a managed child makes it a conversation partner for a person, not a worker that reports back. ${J.join(" ")}`,field:"resident",next:`If the user did not explicitly ask for a node they can talk with back and forth, drop --resident; a terminal child's final report wakes you. ${V} If the user did explicitly ask for one, re-run with --force.`});const k=e.worktree;if(k!==void 0&&k.trim()==="")throw new t({error:"worktree_base_required",message:"--worktree requires a base branch",field:"worktree",next:"Pass an existing local branch that landing can fast-forward."});const y=k?.trim(),C=e.forkFrom,g=e.model?.trim();if(g==="")throw new t({error:"empty_spec",message:"a model spec is required",field:"model",next:`Run \`crtr node new --model -h\` and read the focused contract. ${se}`});const A=e.profile,u=A===void 0?void 0:(await ue(A)).id,v=e.situationalContext?.trim(),I=v!==void 0&&v!==""?v:void 0,U=ie(e.outputSchema),R=U!==null?JSON.stringify(U):null,h=e.deadline;if(h!==void 0){const n=de(h),c=n===null?Number.NaN:new Date(Date.now()+n).getTime();if(n===null||!Number.isFinite(n)||n<=0||!Number.isFinite(c))throw new t({error:"invalid_deadline",message:"--deadline must be a positive representable duration",field:"deadline",next:"Pass positive integer-unit parts using s, m, h, or d."})}const b=e.outcomeAction,_=e.outcomePayload;if(_!==void 0&&b===void 0)throw new t({error:"outcome_payload_requires_action",message:"--outcome-payload requires --outcome-action",field:"outcome-payload",next:"Pass the declared delivery action with --outcome-action."});let x;if(_!==void 0)try{x=JSON.parse(_)}catch{throw new t({error:"invalid_outcome_payload",message:"--outcome-payload must be valid JSON",field:"outcome-payload",next:"Pass one valid JSON value."})}const M=e.scopes,f=M===void 0?void 0:M.split(",").map(n=>n.trim()).filter(n=>n!=="");if(f!==void 0&&f.length===0)throw new t({error:"empty_scopes",message:"--scopes names no scope",field:"scopes",next:"Pass a comma-separated list such as crtr:llm,crtr:act, or omit --scopes to inherit."});const q=e.nodeId?.trim();if(i&&y!==void 0)throw new t({error:"worktree_root_conflict",message:"--worktree is mutually exclusive with --root",field:"worktree",next:"Drop either --root or --worktree."});if(o&&!i)throw new t({error:"no_kickoff_requires_root",message:"--no-kickoff is only valid with --root",field:"no-kickoff",next:"Add --root, or drop --no-kickoff and provide a prompt."});if(o&&P==="orchestrator")throw new t({error:"no_kickoff_orchestrator_unsupported",message:"--no-kickoff cannot be combined with --mode orchestrator",field:"no-kickoff",next:"Drop --no-kickoff and provide a prompt, or spawn in base mode."});const m=Q();if(d!==void 0&&m===void 0){const n=Object.keys(ee(l??process.cwd(),u??(Z()||null)).kinds),c=(await S().listKinds({profile:u})).kinds.map(G=>G.kind),H=[...new Set([...n,...c])];if(!H.includes(d))throw new t({error:"unknown_kind",message:`unknown kind: ${d}`,field:"kind",received:d,next:`Valid kinds: ${H.sort().join(", ")}.`})}const j=Y??m;O("node_new.create_start",{root:i});const L=me(),$={...d!==void 0?{kind:d}:{},mode:P,cwd:process.cwd(),...l!==void 0&&l!==""?{pin_cwd:l}:{},...E!==void 0?{name:E}:{},prompt:r,...i?{root:!0}:{parent:j??null},...m!==void 0?{creator:m}:{},...w?{root_lifecycle:"resident"}:{},...D?{root_lifecycle:"terminal"}:{},...y!==void 0?{worktree:y}:{},...C!==void 0?{fork_from:C}:{},...g!==void 0?{model:g}:{},...u!==void 0?{profile:u}:{},...I!==void 0?{situational_context:I}:{},...o?{no_kickoff:!0}:{},...R!==null?{output_schema:R}:{},...f!==void 0?{scopes:f}:{},...h!==void 0?{deadline:h}:{},...b!==void 0?{outcome_delivery:{action:b,...x===void 0?{}:{payload:x}}}:{},...q!==void 0&&q!==""?{node_id:q}:{},...i?{prefer_warm:!0}:{},request_key:L};let a;try{a=await S().createNode($)}catch(n){B(n)||z(n);try{a=await S().createNode($)}catch(c){ge(c,L)}}O("node_new.node_created",{node:a.node_id});let N={};i&&(N=fe(a.node_id,a.cwd,a.name)),i&&O("node_new.viewer_window_opened");const F=!i&&a.frozen_at!==null;return{node_id:a.node_id,name:a.name,...F?{frozen_at:a.frozen_at}:{},window:N.window,session:N.session,follow_up:i?o?"Independent root spawned idle. No kickoff turn ran; hand it off or attach and prompt it. No report wakes you.":"Independent root spawned. You are not subscribed, so its finish does not wake you; hand it off and move on.":F?"Child row exists and is frozen: its broker has not started yet. A node whose environment is remote (an imported Mac, a Blaxel sandbox) is always born frozen until the cloud launches it; a local node waits here because capacity (broker slots or the app's memory) is full and launches when it frees. Its final report wakes you then.":await ye(j)}}s(xe,"runNodeCreation");const ze=te({name:"new",description:"create and start a node immediately",whenToUse:"a unit of work is genuinely separable from what you are doing: a bounded subtask you would otherwise grind out inline, several independent units worth running in parallel (usually via one orchestrator child of the matching kind rather than a flat fan-out from you), a scouting pass over unfamiliar code, a change that wants its own git worktree, or an answer you need in a fixed shape rather than as prose",tier:"important",help:{name:"node new",summary:"create a node immediately and start its detached broker",guide:"The prompt is the child\u2019s entire brief: it wakes with this prompt, its persona, and ambient bearings \u2014 none of your conversation carries over. State the outcome and constraints. Pass an implementation plan only when it is already settled or necessary to preserve an approved decision; otherwise, let the child investigate and choose how. Give the reason along with the request: the larger goal this serves and what the child's output enables, so the child resolves ambiguity toward your intent instead of guessing. Point at every document the task depends on (a spec, an explore map, an earlier child's findings) as `[[<node-id>/<name>]]`, or `[[name]]` for a repo, profile or user document; the child reads each with `crtr canvas read` and receives nothing the prompt does not point at. Name every file or directory as an absolute host path, never `~`-relative: the child's `~` is its own HOME, not yours, and a hook cwd outside its mounts (e.g. `/tmp`) is refused. When the report must carry something specific\u2014findings inline, or pointers to documents it wrote\u2014say so in the prompt.",params:ve(),output:be(),outputKind:"object",effects:_e()},helpState:{leaf:ce,flags:{profile:le}},run:s(e=>xe(e),"run"),render:s(e=>{const r=e.window?` in window ${e.window}`:"",o=[`Spawned "${e.name}" (${e.node_id})${r}.`];return e.session&&o.push(`- session: ${e.session}`),o.push("",String(e.follow_up)),o.join(`
|
|
2
|
+
`)},"render")});export{ye as childFollowUp,ze as nodeNew};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var n=(t,e)=>a(t,"name",{value:e,configurable:!0});import{ApiError as p}from"../api/index.js";import{personId as c,
|
|
1
|
+
var a=Object.defineProperty;var n=(t,e)=>a(t,"name",{value:e,configurable:!0});import{ApiError as p}from"../api/index.js";import{personId as c,bindClientPerson as f}from"../core/canvas/person-state.js";import{currentSnapshot as g,installPersonSnapshot as S,setSettingsReloader as l,setSettingsTransport as m,SettingsRevisionConflictError as u}from"../core/scoped-state/person-store.js";import{cliClient as r}from"./api-client.js";const s=n(t=>t.snapshot,"fromDto");function d(){return{person:c(),snapshot:g()}}n(d,"loadedPersonSettings");async function A(){h(await r().getSettings())}n(A,"loadPersonSettingsViaApi");function h(t){f(t.person),S(t.person,s(t)),l(async()=>s(await r().getSettings())),m(async(e,i)=>{try{return s(await r().putSettings({ops:i}))}catch(o){throw o instanceof p&&o.status===409?new u:o}})}n(h,"installPersonSettingsDto");export{h as installPersonSettingsDto,A as loadPersonSettingsViaApi,d as loadedPersonSettings};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
3
|
-
\u2026 ${
|
|
4
|
-
`);return
|
|
1
|
+
var d=Object.defineProperty;var i=(n,o)=>d(n,"name",{value:o,configurable:!0});import{stateBlock as c}from"../../core/help.js";import{matchProfileOperand as p}from"../../core/profiles/manifest.js";import{localClient as u}from"../../api/node-transport.js";import{cliClient as h}from"../api-client.js";import{readMergedLaunchConfig as k}from"../../core/config.js";import{envProfileId as f}from"../../shared/env.js";const m=i(()=>u({autostart:!1}),"helpClient"),g=i(n=>({profileId:n.id,name:n.name}),"profileKey");async function C(n){return p(await h().listProfiles(),n,g)}i(C,"resolveProfileViaDaemon");async function j(){const n=await m().listProfiles(),o=20,r=n.slice(0,o).map(s=>`${s.id} \u2014 ${s.name}`).join(`
|
|
2
|
+
`),l=n.length>o?`${r}
|
|
3
|
+
\u2026 ${n.length-o} more; use crtr profile list`:r;return c("profiles",{count:n.length},l)}i(j,"profilesStateBlock");async function B(){const n=(await m().listKinds({profile:f()||void 0})).kinds,o=k(process.cwd(),f()||null).kinds,l=[...n,...Object.keys(o).filter(e=>!n.some(t=>t.kind===e)).map(e=>({kind:e,when_to_use:o[e]?.whenToUse??null,available_to:o[e]?.availableTo??null}))].filter(({kind:e,available_to:t})=>{const a=e.indexOf("/");return a===-1||(t??[e.slice(0,a)]).includes("*")}),s=l.map(({kind:e,when_to_use:t})=>t?`${e} \u2014 ${t}`:e).join(`
|
|
4
|
+
`);return c("kinds",{count:l.length},s)}i(B,"kindsStateBlock");export{B as kindsStateBlock,j as profilesStateBlock,C as resolveProfileViaDaemon};
|
package/dist/commands/sys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(o,s)=>m(o,"name",{value:s,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as a}from"./sys/doctor.js";import{sysFeedbackLeaf as p}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{
|
|
1
|
+
var m=Object.defineProperty;var r=(o,s)=>m(o,"name",{value:s,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as a}from"./sys/doctor.js";import{sysFeedbackLeaf as p}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{sysMachineBranch as l}from"./sys/machine/rotate.js";import{sysDesktopBranch as v}from"./sys/desktop.js";import{sysSigninLeaf as x,sysSignoutLeaf as b}from"./sys/signin.js";import{sysUpdateLeaf as E,sysVersionLeaf as F}from"./sys/update.js";function Z(){return t([S,f,i,g,u,a,k,p,n,c,y,L,h,B,d,E,F,D,l,x,b,v,e])}r(Z,"registerSys");export{Z as registerSys};
|
|
@@ -42,8 +42,6 @@ export interface HistoryArtifact {
|
|
|
42
42
|
from?: string;
|
|
43
43
|
}
|
|
44
44
|
export interface ScopeFilter {
|
|
45
|
-
/** A specific cwd. Default (all flags absent) = the caller's cwd. */
|
|
46
|
-
cwd?: string;
|
|
47
45
|
/** Every cwd on the canvas. */
|
|
48
46
|
allCwds?: boolean;
|
|
49
47
|
/** A node and its subscription descendants (one initiative / sub-DAG). */
|
|
@@ -67,14 +65,10 @@ export interface CorpusFilter {
|
|
|
67
65
|
/** Case-insensitive substring against the artifact's sender attribution. */
|
|
68
66
|
from?: string;
|
|
69
67
|
}
|
|
70
|
-
/**
|
|
71
|
-
* CRTR_NODE_ID via the canvas data layer), falling back to the process cwd
|
|
72
|
-
* when not run as a node. */
|
|
73
|
-
export declare function callerCwd(): Promise<string>;
|
|
74
|
-
/** Build the searchable artifact set for a scope + corpus filter. Node facets
|
|
68
|
+
/** Build the searchable artifact set for a scope + corpus filter; `cwd` is the scope when no other scope field is set. Node facets
|
|
75
69
|
* are applied against the db rows first (cheap); only surviving nodes' files
|
|
76
70
|
* are read. */
|
|
77
|
-
export declare function buildCorpus(scope: ScopeFilter, corpus: CorpusFilter): Promise<HistoryArtifact[]>;
|
|
71
|
+
export declare function buildCorpus(scope: ScopeFilter, corpus: CorpusFilter, cwd: string): Promise<HistoryArtifact[]>;
|
|
78
72
|
export type GroupKey = 'origin' | 'node' | 'kind' | 'day' | 'type' | 'role';
|
|
79
73
|
export interface CorpusGroup {
|
|
80
74
|
key: string;
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var S=Object.defineProperty;var
|
|
1
|
+
var S=Object.defineProperty;var d=(n,s)=>S(n,"name",{value:s,configurable:!0});import{getNode as b,listNodes as M,view as j}from"./canvas.js";import{openDb as v}from"./db.js";import{readTextIfExists as E}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as O}from"../conversation-store/index.js";import{reportBodyByName as I}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as C}from"../async-array.js";const V=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],X=["user","assistant","toolResult"];function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}d(x,"toMs");async function k(n){return(await(await v()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
|
|
2
2
|
FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
3
3
|
WHERE d.destination_id = ? AND d.wake = 1
|
|
4
|
-
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}
|
|
5
|
-
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,
|
|
4
|
+
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}d(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
|
|
5
|
+
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,l=n.ref!==null?o?typeof r=="string"?r:E(n.ref)??"":await I(n.ref)??"":i,f=l!==""&&l!==n.label,u=[s,e];return n.ref!==null&&u.push(`ref: ${n.ref}`),f&&u.push(l),u.join(`
|
|
6
6
|
|
|
7
|
-
`)}
|
|
8
|
-
`)}
|
|
9
|
-
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:
|
|
7
|
+
`)}d(_,"inboxEntryBody");async function B(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}d(B,"inboxArtifact");async function $(n){const s=(await b(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof O)return null;throw t}}d($,"resolveSessionFile");function R(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
|
|
8
|
+
`)}d(R,"textFromBlocks");function D(n){return n==null?"unknown":n.type==="human"?"human":n.kind}d(D,"originToken");function T(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}d(T,"sendersOf");async function N(n){const s=await $(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const l=r.message;if(l===null||typeof l!="object")continue;const f=l,u=typeof f.role=="string"?f.role:"";if(u==="")continue;const a=typeof f.timestamp=="number"?f.timestamp:void 0,c=typeof r.timestamp=="string"?r.timestamp:a!==void 0?new Date(a).toISOString():"",m=R(f.content),p={index:i.length,role:u,text:m,ts:c,tsMs:a??x(c)};if(u==="user"){const h=a!==void 0&&t.has(a)?t.get(a):null;p.origin=D(h);const w=T(h);w!==void 0&&(p.from=w)}i.push(p)}return i}d(N,"sessionMessages");async function F(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}d(F,"rawSessionLine");function L(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
|
|
9
|
+
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}d(L,"transcriptArtifact");async function J(n){return(await b(n))?.description??""}d(J,"nodeDescOf");async function Z(n,s,e){const t=await W(n,e),i=s.kinds,o=s.statuses,r=t.filter(a=>!(i!==void 0&&i.length>0&&!i.includes(a.kind)||o!==void 0&&o.length>0&&!o.includes(a.status))),l=s.types!==void 0&&s.types.length>0?s.types:["inbox"],f=new Set(l),u=[];for(const a of r){const c=await J(a.node_id);if(f.has("inbox")&&await C(await k(a.node_id),async(m,p)=>u.push(await B(a,c,m,p))),f.has("transcript"))for(const m of await N(a.node_id))u.push(L(a,c,m))}return u.filter(a=>s.sinceMs!==void 0&&a.tsMs<s.sinceMs||s.untilMs!==void 0&&a.tsMs>s.untilMs?!1:K(a,s))}d(Z,"buildCorpus");function K(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}d(K,"matchesMessageFilters");function nn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}d(nn,"groupCorpus");async function W(n,s){const e=await M(),t=new Map(e.map(i=>[i.node_id,i]));return n.nodes!==void 0&&n.nodes.length>0?n.nodes.map(i=>t.get(i)).filter(i=>i!==void 0):n.under!==void 0&&n.under!==""?[n.under,...await j(n.under)].map(o=>t.get(o)).filter(o=>o!==void 0):n.allCwds===!0?e:e.filter(i=>i.cwd===s)}d(W,"scopedRows");async function en(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await b(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await $(e);if(o===null)return null;const r=await N(e);if(t==="session"){const u=r.map(a=>`## ${a.role}${a.origin!==void 0?` (origin: ${a.origin})`:""}
|
|
10
10
|
|
|
11
|
-
${
|
|
11
|
+
${a.text}`).join(`
|
|
12
12
|
|
|
13
|
-
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:
|
|
14
|
-
`).join("")},"raw"),path:o}}const
|
|
13
|
+
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:u,raw:d(async()=>{const{header:a,entries:c}=await g().read(y(o));return[a,...c].map(m=>`${JSON.stringify(m)}
|
|
14
|
+
`).join("")},"raw"),path:o}}const l=Number(t.slice(8)),f=r[l];return f===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:f.ts,nodeName:i.name,body:f.text,raw:d(()=>F(o,l),"raw"),path:o}}return null}d(en,"resolveRef");export{X as MESSAGE_ROLES,V as ORIGIN_TOKENS,Z as buildCorpus,nn as groupCorpus,en as resolveRef};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var E=Object.defineProperty;var r=(n,e)=>E(n,"name",{value:e,configurable:!0});import{createHash as
|
|
1
|
+
var E=Object.defineProperty;var r=(n,e)=>E(n,"name",{value:e,configurable:!0});import{createHash as l,randomBytes as g}from"node:crypto";import{openDb as d,withCanvasWrite as k}from"./db.js";import{terminalGrant as w}from"../grants/mirror.js";import{uidForApp as N}from"../spaces/users.js";const u=r(n=>l("sha256").update(n).digest("hex"),"hash");async function S(n,e,o,i){const t=await n.prepare("SELECT grantee, sub, grant_id, client_id, scopes_json, run_id FROM node_rows WHERE node_id = ?").get(o);if(!t)throw new Error(`cannot mint node token: missing node ${o}`);const a=t.run_id&&t.run_id!==o?await n.prepare("SELECT sub, grant_id, client_id FROM nodes WHERE node_id = ?").get(t.run_id):void 0,s=a?.sub??t.sub;if(s==null)throw new Error(`cannot mint node token: node ${o} has no person (null sub)`);const c=t.grantee==="app:terminal"?await w(s):null;if(t.grantee==="app:terminal"&&!c)throw new Error("cannot mint node token: terminal grant is not active");const p=c?.id??a?.grant_id??t.grant_id??null,_=g(32).toString("base64url");if(!await n.prepare("SELECT 1 AS ok FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'launching'").get(e,o))throw new Error(`cannot mint node token: execution ${e} is not launching`);return await n.prepare('INSERT INTO node_tokens (broker_process_id, node_id, token_hash, grantee, uid, sub, "grant", client_id, scopes_json, issued_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)').run(e,o,u(_),t.grantee,await N(t.grantee),s,p,a?.client_id??t.client_id,t.scopes_json,i),_}r(S,"mintNodeToken");const R=r(async(n,e)=>await k(o=>S(o,n,e,new Date().toISOString())),"mintExecutionToken");async function D(n){if(!/^[A-Za-z0-9_-]{43}$/.test(n))return null;const e=await(await d()).prepare(`SELECT t.node_id, t.grantee, t.uid, t.sub, t."grant", t.client_id, t.scopes_json, n.run_id
|
|
2
2
|
FROM node_tokens t JOIN executions e ON e.execution_id = t.broker_process_id
|
|
3
3
|
JOIN nodes n ON n.node_id = t.node_id
|
|
4
|
-
WHERE t.token_hash = ? AND t.revoked_at IS NULL AND e.state != 'exited'`).get(
|
|
5
|
-
AND broker_process_id IN (SELECT execution_id FROM executions WHERE daemon_epoch IS DISTINCT FROM ?)`).run(new Date().toISOString(),n)}r(
|
|
4
|
+
WHERE t.token_hash = ? AND t.revoked_at IS NULL AND e.state != 'exited'`).get(u(n));return e?{app:e.grantee,node:e.node_id,run:e.run_id,uid:e.uid,sub:e.sub,grant:e.grant,client_id:e.client_id,scopes:e.scopes_json===null?null:JSON.parse(e.scopes_json)}:null}r(D,"resolveNodeToken");async function b(n){await h(await d(),"broker_process_id",n,new Date().toISOString())}r(b,"revokeExitedNodeToken");async function v(n){await(await d()).prepare(`UPDATE node_tokens SET revoked_at = ? WHERE revoked_at IS NULL
|
|
5
|
+
AND broker_process_id IN (SELECT execution_id FROM executions WHERE daemon_epoch IS DISTINCT FROM ?)`).run(new Date().toISOString(),n)}r(v,"revokePriorEpochNodeTokens");async function h(n,e,o,i){await n.prepareUncached(`UPDATE node_tokens SET revoked_at = ? WHERE ${e} = ? AND revoked_at IS NULL`).run(i,o)}r(h,"revokeNodeTokens");export{R as mintExecutionToken,S as mintNodeToken,D as resolveNodeToken,b as revokeExitedNodeToken,h as revokeNodeTokens,v as revokePriorEpochNodeTokens};
|
|
@@ -9,8 +9,8 @@ export declare class PersonOutsideRequestError extends Error {
|
|
|
9
9
|
readonly code = "person_outside_request";
|
|
10
10
|
constructor();
|
|
11
11
|
}
|
|
12
|
-
/** crtrd
|
|
13
|
-
export declare function
|
|
12
|
+
/** A CLI, viewer or launch-config subprocess binds the one person it acts for (the person its settings answer named). A crtrd process never calls this: it reads the person from the request or the row it serves. */
|
|
13
|
+
export declare function bindClientPerson(id: string): void;
|
|
14
14
|
/** crtrd calls this at boot on a cloud role, instead of resolving a person: from then on a person read outside a request throws. */
|
|
15
15
|
export declare function markCloudRole(): void;
|
|
16
16
|
/** Whether this process is a cloud role (`markCloudRole` ran at boot). */
|
|
@@ -20,10 +20,8 @@ export declare function markEnginesInProcess(): void;
|
|
|
20
20
|
export declare function areEnginesInProcess(): boolean;
|
|
21
21
|
/** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
|
|
22
22
|
export declare function runAsPerson<T>(person: string, fn: () => T): T;
|
|
23
|
-
/** The request's person; else
|
|
24
|
-
* `PersonUnresolvedError` when
|
|
23
|
+
/** The request's person; else the person a CLI-side process bound. Throws `PersonOutsideRequestError` on a cloud role outside a request and
|
|
24
|
+
* `PersonUnresolvedError` when no client-bound person exists. Tests and non-daemon processes use `personIdAsync()`. */
|
|
25
25
|
export declare function personId(): string;
|
|
26
|
-
/** The
|
|
27
|
-
export declare function bootPersonId(): string | undefined;
|
|
28
|
-
/** The request's person, if any (for `personIdAsync`). */
|
|
26
|
+
/** The request's person, if any. */
|
|
29
27
|
export declare function requestPersonId(): string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{AsyncLocalStorage as
|
|
1
|
+
var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{AsyncLocalStorage as c}from"node:async_hooks";class d extends Error{static{e(this,"PersonUnresolvedError")}code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}}class l extends Error{static{e(this,"PersonOutsideRequestError")}code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}}let o,t=!1;const s=new c;function a(r){o=r}e(a,"bindClientPerson");function x(){t=!0}e(x,"markCloudRole");function P(){return t}e(P,"isCloudRole");let u=!1;function E(){u=!0}e(E,"markEnginesInProcess");function m(){return u}e(m,"areEnginesInProcess");function q(r,n){return s.run(r,n)}e(q,"runAsPerson");function g(){const r=s.getStore();if(r!==void 0)return r;if(t)throw new l;if(o===void 0)throw new d;return o}e(g,"personId");function h(){return s.getStore()}e(h,"requestPersonId");export{l as PersonOutsideRequestError,d as PersonUnresolvedError,m as areEnginesInProcess,a as bindClientPerson,P as isCloudRole,x as markCloudRole,E as markEnginesInProcess,g as personId,h as requestPersonId,q as runAsPerson};
|
|
@@ -1,31 +1,4 @@
|
|
|
1
|
-
import { PersonUnresolvedError, PersonOutsideRequestError,
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export { LEGACY_LOCAL_PERSON };
|
|
5
|
-
export type PersonSource = 'stored' | 'joined' | 'grants';
|
|
6
|
-
export { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId };
|
|
7
|
-
/** As `personId()`, but a process that is not the daemon gets a lazy get-or-create keyed by the active canvas database. */
|
|
1
|
+
import { PersonUnresolvedError, PersonOutsideRequestError, bindClientPerson, markCloudRole, isCloudRole, runAsPerson, personId } from './person-state.js';
|
|
2
|
+
export { PersonUnresolvedError, PersonOutsideRequestError, bindClientPerson, markCloudRole, isCloudRole, runAsPerson, personId };
|
|
3
|
+
/** `personId()` for an async caller. */
|
|
8
4
|
export declare function personIdAsync(): Promise<string>;
|
|
9
|
-
/** Get-or-create the person and say where it came from. Order: stored, the join file's owner, the single `sub` of the
|
|
10
|
-
* mirrored grants (a runtime with an issuer and no join file), else null (nothing is stored): no person is ever minted. */
|
|
11
|
-
export declare function resolvePerson(): Promise<{
|
|
12
|
-
id: string;
|
|
13
|
-
source: PersonSource;
|
|
14
|
-
} | null>;
|
|
15
|
-
export declare function resolvePersonId(): Promise<string | null>;
|
|
16
|
-
type Counts = Record<string, number>;
|
|
17
|
-
/** Replace person `from` with `to` in every known column, inside the caller's `withCanvasWrite` transaction. Idempotent.
|
|
18
|
-
* Rows keyed by the principal merge on collision. Returns rows changed per column. */
|
|
19
|
-
export declare function substitutePerson(db: CanvasDb, from: string, to: string): Promise<Counts>;
|
|
20
|
-
export interface RetireResult {
|
|
21
|
-
person: string;
|
|
22
|
-
/** The join reconcile (part A) ran: the person changed from the stored one to the join file's owner. */
|
|
23
|
-
joinedFrom: string | null;
|
|
24
|
-
/** The legacy retire (part B) ran. */
|
|
25
|
-
retired: boolean;
|
|
26
|
-
/** Rows changed per column (zeros omitted). */
|
|
27
|
-
columns: Counts;
|
|
28
|
-
}
|
|
29
|
-
/** The boot step (flow 2), one transaction. Part A applies a join that landed after the person was minted; part B retires the
|
|
30
|
-
* legacy local person once per person; part C installs the local terminal grant on a runtime without an issuer. */
|
|
31
|
-
export declare function retireLocalPerson(): Promise<RetireResult>;
|
|
@@ -1,11 +1 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
3
|
-
AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of X)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+a(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const s=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=a(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
|
|
4
|
-
AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
|
|
5
|
-
AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(s,p))+a(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,s)),t["relations.written_by"]=a(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=a(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of Z)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of V){const l=a(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+a(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));l!==0&&(t[`${o}.person`]=l)}const u=a(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await Q(n,e))&&(await q(n,e,r),t["charge_totals.rebuilt"]=1),t}c(P,"substitutePerson");async function ee(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
|
|
6
|
-
WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?a(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await F(n,"app:terminal")).id)):0)+a(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+a(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(ee,"rewriteLegacyGrantees");async function ne(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),s=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=a(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t)),p["node_tokens.grant"]=a(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${s})`).run(r,...t)),p["crons.grant_id"]=a(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=a(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
|
|
7
|
-
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
8
|
-
AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${s})`).run(...r===null?[]:[r],...t)),p}c(ne,"repointGrantReferences");async function _e(){const n=await j(async e=>{const r={},t=c((_,w="")=>{for(const[m,f]of Object.entries(_))f!==0&&(r[w+m]=(r[w+m]??0)+f)},"add");let s=await T(e,d);if(s===null)throw new R;let p=null;const u=h();u!==null&&u!==s&&(t(await P(e,s,u),"join."),await g(e,d,u),p=s,s=u);const o=k()??S("user").runtime?.issuer,i=await T(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const l=await T(e,O)!==s;if(l){t({legacy_grantees:await ee(e)}),t(await P(e,E,s));const _=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
|
|
9
|
-
WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${_} LIMIT 1`).get()!==void 0){const w=await x(e,"person","user",s,"user");t({repaired_stubs:a(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${_})`).run(w.id))})}t({"nodes.sub_null_terminal":a(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
|
|
10
|
-
SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
|
|
11
|
-
WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(s))}),t(await ne(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await M(e)}),await g(e,O,s)}return o||await C(i,s),{person:s,joinedFrom:p,retired:l,columns:r}});return y(n.person),n}c(_e,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,R as PersonUnresolvedError,D as isCloudRole,H as markCloudRole,v as personId,de as personIdAsync,B as resolvePerson,K as resolvePersonId,_e as retireLocalPerson,W as runAsPerson,y as setPersonId,P as substitutePerson};
|
|
1
|
+
var s=Object.defineProperty;var r=(e,n)=>s(e,"name",{value:n,configurable:!0});import{PersonUnresolvedError as t,PersonOutsideRequestError as d,bindClientPerson as u,markCloudRole as i,isCloudRole as l,runAsPerson as p,personId as o}from"./person-state.js";async function m(){return o()}r(m,"personIdAsync");export{d as PersonOutsideRequestError,t as PersonUnresolvedError,u as bindClientPerson,l as isCloudRole,i as markCloudRole,o as personId,m as personIdAsync,p as runAsPerson};
|
package/dist/core/config.d.ts
CHANGED
|
@@ -178,7 +178,10 @@ export interface MergedLaunchConfig {
|
|
|
178
178
|
* the target node's) MUST pass the target's own cwd/profile explicitly, or
|
|
179
179
|
* `spawnEnv.allow` resolves from the wrong scope entirely (the C-1
|
|
180
180
|
* follow-up fix this parameterization exists for). */
|
|
181
|
-
export declare function readMergedLaunchConfig(targetCwd?: string, targetProfileId?: string | null): MergedLaunchConfig;
|
|
181
|
+
export declare function readMergedLaunchConfig(targetCwd?: string | null, targetProfileId?: string | null): MergedLaunchConfig;
|
|
182
|
+
/** The launch config a process holding the project's files adds on top of a recipe's config, which a cloud control plane built without them:
|
|
183
|
+
* the project stack's kinds (and the kinds its enabled plugins declare) in `cwd`, over the recipe's kinds. */
|
|
184
|
+
export declare function overlayProjectLaunchConfig(base: MergedLaunchConfig, cwd: string, profileId: string | null): MergedLaunchConfig;
|
|
182
185
|
/** The effective `KindConfig` for one full kind string (top-level, e.g.
|
|
183
186
|
* `developer`, or sub-kind, e.g. `audit/security`), across
|
|
184
187
|
* project > user > builtin precedence. Returns `undefined` for a kind no
|
package/dist/core/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Je=Object.defineProperty;var s=(e,n)=>Je(e,"name",{value:n,configurable:!0});import{envProfileId as Ve}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Ze,mkdirSync as Ye,statSync as Xe}from"node:fs";import{isDeepStrictEqual as Qe}from"node:util";import{CONFIG_FILE as en,STATE_FILE as nn,VERBOSITY_LEVELS as tn,MOUSE_MODE_DEFAULTS as on,WHIP_MESSAGE_MODES as rn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as sn,defaultKindsConfig as cn,defaultRemoteCanvasConfig as un}from"../types.js";import{BINDING_CATALOG as an,BINDING_IDS as dn,isAttachPaneBinding as fn}from"./keybindings/catalog.js";import{notFound as ln}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as pn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as mn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as gn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as ae}from"./installed-plugins.js";import{profileDir as de,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as yn,readCachedSettings as B,readCachedState as hn,revisionOf as E,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as pe,splitUserSettingsWrite as bn,withAppInstalls as me}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as vn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as _n}from"./user-settings.js";import{normalizeWorkingGerunds as wn}from"../shared/working-activity.js";import{mergePageComponentLayers as kn,normalizePageComponents as ge}from"./human/page-catalog.js";function h(e){return re(e,en)}s(h,"configPathFor");function H(e,n){return vn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,nn)}s(J,"statePathFor");function wt(e){const n=g(e);return n?h(n):null}s(wt,"configPath");function kt(e){const n=g(e);return n?J(n):null}s(kt,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(de(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ue()))return O(h(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&pe()?me(yn(),o):o}s(P,"readRawAtRoot");async function ye(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&pe(),c=n(structuredClone((i?me(t,r??null):r)??{}));return o=c.value,i?bn(t,c.next,E(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:E(r)}]}),o}s(ye,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>q(t,n,{createParent:!1}));return}await ye(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function At(e){I[T]=e}s(At,"installBrokerConfigSnapshot");function St(){return I[T]}s(St,"brokerConfigSnapshot");function An(e){const n=I[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?Sn(o):w()}s(An,"readConfig");function Sn(e){const n=P(e);return n?z(n):w()}s(Sn,"readConfigAtRoot");function jn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(jn,"readProjectState");function xn(e){const n=g(e);return n?e==="project"?Ze(n)?jn(n):se():hn(S(n).key):se()}s(xn,"readState");class Rn extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function he(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw ln(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(he,"rawSettingsKeyForTarget");function jt(e){return B(he(e))}s(jt,"readRawSettingsForTarget");async function xt(e,n,o){const t=he(e);try{z(n)}catch(u){throw new Rn(u)}if(B(t).revision!==o)throw new le;const i=await W(u=>E(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=E(i.settings[t]);return{revision:c,changed:c!==o}}s(xt,"replaceRawSettingsForTarget");async function Rt(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Rt,"updateRawConfigAtomically");async function Ot(e,n){await V(k(e),n)}s(Ot,"writeConfig");async function Et(e,n){await V(k(e),n)}s(Et,"writeRawConfig");function On(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(On,"writeProjectState");async function En(e,n){const o=k(e);if(e==="project"){On(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(En,"writeState");async function Pt(e,n){if(e!=="project"){mn(n);return}try{Ye(n)}catch(o){if(o.code!=="EEXIST"||!Xe(n).isDirectory())throw o}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Pt,"ensureScopeInitialized");function Pn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(Pn,"normalizeKeybindings");const In=new Set(an.filter(fn).map(e=>e.id)),Tn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);function Cn(e){return e===void 0?[...Tn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&dn.has(n)&&In.has(n)))]:[]}s(Cn,"normalizeTmuxPassthrough");function C(e,n=sn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,a]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof a=="string"&&(r[i][u]=a)}return r}s(C,"mergeModelLadders");function be(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(be,"validStrength");const Z=["ultra","strong","medium","light"];function Y(){return Object.create(null)}s(Y,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function ve(e){const n=Y();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(ve,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const o=ve(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let a;for(const f of["family","credentialSource","providerId"]){const d=i[f];if(d!==void 0){if(typeof d!="string"||d.trim()===""){a=`${f} must be a non-empty string`;break}u[f]=d}}if(a===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))a="models must be an object";else{const f={...c?.models};for(const[d,l]of Object.entries(i.models)){if(!be(d)){a=`models.${d} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){a=`models.${d} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){a=`models.${d} must be provider/id`;break}f[d]=l}u.models=f}if(a===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,d]of Object.entries(u.models))if(d.slice(0,d.indexOf("/"))!==u.providerId){a=`models.${f} provider prefix must equal providerId`;break}}if(a!==void 0){R(t,a);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function _e(e){const n=Y(),o=Y();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Z.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(_e,"resolveModelRoutes");function $n(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Z.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Z){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s($n,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>be(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Mn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Mn,"isInheritAllGlob");function N(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Mn(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(N,"mergeSpawnEnv");function L(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(L,"mergeProviderOptions");const we=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Nn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Nn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!we.test(e))return`${n}.${e} is not a safe bare command name (expected ${we.source})`}s(F,"bareCommandNameIssue");function Ln(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Ln,"binDeclarationIssues");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Fn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(ke.test(o)||r.push(`action name must match ${ke.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(Dn,"humanActionDeclarationIssues");function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Dn(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(Un,"normalizeHumanActions");function It(e){return Ln(e).map(n=>n.message)}s(It,"invalidPluginBinReasons");function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s(Tt,"normalizeRequires");function Ct(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Ct,"invalidPluginRequiresReasons");function Ae(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Ae,"normalizeKindFields");function b(e,n=cn()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Ae(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(b,"mergeKinds");let D;function $t(e){D=e}s($t,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,a)=>u.localeCompare(a)))i=b(D[c],i);return i}if(n===null)return o;const t=ae(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=b(i.manifest.kinds,r);return r}s(Se,"layerPluginKinds");function Mt(){const e=[{origin:"config.json",components:An("user").page_components}],n=g("user");if(n!==null){const o=ae("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ge(t.manifest.page_components,r)})}}return kn(e)}s(Mt,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Ae(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Nt,"invalidPluginKindsReasons");function zn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(zn,"normalizeRemoteCanvasTarget");function Kn(e,n=un()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=zn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Kn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function U(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(U,"normalizePositiveInteger");function Gn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=U(o.warning,n.warning),r=U(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Gn,"mergeBrokerThresholds");function qn(e,n){return{unattendedParkMs:U((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(qn,"mergeLifecycle");function Bn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...ie]}s(Bn,"normalizeWhipMessages");function Wn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Wn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(pn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,a={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,d=U(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=Gn(e.brokerThresholds,n.brokerThresholds),y=qn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:wn(e.working_gerunds),Oe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Ee=ge(e.page_components),Pe=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Ie=Bn(e.whip_messages),Te=rn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ce=on.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=tn.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Le=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Fe=Pn(e.keybindings),De=Cn(e.tmux_passthrough),Ue=C(e.modelLadders),ze=L(e.providerOptions,n.providerOptions),G=_e($(e.modelRoutes)),Q=G.complete,ee=M(e.modelRouting,void 0),Ke=b(e.kinds),Ge=Kn(e.remoteCanvas),qe=Wn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const Be=N(e.spawnEnv,n.spawnEnv?.allow),We=Fn(e.bin),He=Un(e.humanActions);return{bin:We,humanActions:He,schema_version:o,marketplaces:t,plugins:r,auto_update:a,max_panes_per_window:d,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:K,working_gerunds:m,whip_mode:Oe,page_components:Ee,page_surface:Pe,whip_messages:Ie,whip_message_mode:Te,mouse_mode_default:Ce,bash_tool_purpose:$e,verbosity:Me,detailed_tool_recaps:Ne,document_port:Le,keybindings:Fe,tmux_passthrough:De,modelLadders:Ue,providerOptions:ze,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ke,remoteCanvas:Ge,api:qe,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:Be}}s(z,"mergeConfig");function Hn(e){return P(e)}s(Hn,"readRawConfigAtRoot");function Jn(e){const n=g(e);return n?Hn(n):null}s(Jn,"readRawScopeConfig");function Vn(e){if(e===null||e==="")return null;try{return P(de(e))}catch{return null}}s(Vn,"readRawProfileConfig");function Zn(e,n){return[...gn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Zn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ve()||null){const o=I[T];if(o)return o.launch;const t=w(),r=Jn("user"),i=Vn(n),c=Zn(e,n);let u=b(r?.kinds,Se("user",g("user"),t.kinds)),a=C(r?.modelLadders,t.modelLadders),f=L(r?.providerOptions,t.providerOptions),d=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=N(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),a=C(i.modelLadders,a),f=L(i.providerOptions,f),d=$(i.modelRoutes,d),l=M(i.modelRouting,l),p=N(i.spawnEnv,p.allow));for(const{root:K,raw:m}of c)u=b(m?.kinds,Se("project",K,u)),m!==null&&(a=C(m.modelLadders,a),f=L(m.providerOptions,f),d=$(m.modelRoutes,d),l=M(m.modelRouting,l),p=N(m.spawnEnv,p.allow));const y=_e(d);return{kinds:u,modelLadders:a,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Re,"readMergedLaunchConfig");function Lt(e){return Re().kinds[e]}s(Lt,"resolveKindConfig");function Ft(e){const n=Re().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Ft,"subKindsAvailableTo");function Yn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Yn,"sparseModelLaddersToPersist");async function Xn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of _n)u!=="modelLadders"&&!Qe(r[u],t[u])&&(i[u]=r[u]);const c=Yn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Xn,"mutateConfigAtRoot");async function Dt(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(Dt,"persistModelLadders");async function Ut(e,n,o){if(o!==void 0)$n(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=ve(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Ut,"persistModelRoute");async function Qn(e,n){return await Xn(e,n)}s(Qn,"updateConfigAtRoot");async function zt(e,n){return await Qn(k(e),n)}s(zt,"updateConfig");async function Kt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:h(e.root),field:n}}s(Kt,"persistDefaultKindModel");async function Gt(e,n){const o=xn(e);return n(o),await En(e,o),o}s(Gt,"updateState");export{Tn as DEFAULT_TMUX_PASSTHROUGH,Rn as InvalidRawSettingsError,Ln as binDeclarationIssues,St as brokerConfigSnapshot,wt as configPath,Pt as ensureScopeInitialized,Dn as humanActionDeclarationIssues,At as installBrokerConfigSnapshot,It as invalidPluginBinReasons,Nt as invalidPluginKindsReasons,Ct as invalidPluginRequiresReasons,Fn as normalizeBin,Un as normalizeHumanActions,Tt as normalizeRequires,Cn as normalizeTmuxPassthrough,Kt as persistDefaultKindModel,Dt as persistModelLadders,Ut as persistModelRoute,An as readConfig,Sn as readConfigAtRoot,Re as readMergedLaunchConfig,Hn as readRawConfigAtRoot,Jn as readRawScopeConfig,jt as readRawSettingsForTarget,xn as readState,xt as replaceRawSettingsForTarget,Lt as resolveKindConfig,Mt as resolvePageComponents,$t as setAppPluginKinds,kt as statePath,Ft as subKindsAvailableTo,zt as updateConfig,Qn as updateConfigAtRoot,Rt as updateRawConfigAtomically,Gt as updateState,Ot as writeConfig,Et as writeRawConfig,En as writeState};
|
|
1
|
+
var Ve=Object.defineProperty;var s=(e,n)=>Ve(e,"name",{value:n,configurable:!0});import{envProfileId as Ze}from"../shared/env.js";import{basename as re,join as ie}from"node:path";import{existsSync as Ye,mkdirSync as Xe,statSync as Qe}from"node:fs";import{isDeepStrictEqual as en}from"node:util";import{CONFIG_FILE as nn,STATE_FILE as tn,VERBOSITY_LEVELS as on,MOUSE_MODE_DEFAULTS as rn,WHIP_MESSAGE_MODES as sn,DEFAULT_WHIP_MESSAGES as se,defaultScopeConfig as w,defaultScopeState as ce,defaultModelLaddersConfig as cn,defaultKindsConfig as un,defaultRemoteCanvasConfig as an}from"../types.js";import{BINDING_CATALOG as dn,BINDING_IDS as fn,isAttachPaneBinding as ln}from"./keybindings/catalog.js";import{notFound as pn}from"./errors.js";import{emitEvent as ue}from"./events/emit.js";import{LEDGER_ENV as mn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as gn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as yn,userScopeRoot as ae}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as fe,listProfiles as le}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as hn,readCachedSettings as B,readCachedState as bn,revisionOf as E,SettingsRevisionConflictError as pe,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as me,splitUserSettingsWrite as vn,withAppInstalls as ge}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as _n}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as wn}from"./user-settings.js";import{normalizeWorkingGerunds as kn}from"../shared/working-activity.js";import{mergePageComponentLayers as An,normalizePageComponents as ye}from"./human/page-catalog.js";function b(e){return ie(e,nn)}s(b,"configPathFor");function H(e,n){return _n(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return ie(e,tn)}s(J,"statePathFor");function wt(e){const n=g(e);return n?b(n):null}s(wt,"configPath");function kt(e){const n=g(e);return n?J(n):null}s(kt,"statePath");function S(e){const n=A(e),o=A(ae());if(n===o)return{key:"user",kind:"user",root:o};if(re(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of le()){const r=A(fe(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(re(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ae()))return O(b(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&me()?ge(hn(),o):o}s(P,"readRawAtRoot");async function he(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&me(),c=n(structuredClone((i?ge(t,r??null):r)??{}));return o=c.value,i?vn(t,c.next,E(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:E(r)}]}),o}s(he,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(b(o.root),t=>q(t,n,{createParent:!1}));return}await he(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(b(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await he(o.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function At(e){I[T]=e}s(At,"installBrokerConfigSnapshot");function St(){return I[T]}s(St,"brokerConfigSnapshot");function Sn(e){const n=I[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?jn(o):w()}s(Sn,"readConfig");function jn(e){const n=P(e);return n?z(n):w()}s(jn,"readConfigAtRoot");function xn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(xn,"readProjectState");function Rn(e){const n=g(e);return n?e==="project"?Ye(n)?xn(n):ce():bn(S(n).key):ce()}s(Rn,"readState");class On extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function be(e){if(e.scope==="user")return"user";if(!le().some(n=>n.profileId===e.profileId))throw pn(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(be,"rawSettingsKeyForTarget");function jt(e){return B(be(e))}s(jt,"readRawSettingsForTarget");async function xt(e,n,o){const t=be(e);try{z(n)}catch(u){throw new On(u)}if(B(t).revision!==o)throw new pe;const i=await W(u=>E(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new pe})()),c=E(i.settings[t]);return{revision:c,changed:c!==o}}s(xt,"replaceRawSettingsForTarget");async function Rt(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Rt,"updateRawConfigAtomically");async function Ot(e,n){await V(k(e),n)}s(Ot,"writeConfig");async function Et(e,n){await V(k(e),n)}s(Et,"writeRawConfig");function En(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(En,"writeProjectState");async function Pn(e,n){const o=k(e);if(e==="project"){En(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(Pn,"writeState");async function Pt(e,n){if(e!=="project"){gn(n);return}try{Xe(n)}catch(o){if(o.code!=="EEXIST"||!Qe(n).isDirectory())throw o}O(b(n))===null&&await V(n,{schema_version:w().schema_version})}s(Pt,"ensureScopeInitialized");function In(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(In,"normalizeKeybindings");const Tn=new Set(dn.filter(ln).map(e=>e.id)),Cn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);function $n(e){return e===void 0?[...Cn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&fn.has(n)&&Tn.has(n)))]:[]}s($n,"normalizeTmuxPassthrough");function C(e,n=cn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,a]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof a=="string"&&(r[i][u]=a)}return r}s(C,"mergeModelLadders");function ve(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(ve,"validStrength");const Z=["ultra","strong","medium","light"];function Y(){return Object.create(null)}s(Y,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function _e(e){const n=Y();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(_e,"copyRouteRecord");function R(e,n){ue({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const o=_e(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let a;for(const f of["family","credentialSource","providerId"]){const d=i[f];if(d!==void 0){if(typeof d!="string"||d.trim()===""){a=`${f} must be a non-empty string`;break}u[f]=d}}if(a===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))a="models must be an object";else{const f={...c?.models};for(const[d,l]of Object.entries(i.models)){if(!ve(d)){a=`models.${d} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){a=`models.${d} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){a=`models.${d} must be provider/id`;break}f[d]=l}u.models=f}if(a===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,d]of Object.entries(u.models))if(d.slice(0,d.indexOf("/"))!==u.providerId){a=`models.${f} provider prefix must equal providerId`;break}}if(a!==void 0){R(t,a);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function we(e){const n=Y(),o=Y();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Z.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(we,"resolveModelRoutes");function Mn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Z.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Z){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s(Mn,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>ve(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Ln(e){return e!==""&&e.replace(/\*/g,"")===""}s(Ln,"isInheritAllGlob");function L(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Ln(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(L,"mergeSpawnEnv");function N(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(N,"mergeProviderOptions");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Nn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Nn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!ke.test(e))return`${n}.${e} is not a safe bare command name (expected ${ke.source})`}s(F,"bareCommandNameIssue");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Fn,"binDeclarationIssues");function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Dn,"normalizeBin");const Ae=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(Ae.test(o)||r.push(`action name must match ${Ae.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(Un,"humanActionDeclarationIssues");function zn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Un(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(zn,"normalizeHumanActions");function It(e){return Fn(e).map(n=>n.message)}s(It,"invalidPluginBinReasons");function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s(Tt,"normalizeRequires");function Ct(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Ct,"invalidPluginRequiresReasons");function Se(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Se,"normalizeKindFields");function y(e,n=un()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Se(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(y,"mergeKinds");let D;function $t(e){D=e}s($t,"setAppPluginKinds");function X(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,a)=>u.localeCompare(a)))i=y(D[c],i);return i}if(n===null)return o;const t=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=y(i.manifest.kinds,r);return r}s(X,"layerPluginKinds");function Mt(){const e=[{origin:"config.json",components:Sn("user").page_components}],n=g("user");if(n!==null){const o=de("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ye(t.manifest.page_components,r)})}}return An(e)}s(Mt,"resolvePageComponents");const Q=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Lt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))Q.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...Q].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Se(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...Q].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Lt,"invalidPluginKindsReasons");function Kn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(Kn,"normalizeRemoteCanvasTarget");function Gn(e,n=an()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=Kn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Gn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function U(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(U,"normalizePositiveInteger");function qn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=U(o.warning,n.warning),r=U(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(qn,"mergeBrokerThresholds");function Bn(e,n){return{unattendedParkMs:U((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Bn,"mergeLifecycle");function Wn(e){if(!Array.isArray(e))return[...se];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...se]}s(Wn,"normalizeWhipMessages");function Hn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Hn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ue({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(mn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,a={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,d=U(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=qn(e.brokerThresholds,n.brokerThresholds),h=Bn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:kn(e.working_gerunds),Ee=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Pe=ye(e.page_components),Ie=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Te=Wn(e.whip_messages),Ce=sn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,$e=rn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,Me=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Le=on.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Fe=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,De=In(e.keybindings),Ue=$n(e.tmux_passthrough),ze=C(e.modelLadders),Ke=N(e.providerOptions,n.providerOptions),G=we($(e.modelRoutes)),ee=G.complete,ne=M(e.modelRouting,void 0),Ge=y(e.kinds),qe=Gn(e.remoteCanvas),Be=Hn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const te=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(oe=>Number.isSafeInteger(oe)&&oe>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const We=L(e.spawnEnv,n.spawnEnv?.allow),He=Dn(e.bin),Je=zn(e.humanActions);return{bin:He,humanActions:Je,schema_version:o,marketplaces:t,plugins:r,auto_update:a,max_panes_per_window:d,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:h,completion_bell:K,working_gerunds:m,whip_mode:Ee,page_components:Pe,page_surface:Ie,whip_messages:Te,whip_message_mode:Ce,mouse_mode_default:$e,bash_tool_purpose:Me,verbosity:Le,detailed_tool_recaps:Ne,document_port:Fe,keybindings:De,tmux_passthrough:Ue,modelLadders:ze,providerOptions:Ke,...Object.keys(ee).length>0?{modelRoutes:ee}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ne!==void 0?{modelRouting:ne}:{},kinds:Ge,remoteCanvas:qe,api:Be,...v?{paths:v}:{},...te?{store:te}:{},..._?{runtime:_}:{},spawnEnv:We}}s(z,"mergeConfig");function Jn(e){return P(e)}s(Jn,"readRawConfigAtRoot");function Vn(e){const n=g(e);return n?Jn(n):null}s(Vn,"readRawScopeConfig");function Zn(e){if(e===null||e==="")return null;try{return P(fe(e))}catch{return null}}s(Zn,"readRawProfileConfig");function Re(e,n){return e===null?[]:[...yn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Re,"readRawProjectScopeConfigs");function Oe(e=process.cwd(),n=Ze()||null){const o=I[T];if(o)return o.launch;const t=w(),r=Vn("user"),i=Zn(n),c=Re(e,n);let u=y(r?.kinds,X("user",g("user"),t.kinds)),a=C(r?.modelLadders,t.modelLadders),f=N(r?.providerOptions,t.providerOptions),d=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=L(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=y(i.kinds,u),a=C(i.modelLadders,a),f=N(i.providerOptions,f),d=$(i.modelRoutes,d),l=M(i.modelRouting,l),p=L(i.spawnEnv,p.allow));for(const{root:K,raw:m}of c)u=y(m?.kinds,X("project",K,u)),m!==null&&(a=C(m.modelLadders,a),f=N(m.providerOptions,f),d=$(m.modelRoutes,d),l=M(m.modelRouting,l),p=L(m.spawnEnv,p.allow));const h=we(d);return{kinds:u,modelLadders:a,providerOptions:f,...Object.keys(h.complete).length>0?{modelRoutes:h.complete}:{},...Object.keys(h.legacy).length>0?{legacyModelRoutes:h.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Oe,"readMergedLaunchConfig");function Nt(e,n,o){let t=e.kinds;for(const{root:r,raw:i}of Re(n,o))t=y(i?.kinds,X("project",r,t));return{...e,kinds:t}}s(Nt,"overlayProjectLaunchConfig");function Ft(e){return Oe().kinds[e]}s(Ft,"resolveKindConfig");function Dt(e){const n=Oe().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Dt,"subKindsAvailableTo");function Yn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Yn,"sparseModelLaddersToPersist");async function Xn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of wn)u!=="modelLadders"&&!en(r[u],t[u])&&(i[u]=r[u]);const c=Yn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Xn,"mutateConfigAtRoot");async function Ut(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(Ut,"persistModelLadders");async function zt(e,n,o){if(o!==void 0)Mn(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=_e(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(zt,"persistModelRoute");async function Qn(e,n){return await Xn(e,n)}s(Qn,"updateConfigAtRoot");async function Kt(e,n){return await Qn(k(e),n)}s(Kt,"updateConfig");async function Gt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:b(e.root),field:n}}s(Gt,"persistDefaultKindModel");async function qt(e,n){const o=Rn(e);return n(o),await Pn(e,o),o}s(qt,"updateState");export{Cn as DEFAULT_TMUX_PASSTHROUGH,On as InvalidRawSettingsError,Fn as binDeclarationIssues,St as brokerConfigSnapshot,wt as configPath,Pt as ensureScopeInitialized,Un as humanActionDeclarationIssues,At as installBrokerConfigSnapshot,It as invalidPluginBinReasons,Lt as invalidPluginKindsReasons,Ct as invalidPluginRequiresReasons,Dn as normalizeBin,zn as normalizeHumanActions,Tt as normalizeRequires,$n as normalizeTmuxPassthrough,Nt as overlayProjectLaunchConfig,Gt as persistDefaultKindModel,Ut as persistModelLadders,zt as persistModelRoute,Sn as readConfig,jn as readConfigAtRoot,Oe as readMergedLaunchConfig,Jn as readRawConfigAtRoot,Vn as readRawScopeConfig,jt as readRawSettingsForTarget,Rn as readState,xt as replaceRawSettingsForTarget,Ft as resolveKindConfig,Mt as resolvePageComponents,$t as setAppPluginKinds,kt as statePath,Dt as subKindsAvailableTo,Kt as updateConfig,Qn as updateConfigAtRoot,Rt as updateRawConfigAtomically,qt as updateState,Ot as writeConfig,Et as writeRawConfig,Pn as writeState};
|