@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 +1 @@
1
- var J=Object.defineProperty;var _=(s,e)=>J(s,"name",{value:e,configurable:!0});import{existsSync as v,readFileSync as B,readdirSync as C,statSync as S}from"node:fs";import{bashJobPaths as g,bashJobsDir as E,clearJobDeadlineFile as T,formatBashElapsed as D,isBashJobProcessConfirmedGone as O,readJobSupervisorState as b,signalBashJob as R}from"../../core/bash-jobs.js";import{queueJobStop as L}from"../cron/machine-fire.js";import{killBashJobObject as P,recordBashJobObject as j}from"../../core/spaces/stop.js";import{readFileBeneath as N}from"../../core/spaces/open-beneath.js";import{blobStore as U}from"../../core/blobs/index.js";import{openDb as c,withCanvasWrite as f}from"../../core/canvas/db.js";import{applyJobReport as k,endJobsOfExitedSandboxes as q,endReportedJobs as F,expiredJobs as K,jobRow as z,ownerRunsRemotely as y,recordJobSilence as G,runningJobs as M,setJobDeadline as V}from"../../core/graph/jobs.js";import{publish as Y}from"../../core/graph/events.js";import{envBashSilenceMs as $}from"../../shared/env.js";import{getById as A}from"../../core/graph/objects.js";import{isSafeNodeId as u}from"../../core/canvas/paths.js";import{contextDir as x}from"../../core/canvas/node-agent-paths.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isProfilePaused as H}from"../../core/profiles/manifest.js";import{runThrottledLane as W}from"./throttled-lane.js";const X=300*1e3;function Q(s,e,t){const i=s<t?0:s<2*t?t:s<4*t?2*t:4*t*Math.floor(s/(4*t));return i>e?i:null}_(Q,"dueSilenceThresholdMs");const Z=5*1e3,tt=60*1e3,m=64*1024;class vt{static{_(this,"BashDeadlineReconciler")}startedAt=Date.now();uploadedBytes=new Map;async run(e,t){await this.mirrorSupervisors(t),await this.publishExits(),await W("bash-deadline","",e,Z,tt,i=>this.scan(e,t,i))}async scan(e,t,i){const a=new Set;for(const n of t.rows)if(n.status!=="dead"&&!H(n.profile_id)&&(a.add(n.node_id),!await y(await c(),n.node_id)))try{await this.adoptUnrecorded(n.node_id,await x(n.node_id))}catch(o){p.fresh(()=>{l({level:"error",event:"bash_deadline.scan_failed",...u(n.node_id)?{node_id:n.node_id}:{},error:o})})}for(const n of await K(await c(),e))if(a.has(n.owner)){if(!await i.holds())return;await this.cancel(n)}for(const n of a)try{await this.warnSilent(n,e)}catch(o){p.fresh(()=>{l({level:"error",event:"bash_silence.scan_failed",...u(n)?{node_id:n}:{},error:o})})}}async warnSilent(e,t){const i=$(),a=await y(await c(),e);for(const n of await M(await c(),e)){const o=n.activity??(a?{lastActivityMs:n.startedAtMs,sampledAtMs:t,files:[]}:null);if(n.quietOk||o===null||!a&&t-o.sampledAtMs>X)continue;const r=t-o.lastActivityMs,d=n.silence,I=Q(r,d?.lastActivityMs===o.lastActivityMs?d.thresholdMs:0,i);I!==null&&await f(async h=>{const w=await A(h,n.jobId);w===null||w.type!=="job"||(await z(h,w))?.status!=="running"||(await Y(h,{event:"silent",object:w,actor:null,attrs:{"silent-for":D(r),files:o.files.join(", "),"output-key":n.outputKey}}),await G(h,n.jobId,o.lastActivityMs,I))})}}async mirrorSupervisors(e){for(const t of e.rows)if(t.status!=="dead")try{const i=await M(await c(),t.node_id);if(i.length===0||await y(await c(),t.node_id))continue;const a=await x(t.node_id);for(const n of i)await this.mirror(a,n)}catch(i){p.fresh(()=>{l({level:"error",event:"bash_mirror.failed",...u(t.node_id)?{node_id:t.node_id}:{},error:i})})}}async mirror(e,t){const i=b(e,t.jobId),a=i.pgid??t.pgid??void 0,n=i.pgidIdentity??t.pgidIdentity??void 0,o=i.exitCode===void 0&&O(a,n)&&b(e,t.jobId).exitCode===void 0;i.deadlineMs!==void 0&&(t.deadlineAtMs===null&&await f(r=>V(r,t.jobId,i.deadlineMs)),T(g(e,t.jobId))),await this.uploadOutput(e,t),(i.exitCode!==void 0||o)&&this.uploadedBytes.delete(t.jobId),await f(async r=>k(r,t.jobId,{...i.pgid===void 0||i.pgid===t.pgid?{}:{pgid:i.pgid},...i.pgidIdentity===void 0||i.pgidIdentity===t.pgidIdentity?{}:{pgidIdentity:i.pgidIdentity},...i.activity===void 0?{}:{activity:i.activity},...i.exitCode===void 0?{}:{exitCode:i.exitCode},...o?{vanished:!0}:{}}))}async uploadOutput(e,t){const i=g(e,t.jobId);let a;try{a=S(i.jobLog).size}catch{return}const n=this.uploadedBytes.get(t.jobId)??0;if(a<=n)return;const o=await U(),r=N(i.root,i.jobLog);for(let d=Math.floor(n/m);d*m<r.length;d++)await o.put(`${t.outputKey}/${String(d).padStart(8,"0")}`,r.subarray(d*m,(d+1)*m));this.uploadedBytes.set(t.jobId,r.length)}async publishExits(){try{await f(async e=>{await F(e),await q(e)})}catch(e){p.fresh(()=>l({level:"error",event:"bash_completion.delivery_failed",error:e}))}}async adoptUnrecorded(e,t){let i;try{i=C(E(t))}catch{return}await f(async a=>{for(const n of i){if(await A(a,n)!==null)continue;const o=g(t,n);!v(o.jobBg)||!v(o.cmdSh)||v(o.jobExit)&&S(o.jobExit).mtimeMs<this.startedAt||await j(e,n,{command:B(o.cmdSh,"utf8")})}})}async cancel(e){const t=await y(await c(),e.owner);!t&&(e.pgid===null||e.pgidIdentity===null)||await p.fresh(async()=>{try{if(t||await R(e.pgid,e.pgidIdentity,e.owner),!await P(e.jobId,async()=>null,"deadline"))return;t&&await L(e.owner,e.jobId),l({level:"info",event:"bash_deadline.canceled",...u(e.owner)?{node_id:e.owner}:{},fields:{job_id:e.jobId}})}catch(i){l({level:"error",event:"bash_deadline.notice_failed",...u(e.owner)?{node_id:e.owner}:{},error:i,fields:{job_id:e.jobId}})}})}}export{vt as BashDeadlineReconciler,Q as dueSilenceThresholdMs};
1
+ var J=Object.defineProperty;var _=(s,e)=>J(s,"name",{value:e,configurable:!0});import{existsSync as v,readFileSync as B,readdirSync as C,statSync as S}from"node:fs";import{bashJobPaths as g,bashJobsDir as E,clearJobDeadlineFile as T,formatBashElapsed as D,isBashJobProcessConfirmedGone as O,readJobSupervisorState as b,signalBashJob as R}from"../../core/bash-jobs.js";import{queueJobStop as L}from"../cron/machine-fire.js";import{killBashJobObject as P,recordBashJobObject as j}from"../../core/spaces/stop.js";import{readFileBeneath as N}from"../../core/spaces/open-beneath.js";import{blobStore as U}from"../../core/blobs/index.js";import{openDb as c,withCanvasWrite as f}from"../../core/canvas/db.js";import{applyJobReport as k,endJobsOfExitedSandboxes as q,endReportedJobs as F,expiredJobs as K,jobRow as z,ownerRunsRemotely as y,recordJobSilence as G,runningJobs as M,setJobDeadline as V}from"../../core/graph/jobs.js";import{publish as Y}from"../../core/graph/events.js";import{envBashSilenceMs as $}from"../../shared/env.js";import{getById as A}from"../../core/graph/objects.js";import{isSafeNodeId as u}from"../../core/canvas/paths.js";import{contextDir as x}from"../../core/canvas/node-agent-paths.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isProfilePaused as H}from"../../core/profiles/manifest.js";import{runThrottledLane as W}from"./throttled-lane.js";const X=300*1e3;function Q(s,e,t){const i=s<t?0:s<2*t?t:s<4*t?2*t:4*t*Math.floor(s/(4*t));return i>e?i:null}_(Q,"dueSilenceThresholdMs");const Z=5*1e3,tt=60*1e3,m=64*1024;class vt{static{_(this,"BashDeadlineReconciler")}startedAt=Date.now();uploadedBytes=new Map;async run(e,t){await this.mirrorSupervisors(t),await this.publishExits(),await W("bash-deadline","",e,Z,tt,i=>this.scan(e,t,i))}async scan(e,t,i){const a=new Set;for(const n of t.rows)if(n.status!=="dead"&&!H(n.profile_id)&&(a.add(n.node_id),!await y(await c(),n.node_id)))try{await this.adoptUnrecorded(n.node_id,await x(n.node_id))}catch(o){p.fresh(()=>{l({level:"error",event:"bash_deadline.scan_failed",...u(n.node_id)?{node_id:n.node_id}:{},error:o})})}for(const n of await K(await c(),e))if(a.has(n.owner)){if(!await i.holds())return;await this.cancel(n)}for(const n of a)try{await this.warnSilent(n,e)}catch(o){p.fresh(()=>{l({level:"error",event:"bash_silence.scan_failed",...u(n)?{node_id:n}:{},error:o})})}}async warnSilent(e,t){const i=$(),a=await y(await c(),e);for(const n of await M(await c(),e)){const o=n.activity??(a?{lastActivityMs:n.startedAtMs,sampledAtMs:t,files:[]}:null);if(n.quietOk||o===null||!a&&t-o.sampledAtMs>X)continue;const r=t-o.lastActivityMs,d=n.silence,I=Q(r,d?.lastActivityMs===o.lastActivityMs?d.thresholdMs:0,i);I!==null&&await f(async h=>{const w=await A(h,n.jobId);w===null||w.type!=="job"||(await z(h,w))?.status!=="running"||(await Y(h,{event:"silent",object:w,actor:null,attrs:{"silent-for":D(r),files:o.files.join(", "),"output-key":n.outputKey}}),await G(h,n.jobId,o.lastActivityMs,I))})}}async mirrorSupervisors(e){for(const t of e.rows)if(t.status!=="dead")try{const i=await M(await c(),t.node_id);if(i.length===0||await y(await c(),t.node_id))continue;const a=await x(t.node_id);for(const n of i)await this.mirror(a,n)}catch(i){p.fresh(()=>{l({level:"error",event:"bash_mirror.failed",...u(t.node_id)?{node_id:t.node_id}:{},error:i})})}}async mirror(e,t){const i=b(e,t.jobId),a=i.pgid??t.pgid??void 0,n=i.pgidIdentity??t.pgidIdentity??void 0,o=process.platform!=="linux"&&i.exitCode===void 0&&O(a,n)&&b(e,t.jobId).exitCode===void 0;i.deadlineMs!==void 0&&(t.deadlineAtMs===null&&await f(r=>V(r,t.jobId,i.deadlineMs)),T(g(e,t.jobId))),await this.uploadOutput(e,t),(i.exitCode!==void 0||o)&&this.uploadedBytes.delete(t.jobId),await f(async r=>k(r,t.jobId,{...i.pgid===void 0||i.pgid===t.pgid?{}:{pgid:i.pgid},...i.pgidIdentity===void 0||i.pgidIdentity===t.pgidIdentity?{}:{pgidIdentity:i.pgidIdentity},...i.activity===void 0?{}:{activity:i.activity},...i.exitCode===void 0?{}:{exitCode:i.exitCode},...o?{vanished:!0}:{}}))}async uploadOutput(e,t){const i=g(e,t.jobId);let a;try{a=S(i.jobLog).size}catch{return}const n=this.uploadedBytes.get(t.jobId)??0;if(a<=n)return;const o=await U(),r=N(i.root,i.jobLog);for(let d=Math.floor(n/m);d*m<r.length;d++)await o.put(`${t.outputKey}/${String(d).padStart(8,"0")}`,r.subarray(d*m,(d+1)*m));this.uploadedBytes.set(t.jobId,r.length)}async publishExits(){try{await f(async e=>{await F(e),await q(e)})}catch(e){p.fresh(()=>l({level:"error",event:"bash_completion.delivery_failed",error:e}))}}async adoptUnrecorded(e,t){let i;try{i=C(E(t))}catch{return}await f(async a=>{for(const n of i){if(await A(a,n)!==null)continue;const o=g(t,n);!v(o.jobBg)||!v(o.cmdSh)||v(o.jobExit)&&S(o.jobExit).mtimeMs<this.startedAt||await j(e,n,{command:B(o.cmdSh,"utf8")})}})}async cancel(e){const t=await y(await c(),e.owner);!t&&(e.pgid===null||e.pgidIdentity===null)||await p.fresh(async()=>{try{if(t||await R(e.pgid,e.pgidIdentity,e.owner),!await P(e.jobId,async()=>null,"deadline"))return;t&&await L(e.owner,e.jobId),l({level:"info",event:"bash_deadline.canceled",...u(e.owner)?{node_id:e.owner}:{},fields:{job_id:e.jobId}})}catch(i){l({level:"error",event:"bash_deadline.notice_failed",...u(e.owner)?{node_id:e.owner}:{},error:i,fields:{job_id:e.jobId}})}})}}export{vt as BashDeadlineReconciler,Q as dueSilenceThresholdMs};
@@ -1,7 +1,7 @@
1
- var fe=Object.defineProperty;var o=(e,n)=>fe(e,"name",{value:n,configurable:!0});import{envBashAutoBgDeadlineMs as q,envBashValveMs as he,envNodeId as be}from"../shared/env.js";import{closeSync as me,existsSync as v,mkdirSync as X,openSync as pe,readFileSync as Y,readSync as ge,rmSync as Q,statSync as Z,writeFileSync as M}from"node:fs";import{homedir as we}from"node:os";import{dirname as ye}from"node:path";import{performance as N}from"node:perf_hooks";import{backgroundBashJob as ee,bashJobPaths as ve,clearJobDeadlineFile as Ee,writeJobDeadlineFile as _e,cancelBashJobProcessTree as je,countJobLogLines as Se,formatBashElapsed as te,newBashJobId as ke,normalizeBashJobPurpose as Ie,tailJobLog as Ae}from"../core/bash-jobs.js";import{MAX_BACKGROUND_BASH_LOG_BYTES as gt,BACKGROUND_BASH_LOG_TRUNCATION_MARKER as wt}from"../core/bash-job-supervisor.js";import{brokerApiUrl as Be,recordBackgroundedJob as Le,reportBrokerJob as xe,stopBrokerBashJob as Oe}from"../core/runtime/broker/daemon-ops.js";import{bashJobsUseLauncher as Te,launchBashJobSupervisor as Je}from"../core/runtime/broker/bash-job-launch.js";import{JobReporter as Re}from"../core/runtime/broker/job-reporter.js";import{bashCommandRefusal as $e}from"../core/bash-guard.js";import{readConfig as Me}from"../core/config.js";import{PREVIEW_RESULT_PATH_ENV as Ne,previewResultPath as Ce}from"../core/preview-result-path.js";import{Type as S}from"typebox";import{createBashToolDefinition as ne}from"@earendil-works/pi-coding-agent";const oe=200,De=5e3;function Pe(){return he()}o(Pe,"resolveValveMs");function Ue(e){return ve(e,ke())}o(Ue,"makeJobPaths");const k=new Set;let re=!1;function ie(){for(const e of[...k])try{ee(e),k.delete(e)}catch(n){process.stderr.write(`crtr: failed to background bash job ${e.jobId} during broker termination: ${n.message}
2
- `)}}o(ie,"backgroundLiveJobsForTermination");function Fe(){re||(re=!0,process.prependListener("SIGTERM",ie),process.platform!=="win32"&&process.prependListener("SIGHUP",ie))}o(Fe,"installTerminationHandoff");const Ge=64*1024;function C(e,n,i){let s;try{s=Z(e)}catch{return n}if(s.size<=n)return n;const c=pe(e,"r");try{for(;n<s.size;){const b=Math.min(Ge,s.size-n),m=Buffer.allocUnsafe(b),u=ge(c,m,0,b,n);if(u===0)break;i(m.subarray(0,u)),n+=u}return n}finally{me(c)}}o(C,"tailOnce");function E(e){try{Q(e,{recursive:!0,force:!0})}catch{}}o(E,"cleanupJobDir");function He(e){try{const n=Y(e,"utf8").trim(),i=Number(n);return Number.isFinite(i)?i:null}catch{return null}}o(He,"readExitCode");function Ve(e){try{if(Z(e).isDirectory())return{cwd:e}}catch{}const n=we();return{cwd:n,warning:`[working directory no longer exists: ${e}; running from ${n}]
3
- `}}o(Ve,"resolveExecutionCwd");function se(e,n,i=()=>null,s,c=()=>{}){return{exec:o(async(b,m,{onData:u,signal:f,timeout:p,env:I})=>new Promise((_,d)=>{const w=i();if(f?.aborted){d(new Error("aborted"));return}const A=$e(b,m);if(A!==null){d(new Error(A));return}const t=Ue(n);X(t.dir,{recursive:!0}),M(t.cmdSh,b),M(t.jobLog,""),M(t.jobRun,"");let l=0,g=!1,j,B,L,D=!1;const ae=Te(),P=N.now();let U=0,x=P;const F=o(()=>N.now()-P-U,"foregroundMs"),ce=Pe();let y;const ue=o(()=>{y&&clearInterval(y),f&&f.removeEventListener("abort",z),k.delete(t)},"teardown"),h=o(r=>{g||(g=!0,ue(),r())},"finish");let G=!1;function O(r=!1){if(g||G)return;G=!0,y&&clearInterval(y);const a=r?Date.now()+q():void 0;a!==void 0&&_e(t,a),Le(e,t.jobId,{command:Y(t.cmdSh,"utf8"),...w===null?{}:{purpose:w},...a===void 0?{}:{deadline_at_ms:a}}).then(()=>{try{Ee(t)}catch{}H(r,"")},$=>H(r,`
4
- [crtr could not record job ${t.jobId} (${$.message}); it will NOT message you when it exits. Watch its log.]`))}o(O,"finishBackground");function H(r,a){const $=te(F());let K="";if(r){const le=q();K=`It will be CANCELED in ${te(le)} unless you claim it: crtr node bash extend ${t.jobId} --for <duration> (or --keep to run to completion). `}const W=`
5
- [backgrounded as job ${t.jobId} after ${$} in the foreground${r?" (auto)":""}. `+K+(a===""?"It will interrupt you with a message when it exits. ":"")+`Watch: tail -f ${t.jobLog} ; stop: crtr node bash kill ${t.jobId}]`;u(Buffer.from(W+a)),c({jobId:t.jobId,logPath:t.jobLog,notice:W+a}),h(()=>_({exitCode:0}))}o(H,"handOff");function V(){l=C(t.jobLog,l,u);const r=He(t.jobExit);h(()=>_({exitCode:r})),E(t.dir)}o(V,"finishForeground");function de(r=!1){const a=ee(t);if(a==="backgrounded"||a==="already-backgrounded"){O(r);return}if(a==="finished"){V();return}h(()=>d(new Error(`bash job ${t.jobId} disappeared before it could be backgrounded`))),E(t.dir)}o(de,"requestBackground");function T(r){if(!(g||D)){if(l=C(t.jobLog,l,u),v(t.jobBg)){O();return}if(!v(t.jobExit)){if(j===void 0){L??=r;return}if(ae){D=!0,Oe(e,t.jobId).then(()=>{h(()=>d(r)),E(t.dir)},a=>h(()=>d(a)));return}j!==void 0&&B!==void 0&&je(j,B),h(()=>d(r)),E(t.dir)}}}o(T,"requestStop");function z(){T(new Error("aborted"))}o(z,"onAbort"),f&&f.addEventListener("abort",z,{once:!0});const J=Ve(m);J.warning&&u(Buffer.from(J.warning));let R=I??process.env;s!==void 0&&(X(ye(s),{recursive:!0}),Q(s,{force:!0}),R={...R,[Ne]:s}),Je(e,t,n,J.cwd,R).then(r=>{j=r.pgid,B=r.identity,k.add(t),L!==void 0&&T(L)},r=>{h(()=>d(r)),E(t.dir)}),y=setInterval(()=>{const r=N.now();if(r-x>De&&(U+=r-x-oe),x=r,l=C(t.jobLog,l,u),v(t.jobDone)){V();return}if(v(t.jobBg)){O();return}if(v(t.jobExit))return;const a=F();if(p!==void 0&&p>0){a>=p*1e3&&T(new Error(`timeout:${p}`));return}a>=ce&&de(!0)},oe)}),"exec")}}o(se,"createValveOperations");const ze=["One short clause naming what this step is FOR, in the words of the person you",'are working for \u2014 "Reading the Acme thread", not "Fetching emails" and never','"Running GMAIL_FETCH_EMAILS". A person reads this while the command runs; it',"is the only thing they see of this step. Under about eight words. Omit it for","steps that only touch your own scratch work."].join(" "),Ke=3;function We(e){const n=Ae(e.logPath,Ke),i=Math.max(0,Se(e.logPath)-n.length),s=n.length===0?"(no output yet)":n.join(`
1
+ var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{envBashAutoBgDeadlineMs as W,envBashValveMs as fe,envNodeId as me}from"../shared/env.js";import{closeSync as pe,existsSync as E,mkdirSync as q,openSync as he,readFileSync as X,readSync as be,rmSync as Y,statSync as Q,writeFileSync as J}from"node:fs";import{homedir as ge}from"node:os";import{dirname as we}from"node:path";import{performance as N}from"node:perf_hooks";import{backgroundBashJob as Z,bashJobPaths as ye,clearJobDeadlineFile as Ee,writeJobDeadlineFile as ve,cancelBashJobProcessTree as je,countJobLogLines as _e,formatBashElapsed as ee,newBashJobId as Se,normalizeBashJobPurpose as Ie,tailJobLog as ke}from"../core/bash-jobs.js";import{MAX_BACKGROUND_BASH_LOG_BYTES as pt,BACKGROUND_BASH_LOG_TRUNCATION_MARKER as ht}from"../core/bash-job-supervisor.js";import{brokerApiUrl as Ae,recordBackgroundedJob as Be,reportBrokerJob as Le}from"../core/runtime/broker/daemon-ops.js";import{launchBashJobSupervisor as xe}from"../core/runtime/broker/bash-job-launch.js";import{JobReporter as Oe}from"../core/runtime/broker/job-reporter.js";import{bashCommandRefusal as Te}from"../core/bash-guard.js";import{readConfig as Re}from"../core/config.js";import{PREVIEW_RESULT_PATH_ENV as $e,previewResultPath as Me}from"../core/preview-result-path.js";import{Type as _}from"typebox";import{createBashToolDefinition as te}from"@earendil-works/pi-coding-agent";const ne=200,Je=5e3;function Ne(){return fe()}o(Ne,"resolveValveMs");function Ce(e){return ye(e,Se())}o(Ce,"makeJobPaths");const S=new Set;let oe=!1;function re(){for(const e of[...S])try{Z(e),S.delete(e)}catch(t){process.stderr.write(`crtr: failed to background bash job ${e.jobId} during broker termination: ${t.message}
2
+ `)}}o(re,"backgroundLiveJobsForTermination");function De(){oe||(oe=!0,process.prependListener("SIGTERM",re),process.platform!=="win32"&&process.prependListener("SIGHUP",re))}o(De,"installTerminationHandoff");const Pe=64*1024;function C(e,t,i){let s;try{s=Q(e)}catch{return t}if(s.size<=t)return t;const c=he(e,"r");try{for(;t<s.size;){const m=Math.min(Pe,s.size-t),p=Buffer.allocUnsafe(m),d=be(c,p,0,m,t);if(d===0)break;i(p.subarray(0,d)),t+=d}return t}finally{pe(c)}}o(C,"tailOnce");function I(e){try{Y(e,{recursive:!0,force:!0})}catch{}}o(I,"cleanupJobDir");function Fe(e){try{const t=X(e,"utf8").trim(),i=Number(t);return Number.isFinite(i)?i:null}catch{return null}}o(Fe,"readExitCode");function Ue(e){try{if(Q(e).isDirectory())return{cwd:e}}catch{}const t=ge();return{cwd:t,warning:`[working directory no longer exists: ${e}; running from ${t}]
3
+ `}}o(Ue,"resolveExecutionCwd");function ie(e,t,i=()=>null,s,c=()=>{}){return{exec:o(async(m,p,{onData:d,signal:l,timeout:h,env:k})=>new Promise((v,f)=>{const g=i();if(l?.aborted){f(new Error("aborted"));return}const A=Te(m,p);if(A!==null){f(new Error(A));return}const n=Ce(t);q(n.dir,{recursive:!0}),J(n.cmdSh,m),J(n.jobLog,""),J(n.jobRun,"");let u=0,b=!1,j,B,L,se=!1;const D=N.now();let P=0,x=D;const F=o(()=>N.now()-D-P,"foregroundMs"),ae=Ne();let w;const ce=o(()=>{w&&clearInterval(w),l&&l.removeEventListener("abort",V),S.delete(n)},"teardown"),y=o(r=>{b||(b=!0,ce(),r())},"finish");let U=!1;function O(r=!1){if(b||U)return;U=!0,w&&clearInterval(w);const a=r?Date.now()+W():void 0;a!==void 0&&ve(n,a),Be(e,n.jobId,{command:X(n.cmdSh,"utf8"),...g===null?{}:{purpose:g},...a===void 0?{}:{deadline_at_ms:a}}).then(()=>{try{Ee(n)}catch{}G(r,"")},M=>G(r,`
4
+ [crtr could not record job ${n.jobId} (${M.message}); it will NOT message you when it exits. Watch its log.]`))}o(O,"finishBackground");function G(r,a){const M=ee(F());let z="";if(r){const ue=W();z=`It will be CANCELED in ${ee(ue)} unless you claim it: crtr node bash extend ${n.jobId} --for <duration> (or --keep to run to completion). `}const K=`
5
+ [backgrounded as job ${n.jobId} after ${M} in the foreground${r?" (auto)":""}. `+z+(a===""?"It will interrupt you with a message when it exits. ":"")+`Watch: tail -f ${n.jobLog} ; stop: crtr node bash kill ${n.jobId}]`;d(Buffer.from(K+a)),c({jobId:n.jobId,logPath:n.jobLog,notice:K+a}),y(()=>v({exitCode:0}))}o(G,"handOff");function H(){u=C(n.jobLog,u,d);const r=Fe(n.jobExit);y(()=>v({exitCode:r})),I(n.dir)}o(H,"finishForeground");function de(r=!1){const a=Z(n);if(a==="backgrounded"||a==="already-backgrounded"){O(r);return}if(a==="finished"){H();return}y(()=>f(new Error(`bash job ${n.jobId} disappeared before it could be backgrounded`))),I(n.dir)}o(de,"requestBackground");function T(r){if(!(b||se)){if(u=C(n.jobLog,u,d),E(n.jobBg)){O();return}if(!E(n.jobExit)){if(j===void 0){L??=r;return}j!==void 0&&B!==void 0&&je(j,B),y(()=>f(r)),I(n.dir)}}}o(T,"requestStop");function V(){T(new Error("aborted"))}o(V,"onAbort"),l&&l.addEventListener("abort",V,{once:!0});const R=Ue(p);R.warning&&d(Buffer.from(R.warning));let $=k??process.env;s!==void 0&&(q(we(s),{recursive:!0}),Y(s,{force:!0}),$={...$,[$e]:s}),xe(e,n,t,R.cwd,$).then(r=>{j=r.pgid,B=r.identity,S.add(n),L!==void 0&&T(L)},r=>{y(()=>f(r)),I(n.dir)}),w=setInterval(()=>{const r=N.now();if(r-x>Je&&(P+=r-x-ne),x=r,u=C(n.jobLog,u,d),E(n.jobDone)){H();return}if(E(n.jobBg)){O();return}if(E(n.jobExit))return;const a=F();if(h!==void 0&&h>0){a>=h*1e3&&T(new Error(`timeout:${h}`));return}a>=ae&&de(!0)},ne)}),"exec")}}o(ie,"createValveOperations");const Ge=["One short clause naming what this step is FOR, in the words of the person you",'are working for \u2014 "Reading the Acme thread", not "Fetching emails" and never','"Running GMAIL_FETCH_EMAILS". A person reads this while the command runs; it',"is the only thing they see of this step. Under about eight words. Omit it for","steps that only touch your own scratch work."].join(" "),He=3;function Ve(e){const t=ke(e.logPath,He),i=Math.max(0,_e(e.logPath)-t.length),s=t.length===0?"(no output yet)":t.join(`
6
6
  `),c=i===0?"":`
7
- [${i} earlier output line${i===1?"":"s"} are in the job log only]`;return{content:[{type:"text",text:`${s}${c}${e.notice}`}],details:void 0}}o(We,"handoffResult");function qe(e){return{...e,parameters:S.Object({purpose:S.Optional(S.String({description:ze})),...e.parameters.properties})}}o(qe,"withPurpose");const Xe=["A command that needs longer than one call \u2014 a test lane, a build, a soak \u2014 is started with","`crtr node bash run '<command>'`, which returns at once and wakes you with the exit code; the job is a canvas","object others can watch. Do not use `&`, `nohup`, `setsid`, or a cron that polls a log. A foreground command","past 5 minutes is moved to a job automatically; a `timeout` kills it and everything it started."].join(" ");function Ye(e){const{command:n,...i}=e.parameters.properties;return{...e,parameters:S.Object({command:{...n,description:`${n.description??""} ${Xe}`.trim()},...i})}}o(Ye,"withJobGuidance");function Qe(e,n,i,s){const c=Ye(ne(i,{operations:se(e,n)}));return{...s?qe(c):c,execute:o(async(u,f,p,I,_)=>{const d=s?Ie(f.purpose):null;let w=null;const t=await ne(i,{operations:se(e,n,()=>d,Ce(u),g=>{w=g})}).execute(u,f,p,I,_),l=w;return l===null?t:We(l)},"execute")}}o(Qe,"createValveToolDefinition");function Ze(e){const n=be();if(n===void 0||n.trim()==="")return;const i=process.env.CRTR_CONTEXT_DIR;i===void 0||i.trim()===""||(Fe(),Be()!==void 0&&new Re(i,(s,c)=>xe(n,s,c)).start(),e.on("session_start",(s,c)=>{e.registerTool(Qe(n,i,c.cwd,Me("user").bash_tool_purpose))}))}o(Ze,"default");export{wt as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,gt as MAX_BACKGROUND_BASH_LOG_BYTES,se as createValveOperations,Qe as createValveToolDefinition,Ze as default};
7
+ [${i} earlier output line${i===1?"":"s"} are in the job log only]`;return{content:[{type:"text",text:`${s}${c}${e.notice}`}],details:void 0}}o(Ve,"handoffResult");function ze(e){return{...e,parameters:_.Object({purpose:_.Optional(_.String({description:Ge})),...e.parameters.properties})}}o(ze,"withPurpose");const Ke=["A command that needs longer than one call \u2014 a test lane, a build, a soak \u2014 is started with","`crtr node bash run '<command>'`, which returns at once and wakes you with the exit code; the job is a canvas","object others can watch. Do not use `&`, `nohup`, `setsid`, or a cron that polls a log. A foreground command","past 5 minutes is moved to a job automatically; a `timeout` kills it and everything it started."].join(" ");function We(e){const{command:t,...i}=e.parameters.properties;return{...e,parameters:_.Object({command:{...t,description:`${t.description??""} ${Ke}`.trim()},...i})}}o(We,"withJobGuidance");function qe(e,t,i,s){const c=We(te(i,{operations:ie(e,t)}));return{...s?ze(c):c,execute:o(async(d,l,h,k,v)=>{const f=s?Ie(l.purpose):null;let g=null;const n=await te(i,{operations:ie(e,t,()=>f,Me(d),b=>{g=b})}).execute(d,l,h,k,v),u=g;return u===null?n:Ve(u)},"execute")}}o(qe,"createValveToolDefinition");function Xe(e){const t=me();if(t===void 0||t.trim()==="")return;const i=process.env.CRTR_CONTEXT_DIR;i===void 0||i.trim()===""||(De(),(Ae()!==void 0||process.platform==="linux")&&new Oe(i,(s,c)=>Le(t,s,c)).start(),e.on("session_start",(s,c)=>{e.registerTool(qe(t,i,c.cwd,Re("user").bash_tool_purpose))}))}o(Xe,"default");export{ht as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,pt as MAX_BACKGROUND_BASH_LOG_BYTES,ie as createValveOperations,qe as createValveToolDefinition,Xe as default};
@@ -1,2 +1,2 @@
1
- var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as b}from"../shared/env.js";import{CONTEXT_INTRO_CUSTOM_TYPE as a,formatCard as C}from"../shared/generated-context.js";import{brokerDelivery as f}from"../core/runtime/broker/daemon-ops.js";import{boundExtensionState as l}from"../core/runtime/broker/boot-state.js";import{takeCycleBoot as T}from"../core/runtime/broker/cycle-start.js";import{buildForkBearingsFromState as p}from"../core/runtime/broker-extension-render.js";import{acknowledgePersonaBaseline as _}from"../core/runtime/broker-persona-guidance.js";async function S(e){return(await f(e,{activity:"boot"})).content}s(S,"buildContextIntro");async function A(e){const t=await l(e);return p(t,t.situational_card??"")}s(A,"buildForkContextIntro");function y(e){const t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>typeof r?.text=="string").map(r=>r.text).join(`
2
- `):""}s(y,"entryText");function I(e){e.on("session_start",async(t,r)=>{const n=b();if(n===void 0||n.trim()==="")return;const g=t?.reason,i=await l(n);if(i.warm_spare||g==="new"&&i.node.parent===null)return;const c=r.sessionManager.getBranch().filter(o=>o.type==="custom_message"&&o.customType===a);if(c.some(o=>o.details?.nodeId===n||y(o).includes(n)))return;const d=T(n),u=d??await f(n,{activity:"boot",inherited:c.length>0}),x=u.inherited===!0?p(i,i.situational_card??""):u.content,m=C("bearings",{},x);if(e.sendMessage({customType:a,content:m,display:!0,details:{nodeId:n}}),!r.sessionManager.getBranch().some(o=>o.type==="custom_message"&&o.customType===a&&o.details?.nodeId===n&&y(o)===m))throw new Error(`Pi did not materialize the context baseline for ${n}`);d===void 0&&await _(i)})}s(I,"registerCanvasContextIntro");var j=I;export{a as CONTEXT_INTRO_CUSTOM_TYPE,S as buildContextIntro,A as buildForkContextIntro,j as default,I as registerCanvasContextIntro};
1
+ var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as T}from"../shared/env.js";import{CONTEXT_INTRO_CUSTOM_TYPE as a,formatCard as b}from"../shared/generated-context.js";import{expandHostPathTokens as C}from"../core/runtime/broker/host-path-tokens.js";import{brokerDelivery as f}from"../core/runtime/broker/daemon-ops.js";import{boundExtensionState as p}from"../core/runtime/broker/boot-state.js";import{takeCycleBoot as _}from"../core/runtime/broker/cycle-start.js";import{buildForkBearingsFromState as l}from"../core/runtime/broker-extension-render.js";import{acknowledgePersonaBaseline as h}from"../core/runtime/broker-persona-guidance.js";async function j(e){return(await f(e,{activity:"boot"})).content}s(j,"buildContextIntro");async function z(e){const t=await p(e);return l(t,t.situational_card??"")}s(z,"buildForkContextIntro");function y(e){const t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>typeof r?.text=="string").map(r=>r.text).join(`
2
+ `):""}s(y,"entryText");function I(e){e.on("session_start",async(t,r)=>{const o=T();if(o===void 0||o.trim()==="")return;const g=t?.reason,i=await p(o);if(i.warm_spare||g==="new"&&i.node.parent===null)return;const c=r.sessionManager.getBranch().filter(n=>n.type==="custom_message"&&n.customType===a);if(c.some(n=>n.details?.nodeId===o||y(n).includes(o)))return;const d=_(o),u=d??await f(o,{activity:"boot",inherited:c.length>0}),x=u.inherited===!0?l(i,i.situational_card??""):u.content,m=b("bearings",{},C(x));if(e.sendMessage({customType:a,content:m,display:!0,details:{nodeId:o}}),!r.sessionManager.getBranch().some(n=>n.type==="custom_message"&&n.customType===a&&n.details?.nodeId===o&&y(n)===m))throw new Error(`Pi did not materialize the context baseline for ${o}`);d===void 0&&await h(i)})}s(I,"registerCanvasContextIntro");var D=I;export{a as CONTEXT_INTRO_CUSTOM_TYPE,j as buildContextIntro,z as buildForkContextIntro,D as default,I as registerCanvasContextIntro};
@@ -1,2 +1,2 @@
1
- var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as me,brokerRunTurnBusy as pe,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ye}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ge=3e4,be=5*6e4,U="inbox daemon unreachable",B=16;let v,ve=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function we(){return{tickMs:V(),debounceMs:z()}}c(we,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&ue(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function _e(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}c(_e,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}c(b,"deliveryFields");function Ee(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ee,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function Ie(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
2
- `):""}c(Ie,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function ke(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(ke,"disposalReasonForShutdown");function xe(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}c(xe,"boundedRuntimeReason");class Se{static{c(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=G();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=c((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(a=>a.awaitingDequeue!==void 0))return;const n=C(Ie(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=$(i)?ke(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:xe(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=O();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const o of a)R(o,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=O().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),Y()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ge,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<be)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&ie(t).then(e=>e.fault?.op===U?N(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&pe())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||W()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return K(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=me();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(d,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,_e(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||W())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const a of e.handoffs)T(a.operationId,a,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ne(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ee(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Ce(r,t){v?.dispose("reload",!1);const e=new Se(r,t,++ve);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ye]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Ce,"installWatcher");function Fe(r){const t=Ce(r,we());return()=>t.dispose("shutdown",!1)}c(Fe,"registerCanvasInboxWatcher");var je=Fe;export{je as default,Fe as registerCanvasInboxWatcher};
1
+ var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{expandHostPathTokens as ue}from"../core/runtime/broker/host-path-tokens.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as me}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as pe,brokerRunTurnBusy as ye,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ge}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,be=3e4,ve=5*6e4,U="inbox daemon unreachable",B=16;let v,we=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function _e(){return{tickMs:V(),debounceMs:z()}}c(_e,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&me(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function Ee(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}c(Ee,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}c(b,"deliveryFields");function Ie(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ie,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function ke(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
2
+ `):""}c(ke,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function xe(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(xe,"disposalReasonForShutdown");function Se(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}c(Se,"boundedRuntimeReason");class Ce{static{c(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=G();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=c((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(a=>a.awaitingDequeue!==void 0))return;const n=C(ke(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=$(i)?xe(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:Se(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=O();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const o of a)R(o,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=O().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),Y()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(be,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ve)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&ie(t).then(e=>e.fault?.op===U?N(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&ye())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||W()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return K(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){return i=ue(i),this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=pe();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(d,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,Ee(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||W())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const a of e.handoffs)T(a.operationId,a,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ne(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ie(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Fe(r,t){v?.dispose("reload",!1);const e=new Ce(r,t,++we);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ge]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Fe,"installWatcher");function Me(r){const t=Fe(r,_e());return()=>t.dispose("shutdown",!1)}c(Me,"registerCanvasInboxWatcher");var Ve=Me;export{Ve as default,Me as registerCanvasInboxWatcher};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.790",
3
+ "version": "0.3.791",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.790",
161
- "@north-light/plugin": "0.3.790",
160
+ "@north-light/identity": "0.3.791",
161
+ "@north-light/plugin": "0.3.791",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.89';
15
+ export const CONTRACT_LEVEL = '1.90';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -106,19 +106,10 @@ export function scopesFilePath(nodeId) {
106
106
  export function contextDir(nodeId, grantee) {
107
107
  return join(nodeAgentDir(nodeId, grantee), 'context');
108
108
  }
109
- /** Replace the literal env-var tokens `$CRTR_CONTEXT_DIR` / `$CRTR_NODE_ID` in
110
- * agent-facing doc text with the node's real values, so a doc surfaced INTO a
111
- * node hands it a concrete absolute path instead of a shell-only string. The
112
- * env vars only expand in bash; an agent that pastes `$CRTR_CONTEXT_DIR/x.md`
113
- * into the (non-expanding) Write tool creates a literal `$CRTR_CONTEXT_DIR/`
114
- * dir under the project repo. The resolved absolute path works in both bash and
115
- * Write, so this substitution is strictly safer. Callers must only apply it
116
- * when they have a concrete node to render for (never on generic, node-less
117
- * output). Pure string work — no I/O. */
118
- export function interpolateNodePaths(text, nodeId, grantee) {
119
- return text
120
- .replaceAll('$CRTR_CONTEXT_DIR', contextDir(nodeId, grantee))
121
- .replaceAll('$CRTR_NODE_ID', nodeId);
109
+ /** Replace the literal token `$CRTR_NODE_ID` in agent-facing doc text with the node's id. `$CRTR_CONTEXT_DIR` stays a token: only the machine hosting the
110
+ * node's broker knows its path, and the broker expands it (`expandHostPathTokens`) before the text reaches the model. Pure string work — no I/O. */
111
+ export function interpolateNodePaths(text, nodeId) {
112
+ return text.replaceAll('$CRTR_NODE_ID', nodeId);
122
113
  }
123
114
  export function jobDir(nodeId) {
124
115
  return join(nodeRecordDir(nodeId), 'job');
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname } from 'node:path';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
3
  import { daemonClient } from './daemon-ops.js';
4
+ import { hostContextDir } from './host-path-tokens.js';
4
5
  /** Download every attachment of this node's run that is not already on the broker's disk (D98). The control plane puts
5
6
  * each fetched upload in the blob store and records it on the run; the files are written where the run's prompt names
6
7
  * them. Run before the broker hands the agent a prompt or mail. A failed download throws: the agent must not be told
@@ -8,7 +9,14 @@ import { daemonClient } from './daemon-ops.js';
8
9
  export async function fetchRunAttachments(nodeId, listed) {
9
10
  const client = daemonClient();
10
11
  const attachments = listed ?? (await client.listNodeAttachments(nodeId)).attachments;
11
- for (const file of attachments) {
12
+ if (attachments.length === 0)
13
+ return;
14
+ const contextDir = hostContextDir();
15
+ if (contextDir === undefined)
16
+ throw new Error(`cannot place attachments of node ${nodeId}: this broker has no CRTR_CONTEXT_DIR and no CRTR_NODE_ID/CRTR_GRANTEE to derive it from`);
17
+ const nodeDir = dirname(contextDir);
18
+ for (const listed of attachments) {
19
+ const file = { ...listed, path: hostPath(nodeDir, listed.path) };
12
20
  if (existsSync(file.path))
13
21
  continue;
14
22
  const bytes = await client.readNodeAttachment(nodeId, file.sha256);
@@ -18,3 +26,11 @@ export async function fetchRunAttachments(nodeId, listed) {
18
26
  renameSync(partial, file.path);
19
27
  }
20
28
  }
29
+ /** A node-relative row (`attachments/<name>`) is under this host's node folder; an absolute row from before paths were relative is re-rooted from its
30
+ * `…/apps/<app>/nodes/<id>/` prefix onto the same folder. */
31
+ function hostPath(nodeDir, path) {
32
+ if (!isAbsolute(path))
33
+ return join(nodeDir, path);
34
+ const rest = /\/apps\/[^/]+\/nodes\/[^/]+\/(.+)$/.exec(path);
35
+ return rest === null ? path : join(nodeDir, rest[1]);
36
+ }
@@ -50,11 +50,6 @@ export function clearBrokerPushedFinal(nodeId) {
50
50
  export function consumeBrokerPushedFinal(nodeId) {
51
51
  return daemonClient().nodePushedFinal(nodeId, { action: 'consume', expected_execution_id: brokerExecutionId() });
52
52
  }
53
- export function startBrokerBashJob(nodeId, request) {
54
- return daemonClient().request('POST', `/v1/nodes/${encodeURIComponent(nodeId)}/jobs/start`, {
55
- ...request, expected_execution_id: brokerExecutionId(),
56
- });
57
- }
58
53
  /** Record a command the valve just backgrounded as this node's job object. */
59
54
  export function recordBackgroundedJob(nodeId, jobId, request) {
60
55
  return daemonClient().recordBackgroundedJob(nodeId, jobId, request);
@@ -63,11 +58,6 @@ export function recordBackgroundedJob(nodeId, jobId, request) {
63
58
  export function reportBrokerJob(nodeId, jobId, request) {
64
59
  return daemonClient().reportBashJob(nodeId, jobId, { ...request, expected_execution_id: brokerExecutionId() });
65
60
  }
66
- export function stopBrokerBashJob(nodeId, jobId) {
67
- return daemonClient().request('DELETE', `/v1/nodes/${encodeURIComponent(nodeId)}/jobs/${encodeURIComponent(jobId)}?foreground=1`, {
68
- expected_execution_id: brokerExecutionId(),
69
- });
70
- }
71
61
  export function brokerExecutionId() {
72
62
  const id = envExecutionId();
73
63
  if (id === undefined || id === '')
@@ -0,0 +1,21 @@
1
+ import { dirname } from 'node:path';
2
+ import { contextDir } from '../../canvas/paths.js';
3
+ /** 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
4
+ * 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. */
5
+ export function expandHostPathTokens(text) {
6
+ if (!text.includes('$CRTR_'))
7
+ return text;
8
+ const context = hostContextDir();
9
+ if (context === undefined)
10
+ return text;
11
+ return text.replaceAll('$CRTR_CONTEXT_DIR', context).replaceAll('$CRTR_NODE_DIR', dirname(context));
12
+ }
13
+ /** The broker's own context dir: its env, else derived from its node id and app on this host's layout. */
14
+ export function hostContextDir() {
15
+ const set = process.env['CRTR_CONTEXT_DIR'];
16
+ if (set !== undefined && set !== '')
17
+ return set;
18
+ const node = process.env['CRTR_NODE_ID'];
19
+ const app = process.env['CRTR_GRANTEE'];
20
+ return node && app ? contextDir(node, app) : undefined;
21
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.790",
3
+ "version": "0.3.791",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.790",
3
+ "version": "0.3.791",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.790",
3
+ "version": "0.3.791",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.790",
31
- "@north-light/identity": "0.3.790"
30
+ "@north-light/api": "0.3.791",
31
+ "@north-light/identity": "0.3.791"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.790",
3
+ "version": "0.3.791",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.790",
9
+ "version": "0.3.791",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.790",
32
- "@north-light/plugin": "0.3.790",
31
+ "@north-light/identity": "0.3.791",
32
+ "@north-light/plugin": "0.3.791",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.790",
11905
+ "version": "0.3.791",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.790",
11910
+ "version": "0.3.791",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.790",
11915
+ "version": "0.3.791",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.790",
11923
+ "version": "0.3.791",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.790",
11927
- "@north-light/identity": "0.3.790"
11926
+ "@north-light/api": "0.3.791",
11927
+ "@north-light/identity": "0.3.791"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.790",
11932
+ "version": "0.3.791",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.790",
11936
- "@north-light/identity": "0.3.790",
11937
- "@north-light/plugin": "0.3.790",
11935
+ "@north-light/api": "0.3.791",
11936
+ "@north-light/identity": "0.3.791",
11937
+ "@north-light/plugin": "0.3.791",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -12,7 +12,7 @@ import { randomBytes } from 'node:crypto';
12
12
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
13
13
  import { tmpdir, uptime } from 'node:os';
14
14
  import { basename, dirname, join, resolve, sep } from 'node:path';
15
- import { fileURLToPath } from 'node:url';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
16
 
17
17
  export const EXIT_NO_BROKER = 3;
18
18
  const here = dirname(fileURLToPath(import.meta.url));
@@ -337,7 +337,9 @@ async function start(env) {
337
337
  const models = launch.models;
338
338
  if (models) writeFileSync(join(agentDir, 'models.json'), `${JSON.stringify(models, null, 2)}\n`);
339
339
  // The recipe's env names the control plane's homes (`/opt/crouter/runtime`, `/work/crtr`); the broker merges it into its own env, which would put them back in every tool the node runs. The sandbox's own homes win.
340
- writeFileSync(join(runDir, 'broker-launch.json'), JSON.stringify({ ...launch, argv, env: { ...launch.env, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime') } }));
340
+ const { hostLaunchEnv, sandboxContextDir } = await import(pathToFileURL(join(releaseDir, 'dist', 'core', 'runtime', 'runner', 'launch-env.js')).href);
341
+ const hostEnv = hostLaunchEnv(launch.env ?? {}, { contextDir: sandboxContextDir(bundle.node.app, nodeId, root), scopesFile: join(runDir, 'scopes.json') });
342
+ writeFileSync(join(runDir, 'broker-launch.json'), JSON.stringify({ ...launch, argv, env: { ...hostEnv, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime') } }));
341
343
  const settingsPath = join(agentDir, 'settings.json');
342
344
  const builtin = join(releaseDir, 'dist', 'builtin-pi-packages', 'pi-crtr-extensions');
343
345
  let settings = {};
@@ -353,7 +355,7 @@ async function start(env) {
353
355
  writeFileSync(settingsPath, `${JSON.stringify({ ...settings, packages })}\n`);
354
356
 
355
357
  // 5.9 the broker, with the token on fd 3 and not in its environment.
356
- const brokerEnv = { ...env, ...launch.env, HOME: home, PI_CODING_AGENT_DIR: agentDir, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime'),
358
+ const brokerEnv = { ...env, ...hostEnv, HOME: home, PI_CODING_AGENT_DIR: agentDir, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime'),
357
359
  CRTR_FRONT_DOOR: '1', CRTR_EXECUTION_ID: executionId, CRTR_API_URL: apiUrl, CRTR_FEEDBACK_ENDPOINT: `${apiUrl.replace(/\/$/, '')}/v1/feedback`, CRTR_NO_AUTO_INIT: '1',
358
360
  CRTR_PLUGINS_REVISION: String(bundle.plugins_revision), ...(environmentId ? { CRTR_ENVIRONMENT_ID: environmentId } : {}), ...(scopesFile ? { CRTR_SCOPES_FILE: scopesFile } : {}),
359
361
  PATH: `${join(releaseDir, 'bin')}:${env.PATH ?? '/usr/local/bin:/usr/bin:/bin'}` };