@north-light/cli 0.3.698 → 0.3.700
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/input/controller.d.ts +3 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/render/chat-view.d.ts +12 -0
- 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 +289 -289
- 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/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/feed/messages.js +4 -4
- 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-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/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 +14 -2
- package/dist/daemon/machine-link/client.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 +8 -0
- 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/input/controller.js +5 -1
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +55 -1
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +2 -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/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/feed/messages.js +1 -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/frames.js +4 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +63 -1
- 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
|
@@ -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.700",
|
|
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.700",
|
|
160
|
+
"@north-light/plugin": "0.3.700",
|
|
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`,
|
|
@@ -222,11 +222,13 @@ export class InputController {
|
|
|
222
222
|
const submit = this.hooks.onDormantSubmit;
|
|
223
223
|
if (submit === undefined)
|
|
224
224
|
return;
|
|
225
|
-
|
|
225
|
+
const expanded = this.expandImagePlaceholders(classification.text);
|
|
226
|
+
submit(expanded);
|
|
226
227
|
this.recordCompletionUse(text);
|
|
227
228
|
this.editor.addToHistory(classification.trimmed);
|
|
228
229
|
this.editor.setText('');
|
|
229
230
|
this.clearPastedImages();
|
|
231
|
+
this.hooks.onMessageSent?.(expanded);
|
|
230
232
|
this.hooks.onPromptSent?.();
|
|
231
233
|
return;
|
|
232
234
|
}
|
|
@@ -249,6 +251,8 @@ export class InputController {
|
|
|
249
251
|
this.editor.addToHistory(classification.trimmed);
|
|
250
252
|
this.editor.setText('');
|
|
251
253
|
this.clearPastedImages();
|
|
254
|
+
if (delivery === 'prompt')
|
|
255
|
+
this.hooks.onMessageSent?.(expanded);
|
|
252
256
|
this.hooks.onPromptSent?.();
|
|
253
257
|
}
|
|
254
258
|
handleFollowUp() {
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
// for crouter-owned message/tool types it understands; other extension
|
|
21
21
|
// `renderCall`/`renderResult` hooks degrade to the default ToolExecutionComponent
|
|
22
22
|
// path while builtin tools, diffs, and partial-result streaming keep working.
|
|
23
|
-
import { Container, Loader, Spacer, Text } from '@earendil-works/pi-tui';
|
|
23
|
+
import { Container, Loader, Markdown, Spacer, Text } from '@earendil-works/pi-tui';
|
|
24
24
|
import { AssistantMessageComponent, BashExecutionComponent, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomMessageComponent, parseSkillBlock, SkillInvocationMessageComponent, ToolExecutionComponent, UserMessageComponent, } from '@earendil-works/pi-coding-agent';
|
|
25
25
|
import { attachMarkdownTheme } from '../config.js';
|
|
26
26
|
import { ContextMessageComponent } from './context-message.js';
|
|
@@ -274,6 +274,11 @@ export class ChatView {
|
|
|
274
274
|
/** Standalone ChatViews render activity inline; the attach viewer supplies
|
|
275
275
|
* `onActivityChange`, so its transcript excludes this container. */
|
|
276
276
|
statusContainer = new MeasuredContainer();
|
|
277
|
+
/** Messages the person sent from this viewer that the engine has not echoed
|
|
278
|
+
* back yet, drawn gray below history. Outside `historyContainer`, so a
|
|
279
|
+
* welcome snapshot rebuild never drops them. */
|
|
280
|
+
pendingContainer = new MeasuredContainer();
|
|
281
|
+
pendingSends = [];
|
|
277
282
|
/** Optional banner, above history and status in the viewport's flat source. */
|
|
278
283
|
bannerContainer;
|
|
279
284
|
transcript;
|
|
@@ -436,11 +441,13 @@ export class ChatView {
|
|
|
436
441
|
this.container.addChild(banner);
|
|
437
442
|
}
|
|
438
443
|
this.container.addChild(this.historyContainer);
|
|
444
|
+
this.container.addChild(this.pendingContainer);
|
|
439
445
|
if (!this.onActivityChange)
|
|
440
446
|
this.container.addChild(this.statusContainer);
|
|
441
447
|
this.transcript = new CompositeViewportSource([
|
|
442
448
|
...(this.bannerContainer ? [this.bannerContainer] : []),
|
|
443
449
|
this.historyContainer,
|
|
450
|
+
this.pendingContainer,
|
|
444
451
|
...(this.onActivityChange ? [] : [this.statusContainer]),
|
|
445
452
|
]);
|
|
446
453
|
}
|
|
@@ -597,6 +604,7 @@ export class ChatView {
|
|
|
597
604
|
}
|
|
598
605
|
for (const turn of this.turns)
|
|
599
606
|
this.refreshTurn(turn);
|
|
607
|
+
this.confirmPendingSendsIn(messages);
|
|
600
608
|
// A rebuild constructs fresh components, which are born unfolded; re-apply the
|
|
601
609
|
// setting so a reconnect/welcome does not silently unfold the transcript.
|
|
602
610
|
this.applyToolDisplay();
|
|
@@ -1030,6 +1038,8 @@ export class ChatView {
|
|
|
1030
1038
|
break;
|
|
1031
1039
|
}
|
|
1032
1040
|
case 'message_start': {
|
|
1041
|
+
if (event.message.role === 'user' && isTrueUserMessage(event.message))
|
|
1042
|
+
this.confirmPendingSend(this.userMessageText(event.message).trim());
|
|
1033
1043
|
if (event.message.role === 'custom' || event.message.role === 'user') {
|
|
1034
1044
|
this.addMessageToChat(event.message);
|
|
1035
1045
|
// A card that joined a folded turn hides at once.
|
|
@@ -1858,6 +1868,50 @@ export class ChatView {
|
|
|
1858
1868
|
this.historyContainer.markDirty(component);
|
|
1859
1869
|
this.bashComponent = undefined;
|
|
1860
1870
|
}
|
|
1871
|
+
/** Show a message the person just sent as pending: gray text, no background,
|
|
1872
|
+
* until the engine echoes it as a user message. */
|
|
1873
|
+
addPendingSend(text) {
|
|
1874
|
+
const trimmed = text.trim();
|
|
1875
|
+
if (!trimmed)
|
|
1876
|
+
return;
|
|
1877
|
+
const parts = [
|
|
1878
|
+
new Spacer(1),
|
|
1879
|
+
new Markdown(trimmed, 1, 1, attachMarkdownTheme(), { color: this.dimStyle }),
|
|
1880
|
+
];
|
|
1881
|
+
for (const part of parts)
|
|
1882
|
+
this.pendingContainer.addChild(part);
|
|
1883
|
+
this.pendingSends.push({ text: trimmed, parts });
|
|
1884
|
+
this.tui.requestRender();
|
|
1885
|
+
}
|
|
1886
|
+
/** The engine echoed a user message: the matching pending send landed. */
|
|
1887
|
+
confirmPendingSend(text) {
|
|
1888
|
+
// The engine may reshape the text (image blocks, wrapping); with no exact
|
|
1889
|
+
// match the oldest pending send is the one that landed.
|
|
1890
|
+
const exact = this.pendingSends.findIndex((sent) => sent.text === text);
|
|
1891
|
+
const index = exact >= 0 ? exact : 0;
|
|
1892
|
+
if (this.pendingSends.length === 0)
|
|
1893
|
+
return;
|
|
1894
|
+
const [sent] = this.pendingSends.splice(index, 1);
|
|
1895
|
+
for (const part of sent.parts)
|
|
1896
|
+
this.pendingContainer.removeChild(part);
|
|
1897
|
+
}
|
|
1898
|
+
/** A snapshot rebuild: drop pending sends whose text the history now holds. */
|
|
1899
|
+
confirmPendingSendsIn(messages) {
|
|
1900
|
+
if (this.pendingSends.length === 0)
|
|
1901
|
+
return;
|
|
1902
|
+
const seen = new Set();
|
|
1903
|
+
for (const message of messages.slice(-50)) {
|
|
1904
|
+
if (message.role === 'user')
|
|
1905
|
+
seen.add(this.userMessageText(message).trim());
|
|
1906
|
+
}
|
|
1907
|
+
for (const sent of [...this.pendingSends]) {
|
|
1908
|
+
if (!seen.has(sent.text))
|
|
1909
|
+
continue;
|
|
1910
|
+
this.pendingSends.splice(this.pendingSends.indexOf(sent), 1);
|
|
1911
|
+
for (const part of sent.parts)
|
|
1912
|
+
this.pendingContainer.removeChild(part);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1861
1915
|
/** Swap the single active activity indicator (working/compaction/retry). */
|
|
1862
1916
|
setActivity(loader) {
|
|
1863
1917
|
this.activityLoader?.stop();
|
|
@@ -92,6 +92,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
|
|
|
92
92
|
},
|
|
93
93
|
onColor: hooks.setChipColor,
|
|
94
94
|
onPromptSent: hooks.onPromptSent,
|
|
95
|
+
onMessageSent: hooks.onMessageSent,
|
|
95
96
|
frecency: hooks.frecency,
|
|
96
97
|
knownRefNames: () => editor.getResolvedRefNames(),
|
|
97
98
|
// Global display toggles (Ctrl+O tools / Ctrl+T thinking) — pure render
|
|
@@ -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,
|
|
@@ -469,6 +469,7 @@ onConnected) {
|
|
|
469
469
|
if (userConfig.whip_mode)
|
|
470
470
|
whipAnimation.play();
|
|
471
471
|
},
|
|
472
|
+
onMessageSent: (text) => chatView.addPendingSend(text),
|
|
472
473
|
frecency,
|
|
473
474
|
});
|
|
474
475
|
const whip = () => {
|
|
@@ -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') {
|
|
@@ -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
|
+
}
|
|
@@ -62,6 +62,11 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
62
62
|
if (!('type' in param))
|
|
63
63
|
continue;
|
|
64
64
|
const key = param.name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
65
|
+
// A yes/no flag the caller did not pass is not sent: the parser seeds it false, which a provider reads as "turn it off".
|
|
66
|
+
if (param.type === 'bool' && param.default === undefined && context !== undefined && !context.providedParams.has(key)) {
|
|
67
|
+
delete argumentsForDaemon[key];
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
65
70
|
const value = argumentsForDaemon[key];
|
|
66
71
|
// `file` params are uploaded by the daemon from an absolute path; `path`
|
|
67
72
|
// params are read here, in the caller's cwd, and travel as their content.
|
|
@@ -439,6 +439,18 @@ export async function parseArgv(params, tokens, options) {
|
|
|
439
439
|
i++;
|
|
440
440
|
continue;
|
|
441
441
|
}
|
|
442
|
+
// `--no-<name>` turns a declared boolean flag off, unless the leaf declares a flag of that exact name.
|
|
443
|
+
const negated = flagsByName.has(flagName) || !flagName.startsWith('no-') ? undefined : flagsByName.get(flagName.slice(3));
|
|
444
|
+
if (negated !== undefined && negated.type === 'bool') {
|
|
445
|
+
if (inlineValue !== undefined) {
|
|
446
|
+
throw parseArgvError('invalid_type', `boolean flag --${flagName} takes no value`, `--${flagName}=${inlineValue}`, negated.name, `Use --${flagName} (presence = false) with no value.`);
|
|
447
|
+
}
|
|
448
|
+
const negatedKey = flagNameToKey(negated.name);
|
|
449
|
+
provided.add(negatedKey);
|
|
450
|
+
result[negatedKey] = false;
|
|
451
|
+
i++;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
442
454
|
const flagDef = flagsByName.get(flagName);
|
|
443
455
|
if (flagDef === undefined) {
|
|
444
456
|
throw parseArgvError('unknown_flag', `unknown flag: --${flagName}`, `--${flagName}`, undefined, 'Use --<flag-name> for declared flags only. Run -h for the schema.');
|
|
@@ -447,7 +459,7 @@ export async function parseArgv(params, tokens, options) {
|
|
|
447
459
|
provided.add(key);
|
|
448
460
|
if (flagDef.type === 'bool') {
|
|
449
461
|
if (inlineValue !== undefined) {
|
|
450
|
-
throw parseArgvError('invalid_type', `boolean flag --${flagName} takes no value`, `--${flagName}=${inlineValue}`, flagName, `Use --${flagName} (presence = true) with no value.`);
|
|
462
|
+
throw parseArgvError('invalid_type', `boolean flag --${flagName} takes no value`, `--${flagName}=${inlineValue}`, flagName, `Use --${flagName} (presence = true) or --no-${flagName} (false), with no value.`);
|
|
451
463
|
}
|
|
452
464
|
result[key] = true;
|
|
453
465
|
i++;
|
|
@@ -15,7 +15,7 @@ export function newId() {
|
|
|
15
15
|
return id;
|
|
16
16
|
}
|
|
17
17
|
function stringify(value, name) {
|
|
18
|
-
const json = JSON.stringify(value);
|
|
18
|
+
const json = JSON.stringify(value, (_key, v) => (typeof v === 'string' ? v.replace(/\p{Cs}/gu, '\uFFFD') : v));
|
|
19
19
|
if (json === undefined)
|
|
20
20
|
throw new TypeError(`${name} must be JSON-serializable`);
|
|
21
21
|
return json;
|