@north-light/cli 0.3.712 → 0.3.714

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 (113) hide show
  1. package/dist/clients/attach/input/controller.d.ts +8 -0
  2. package/dist/clients/attach/input/controller.js +3 -3
  3. package/dist/clients/attach/input/local-files.d.ts +18 -0
  4. package/dist/clients/attach/input/local-files.js +11 -0
  5. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/editor-frame.d.ts +2 -2
  8. package/dist/clients/attach/session/editor-frame.js +1 -1
  9. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  10. package/dist/clients/attach/session/input-wiring.js +1 -1
  11. package/dist/clients/attach/viewer.js +526 -517
  12. package/dist/commands/node/bash.js +1 -1
  13. package/dist/commands/node/inspect.js +5 -5
  14. package/dist/core/bash-guard.d.ts +10 -0
  15. package/dist/core/bash-guard.js +4 -4
  16. package/dist/core/broker-client/client.d.ts +2 -2
  17. package/dist/core/broker-client/client.js +1 -1
  18. package/dist/core/canvas/canvas.js +1 -1
  19. package/dist/core/canvas/deliveries.js +10 -10
  20. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  21. package/dist/core/canvas/schema-version.d.ts +1 -1
  22. package/dist/core/canvas/schema-version.js +1 -1
  23. package/dist/core/canvas/types.d.ts +1 -0
  24. package/dist/core/checkout-identities.js +1 -1
  25. package/dist/core/conversation-store/row-store.js +1 -1
  26. package/dist/core/graph/documents.d.ts +5 -5
  27. package/dist/core/graph/documents.js +9 -9
  28. package/dist/core/graph/kinds/custom.js +2 -2
  29. package/dist/core/graph/kinds/document.js +4 -4
  30. package/dist/core/graph/kinds/environment.js +2 -2
  31. package/dist/core/graph/kinds/job.js +2 -2
  32. package/dist/core/graph/kinds/kind.d.ts +9 -1
  33. package/dist/core/graph/kinds/live-read.d.ts +4 -2
  34. package/dist/core/graph/kinds/live-read.js +1 -1
  35. package/dist/core/graph/kinds/node.js +5 -5
  36. package/dist/core/graph/kinds/owner.js +2 -2
  37. package/dist/core/import/load/bind.d.ts +8 -0
  38. package/dist/core/import/load/bind.js +15 -15
  39. package/dist/core/import/load/prepare.d.ts +8 -1
  40. package/dist/core/import/load/prepare.js +9 -7
  41. package/dist/core/import/load/run.js +2 -2
  42. package/dist/core/llm/run.d.ts +1 -1
  43. package/dist/core/pool-credential-store.d.ts +5 -5
  44. package/dist/core/runtime/bearings-render.d.ts +3 -0
  45. package/dist/core/runtime/bearings-render.js +7 -7
  46. package/dist/core/runtime/bearings.js +5 -5
  47. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  48. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  49. package/dist/core/runtime/broker/frame-read.d.ts +5 -1
  50. package/dist/core/runtime/broker/frame-read.js +1 -1
  51. package/dist/core/runtime/broker-protocol.d.ts +37 -2
  52. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  53. package/dist/core/runtime/broker-wedge.js +2 -2
  54. package/dist/core/subscription-state.d.ts +3 -3
  55. package/dist/core/subscription-state.js +1 -1
  56. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  57. package/dist/daemon/api/handlers/llm.js +3 -3
  58. package/dist/daemon/api/handlers/objects.js +3 -3
  59. package/dist/daemon/api/handlers/reviews.js +1 -1
  60. package/dist/daemon/api/map.d.ts +6 -0
  61. package/dist/daemon/api/map.js +1 -1
  62. package/dist/daemon/fleet.d.ts +1 -12
  63. package/dist/daemon/fleet.js +2 -2
  64. package/dist/daemon/machine-daemon.js +1 -1
  65. package/dist/daemon/machine-link/holder.js +1 -1
  66. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  67. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  68. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  69. package/docs/ci-runner.md +4 -4
  70. package/package.json +3 -3
  71. package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
  72. package/packages/crouter-api/dist/clients/attach/input/local-files.js +113 -0
  73. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  74. package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
  75. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  76. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  77. package/packages/crouter-api/dist/commands/node/bash.js +2 -2
  78. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  79. package/packages/crouter-api/dist/core/bash-guard.js +1 -1
  80. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  81. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  82. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  83. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  84. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  85. package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
  86. package/packages/crouter-api/dist/core/graph/documents.js +12 -24
  87. package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
  88. package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
  89. package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
  90. package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
  91. package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
  92. package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
  93. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  94. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  95. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  96. package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
  97. package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
  98. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  99. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  100. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -6
  101. package/packages/crouter-api/dist/daemon/api/map.js +1 -1
  102. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  103. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  104. package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
  105. package/packages/crouter-api/package.json +1 -1
  106. package/packages/crouter-identity/package.json +1 -1
  107. package/packages/crouter-plugin/package.json +3 -3
  108. package/runtime.lock.json +14 -14
  109. package/scripts/install-runtime.mjs +3 -2
  110. package/scripts/self-update.mjs +5 -1
  111. package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
  112. /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
  113. /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
@@ -1,3 +1,3 @@
1
- var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as ae}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as re,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await re(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,a=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(a)||t<a?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,a,r){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return a?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":r?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,a)=>{if(process.platform==="linux"&&J(Q)){if(a!=="SIGTERM"&&a!=="SIGKILL")throw new Error(`unsupported launcher signal ${a}`);return X({operation:"stop",pid:t,signal:a}).then(()=>{})}process.kill(t,a)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const a=He();for(const r of await ie())t.held.has(r)||await D.fresh(async()=>{try{await this.handleFatalFault(r)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(r)?{node_id:r}:{fields:{affected_node_id:r}},error:n})}});for(const r of t.rows){const n=r.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||r.status!=="active"&&r.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(r,s,t.fleet,e),await this.handleWedgeDetection(r,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(r,d,e),await this.handleRemoteWedge(r,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,a)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const r of await Pe())await t.fleet.has(r)||await T(r);await ke(e)}async parkResetCondition(e,t,a,r){if(t.pi_session_id==null||t.pi_pid!==a||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,r)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,a,r,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,a,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,r);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,r);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,r);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,r);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,r)))}}async requestParkSummary(e,t){try{const a=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:a}})}catch(a){if(await T(e)===void 0)return;if(a instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:a})}}async warnOverCapInTmux(e,t,a){const r=Date.now();if(r-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=r;const{warning:n,automaticReviveCap:s}=t,d=a.stalled+a.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:a.stalled,frozen_waiting_on_mail:a.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${a.stalled} stalled, ${a.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
2
- `).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const a=await he(e.runner).stop(e,{reason:t});return a.confirmed?await me(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:a.error}),a}async handleRemoteYieldStall(e,t,a){const r=e.node_id;if(e.intent!=="refresh"||await b(e)!==null){await h(r,"stall_noticed_at");return}const n=await A(r,"stall_noticed_at");if(n===void 0){await I(r,"stall_noticed_at",a);return}q(!0,e.intent,!1,a-n)==="kill"&&(await N(r))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(r)?{node_id:r}:{},fields:{...c(r)?{}:{affected_node_id:r},execution_id:t.executionId,elapsed_ms:a-n,grace_ms:U}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,a){const r=e.node_id,n=await b(e);if(n===null){await h(r,"wedge_noticed_at");return}const s=a-n;if(s<O)return;const d=await S(r);if(d===null||(await N(r))?.executionId!==t.executionId||await b(d)!==n||await A(r,"wedge_noticed_at")===n)return;await I(r,"wedge_noticed_at",n);const l=Math.round(s/6e4);await K(r,{quietForMs:s,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${$(d)} (${r}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${l}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,a,r){const n=e.node_id,s=V(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"||await b(e)!==null||s===null){await h(n,"stall_noticed_at"),s!==null&&this.yieldTermedAt.delete(s);return}const d=await A(n,"stall_noticed_at");if(d===void 0){await I(n,"stall_noticed_at",r);return}const l={since:d,termedAt:this.yieldTermedAt.get(s)};if(q(!0,e.intent,!1,r-l.since)!=="kill")return;const o=await S(n);if(!(a.get(n)!==t||o?.pi_pid!==t.pid||o.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(l.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(s,r),l.termedAt=r,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:r-l.since,grace_ms:U}})}else r-l.termedAt>=G&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:r-l.termedAt,grace_ms:G,stall_elapsed_ms:r-l.since}})}async signalYieldStall(e,t,a){try{return await this.signal(t,a),!0}catch(r){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:r,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:a}}),!1}}async handleWedgeDetection(e,t,a,r){const n=e.node_id,s=V(t.pid,e.pi_pid_identity),d=await b(e);if(d===null||s===null){await h(n,"wedge_noticed_at");return}const l=r-d,o=l>=O?await this.sampleTree(t.pid):null,p=await S(n),u=p===null?null:await b(p);if(a.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==d)return;const w=o?.cpuPercent??null,k=o?.hasDescendants??null;if(Ge({busy:!0,quietForMs:l,cpuPercent:w,hasDescendants:k})!=="wedged"||await A(n,"wedge_noticed_at")===d)return;await I(n,"wedge_noticed_at",d);const v=$(p),E=Math.round((l??O)/6e4),g=k??!0,y=!g&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let M=!1,m=!1;if(!g&&y===null){M=!0;try{await this.signal(t.pid,"SIGTERM"),m=!0}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}})}}const P=Ke(`${v} (${n})`,E,g,y!==null,m);await K(n,{quietForMs:l,cpuPercent:w,hasDescendants:g,kickAttempted:M,kicked:m,kickSuppressionReason:y,pid:t.pid,label:P})}async handleFatalFault(e,t=!0){const a=await L(e);if(a===null||a.retry.disposition!=="fatal"||a.link!=="pi\u2192provider"||a.notifiedSince===a.since)return;const r=await S(e),n=await Y(e),s=r!==null?$(r):e,d=a.kind==="auth",l=(a.message.split(`
3
- `)[0]??"").slice(0,200),o=a.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(o.ratelimit===void 0?"":` Rate limit: ${o.ratelimit.scope??"account"}${o.ratelimit.claim===void 0?"":` (${o.ratelimit.claim})`}${o.ratelimit.model===void 0?"":` on ${o.ratelimit.model}`}.`),u=a.kind==="context-overflow",w=Ve(r,typeof o?.code=="string"?o.code:void 0),k=u||w,v=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${l}`:`got a non-retryable ${a.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(d?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${l}.${p}`,E=u?"failed":"hit a fatal provider fault",g=new Set((await ne(e)).map(m=>m.node_id)),y=await fe(await x(),await ue(await x(),e)),M=[{relation:"Child",recipients:y.filter(m=>g.has(m))},{relation:"Watched node",recipients:y.filter(m=>!g.has(m))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:a.kind,link:a.link,terminal_overflow:u,terminal_provider_fault:w}}),await ce(async()=>{for(const{relation:m,recipients:P}of M)P.length!==0&&await W(e,"notice.crash",`${m} ${E} \u2014 ${s} (${e}) ${v}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:a.kind,message:l,...o===void 0?{}:{provider_error:o}},"normal",null,P);await oe(a.faultId),t&&k&&await ae(e,"crash",{reason:u?"context_overflow":o?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a.message,fault_kind:a.kind,error_class:de(a).class,...typeof o?.code=="string"?{provider_code:o.code}:{},...o?.payment===void 0?{}:{payment:o.payment}}}})}),t&&k&&this.teardownBroker(e,n).then(m=>{m.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m.error??new Error("Broker teardown not confirmed")})},m=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m}))}}export{Nt as BrokerSupervisionReconciler,H as parkSummaryGraceMsForDaemon,K as reportWedge,Ve as settlesOnFatalProviderFault,He as unattendedParkMsForDaemon,Ke as wedgeLabel};
1
+ var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as re}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as ae,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await ae(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,r,a){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return r?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":a?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=He();for(const a of await ie())t.held.has(a)||await D.fresh(async()=>{try{await this.handleFatalFault(a)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(a)?{node_id:a}:{fields:{affected_node_id:a}},error:n})}});for(const a of t.rows){const n=a.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||a.status!=="active"&&a.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(a,s,t.fleet,e),await this.handleWedgeDetection(a,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(a,d,e),await this.handleRemoteWedge(a,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,r)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const a of await Pe())await t.fleet.has(a)||await T(a);await ke(e)}async parkResetCondition(e,t,r,a){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,a)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,r,a,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,r,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,a);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,a);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,a);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,a);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,a)))}}async requestParkSummary(e,t){try{const r=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await T(e)===void 0)return;if(r instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const a=Date.now();if(a-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=a;const{warning:n,automaticReviveCap:s}=t,d=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
2
+ `).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const r=await he(e.runner).stop(e,{reason:t});return r.confirmed?await me(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:r.error}),r}async handleRemoteYieldStall(e,t,r){const a=e.node_id;if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null){await h(a,"stall_noticed_at");return}const n=await A(a,"stall_noticed_at");if(n===void 0){await I(a,"stall_noticed_at",r);return}q(!0,!1,r-n)==="kill"&&(await N(a))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(a)?{node_id:a}:{},fields:{...c(a)?{}:{affected_node_id:a},execution_id:t.executionId,elapsed_ms:r-n,grace_ms:U}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,r){const a=e.node_id,n=await b(e);if(n===null){await h(a,"wedge_noticed_at");return}const s=r-n;if(s<O)return;const d=await S(a);if(d===null||(await N(a))?.executionId!==t.executionId||await b(d)!==n||await A(a,"wedge_noticed_at")===n)return;await I(a,"wedge_noticed_at",n);const l=Math.round(s/6e4);await K(a,{quietForMs:s,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${$(d)} (${a}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${l}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null||s===null){await h(n,"stall_noticed_at"),s!==null&&this.yieldTermedAt.delete(s);return}const d=await A(n,"stall_noticed_at");if(d===void 0){await I(n,"stall_noticed_at",a);return}const l={since:d,termedAt:this.yieldTermedAt.get(s)};if(q(!0,!1,a-l.since)!=="kill")return;const o=await S(n);if(!(r.get(n)!==t||o?.pi_pid!==t.pid||o.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(l.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(s,a),l.termedAt=a,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.since,grace_ms:U}})}else a-l.termedAt>=G&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.termedAt,grace_ms:G,stall_elapsed_ms:a-l.since}})}async signalYieldStall(e,t,r){try{return await this.signal(t,r),!0}catch(a){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:a,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:r}}),!1}}async handleWedgeDetection(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity),d=await b(e);if(d===null||s===null){await h(n,"wedge_noticed_at");return}const l=a-d,o=l>=O?await this.sampleTree(t.pid):null,p=await S(n),u=p===null?null:await b(p);if(r.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==d)return;const w=o?.cpuPercent??null,k=o?.hasDescendants??null;if(Ge({busy:!0,quietForMs:l,cpuPercent:w,hasDescendants:k})!=="wedged"||await A(n,"wedge_noticed_at")===d)return;await I(n,"wedge_noticed_at",d);const v=$(p),E=Math.round((l??O)/6e4),g=k??!0,y=!g&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let M=!1,m=!1;if(!g&&y===null){M=!0;try{await this.signal(t.pid,"SIGTERM"),m=!0}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}})}}const P=Ke(`${v} (${n})`,E,g,y!==null,m);await K(n,{quietForMs:l,cpuPercent:w,hasDescendants:g,kickAttempted:M,kicked:m,kickSuppressionReason:y,pid:t.pid,label:P})}async handleFatalFault(e,t=!0){const r=await L(e);if(r===null||r.retry.disposition!=="fatal"||r.link!=="pi\u2192provider"||r.notifiedSince===r.since)return;const a=await S(e),n=await Y(e),s=a!==null?$(a):e,d=r.kind==="auth",l=(r.message.split(`
3
+ `)[0]??"").slice(0,200),o=r.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(o.ratelimit===void 0?"":` Rate limit: ${o.ratelimit.scope??"account"}${o.ratelimit.claim===void 0?"":` (${o.ratelimit.claim})`}${o.ratelimit.model===void 0?"":` on ${o.ratelimit.model}`}.`),u=r.kind==="context-overflow",w=Ve(a,typeof o?.code=="string"?o.code:void 0),k=u||w,v=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${l}`:`got a non-retryable ${r.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(d?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${l}.${p}`,E=u?"failed":"hit a fatal provider fault",g=new Set((await ne(e)).map(m=>m.node_id)),y=await fe(await x(),await ue(await x(),e)),M=[{relation:"Child",recipients:y.filter(m=>g.has(m))},{relation:"Watched node",recipients:y.filter(m=>!g.has(m))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:r.kind,link:r.link,terminal_overflow:u,terminal_provider_fault:w}}),await ce(async()=>{for(const{relation:m,recipients:P}of M)P.length!==0&&await W(e,"notice.crash",`${m} ${E} \u2014 ${s} (${e}) ${v}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:r.kind,message:l,...o===void 0?{}:{provider_error:o}},"normal",null,P);await oe(r.faultId),t&&k&&await re(e,"crash",{reason:u?"context_overflow":o?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:r.message,fault_kind:r.kind,error_class:de(r).class,...typeof o?.code=="string"?{provider_code:o.code}:{},...o?.payment===void 0?{}:{payment:o.payment}}}})}),t&&k&&this.teardownBroker(e,n).then(m=>{m.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m.error??new Error("Broker teardown not confirmed")})},m=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m}))}}export{Nt as BrokerSupervisionReconciler,H as parkSummaryGraceMsForDaemon,K as reportWedge,Ve as settlesOnFatalProviderFault,He as unattendedParkMsForDaemon,Ke as wedgeLabel};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t!==null&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,i){await this.pass(t,{rows:[e],fleet:i})}async pass(t,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,i))}catch(a){const l=n.node_id;E({level:a instanceof R?"warn":"error",event:a instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(l)?{node_id:l}:{fields:{affected_node_id:l}},error:a})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:i})}async classifyRow(t,e,i,n){const a=e.node_id;if(X(e)){if(H(e,await i.fleet.has(a)))return;if(S(e)&&!await i.fleet.has(a)&&!f(e.profile_id)&&!await I(a)&&!k(e,t)&&await m(a)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(a);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(a):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(a)){const r=await p(a);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(a))try{if(await Q(r)==="lost")return}catch(o){if(o instanceof x)return;throw o}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(a)){f(e.profile_id)?await i.fleet.interruptForProfilePause(a):await this.thawMark(e);return}}if(await K(a,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(a);return}if(await I(a))return;const l=e.pi_pid==null?await v(a):null,u=l!==null&&D(l),h=l!==null&&!u&&M(l),_=e.pi_pid!=null?await b(a):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(a)){const r=_??l;r!==null&&await P(r.executionId,{reason:"observed-dead"});const o=await p(a);if(o!==null&&o.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await m(a)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(a)||Z(e,t,await v(a)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:a}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await z(a),(await A(a))?.interrupted===!0,await U(a));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(a),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
1
+ var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as c}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as p}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const a=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return a>0&&t-a<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await c(s);return t?.runner==="process"&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,a){await this.pass(t,{rows:[e],fleet:a})}async pass(t,e){const a=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,a))}catch(i){const o=n.node_id;E({level:i instanceof R?"warn":"error",event:i instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(o)?{node_id:o}:{fields:{affected_node_id:o}},error:i})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:a})}async classifyRow(t,e,a,n){const i=e.node_id;if(X(e)){if(H(e,await a.fleet.has(i)))return;if(S(e)&&!await a.fleet.has(i)&&!f(e.profile_id)&&!await I(i)&&!k(e,t)&&await p(i)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(i);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(i):n.push({row:e,enact:"thaw"}));return}if(await a.fleet.has(i)){const r=await c(i);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await p(i))try{if(await Q(r)==="lost")return}catch(l){if(l instanceof x)return;throw l}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await a.fleet.has(i)){f(e.profile_id)?await a.fleet.interruptForProfilePause(i):await this.thawMark(e);return}}if(await K(i,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(i);return}if(await I(i))return;const o=e.pi_pid==null?await v(i):null,u=o!==null&&D(o),m=o!==null&&!u&&M(o),h=e.pi_pid!=null?await b(i):null,_=u||m||h!==null;if(_&&!await a.fleet.hasProfilePauseInterruption(i)){const r=h??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const l=await c(i);if(l!==null&&l.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await p(i)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!m){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await a.fleet.isClaimed(i)||Z(e,t,await v(i)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:i}),n.push({row:e,enact:"thaw"});return}if(!_)return;const y=O(await z(i),(await A(i))?.interrupted===!0,await U(i));if(y==="respawn-fresh"||y==="respawn-resume"){n.push({row:e,enact:"policy"});return}await a.fleet.applyDeadRowPolicy(i),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
@@ -1,2 +1,2 @@
1
- var J=Object.defineProperty;var l=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as $,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as L}from"../shared/env.js";import{coalesceBrokerInbox as V,entryCards as Q}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as O,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as P}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as D}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as g}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as x}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as _,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const E=64,U=16;let v,ce=0;class q extends Error{static{l(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:z(),debounceMs:j()}}l(me,"resolveCadence");function T(){const r=G();return r===void 0||r.trim()===""?void 0:r}l(T,"currentNodeId");function B(){const r=X();return r!==void 0&&r!==""&&fe(r)}l(B,"profilePaused");function S(r){try{return oe(r)}catch{return{class:"unknown"}}}l(S,"safeErrorClass");function w(r){try{D(r)}catch{}}l(w,"emitBestEffort");function I(r){try{g.fresh(t=>{w({...r,operation_id:t})})}catch{}}l(I,"emitFreshBestEffort");function F(r,t){try{g.run(r,()=>{w({...t,operation_id:r})})}catch{}}l(F,"emitStoredBestEffort");function pe(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}}))}}l(pe,"deliveryOrigin");function k(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-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}l(k,"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}}}l(b,"deliveryFields");function ye(r){F(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}l(ye,"emitDeliveryCompleted");function M(r,t,e,i){F(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:e,...b(t)}})}l(M,"emitDeliveryFailure");function R(r,t){F(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}l(R,"emitDeliveryAbandoned");function ge(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
- `):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(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}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();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=l((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(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();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=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(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=P();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=T();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 d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...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 a of d)R(a,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=P().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"),L()),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)}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&&he())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(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(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(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({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 K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}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(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||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))&&_()?.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=_()?.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))&&_()?.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(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}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 O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}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 V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){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 a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,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(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.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 o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.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>E)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||B())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>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.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=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}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 Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return D({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 Z(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(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(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=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}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 _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
1
+ var W=Object.defineProperty;var h=(r,t)=>W(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as J,envNodeId as $,envProfileId as G,envWatcherDebounceMs as X,envWatcherTickMs as j,envWatcherBackstopMs as z}from"../shared/env.js";import{coalesceBrokerInbox as L,entryCards as V}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as Q,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as k}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as C}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as D,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as w,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const _=64,O=16;let b,ce=0;class H extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:j(),debounceMs:X()}}h(me,"resolveCadence");function x(){const r=$();return r===void 0||r.trim()===""?void 0:r}h(x,"currentNodeId");function U(){const r=G();return r!==void 0&&r!==""&&fe(r)}h(U,"profilePaused");function T(r){try{return oe(r)}catch{return{class:"unknown"}}}h(T,"safeErrorClass");function v(r){try{P(r)}catch{}}h(v,"emitBestEffort");function E(r){try{y.fresh(t=>{v({...r,operation_id:t})})}catch{}}h(E,"emitFreshBestEffort");function S(r,t){try{y.run(r,()=>{v({...t,operation_id:r})})}catch{}}h(S,"emitStoredBestEffort");function pe(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}}))}}h(pe,"deliveryOrigin");function I(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-O;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,O),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(I,"deliveryFacts");function g(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}}}h(g,"deliveryFields");function ye(r){S(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:g(r)})}h(ye,"emitDeliveryCompleted");function F(r,t,e,i){S(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:e,...g(t)}})}h(F,"emitDeliveryFailure");function M(r,t){S(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...g(r)}})}h(M,"emitDeliveryAbandoned");function ge(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
+ `):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(be,"disposalReasonForShutdown");function ve(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}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();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=h((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(d=>d.awaitingDequeue!==void 0))return;const n=k(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=x();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=B(i)?be(i):"reload";B(i)||E({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(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=N();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=x();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 d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...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()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.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=N().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"),z()),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)}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&&he())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 H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(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 H)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("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 K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}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(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||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))&&w()?.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=w()?.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))&&w()?.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(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}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 Q(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}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(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}sendVisible(t,e,i,n,s,d){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 a of e)this.pi.sendMessage({customType:C,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.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 o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.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 f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.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 d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.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>_)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||U())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>_)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.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=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&M(a,this.disposalReason);return}this.pendingHandoffs.push(a)}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 Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(l=>l.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)F(d.operationId,d,"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 Z(t,s),D()?.("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(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(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=ne(),d=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);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 _e(r,t){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
package/docs/ci-runner.md CHANGED
@@ -36,7 +36,7 @@ gh variable set CRTR_CI_RUNNER --body self-hosted -R Northlight-Systems/crouter
36
36
  gh variable delete CRTR_CI_RUNNER -R Northlight-Systems/crouter # fall back to macos-latest
37
37
  ```
38
38
 
39
- It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job; it runs, in sequence, each lane that has a selected laptop-only file.
39
+ It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job per lane that has a selected laptop-only file (`macos unit`, `macos integration`, `macos seam`), plus `macos build-output` (the macOS concurrent-build test) only when the diff reaches the build (`scripts/build*`, `atomic-swap.c`, `pack-minify.mjs`, `runtime-lock.mjs`, `ensure-native-linux.mjs`, the patch and `check-*` scripts the build runs, `package.json`, the lockfile, `runtime.lock.json`, package manifests, tsconfigs, `test.yml`; the selector's `macos_build_output` output) or when there is no release tag to diff against; they run in parallel. Each macOS lane runs only the tests tagged `laptopOnly`, not whole files (a preload, `scripts/laptop-only-filter.mjs`, skips the rest), and fails if it ran none.
40
40
 
41
41
  ### Routing: minis first, hosted when none is free
42
42
 
@@ -83,7 +83,7 @@ Installing and upgrading: get a registration token (`gh api -X POST repos/Northl
83
83
 
84
84
  ## No double run on `main`
85
85
 
86
- `publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `checks` and every `linux` shard pass and every `macos` job passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
86
+ `publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `build`, `checks` and every `linux` shard pass and every `macos` job (including `macos build-output`) passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
87
87
 
88
88
  - Rebase-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
89
89
  - A direct push to `main`, or a merge after `main` moved (a different tree from the one the PR run tested) → no artifact → the full suite runs exactly as before. A release commit (`chore: release …`, pushed by Publish itself) changes the tree, so a PR not updated since before the latest release runs the suite once on merge; update the branch to avoid it.
@@ -116,8 +116,8 @@ The hourly `17 * * * *` schedule and the `promote`, `api_ref`, `env_docker_ref`
116
116
  - Selected tests run on every push with no label. Add `full-ci` to force the whole suite (`gh pr edit <n> --add-label full-ci`). Labels other than `full-ci` start nothing and cancel nothing.
117
117
  - On a pull request each matrix (`linux`; `macos` never runs there) is `fail-fast`: the first failing job cancels that matrix's other jobs, the matrix result is `failure`, and `full suite` still runs and is red. On main, merge queue and dispatch runs every job finishes. A Linux failure does not cancel the macOS matrix.
118
118
  - `record tested tree` runs only in mode `full`, so a partial run never lets Publish skip the suite.
119
- - The `full suite` job is the single result to require. It fails if `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
120
- - `checks` builds once on ubuntu and uploads the JS output; the `linux` jobs unpack it and compile the Linux native addon in the container (the build is glibc, the image musl), and the `macos` jobs unpack it as is.
119
+ - The `full suite` job is the single result to require. It fails if `build`, `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
120
+ - `build` builds once on ubuntu and uploads the JS output; `checks` (typecheck of examples, contract check, script tests, the concurrent-build test) runs beside the lanes on that build, and the lanes wait only for `build`. The `linux` jobs unpack it and compile the Linux native addon in the container (the build is glibc, the image musl), and the `macos` jobs unpack it as is.
121
121
 
122
122
  ## The selector: `scripts/ci-select.mjs`
123
123
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.712",
3
+ "version": "0.3.714",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.712",
162
- "@north-light/plugin": "0.3.712",
161
+ "@north-light/identity": "0.3.714",
162
+ "@north-light/plugin": "0.3.714",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -12,6 +12,7 @@ import { dispatchSlashCommand, isSlashCommand } from '../slash/dispatch.js';
12
12
  import { viewerOperationForFrame } from './capabilities.js';
13
13
  import { readClipboardImage, writeClipboardImageToFile } from './clipboard-image.js';
14
14
  import { InputOverlayOwner } from './overlay-owner.js';
15
+ import { attachLocalFiles, hasLocalPaths } from './local-files.js';
15
16
  import { announceFallbackEditor, NO_EDITOR_MESSAGE, resolveEditor } from '../../../core/editor-resolver.js';
16
17
  const DOUBLE_ESCAPE_MS = 500;
17
18
  const MAX_FRAME_BYTES = BROKER_READ_CAPS.maxLineBytes - 4 * 1024 * 1024;
@@ -257,26 +258,56 @@ export class InputController {
257
258
  if (delivery !== 'steer' && delivery !== 'prompt')
258
259
  return;
259
260
  const expanded = this.expandImagePlaceholders(classification.kind === 'slash' ? text : classification.text);
260
- if (!this.emitDrive(delivery === 'steer' ? { type: 'steer', text: expanded } : { type: 'prompt', text: expanded }))
261
+ const sent = () => {
262
+ this.recordCompletionUse(text);
263
+ this.editor.addToHistory(classification.trimmed);
264
+ this.clearPastedImages();
265
+ };
266
+ const deliver = (final) => {
267
+ if (!this.emitDrive(delivery === 'steer' ? { type: 'steer', text: final } : { type: 'prompt', text: final }))
268
+ return false;
269
+ if (delivery === 'prompt')
270
+ this.hooks.onMessageSent?.(final, true);
271
+ this.hooks.onPromptSent?.();
272
+ return true;
273
+ };
274
+ this.sendMessage(expanded, text, classification.kind !== 'slash', sent, deliver);
275
+ }
276
+ /** Send one message through `deliver`, with `sent` run and the editor cleared
277
+ * exactly once it is accepted. A message naming files on this machine (when
278
+ * `files` allows it and a broker can take them) clears the editor first, sends
279
+ * each file to the node, then delivers the rewritten text; a refused delivery
280
+ * puts the typed text back. */
281
+ sendMessage(expanded, typed, files, sent, deliver) {
282
+ const request = this.hooks.onRequest;
283
+ if (!files || request === undefined || !hasLocalPaths(expanded)) {
284
+ if (!deliver(expanded))
285
+ return;
286
+ sent();
287
+ this.editor.setText('');
261
288
  return;
262
- this.recordCompletionUse(text);
263
- this.editor.addToHistory(classification.trimmed);
289
+ }
290
+ sent();
264
291
  this.editor.setText('');
265
- this.clearPastedImages();
266
- if (delivery === 'prompt')
267
- this.hooks.onMessageSent?.(expanded, true);
268
- this.hooks.onPromptSent?.();
292
+ this.tui.requestRender();
293
+ void attachLocalFiles(expanded, request, this.hooks.whenBrokerReady).then((final) => {
294
+ if (!deliver(final) && this.editor.getText().trim() === '') {
295
+ this.editor.setText(typed);
296
+ this.tui.requestRender();
297
+ }
298
+ });
269
299
  }
270
300
  handleFollowUp() {
271
301
  const text = this.editor.getText();
272
302
  const trimmed = text.trim();
273
303
  if (!trimmed)
274
304
  return;
275
- if (!this.emitDrive({ type: 'follow_up', text: this.expandImagePlaceholders(text) }))
276
- return;
277
- this.editor.addToHistory(trimmed);
278
- this.editor.setText('');
279
- this.clearPastedImages();
305
+ const expanded = this.expandImagePlaceholders(text);
306
+ const sent = () => {
307
+ this.editor.addToHistory(trimmed);
308
+ this.clearPastedImages();
309
+ };
310
+ this.sendMessage(expanded, text, true, sent, (final) => this.emitDrive({ type: 'follow_up', text: final }));
280
311
  }
281
312
  async handleDequeue() {
282
313
  if (this.refuseStarting())
@@ -0,0 +1,113 @@
1
+ // input/local-files.ts — file paths in a message the person sends. A path they
2
+ // typed or pasted (or a pasted image's temp file) names a file on the viewer's
3
+ // machine, which the node may not share. Before the message leaves, each such
4
+ // file is sent to the node's broker (`upload_file`) and its path in the text is
5
+ // replaced with the path the node can read. Nothing here blocks the send: a file
6
+ // that is missing, too large or fails to upload stays as typed and the message
7
+ // gains a `<runtime>` note saying why.
8
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ /** Base64 grows the bytes by a third and the frame must fit the broker's read cap, so a file above this stays on the viewer. */
11
+ export const LOCAL_FILE_MAX_BYTES = 16 * 1024 * 1024;
12
+ /** An absolute or `~/` path, with shell-escaped spaces (`a\ b`) as a terminal drag-and-drop writes them. */
13
+ const PATH_TOKEN = /(?<![\w/~.:-])(~?\/(?:\\ |[^\s'"`<>()[\]{}])+)/g;
14
+ /** Every path token in `text`, with sentence punctuation trimmed and escapes undone. Exported for tests. */
15
+ export function findLocalPaths(text) {
16
+ const out = [];
17
+ for (const m of text.matchAll(PATH_TOKEN)) {
18
+ const raw = m[1].replace(/[.,;:!?]+$/, '');
19
+ if (raw === '/' || raw === '~/' || raw.startsWith('//'))
20
+ continue;
21
+ const unescaped = raw.replace(/\\ /g, ' ');
22
+ const path = unescaped.startsWith('~/') ? `${homedir()}${unescaped.slice(1)}` : unescaped;
23
+ out.push({ start: m.index, end: m.index + raw.length, raw, path });
24
+ }
25
+ return out;
26
+ }
27
+ function readLocal(path) {
28
+ let fd;
29
+ try {
30
+ fd = openSync(path, constants.O_RDONLY);
31
+ }
32
+ catch {
33
+ return { kind: 'missing' };
34
+ }
35
+ try {
36
+ const stat = fstatSync(fd);
37
+ if (!stat.isFile())
38
+ return { kind: 'not-file' };
39
+ if (stat.size > LOCAL_FILE_MAX_BYTES)
40
+ return { kind: 'too-large', size: stat.size };
41
+ return { kind: 'file', bytes: readFileSync(fd) };
42
+ }
43
+ finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ function mib(bytes) {
48
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
49
+ }
50
+ /** True when `text` names any path, so the caller can keep the plain synchronous send otherwise. */
51
+ export function hasLocalPaths(text) {
52
+ return findLocalPaths(text).length > 0;
53
+ }
54
+ /** The runtime note attachLocalFiles appends, found at the end of a user message. */
55
+ const TRAILING_RUNTIME_NOTE = /\n\n<runtime>\n[\s\S]*?\n<\/runtime>\s*$/;
56
+ /** A user message's text without the trailing runtime note: the note is for the node, not the person. */
57
+ export function withoutRuntimeNote(text) {
58
+ return text.replace(TRAILING_RUNTIME_NOTE, '');
59
+ }
60
+ /** Send each local file `text` names to the node and rewrite its path; append a `<runtime>` note for every file that could not go. */
61
+ export async function attachLocalFiles(text, request, brokerReady = () => Promise.resolve(true)) {
62
+ const matches = findLocalPaths(text);
63
+ if (matches.length === 0)
64
+ return text;
65
+ const notes = [];
66
+ // A viewer that attached before the node's runtime finished starting has no broker to take a file yet: wait for it.
67
+ if (!(await brokerReady())) {
68
+ const named = [...new Set(matches.filter((m) => readLocal(m.path).kind === 'file').map((m) => m.raw))];
69
+ if (named.length === 0)
70
+ return text;
71
+ return `${text}\n\n<runtime>\n${named.map((raw) => `the node's runtime was not ready, so ${raw} was not sent to you.`).join('\n')}\n</runtime>`;
72
+ }
73
+ const sent = new Map();
74
+ const replaced = [];
75
+ for (const match of matches) {
76
+ const done = sent.get(match.path);
77
+ if (done !== undefined) {
78
+ replaced.push({ match, to: done });
79
+ continue;
80
+ }
81
+ const read = readLocal(match.path);
82
+ if (read.kind === 'not-file')
83
+ continue;
84
+ if (read.kind === 'missing') {
85
+ notes.push(`${match.raw} does not exist on the person's machine, so it was not sent to you.`);
86
+ continue;
87
+ }
88
+ if (read.kind === 'too-large') {
89
+ notes.push(`file ${match.raw} is too large (${mib(read.size)}; the limit is ${mib(LOCAL_FILE_MAX_BYTES)}), not uploaded.`);
90
+ continue;
91
+ }
92
+ try {
93
+ const reply = await request({ type: 'upload_file', source_path: match.path, data: read.bytes.toString('base64') });
94
+ if (reply.kind !== 'upload_file')
95
+ throw new Error('unexpected reply');
96
+ sent.set(match.path, reply.path);
97
+ replaced.push({ match, to: reply.path });
98
+ }
99
+ catch (error) {
100
+ const message = error instanceof Error ? error.message : String(error);
101
+ notes.push(error?.code === 'unknown_frame'
102
+ ? `this node's runtime is too old to receive files from the viewer; ${match.raw} was not sent.`
103
+ : `file ${match.raw} could not be uploaded (${message}).`);
104
+ }
105
+ }
106
+ let out = text;
107
+ for (const { match, to } of replaced.reverse()) {
108
+ if (to === match.path && match.raw === to)
109
+ continue;
110
+ out = `${out.slice(0, match.start)}${to}${out.slice(match.end)}`;
111
+ }
112
+ return notes.length === 0 ? out : `${out}\n\n<runtime>\n${notes.join('\n')}\n</runtime>`;
113
+ }
@@ -21,6 +21,7 @@
21
21
  // `renderCall`/`renderResult` hooks degrade to the default ToolExecutionComponent
22
22
  // path while builtin tools, diffs, and partial-result streaming keep working.
23
23
  import { Container, Loader, Markdown, Spacer, Text } from '@earendil-works/pi-tui';
24
+ import { withoutRuntimeNote } from '../input/local-files.js';
24
25
  import { AssistantMessageComponent, BashExecutionComponent, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomMessageComponent, parseSkillBlock, SkillInvocationMessageComponent, ToolExecutionComponent, UserMessageComponent, } from '@earendil-works/pi-coding-agent';
25
26
  import { attachMarkdownTheme } from '../config.js';
26
27
  import { ContextMessageComponent } from './context-message.js';
@@ -1686,7 +1687,7 @@ export class ChatView {
1686
1687
  return;
1687
1688
  const parts = [
1688
1689
  new Spacer(1),
1689
- new Markdown(trimmed, 1, 1, attachMarkdownTheme(), { color: this.dimStyle }),
1690
+ new Markdown(withoutRuntimeNote(trimmed).trim(), 1, 1, attachMarkdownTheme(), { color: this.dimStyle }),
1690
1691
  ];
1691
1692
  for (const part of parts)
1692
1693
  this.pendingContainer.addChild(part);
@@ -1716,7 +1717,7 @@ export class ChatView {
1716
1717
  if (message.role === 'user')
1717
1718
  seen.add(this.userMessageText(message).trim());
1718
1719
  }
1719
- return this.pendingSends.filter((sent) => sent.resend && !seen.has(sent.text)).map((sent) => sent.text);
1720
+ return this.pendingSends.filter((sent) => sent.resend && !seen.has(withoutRuntimeNote(sent.text).trim())).map((sent) => sent.text);
1720
1721
  }
1721
1722
  /** The pending messages were handed to a parked node's wake message, so a reconnect must not send them again. */
1722
1723
  stopResendingPendingSends() {
@@ -1728,7 +1729,7 @@ export class ChatView {
1728
1729
  confirmPendingSend(text) {
1729
1730
  // The engine may reshape the text (image blocks, wrapping); with no exact
1730
1731
  // match the oldest pending send is the one that landed.
1731
- const exact = this.pendingSends.findIndex((sent) => sent.text === text);
1732
+ const exact = this.pendingSends.findIndex((sent) => withoutRuntimeNote(sent.text).trim() === text);
1732
1733
  const index = exact >= 0 ? exact : 0;
1733
1734
  if (this.pendingSends.length === 0)
1734
1735
  return;
@@ -1747,7 +1748,7 @@ export class ChatView {
1747
1748
  seen.add(this.userMessageText(message).trim());
1748
1749
  }
1749
1750
  for (const sent of [...this.pendingSends]) {
1750
- if (!seen.has(sent.text))
1751
+ if (!seen.has(withoutRuntimeNote(sent.text).trim()))
1751
1752
  continue;
1752
1753
  this.pendingSends.splice(this.pendingSends.indexOf(sent), 1);
1753
1754
  for (const part of sent.parts)
@@ -1940,16 +1941,16 @@ export class ChatView {
1940
1941
  // Tool payloads that cannot serialize are not transcript text.
1941
1942
  }
1942
1943
  }
1943
- /** Concatenate the text blocks of a user message (string or content array). */
1944
+ /** Concatenate the text blocks of a user message (string or content array), without the viewer's trailing runtime note. */
1944
1945
  userMessageText(message) {
1945
1946
  const content = message.content;
1946
1947
  if (typeof content === 'string')
1947
- return content;
1948
+ return withoutRuntimeNote(content);
1948
1949
  if (!Array.isArray(content))
1949
1950
  return '';
1950
- return content
1951
+ return withoutRuntimeNote(content
1951
1952
  .filter((c) => typeof c === 'object' && c !== null && c.type === 'text')
1952
1953
  .map((c) => c.text)
1953
- .join('');
1954
+ .join(''));
1954
1955
  }
1955
1956
  }