@north-light/cli 0.3.790 → 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 (66) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/nodes.d.ts +0 -12
  4. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  5. package/dist/clients/attach/viewer.js +526 -526
  6. package/dist/commands/node/bash.js +1 -1
  7. package/dist/commands/node/inspect.js +6 -6
  8. package/dist/commands/node/lifecycle.js +4 -4
  9. package/dist/commands/node-context.js +2 -2
  10. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  11. package/dist/core/canvas/node-agent-paths.js +1 -1
  12. package/dist/core/canvas/paths.d.ts +3 -10
  13. package/dist/core/canvas/paths.js +1 -1
  14. package/dist/core/canvas/render-source.js +1 -1
  15. package/dist/core/providers/files.js +1 -1
  16. package/dist/core/runtime/bearings-render.d.ts +2 -2
  17. package/dist/core/runtime/bearings-render.js +11 -11
  18. package/dist/core/runtime/bearings.js +1 -1
  19. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  20. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  21. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  22. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  23. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  24. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  25. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  26. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  27. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  28. package/dist/core/runtime/broker-extension-render.js +2 -2
  29. package/dist/core/runtime/broker.js +1 -1
  30. package/dist/core/runtime/host.js +3 -3
  31. package/dist/core/runtime/kickoff.d.ts +1 -1
  32. package/dist/core/runtime/kickoff.js +12 -12
  33. package/dist/core/runtime/nodes.js +1 -1
  34. package/dist/core/runtime/revive.js +2 -2
  35. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  36. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  37. package/dist/core/runtime/runner/launch-env.js +1 -0
  38. package/dist/core/runtime/runner/machine/executor.js +2 -2
  39. package/dist/core/runtime/runner/types.d.ts +1 -0
  40. package/dist/core/runtime/spawn.js +2 -2
  41. package/dist/core/storage/attachments.d.ts +1 -1
  42. package/dist/core/storage/attachments.js +1 -1
  43. package/dist/core/storage/tables.d.ts +6 -2
  44. package/dist/core/storage/tables.js +4 -4
  45. package/dist/core/substrate/delivery/deliver.js +1 -1
  46. package/dist/core/substrate/delivery/render-boot.js +1 -1
  47. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  48. package/dist/daemon/api/handlers/nodes.js +1 -1
  49. package/dist/daemon/api/map.d.ts +1 -4
  50. package/dist/daemon/api/map.js +2 -2
  51. package/dist/daemon/cron/machine-fire.js +1 -1
  52. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  53. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  54. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  55. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  56. package/package.json +3 -3
  57. package/packages/crouter-api/dist/api/contract.js +1 -1
  58. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  59. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  60. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  61. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  62. package/packages/crouter-api/package.json +1 -1
  63. package/packages/crouter-identity/package.json +1 -1
  64. package/packages/crouter-plugin/package.json +3 -3
  65. package/runtime.lock.json +14 -14
  66. package/scripts/sandbox-start.mjs +5 -3
@@ -1,18 +1,18 @@
1
- var b=Object.defineProperty;var s=(e,t)=>b(e,"name",{value:t,configurable:!0});import{projectPaths as w}from"../../api/dto/profiles.js";import{contextDir as m}from"../canvas/paths.js";import{fullName as v}from"../canvas/labels.js";import{tmuxSessionsReachable as x}from"./tmux-driver.js";import{spawnSync as k}from"node:child_process";import{readdirBeneath as _}from"../spaces/open-beneath.js";import{hostname as C}from"node:os";import{loadProfileManifest as D}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function A(){const e=x();return`Host: ${[`${process.platform} ${process.arch}`,C(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function T(e){try{const n=_("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),r=n.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=n.length-r.length;return o>0?[...r,`[+${o} more]`]:r}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(T,"directoryListingLines");function f(e,t,n,r){const o=k(t,n,{cwd:e,encoding:"utf8",...r===void 0?{}:{env:r}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(f,"runCommand");function $(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s($,"gitEnv");function d(e,t){const n=f(e,"git",t,$());return n.ok?n.stdout:""}s(d,"runGit");function G(e){const t=[];let n={};for(const r of e)r.startsWith("worktree ")?(n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),n={path:r.slice(9)}):r.startsWith("branch ")&&(n.branch=r.slice(7).replace(/^refs\/heads\//,""));return n.path!==void 0&&t.push({path:n.path,branch:n.branch??"detached HEAD"}),t}s(G,"parseWorktrees");function O(e){const t=f(e,"git",["rev-parse","--is-inside-work-tree"],$());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const n=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",r=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
1
+ var g=Object.defineProperty;var s=(e,t)=>g(e,"name",{value:t,configurable:!0});import{projectPaths as b}from"../../api/dto/profiles.js";import{fullName as w}from"../canvas/labels.js";import{tmuxSessionsReachable as v}from"./tmux-driver.js";import{spawnSync as x}from"node:child_process";import{readdirBeneath as k}from"../spaces/open-beneath.js";import{hostname as _}from"node:os";import{loadProfileManifest as C}from"../profiles/manifest.js";function N(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}s(N,"escapeAttribute");function A(){const e=v();return`Host: ${[`${process.platform} ${process.arch}`,_(),`node ${process.version}`,`tmux server: ${e?"reachable":"none"}`].join(" \xB7 ")}`}s(A,"runtimeLine");function D(e){try{const r=k("/",e).sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name)),n=r.slice(0,50).map(i=>`${i.name}${i.isDirectory()?"/":""}`),o=r.length-n.length;return o>0?[...n,`[+${o} more]`]:n}catch{return["Directory listing: unavailable (cwd missing or unreadable)."]}}s(D,"directoryListingLines");function m(e,t,r,n){const o=x(t,r,{cwd:e,encoding:"utf8",...n===void 0?{}:{env:n}});return o.error!==void 0?{ok:!1,stdout:"",stderr:o.error.message}:{ok:o.status===0,stdout:(o.stdout??"").trim(),stderr:(o.stderr??"").trim()}}s(m,"runCommand");function f(){const e={...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null"};return delete e.GIT_CONFIG_PARAMETERS,delete e.GIT_CONFIG_COUNT,e}s(f,"gitEnv");function d(e,t){const r=m(e,"git",t,f());return r.ok?r.stdout:""}s(d,"runGit");function T(e){const t=[];let r={};for(const n of e)n.startsWith("worktree ")?(r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),r={path:n.slice(9)}):n.startsWith("branch ")&&(r.branch=n.slice(7).replace(/^refs\/heads\//,""));return r.path!==void 0&&t.push({path:r.path,branch:r.branch??"detached HEAD"}),t}s(T,"parseWorktrees");function G(e){const t=m(e,"git",["rev-parse","--is-inside-work-tree"],f());if(!t.ok)return/not a git repository/i.test(t.stderr)?["Git: not a git repository."]:[`Git: unavailable (${t.stderr||"git command failed"}).`];const r=d(e,["branch","--show-current"])||d(e,["rev-parse","--abbrev-ref","HEAD"])||"HEAD",n=d(e,["rev-parse","--short","HEAD"])||"unknown",o=d(e,["status","--porcelain"]).split(`
2
2
  `).filter(c=>c!=="").length,i=d(e,["worktree","list","--porcelain"]).split(`
3
- `),a=G(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${n} @ ${r}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(O,"gitSnapshotLines");function P(e){const t=T(e),n=O(e);let r=`<project_context>
3
+ `),a=T(i),u=o===0?"clean":`${o} uncommitted change${o===1?"":"s"}`,h=`Git: ${r} @ ${n}; ${u}; ${a.length} worktree${a.length===1?"":"s"}.`,l=a.length===0?"Worktrees: none.":`Worktrees: ${a.map(c=>`${c.path} (${c.branch})`).join(", ")}`;return[h,l]}s(G,"gitSnapshotLines");function B(e){const t=D(e),r=G(e);let n=`<project_context>
4
4
 
5
- `;return r+=`<environment cwd="${N(e)}">
6
- `,r+=`${A()}
7
- `,r+=`Directory:
5
+ `;return n+=`<environment cwd="${N(e)}">
6
+ `,n+=`${A()}
7
+ `,n+=`Directory:
8
8
  ${t.map(o=>` ${o}`).join(`
9
9
  `)}
10
- `,r+=`${n.map(o=>`${o}`).join(`
10
+ `,n+=`${r.map(o=>`${o}`).join(`
11
11
  `)}
12
- `,r+=`</environment>
13
- </project_context>`,r}s(P,"buildProjectContextBlock");function W(e,t){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`${m(e,t)}\` (also \`$CRTR_CONTEXT_DIR\`) holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(W,"contextDirNote");function F(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(F,"whereYouRunNote");function X(e,t){if(t==null||t==="")return"";let n;try{n=D(t)}catch{return""}const r=w(n.manifest.projects);return r.length===0?"":`Your working dir is \`${e}\`. Your profile **${n.manifest.name}** also has purview over: ${r.join(", ")}.`}s(X,"profileNote");function z(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(z,"orchestratorContextNote");function K(e,t,n){return`Context directory: \`${m(e,t)}\` (\`$CRTR_CONTEXT_DIR\`), for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${n}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(K,"forkContextNote");function y(e){const t=v(e),n=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${n}`}s(y,"relativeLabel");const j=5;function U(e,t,n,r,o){if(r.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];r.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${y(c)}`)});const u=r.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${n})`);const h=o.slice(0,j),l=o.length-h.length;return h.forEach((c,p)=>{const g=p===h.length-1&&l===0;a.push(`${i(u+1)}${g?"\u2514 ":"\u251C "}${y(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
- `)}s(U,"renderGraphMap");function q(e,t,n,r,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${n}.`];return r!=null&&r!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
- `)}s(q,"buildIdentityAssertion");function J(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
12
+ `,n+=`</environment>
13
+ </project_context>`,n}s(B,"buildProjectContextBlock");function M(e){return`Documents you write for another reader \u2014 specs, designs, findings, maps, plans \u2014 are canvas documents you own: write one with \`crtr doc write <name>\` (see \`crtr doc write -h\`), and point at it by the name it prints, \`[[${e}/<name>]]\`, never by a file path; other nodes read it with \`crtr canvas read\`, and inside this node the bare name resolves too. Your context directory \`$CRTR_CONTEXT_DIR\` holds only what is not a document: scripts, data, logs and page modules. Your working dir is the project, NOT this directory, so a bare relative \`context/...\` lands in the repo, not here.`}s(M,"contextDirNote");function P(e){return e==="blaxel"?"You run in a cloud sandbox, not on the person's computer. A file path from their Mac (such as `/Users/...` or `/var/folders/...`) does not exist here; their Mac's files and shell are reached through `crtr device`.":e==="process"||e==="machine"?"You run on the person's own computer: file paths they give you exist here.":""}s(P,"whereYouRunNote");function W(e,t){if(t==null||t==="")return"";let r;try{r=C(t)}catch{return""}const n=b(r.manifest.projects);return n.length===0?"":`Your working dir is \`${e}\`. Your profile **${r.manifest.name}** also has purview over: ${n.join(", ")}.`}s(W,"profileNote");function F(){return"Because you persist across refresh cycles, the documents you own are also where a future cycle of you resumes the work: your document `roadmap` loads at every new session, and it points at the documents holding the decisions and findings a refreshed you would need, alongside the ones you share with the nodes you spawn."}s(F,"orchestratorContextNote");function X(e){return`Context directory: \`$CRTR_CONTEXT_DIR\`, for files only; use it in place of every source-node context path above. Documents you write are yours. The source node's documents stay the source's: read them as \`[[${e}/<name>]]\`, and a bare document name in the copied conversation that meant one of them now needs that prefix.`}s(X,"forkContextNote");function $(e){const t=w(e),r=t!==""&&t!==e.kind&&t!==e.name?` \u2014 ${t}`:"";return`${e.node_id} (${e.kind} \xB7 ${e.status})${r}`}s($,"relativeLabel");const O=5;function z(e,t,r,n,o){if(n.length===0&&o.length===0)return"";const i=s(c=>" ".repeat(c),"indent"),a=["Your place in the canvas graph (ancestry above you, your direct children below):"];n.forEach((c,p)=>{a.push(`${i(p)}${p===0?"":"\u2514 "}${$(c)}`)});const u=n.length;a.push(`${i(u)}${u===0?"":"\u2514 "}\u25CF you: ${e} (${t}, ${r})`);const h=o.slice(0,O),l=o.length-h.length;return h.forEach((c,p)=>{const y=p===h.length-1&&l===0;a.push(`${i(u+1)}${y?"\u2514 ":"\u251C "}${$(c)}`)}),l>0&&a.push(`${i(u+1)}\u2514 +${l} more`),a.join(`
14
+ `)}s(z,"renderGraphMap");function K(e,t,r,n,o){const i=[`You are node ${e} \u2014 kind ${t}, mode ${r}.`];return n!=null&&n!==""&&i.push("",`You are a new FORK of ${o}, not ${o}. Pi copied the earlier conversation into this session. Treat that first-person history as reference material, not your own past.`),i.join(`
15
+ `)}s(K,"buildIdentityAssertion");function U(e){return e?.state!=="open"?"":`Branch: \`${e.branch}\`
16
16
  Worktree: \`${e.path}\`
17
17
  Base: \`${e.base_ref}\` @ \`${e.base_sha}\`
18
- Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(J,"worktreeNote");export{q as buildIdentityAssertion,P as buildProjectContextBlock,W as contextDirNote,N as escapeAttribute,K as forkContextNote,z as orchestratorContextNote,X as profileNote,y as relativeLabel,U as renderGraphMap,F as whereYouRunNote,J as worktreeNote};
18
+ Commit work here. Before finishing, land it with \`crtr node worktree close\` or keep the checkout and branch when the worktree is clean and its exact tip exists on any branch on origin. Auto-drop applies only when the worktree is clean (no uncommitted changes) and nothing remains to land (zero commits ahead of the base, or its commits are already contained in the base); otherwise, unlanded commits or uncommitted changes block finalization.`}s(U,"worktreeNote");export{K as buildIdentityAssertion,B as buildProjectContextBlock,M as contextDirNote,N as escapeAttribute,X as forkContextNote,F as orchestratorContextNote,W as profileNote,$ as relativeLabel,z as renderGraphMap,P as whereYouRunNote,U as worktreeNote};
@@ -2,6 +2,6 @@ var g=Object.defineProperty;var a=(e,n)=>g(e,"name",{value:n,configurable:!0});i
2
2
  ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
3
  </crtr-wake>`;const o=L(e);return`<crtr-wake>
4
4
  ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e,t?.grantee));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
5
+ </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
6
6
  `),n,r,k,o].filter(N=>N!=="").join(`
7
7
  `)}a(F,"bearingsShell");async function Z(e){const n=await s(e),r=await f(e);return n?.cwd!==void 0&&r?.runner==="process"?m(n.cwd):""}a(Z,"projectContextForNode");async function ee(e,n,r){const o=await Y(n),t=await $(n);return{content:await F(e,o.content,t.content,r),delivered:[...o.delivered,...t.delivered]}}a(ee,"buildContextBearings");export{te as CONTEXT_INTRO_CUSTOM_TYPE,ee as buildContextBearings,D as buildGraphMap,m as buildProjectContextBlock,V as buildWakeBearings,y as contextDirNote,Q as cronWakeOrigin,b as orchestratorContextNote,B as profileNote,Z as projectContextForNode};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var i=(a,e)=>s(a,"name",{value:e,configurable:!0});import{existsSync as m,mkdirSync as h,renameSync as p,writeFileSync as f}from"node:fs";import{dirname as l}from"node:path";import{daemonClient as y}from"./daemon-ops.js";async function A(a,e){const n=y(),o=e??(await n.listNodeAttachments(a)).attachments;for(const t of o){if(m(t.path))continue;const r=await n.readNodeAttachment(a,t.sha256);h(l(t.path),{recursive:!0});const c=`${t.path}.partial`;f(c,r),p(c,t.path)}}i(A,"fetchRunAttachments");export{A as fetchRunAttachments};
1
+ var p=Object.defineProperty;var r=(t,n)=>p(t,"name",{value:n,configurable:!0});import{existsSync as u,mkdirSync as d,renameSync as R,writeFileSync as y}from"node:fs";import{dirname as m,isAbsolute as C,join as h}from"node:path";import{daemonClient as T}from"./daemon-ops.js";import{hostContextDir as w}from"./host-path-tokens.js";async function S(t,n){const e=T(),i=n??(await e.listNodeAttachments(t)).attachments;if(i.length===0)return;const a=w();if(a===void 0)throw new Error(`cannot place attachments of node ${t}: this broker has no CRTR_CONTEXT_DIR and no CRTR_NODE_ID/CRTR_GRANTEE to derive it from`);const f=m(a);for(const s of i){const o={...s,path:x(f,s.path)};if(u(o.path))continue;const l=await e.readNodeAttachment(t,o.sha256);d(m(o.path),{recursive:!0});const c=`${o.path}.partial`;y(c,l),R(c,o.path)}}r(S,"fetchRunAttachments");function x(t,n){if(!C(n))return h(t,n);const e=/\/apps\/[^/]+\/nodes\/[^/]+\/(.+)$/.exec(n);return e===null?n:h(t,e[1])}r(x,"hostPath");export{S as fetchRunAttachments};
@@ -1,8 +1,4 @@
1
1
  import { type BashJobPaths } from '../../bash-jobs.js';
2
- /** True when the daemon's launcher starts jobs rather than this process: a Linux broker that shares the API host's
3
- * launcher. A sandbox broker (`CRTR_API_URL` set) runs on another machine, so it spawns its supervisor itself
4
- * and reports the job through `report`. */
5
- export declare function bashJobsUseLauncher(): boolean;
6
2
  /** The supervisor's optional notify arguments: the machine daemon's socket, the node and the job, only where a machine daemon runs beside the broker — an
7
3
  * install with `machine.json`, i.e. a Mac that is a machine environment. That Mac's brokers also have `CRTR_API_URL` set, so it says nothing about the
8
4
  * machine daemon. A sandbox has no `machine.json`, so it passes none and the supervisor skips the notice. */
@@ -1 +1 @@
1
- var p=Object.defineProperty;var n=(o,r)=>p(o,"name",{value:r,configurable:!0});import{spawn as h}from"node:child_process";import{writeFileSync as s}from"node:fs";import{BASH_JOB_SUPERVISOR_SCRIPT as l}from"../../bash-job-supervisor.js";import{readBashNiceness as j}from"../../bash-jobs.js";import{capturePidIdentities as g}from"../../canvas/pid.js";import{apiSocketPath as S}from"../../canvas/paths.js";import{readMachineConfig as y}from"../../../daemon/machine-link/config.js";import{freshChildNodeExecPath as P}from"../branded-host.js";import{resolveAdmittedHostCommand as I}from"../spawn-env.js";import{brokerApiUrl as w,startBrokerBashJob as x}from"./daemon-ops.js";function B(){return process.platform==="linux"&&w()===void 0}n(B,"bashJobsUseLauncher");function A(o,r){try{if(y()===void 0)return[]}catch{return[]}return[S(),o,r]}n(A,"exitNotifyArgs");async function $(o,r,a,d,c){const u=await P();if(B()){const{pid:e}=await x(o,{job_id:r.jobId,cwd:d,env:c});return{pgid:e,identity:`launcher:${e}`}}const m=I("bash",c,d),t=h(m,["-c",l,"--",r.cmdSh,r.jobLog,r.jobExit,r.jobRun,r.jobDone,m,String(j(a)),u,r.jobActivity,...A(o,r.jobId)],{cwd:d,detached:!0,stdio:"ignore",env:c}),i=await new Promise((e,b)=>{t.once("error",b),t.pid!==void 0&&e(t.pid)});t.unref();const f=g([i])?.get(i);if(f===void 0){try{process.kill(-i,"SIGKILL")}catch{}throw new Error(`bash job ${r.jobId} started without a process identity`)}return s(r.jobPgid,String(i)),s(r.jobPgidIdentity,f),{pgid:i,identity:f}}n($,"launchBashJobSupervisor");export{B as bashJobsUseLauncher,A as exitNotifyArgs,$ as launchBashJobSupervisor};
1
+ var p=Object.defineProperty;var n=(i,o)=>p(i,"name",{value:o,configurable:!0});import{spawn as S}from"node:child_process";import{writeFileSync as f}from"node:fs";import{BASH_JOB_SUPERVISOR_SCRIPT as g}from"../../bash-job-supervisor.js";import{readBashNiceness as h}from"../../bash-jobs.js";import{capturePidIdentities as j}from"../../canvas/pid.js";import{apiSocketPath as l}from"../../canvas/paths.js";import{readMachineConfig as y}from"../../../daemon/machine-link/config.js";import{freshChildNodeExecPath as P}from"../branded-host.js";import{resolveAdmittedHostCommand as I}from"../spawn-env.js";function w(i,o){try{if(y()===void 0)return[]}catch{return[]}return[l(),i,o]}n(w,"exitNotifyArgs");async function v(i,o,s,d,c){const a=await P(),m=I("bash",c,d),t=S(m,["-c",g,"--",o.cmdSh,o.jobLog,o.jobExit,o.jobRun,o.jobDone,m,String(h(s)),a,o.jobActivity,...w(i,o.jobId)],{cwd:d,detached:!0,stdio:"ignore",env:c}),r=await new Promise((u,b)=>{t.once("error",b),t.pid!==void 0&&u(t.pid)});t.unref();const e=j([r])?.get(r);if(e===void 0){try{process.kill(-r,"SIGKILL")}catch{}throw new Error(`bash job ${o.jobId} started without a process identity`)}return f(o.jobPgid,String(r)),f(o.jobPgidIdentity,e),{pgid:r,identity:e}}n(v,"launchBashJobSupervisor");export{w as exitNotifyArgs,v as launchBashJobSupervisor};
@@ -18,18 +18,10 @@ export declare function putBrokerRecap(nodeId: string, briefing: string): Promis
18
18
  export declare function readBrokerPassiveMessage(nodeId: string, ref: string): Promise<NodeMessageBodyDTO>;
19
19
  export declare function clearBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
20
20
  export declare function consumeBrokerPushedFinal(nodeId: string): Promise<NodePushedFinalResultDTO>;
21
- export declare function startBrokerBashJob(nodeId: string, request: {
22
- job_id: string;
23
- cwd: string;
24
- env: NodeJS.ProcessEnv;
25
- }): Promise<{
26
- pid: number;
27
- }>;
28
21
  /** Record a command the valve just backgrounded as this node's job object. */
29
22
  export declare function recordBackgroundedJob(nodeId: string, jobId: string, request: BackgroundedJobRequest): Promise<BackgroundedJobDTO>;
30
23
  /** Report on a job this broker runs: process identity, activity, output, exit. */
31
24
  export declare function reportBrokerJob(nodeId: string, jobId: string, request: Omit<JobReportRequest, 'expected_execution_id'>): Promise<void>;
32
- export declare function stopBrokerBashJob(nodeId: string, jobId: string): Promise<void>;
33
25
  export declare function brokerExecutionId(): string;
34
26
  export declare function bindBrokerSession(nodeId: string, request: Omit<BrokerSessionBoundRequest, 'executionId'>): Promise<BrokerSessionBoundResultDTO>;
35
27
  type BrokerInput<T> = T extends unknown ? Omit<T, 'expected_execution_id'> : never;
@@ -1 +1 @@
1
- var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{CrtrClient as y}from"../../../api/client.js";import{currentNodeToken as R}from"./node-token.js";import{localClient as w}from"../../../api/node-transport.js";import{ApiError as x}from"../../../api/errors.js";import{crtrVersion as b}from"../../../shared/crtr-version.js";import{envExecutionId as v}from"../../../shared/env.js";import{brokerSignalClient as P}from"./signal-stream.js";import{emitEvent as N}from"../../events/emit.js";import{cachedBrokerNodeFields as k}from"../../../daemon/broker-signals/bus.js";import{fetchRunAttachments as g}from"./attachments-fetch.js";import{reportRefNodeId as C}from"../../../shared/inbox-entry-body.js";function E(){const e=process.env.CRTR_API_URL;if(!(e===void 0||e==="")){if(!/^https?:\/\//.test(e))throw new Error(`CRTR_API_URL must be an http(s) URL: ${e}`);return e}}t(E,"brokerApiUrl");function o(){const e=E();if(e===void 0)return w({autostart:!1});const r=R();if(r===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new y({baseUrl:e,headers:{authorization:`Bearer ${r}`}})}t(o,"daemonClient");function O(e,r){return o().appendNodeLog(e,{record:r,expected_execution_id:n()})}t(O,"appendBrokerLog");function V(e,r){return o().putNodeTelemetry(e,{...r,expected_execution_id:n()})}t(V,"putBrokerTelemetry");function q(e,r){return o().putNodeRecap(e,{briefing:r,expected_execution_id:n()})}t(q,"putBrokerRecap");function W(e,r){return o().readNodePassiveMessage(e,r)}t(W,"readBrokerPassiveMessage");function X(e){return o().nodePushedFinal(e,{action:"clear",expected_execution_id:n()})}t(X,"clearBrokerPushedFinal");function H(e){return o().nodePushedFinal(e,{action:"consume",expected_execution_id:n()})}t(H,"consumeBrokerPushedFinal");function K(e,r){return o().request("POST",`/v1/nodes/${encodeURIComponent(e)}/jobs/start`,{...r,expected_execution_id:n()})}t(K,"startBrokerBashJob");function Q(e,r,i){return o().recordBackgroundedJob(e,r,i)}t(Q,"recordBackgroundedJob");function Y(e,r,i){return o().reportBashJob(e,r,{...i,expected_execution_id:n()})}t(Y,"reportBrokerJob");function Z(e,r){return o().request("DELETE",`/v1/nodes/${encodeURIComponent(e)}/jobs/${encodeURIComponent(r)}?foreground=1`,{expected_execution_id:n()})}t(Z,"stopBrokerBashJob");function n(){const e=v();if(e===void 0||e==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return e}t(n,"brokerExecutionId");function ee(e,r){return o().bindBrokerSession(e,{...r,executionId:n()})}t(ee,"bindBrokerSession");function re(e,r){return o().settleBroker(e,{...r,expected_execution_id:n()})}t(re,"settleBroker");function te(e){return o().startBrokerCycle(e,{expected_execution_id:n(),brokerVersion:b()})}t(te,"startBrokerCycle");function oe(e){return o().postBrokerIdle(e,{expected_execution_id:n()})}t(oe,"postBrokerIdle");function ne(e,r){return o().completeBrokerPark(e,{...r,expected_execution_id:n()})}t(ne,"completeBrokerPark");function ie(e){return o().recordBrokerParkActivity(e,{expected_execution_id:n()})}t(ie,"recordBrokerParkActivity");function ce(e,r){return o().recordBrokerTelemetry(e,{...r,expected_execution_id:n()})}t(ce,"recordBrokerTelemetry");const m=new Set;async function de(e,r,i){const a=o(),p=n(),s=await a.claimNodeMail(e,{execution_id:p,channel:r});if(s.action==="hold")return s;const l=s.deliveries.filter(d=>!m.has(d.entry.entry_id));if(l.length>0){await g(e);for(const d of l)m.add(d.entry.entry_id)}const f=await Promise.all(s.deliveries.map(async d=>{const c=d.entry.ref;if(c===void 0||C(c)===void 0)return d;try{let u=i.get(c);u===void 0&&(u=a.readNodeInboxReport(e,c,p).then(({content:B})=>B),i.set(c,u));const _=await u;return{...d,entry:{...d.entry,data:{...d.entry.data,report_body:_}}}}catch(u){if(i.delete(c),u instanceof x&&u.status===404)return d;throw u}}));if(f.length>0){const d=new Set(f.map(({entry:c})=>c.ref).filter(c=>c!==void 0));for(const c of i.keys())d.has(c)||i.delete(c)}return{...s,deliveries:f}}t(de,"claimBrokerMail");async function ue(e,r){return await(await import("../../conversation-store/index.js")).flushConversation(),o().acknowledgeNodeMail(e,{execution_id:n(),deliveries:r})}t(ue,"acknowledgeBrokerMail");function ae(e,r){return o().recordBrokerTurn(e,{...r,expected_execution_id:n()})}t(ae,"recordBrokerTurn");function se(e,r){return o().mutateBrokerProviderRetry(e,{...r,expected_execution_id:n()})}t(se,"mutateBrokerProviderRetry");function T(e,r){return o().mutateBrokerFault(e,{...r,expected_execution_id:n()})}t(T,"mutateBrokerFault");async function pe(e,r){const i=T(e,{op:"record",input:{link:"daemon\u2192node",op:"conversation_write_failed",kind:"other",retry:{disposition:"manual"},message:r instanceof Error?r.message:String(r)}});await Promise.race([i,new Promise((a,p)=>setTimeout(()=>p(new Error("conversation_write_failed fault record timed out")),5e3).unref())]).catch(a=>N({level:"error",event:"broker.daemon.operation.failed",node_id:e,error:a,fields:{operation:"conversation_write_fault_record"}}))}t(pe,"recordConversationWriteFault");function fe(e){return o().getBrokerRecovery(e,n())}t(fe,"brokerRecovery");async function le(e,r){return o().recordNodeFault(e,r)}t(le,"recordNodeFault");async function xe(e,r={}){return o().clearNodeFault(e,{...r.link===void 0?{}:{link:r.link},...r.preserveEpisode===void 0?{}:{preserve_episode:r.preserveEpisode}}).then(i=>i.cleared)}t(xe,"clearNodeFault");function ke(e,r){return o().commitBrokerModel(e,{...r,expected_execution_id:n()})}t(ke,"commitBrokerModel");function I(e){return o().brokerExtensionState(e)}t(I,"brokerExtensionState");async function me(e){const r=P();return r.state==="connected"&&r.latestNode!==void 0?k(r.latestNode):k((await I(e)).node)}t(me,"cachedBrokerNode");function _e(e,r){return o().nodeDelivery(e,{...r,expected_execution_id:n()})}t(_e,"brokerDelivery");function Be(e,r){return o().commitBrokerGeneratedName(e,{...r,expected_execution_id:n()})}t(Be,"commitBrokerGeneratedName");function he(e,r){return o().commitBrokerPersonaAck(e,{...r,expected_execution_id:n()})}t(he,"commitBrokerPersonaAck");async function ye(e,r){try{await o().pushReport(e,r)}catch(i){if(r.tier==="final"&&i instanceof x&&i.code==="already_finalized")return;throw i}}t(ye,"publishBrokerReport");function Re(e){return o().relaunchRoot(e)}t(Re,"relaunchBrokerRoot");export{ue as acknowledgeBrokerMail,O as appendBrokerLog,ee as bindBrokerSession,E as brokerApiUrl,_e as brokerDelivery,n as brokerExecutionId,I as brokerExtensionState,fe as brokerRecovery,me as cachedBrokerNode,de as claimBrokerMail,X as clearBrokerPushedFinal,xe as clearNodeFault,Be as commitBrokerGeneratedName,ke as commitBrokerModel,he as commitBrokerPersonaAck,ne as completeBrokerPark,H as consumeBrokerPushedFinal,o as daemonClient,T as mutateBrokerFault,se as mutateBrokerProviderRetry,oe as postBrokerIdle,ye as publishBrokerReport,q as putBrokerRecap,V as putBrokerTelemetry,W as readBrokerPassiveMessage,Q as recordBackgroundedJob,ie as recordBrokerParkActivity,ce as recordBrokerTelemetry,ae as recordBrokerTurn,pe as recordConversationWriteFault,le as recordNodeFault,Re as relaunchBrokerRoot,Y as reportBrokerJob,re as settleBroker,K as startBrokerBashJob,te as startBrokerCycle,Z as stopBrokerBashJob};
1
+ var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{CrtrClient as y}from"../../../api/client.js";import{currentNodeToken as w}from"./node-token.js";import{localClient as R}from"../../../api/node-transport.js";import{ApiError as x}from"../../../api/errors.js";import{crtrVersion as v}from"../../../shared/crtr-version.js";import{envExecutionId as b}from"../../../shared/env.js";import{brokerSignalClient as N}from"./signal-stream.js";import{emitEvent as P}from"../../events/emit.js";import{cachedBrokerNodeFields as k}from"../../../daemon/broker-signals/bus.js";import{fetchRunAttachments as g}from"./attachments-fetch.js";import{reportRefNodeId as C}from"../../../shared/inbox-entry-body.js";function E(){const e=process.env.CRTR_API_URL;if(!(e===void 0||e==="")){if(!/^https?:\/\//.test(e))throw new Error(`CRTR_API_URL must be an http(s) URL: ${e}`);return e}}t(E,"brokerApiUrl");function o(){const e=E();if(e===void 0)return R({autostart:!1});const r=w();if(r===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new y({baseUrl:e,headers:{authorization:`Bearer ${r}`}})}t(o,"daemonClient");function O(e,r){return o().appendNodeLog(e,{record:r,expected_execution_id:n()})}t(O,"appendBrokerLog");function W(e,r){return o().putNodeTelemetry(e,{...r,expected_execution_id:n()})}t(W,"putBrokerTelemetry");function X(e,r){return o().putNodeRecap(e,{briefing:r,expected_execution_id:n()})}t(X,"putBrokerRecap");function j(e,r){return o().readNodePassiveMessage(e,r)}t(j,"readBrokerPassiveMessage");function H(e){return o().nodePushedFinal(e,{action:"clear",expected_execution_id:n()})}t(H,"clearBrokerPushedFinal");function K(e){return o().nodePushedFinal(e,{action:"consume",expected_execution_id:n()})}t(K,"consumeBrokerPushedFinal");function Q(e,r,i){return o().recordBackgroundedJob(e,r,i)}t(Q,"recordBackgroundedJob");function Y(e,r,i){return o().reportBashJob(e,r,{...i,expected_execution_id:n()})}t(Y,"reportBrokerJob");function n(){const e=b();if(e===void 0||e==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return e}t(n,"brokerExecutionId");function Z(e,r){return o().bindBrokerSession(e,{...r,executionId:n()})}t(Z,"bindBrokerSession");function q(e,r){return o().settleBroker(e,{...r,expected_execution_id:n()})}t(q,"settleBroker");function ee(e){return o().startBrokerCycle(e,{expected_execution_id:n(),brokerVersion:v()})}t(ee,"startBrokerCycle");function re(e){return o().postBrokerIdle(e,{expected_execution_id:n()})}t(re,"postBrokerIdle");function te(e,r){return o().completeBrokerPark(e,{...r,expected_execution_id:n()})}t(te,"completeBrokerPark");function oe(e){return o().recordBrokerParkActivity(e,{expected_execution_id:n()})}t(oe,"recordBrokerParkActivity");function ne(e,r){return o().recordBrokerTelemetry(e,{...r,expected_execution_id:n()})}t(ne,"recordBrokerTelemetry");const m=new Set;async function ie(e,r,i){const a=o(),p=n(),s=await a.claimNodeMail(e,{execution_id:p,channel:r});if(s.action==="hold")return s;const l=s.deliveries.filter(u=>!m.has(u.entry.entry_id));if(l.length>0){await g(e);for(const u of l)m.add(u.entry.entry_id)}const f=await Promise.all(s.deliveries.map(async u=>{const c=u.entry.ref;if(c===void 0||C(c)===void 0)return u;try{let d=i.get(c);d===void 0&&(d=a.readNodeInboxReport(e,c,p).then(({content:B})=>B),i.set(c,d));const _=await d;return{...u,entry:{...u.entry,data:{...u.entry.data,report_body:_}}}}catch(d){if(i.delete(c),d instanceof x&&d.status===404)return u;throw d}}));if(f.length>0){const u=new Set(f.map(({entry:c})=>c.ref).filter(c=>c!==void 0));for(const c of i.keys())u.has(c)||i.delete(c)}return{...s,deliveries:f}}t(ie,"claimBrokerMail");async function ce(e,r){return await(await import("../../conversation-store/index.js")).flushConversation(),o().acknowledgeNodeMail(e,{execution_id:n(),deliveries:r})}t(ce,"acknowledgeBrokerMail");function ue(e,r){return o().recordBrokerTurn(e,{...r,expected_execution_id:n()})}t(ue,"recordBrokerTurn");function de(e,r){return o().mutateBrokerProviderRetry(e,{...r,expected_execution_id:n()})}t(de,"mutateBrokerProviderRetry");function T(e,r){return o().mutateBrokerFault(e,{...r,expected_execution_id:n()})}t(T,"mutateBrokerFault");async function ae(e,r){const i=T(e,{op:"record",input:{link:"daemon\u2192node",op:"conversation_write_failed",kind:"other",retry:{disposition:"manual"},message:r instanceof Error?r.message:String(r)}});await Promise.race([i,new Promise((a,p)=>setTimeout(()=>p(new Error("conversation_write_failed fault record timed out")),5e3).unref())]).catch(a=>P({level:"error",event:"broker.daemon.operation.failed",node_id:e,error:a,fields:{operation:"conversation_write_fault_record"}}))}t(ae,"recordConversationWriteFault");function se(e){return o().getBrokerRecovery(e,n())}t(se,"brokerRecovery");async function pe(e,r){return o().recordNodeFault(e,r)}t(pe,"recordNodeFault");async function fe(e,r={}){return o().clearNodeFault(e,{...r.link===void 0?{}:{link:r.link},...r.preserveEpisode===void 0?{}:{preserve_episode:r.preserveEpisode}}).then(i=>i.cleared)}t(fe,"clearNodeFault");function le(e,r){return o().commitBrokerModel(e,{...r,expected_execution_id:n()})}t(le,"commitBrokerModel");function F(e){return o().brokerExtensionState(e)}t(F,"brokerExtensionState");async function xe(e){const r=N();return r.state==="connected"&&r.latestNode!==void 0?k(r.latestNode):k((await F(e)).node)}t(xe,"cachedBrokerNode");function ke(e,r){return o().nodeDelivery(e,{...r,expected_execution_id:n()})}t(ke,"brokerDelivery");function me(e,r){return o().commitBrokerGeneratedName(e,{...r,expected_execution_id:n()})}t(me,"commitBrokerGeneratedName");function _e(e,r){return o().commitBrokerPersonaAck(e,{...r,expected_execution_id:n()})}t(_e,"commitBrokerPersonaAck");async function Be(e,r){try{await o().pushReport(e,r)}catch(i){if(r.tier==="final"&&i instanceof x&&i.code==="already_finalized")return;throw i}}t(Be,"publishBrokerReport");function he(e){return o().relaunchRoot(e)}t(he,"relaunchBrokerRoot");export{ce as acknowledgeBrokerMail,O as appendBrokerLog,Z as bindBrokerSession,E as brokerApiUrl,ke as brokerDelivery,n as brokerExecutionId,F as brokerExtensionState,se as brokerRecovery,xe as cachedBrokerNode,ie as claimBrokerMail,H as clearBrokerPushedFinal,fe as clearNodeFault,me as commitBrokerGeneratedName,le as commitBrokerModel,_e as commitBrokerPersonaAck,te as completeBrokerPark,K as consumeBrokerPushedFinal,o as daemonClient,T as mutateBrokerFault,de as mutateBrokerProviderRetry,re as postBrokerIdle,Be as publishBrokerReport,X as putBrokerRecap,W as putBrokerTelemetry,j as readBrokerPassiveMessage,Q as recordBackgroundedJob,oe as recordBrokerParkActivity,ne as recordBrokerTelemetry,ue as recordBrokerTurn,ae as recordConversationWriteFault,pe as recordNodeFault,he as relaunchBrokerRoot,Y as reportBrokerJob,q as settleBroker,ee as startBrokerCycle};
@@ -65,4 +65,4 @@ export declare function createFrameDispatchContext(deps: FrameDispatchDeps): {
65
65
  refreshMemoryNames: (names: import("./frame-memory-refs.js").ComposerNames | undefined) => Promise<void>;
66
66
  };
67
67
  /** The socket listener calls this explicit dispatcher for every decoded client frame. */
68
- export declare function handleFrame(ctx: FrameDispatchContext, client: BrokerClient, frame: ClientToBroker): void;
68
+ export declare function handleFrame(ctx: FrameDispatchContext, client: BrokerClient, rawFrame: ClientToBroker): void;
@@ -1 +1 @@
1
- var U=Object.defineProperty;var o=(n,e)=>U(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as $}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as V,createPromptDispatchTracker as X,createTurnAcceptanceGate as Y}from"./turn-ignition.js";import{prependRunDeferredMail as v}from"./run-deferred-mail.js";function de(n){const{nodeId:e,registry:s,toolGroups:c,projection:k,rebind:p,boundaryReviewId:m,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:F,broadcastModelChanged:M,registryOf:S,formatModelSpec:E,formatExactModelSpec:R,turnAdmission:h,runNode:f,memoryInventory:H,onKickoffAdmitted:P}=n,a=o(()=>p.session(),"currentSession"),T=o(()=>p.services(),"currentServices"),i=j(s),{notWritable:G}=i,d=B(a,e,H),u=X(a),_=Y(),g=V({session:a,dispatches:u,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0,onAdmitted:P}),y=q({nodeId:e,registry:s,replies:i,session:a,dispatches:u,memoryRefs:d,rebind:p,projection:k,toolGroups:c,turnAdmission:h,prependDeferred:f?r=>v(e,r):void 0}),I=o((r,t)=>{G(r,"drive the engine")||((t.type==="prompt"||t.type==="steer"||t.type==="follow_up")&&$(t.text,{type:"human",channel:{type:"viewer"}}),y(r,t))},"handleDriveFrame"),l=z({registry:s,replies:i,session:a,driveEngine:y,turnAcceptance:_,pendingDialogs:w,sendWelcome:b,replayExtraPendingDialogsTo:D,disposeAndExit:C}),W=J({registry:s,replies:i,session:a,services:T,registryOf:S,persistModelChoice:F,broadcastModelChanged:o(async(...r)=>{await M(...r),g.drivePending()},"broadcastModelChanged"),formatModelSpec:E}),K=L({nodeId:e,registry:s,replies:i,session:a,boundaryReviewId:m,memoryRefs:d,formatExactModelSpec:R}),N=Q({registry:s,replies:i,rebind:p,session:a,boundaryReviewId:m,memoryRefs:d,reWelcomeAll:A});return{handlers:{hello:l.hello,drive:I,deliver:l.deliver,dialog:l.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{i.ackTo(r,"reload_auth")},"authentication"),bye:l.bye,shutdown:l.shutdown},kickoff:o((r,t)=>g.kickoff(r,t),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:u.pending,resetForSession:o(()=>{},"resetForSession"),refuseUnknown:o((r,t,O)=>s.sendFrame(r,{type:"error",code:"unknown_frame",id:O,message:`this broker does not handle '${t}' frames`}),"refuseUnknown"),refreshMemoryNames:o(r=>r===void 0?d.invalidate():(d.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(de,"createFrameDispatchContext");function le(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return;default:{const c=s;typeof c.id=="string"&&n.refuseUnknown(e,String(c.type),c.id)}}}o(le,"handleFrame");export{de as createFrameDispatchContext,le as handleFrame};
1
+ var O=Object.defineProperty;var o=(r,e)=>O(r,"name",{value:e,configurable:!0});import{createFrameReplies as U}from"./frame-replies.js";import{createEngineDriver as j}from"./engine-drive.js";import{expandHostPathTokens as q}from"./host-path-tokens.js";import{announceMessageOrigin as $}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as V,createPromptDispatchTracker as X,createTurnAcceptanceGate as Y}from"./turn-ignition.js";import{prependRunDeferredMail as k}from"./run-deferred-mail.js";function pe(r){const{nodeId:e,registry:n,toolGroups:t,projection:c,rebind:m,boundaryReviewId:f,pendingDialogs:b,sendWelcome:D,replayExtraPendingDialogsTo:w,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:M,broadcastModelChanged:S,registryOf:E,formatModelSpec:R,formatExactModelSpec:H,turnAdmission:h,runNode:_,memoryInventory:P,onKickoffAdmitted:T}=r,i=o(()=>m.session(),"currentSession"),F=o(()=>m.services(),"currentServices"),d=U(n),{notWritable:G}=d,l=B(i,e,P),u=X(i),g=Y(),y=V({session:i,dispatches:u,turnAdmission:h,prependDeferred:_?s=>k(e,s):void 0,onAdmitted:T}),v=j({nodeId:e,registry:n,replies:d,session:i,dispatches:u,memoryRefs:l,rebind:m,projection:c,toolGroups:t,turnAdmission:h,prependDeferred:_?s=>k(e,s):void 0}),I=o((s,a)=>{G(s,"drive the engine")||((a.type==="prompt"||a.type==="steer"||a.type==="follow_up")&&$(a.text,{type:"human",channel:{type:"viewer"}}),v(s,a))},"handleDriveFrame"),p=z({registry:n,replies:d,session:i,driveEngine:v,turnAcceptance:g,pendingDialogs:b,sendWelcome:D,replayExtraPendingDialogsTo:w,disposeAndExit:C}),W=J({registry:n,replies:d,session:i,services:F,registryOf:E,persistModelChoice:M,broadcastModelChanged:o(async(...s)=>{await S(...s),y.drivePending()},"broadcastModelChanged"),formatModelSpec:R}),x=L({nodeId:e,registry:n,replies:d,session:i,boundaryReviewId:f,memoryRefs:l,formatExactModelSpec:H}),K=Q({registry:n,replies:d,rebind:m,session:i,boundaryReviewId:f,memoryRefs:l,reWelcomeAll:A});return{handlers:{hello:p.hello,drive:I,deliver:p.deliver,dialog:p.dialog,engineControl:W,read:x,session:K,authentication:o(s=>{d.ackTo(s,"reload_auth")},"authentication"),bye:p.bye,shutdown:p.shutdown},kickoff:o((s,a)=>y.kickoff(s,a),"kickoff"),notifyTurnAccepted:g.notifyAccepted,pendingPromptDispatches:u.pending,resetForSession:o(()=>{},"resetForSession"),refuseUnknown:o((s,a,N)=>n.sendFrame(s,{type:"error",code:"unknown_frame",id:N,message:`this broker does not handle '${a}' frames`}),"refuseUnknown"),refreshMemoryNames:o(s=>s===void 0?l.invalidate():(l.replace(s),Promise.resolve()),"refreshMemoryNames")}}o(pe,"createFrameDispatchContext");function me(r,e,n){const t=n.type==="prompt"||n.type==="steer"||n.type==="follow_up"||n.type==="deliver"?{...n,text:q(n.text)}:n;switch(t.type){case"hello":r.handlers.hello(e,t);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":r.handlers.drive(e,t);return;case"deliver":r.handlers.deliver(e,t);return;case"extension_ui_response":r.handlers.dialog(e,t);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":r.handlers.engineControl(e,t);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":case"get_git_status":case"upload_file":r.handlers.read(e,t);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":r.handlers.session(e,t);return;case"reload_auth":r.handlers.authentication(e);return;case"bye":r.handlers.bye(e);return;case"shutdown":r.handlers.shutdown(e);return;default:{const c=t;typeof c.id=="string"&&r.refuseUnknown(e,String(c.type),c.id)}}}o(me,"handleFrame");export{pe as createFrameDispatchContext,me as handleFrame};
@@ -0,0 +1,5 @@
1
+ /** The control plane renders prompt text with `$CRTR_CONTEXT_DIR` and `$CRTR_NODE_DIR` as literal tokens, because only the machine that hosts a node's broker
2
+ * knows where the node's folder is. The broker swaps them for its own paths before the text reaches the model. Text is unchanged when the env names no context dir. */
3
+ export declare function expandHostPathTokens(text: string): string;
4
+ /** The broker's own context dir: its env, else derived from its node id and app on this host's layout. */
5
+ export declare function hostContextDir(): string | undefined;
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});import{dirname as R}from"node:path";import{contextDir as s}from"../../canvas/paths.js";function u(n){if(!n.includes("$CRTR_"))return n;const e=c();return e===void 0?n:n.replaceAll("$CRTR_CONTEXT_DIR",e).replaceAll("$CRTR_NODE_DIR",R(e))}r(u,"expandHostPathTokens");function c(){const n=process.env.CRTR_CONTEXT_DIR;if(n!==void 0&&n!=="")return n;const e=process.env.CRTR_NODE_ID,o=process.env.CRTR_GRANTEE;return e&&o?s(e,o):void 0}r(c,"hostContextDir");export{u as expandHostPathTokens,c as hostContextDir};
@@ -1,3 +1,3 @@
1
- var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import{fullName as h}from"../canvas/labels.js";import{profileNote as f,renderGraphMap as p,buildIdentityAssertion as m,forkContextNote as g,orchestratorContextNote as w,worktreeNote as k}from"./bearings-render.js";function S(e){const r=(e.icon??"").trim(),t=e.name!==e.kind?e.name.trim():"",n=t!==""?t:(e.description??"").trim()||e.name;return r===""?n:`${r} ${n}`}i(S,"editorLabelForBrokerNode");function y(e){return f(e.cwd,e.profile_id)}i(y,"profileNote");function b(e){const{ancestors:r,children:t,node:n}=e;return p(n.node_id,n.kind,n.mode,r,t)}i(b,"graphMap");function v(e){const{node:r,fork_source:t}=e,n=t===null?r.fork_from??"":`${r.fork_from} ("${h(t)}")`;return m(r.node_id,r.kind,r.mode,r.fork_from,n)}i(v,"identity");function _(e){return k(e.managed_worktree)}i(_,"worktreeNote");function x(e){const r=e.review_binding;if(r==null)return"";if(r.kind==="page_feedback"){const t=r.review_id,n=r.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${t}\`, page source \`${n}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${t} --page ${n}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${t}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of the canvas document \`${r.target_file}\`, which you revise with \`crtr doc edit\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}i(x,"reviewNote");function F(e,r=""){const{node:t,fork_source:n}=e,l=n?.status==="active"||n?.status==="idle"?`Source node ${n.node_id} ("${h(n)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",o=["<crtr-bearings>",v(e),"",l,"","## Your node now",`Lifecycle: ${t.lifecycle}.`],s=b(e);if(o.push(...s===""?["Canvas: independent root with no parent or inherited graph edges."]:["",s]),o.push(g(t.node_id,t.grantee,t.fork_from??"")),(n===null||n.cwd!==t.cwd)&&o.push(`Working directory: \`${t.cwd}\`.`),n===null||n.profile_id!==t.profile_id){const a=y(t);a!==""&&o.push(a)}const c=_(t);c!==""&&o.push("","## Your managed worktree",c),t.mode==="orchestrator"&&o.push("",w());const d=x(t);return d!==""&&o.push("",d),o.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[o.join(`
2
- `),r].filter(a=>a!=="").join(`
1
+ var u=Object.defineProperty;var i=(e,t)=>u(e,"name",{value:t,configurable:!0});import{fullName as h}from"../canvas/labels.js";import{profileNote as f,renderGraphMap as p,buildIdentityAssertion as m,forkContextNote as g,orchestratorContextNote as w,worktreeNote as k}from"./bearings-render.js";function S(e){const t=(e.icon??"").trim(),r=e.name!==e.kind?e.name.trim():"",n=r!==""?r:(e.description??"").trim()||e.name;return t===""?n:`${t} ${n}`}i(S,"editorLabelForBrokerNode");function y(e){return f(e.cwd,e.profile_id)}i(y,"profileNote");function b(e){const{ancestors:t,children:r,node:n}=e;return p(n.node_id,n.kind,n.mode,t,r)}i(b,"graphMap");function v(e){const{node:t,fork_source:r}=e,n=r===null?t.fork_from??"":`${t.fork_from} ("${h(r)}")`;return m(t.node_id,t.kind,t.mode,t.fork_from,n)}i(v,"identity");function _(e){return k(e.managed_worktree)}i(_,"worktreeNote");function x(e){const t=e.review_binding;if(t==null)return"";if(t.kind==="page_feedback"){const r=t.review_id,n=t.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${r}\`, page source \`${n}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${r} --page ${n}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${r}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of the canvas document \`${t.target_file}\`, which you revise with \`crtr doc edit\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}i(x,"reviewNote");function F(e,t=""){const{node:r,fork_source:n}=e,l=n?.status==="active"||n?.status==="idle"?`Source node ${n.node_id} ("${h(n)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",o=["<crtr-bearings>",v(e),"",l,"","## Your node now",`Lifecycle: ${r.lifecycle}.`],s=b(e);if(o.push(...s===""?["Canvas: independent root with no parent or inherited graph edges."]:["",s]),o.push(g(r.fork_from??"")),(n===null||n.cwd!==r.cwd)&&o.push(`Working directory: \`${r.cwd}\`.`),n===null||n.profile_id!==r.profile_id){const a=y(r);a!==""&&o.push(a)}const c=_(r);c!==""&&o.push("","## Your managed worktree",c),r.mode==="orchestrator"&&o.push("",w());const d=x(r);return d!==""&&o.push("",d),o.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[o.join(`
2
+ `),t].filter(a=>a!=="").join(`
3
3
  `)}i(F,"buildForkBearingsFromState");export{F as buildForkBearingsFromState,S as editorLabelForBrokerNode};
@@ -1 +1 @@
1
- var ft=Object.defineProperty;var n=(t,o)=>ft(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as pt,envModelExact as gt,envModelIntent as Be,envNodeCwd as vt,envNodeId as _t,envProfileId as ht,envScopes as wt,scopeAllowed as bt}from"../../shared/env.js";import{createServer as St}from"node:net";import{WebSocketServer as yt,createWebSocketStream as Rt}from"ws";import{BROKER_VIEW_PORT as Et}from"./view-socket.js";import{existsSync as $e,readFileSync as kt,unlinkSync as ve,writeFileSync as Tt}from"node:fs";import{join as Ke}from"node:path";import{randomUUID as U}from"node:crypto";import{mark as Ue}from"../timing.js";import{SUBMIT_RESULT_TOOL as Ct}from"./structured-output.js";import{conversationIdFromPath as Mt,flushConversation as _e,installSessionManagerStorePatch as At,readConversationAsync as xt}from"../conversation-store/index.js";import{getAgentDir as ie,ModelRegistry as Pt,ModelRuntime as Ot}from"@earendil-works/pi-coding-agent";import{nodeRunDir as Nt,viewSocketPath as Dt}from"../canvas/paths.js";import{bindBrokerEventSource as It}from"../events/source.js";import{emitEvent as h,flushBrokerLog as We}from"../events/emit.js";import{operationIdContext as Lt}from"../events/operation-id.js";import{findMissingPackagePaths as Ft}from"./package-health.js";import{installBrokerConfigSnapshot as Ge,overlayProjectLaunchConfig as Bt}from"../config.js";import{FRONT_DOOR_ENV as $t}from"./front-door.js";import{CANVAS_EXTENSIONS as he,buildLaunchSpecFromMerged as Kt,piInvocationToSdkConfig as Ut}from"./launch.js";import{setConversationRequestMark as je}from"../conversation-store/index.js";import{assertEngineVersion as Wt,loadBrokerEngine as Gt}from"./broker-sdk.js";import{initCrtrTheme as jt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Vt}from"./pi-cli.js";import{captureSessionChatCapabilities as qt}from"./command-surface.js";import{InMemoryCredentialStore as Xt}from"@earendil-works/pi-ai";import{askGateway as Yt,configureBrokerModelRuntime as Ht,refusalRetryAt as Jt}from"./broker/model-adapter.js";import{brokerApiUrl as zt,brokerExecutionId as Qt,mutateBrokerFault as ae,recordBrokerTurn as Ve}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Zt}from"./launch-recipe.js";import{fetchRunAttachments as qe}from"./broker/attachments-fetch.js";import{llmModelFor as en,modelRequestFromConfig as tn,expandModelCandidates as nn,parseModelSpec as rn,unregisteredConcreteModel as on}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as sn}from"./stream-watchdog.js";import{CRTR_CYCLE_CUSTOM_TYPE as we,earlierCycleMessages as an,endedByAbort as dn,identifiedMessages as ln,welcomeWindow as cn,WELCOME_EARLIER_BYTES as mn,WELCOME_EARLIER_CYCLES as un}from"./session-cycles.js";import{turnErrorOf as fn}from"../llm/refusal.js";import{projectTranscript as pn}from"./session-visibility.js";import{currentTurnVisibility as gn}from"./turn-visibility.js";import{isUnknownModel as be}from"./model-selection.js";import{BrokerClientRegistry as vn}from"./broker/client-registry.js";import{ToolGroupTracker as _n}from"./broker/tool-groups.js";import{TurnReplyTracker as hn}from"./broker/turn-replies.js";import{onNodeNamed as wn}from"./broker/node-named.js";import{FaultRetry as bn,willDaemonRetry as Sn}from"./broker/fault-retry.js";import{RunTurnEnds as yn}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as Rn}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as En,BROKER_START_CYCLE as kn,BROKER_IDLE_TURN_START as Tn,BROKER_RUN_TURN_BUSY as Cn,BROKER_RUN_STEER as Mn}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as An}from"./broker/run-steer.js";import{prependRunDeferredMail as xn,settleRunDeferredMail as Pn}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as On}from"./broker/run-turn-queue.js";import{EventProjection as Nn}from"./broker/event-projection.js";import{createFrameDispatchContext as Dn,handleFrame as In}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as Ln,installAdvertisedCommandInvocationContract as Fn}from"./advertised-command-invocation.js";import{RebindDriver as Bn}from"./broker/rebind.js";import{beginRuntimeTeardown as $n}from"./broker/extension-abort.js";import{receiveNodeToken as Kn}from"./broker/node-token.js";import{serveCliRelay as Un}from"./broker/cli-relay.js";import{recordBrokerRelease as Wn}from"./lifecycle.js";import{setTurnCauseSource as Gn}from"./broker/turn-cause.js";import{decodeKickoffOrigin as Xe,KICKOFF_ORIGIN_ENV as Ye}from"./stamp/protocol.js";import{announceMessageOrigin as He}from"./stamp/channel.js";import{commitBrokerModel as jn,recordConversationWriteFault as Je}from"./broker/daemon-ops.js";import{bootExtensionState as Vn,holdStartupClaims as qn,releaseStartupClaims as Xn}from"./broker/boot-state.js";import{bindCarriedStart as ze,publishCarriedStart as Yn,startCycle as Qe,takeCycleAttachments as Ze}from"./broker/cycle-start.js";import{composerNames as Hn}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Jn,FrameOverflowError as zn,withoutImages as et,toolCallIds as Qn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as ko,REVIEW_BOUNDARY_NAVIGATION_CODE as To}from"./broker/frame-replies.js";function Se(t){return new Pt(t.modelRuntime)}n(Se,"registryOf");function J(t,o){if(t==null||be(t))return null;const s=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${s}`}n(J,"formatModelSpec");function Zn(t,o){const s=J(t,void 0);return s===null?null:`${s}:${o===void 0||o===""?"off":o}`}n(Zn,"formatExactModelSpec");const er=12e4;let de=null;import{brokerSignalClient as V}from"./broker/signal-stream.js";function tr(){V().stop();const t=de;if(de=null,t!==null)try{t.dispose()}catch{}}n(tr,"disposeActiveSession");function nr(t,o){const s=bt(o,"crtr:act")?void 0:["bash"],v=t!==void 0&&t.length>0?[...new Set([...t,Ct])]:t===void 0?void 0:[...t];return{...v!==void 0?{tools:v}:{},...s!==void 0?{excludeTools:s}:{}}}n(nr,"brokerToolOptions");function rr(t,o){const s=t.env.CRTR_KIND,v=t.configSnapshot;if(s===void 0||v===void 0||v.launch.kinds[s]!==void 0)return;const a=Bt(v.launch,o.cwd,t.env.CRTR_PROFILE_ID||null);if(a.kinds[s]===void 0)throw new Error(`unknown kind ${s}`);v.launch=a,Ge(v);const{launch:d}=Kt(s,t.env.CRTR_MODE??"base",{lifecycle:"terminal",hasManager:!0,...o.model!==void 0?{model:o.model}:{}},a);o.tools=d.tools,o.extensionPaths=[...d.extensions],o.model??=d.model,d.modelIntent!==void 0&&(process.env.CRTR_MODEL_INTENT=`${d.modelIntent.family}/${d.modelIntent.strength}`)}n(rr,"applyProjectKind");async function yo(t,o=process.hrtime.bigint(),s=new Date().toISOString()){It(t);const v=await Kn(),a=await Un(t,v);process.env.CRTR_API_SOCKET=a.path,Lt.fresh(()=>{h({level:"info",event:"broker.startup.cli_entry",ts:s,duration_ms:0,fields:{pid:process.pid,runtime_version:process.version,engine_version:null,model:null}}),h({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let f=null;const l=n((e,r=null)=>{d.has(e)||(d.add(e),Ue(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),h({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:f,model:r}}))},"emitStartupMilestone"),_=n((e,r,i={})=>{const u=process.hrtime.bigint(),p=Number(u-r)/1e6,g=Number(u-o)/1e6;Ue(e,{duration_ms:p}),h({level:"info",event:e,duration_ms:p,fields:{at_ms:g,...i}})},"emitStartupStep");process.env[$t]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,At(t),je(e=>_("broker.startup.conversation_request",process.hrtime.bigint()-BigInt(Math.round(e.durationMs*1e6)),{method:e.method,route:e.route,first_request:e.firstRequest,worker_age_ms:e.workerAgeMs}));const R=process.hrtime.bigint(),E=await Gt();_("broker.startup.engine_loaded",R);const x=process.hrtime.bigint();Wt(E.VERSION),_("broker.startup.version_checked",x),f=E.VERSION;const T=process.hrtime.bigint(),q=Nt(t),b=Ke(q,"broker-launch.json"),S=JSON.parse(kt(b,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Ge(S.configSnapshot),S.start!==void 0){const{start:e,...r}=S;Tt(b,JSON.stringify(r))}const c=Ut(S);rr(S,c),c.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,_("broker.startup.launch_recipe_read",T);let k,N;const P=new AbortController,X=n(e=>{k!==void 0?k(e):(N??=e,P.abort())},"onSignal");process.on("SIGTERM",()=>X("SIGTERM")),process.on("SIGINT",()=>X("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&V().start(t,e)});const I=Dt(t),L=new Set;let z;try{$e(I)&&ve(I)}catch{}const te=n(()=>{try{ve(I)}catch{}},"removeViewSocket"),D=St(e=>{if(z!==void 0){z(e);return}e.pause(),L.add(e),e.once("close",()=>L.delete(e)),e.on("error",()=>{})});await new Promise((e,r)=>{D.once("error",r),D.listen(I,()=>{D.off("error",r),e()})}),l("broker.startup.listening");const Q=process.hrtime.bigint();let Z;try{Z=await ir(E,c,(e,r)=>_(e,r))}catch(e){throw te(),e}let{session:C,services:F,resuming:dr,runtime:rt}=Z;je(void 0),_("broker.startup.session_build",Q),l("broker.startup.session_built");const W=S.start;W!==void 0&&qn();const ye=W===void 0?await Qe(t,C,"startup",P.signal):Yn(t,W);P.signal.aborted&&(C.dispose(),te(),await We(),process.exit(0));const ot=ye?.names===void 0?await Hn(t):ye.names,ne=(await Vn(t)).node.review_binding?.review_id,G=pt();de=C;const st=n(async()=>{const e=m.session().model;return e===void 0?{ok:!0}:await Yt(en(`${e.provider}/${e.id}`,Be(),gt()))},"retryProbe");try{process.env.PI_PACKAGE_DIR=Vt(),jt(F.settingsManager.getTheme(),ie(),!1)}catch(e){h({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of Ft(ie()))h({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const w=new vn(t),re=new Map,B=new _n(t,e=>w.broadcast(e)),Y=new hn(t,e=>w.broadcast(e));wn(e=>w.broadcast({type:"node_named",...e}));let j=!1,Re=!1,oe,Ee,m,ee;const le=new yn;let H,ke=n(()=>{},"notifyTurnAccepted"),Te=n(()=>{},"resetFrameState"),Ce=n(()=>{},"bindAnswered");const ce=Rn(W===void 0?void 0:new Promise(e=>{Ce=e}));let Me=n(()=>0,"pendingPromptDispatches"),Ae;const $=On({runNode:G,session:n(()=>m.session(),"session"),isReplacing:n(()=>m.isReplacing(),"isReplacing"),pendingRebind:n(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>Me(),"pendingDispatches"),turnAdmission:ce,prependDeferred:n(e=>xn(t,e),"prependDeferred"),onError:n(e=>h({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),xe=An($.steerable);globalThis[Mn]=xe,Gn(()=>m.session());const Pe=$.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&$.holdForKickoff(),globalThis[Tn]=$.start,globalThis[Cn]=$.busy,m=new Bn({nodeId:t,cfg:c,session:C,services:F,runtime:rt,registry:w,toolGroups:B,turnReplies:Y,runSteer:xe,runNode:G,transcriptMessages:n(e=>me(e),"transcriptMessages"),uiContext:n(()=>Ee,"uiContext"),faultRetry:n(()=>ee,"faultRetry"),projection:n(()=>H,"projection"),setActiveSession:n(e=>{if(de=e,Ae?.(),G||process.env.CRTR_RUN_ID){let r="stop",i,u=!1;Ae=e.subscribe(p=>{if(p.type==="agent_start"&&(r="stop",i=void 0,u=!1,le.started()),p.type==="agent_end"){const g=[...p.messages??[]].reverse().find(y=>y.role==="assistant");g&&(r=g.stopReason,i=dn(g)?void 0:fn(g,Jt(g)),u=g.role==="assistant"&&Sn(g,e.model?.contextWindow))}p.type==="agent_settled"&&(le.settled(e.sessionManager,{stop_reason:r,...i?{error:i}:{}},u),G&&(_e().then(()=>Pn(t,e)).catch(async g=>{if(String(g?.message).startsWith("conversation_write_failed")){h({level:"error",event:"broker.exited",node_id:t,error:g,fields:{fault:"conversation_write_failed"}}),await Je(t,g),A("conversation_write_failed",1);return}h({level:"error",event:"broker.run_deferred_mail.settle_failed",error:g})}),queueMicrotask(()=>{m.session()===e&&Pe()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>A(e,r),"disposeAndExit"),onSessionRebind:n(()=>{Te()},"onSessionRebind"),onReplacementIdle:n(()=>{G&&Pe()},"onReplacementIdle"),reWelcomeAll:n(()=>ue(),"reWelcomeAll")});const Oe=n(async(e,r=!1)=>{const i=m.session(),u=J(i.model,i.thinkingLevel);if(u===null)return null;const p=await jn(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:r});return r&&(c.model=p.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,c.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",c.modelExact=!0)),p.modelOverride},"persistModelChoice"),Ne=n(async(e=!0,r,i=!1)=>{const u=m.session(),p=J(u.model,u.thinkingLevel),g=e?await Oe(r,i):p;w.broadcast({type:"model_changed",model:be(u.model)?void 0:u.model,spec:g})},"broadcastModelChanged");ee=new bn({nodeId:t,cfg:c,retryProbe:st,currentSession:n(()=>m.session(),"currentSession"),currentServices:n(()=>m.services(),"currentServices"),installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),registryOf:Se,formatModelSpec:J,broadcastModelChanged:Ne,turnAdmission:ce,reWelcomeAll:n(()=>ue(),"reWelcomeAll"),...G?{turnEnds:le}:{}});const De=n(()=>{ee.rearmIfStranded().catch(e=>{h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");V().subscribe("resync",De),V().subscribe("fault-retry",De),H=new Nn({registry:w,faultRetry:ee,installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),currentSession:n(()=>m.session(),"currentSession"),notifyTurnAccepted:n(()=>ke(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:J});let se=[];const Ie=n(async e=>{se=[];const r=e.sessionManager.getEntries()[0],i=e.sessionManager.getSessionFile(),u=i===void 0?null:Mt(i);if(!(ne!==void 0||r?.type!=="custom"||r.customType!==we||u===null))try{const{entries:p}=await xt(u,{beforeCycle:mn});se=an(p,r,un)}catch(p){h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`earlier cycles read failed: ${String(p)}`}})}},"loadEarlierCycles"),it=Ie(C);function me(e){const r=tt(e,ne)?.map(({message:i})=>i)??e.sessionManager.buildSessionContext().messages;return[...se.map(({message:i})=>i),...r]}n(me,"turnSeedMessages");const at=n(e=>{const r=m.session(),i=tt(r,ne),u=i===void 0?void 0:[...se.map(M=>({...M,visibility:"visible"})),...i],p=u?.map(({message:M})=>M)??r.sessionManager.buildSessionContext().messages,{start:g}=cn(p,M=>JSON.stringify(et(M,t)).length),y=e.snapshotTail===void 0?g:Math.max(g,p.length-e.snapshotTail),K=u?.slice(y),ge=p.slice(y).map(M=>et(M,t)),mt=Qn(ge),ut=Object.fromEntries(Object.entries(B.summaries()).filter(([M])=>mt.has(M)));return{messages:ge,...K===void 0?{}:{messageIds:K.map(({id:M})=>M)},messageVisibility:K?.map(({visibility:M})=>M)??ge.map(()=>"visible"),turnVisibility:gn(),stats:r.getSessionStats(),state:{model:be(r.model)?void 0:r.model,thinkingLevel:r.thinkingLevel,isStreaming:r.isStreaming,isCompacting:r.isCompacting,steeringMode:r.steeringMode,followUpMode:r.followUpMode,sessionFile:r.sessionFile,sessionId:r.sessionId,sessionName:r.sessionName,autoCompactionEnabled:r.autoCompactionEnabled,messageCount:r.messages.length,pendingMessageCount:r.pendingMessageCount},display:{...w.displaySnapshot()},toolGroupSummaries:ut,turnReplies:Y.snapshot(),workingActivity:H.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),Le=n(e=>{const r=e.role==="controller"?re.values().next().value:void 0;w.sendFrame(e,{type:"welcome",snapshot:at(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:ie()})},"sendWelcome"),dt=n(e=>{const r=[...re.values()];for(let i=1;i<r.length;i++)w.sendFrame(e,r[i].request)},"replayExtraPendingDialogsTo"),ue=n(()=>{try{const e=m.session();Y.seed(me(e))}catch(e){h({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}w.forEachHelloed(Le)},"reWelcomeAll"),Fe=n(async e=>{if(j)return;j=!0;const r=V().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&Wn(t,process.env.CRTR_EXECUTION_ID??null),V().stop(),e===0&&await _e().catch(async i=>{e=1,h({level:"error",event:"broker.exited",node_id:t,error:i,fields:{fault:"conversation_write_failed"}}),await Je(t,i)}),B.persistPendingSummary(),H.dispose(),tr();try{D?.close(),oe?.close()}catch{}a.close(),w.dispose();try{$e(I)&&ve(I)}catch{}w.clearAttachState(),await We(),process.exit(e)},"completeExit"),A=n((e,r=0)=>{if(j)return;const i=e==="shutdown-hook"||e==="shutdown-after-settle";if(i&&B.finishOpenToolGroup(!0),i&&(B.hasSummaryTasks()||Y.hasTasks())){if(Re)return;Re=!0,Promise.allSettled([B.waitForSummaryTasks(),Y.waitForTasks()]).finally(()=>Fe(r));return}Fe(r)},"disposeAndExit");globalThis[En]=A,Ee=ar({writable:n(()=>w.writableClients(),"writable"),forward:n((e,r)=>w.sendFrame(e,r),"forward"),pending:re,broadcast:n(e=>w.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>H.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,F),l("broker.startup.extensions_bound");const O=Dn({nodeId:t,registry:w,toolGroups:B,projection:H,rebind:m,boundaryReviewId:ne,pendingDialogs:re,sendWelcome:Le,replayExtraPendingDialogsTo:dt,reWelcomeAll:ue,disposeAndExit:A,persistModelChoice:Oe,broadcastModelChanged:Ne,registryOf:Se,formatModelSpec:J,formatExactModelSpec:Zn,turnAdmission:ce,memoryInventory:ot,runNode:G,onKickoffAdmitted:$.releaseKickoff});ke=O.notifyTurnAccepted,Te=O.resetForSession,Me=O.pendingPromptDispatches,globalThis[kn]=async e=>{for(const y of Zt){const K=e.env[y];K===void 0?delete process.env[y]:process.env[y]=K}process.env[Ye]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?c.model=e.model:delete c.model,e.modelExact?(c.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete c.modelExact,delete process.env.CRTR_MODEL_EXACT),c.editorName=e.editorLabel,$.holdForKickoff(),B.finishOpenToolGroup(!0);const r=m.session(),i=r.sessionManager.getSessionFile();if(i===void 0||i==="")throw new Error("in-place cycle needs a persisted session file");const u=r.sessionManager,p=u.getLeafId();u.resetLeaf(),u.appendCustomEntry(we,{cycle:e.cycle,fromLeaf:p}),await _e(),m.beforeNextBind(async y=>{const[K]=await Promise.all([Qe(t,y,"resume"),Ie(y)]);await O.refreshMemoryNames(K?.names)});const g=await m.runReplacement(null,"cycle",y=>y.switchSession(i));if(m.beforeNextBind(void 0),!g)return A("cycle-replacement-failed",1),!1;He(e.prompt,Xe(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await qe(t,Ze(t))}catch(y){return h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:y,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1),!1}return O.kickoff(e.prompt,e.messageIds),!0};const lt=2500;let fe=!1;const ct=n(async e=>{if(j||fe)return;if(fe=!0,m.isAgentRunActive()||m.session().isStreaming||O.pendingPromptDispatches()>0){const i=Date.now()+lt;for(;O.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<i;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=i-Date.now();if(u>0){let p;try{$n(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(y=>{p=setTimeout(()=>y(!1),u)})])&&await Ve(t,{event:"closed",end_reason:"teardown-aborted"})}finally{p!==void 0&&clearTimeout(p)}}}else(O.pendingPromptDispatches()>0||m.isAgentRunActive())&&await Ve(t,{event:"interrupted"})}A(e)},"abortAndExit");if(k=n(e=>{ct(e)},"signalTeardown"),N!==void 0){k(N);return}const pe=n(e=>{l("broker.startup.first_viewer_connected");const r=w.create(e);e.on("data",u=>{let p;try{p=r.decoder.push(u)}catch(g){g instanceof zn?(w.sendFrame(r,{type:"error",code:"frame_overflow",message:g.message}),w.dropClient(r,`frame overflow: ${g.message}`)):w.dropClient(r,`decoder error: ${String(g)}`);return}for(const g of p)try{In(O,r,g)}catch{}});const i=n(()=>{w.removeClient(r)},"drop");e.on("close",i),e.on("error",()=>{})},"serveViewer");zt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(oe=new yt({host:"::",port:Et,path:"/view",maxPayload:Jn.maxLineBytes}),oe.on("connection",e=>pe(Rt(e))),oe.on("error",e=>{j||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))})),D.on("error",e=>{j||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))}),await it;try{Y.seed(me(m.session()))}catch(e){h({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply seed failed: ${String(e)}`}})}z=pe;for(const e of L)L.delete(e),pe(e),e.resume();(async()=>{if(Promise.all([ae(t,{op:"clear",link:"viewer\u2194broker"}),ae(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}})),W!==void 0){let r;try{try{r=await ze(t,m.session(),W)}catch(i){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:i,fields:{operation:"session_bound",attempt:1}}),r=await ze(t,m.session(),W)}}catch(i){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:i,fields:{operation:"session_bound",attempt:2}}),A("session-bound-failed",1);return}if(r?.action==="shutdown"){m.requestShutdown();return}if(r?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");V().start(t,Qt()),Xn(),Ce()}l("broker.startup.ready_for_turn");let e;try{e=await ee.recoverOnStartup()}catch(r){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),A("recovery-startup-failed",1);return}if(!(j||fe))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const r=Xe(process.env[Ye]);r!==null&&He(c.firstPrompt,r);try{await qe(t,Ze(t))}catch(u){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1);return}const i=process.env.CRTR_KICKOFF_MESSAGE_IDS;O.kickoff(c.firstPrompt,i?JSON.parse(i):[])}else $.releaseKickoff()})(),w.persistAttachState()}n(yo,"runBroker");function tt(t,o){const s=t.sessionManager,v=s.getEntries===void 0?void 0:ln(s.getEntries(),s.getLeafId?.());return v!==void 0&&Ln(v.map(({message:a})=>a)),v===void 0?void 0:pn(v,{boundaryReviewId:o,sessionEntries:s.getEntries?.()})}n(tt,"snapshotMessages");function nt(){const t=_t();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(nt,"currentBrokerNodeId");async function or(t,o){const s=tn(o.model,Be(),o.modelExact===!0);if(s===void 0)return;const v=Se(t),a={cwd:vt()??o.cwd,profileId:ht()},d=await on(s,v,a);if(d!==void 0)throw await ae(nt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const f=await nn(s,a.cwd,a.profileId),l=rn(s.spec);for(const _ of f){const R=v.find(_.providerId,_.modelId);if(R===void 0)continue;const x=l?.providerId===_.providerId&&l.modelId===_.modelId?l.thinkingLevel??(_.thinkingLevel===void 0?void 0:"off"):_.thinkingLevel;return{model:R,thinkingLevel:x}}if(o.modelExact===!0){const _=f.map(R=>`'${R.providerId}/${R.modelId}' unregistered`).join("; ");throw await ae(nt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${_})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}h({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:f.map(_=>({provider:_.providerId,model:_.modelId,reason:"unregistered"})).slice(0,16)}})}n(or,"resolveLaunchModel");function sr(t){let o=!0;return{runtime:new Proxy(t,{get(v,a,d){return o&&a==="getAvailableSnapshot"?()=>[]:o&&a==="getAvailable"?async()=>[]:o&&a==="getModel"?()=>{}:Reflect.get(v,a,d)}}),reveal:n(()=>{o=!1},"reveal")}}n(sr,"modelLessRegistry");async function ir(t,o,s=()=>{}){const v=ie(),a=n(async b=>{const S=process.hrtime.bigint(),c=await Ot.create({credentials:new Xt,modelsPath:Ke(b.agentDir,"models.json")});Ht(c),s("broker.startup.model_runtime",S);const k=process.hrtime.bigint(),N=await t.createAgentSessionServices({cwd:b.cwd,agentDir:b.agentDir,modelRuntime:c,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(P=>({...P,extensions:P.extensions.filter(X=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(X.path))}),"extensionsOverride")}});return s("broker.startup.resources_loaded",k),N},"loadServices");let d;const f=n(async b=>{const S=d;d=void 0;const c=await(S??a(b)),k=c.resourceLoader.getExtensions();if(o.extensionPaths.some(Q=>he.includes(Q))){const Q=new Set(k.extensions.map(C=>C.path)),Z=he.filter(C=>!Q.has(C));if(Z.length>0){const C=k.errors.filter(F=>he.includes(F.path)).map(F=>`${F.path}: ${F.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${Z.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const N=process.hrtime.bigint(),P=await or(c,o);s("broker.startup.model_resolved",N);const X=P?.model,I=P?.thinkingLevel,L=P===void 0?sr(c.modelRuntime):void 0,z=L!==void 0?{...c,modelRuntime:L.runtime}:c,te=process.hrtime.bigint(),D=await t.createAgentSessionFromServices({services:z,sessionManager:b.sessionManager,model:X,thinkingLevel:I,...nr(o.tools,wt()),sessionStartEvent:b.sessionStartEvent});return s("broker.startup.session_from_services",te),Fn(D.session),qt(D.session),L?.reveal(),{...D,services:c}},"buildForManager"),l=o.resumeSessionPath,_=o.forkFrom!==void 0&&o.forkFrom!=="";if(!_&&(l===void 0||l==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const R=!_&&l!==void 0&&l!=="",E=R&&o.newCycle===!0,x=R&&!E;let T;if(_)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(x||E){if(T=await t.SessionManager.open(l),E){const b=T.getLeafId();T.resetLeaf(),T.appendCustomEntry(we,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:b})}}else{const b=process.hrtime.bigint(),S=t.SessionManager.createAsync,c=(S!==void 0?S.call(t.SessionManager,o.cwd):Promise.resolve(t.SessionManager.create(o.cwd))).then(N=>(s("broker.startup.conversation_created",b),N));d=a({cwd:o.cwd,agentDir:v}),d.catch(()=>{});const k=process.hrtime.bigint();T=await c,await d,s("broker.startup.create_and_resources_joined",k)}if(t.createAgentSessionRuntime!==void 0){const b=n(async c=>{const k=await f({cwd:c.cwd,agentDir:c.agentDir,sessionManager:c.sessionManager,sessionStartEvent:c.sessionStartEvent});return{...k,diagnostics:k.services.diagnostics??[]}},"factory"),S=await t.createAgentSessionRuntime(b,{cwd:o.cwd,agentDir:v,sessionManager:T});return{session:S.session,services:S.services,resuming:x,runtime:S}}const q=await f({cwd:o.cwd,agentDir:v,sessionManager:T});return{session:q.session,services:q.services,resuming:x,runtime:void 0}}n(ir,"buildBrokerSession");function ar(t){const o=n((a,d,f,l)=>{if(l?.signal?.aborted)return Promise.resolve(a);const _=t.writable();return _.length===0?Promise.resolve(a):new Promise(R=>{let E;const x=n(()=>{E!==void 0&&clearTimeout(E),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=n(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),R(a)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const q=l?.timeout!==void 0?l.timeout:er;E=setTimeout(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),R(a)},q),typeof E.unref=="function"&&E.unref(),t.pending.set(d.id,{request:d,resolve:n(b=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),R(f(b))},"resolve")});for(const b of _)t.forward(b,d)})},"dialogPromise"),s=n(()=>{},"noop");return{[sn]:t.onKnownStreamWait??(a=>()=>{}),get theme(){const a=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(a==null)throw new Error("Theme not initialized. Call initTheme() first.");return a},select:n((a,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"select",title:a,options:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"select"),confirm:n((a,d,f)=>o(!1,{type:"extension_ui_request",id:U(),method:"confirm",title:a,message:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,f),"confirm"),input:n((a,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"input",title:a,placeholder:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"input"),editor:n((a,d)=>o(void 0,{type:"extension_ui_request",id:U(),method:"editor",title:a,prefill:d},f=>"cancelled"in f&&f.cancelled?void 0:"value"in f?f.value:void 0),"editor"),setStatus:n((a,d)=>t.broadcast({type:"extension_ui_request",id:U(),method:"setStatus",statusKey:a,statusText:d}),"setStatus"),setWidget:n((a,d,f)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:U(),method:"setWidget",widgetKey:a,widgetLines:d,widgetPlacement:f?.placement})},"setWidget"),setTitle:n(a=>t.broadcast({type:"extension_ui_request",id:U(),method:"setTitle",title:a}),"setTitle"),notify:n((a,d)=>{const f=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:U(),method:"notify",message:a,notifyType:f})},"notify"),onTerminalInput:n(()=>s,"onTerminalInput"),setWorkingMessage:s,setWorkingVisible:s,setWorkingIndicator:s,setHiddenThinkingLabel:s,setFooter:s,setHeader:s,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:s,setEditorText:s,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:s,setEditorComponent:s,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:s,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:s}}n(ar,"makeBrokerUiContext");export{To as REVIEW_BOUNDARY_NAVIGATION_CODE,ko as ReviewBoundaryNavigationError,nr as brokerToolOptions,ir as buildBrokerSession,tr as disposeActiveSession,ar as makeBrokerUiContext,yo as runBroker,tt as snapshotMessages};
1
+ var pt=Object.defineProperty;var n=(t,o)=>pt(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as gt,envModelExact as vt,envModelIntent as Be,envNodeCwd as _t,envNodeId as ht,envProfileId as wt,envScopes as bt,scopeAllowed as St}from"../../shared/env.js";import{createServer as yt}from"node:net";import{WebSocketServer as Rt,createWebSocketStream as Et}from"ws";import{BROKER_VIEW_PORT as kt}from"./view-socket.js";import{existsSync as $e,readFileSync as Tt,unlinkSync as ve,writeFileSync as Ct}from"node:fs";import{join as Ke}from"node:path";import{randomUUID as W}from"node:crypto";import{mark as Ue}from"../timing.js";import{SUBMIT_RESULT_TOOL as Mt}from"./structured-output.js";import{conversationIdFromPath as At,flushConversation as _e,installSessionManagerStorePatch as xt,readConversationAsync as Pt}from"../conversation-store/index.js";import{getAgentDir as ae,ModelRegistry as Ot,ModelRuntime as Nt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as Dt,viewSocketPath as It}from"../canvas/paths.js";import{bindBrokerEventSource as Lt}from"../events/source.js";import{emitEvent as h,flushBrokerLog as We}from"../events/emit.js";import{operationIdContext as Ft}from"../events/operation-id.js";import{findMissingPackagePaths as Bt}from"./package-health.js";import{installBrokerConfigSnapshot as Ge,overlayProjectLaunchConfig as $t}from"../config.js";import{FRONT_DOOR_ENV as Kt}from"./front-door.js";import{CANVAS_EXTENSIONS as he,buildLaunchSpecFromMerged as Ut,piInvocationToSdkConfig as Wt}from"./launch.js";import{setConversationRequestMark as je}from"../conversation-store/index.js";import{assertEngineVersion as Gt,loadBrokerEngine as jt}from"./broker-sdk.js";import{initCrtrTheme as Vt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as qt}from"./pi-cli.js";import{captureSessionChatCapabilities as Xt}from"./command-surface.js";import{InMemoryCredentialStore as Yt}from"@earendil-works/pi-ai";import{askGateway as Ht,configureBrokerModelRuntime as Jt,refusalRetryAt as zt}from"./broker/model-adapter.js";import{brokerApiUrl as Qt,brokerExecutionId as Zt,mutateBrokerFault as de,recordBrokerTurn as Ve}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as en}from"./launch-recipe.js";import{expandHostPathTokens as qe}from"./broker/host-path-tokens.js";import{fetchRunAttachments as Xe}from"./broker/attachments-fetch.js";import{llmModelFor as tn,modelRequestFromConfig as nn,expandModelCandidates as rn,parseModelSpec as on,unregisteredConcreteModel as sn}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as an}from"./stream-watchdog.js";import{CRTR_CYCLE_CUSTOM_TYPE as we,earlierCycleMessages as dn,endedByAbort as ln,identifiedMessages as cn,welcomeWindow as mn,WELCOME_EARLIER_BYTES as un,WELCOME_EARLIER_CYCLES as fn}from"./session-cycles.js";import{turnErrorOf as pn}from"../llm/refusal.js";import{projectTranscript as gn}from"./session-visibility.js";import{currentTurnVisibility as vn}from"./turn-visibility.js";import{isUnknownModel as be}from"./model-selection.js";import{BrokerClientRegistry as _n}from"./broker/client-registry.js";import{ToolGroupTracker as hn}from"./broker/tool-groups.js";import{TurnReplyTracker as wn}from"./broker/turn-replies.js";import{onNodeNamed as bn}from"./broker/node-named.js";import{FaultRetry as Sn,willDaemonRetry as yn}from"./broker/fault-retry.js";import{RunTurnEnds as Rn}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as En}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as kn,BROKER_START_CYCLE as Tn,BROKER_IDLE_TURN_START as Cn,BROKER_RUN_TURN_BUSY as Mn,BROKER_RUN_STEER as An}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as xn}from"./broker/run-steer.js";import{prependRunDeferredMail as Pn,settleRunDeferredMail as On}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as Nn}from"./broker/run-turn-queue.js";import{EventProjection as Dn}from"./broker/event-projection.js";import{createFrameDispatchContext as In,handleFrame as Ln}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as Fn,installAdvertisedCommandInvocationContract as Bn}from"./advertised-command-invocation.js";import{RebindDriver as $n}from"./broker/rebind.js";import{beginRuntimeTeardown as Kn}from"./broker/extension-abort.js";import{receiveNodeToken as Un}from"./broker/node-token.js";import{serveCliRelay as Wn}from"./broker/cli-relay.js";import{recordBrokerRelease as Gn}from"./lifecycle.js";import{setTurnCauseSource as jn}from"./broker/turn-cause.js";import{decodeKickoffOrigin as Ye,KICKOFF_ORIGIN_ENV as He}from"./stamp/protocol.js";import{announceMessageOrigin as Je}from"./stamp/channel.js";import{commitBrokerModel as Vn,recordConversationWriteFault as ze}from"./broker/daemon-ops.js";import{bootExtensionState as qn,holdStartupClaims as Xn,releaseStartupClaims as Yn}from"./broker/boot-state.js";import{bindCarriedStart as Qe,publishCarriedStart as Hn,startCycle as Ze,takeCycleAttachments as et}from"./broker/cycle-start.js";import{composerNames as Jn}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as zn,FrameOverflowError as Qn,withoutImages as tt,toolCallIds as Zn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as Co,REVIEW_BOUNDARY_NAVIGATION_CODE as Mo}from"./broker/frame-replies.js";function Se(t){return new Ot(t.modelRuntime)}n(Se,"registryOf");function z(t,o){if(t==null||be(t))return null;const s=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${s}`}n(z,"formatModelSpec");function er(t,o){const s=z(t,void 0);return s===null?null:`${s}:${o===void 0||o===""?"off":o}`}n(er,"formatExactModelSpec");const tr=12e4;let le=null;import{brokerSignalClient as q}from"./broker/signal-stream.js";function nr(){q().stop();const t=le;if(le=null,t!==null)try{t.dispose()}catch{}}n(nr,"disposeActiveSession");function rr(t,o){const s=St(o,"crtr:act")?void 0:["bash"],v=t!==void 0&&t.length>0?[...new Set([...t,Mt])]:t===void 0?void 0:[...t];return{...v!==void 0?{tools:v}:{},...s!==void 0?{excludeTools:s}:{}}}n(rr,"brokerToolOptions");function or(t,o){const s=t.env.CRTR_KIND,v=t.configSnapshot;if(s===void 0||v===void 0||v.launch.kinds[s]!==void 0)return;const a=$t(v.launch,o.cwd,t.env.CRTR_PROFILE_ID||null);if(a.kinds[s]===void 0)throw new Error(`unknown kind ${s}`);v.launch=a,Ge(v);const{launch:d}=Ut(s,t.env.CRTR_MODE??"base",{lifecycle:"terminal",hasManager:!0,...o.model!==void 0?{model:o.model}:{}},a);o.tools=d.tools,o.extensionPaths=[...d.extensions],o.model??=d.model,d.modelIntent!==void 0&&(process.env.CRTR_MODEL_INTENT=`${d.modelIntent.family}/${d.modelIntent.strength}`)}n(or,"applyProjectKind");async function Eo(t,o=process.hrtime.bigint(),s=new Date().toISOString()){Lt(t);const v=await Un(),a=await Wn(t,v);process.env.CRTR_API_SOCKET=a.path,Ft.fresh(()=>{h({level:"info",event:"broker.startup.cli_entry",ts:s,duration_ms:0,fields:{pid:process.pid,runtime_version:process.version,engine_version:null,model:null}}),h({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let p=null;const l=n((e,r=null)=>{d.has(e)||(d.add(e),Ue(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),h({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:p,model:r}}))},"emitStartupMilestone"),_=n((e,r,i={})=>{const u=process.hrtime.bigint(),f=Number(u-r)/1e6,g=Number(u-o)/1e6;Ue(e,{duration_ms:f}),h({level:"info",event:e,duration_ms:f,fields:{at_ms:g,...i}})},"emitStartupStep");process.env[Kt]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,xt(t),je(e=>_("broker.startup.conversation_request",process.hrtime.bigint()-BigInt(Math.round(e.durationMs*1e6)),{method:e.method,route:e.route,first_request:e.firstRequest,worker_age_ms:e.workerAgeMs}));const y=process.hrtime.bigint(),R=await jt();_("broker.startup.engine_loaded",y);const x=process.hrtime.bigint();Gt(R.VERSION),_("broker.startup.version_checked",x),p=R.VERSION;const T=process.hrtime.bigint(),X=Dt(t),b=Ke(X,"broker-launch.json"),S=JSON.parse(Tt(b,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Ge(S.configSnapshot),S.start!==void 0){const{start:e,...r}=S;Ct(b,JSON.stringify(r))}const c=Wt(S);or(S,c),c.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,_("broker.startup.launch_recipe_read",T);let E,N;const P=new AbortController,Y=n(e=>{E!==void 0?E(e):(N??=e,P.abort())},"onSignal");process.on("SIGTERM",()=>Y("SIGTERM")),process.on("SIGINT",()=>Y("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&q().start(t,e)});const L=It(t),F=new Set;let Q;try{$e(L)&&ve(L)}catch{}const ne=n(()=>{try{ve(L)}catch{}},"removeViewSocket"),D=yt(e=>{if(Q!==void 0){Q(e);return}e.pause(),F.add(e),e.once("close",()=>F.delete(e)),e.on("error",()=>{})});await new Promise((e,r)=>{D.once("error",r),D.listen(L,()=>{D.off("error",r),e()})}),l("broker.startup.listening");const Z=process.hrtime.bigint();let ee;try{ee=await ar(R,c,(e,r)=>_(e,r))}catch(e){throw ne(),e}let{session:C,services:B,resuming:lr,runtime:ot}=ee;je(void 0),_("broker.startup.session_build",Z),l("broker.startup.session_built");const G=S.start;G!==void 0&&Xn();const ye=G===void 0?await Ze(t,C,"startup",P.signal):Hn(t,G);P.signal.aborted&&(C.dispose(),ne(),await We(),process.exit(0));const st=ye?.names===void 0?await Jn(t):ye.names,re=(await qn(t)).node.review_binding?.review_id,j=gt();le=C;const it=n(async()=>{const e=m.session().model;return e===void 0?{ok:!0}:await Ht(tn(`${e.provider}/${e.id}`,Be(),vt()))},"retryProbe");try{process.env.PI_PACKAGE_DIR=qt(),Vt(B.settingsManager.getTheme(),ae(),!1)}catch(e){h({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of Bt(ae()))h({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const w=new _n(t),oe=new Map,$=new hn(t,e=>w.broadcast(e)),H=new wn(t,e=>w.broadcast(e));bn(e=>w.broadcast({type:"node_named",...e}));let V=!1,Re=!1,se,Ee,m,te;const ce=new Rn;let J,ke=n(()=>{},"notifyTurnAccepted"),Te=n(()=>{},"resetFrameState"),Ce=n(()=>{},"bindAnswered");const me=En(G===void 0?void 0:new Promise(e=>{Ce=e}));let Me=n(()=>0,"pendingPromptDispatches"),Ae;const K=Nn({runNode:j,session:n(()=>m.session(),"session"),isReplacing:n(()=>m.isReplacing(),"isReplacing"),pendingRebind:n(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>Me(),"pendingDispatches"),turnAdmission:me,prependDeferred:n(e=>Pn(t,e),"prependDeferred"),onError:n(e=>h({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),xe=xn(K.steerable);globalThis[An]=xe,jn(()=>m.session());const Pe=K.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&K.holdForKickoff(),globalThis[Cn]=K.start,globalThis[Mn]=K.busy,m=new $n({nodeId:t,cfg:c,session:C,services:B,runtime:ot,registry:w,toolGroups:$,turnReplies:H,runSteer:xe,runNode:j,transcriptMessages:n(e=>ue(e),"transcriptMessages"),uiContext:n(()=>Ee,"uiContext"),faultRetry:n(()=>te,"faultRetry"),projection:n(()=>J,"projection"),setActiveSession:n(e=>{if(le=e,Ae?.(),j||process.env.CRTR_RUN_ID){let r="stop",i,u=!1;Ae=e.subscribe(f=>{if(f.type==="agent_start"&&(r="stop",i=void 0,u=!1,ce.started()),f.type==="agent_end"){const g=[...f.messages??[]].reverse().find(I=>I.role==="assistant");g&&(r=g.stopReason,i=ln(g)?void 0:pn(g,zt(g)),u=g.role==="assistant"&&yn(g,e.model?.contextWindow))}f.type==="agent_settled"&&(ce.settled(e.sessionManager,{stop_reason:r,...i?{error:i}:{}},u),j&&(_e().then(()=>On(t,e)).catch(async g=>{if(String(g?.message).startsWith("conversation_write_failed")){h({level:"error",event:"broker.exited",node_id:t,error:g,fields:{fault:"conversation_write_failed"}}),await ze(t,g),A("conversation_write_failed",1);return}h({level:"error",event:"broker.run_deferred_mail.settle_failed",error:g})}),queueMicrotask(()=>{m.session()===e&&Pe()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>A(e,r),"disposeAndExit"),onSessionRebind:n(()=>{Te()},"onSessionRebind"),onReplacementIdle:n(()=>{j&&Pe()},"onReplacementIdle"),reWelcomeAll:n(()=>fe(),"reWelcomeAll")});const Oe=n(async(e,r=!1)=>{const i=m.session(),u=z(i.model,i.thinkingLevel);if(u===null)return null;const f=await Vn(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:r});return r&&(c.model=f.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,c.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",c.modelExact=!0)),f.modelOverride},"persistModelChoice"),Ne=n(async(e=!0,r,i=!1)=>{const u=m.session(),f=z(u.model,u.thinkingLevel),g=e?await Oe(r,i):f;w.broadcast({type:"model_changed",model:be(u.model)?void 0:u.model,spec:g})},"broadcastModelChanged");te=new Sn({nodeId:t,cfg:c,retryProbe:it,currentSession:n(()=>m.session(),"currentSession"),currentServices:n(()=>m.services(),"currentServices"),installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),registryOf:Se,formatModelSpec:z,broadcastModelChanged:Ne,turnAdmission:me,reWelcomeAll:n(()=>fe(),"reWelcomeAll"),...j?{turnEnds:ce}:{}});const De=n(()=>{te.rearmIfStranded().catch(e=>{h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");q().subscribe("resync",De),q().subscribe("fault-retry",De),J=new Dn({registry:w,faultRetry:te,installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),currentSession:n(()=>m.session(),"currentSession"),notifyTurnAccepted:n(()=>ke(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:z});let ie=[];const Ie=n(async e=>{ie=[];const r=e.sessionManager.getEntries()[0],i=e.sessionManager.getSessionFile(),u=i===void 0?null:At(i);if(!(re!==void 0||r?.type!=="custom"||r.customType!==we||u===null))try{const{entries:f}=await Pt(u,{beforeCycle:un});ie=dn(f,r,fn)}catch(f){h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`earlier cycles read failed: ${String(f)}`}})}},"loadEarlierCycles"),at=Ie(C);function ue(e){const r=nt(e,re)?.map(({message:i})=>i)??e.sessionManager.buildSessionContext().messages;return[...ie.map(({message:i})=>i),...r]}n(ue,"turnSeedMessages");const dt=n(e=>{const r=m.session(),i=nt(r,re),u=i===void 0?void 0:[...ie.map(M=>({...M,visibility:"visible"})),...i],f=u?.map(({message:M})=>M)??r.sessionManager.buildSessionContext().messages,{start:g}=mn(f,M=>JSON.stringify(tt(M,t)).length),I=e.snapshotTail===void 0?g:Math.max(g,f.length-e.snapshotTail),k=u?.slice(I),U=f.slice(I).map(M=>tt(M,t)),ut=Zn(U),ft=Object.fromEntries(Object.entries($.summaries()).filter(([M])=>ut.has(M)));return{messages:U,...k===void 0?{}:{messageIds:k.map(({id:M})=>M)},messageVisibility:k?.map(({visibility:M})=>M)??U.map(()=>"visible"),turnVisibility:vn(),stats:r.getSessionStats(),state:{model:be(r.model)?void 0:r.model,thinkingLevel:r.thinkingLevel,isStreaming:r.isStreaming,isCompacting:r.isCompacting,steeringMode:r.steeringMode,followUpMode:r.followUpMode,sessionFile:r.sessionFile,sessionId:r.sessionId,sessionName:r.sessionName,autoCompactionEnabled:r.autoCompactionEnabled,messageCount:r.messages.length,pendingMessageCount:r.pendingMessageCount},display:{...w.displaySnapshot()},toolGroupSummaries:ft,turnReplies:H.snapshot(),workingActivity:J.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),Le=n(e=>{const r=e.role==="controller"?oe.values().next().value:void 0;w.sendFrame(e,{type:"welcome",snapshot:dt(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:ae()})},"sendWelcome"),lt=n(e=>{const r=[...oe.values()];for(let i=1;i<r.length;i++)w.sendFrame(e,r[i].request)},"replayExtraPendingDialogsTo"),fe=n(()=>{try{const e=m.session();H.seed(ue(e))}catch(e){h({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}w.forEachHelloed(Le)},"reWelcomeAll"),Fe=n(async e=>{if(V)return;V=!0;const r=q().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&Gn(t,process.env.CRTR_EXECUTION_ID??null),q().stop(),e===0&&await _e().catch(async i=>{e=1,h({level:"error",event:"broker.exited",node_id:t,error:i,fields:{fault:"conversation_write_failed"}}),await ze(t,i)}),$.persistPendingSummary(),J.dispose(),nr();try{D?.close(),se?.close()}catch{}a.close(),w.dispose();try{$e(L)&&ve(L)}catch{}w.clearAttachState(),await We(),process.exit(e)},"completeExit"),A=n((e,r=0)=>{if(V)return;const i=e==="shutdown-hook"||e==="shutdown-after-settle";if(i&&$.finishOpenToolGroup(!0),i&&($.hasSummaryTasks()||H.hasTasks())){if(Re)return;Re=!0,Promise.allSettled([$.waitForSummaryTasks(),H.waitForTasks()]).finally(()=>Fe(r));return}Fe(r)},"disposeAndExit");globalThis[kn]=A,Ee=dr({writable:n(()=>w.writableClients(),"writable"),forward:n((e,r)=>w.sendFrame(e,r),"forward"),pending:oe,broadcast:n(e=>w.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>J.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,B),l("broker.startup.extensions_bound");const O=In({nodeId:t,registry:w,toolGroups:$,projection:J,rebind:m,boundaryReviewId:re,pendingDialogs:oe,sendWelcome:Le,replayExtraPendingDialogsTo:lt,reWelcomeAll:fe,disposeAndExit:A,persistModelChoice:Oe,broadcastModelChanged:Ne,registryOf:Se,formatModelSpec:z,formatExactModelSpec:er,turnAdmission:me,memoryInventory:st,runNode:j,onKickoffAdmitted:K.releaseKickoff});ke=O.notifyTurnAccepted,Te=O.resetForSession,Me=O.pendingPromptDispatches,globalThis[Tn]=async e=>{for(const k of en){const U=e.env[k];U===void 0?delete process.env[k]:process.env[k]=U}process.env[He]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?c.model=e.model:delete c.model,e.modelExact?(c.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete c.modelExact,delete process.env.CRTR_MODEL_EXACT),c.editorName=e.editorLabel,K.holdForKickoff(),$.finishOpenToolGroup(!0);const r=m.session(),i=r.sessionManager.getSessionFile();if(i===void 0||i==="")throw new Error("in-place cycle needs a persisted session file");const u=r.sessionManager,f=u.getLeafId();u.resetLeaf(),u.appendCustomEntry(we,{cycle:e.cycle,fromLeaf:f}),await _e(),m.beforeNextBind(async k=>{const[U]=await Promise.all([Ze(t,k,"resume"),Ie(k)]);await O.refreshMemoryNames(U?.names)});const g=await m.runReplacement(null,"cycle",k=>k.switchSession(i));if(m.beforeNextBind(void 0),!g)return A("cycle-replacement-failed",1),!1;const I=qe(e.prompt);Je(I,Ye(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Xe(t,et(t))}catch(k){return h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:k,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1),!1}return O.kickoff(I,e.messageIds),!0};const ct=2500;let pe=!1;const mt=n(async e=>{if(V||pe)return;if(pe=!0,m.isAgentRunActive()||m.session().isStreaming||O.pendingPromptDispatches()>0){const i=Date.now()+ct;for(;O.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<i;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=i-Date.now();if(u>0){let f;try{Kn(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(I=>{f=setTimeout(()=>I(!1),u)})])&&await Ve(t,{event:"closed",end_reason:"teardown-aborted"})}finally{f!==void 0&&clearTimeout(f)}}}else(O.pendingPromptDispatches()>0||m.isAgentRunActive())&&await Ve(t,{event:"interrupted"})}A(e)},"abortAndExit");if(E=n(e=>{mt(e)},"signalTeardown"),N!==void 0){E(N);return}const ge=n(e=>{l("broker.startup.first_viewer_connected");const r=w.create(e);e.on("data",u=>{let f;try{f=r.decoder.push(u)}catch(g){g instanceof Qn?(w.sendFrame(r,{type:"error",code:"frame_overflow",message:g.message}),w.dropClient(r,`frame overflow: ${g.message}`)):w.dropClient(r,`decoder error: ${String(g)}`);return}for(const g of f)try{Ln(O,r,g)}catch{}});const i=n(()=>{w.removeClient(r)},"drop");e.on("close",i),e.on("error",()=>{})},"serveViewer");Qt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(se=new Rt({host:"::",port:kt,path:"/view",maxPayload:zn.maxLineBytes}),se.on("connection",e=>ge(Et(e))),se.on("error",e=>{V||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))})),D.on("error",e=>{V||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))}),await at;try{H.seed(ue(m.session()))}catch(e){h({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply seed failed: ${String(e)}`}})}Q=ge;for(const e of F)F.delete(e),ge(e),e.resume();(async()=>{if(Promise.all([de(t,{op:"clear",link:"viewer\u2194broker"}),de(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}})),G!==void 0){let r;try{try{r=await Qe(t,m.session(),G)}catch(i){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:i,fields:{operation:"session_bound",attempt:1}}),r=await Qe(t,m.session(),G)}}catch(i){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:i,fields:{operation:"session_bound",attempt:2}}),A("session-bound-failed",1);return}if(r?.action==="shutdown"){m.requestShutdown();return}if(r?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");q().start(t,Zt()),Yn(),Ce()}l("broker.startup.ready_for_turn");let e;try{e=await te.recoverOnStartup()}catch(r){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),A("recovery-startup-failed",1);return}if(!(V||pe))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const r=Ye(process.env[He]),i=qe(c.firstPrompt);r!==null&&Je(i,r);try{await Xe(t,et(t))}catch(f){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:f,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1);return}const u=process.env.CRTR_KICKOFF_MESSAGE_IDS;O.kickoff(i,u?JSON.parse(u):[])}else K.releaseKickoff()})(),w.persistAttachState()}n(Eo,"runBroker");function nt(t,o){const s=t.sessionManager,v=s.getEntries===void 0?void 0:cn(s.getEntries(),s.getLeafId?.());return v!==void 0&&Fn(v.map(({message:a})=>a)),v===void 0?void 0:gn(v,{boundaryReviewId:o,sessionEntries:s.getEntries?.()})}n(nt,"snapshotMessages");function rt(){const t=ht();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(rt,"currentBrokerNodeId");async function sr(t,o){const s=nn(o.model,Be(),o.modelExact===!0);if(s===void 0)return;const v=Se(t),a={cwd:_t()??o.cwd,profileId:wt()},d=await sn(s,v,a);if(d!==void 0)throw await de(rt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const p=await rn(s,a.cwd,a.profileId),l=on(s.spec);for(const _ of p){const y=v.find(_.providerId,_.modelId);if(y===void 0)continue;const x=l?.providerId===_.providerId&&l.modelId===_.modelId?l.thinkingLevel??(_.thinkingLevel===void 0?void 0:"off"):_.thinkingLevel;return{model:y,thinkingLevel:x}}if(o.modelExact===!0){const _=p.map(y=>`'${y.providerId}/${y.modelId}' unregistered`).join("; ");throw await de(rt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${_})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}h({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:p.map(_=>({provider:_.providerId,model:_.modelId,reason:"unregistered"})).slice(0,16)}})}n(sr,"resolveLaunchModel");function ir(t){let o=!0;return{runtime:new Proxy(t,{get(v,a,d){return o&&a==="getAvailableSnapshot"?()=>[]:o&&a==="getAvailable"?async()=>[]:o&&a==="getModel"?()=>{}:Reflect.get(v,a,d)}}),reveal:n(()=>{o=!1},"reveal")}}n(ir,"modelLessRegistry");async function ar(t,o,s=()=>{}){const v=ae(),a=n(async b=>{const S=process.hrtime.bigint(),c=await Nt.create({credentials:new Yt,modelsPath:Ke(b.agentDir,"models.json")});Jt(c),s("broker.startup.model_runtime",S);const E=process.hrtime.bigint(),N=await t.createAgentSessionServices({cwd:b.cwd,agentDir:b.agentDir,modelRuntime:c,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(P=>({...P,extensions:P.extensions.filter(Y=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(Y.path))}),"extensionsOverride")}});return s("broker.startup.resources_loaded",E),N},"loadServices");let d;const p=n(async b=>{const S=d;d=void 0;const c=await(S??a(b)),E=c.resourceLoader.getExtensions();if(o.extensionPaths.some(Z=>he.includes(Z))){const Z=new Set(E.extensions.map(C=>C.path)),ee=he.filter(C=>!Z.has(C));if(ee.length>0){const C=E.errors.filter(B=>he.includes(B.path)).map(B=>`${B.path}: ${B.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${ee.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const N=process.hrtime.bigint(),P=await sr(c,o);s("broker.startup.model_resolved",N);const Y=P?.model,L=P?.thinkingLevel,F=P===void 0?ir(c.modelRuntime):void 0,Q=F!==void 0?{...c,modelRuntime:F.runtime}:c,ne=process.hrtime.bigint(),D=await t.createAgentSessionFromServices({services:Q,sessionManager:b.sessionManager,model:Y,thinkingLevel:L,...rr(o.tools,bt()),sessionStartEvent:b.sessionStartEvent});return s("broker.startup.session_from_services",ne),Bn(D.session),Xt(D.session),F?.reveal(),{...D,services:c}},"buildForManager"),l=o.resumeSessionPath,_=o.forkFrom!==void 0&&o.forkFrom!=="";if(!_&&(l===void 0||l==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const y=!_&&l!==void 0&&l!=="",R=y&&o.newCycle===!0,x=y&&!R;let T;if(_)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(x||R){if(T=await t.SessionManager.open(l),R){const b=T.getLeafId();T.resetLeaf(),T.appendCustomEntry(we,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:b})}}else{const b=process.hrtime.bigint(),S=t.SessionManager.createAsync,c=(S!==void 0?S.call(t.SessionManager,o.cwd):Promise.resolve(t.SessionManager.create(o.cwd))).then(N=>(s("broker.startup.conversation_created",b),N));d=a({cwd:o.cwd,agentDir:v}),d.catch(()=>{});const E=process.hrtime.bigint();T=await c,await d,s("broker.startup.create_and_resources_joined",E)}if(t.createAgentSessionRuntime!==void 0){const b=n(async c=>{const E=await p({cwd:c.cwd,agentDir:c.agentDir,sessionManager:c.sessionManager,sessionStartEvent:c.sessionStartEvent});return{...E,diagnostics:E.services.diagnostics??[]}},"factory"),S=await t.createAgentSessionRuntime(b,{cwd:o.cwd,agentDir:v,sessionManager:T});return{session:S.session,services:S.services,resuming:x,runtime:S}}const X=await p({cwd:o.cwd,agentDir:v,sessionManager:T});return{session:X.session,services:X.services,resuming:x,runtime:void 0}}n(ar,"buildBrokerSession");function dr(t){const o=n((a,d,p,l)=>{if(l?.signal?.aborted)return Promise.resolve(a);const _=t.writable();return _.length===0?Promise.resolve(a):new Promise(y=>{let R;const x=n(()=>{R!==void 0&&clearTimeout(R),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=n(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(a)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const X=l?.timeout!==void 0?l.timeout:tr;R=setTimeout(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(a)},X),typeof R.unref=="function"&&R.unref(),t.pending.set(d.id,{request:d,resolve:n(b=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(p(b))},"resolve")});for(const b of _)t.forward(b,d)})},"dialogPromise"),s=n(()=>{},"noop");return{[an]:t.onKnownStreamWait??(a=>()=>{}),get theme(){const a=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(a==null)throw new Error("Theme not initialized. Call initTheme() first.");return a},select:n((a,d,p)=>o(void 0,{type:"extension_ui_request",id:W(),method:"select",title:a,options:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"select"),confirm:n((a,d,p)=>o(!1,{type:"extension_ui_request",id:W(),method:"confirm",title:a,message:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,p),"confirm"),input:n((a,d,p)=>o(void 0,{type:"extension_ui_request",id:W(),method:"input",title:a,placeholder:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"input"),editor:n((a,d)=>o(void 0,{type:"extension_ui_request",id:W(),method:"editor",title:a,prefill:d},p=>"cancelled"in p&&p.cancelled?void 0:"value"in p?p.value:void 0),"editor"),setStatus:n((a,d)=>t.broadcast({type:"extension_ui_request",id:W(),method:"setStatus",statusKey:a,statusText:d}),"setStatus"),setWidget:n((a,d,p)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:W(),method:"setWidget",widgetKey:a,widgetLines:d,widgetPlacement:p?.placement})},"setWidget"),setTitle:n(a=>t.broadcast({type:"extension_ui_request",id:W(),method:"setTitle",title:a}),"setTitle"),notify:n((a,d)=>{const p=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:W(),method:"notify",message:a,notifyType:p})},"notify"),onTerminalInput:n(()=>s,"onTerminalInput"),setWorkingMessage:s,setWorkingVisible:s,setWorkingIndicator:s,setHiddenThinkingLabel:s,setFooter:s,setHeader:s,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:s,setEditorText:s,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:s,setEditorComponent:s,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:s,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:s}}n(dr,"makeBrokerUiContext");export{Mo as REVIEW_BOUNDARY_NAVIGATION_CODE,Co as ReviewBoundaryNavigationError,rr as brokerToolOptions,ar as buildBrokerSession,nr as disposeActiveSession,dr as makeBrokerUiContext,Eo as runBroker,nt as snapshotMessages};
@@ -1,3 +1,3 @@
1
- var Ce=Object.defineProperty;var c=(e,r)=>Ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as Ne}from"./unsandboxed.js";import{spawn as De}from"node:child_process";import{mkdirSync as de,existsSync as j,unlinkSync as me,openSync as F,closeSync as L,writeSync as Le,chmodSync as Ae,lstatSync as $e}from"node:fs";import{ensureAppSpace as Be}from"../spaces/space.js";import{sandboxCacheEnv as je}from"../spaces/cache-env.js";import{compileLaunch as Fe,launchStillGranted as Ge}from"../spaces/mounts.js";import{grantsGeneration as he}from"../grants/mirror.js";import{LAUNCHER_SOCKET as z}from"../../launcher/spec.js";import{launcherRequest as G}from"../../launcher/client.js";import{piAgentDir as pe}from"./package-health.js";import{existsBeneath as V,readFileBeneath as Me,readTextBeneathIfExists as Ke,setModeBeneath as S,withDirBeneath as Q,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Y,join as m,resolve as Je,isAbsolute as Ue}from"node:path";import{fileURLToPath as we}from"node:url";import{connectViewSocket as He}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as We,readMergedLaunchConfig as qe}from"../config.js";import{isCloudRole as Xe}from"../canvas/person-state.js";import{readMergedLaunchConfigAsync as ze}from"./launch.js";import{loadRotationConfig as Ve}from"../subscription-state.js";import{getNode as _}from"../canvas/index.js";import{withCanvasWrite as Qe}from"../canvas/db.js";import{liveExecutionForNode as Ye,requestExecutionStop as Ze,setExecutionLaunchJson as Ie}from"../canvas/executions.js";import{scopesFilePath as Z,crtrHome as ge,nodeRunDir as I,nodeRunJobDir as er,jobDir as rr,viewSocketPath as nr,nodeAgentDir as tr,contextDir as or,nodeHome as ir}from"../canvas/paths.js";import{encodeFrame as Ee}from"./broker-protocol.js";import{buildBrokerEnv as ar}from"./spawn-env-rows.js";import{hostExecPathFresh as sr}from"./branded-host.js";import{isPidAlive as ee,killProcessTreePids as _e,isAnyPidAlive as cr,captureTeardownSnapshot as lr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ur}from"./canvas-extensions.js";import{appMemoryFull as fr,appMemoryTooSmall as dr,boundFleet as mr,brokerCapReached as hr,brokerThresholdsForDaemon as pr}from"./fleet.js";import{admitBrokerMemory as wr}from"./memory-admission.js";import{emitEvent as w}from"../events/emit.js";import{bindBrokerEventSource as gr,eventSource as Er}from"../events/source.js";import{envBrokerEngine as _r}from"../../shared/env.js";import{conversationIdFromPath as kr,conversationStore as vr,ConversationNotFoundError as ke}from"../conversation-store/index.js";import{mintNodeToken as yr}from"../canvas/node-tokens.js";import{launchSub as br}from"../runs/node-sub.js";function J(){const e=Y(we(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const Sr="@earendil-works/pi-coding-agent";function ve(){const e=m(pe(),"models.json"),r=Ke(Y(e),e);if(r===null)return null;const t=JSON.parse(r),o=c(n=>Array.isArray(n)?n.map(o):n===null||typeof n!="object"?n:Object.fromEntries(Object.entries(n).filter(([i])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(i)).map(([i,s])=>[i,o(s)])),"scrub");return{text:r,clean:`${JSON.stringify(o(t),null,2)}
2
- `,credentialed:JSON.stringify(t)!==JSON.stringify(o(t))}}c(ve,"scrubbedBrokerModels");function Rr(e,r){const t=m(pe(),"models.json"),o=m(r,"models.json"),n=ve();if(n!==null){if(t===o&&n.text!==n.clean){if(n.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");S(e,o,432);return}M(e,o,n.clean,{atomic:!0,mode:432}),S(e,o,432)}}c(Rr,"writeBrokerModels");function ye(e){return e.env.CRTR_BROKER_ENGINE??_r()}c(ye,"resolveEngineSpec");function be(e){return e.includes("/")||e.endsWith(".jsonl")}c(be,"isPlainLaunchSessionPath");function xr(e,r){return Ue(e)?e:Je(r,e)}c(xr,"resolvePlainLaunchPath");async function Pr(e,r,t,o){if(t==="--session"&&!be(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!be(o))return;const n=xr(o,r),i=kr(n);try{if(i===null)throw new ke(n);await vr().header(i)}catch(s){if(!(s instanceof ke))throw s;const u=t==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${n})`)}}c(Pr,"preflightLaunchSessionArg");async function Se(e,r,t){const o=ve();return JSON.stringify({...r,configSnapshot:{user:We("user"),launch:Xe()?await ze(t,r.env.CRTR_PROFILE_ID||null,r.env.CRTR_GRANTEE??"app:terminal"):qe(t,r.env.CRTR_PROFILE_ID||null),rotation:await Ve()},scopes:(await _(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Se,"brokerLaunchJson");async function Tr(e,r,t,o){const n=I(e);de(n,{recursive:!0}),process.platform==="linux"&&j(z)&&$e(n).uid===process.getuid()&&Ae(n,504);const i=m(n,"broker-launch.json");M(n,i,o??await Se(e,r,t),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(n,Z(e),JSON.stringify((await _(e))?.scopes??[]),{atomic:!0});const s=Me(n,i).toString("utf8"),u=JSON.parse(s);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const g=ye(r);try{const l=import.meta.resolve(g);if(l.startsWith("file:")&&!j(we(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${g}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,C=[];for(let l=0;l<h.length;l++){const T=h[l];if(T==="-e"){const N=h[++l];N!==void 0&&C.push(N);continue}if(T!=="--session"&&T!=="--fork")continue;const R=h[++l];R!==void 0&&await Pr(e,t,T,R)}try{ur(C)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Tr,"preflightBrokerLaunch");const Or=2e3,Cr=2e3,Nr=150;async function U(e,r){const t=Date.now()+r;for(;cr(e);){const o=t-Date.now();if(o<=0)return!1;await new Promise(n=>setTimeout(n,Math.min(Nr,o)))}return!0}c(U,"waitForTreeExit");async function Dr(e,r,t){return e.length===0?{confirmed:!0}:t&&await U(e,Or)?{confirmed:!0}:(_e(e,"SIGTERM",r),await U(e,Cr)?{confirmed:!0}:(_e(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Dr,"terminateBrokerTree");async function Re(e,r){const t=await _(e),o=t?.pi_pid,n=o!=null?lr(o,t?.pi_pid_identity??null,r.excludePid):null;return n?.reused===!0&&w({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:t?.pi_pid_identity??null}}),{tree:n?.tree??[],identities:n?.identities??null,nodeId:e,launcherPid:j(z)&&n?.tree.includes(o)?o:null}}c(Re,"prepareBrokerTeardown");async function xe(e){if(e.launcherPid!==null){try{await G({operation:"stop",pid:e.launcherPid})}catch(r){return ee(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let t=!1,o=!1;const n=c(g=>{o||(o=!0,r(g))},"settle"),i=c(()=>{try{me(nr(e.nodeId))}catch{}},"cleanupSocket"),s=c(g=>{Dr(e.tree,e.identities,g).then(n,h=>n({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=He(e.nodeId);u.once("error",()=>{t||(i(),s(!1))}),u.once("connect",()=>{t=!0;try{u.write(Ee({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(Ee({type:"shutdown"}))}catch{}u.end(),i(),s(!0)})})}c(xe,"runPreparedBrokerTeardown");async function gn(e,r={},t){let o;try{await Ze(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"});const n=await Ye(e);if(n?.runner==="machine"){const{runnerForExecution:i}=await import("./runner/index.js");o={machine:c(()=>i("machine").stop(n,{reason:r.reason??"teardown"}),"machine")}}else o=await Re(e,r)}catch(n){const i={confirmed:!1,error:n instanceof Error?n:new Error(String(n))};return w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:i.error}),i}return await new Promise(n=>{const i=c(()=>{("machine"in o?o.machine():xe(o)).then(async s=>{if(s.confirmed){if(t!==void 0)try{await t()}catch(u){w({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error});n(s)},s=>{const u={confirmed:!1,error:s instanceof Error?s:new Error(String(s))};w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),n(u)})},"run");r.startAfter===void 0?setImmediate(i):r.startAfter.then(i,i)})}c(gn,"requestBrokerTeardown");function Pe(){return process.platform==="linux"&&j(z)}c(Pe,"isolatedBrokerLauncherAvailable");const En={async launch(e,r,t){if(Ne((await _(e))?.grantee),(await _(e))?.isolated===!0&&!Pe())throw new Error("isolated broker requires the Linux root launcher");const o=t.launchJson??await Se(e,r,t.cwd);await Tr(e,r,t.cwd,o);const n=r.env.CRTR_EXECUTION_ID;t.launchJson===void 0&&n!==void 0&&await Ie(n,o);const i=mr();if(!await i.reserveSlot(e))throw hr(pr().automaticReviveCap,await i.occupancy());let s=null,u,g=!1;try{const h=rr(e);de(h,{recursive:!0}),s=F(m(h,"broker.log"),"a");const C=ye(r),l={...await ar(r),CRTR_BROKER_ENGINE:C};if(C!==Sr){const a=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;a!==void 0&&(l.NODE_OPTIONS=a);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}Er()===void 0&&gr(e);const T=(await _(e))?.run_id;if(T){const a=await _(T);if(!a||a.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const N=await Qe(a=>yr(a,R,e,new Date().toISOString())),H=Pe();if((await _(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const a=await _(e);if(!a)throw new Error(`missing node ${e}`);const f=a.grantee??"app:terminal",O=await wr(e,{useMemo:!1});if(O.verdict==="denied")throw fr(O);if(O.verdict==="too_small")throw dr(O);const v=await Be(f);Object.assign(l,je(f));const y={uid:process.getuid(),gid:v.gid},E=I(e);for(const[d,k]of[[K(f).nodes,tr(e,f)],[K(f).nodes,or(e,f)],[E,er(e)]])Q(d,k,()=>{},!0),S(d,k,1528,y);S(E,m(E,"broker-launch.json"),416,y),V(E,Z(e))&&S(E,Z(e),416,y);const te=m(E,"system-prompt.md");V(E,te)&&S(E,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(E,d);V(E,k)&&S(E,k,432,y)}const oe=a.isolated===!0,b=ir(e,f,oe);oe&&(Q(K(f).nodes,b,()=>{},!0),S(K(f).nodes,b,1528,y),l.HOME=b,l.PI_CODING_AGENT_DIR=m(b,".pi","agent"));const X=m(b,".pi","agent");Q(b,X,()=>{},!0),Rr(b,X);const ie=m(X,"settings.json"),Te=m(Y(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(b,ie,`${JSON.stringify({packages:[Te]})}
3
- `,{atomic:!0,mode:432}),S(b,ie,432);const ae=m(I(e),`token-${R}`),$=F(ae,"wx+",384);me(ae),Le($,N);const se=[F(`/proc/self/fd/${$}`,"r"),F(`/proc/self/fd/${$}`,"r")];L($);const ce={nodeId:e,app:f,sub:br(a.sub,e),grantId:a.grant_id??null,scopes:a.scopes??null,isolated:a.isolated===!0,...a.isolated===!0?{cwd:a.cwd}:{},command:[process.execPath,J(),"--canvas-home",ge(),"--epoch",i.epoch(),e],env:Object.fromEntries(Object.entries({...l,...a.isolated===!0?{PWD:a.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>w({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const D of se){const B=await he(),p=await Fe(ce);p.broker=!0;const P=await G({operation:"launch",spec:p},[D]);if(!("pid"in P))throw new Error("launcher did not return a pid");if(await he()===B||await Ge(ce,p)){d=P.pid;break}w({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:P.pid}}),await G({operation:"stop",pid:P.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Oe=Date.now(),le=new Promise(D=>{const B=setInterval(()=>{ee(k)||(clearInterval(B),G({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:P,signal:fe})=>{w({level:p||P!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:P,signal:fe,uptime_ms:Date.now()-Oe,oom_killed:p}}),D({code:P,signal:fe,...p?{oomKilled:!0}:{}})}))},250);B.unref()});L(s),s=null;const ue={pid:k,exited:le};return i.register(e,ue),g=!0,le.then(async D=>await i.onChildExit(e,D,R)),ue}finally{for(const d of se)L(d)}}const W=await sr(),x=De(W,[J(),"--canvas-home",ge(),"--epoch",i.epoch(),e],{cwd:t.cwd,detached:!0,stdio:["ignore",s,s,"pipe"],env:l});u=x;try{await new Promise((a,f)=>{x.once("spawn",a),x.once("error",f)})}catch(a){throw w({level:"error",event:"broker.launch.failed",node_id:e,error:a,fields:{cwd:t.cwd,executable:W}}),new Error(`could not spawn the broker (executable ${W}, cwd ${t.cwd}): ${a.message}`,{cause:a})}const A=x.stdio[3];if(!A||!("end"in A))throw new Error("broker token pipe did not open");A.on("error",a=>w({event:"broker.token_pipe.failed",level:"error",node_id:e,error:a})),A.end(N),L(s),s=null;const re=Date.now(),ne=new Promise(a=>{let f=!1;const O=c(v=>{f||(f=!0,a(v))},"finish");x.once("exit",(v,y)=>{w({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-re}}),O({code:v,signal:y})}),x.once("error",v=>{w({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-re}}),O({code:null,signal:null})})});x.unref();const q={pid:x.pid??null,exited:ne};return q.pid!==null&&(i.register(e,q),g=!0,ne.then(async a=>await i.onChildExit(e,a,R))),q}catch(h){if(!g&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{g||i.releaseReservation(e),s!==null&&L(s)}},async isAlive(e){return ee((typeof e=="string"?await _(e):e)?.pi_pid)},async teardown(e,r={}){try{return xe(await Re(e,r))}catch(t){return Promise.resolve({confirmed:!1,error:t instanceof Error?t:new Error(String(t))})}},async signal(e,r){const t=(await _(e))?.pi_pid;if(t!=null)try{process.kill(t,r)}catch{}}};export{Se as brokerLaunchJson,En as headlessBrokerHost,Pe as isolatedBrokerLauncherAvailable,Tr as preflightBrokerLaunch,gn as requestBrokerTeardown};
1
+ var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Le}from"node:child_process";import{mkdirSync as de,existsSync as j,unlinkSync as me,openSync as F,closeSync as L,writeSync as Ae,chmodSync as $e,lstatSync as Be}from"node:fs";import{ensureAppSpace as je}from"../spaces/space.js";import{sandboxCacheEnv as Fe}from"../spaces/cache-env.js";import{compileLaunch as Ge,launchStillGranted as Me}from"../spaces/mounts.js";import{grantsGeneration as he}from"../grants/mirror.js";import{LAUNCHER_SOCKET as z}from"../../launcher/spec.js";import{launcherRequest as G}from"../../launcher/client.js";import{piAgentDir as pe}from"./package-health.js";import{existsBeneath as V,readFileBeneath as Ke,readTextBeneathIfExists as Je,setModeBeneath as S,withDirBeneath as Q,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Y,join as m,resolve as Ue,isAbsolute as He}from"node:path";import{fileURLToPath as we}from"node:url";import{connectViewSocket as We}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as qe,readMergedLaunchConfig as Xe}from"../config.js";import{isCloudRole as ze}from"../canvas/person-state.js";import{readMergedLaunchConfigAsync as Ve}from"./launch.js";import{loadRotationConfig as Qe}from"../subscription-state.js";import{getNode as _}from"../canvas/index.js";import{withCanvasWrite as Ye}from"../canvas/db.js";import{liveExecutionForNode as Ze,requestExecutionStop as Ie,setExecutionLaunchJson as er}from"../canvas/executions.js";import{scopesFilePath as Z,crtrHome as ge,nodeRunDir as I,nodeRunJobDir as rr,jobDir as nr,viewSocketPath as tr,nodeAgentDir as or,contextDir as Ee,nodeHome as ir}from"../canvas/paths.js";import{encodeFrame as _e}from"./broker-protocol.js";import{buildBrokerEnv as ar}from"./spawn-env-rows.js";import{hostExecPathFresh as sr}from"./branded-host.js";import{isPidAlive as ee,killProcessTreePids as ke,isAnyPidAlive as cr,captureTeardownSnapshot as lr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ur}from"./canvas-extensions.js";import{appMemoryFull as fr,appMemoryTooSmall as dr,boundFleet as mr,brokerCapReached as hr,brokerThresholdsForDaemon as pr}from"./fleet.js";import{admitBrokerMemory as wr}from"./memory-admission.js";import{emitEvent as w}from"../events/emit.js";import{bindBrokerEventSource as gr,eventSource as Er}from"../events/source.js";import{envBrokerEngine as _r}from"../../shared/env.js";import{conversationIdFromPath as kr,conversationStore as vr,ConversationNotFoundError as ve}from"../conversation-store/index.js";import{mintNodeToken as yr}from"../canvas/node-tokens.js";import{launchSub as br}from"../runs/node-sub.js";function J(){const e=Y(we(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const Sr="@earendil-works/pi-coding-agent";function ye(){const e=m(pe(),"models.json"),r=Je(Y(e),e);if(r===null)return null;const t=JSON.parse(r),o=c(n=>Array.isArray(n)?n.map(o):n===null||typeof n!="object"?n:Object.fromEntries(Object.entries(n).filter(([i])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(i)).map(([i,s])=>[i,o(s)])),"scrub");return{text:r,clean:`${JSON.stringify(o(t),null,2)}
2
+ `,credentialed:JSON.stringify(t)!==JSON.stringify(o(t))}}c(ye,"scrubbedBrokerModels");function Rr(e,r){const t=m(pe(),"models.json"),o=m(r,"models.json"),n=ye();if(n!==null){if(t===o&&n.text!==n.clean){if(n.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");S(e,o,432);return}M(e,o,n.clean,{atomic:!0,mode:432}),S(e,o,432)}}c(Rr,"writeBrokerModels");function be(e){return e.env.CRTR_BROKER_ENGINE??_r()}c(be,"resolveEngineSpec");function Se(e){return e.includes("/")||e.endsWith(".jsonl")}c(Se,"isPlainLaunchSessionPath");function Tr(e,r){return He(e)?e:Ue(r,e)}c(Tr,"resolvePlainLaunchPath");async function xr(e,r,t,o){if(t==="--session"&&!Se(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!Se(o))return;const n=Tr(o,r),i=kr(n);try{if(i===null)throw new ve(n);await vr().header(i)}catch(s){if(!(s instanceof ve))throw s;const u=t==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${n})`)}}c(xr,"preflightLaunchSessionArg");async function Re(e,r,t){const o=ye();return JSON.stringify({...r,configSnapshot:{user:qe("user"),launch:ze()?await Ve(t,r.env.CRTR_PROFILE_ID||null,r.env.CRTR_GRANTEE??"app:terminal"):Xe(t,r.env.CRTR_PROFILE_ID||null),rotation:await Qe()},scopes:(await _(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Re,"brokerLaunchJson");async function Pr(e,r,t,o){const n=I(e);de(n,{recursive:!0}),process.platform==="linux"&&j(z)&&Be(n).uid===process.getuid()&&$e(n,504);const i=m(n,"broker-launch.json");M(n,i,o??await Re(e,r,t),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(n,Z(e),JSON.stringify((await _(e))?.scopes??[]),{atomic:!0});const s=Ke(n,i).toString("utf8"),u=JSON.parse(s);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const g=be(r);try{const l=import.meta.resolve(g);if(l.startsWith("file:")&&!j(we(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${g}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,C=[];for(let l=0;l<h.length;l++){const P=h[l];if(P==="-e"){const N=h[++l];N!==void 0&&C.push(N);continue}if(P!=="--session"&&P!=="--fork")continue;const R=h[++l];R!==void 0&&await xr(e,t,P,R)}try{ur(C)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Pr,"preflightBrokerLaunch");const Or=2e3,Cr=2e3,Nr=150;async function U(e,r){const t=Date.now()+r;for(;cr(e);){const o=t-Date.now();if(o<=0)return!1;await new Promise(n=>setTimeout(n,Math.min(Nr,o)))}return!0}c(U,"waitForTreeExit");async function Dr(e,r,t){return e.length===0?{confirmed:!0}:t&&await U(e,Or)?{confirmed:!0}:(ke(e,"SIGTERM",r),await U(e,Cr)?{confirmed:!0}:(ke(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Dr,"terminateBrokerTree");async function Te(e,r){const t=await _(e),o=t?.pi_pid,n=o!=null?lr(o,t?.pi_pid_identity??null,r.excludePid):null;return n?.reused===!0&&w({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:t?.pi_pid_identity??null}}),{tree:n?.tree??[],identities:n?.identities??null,nodeId:e,launcherPid:j(z)&&n?.tree.includes(o)?o:null}}c(Te,"prepareBrokerTeardown");async function xe(e){if(e.launcherPid!==null){try{await G({operation:"stop",pid:e.launcherPid})}catch(r){return ee(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let t=!1,o=!1;const n=c(g=>{o||(o=!0,r(g))},"settle"),i=c(()=>{try{me(tr(e.nodeId))}catch{}},"cleanupSocket"),s=c(g=>{Dr(e.tree,e.identities,g).then(n,h=>n({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=We(e.nodeId);u.once("error",()=>{t||(i(),s(!1))}),u.once("connect",()=>{t=!0;try{u.write(_e({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(_e({type:"shutdown"}))}catch{}u.end(),i(),s(!0)})})}c(xe,"runPreparedBrokerTeardown");async function gn(e,r={},t){let o;try{await Ie(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"});const n=await Ze(e);if(n?.runner==="machine"){const{runnerForExecution:i}=await import("./runner/index.js");o={machine:c(()=>i("machine").stop(n,{reason:r.reason??"teardown"}),"machine")}}else o=await Te(e,r)}catch(n){const i={confirmed:!1,error:n instanceof Error?n:new Error(String(n))};return w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:i.error}),i}return await new Promise(n=>{const i=c(()=>{("machine"in o?o.machine():xe(o)).then(async s=>{if(s.confirmed){if(t!==void 0)try{await t()}catch(u){w({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error});n(s)},s=>{const u={confirmed:!1,error:s instanceof Error?s:new Error(String(s))};w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),n(u)})},"run");r.startAfter===void 0?setImmediate(i):r.startAfter.then(i,i)})}c(gn,"requestBrokerTeardown");function Pe(){return process.platform==="linux"&&j(z)}c(Pe,"isolatedBrokerLauncherAvailable");const En={async launch(e,r,t){if(De((await _(e))?.grantee),(await _(e))?.isolated===!0&&!Pe())throw new Error("isolated broker requires the Linux root launcher");const o=t.launchJson??await Re(e,r,t.cwd);await Pr(e,r,t.cwd,o);const n=r.env.CRTR_EXECUTION_ID;t.launchJson===void 0&&n!==void 0&&await er(n,o);const i=mr();if(!await i.reserveSlot(e))throw hr(pr().automaticReviveCap,await i.occupancy());let s=null,u,g=!1;try{const h=nr(e);de(h,{recursive:!0}),s=F(m(h,"broker.log"),"a");const C=be(r),l={...await ar(r),CRTR_BROKER_ENGINE:C,CRTR_CONTEXT_DIR:Ee(e,r.env.CRTR_GRANTEE??"app:terminal")};if(C!==Sr){const a=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;a!==void 0&&(l.NODE_OPTIONS=a);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}Er()===void 0&&gr(e);const P=(await _(e))?.run_id;if(P){const a=await _(P);if(!a||a.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const N=await Ye(a=>yr(a,R,e,new Date().toISOString())),H=Pe();if((await _(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const a=await _(e);if(!a)throw new Error(`missing node ${e}`);const f=a.grantee??"app:terminal",O=await wr(e,{useMemo:!1});if(O.verdict==="denied")throw fr(O);if(O.verdict==="too_small")throw dr(O);const v=await je(f);Object.assign(l,Fe(f));const y={uid:process.getuid(),gid:v.gid},E=I(e);for(const[d,k]of[[K(f).nodes,or(e,f)],[K(f).nodes,Ee(e,f)],[E,rr(e)]])Q(d,k,()=>{},!0),S(d,k,1528,y);S(E,m(E,"broker-launch.json"),416,y),V(E,Z(e))&&S(E,Z(e),416,y);const te=m(E,"system-prompt.md");V(E,te)&&S(E,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(E,d);V(E,k)&&S(E,k,432,y)}const oe=a.isolated===!0,b=ir(e,f,oe);oe&&(Q(K(f).nodes,b,()=>{},!0),S(K(f).nodes,b,1528,y),l.HOME=b,l.PI_CODING_AGENT_DIR=m(b,".pi","agent"));const X=m(b,".pi","agent");Q(b,X,()=>{},!0),Rr(b,X);const ie=m(X,"settings.json"),Oe=m(Y(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(b,ie,`${JSON.stringify({packages:[Oe]})}
3
+ `,{atomic:!0,mode:432}),S(b,ie,432);const ae=m(I(e),`token-${R}`),$=F(ae,"wx+",384);me(ae),Ae($,N);const se=[F(`/proc/self/fd/${$}`,"r"),F(`/proc/self/fd/${$}`,"r")];L($);const ce={nodeId:e,app:f,sub:br(a.sub,e),grantId:a.grant_id??null,scopes:a.scopes??null,isolated:a.isolated===!0,...a.isolated===!0?{cwd:a.cwd}:{},command:[process.execPath,J(),"--canvas-home",ge(),"--epoch",i.epoch(),e],env:Object.fromEntries(Object.entries({...l,...a.isolated===!0?{PWD:a.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>w({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const D of se){const B=await he(),p=await Ge(ce);p.broker=!0;const x=await G({operation:"launch",spec:p},[D]);if(!("pid"in x))throw new Error("launcher did not return a pid");if(await he()===B||await Me(ce,p)){d=x.pid;break}w({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:x.pid}}),await G({operation:"stop",pid:x.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Ce=Date.now(),le=new Promise(D=>{const B=setInterval(()=>{ee(k)||(clearInterval(B),G({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:x,signal:fe})=>{w({level:p||x!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:x,signal:fe,uptime_ms:Date.now()-Ce,oom_killed:p}}),D({code:x,signal:fe,...p?{oomKilled:!0}:{}})}))},250);B.unref()});L(s),s=null;const ue={pid:k,exited:le};return i.register(e,ue),g=!0,le.then(async D=>await i.onChildExit(e,D,R)),ue}finally{for(const d of se)L(d)}}const W=await sr(),T=Le(W,[J(),"--canvas-home",ge(),"--epoch",i.epoch(),e],{cwd:t.cwd,detached:!0,stdio:["ignore",s,s,"pipe"],env:l});u=T;try{await new Promise((a,f)=>{T.once("spawn",a),T.once("error",f)})}catch(a){throw w({level:"error",event:"broker.launch.failed",node_id:e,error:a,fields:{cwd:t.cwd,executable:W}}),new Error(`could not spawn the broker (executable ${W}, cwd ${t.cwd}): ${a.message}`,{cause:a})}const A=T.stdio[3];if(!A||!("end"in A))throw new Error("broker token pipe did not open");A.on("error",a=>w({event:"broker.token_pipe.failed",level:"error",node_id:e,error:a})),A.end(N),L(s),s=null;const re=Date.now(),ne=new Promise(a=>{let f=!1;const O=c(v=>{f||(f=!0,a(v))},"finish");T.once("exit",(v,y)=>{w({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-re}}),O({code:v,signal:y})}),T.once("error",v=>{w({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-re}}),O({code:null,signal:null})})});T.unref();const q={pid:T.pid??null,exited:ne};return q.pid!==null&&(i.register(e,q),g=!0,ne.then(async a=>await i.onChildExit(e,a,R))),q}catch(h){if(!g&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{g||i.releaseReservation(e),s!==null&&L(s)}},async isAlive(e){return ee((typeof e=="string"?await _(e):e)?.pi_pid)},async teardown(e,r={}){try{return xe(await Te(e,r))}catch(t){return Promise.resolve({confirmed:!1,error:t instanceof Error?t:new Error(String(t))})}},async signal(e,r){const t=(await _(e))?.pi_pid;if(t!=null)try{process.kill(t,r)}catch{}}};export{Re as brokerLaunchJson,En as headlessBrokerHost,Pe as isolatedBrokerLauncherAvailable,Pr as preflightBrokerLaunch,gn as requestBrokerTeardown};
@@ -4,7 +4,7 @@ import { type WakeOrigin } from './bearings.js';
4
4
  * it as the prompt of a strict resume that follows a cleanly aborted turn. */
5
5
  export declare const RUNTIME_RESTART_CONTINUATION: string;
6
6
  /** The original spawning prompt, retained in the node row. */
7
- export declare function goalPath(nodeId: string): Promise<string>;
7
+ export declare function goalPath(_nodeId: string): Promise<string>;
8
8
  export declare function readGoal(nodeId: string): Promise<string | null>;
9
9
  export declare function writeGoal(nodeId: string, text: string): Promise<void>;
10
10
  /** A concurrent first user message must never overwrite the first goal. */