@north-light/cli 0.3.713 → 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.
- package/dist/clients/attach/input/controller.d.ts +2 -0
- package/dist/clients/attach/input/controller.js +1 -1
- package/dist/clients/attach/input/local-files.d.ts +3 -1
- package/dist/clients/attach/input/local-files.js +8 -3
- package/dist/clients/attach/render/chat-view.d.ts +1 -1
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/viewer.js +526 -521
- package/dist/commands/node/inspect.js +5 -5
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +1 -1
- package/dist/core/canvas/deliveries.js +10 -10
- package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/types.d.ts +1 -0
- package/dist/core/checkout-identities.js +1 -1
- package/dist/core/import/load/bind.d.ts +8 -0
- package/dist/core/import/load/bind.js +15 -15
- package/dist/core/import/load/prepare.d.ts +8 -1
- package/dist/core/import/load/prepare.js +9 -7
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/llm/run.d.ts +1 -1
- package/dist/core/pool-credential-store.d.ts +5 -5
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker-wedge.d.ts +1 -2
- package/dist/core/runtime/broker-wedge.js +2 -2
- package/dist/core/subscription-state.d.ts +3 -3
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -12
- package/dist/daemon/fleet.js +2 -2
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/holder.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +3 -3
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
- package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
- package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
- package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
- package/packages/crouter-api/dist/core/subscription-state.js +70 -81
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +3 -2
- package/scripts/self-update.mjs +5 -1
|
@@ -2,7 +2,7 @@ var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});i
|
|
|
2
2
|
WHERE call_id IN (SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'pending'
|
|
3
3
|
AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)
|
|
4
4
|
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${S})
|
|
5
|
-
RETURNING call_id, op, args_json`).all(this.generation,_(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<S)return}}finally{this.claiming=!1}}}async failCall(e,n,t,s){await this.settle(e,"failed",{code:n,message:t,sent:s},!1)}async isCurrentGeneration(){return await(await o()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await o()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,s){await re(e,n,t,this.environmentId,this.generation,s)}async onMessage(e){const n=Y(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await D(this.environmentId,n);return;case"running":if(!await this.isCurrentGeneration())return;await oe(this.environmentId,new Set(n.executions),this.openedAt);return;case"job.report":await this.storeJobReport(n);return;case"turns":this.send({type:"turns.answer",id:n.id,turns:await this.turns(n.brokers)});return;case"wedge":await this.recordWedge(n);return;case"view.ready":{const t=this.channels.get(n.channel);d({level:"info",event:"daemon.timing.view_ready_received",...t===void 0?{}:{node_id:t.nodeId},fields:{channel:n.channel,known:t!==void 0,...t===void 0?{}:{open_to_ready_ms:t.sinceOpenMs()}}}),t?.emit("connect");return}case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await K(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async ownNode(e,n){return typeof n!="string"||await p(n)!==this.environmentId||(await C(n))?.executionId!==e?null:await W(n)}async turns(e){const n={};for(const{execution:t,node:s}of e){const r=await this.ownNode(t,s);if(r===null)continue;const c=await P(s),l=c?.busy===!0&&c.progressAt!==null?Date.parse(c.progressAt):Number.NaN,u=Date.parse(r.launched_at??"");n[t]={since:Number.isFinite(l)&&Number.isFinite(u)&&l>=u?l:null,refresh:r.intent==="refresh",jobs:(await F(await o(),s)).length>0}}return n}async recordWedge(e){const n=await this.ownNode(e.execution,e.node);if(n===null||await j(e.node,"wedge_noticed_at")===e.since)return;await $(e.node,"wedge_noticed_at",e.since);const t=e.has_descendants??!0;await B(e.node,{quietForMs:e.quiet_ms,cpuPercent:e.cpu_percent,hasDescendants:e.has_descendants,kickAttempted:e.kick_attempted,kicked:e.kicked,kickSuppressionReason:null,pid:null,label:J(`${H(n)} (${e.node})`,Math.round(e.quiet_ms/6e4),t,!1,e.kicked)})}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),h.get(this.environmentId)===this&&h.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await o(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function re(i,e,n,t,s,r){const c=await o();(await c.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
|
|
5
|
+
RETURNING call_id, op, args_json`).all(this.generation,_(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<S)return}}finally{this.claiming=!1}}}async failCall(e,n,t,s){await this.settle(e,"failed",{code:n,message:t,sent:s},!1)}async isCurrentGeneration(){return await(await o()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await o()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,s){await re(e,n,t,this.environmentId,this.generation,s)}async onMessage(e){const n=Y(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await D(this.environmentId,n);return;case"running":if(!await this.isCurrentGeneration())return;await oe(this.environmentId,new Set(n.executions),this.openedAt);return;case"job.report":await this.storeJobReport(n);return;case"turns":this.send({type:"turns.answer",id:n.id,turns:await this.turns(n.brokers)});return;case"wedge":await this.recordWedge(n);return;case"view.ready":{const t=this.channels.get(n.channel);d({level:"info",event:"daemon.timing.view_ready_received",...t===void 0?{}:{node_id:t.nodeId},fields:{channel:n.channel,known:t!==void 0,...t===void 0?{}:{open_to_ready_ms:t.sinceOpenMs()}}}),t?.emit("connect");return}case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await K(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async ownNode(e,n){return typeof n!="string"||await p(n)!==this.environmentId||(await C(n))?.executionId!==e?null:await W(n)}async turns(e){const n={};for(const{execution:t,node:s}of e){const r=await this.ownNode(t,s);if(r===null)continue;const c=await P(s),l=c?.busy===!0&&c.progressAt!==null?Date.parse(c.progressAt):Number.NaN,u=Date.parse(r.launched_at??"");n[t]={since:Number.isFinite(l)&&Number.isFinite(u)&&l>=u?l:null,refresh:r.intent==="refresh"||r.cycle_pending===!0,jobs:(await F(await o(),s)).length>0}}return n}async recordWedge(e){const n=await this.ownNode(e.execution,e.node);if(n===null||await j(e.node,"wedge_noticed_at")===e.since)return;await $(e.node,"wedge_noticed_at",e.since);const t=e.has_descendants??!0;await B(e.node,{quietForMs:e.quiet_ms,cpuPercent:e.cpu_percent,hasDescendants:e.has_descendants,kickAttempted:e.kick_attempted,kicked:e.kicked,kickSuppressionReason:null,pid:null,label:J(`${H(n)} (${e.node})`,Math.round(e.quiet_ms/6e4),t,!1,e.kicked)})}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),h.get(this.environmentId)===this&&h.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await o(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function re(i,e,n,t,s,r){const c=await o();(await c.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
|
|
6
6
|
WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
|
|
7
7
|
${r?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,s,...r?[t,s]:[])).changes>0&&await c.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}a(re,"withNotify");async function D(i,e){const n=await o(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await x()).has(e.node)||(await U(e.execution,{code:e.code,signal:e.signal}),!await M(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),d({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}a(D,"recordMachineBrokerExit");async function oe(i,e,n){const t=await(await o()).prepare(`SELECT x.execution_id, x.node_id FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
|
|
8
8
|
WHERE x.state = 'running' AND x.runner = 'machine' AND p.environment_id = ? AND x.started_at < ?`).all(i,n);for(const s of t)e.has(s.execution_id)||await D(i,{execution:s.execution_id,node:s.node_id,code:null,signal:null})}a(oe,"endUnlistedMachineExecutions");class Oe extends w{static{a(this,"MachineViewLink")}link;nodeId;ended=!1;failed=!1;channel=L();opened=performance.now();constructor(e,n){super(),this.link=e,this.nodeId=n,e.channels.set(this.channel,this),this.once("connect",()=>d({level:"info",event:"daemon.timing.machine_view_ready",node_id:n,fields:{channel:this.channel,open_to_ready_ms:this.sinceOpenMs()}}));const t=e.send({type:"view.open",channel:this.channel,node:n});d({level:"info",event:"daemon.timing.view_open_sent",node_id:n,fields:{channel:this.channel,sent:t,link_buffered_bytes:e.ws.bufferedAmount,send_sync_ms:this.sinceOpenMs()}}),t||queueMicrotask(()=>this.finish("machine link closed"))}sinceOpenMs(){return Math.round((performance.now()-this.opened)*10)/10}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const Me=a(i=>h.get(i)??null,"heldLinkOf"),ce=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function Ce(i){const e=ce.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Ce,"machineLinkEnvironment");async function Ue(i,e,n,t){const s=i.headers.authorization,r=/^Bearer (\S+)$/.exec(Array.isArray(s)?s[0]??"":s??"")?.[1];if(r===void 0||!await g(t,r))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};if(X(String(i.headers[G.toLowerCase()]??""),v())<0)return{status:426,text:"Upgrade Required",code:"machine_release_behind",message:v()};const c=new Date().toISOString(),l=await o(),u=await l.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
|
|
@@ -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
|
|
3
|
-
`)[0]??"").slice(0,200),o=
|
|
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
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
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.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
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",
|
|
@@ -290,7 +290,7 @@ export class InputController {
|
|
|
290
290
|
sent();
|
|
291
291
|
this.editor.setText('');
|
|
292
292
|
this.tui.requestRender();
|
|
293
|
-
void attachLocalFiles(expanded, request).then((final) => {
|
|
293
|
+
void attachLocalFiles(expanded, request, this.hooks.whenBrokerReady).then((final) => {
|
|
294
294
|
if (!deliver(final) && this.editor.getText().trim() === '') {
|
|
295
295
|
this.editor.setText(typed);
|
|
296
296
|
this.tui.requestRender();
|
|
@@ -51,12 +51,25 @@ function mib(bytes) {
|
|
|
51
51
|
export function hasLocalPaths(text) {
|
|
52
52
|
return findLocalPaths(text).length > 0;
|
|
53
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
|
+
}
|
|
54
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. */
|
|
55
|
-
export async function attachLocalFiles(text, request) {
|
|
61
|
+
export async function attachLocalFiles(text, request, brokerReady = () => Promise.resolve(true)) {
|
|
56
62
|
const matches = findLocalPaths(text);
|
|
57
63
|
if (matches.length === 0)
|
|
58
64
|
return text;
|
|
59
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
|
+
}
|
|
60
73
|
const sent = new Map();
|
|
61
74
|
const replaced = [];
|
|
62
75
|
for (const match of matches) {
|
|
@@ -84,7 +97,10 @@ export async function attachLocalFiles(text, request) {
|
|
|
84
97
|
replaced.push({ match, to: reply.path });
|
|
85
98
|
}
|
|
86
99
|
catch (error) {
|
|
87
|
-
|
|
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}).`);
|
|
88
104
|
}
|
|
89
105
|
}
|
|
90
106
|
let out = text;
|
|
@@ -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
|
}
|
|
@@ -93,6 +93,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
|
|
|
93
93
|
onColor: hooks.setChipColor,
|
|
94
94
|
onPromptSent: hooks.onPromptSent,
|
|
95
95
|
onMessageSent: hooks.onMessageSent,
|
|
96
|
+
whenBrokerReady: hooks.whenBrokerReady,
|
|
96
97
|
frecency: hooks.frecency,
|
|
97
98
|
knownRefNames: () => editor.getResolvedRefNames(),
|
|
98
99
|
// Global display toggles (Ctrl+O tools / Ctrl+T thinking) — pure render
|
|
@@ -462,9 +462,22 @@ onConnected) {
|
|
|
462
462
|
socket.send(frame);
|
|
463
463
|
reconnect.probe();
|
|
464
464
|
};
|
|
465
|
+
// Uploading a file needs the broker: a message naming one waits here for the first welcome, at most a minute.
|
|
466
|
+
let brokerReadyResolve = () => { };
|
|
467
|
+
const brokerReady = new Promise((resolve) => { brokerReadyResolve = resolve; });
|
|
468
|
+
const whenBrokerReady = () => {
|
|
469
|
+
if (welcomed)
|
|
470
|
+
return Promise.resolve(true);
|
|
471
|
+
if (settled)
|
|
472
|
+
return Promise.resolve(false);
|
|
473
|
+
let timer;
|
|
474
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(false), 60_000); timer.unref?.(); });
|
|
475
|
+
return Promise.race([brokerReady, timeout]).finally(() => clearTimeout(timer));
|
|
476
|
+
};
|
|
465
477
|
const onFirstWelcome = () => {
|
|
466
478
|
welcomed = true;
|
|
467
479
|
settled = true;
|
|
480
|
+
brokerReadyResolve(true);
|
|
468
481
|
for (const frame of heldFrames.splice(0))
|
|
469
482
|
socket.send(frame);
|
|
470
483
|
};
|
|
@@ -492,6 +505,7 @@ onConnected) {
|
|
|
492
505
|
},
|
|
493
506
|
onMessageSent: (text, viaSocket) => chatView.addPendingSend(text, viaSocket),
|
|
494
507
|
send: sendToBroker,
|
|
508
|
+
whenBrokerReady,
|
|
495
509
|
frecency,
|
|
496
510
|
});
|
|
497
511
|
const whip = () => {
|
|
@@ -912,6 +926,7 @@ onConnected) {
|
|
|
912
926
|
// Text sent while the dial was still running has no broker to hold it: deliver it as the wake message a parked viewer's own sends use.
|
|
913
927
|
// An engine command (`/x`, `!x`) is refused as a later parked submission is, and returned to the editor.
|
|
914
928
|
settled = true;
|
|
929
|
+
brokerReadyResolve(false);
|
|
915
930
|
chatView.stopResendingPendingSends();
|
|
916
931
|
const refused = [];
|
|
917
932
|
for (const frame of heldFrames.splice(0)) {
|
|
@@ -175,9 +175,10 @@ const nodeShow = defineLeaf({
|
|
|
175
175
|
hints.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${reports.map((r) => r['node_id']).join(', ')}).`);
|
|
176
176
|
hints.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${id}\`.`);
|
|
177
177
|
const result = { node, fault: node.fault ?? null, reports, managers, pending_crons, paths, follow_up: hints.join('\n') };
|
|
178
|
-
// The environment read answers 400 for a profile that runs on a machine
|
|
179
|
-
|
|
180
|
-
|
|
178
|
+
// The environment read answers 400 for a profile that runs on a machine, and 404 for a profile the caller cannot see
|
|
179
|
+
// (another app's): reading a node does not require its owning profile to be visible, so that is not a failure.
|
|
180
|
+
const inSandbox = node.runner === 'blaxel' || node.profile_id !== null && await client.getProfileEnvironment(node.profile_id).then(() => true, (err) => {
|
|
181
|
+
if (err instanceof ApiError && (err.status === 400 || err.status === 404))
|
|
181
182
|
return false;
|
|
182
183
|
return rethrowAsCliError(err);
|
|
183
184
|
});
|
|
@@ -164,7 +164,7 @@ export class BrokerClient extends EventEmitter {
|
|
|
164
164
|
const entry = this.pending.get(frame.id);
|
|
165
165
|
this.pending.delete(frame.id);
|
|
166
166
|
clearTimeout(entry.timer);
|
|
167
|
-
entry.reject(new Error(frame.message || `request failed: ${frame.code}`));
|
|
167
|
+
entry.reject(Object.assign(new Error(frame.message || `request failed: ${frame.code}`), { code: frame.code }));
|
|
168
168
|
return;
|
|
169
169
|
}
|
|
170
170
|
this.emit('frame', frame);
|
|
@@ -108,6 +108,7 @@ function rowFrom(r) {
|
|
|
108
108
|
parent: r['parent'] ?? null,
|
|
109
109
|
created: r['created'],
|
|
110
110
|
intent: r['intent'] ?? null,
|
|
111
|
+
cycle_pending: r['cycle_pending'] === 1,
|
|
111
112
|
frozen_at: r['frozen_at'] ?? null,
|
|
112
113
|
respawn_failures: r['respawn_failures'] ?? 0,
|
|
113
114
|
respawn_not_before: r['respawn_not_before'] ?? null,
|
|
@@ -153,7 +154,6 @@ async function metaFrom(r, worktree) {
|
|
|
153
154
|
fork_from: r['fork_from'] ?? null,
|
|
154
155
|
fork_source_file: r['fork_source_file'] ?? null,
|
|
155
156
|
passive_default: r['passive_default'] === 1,
|
|
156
|
-
cycle_pending: r['cycle_pending'] === 1,
|
|
157
157
|
model_override: r['model_override'] ?? null,
|
|
158
158
|
scopes: r['scopes_json'] == null ? null : JSON.parse(r['scopes_json']),
|
|
159
159
|
persona_ack: r['persona_ack_json'] == null ? undefined : JSON.parse(r['persona_ack_json']),
|
|
@@ -30,7 +30,7 @@ export function deliveryFrom(row) {
|
|
|
30
30
|
}
|
|
31
31
|
async function executionIsLive(db, nodeId, executionId, rejectRefresh) {
|
|
32
32
|
const row = await db.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
|
|
33
|
-
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh'" : ''}`).get(nodeId, executionId);
|
|
33
|
+
WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh' AND n.cycle_pending = 0" : ''}`).get(nodeId, executionId);
|
|
34
34
|
return row !== undefined;
|
|
35
35
|
}
|
|
36
36
|
async function nodeMailRows(db, nodeId, executionId, wake, freshIds, deferredRun = false) {
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 29;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -30,7 +30,7 @@ export const machineCheckoutHandlers = {
|
|
|
30
30
|
// ---------------------------------------------------------------------------------------------------------------- the control plane's side
|
|
31
31
|
/** Ask the Mac for the checkout chains of `dirs` and store the answers. A call that fails (offline, lost, refused) stores nothing and returns false. */
|
|
32
32
|
export async function warmMachineCheckouts(environment, dirs) {
|
|
33
|
-
const wanted = [...new Set(dirs.map((d) => resolve(d)))];
|
|
33
|
+
const wanted = [...new Set(dirs.map((d) => resolve(d)))].sort(); // one row order for every writer, so two warms of one Mac cannot deadlock
|
|
34
34
|
if (wanted.length === 0)
|
|
35
35
|
return true;
|
|
36
36
|
let answer;
|
|
@@ -81,20 +81,37 @@ function rewriteJsonPaths(text, map) {
|
|
|
81
81
|
return mapPath(map, text);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
-
/** A profile whose name
|
|
84
|
+
/** A profile whose name another profile already holds is renamed `<name>-<install id>` (staging only; runs before the pre-check), in its `profiles` row and in its `profile`
|
|
85
|
+
* object's handle. The name clashes when the person already uses it for another profile, or when the object's handle is held by any other live profile object: `objects_handle`
|
|
86
|
+
* is unique per type across the whole fleet, so another person's profile counts. Only a handle that is the profile's name moves (a cloud role's handle is the profile id).
|
|
87
|
+
* The new name is a function of the install, so a second load of the bundle derives the same one. Runs after `mapProfileIds`, which leaves the staged identity at the profile's id. */
|
|
85
88
|
export async function renameClashingProfiles(db, schema, target, installId, person) {
|
|
86
89
|
const S = (t) => sq(schema, t);
|
|
87
90
|
const profiles = await db.prepareUncached(`SELECT id, name FROM ${S('profiles')} ORDER BY id`).all();
|
|
88
91
|
let renamed = 0;
|
|
89
92
|
for (const profile of profiles) {
|
|
90
|
-
const
|
|
91
|
-
|
|
93
|
+
const object = await db.prepareUncached(`SELECT o.id FROM ${S('objects')} o JOIN ${S('identities')} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
94
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(profile.id, profile.name);
|
|
95
|
+
const sameName = await db.prepareUncached(`SELECT 1 AS found FROM ${sq(target, 'profiles')} WHERE person = ? AND name = ? AND id <> ?`).get(person, profile.name, profile.id);
|
|
96
|
+
const handleHeld = object === undefined ? undefined : await db.prepareUncached(`SELECT 1 AS found FROM ${sq(target, 'objects')} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(profile.name, object.id);
|
|
97
|
+
if (sameName === undefined && handleHeld === undefined)
|
|
92
98
|
continue;
|
|
93
|
-
|
|
99
|
+
const next = `${profile.name}-${installId}`;
|
|
100
|
+
await db.prepareUncached(`UPDATE ${S('profiles')} SET name = ? WHERE id = ?`).run(next, profile.id);
|
|
101
|
+
if (object !== undefined)
|
|
102
|
+
await db.prepareUncached(`UPDATE ${S('objects')} SET name = ? WHERE id = ?`).run(next, object.id);
|
|
94
103
|
renamed += 1;
|
|
95
104
|
}
|
|
96
105
|
return renamed;
|
|
97
106
|
}
|
|
107
|
+
/** A migrated usage charge (`legacy:` id, `importLegacyUsage`) has no install id, so two Macs of one person with usage in the same month and model produce one id with
|
|
108
|
+
* different amounts. A staged one whose id the target holds with a different payer, units or usd is renamed `<id>:install-<install id>`; one the target holds unchanged keeps its
|
|
109
|
+
* id and is skipped by the copy. A second load of the same bundle derives the same id. Runs before the pre-check. */
|
|
110
|
+
export async function renameClashingLegacyCharges(db, schema, target, installId) {
|
|
111
|
+
const done = await db.prepareUncached(`UPDATE ${sq(schema, 'charges')} s SET id = s.id || ':install-' || ?::text FROM ${sq(target, 'charges')} t
|
|
112
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(installId);
|
|
113
|
+
return Number(done.changes);
|
|
114
|
+
}
|
|
98
115
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
99
116
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
100
117
|
export async function fillEnvironments(tx, schema, target, source, person) {
|
|
@@ -44,7 +44,7 @@ function refreshFailure(error, served) {
|
|
|
44
44
|
return error;
|
|
45
45
|
return new RunError(503, 'upstream_model_unavailable', message.slice(0, 500), undefined, { served_model: served });
|
|
46
46
|
}
|
|
47
|
-
/** The account's access token, refreshed under the
|
|
47
|
+
/** The account's access token, refreshed under the account's refresh claim (no connection held during the vendor call) when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
|
|
48
48
|
export async function freshSubscriptionAccess(registry, provider, account, served, signal) {
|
|
49
49
|
if (account.expires > Date.now())
|
|
50
50
|
return account.access;
|
|
@@ -69,11 +69,11 @@ export class PoolCredentialStore {
|
|
|
69
69
|
return listedCredentials(stored, (providerId) => sizes.get(providerId) ?? 0);
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
|
-
* pi's
|
|
73
|
-
*
|
|
74
|
-
* expired account
|
|
75
|
-
* `invalid_grant`.
|
|
76
|
-
* back on exactly the account whose token was spent.
|
|
72
|
+
* pi's read-modify-write, chiefly its OAuth refresh. Running pi's `fn` and committing the result
|
|
73
|
+
* happen under the account's refresh claim, because a refresh token is single-use: two brokers
|
|
74
|
+
* refreshing the same expired account without it would both spend it and the loser would get a
|
|
75
|
+
* genuine `invalid_grant`. The commit is conditional on the spent token, so the refreshed token
|
|
76
|
+
* lands back on exactly the account whose token was spent.
|
|
77
77
|
*
|
|
78
78
|
* A managed provider with no pool account is NOT created here — pi must not be able to mint a
|
|
79
79
|
* managed account behind crouter's login surfaces, which own the account-identity gate.
|
|
@@ -7,11 +7,9 @@ export const YIELD_STALL_GRACE_MS = 3 * 60_000;
|
|
|
7
7
|
export const KILL_ESCALATE_MS = 20_000;
|
|
8
8
|
export const WEDGE_QUIET_MS = 20 * 60_000;
|
|
9
9
|
export const WEDGE_CPU_MAX_PERCENT = 2;
|
|
10
|
-
export function yieldStallVerdict(piPidAlive,
|
|
10
|
+
export function yieldStallVerdict(piPidAlive, busy, stalledFor) {
|
|
11
11
|
if (piPidAlive !== true)
|
|
12
12
|
return 'leave';
|
|
13
|
-
if (intent !== 'refresh')
|
|
14
|
-
return 'leave';
|
|
15
13
|
if (busy)
|
|
16
14
|
return 'leave';
|
|
17
15
|
if (stalledFor === null || stalledFor < YIELD_STALL_GRACE_MS)
|