@north-light/cli 0.3.699 → 0.3.701
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/api/client.d.ts +4 -0
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +263 -263
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/node-lifecycle-revive.d.ts +2 -10
- package/dist/commands/node-lifecycle-revive.js +1 -1
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/canvas/status-glyph.d.ts +9 -0
- package/dist/core/canvas/status-glyph.js +1 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.js +8 -8
- package/dist/core/graph/names.d.ts +1 -1
- package/dist/core/graph/names.js +10 -10
- package/dist/core/help.js +2 -2
- package/dist/core/permissions/ceiling.d.ts +1 -1
- package/dist/core/permissions/evaluator.d.ts +4 -6
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +2 -2
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/frame-client.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +8 -10
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-wedge.d.ts +20 -0
- package/dist/core/runtime/broker-wedge.js +2 -0
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/runner/machine/call.js +1 -1
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +1 -14
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +19 -3
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +38 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +12 -1
- package/dist/daemon/machine-link/holder.js +5 -4
- package/dist/daemon/machine-supervision.d.ts +17 -0
- package/dist/daemon/machine-supervision.js +1 -0
- package/dist/daemon/reconcilers/broker-supervision.d.ts +11 -14
- package/dist/daemon/reconcilers/broker-supervision.js +3 -4
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +1 -1
- package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
- package/packages/crouter-api/dist/commands/node-lifecycle-revive.js +14 -16
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +8 -0
- package/packages/crouter-api/dist/core/canvas/status-glyph.js +15 -0
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -0
- package/packages/crouter-api/dist/core/command.js +13 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -8
- package/packages/crouter-api/dist/core/help.js +1 -1
- package/packages/crouter-api/dist/core/permissions/ceiling.js +1 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +20 -12
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +26 -12
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +99 -0
- package/packages/crouter-api/dist/core/runtime/host.js +10 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +3 -3
- package/packages/crouter-api/dist/daemon/api/map.js +2 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +6 -2
- package/packages/crouter-api/dist/daemon/machine-link/frames.js +4 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +77 -6
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +61 -163
- 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/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +0 -5
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +0 -4
|
@@ -27,6 +27,11 @@ export type MachineFrame =
|
|
|
27
27
|
code: number | null;
|
|
28
28
|
signal: string | null;
|
|
29
29
|
}
|
|
30
|
+
/** Mac → holder, once per link open: the executions of every broker this machine runs for its canvas home. */
|
|
31
|
+
| {
|
|
32
|
+
type: 'running';
|
|
33
|
+
executions: string[];
|
|
34
|
+
}
|
|
30
35
|
/** Mac → holder: a report on a background job of a node whose broker is not running (the broker's own job reporter is gone with it). `request` is a `JobReportRequest` without `expected_execution_id`. */
|
|
31
36
|
| {
|
|
32
37
|
type: 'job.report';
|
|
@@ -45,6 +50,34 @@ export type MachineFrame =
|
|
|
45
50
|
message: string;
|
|
46
51
|
};
|
|
47
52
|
}
|
|
53
|
+
/** Mac → holder: the turn state of the brokers it runs, for its stuck-turn check; answered by `turns.answer` with the same `id`. */
|
|
54
|
+
| {
|
|
55
|
+
type: 'turns';
|
|
56
|
+
id: string;
|
|
57
|
+
brokers: Array<{
|
|
58
|
+
execution: string;
|
|
59
|
+
node: string;
|
|
60
|
+
}>;
|
|
61
|
+
}
|
|
62
|
+
/** holder → Mac: per execution still live for this machine, when its open turn last made progress (epoch ms, null when no turn is open), whether the node is
|
|
63
|
+
* refreshing, and whether it has a running bash job. */
|
|
64
|
+
| {
|
|
65
|
+
type: 'turns.answer';
|
|
66
|
+
id: string;
|
|
67
|
+
turns: Record<string, BrokerTurn>;
|
|
68
|
+
}
|
|
69
|
+
/** Mac → holder: a broker's turn made no progress past the stuck-turn limit; `kicked` when the Mac sent it SIGTERM. */
|
|
70
|
+
| {
|
|
71
|
+
type: 'wedge';
|
|
72
|
+
execution: string;
|
|
73
|
+
node: string;
|
|
74
|
+
since: number;
|
|
75
|
+
quiet_ms: number;
|
|
76
|
+
cpu_percent: number | null;
|
|
77
|
+
has_descendants: boolean | null;
|
|
78
|
+
kick_attempted: boolean;
|
|
79
|
+
kicked: boolean;
|
|
80
|
+
}
|
|
48
81
|
/** holder → Mac: open a viewer channel to `node`'s view.sock. */
|
|
49
82
|
| {
|
|
50
83
|
type: 'view.open';
|
|
@@ -68,6 +101,11 @@ export type MachineFrame =
|
|
|
68
101
|
channel: string;
|
|
69
102
|
error?: string;
|
|
70
103
|
};
|
|
104
|
+
export interface BrokerTurn {
|
|
105
|
+
since: number | null;
|
|
106
|
+
refresh: boolean;
|
|
107
|
+
jobs: boolean;
|
|
108
|
+
}
|
|
71
109
|
export declare const LINK_MAX_PAYLOAD_BYTES: number;
|
|
72
110
|
/** WebSocket close codes of the holder: a newer link took the environment's row; the credential is revoked (the Mac does not reconnect with it). */
|
|
73
111
|
export declare const CLOSE_SUPERSEDED = 4001;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var u=(n,l)=>s(n,"name",{value:l,configurable:!0});const a=33554432,f=4001,y=4003,c=u(n=>n===null||typeof n=="number","nullableNumber");function p(n){const l=Array.isArray(n)?Buffer.concat(n):Buffer.isBuffer(n)?n:Buffer.from(new Uint8Array(n));try{const e=JSON.parse(l.toString("utf8"));if(typeof e!="object"||e===null)return null;const r=u((...t)=>t.every(o=>typeof e[o]=="string"),"strings");switch(e.type){case"call":return r("call_id","op")?e:null;case"result":return r("call_id")&&(e.ok===!0||e.ok===!1&&r("error"))?e:null;case"exit":return r("execution","node")&&c(e.code)&&(e.signal===null||typeof e.signal=="string")?e:null;case"job.report":return r("id","node","job")&&typeof e.request=="object"&&e.request!==null?e:null;case"running":return Array.isArray(e.executions)&&e.executions.every(t=>typeof t=="string")?e:null;case"turns":return r("id")&&Array.isArray(e.brokers)&&e.brokers.every(t=>typeof t=="object"&&t!==null&&typeof t.execution=="string"&&typeof t.node=="string")?e:null;case"turns.answer":return r("id")&&typeof e.turns=="object"&&e.turns!==null?e:null;case"wedge":return r("execution","node")&&typeof e.since=="number"&&typeof e.quiet_ms=="number"?e:null;case"job.reported":return r("id")?e:null;case"view.open":return r("channel","node")?e:null;case"view.ready":case"view.close":return r("channel")?e:null;case"view.data":return r("channel","bytes")?e:null;default:return null}}catch{return null}}u(p,"parseFrame");export{y as CLOSE_REVOKED,f as CLOSE_SUPERSEDED,a as LINK_MAX_PAYLOAD_BYTES,p as parseFrame};
|
|
@@ -23,6 +23,7 @@ export declare class HeldLink extends EventEmitter {
|
|
|
23
23
|
private claiming;
|
|
24
24
|
private closed;
|
|
25
25
|
private alive;
|
|
26
|
+
private readonly openedAt;
|
|
26
27
|
readonly channels: Map<string, MachineViewLink>;
|
|
27
28
|
constructor(environmentId: string, generation: number, ws: WebSocket, token: string);
|
|
28
29
|
start(): void;
|
|
@@ -46,6 +47,13 @@ export declare class HeldLink extends EventEmitter {
|
|
|
46
47
|
private onMessage;
|
|
47
48
|
/** Store a job report the Mac sent for a node of this environment and answer with what the report route would have. */
|
|
48
49
|
private storeJobReport;
|
|
50
|
+
/** The node row of a broker this machine runs, when that broker is the node's live execution and the node runs in this link's environment. */
|
|
51
|
+
private ownNode;
|
|
52
|
+
/** The turn state the Mac's stuck-turn check needs, for each of its brokers that is its node's live execution. A turn's progress from before the node's
|
|
53
|
+
* latest launch is not this broker's, so it reads as no open turn. */
|
|
54
|
+
private turns;
|
|
55
|
+
/** A stuck turn the Mac found: recorded and announced once per turn, as for a broker this control plane runs. */
|
|
56
|
+
private recordWedge;
|
|
49
57
|
private teardown;
|
|
50
58
|
}
|
|
51
59
|
/** A broker exit the Mac reported: what `Fleet.onChildExit` does for a local child. Only a live machine execution of this node whose profile
|
|
@@ -62,10 +70,13 @@ export declare function recordMachineBrokerExit(environmentId: string, exit: {
|
|
|
62
70
|
/** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
|
|
63
71
|
export declare class MachineViewLink extends EventEmitter implements BrokerViewLink {
|
|
64
72
|
private readonly link;
|
|
73
|
+
readonly nodeId: string;
|
|
65
74
|
private ended;
|
|
66
75
|
private failed;
|
|
67
|
-
|
|
76
|
+
readonly channel: `${string}-${string}-${string}-${string}-${string}`;
|
|
77
|
+
private readonly opened;
|
|
68
78
|
constructor(link: HeldLink, nodeId: string);
|
|
79
|
+
sinceOpenMs(): number;
|
|
69
80
|
get destroyed(): boolean;
|
|
70
81
|
write(line: string | Buffer): boolean;
|
|
71
82
|
destroy(): this;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{importedNodesHeld as x}from"../reconcilers/live-obligation.js";import{EventEmitter as w}from"node:events";import{hostname as I}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as T,WebSocketServer as O}from"ws";import{openDb as o}from"../../core/canvas/db.js";import{emitEvent as d}from"../../core/events/emit.js";import{endExecution as M,liveExecutionForNode as C,recordExecutionExit as U}from"../../core/canvas/executions.js";import{getNode as W}from"../../core/canvas/index.js";import{fullName as H}from"../../core/canvas/labels.js";import{readLiveTurn as P}from"../../core/canvas/recovery.js";import{runningJobs as F}from"../../core/graph/jobs.js";import{readSupervisionMark as j,writeSupervisionMark as $}from"../park-pending.js";import{reportWedge as B,wedgeLabel as J}from"../reconcilers/broker-supervision.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as K}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as V}from"../broker-signals/bus.js";import{verifyMachineCredential as g}from"./credential.js";import{compareReleaseVersions as X,RUNTIME_VERSION_HEADER as G}from"../../api/runtime-version.js";import{crtrVersion as v}from"../../shared/crtr-version.js";import{CLOSE_REVOKED as q,CLOSE_SUPERSEDED as N,LINK_MAX_PAYLOAD_BYTES as z,parseFrame as Y}from"./frames.js";const Z=45e3,Q=15e3,ee=3e4,ne=1e3,S=10,te=new O({noServer:!0,maxPayload:z}),h=new Map,ie="unroutable:";let A;const Te=a(i=>{A=i},"setApiAddress"),se=a(()=>process.env.CRTR_API_ADDRESS??A??`${ie}${I()}:${process.pid}`,"apiAddress"),_=a(()=>new Date(Date.now()+Z).toISOString(),"lease");class ae extends w{static{a(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;openedAt=new Date().toISOString();channels=new Map;constructor(e,n,t,s){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=s}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},Q)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},ee)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},ne)),V.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:a(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){d({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==T.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await o(),n=_();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(N,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(q,"revoked")}async credentialValid(){return await g(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await o()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
|
|
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,
|
|
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 = '{}'
|
|
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
|
+
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, ?, ?, ?)
|
|
8
9
|
ON CONFLICT (environment) DO UPDATE SET generation = machine_links.generation + 1, api_address = EXCLUDED.api_address, connected_at = EXCLUDED.connected_at, lease_expires_at = EXCLUDED.lease_expires_at
|
|
9
|
-
RETURNING generation`).get(t,
|
|
10
|
+
RETURNING generation`).get(t,se(),c,_());await l.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(c,t);const f=Number(u.generation);return e.destroyed?(await l.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,f),null):(te.handleUpgrade(i,e,n,k=>{const m=new ae(t,f,k,r),y=h.get(t);h.set(t,m),y?.ws.close(N,"superseded"),m.start(),m.claim().catch(R=>d({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:R}))}),null)}a(Ue,"handleMachineLinkUpgrade");export{ae as HeldLink,Z as LINK_LEASE_MS,ee as LINK_PING_MS,Q as LINK_RENEW_MS,Oe as MachineViewLink,ie as UNROUTABLE_PREFIX,se as apiAddress,Ue as handleMachineLinkUpgrade,Me as heldLinkOf,Ce as machineLinkEnvironment,D as recordMachineBrokerExit,Te as setApiAddress};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { sampleBrokerTree } from '../core/runtime/broker-wedge.js';
|
|
2
|
+
import type { MachineLink } from './machine-link/client.js';
|
|
3
|
+
export declare const SUPERVISION_TICK_MS = 15000;
|
|
4
|
+
export interface MachineSupervisionDeps {
|
|
5
|
+
link: Pick<MachineLink, 'turns' | 'reportWedge' | 'reportExit'>;
|
|
6
|
+
stop: (execution: string, node: string) => Promise<unknown>;
|
|
7
|
+
brokers?: () => Promise<Array<{
|
|
8
|
+
pid: number;
|
|
9
|
+
execution: string;
|
|
10
|
+
node: string;
|
|
11
|
+
command: string;
|
|
12
|
+
}>>;
|
|
13
|
+
sample?: typeof sampleBrokerTree;
|
|
14
|
+
signal?: (pid: number, signal: NodeJS.Signals) => void;
|
|
15
|
+
}
|
|
16
|
+
/** One check over this home's brokers; returns the function to call each tick with the current time. */
|
|
17
|
+
export declare function machineSupervision(deps: MachineSupervisionDeps): (now: number) => Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var T=Object.defineProperty;var h=(t,a)=>T(t,"name",{value:a,configurable:!0});import{emitEvent as M}from"../core/events/emit.js";import{crtrHome as x}from"../core/canvas/paths.js";import{brokerCommandDeclaresCanvasHome as N}from"../core/runtime/broker-ownership.js";import{sampleBrokerTree as v,wedgeVerdict as b,WEDGE_QUIET_MS as w,YIELD_STALL_GRACE_MS as y}from"../core/runtime/broker-wedge.js";import{findBrokers as D}from"../core/runtime/runner/machine/executor.js";const V=15e3,G=6e4;function Y(t){const a=t.brokers??D,g=t.sample??v,S=t.signal??((i,o)=>process.kill(i,o));let k=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY;const d=new Map,r=new Map;let _=new Map;return async i=>{i-k>G&&(u=i),k=i;const o=(await a()).filter(e=>N(e.command,x()));for(const[e,n]of _)o.some(c=>c.execution===e)||t.link.reportExit({execution:e,node:n,code:null,signal:null});_=new Map(o.map(e=>[e.execution,e.node]));const m=o.length===0?{}:await t.link.turns(o.map(({execution:e,node:n})=>({execution:e,node:n})));if(m===void 0){u=i;return}for(const e of[...d.keys(),...r.keys()])m[e]===void 0&&(d.delete(e),r.delete(e));for(const{pid:e,execution:n,node:c}of o){const s=m[n];if(s===void 0)continue;if(!s.refresh||s.since!==null)r.delete(n);else if(!r.has(n))r.set(n,i);else if(i-Math.max(r.get(n),u)>=y){r.delete(n),M({level:"warn",event:"broker.yield_stall.machine_stop",node_id:c,fields:{execution:n}}),await t.stop(n,c);continue}if(s.since===null||s.jobs||d.get(n)===s.since)continue;const p=i-Math.max(s.since,u);if(p<w)continue;const l=await g(e);if(b({busy:!0,quietForMs:p,cpuPercent:l?.cpuPercent??null,hasDescendants:l?.hasDescendants??null})!=="wedged")continue;d.set(n,s.since);const E=l?.hasDescendants===!1;let I=!1;if(E&&(await a()).some(f=>f.pid===e&&f.execution===n))try{S(e,"SIGTERM"),I=!0}catch(f){M({level:"error",event:"broker.wedge.signal_failed",node_id:c,error:f,fields:{pid:e,signal:"SIGTERM"}})}t.link.reportWedge({execution:n,node:c,since:s.since,quiet_ms:p,cpu_percent:l?.cpuPercent??null,has_descendants:l?.hasDescendants??null,kick_attempted:E,kicked:I})}}}h(Y,"machineSupervision");export{V as SUPERVISION_TICK_MS,Y as machineSupervision};
|
|
@@ -35,9 +35,6 @@ export interface SaturationContext {
|
|
|
35
35
|
waitingOnMail: number;
|
|
36
36
|
};
|
|
37
37
|
}
|
|
38
|
-
export declare const YIELD_STALL_GRACE_MS: number;
|
|
39
|
-
export declare const WEDGE_QUIET_MS: number;
|
|
40
|
-
export declare const WEDGE_CPU_MAX_PERCENT = 2;
|
|
41
38
|
/** Whether a fatal provider fault ends the node: a parentless terminal node's run has failed,
|
|
42
39
|
* and an app run's root (resident, `run_id` = its own id) settles once a model call is finally refused
|
|
43
40
|
* `cap_exhausted` (D2-VOC-18), `payment_refused` or `all_routes_exhausted` (`nothing_left`), so the app sees the refusal instead of a run left idle. Any other
|
|
@@ -50,16 +47,19 @@ export declare function settlesOnFatalProviderFault(meta: {
|
|
|
50
47
|
} | null, code: string | undefined): boolean;
|
|
51
48
|
export declare function unattendedParkMsForDaemon(): number;
|
|
52
49
|
export declare function parkSummaryGraceMsForDaemon(): number;
|
|
53
|
-
|
|
54
|
-
export declare function
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
quietForMs: number
|
|
50
|
+
/** The notice for a stuck turn: what the supervisor saw and what it did about it. */
|
|
51
|
+
export declare function wedgeLabel(who: string, minutes: number, hasDescendants: boolean, unproven: boolean, kicked: boolean): string;
|
|
52
|
+
/** Record and announce a wedged broker: the event, the fault, and the notice to its managers. */
|
|
53
|
+
export declare function reportWedge(id: string, r: {
|
|
54
|
+
quietForMs: number;
|
|
58
55
|
cpuPercent: number | null;
|
|
59
56
|
hasDescendants: boolean | null;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
57
|
+
kickAttempted: boolean;
|
|
58
|
+
kicked: boolean;
|
|
59
|
+
kickSuppressionReason: string | null;
|
|
60
|
+
pid: number | null;
|
|
61
|
+
label: string;
|
|
62
|
+
}): Promise<void>;
|
|
63
63
|
export declare class BrokerSupervisionReconciler {
|
|
64
64
|
/** SIGTERM times of yield-stalled brokers this process signalled; the stall's start is `nodes.stall_noticed_at`. */
|
|
65
65
|
private readonly yieldTermedAt;
|
|
@@ -100,10 +100,7 @@ export declare class BrokerSupervisionReconciler {
|
|
|
100
100
|
private handleRemoteWedge;
|
|
101
101
|
private handleYieldStall;
|
|
102
102
|
private signalYieldStall;
|
|
103
|
-
private readTreeSample;
|
|
104
103
|
private handleWedgeDetection;
|
|
105
|
-
/** Record and announce a wedged broker: the event, the fault, and the notice to its managers. */
|
|
106
|
-
private reportWedge;
|
|
107
104
|
/** Publish a fatal provider fault's notice once per episode and, for a node that settles on it, end the node.
|
|
108
105
|
* The notices, the `notified_since` mark and the terminal transition commit in one write, so a daemon exit
|
|
109
106
|
* leaves the fault either fully announced or fully unannounced. The daemon registers this as the announcer
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
var j=Object.defineProperty;var m=(a,e)=>j(a,"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 P,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as x}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 ie,listUnnotifiedFatalFaultNodes as ae,markFaultNotified as se,readFault as G,readLiveTurn as F,recordFault as oe}from"../../core/canvas/recovery.js";import{errorClassFromFault as le}from"../../core/fault-classifier.js";import{nextFaultRetry as de}from"../../core/runtime/fault-recovery.js";import{publishNotice as L}from"../../core/runtime/close.js";import{openDb as O,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 C,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 Pe}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as $e}from"../../core/runtime/fleet.js";import{readConfig as Me}from"../../core/config.js";import{beginPendingPark as Ae,clearSupervisionMark as h,consumePendingPark as $,pendingParkIds as Ee,pendingParkStartedAt as Ne,readSupervisionMark as M,writeSupervisionMark as A}from"../park-pending.js";import{shouldParkAfterSummary as Re}from"../park-activity.js";import{applyParkEvent as E,noticeUnfinishedIdle as Ie,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Fe}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as Oe}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Ce,envTestUnattendedParkMs as De,parkSummaryGraceMs as We,envUnattendedParkMs as Be}from"../../shared/env.js";const R=ee(Z);async function Ge(a){return!await ie(a)&&((await Fe(a))?.trim()??"")!==""}m(Ge,"awaitsBirthTurn");async function q(a){const e=await C(a);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}m(q,"remoteExecutionOf");async function Le(a){return(await F(a))?.busy===!0}m(Le,"liveBusy");async function xt(a){const e=(await F(a))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}m(xt,"liveTurnProgressMs");function U(a,e){return e===null?null:`${a}:${e}`}m(U,"incarnationOf");async function S(a){const e=await F(a.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=a.launched_at===null||a.launched_at===void 0?Number.NaN:Date.parse(a.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}m(S,"busySinceForIncarnation");const W=3*6e4,Y=2e4,I=20*6e4,qe=2,Ue=5*6e4;function Ye(a,e){return a===null||a.parent!=null?!1:a.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&a.run_id===a.node_id}m(Ye,"settlesOnFatalProviderFault");function He(){const a=Be();if(a!==void 0)return a;const e=Me("user").lifecycle.unattendedParkMs;return Ce()?De()??e:e}m(He,"unattendedParkMsForDaemon");function H(){return We()}m(H,"parkSummaryGraceMsForDaemon");function V(a,e,t,r){return a!==!0||e!=="refresh"||t?"leave":r===null||r<W?"pending":"kill"}m(V,"yieldStallVerdict");function Ve(a){return!a.busy||a.quietForMs===null||a.quietForMs<I?"leave":a.cpuPercent===null||a.hasDescendants!==!1&&a.cpuPercent>qe?"pending":"wedged"}m(Ve,"wedgeVerdict");function K(a){const e=new Map,t=new Map;for(const r of a.split(`
|
|
2
|
-
`)
|
|
3
|
-
`)
|
|
4
|
-
`)[0]??"").slice(0,200),s=r.providerError,p=s===void 0?"":` Provider: ${s.provider}/${s.model}.`+(s.status===void 0?"":` HTTP status: ${s.status}.`)+(s.errno===void 0?"":` Errno: ${s.errno}.`)+(s.code===void 0?"":` Code: ${s.code}.`)+(s.body===void 0?"":` Body: ${s.body.slice(0,200)}.`)+(s.ratelimit===void 0?"":` Rate limit: ${s.ratelimit.scope??"account"}${s.ratelimit.claim===void 0?"":` (${s.ratelimit.claim})`}${s.ratelimit.model===void 0?"":` on ${s.ratelimit.model}`}.`),u=r.kind==="context-overflow",w=Ye(i,typeof s?.code=="string"?s.code:void 0),v=u||w,k=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: ${d}`:`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. "+(l?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${d}.${p}`,y=u?"failed":"hit a fatal provider fault",b=new Set((await ne(e)).map(_=>_.node_id)),T=await fe(await O(),await ue(await O(),e)),N=[{relation:"Child",recipients:T.filter(_=>b.has(_))},{relation:"Watched node",recipients:T.filter(_=>!b.has(_))}];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:_,recipients:g}of N)g.length!==0&&await L(e,"notice.crash",`${_} ${y} \u2014 ${o} (${e}) ${k}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:r.kind,message:d,...s===void 0?{}:{provider_error:s}},"normal",null,g);await se(r.faultId),t&&v&&await re(e,"crash",{reason:u?"context_overflow":s?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:r.message,fault_kind:r.kind,error_class:le(r).class,...typeof s?.code=="string"?{provider_code:s.code}:{},...s?.payment===void 0?{}:{payment:s.payment}}}})}),t&&v&&this.teardownBroker(e,n).then(_=>{_.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:_.error??new Error("Broker teardown not confirmed")})},_=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:_}))}}export{Ft as BrokerSupervisionReconciler,qe as WEDGE_CPU_MAX_PERCENT,I as WEDGE_QUIET_MS,W as YIELD_STALL_GRACE_MS,H as parkSummaryGraceMsForDaemon,Ye as settlesOnFatalProviderFault,Ke as sumTreeCpu,ze as treeHasDescendants,He as unattendedParkMsForDaemon,Ve as wedgeVerdict,V as yieldStallVerdict};
|
|
1
|
+
var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as ae}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as re,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await re(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,a=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(a)||t<a?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,a,r){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return a?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":r?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,a)=>{if(process.platform==="linux"&&J(Q)){if(a!=="SIGTERM"&&a!=="SIGKILL")throw new Error(`unsupported launcher signal ${a}`);return X({operation:"stop",pid:t,signal:a}).then(()=>{})}process.kill(t,a)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const a=He();for(const r of await ie())t.held.has(r)||await D.fresh(async()=>{try{await this.handleFatalFault(r)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(r)?{node_id:r}:{fields:{affected_node_id:r}},error:n})}});for(const r of t.rows){const n=r.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||r.status!=="active"&&r.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(r,s,t.fleet,e),await this.handleWedgeDetection(r,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(r,d,e),await this.handleRemoteWedge(r,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,a)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const r of await Pe())await t.fleet.has(r)||await T(r);await ke(e)}async parkResetCondition(e,t,a,r){if(t.pi_session_id==null||t.pi_pid!==a||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,r)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,a,r,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,a,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,r);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,r);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,r);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,r);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,r)))}}async requestParkSummary(e,t){try{const a=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:a}})}catch(a){if(await T(e)===void 0)return;if(a instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:a})}}async warnOverCapInTmux(e,t,a){const r=Date.now();if(r-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=r;const{warning:n,automaticReviveCap:s}=t,d=a.stalled+a.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:a.stalled,frozen_waiting_on_mail:a.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${a.stalled} stalled, ${a.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
+
`).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const a=await he(e.runner).stop(e,{reason:t});return a.confirmed?await me(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:a.error}),a}async handleRemoteYieldStall(e,t,a){const r=e.node_id;if(e.intent!=="refresh"||await b(e)!==null){await h(r,"stall_noticed_at");return}const n=await A(r,"stall_noticed_at");if(n===void 0){await I(r,"stall_noticed_at",a);return}q(!0,e.intent,!1,a-n)==="kill"&&(await N(r))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(r)?{node_id:r}:{},fields:{...c(r)?{}:{affected_node_id:r},execution_id:t.executionId,elapsed_ms:a-n,grace_ms:U}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,a){const r=e.node_id,n=await b(e);if(n===null){await h(r,"wedge_noticed_at");return}const s=a-n;if(s<O)return;const d=await S(r);if(d===null||(await N(r))?.executionId!==t.executionId||await b(d)!==n||await A(r,"wedge_noticed_at")===n)return;await I(r,"wedge_noticed_at",n);const l=Math.round(s/6e4);await K(r,{quietForMs:s,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${$(d)} (${r}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${l}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,a,r){const n=e.node_id,s=V(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"||await b(e)!==null||s===null){await h(n,"stall_noticed_at"),s!==null&&this.yieldTermedAt.delete(s);return}const d=await A(n,"stall_noticed_at");if(d===void 0){await I(n,"stall_noticed_at",r);return}const l={since:d,termedAt:this.yieldTermedAt.get(s)};if(q(!0,e.intent,!1,r-l.since)!=="kill")return;const o=await S(n);if(!(a.get(n)!==t||o?.pi_pid!==t.pid||o.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(l.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(s,r),l.termedAt=r,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:r-l.since,grace_ms:U}})}else r-l.termedAt>=G&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:r-l.termedAt,grace_ms:G,stall_elapsed_ms:r-l.since}})}async signalYieldStall(e,t,a){try{return await this.signal(t,a),!0}catch(r){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:r,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:a}}),!1}}async handleWedgeDetection(e,t,a,r){const n=e.node_id,s=V(t.pid,e.pi_pid_identity),d=await b(e);if(d===null||s===null){await h(n,"wedge_noticed_at");return}const l=r-d,o=l>=O?await this.sampleTree(t.pid):null,p=await S(n),u=p===null?null:await b(p);if(a.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==d)return;const w=o?.cpuPercent??null,k=o?.hasDescendants??null;if(Ge({busy:!0,quietForMs:l,cpuPercent:w,hasDescendants:k})!=="wedged"||await A(n,"wedge_noticed_at")===d)return;await I(n,"wedge_noticed_at",d);const v=$(p),E=Math.round((l??O)/6e4),g=k??!0,y=!g&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let M=!1,m=!1;if(!g&&y===null){M=!0;try{await this.signal(t.pid,"SIGTERM"),m=!0}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}})}}const P=Ke(`${v} (${n})`,E,g,y!==null,m);await K(n,{quietForMs:l,cpuPercent:w,hasDescendants:g,kickAttempted:M,kicked:m,kickSuppressionReason:y,pid:t.pid,label:P})}async handleFatalFault(e,t=!0){const a=await L(e);if(a===null||a.retry.disposition!=="fatal"||a.link!=="pi\u2192provider"||a.notifiedSince===a.since)return;const r=await S(e),n=await Y(e),s=r!==null?$(r):e,d=a.kind==="auth",l=(a.message.split(`
|
|
3
|
+
`)[0]??"").slice(0,200),o=a.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(o.ratelimit===void 0?"":` Rate limit: ${o.ratelimit.scope??"account"}${o.ratelimit.claim===void 0?"":` (${o.ratelimit.claim})`}${o.ratelimit.model===void 0?"":` on ${o.ratelimit.model}`}.`),u=a.kind==="context-overflow",w=Ve(r,typeof o?.code=="string"?o.code:void 0),k=u||w,v=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${l}`:`got a non-retryable ${a.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(d?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${l}.${p}`,E=u?"failed":"hit a fatal provider fault",g=new Set((await ne(e)).map(m=>m.node_id)),y=await fe(await x(),await ue(await x(),e)),M=[{relation:"Child",recipients:y.filter(m=>g.has(m))},{relation:"Watched node",recipients:y.filter(m=>!g.has(m))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:a.kind,link:a.link,terminal_overflow:u,terminal_provider_fault:w}}),await ce(async()=>{for(const{relation:m,recipients:P}of M)P.length!==0&&await W(e,"notice.crash",`${m} ${E} \u2014 ${s} (${e}) ${v}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:a.kind,message:l,...o===void 0?{}:{provider_error:o}},"normal",null,P);await oe(a.faultId),t&&k&&await ae(e,"crash",{reason:u?"context_overflow":o?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a.message,fault_kind:a.kind,error_class:de(a).class,...typeof o?.code=="string"?{provider_code:o.code}:{},...o?.payment===void 0?{}:{payment:o.payment}}}})}),t&&k&&this.teardownBroker(e,n).then(m=>{m.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m.error??new Error("Broker teardown not confirmed")})},m=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m}))}}export{Nt as BrokerSupervisionReconciler,H as parkSummaryGraceMsForDaemon,K as reportWedge,Ve as settlesOnFatalProviderFault,He as unattendedParkMsForDaemon,Ke as wedgeLabel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var d=(s,
|
|
1
|
+
var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t!==null&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,i){await this.pass(t,{rows:[e],fleet:i})}async pass(t,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,i))}catch(a){const l=n.node_id;E({level:a instanceof R?"warn":"error",event:a instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(l)?{node_id:l}:{fields:{affected_node_id:l}},error:a})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:i})}async classifyRow(t,e,i,n){const a=e.node_id;if(X(e)){if(H(e,await i.fleet.has(a)))return;if(S(e)&&!await i.fleet.has(a)&&!f(e.profile_id)&&!await I(a)&&!k(e,t)&&await m(a)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(a);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(a):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(a)){const r=await p(a);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(a))try{if(await Q(r)==="lost")return}catch(o){if(o instanceof x)return;throw o}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(a)){f(e.profile_id)?await i.fleet.interruptForProfilePause(a):await this.thawMark(e);return}}if(await K(a,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(a);return}if(await I(a))return;const l=e.pi_pid==null?await v(a):null,u=l!==null&&D(l),h=l!==null&&!u&&M(l),_=e.pi_pid!=null?await b(a):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(a)){const r=_??l;r!==null&&await P(r.executionId,{reason:"observed-dead"});const o=await p(a);if(o!==null&&o.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await m(a)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(a)||Z(e,t,await v(a)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:a}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await z(a),(await A(a))?.interrupted===!0,await U(a));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(a),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.701",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.701",
|
|
160
|
+
"@north-light/plugin": "0.3.701",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -338,6 +338,10 @@ export class CrtrClient {
|
|
|
338
338
|
forkNode(id) {
|
|
339
339
|
return this.request('POST', routes.nodeFork(this.nodePath(id)), {});
|
|
340
340
|
}
|
|
341
|
+
/** Stop a Mac-run node's broker parked on an eligible provider fault, so the daemon resumes it (`revive --now`). */
|
|
342
|
+
kickNode(id) {
|
|
343
|
+
return this.request('POST', routes.nodeKick(this.nodePath(id)), {});
|
|
344
|
+
}
|
|
341
345
|
reviveNode(id, req) {
|
|
342
346
|
return this.request('POST', routes.nodeRevive(this.nodePath(id)), req ?? {});
|
|
343
347
|
}
|
|
@@ -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.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.66';
|
|
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`. */
|
|
@@ -63,6 +63,7 @@ export const routes = {
|
|
|
63
63
|
// Node lifecycle actions
|
|
64
64
|
nodeFork: (id) => `${V}/nodes/${id}/fork`,
|
|
65
65
|
nodeRevive: (id) => `${V}/nodes/${id}/revive`,
|
|
66
|
+
nodeKick: (id) => `${V}/nodes/${id}/kick`,
|
|
66
67
|
nodeRelaunchRoot: (id) => `${V}/nodes/${id}/relaunch-root`,
|
|
67
68
|
nodeBrokerSessionBound: (id) => `${V}/nodes/${id}/broker/session-bound`,
|
|
68
69
|
nodeBrokerCycleStart: (id) => `${V}/nodes/${id}/broker/cycle-start`,
|
|
@@ -130,7 +130,7 @@ onConnected) {
|
|
|
130
130
|
cwd: meta.cwd,
|
|
131
131
|
palette: pal,
|
|
132
132
|
hideThinking: true,
|
|
133
|
-
banner: croutonBannerLines(buildBannerInfo(meta)),
|
|
133
|
+
banner: [...croutonBannerLines(buildBannerInfo(meta)), pal.muted(`Older messages: crtr canvas read ${nodeId}`)],
|
|
134
134
|
// Local only: a remote attach cannot read this canvas's ticket dirs, so it
|
|
135
135
|
// has nothing to render a page block from.
|
|
136
136
|
inlinePageBlocks: !remote,
|
|
@@ -192,7 +192,8 @@ const nodeShow = defineLeaf({
|
|
|
192
192
|
const isRemoteShow = remoteShowResults.has(r);
|
|
193
193
|
const alive = isRemoteShow
|
|
194
194
|
? 'remote (liveness not checked locally)'
|
|
195
|
-
:
|
|
195
|
+
: node['runner'] === 'machine' ? 'on a Mac (liveness not checked locally)'
|
|
196
|
+
: sandboxShowResults.has(r) ? 'in a cloud sandbox (liveness not checked locally)' : (isPidAlive(pid) ? 'alive' : 'dead');
|
|
196
197
|
const intent = node['intent'] ? `/${String(node['intent'])}` : '';
|
|
197
198
|
const fault = r['fault'];
|
|
198
199
|
const parts = [];
|
|
@@ -34,22 +34,8 @@ import { cliClient, rethrowAsCliError } from './api-client.js';
|
|
|
34
34
|
// imports all reached the db barrel and are replaced by the client call + helpers below.
|
|
35
35
|
import { recordedPidLiveness } from '../core/canvas/pid.js';
|
|
36
36
|
import { fullName } from '../core/canvas/labels.js';
|
|
37
|
-
import {
|
|
38
|
-
|
|
39
|
-
* (kick it early instead of waiting out the schedule), or any fault the
|
|
40
|
-
* canvas dashboard flags "needs you" (`faultNeedsYou`, status-glyph.ts) — the
|
|
41
|
-
* disposition that otherwise has NO sanctioned recovery verb.
|
|
42
|
-
* Both are scoped to `pi→provider`: refuses a client-owned auto retry
|
|
43
|
-
* (redialing) already in flight, and refuses any OTHER link — notably a
|
|
44
|
-
* `daemon→node` wedge fault, which --now can't clear (SIGTERM doesn't touch
|
|
45
|
-
* the runaway subprocess; see `wedged-child-on-runaway-bash`). */
|
|
46
|
-
export function isNowEligibleFault(fault) {
|
|
47
|
-
if (fault === null || fault.link !== 'pi→provider')
|
|
48
|
-
return false;
|
|
49
|
-
if (faultNeedsYou(fault))
|
|
50
|
-
return true;
|
|
51
|
-
return fault.retry.by === 'daemon';
|
|
52
|
-
}
|
|
37
|
+
import { isNowEligibleFault } from '../core/canvas/status-glyph.js';
|
|
38
|
+
export { isNowEligibleFault };
|
|
53
39
|
export const nodeReviveLeaf = defineLeaf({
|
|
54
40
|
name: 'revive',
|
|
55
41
|
description: 'reopen a window for a done/idle/dead/canceled node',
|
|
@@ -148,6 +134,18 @@ export const nodeReviveLeaf = defineLeaf({
|
|
|
148
134
|
catch (e) {
|
|
149
135
|
rethrowAsCliError(e);
|
|
150
136
|
}
|
|
137
|
+
if (detail.runner === 'machine') {
|
|
138
|
+
try {
|
|
139
|
+
await client.kickNode(nodeId);
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
rethrowAsCliError(e);
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
kicked: true,
|
|
146
|
+
message: `Stopped ${fullName(detail)} (${nodeId}) on its Mac. The daemon relaunched it on the saved session.`,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
151
149
|
const pid = detail.pi_pid;
|
|
152
150
|
const stall = detail.fault ?? null;
|
|
153
151
|
if (pid == null || recordedPidLiveness(pid, detail.pi_pid_identity ?? null) !== 'alive') {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// header and never logs it.
|
|
9
9
|
import { EventEmitter } from 'node:events';
|
|
10
10
|
import { WebSocket } from 'ws';
|
|
11
|
+
import { mark } from '../timing.js';
|
|
11
12
|
import { classify } from '../fault-classifier.js';
|
|
12
13
|
import { AttachRefusedError, BrokerUnavailableError } from './transport.js';
|
|
13
14
|
function relayUrl(target, nodeId, wakeParked) {
|
|
@@ -46,10 +47,17 @@ export class RelayTransport extends EventEmitter {
|
|
|
46
47
|
return relayUrl(this.target, this.nodeId, this.wakeParked);
|
|
47
48
|
}
|
|
48
49
|
dial() {
|
|
50
|
+
// CRTR_TIMING marks (stderr, same timeline as `viewer.*`): the target kind and the dial's own steps, each with the duration since this dial began.
|
|
51
|
+
const dialStart = performance.now();
|
|
52
|
+
const since = () => (performance.now() - dialStart).toFixed(1);
|
|
53
|
+
const kind = 'socketPath' in this.target ? 'local' : 'remote';
|
|
54
|
+
mark('relay.dial_start', { node: this.nodeId, target: kind });
|
|
49
55
|
const ws = new WebSocket(this.url, {
|
|
50
56
|
...('relayToken' in this.target ? { headers: { authorization: `Bearer ${this.target.relayToken}` } } : {}),
|
|
51
57
|
perMessageDeflate: false,
|
|
52
58
|
});
|
|
59
|
+
ws.once('upgrade', () => mark('relay.upgrade_response', { node: this.nodeId, target: kind, since_dial_ms: since() }));
|
|
60
|
+
ws.once('open', () => mark('relay.ws_open', { node: this.nodeId, target: kind, since_dial_ms: since() }));
|
|
53
61
|
// A refusal's JSON body carries the reason (`broker_not_ready`, `attach_revive_failed`); ws would drop it as a bare status.
|
|
54
62
|
ws.on('unexpected-response', (_req, res) => {
|
|
55
63
|
let text = '';
|
|
@@ -130,3 +130,18 @@ export function hangingCountdown(since, now = Date.now()) {
|
|
|
130
130
|
return `retry in ~${Math.max(1, Math.round(remaining / 60_000))}m`;
|
|
131
131
|
return `retry in ~${Math.ceil(remaining / 1000)}s`;
|
|
132
132
|
}
|
|
133
|
+
/** --now eligibility for a live, non-busy fault: a daemon-owned AUTO retry
|
|
134
|
+
* (kick it early instead of waiting out the schedule), or any fault the
|
|
135
|
+
* canvas dashboard flags "needs you" (`faultNeedsYou`, status-glyph.ts) — the
|
|
136
|
+
* disposition that otherwise has NO sanctioned recovery verb.
|
|
137
|
+
* Both are scoped to `pi→provider`: refuses a client-owned auto retry
|
|
138
|
+
* (redialing) already in flight, and refuses any OTHER link — notably a
|
|
139
|
+
* `daemon→node` wedge fault, which --now can't clear (SIGTERM doesn't touch
|
|
140
|
+
* the runaway subprocess; see `wedged-child-on-runaway-bash`). */
|
|
141
|
+
export function isNowEligibleFault(fault) {
|
|
142
|
+
if (fault === null || fault.link !== 'pi→provider')
|
|
143
|
+
return false;
|
|
144
|
+
if (faultNeedsYou(fault))
|
|
145
|
+
return true;
|
|
146
|
+
return fault.retry.by === 'daemon';
|
|
147
|
+
}
|