@north-light/cli 0.3.789 → 0.3.791

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.
Files changed (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/nodes.d.ts +0 -12
  6. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  7. package/dist/clients/attach/viewer.js +526 -526
  8. package/dist/commands/canvas-history/shared.js +1 -1
  9. package/dist/commands/node/bash.js +1 -1
  10. package/dist/commands/node/create.js +2 -2
  11. package/dist/commands/node/inspect.js +6 -6
  12. package/dist/commands/node/lifecycle.js +4 -4
  13. package/dist/commands/node-context.js +2 -2
  14. package/dist/commands/person-settings.js +1 -1
  15. package/dist/commands/profile/daemon-profiles.js +4 -4
  16. package/dist/commands/sys.js +1 -1
  17. package/dist/core/canvas/history.d.ts +2 -8
  18. package/dist/core/canvas/history.js +9 -9
  19. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  20. package/dist/core/canvas/node-agent-paths.js +1 -1
  21. package/dist/core/canvas/node-tokens.js +3 -3
  22. package/dist/core/canvas/paths.d.ts +3 -10
  23. package/dist/core/canvas/paths.js +1 -1
  24. package/dist/core/canvas/person-state.d.ts +5 -7
  25. package/dist/core/canvas/person-state.js +1 -1
  26. package/dist/core/canvas/person.d.ts +3 -30
  27. package/dist/core/canvas/person.js +1 -11
  28. package/dist/core/canvas/render-source.js +1 -1
  29. package/dist/core/config.d.ts +4 -1
  30. package/dist/core/config.js +1 -1
  31. package/dist/core/directory/join.d.ts +4 -6
  32. package/dist/core/directory/join.js +1 -1
  33. package/dist/core/grants/sync.js +1 -1
  34. package/dist/core/human/requests.d.ts +11 -1
  35. package/dist/core/human/requests.js +22 -22
  36. package/dist/core/providers/files.js +1 -1
  37. package/dist/core/review/store.js +1 -1
  38. package/dist/core/runtime/bearings-render.d.ts +2 -2
  39. package/dist/core/runtime/bearings-render.js +11 -11
  40. package/dist/core/runtime/bearings.js +1 -1
  41. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  42. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  43. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  44. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  45. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  46. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  47. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  48. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  49. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  50. package/dist/core/runtime/broker-extension-render.js +2 -2
  51. package/dist/core/runtime/broker.js +1 -1
  52. package/dist/core/runtime/host.js +3 -3
  53. package/dist/core/runtime/kickoff.d.ts +1 -1
  54. package/dist/core/runtime/kickoff.js +12 -12
  55. package/dist/core/runtime/launch-config-worker.js +1 -1
  56. package/dist/core/runtime/launch-target.d.ts +6 -4
  57. package/dist/core/runtime/launch-target.js +1 -1
  58. package/dist/core/runtime/launch.d.ts +5 -1
  59. package/dist/core/runtime/launch.js +2 -2
  60. package/dist/core/runtime/nodes.js +1 -1
  61. package/dist/core/runtime/revive.js +2 -2
  62. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  63. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  64. package/dist/core/runtime/runner/launch-env.js +1 -0
  65. package/dist/core/runtime/runner/machine/executor.js +2 -2
  66. package/dist/core/runtime/runner/machine/runner.js +1 -1
  67. package/dist/core/runtime/runner/types.d.ts +1 -0
  68. package/dist/core/runtime/spawn-env-rows.js +1 -1
  69. package/dist/core/runtime/spawn.js +2 -2
  70. package/dist/core/secrets/environment-owner.js +1 -1
  71. package/dist/core/storage/attachments.d.ts +1 -1
  72. package/dist/core/storage/attachments.js +1 -1
  73. package/dist/core/storage/tables.d.ts +6 -2
  74. package/dist/core/storage/tables.js +4 -4
  75. package/dist/core/substrate/delivery/deliver.js +1 -1
  76. package/dist/core/substrate/delivery/render-boot.js +1 -1
  77. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  78. package/dist/daemon/api/handlers/canvas.js +5 -5
  79. package/dist/daemon/api/handlers/nodes.js +1 -1
  80. package/dist/daemon/api/handlers/profiles.js +1 -1
  81. package/dist/daemon/api/map.d.ts +1 -4
  82. package/dist/daemon/api/map.js +2 -2
  83. package/dist/daemon/cron/lease-recovery.js +1 -1
  84. package/dist/daemon/cron/machine-fire.js +1 -1
  85. package/dist/daemon/human/sweep.js +1 -1
  86. package/dist/daemon/peer/ingress.d.ts +2 -2
  87. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  88. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  89. package/dist/daemon/runs/observer.js +6 -5
  90. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  91. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  92. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  93. package/package.json +3 -3
  94. package/packages/crouter-api/dist/api/client.js +2 -2
  95. package/packages/crouter-api/dist/api/contract.js +1 -1
  96. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  97. package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
  98. package/packages/crouter-api/dist/core/config.js +10 -0
  99. package/packages/crouter-api/dist/core/directory/join.js +11 -45
  100. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  101. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  102. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/sandbox-start.mjs +5 -3
  108. package/dist/commands/sys/join.d.ts +0 -3
  109. package/dist/commands/sys/join.js +0 -1
@@ -42,8 +42,6 @@ export interface HistoryArtifact {
42
42
  from?: string;
43
43
  }
44
44
  export interface ScopeFilter {
45
- /** A specific cwd. Default (all flags absent) = the caller's cwd. */
46
- cwd?: string;
47
45
  /** Every cwd on the canvas. */
48
46
  allCwds?: boolean;
49
47
  /** A node and its subscription descendants (one initiative / sub-DAG). */
@@ -67,14 +65,10 @@ export interface CorpusFilter {
67
65
  /** Case-insensitive substring against the artifact's sender attribution. */
68
66
  from?: string;
69
67
  }
70
- /** The cwd the caller means by default: the calling node's cwd (resolved from
71
- * CRTR_NODE_ID via the canvas data layer), falling back to the process cwd
72
- * when not run as a node. */
73
- export declare function callerCwd(): Promise<string>;
74
- /** Build the searchable artifact set for a scope + corpus filter. Node facets
68
+ /** Build the searchable artifact set for a scope + corpus filter; `cwd` is the scope when no other scope field is set. Node facets
75
69
  * are applied against the db rows first (cheap); only surviving nodes' files
76
70
  * are read. */
77
- export declare function buildCorpus(scope: ScopeFilter, corpus: CorpusFilter): Promise<HistoryArtifact[]>;
71
+ export declare function buildCorpus(scope: ScopeFilter, corpus: CorpusFilter, cwd: string): Promise<HistoryArtifact[]>;
78
72
  export type GroupKey = 'origin' | 'node' | 'kind' | 'day' | 'type' | 'role';
79
73
  export interface CorpusGroup {
80
74
  key: string;
@@ -1,14 +1,14 @@
1
- var S=Object.defineProperty;var a=(n,s)=>S(n,"name",{value:s,configurable:!0});import{envNodeId as M}from"../../shared/env.js";import{getNode as p,listNodes as j,view as v}from"./canvas.js";import{openDb as E}from"./db.js";import{readTextIfExists as O}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as I}from"../conversation-store/index.js";import{reportBodyByName as C}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as B}from"../async-array.js";const nn=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],en=["user","assistant","toolResult"];async function R(){const n=M();if(n!==void 0&&n!==""){const s=await p(n);if(s!==null)return s.cwd}return process.cwd()}a(R,"callerCwd");function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}a(x,"toMs");async function k(n){return(await(await E()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
1
+ var S=Object.defineProperty;var d=(n,s)=>S(n,"name",{value:s,configurable:!0});import{getNode as b,listNodes as M,view as j}from"./canvas.js";import{openDb as v}from"./db.js";import{readTextIfExists as E}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as O}from"../conversation-store/index.js";import{reportBodyByName as I}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as C}from"../async-array.js";const V=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],X=["user","assistant","toolResult"];function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}d(x,"toMs");async function k(n){return(await(await v()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
2
2
  FROM deliveries d JOIN messages m ON m.message_id = d.message_id
3
3
  WHERE d.destination_id = ? AND d.wake = 1
4
- ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}a(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
5
- `),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,d=[s,e];return n.ref!==null&&d.push(`ref: ${n.ref}`),u&&d.push(c),d.join(`
4
+ ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}d(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
5
+ `),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,l=n.ref!==null?o?typeof r=="string"?r:E(n.ref)??"":await I(n.ref)??"":i,f=l!==""&&l!==n.label,u=[s,e];return n.ref!==null&&u.push(`ref: ${n.ref}`),f&&u.push(l),u.join(`
6
6
 
7
- `)}a(_,"inboxEntryBody");async function D(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}a(D,"inboxArtifact");async function N(n){const s=(await p(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof I)return null;throw t}}a(N,"resolveSessionFile");function T(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
8
- `)}a(T,"textFromBlocks");function F(n){return n==null?"unknown":n.type==="human"?"human":n.kind}a(F,"originToken");function L(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}a(L,"sendersOf");async function $(n){const s=await N(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const c=r.message;if(c===null||typeof c!="object")continue;const u=c,d=typeof u.role=="string"?u.role:"";if(d==="")continue;const f=typeof u.timestamp=="number"?u.timestamp:void 0,l=typeof r.timestamp=="string"?r.timestamp:f!==void 0?new Date(f).toISOString():"",m=T(u.content),b={index:i.length,role:d,text:m,ts:l,tsMs:f??x(l)};if(d==="user"){const w=f!==void 0&&t.has(f)?t.get(f):null;b.origin=F(w);const h=L(w);h!==void 0&&(b.from=h)}i.push(b)}return i}a($,"sessionMessages");async function J(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}a(J,"rawSessionLine");function K(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
9
- `).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}a(K,"transcriptArtifact");async function W(n){return(await p(n))?.description??""}a(W,"nodeDescOf");async function tn(n,s){const e=await P(n),t=s.kinds,i=s.statuses,o=e.filter(d=>!(t!==void 0&&t.length>0&&!t.includes(d.kind)||i!==void 0&&i.length>0&&!i.includes(d.status))),r=s.types!==void 0&&s.types.length>0?s.types:["inbox"],c=new Set(r),u=[];for(const d of o){const f=await W(d.node_id);if(c.has("inbox")&&await B(await k(d.node_id),async(l,m)=>u.push(await D(d,f,l,m))),c.has("transcript"))for(const l of await $(d.node_id))u.push(K(d,f,l))}return u.filter(d=>s.sinceMs!==void 0&&d.tsMs<s.sinceMs||s.untilMs!==void 0&&d.tsMs>s.untilMs?!1:G(d,s))}a(tn,"buildCorpus");function G(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}a(G,"matchesMessageFilters");function sn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}a(sn,"groupCorpus");async function P(n){const s=await j(),e=new Map(s.map(i=>[i.node_id,i]));if(n.nodes!==void 0&&n.nodes.length>0)return n.nodes.map(i=>e.get(i)).filter(i=>i!==void 0);if(n.under!==void 0&&n.under!=="")return[n.under,...await v(n.under)].map(o=>e.get(o)).filter(o=>o!==void 0);if(n.allCwds===!0)return s;const t=n.cwd!==void 0&&n.cwd!==""?n.cwd:await R();return s.filter(i=>i.cwd===t)}a(P,"scopedRows");async function on(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await p(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await N(e);if(o===null)return null;const r=await $(e);if(t==="session"){const d=r.map(f=>`## ${f.role}${f.origin!==void 0?` (origin: ${f.origin})`:""}
7
+ `)}d(_,"inboxEntryBody");async function B(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}d(B,"inboxArtifact");async function $(n){const s=(await b(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof O)return null;throw t}}d($,"resolveSessionFile");function R(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
8
+ `)}d(R,"textFromBlocks");function D(n){return n==null?"unknown":n.type==="human"?"human":n.kind}d(D,"originToken");function T(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}d(T,"sendersOf");async function N(n){const s=await $(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const l=r.message;if(l===null||typeof l!="object")continue;const f=l,u=typeof f.role=="string"?f.role:"";if(u==="")continue;const a=typeof f.timestamp=="number"?f.timestamp:void 0,c=typeof r.timestamp=="string"?r.timestamp:a!==void 0?new Date(a).toISOString():"",m=R(f.content),p={index:i.length,role:u,text:m,ts:c,tsMs:a??x(c)};if(u==="user"){const h=a!==void 0&&t.has(a)?t.get(a):null;p.origin=D(h);const w=T(h);w!==void 0&&(p.from=w)}i.push(p)}return i}d(N,"sessionMessages");async function F(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}d(F,"rawSessionLine");function L(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
9
+ `).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}d(L,"transcriptArtifact");async function J(n){return(await b(n))?.description??""}d(J,"nodeDescOf");async function Z(n,s,e){const t=await W(n,e),i=s.kinds,o=s.statuses,r=t.filter(a=>!(i!==void 0&&i.length>0&&!i.includes(a.kind)||o!==void 0&&o.length>0&&!o.includes(a.status))),l=s.types!==void 0&&s.types.length>0?s.types:["inbox"],f=new Set(l),u=[];for(const a of r){const c=await J(a.node_id);if(f.has("inbox")&&await C(await k(a.node_id),async(m,p)=>u.push(await B(a,c,m,p))),f.has("transcript"))for(const m of await N(a.node_id))u.push(L(a,c,m))}return u.filter(a=>s.sinceMs!==void 0&&a.tsMs<s.sinceMs||s.untilMs!==void 0&&a.tsMs>s.untilMs?!1:K(a,s))}d(Z,"buildCorpus");function K(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}d(K,"matchesMessageFilters");function nn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}d(nn,"groupCorpus");async function W(n,s){const e=await M(),t=new Map(e.map(i=>[i.node_id,i]));return n.nodes!==void 0&&n.nodes.length>0?n.nodes.map(i=>t.get(i)).filter(i=>i!==void 0):n.under!==void 0&&n.under!==""?[n.under,...await j(n.under)].map(o=>t.get(o)).filter(o=>o!==void 0):n.allCwds===!0?e:e.filter(i=>i.cwd===s)}d(W,"scopedRows");async function en(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await b(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await $(e);if(o===null)return null;const r=await N(e);if(t==="session"){const u=r.map(a=>`## ${a.role}${a.origin!==void 0?` (origin: ${a.origin})`:""}
10
10
 
11
- ${f.text}`).join(`
11
+ ${a.text}`).join(`
12
12
 
13
- `);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:d,raw:a(async()=>{const{header:f,entries:l}=await g().read(y(o));return[f,...l].map(m=>`${JSON.stringify(m)}
14
- `).join("")},"raw"),path:o}}const c=Number(t.slice(8)),u=r[c];return u===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:u.ts,nodeName:i.name,body:u.text,raw:a(()=>J(o,c),"raw"),path:o}}return null}a(on,"resolveRef");export{en as MESSAGE_ROLES,nn as ORIGIN_TOKENS,tn as buildCorpus,R as callerCwd,sn as groupCorpus,on as resolveRef};
13
+ `);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:u,raw:d(async()=>{const{header:a,entries:c}=await g().read(y(o));return[a,...c].map(m=>`${JSON.stringify(m)}
14
+ `).join("")},"raw"),path:o}}const l=Number(t.slice(8)),f=r[l];return f===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:f.ts,nodeName:i.name,body:f.text,raw:d(()=>F(o,l),"raw"),path:o}}return null}d(en,"resolveRef");export{X as MESSAGE_ROLES,V as ORIGIN_TOKENS,Z as buildCorpus,nn as groupCorpus,en as resolveRef};
@@ -6,3 +6,8 @@ export declare function contextDir(nodeId: string, grantee?: string): Promise<st
6
6
  export declare function reportsDir(nodeId: string, grantee?: string): Promise<string>;
7
7
  export declare function interpolateNodePaths(text: string, nodeId: string): Promise<string>;
8
8
  export declare function ensureNodeDirs(nodeId: string, grantee?: string): Promise<void>;
9
+ /** The node folder paths a lifecycle-hook payload names. A pod hosts no broker, so it hands out the tokens the broker host expands; any process that hosts the node names the real paths. */
10
+ export declare function hookNodePaths(nodeId: string): Promise<{
11
+ nodeDir: string;
12
+ contextDir: string;
13
+ }>;
@@ -1 +1 @@
1
- var p=Object.defineProperty;var e=(r,t)=>p(r,"name",{value:t,configurable:!0});import{join as a}from"node:path";import{envGrantee as s,envNodeId as c}from"../../shared/env.js";import{openDb as u}from"./db.js";import{nodeAgentDir as f,ensureNodeDirs as w,interpolateNodePaths as m}from"./paths.js";async function n(r){const t=s();if(c()===r&&t)return t;const o=await(await u()).prepare("SELECT grantee FROM node_rows WHERE node_id = ?").get(r);if(!o?.grantee)throw new Error(`node ${r} has no app assignment`);return o.grantee}e(n,"appForNode");async function i(r,t){return f(r,t??await n(r))}e(i,"nodeAgentDir");async function N(r,t){return a(await i(r,t),"context")}e(N,"contextDir");async function h(r,t){return a(await i(r,t),"reports")}e(h,"reportsDir");async function E(r,t){return m(r,t,await n(t))}e(E,"interpolateNodePaths");async function F(r,t){w(r,t??await n(r))}e(F,"ensureNodeDirs");export{n as appForNode,N as contextDir,F as ensureNodeDirs,E as interpolateNodePaths,i as nodeAgentDir,h as reportsDir};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});import{areEnginesInProcess as a,isCloudRole as i}from"./person-state.js";import{join as p}from"node:path";import{envGrantee as u,envNodeId as f}from"../../shared/env.js";import{openDb as D}from"./db.js";import{nodeAgentDir as w,ensureNodeDirs as m,interpolateNodePaths as x}from"./paths.js";async function s(r){const t=u();if(f()===r&&t)return t;const o=await(await D()).prepare("SELECT grantee FROM node_rows WHERE node_id = ?").get(r);if(!o?.grantee)throw new Error(`node ${r} has no app assignment`);return o.grantee}e(s,"appForNode");async function n(r,t){return w(r,t??await s(r))}e(n,"nodeAgentDir");async function g(r,t){return p(await n(r,t),"context")}e(g,"contextDir");async function A(r,t){return p(await n(r,t),"reports")}e(A,"reportsDir");async function _(r,t){return x(r,t)}e(_,"interpolateNodePaths");async function l(r,t){i()&&!a()||m(r,t??await s(r))}e(l,"ensureNodeDirs");async function C(r){return i()&&!a()?{nodeDir:"$CRTR_NODE_DIR",contextDir:"$CRTR_CONTEXT_DIR"}:{nodeDir:await n(r),contextDir:await g(r)}}e(C,"hookNodePaths");export{s as appForNode,g as contextDir,l as ensureNodeDirs,C as hookNodePaths,_ as interpolateNodePaths,n as nodeAgentDir,A as reportsDir};
@@ -1,5 +1,5 @@
1
- var E=Object.defineProperty;var r=(n,e)=>E(n,"name",{value:e,configurable:!0});import{createHash as g,randomBytes as l}from"node:crypto";import{openDb as s,withCanvasWrite as k}from"./db.js";import{terminalGrant as w}from"../grants/mirror.js";import{personIdAsync as N}from"./person.js";import{uidForApp as m}from"../spaces/users.js";const p=r(n=>g("sha256").update(n).digest("hex"),"hash");async function S(n,e,o,i){const t=await n.prepare("SELECT grantee, sub, grant_id, client_id, scopes_json, run_id FROM node_rows WHERE node_id = ?").get(o);if(!t)throw new Error(`cannot mint node token: missing node ${o}`);const a=t.run_id&&t.run_id!==o?await n.prepare("SELECT sub, grant_id, client_id FROM nodes WHERE node_id = ?").get(t.run_id):void 0,d=a?.sub??t.sub??await N(),c=t.grantee==="app:terminal"?await w(d):null;if(t.grantee==="app:terminal"&&!c)throw new Error("cannot mint node token: terminal grant is not active");const u=c?.id??a?.grant_id??t.grant_id??null,_=l(32).toString("base64url");if(!await n.prepare("SELECT 1 AS ok FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'launching'").get(e,o))throw new Error(`cannot mint node token: execution ${e} is not launching`);return await n.prepare('INSERT INTO node_tokens (broker_process_id, node_id, token_hash, grantee, uid, sub, "grant", client_id, scopes_json, issued_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)').run(e,o,p(_),t.grantee,await m(t.grantee),d,u,a?.client_id??t.client_id,t.scopes_json,i),_}r(S,"mintNodeToken");const D=r(async(n,e)=>await k(o=>S(o,n,e,new Date().toISOString())),"mintExecutionToken");async function v(n){if(!/^[A-Za-z0-9_-]{43}$/.test(n))return null;const e=await(await s()).prepare(`SELECT t.node_id, t.grantee, t.uid, t.sub, t."grant", t.client_id, t.scopes_json, n.run_id
1
+ var E=Object.defineProperty;var r=(n,e)=>E(n,"name",{value:e,configurable:!0});import{createHash as l,randomBytes as g}from"node:crypto";import{openDb as d,withCanvasWrite as k}from"./db.js";import{terminalGrant as w}from"../grants/mirror.js";import{uidForApp as N}from"../spaces/users.js";const u=r(n=>l("sha256").update(n).digest("hex"),"hash");async function S(n,e,o,i){const t=await n.prepare("SELECT grantee, sub, grant_id, client_id, scopes_json, run_id FROM node_rows WHERE node_id = ?").get(o);if(!t)throw new Error(`cannot mint node token: missing node ${o}`);const a=t.run_id&&t.run_id!==o?await n.prepare("SELECT sub, grant_id, client_id FROM nodes WHERE node_id = ?").get(t.run_id):void 0,s=a?.sub??t.sub;if(s==null)throw new Error(`cannot mint node token: node ${o} has no person (null sub)`);const c=t.grantee==="app:terminal"?await w(s):null;if(t.grantee==="app:terminal"&&!c)throw new Error("cannot mint node token: terminal grant is not active");const p=c?.id??a?.grant_id??t.grant_id??null,_=g(32).toString("base64url");if(!await n.prepare("SELECT 1 AS ok FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'launching'").get(e,o))throw new Error(`cannot mint node token: execution ${e} is not launching`);return await n.prepare('INSERT INTO node_tokens (broker_process_id, node_id, token_hash, grantee, uid, sub, "grant", client_id, scopes_json, issued_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)').run(e,o,u(_),t.grantee,await N(t.grantee),s,p,a?.client_id??t.client_id,t.scopes_json,i),_}r(S,"mintNodeToken");const R=r(async(n,e)=>await k(o=>S(o,n,e,new Date().toISOString())),"mintExecutionToken");async function D(n){if(!/^[A-Za-z0-9_-]{43}$/.test(n))return null;const e=await(await d()).prepare(`SELECT t.node_id, t.grantee, t.uid, t.sub, t."grant", t.client_id, t.scopes_json, n.run_id
2
2
  FROM node_tokens t JOIN executions e ON e.execution_id = t.broker_process_id
3
3
  JOIN nodes n ON n.node_id = t.node_id
4
- WHERE t.token_hash = ? AND t.revoked_at IS NULL AND e.state != 'exited'`).get(p(n));return e?{app:e.grantee,node:e.node_id,run:e.run_id,uid:e.uid,sub:e.sub,grant:e.grant,client_id:e.client_id,scopes:e.scopes_json===null?null:JSON.parse(e.scopes_json)}:null}r(v,"resolveNodeToken");async function b(n){await h(await s(),"broker_process_id",n,new Date().toISOString())}r(b,"revokeExitedNodeToken");async function I(n){await(await s()).prepare(`UPDATE node_tokens SET revoked_at = ? WHERE revoked_at IS NULL
5
- AND broker_process_id IN (SELECT execution_id FROM executions WHERE daemon_epoch IS DISTINCT FROM ?)`).run(new Date().toISOString(),n)}r(I,"revokePriorEpochNodeTokens");async function h(n,e,o,i){await n.prepareUncached(`UPDATE node_tokens SET revoked_at = ? WHERE ${e} = ? AND revoked_at IS NULL`).run(i,o)}r(h,"revokeNodeTokens");export{D as mintExecutionToken,S as mintNodeToken,v as resolveNodeToken,b as revokeExitedNodeToken,h as revokeNodeTokens,I as revokePriorEpochNodeTokens};
4
+ WHERE t.token_hash = ? AND t.revoked_at IS NULL AND e.state != 'exited'`).get(u(n));return e?{app:e.grantee,node:e.node_id,run:e.run_id,uid:e.uid,sub:e.sub,grant:e.grant,client_id:e.client_id,scopes:e.scopes_json===null?null:JSON.parse(e.scopes_json)}:null}r(D,"resolveNodeToken");async function b(n){await h(await d(),"broker_process_id",n,new Date().toISOString())}r(b,"revokeExitedNodeToken");async function v(n){await(await d()).prepare(`UPDATE node_tokens SET revoked_at = ? WHERE revoked_at IS NULL
5
+ AND broker_process_id IN (SELECT execution_id FROM executions WHERE daemon_epoch IS DISTINCT FROM ?)`).run(new Date().toISOString(),n)}r(v,"revokePriorEpochNodeTokens");async function h(n,e,o,i){await n.prepareUncached(`UPDATE node_tokens SET revoked_at = ? WHERE ${e} = ? AND revoked_at IS NULL`).run(i,o)}r(h,"revokeNodeTokens");export{R as mintExecutionToken,S as mintNodeToken,D as resolveNodeToken,b as revokeExitedNodeToken,h as revokeNodeTokens,v as revokePriorEpochNodeTokens};
@@ -45,16 +45,9 @@ export declare const BROKER_RELAY_GENERATION = "cli-relay-generation";
45
45
  /** The run's scope allow-list as a JSON array, beside `broker-launch.json`. */
46
46
  export declare function scopesFilePath(nodeId: string): string;
47
47
  export declare function contextDir(nodeId: string, grantee?: string): string;
48
- /** Replace the literal env-var tokens `$CRTR_CONTEXT_DIR` / `$CRTR_NODE_ID` in
49
- * agent-facing doc text with the node's real values, so a doc surfaced INTO a
50
- * node hands it a concrete absolute path instead of a shell-only string. The
51
- * env vars only expand in bash; an agent that pastes `$CRTR_CONTEXT_DIR/x.md`
52
- * into the (non-expanding) Write tool creates a literal `$CRTR_CONTEXT_DIR/`
53
- * dir under the project repo. The resolved absolute path works in both bash and
54
- * Write, so this substitution is strictly safer. Callers must only apply it
55
- * when they have a concrete node to render for (never on generic, node-less
56
- * output). Pure string work — no I/O. */
57
- export declare function interpolateNodePaths(text: string, nodeId: string, grantee?: string): string;
48
+ /** Replace the literal token `$CRTR_NODE_ID` in agent-facing doc text with the node's id. `$CRTR_CONTEXT_DIR` stays a token: only the machine hosting the
49
+ * node's broker knows its path, and the broker expands it (`expandHostPathTokens`) before the text reaches the model. Pure string work — no I/O. */
50
+ export declare function interpolateNodePaths(text: string, nodeId: string): string;
58
51
  export declare function jobDir(nodeId: string): string;
59
52
  export declare function nodeRunJobDir(nodeId: string): string;
60
53
  /** Overflow store for inbox entries whose inline body exceeds the digest's
@@ -1 +1 @@
1
- var v=Object.defineProperty;var e=(t,n)=>v(t,"name",{value:n,configurable:!0});import{join as r}from"node:path";import{mkdirSync as c}from"node:fs";import{appSpace as f,runtimeRoot as k,socketDir as m}from"../layout.js";import{envGrantee as E,envNodeId as P}from"../../shared/env.js";import{withDirBeneath as h}from"../spaces/open-beneath.js";function i(){return k()}e(i,"crtrHome");function B(){return r(i(),"canvas.db")}e(B,"canvasDbPath");function C(){return r(i(),"on-disk-migration.lock")}e(C,"onDiskMigrationLockPath");function L(){return r(i(),"on-disk-migrations.json")}e(L,"onDiskMigrationMarkerPath");function H(t){return r(s(t),"view.sock")}e(H,"viewSocketPath");function l(){return r(i(),"nodes")}e(l,"nodesRoot");function b(){return r(i(),"reviews")}e(b,"reviewsRoot");function D(t){return p(t),r(b(),t)}e(D,"reviewDir");function K(t){return r(D(t),"result.json")}e(K,"reviewResultPath");function $(t){c(D(t),{recursive:!0,mode:448})}e($,"ensureReviewDir");function F(){return r(m(),"api.sock")}e(F,"apiSocketPath");function G(){return r(i(),"session-list-cache.json")}e(G,"sessionListCachePath");const j=128;function w(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=j}e(w,"isSafeNodeId");function p(t){if(!w(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}e(p,"assertSafeNodeId");function a(t){return p(t),r(l(),t)}e(a,"nodeRecordDir");const u=a;function x(t,n){p(t);const o=n??(P()===t?E():void 0);if(!o)throw new Error(`node ${t} has no app assignment`);return r(f(o).nodes,t)}e(x,"nodeAgentDir");function _(t,n){return r(x(t,n),"home")}e(_,"isolatedNodeHome");function X(t,n,o){return o?_(t,n):f(n).home}e(X,"nodeHome");function s(t){return p(t),process.platform==="linux"?r(m(),"nodes",t):r(a(t),"run")}e(s,"nodeRunDir");const Y="broker-released",J="cli-relay-generation";function U(t){return r(s(t),"scopes.json")}e(U,"scopesFilePath");function g(t,n){return r(x(t,n),"context")}e(g,"contextDir");function q(t,n,o){return t.replaceAll("$CRTR_CONTEXT_DIR",g(n,o)).replaceAll("$CRTR_NODE_ID",n)}e(q,"interpolateNodePaths");function N(t){return r(a(t),"job")}e(N,"jobDir");function A(t){return r(s(t),"job")}e(A,"nodeRunJobDir");function z(t){return r(u(t),"messages")}e(z,"messagesDir");function Q(t){return r(u(t),"meta.json")}e(Q,"nodeMetaPath");function V(t){return r(u(t),"inbox.jsonl")}e(V,"inboxPath");function W(t){return r(s(t),"situational-context.md")}e(W,"situationalContextPath");function Z(t){return r(u(t),"passive.jsonl")}e(Z,"passivePath");function I(t){return r(u(t),"transcript.jsonl")}e(I,"transcriptPath");function tt(t,n){const o=x(t,n);c(a(t),{recursive:!0}),c(N(t),{recursive:!0});for(const R of["context","reports","attachments","worktree"])h(f(n).nodes,r(o,R),()=>{},!0);h(s(t),A(t),()=>{},!0)}e(tt,"ensureNodeDirs");function et(){c(l(),{recursive:!0})}e(et,"ensureHome");export{J as BROKER_RELAY_GENERATION,Y as BROKER_RELEASED_MARKER,F as apiSocketPath,B as canvasDbPath,g as contextDir,i as crtrHome,et as ensureHome,tt as ensureNodeDirs,$ as ensureReviewDir,V as inboxPath,q as interpolateNodePaths,w as isSafeNodeId,_ as isolatedNodeHome,N as jobDir,z as messagesDir,x as nodeAgentDir,u as nodeDir,X as nodeHome,Q as nodeMetaPath,a as nodeRecordDir,s as nodeRunDir,A as nodeRunJobDir,l as nodesRoot,C as onDiskMigrationLockPath,L as onDiskMigrationMarkerPath,Z as passivePath,D as reviewDir,K as reviewResultPath,b as reviewsRoot,U as scopesFilePath,G as sessionListCachePath,W as situationalContextPath,I as transcriptPath,H as viewSocketPath};
1
+ var v=Object.defineProperty;var e=(t,n)=>v(t,"name",{value:n,configurable:!0});import{join as r}from"node:path";import{mkdirSync as c}from"node:fs";import{appSpace as f,runtimeRoot as k,socketDir as m}from"../layout.js";import{envGrantee as E,envNodeId as P}from"../../shared/env.js";import{withDirBeneath as h}from"../spaces/open-beneath.js";function i(){return k()}e(i,"crtrHome");function L(){return r(i(),"canvas.db")}e(L,"canvasDbPath");function O(){return r(i(),"on-disk-migration.lock")}e(O,"onDiskMigrationLockPath");function T(){return r(i(),"on-disk-migrations.json")}e(T,"onDiskMigrationMarkerPath");function H(t){return r(s(t),"view.sock")}e(H,"viewSocketPath");function D(){return r(i(),"nodes")}e(D,"nodesRoot");function b(){return r(i(),"reviews")}e(b,"reviewsRoot");function l(t){return p(t),r(b(),t)}e(l,"reviewDir");function C(t){return r(l(t),"result.json")}e(C,"reviewResultPath");function K(t){c(l(t),{recursive:!0,mode:448})}e(K,"ensureReviewDir");function F(){return r(m(),"api.sock")}e(F,"apiSocketPath");function G(){return r(i(),"session-list-cache.json")}e(G,"sessionListCachePath");const j=128;function w(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=j}e(w,"isSafeNodeId");function p(t){if(!w(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}e(p,"assertSafeNodeId");function a(t){return p(t),r(D(),t)}e(a,"nodeRecordDir");const u=a;function x(t,n){p(t);const o=n??(P()===t?E():void 0);if(!o)throw new Error(`node ${t} has no app assignment`);return r(f(o).nodes,t)}e(x,"nodeAgentDir");function g(t,n){return r(x(t,n),"home")}e(g,"isolatedNodeHome");function Y(t,n,o){return o?g(t,n):f(n).home}e(Y,"nodeHome");function s(t){return p(t),process.platform==="linux"?r(m(),"nodes",t):r(a(t),"run")}e(s,"nodeRunDir");const $="broker-released",J="cli-relay-generation";function U(t){return r(s(t),"scopes.json")}e(U,"scopesFilePath");function X(t,n){return r(x(t,n),"context")}e(X,"contextDir");function q(t,n){return t.replaceAll("$CRTR_NODE_ID",n)}e(q,"interpolateNodePaths");function N(t){return r(a(t),"job")}e(N,"jobDir");function _(t){return r(s(t),"job")}e(_,"nodeRunJobDir");function z(t){return r(u(t),"messages")}e(z,"messagesDir");function Q(t){return r(u(t),"meta.json")}e(Q,"nodeMetaPath");function V(t){return r(u(t),"inbox.jsonl")}e(V,"inboxPath");function W(t){return r(s(t),"situational-context.md")}e(W,"situationalContextPath");function Z(t){return r(u(t),"passive.jsonl")}e(Z,"passivePath");function I(t){return r(u(t),"transcript.jsonl")}e(I,"transcriptPath");function tt(t,n){const o=x(t,n);c(a(t),{recursive:!0}),c(N(t),{recursive:!0});for(const R of["context","reports","attachments","worktree"])h(f(n).nodes,r(o,R),()=>{},!0);h(s(t),_(t),()=>{},!0)}e(tt,"ensureNodeDirs");function et(){c(D(),{recursive:!0})}e(et,"ensureHome");export{J as BROKER_RELAY_GENERATION,$ as BROKER_RELEASED_MARKER,F as apiSocketPath,L as canvasDbPath,X as contextDir,i as crtrHome,et as ensureHome,tt as ensureNodeDirs,K as ensureReviewDir,V as inboxPath,q as interpolateNodePaths,w as isSafeNodeId,g as isolatedNodeHome,N as jobDir,z as messagesDir,x as nodeAgentDir,u as nodeDir,Y as nodeHome,Q as nodeMetaPath,a as nodeRecordDir,s as nodeRunDir,_ as nodeRunJobDir,D as nodesRoot,O as onDiskMigrationLockPath,T as onDiskMigrationMarkerPath,Z as passivePath,l as reviewDir,C as reviewResultPath,b as reviewsRoot,U as scopesFilePath,G as sessionListCachePath,W as situationalContextPath,I as transcriptPath,H as viewSocketPath};
@@ -9,8 +9,8 @@ export declare class PersonOutsideRequestError extends Error {
9
9
  readonly code = "person_outside_request";
10
10
  constructor();
11
11
  }
12
- /** crtrd sets this once at boot; it wins unconditionally. */
13
- export declare function setPersonId(id: string): void;
12
+ /** A CLI, viewer or launch-config subprocess binds the one person it acts for (the person its settings answer named). A crtrd process never calls this: it reads the person from the request or the row it serves. */
13
+ export declare function bindClientPerson(id: string): void;
14
14
  /** crtrd calls this at boot on a cloud role, instead of resolving a person: from then on a person read outside a request throws. */
15
15
  export declare function markCloudRole(): void;
16
16
  /** Whether this process is a cloud role (`markCloudRole` ran at boot). */
@@ -20,10 +20,8 @@ export declare function markEnginesInProcess(): void;
20
20
  export declare function areEnginesInProcess(): boolean;
21
21
  /** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
22
22
  export declare function runAsPerson<T>(person: string, fn: () => T): T;
23
- /** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
24
- * `PersonUnresolvedError` when a Mac's person is not bound. Tests and non-daemon processes use `personIdAsync()`. */
23
+ /** The request's person; else the person a CLI-side process bound. Throws `PersonOutsideRequestError` on a cloud role outside a request and
24
+ * `PersonUnresolvedError` when no client-bound person exists. Tests and non-daemon processes use `personIdAsync()`. */
25
25
  export declare function personId(): string;
26
- /** The boot-set person, if any (for `personIdAsync`). */
27
- export declare function bootPersonId(): string | undefined;
28
- /** The request's person, if any (for `personIdAsync`). */
26
+ /** The request's person, if any. */
29
27
  export declare function requestPersonId(): string | undefined;
@@ -1 +1 @@
1
- var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{AsyncLocalStorage as d}from"node:async_hooks";class c extends Error{static{e(this,"PersonUnresolvedError")}code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}}class l extends Error{static{e(this,"PersonOutsideRequestError")}code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}}let o,t=!1;const s=new d;function a(r){o=r}e(a,"setPersonId");function x(){t=!0}e(x,"markCloudRole");function P(){return t}e(P,"isCloudRole");let u=!1;function m(){u=!0}e(m,"markEnginesInProcess");function E(){return u}e(E,"areEnginesInProcess");function I(r,n){return s.run(r,n)}e(I,"runAsPerson");function q(){const r=s.getStore();if(r!==void 0)return r;if(t)throw new l;if(o===void 0)throw new c;return o}e(q,"personId");function g(){return o}e(g,"bootPersonId");function h(){return s.getStore()}e(h,"requestPersonId");export{l as PersonOutsideRequestError,c as PersonUnresolvedError,E as areEnginesInProcess,g as bootPersonId,P as isCloudRole,x as markCloudRole,m as markEnginesInProcess,q as personId,h as requestPersonId,I as runAsPerson,a as setPersonId};
1
+ var i=Object.defineProperty;var e=(r,n)=>i(r,"name",{value:n,configurable:!0});import{AsyncLocalStorage as c}from"node:async_hooks";class d extends Error{static{e(this,"PersonUnresolvedError")}code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}}class l extends Error{static{e(this,"PersonOutsideRequestError")}code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}}let o,t=!1;const s=new c;function a(r){o=r}e(a,"bindClientPerson");function x(){t=!0}e(x,"markCloudRole");function P(){return t}e(P,"isCloudRole");let u=!1;function E(){u=!0}e(E,"markEnginesInProcess");function m(){return u}e(m,"areEnginesInProcess");function q(r,n){return s.run(r,n)}e(q,"runAsPerson");function g(){const r=s.getStore();if(r!==void 0)return r;if(t)throw new l;if(o===void 0)throw new d;return o}e(g,"personId");function h(){return s.getStore()}e(h,"requestPersonId");export{l as PersonOutsideRequestError,d as PersonUnresolvedError,m as areEnginesInProcess,a as bindClientPerson,P as isCloudRole,x as markCloudRole,E as markEnginesInProcess,g as personId,h as requestPersonId,q as runAsPerson};
@@ -1,31 +1,4 @@
1
- import { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId } from './person-state.js';
2
- import { type CanvasDb } from './db.js';
3
- import { LEGACY_LOCAL_PERSON } from './legacy-person.js';
4
- export { LEGACY_LOCAL_PERSON };
5
- export type PersonSource = 'stored' | 'joined' | 'grants';
6
- export { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId };
7
- /** As `personId()`, but a process that is not the daemon gets a lazy get-or-create keyed by the active canvas database. */
1
+ import { PersonUnresolvedError, PersonOutsideRequestError, bindClientPerson, markCloudRole, isCloudRole, runAsPerson, personId } from './person-state.js';
2
+ export { PersonUnresolvedError, PersonOutsideRequestError, bindClientPerson, markCloudRole, isCloudRole, runAsPerson, personId };
3
+ /** `personId()` for an async caller. */
8
4
  export declare function personIdAsync(): Promise<string>;
9
- /** Get-or-create the person and say where it came from. Order: stored, the join file's owner, the single `sub` of the
10
- * mirrored grants (a runtime with an issuer and no join file), else null (nothing is stored): no person is ever minted. */
11
- export declare function resolvePerson(): Promise<{
12
- id: string;
13
- source: PersonSource;
14
- } | null>;
15
- export declare function resolvePersonId(): Promise<string | null>;
16
- type Counts = Record<string, number>;
17
- /** Replace person `from` with `to` in every known column, inside the caller's `withCanvasWrite` transaction. Idempotent.
18
- * Rows keyed by the principal merge on collision. Returns rows changed per column. */
19
- export declare function substitutePerson(db: CanvasDb, from: string, to: string): Promise<Counts>;
20
- export interface RetireResult {
21
- person: string;
22
- /** The join reconcile (part A) ran: the person changed from the stored one to the join file's owner. */
23
- joinedFrom: string | null;
24
- /** The legacy retire (part B) ran. */
25
- retired: boolean;
26
- /** Rows changed per column (zeros omitted). */
27
- columns: Counts;
28
- }
29
- /** The boot step (flow 2), one transaction. Part A applies a join that landed after the person was minted; part B retires the
30
- * legacy local person once per person; part C installs the local terminal grant on a runtime without an issuer. */
31
- export declare function retireLocalPerson(): Promise<RetireResult>;
@@ -1,11 +1 @@
1
- var U=Object.defineProperty;var c=(n,e)=>U(n,"name",{value:e,configurable:!0});import{CrtrError as N}from"../errors.js";import{PersonUnresolvedError as R,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as H,isCloudRole as D,runAsPerson as W,personId as v,bootPersonId as b,requestPersonId as $}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as k,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as C}from"../grants/local.js";import{dropLocalGrantMirror as M}from"../grants/mirror.js";import{ownerForGrantee as F,ensureOwner as x}from"../graph/objects.js";import{canvasDatabaseUrl as G,CanvasConstraintError as J,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as q}from"../ledger/totals.js";const d="person_id",O="local_person_retired",z=/^user:[A-Za-z0-9._-]+$/,I=new Map;async function de(){const n=$();if(n!==void 0)return n;if(D())throw new A;const e=b();if(e!==void 0)return e;const r=await G(),t=I.get(r);if(t!==void 0)return t;const s=await K();if(s===null)throw new R;return I.set(r,s),s}c(de,"personIdAsync");async function T(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(T,"readMeta");async function g(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(g,"writeMeta");async function B(){return await j(async n=>{const e=await T(n,d);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await g(n,d,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const t=await n.prepare("SELECT DISTINCT sub FROM grants").all();return t.length!==1?null:(await g(n,d,t[0].sub),{id:t[0].sub,source:"grants"})}return null})}c(B,"resolvePerson");async function K(){return(await B())?.id??null}c(K,"resolvePersonId");const a=c(n=>Number(n.changes),"changes"),X=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["files","sub"],["files","grantee"],["shares","sub"],["provider_approvals","grantee"]],V=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],Z=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function L(n,e){if(!z.test(e))throw new N("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(L,"assertPerson");async function Q(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(Q,"namesPerson");async function P(n,e,r){if(L("from",e),L("to",r),e===r)throw new N("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=a(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=a(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof J?new N("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=a(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
2
- WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
3
- AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of X)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+a(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const s=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=a(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
4
- AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
5
- AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(s,p))+a(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,s)),t["relations.written_by"]=a(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=a(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of Z)t[`${o}.${i}`]=a(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of V){const l=a(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+a(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));l!==0&&(t[`${o}.person`]=l)}const u=a(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await Q(n,e))&&(await q(n,e,r),t["charge_totals.rebuilt"]=1),t}c(P,"substitutePerson");async function ee(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
6
- WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?a(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await F(n,"app:terminal")).id)):0)+a(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+a(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+a(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(ee,"rewriteLegacyGrantees");async function ne(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),s=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=a(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t)),p["node_tokens.grant"]=a(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${s})`).run(r,...t)),p["crons.grant_id"]=a(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${s})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=a(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
7
- WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
8
- AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${s})`).run(...r===null?[]:[r],...t)),p}c(ne,"repointGrantReferences");async function _e(){const n=await j(async e=>{const r={},t=c((_,w="")=>{for(const[m,f]of Object.entries(_))f!==0&&(r[w+m]=(r[w+m]??0)+f)},"add");let s=await T(e,d);if(s===null)throw new R;let p=null;const u=h();u!==null&&u!==s&&(t(await P(e,s,u),"join."),await g(e,d,u),p=s,s=u);const o=k()??S("user").runtime?.issuer,i=await T(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const l=await T(e,O)!==s;if(l){t({legacy_grantees:await ee(e)}),t(await P(e,E,s));const _=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
9
- WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${_} LIMIT 1`).get()!==void 0){const w=await x(e,"person","user",s,"user");t({repaired_stubs:a(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${_})`).run(w.id))})}t({"nodes.sub_null_terminal":a(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
10
- SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
11
- WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(s))}),t(await ne(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await M(e)}),await g(e,O,s)}return o||await C(i,s),{person:s,joinedFrom:p,retired:l,columns:r}});return y(n.person),n}c(_e,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,R as PersonUnresolvedError,D as isCloudRole,H as markCloudRole,v as personId,de as personIdAsync,B as resolvePerson,K as resolvePersonId,_e as retireLocalPerson,W as runAsPerson,y as setPersonId,P as substitutePerson};
1
+ var s=Object.defineProperty;var r=(e,n)=>s(e,"name",{value:n,configurable:!0});import{PersonUnresolvedError as t,PersonOutsideRequestError as d,bindClientPerson as u,markCloudRole as i,isCloudRole as l,runAsPerson as p,personId as o}from"./person-state.js";async function m(){return o()}r(m,"personIdAsync");export{d as PersonOutsideRequestError,t as PersonUnresolvedError,u as bindClientPerson,l as isCloudRole,i as markCloudRole,o as personId,m as personIdAsync,p as runAsPerson};
@@ -4,4 +4,4 @@ var Y=Object.defineProperty;var u=(t,e)=>Y(t,"name",{value:e,configurable:!0});i
4
4
  `)}u(bt,"renderForestFromSource");const E=4096;function O(t){try{const e=K(U(t),R(t,"initial-prompt.md"))?.trim()??"";return e===""?void 0:e.length>E?e.slice(0,E):e}catch{return}}u(O,"readGoalText");const F=1024;function nt(t){if(t==null)return;const e=t.tier,i=t.created,n=t.body,r=n.split(`
5
5
  `);let s="",c=n;for(let l=0;l<r.length;l++){const o=(r[l]??"").trim();if(o!==""){s=o.startsWith("#")?o.replace(/^#+\s*/,"").trim():o,c=r.slice(l+1).join(`
6
6
  `);break}}const a=c.replace(/\s+/g," ").trim();return{kind:e,ts:i,heading:s,body:a.length>F?a.slice(0,F):a}}u(nt,"reportPreview");const it=[262144,1<<20,4<<20],rt=65536,st=65536;async function M(t,e,i){if(t==null||t==="")return null;const n=v(t);if(n===null)return null;try{const{entries:r,tail:s}=await J(n,{head:e,tail:i});return{head:r,tail:s??r,windowed:s!==void 0}}catch(r){if(r instanceof N)return null;throw r}}u(M,"readSessionWindow");const b=8192,k=2048;async function at(t){const e=await M(t,rt,st);if(e===null)return;const i=[];let n=0;for(const s of e.windowed?[...e.head,...e.tail]:e.head){if(s.type!=="message"||s.message.role!=="user")continue;const c=D(s.message.content);if(c===""||C({role:"user",content:c})!==null)continue;const a=c.length>k?c.slice(0,k):c;if(i.push(a),n+=a.length+1,n>=b)break}if(i.length===0)return;const r=i.join(`
7
- `);return r.length>b?r.slice(0,b):r}u(at,"readSessionPrompts");const j=120,z=4096;async function ot(t){let e={transcript:[]};for(const i of it){const n=await M(t,0,i);if(n===null||(e=ct(n.tail),!n.windowed||e.lastAssistant!==void 0))return e}return e}u(ot,"readSessionTail");function ct(t){const e=[];let i;for(const n of t){if(n.type!=="message")continue;const r=n.message.role;if(r!=="user"&&r!=="assistant")continue;const s=D(n.message.content);s!==""&&(r==="assistant"&&(i=s.length>k?s.slice(0,k):s),C({role:r,content:s})===null&&e.push({role:r,text:s.length>z?s.slice(0,z):s}))}return{transcript:e.length>j?e.slice(e.length-j):e,...i===void 0?{}:{lastAssistant:i}}}u(ct,"sessionTailFrom");async function vt(t){if(t==null||t==="")return!1;const e=v(t);if(e===null)return!1;let i;try{i=(await H().read(e)).entries}catch(n){if(n instanceof N)return!1;throw n}for(const n of i)if(!(n.type!=="message"||n.message.role!=="assistant")&&ut(n.message.content))return!0;return!1}u(vt,"nodeHasAssistantMessage");function ut(t){if(typeof t=="string")return t.trim()!=="";if(!Array.isArray(t))return!1;for(const e of t){if(e===null||typeof e!="object")continue;const i=e,n=(i.type??"").toLowerCase();if(n==="text"){if(typeof i.text=="string"&&i.text.trim()!=="")return!0}else if(n==="thinking"){if(typeof i.thinking=="string"&&i.thinking.trim()!=="")return!0}else return!0}return!1}u(ut,"assistantContentIsSubstantive");function D(t){if(typeof t=="string")return t.trim();if(!Array.isArray(t))return"";const e=[];for(const i of t)if(i!==null&&typeof i=="object"){const n=i;n.type==="text"&&typeof n.text=="string"&&e.push(n.text)}return e.join(" ").trim()}u(D,"extractUserText");function lt(t,e,i=!1){if(!i&&e!==null&&e!==void 0){const r=Date.parse(e);if(!Number.isNaN(r))return r}const n=Date.parse(t);return Number.isNaN(n)?0:n}u(lt,"sessionMtime");function ft(t){if(t.status!=="active")return!1;try{const e=JSON.parse(q(Q(t.node_id),R(X(t.node_id),"attach.json")).toString("utf8"));return typeof e.viewers=="number"&&e.viewers>0}catch{return!1}}u(ft,"hasLiveBrokerViewer");function dt(t,e,i){const n=t.status==="active"||t.status==="idle",r=t.fault??null;return{node_id:t.node_id,name:S(t),handle:t.name,description:t.description,status:t.status,frozen_at:t.frozen_at??null,terminal_reason:t.terminal_reason??null,kind:t.kind,mode:t.mode,ctx_tokens:i?0:t.telemetry_tokens_in??0,asks:0,cwd:t.cwd,profile_id:t.profile_id,created:t.created,lifecycle:t.lifecycle,finalized:t.final_report!=null,mtimeMs:lt(t.created,t.telemetry_updated_at,i),streaming:r===null&&n&&t.streaming===!0,hanging:r,viewed:i?!1:e.has(t.node_id)||ft(t),srcRow:t}}u(dt,"dashboardRowFromNodeRow");async function Nt(t,e,i,n){const r=t instanceof y,s=n??await t.ticketCountsForView(e).catch(()=>({})),c=new Map((i??await t.listNodes()).map(l=>[l.node_id,l]));return[e,...await t.view(e)].flatMap(l=>{const o=c.get(l);return o===void 0?[]:[{node_id:l,name:S(o),handle:o.name,description:o.description,status:o.status,frozen_at:o.frozen_at??null,terminal_reason:o.terminal_reason??null,kind:o.kind,mode:o.mode,ctx_tokens:r?0:o.telemetry_tokens_in??0,asks:s[l]??0,cwd:o.cwd,profile_id:o.profile_id,created:o.created}]})}u(Nt,"dashboardRowsFromSource");async function Rt(t,e=new Set,i=!1,n){const r=t instanceof y,s=r?new Set:e;return(n??await t.listNodes(i?{status:["active","idle"]}:void 0)).map(a=>dt(a,s,r))}u(Rt,"dashboardRowsAllFromSource");async function Tt(t,e,i){const n=e.filter(s=>s.enriched!==!0);if(n.length===0)return;const r=i??{};for(const s of n)s.asks=r[s.node_id]??0,s.enriched=!0}u(Tt,"enrichRowsFromSource");async function B(t,e,i){const n=i?.paths;if(n!==void 0)return n.context_dir;const r=e.srcRow?.grantee??(await t.getRow(e.node_id))?.grantee;if(!r)throw new Error(`node ${e.node_id} has no app assignment`);return Z(e.node_id,r)}u(B,"contextPathOf");async function wt(t,e,i={}){const n=i.transcript===!0&&e.transcriptLoaded!==!0;if(e.previewLoaded===!0&&!n)return e;if(t instanceof y)return e.previewLoaded=!0,n&&(e.transcript=[],e.transcriptLoaded=!0),e;const r=await t.getNode(e.node_id),s=await ot(r?.pi_session_file);return e.previewLoaded!==!0&&(e.goal??=O(await B(t,e,r)),e.lastAssistant=s.lastAssistant,e.recap=I(e.node_id),e.report=nt(await t.newestReport?.(e.node_id).catch(()=>null)),e.previewLoaded=!0),n&&(e.transcript=s.transcript,e.transcriptLoaded=!0),e}u(wt,"loadPreviewFromSource");async function At(t,e){if(e.promptsLoaded===!0)return e;if(!(t instanceof y)){const i=await t.getNode(e.node_id);e.goal??=O(await B(t,e,i)),e.prompts=await at(i?.pi_session_file)}return e.promptsLoaded=!0,e}u(At,"loadSearchTextFromSource");export{dt as dashboardRowFromNodeRow,Rt as dashboardRowsAllFromSource,Nt as dashboardRowsFromSource,Tt as enrichRowsFromSource,P as fmtCtx,wt as loadPreviewFromSource,At as loadSearchTextFromSource,vt as nodeHasAssistantMessage,O as readGoalText,at as readSessionPrompts,ot as readSessionTail,bt as renderForestFromSource,et as renderTreeFromSource,nt as reportPreview,lt as sessionMtime};
7
+ `);return r.length>b?r.slice(0,b):r}u(at,"readSessionPrompts");const j=120,z=4096;async function ot(t){let e={transcript:[]};for(const i of it){const n=await M(t,0,i);if(n===null||(e=ct(n.tail),!n.windowed||e.lastAssistant!==void 0))return e}return e}u(ot,"readSessionTail");function ct(t){const e=[];let i;for(const n of t){if(n.type!=="message")continue;const r=n.message.role;if(r!=="user"&&r!=="assistant")continue;const s=D(n.message.content);s!==""&&(r==="assistant"&&(i=s.length>k?s.slice(0,k):s),C({role:r,content:s})===null&&e.push({role:r,text:s.length>z?s.slice(0,z):s}))}return{transcript:e.length>j?e.slice(e.length-j):e,...i===void 0?{}:{lastAssistant:i}}}u(ct,"sessionTailFrom");async function vt(t){if(t==null||t==="")return!1;const e=v(t);if(e===null)return!1;let i;try{i=(await H().read(e)).entries}catch(n){if(n instanceof N)return!1;throw n}for(const n of i)if(!(n.type!=="message"||n.message.role!=="assistant")&&ut(n.message.content))return!0;return!1}u(vt,"nodeHasAssistantMessage");function ut(t){if(typeof t=="string")return t.trim()!=="";if(!Array.isArray(t))return!1;for(const e of t){if(e===null||typeof e!="object")continue;const i=e,n=(i.type??"").toLowerCase();if(n==="text"){if(typeof i.text=="string"&&i.text.trim()!=="")return!0}else if(n==="thinking"){if(typeof i.thinking=="string"&&i.thinking.trim()!=="")return!0}else return!0}return!1}u(ut,"assistantContentIsSubstantive");function D(t){if(typeof t=="string")return t.trim();if(!Array.isArray(t))return"";const e=[];for(const i of t)if(i!==null&&typeof i=="object"){const n=i;n.type==="text"&&typeof n.text=="string"&&e.push(n.text)}return e.join(" ").trim()}u(D,"extractUserText");function lt(t,e,i=!1){if(!i&&e!==null&&e!==void 0){const r=Date.parse(e);if(!Number.isNaN(r))return r}const n=Date.parse(t);return Number.isNaN(n)?0:n}u(lt,"sessionMtime");function ft(t){if(t.status!=="active")return!1;try{const e=JSON.parse(q(Q(t.node_id),R(X(t.node_id),"attach.json")).toString("utf8"));return typeof e.viewers=="number"&&e.viewers>0}catch{return!1}}u(ft,"hasLiveBrokerViewer");function dt(t,e,i){const n=t.status==="active"||t.status==="idle",r=t.fault??null;return{node_id:t.node_id,name:S(t),handle:t.name,description:t.description,status:t.status,frozen_at:t.frozen_at??null,terminal_reason:t.terminal_reason??null,kind:t.kind,mode:t.mode,ctx_tokens:i?0:t.telemetry_tokens_in??0,asks:0,cwd:t.cwd,profile_id:t.profile_id,created:t.created,lifecycle:t.lifecycle,finalized:t.final_report!=null,mtimeMs:lt(t.created,t.telemetry_updated_at,i),streaming:r===null&&n&&t.streaming===!0,hanging:r,viewed:i?!1:e.has(t.node_id)||ft(t),srcRow:t}}u(dt,"dashboardRowFromNodeRow");async function Nt(t,e,i,n){const r=t instanceof y,s=n??await t.ticketCountsForView(e).catch(()=>({})),c=new Map((i??await t.listNodes()).map(l=>[l.node_id,l]));return[e,...await t.view(e)].flatMap(l=>{const o=c.get(l);return o===void 0?[]:[{node_id:l,name:S(o),handle:o.name,description:o.description,status:o.status,frozen_at:o.frozen_at??null,terminal_reason:o.terminal_reason??null,kind:o.kind,mode:o.mode,ctx_tokens:r?0:o.telemetry_tokens_in??0,asks:s[l]??0,cwd:o.cwd,profile_id:o.profile_id,created:o.created}]})}u(Nt,"dashboardRowsFromSource");async function Rt(t,e=new Set,i=!1,n){const r=t instanceof y,s=r?new Set:e;return(n??await t.listNodes(i?{status:["active","idle"]}:void 0)).map(a=>dt(a,s,r))}u(Rt,"dashboardRowsAllFromSource");async function Tt(t,e,i){const n=e.filter(s=>s.enriched!==!0);if(n.length===0)return;const r=i??{};for(const s of n)s.asks=r[s.node_id]??0,s.enriched=!0}u(Tt,"enrichRowsFromSource");async function B(t,e,i){const n=e.srcRow?.grantee??(await t.getRow(e.node_id))?.grantee;if(!n)throw new Error(`node ${e.node_id} has no app assignment`);return Z(e.node_id,n)}u(B,"contextPathOf");async function wt(t,e,i={}){const n=i.transcript===!0&&e.transcriptLoaded!==!0;if(e.previewLoaded===!0&&!n)return e;if(t instanceof y)return e.previewLoaded=!0,n&&(e.transcript=[],e.transcriptLoaded=!0),e;const r=await t.getNode(e.node_id),s=await ot(r?.pi_session_file);return e.previewLoaded!==!0&&(e.goal??=O(await B(t,e,r)),e.lastAssistant=s.lastAssistant,e.recap=I(e.node_id),e.report=nt(await t.newestReport?.(e.node_id).catch(()=>null)),e.previewLoaded=!0),n&&(e.transcript=s.transcript,e.transcriptLoaded=!0),e}u(wt,"loadPreviewFromSource");async function At(t,e){if(e.promptsLoaded===!0)return e;if(!(t instanceof y)){const i=await t.getNode(e.node_id);e.goal??=O(await B(t,e,i)),e.prompts=await at(i?.pi_session_file)}return e.promptsLoaded=!0,e}u(At,"loadSearchTextFromSource");export{dt as dashboardRowFromNodeRow,Rt as dashboardRowsAllFromSource,Nt as dashboardRowsFromSource,Tt as enrichRowsFromSource,P as fmtCtx,wt as loadPreviewFromSource,At as loadSearchTextFromSource,vt as nodeHasAssistantMessage,O as readGoalText,at as readSessionPrompts,ot as readSessionTail,bt as renderForestFromSource,et as renderTreeFromSource,nt as reportPreview,lt as sessionMtime};
@@ -178,7 +178,10 @@ export interface MergedLaunchConfig {
178
178
  * the target node's) MUST pass the target's own cwd/profile explicitly, or
179
179
  * `spawnEnv.allow` resolves from the wrong scope entirely (the C-1
180
180
  * follow-up fix this parameterization exists for). */
181
- export declare function readMergedLaunchConfig(targetCwd?: string, targetProfileId?: string | null): MergedLaunchConfig;
181
+ export declare function readMergedLaunchConfig(targetCwd?: string | null, targetProfileId?: string | null): MergedLaunchConfig;
182
+ /** The launch config a process holding the project's files adds on top of a recipe's config, which a cloud control plane built without them:
183
+ * the project stack's kinds (and the kinds its enabled plugins declare) in `cwd`, over the recipe's kinds. */
184
+ export declare function overlayProjectLaunchConfig(base: MergedLaunchConfig, cwd: string, profileId: string | null): MergedLaunchConfig;
182
185
  /** The effective `KindConfig` for one full kind string (top-level, e.g.
183
186
  * `developer`, or sub-kind, e.g. `audit/security`), across
184
187
  * project > user > builtin precedence. Returns `undefined` for a kind no
@@ -1 +1 @@
1
- var Je=Object.defineProperty;var s=(e,n)=>Je(e,"name",{value:n,configurable:!0});import{envProfileId as Ve}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Ze,mkdirSync as Ye,statSync as Xe}from"node:fs";import{isDeepStrictEqual as Qe}from"node:util";import{CONFIG_FILE as en,STATE_FILE as nn,VERBOSITY_LEVELS as tn,MOUSE_MODE_DEFAULTS as on,WHIP_MESSAGE_MODES as rn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as sn,defaultKindsConfig as cn,defaultRemoteCanvasConfig as un}from"../types.js";import{BINDING_CATALOG as an,BINDING_IDS as dn,isAttachPaneBinding as fn}from"./keybindings/catalog.js";import{notFound as ln}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as pn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as mn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as gn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as ae}from"./installed-plugins.js";import{profileDir as de,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as yn,readCachedSettings as B,readCachedState as hn,revisionOf as E,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as pe,splitUserSettingsWrite as bn,withAppInstalls as me}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as vn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as _n}from"./user-settings.js";import{normalizeWorkingGerunds as wn}from"../shared/working-activity.js";import{mergePageComponentLayers as kn,normalizePageComponents as ge}from"./human/page-catalog.js";function h(e){return re(e,en)}s(h,"configPathFor");function H(e,n){return vn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,nn)}s(J,"statePathFor");function wt(e){const n=g(e);return n?h(n):null}s(wt,"configPath");function kt(e){const n=g(e);return n?J(n):null}s(kt,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(de(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ue()))return O(h(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&pe()?me(yn(),o):o}s(P,"readRawAtRoot");async function ye(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&pe(),c=n(structuredClone((i?me(t,r??null):r)??{}));return o=c.value,i?bn(t,c.next,E(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:E(r)}]}),o}s(ye,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>q(t,n,{createParent:!1}));return}await ye(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function At(e){I[T]=e}s(At,"installBrokerConfigSnapshot");function St(){return I[T]}s(St,"brokerConfigSnapshot");function An(e){const n=I[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?Sn(o):w()}s(An,"readConfig");function Sn(e){const n=P(e);return n?z(n):w()}s(Sn,"readConfigAtRoot");function jn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(jn,"readProjectState");function xn(e){const n=g(e);return n?e==="project"?Ze(n)?jn(n):se():hn(S(n).key):se()}s(xn,"readState");class Rn extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function he(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw ln(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(he,"rawSettingsKeyForTarget");function jt(e){return B(he(e))}s(jt,"readRawSettingsForTarget");async function xt(e,n,o){const t=he(e);try{z(n)}catch(u){throw new Rn(u)}if(B(t).revision!==o)throw new le;const i=await W(u=>E(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=E(i.settings[t]);return{revision:c,changed:c!==o}}s(xt,"replaceRawSettingsForTarget");async function Rt(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Rt,"updateRawConfigAtomically");async function Ot(e,n){await V(k(e),n)}s(Ot,"writeConfig");async function Et(e,n){await V(k(e),n)}s(Et,"writeRawConfig");function On(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(On,"writeProjectState");async function En(e,n){const o=k(e);if(e==="project"){On(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(En,"writeState");async function Pt(e,n){if(e!=="project"){mn(n);return}try{Ye(n)}catch(o){if(o.code!=="EEXIST"||!Xe(n).isDirectory())throw o}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Pt,"ensureScopeInitialized");function Pn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(Pn,"normalizeKeybindings");const In=new Set(an.filter(fn).map(e=>e.id)),Tn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);function Cn(e){return e===void 0?[...Tn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&dn.has(n)&&In.has(n)))]:[]}s(Cn,"normalizeTmuxPassthrough");function C(e,n=sn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,a]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof a=="string"&&(r[i][u]=a)}return r}s(C,"mergeModelLadders");function be(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(be,"validStrength");const Z=["ultra","strong","medium","light"];function Y(){return Object.create(null)}s(Y,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function ve(e){const n=Y();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(ve,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const o=ve(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let a;for(const f of["family","credentialSource","providerId"]){const d=i[f];if(d!==void 0){if(typeof d!="string"||d.trim()===""){a=`${f} must be a non-empty string`;break}u[f]=d}}if(a===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))a="models must be an object";else{const f={...c?.models};for(const[d,l]of Object.entries(i.models)){if(!be(d)){a=`models.${d} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){a=`models.${d} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){a=`models.${d} must be provider/id`;break}f[d]=l}u.models=f}if(a===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,d]of Object.entries(u.models))if(d.slice(0,d.indexOf("/"))!==u.providerId){a=`models.${f} provider prefix must equal providerId`;break}}if(a!==void 0){R(t,a);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function _e(e){const n=Y(),o=Y();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Z.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(_e,"resolveModelRoutes");function $n(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Z.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Z){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s($n,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>be(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Mn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Mn,"isInheritAllGlob");function N(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Mn(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(N,"mergeSpawnEnv");function L(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(L,"mergeProviderOptions");const we=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Nn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Nn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!we.test(e))return`${n}.${e} is not a safe bare command name (expected ${we.source})`}s(F,"bareCommandNameIssue");function Ln(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Ln,"binDeclarationIssues");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Fn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(ke.test(o)||r.push(`action name must match ${ke.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(Dn,"humanActionDeclarationIssues");function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Dn(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(Un,"normalizeHumanActions");function It(e){return Ln(e).map(n=>n.message)}s(It,"invalidPluginBinReasons");function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s(Tt,"normalizeRequires");function Ct(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Ct,"invalidPluginRequiresReasons");function Ae(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Ae,"normalizeKindFields");function b(e,n=cn()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Ae(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(b,"mergeKinds");let D;function $t(e){D=e}s($t,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,a)=>u.localeCompare(a)))i=b(D[c],i);return i}if(n===null)return o;const t=ae(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=b(i.manifest.kinds,r);return r}s(Se,"layerPluginKinds");function Mt(){const e=[{origin:"config.json",components:An("user").page_components}],n=g("user");if(n!==null){const o=ae("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ge(t.manifest.page_components,r)})}}return kn(e)}s(Mt,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Ae(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Nt,"invalidPluginKindsReasons");function zn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(zn,"normalizeRemoteCanvasTarget");function Kn(e,n=un()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=zn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Kn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function U(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(U,"normalizePositiveInteger");function Gn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=U(o.warning,n.warning),r=U(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Gn,"mergeBrokerThresholds");function qn(e,n){return{unattendedParkMs:U((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(qn,"mergeLifecycle");function Bn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...ie]}s(Bn,"normalizeWhipMessages");function Wn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Wn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(pn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,a={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,d=U(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=Gn(e.brokerThresholds,n.brokerThresholds),y=qn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:wn(e.working_gerunds),Oe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Ee=ge(e.page_components),Pe=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Ie=Bn(e.whip_messages),Te=rn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ce=on.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=tn.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Le=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Fe=Pn(e.keybindings),De=Cn(e.tmux_passthrough),Ue=C(e.modelLadders),ze=L(e.providerOptions,n.providerOptions),G=_e($(e.modelRoutes)),Q=G.complete,ee=M(e.modelRouting,void 0),Ke=b(e.kinds),Ge=Kn(e.remoteCanvas),qe=Wn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const Be=N(e.spawnEnv,n.spawnEnv?.allow),We=Fn(e.bin),He=Un(e.humanActions);return{bin:We,humanActions:He,schema_version:o,marketplaces:t,plugins:r,auto_update:a,max_panes_per_window:d,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:K,working_gerunds:m,whip_mode:Oe,page_components:Ee,page_surface:Pe,whip_messages:Ie,whip_message_mode:Te,mouse_mode_default:Ce,bash_tool_purpose:$e,verbosity:Me,detailed_tool_recaps:Ne,document_port:Le,keybindings:Fe,tmux_passthrough:De,modelLadders:Ue,providerOptions:ze,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ke,remoteCanvas:Ge,api:qe,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:Be}}s(z,"mergeConfig");function Hn(e){return P(e)}s(Hn,"readRawConfigAtRoot");function Jn(e){const n=g(e);return n?Hn(n):null}s(Jn,"readRawScopeConfig");function Vn(e){if(e===null||e==="")return null;try{return P(de(e))}catch{return null}}s(Vn,"readRawProfileConfig");function Zn(e,n){return[...gn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Zn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ve()||null){const o=I[T];if(o)return o.launch;const t=w(),r=Jn("user"),i=Vn(n),c=Zn(e,n);let u=b(r?.kinds,Se("user",g("user"),t.kinds)),a=C(r?.modelLadders,t.modelLadders),f=L(r?.providerOptions,t.providerOptions),d=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=N(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),a=C(i.modelLadders,a),f=L(i.providerOptions,f),d=$(i.modelRoutes,d),l=M(i.modelRouting,l),p=N(i.spawnEnv,p.allow));for(const{root:K,raw:m}of c)u=b(m?.kinds,Se("project",K,u)),m!==null&&(a=C(m.modelLadders,a),f=L(m.providerOptions,f),d=$(m.modelRoutes,d),l=M(m.modelRouting,l),p=N(m.spawnEnv,p.allow));const y=_e(d);return{kinds:u,modelLadders:a,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Re,"readMergedLaunchConfig");function Lt(e){return Re().kinds[e]}s(Lt,"resolveKindConfig");function Ft(e){const n=Re().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Ft,"subKindsAvailableTo");function Yn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Yn,"sparseModelLaddersToPersist");async function Xn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of _n)u!=="modelLadders"&&!Qe(r[u],t[u])&&(i[u]=r[u]);const c=Yn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Xn,"mutateConfigAtRoot");async function Dt(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(Dt,"persistModelLadders");async function Ut(e,n,o){if(o!==void 0)$n(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=ve(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Ut,"persistModelRoute");async function Qn(e,n){return await Xn(e,n)}s(Qn,"updateConfigAtRoot");async function zt(e,n){return await Qn(k(e),n)}s(zt,"updateConfig");async function Kt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:h(e.root),field:n}}s(Kt,"persistDefaultKindModel");async function Gt(e,n){const o=xn(e);return n(o),await En(e,o),o}s(Gt,"updateState");export{Tn as DEFAULT_TMUX_PASSTHROUGH,Rn as InvalidRawSettingsError,Ln as binDeclarationIssues,St as brokerConfigSnapshot,wt as configPath,Pt as ensureScopeInitialized,Dn as humanActionDeclarationIssues,At as installBrokerConfigSnapshot,It as invalidPluginBinReasons,Nt as invalidPluginKindsReasons,Ct as invalidPluginRequiresReasons,Fn as normalizeBin,Un as normalizeHumanActions,Tt as normalizeRequires,Cn as normalizeTmuxPassthrough,Kt as persistDefaultKindModel,Dt as persistModelLadders,Ut as persistModelRoute,An as readConfig,Sn as readConfigAtRoot,Re as readMergedLaunchConfig,Hn as readRawConfigAtRoot,Jn as readRawScopeConfig,jt as readRawSettingsForTarget,xn as readState,xt as replaceRawSettingsForTarget,Lt as resolveKindConfig,Mt as resolvePageComponents,$t as setAppPluginKinds,kt as statePath,Ft as subKindsAvailableTo,zt as updateConfig,Qn as updateConfigAtRoot,Rt as updateRawConfigAtomically,Gt as updateState,Ot as writeConfig,Et as writeRawConfig,En as writeState};
1
+ var Ve=Object.defineProperty;var s=(e,n)=>Ve(e,"name",{value:n,configurable:!0});import{envProfileId as Ze}from"../shared/env.js";import{basename as re,join as ie}from"node:path";import{existsSync as Ye,mkdirSync as Xe,statSync as Qe}from"node:fs";import{isDeepStrictEqual as en}from"node:util";import{CONFIG_FILE as nn,STATE_FILE as tn,VERBOSITY_LEVELS as on,MOUSE_MODE_DEFAULTS as rn,WHIP_MESSAGE_MODES as sn,DEFAULT_WHIP_MESSAGES as se,defaultScopeConfig as w,defaultScopeState as ce,defaultModelLaddersConfig as cn,defaultKindsConfig as un,defaultRemoteCanvasConfig as an}from"../types.js";import{BINDING_CATALOG as dn,BINDING_IDS as fn,isAttachPaneBinding as ln}from"./keybindings/catalog.js";import{notFound as pn}from"./errors.js";import{emitEvent as ue}from"./events/emit.js";import{LEDGER_ENV as mn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as gn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as yn,userScopeRoot as ae}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as fe,listProfiles as le}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as hn,readCachedSettings as B,readCachedState as bn,revisionOf as E,SettingsRevisionConflictError as pe,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as me,splitUserSettingsWrite as vn,withAppInstalls as ge}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as _n}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as wn}from"./user-settings.js";import{normalizeWorkingGerunds as kn}from"../shared/working-activity.js";import{mergePageComponentLayers as An,normalizePageComponents as ye}from"./human/page-catalog.js";function b(e){return ie(e,nn)}s(b,"configPathFor");function H(e,n){return _n(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return ie(e,tn)}s(J,"statePathFor");function wt(e){const n=g(e);return n?b(n):null}s(wt,"configPath");function kt(e){const n=g(e);return n?J(n):null}s(kt,"statePath");function S(e){const n=A(e),o=A(ae());if(n===o)return{key:"user",kind:"user",root:o};if(re(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of le()){const r=A(fe(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(re(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ae()))return O(b(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&me()?ge(hn(),o):o}s(P,"readRawAtRoot");async function he(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&me(),c=n(structuredClone((i?ge(t,r??null):r)??{}));return o=c.value,i?vn(t,c.next,E(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:E(r)}]}),o}s(he,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(b(o.root),t=>q(t,n,{createParent:!1}));return}await he(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(b(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await he(o.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function At(e){I[T]=e}s(At,"installBrokerConfigSnapshot");function St(){return I[T]}s(St,"brokerConfigSnapshot");function Sn(e){const n=I[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?jn(o):w()}s(Sn,"readConfig");function jn(e){const n=P(e);return n?z(n):w()}s(jn,"readConfigAtRoot");function xn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(xn,"readProjectState");function Rn(e){const n=g(e);return n?e==="project"?Ye(n)?xn(n):ce():bn(S(n).key):ce()}s(Rn,"readState");class On extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function be(e){if(e.scope==="user")return"user";if(!le().some(n=>n.profileId===e.profileId))throw pn(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(be,"rawSettingsKeyForTarget");function jt(e){return B(be(e))}s(jt,"readRawSettingsForTarget");async function xt(e,n,o){const t=be(e);try{z(n)}catch(u){throw new On(u)}if(B(t).revision!==o)throw new pe;const i=await W(u=>E(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new pe})()),c=E(i.settings[t]);return{revision:c,changed:c!==o}}s(xt,"replaceRawSettingsForTarget");async function Rt(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Rt,"updateRawConfigAtomically");async function Ot(e,n){await V(k(e),n)}s(Ot,"writeConfig");async function Et(e,n){await V(k(e),n)}s(Et,"writeRawConfig");function En(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(En,"writeProjectState");async function Pn(e,n){const o=k(e);if(e==="project"){En(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(Pn,"writeState");async function Pt(e,n){if(e!=="project"){gn(n);return}try{Xe(n)}catch(o){if(o.code!=="EEXIST"||!Qe(n).isDirectory())throw o}O(b(n))===null&&await V(n,{schema_version:w().schema_version})}s(Pt,"ensureScopeInitialized");function In(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(In,"normalizeKeybindings");const Tn=new Set(dn.filter(ln).map(e=>e.id)),Cn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);function $n(e){return e===void 0?[...Cn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&fn.has(n)&&Tn.has(n)))]:[]}s($n,"normalizeTmuxPassthrough");function C(e,n=cn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,a]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof a=="string"&&(r[i][u]=a)}return r}s(C,"mergeModelLadders");function ve(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(ve,"validStrength");const Z=["ultra","strong","medium","light"];function Y(){return Object.create(null)}s(Y,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function _e(e){const n=Y();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(_e,"copyRouteRecord");function R(e,n){ue({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const o=_e(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let a;for(const f of["family","credentialSource","providerId"]){const d=i[f];if(d!==void 0){if(typeof d!="string"||d.trim()===""){a=`${f} must be a non-empty string`;break}u[f]=d}}if(a===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))a="models must be an object";else{const f={...c?.models};for(const[d,l]of Object.entries(i.models)){if(!ve(d)){a=`models.${d} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){a=`models.${d} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){a=`models.${d} must be provider/id`;break}f[d]=l}u.models=f}if(a===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,d]of Object.entries(u.models))if(d.slice(0,d.indexOf("/"))!==u.providerId){a=`models.${f} provider prefix must equal providerId`;break}}if(a!==void 0){R(t,a);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function we(e){const n=Y(),o=Y();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Z.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(we,"resolveModelRoutes");function Mn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Z.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Z){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s(Mn,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>ve(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Ln(e){return e!==""&&e.replace(/\*/g,"")===""}s(Ln,"isInheritAllGlob");function L(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Ln(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(L,"mergeSpawnEnv");function N(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(N,"mergeProviderOptions");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Nn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Nn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!ke.test(e))return`${n}.${e} is not a safe bare command name (expected ${ke.source})`}s(F,"bareCommandNameIssue");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Fn,"binDeclarationIssues");function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Dn,"normalizeBin");const Ae=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(Ae.test(o)||r.push(`action name must match ${Ae.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(Un,"humanActionDeclarationIssues");function zn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Un(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(zn,"normalizeHumanActions");function It(e){return Fn(e).map(n=>n.message)}s(It,"invalidPluginBinReasons");function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s(Tt,"normalizeRequires");function Ct(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Ct,"invalidPluginRequiresReasons");function Se(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Se,"normalizeKindFields");function y(e,n=un()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Se(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(y,"mergeKinds");let D;function $t(e){D=e}s($t,"setAppPluginKinds");function X(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,a)=>u.localeCompare(a)))i=y(D[c],i);return i}if(n===null)return o;const t=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=y(i.manifest.kinds,r);return r}s(X,"layerPluginKinds");function Mt(){const e=[{origin:"config.json",components:Sn("user").page_components}],n=g("user");if(n!==null){const o=de("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ye(t.manifest.page_components,r)})}}return An(e)}s(Mt,"resolvePageComponents");const Q=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Lt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))Q.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...Q].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Se(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...Q].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Lt,"invalidPluginKindsReasons");function Kn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(Kn,"normalizeRemoteCanvasTarget");function Gn(e,n=an()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=Kn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Gn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function U(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(U,"normalizePositiveInteger");function qn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=U(o.warning,n.warning),r=U(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(qn,"mergeBrokerThresholds");function Bn(e,n){return{unattendedParkMs:U((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Bn,"mergeLifecycle");function Wn(e){if(!Array.isArray(e))return[...se];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...se]}s(Wn,"normalizeWhipMessages");function Hn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Hn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ue({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(mn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,a={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,d=U(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=qn(e.brokerThresholds,n.brokerThresholds),h=Bn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:kn(e.working_gerunds),Ee=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Pe=ye(e.page_components),Ie=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Te=Wn(e.whip_messages),Ce=sn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,$e=rn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,Me=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Le=on.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Fe=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,De=In(e.keybindings),Ue=$n(e.tmux_passthrough),ze=C(e.modelLadders),Ke=N(e.providerOptions,n.providerOptions),G=we($(e.modelRoutes)),ee=G.complete,ne=M(e.modelRouting,void 0),Ge=y(e.kinds),qe=Gn(e.remoteCanvas),Be=Hn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const te=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(oe=>Number.isSafeInteger(oe)&&oe>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const We=L(e.spawnEnv,n.spawnEnv?.allow),He=Dn(e.bin),Je=zn(e.humanActions);return{bin:He,humanActions:Je,schema_version:o,marketplaces:t,plugins:r,auto_update:a,max_panes_per_window:d,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:h,completion_bell:K,working_gerunds:m,whip_mode:Ee,page_components:Pe,page_surface:Ie,whip_messages:Te,whip_message_mode:Ce,mouse_mode_default:$e,bash_tool_purpose:Me,verbosity:Le,detailed_tool_recaps:Ne,document_port:Fe,keybindings:De,tmux_passthrough:Ue,modelLadders:ze,providerOptions:Ke,...Object.keys(ee).length>0?{modelRoutes:ee}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ne!==void 0?{modelRouting:ne}:{},kinds:Ge,remoteCanvas:qe,api:Be,...v?{paths:v}:{},...te?{store:te}:{},..._?{runtime:_}:{},spawnEnv:We}}s(z,"mergeConfig");function Jn(e){return P(e)}s(Jn,"readRawConfigAtRoot");function Vn(e){const n=g(e);return n?Jn(n):null}s(Vn,"readRawScopeConfig");function Zn(e){if(e===null||e==="")return null;try{return P(fe(e))}catch{return null}}s(Zn,"readRawProfileConfig");function Re(e,n){return e===null?[]:[...yn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Re,"readRawProjectScopeConfigs");function Oe(e=process.cwd(),n=Ze()||null){const o=I[T];if(o)return o.launch;const t=w(),r=Vn("user"),i=Zn(n),c=Re(e,n);let u=y(r?.kinds,X("user",g("user"),t.kinds)),a=C(r?.modelLadders,t.modelLadders),f=N(r?.providerOptions,t.providerOptions),d=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=L(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=y(i.kinds,u),a=C(i.modelLadders,a),f=N(i.providerOptions,f),d=$(i.modelRoutes,d),l=M(i.modelRouting,l),p=L(i.spawnEnv,p.allow));for(const{root:K,raw:m}of c)u=y(m?.kinds,X("project",K,u)),m!==null&&(a=C(m.modelLadders,a),f=N(m.providerOptions,f),d=$(m.modelRoutes,d),l=M(m.modelRouting,l),p=L(m.spawnEnv,p.allow));const h=we(d);return{kinds:u,modelLadders:a,providerOptions:f,...Object.keys(h.complete).length>0?{modelRoutes:h.complete}:{},...Object.keys(h.legacy).length>0?{legacyModelRoutes:h.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Oe,"readMergedLaunchConfig");function Nt(e,n,o){let t=e.kinds;for(const{root:r,raw:i}of Re(n,o))t=y(i?.kinds,X("project",r,t));return{...e,kinds:t}}s(Nt,"overlayProjectLaunchConfig");function Ft(e){return Oe().kinds[e]}s(Ft,"resolveKindConfig");function Dt(e){const n=Oe().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Dt,"subKindsAvailableTo");function Yn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Yn,"sparseModelLaddersToPersist");async function Xn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of wn)u!=="modelLadders"&&!en(r[u],t[u])&&(i[u]=r[u]);const c=Yn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Xn,"mutateConfigAtRoot");async function Ut(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(Ut,"persistModelLadders");async function zt(e,n,o){if(o!==void 0)Mn(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=_e(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(zt,"persistModelRoute");async function Qn(e,n){return await Xn(e,n)}s(Qn,"updateConfigAtRoot");async function Kt(e,n){return await Qn(k(e),n)}s(Kt,"updateConfig");async function Gt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:b(e.root),field:n}}s(Gt,"persistDefaultKindModel");async function qt(e,n){const o=Rn(e);return n(o),await Pn(e,o),o}s(qt,"updateState");export{Cn as DEFAULT_TMUX_PASSTHROUGH,On as InvalidRawSettingsError,Fn as binDeclarationIssues,St as brokerConfigSnapshot,wt as configPath,Pt as ensureScopeInitialized,Un as humanActionDeclarationIssues,At as installBrokerConfigSnapshot,It as invalidPluginBinReasons,Lt as invalidPluginKindsReasons,Ct as invalidPluginRequiresReasons,Dn as normalizeBin,zn as normalizeHumanActions,Tt as normalizeRequires,$n as normalizeTmuxPassthrough,Nt as overlayProjectLaunchConfig,Gt as persistDefaultKindModel,Ut as persistModelLadders,zt as persistModelRoute,Sn as readConfig,jn as readConfigAtRoot,Oe as readMergedLaunchConfig,Jn as readRawConfigAtRoot,Vn as readRawScopeConfig,jt as readRawSettingsForTarget,Rn as readState,xt as replaceRawSettingsForTarget,Ft as resolveKindConfig,Mt as resolvePageComponents,$t as setAppPluginKinds,kt as statePath,Dt as subKindsAvailableTo,Kt as updateConfig,Qn as updateConfigAtRoot,Rt as updateRawConfigAtomically,qt as updateState,Ot as writeConfig,Et as writeRawConfig,Pn as writeState};
@@ -23,15 +23,13 @@ export interface JoinResult extends Registration {
23
23
  }
24
24
  /** Provider plugin ids installed on this machine (reported for display only). */
25
25
  export declare function installedPluginIds(): string[];
26
- /** The owner a successful join recorded, or null when `crtr sys join` never wrote the client file. */
26
+ /** The owner a successful registration recorded, or null when no registration wrote the client file. */
27
27
  export declare function joinedOwner(): string | null;
28
- /** The issuer a successful join recorded, or null. */
28
+ /** The issuer a successful registration recorded, or null. */
29
29
  export declare function joinedIssuer(): string | null;
30
- /** The whole registration a successful join recorded, or null; a damaged file throws. */
30
+ /** The whole registration a successful registration recorded, or null; a damaged file throws. */
31
31
  export declare function joinedClient(): Registration | null;
32
- /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
33
- export declare function joinDirectory(directory: string, token: string, name?: string): Promise<JoinResult>;
34
32
  /** `crtr sys signin`'s registration: the signed-in person's bearer registers this computer as one of the person's runtimes, once. A computer that
35
- * already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
33
+ * already holds a registration for this directory's owner (an earlier signin) is left as it is. */
36
34
  export declare function registerSignedInMac(directory: string, bearer: string): Promise<JoinResult | null>;
37
35
  export {};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var o=(e,r)=>v(e,"name",{value:r,configurable:!0});import{createHash as U,generateKeyPairSync as D,randomUUID as J}from"node:crypto";import{existsSync as N,mkdirSync as R,readdirSync as I,rmSync as x}from"node:fs";import{request as O}from"node:http";import{hostname as S}from"node:os";import{join as _}from"node:path";import{InputError as m}from"../io.js";import{network as l}from"../errors.js";import{secretsDir as g}from"../layout.js";import{apiSocketPath as q}from"../canvas/paths.js";import{atomicWriteJson as b,readJsonIfExists as h}from"../fs-utils.js";import{launcherPresent as T}from"../grants/sandboxes.js";import{crtrVersion as A}from"../../shared/crtr-version.js";import{pluginsDir as C}from"../scope.js";function f(){return _(g(),"runtime-client.json")}o(f,"clientPath");function w(e){if(typeof e!="string")return!1;try{const{protocol:r}=new URL(e);return r==="http:"||r==="https:"}catch{return!1}}o(w,"isUrl");function y(e){const r=e??{},{runtime:i,client_id:t,issuer:u,owner:s,url:n}=r;if(typeof i!="string"||!/^runtime:.+/.test(i)||typeof t!="string"||t===""||!w(u)||typeof s!="string"||!/^user:.+/.test(s)||!w(n))throw l("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:c,is_default:a}=r;return{runtime:i,client_id:t,issuer:u,owner:s,url:n,...typeof c=="string"?{machine_id:c}:{},...typeof a=="boolean"?{is_default:a}:{}}}o(y,"registration");function d(){return _(g(),"runtime-client.pending.json")}o(d,"pendingPath");function K(){try{const e=C("user");return!e||!N(e)?[]:I(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>r.name).sort()}catch{return[]}}o(K,"installedPluginIds");async function L(e,r,i,t,u){const s=`${e.replace(/\/$/,"")}/v1/runtimes/registration`;let n;try{n=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({jwk:i,name:t,platform:`${process.platform}-${process.arch}`,crtr_version:A(),plugins:K(),sandboxed:T()}),signal:AbortSignal.timeout(3e4)})}catch(a){throw l(`directory registration request to ${s} failed: ${a instanceof Error?a.message:String(a)}`)}const c=await n.text();if(!n.ok)throw n.status<500&&x(d(),{force:!0}),new m({error:"join_refused",message:`directory refused the registration: ${n.status} ${c.slice(0,500)}`,next:u});try{return y(JSON.parse(c))}catch(a){throw a instanceof SyntaxError?l("directory registration answer is not JSON"):a}}o(L,"register");function p(){const e=h(f());if(e?.token_sha256===void 0)return null;const{owner:r}=e;if(typeof r!="string"||!/^user:.+/.test(r))throw new Error(`${f()} was written by join but has a missing or invalid owner`);return e}o(p,"readJoined");function se(){return p()?.owner??null}o(se,"joinedOwner");function ae(){return p()?.issuer??null}o(ae,"joinedIssuer");function ue(){const e=p();return e===null?null:y(e)}o(ue,"joinedClient");function z(e){return new m({error:"daemon_running",message:`cannot register while a daemon answers on ${e}`,next:"Stop the daemon that owns this volume, then run `crtr sys join` again."})}o(z,"daemonRunningError");async function F(e,r,i,t,u){const s=h(f());if(s?.token_sha256===t)return{joined:y(s),registered:!1};R(g(),{recursive:!0,mode:448});let n=h(d());if(n?.token_sha256!==t||n.directory!==e||!n.jwk||!n.public_jwk){const{privateKey:P,publicKey:$}=D("ec",{namedCurve:"P-256"}),j=J();n={token_sha256:t,directory:e,jwk:{...P.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},b(d(),n,{mode:384})}const{jwk:c,public_jwk:a}=n,k=await L(e,r,a,i,u);return{joined:k,registered:!0,client:{jwk:c,kid:c.kid,alg:"ES256",...k,token_sha256:t}}}o(F,"obtainRegistration");function W(e){if(!w(e))throw new m({error:"invalid_directory",message:"directory must be an http or https URL",received:e,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}o(W,"requireDirectory");async function E(e,r,i,t){if(W(e),r==="")throw new m({error:"invalid_token",message:"credential is empty",field:"token",next:"Pass the enrollment token provisioning supplied."});const{joined:u,registered:s,client:n}=await F(e,r,i,U("sha256").update(r).digest("hex"),t);return n&&(b(f(),n,{mode:384}),x(d(),{force:!0})),{...u,registered:s}}o(E,"registerAndStore");function B(e){return new Promise(r=>{const i=O({socketPath:e,path:"/healthz",method:"GET",timeout:1e3},t=>{t.resume(),r(!0)});i.on("timeout",()=>i.destroy(new Error("daemon probe timed out"))),i.on("error",t=>{t.code==="ENOENT"||t.code==="ECONNREFUSED"?r(!1):r(!0)}),i.end()})}o(B,"daemonAnswers");async function ce(e,r,i=S()){const t=q();if(await B(t))throw z(t);return E(e,r,i,"Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.")}o(ce,"joinDirectory");async function me(e,r){return p()!==null?null:E(e,r,S(),"Run `crtr sys signin` again.")}o(me,"registerSignedInMac");export{K as installedPluginIds,ce as joinDirectory,ue as joinedClient,ae as joinedIssuer,se as joinedOwner,me as registerSignedInMac};
1
+ var v=Object.defineProperty;var n=(r,t)=>v(r,"name",{value:t,configurable:!0});import{createHash as E,generateKeyPairSync as P,randomUUID as J}from"node:crypto";import{existsSync as U,mkdirSync as I,readdirSync as D,rmSync as x}from"node:fs";import{hostname as R}from"node:os";import{join as S}from"node:path";import{InputError as p}from"../io.js";import{network as m}from"../errors.js";import{secretsDir as g}from"../layout.js";import{atomicWriteJson as _,readJsonIfExists as w}from"../fs-utils.js";import{launcherPresent as O}from"../grants/sandboxes.js";import{crtrVersion as K}from"../../shared/crtr-version.js";import{pluginsDir as L}from"../scope.js";function f(){return S(g(),"runtime-client.json")}n(f,"clientPath");function y(r){if(typeof r!="string")return!1;try{const{protocol:t}=new URL(r);return t==="http:"||t==="https:"}catch{return!1}}n(y,"isUrl");function h(r){const t=r??{},{runtime:a,client_id:i,issuer:c,owner:o,url:e}=t;if(typeof a!="string"||!/^runtime:.+/.test(a)||typeof i!="string"||i===""||!y(c)||typeof o!="string"||!/^user:.+/.test(o)||!y(e))throw m("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:u,is_default:s}=t;return{runtime:a,client_id:i,issuer:c,owner:o,url:e,...typeof u=="string"?{machine_id:u}:{},...typeof s=="boolean"?{is_default:s}:{}}}n(h,"registration");function d(){return S(g(),"runtime-client.pending.json")}n(d,"pendingPath");function N(){try{const r=L("user");return!r||!U(r)?[]:D(r,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name).sort()}catch{return[]}}n(N,"installedPluginIds");async function q(r,t,a,i,c){const o=`${r.replace(/\/$/,"")}/v1/runtimes/registration`;let e;try{e=await fetch(o,{method:"PUT",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({jwk:a,name:i,platform:`${process.platform}-${process.arch}`,crtr_version:K(),plugins:N(),sandboxed:O()}),signal:AbortSignal.timeout(3e4)})}catch(s){throw m(`directory registration request to ${o} failed: ${s instanceof Error?s.message:String(s)}`)}const u=await e.text();if(!e.ok)throw e.status<500&&x(d(),{force:!0}),new p({error:"registration_refused",message:`directory refused the registration: ${e.status} ${u.slice(0,500)}`,next:c});try{return h(JSON.parse(u))}catch(s){throw s instanceof SyntaxError?m("directory registration answer is not JSON"):s}}n(q,"register");function l(){const r=w(f());if(r?.token_sha256===void 0)return null;const{owner:t}=r;if(typeof t!="string"||!/^user:.+/.test(t))throw new Error(`${f()} was written by registration but has a missing or invalid owner`);return r}n(l,"readJoined");function rr(){return l()?.owner??null}n(rr,"joinedOwner");function tr(){return l()?.issuer??null}n(tr,"joinedIssuer");function er(){const r=l();return r===null?null:h(r)}n(er,"joinedClient");async function A(r,t,a,i,c){const o=w(f());if(o?.token_sha256===i)return{joined:h(o),registered:!1};I(g(),{recursive:!0,mode:448});let e=w(d());if(e?.token_sha256!==i||e.directory!==r||!e.jwk||!e.public_jwk){const{privateKey:b,publicKey:$}=P("ec",{namedCurve:"P-256"}),j=J();e={token_sha256:i,directory:r,jwk:{...b.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},_(d(),e,{mode:384})}const{jwk:u,public_jwk:s}=e,k=await q(r,t,s,a,c);return{joined:k,registered:!0,client:{jwk:u,kid:u.kid,alg:"ES256",...k,token_sha256:i}}}n(A,"obtainRegistration");function C(r){if(!y(r))throw new p({error:"invalid_directory",message:"directory must be an http or https URL",received:r,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}n(C,"requireDirectory");async function T(r,t,a,i){if(C(r),t==="")throw new p({error:"invalid_token",message:"credential is empty",field:"token",next:"Sign in again with `crtr sys signin`."});const{joined:c,registered:o,client:e}=await A(r,t,a,E("sha256").update(t).digest("hex"),i);return e&&(_(f(),e,{mode:384}),x(d(),{force:!0})),{...c,registered:o}}n(T,"registerAndStore");async function nr(r,t){return l()!==null?null:T(r,t,R(),"Run `crtr sys signin` again.")}n(nr,"registerSignedInMac");export{N as installedPluginIds,er as joinedClient,tr as joinedIssuer,rr as joinedOwner,nr as registerSignedInMac};