@north-light/cli 0.3.708 → 0.3.710
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/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/crons.d.ts +3 -0
- package/dist/clients/attach/chrome/inbox-strip.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/chrome/status-line.d.ts +1 -1
- package/dist/clients/attach/chrome/status-line.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +4 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/overlays/graph.d.ts +3 -2
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +2 -0
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/render/doc-links.d.ts +1 -1
- package/dist/clients/attach/session/chrome-refresh.js +1 -1
- package/dist/clients/attach/session/connection.d.ts +10 -9
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/context.d.ts +1 -1
- package/dist/clients/attach/session/document-links.d.ts +1 -1
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/session/identity.d.ts +2 -0
- package/dist/clients/attach/session/identity.js +1 -1
- 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/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/layout-record.d.ts +13 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/pane-tag.d.ts +3 -1
- package/dist/clients/attach/session/pane-tag.js +1 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +4 -2
- package/dist/clients/attach/session/teardown.js +9 -7
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +2 -0
- package/dist/clients/attach/viewer.d.ts +7 -5
- package/dist/clients/attach/viewer.js +563 -558
- package/dist/commands/node/wait.js +2 -6
- package/dist/core/broker-client/client.d.ts +6 -3
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/crons.d.ts +11 -1
- package/dist/core/canvas/crons.js +14 -14
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
- package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command.js +5 -5
- package/dist/core/feed/messages.d.ts +5 -0
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/runtime/bearings.js +4 -4
- package/dist/core/runtime/boot-root.js +4 -4
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
- package/dist/core/runtime/runner/blaxel/client.js +1 -1
- package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/types.d.ts +19 -3
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/bridge.d.ts +5 -0
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/handlers/crons.d.ts +2 -0
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/ended.d.ts +3 -0
- package/dist/daemon/cron/ended.js +2 -2
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/machine-fire.d.ts +9 -2
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/cron/passes.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
- package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +3 -1
- package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
- package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
- package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
- package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +9 -4
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +86 -31
- package/packages/crouter-api/dist/commands/node/wait.js +2 -10
- package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
- package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
- package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command.js +3 -0
- package/packages/crouter-api/dist/core/feed/messages.js +15 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
- package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
- package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- 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/core/runtime/starting-screen.d.ts +0 -12
- package/dist/core/runtime/starting-screen.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as v,cronOwnerAlive as p,ensureCronOwnerLease as D}from"./live-runs.js";import{crashedOneShotSummary as L,escalateFailure as C}from"./escalation.js";import{settleRun as I}from"./settle.js";import{adoptCronRunId as E,getCron as g,runningCrons as M,stopLeasedCronRun as S,setCronState as T,verifyLeasedCronRun as _}from"../../core/canvas/crons.js";import{claimReconcilerLease as H,releaseReconcilerLease as b,renewReconcilerLease as N}from"../../core/canvas/reconciler-leases.js";import{emitEvent as l}from"../../core/events/emit.js";import{openDb as $}from"../../core/canvas/db.js";import{cronEnvironment as k,fireInSandbox as G,resumeMachineFire as U}from"./machine-fire.js";const c="cron-recovery",f=3e4;async function B(e){const t=w();if(await H(c,e,t,f)===void 0)return;let n=!1;const r=s(async()=>{if(n)return!1;try{n=!await N(c,e,t,f)}catch{n=!0}return!n},"holds"),a=setInterval(()=>{r()},f/3);return a.unref(),{holds:r,release:s(async()=>{clearInterval(a),await b(c,e,t)},"release")}}s(B,"claimRecovery");async function F(e){const t=await g(e.cron_id);if(t===null||t.run_state!=="running"||t.run_execution_id!==e.run_execution_id||t.run_started_at!==e.run_started_at||t.run_lease_owner!==e.run_lease_owner||t.run_lease_owner!==null&&await p(t.run_lease_owner))return null;if(t.run_execution_id!==null)return t;const n=w();return await E(t,n)?{...t,run_execution_id:n}:null}s(F,"reverifyAbandoned");async function oe(e,t={}){await D();for(const n of await M()){if(n.run_lease_owner===v||n.run_lease_owner!==null&&await p(n.run_lease_owner))continue;const r=n.run_pid===null&&n.run_execution_id!==null?await k(n):null,a=r===null&&(n.run_pid===null||!_(n));if(r===null&&!a&&e-(n.run_started_at!=null?new Date(n.run_started_at).getTime():e)<n.run_timeout_s*1e3)continue;const o=await B(n.cron_id);if(o===void 0)continue;let i;try{i=await F(n)}catch(u){throw await o.release(),u}if(i===null){await o.release();continue}if(r!==null){P(i,r,t,o);continue}if(a){W(i,e,t,o);continue}K(i,e,t,o)}}s(oe,"recoverStaleCronLeases");function K(e,t,n,r){const a=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,o={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:-1,timedOut:!0,runTimeoutS:e.run_timeout_s,processErrorMessage:null,stdoutHead:"",stdoutSha256:h,stderrHead:`run timed out after ${e.run_timeout_s}s (recovered stale lease from a prior daemon instance)`},i=(async()=>{await r.holds()&&(await S(e),await V(e),await r.holds()&&await I(e,{outOfBand:!1,outcome:{kind:"disposed",ctx:o},record:{runId:o.runId,startedAtIso:o.startedAtIso,finishedAtMs:t,durationMs:t-a,exitCode:-1,stdoutHead:null,stderrHead:o.stderrHead},lease:{kind:"clear"}}))})().finally(()=>r.release());n.register?.(i),i.catch(u=>{l({level:"error",event:"cron.stale_lease.settle_failed",error:u,fields:{cron_id:e.cron_id}})})}s(K,"recoverTimedOutRun");function P(e,t,n,r){const a=(async()=>{await r.holds()&&await Y(e)&&(t.kind==="machine"?await U(e,t.id):await G(e,{runId:e.run_execution_id,outOfBand:e.run_out_of_band,startedAtIso:e.run_started_at,startedAtMs:Date.parse(e.run_started_at)},()=>{},!0))})().finally(()=>r.release());n.register?.(a),a.catch(o=>{l({level:"error",event:"cron.machine_resume.failed",error:o,fields:{cron_id:e.cron_id,run_id:e.run_execution_id}})})}s(P,"resumeMachineRun");async function Y(e){const t=await(await $()).prepare("UPDATE crons SET run_lease_owner = ?, updated = ? WHERE cron_id = ? AND run_state = 'running' AND run_execution_id = ? AND run_lease_owner IS NOT DISTINCT FROM ?").run(v,new Date().toISOString(),e.cron_id,e.run_execution_id,e.run_lease_owner);return Number(t.changes)>0}s(Y,"takeOverLease");async function V(e){if(!await y(e)&&(await S(e,"SIGKILL"),!await y(e)))throw new Error(`cron ${e.cron_id} run ${e.run_pid} survived SIGKILL`)}s(V,"awaitLeasedRunDeath");async function y(e){const t=Date.now()+O;for(;Date.now()<t;){if(!_(e))return!0;await R(x)}return!_(e)}s(y,"pollLeasedRunGone");function W(e,t,n,r){const a=e.recur==null,o=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,i=e.run_pid===null?"the daemon life that claimed this run ended before its launch pid was recorded \u2014 the command may have started and its outcome is unknown":"the daemon life that owned this run ended before it settled \u2014 the process is gone and its outcome was never observed",u={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:null,timedOut:!1,runTimeoutS:e.run_timeout_s,processErrorMessage:i,stdoutHead:"",stdoutSha256:h,stderrHead:`run outcome unobserved: ${i}`},m=(async()=>{let d=`crashed: ${i}${a?"":" \u2014 the next occurrence is unaffected"}`;if(a){if(!await r.holds())return;if(await T(e.cron_id,"paused"),e.on_output==="silent")d=`crashed: ${i} \u2014 one-shot paused, not re-fired (silent: not escalated)`;else{if(!await r.holds())return;d=`crashed one-shot: ${await C(e,u,L(i))}`}}await r.holds()&&(await I(e,{outOfBand:!1,outcome:{kind:"stated",delivered:d,paused:a},record:{runId:u.runId,startedAtIso:u.startedAtIso,finishedAtMs:t,durationMs:Math.max(0,t-o),exitCode:null,stdoutHead:null,stderrHead:u.stderrHead},lease:"release"}),l({level:"warn",event:"cron.run.unobserved",fields:{cron_id:e.cron_id,name:e.name,one_shot:a}}))})().finally(()=>r.release());n.register?.(m),m.catch(d=>{l({level:"error",event:"cron.crashed_run.settle_failed",error:d,fields:{cron_id:e.cron_id}})})}s(W,"settleCrashedRun");export{oe as recoverStaleCronLeases};
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { type MachineCronRunArgs, type MachineCronRunResult } from '../../core/runtime/runner/machine/ops.js';
|
|
2
2
|
import { type Cron, type CronRunRecord } from '../../core/canvas/crons.js';
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/** Where a cron runs off this process: its profile's machine or Blaxel environment on a cloud role, or null when it runs here (a Mac's own
|
|
4
|
+
* daemon, a local runtime, a cron with no profile). */
|
|
5
|
+
export declare function cronEnvironment(c: Cron): Promise<{
|
|
6
|
+
kind: 'machine' | 'blaxel';
|
|
7
|
+
id: string;
|
|
8
|
+
} | null>;
|
|
5
9
|
export declare function machineLinkLive(environmentId: string): Promise<boolean>;
|
|
6
10
|
/** What a machine cron's call carries beyond the command: the stored variables and armed env, and who the Mac rebuilds its run context for. */
|
|
7
11
|
type PreparedRun = Pick<MachineCronRunArgs, 'env' | 'grantee' | 'profileId' | 'contextAnchor'>;
|
|
@@ -26,4 +30,7 @@ export declare function fireOnMachine(c: Cron, fire: MachineFire, admit: () => v
|
|
|
26
30
|
/** A control plane that took a cron's run lease over from one that ended mid-fire: the same run id goes to the machine again, so the machine
|
|
27
31
|
* returns the stored result or joins the live run. A fresh id is never minted for this occurrence. Resolves with the settled record. */
|
|
28
32
|
export declare function resumeMachineFire(c: Cron, environmentId: string): Promise<CronRunRecord | null>;
|
|
33
|
+
/** Fire `c` in its anchor node's sandbox through the Blaxel runner and settle the run. The same run id names the sandbox process, so a
|
|
34
|
+
* control plane that recovers the run (`resume`) reads the first start instead of running the command again. */
|
|
35
|
+
export declare function fireInSandbox(c: Cron, fire: Omit<MachineFire, 'environmentId'>, admit: () => void, resume?: boolean): Promise<CronRunRecord | null>;
|
|
29
36
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=Object.defineProperty;var d=(e,n)=>P(e,"name",{value:n,configurable:!0});import{createHash as k,randomUUID as B}from"node:crypto";import{join as O}from"node:path";import{setTimeout as F}from"node:timers/promises";import{openDb as C}from"../../core/canvas/db.js";import{isCloudRole as j}from"../../core/canvas/person.js";import{withCanvasWrite as W}from"../../core/canvas/db.js";import{getNode as q}from"../../core/canvas/canvas.js";import{runnerForEnvironment as J}from"../../core/runtime/runner/index.js";import{callMachine as $}from"../../core/runtime/runner/machine/call.js";import{machineEnvironmentOfNode as K}from"../../core/runtime/runner/machine/runner.js";import{MachineCallFailedError as V,MachineLostError as X,MachineOfflineError as g}from"../../core/runtime/runner/machine/ops.js";import{environmentSecrets as Y}from"../../core/secrets/environment-secrets.js";import{profileInApp as z}from"../../core/secrets/environment-owner.js";import{getCron as G}from"../../core/canvas/crons.js";import{emitEvent as E}from"../../core/events/emit.js";import{runTokenFor as Q}from"./run-token.js";import{parseArmedEnv as Z}from"./armed-context.js";import{CRON_OUTPUT_HEAD_BYTES as v,formatCronOutputHead as ee}from"./capture.js";import{settleClosedRun as y,settleUnspawnedRun as h}from"./closed.js";import{clearLiveRun as T,registerLiveRun as x}from"./live-runs.js";import{advanceRecurrence as S}from"./recurrence.js";const ne=15,re=2e3;async function ye(e){return!j()||e.profile==null?null:await(await C()).prepare("SELECT e.object AS id, e.kind AS kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(e.profile)??null}d(ye,"cronEnvironment");async function Te(e){return await(await C()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,new Date().toISOString())!==void 0}d(Te,"machineLinkLive");async function A(e,n){const r=e.profile,i=await(await C()).prepare("SELECT person FROM profiles WHERE id = ?").get(r);if(i===void 0)throw new Error(`profile ${r} of cron ${e.cron_id} is not in the control plane`);const t=await Y({person:i.person,app:e.grantee,ownerProfile:r,ownerProfileInApp:await z(r,e.grantee),includeDeployment:!1}),o=e.grantee==="app:terminal",l=e.anchor_node!=null?await q(e.anchor_node):null;return{env:{...t,...Z(e.env_json),...o?{CRTR_PROFILE_ID:r}:{},CRTR_CRON_ID:e.cron_id,CRTR_CRON_NAME:e.name,CRTR_RUN_ID:n,CRTR_API_TOKEN:Q(n),...e.anchor_node!=null?{CRTR_ANCHOR:e.anchor_node}:{}},grantee:e.grantee,profileId:r,contextAnchor:l===null?null:{node:l.node_id,grantee:l.grantee??e.grantee}}}d(A,"prepareRun");async function te(e,n,r,i){const t=(e.run_timeout_s+ne)*1e3;return await $(n,"cron.run",{runId:r,cronId:e.cron_id,command:e.command,cwd:e.cwd,...i,timeoutS:e.run_timeout_s,leaseExpiresAt:new Date(Date.now()+t).toISOString()},{timeoutMs:t})}d(te,"sendCronRun");async function oe(e,n){await M(e,"cron.cancel",{runId:n})}d(oe,"queueCronCancel");async function xe(e,n){const r=await K(e);r!==null&&await M(r,"job.stop",{node:e,job:n})}d(xe,"queueJobStop");async function M(e,n,r){await W(async i=>{await i.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(B(),e,n,JSON.stringify(r),new Date().toISOString()),await i.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`)})}d(M,"queueMachineCall");async function Me(e,n,r){const{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l}=n;let c;try{if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a machine does not have");if(c=await A(e,i),!t&&e.recur!=null){const s=await S(e,l);if(s!==null)throw s}}catch(s){return await h(e,{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l},"run could not be armed",s)}return await N(e,n,c,r)}d(Me,"fireOnMachine");async function Ne(e,n){const r=e.run_execution_id,i=e.run_started_at,t=Date.parse(i),o=e.run_out_of_band,l={environmentId:n,runId:r,outOfBand:o,startedAtIso:i,startedAtMs:t};let c;try{if(c=await A(e,r),!o&&e.recur!=null&&Date.parse(e.fire_at)<=t){const s=await S(e,t);if(s!==null)throw s}}catch(s){return await h(e,l,"run could not be armed",s)}return await N(e,l,c,()=>{})}d(Ne,"resumeMachineFire");async function N(e,n,r,i){const{environmentId:t,runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s}=n,p={runId:o,replaced:!1,selfCanceled:!1,kill:d(()=>{oe(t,o).catch(_=>{E({level:"error",event:"cron.machine.cancel_failed",error:_,fields:{cron_id:e.cron_id,run_id:o}})})},"kill")};x(e.cron_id,p),i();try{let _=null,m=null;for(;_===null&&m===null;){try{const f=await te(e,t,o,r);if(f.notStarted!==!0){_=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.stderrHead}})}catch(f){if(f instanceof V){m=f;break}if(!(f instanceof g)&&!(f instanceof X))throw f;if(l&&f instanceof g){m=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.message}})}if(!p.selfCanceled&&await G(e.cron_id)===null)return null;await F(re)}if(m!==null)return await h(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s},"run failed on the machine",m);const{exitCode:a,stdoutHead:w,stderrHead:u,durationMs:R,stdoutSha256:D}=_,I=a===-1,L=a===null?new Error((u??"the machine reported no exit").slice(0,v)):null,H=p.replaced,U=p.selfCanceled;return await y(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s,finishedAtMs:s+R,code:I?null:a,timedOut:I,processError:L,stdoutHead:w??"",stderrHead:u??"",stdoutSha256:D,wasReplaced:H,wasSelfCanceled:U})}finally{T(e.cron_id,o)}}d(N,"driveFire");const b="/var/lib/crtr";async function be(e,n,r,i=!1){const{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c}=n;let s,p;try{if(p=J("blaxel"),p.cronRun===void 0||p.cronCancel===void 0)throw new Error("the registered Blaxel runner cannot run crons");const a=process.env.CRTR_PUBLIC_API_URL;if(!a)throw new Error("CRTR_PUBLIC_API_URL is not set, so a sandbox cron could not reach the API");if(e.anchor_node==null)throw new Error("a hosted cron runs in its anchor node's sandbox, and this cron has no anchor node");if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a sandbox does not have");const w=await A(e,t),u=w.contextAnchor;if(s={...w.env,CRTR_API_URL:a,HOME:O(b,"apps",e.grantee.replace(/^app:/,""),"home"),...u!==null?{CRTR_CONTEXT_DIR:O(b,"apps",u.grantee.replace(/^app:/,""),"nodes",u.node,"context")}:{}},!o&&e.recur!=null&&(!i||Date.parse(e.fire_at)<=c)){const R=await S(e,c);if(R!==null)throw R}}catch(a){return await h(e,n,"run could not be armed",a)}const _=e.anchor_node,m={runId:t,replaced:!1,selfCanceled:!1,kill:d(()=>{p.cronCancel(_,t).catch(a=>{E({level:"error",event:"cron.sandbox.cancel_failed",error:a,fields:{cron_id:e.cron_id,run_id:t}})})},"kill")};x(e.cron_id,m),r();try{let a;try{a=await p.cronRun(_,{runId:t,command:e.command,cwd:e.cwd,env:s,timeoutS:e.run_timeout_s,startedAtMs:c})}catch(u){return await h(e,n,"run failed in the sandbox",u)}const w=d(u=>u.length>v?ee(u.slice(0,v),!0):u,"head");return await y(e,{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c,finishedAtMs:Date.now(),code:a.exitCode,timedOut:a.timedOut,processError:a.error===void 0?null:new Error(a.error),stdoutHead:w(a.stdout),stderrHead:w(a.stderr),stdoutSha256:k("sha256").update(a.stdout).digest("hex"),wasReplaced:m.replaced,wasSelfCanceled:m.selfCanceled})}finally{T(e.cron_id,t)}}d(be,"fireInSandbox");export{ye as cronEnvironment,be as fireInSandbox,Me as fireOnMachine,Te as machineLinkLive,oe as queueCronCancel,xe as queueJobStop,Ne as resumeMachineFire,te as sendCronRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var o=(n,e)=>l(n,"name",{value:e,configurable:!0});import{randomUUID as f}from"node:crypto";import{cronDaemonInstanceId as u,liveRunFor as p}from"./live-runs.js";import{advanceCron as _,dueOverlapCrons as m,cappedIdleCrons as v,expiredIdleCrons as x,HOSTED_CRON_MAX_FIRES as a,listCronRuns as w,recordCronRun as C}from"../../core/canvas/crons.js";import{emitEvent as d}from"../../core/events/emit.js";import{nextSlotAfter as h}from"../../core/wake.js";import{endCron as c}from"./ended.js";const s="skipped (overlap=skip)";async function A(n){for(const e of await x(n))await c(e,{kind:"expired"})&&d({level:"info",event:"cron.expired",fields:{cron_id:e.cron_id,name:e.name,expires_at:e.expires_at}});for(const e of await v(a))await c(e,{kind:"max_fires",max:a})&&d({level:"info",event:"cron.max_fires",fields:{cron_id:e.cron_id,name:e.name,fires:e.fires}})}o(A,"expireDueCrons");async function k(n){return(await w(n))[0]?.delivered?.startsWith(s)===!0}o(k,"latestRunIsSkip");async function F(n,e){for(const r of await m(e)){if(r.overlap==="queue")continue;if(r.overlap==="skip"){let t;try{t=h(r.recur,new Date(n))}catch{continue}await _(r.cron_id,t),await k(r.cron_id)||await C({run_id:f(),cron_id:r.cron_id,started:e,finished:e,duration_ms:0,exit_code:null,stdout_head:null,stderr_head:null,delivered:`${s}: fire landed while the previous run was in flight (consecutive skips are not re-recorded until a run settles)`});continue}const i=p(r.cron_id);r.run_lease_owner===u&&i!==void 0&&!i.replaced&&(i.replaced=!0,i.kill())}}o(F,"applyOverlapPolicies");export{F as applyOverlapPolicies,A as expireDueCrons};
|
package/dist/daemon/cron-run.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
1
|
+
var Y=Object.defineProperty;var i=(e,m)=>Y(e,"name",{value:m,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as _,cronDaemonInstanceId as M,ensureCronOwnerLease as z,registerLiveRun as G}from"./cron/live-runs.js";import{closeCronExecution as J,openCronExecution as K}from"./cron/run-socket.js";import{appProcessSandboxed as Q}from"../core/spaces/process.js";import{nodeAgentDir as V}from"../core/canvas/paths.js";import{uidForApp as W}from"../core/spaces/users.js";import{buildArmedRunContext as Z}from"./cron/armed-context.js";import{asPerson as j}from"./reconcilers/node-lifecycle/node-person.js";import{isProfilePaused as ee}from"../core/profiles/manifest.js";import{ensureCronFolder as ne}from"./cron/folders.js";import{cronEnvironment as re,fireInSandbox as te,fireOnMachine as oe,machineLinkLive as ae}from"./cron/machine-fire.js";import{advanceRecurrence as U}from"./cron/recurrence.js";import{checkCronFire as ie,cronPrincipalOf as se}from"./cron/authority.js";import{refusalError as de}from"../core/ledger/index.js";import{startRefusal as le}from"../core/runtime/start-check.js";import{settleClosedRun as ue,settleUnspawnedRun as v}from"./cron/closed.js";import{settleRun as B}from"./cron/settle.js";import{applyOverlapPolicies as fe,expireDueCrons as me}from"./cron/passes.js";import{dueClockCrons as ce,acquireCronRunLease as pe,releaseCronRunLease as he,attachCronRunPid as _e,HOSTED_CRON_MAX_FIRES as we}from"../core/canvas/crons.js";import{emitEvent as $}from"../core/events/emit.js";import{deliverDueDeadline as Ce}from"../core/feed/messages.js";import{runAppCommand as ge}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as Qe}from"./cron/capture.js";import{cronDaemonInstanceId as We,markSelfCanceledCronRun as Ze}from"./cron/live-runs.js";import{recoverStaleCronLeases as en}from"./cron/lease-recovery.js";function ze(e,m){return F(e,m).settled}i(ze,"executeCron");function F(e,m){const{outOfBand:s}=m;let u=i(()=>{},"admit");const d=new Promise(t=>{u=t}),w=new Promise((t,a)=>{let p=!1;const r=X();let I=i(()=>{},"undo");const R=i(l=>{if(I(),!p){a(l);return}p=!1,he(e.cron_id,r).then(()=>a(l),f=>{$({level:"error",event:"cron.lease.release_failed",error:f,fields:{cron_id:e.cron_id}}),a(l)})},"fail");(async()=>{const l=Date.now(),f=new Date(l).toISOString(),C={runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l},D=await re(e),b=D?.kind==="machine"?D.id:null;if(b!==null&&!s&&!await ae(b)){t(null);return}if(await z(),!await pe(e.cron_id,M,f,s,r,D?.kind==="blaxel"?we:null)){t(null);return}p=!0;let c=await ie(se(e));if(c.allowed){e={...e,scopes:c.scopes};const n=await le({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(c={allowed:!1,reason:"limit_reached",message:de(n).message})}if(!c.allowed){try{if(!s&&e.recur!=null){const h=await U(e,l);if(h!==null)throw h}}catch(h){v(e,C,"run could not be armed",h).then(t,a);return}const n=Date.now();B(e,{outOfBand:s,outcome:{kind:"refused",reason:c.reason,message:c.message},record:{runId:r,startedAtIso:f,finishedAtMs:n,durationMs:n-l,exitCode:null,stdoutHead:null,stderrHead:`${c.reason}: ${c.message}`.slice(0,A)},lease:"release"}).then(t,a);return}if(D?.kind==="blaxel"){te(e,C,u).then(t,R);return}if(b!==null){oe(e,{environmentId:b,runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l},u).then(t,R);return}let H;try{if(e.isolated&&ne(e.grantee,e.cron_id),{env:H}=await Z(e,r),!s&&e.recur!=null){const n=await U(e,l);if(n!==null)throw n}}catch(n){v(e,C,"run could not be armed",n).then(t,a);return}let k=null,y=!1;const O={runId:r,replaced:!1,selfCanceled:!1,kill:i(()=>{k!==null?k():y=!0},"kill")};G(e.cron_id,O),I=i(()=>_(e.cron_id,r),"undo"),u();const g=Q()?{executionId:r,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await W(e.grantee),rebuilt:!1,refusal:null}:null,x=i(()=>{g!==null&&J(r)},"closeExecution");I=i(()=>{_(e.cron_id,r),x()},"undo"),i(async()=>(g!==null&&await K(g,e.cwd,e.profile),ge({command:e.command,cwd:e.cwd,env:H,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...g!==null?{cron:{executionId:r,...e.anchor_node===null||e.isolated?{}:{anchorDir:V(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:A})),"launch")().then(async n=>{if(n.pid===null){_(e.cron_id,r),x(),n.completion.then(o=>{v(e,C,"run failed to spawn",o.processError??new Error("bash did not provide a process id")).then(t,a)},a);return}I=i(()=>{_(e.cron_id,r),x(),n.terminate()},"undo");let h=!1;const P=i(()=>{n.completion.then(o=>{const T=O.replaced,N=O.selfCanceled,E=g?.refusal??null;if(_(e.cron_id,r),x(),h){t(null);return}if(E!==null&&!T){const L=Date.now(),q=S(o.stderr,o.stderrTruncated);B(e,{outOfBand:s,outcome:{kind:"refused",reason:E.reason,message:E.message},record:{runId:r,startedAtIso:f,finishedAtMs:L,durationMs:L-l,exitCode:o.exitCode,stdoutHead:S(o.stdout,o.stdoutTruncated)||null,stderrHead:`${E.reason}: ${E.message}
|
|
2
|
+
${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}ue(e,{runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l,finishedAtMs:Date.now(),code:o.exitCode,timedOut:o.timedOut,processError:o.processError,stdoutHead:S(o.stdout,o.stdoutTruncated),stderrHead:S(o.stderr,o.stderrTruncated),stdoutSha256:o.stdoutSha256,wasReplaced:T,wasSelfCanceled:N}).then(t,a)},a)},"settleCommand");if(!await _e(e.cron_id,M,f,n.pid)&&!O.selfCanceled){h=!0,n.terminate(),P();return}k=n.terminate,y&&n.terminate(),P()},n=>{_(e.cron_id,r),x(),v(e,C,"run failed to spawn",n).then(t,a)}).catch(R)})().catch(R)});return w.then(u,u),{admitted:d,settled:w}}i(F,"startCron");async function Ge(e,m){const s=new Date(e).toISOString();await me(s),await fe(e,s);const u=[];for(const d of await ce(s)){if(d.anchor_node!=null&&m.held.has(d.anchor_node))continue;const w=await j(d.sub,async()=>ee(d.profile)?null:d.deadline_body!==null?await Ce(d).then(()=>null):F(d,{outOfBand:!1})).catch(r=>($({level:"error",event:"cron.fire_failed",error:r,fields:{cron_id:d.cron_id}}),null));if(w===null)continue;const{admitted:t,settled:a}=w,p=a.then(()=>{});p.catch(()=>{}),await t,u.push(p),m.register?.(p)}for(const d of u)d.catch(()=>{});return u}i(Ge,"runDueCrons");export{Qe as CRON_OUTPUT_HEAD_BYTES,We as cronDaemonInstanceId,ze as executeCron,Ze as markSelfCanceledCronRun,en as recoverStaleCronLeases,Ge as runDueCrons,F as startCron};
|
package/dist/daemon/fleet.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ export type DeadNodeRow = Pick<NodeMeta, 'status' | 'intent' | 'pi_session_id' |
|
|
|
36
36
|
* `pendingWake` is the one non-row input (`hasPendingWake`): whether anything
|
|
37
37
|
* would drive a turn if the engine came back. It selects row 4b and defaults
|
|
38
38
|
* to `true`, so an uninformed caller keeps the conservative respawn. */
|
|
39
|
-
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean): DeadNodeAction;
|
|
39
|
+
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean, admittedTurn?: boolean): DeadNodeAction;
|
|
40
40
|
export interface DaemonFleetOpts {
|
|
41
41
|
/** This daemon's epoch id (randomBytes(8).toString('hex'), minted by
|
|
42
42
|
* runDaemon after the ownership claim). */
|
package/dist/daemon/fleet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as
|
|
1
|
+
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as A}from"../core/profiles/manifest.js";import{fullName as p}from"../core/canvas/labels.js";import{isSafeNodeId as o}from"../core/canvas/paths.js";import{hasIdleReleaseIntent as z,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as B,readFault as D,readInterruptedTurn as W,readTransportPoisonVerdict as q}from"../core/canvas/recovery.js";import{hasPendingWake as G}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as H,MAX_RESPAWN_ATTEMPTS as Y,OFFLINE_RESPAWN_RETRY_MS as U,recordRespawnPolicy as V,respawnBackoffMs as j}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as K}from"../core/runtime/connectivity.js";import{runnerForExecution as X}from"../core/runtime/runner/index.js";import{reviveNode as J}from"../core/runtime/revive.js";import{isStartRefusal as Q}from"../core/runtime/start-check.js";import{MachineOfflineError as Z}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as u}from"../core/events/emit.js";import{brokerThresholdsForDaemon as I}from"../core/runtime/fleet.js";import{isRecoveryHeld as ee}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await D(i.node_id),t=r===null?"":`The broker reported a ${r.kind} fault on ${r.link} (${r.op}) before it exited: ${r.message}
|
|
2
2
|
|
|
3
3
|
`,s=e===void 0?"The daemon did not observe an exit status.":`The observed exit status was code ${e.code??"null"}, signal ${e.signal??"null"}.`;return`\u26A0 Spawn failed \u2014 \`${i.name}\` (${i.kind}) never started.
|
|
4
4
|
|
|
@@ -8,14 +8,14 @@ Its pi vehicle exited before the session came up (no pi_session_id was ever reco
|
|
|
8
8
|
|
|
9
9
|
If the work still needs doing, re-spawn it.`}l(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}l($,"surfaceBootFailure");function x(i){return`\u26A0 Out of memory \u2014 \`${i.name}\` (${i.kind}) was killed because its app's processes together passed the app's memory limit.
|
|
10
10
|
|
|
11
|
-
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function
|
|
11
|
+
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function te(i){const e=await q(i.node_id),r=e===null?"":`
|
|
12
12
|
|
|
13
13
|
Provider rotation observed ${e.consecutivePasses} consecutive route-queue passes with no HTTP response (tried ${e.routes.join(", ")}). Check network and provider transport before reviving.`,t=`\u26A0 Crash loop \u2014 \`${i.name}\` (${i.kind}) kept dying without settling a turn.
|
|
14
14
|
|
|
15
15
|
Its session started successfully, but six consecutive relaunches made no progress, so the daemon stopped retrying.`+r+`
|
|
16
16
|
|
|
17
|
-
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
17
|
+
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(te,"surfaceCrashLoop");async function re(i,e){const r=e instanceof Error?e.message:String(e),t=`\u26A0 Recovery failed \u2014 \`${i.name}\` (${i.kind}) could not be relaunched.
|
|
18
18
|
|
|
19
19
|
The daemon refused this recovery before starting a broker: ${r}
|
|
20
20
|
|
|
21
|
-
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
21
|
+
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(re,"surfaceRecoveryFailure");function ie(i){return i?.cycle_pending!==!0}l(ie,"retryResumeMode");function se(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"?"respawn-fresh":z(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?ie(i)?"respawn-resume":"respawn-cycle":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}l(se,"classifyDeadNode");const ae=3e4;class Re{static{l(this,"DaemonFleet")}#a;#n;#r;#o;#e=new Map;#t=new Set;#l=Number.NEGATIVE_INFINITY;constructor(e){this.#a=e.epoch,this.#n=e.enqueue,this.#r=e.now??Date.now,this.#o=e.probeOnline??(()=>K())}epoch(){return this.#a}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}async has(e){return this.#e.has(e)||await b(e)}async isClaimed(e){return this.#e.has(e)||this.#t.has(e)||await b(e)||await S(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await C();for(const r of this.#e.keys())e.add(r);for(const r of this.#t)e.add(r);return e}async occupancy(){return(await this.#c()).size}async reserveSlot(e){if(this.#t.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=I(),t=await this.#c();if(this.#t.has(e)||this.#e.has(e))return!0;if(t.delete(e),t.size<r)return this.#t.has(e)||this.#t.add(e),!0;const s=this.#r();return s-this.#l>=ae&&(this.#l=s,u({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:t.size,hard_cap:r}})),!1}releaseReservation(e){this.#t.delete(e)}entries(){return this.#e.entries()}async interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r===void 0){const t=await g(e);if(t===null||t.runner==="process"||t.state!=="running")return;await k(e),(await X(t.runner).stop(t,{reason:_})).confirmed&&await y(t.executionId,{reason:_});return}await k(e);try{process.kill(r,"SIGTERM")}catch{}}async hasProfilePauseInterruption(e){return await F(e)}forget(e){this.#e.delete(e),this.#t.delete(e)}#i=new Set;async exitsSettled(){for(;this.#i.size>0;)await Promise.allSettled([...this.#i])}async onChildExit(e,r,t){const s=this.#u(e,r,t);this.#i.add(s);try{await s}finally{this.#i.delete(s)}}async#u(e,r,t){const s=t??(await g(e))?.executionId;t&&await T(t),this.#e.delete(e),s!==void 0&&(await O(s,r),await y(s,{reason:"exited"})),this.#n(async()=>{const a=await w(e),n=a?.launched_at==null?Number.NaN:Date.parse(a.launched_at),d=Number.isFinite(n)?Math.max(0,this.#r()-n):null,f=a?.respawn_failures??0;this.#f(e,r,d,f)})}async deliverExit(e,r){await this.onChildExit(e,r)}async applyDeadRowPolicy(e){await this.#h(e,await M(e))}async terminalizeIfStillNonTerminal(e,r,t,s,a){const n=await w(e);return n===null||n.status==="done"||n.status==="canceled"||n.status==="dead"?!1:(await this.#s(e,n,{event:r,reason:s,detail:a,wake:`Child crashed \u2014 ${p(n)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>re(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){u({level:"info",event:"broker.exit.observed",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:s}})}async#h(e,r){return this.#d(e,r)}async#d(e,r){const t=await w(e);if(t!==null&&A(t.profile_id))return await h(e),"forget";if(await N(e))return await h(e),"forget";if(await ee(e))return"dormant";const s=(await W(e))?.interrupted===!0;if(r?.oomKilled===!0&&t!==null&&t.status!=="done"&&t.status!=="canceled"&&t.status!=="dead")return await h(e),await this.#s(e,t,{event:"broker.out_of_memory",reason:"out_of_memory",detail:{schema:"crtr.node-outcome-detail/v1",message:x(t)},wake:`Child out of memory \u2014 ${p(t)} (${e}) used more memory than its app is allowed and is now dead. It is not restarted automatically. Revive it with \`crtr node lifecycle revive ${e}\` once the work needs less memory or the cap is raised (\`crtr sys limits set\`).`,surface:l(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=se(t,s,await G(e),await B(e));switch(a){case"forget":await h(e);break;case"dormant":await h(e);break;case"release-idle":await h(e),await v(e,"release"),u({level:"info",event:"broker.recovery.released",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#s(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:await E(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>$(t,r),"surface")});break;case"respawn-fresh":case"respawn-cycle":case"respawn-resume":await this.#p(e,t,a,s);break}return a}async#p(e,r,t,s){const a=await R(e);if(a===null)return;const n=a.respawn_failures??0;if(!await this.#o()){await H(e,n,this.#r()),u({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:U,consecutive_failures:n}});return}const d=a.respawn_not_before==null,f=d?await V(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=Y};if(f.exhausted){const c=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${f.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#s(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:c,respawn_failures:f.failures},wake:c,...r.pi_session_id!=null?{surface:l(()=>te(r),"surface")}:{}});return}if(d&&f.notBefore!==null){u({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:j(f.failures),consecutive_failures:f.failures}});return}u({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:f.failures}});try{await J(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(c){if(Q(c)||c instanceof Z){await h(e),await v(e,"release"),u({level:"warn",event:"node.start.refused",node_id:e,error:c,fields:{enact:"respawn"}});return}u({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:c,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",c,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:c instanceof Error?c.message:String(c)})}}async#s(e,r,t){u({level:"error",event:t.event,...o(e)?{node_id:e}:{fields:{affected_node_id:e}}}),await v(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>$(r)))()}catch(s){u({level:"error",event:"broker.boot_failure_surface.failed",...o(e)?{node_id:e}:{fields:{affected_node_id:e}},error:s})}await L(e,"notice.crash",t.wake,{reason:"child-crashed",child:e})}}export{Re as DaemonFleet,se as classifyDeadNode,ie as retryResumeMode,$ as surfaceBootFailure};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var z=Object.defineProperty;var o=(s,f)=>z(s,"name",{value:f,configurable:!0});import{randomUUID as K}from"node:crypto";import{WebSocket as g}from"ws";import{APIError as C}from"../../api/errors.js";import{emitEvent as q}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as H}from"../../api/runtime-version.js";import{crtrVersion as Q}from"../../shared/crtr-version.js";import{connectViewSocket as G}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as Z,LINK_MAX_PAYLOAD_BYTES as ee,parseFrame as ne}from"./frames.js";const te=1e3,re=6e4,oe=64*1024,se=4*1024*1024,ie=1024*1024,de=8*1024*1024,D=15e3,$=75e3;function ce(s){const f=new Map,h=o(()=>{for(;s.open()&&s.bufferedAmount<oe;){let a;for(const S of f)(a===void 0||S[1].bytes<a[1].bytes)&&(a=S);if(a===void 0)return;const[_,m]=a,{data:i,trace:d}=m.frames.shift();m.bytes-=i.length,m.paused!==void 0&&m.bytes<ie&&(m.paused.resume(),m.paused=void 0),m.frames.length===0&&f.delete(_),d?.dequeued(),s.send(i,d===void 0?h:()=>{d.sent(),h()})}},"pump");return{push(a,_,m="",i){if(!s.open())return;const d=f.get(m)??{frames:[],bytes:0};f.set(m,d),d.frames.push({data:a,...i===void 0?{}:{trace:i}}),d.bytes+=a.length,_!==void 0&&d.paused===void 0&&d.bytes>se&&(_.pause(),d.paused=_),h()},waiting:o(()=>[...f.values()].reduce((a,_)=>({bytes:a.bytes+_.bytes,frames:a.frames+_.frames.length}),{bytes:0,frames:0}),"waiting"),drop(a){f.delete(a)},forget(a){for(const _ of f.values())_.paused===a&&(_.paused=void 0)}}}o(ce,"createViewQueue");function ae(s,f){const h=new URL(`/v1/machines/${encodeURIComponent(f)}/link`,s);return h.protocol=h.protocol==="https:"?"wss:":h.protocol==="http:"?"ws:":h.protocol,h.toString()}o(ae,"linkUrl");function be(s){const f=s.backoffMinMs??te,h=s.backoffMaxMs??re,a=s.openView??G,_=s.silenceMs??$;let m=!1,i,d=f,S;const N=new Map,A=new Map,F=200,O=[],U=o(()=>{const l=i;for(;O.length>0&&l?.readyState===g.OPEN;)l.send(JSON.stringify({type:"exit",...O.shift()}))},"flushExits"),x=o((l,t)=>{q({level:"error",event:l,fields:{environment:s.environmentId},error:t})},"fault");let P;const J=o(()=>{if(m)return;if(P!==void 0){if(s.credential()===P){S=setTimeout(J,d),d=Math.min(d*2,h);return}P=void 0}const l=s.credential(),t=new g(ae(s.apiUrl,s.environmentId),{headers:{authorization:`Bearer ${l}`,[H]:Q()},maxPayload:ee,handshakeTimeout:$});i=t;const u=new Map,y=new Map,v=o(e=>{t.readyState===g.OPEN&&t.send(JSON.stringify(e))},"send"),w=ce({get bufferedAmount(){return t.bufferedAmount},open:o(()=>t.readyState===g.OPEN,"open"),send:o((e,n)=>t.send(e,n),"send")}),E=o((e,n,r)=>w.push(JSON.stringify(e),n,e.channel,r),"sendView"),b=o(e=>Math.round(e*10)/10,"round"),L=o(async e=>{const n=s.handlers[e.op];if(n===void 0){v({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const r=new AbortController,c=o(()=>r.abort(new Error("the machine link closed")),"onClose");t.once("close",c);try{v({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,r.signal)??null})}catch(k){v({type:"result",call_id:e.call_id,ok:!1,error:k instanceof Error?k.message:String(k)})}finally{t.off("close",c)}},"runCall"),Y=o(e=>{const n=performance.now(),r=o((p,M={})=>{q({level:"info",event:`daemon.timing.${p}`,node_id:e.node,fields:{channel:e.channel,...M}})},"mark");r("view_open_received",{link_buffered_bytes:t.bufferedAmount});const c=a(e.node);u.set(e.channel,c);const k=performance.now();r("view_open_started",{open_sync_ms:b(k-n)});let R;c.once("connect",()=>{const p=performance.now();R=p;const M=w.waiting(),I=t.bufferedAmount;t.readyState===g.OPEN&&t.send(JSON.stringify({type:"view.ready",channel:e.channel}),()=>r("view_ready_flushed",{send_ms:b(performance.now()-p),link_buffered_bytes:t.bufferedAmount})),r("view_ready_sent",{open_to_connect_ms:b(p-k),queued_bytes:M.bytes,queued_frames:M.frames,link_buffered_bytes_before:I,link_buffered_bytes_after:t.bufferedAmount})});let B=0,j=0,W=!1;c.on("data",p=>{let M;if(!W){const I=performance.now();B+=1,j+=p.length,B===1&&r("view_output_first_received",{bytes:p.length,since_ready_ms:R===void 0?null:b(I-R)}),p.includes(10)&&(W=!0,r("view_welcome_received",{chunks:B,bytes:j,queued_bytes:w.waiting().bytes,link_buffered_bytes:t.bufferedAmount}),M={dequeued:o(()=>r("view_welcome_dequeued",{queue_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"dequeued"),sent:o(()=>r("view_welcome_sent",{since_received_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"sent")})}E({type:"view.data",channel:e.channel,bytes:p.toString("base64")},c,M)}),c.once("error",p=>{R===void 0&&r("view_connect_failed",{open_to_error_ms:b(performance.now()-k),code:p.code??"unknown"}),w.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel,error:p.message})}),c.once("close",()=>{w.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel})})},"openChannel"),X=o((e,n)=>{const r=u.get(e);if(r===void 0||r.write(n))return;const c=(y.get(e)??0)+n.length;if(c>de){u.delete(e),y.delete(e),r.destroy(),E({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}y.has(e)||r.once("drain",()=>y.delete(e)),y.set(e,c)},"writeToChannel");let T;const V=o(()=>{T!==void 0&&clearTimeout(T),T=setTimeout(()=>{q({level:"warn",event:"daemon.machine_link.silent",fields:{environment:s.environmentId}}),t.terminate()},_)},"heard");t.on("open",()=>{d=f,V(),U(),s.onOpen?.()}),t.on("ping",V),t.on("message",e=>{V();const n=ne(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"job.reported":{const r=N.get(n.id);N.delete(n.id),n.error===void 0?r?.resolve():r?.reject(new C(n.error.status,n.error.code,n.error.message));return}case"turns.answer":A.get(n.id)?.(n.turns);return;case"view.open":Y(n);return;case"view.data":X(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const r=u.get(n.channel);u.delete(n.channel),r?.destroy(),w.drop(n.channel);return}default:return}}catch(r){x("daemon.machine_link.frame_failed",r)}}),t.on("unexpected-response",(e,n)=>{let r="";n.on("data",c=>{r+=c.toString("utf8")}).on("close",()=>{t.terminate(),x("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${r}`));try{n.statusCode===426&&s.onBehind?.(JSON.parse(r).error.message)}catch(c){x("daemon.machine_link.client_error",c)}})}),t.on("error",e=>x("daemon.machine_link.client_error",e)),t.on("close",e=>{T!==void 0&&clearTimeout(T);for(const n of u.values())n.destroy();u.clear(),i===t&&(i=void 0);for(const n of A.values())n(void 0);for(const[n,r]of N)N.delete(n),r.reject(new C(503,"machine_offline","the machine link closed before the job report was answered"));m||(e===Z&&(q({level:"error",event:"daemon.machine_link.revoked",fields:{environment:s.environmentId}}),P=l),S=setTimeout(J,d),d=Math.min(d*2,h))})},"connect");return J(),{stop(){m=!0,S!==void 0&&clearTimeout(S),i?.close()},connected:o(()=>i?.readyState===g.OPEN,"connected"),reportJob(l,t,u){const y=i;if(y?.readyState!==g.OPEN)return Promise.reject(new C(503,"machine_offline","the machine link is not open"));const v=K();return new Promise((w,E)=>{const b=setTimeout(()=>{N.delete(v),E(new C(504,"request_timeout","the control plane did not answer the job report"))},s.jobReportTimeoutMs??D);N.set(v,{resolve:o(()=>{clearTimeout(b),w()},"resolve"),reject:o(L=>{clearTimeout(b),E(L)},"reject")}),y.send(JSON.stringify({type:"job.report",id:v,node:l,job:t,request:u}))})},turns(l){const t=i;if(t?.readyState!==g.OPEN)return Promise.resolve(void 0);const u=K();return new Promise(y=>{const v=setTimeout(()=>w(void 0),s.jobReportTimeoutMs??D),w=o(E=>{clearTimeout(v),A.delete(u),y(E)},"answer");A.set(u,w),t.send(JSON.stringify({type:"turns",id:u,brokers:l}))})},reportWedge(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"wedge",...l}))},reportRunning(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"running",executions:l}))},reportExit(l){O.push(l),O.length>F&&O.shift(),U()}}}o(be,"startMachineLink");export{D as JOB_REPORT_TIMEOUT_MS,re as LINK_BACKOFF_MAX_MS,te as LINK_BACKOFF_MIN_MS,$ as LINK_SILENCE_MS,de as VIEW_WRITE_LIMIT_BYTES,ce as createViewQueue,ae as linkUrl,be as startMachineLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var l=(a,t)=>y(a,"name",{value:t,configurable:!0});import{filterAsync as h}from"../../core/async-array.js";import{openDb as A,withCanvasWrite as b}from"../../core/canvas/db.js";import{getNode as I}from"../../core/canvas/canvas.js";import{liveExecutionForNode as k}from"../../core/canvas/executions.js";import{claimFaultNudge as v,listPendingProviderRetries as g,readLiveTurn as E}from"../../core/canvas/recovery.js";import{probeOnline as R}from"../../core/runtime/connectivity.js";import{nextFaultRetry as N}from"../../core/runtime/fault-recovery.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isSafeNodeId as m}from"../../core/canvas/paths.js";import{runThrottledLane as L}from"./throttled-lane.js";import{asNodePerson as S}from"./node-lifecycle/node-person.js";import{wakeResident as T}from"./node-lifecycle/remote-wake.js";const u=2*6e4,F=15e3;function _(a){const{fault:t}=a;if(t.retry.nextAt!==void 0){const i=Date.parse(t.retry.nextAt);return Number.isFinite(i)?i:null}const n=Date.parse(a.updatedAt),o=N(t,n);return Number.isFinite(n)&&o!==null?n+o.delayMs:null}l(_,"dueAtMs");const x=6e4,C="fault-retry-backstop";class J{static{l(this,"FaultRetryBackstopReconciler")}deps;constructor(t={}){this.deps=t}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return Promise.resolve();const o=L(C,"",t,F,x,()=>this.scan(t,n)).then(()=>{}).catch(i=>{p.fresh(()=>{d({level:"warn",event:"fault_retry_backstop.scan_failed",error:i})})});return n.lifecycle.registerDetached(o),o}async scan(t,n){const o=await(this.deps.list??g)(),i=this.deps.busy??(async e=>(await E(e))?.busy===!0),c=await h(o,async e=>{if(!await n.fleet.has(e.nodeId)||await i(e.nodeId))return!1;const r=_(e);return r===null||t<r+u?!1:e.nudgedAt===null||t-Date.parse(e.nudgedAt)>=u});if(c.length===0)return;let f;for(const e of c){if(e.fault.kind==="connection"&&(f??=await(this.deps.probeOnline??(()=>R()))(),!f)||!await n.fleet.has(e.nodeId)||await i(e.nodeId)||!await b(async()=>await v(e.fault.faultId,t,u)))continue;const r=await k(e.nodeId),s=r!==null&&r.runner!=="process"&&r.state==="running"?await I(e.nodeId):null;(r===null||s===null?"woken":await S({node_id:s.node_id,sub:s.sub??null,profile_id:s.profile_id??null},()=>T(r)).catch(w=>(d({level:"warn",event:"fault_retry_backstop.wake_failed",...m(e.nodeId)?{node_id:e.nodeId}:{},error:w}),null)))!=="lost"&&(await(await A()).prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`fault_retry:${e.nodeId}`),p.fresh(()=>{d({level:"info",event:"fault_retry_backstop.nudged",...m(e.nodeId)?{node_id:e.nodeId}:{},fields:{kind:e.fault.kind,since:e.fault.since,overdue_ms:t-(_(e)??t)}})}))}}}export{F as FAULT_RETRY_SCAN_INTERVAL_MS,u as FAULT_RETRY_STALE_GRACE_MS,J as FaultRetryBackstopReconciler,_ as dueAtMs};
|
|
@@ -13,6 +13,6 @@ export declare class IdleSandboxReconciler {
|
|
|
13
13
|
run(now: number, ctx: {
|
|
14
14
|
lifecycle: DetachedWorkLifecycle;
|
|
15
15
|
}): void;
|
|
16
|
-
/** One pass. `deleteExecution` is the runner's delete by default; tests pass their own. */
|
|
16
|
+
/** One pass. `deleteExecution` is the runner's delete of the node's sandbox by default; tests pass their own. */
|
|
17
17
|
pass(now: number, lane?: LanePass, deleteExecution?: (execution: RunnerExecution) => Promise<void>): Promise<IdleSandboxResult>;
|
|
18
18
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var c=(a,n)=>p(a,"name",{value:n,configurable:!0});import{openDb as m}from"../../core/canvas/db.js";import{endExecution as u}from"../../core/canvas/executions.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as _}from"../../core/events/operation-id.js";import{runnerForExecution as f}from"../../core/runtime/runner/index.js";import{runThrottledLane as E}from"./throttled-lane.js";const N=60*6e4,D=10080*6e4,S=10*6e4,I=50;class R{static{c(this,"IdleSandboxReconciler")}run(n,i){if(!i.lifecycle.acceptsDetachedWork())return;const o=_.fresh(()=>E("idle-sandbox","",n,N,S,async t=>{await this.pass(n,t)})).then(()=>{}).catch(t=>{_.fresh(()=>d({level:"error",event:"idle_sandbox.failed",error:t}))});i.lifecycle.registerDetached(o)}async pass(n,i,o=async t=>{await f("blaxel").delete(t.nodeId)}){const t={deleted:0,failed:0},r=new Date(n-D).toISOString(),s=await m(),x=await s.prepare(`SELECT x.execution_id, x.node_id, x.attempt, x.sandbox_name FROM executions x
|
|
2
2
|
JOIN nodes n ON n.node_id = x.node_id
|
|
3
3
|
JOIN profiles p ON p.id = n.profile_id
|
|
4
4
|
JOIN environments e ON e.object = p.environment_id
|
|
5
5
|
WHERE x.runner = 'blaxel' AND x.state = 'running' AND x.idle_at IS NOT NULL AND x.idle_at::timestamptz < ?::timestamptz
|
|
6
6
|
AND e.kind = 'blaxel' AND EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = e.object)
|
|
7
|
-
ORDER BY x.idle_at LIMIT ?`).all(
|
|
7
|
+
ORDER BY x.idle_at LIMIT ?`).all(r,I);for(const e of x){if(i&&!await i.holds())break;try{if(await s.prepare("SELECT 1 AS idle FROM executions WHERE execution_id = ? AND state = 'running' AND idle_at IS NOT NULL AND idle_at::timestamptz < ?::timestamptz").get(e.execution_id,r)===void 0)continue;await o({executionId:e.execution_id,nodeId:e.node_id,attempt:Number(e.attempt),sandboxName:e.sandbox_name}),await u(e.execution_id,{reason:"lost"}),t.deleted+=1,d({level:"info",event:"idle_sandbox.deleted",node_id:e.node_id,fields:{execution_id:e.execution_id}})}catch(l){t.failed+=1,d({level:"warn",event:"idle_sandbox.delete_failed",node_id:e.node_id,error:l,fields:{execution_id:e.execution_id}})}}return t}}export{I as IDLE_SANDBOX_BUDGET,N as IDLE_SANDBOX_INTERVAL_MS,D as IDLE_SANDBOX_MAX_AGE_MS,R as IdleSandboxReconciler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var o=(e,t)=>k(e,"name",{value:t,configurable:!0});import{getNode as _,getRow as h}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as y}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as w}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as S,recordedPidLiveness as v}from"../../core/canvas/pid.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as R}from"../../core/worktree-sweep.js";import{sweepOnMachine as T,worktreeMachineOf as W}from"../../core/worktree-machine.js";import{runThrottledLane as I}from"./throttled-lane.js";const M=60*1e3,O=300*1e3,L=3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)}o(g,"isTerminal");function E(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(E,"hasSweepDisposition");async function b(e,t,r,s){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!g(e)||!E(e,(await _(e.node_id))?.managed_worktree)?!1:s||v(e.pi_pid,e.pi_pid_identity,r)==="dead"}o(b,"engineIsGone");function A(e,t){const r=e.node_id,s=e.pi_pid,i=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(r))return!1;const n=await h(r);return n===null||!g(n)||n.frozen_at!==null||!E(n,(await _(r))?.managed_worktree)?!1:n.pi_pid===s&&n.pi_pid_identity===i},"stillEligible")}}o(A,"eligibilityGuard");class j{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,r){if(!r.lifecycle.acceptsDetachedWork())return;const s=I("managed-worktree-sweep","",t,M,O,i=>this.sweep(t,r.fleet,i)).then(()=>{}).catch(i=>{p.fresh(()=>u({level:"error",event:"worktree.sweep.failed",error:i}))});r.lifecycle.registerDetached(s)}async candidates(t){try{return await y(t)}catch(r){return p.fresh(()=>{u({level:"error",event:"worktree.sweep.scan_failed",error:r})}),null}}async sweep(t,r,s){const i=await this.candidates(t);if(i===null||i.length===0)return;let n=Number(s.state??0);(!Number.isInteger(n)||n>=i.length)&&(n=0);const d=Math.min(L,i.length),l=[];for(let c=0;c<d;c+=1)l.push(i[(n+c)%i.length]);if(!await s.save(String((n+d)%i.length)))return;const a=await S();if(a!==null)for(const c of l){const f=await h(c),m=f===null?null:await W(f.profile_id);if(!(f===null||!await b(f,r,a,m!==null))){if(!await s.holds())return;await this.reconcileOne(f,t,r,m)}}}async reconcileOne(t,r,s,i){const n=t.node_id,d=w(n)?{node_id:n}:{},l=w(n)?{}:{affected_node_id:n};try{const a=await R(n,A(t,s),r,i===null?void 0:T(i,n));p.fresh(()=>{if(a.status==="complete"){u({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...d,fields:l});return}a.status!=="skipped"&&(a.status==="refused"&&a.unchanged===!0||u({level:a.status==="failed"?"error":"warn",event:a.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:a.status==="failed"?"failed":"skipped",...d,fields:{...l,reason:a.reason,...a.detail===void 0?{}:{detail:a.detail}}}))})}catch(a){p.fresh(()=>{u({level:"error",event:"worktree.sweep.failed",...d,error:a,fields:l})})}}}export{j as ManagedWorktreeSweepReconciler,L as WORKTREE_SWEEP_BUDGET,M as WORKTREE_SWEEP_INTERVAL_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var h=Object.defineProperty;var a=(e,
|
|
2
|
-
${o.output}`));const c=await b(e);if(c!==null){const l=await O(c,
|
|
1
|
+
var h=Object.defineProperty;var a=(e,t)=>h(e,"name",{value:t,configurable:!0});import{liveExecutionForNode as _,endExecution as f,recordExecutionAwake as v,endLaunchingExecution as m,requestExecutionStop as x}from"../../../core/canvas/executions.js";import{openDb as E}from"../../../core/canvas/db.js";import{isCloudRole as g}from"../../../core/canvas/person-state.js";import{getRow as b}from"../../../core/canvas/index.js";import{fullName as k}from"../../../core/canvas/labels.js";import{publishNotice as y}from"../../../core/runtime/close.js";import{emitEvent as i}from"../../../core/events/emit.js";import{findRefusal as $,refusalError as A,refusedMark as L,writeCharge as N}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as R}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as S}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as I}from"../ledger-sandbox.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as C}from"../recipe-image.js";import{recordRespawnPolicy as O}from"./respawn-policy.js";import{recordLaunchFailure as T}from"./launch-failure.js";const P=45*6e4,U=12e4,W=a(()=>D(),"acceptedRelease");async function ne(e){return e===null||!g()?null:await R(e)}a(ne,"remoteMachineEnvironmentOf");async function ae(e){const t=await S(e);if(t===null)return;const r={scope:"call",payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,provider:"blaxel"},n=await $(r),s=await E();if(n===null){await s.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await s.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:n.limit.id,usd:n.usd,reset_at:n.reset_at,at:new Date().toISOString()}),e.node_id),await N({id:`refused:sandbox:${e.node_id}:${n.limit.id}:${n.month}`,kind:"sandbox",what:"wake",usd:null,payer:r.payer,funding:"bill",sub:r.sub,grantee:r.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:L(n)}),A(n)}a(ae,"checkBilledWake");class oe extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(t,r){super(`environment ${t} has no built image yet${r===null?"":` (${r})`}; the wake waits for the build.`),this.environmentId=t,this.imageError=r,this.name="EnvironmentImagePending"}}async function ie(e){return await C(e)}a(ie,"imageForWake");async function se(e){if(e.release!==W()){if(await x(e.nodeId,{afterTurn:!1,reason:"release"}),e.stopRequestedAt!==null)return"lost";const t=await u(e.runner).stop(e,{reason:"release"});return t.confirmed?(await f(e.executionId,{reason:"release"}),"lost"):(i({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:t.error}),"lost")}return await u(e.runner).wake(e)==="no_broker"?(await f(e.executionId,{reason:"lost"}),"lost"):(await I(e.executionId,Date.now()),await v(e.executionId),"woken")}a(se,"wakeResident");async function le(e){const t=await u(e.runner).status(e,{idle:e.idleAt!==null});if(t.state!=="gone"&&t.state!=="failed")return!1;const r=await f(e.executionId,{reason:"lost"});return r&&i({level:"warn",event:"execution.lost",node_id:e.nodeId}),r}a(le,"endRemoteExecutionIfGone");async function ue(e,t){const r=await _(e);if(r===null||r.state!=="launching"||r.runner==="process")return!1;const n=u(r.runner),s=t-Date.parse(r.startedAt),o=await n.status(r);if(o.state==="unknown")return!1;if(o.state==="running")return s<=P||!await m(r.executionId,{reason:"launch_timeout"})?!1:(await n.stop(r,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),i({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(o.state==="failed"){if(!await m(r.executionId,{reason:"launch_failed"}))return!1;const d=`the sandbox start script failed: ${o.reason}`;await T(r.executionId,new Error(o.output===void 0?d:`${d}
|
|
2
|
+
${o.output}`));const c=await b(e);if(c!==null){const l=await O(c,t);if(!l.exhausted)i({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:o.reason,consecutive_failures:l.failures}});else{const p=`Child crashed \u2014 ${k(c)} (${e}) failed ${l.failures} consecutive sandbox launches (${d}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;i({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:p,respawn_failures:l.failures}}}),await y(e,"notice.crash",p,{reason:"child-crashed",child:e})}}return await n.delete(r.nodeId),!0}if(s>U){if(!await m(r.executionId,{reason:"launch_lost"}))return!1;i({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(ue,"recoverLaunching");export{oe as EnvironmentImagePending,P as LAUNCH_DEADLINE_MS,U as LAUNCH_LOST_GRACE_MS,W as acceptedRelease,ae as checkBilledWake,le as endRemoteExecutionIfGone,ie as imageForWake,ue as recoverLaunching,ne as remoteMachineEnvironmentOf,se as wakeResident};
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type { Transport } from '../../core/broker-client/transport.js';
|
|
2
|
+
/** The transport to the node's live broker, from where its runner says viewers connect: this machine's `view.sock`, or
|
|
3
|
+
* the `/view` WebSocket behind a sandbox's preview. */
|
|
4
|
+
export declare function viewTransport(nodeId: string): Promise<Transport>;
|
|
1
5
|
/** What the model is streaming now in a node's open assistant message. */
|
|
2
6
|
export type OpenAssistantBlock = {
|
|
3
7
|
kind: 'thinking' | 'text';
|
|
@@ -3,4 +3,4 @@ var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});i
|
|
|
3
3
|
FROM node_rows n
|
|
4
4
|
LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
|
|
5
5
|
AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
|
|
6
|
-
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers};
|
|
6
|
+
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,$ as viewTransport};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var J=Object.defineProperty;var l=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as $,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as L}from"../shared/env.js";import{coalesceBrokerInbox as V,entryCards as Q}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as O,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as P}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as D}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as g}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as x}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as _,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const E=64,U=16;let v,ce=0;class q extends Error{static{l(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:z(),debounceMs:j()}}l(me,"resolveCadence");function T(){const r=G();return r===void 0||r.trim()===""?void 0:r}l(T,"currentNodeId");function B(){const r=X();return r!==void 0&&r!==""&&fe(r)}l(B,"profilePaused");function S(r){try{return oe(r)}catch{return{class:"unknown"}}}l(S,"safeErrorClass");function w(r){try{D(r)}catch{}}l(w,"emitBestEffort");function I(r){try{g.fresh(t=>{w({...r,operation_id:t})})}catch{}}l(I,"emitFreshBestEffort");function F(r,t){try{g.run(r,()=>{w({...t,operation_id:r})})}catch{}}l(F,"emitStoredBestEffort");function pe(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}l(pe,"deliveryOrigin");function k(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}l(k,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}l(b,"deliveryFields");function ye(r){F(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}l(ye,"emitDeliveryCompleted");function M(r,t,e,i){F(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:e,...b(t)}})}l(M,"emitDeliveryFailure");function R(r,t){F(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}l(R,"emitDeliveryAbandoned");function ge(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
-
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return String(s?.message).startsWith("conversation_write_failed")&&(D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"conversation_write_failed"}}),await Z(t,s),H()?.("conversation_write_failed",1)),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|
|
2
|
+
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|