@north-light/cli 0.3.654 → 0.3.655
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/clients/attach/config.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +2 -3
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/render/chat-view.d.ts +41 -37
- package/dist/clients/attach/render/chat-view.js +3 -3
- package/dist/clients/attach/session/bindings.d.ts +1 -1
- package/dist/clients/attach/session/bindings.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +9 -9
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/slash/dispatch.d.ts +6 -8
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/viewer.js +514 -514
- package/dist/commands/node/create.js +1 -1
- package/dist/commands/sys/panels/prefs-panel.js +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/graph/documents.js +13 -11
- package/dist/core/graph/edges.js +4 -3
- package/dist/core/graph/exposures.js +7 -4
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/dto.d.ts +2 -0
- package/dist/core/graph/kinds/dto.js +1 -1
- package/dist/core/graph/names.d.ts +4 -0
- package/dist/core/graph/names.js +9 -8
- package/dist/core/graph/rules.d.ts +2 -0
- package/dist/core/graph/rules.js +3 -3
- package/dist/core/keybindings/catalog.d.ts +3 -3
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker/turn-replies.d.ts +1 -4
- package/dist/core/runtime/broker/turn-replies.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +2 -2
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +3 -0
- package/dist/core/substrate/delivery/corpus.js +2 -3
- package/dist/core/substrate/delivery/render-event.js +4 -4
- package/dist/core/user-settings.d.ts +13 -35
- package/dist/core/user-settings.js +1 -1
- package/dist/types.d.ts +13 -15
- package/dist/types.js +1 -1
- package/docs/cli/the-viewer.md +16 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -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 ie,profilesStateBlock as ae,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,i=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&&!i&&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(i&&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&&!i)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:i});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,...i?{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}:{},...i?{prefer_warm:!0}:{},request_key:L};let a;try{a=await H().createNode(j)}catch(r){W(r)||$(r);try{a=await H().createNode(j)}catch(q){pe(q,L)}}N("node_new.node_created",{node:a.node_id});let x={};i&&(x=ce(a.node_id,a.cwd,a.name)),i&&N("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:x.window,session:x.session,follow_up:i?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, but no broker started because capacity (broker slots or the app's memory) is full. It is frozen and will launch when capacity 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:ie,flags:{profile:ae}},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(`
|
|
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
2
|
`)},"render")});export{me as childFollowUp,Le as nodeNew};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var p=(g,t)=>$(g,"name",{value:t,configurable:!0});import{truncateToWidth as l}from"@earendil-works/pi-tui";import{readConfig as b,updateConfig as w}from"../../../core/config.js";import{userSettingsInGroup as
|
|
1
|
+
var $=Object.defineProperty;var p=(g,t)=>$(g,"name",{value:t,configurable:!0});import{truncateToWidth as l}from"@earendil-works/pi-tui";import{readConfig as b,updateConfig as w}from"../../../core/config.js";import{userSettingsInGroup as y}from"../../../core/user-settings.js";import{padAnsi as u,theme as r,visibleRange as v,wrapText as d}from"../../../core/tui/panel.js";const x=26;class B{static{p(this,"PrefsPanel")}title;subtitle;onChange;rows;index=0;notice;constructor(t,e,o,s){this.title=e,this.subtitle=o,this.onChange=s,this.rows=y(t)}badge(){return String(this.rows.length)}handleInput(t,e){if(!e||this.rows.length===0)return!1;if(e("crtr.setup.list-down",t))this.index=(this.index+1)%this.rows.length;else if(e("crtr.setup.list-up",t))this.index=(this.index-1+this.rows.length)%this.rows.length;else if(e("crtr.setup.toggle",t)||e("crtr.setup.cell-next",t))this.cycle(1);else if(e("crtr.setup.cell-previous",t))this.cycle(-1);else return!1;return this.onChange(),!0}cycle(t){this.save(t)}async save(t){const e=this.rows[this.index];let o;try{o=await w("user",s=>e.cycle(s,t))}catch(s){this.notice=`Could not save: ${s instanceof Error?s.message:String(s)}`,this.onChange();return}this.notice=`Saved ${e.key} = ${e.format(o)}. ${e.applies}`,this.onChange()}render(t,e){const o=b("user"),s=Math.max(1,e-6),h=v(this.rows.length,this.index,s),i=[l(r.fg("accent",r.bold(this.title)),t),l(r.fg("dim",this.subtitle),t),""];for(let n=h.start;n<h.end;n+=1){const c=this.rows[n],a=(c.display??c.format)(o);if(n===this.index){const m=`\u25B8 ${u(c.label,x)} ${a}`;i.push(r.bg("selectedBg",u(m,t)))}else i.push(l(` ${u(c.label,x)} ${r.fg("success",a)}`,t))}(h.start>0||h.end<this.rows.length)&&i.push(l(r.fg("dim",` ${this.index+1}/${this.rows.length}`),t));const f=this.rows[this.index];if(f){i.push("");for(const n of d(f.description,Math.max(1,t-2)))i.push(l(r.fg("dim",` ${n}`),t))}if(this.notice){i.push("");for(const n of d(this.notice,t))i.push(l(r.fg("success",n),t))}return i}}export{B as PrefsPanel};
|
package/dist/core/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ye=Object.defineProperty;var s=(e,n)=>Ye(e,"name",{value:n,configurable:!0});import{envProfileId as Ve}from"../shared/env.js";import{basename as te,join as re}from"node:path";import{existsSync as Xe,mkdirSync as Qe,statSync as en}from"node:fs";import{isDeepStrictEqual as nn}from"node:util";import{CONFIG_FILE as on,STATE_FILE as tn,CONDENSED_HISTORY_MODES as rn,MOUSE_MODE_DEFAULTS as sn,WHIP_MESSAGE_MODES as cn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as un,defaultKindsConfig as dn,defaultRemoteCanvasConfig as an}from"../types.js";import{BINDING_CATALOG as fn,BINDING_IDS as ln,isAttachPaneBinding as mn}from"./keybindings/catalog.js";import{notFound as pn}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as gn}from"./ledger/rates.js";import{atomicWriteJson as G,readJsonIfExists as E,ensureDir as yn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as hn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as ae,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{readCachedSettings as q,readCachedState as bn,revisionOf as B,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{withExclusiveDirectoryLock as _n}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as vn}from"./user-settings.js";import{normalizeWorkingGerunds as wn}from"../shared/working-activity.js";import{mergePageComponentLayers as kn,normalizePageComponents as me}from"./human/page-catalog.js";function h(e){return re(e,on)}s(h,"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 re(e,tn)}s(J,"statePathFor");function vo(e){const n=g(e);return n?h(n):null}s(vo,"configPath");function wo(e){const n=g(e);return n?J(n):null}s(wo,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(te(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(ae(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(te(e)===".crouter"){let n;try{n=A(e)}catch(o){if(o.code==="ENOENT")return null;throw o}if(n!==A(ue()))return E(h(e))}return q(S(e).key).settings}s(P,"readRawAtRoot");async function pe(e,n){let o;return await W(t=>{const r=t.settings[e],i=n(structuredClone(r??{}));return o=i.value,[{op:"settings.replace",owner:e,raw:i.next,ifRevision:B(r)}]}),o}s(pe,"mutatePersonSettings");async function Z(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>G(t,n,{createParent:!1}));return}await pe(o.key,()=>({value:void 0,next:n}))}s(Z,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(E(t)??{});return G(t,r.next,{createParent:!1}),r.value}):await pe(o.key,n)}s(j,"mutateRawAtRoot");const C=globalThis,I=Symbol.for("crtr.broker.config-snapshot");function ko(e){C[I]=e}s(ko,"installBrokerConfigSnapshot");function Ao(){return C[I]}s(Ao,"brokerConfigSnapshot");function An(e){const n=C[I];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=E(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"?Xe(n)?jn(n):se():bn(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 ge(e){if(e.scope==="user")return"user";if(!fe().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(ge,"rawSettingsKeyForTarget");function So(e){return q(ge(e))}s(So,"readRawSettingsForTarget");async function jo(e,n,o){const t=ge(e);try{z(n)}catch(u){throw new Rn(u)}if(q(t).revision!==o)throw new le;const i=await W(u=>B(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=B(i.settings[t]);return{revision:c,changed:c!==o}}s(jo,"replaceRawSettingsForTarget");async function xo(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(xo,"updateRawConfigAtomically");async function Ro(e,n){await Z(k(e),n)}s(Ro,"writeConfig");async function Oo(e,n){await Z(k(e),n)}s(Oo,"writeRawConfig");function On(e,n){H(J(e),o=>G(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 Eo(e,n){if(e!=="project"){yn(n);return}try{Qe(n)}catch(o){if(o.code!=="EEXIST"||!en(n).isDirectory())throw o}E(h(n))===null&&await Z(n,{schema_version:w().schema_version})}s(Eo,"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 Cn=new Set(fn.filter(mn).map(e=>e.id));function In(e){return Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&ln.has(n)&&Cn.has(n)))]:[]}s(In,"normalizeTmuxPassthrough");function T(e,n=un()){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,d]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof d=="string"&&(r[i][u]=d)}return r}s(T,"mergeModelLadders");function ye(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(ye,"validStrength");const Y=["ultra","strong","medium","light"];function V(){return Object.create(null)}s(V,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function he(e){const n=V();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(he,"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=he(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 d;for(const f of["family","credentialSource","providerId"]){const a=i[f];if(a!==void 0){if(typeof a!="string"||a.trim()===""){d=`${f} must be a non-empty string`;break}u[f]=a}}if(d===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))d="models must be an object";else{const f={...c?.models};for(const[a,l]of Object.entries(i.models)){if(!ye(a)){d=`models.${a} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){d=`models.${a} must be a non-empty provider/id ref`;break}const m=l.indexOf("/");if(m<=0||m===l.length-1){d=`models.${a} must be provider/id`;break}f[a]=l}u.models=f}if(d===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,a]of Object.entries(u.models))if(a.slice(0,a.indexOf("/"))!==u.providerId){d=`models.${f} provider prefix must equal providerId`;break}}if(d!==void 0){R(t,d);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function be(e){const n=V(),o=V();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=Y.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(be,"resolveModelRoutes");function Tn(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=Y.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 Y){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(Tn,"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=>ye(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 $n(e){return e!==""&&e.replace(/\*/g,"")===""}s($n,"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($n(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 _e=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Mn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Mn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!_e.test(e))return`${n}.${e} is not a safe bare command name (expected ${_e.source})`}s(F,"bareCommandNameIssue");function Nn(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(Nn,"binDeclarationIssues");function Ln(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(Ln,"normalizeBin");const ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Fn(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(ve.test(o)||r.push(`action name must match ${ve.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(Fn,"humanActionDeclarationIssues");function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Fn(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(Dn,"normalizeHumanActions");function Po(e){return Nn(e).map(n=>n.message)}s(Po,"invalidPluginBinReasons");function Co(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(Co,"normalizeRequires");function Io(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(Io,"invalidPluginRequiresReasons");function we(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(we,"normalizeKindFields");function b(e,n=dn()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=we(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 To(e){D=e}s(To,"setAppPluginKinds");function ke(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,d)=>u.localeCompare(d)))i=b(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=b(i.manifest.kinds,r);return r}s(ke,"layerPluginKinds");function $o(){const e=[{origin:"config.json",components:An("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:me(t.manifest.page_components,r)})}}return kn(e)}s($o,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Mo(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`);we(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(Mo,"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=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=zn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Kn,"mergeRemoteCanvas");function Ae(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(Ae,"normalizeMode");function O(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(O,"normalizePositiveInteger");function Un(e,n){const o=e!==null&&typeof e=="object"?e:{},t=O(o.warning,n.warning),r=O(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Un,"mergeBrokerThresholds");function Gn(e,n){return{unattendedParkMs:O((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Gn,"mergeLifecycle");function qn(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(qn,"normalizeWhipMessages");function Bn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Bn,"mergeApi");let Se=!1;function z(e){!Se&&e.ledger!==void 0&&(Se=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(gn)}}));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,d={crtr:Ae(i?.crtr,n.auto_update.crtr),content:Ae(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,a=O(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,m=Un(e.brokerThresholds,n.brokerThresholds),y=Gn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,p=e.working_gerunds===void 0?[...n.working_gerunds]:wn(e.working_gerunds),xe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Re=me(e.page_components),Oe=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Ee=qn(e.whip_messages),Pe=cn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ce=sn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,Ie=O(e.live_cycles,n.live_cycles),Te=rn.includes(e.condensed_history)?e.condensed_history:n.condensed_history,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=typeof e.fold_finished_tools=="boolean"?e.fold_finished_tools:n.fold_finished_tools,Ne=typeof e.summarize_tool_calls=="boolean"?e.summarize_tool_calls:n.summarize_tool_calls,Le=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=typeof e.consolidate_replies=="boolean"?e.consolidate_replies:n.consolidate_replies,ze=Pn(e.keybindings),Ke=In(e.tmux_passthrough),Ue=T(e.modelLadders),Ge=L(e.providerOptions,n.providerOptions),U=be($(e.modelRoutes)),Q=U.complete,ee=M(e.modelRouting,void 0),qe=b(e.kinds),Be=Kn(e.remoteCanvas),We=Bn(e.api,n.api),_=e.paths;if(_?.user_files!==void 0&&(typeof _.user_files!="string"||!_.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,v=e.runtime;if(v?.person_uids!==void 0&&(!Array.isArray(v.person_uids)||!v.person_uids.every(oe=>Number.isSafeInteger(oe)&&oe>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const He=N(e.spawnEnv,n.spawnEnv?.allow),Je=Ln(e.bin),Ze=Dn(e.humanActions);return{bin:Je,humanActions:Ze,schema_version:o,marketplaces:t,plugins:r,auto_update:d,max_panes_per_window:a,auto_open_child_viewers:l,brokerThresholds:m,lifecycle:y,completion_bell:K,working_gerunds:p,whip_mode:xe,page_components:Re,page_surface:Oe,whip_messages:Ee,whip_message_mode:Pe,mouse_mode_default:Ce,live_cycles:Ie,condensed_history:Te,bash_tool_purpose:$e,fold_finished_tools:Me,summarize_tool_calls:Ne,detailed_tool_recaps:Le,document_port:Fe,consolidate_replies:De,keybindings:ze,tmux_passthrough:Ke,modelLadders:Ue,providerOptions:Ge,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(U.legacy).length>0?{legacyModelRoutes:U.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:qe,remoteCanvas:Be,api:We,..._?{paths:_}:{},...ne?{store:ne}:{},...v?{runtime:v}:{},spawnEnv:He}}s(z,"mergeConfig");function Wn(e){return P(e)}s(Wn,"readRawConfigAtRoot");function Hn(e){const n=g(e);return n?Wn(n):null}s(Hn,"readRawScopeConfig");function Jn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Jn,"readRawProfileConfig");function Zn(e,n){return[...hn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Zn,"readRawProjectScopeConfigs");function je(e=process.cwd(),n=Ve()||null){const o=C[I];if(o)return o.launch;const t=w(),r=Hn("user"),i=Jn(n),c=Zn(e,n);let u=b(r?.kinds,ke("user",g("user"),t.kinds)),d=T(r?.modelLadders,t.modelLadders),f=L(r?.providerOptions,t.providerOptions),a=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),m=N(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),d=T(i.modelLadders,d),f=L(i.providerOptions,f),a=$(i.modelRoutes,a),l=M(i.modelRouting,l),m=N(i.spawnEnv,m.allow));for(const{root:K,raw:p}of c)u=b(p?.kinds,ke("project",K,u)),p!==null&&(d=T(p.modelLadders,d),f=L(p.providerOptions,f),a=$(p.modelRoutes,a),l=M(p.modelRouting,l),m=N(p.spawnEnv,m.allow));const y=be(a);return{kinds:u,modelLadders:d,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:m}}s(je,"readMergedLaunchConfig");function No(e){return je().kinds[e]}s(No,"resolveKindConfig");function Lo(e){const n=je().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(Lo,"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 Vn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of vn)u!=="modelLadders"&&!nn(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(Vn,"mutateConfigAtRoot");async function Fo(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(Fo,"persistModelLadders");async function Do(e,n,o){if(o!==void 0)Tn(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=he(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(Do,"persistModelRoute");async function Xn(e,n){return await Vn(e,n)}s(Xn,"updateConfigAtRoot");async function zo(e,n){return await Xn(k(e),n)}s(zo,"updateConfig");async function Ko(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(Ko,"persistDefaultKindModel");async function Uo(e,n){const o=xn(e);return n(o),await En(e,o),o}s(Uo,"updateState");export{Rn as InvalidRawSettingsError,Nn as binDeclarationIssues,Ao as brokerConfigSnapshot,vo as configPath,Eo as ensureScopeInitialized,Fn as humanActionDeclarationIssues,ko as installBrokerConfigSnapshot,Po as invalidPluginBinReasons,Mo as invalidPluginKindsReasons,Io as invalidPluginRequiresReasons,Ln as normalizeBin,Dn as normalizeHumanActions,Co as normalizeRequires,In as normalizeTmuxPassthrough,Ko as persistDefaultKindModel,Fo as persistModelLadders,Do as persistModelRoute,An as readConfig,Sn as readConfigAtRoot,je as readMergedLaunchConfig,Wn as readRawConfigAtRoot,Hn as readRawScopeConfig,So as readRawSettingsForTarget,xn as readState,jo as replaceRawSettingsForTarget,No as resolveKindConfig,$o as resolvePageComponents,To as setAppPluginKinds,wo as statePath,Lo as subKindsAvailableTo,zo as updateConfig,Xn as updateConfigAtRoot,xo as updateRawConfigAtomically,Uo as updateState,Ro as writeConfig,Oo as writeRawConfig,En as writeState};
|
|
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 Ye,mkdirSync as Ze,statSync as Xe}from"node:fs";import{isDeepStrictEqual as Qe}from"node:util";import{CONFIG_FILE as en,STATE_FILE as nn,CONDENSED_HISTORY_MODES as tn,VERBOSITY_LEVELS as on,MOUSE_MODE_DEFAULTS as rn,WHIP_MESSAGE_MODES as sn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as cn,defaultKindsConfig as un,defaultRemoteCanvasConfig as dn}from"../types.js";import{BINDING_CATALOG as an,BINDING_IDS as fn,isAttachPaneBinding as ln}from"./keybindings/catalog.js";import{notFound as pn}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as mn}from"./ledger/rates.js";import{atomicWriteJson as G,readJsonIfExists as O,ensureDir as gn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as yn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as ae,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{readCachedSettings as q,readCachedState as hn,revisionOf as B,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{withExclusiveDirectoryLock as bn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as vn}from"./user-settings.js";import{normalizeWorkingGerunds as _n}from"../shared/working-activity.js";import{mergePageComponentLayers as wn,normalizePageComponents as pe}from"./human/page-catalog.js";function h(e){return re(e,en)}s(h,"configPathFor");function H(e,n){return bn(`${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 bt(e){const n=g(e);return n?h(n):null}s(bt,"configPath");function vt(e){const n=g(e);return n?J(n):null}s(vt,"statePath");function S(e){const n=A(e),t=A(ue());if(n===t)return{key:"user",kind:"user",root:t};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const o of fe()){const r=A(ae(o.profileId));if(n===r)return{key:`profile:${o.profileId}`,kind:"profile",root:r,profileId:o.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let n;try{n=A(e)}catch(t){if(t.code==="ENOENT")return null;throw t}if(n!==A(ue()))return O(h(e))}return q(S(e).key).settings}s(P,"readRawAtRoot");async function me(e,n){let t;return await W(o=>{const r=o.settings[e],i=n(structuredClone(r??{}));return t=i.value,[{op:"settings.replace",owner:e,raw:i.next,ifRevision:B(r)}]}),t}s(me,"mutatePersonSettings");async function V(e,n){const t=S(e);if(t.kind==="project"){H(h(t.root),o=>G(o,n,{createParent:!1}));return}await me(t.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const t=S(e);return t.kind==="project"?H(h(t.root),o=>{const r=n(O(o)??{});return G(o,r.next,{createParent:!1}),r.value}):await me(t.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,C=Symbol.for("crtr.broker.config-snapshot");function _t(e){I[C]=e}s(_t,"installBrokerConfigSnapshot");function wt(){return I[C]}s(wt,"brokerConfigSnapshot");function kn(e){const n=I[C];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const t=g(e);return t?An(t):w()}s(kn,"readConfig");function An(e){const n=P(e);return n?K(n):w()}s(An,"readConfigAtRoot");function Sn(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(Sn,"readProjectState");function jn(e){const n=g(e);return n?e==="project"?Ye(n)?Sn(n):se():hn(S(n).key):se()}s(jn,"readState");class xn extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function ge(e){if(e.scope==="user")return"user";if(!fe().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(ge,"rawSettingsKeyForTarget");function kt(e){return q(ge(e))}s(kt,"readRawSettingsForTarget");async function At(e,n,t){const o=ge(e);try{K(n)}catch(u){throw new xn(u)}if(q(o).revision!==t)throw new le;const i=await W(u=>B(u.settings[o])===t?[{op:"settings.replace",owner:o,raw:n,ifRevision:t}]:(()=>{throw new le})()),c=B(i.settings[o]);return{revision:c,changed:c!==t}}s(At,"replaceRawSettingsForTarget");async function St(e,n){const t=k(e);return await j(t,o=>{const r=n(o);return{value:r,next:r}})}s(St,"updateRawConfigAtomically");async function jt(e,n){await V(k(e),n)}s(jt,"writeConfig");async function xt(e,n){await V(k(e),n)}s(xt,"writeRawConfig");function Rn(e,n){H(J(e),t=>G(t,n,{createParent:!1}))}s(Rn,"writeProjectState");async function En(e,n){const t=k(e);if(e==="project"){Rn(t,n);return}const o=S(t).key;await W(()=>[{op:"state.write",owner:o,state:n}])}s(En,"writeState");async function Rt(e,n){if(e!=="project"){gn(n);return}try{Ze(n)}catch(t){if(t.code!=="EEXIST"||!Xe(n).isDirectory())throw t}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Rt,"ensureScopeInitialized");function On(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))Array.isArray(o)&&o.every(r=>typeof r=="string")&&(n[t]=[...o]);return n}s(On,"normalizeKeybindings");const Pn=new Set(an.filter(ln).map(e=>e.id));function In(e){return Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&fn.has(n)&&Pn.has(n)))]:[]}s(In,"normalizeTmuxPassthrough");function T(e,n=cn()){const t=n;if(e===null||typeof e!="object")return t;const o=e,r={anthropic:{...t.anthropic},openai:{...t.openai},...t.defaultProvider!==void 0?{defaultProvider:t.defaultProvider}:{}};(o.defaultProvider==="anthropic"||o.defaultProvider==="openai")&&(r.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"]){const c=o[i];if(!(c===null||typeof c!="object"))for(const[u,d]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof d=="string"&&(r[i][u]=d)}return r}s(T,"mergeModelLadders");function ye(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(ye,"validStrength");const Y=["ultra","strong","medium","light"];function Z(){return Object.create(null)}s(Z,"routeRecord");function x(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function he(e){const n=Z();for(const[t,o]of Object.entries(e??{}))x(n,t,o);return n}s(he,"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 t=he(n);if(e===null||typeof e!="object"||Array.isArray(e))return t;for(const[o,r]of Object.entries(e)){if(o.trim()===""){R(o,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(o,"route must be an object");continue}const i=r,c=t[o],u={...c};let d;for(const f of["family","credentialSource","providerId"]){const a=i[f];if(a!==void 0){if(typeof a!="string"||a.trim()===""){d=`${f} must be a non-empty string`;break}u[f]=a}}if(d===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))d="models must be an object";else{const f={...c?.models};for(const[a,l]of Object.entries(i.models)){if(!ye(a)){d=`models.${a} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){d=`models.${a} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){d=`models.${a} must be provider/id`;break}f[a]=l}u.models=f}if(d===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,a]of Object.entries(u.models))if(a.slice(0,a.indexOf("/"))!==u.providerId){d=`models.${f} provider prefix must equal providerId`;break}}if(d!==void 0){R(o,d);continue}x(t,o,u)}return t}s($,"mergeModelRoutePatches");function be(e){const n=Z(),t=Z();for(const[o,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(o,"route must include family, credentialSource, providerId, and models");continue}const i=Y.filter(c=>r.models[c]===void 0);if(i.length>0){R(o,`incomplete route; missing strengths: ${i.join(", ")}`),x(t,o,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,o,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:t}}s(be,"resolveModelRoutes");function Cn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const o of["family","credentialSource","providerId"])if(typeof n[o]!="string"||n[o].trim()==="")throw new Error(`model route "${e}" ${o} must be a non-empty string`);const t=Y.filter(o=>n.models?.[o]===void 0);if(t.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${t.join(", ")}`);for(const o of Y){const r=n.models[o];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${o} 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.${o} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${o} provider prefix must equal providerId`)}}s(Cn,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const t=e,o=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(t.strengthFallback)&&t.strengthFallback.every(i=>ye(i))?[...t.strengthFallback]:void 0;return{...o(t.credentialSourceOrder)!==void 0?{credentialSourceOrder:o(t.credentialSourceOrder)}:{},...o(t.familyOrder)!==void 0?{familyOrder:o(t.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Tn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Tn,"isInheritAllGlob");function N(e,n=[]){const t=e,o=Array.isArray(t?.allow)?t.allow.filter(r=>typeof r=="string"):[];for(const r of o)if(Tn(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,...o])]}}s(N,"mergeSpawnEnv");function L(e,n={}){const t={};for(const[o,r]of Object.entries(n))t[o]={...r};if(e!==null&&typeof e=="object")for(const[o,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...t[o]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),t[o]=i}return t}s(L,"mergeProviderOptions");const ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,$n=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&$n.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!ve.test(e))return`${n}.${e} is not a safe bare command name (expected ${ve.source})`}s(F,"bareCommandNameIssue");function Mn(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[t,o]of Object.entries(e)){const r=F(t,"bin");r!==void 0&&n.push({name:t,message:r}),(typeof o!="string"||o.trim()==="")&&n.push({name:t,message:`bin.${t} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Mn,"binDeclarationIssues");function Nn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))F(t,"bin")===void 0&&(typeof o!="string"||o.trim()===""||(n[t]=o));return n}s(Nn,"normalizeBin");const _e=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Ln(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[t,o]of Object.entries(e)){const r=[];if(_e.test(t)||r.push(`action name must match ${_e.source}`),o===null||typeof o!="object"||Array.isArray(o))r.push("action must be an object with argv and cwd");else{const i=o,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:t,reason:r.join("; ")})}return n}s(Ln,"humanActionDeclarationIssues");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Ln(e).map(o=>o.name)),t={};for(const[o,r]of Object.entries(e)){if(n.has(o))continue;const i=r;t[o]={argv:[...i.argv],cwd:i.cwd}}return t}s(Fn,"normalizeHumanActions");function Et(e){return Mn(e).map(n=>n.message)}s(Et,"invalidPluginBinReasons");function Ot(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))F(t,"requires")===void 0&&(typeof o!="string"||o.trim()===""||/[\r\n]/.test(o)||(n[t]=o));return n}s(Ot,"normalizeRequires");function Pt(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[t,o]of Object.entries(e)){const r=F(t,"requires");r!==void 0&&n.push(r),typeof o!="string"||o.trim()===""?n.push(`requires.${t} must be a non-empty one-line install hint`):/[\r\n]/.test(o)&&n.push(`requires.${t} must be a one-line install hint`)}return n}s(Pt,"invalidPluginRequiresReasons");function we(e){if(e===null||typeof e!="object")return null;const n=e,t={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(t.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(t.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(t.orchestratorModel=n.orchestratorModel);const o=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return o(n.tools)&&(t.tools=n.tools),o(n.extensions)&&(t.extensions=n.extensions),o(n.availableTo)&&(t.availableTo=n.availableTo),Object.keys(t).length>0?t:null}s(we,"normalizeKindFields");function b(e,n=un()){const t={...n};if(e!==null&&typeof e=="object")for(const[o,r]of Object.entries(e)){const i=we(r);if(i===null)continue;const c=t[o];c!==void 0?t[o]={...c,...i}:i.whenToUse!==void 0&&(t[o]=i)}return t}s(b,"mergeKinds");let D;function It(e){D=e}s(It,"setAppPluginKinds");function ke(e,n,t){if(e==="user"&&D!==void 0){let i=t;for(const c of Object.keys(D).sort((u,d)=>u.localeCompare(d)))i=b(D[c],i);return i}if(n===null)return t;const o=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=t;for(const i of o)r=b(i.manifest.kinds,r);return r}s(ke,"layerPluginKinds");function Ct(){const e=[{origin:"config.json",components:kn("user").page_components}],n=g("user");if(n!==null){const t=de("user",n).filter(o=>o.enabled&&o.manifest.page_components!==void 0).sort((o,r)=>o.name.localeCompare(r.name));for(const o of t){const r=`plugin "${o.name}" page_components`;e.push({origin:`plugin "${o.name}"`,components:pe(o.manifest.page_components,r)})}}return wn(e)}s(Ct,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],t=s(o=>Array.isArray(o)&&o.every(r=>typeof r=="string"),"isStringArray");for(const[o,r]of Object.entries(e)){if(o.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${o} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${o}.${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.${o}.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.${o}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!t(i[c])&&n.push(`kinds.${o}.${c} must be an array of strings`);we(r)===null&&n.push(`kinds.${o} 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(Tt,"invalidPluginKindsReasons");function Dn(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 t={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(t.cpOrigin=n.cpOrigin),t}s(Dn,"normalizeRemoteCanvasTarget");function Kn(e,n=dn()){const t={...n.targets};if(e!==null&&typeof e=="object"){const o=e;if(o.targets!==null&&typeof o.targets=="object")for(const[r,i]of Object.entries(o.targets)){const c=Dn(i);c!==null&&(t[r]=c)}}return{targets:t}}s(Kn,"mergeRemoteCanvas");function Ae(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(Ae,"normalizeMode");function E(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(E,"normalizePositiveInteger");function zn(e,n){const t=e!==null&&typeof e=="object"?e:{},o=E(t.warning,n.warning),r=E(t.automaticReviveCap,n.automaticReviveCap);return o<=r?{warning:o,automaticReviveCap:r}:{...n}}s(zn,"mergeBrokerThresholds");function Un(e,n){return{unattendedParkMs:E((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Un,"mergeLifecycle");function Gn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim());return n.length>0?n:[...ie]}s(Gn,"normalizeWhipMessages");function qn(e,n){if(e===null||typeof e!="object")return{...n};const t=e.tcp;return{tcp:typeof t=="string"?t:n.tcp}}s(qn,"mergeApi");let Se=!1;function K(e){!Se&&e.ledger!==void 0&&(Se=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(mn)}}));const n=w(),t=n.schema_version,o=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,d={crtr:Ae(i?.crtr,n.auto_update.crtr),content:Ae(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,a=E(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=zn(e.brokerThresholds,n.brokerThresholds),y=Un(e.lifecycle,n.lifecycle),z=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:_n(e.working_gerunds),xe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Re=pe(e.page_components),Ee=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Oe=Gn(e.whip_messages),Pe=sn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ie=rn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,Ce=E(e.live_cycles,n.live_cycles),Te=tn.includes(e.condensed_history)?e.condensed_history:n.condensed_history,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=on.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=On(e.keybindings),De=In(e.tmux_passthrough),Ke=T(e.modelLadders),ze=L(e.providerOptions,n.providerOptions),U=be($(e.modelRoutes)),Q=U.complete,ee=M(e.modelRouting,void 0),Ue=b(e.kinds),Ge=Kn(e.remoteCanvas),qe=qn(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=Nn(e.bin),He=Fn(e.humanActions);return{bin:We,humanActions:He,schema_version:t,marketplaces:o,plugins:r,auto_update:d,max_panes_per_window:a,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:z,working_gerunds:m,whip_mode:xe,page_components:Re,page_surface:Ee,whip_messages:Oe,whip_message_mode:Pe,mouse_mode_default:Ie,live_cycles:Ce,condensed_history:Te,bash_tool_purpose:$e,verbosity:Me,detailed_tool_recaps:Ne,document_port:Le,keybindings:Fe,tmux_passthrough:De,modelLadders:Ke,providerOptions:ze,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(U.legacy).length>0?{legacyModelRoutes:U.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ue,remoteCanvas:Ge,api:qe,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:Be}}s(K,"mergeConfig");function Bn(e){return P(e)}s(Bn,"readRawConfigAtRoot");function Wn(e){const n=g(e);return n?Bn(n):null}s(Wn,"readRawScopeConfig");function Hn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Hn,"readRawProfileConfig");function Jn(e,n){return[...yn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Jn,"readRawProjectScopeConfigs");function je(e=process.cwd(),n=Ve()||null){const t=I[C];if(t)return t.launch;const o=w(),r=Wn("user"),i=Hn(n),c=Jn(e,n);let u=b(r?.kinds,ke("user",g("user"),o.kinds)),d=T(r?.modelLadders,o.modelLadders),f=L(r?.providerOptions,o.providerOptions),a=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=N(r?.spawnEnv,o.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),d=T(i.modelLadders,d),f=L(i.providerOptions,f),a=$(i.modelRoutes,a),l=M(i.modelRouting,l),p=N(i.spawnEnv,p.allow));for(const{root:z,raw:m}of c)u=b(m?.kinds,ke("project",z,u)),m!==null&&(d=T(m.modelLadders,d),f=L(m.providerOptions,f),a=$(m.modelRoutes,a),l=M(m.modelRouting,l),p=N(m.spawnEnv,p.allow));const y=be(a);return{kinds:u,modelLadders:d,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(je,"readMergedLaunchConfig");function $t(e){return je().kinds[e]}s($t,"resolveKindConfig");function Mt(e){const n=je().kinds,t=[];for(const[o,r]of Object.entries(n)){const i=o.indexOf("/");if(i===-1)continue;const c=o.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&t.push({kind:o,whenToUse:r.whenToUse})}return t.sort((o,r)=>o.kind.localeCompare(r.kind))}s(Mt,"subKindsAvailableTo");function Vn(e,n,t){const o={...e??{}};o.anthropic!==void 0&&(o.anthropic={...o.anthropic}),o.openai!==void 0&&(o.openai={...o.openai}),t.defaultProvider!==n.defaultProvider&&t.defaultProvider!==void 0&&(o.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])t[i][c]!==n[i][c]&&(o[i]={...o[i]??{},[c]:t[i][c]});return o.defaultProvider!==void 0||o.anthropic!==void 0||o.openai!==void 0?o:void 0}s(Vn,"sparseModelLaddersToPersist");async function Yn(e,n){return await j(e,t=>{const o=K(t),r=K(t);n(r);const i={...t};for(const u of vn)u!=="modelLadders"&&!Qe(r[u],o[u])&&(i[u]=r[u]);const c=Vn(t.modelLadders,o.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Yn,"mutateConfigAtRoot");async function Nt(e,n){await j(e,t=>{const o=t.modelLadders??{},r={...o};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...o[i]??{},...n[i]});return{value:void 0,next:{...t,modelLadders:r}}})}s(Nt,"persistModelLadders");async function Lt(e,n,t){if(t!==void 0)Cn(n,t);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,o=>{const r=he(o.modelRoutes??{});t===void 0?delete r[n]:x(r,n,{...t,models:{...t.models}});const i={...o};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Lt,"persistModelRoute");async function Zn(e,n){return await Yn(e,n)}s(Zn,"updateConfigAtRoot");async function Ft(e,n){return await Zn(k(e),n)}s(Ft,"updateConfig");async function Dt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,t=>{const o={...t.kinds??{},[e.kind]:{...(t.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...t,kinds:o}}}),{path:h(e.root),field:n}}s(Dt,"persistDefaultKindModel");async function Kt(e,n){const t=jn(e);return n(t),await En(e,t),t}s(Kt,"updateState");export{xn as InvalidRawSettingsError,Mn as binDeclarationIssues,wt as brokerConfigSnapshot,bt as configPath,Rt as ensureScopeInitialized,Ln as humanActionDeclarationIssues,_t as installBrokerConfigSnapshot,Et as invalidPluginBinReasons,Tt as invalidPluginKindsReasons,Pt as invalidPluginRequiresReasons,Nn as normalizeBin,Fn as normalizeHumanActions,Ot as normalizeRequires,In as normalizeTmuxPassthrough,Dt as persistDefaultKindModel,Nt as persistModelLadders,Lt as persistModelRoute,kn as readConfig,An as readConfigAtRoot,je as readMergedLaunchConfig,Bn as readRawConfigAtRoot,Wn as readRawScopeConfig,kt as readRawSettingsForTarget,jn as readState,At as replaceRawSettingsForTarget,$t as resolveKindConfig,Ct as resolvePageComponents,It as setAppPluginKinds,vt as statePath,Mt as subKindsAvailableTo,Ft as updateConfig,Zn as updateConfigAtRoot,St as updateRawConfigAtomically,Kt as updateState,jt as writeConfig,xt as writeRawConfig,En as writeState};
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
var se=Object.defineProperty;var
|
|
1
|
+
var se=Object.defineProperty;var c=(t,n)=>se(t,"name",{value:n,configurable:!0});import{randomUUID as ce}from"node:crypto";import{CrtrError as R,notFound as g,usage as m}from"../errors.js";import{ExitCode as O}from"../../types.js";import{get as ue,getMany as we,put as B}from"./bodies.js";import{dropUnresolved as pe,linksOf as le,recordActedOn as S,setLinks as G,setUnresolved as de,unresolvedLinksCouldName as me}from"./edges.js";import{publish as j}from"./events.js";import{readableOrDeleted as fe,resolveNames as ye}from"./names.js";import{createObject as he,getById as f}from"./objects.js";import{liveLookups as _e,readerForNode as Ee,readerForObject as ve}from"./reader.js";import{replaceRules as q,setRulesOwner as Ne}from"./rules.js";import{recordWatch as k}from"./watches.js";import{withCanvasWrite as y}from"../canvas/db.js";import{PURGE_RETENTION_MS as Re}from"../storage/purge.js";import{filterAsync as ge,forEachAsync as Oe,mapAsync as A}from"../async-array.js";import{check as L,resolveReader as Se,userOf as K}from"../permissions/evaluator.js";import{missingMemoryScope as Y}from"../permissions/ceiling.js";import{deleteFact as Te,parseSubject as De,writeActsFor as xe,writeFact as je}from"../permissions/facts.js";import{PermissionError as ke}from"../permissions/errors.js";function E(t){return t.class==="node"?t.node:t.class==="app"?t.app:t.class==="object"?t.object:t.person}c(E,"actorOf");async function C(t,n){const e=`user:${await K(t,n)}`;return n.class==="person"?{app:null,for:e}:{app:(await t.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(n.app.id))?.external_id??null,for:e}}c(C,"actingOf");function Ae(t,n){return new R("conflict",t,O.GENERAL,n)}c(Ae,"conflict");function h(t){if(t.type!=="document")throw m(`${t.type} ${t.id} is not a document`)}c(h,"assertDocument");async function V(t,n){return(await t.prepare(`WITH RECURSIVE chain(id, owner, type, depth) AS (
|
|
2
2
|
SELECT id, owner, type, 0 FROM objects WHERE id = ?
|
|
3
3
|
UNION ALL
|
|
4
4
|
SELECT o.id, o.owner, o.type, c.depth + 1 FROM objects o JOIN chain c ON o.id = c.owner WHERE c.depth < 12
|
|
5
|
-
) SELECT type FROM chain ORDER BY depth DESC LIMIT 1`).get(n.id))?.type??n.type}
|
|
6
|
-
WHERE rp.child = ? ORDER BY p.rev_id`).all(n.rev_id);return{rev_id:n.rev_id,seq:n.seq,number:n.number,body_hash:n.body_hash,author:n.author,rationale:n.rationale,verbatim:n.verbatim===1,created_at:n.created_at,acting_app:n.acting_app,acting_for:n.acting_for,parents:
|
|
7
|
-
AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id`).all(n.id);return await
|
|
8
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(n.id,
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
WHERE
|
|
5
|
+
) SELECT type FROM chain ORDER BY depth DESC LIMIT 1`).get(n.id))?.type??n.type}c(V,"spaceType");async function M(t,n,e){if(e!=="public"&&await V(t,n)==="repo")throw m(`a repo owns only public documents; ${n.name} cannot own a ${e} one`,{rule:"repo-public-only",next:"Write it as public, or give it another owner (your own documents can carry `if: {repo: <handle>}`)."})}c(M,"assertPublicInRepo");async function W(t,n,e,a){if(e.trim()===""||e!==e.trim())throw m(`invalid document name ${JSON.stringify(e)}`);const i=await t.prepare("SELECT id FROM objects WHERE (type = 'document' OR strpos(type, '.') > 0) AND owner = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(n.id,e);if(i&&i.id!==a?.id)throw Ae(`${n.name} already has a document named ${e}`,{name:e,holder:i.id})}c(W,"assertNameFree");async function U(t,n,e){if(!await L(t,n,"read",e.id))throw g(`no document ${e.id}`)}c(U,"readable");function X(t){return new R("scope_missing",`missing scope ${t}`,O.GENERAL,{scope:t})}c(X,"scopeMissing");async function T(t,n,e){await U(t,n,e);const{source_path:a}=await N(t,e);if(a!==null)throw new R("forbidden",`${e.name} is a built-in document shipped by a package; \`crtr doc\` cannot change it`,O.GENERAL,{id:e.id,next:"Edit it in the source repository of the package that ships it (for crtr's own documents, the crouter repo), not with `crtr doc`."});const i=await Y(t,n,e.id,"rw");if(i!==null)throw X(i);if(!await L(t,n,"edit",e.id))throw new R("forbidden",`you cannot change ${e.name}`,O.GENERAL,{id:e.id})}c(T,"changeable");async function z(t,n){const e=await t.prepare(`SELECT p.rev_id FROM revision_parents rp JOIN revisions p ON p.rev_id = rp.parent
|
|
6
|
+
WHERE rp.child = ? ORDER BY p.rev_id`).all(n.rev_id);return{rev_id:n.rev_id,seq:n.seq,number:n.number,body_hash:n.body_hash,author:n.author,rationale:n.rationale,verbatim:n.verbatim===1,created_at:n.created_at,acting_app:n.acting_app,acting_for:n.acting_for,parents:e.map(a=>a.rev_id)}}c(z,"toRevision");async function I(t,n){const e=await t.prepare(`SELECT * FROM revisions r WHERE r.document = ?
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id`).all(n.id);return await A(e,async a=>await z(t,a))}c(I,"heads");function Le(t){return t.map(n=>n.rev_id).sort().join(",")}c(Le,"headsKeyOf");async function N(t,n){const e=await t.prepare("SELECT * FROM documents WHERE object = ?").get(n.id);if(!e)throw g(`no document record for ${n.id}`);return{summary:e.summary,heads_key:e.heads_key,revision:e.revision,why_it_exists:e.why_it_exists,unlisted:e.unlisted===1,lint_ignore:e.lint_ignore_json===null?null:JSON.parse(e.lint_ignore_json),extensions:e.extensions_json===null?null:JSON.parse(e.extensions_json),source_path:e.source_path}}c(N,"documentRecord");async function D(t,n,e){const a=await t.prepare(`INSERT INTO revisions (document, rev_id, number, body_hash, author, rationale, verbatim, created_at, acting_app, acting_for)
|
|
8
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(n.id,e.rev_id??ce(),e.number,e.body_hash,e.author?.id??null,e.rationale,e.verbatim?1:0,e.created_at??new Date().toISOString(),e.acting?.app??null,e.acting?.for??null),i=t.prepare("INSERT INTO revision_parents (child, parent) VALUES (?, ?)");for(const r of e.parents)await i.run(a.rev_id,r);return a}c(D,"insertRevision");function Ie(t){const n=new Set;for(const e of t.matchAll(/\[\[([^[\]\n]+?)\]\]/g))n.add(e[1].trim());return[...n]}c(Ie,"linksIn");async function Q(t,n,e){const a=[],i=[];for(const[r,o]of await ye(t,n,e))"object"in o?a.push({written_as:r,dst:o.object}):"deleted"in o?a.push({written_as:r,dst:o.deleted}):"remote"in o||i.push(r);return{links:a,unresolved:i}}c(Q,"resolveLinks");async function Z(t,n,e,a){const{links:i,unresolved:r}=await Q(t,n,Ie(a));return await ie(t,await G(t,e,i)),await de(t,e,r),r}c(Z,"setRevisionLinks");async function F(t,n,e){const a=new Map;for(const{src:i,name:r}of await me(t,n.name,n.id))a.set(i,[...a.get(i)??[],r]);for(const[i,r]of a){const o=await f(t,i),p=o?.owner==null?null:await f(t,o.owner);if(!o||o.deleted_at||o.home_machine!==null||!p||p.deleted_at)continue;const u=p.type==="node"?await Ee(t,p.id,e??(async()=>[]),_e(t),!0):await ve(t,o,e),s=(await Q(t,u,r)).links.filter(l=>l.dst.id===n.id);s.length!==0&&(await G(t,o,[...await le(t,o),...s]),await pe(t,o,s.map(l=>l.written_as)))}}c(F,"linkNewlyNamed");async function $e(t,n){const e=n.filter(r=>r.ownerType!=="node"),a=new Set,i=c((r,o,p)=>JSON.stringify([r,o,p]),"key");if(e.length>0){const r=await t.prepare(`SELECT DISTINCT v.owner_name, v.owner_type, v.name
|
|
9
|
+
FROM unnest(?::text[], ?::text[], ?::text[]) AS v(owner_name, owner_type, name)
|
|
10
|
+
JOIN objects o ON o.name = v.owner_name AND o.type <> v.owner_type AND o.type IN ('person','app','repo','profile')
|
|
11
|
+
JOIN objects d ON d.owner = o.id AND d.type = 'document' AND d.name = v.name AND d.deleted_at IS NULL`).all(e.map(o=>o.ownerName),e.map(o=>o.ownerType),e.map(o=>o.name));for(const o of r)a.add(i(o.owner_name,o.owner_type,o.name))}return n.map(r=>r.ownerType==="node"?r.ownerName:a.has(i(r.ownerName,r.ownerType,r.name))?`${r.ownerType}:${r.ownerName}`:r.ownerName)}c($e,"ownerPrefixes");async function b(t,n,e){const i=(await t.prepare(`SELECT e.written_as, o.*, w.type AS owner_type, CASE WHEN w.type = 'node' THEN w.id ELSE w.name END AS owner_handle
|
|
12
|
+
FROM edges e JOIN objects o ON o.id = e.dst LEFT JOIN objects w ON w.id = o.owner
|
|
13
|
+
WHERE e.type = 'links-to' AND e.src = ? AND e.written_as IS NOT NULL`).all(n.id)).filter(s=>!s.deleted_at&&s.written_as!==s.id&&!(!s.written_as.includes("/")&&s.name===s.written_as));if(i.length===0)return e;const r=i.filter(s=>s.owner_type!==null),o=await $e(t,r.map(s=>({ownerType:s.owner_type,ownerName:s.owner_handle,name:s.name}))),p=new Map(r.map((s,l)=>[s,o[l]])),u=new Map;for(const s of i){const l=!s.written_as.includes("/"),w=p.get(s),d=w!==void 0?`${w}/${s.name}`:s.name,_=l&&s.owner===n.owner?s.name:d;_!==s.written_as&&u.set(s.written_as,_)}return u.size===0?e:e.replace(/\[\[([^[\]\n]+?)\]\]/g,(s,l)=>{const w=u.get(l.trim());return w===void 0?s:`[[${w}]]`})}c(b,"withCurrentNames");async function J(t,n,e){if(e.preview!==void 0){if(e.preview.trim()==="")throw m("a document needs a preview",{field:"preview"});await t.prepare("UPDATE objects SET preview = ? WHERE id = ?").run(e.preview,n.id)}e.privacy!==void 0&&(await M(t,await f(t,n.owner),e.privacy),await t.prepare("UPDATE objects SET privacy = ? WHERE id = ?").run(e.privacy,n.id));const a=c(async(r,o)=>await t.prepareUncached(`UPDATE documents SET ${r} = ? WHERE object = ?`).run(o,n.id),"set");e.summary!==void 0&&await a("summary",e.summary),e.whyItExists!==void 0&&await a("why_it_exists",e.whyItExists),e.unlisted!==void 0&&await a("unlisted",e.unlisted?1:0),e.lintIgnore!==void 0&&await a("lint_ignore_json",e.lintIgnore===null?null:JSON.stringify(e.lintIgnore)),e.extensions!==void 0&&await a("extensions_json",e.extensions===null?null:JSON.stringify(e.extensions));const i=await f(t,n.id);return e.rules!==void 0&&await q(t,i,e.rules),i}c(J,"applyDocumentFields");async function ee(t,n,e,a="crtr"){if(n.owner.deleted_at)throw m(`${n.owner.name} is deleted`);if(n.relations?.length&&n.schemaType===void 0)throw new ke(400,"schema_type_required","relations need a schemaType: they are facts about a typed resource",{field:"relations"});if(n.preview.trim()==="")throw m("a document needs a preview",{field:"preview"});await M(t,n.owner,n.privacy),await W(t,n.owner,n.name);const i=await he(t,{...n.id?{id:n.id}:{},type:"document",kind:n.kind,owner:n.owner.id,privacy:n.privacy,name:n.name,preview:n.preview,...n.schemaType!==void 0?{schema_type:n.schemaType}:{}});for(const{relation:o,subject:p}of n.relations??[])await je(t,{resourceType:n.schemaType,resourceId:i.id,relation:o,subject:De(p),writtenBy:a});await t.prepare("INSERT INTO documents (object, heads_key, revision) VALUES (?, '', 0)").run(i.id);const r=await J(t,i,{...n,preview:void 0,privacy:void 0,rules:n.rules??[]});return await F(t,r,e),r}c(ee,"createDocument");async function $(t,n){const e=await I(t,n),a=Le(e),i=Math.max(0,...e.map(r=>r.number));return await t.prepare("UPDATE documents SET heads_key = ?, revision = ? WHERE object = ?").run(a,i,n.id),{heads_key:a,revision:i,headCount:e.length}}c($,"setHeads");async function rt(t,n,e,a,i){return await y(async()=>{const r=await B(t,a),o=E(n),p=await Y(t,n,e.owner.id,"rw",!0);if(p!==null)throw X(p);const u=await C(t,n),s=await ee(t,e,i,u.app??u.for);e.owner.type==="app"&&e.schemaType===void 0&&await xe(t,s.id,await K(t,n));const l=await D(t,s,{number:1,body_hash:r,author:o,rationale:null,parents:[],acting:u});if(!await L(t,n,"edit",s.id))throw g(`no owner ${e.owner.name} you can write to`);const{heads_key:w}=await $(t,s),d=await Z(t,n,s,a);return await S(t,o,s),await k(t,o,s,"write",{readHeadsKey:w}),await j(t,{event:"created",object:s,actor:o,attrs:{revision:1},pointer:l.rev_id},i),{object:s,revision:1,unresolved:d}},{savepoint:!0})}c(rt,"writeDocument");async function He(t,n,e){return(await t.prepare("SELECT read_heads_key FROM watches WHERE watcher = ? AND object = ?").get(E(n).id,e.id))?.read_heads_key??null}c(He,"readBase");function Ce(t,n){let e=t;for(const[a,{old:i,new:r}]of n.entries()){if(i==="")throw m(`block ${a+1}: a replacement needs non-empty old text`,{field:"replace"});const o=e.indexOf(i);if(o<0)throw m(`block ${a+1}: old text not found: ${JSON.stringify(i.slice(0,120))}`,{field:"replace",old:i});if(e.indexOf(i,o+1)>=0)throw m(`block ${a+1}: old text occurs more than once: ${JSON.stringify(i.slice(0,120))}`,{field:"replace",old:i});e=e.slice(0,o)+r+e.slice(o+i.length)}return e}c(Ce,"applyReplacements");async function ot(t,n,e,a,i,r,o={},p){if(h(e),await T(t,n,e),e.deleted_at)throw m(`${e.name} is deleted`);if(r===null)throw new R("read_first",`read ${e.name} before editing it`,O.GENERAL,{id:e.id});if(i.trim()==="")throw m("an edit needs a rationale",{field:"rationale"});const u=await N(t,e);if(u.heads_key!==r)return{stale:{heads_key:u.heads_key,revision:u.revision}};const s=await I(t,e);let l;if("body"in a)l=a.body;else{if(s.length!==1)throw m(`${e.name} has ${s.length} heads and needs a merge; pass the whole merged body`,{heads:s.length});l=Ce(await b(t,e,await ue(t,s[0].body_hash)),a.replace)}try{return await y(async()=>{const w=await B(t,l),d=E(n),_=1+Math.max(0,...s.map(v=>v.number)),P=await D(t,e,{number:_,body_hash:w,author:d,rationale:i,verbatim:a.verbatim===!0,parents:s.map(v=>v.rev_id),acting:await C(t,n)}),H=P.rev_id,re=await t.prepare("UPDATE documents SET heads_key = ?, revision = ? WHERE object = ? AND heads_key = ?").run(H,_,e.id,r);if(Number(re.changes)===0){const v=await N(t,e);throw new te(v.heads_key,v.revision)}const x=await J(t,e,o),oe=await Z(t,n,x,l);return await S(t,d,x),await k(t,d,x,"write",{readHeadsKey:H}),await j(t,{event:"edited",object:x,actor:d,pointer:P.rev_id,attrs:{revision:_,from_revision:u.revision,rationale:i}},p),{revision:_,heads_key:H,unresolved:oe}},{savepoint:!0})}catch(w){if(w instanceof te)return{stale:{heads_key:w.heads_key,revision:w.revision}};throw w}}c(ot,"editDocument");class te extends Error{static{c(this,"StaleEdit")}heads_key;revision;constructor(n,e){super("stale"),this.heads_key=n,this.revision=e}}async function st(t,n,e,a,i){if(h(e),n&&(await T(t,n,e),i===void 0||i.trim()===""))throw m("an edit needs a rationale",{field:"rationale"});return await y(async()=>{const r=await J(t,e,a);if(n){const o=E(n),p=await N(t,e),u=await He(t,n,e),s=await I(t,e),l=s[0];await D(t,e,{number:1+Math.max(...s.map(d=>d.number)),body_hash:l.body_hash,author:o,rationale:i,parents:[l.rev_id],acting:await C(t,n)});const{heads_key:w}=await $(t,e);await S(t,o,r),await k(t,o,e,"write",u===p.heads_key?{readHeadsKey:w}:{})}return r},{savepoint:!0})}c(st,"setDocumentRecord");async function Me(t,n,e,a){const i=E(n),{heads_key:r}=await N(t,e);await k(t,i,e,"read",{readHeadsKey:r}),await j(t,{event:"read",object:e,actor:i,attrs:{}},a)}c(Me,"recordRead");async function ct(t,n,e,a){return h(e),await U(t,n,e),await y(async()=>{const i=await N(t,e),r=await I(t,e),o=await we(t,r.map(w=>w.body_hash)),p=await A(r,async w=>({...w,body:await b(t,e,o.get(w.body_hash))})),u=await fe(t,await Se(t,n),"o"),l=(await t.prepareUncached(`SELECT e.written_as AS _written_as, o.* FROM edges e JOIN objects o ON o.id = e.dst
|
|
14
|
+
WHERE e.type = 'links-to' AND e.src = ? AND (${u.sql}) ORDER BY e.written_as`).all(e.id,...u.params)).map(({_written_as:w,...d})=>({written_as:w??"",object:d,deleted:d.deleted_at!==null}));return e.deleted_at||await Me(t,n,e,a),{object:e,record:i,heads:p,needsMerge:p.length>1,links:l}},{savepoint:!0})}c(ct,"readDocument");async function ut(t,n,e){h(e),await U(t,n,e);const a=await t.prepare("SELECT * FROM revisions WHERE document = ? ORDER BY number DESC, created_at DESC, seq DESC").all(e.id);return await A(a,async i=>await z(t,i))}c(ut,"history");async function wt(t,n,e,a,i){if(h(e),e.deleted_at)throw m(`${e.name} is deleted`);return n&&await T(t,n,e),await y(async()=>{const r=a.owner??await f(t,e.owner),o=a.name??e.name;await W(t,r,o,e),await M(t,r,e.privacy),await t.prepare("UPDATE objects SET name = ?, owner = ? WHERE id = ?").run(o,r.id,e.id);const p=await f(t,e.id);if(r.id!==e.owner&&(await Ne(t,p),n&&!await L(t,n,"edit",p.id)))throw g(`no owner ${r.name} you can move documents to`);return n&&await S(t,E(n),p),(o!==e.name||r.id!==e.owner)&&await F(t,p,i),p},{savepoint:!0})}c(wt,"moveDocument");async function pt(t,n,e,a,i){return h(e),e.deleted_at?e:(n&&await T(t,n,e),await y(async()=>{const r=await ne(t,n,e,a,i);return await We(t,e),await ie(t,await ae(t,e.id),a),r},{savepoint:!0}))}c(pt,"deleteDocument");async function We(t,n){if(n.schema_type==null)return;const e=await t.prepare(`SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations
|
|
15
|
+
WHERE (resource_type = ? AND resource_id = ?) OR (subject_type = ? AND subject_id = ?)`).all(n.schema_type,n.id,n.schema_type,n.id);for(const a of e)await Te(t,{resourceType:a.resource_type,resourceId:a.resource_id,relation:a.relation,subject:{type:a.subject_type,id:a.subject_id,relation:a.subject_relation}})}c(We,"deleteFactsOf");async function Ue(t,n,e,a){return h(n),n.deleted_at?await y(async()=>{await W(t,await f(t,n.owner),e,n),await t.prepare("UPDATE objects SET deleted_at = NULL, name = ? WHERE id = ?").run(e,n.id);const i=await f(t,n.id);return await F(t,i,a),i},{savepoint:!0}):n}c(Ue,"restoreDocument");async function lt(t,n,e,a=Date.now()){if(h(e),!e.deleted_at)return e;if(Date.parse(e.deleted_at)<a-Re)throw m(`${e.name} was deleted over 30 days ago and can no longer be undeleted`,{id:e.id,deleted_at:e.deleted_at});const i=e.owner===null?null:await f(t,e.owner);if(i===null||i.deleted_at)throw m(`${e.name} cannot be undeleted while its owner is deleted`,{id:e.id});return await y(async()=>{const r=await Ue(t,e,e.name);return n&&await T(t,n,r),r},{savepoint:!0})}c(lt,"undeleteDocument");async function ne(t,n,e,a,i){await t.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(i??new Date().toISOString(),e.id);const r=await f(t,e.id),o=n?E(n):null;return o&&await S(t,o,r),await j(t,{event:"deleted",object:r,actor:o,attrs:{}},a),await t.prepare("DELETE FROM watches WHERE object = ?").run(e.id),await q(t,r,[]),r}c(ne,"markDeleted");async function ae(t,n){return(await t.prepare("SELECT dst FROM edges WHERE type = 'links-to' AND src = ?").all(n)).map(({dst:e})=>e)}c(ae,"linkTargets");async function ie(t,n,e){const a=t.prepare(`SELECT 1 FROM objects d JOIN objects w ON w.id = d.owner
|
|
14
16
|
WHERE d.id = ? AND d.type = 'document' AND d.deleted_at IS NULL AND w.deleted_at IS NOT NULL
|
|
15
17
|
AND NOT EXISTS (SELECT 1 FROM edges e JOIN objects s ON s.id = e.src
|
|
16
|
-
WHERE e.type = 'links-to' AND e.dst = d.id AND e.src != d.id AND s.deleted_at IS NULL)`),
|
|
18
|
+
WHERE e.type = 'links-to' AND e.dst = d.id AND e.src != d.id AND s.deleted_at IS NULL)`),i=[...n];for(;i.length>0;){const r=i.pop();await a.get(r)!==void 0&&(await ne(t,null,await f(t,r),e),i.push(...await ae(t,r)))}}c(ie,"collectUnlinked");async function dt(t,n,e){if(n.revisions.length===0)throw m(`import of ${n.name}: no revisions`);return await y(async()=>{const a=await ee(t,n,e);await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(n.revisions[0].created_at,a.id);let i=null;return await Oe(n.revisions,async(r,o)=>{i=(await D(t,a,{...r,number:o+1,parents:i===null?[]:[i]})).rev_id}),await $(t,a),await f(t,a.id)},{savepoint:!0})}c(dt,"importDocument");async function mt(t,n,e){if(h(n),n.privacy!=="public"&&await V(t,n)==="repo")throw m(`a repo owns only public documents; refusing revisions of ${n.name}`);return await y(async()=>{const a=t.prepare("SELECT rev_id, number, document, body_hash FROM revisions WHERE rev_id = ?"),i=t.prepare("SELECT parent FROM revision_parents WHERE child = ?");let r=await ge(e,async u=>{const s=await a.get(u.rev_id);if(s===void 0)return!0;const l=(await i.all(u.rev_id)).map(w=>w.parent).sort().join(",");if(s.document!==n.id||s.body_hash!==u.body_hash||l!==[...u.parents].sort().join(","))throw m(`revision ${u.rev_id} already exists with different content (document, body hash or parents); refusing to overwrite it`);return!1});for(;r.length>0;){const u=[];for(const s of r){const l=await A(s.parents,async d=>await a.get(d));if(l.some(d=>d===void 0)){u.push(s);continue}const w=l;if(w.some(d=>d.document!==n.id))throw m(`revision ${s.rev_id} names a parent of another document`);await D(t,n,{...s,author:null,number:1+Math.max(0,...w.map(d=>d.number)),parents:w.map(d=>d.rev_id)})}if(u.length===r.length)throw m(`revisions of ${n.name} name unknown parents: ${u.map(s=>s.rev_id).join(", ")}`);r=u}const{heads_key:o,headCount:p}=await $(t,n);return{heads_key:o,headCount:p}},{savepoint:!0})}c(mt,"insertImportedRevisions");async function ft(t,n){const e=await f(t,n);if(!e||e.type!=="document")throw g(`no document ${n}`);return e}c(ft,"documentById");export{E as actorOf,J as applyDocumentFields,Ce as applyReplacements,ie as collectUnlinked,pt as deleteDocument,ft as documentById,N as documentRecord,ot as editDocument,I as heads,ut as history,dt as importDocument,mt as insertImportedRevisions,Ie as linksIn,wt as moveDocument,He as readBase,ct as readDocument,Me as recordRead,Ue as restoreDocument,st as setDocumentRecord,Z as setRevisionLinks,lt as undeleteDocument,b as withCurrentNames,rt as writeDocument};
|
package/dist/core/graph/edges.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
ON CONFLICT DO NOTHING`).run(
|
|
3
|
-
|
|
1
|
+
var R=Object.defineProperty;var i=(e,n)=>R(e,"name",{value:n,configurable:!0});import{check as f,permits as y,resolveReader as T}from"../permissions/evaluator.js";import{getById as d}from"./objects.js";import{mapAsync as m}from"../async-array.js";async function A(e,n,t){await e.prepare(`INSERT INTO edges (type, src, dst, written_as, created_at) VALUES ('acted-on', ?, ?, NULL, ?)
|
|
2
|
+
ON CONFLICT DO NOTHING`).run(n.id,t.id,new Date().toISOString())}i(A,"recordActedOn");async function x(e,n,t){const s=(await e.prepare("SELECT dst FROM edges WHERE type = 'links-to' AND src = ?").all(n.id)).map(({dst:a})=>a);await e.prepare("DELETE FROM edges WHERE type = 'links-to' AND src = ?").run(n.id),t.length>0&&await e.prepare(`INSERT INTO edges (type, src, dst, written_as, created_at)
|
|
3
|
+
SELECT 'links-to', ?, v.dst, v.written_as, ? FROM unnest(?::text[], ?::text[]) WITH ORDINALITY AS v(dst, written_as, n) ORDER BY v.n
|
|
4
|
+
ON CONFLICT DO NOTHING`).run(n.id,new Date().toISOString(),t.map(a=>a.dst.id),t.map(a=>a.written_as));const o=new Set(t.map(a=>a.dst.id));return s.filter(a=>!o.has(a))}i(x,"setLinks");async function C(e,n,t){await e.prepare("DELETE FROM unresolved_links WHERE src = ?").run(n.id);const s=e.prepare("INSERT INTO unresolved_links (src, name) VALUES (?, ?) ON CONFLICT DO NOTHING");for(const o of t)await s.run(n.id,o)}i(C,"setUnresolved");async function g(e,n,t){const s=e.prepare("DELETE FROM unresolved_links WHERE src = ? AND name = ?");for(const o of t)await s.run(n.id,o)}i(g,"dropUnresolved");async function k(e,n,t){return await e.prepare("SELECT src, name FROM unresolved_links WHERE name = ? OR name = ? OR right(name, length(CAST(? AS text)) + 1) = '/' || CAST(? AS text) ORDER BY src, name").all(n,t,n,n)}i(k,"unresolvedLinksCouldName");async function h(e,n){const t=await e.prepare("SELECT e.dst, e.written_as FROM edges e WHERE e.type = 'links-to' AND e.src = ? ORDER BY e.written_as").all(n.id);return await m(t,async s=>({written_as:s.written_as??"",dst:await d(e,s.dst)}))}i(h,"linksOf");async function v(e,n,t){return await S(e,n,t,{type:"links-to",direction:"in"})}i(v,"backlinks");async function S(e,n,t,s={}){const o=await T(e,n);if(!await f(e,o,"read",t.id))return[];const a=s.direction??"both",N=s.type?[s.type]:["acted-on","links-to"],c=await y(e,o,"read","x"),p=[];for(const r of N)a!=="in"&&p.push(...await e.prepareUncached(`SELECT e.* FROM edges e JOIN objects x ON x.id = e.dst WHERE e.type = ? AND e.src = ? AND ${c.sql}`).all(r,t.id,...c.params)),a!=="out"&&p.push(...await e.prepareUncached(`SELECT e.* FROM edges e JOIN objects x ON x.id = e.src WHERE e.type = ? AND e.dst = ? AND ${c.sql}`).all(r,t.id,...c.params));const E=new Set,O=[];for(const r of p){const w=`${r.type}|${r.src}|${r.dst}`;if(E.has(w))continue;E.add(w);const l=r.src===t.id?t:await d(e,r.src),u=r.dst===t.id?t:await d(e,r.dst);!l||!u||O.push({type:r.type,src:l,dst:u,written_as:r.written_as,created_at:r.created_at})}return O}i(S,"edgesOf");export{v as backlinks,g as dropUnresolved,S as edgesOf,h as linksOf,A as recordActedOn,x as setLinks,C as setUnresolved,k as unresolvedLinksCouldName};
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
ON CONFLICT(node) DO UPDATE SET preference_snapshot = excluded.preference_snapshot, listed_json = excluded.listed_json`).run(e.node,e.preferenceSnapshot,s);const r=
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
var S=Object.defineProperty;var i=(n,e)=>S(n,"name",{value:e,configurable:!0});const f={name:1,preview:2,content:3},b=["system","transcript"],l=new WeakMap;function j(n){return{node:n.node,preferenceSnapshot:n.preferenceSnapshot,objects:new Map([...n.objects].map(([e,t])=>[e,{...t}])),listed:new Map([...n.listed].map(([e,t])=>[e,{...t}]))}}i(j,"cloneLedger");function _(n){return{node:n,preferenceSnapshot:null,objects:new Map,listed:new Map}}i(_,"emptyLedger");async function x(n,e){const t=_(e),s=await n.prepare("SELECT preference_snapshot, listed_json FROM context_sessions WHERE node = ?").get(e);if(s!==void 0){t.preferenceSnapshot=s.preference_snapshot;for(const[o,r]of Object.entries(JSON.parse(s.listed_json)))t.listed.set(o,r)}const c=await n.prepare("SELECT object, channel, level, heads_key, content_hash FROM exposures WHERE node = ?").all(e);for(const o of c){const r=t.objects.get(o.object)??{headsKey:o.heads_key,contentHash:o.content_hash};r[o.channel]=o.level,t.objects.set(o.object,r)}return l.set(t,j(t)),t}i(x,"loadLedger");async function L(n,e){const t=l.get(e)??_(e.node),s=JSON.stringify(Object.fromEntries(e.listed));(e.preferenceSnapshot!==t.preferenceSnapshot||s!==JSON.stringify(Object.fromEntries(t.listed)))&&await n.prepare(`INSERT INTO context_sessions (node, preference_snapshot, listed_json) VALUES (?, ?, ?)
|
|
2
|
+
ON CONFLICT(node) DO UPDATE SET preference_snapshot = excluded.preference_snapshot, listed_json = excluded.listed_json`).run(e.node,e.preferenceSnapshot,s);const c=[],o=[],r=new Set([...t.objects.keys(),...e.objects.keys()]);for(const a of r){const p=e.objects.get(a),d=t.objects.get(a);for(const h of b){const u=p?.[h];u===void 0?d?.[h]!==void 0&&o.push([a,h]):(u!==d?.[h]||p.headsKey!==d?.headsKey||p.contentHash!==d?.contentHash)&&c.push([a,h,u,p.headsKey,p.contentHash])}}if(o.length>0&&await n.prepare(`DELETE FROM exposures e USING unnest(?::text[], ?::text[]) AS v(object, channel)
|
|
3
|
+
WHERE e.node = ? AND e.object = v.object AND e.channel = v.channel`).run(o.map(a=>a[0]),o.map(a=>a[1]),e.node),c.length>0){const a=i(p=>c.map(d=>d[p]),"col");await n.prepare(`INSERT INTO exposures (node, object, channel, level, heads_key, content_hash)
|
|
4
|
+
SELECT ?, v.object, v.channel, v.level, v.heads_key, v.content_hash FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[])
|
|
5
|
+
AS v(object, channel, level, heads_key, content_hash)
|
|
6
|
+
ON CONFLICT(node, object, channel) DO UPDATE SET level = excluded.level, heads_key = excluded.heads_key, content_hash = excluded.content_hash`).run(e.node,a(0),a(1),a(2),a(3),a(4))}l.set(e,j(e))}i(L,"saveLedger");async function N(n,e){return await n.prepare("SELECT 1 FROM context_sessions WHERE node = ? UNION ALL SELECT 1 FROM exposures WHERE node = ? LIMIT 1").get(e,e)!==void 0}i(N,"hasLedger");async function y(n,e){await n.prepare("DELETE FROM exposures WHERE node = ?").run(e),await n.prepare("DELETE FROM context_sessions WHERE node = ?").run(e)}i(y,"clearLedger");async function T(n,e,t){await y(n,t),await n.prepare(`INSERT INTO exposures (node, object, channel, level, heads_key, content_hash)
|
|
7
|
+
SELECT ?, object, channel, level, heads_key, content_hash FROM exposures WHERE node = ? AND channel = 'transcript'`).run(t,e);const s=await n.prepare("SELECT listed_json FROM context_sessions WHERE node = ?").get(e);if(s===void 0)return;const c={};for(const[o,r]of Object.entries(JSON.parse(s.listed_json)))r.transcript!==void 0&&(c[o]={transcript:r.transcript});await n.prepare("INSERT INTO context_sessions (node, preference_snapshot, listed_json) VALUES (?, NULL, ?)").run(t,JSON.stringify(c))}i(T,"forkLedger");function E(n,e){if(n===void 0)return 0;const t=i(s=>n[s]!==void 0?f[n[s]]:0,"of");return e!==void 0?t(e):Math.max(t("system"),t("transcript"))}i(E,"rankIn");function v(n,e,t,s){const c=f[t],o=n.objects.get(e.object);if(o!==void 0&&E(o,s)>=c&&(t!=="content"||o.headsKey===e.headsKey))return!0;if(e.contentHash===null)return!1;for(const r of n.objects.values())if(r.contentHash===e.contentHash&&E(r,s)>=c)return!0;return!1}i(v,"heldAtOrAbove");function w(n,e,t,s){const c=n.objects.get(t.object),o=c!==void 0&&c.headsKey===t.headsKey&&c.contentHash===t.contentHash,r=o?{...c}:{headsKey:t.headsKey,contentHash:t.contentHash},a=o?c[e]:void 0;r[e]=a!==void 0&&f[a]>=f[s]?a:s,n.objects.set(t.object,r)}i(w,"hold");function R(n,e,t,s){return E(n.listed.get(e),s)>=f[t]}i(R,"listedAtOrAbove");function H(n,e,t,s){const c=n.listed.get(t)??{},o=c[e];o!==void 0&&f[o]>=f[s]||n.listed.set(t,{...c,[e]:s})}i(H,"holdListing");function m(n,e){const t=n.objects.get(e);if(t!==void 0)for(const[s,c]of n.objects){if(s!==e&&(t.contentHash===null||c.contentHash!==t.contentHash))continue;const{transcript:o,...r}=c;r.system===void 0?n.objects.delete(s):n.objects.set(s,r)}}i(m,"demoteTranscript");function M(n,e){return n.preferenceSnapshot===null&&(n.preferenceSnapshot=e),n.preferenceSnapshot}i(M,"freezePreferences");function A(n){return[...n.objects.values()].some(e=>e.transcript!==void 0)||[...n.listed.values()].some(e=>e.transcript!==void 0)}i(A,"hasTranscript");export{y as clearLedger,m as demoteTranscript,T as forkLedger,M as freezePreferences,N as hasLedger,A as hasTranscript,v as heldAtOrAbove,w as hold,H as holdListing,R as listedAtOrAbove,x as loadLedger,L as saveLedger};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND substr(o.name, 1, ?) = ? AND strpos(substr(o.name, ? + 1), '/') = 0 AND ${s.sql} ORDER BY o.name`).all(n.owner,i.length,i,i.length,...s.params);return await h(
|
|
1
|
+
var y=Object.defineProperty;var m=(e,t)=>y(e,"name",{value:t,configurable:!0});import{recordMemoryReadsIn as v}from"../../canvas/memory-reads.js";import{deliveryDocOf as _,nodeSubject as D,ownerHandle as N}from"../../substrate/delivery/corpus.js";import{recordContentDelivery as $}from"../../substrate/delivery/deliver.js";import{renderExplicitRead as x}from"../../substrate/delivery/render-event.js";import{permits as S,resolveReader as O}from"../../permissions/evaluator.js";import{documentRecord as R,readDocument as j}from"../documents.js";import{loadLedger as k,saveLedger as A}from"../exposures.js";import{getById as E}from"../objects.js";import{rulesOf as f}from"../rules.js";import{objectDTO as I,objectDTOs as h}from"./dto.js";import{withBase as L}from"./kind.js";import{attr as l,header as M,section as T}from"./render.js";async function b(e,t,n){const i=`${n.name}/`,s=await S(e,await O(e,t),"read","o"),a=await e.prepareUncached(`SELECT o.* FROM objects o WHERE o.type = 'document' AND o.deleted_at IS NULL AND o.home_machine IS NULL AND o.owner IS NOT DISTINCT FROM ?
|
|
2
|
+
AND substr(o.name, 1, ?) = ? AND strpos(substr(o.name, ? + 1), '/') = 0 AND ${s.sql} ORDER BY o.name`).all(n.owner,i.length,i,i.length,...s.params);return await h(e,a)}m(b,"listingOf");async function B(e,t,n){const i=t.class==="node",s=i?await k(e,t.node.id):{node:"",preferenceSnapshot:null,objects:new Map,listed:new Map},a={db:e,reader:t,subject:i?await D(e,t):null,ledger:s,channel:"transcript"},o=await x(a,await _(e,t,n));return i&&(await $(e,t,o.delivered),await A(e,s)),{attachments:o.attachments,linked:o.linked.map(u=>u.object)}}m(B,"explicitReadAttachments");async function C(e,t,n){if(t.class!=="node"||n.kind!=="knowledge"&&n.kind!=="preference"||n.owner===null)return;const i=await E(e,n.owner);i!==null&&await v(e,t.node.id,[{name:n.name,scope:N(i),at:new Date().toISOString(),type:"read"}])}m(C,"recordExplicitMemoryRead");function U(e,t){const n=[];if(t.attachments&&n.push(t.attachments,""),n.push(M("object",e,l("privacy",e.privacy)+l("revision",t.revision))),n.push(`Preview: ${e.preview}`),t.summary&&n.push(`Summary: ${t.summary}`),t.fields!==void 0&&n.push(`<fields>
|
|
3
3
|
${JSON.stringify(t.fields,null,2)}
|
|
4
|
-
</fields>`),t.needs_merge?(t.heads.forEach((i,s)=>{n.push(`<head${l("rev",i.rev_id)}${l("number",i.number)}${l("author",i.author_id)}>`,t.bodies[s]??"","</head>")}),n.push(`This document has ${t.heads.length} heads. Your next \`crtr doc edit\` writes the merged body and joins them into one revision.`)):n.push("",t.bodies[0]??""),t.listing&&t.listing.length>0){const i=t.listing.some(
|
|
5
|
-
`)}m(U,"render");function W(e){const t=e.attrs.revision,n=e.attrs.from_revision??(typeof t=="number"?t-1:null),i=e.attrs.rationale;return{...e.attrs,from_revision:n,revision:t,authors:e.actor?[e.actor.id]:[],rationales:typeof i=="string"?[i]:[]}}m(W,"editAttrs");const F=m((e,t)=>{const n=W(t);if(e===null)return n;const i=e.authors??[];return{...n,from_revision:e.from_revision??null,authors:[...i,...n.authors.filter(s=>!i.includes(s))],rationales:[...e.rationales??[],...n.rationales]}},"mergeEdits"),
|
|
4
|
+
</fields>`),t.needs_merge?(t.heads.forEach((i,s)=>{n.push(`<head${l("rev",i.rev_id)}${l("number",i.number)}${l("author",i.author_id)}>`,t.bodies[s]??"","</head>")}),n.push(`This document has ${t.heads.length} heads. Your next \`crtr doc edit\` writes the merged body and joins them into one revision.`)):n.push("",t.bodies[0]??""),t.listing&&t.listing.length>0){const i=t.listing.some(o=>o.owner?.id===e.owner?.id&&o.name.startsWith(`${e.name}/`)),s=t.listing.some(o=>o.owner?.id!==e.owner?.id||!o.name.startsWith(`${e.name}/`)),a=i&&s?`Names under ${e.name}/ and documents it links to`:i?`Names under ${e.name}/`:"Documents it links to";n.push("",...T(a,t.listing))}return n.join(`
|
|
5
|
+
`)}m(U,"render");function W(e){const t=e.attrs.revision,n=e.attrs.from_revision??(typeof t=="number"?t-1:null),i=e.attrs.rationale;return{...e.attrs,from_revision:n,revision:t,authors:e.actor?[e.actor.id]:[],rationales:typeof i=="string"?[i]:[]}}m(W,"editAttrs");const F=m((e,t)=>{const n=W(t);if(e===null)return n;const i=e.authors??[];return{...n,from_revision:e.from_revision??null,authors:[...i,...n.authors.filter(s=>!i.includes(s))],rationales:[...e.rationales??[],...n.rationales]}},"mergeEdits"),te={name:"document",addressable:"name",events:L({edited:{level:8,supersedes:!0,merge:F},deleted:{level:8}}),async listItem(e,t){return{summary:(await R(e,t)).summary??null,rules:(await f(e,t)).length}},async read(e,t,n,i){const s=await j(e,t,n,i.reposFn);await C(e,t,n);const a=s.record,o=await b(e,t,n),{attachments:u,linked:p}=await B(e,t,n),w=new Set(o.map(r=>r.id)),d=[...o,...await h(e,p.filter(r=>!w.has(r.id)))],c={summary:a.summary??null,revision:a.revision,heads:s.heads.map(r=>({rev_id:r.rev_id,number:r.number,author_id:r.author,created_at:r.created_at})),bodies:s.heads.map(r=>r.body),needs_merge:s.needsMerge,...d.length>0?{listing:d}:{},...u===""?{}:{attachments:u}};return i.fields&&(c.fields={why_it_exists:a.why_it_exists??null,unlisted:a.unlisted,lint_ignore:a.lint_ignore??[],extensions:a.extensions??{},rules:(await f(e,n)).map(({matchFrontmatter:r,...g})=>({...g,...r===void 0?{}:{match_frontmatter:r}}))}),{data:c,text:U(await I(e,n),c)}}};export{te as documentKind};
|
|
@@ -3,3 +3,5 @@ import type { ObjectDTO } from '../../../api/dto/objects.js';
|
|
|
3
3
|
import type { ObjectRow } from '../types.js';
|
|
4
4
|
import type { CanvasDb } from '../../canvas/db.js';
|
|
5
5
|
export declare function objectDTO(db: CanvasDb, o: ObjectRow): Promise<ObjectDTO>;
|
|
6
|
+
/** `rows` as wire objects, in order, with every owner loaded in one query. */
|
|
7
|
+
export declare function objectDTOs(db: CanvasDb, rows: readonly ObjectRow[]): Promise<ObjectDTO[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var l=(t,e)=>p(t,"name",{value:e,configurable:!0});import{getById as c}from"../objects.js";async function s(t,e){return r(e,e.owner===null?null:await c(t,e.owner))}l(s,"objectDTO");async function w(t,e){const a=[...new Set(e.flatMap(n=>n.owner===null?[]:[n.owner]))],d=a.length===0?[]:await t.prepare("SELECT * FROM objects WHERE id = ANY(?::text[])").all(a),i=new Map(d.map(n=>[n.id,n]));return e.map(n=>r(n,n.owner===null?null:i.get(n.owner)??null))}l(w,"objectDTOs");function r(t,e){const a=e?{id:e.id,type:e.type,handle:e.type==="node"?e.id:e.name}:null;return{id:t.id,type:t.type,kind:t.kind,owner:a,privacy:t.privacy,name:t.name,preview:t.preview??"",created_at:t.created_at,deleted_at:t.deleted_at}}l(r,"toDTO");export{s as objectDTO,w as objectDTOs};
|
|
@@ -50,6 +50,10 @@ export interface ResolveContext {
|
|
|
50
50
|
* query per owner. */
|
|
51
51
|
export declare function viewResolutions(db: CanvasDb, context: ResolveContext, names: readonly string[]): Promise<Map<string, string | null>>;
|
|
52
52
|
export declare function resolveName(db: CanvasDb, reader: Reader, raw: string, context?: ResolveContext): Promise<Resolution>;
|
|
53
|
+
/** `resolveName` for many names at once, keyed by each raw name, with the same answers. A name that is a readable object id, a live object
|
|
54
|
+
* under an owner in the view, or a live object under the owners its `<owner handle>/` names resolves here in a few queries for all names;
|
|
55
|
+
* only the rest (deleted, remote or missing) walk `resolveName` one at a time. Deriving a document's links resolves every link it names. */
|
|
56
|
+
export declare function resolveNames(db: CanvasDb, reader: Reader, raws: Iterable<string>, context?: ResolveContext): Promise<Map<string, Resolution>>;
|
|
53
57
|
/** Every readable stub of another machine's object that `raw` (`<owner handle>/<name>`, `<type>:<owner handle>/<name>` or a bare name) names:
|
|
54
58
|
* empty when none does, more than one when the name is ambiguous. `resolveName` never answers a stub, so a stub cannot shadow a local
|
|
55
59
|
* object; this is the lookup a forwarding handler makes only after `resolveName` found no local object, to learn that the name belongs
|