@north-light/cli 0.3.789 → 0.3.791

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/nodes.d.ts +0 -12
  6. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  7. package/dist/clients/attach/viewer.js +526 -526
  8. package/dist/commands/canvas-history/shared.js +1 -1
  9. package/dist/commands/node/bash.js +1 -1
  10. package/dist/commands/node/create.js +2 -2
  11. package/dist/commands/node/inspect.js +6 -6
  12. package/dist/commands/node/lifecycle.js +4 -4
  13. package/dist/commands/node-context.js +2 -2
  14. package/dist/commands/person-settings.js +1 -1
  15. package/dist/commands/profile/daemon-profiles.js +4 -4
  16. package/dist/commands/sys.js +1 -1
  17. package/dist/core/canvas/history.d.ts +2 -8
  18. package/dist/core/canvas/history.js +9 -9
  19. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  20. package/dist/core/canvas/node-agent-paths.js +1 -1
  21. package/dist/core/canvas/node-tokens.js +3 -3
  22. package/dist/core/canvas/paths.d.ts +3 -10
  23. package/dist/core/canvas/paths.js +1 -1
  24. package/dist/core/canvas/person-state.d.ts +5 -7
  25. package/dist/core/canvas/person-state.js +1 -1
  26. package/dist/core/canvas/person.d.ts +3 -30
  27. package/dist/core/canvas/person.js +1 -11
  28. package/dist/core/canvas/render-source.js +1 -1
  29. package/dist/core/config.d.ts +4 -1
  30. package/dist/core/config.js +1 -1
  31. package/dist/core/directory/join.d.ts +4 -6
  32. package/dist/core/directory/join.js +1 -1
  33. package/dist/core/grants/sync.js +1 -1
  34. package/dist/core/human/requests.d.ts +11 -1
  35. package/dist/core/human/requests.js +22 -22
  36. package/dist/core/providers/files.js +1 -1
  37. package/dist/core/review/store.js +1 -1
  38. package/dist/core/runtime/bearings-render.d.ts +2 -2
  39. package/dist/core/runtime/bearings-render.js +11 -11
  40. package/dist/core/runtime/bearings.js +1 -1
  41. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  42. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  43. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  44. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  45. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  46. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  47. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  48. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  49. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  50. package/dist/core/runtime/broker-extension-render.js +2 -2
  51. package/dist/core/runtime/broker.js +1 -1
  52. package/dist/core/runtime/host.js +3 -3
  53. package/dist/core/runtime/kickoff.d.ts +1 -1
  54. package/dist/core/runtime/kickoff.js +12 -12
  55. package/dist/core/runtime/launch-config-worker.js +1 -1
  56. package/dist/core/runtime/launch-target.d.ts +6 -4
  57. package/dist/core/runtime/launch-target.js +1 -1
  58. package/dist/core/runtime/launch.d.ts +5 -1
  59. package/dist/core/runtime/launch.js +2 -2
  60. package/dist/core/runtime/nodes.js +1 -1
  61. package/dist/core/runtime/revive.js +2 -2
  62. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  63. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  64. package/dist/core/runtime/runner/launch-env.js +1 -0
  65. package/dist/core/runtime/runner/machine/executor.js +2 -2
  66. package/dist/core/runtime/runner/machine/runner.js +1 -1
  67. package/dist/core/runtime/runner/types.d.ts +1 -0
  68. package/dist/core/runtime/spawn-env-rows.js +1 -1
  69. package/dist/core/runtime/spawn.js +2 -2
  70. package/dist/core/secrets/environment-owner.js +1 -1
  71. package/dist/core/storage/attachments.d.ts +1 -1
  72. package/dist/core/storage/attachments.js +1 -1
  73. package/dist/core/storage/tables.d.ts +6 -2
  74. package/dist/core/storage/tables.js +4 -4
  75. package/dist/core/substrate/delivery/deliver.js +1 -1
  76. package/dist/core/substrate/delivery/render-boot.js +1 -1
  77. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  78. package/dist/daemon/api/handlers/canvas.js +5 -5
  79. package/dist/daemon/api/handlers/nodes.js +1 -1
  80. package/dist/daemon/api/handlers/profiles.js +1 -1
  81. package/dist/daemon/api/map.d.ts +1 -4
  82. package/dist/daemon/api/map.js +2 -2
  83. package/dist/daemon/cron/lease-recovery.js +1 -1
  84. package/dist/daemon/cron/machine-fire.js +1 -1
  85. package/dist/daemon/human/sweep.js +1 -1
  86. package/dist/daemon/peer/ingress.d.ts +2 -2
  87. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  88. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  89. package/dist/daemon/runs/observer.js +6 -5
  90. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  91. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  92. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  93. package/package.json +3 -3
  94. package/packages/crouter-api/dist/api/client.js +2 -2
  95. package/packages/crouter-api/dist/api/contract.js +1 -1
  96. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  97. package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
  98. package/packages/crouter-api/dist/core/config.js +10 -0
  99. package/packages/crouter-api/dist/core/directory/join.js +11 -45
  100. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  101. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  102. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/sandbox-start.mjs +5 -3
  108. package/dist/commands/sys/join.d.ts +0 -3
  109. package/dist/commands/sys/join.js +0 -1
@@ -1,2 +1,2 @@
1
- var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as me,brokerRunTurnBusy as pe,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ye}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ge=3e4,be=5*6e4,U="inbox daemon unreachable",B=16;let v,ve=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function we(){return{tickMs:V(),debounceMs:z()}}c(we,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&ue(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function _e(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}c(_e,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}c(b,"deliveryFields");function Ee(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ee,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function Ie(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
2
- `):""}c(Ie,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function ke(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(ke,"disposalReasonForShutdown");function xe(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}c(xe,"boundedRuntimeReason");class Se{static{c(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=G();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=c((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(a=>a.awaitingDequeue!==void 0))return;const n=C(Ie(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=$(i)?ke(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:xe(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=O();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const o of a)R(o,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=O().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),Y()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ge,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<be)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&ie(t).then(e=>e.fault?.op===U?N(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&pe())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||W()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return K(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=me();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(d,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,_e(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||W())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const a of e.handoffs)T(a.operationId,a,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ne(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ee(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Ce(r,t){v?.dispose("reload",!1);const e=new Se(r,t,++ve);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ye]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Ce,"installWatcher");function Fe(r){const t=Ce(r,we());return()=>t.dispose("shutdown",!1)}c(Fe,"registerCanvasInboxWatcher");var je=Fe;export{je as default,Fe as registerCanvasInboxWatcher};
1
+ var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{expandHostPathTokens as ue}from"../core/runtime/broker/host-path-tokens.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as me}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as pe,brokerRunTurnBusy as ye,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ge}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,be=3e4,ve=5*6e4,U="inbox daemon unreachable",B=16;let v,we=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function _e(){return{tickMs:V(),debounceMs:z()}}c(_e,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&me(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function Ee(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}c(Ee,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}c(b,"deliveryFields");function Ie(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ie,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function ke(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
2
+ `):""}c(ke,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function xe(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(xe,"disposalReasonForShutdown");function Se(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}c(Se,"boundedRuntimeReason");class Ce{static{c(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=G();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=c((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(a=>a.awaitingDequeue!==void 0))return;const n=C(ke(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=$(i)?xe(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:Se(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=O();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const o of a)R(o,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=O().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),Y()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(be,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ve)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&ie(t).then(e=>e.fault?.op===U?N(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&ye())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||W()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return K(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){return i=ue(i),this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=pe();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(d,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,Ee(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||W())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const a of e.handoffs)T(a.operationId,a,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ne(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ie(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Fe(r,t){v?.dispose("reload",!1);const e=new Ce(r,t,++we);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ge]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Fe,"installWatcher");function Me(r){const t=Fe(r,_e());return()=>t.dispose("shutdown",!1)}c(Me,"registerCanvasInboxWatcher");var Ve=Me;export{Ve as default,Me as registerCanvasInboxWatcher};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.789",
3
+ "version": "0.3.791",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.789",
161
- "@north-light/plugin": "0.3.789",
160
+ "@north-light/identity": "0.3.791",
161
+ "@north-light/plugin": "0.3.791",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -450,8 +450,8 @@ export class CrtrClient {
450
450
  waitNode(id, req) {
451
451
  return this.request('POST', routes.nodeWait(this.nodePath(id)), req);
452
452
  }
453
- listKinds() {
454
- return this.request('GET', routes.kinds());
453
+ listKinds(opts = {}) {
454
+ return this.request('GET', withQuery(routes.kinds(), { profile: opts.profile }));
455
455
  }
456
456
  /** A model change may first wait up to 30 s for a starting broker's view
457
457
  * socket and then 15 s for its ack, so it gets that budget on top. */
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.88';
15
+ export const CONTRACT_LEVEL = '1.90';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -106,19 +106,10 @@ export function scopesFilePath(nodeId) {
106
106
  export function contextDir(nodeId, grantee) {
107
107
  return join(nodeAgentDir(nodeId, grantee), 'context');
108
108
  }
109
- /** Replace the literal env-var tokens `$CRTR_CONTEXT_DIR` / `$CRTR_NODE_ID` in
110
- * agent-facing doc text with the node's real values, so a doc surfaced INTO a
111
- * node hands it a concrete absolute path instead of a shell-only string. The
112
- * env vars only expand in bash; an agent that pastes `$CRTR_CONTEXT_DIR/x.md`
113
- * into the (non-expanding) Write tool creates a literal `$CRTR_CONTEXT_DIR/`
114
- * dir under the project repo. The resolved absolute path works in both bash and
115
- * Write, so this substitution is strictly safer. Callers must only apply it
116
- * when they have a concrete node to render for (never on generic, node-less
117
- * output). Pure string work — no I/O. */
118
- export function interpolateNodePaths(text, nodeId, grantee) {
119
- return text
120
- .replaceAll('$CRTR_CONTEXT_DIR', contextDir(nodeId, grantee))
121
- .replaceAll('$CRTR_NODE_ID', nodeId);
109
+ /** Replace the literal token `$CRTR_NODE_ID` in agent-facing doc text with the node's id. `$CRTR_CONTEXT_DIR` stays a token: only the machine hosting the
110
+ * node's broker knows its path, and the broker expands it (`expandHostPathTokens`) before the text reaches the model. Pure string work — no I/O. */
111
+ export function interpolateNodePaths(text, nodeId) {
112
+ return text.replaceAll('$CRTR_NODE_ID', nodeId);
122
113
  }
123
114
  export function jobDir(nodeId) {
124
115
  return join(nodeRecordDir(nodeId), 'job');
@@ -1,4 +1,4 @@
1
- // person-state.ts — the process's person binding (boot-set person, cloud-role flag, per-request person). Pure: no database, so the
1
+ // person-state.ts — the process's person binding (client-bound person, cloud-role flag, per-request person). Pure: no database, so the
2
2
  // CLI-reachable settings cache can read the current person without reaching canvas state.
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
4
  /** Thrown by `personId()` before the person is known (a hosted first boot, before its first grant snapshot). */
@@ -12,11 +12,11 @@ export class PersonOutsideRequestError extends Error {
12
12
  code = 'person_outside_request';
13
13
  constructor() { super('no person: a cloud role reads the person only inside a request, from its token'); this.name = 'PersonOutsideRequestError'; }
14
14
  }
15
- let daemonPersonId;
15
+ let clientPersonId;
16
16
  let cloudRole = false;
17
17
  const requestPersons = new AsyncLocalStorage();
18
- /** crtrd sets this once at boot; it wins unconditionally. */
19
- export function setPersonId(id) { daemonPersonId = id; }
18
+ /** A CLI, viewer or launch-config subprocess binds the one person it acts for (the person its settings answer named). A crtrd process never calls this: it reads the person from the request or the row it serves. */
19
+ export function bindClientPerson(id) { clientPersonId = id; }
20
20
  /** crtrd calls this at boot on a cloud role, instead of resolving a person: from then on a person read outside a request throws. */
21
21
  export function markCloudRole() { cloudRole = true; }
22
22
  /** Whether this process is a cloud role (`markCloudRole` ran at boot). */
@@ -27,19 +27,17 @@ export function markEnginesInProcess() { enginesInProcess = true; }
27
27
  export function areEnginesInProcess() { return enginesInProcess; }
28
28
  /** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
29
29
  export function runAsPerson(person, fn) { return requestPersons.run(person, fn); }
30
- /** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
31
- * `PersonUnresolvedError` when a Mac's person is not bound. Tests and non-daemon processes use `personIdAsync()`. */
30
+ /** The request's person; else the person a CLI-side process bound. Throws `PersonOutsideRequestError` on a cloud role outside a request and
31
+ * `PersonUnresolvedError` when no client-bound person exists. Tests and non-daemon processes use `personIdAsync()`. */
32
32
  export function personId() {
33
33
  const request = requestPersons.getStore();
34
34
  if (request !== undefined)
35
35
  return request;
36
36
  if (cloudRole)
37
37
  throw new PersonOutsideRequestError();
38
- if (daemonPersonId === undefined)
38
+ if (clientPersonId === undefined)
39
39
  throw new PersonUnresolvedError();
40
- return daemonPersonId;
40
+ return clientPersonId;
41
41
  }
42
- /** The boot-set person, if any (for `personIdAsync`). */
43
- export function bootPersonId() { return daemonPersonId; }
44
- /** The request's person, if any (for `personIdAsync`). */
42
+ /** The request's person, if any. */
45
43
  export function requestPersonId() { return requestPersons.getStore(); }
@@ -934,6 +934,8 @@ function readRawProfileConfig(profileId) {
934
934
  * — the SCOPE THE CONFIG IS FOR, not necessarily the calling process's own
935
935
  * ambient cwd/profile (see `readMergedLaunchConfig`). */
936
936
  function readRawProjectScopeConfigs(targetCwd, targetProfileId) {
937
+ if (targetCwd === null)
938
+ return [];
937
939
  const nearestFirst = findProjectScopeRoots(targetCwd, targetProfileId);
938
940
  const farthestFirst = [...nearestFirst].reverse();
939
941
  // A root with no config.json still contributes: its installed plugins may
@@ -1020,6 +1022,14 @@ export function readMergedLaunchConfig(targetCwd = process.cwd(), targetProfileI
1020
1022
  spawnEnv,
1021
1023
  };
1022
1024
  }
1025
+ /** The launch config a process holding the project's files adds on top of a recipe's config, which a cloud control plane built without them:
1026
+ * the project stack's kinds (and the kinds its enabled plugins declare) in `cwd`, over the recipe's kinds. */
1027
+ export function overlayProjectLaunchConfig(base, cwd, profileId) {
1028
+ let kinds = base.kinds;
1029
+ for (const { root, raw } of readRawProjectScopeConfigs(cwd, profileId))
1030
+ kinds = mergeKinds(raw?.kinds, layerPluginKinds('project', root, kinds));
1031
+ return { ...base, kinds };
1032
+ }
1023
1033
  /** The effective `KindConfig` for one full kind string (top-level, e.g.
1024
1034
  * `developer`, or sub-kind, e.g. `audit/security`), across
1025
1035
  * project > user > builtin precedence. Returns `undefined` for a kind no
@@ -1,15 +1,12 @@
1
- // Runtime registration: send the directory a new public ES256 key under a credential (a hosted runtime's single-use enrollment token at first
2
- // boot, or a signed-in person's bearer from `crtr sys signin`), then record the returned identity and the private key in the runtime-client file.
1
+ // Runtime registration: send the directory a new public ES256 key under a credential (a signed-in person's bearer from `crtr sys signin`), then record the returned identity and the private key in the runtime-client file.
3
2
  // It writes no settings (the daemon applies them at its start); the private key never leaves this computer.
4
3
  import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
5
4
  import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
6
- import { request } from 'node:http';
7
5
  import { hostname } from 'node:os';
8
6
  import { join } from 'node:path';
9
7
  import { InputError } from '../io.js';
10
8
  import { network } from '../errors.js';
11
9
  import { secretsDir } from '../layout.js';
12
- import { apiSocketPath } from '../canvas/paths.js';
13
10
  import { atomicWriteJson, readJsonIfExists } from '../fs-utils.js';
14
11
  import { launcherPresent } from '../grants/sandboxes.js';
15
12
  import { crtrVersion } from '../../shared/crtr-version.js';
@@ -74,7 +71,7 @@ async function register(directory, token, publicJwk, name, retry) {
74
71
  if (response.status < 500)
75
72
  rmSync(pendingPath(), { force: true });
76
73
  throw new InputError({
77
- error: 'join_refused',
74
+ error: 'registration_refused',
78
75
  message: `directory refused the registration: ${response.status} ${text.slice(0, 500)}`,
79
76
  next: retry,
80
77
  });
@@ -88,34 +85,27 @@ async function register(directory, token, publicJwk, name, retry) {
88
85
  throw error;
89
86
  }
90
87
  }
91
- /** What a successful `crtr sys join` recorded in the client file, or null when join never wrote it (no file, or one provisioned
92
- * without join, which has no `token_sha256`). Join writes no settings: the daemon applies this at its start (`applyBootSettings`),
93
- * and its `retireLocalPerson` makes `owner` the install's person. */
88
+ /** What a successful registration recorded in the client file, or null when none did (no file, or one provisioned
89
+ * without registration, which has no `token_sha256`). Registration writes no settings: the daemon applies this at its start (`applyBootSettings`),
90
+ * and takes `owner` as the install's person. */
94
91
  function readJoined() {
95
92
  const stored = readJsonIfExists(clientPath());
96
93
  if (stored?.token_sha256 === undefined)
97
94
  return null;
98
95
  const { owner } = stored;
99
96
  if (typeof owner !== 'string' || !/^user:.+/.test(owner))
100
- throw new Error(`${clientPath()} was written by join but has a missing or invalid owner`);
97
+ throw new Error(`${clientPath()} was written by registration but has a missing or invalid owner`);
101
98
  return stored;
102
99
  }
103
- /** The owner a successful join recorded, or null when `crtr sys join` never wrote the client file. */
100
+ /** The owner a successful registration recorded, or null when no registration wrote the client file. */
104
101
  export function joinedOwner() { return readJoined()?.owner ?? null; }
105
- /** The issuer a successful join recorded, or null. */
102
+ /** The issuer a successful registration recorded, or null. */
106
103
  export function joinedIssuer() { return readJoined()?.issuer ?? null; }
107
- /** The whole registration a successful join recorded, or null; a damaged file throws. */
104
+ /** The whole registration a successful registration recorded, or null; a damaged file throws. */
108
105
  export function joinedClient() {
109
106
  const stored = readJoined();
110
107
  return stored === null ? null : registration(stored);
111
108
  }
112
- function daemonRunningError(socket) {
113
- return new InputError({
114
- error: 'daemon_running',
115
- message: `cannot register while a daemon answers on ${socket}`,
116
- next: 'Stop the daemon that owns this volume, then run `crtr sys join` again.',
117
- });
118
- }
119
109
  /** Register (or reuse the stored registration) without touching local state beyond the pending key. */
120
110
  async function obtainRegistration(directory, token, name, tokenHash, retry) {
121
111
  const stored = readJsonIfExists(clientPath());
@@ -143,7 +133,7 @@ function requireDirectory(directory) {
143
133
  async function registerAndStore(directory, credential, name, retry) {
144
134
  requireDirectory(directory);
145
135
  if (credential === '')
146
- throw new InputError({ error: 'invalid_token', message: 'credential is empty', field: 'token', next: 'Pass the enrollment token provisioning supplied.' });
136
+ throw new InputError({ error: 'invalid_token', message: 'credential is empty', field: 'token', next: 'Sign in again with `crtr sys signin`.' });
147
137
  const { joined, registered, client } = await obtainRegistration(directory, credential, name, createHash('sha256').update(credential).digest('hex'), retry);
148
138
  if (client) {
149
139
  atomicWriteJson(clientPath(), client, { mode: 0o600 });
@@ -151,32 +141,8 @@ async function registerAndStore(directory, credential, name, retry) {
151
141
  }
152
142
  return { ...joined, registered };
153
143
  }
154
- /** True when a daemon answers /healthz on the socket (a blocked daemon still answers and owns its files). */
155
- function daemonAnswers(socketPath) {
156
- return new Promise(resolve => {
157
- const req = request({ socketPath, path: '/healthz', method: 'GET', timeout: 1000 }, res => {
158
- res.resume();
159
- resolve(true);
160
- });
161
- req.on('timeout', () => req.destroy(new Error('daemon probe timed out')));
162
- req.on('error', error => {
163
- if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
164
- resolve(false);
165
- else
166
- resolve(true); // Uncertain probe: do not touch an owned volume.
167
- });
168
- req.end();
169
- });
170
- }
171
- /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
172
- export async function joinDirectory(directory, token, name = hostname()) {
173
- const socket = apiSocketPath();
174
- if (await daemonAnswers(socket))
175
- throw daemonRunningError(socket);
176
- return registerAndStore(directory, token, name, 'Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.');
177
- }
178
144
  /** `crtr sys signin`'s registration: the signed-in person's bearer registers this computer as one of the person's runtimes, once. A computer that
179
- * already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
145
+ * already holds a registration for this directory's owner (an earlier signin) is left as it is. */
180
146
  export async function registerSignedInMac(directory, bearer) {
181
147
  if (readJoined() !== null)
182
148
  return null;
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname } from 'node:path';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
3
  import { daemonClient } from './daemon-ops.js';
4
+ import { hostContextDir } from './host-path-tokens.js';
4
5
  /** Download every attachment of this node's run that is not already on the broker's disk (D98). The control plane puts
5
6
  * each fetched upload in the blob store and records it on the run; the files are written where the run's prompt names
6
7
  * them. Run before the broker hands the agent a prompt or mail. A failed download throws: the agent must not be told
@@ -8,7 +9,14 @@ import { daemonClient } from './daemon-ops.js';
8
9
  export async function fetchRunAttachments(nodeId, listed) {
9
10
  const client = daemonClient();
10
11
  const attachments = listed ?? (await client.listNodeAttachments(nodeId)).attachments;
11
- for (const file of attachments) {
12
+ if (attachments.length === 0)
13
+ return;
14
+ const contextDir = hostContextDir();
15
+ if (contextDir === undefined)
16
+ throw new Error(`cannot place attachments of node ${nodeId}: this broker has no CRTR_CONTEXT_DIR and no CRTR_NODE_ID/CRTR_GRANTEE to derive it from`);
17
+ const nodeDir = dirname(contextDir);
18
+ for (const listed of attachments) {
19
+ const file = { ...listed, path: hostPath(nodeDir, listed.path) };
12
20
  if (existsSync(file.path))
13
21
  continue;
14
22
  const bytes = await client.readNodeAttachment(nodeId, file.sha256);
@@ -18,3 +26,11 @@ export async function fetchRunAttachments(nodeId, listed) {
18
26
  renameSync(partial, file.path);
19
27
  }
20
28
  }
29
+ /** A node-relative row (`attachments/<name>`) is under this host's node folder; an absolute row from before paths were relative is re-rooted from its
30
+ * `…/apps/<app>/nodes/<id>/` prefix onto the same folder. */
31
+ function hostPath(nodeDir, path) {
32
+ if (!isAbsolute(path))
33
+ return join(nodeDir, path);
34
+ const rest = /\/apps\/[^/]+\/nodes\/[^/]+\/(.+)$/.exec(path);
35
+ return rest === null ? path : join(nodeDir, rest[1]);
36
+ }
@@ -50,11 +50,6 @@ export function clearBrokerPushedFinal(nodeId) {
50
50
  export function consumeBrokerPushedFinal(nodeId) {
51
51
  return daemonClient().nodePushedFinal(nodeId, { action: 'consume', expected_execution_id: brokerExecutionId() });
52
52
  }
53
- export function startBrokerBashJob(nodeId, request) {
54
- return daemonClient().request('POST', `/v1/nodes/${encodeURIComponent(nodeId)}/jobs/start`, {
55
- ...request, expected_execution_id: brokerExecutionId(),
56
- });
57
- }
58
53
  /** Record a command the valve just backgrounded as this node's job object. */
59
54
  export function recordBackgroundedJob(nodeId, jobId, request) {
60
55
  return daemonClient().recordBackgroundedJob(nodeId, jobId, request);
@@ -63,11 +58,6 @@ export function recordBackgroundedJob(nodeId, jobId, request) {
63
58
  export function reportBrokerJob(nodeId, jobId, request) {
64
59
  return daemonClient().reportBashJob(nodeId, jobId, { ...request, expected_execution_id: brokerExecutionId() });
65
60
  }
66
- export function stopBrokerBashJob(nodeId, jobId) {
67
- return daemonClient().request('DELETE', `/v1/nodes/${encodeURIComponent(nodeId)}/jobs/${encodeURIComponent(jobId)}?foreground=1`, {
68
- expected_execution_id: brokerExecutionId(),
69
- });
70
- }
71
61
  export function brokerExecutionId() {
72
62
  const id = envExecutionId();
73
63
  if (id === undefined || id === '')
@@ -0,0 +1,21 @@
1
+ import { dirname } from 'node:path';
2
+ import { contextDir } from '../../canvas/paths.js';
3
+ /** The control plane renders prompt text with `$CRTR_CONTEXT_DIR` and `$CRTR_NODE_DIR` as literal tokens, because only the machine that hosts a node's broker
4
+ * knows where the node's folder is. The broker swaps them for its own paths before the text reaches the model. Text is unchanged when the env names no context dir. */
5
+ export function expandHostPathTokens(text) {
6
+ if (!text.includes('$CRTR_'))
7
+ return text;
8
+ const context = hostContextDir();
9
+ if (context === undefined)
10
+ return text;
11
+ return text.replaceAll('$CRTR_CONTEXT_DIR', context).replaceAll('$CRTR_NODE_DIR', dirname(context));
12
+ }
13
+ /** The broker's own context dir: its env, else derived from its node id and app on this host's layout. */
14
+ export function hostContextDir() {
15
+ const set = process.env['CRTR_CONTEXT_DIR'];
16
+ if (set !== undefined && set !== '')
17
+ return set;
18
+ const node = process.env['CRTR_NODE_ID'];
19
+ const app = process.env['CRTR_GRANTEE'];
20
+ return node && app ? contextDir(node, app) : undefined;
21
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.789",
3
+ "version": "0.3.791",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.789",
3
+ "version": "0.3.791",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.789",
3
+ "version": "0.3.791",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.789",
31
- "@north-light/identity": "0.3.789"
30
+ "@north-light/api": "0.3.791",
31
+ "@north-light/identity": "0.3.791"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.789",
3
+ "version": "0.3.791",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.789",
9
+ "version": "0.3.791",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.789",
32
- "@north-light/plugin": "0.3.789",
31
+ "@north-light/identity": "0.3.791",
32
+ "@north-light/plugin": "0.3.791",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.789",
11905
+ "version": "0.3.791",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.789",
11910
+ "version": "0.3.791",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.789",
11915
+ "version": "0.3.791",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.789",
11923
+ "version": "0.3.791",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.789",
11927
- "@north-light/identity": "0.3.789"
11926
+ "@north-light/api": "0.3.791",
11927
+ "@north-light/identity": "0.3.791"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.789",
11932
+ "version": "0.3.791",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.789",
11936
- "@north-light/identity": "0.3.789",
11937
- "@north-light/plugin": "0.3.789",
11935
+ "@north-light/api": "0.3.791",
11936
+ "@north-light/identity": "0.3.791",
11937
+ "@north-light/plugin": "0.3.791",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -12,7 +12,7 @@ import { randomBytes } from 'node:crypto';
12
12
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
13
13
  import { tmpdir, uptime } from 'node:os';
14
14
  import { basename, dirname, join, resolve, sep } from 'node:path';
15
- import { fileURLToPath } from 'node:url';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
16
 
17
17
  export const EXIT_NO_BROKER = 3;
18
18
  const here = dirname(fileURLToPath(import.meta.url));
@@ -337,7 +337,9 @@ async function start(env) {
337
337
  const models = launch.models;
338
338
  if (models) writeFileSync(join(agentDir, 'models.json'), `${JSON.stringify(models, null, 2)}\n`);
339
339
  // The recipe's env names the control plane's homes (`/opt/crouter/runtime`, `/work/crtr`); the broker merges it into its own env, which would put them back in every tool the node runs. The sandbox's own homes win.
340
- writeFileSync(join(runDir, 'broker-launch.json'), JSON.stringify({ ...launch, argv, env: { ...launch.env, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime') } }));
340
+ const { hostLaunchEnv, sandboxContextDir } = await import(pathToFileURL(join(releaseDir, 'dist', 'core', 'runtime', 'runner', 'launch-env.js')).href);
341
+ const hostEnv = hostLaunchEnv(launch.env ?? {}, { contextDir: sandboxContextDir(bundle.node.app, nodeId, root), scopesFile: join(runDir, 'scopes.json') });
342
+ writeFileSync(join(runDir, 'broker-launch.json'), JSON.stringify({ ...launch, argv, env: { ...hostEnv, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime') } }));
341
343
  const settingsPath = join(agentDir, 'settings.json');
342
344
  const builtin = join(releaseDir, 'dist', 'builtin-pi-packages', 'pi-crtr-extensions');
343
345
  let settings = {};
@@ -353,7 +355,7 @@ async function start(env) {
353
355
  writeFileSync(settingsPath, `${JSON.stringify({ ...settings, packages })}\n`);
354
356
 
355
357
  // 5.9 the broker, with the token on fd 3 and not in its environment.
356
- const brokerEnv = { ...env, ...launch.env, HOME: home, PI_CODING_AGENT_DIR: agentDir, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime'),
358
+ const brokerEnv = { ...env, ...hostEnv, HOME: home, PI_CODING_AGENT_DIR: agentDir, CRTR_HOME: root, CRTR_RUNTIME_HOME: join(root, 'runtime'),
357
359
  CRTR_FRONT_DOOR: '1', CRTR_EXECUTION_ID: executionId, CRTR_API_URL: apiUrl, CRTR_FEEDBACK_ENDPOINT: `${apiUrl.replace(/\/$/, '')}/v1/feedback`, CRTR_NO_AUTO_INIT: '1',
358
360
  CRTR_PLUGINS_REVISION: String(bundle.plugins_revision), ...(environmentId ? { CRTR_ENVIRONMENT_ID: environmentId } : {}), ...(scopesFile ? { CRTR_SCOPES_FILE: scopesFile } : {}),
359
361
  PATH: `${join(releaseDir, 'bin')}:${env.PATH ?? '/usr/local/bin:/usr/bin:/bin'}` };