@north-light/cli 0.3.670 → 0.3.671
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +2 -0
- package/dist/api/dto/execution-start.d.ts +7 -0
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/node/bash.js +3 -3
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/canvas/canvas.d.ts +10 -1
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/canvas/schema-pg/022-create-request-lease.sql +5 -0
- package/dist/core/canvas/schema-pg/023-machine-calls-job-stop.sql +7 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/runtime/broker/boot-state.d.ts +8 -0
- package/dist/core/runtime/broker/boot-state.js +1 -1
- package/dist/core/runtime/broker/cycle-start.d.ts +8 -1
- package/dist/core/runtime/broker/cycle-start.js +2 -2
- package/dist/core/runtime/broker/turn-admission.d.ts +4 -1
- package/dist/core/runtime/broker/turn-admission.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.d.ts +3 -3
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/ops.d.ts +18 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/delivery.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/cron/machine-fire.d.ts +3 -0
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/crtrd.js +16 -16
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/job-sweep.d.ts +7 -0
- package/dist/daemon/machine-link/job-sweep.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/daemon/reconcilers/machine-offline.d.ts +6 -0
- package/dist/daemon/reconcilers/machine-offline.js +7 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +1 -1
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/execution-start.js +0 -1
- package/packages/crouter-api/dist/commands/node/bash.js +7 -4
- package/packages/crouter-api/dist/core/bash-job-supervisor.js +15 -2
- package/packages/crouter-api/dist/core/canvas/canvas.js +23 -2
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/grants/sync.js +3 -0
- package/packages/crouter-api/dist/core/runtime/revive-all.js +108 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +13 -2
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +140 -0
- package/packages/crouter-api/dist/daemon/cron/capture.js +50 -0
- package/packages/crouter-api/dist/daemon/cron/closed.js +108 -0
- package/packages/crouter-api/dist/daemon/cron/disposition.js +63 -0
- package/packages/crouter-api/dist/daemon/cron/ended.js +80 -0
- package/packages/crouter-api/dist/daemon/cron/escalation.js +136 -0
- package/packages/crouter-api/dist/daemon/cron/held.js +20 -0
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +177 -0
- package/packages/crouter-api/dist/daemon/cron/narrowed.js +34 -0
- package/packages/crouter-api/dist/daemon/cron/recurrence.js +38 -0
- package/packages/crouter-api/dist/daemon/cron/run-token.js +37 -0
- package/packages/crouter-api/dist/daemon/cron/settle.js +78 -0
- package/packages/crouter-api/dist/daemon/cron/sinks.js +70 -0
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
var k=Object.defineProperty;var
|
|
1
|
+
var k=Object.defineProperty;var c=(n,r)=>k(n,"name",{value:r,configurable:!0});import{chmodSync as T,existsSync as x,mkdirSync as S,unlinkSync as R,writeFileSync as j,rmSync as M}from"node:fs";import{createServer as O}from"node:http";import{dirname as P}from"node:path";import{apiSocketPath as C}from"../core/canvas/paths.js";import{bindDaemonEventSource as F}from"../core/events/source.js";import{emitEvent as p}from"../core/events/emit.js";import{createMachineExecutor as G,stopAllBrokers as H}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as N}from"../core/checkout-identities.js";import{machineWorktreeHandlers as Y}from"../core/worktree-machine.js";import{readPersonCredential as B}from"../core/directory/person-credential.js";import{socketDir as D}from"../core/layout.js";import{isDaemonRunning as A,pidfilePath as v,readPidfile as J}from"./pidfile.js";import{cancelMachineCron as U,runMachineCron as X,stopOrphanedMachineCrons as z}from"./cron/machine-exec.js";import{startMachineLink as L}from"./machine-link/client.js";import{deleteMoveRecord as I,readMachineConfig as W,readMachineCredential as b,readMoveRecord as K,writeMoveRecord as Q}from"./machine-link/config.js";import{jobExitReporting as V,stopMachineJob as Z}from"./machine-link/job-sweep.js";import{notifyMoveFinished as $}from"./machine-link/move-notify.js";const E=1024;function q(n,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:n,signed_in:r,startup_phase:n?"ready":"recovering"}}c(q,"machineHealth");async function Se(){const n=W();if(n===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=B()!==void 0;if(r&&b(),A())throw new Error("a crtrd is already running for this home");F(),r||(await H(),await z(),p({level:"info",event:"daemon.machine.signed_out",fields:{environment:n.environmentId}})),S(D(),{recursive:!0,mode:493});const d=C();x(d)&&R(d);let e;const m=V(()=>e),o=O((t,i)=>{const u=(t.url??"").split("?")[0];if(t.method==="POST"&&(u==="/job-exit"||u==="/job-activity")){const _=[];let h=0;t.on("data",s=>{h+=s.length,h<=E&&_.push(s)}),t.on("end",()=>{if(h>E){i.writeHead(413),i.end();return}let s={};try{s=JSON.parse(Buffer.concat(_).toString("utf8"))}catch{}const g=typeof s.node=="string"&&typeof s.job=="string";i.writeHead(g?202:400,{"content-type":"application/json; charset=utf-8"}),i.end("{}"),g&&(u==="/job-exit"?m.notice:m.activity)(s.node,s.job)});return}const w=(t.method??"GET")==="GET"&&(t.url??"/").split("?")[0]==="/healthz";i.writeHead(w?200:404,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify(w?q(e?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((t,i)=>{o.once("error",i),o.listen(d,()=>{o.off("error",i),T(d,384),t()})}),S(P(v()),{recursive:!0}),j(v(),String(process.pid),"utf8");let f;await te(n.runId,r,()=>f!==void 0);const a=G({apiUrl:n.apiUrl,environmentId:n.environmentId,onExit:c(t=>e?.reportExit(t),"onExit")});e=r?L({apiUrl:n.apiUrl,environmentId:n.environmentId,credential:b,onOpen:m.onOpen,handlers:{start:a.start,wake:a.wake,stop:a.stop,status:a.status,"status.all":a["status.all"],delete:a.delete,viewer:a.viewer,"cron.run":X,"cron.cancel":U,"job.stop":c(t=>Z(t),"job.stop"),...Y,...N}}):void 0,p({level:"info",event:"daemon.machine.started",fields:{environment:n.environmentId}});const y=c(()=>f??=(async()=>{e?.stop(),await new Promise(t=>{o.close(()=>t()),o.closeAllConnections()}),J()===process.pid&&(M(d,{force:!0}),M(v(),{force:!0})),process.off("SIGINT",l),process.off("SIGTERM",l)})(),"teardown"),l=c(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",l),process.on("SIGTERM",l),y}c(Se,"runMachineDaemon");const ee=5e3,ne=3e5;async function te(n,r,d){let e;try{e=K()}catch(o){p({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:o.message}});return}if(e===void 0||e.state==="running"||e.runId!==n)return;if(e.notified||e.notify===null){I();return}if(e.state==="committed"&&(e={...e,state:"activated"},Q(e)),!r)return;const m=e;(async()=>{let o=ee;for(;;){try{await $(m),I();return}catch(f){p({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:m.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,o).unref()}),d())return;o=Math.min(o*2,ne)}})()}c(te,"settleFinishedMove");export{q as machineHealth,Se as runMachineDaemon};
|
|
@@ -1,15 +1,22 @@
|
|
|
1
|
+
import type { MachineJobStopArgs, MachineJobStopResult } from '../../core/runtime/runner/machine/ops.js';
|
|
1
2
|
import type { MachineLink } from './client.js';
|
|
2
3
|
type JobLink = Pick<MachineLink, 'connected' | 'reportJob'>;
|
|
4
|
+
/** What the Mac does for a `job.stop` call: stop the job's process tree. A node or job this home does not know, or one already ended, is a no-op. */
|
|
5
|
+
export declare function stopMachineJob(args: MachineJobStopArgs): Promise<MachineJobStopResult>;
|
|
3
6
|
/** The supervisor of `job` of `node` wrote its exit: upload its remaining output and the exit. The daemon reports whether or not the node has a broker: a
|
|
4
7
|
* broker's own reporter may have the same job in flight, and the control plane stores a report once (a second answers `job_not_running`, which only marks the
|
|
5
8
|
* job done), so no check of which brokers run is needed and an exit is reported even when its broker stopped or was killed first. A report that fails while
|
|
6
9
|
* the link is up (timeout, 5xx, database error) is retried for this one job with doubling delays; when the link is down the next `recoverJobs` takes over. */
|
|
7
10
|
export declare function reportJobExit(link: JobLink, node: string, job: string, delays?: readonly number[]): Promise<void>;
|
|
11
|
+
/** The supervisor of `job` of `node` saw its output activity move while the node may have no broker: one report pass for this job, so the control plane
|
|
12
|
+
* gets the fresh `job.activity`. No retry and nothing marked settled here: only an exit or `job_not_running` ends a job, and `recoverJobs` still covers the rest. */
|
|
13
|
+
export declare function reportJobActivity(link: JobLink, node: string, job: string): Promise<void>;
|
|
8
14
|
/** One pass over every node dir of this home: report each unreported job (exit written while nobody listened, or process gone). */
|
|
9
15
|
export declare function recoverJobs(link: JobLink): Promise<void>;
|
|
10
16
|
/** Wire both triggers to a link: returns the `onOpen` hook (the pass at start and at every reconnect) and the handler of the supervisor's notice. */
|
|
11
17
|
export declare function jobExitReporting(getLink: () => JobLink | undefined): {
|
|
12
18
|
onOpen: () => void;
|
|
13
19
|
notice: (node: string, job: string) => Promise<void>;
|
|
20
|
+
activity: (node: string, job: string) => Promise<void>;
|
|
14
21
|
};
|
|
15
22
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var i=(t,e)=>y(t,"name",{value:e,configurable:!0});import{readdirSync as w}from"node:fs";import{join as l}from"node:path";import{appsRoot as h}from"../../core/layout.js";import{JobReporter as x,isJobReportSettled as J}from"../../core/runtime/broker/job-reporter.js";import{isSafeNodeId as s}from"../../core/canvas/paths.js";import{isSafeBashJobId as d,stopBackgroundBashJob as v}from"../../core/bash-jobs.js";import{emitEvent as R}from"../../core/events/emit.js";const b=i(t=>{try{return w(t)}catch{return[]}},"dirs");function a(t){const e=[];for(const o of b(h())){const n=l(h(),o,"nodes");for(const r of t===void 0?b(n):[t])s(r)&&e.push([r,l(n,r,"context")])}return e}i(a,"nodeContexts");async function Y(t){if(!s(t.node)||!d(t.job))return{stopped:!1};let e=!1;for(const[,o]of a(t.node))e=(await v(o,t.job,!0,t.node,"stopped by the control plane")).kind==="stopped"||e;return{stopped:e}}i(Y,"stopMachineJob");const p=new Map;function u(t,e,o,n){const c=(p.get(o)??Promise.resolve()).then(()=>new x(o,(f,m)=>t.reportJob(e,f,m)).tick(n)).finally(()=>{p.get(o)===c&&p.delete(o)});return p.set(o,c),c}i(u,"reportOne");const S=[1e3,2e3,4e3,8e3,16e3,32e3];async function E(t,e,o,n=S){if(!s(e)||!d(o))return;const r=a(e).map(([,c])=>c);for(let c=0;t.connected();c++){for(const f of r)await u(t,e,f,o);if(r.every(f=>J(f,o))||c>=n.length)return;await new Promise(f=>{setTimeout(f,n[c]).unref()})}}i(E,"reportJobExit");async function _(t,e,o){if(!(!s(e)||!d(o)||!t.connected()))for(const[,n]of a(e))await u(t,e,n,o)}i(_,"reportJobActivity");async function B(t){if(t.connected())for(const[e,o]of a())await u(t,e,o)}i(B,"recoverJobs");function q(t){const e=i(o=>{R({level:"error",event:"daemon.machine_link.job_report_failed",error:o})},"failed");return{onOpen:i(()=>{const o=t();o!==void 0&&B(o).catch(e)},"onOpen"),notice:i(async(o,n)=>{const r=t();r!==void 0&&await E(r,o,n).catch(e)},"notice"),activity:i(async(o,n)=>{const r=t();r!==void 0&&await _(r,o,n).catch(e)},"activity")}}i(q,"jobExitReporting");export{q as jobExitReporting,B as recoverJobs,_ as reportJobActivity,E as reportJobExit,Y as stopMachineJob};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var J=Object.defineProperty;var _=(s,e)=>J(s,"name",{value:e,configurable:!0});import{existsSync as v,readFileSync as B,readdirSync as C,statSync as S}from"node:fs";import{bashJobPaths as g,bashJobsDir as E,clearJobDeadlineFile as T,formatBashElapsed as D,isBashJobProcessConfirmedGone as O,readJobSupervisorState as b,signalBashJob as R}from"../../core/bash-jobs.js";import{queueJobStop as L}from"../cron/machine-fire.js";import{killBashJobObject as P,recordBashJobObject as j}from"../../core/spaces/stop.js";import{readFileBeneath as N}from"../../core/spaces/open-beneath.js";import{blobStore as U}from"../../core/blobs/index.js";import{openDb as c,withCanvasWrite as f}from"../../core/canvas/db.js";import{applyJobReport as k,endJobsOfExitedSandboxes as q,endReportedJobs as F,expiredJobs as K,jobRow as z,ownerRunsRemotely as y,recordJobSilence as G,runningJobs as M,setJobDeadline as V}from"../../core/graph/jobs.js";import{publish as Y}from"../../core/graph/events.js";import{envBashSilenceMs as $}from"../../shared/env.js";import{getById as A}from"../../core/graph/objects.js";import{isSafeNodeId as u}from"../../core/canvas/paths.js";import{contextDir as x}from"../../core/canvas/node-agent-paths.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isProfilePaused as H}from"../../core/profiles/manifest.js";import{runThrottledLane as W}from"./throttled-lane.js";const X=300*1e3;function Q(s,e,t){const i=s<t?0:s<2*t?t:s<4*t?2*t:4*t*Math.floor(s/(4*t));return i>e?i:null}_(Q,"dueSilenceThresholdMs");const Z=5*1e3,tt=60*1e3,m=64*1024;class vt{static{_(this,"BashDeadlineReconciler")}startedAt=Date.now();uploadedBytes=new Map;async run(e,t){await this.mirrorSupervisors(t),await this.publishExits(),await W("bash-deadline","",e,Z,tt,i=>this.scan(e,t,i))}async scan(e,t,i){const a=new Set;for(const n of t.rows)if(n.status!=="dead"&&!H(n.profile_id)&&(a.add(n.node_id),!await y(await c(),n.node_id)))try{await this.adoptUnrecorded(n.node_id,await x(n.node_id))}catch(o){p.fresh(()=>{l({level:"error",event:"bash_deadline.scan_failed",...u(n.node_id)?{node_id:n.node_id}:{},error:o})})}for(const n of await K(await c(),e))if(a.has(n.owner)){if(!await i.holds())return;await this.cancel(n)}for(const n of a)try{await this.warnSilent(n,e)}catch(o){p.fresh(()=>{l({level:"error",event:"bash_silence.scan_failed",...u(n)?{node_id:n}:{},error:o})})}}async warnSilent(e,t){const i=$(),a=await y(await c(),e);for(const n of await M(await c(),e)){const o=n.activity??(a?{lastActivityMs:n.startedAtMs,sampledAtMs:t,files:[]}:null);if(n.quietOk||o===null||!a&&t-o.sampledAtMs>X)continue;const r=t-o.lastActivityMs,d=n.silence,I=Q(r,d?.lastActivityMs===o.lastActivityMs?d.thresholdMs:0,i);I!==null&&await f(async h=>{const w=await A(h,n.jobId);w===null||w.type!=="job"||(await z(h,w))?.status!=="running"||(await Y(h,{event:"silent",object:w,actor:null,attrs:{"silent-for":D(r),files:o.files.join(", "),"output-key":n.outputKey}}),await G(h,n.jobId,o.lastActivityMs,I))})}}async mirrorSupervisors(e){for(const t of e.rows)if(t.status!=="dead")try{const i=await M(await c(),t.node_id);if(i.length===0||await y(await c(),t.node_id))continue;const a=await x(t.node_id);for(const n of i)await this.mirror(a,n)}catch(i){p.fresh(()=>{l({level:"error",event:"bash_mirror.failed",...u(t.node_id)?{node_id:t.node_id}:{},error:i})})}}async mirror(e,t){const i=b(e,t.jobId),a=i.pgid??t.pgid??void 0,n=i.pgidIdentity??t.pgidIdentity??void 0,o=i.exitCode===void 0&&O(a,n)&&b(e,t.jobId).exitCode===void 0;i.deadlineMs!==void 0&&(t.deadlineAtMs===null&&await f(r=>V(r,t.jobId,i.deadlineMs)),T(g(e,t.jobId))),await this.uploadOutput(e,t),(i.exitCode!==void 0||o)&&this.uploadedBytes.delete(t.jobId),await f(async r=>k(r,t.jobId,{...i.pgid===void 0||i.pgid===t.pgid?{}:{pgid:i.pgid},...i.pgidIdentity===void 0||i.pgidIdentity===t.pgidIdentity?{}:{pgidIdentity:i.pgidIdentity},...i.activity===void 0?{}:{activity:i.activity},...i.exitCode===void 0?{}:{exitCode:i.exitCode},...o?{vanished:!0}:{}}))}async uploadOutput(e,t){const i=g(e,t.jobId);let a;try{a=S(i.jobLog).size}catch{return}const n=this.uploadedBytes.get(t.jobId)??0;if(a<=n)return;const o=await U(),r=N(i.root,i.jobLog);for(let d=Math.floor(n/m);d*m<r.length;d++)await o.put(`${t.outputKey}/${String(d).padStart(8,"0")}`,r.subarray(d*m,(d+1)*m));this.uploadedBytes.set(t.jobId,r.length)}async publishExits(){try{await f(async e=>{await F(e),await q(e)})}catch(e){p.fresh(()=>l({level:"error",event:"bash_completion.delivery_failed",error:e}))}}async adoptUnrecorded(e,t){let i;try{i=C(E(t))}catch{return}await f(async a=>{for(const n of i){if(await A(a,n)!==null)continue;const o=g(t,n);!v(o.jobBg)||!v(o.cmdSh)||v(o.jobExit)&&S(o.jobExit).mtimeMs<this.startedAt||await j(e,n,{command:B(o.cmdSh,"utf8")})}})}async cancel(e){const t=await y(await c(),e.owner);!t&&(e.pgid===null||e.pgidIdentity===null)||await p.fresh(async()=>{try{if(t||await R(e.pgid,e.pgidIdentity,e.owner),!await P(e.jobId,async()=>null,"deadline"))return;t&&await L(e.owner,e.jobId),l({level:"info",event:"bash_deadline.canceled",...u(e.owner)?{node_id:e.owner}:{},fields:{job_id:e.jobId}})}catch(i){l({level:"error",event:"bash_deadline.notice_failed",...u(e.owner)?{node_id:e.owner}:{},error:i,fields:{job_id:e.jobId}})}})}}export{vt as BashDeadlineReconciler,Q as dueSilenceThresholdMs};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** 5 minutes (20 link renewals): a connected link renews every 15 s and the Mac reconnects with backoff of at most 60 s, so a Mac between renewals or reconnecting after a brief drop or an API roll never reaches it. */
|
|
2
|
+
export declare const MACHINE_OFFLINE_NOTICE_MS: number;
|
|
3
|
+
export declare class MachineOfflineReconciler {
|
|
4
|
+
run(now: number): Promise<void>;
|
|
5
|
+
private notify;
|
|
6
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var _=Object.defineProperty;var d=(o,e)=>_(o,"name",{value:e,configurable:!0});import{openDb as c}from"../../core/canvas/db.js";import{isCloudRole as N}from"../../core/canvas/person.js";import{subscribersOf as p}from"../../core/canvas/tree.js";import{enqueueNodeMail as m}from"../../core/feed/messages.js";import{operationIdContext as O}from"../../core/events/operation-id.js";import{emitEvent as w}from"../../core/events/emit.js";const E=5*6e4;async function u(o){const e=await c(),a=new Map,t=d((n,s)=>{n!==null&&a.set(n,(a.get(n)??new Set).add(s))},"add"),i="JOIN profiles p ON p.id = n.profile_id WHERE p.environment_id = ?",r=await e.prepare(`SELECT DISTINCT x.node_id FROM executions x JOIN nodes n ON n.node_id = x.node_id ${i}
|
|
2
|
+
AND x.runner = 'machine' AND x.state IN ('launching', 'running')`).all(o);for(const{node_id:n}of r)for(const s of await p(n))t(s.node_id,`its report ${n} runs on it`);const l=await e.prepare(`SELECT DISTINCT m.sender_node_id, d.destination_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
3
|
+
JOIN nodes n ON n.node_id = d.destination_id ${i}
|
|
4
|
+
AND d.state IN ('pending', 'handed_off') AND d.canceled_at IS NULL AND m.sender_node_id IS NOT NULL`).all(o);for(const n of l)t(n.sender_node_id,`its message to ${n.destination_id} is waiting for delivery`);const f=await e.prepare(`SELECT c.created_by, c.name FROM crons c JOIN profiles p ON p.id = c.profile
|
|
5
|
+
WHERE p.environment_id = ? AND c.run_state = 'running' AND c.run_execution_id IS NOT NULL AND c.created_by IS NOT NULL`).all(o);for(const n of f)t(n.created_by,`its cron ${n.name} has a run waiting to start on it`);return new Map([...a].map(([n,s])=>[n,[...s]]))}d(u,"waitersOn");class T{static{d(this,"MachineOfflineReconciler")}async run(e){if(!N())return;const t=await(await c()).prepare(`SELECT e.object, e.last_seen_at, o.name FROM environments e JOIN objects o ON o.id = e.object
|
|
6
|
+
WHERE e.kind = 'machine' AND e.last_seen_at < ?
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM machine_links l WHERE l.environment = e.object AND l.lease_expires_at > ?)`).all(new Date(e-E).toISOString(),new Date(e).toISOString());for(const i of t)try{await O.fresh(()=>this.notify(i))}catch(r){w({level:"warn",event:"machine.offline_notice_failed",fields:{environment:i.object},error:r})}}async notify(e){const a=await c();for(const[t,i]of await u(e.object))await a.prepare("SELECT 1 AS live FROM nodes WHERE node_id = ? AND status IN ('active', 'idle')").get(t)!==void 0&&await m(t,{kind:"update",label:"machine offline",urgency:"normal",wake:1,bodyJson:{body:`The Mac ${e.name??e.object} has been offline since ${e.last_seen_at}; ${i.join("; ")}. Nothing was stopped: everything resumes when it reconnects.`},idempotencyKey:`machine-offline:${e.object}:${e.last_seen_at}:${t}`})}}export{E as MACHINE_OFFLINE_NOTICE_MS,T as MachineOfflineReconciler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var
|
|
1
|
+
var g=Object.defineProperty;var d=(s,a)=>g(s,"name",{value:a,configurable:!0});import{MachineOfflineError as z}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as L,getRow as M}from"../../../core/canvas/index.js";import{isSafeNodeId as N}from"../../../core/canvas/paths.js";import{recordedPidLiveness as x}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as D,hasObservedExit as F,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as A}from"../../../core/events/operation-id.js";import{readInterruptedTurn as C}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as S,isParkedResident as G}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as R}from"./respawn-policy.js";import{asNodePerson as H,NodePersonUnresolvedError as k}from"./node-person.js";import{handleTerminatingRow as q}from"./terminating.js";import{wantsExecution as j}from"./wants-execution.js";import{enactRequestedStops as J}from"./requested-stops.js";import{endRemoteExecutionIfGone as K,recoverLaunching as Q,wakeResident as V}from"./remote-wake.js";import{endGoneMachineExecutions as X}from"./machine-sweep.js";import{isDrained as Y}from"../../drain.js";function Z(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(Z,"isTerminal");const $=12e4;function ee(s,a,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&a-i<$&&e?.state!=="exited"}d(ee,"isLaunchInFlight");async function b(s){const a=await p(s);return a!==null&&a.state==="running"&&a.pid!=null&&x(a.pid,a.processIdentity)==="dead"?a:null}d(b,"executionWithDeadPid");class be{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(a,e){await J(a);const i=await X();if(i.size===0)return await this.pass(a,e);const n=await Promise.all(e.rows.map(async t=>i.has(t.node_id)?await M(t.node_id)??t:t));return await this.pass(a,{...e,rows:n})}async runNode(a,e,i){await this.pass(a,{rows:[e],fleet:i})}async pass(a,e){const i=[];for(const n of e.rows)await A.fresh(async()=>{try{await H(n,()=>this.classifyRow(a,n,e,i))}catch(t){const o=n.node_id;E({level:t instanceof k?"warn":"error",event:t instanceof k?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...N(o)?{node_id:o}:{fields:{affected_node_id:o}},error:t})}});return await Y()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(a,{fleet:e.fleet,candidates:i})}async classifyRow(a,e,i,n){const t=e.node_id;if(Z(e)){if(q(e,await i.fleet.has(t)))return;if(G(e)&&!await i.fleet.has(t)&&!f(e.profile_id)&&!await I(t)&&!R(e,a)&&await m(t)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(t);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(t):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(t)){const r=await p(t);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(t))try{if(await V(r)==="lost")return}catch(l){if(l instanceof z)return;throw l}else r?.runner==="blaxel"&&r.state==="running"&&await K(r);if(await i.fleet.has(t)){f(e.profile_id)?await i.fleet.interruptForProfilePause(t):await this.thawMark(e);return}}if(await Q(t,a))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(t);return}if(await I(t))return;const o=e.pi_pid==null?await v(t):null,u=o!==null&&F(o),h=o!==null&&!u&&D(o),_=e.pi_pid!=null?await b(t):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(t)){const r=_??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const l=await p(t);if(l!==null&&l.executionId!==r?.executionId)return}if(!await j(e)){await this.thawMark(e),await this.settleParked(e);return}if(R(e,a))return;if(e.status==="idle"&&S(e)&&await m(t)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(t)||ee(e,a,await v(t)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:t}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await L(t),(await C(t))?.interrupted===!0,await U(t));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(t),await this.thawMark(e)}async thawMark(a){a.frozen_at!=null&&await w(a.node_id)}async settleParked(a){if(a.status!=="idle")return;await this.freezeLane.endEpisode(a.node_id);const e=await W(a.node_id,a.lifecycle);e!=="release"&&await T(a.node_id,e)}}export{$ as LAUNCH_GRACE_MS,be as NodeLifecycleReconciler,ee as isLaunchInFlight};
|
|
@@ -1,2 +1,2 @@
|
|
|
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{
|
|
2
|
-
`):""}l(pe,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function ye(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(ye,"disposalReasonForShutdown");function ge(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(ge,"boundedRuntimeReason");class be{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!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(pe(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)?ye(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ge(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&&fe())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:M(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(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:M(i),fields:{stage:"poll"}});return}if(this.polledOk&&ie(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),F(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(ne(i,n),s==="idle"){const a=oe();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,ce(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 se(t,a.text).catch(()=>{}),re(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),F(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)F(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&&me(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=te(),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 ve(r,t){v?.dispose("reload",!1);const e=new be(r,t,++he);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[le]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(ve,"installWatcher");function we(r){const t=ve(r,ue());return()=>t.dispose("shutdown",!1)}l(we,"registerCanvasInboxWatcher");var He=we;export{He as default,we as registerCanvasInboxWatcher};
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Z=Object.defineProperty;var l=(r,t)=>Z(r,"name",{value:t,configurable:!0});import{brokerSignalClient as C}from"../core/runtime/broker/signal-stream.js";import{brokerExecutionId as ee}from"../core/runtime/broker/daemon-ops.js";import{takeCycleBind as te}from"../core/runtime/broker/cycle-start.js";import{markSeededStateBound as ne}from"../core/runtime/broker/boot-state.js";import{envNodeId as re}from"../shared/env.js";import{stripCdPrefix as oe}from"../shared/strip-cd-prefix.js";import{brokerRecovery as se,mutateBrokerFault as Y,recordBrokerTelemetry as ae,recordBrokerTurn as A,clearBrokerPushedFinal as ie,consumeBrokerPushedFinal as le}from"../core/runtime/broker/daemon-ops.js";import{bindBrokerSession as ce,cachedBrokerNode as j,postBrokerIdle as ue,relaunchBrokerRoot as de,settleBroker as z,startBrokerCycle as fe}from"../core/runtime/broker/daemon-ops.js";import{emitEvent as F}from"../core/events/emit.js";import{brokerStartCycle as he}from"../core/runtime/broker/held-deferred-inbox.js";import{CONTEXT_NUDGE_CUSTOM_TYPE as me,formatCard as ye}from"../shared/generated-context.js";import{isReviewBoundary as pe}from"../core/runtime/session-visibility.js";import{clearRefusedTurn as ge,isRuntimeTeardownInProgress as we,refuseTurn as _e,runRefreshAbort as ke}from"../core/runtime/broker/extension-abort.js";import{announceMessageOrigin as G}from"../core/runtime/stamp/channel.js";const Q=80;function be(r,t){const i=t??{},s=l(_=>typeof _=="string"?_:"","pick"),c=oe(s(i.command).trim())||s(i.path)||s(i.file_path)||s(i.pattern)||s(i.description)||s(i.prompt),f=(c!==""?`${r}: ${c}`:r).replace(/\s+/g," ").trim();return f.length>Q?f.slice(0,Q):f}l(be,"summarizeActivity");function ve(r){for(let t=r.length-1;t>=0;t--)if(r[t]?.role==="assistant")return r[t]}l(ve,"lastAssistantMessage");function Te(r){try{const t=r?.sessionManager?.getBranch();if(!Array.isArray(t))return[];const i=new Set;for(const s of t){if(!pe(s))continue;const u=s.details?.reviewId;typeof u=="string"&&i.add(u)}return[...i]}catch{return[]}}l(Te,"currentReviewBoundaryIds");const V=1e4,S=[13e4,15e4,17e4,185e3,2e5];function Ce(r){const t=S[0],i=S[S.length-1];if(r<t)return null;if(r>=i)return i+Math.floor((r-i)/V)*V;let s=t;for(const u of S)r>=u&&(s=u);return s}l(Ce,"steerBand");function Ae(r,t,i){const s=Math.round(r/1e3),u=r>=185e3,c="This is not a request to stop: keep going until your task is done.";if(i==="orchestrator")return r<15e4?`Context ~${s}k and growing. ${c} When you reach a good stopping point, consider updating your roadmap (\`crtr doc edit roadmap\`) and running \`crtr node yield\` to refresh against it \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. ${c} Bring your roadmap current, hand off anything outstanding, and \`crtr node yield\` immediately to refresh before this context overflows; the fresh window continues the work.`:`Context ~${s}k. ${c} Update your roadmap (\`crtr doc edit roadmap\`) so a fresh revive can continue, delegate any outstanding work, then \`crtr node yield\` to refresh.`;if(t==="resident"){const f="If substantial work remains, `crtr node yield` to continue fresh against your goal and your note. Add --promote only when worthwhile independent work can run in parallel and coordinating it should become your primary job; `crtr node yield -h` has the boundary.";return r<15e4?`Context ~${s}k and growing. ${c} ${f} Otherwise no rush.`:u?`Context ~${s}k \u2014 this is getting long. ${c} If little remains, finish the task now; if much remains, \`crtr node yield\` immediately, with a note saying where things stand, to continue fresh against your goal before this context overflows.`:`Context ~${s}k. ${c} ${f} If little remains, finish the task here; if much remains, \`crtr node yield\` rather than letting this context grow.`}return r<15e4?`Context ~${s}k and growing. ${c} If the task is done, finish with \`crtr push final\`. If real work remains, \`crtr node yield\` to continue in a fresh window against your goal and your note \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. ${c} \`crtr push final\` only if the task is done; otherwise \`crtr node yield\` immediately, with a note saying where things stand, to continue in a fresh window before this context overflows.`:`Context ~${s}k. ${c} If the task is done, finish with \`crtr push final\`; otherwise \`crtr node yield\` now to refresh into a clean window and keep going against your goal and your note.`}l(Ae,"steerNote");function Se(r){const t=re();if(t===void 0||t.trim()==="")return;let i=0,s=0,u="",c=null,f=null;const _=new Set;let b=!1,x=!1;const N=l(e=>{if(!x){x=!0;try{ke(()=>e?.abort?.())}catch{}}},"abortForRefresh");let v;const W=C().subscribe("node",()=>{const e=C();b&&e.state==="connected"&&e.latestNode?.intent==="refresh"&&N(v)}),d=l((e,n)=>{F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:n,fields:{operation:e}})},"emitDaemonOperationFailure"),X=l(async e=>{try{const n=he();if(n===void 0)throw new Error("broker has no in-place cycle start");const o=await fe(t);if(o.action==="restart"){e?.shutdown?.();return}if(!await n(o))return}catch(n){d("cycle",n);try{e?.shutdown?.()}catch{}}},"startNextCycle"),D=l((e,n)=>{if(e.action==="new_cycle"){X(n);return}if(e.action==="reprompt"){G(e.prompt,{type:"runtime",kind:"stop-guard"}),r.sendUserMessage(e.prompt,{deliverAs:"followUp"});return}if(e.action==="stay_resident"){ue(t).then(()=>C().stop(),o=>d("idle",o));return}if(e.action==="shutdown")try{n?.shutdown?.()}catch{}},"enactSettleDirective"),J=3e3;let O=0,I=Promise.resolve(),h=null,U=null,q=-1/0,p=null,$=0;const B=l(()=>{if(h===null||h===U)return;const e=h;U=e,q=Date.now(),I=I.then(()=>ae(t,e)).catch(n=>d("telemetry",n))},"queueTelemetry"),R=l((e,n)=>{if(h!==null&&h.tokens_in===i&&h.tokens_out===s&&h.model===u&&h.context_tokens===e&&h.last_activity===n)return;$=Math.max(Date.now(),$+1),h={tokens_in:i,tokens_out:s,model:u,context_tokens:e,last_activity:n,updated_at:new Date($).toISOString()};const o=2e3-(Date.now()-q);o<=0?B():p===null&&(p=setTimeout(()=>{p=null,B()},o),p.unref?.())},"publishTelemetry"),P=l(()=>(p!==null&&clearTimeout(p),p=null,B(),I),"flushTelemetry");let E=Promise.resolve();const H=l(e=>(E=E.catch(()=>{}).then(async()=>{const n=await A(t,{event:"progress"});if(n.fault_link==="daemon\u2192node"&&(await se(t)).fault?.op==="conversation_write_failed"){if(!e)return;await(await import("../core/conversation-store/index.js")).flushConversation(),await Y(t,{op:"clear",link:"daemon\u2192node"})}else(n.fault_link==="daemon\u2192node"||e&&n.fault_link==="pi\u2192provider")&&await Y(t,{op:"clear",link:n.fault_link})}),E),"reportProgress"),T=l(()=>{const e=Date.now();e-O<J||(O=e,H(!1).catch(n=>d("turn_progress",n)))},"heartbeat");r.on("session_start",async(e,n)=>{try{const o=n?.sessionManager?.getSessionId?.();if(typeof o!="string"||o==="")return;const g=n?.sessionManager?.getSessionFile?.(),w=typeof g=="string"&&g!==""?g:null,k=typeof e?.reason=="string"?e.reason:null;k==="new"&&(i=0,s=0,_.clear());const a=te(t),m=a!==void 0&&!a.bindPending?{action:a.action}:await ce(t,{piSessionId:o,sessionFile:w,pid:process.pid,reason:k,reviewBoundaryIds:Te(n)});if(a?.bindPending===!0&&m.action==="none"&&ne(t),m.action==="none"&&C().start(t,ee()),m.action==="shutdown"){try{n?.shutdown?.()}catch{}return}if(m.action==="relaunch_root"){de(t).catch(y=>{const K=y instanceof Error?y.message:String(y);n?.ui?.notify?.(`/new refused: ${K}`,"error"),F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:y,fields:{operation:"relaunch_root"}})});return}}catch(o){F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:o,fields:{operation:"session_bound"}})}}),r.on("agent_start",async(e,n)=>{b=!0,v=n;try{if(!(await A(t,{event:"started"})).applied)throw new Error("daemon refused turn open")}catch(o){d("turn_open",o),n?.ui?.notify?.("Turn refused: the broker no longer owns this node.","error"),_e(()=>n?.abort?.())}}),r.on("input",async()=>{b||(x=!1),ge();try{await ie(t)}catch(e){throw d("clear_pushed_final",e),e}}),r.on("tool_execution_start",e=>{try{f=be(String(e?.toolName??""),e?.args),R(c,f),T()}catch{}}),r.on("tool_execution_update",()=>{try{T()}catch{}}),r.on("message_update",()=>{try{T()}catch{}}),r.on("tool_execution_end",async(e,n)=>{try{T(),(await j(t)).intent==="refresh"&&N(n)}catch{}}),r.on("session_shutdown",async(e,n)=>{W(),b=!1,v=void 0,await P();try{await A(t,{event:"closed",end_reason:"teardown-aborted"})}catch(o){d("turn_close_teardown",o)}if(e?.reason==="quit")try{const o=await z(t,{stopReason:"quit",pushedFinal:!1,inPlaceCycle:!0});D(o,n)}catch(o){d("settle_quit",o)}});const L=l(e=>{e?.role!=="assistant"||e.usage==null||(i+=Number(e.usage.input??0)||0,s+=Number(e.usage.output??0)||0,typeof e.model=="string"&&e.model!==""&&(u=e.model))},"accumulate");r.on("turn_end",async(e,n)=>{L(e?.message);let o=null;try{const a=n.getContextUsage()?.tokens;typeof a=="number"&&(o=a)}catch{}o!==null&&(c=o),R(o,f),await P();try{const a=e?.message?.stopReason!=="error"&&e?.message?.stopReason!=="aborted";await H(a)}catch(a){d("turn_end_fault_clear",a)}const g=Array.isArray(e?.message?.content)?e.message.content:[],w=e?.message?.stopReason??"",k=w!=="error"&&w!=="aborted"&&g.some(a=>a?.type==="toolCall");try{const a=o!==null?Ce(o):null,m=a!==null&&!_.has(a)?await j(t):null;if(a!==null&&m!==null){_.add(a);const y=ye("context-nudge",{},Ae(a,m.lifecycle,m.mode));k?(G(y,{type:"runtime",kind:"context-nudge"}),r.sendUserMessage(y,{deliverAs:"steer"})):r.sendMessage({customType:me,content:y,display:!0},{deliverAs:"nextTurn"})}}catch(a){d("turn_boundary",a)}});let M=null;r.on("agent_end",e=>{M=e;try{const n=Array.isArray(e?.messages)?e.messages:[];for(const o of n)L(o)}catch{}}),r.on("agent_settled",async(e,n)=>{b=!1,v=void 0,R(c,f),await P();const o=M;if(M=null,we())return;try{await A(t,{event:"closed",end_reason:"settled"})}catch(a){d("turn_close",a);return}const g=Array.isArray(o?.messages)?o.messages:[],w=ve(g),k=typeof w?.stopReason=="string"?w.stopReason:"";try{const a=o===null?{pushedFinal:!1}:await le(t),m=await z(t,{stopReason:k,pushedFinal:a.pushedFinal,inPlaceCycle:!0});D(m,n)}catch(a){d("settle",a)}})}l(Se,"registerCanvasStophook");var Le=Se;export{Le as default,Se as registerCanvasStophook,Ae as steerNote};
|
|
1
|
+
var Z=Object.defineProperty;var l=(r,t)=>Z(r,"name",{value:t,configurable:!0});import{brokerSignalClient as C}from"../core/runtime/broker/signal-stream.js";import{brokerExecutionId as ee}from"../core/runtime/broker/daemon-ops.js";import{takeCycleBind as te}from"../core/runtime/broker/cycle-start.js";import{markSeededStateBound as ne,startupClaimsHeld as re}from"../core/runtime/broker/boot-state.js";import{envNodeId as oe}from"../shared/env.js";import{stripCdPrefix as se}from"../shared/strip-cd-prefix.js";import{brokerRecovery as ae,mutateBrokerFault as Y,recordBrokerTelemetry as ie,recordBrokerTurn as A,clearBrokerPushedFinal as le,consumeBrokerPushedFinal as ce}from"../core/runtime/broker/daemon-ops.js";import{bindBrokerSession as ue,cachedBrokerNode as j,postBrokerIdle as de,relaunchBrokerRoot as fe,settleBroker as z,startBrokerCycle as he}from"../core/runtime/broker/daemon-ops.js";import{emitEvent as F}from"../core/events/emit.js";import{brokerStartCycle as me}from"../core/runtime/broker/held-deferred-inbox.js";import{CONTEXT_NUDGE_CUSTOM_TYPE as ye,formatCard as pe}from"../shared/generated-context.js";import{isReviewBoundary as ge}from"../core/runtime/session-visibility.js";import{clearRefusedTurn as we,isRuntimeTeardownInProgress as _e,refuseTurn as ke,runRefreshAbort as be}from"../core/runtime/broker/extension-abort.js";import{announceMessageOrigin as G}from"../core/runtime/stamp/channel.js";const Q=80;function ve(r,t){const i=t??{},s=l(_=>typeof _=="string"?_:"","pick"),c=se(s(i.command).trim())||s(i.path)||s(i.file_path)||s(i.pattern)||s(i.description)||s(i.prompt),f=(c!==""?`${r}: ${c}`:r).replace(/\s+/g," ").trim();return f.length>Q?f.slice(0,Q):f}l(ve,"summarizeActivity");function Te(r){for(let t=r.length-1;t>=0;t--)if(r[t]?.role==="assistant")return r[t]}l(Te,"lastAssistantMessage");function Ce(r){try{const t=r?.sessionManager?.getBranch();if(!Array.isArray(t))return[];const i=new Set;for(const s of t){if(!ge(s))continue;const u=s.details?.reviewId;typeof u=="string"&&i.add(u)}return[...i]}catch{return[]}}l(Ce,"currentReviewBoundaryIds");const V=1e4,S=[13e4,15e4,17e4,185e3,2e5];function Ae(r){const t=S[0],i=S[S.length-1];if(r<t)return null;if(r>=i)return i+Math.floor((r-i)/V)*V;let s=t;for(const u of S)r>=u&&(s=u);return s}l(Ae,"steerBand");function Se(r,t,i){const s=Math.round(r/1e3),u=r>=185e3,c="This is not a request to stop: keep going until your task is done.";if(i==="orchestrator")return r<15e4?`Context ~${s}k and growing. ${c} When you reach a good stopping point, consider updating your roadmap (\`crtr doc edit roadmap\`) and running \`crtr node yield\` to refresh against it \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. ${c} Bring your roadmap current, hand off anything outstanding, and \`crtr node yield\` immediately to refresh before this context overflows; the fresh window continues the work.`:`Context ~${s}k. ${c} Update your roadmap (\`crtr doc edit roadmap\`) so a fresh revive can continue, delegate any outstanding work, then \`crtr node yield\` to refresh.`;if(t==="resident"){const f="If substantial work remains, `crtr node yield` to continue fresh against your goal and your note. Add --promote only when worthwhile independent work can run in parallel and coordinating it should become your primary job; `crtr node yield -h` has the boundary.";return r<15e4?`Context ~${s}k and growing. ${c} ${f} Otherwise no rush.`:u?`Context ~${s}k \u2014 this is getting long. ${c} If little remains, finish the task now; if much remains, \`crtr node yield\` immediately, with a note saying where things stand, to continue fresh against your goal before this context overflows.`:`Context ~${s}k. ${c} ${f} If little remains, finish the task here; if much remains, \`crtr node yield\` rather than letting this context grow.`}return r<15e4?`Context ~${s}k and growing. ${c} If the task is done, finish with \`crtr push final\`. If real work remains, \`crtr node yield\` to continue in a fresh window against your goal and your note \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. ${c} \`crtr push final\` only if the task is done; otherwise \`crtr node yield\` immediately, with a note saying where things stand, to continue in a fresh window before this context overflows.`:`Context ~${s}k. ${c} If the task is done, finish with \`crtr push final\`; otherwise \`crtr node yield\` now to refresh into a clean window and keep going against your goal and your note.`}l(Se,"steerNote");function xe(r){const t=oe();if(t===void 0||t.trim()==="")return;let i=0,s=0,u="",c=null,f=null;const _=new Set;let b=!1,x=!1;const N=l(e=>{if(!x){x=!0;try{be(()=>e?.abort?.())}catch{}}},"abortForRefresh");let v;const W=C().subscribe("node",()=>{const e=C();b&&e.state==="connected"&&e.latestNode?.intent==="refresh"&&N(v)}),d=l((e,n)=>{F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:n,fields:{operation:e}})},"emitDaemonOperationFailure"),X=l(async e=>{try{const n=me();if(n===void 0)throw new Error("broker has no in-place cycle start");const o=await he(t);if(o.action==="restart"){e?.shutdown?.();return}if(!await n(o))return}catch(n){d("cycle",n);try{e?.shutdown?.()}catch{}}},"startNextCycle"),D=l((e,n)=>{if(e.action==="new_cycle"){X(n);return}if(e.action==="reprompt"){G(e.prompt,{type:"runtime",kind:"stop-guard"}),r.sendUserMessage(e.prompt,{deliverAs:"followUp"});return}if(e.action==="stay_resident"){de(t).then(()=>C().stop(),o=>d("idle",o));return}if(e.action==="shutdown")try{n?.shutdown?.()}catch{}},"enactSettleDirective"),J=3e3;let O=0,I=Promise.resolve(),h=null,U=null,q=-1/0,p=null,$=0;const B=l(()=>{if(h===null||h===U)return;const e=h;U=e,q=Date.now(),I=I.then(()=>ie(t,e)).catch(n=>d("telemetry",n))},"queueTelemetry"),R=l((e,n)=>{if(h!==null&&h.tokens_in===i&&h.tokens_out===s&&h.model===u&&h.context_tokens===e&&h.last_activity===n)return;$=Math.max(Date.now(),$+1),h={tokens_in:i,tokens_out:s,model:u,context_tokens:e,last_activity:n,updated_at:new Date($).toISOString()};const o=2e3-(Date.now()-q);o<=0?B():p===null&&(p=setTimeout(()=>{p=null,B()},o),p.unref?.())},"publishTelemetry"),P=l(()=>(p!==null&&clearTimeout(p),p=null,B(),I),"flushTelemetry");let E=Promise.resolve();const H=l(e=>(E=E.catch(()=>{}).then(async()=>{const n=await A(t,{event:"progress"});if(n.fault_link==="daemon\u2192node"&&(await ae(t)).fault?.op==="conversation_write_failed"){if(!e)return;await(await import("../core/conversation-store/index.js")).flushConversation(),await Y(t,{op:"clear",link:"daemon\u2192node"})}else(n.fault_link==="daemon\u2192node"||e&&n.fault_link==="pi\u2192provider")&&await Y(t,{op:"clear",link:n.fault_link})}),E),"reportProgress"),T=l(()=>{const e=Date.now();e-O<J||(O=e,H(!1).catch(n=>d("turn_progress",n)))},"heartbeat");r.on("session_start",async(e,n)=>{try{const o=n?.sessionManager?.getSessionId?.();if(typeof o!="string"||o==="")return;const g=n?.sessionManager?.getSessionFile?.(),w=typeof g=="string"&&g!==""?g:null,k=typeof e?.reason=="string"?e.reason:null;k==="new"&&(i=0,s=0,_.clear());const a=te(t),m=a!==void 0&&!a.bindPending?{action:a.action}:await ue(t,{piSessionId:o,sessionFile:w,pid:process.pid,reason:k,reviewBoundaryIds:Ce(n)});if(a?.bindPending===!0&&m.action==="none"&&ne(t),m.action==="none"&&!re()&&C().start(t,ee()),m.action==="shutdown"){try{n?.shutdown?.()}catch{}return}if(m.action==="relaunch_root"){fe(t).catch(y=>{const K=y instanceof Error?y.message:String(y);n?.ui?.notify?.(`/new refused: ${K}`,"error"),F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:y,fields:{operation:"relaunch_root"}})});return}}catch(o){F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:o,fields:{operation:"session_bound"}})}}),r.on("agent_start",async(e,n)=>{b=!0,v=n;try{if(!(await A(t,{event:"started"})).applied)throw new Error("daemon refused turn open")}catch(o){d("turn_open",o),n?.ui?.notify?.("Turn refused: the broker no longer owns this node.","error"),ke(()=>n?.abort?.())}}),r.on("input",async()=>{b||(x=!1),we();try{await le(t)}catch(e){throw d("clear_pushed_final",e),e}}),r.on("tool_execution_start",e=>{try{f=ve(String(e?.toolName??""),e?.args),R(c,f),T()}catch{}}),r.on("tool_execution_update",()=>{try{T()}catch{}}),r.on("message_update",()=>{try{T()}catch{}}),r.on("tool_execution_end",async(e,n)=>{try{T(),(await j(t)).intent==="refresh"&&N(n)}catch{}}),r.on("session_shutdown",async(e,n)=>{W(),b=!1,v=void 0,await P();try{await A(t,{event:"closed",end_reason:"teardown-aborted"})}catch(o){d("turn_close_teardown",o)}if(e?.reason==="quit")try{const o=await z(t,{stopReason:"quit",pushedFinal:!1,inPlaceCycle:!0});D(o,n)}catch(o){d("settle_quit",o)}});const L=l(e=>{e?.role!=="assistant"||e.usage==null||(i+=Number(e.usage.input??0)||0,s+=Number(e.usage.output??0)||0,typeof e.model=="string"&&e.model!==""&&(u=e.model))},"accumulate");r.on("turn_end",async(e,n)=>{L(e?.message);let o=null;try{const a=n.getContextUsage()?.tokens;typeof a=="number"&&(o=a)}catch{}o!==null&&(c=o),R(o,f),await P();try{const a=e?.message?.stopReason!=="error"&&e?.message?.stopReason!=="aborted";await H(a)}catch(a){d("turn_end_fault_clear",a)}const g=Array.isArray(e?.message?.content)?e.message.content:[],w=e?.message?.stopReason??"",k=w!=="error"&&w!=="aborted"&&g.some(a=>a?.type==="toolCall");try{const a=o!==null?Ae(o):null,m=a!==null&&!_.has(a)?await j(t):null;if(a!==null&&m!==null){_.add(a);const y=pe("context-nudge",{},Se(a,m.lifecycle,m.mode));k?(G(y,{type:"runtime",kind:"context-nudge"}),r.sendUserMessage(y,{deliverAs:"steer"})):r.sendMessage({customType:ye,content:y,display:!0},{deliverAs:"nextTurn"})}}catch(a){d("turn_boundary",a)}});let M=null;r.on("agent_end",e=>{M=e;try{const n=Array.isArray(e?.messages)?e.messages:[];for(const o of n)L(o)}catch{}}),r.on("agent_settled",async(e,n)=>{b=!1,v=void 0,R(c,f),await P();const o=M;if(M=null,_e())return;try{await A(t,{event:"closed",end_reason:"settled"})}catch(a){d("turn_close",a);return}const g=Array.isArray(o?.messages)?o.messages:[],w=Te(g),k=typeof w?.stopReason=="string"?w.stopReason:"";try{const a=o===null?{pushedFinal:!1}:await ce(t),m=await z(t,{stopReason:k,pushedFinal:a.pushedFinal,inPlaceCycle:!0});D(m,n)}catch(a){d("settle",a)}})}l(xe,"registerCanvasStophook");var Ye=xe;export{Ye as default,xe as registerCanvasStophook,Se as steerNote};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.671",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.671",
|
|
160
|
+
"@north-light/plugin": "0.3.671",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -192,7 +192,7 @@ export class CrtrClient {
|
|
|
192
192
|
return this.request('POST', routes.nodePushedFinal(this.nodePath(id)), req);
|
|
193
193
|
}
|
|
194
194
|
createNode(req) {
|
|
195
|
-
return this.request('POST', routes.nodes(), req);
|
|
195
|
+
return this.request('POST', routes.nodes(), req, { timeout: 120_000 + this.timeoutMs });
|
|
196
196
|
}
|
|
197
197
|
/** List canvas nodes with composable row filters. `include: 'activity'` adds
|
|
198
198
|
* latest/canonical reports and pending-human counts in the same response. */
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.59';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -273,6 +273,7 @@ const nodeBashKill = defineLeaf({
|
|
|
273
273
|
{ name: 'node_id', type: 'string', required: true, constraint: 'The owning node.' },
|
|
274
274
|
{ name: 'signaled', type: 'boolean', required: true, constraint: 'True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet.' },
|
|
275
275
|
{ name: 'stop_pending_on_machine', type: 'boolean', required: true, constraint: 'True when the job’s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet.' },
|
|
276
|
+
{ name: 'stop_queue_error', type: 'string', required: false, constraint: 'The error when the job ended here but the stop for its machine could not be queued, so the process may still be running there; null otherwise.' },
|
|
276
277
|
],
|
|
277
278
|
outputKind: 'object',
|
|
278
279
|
effects: [
|
|
@@ -291,11 +292,13 @@ const nodeBashKill = defineLeaf({
|
|
|
291
292
|
throw new InputError({ error: 'invalid_job_id', message: `invalid background job id: ${jobId}`, next: 'Use a job id reported by `crtr node bash list`.' });
|
|
292
293
|
}
|
|
293
294
|
const stopped = await cliClient().stopBashJob(node.node_id, jobId);
|
|
294
|
-
return { node_id: node.node_id, signaled: stopped.signaled, stop_pending_on_machine: stopped.stop_pending_on_machine === true };
|
|
295
|
+
return { node_id: node.node_id, signaled: stopped.signaled, stop_pending_on_machine: stopped.stop_pending_on_machine === true, ...(stopped.stop_queue_error === undefined ? {} : { stop_queue_error: stopped.stop_queue_error }) };
|
|
295
296
|
},
|
|
296
|
-
render: (result) => result['
|
|
297
|
-
? `Ended
|
|
298
|
-
:
|
|
297
|
+
render: (result) => typeof result['stop_queue_error'] === 'string'
|
|
298
|
+
? `Ended the background bash job for ${result['node_id']}, but the stop could not be queued for its machine (${result['stop_queue_error']}); the process may still be running there. Check with \`ps\` on that machine.`
|
|
299
|
+
: result['stop_pending_on_machine'] === true
|
|
300
|
+
? `Ended a background bash job for ${result['node_id']}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`
|
|
301
|
+
: `Canceled a background bash job for ${result['node_id']}${result['signaled'] === true ? '' : ' (no observed job process was still running)'}.`,
|
|
299
302
|
});
|
|
300
303
|
const nodeBashQuiet = defineLeaf({
|
|
301
304
|
name: 'quiet',
|
|
@@ -28,7 +28,8 @@ const LOG_COLLECTOR_SCRIPT = [
|
|
|
28
28
|
* `job.activity`: line 1 `<epoch-ms of the last activity> <epoch-ms of this sample>`, then one watched file path per line.
|
|
29
29
|
* Self-contained (Node built-ins only) so a sandboxed job host can run it unchanged. Process tree and open
|
|
30
30
|
* files come from /proc where it exists, else `ps` and `lsof`; a missing `lsof` degrades to CPU and the job
|
|
31
|
-
* log alone. Arguments: supervisor pid, job log path, activity file path
|
|
31
|
+
* log alone. Arguments: supervisor pid, job log path, activity file path, then optionally the machine daemon's socket, node id and job id:
|
|
32
|
+
* when given, it POSTs `/job-activity` to the daemon when the last-activity time has moved, at most once per CRTR_BASH_ACTIVITY_NOTIFY_MS (default 5 min). */
|
|
32
33
|
const ACTIVITY_SAMPLER_SCRIPT = [
|
|
33
34
|
'const fs = require("node:fs"), cp = require("node:child_process");',
|
|
34
35
|
'const rootPid = Number(process.argv[1]), out = process.argv[3];',
|
|
@@ -99,6 +100,17 @@ const ACTIVITY_SAMPLER_SCRIPT = [
|
|
|
99
100
|
'}',
|
|
100
101
|
'let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];',
|
|
101
102
|
'try { prevCpu = tree(processes()); } catch {}',
|
|
103
|
+
'const socket = process.argv[4], node = process.argv[5], job = process.argv[6];',
|
|
104
|
+
'const notifyEvery = Number(process.env.CRTR_BASH_ACTIVITY_NOTIFY_MS) || 300000;',
|
|
105
|
+
'let notified = lastActivity, notifiedAt = 0;',
|
|
106
|
+
// Best effort, bounded: the daemon reports this job's fresh activity once; a missing daemon or any failure is ignored.
|
|
107
|
+
'function notify() {',
|
|
108
|
+
' if (!socket) return;',
|
|
109
|
+
' notified = lastActivity; notifiedAt = Date.now();',
|
|
110
|
+
' const req = require("node:http").request({ socketPath: socket, path: "/job-activity", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => res.resume());',
|
|
111
|
+
' req.on("error", () => {}); req.on("timeout", () => req.destroy());',
|
|
112
|
+
' req.end(JSON.stringify({ node, job }));',
|
|
113
|
+
'}',
|
|
102
114
|
'function record() {',
|
|
103
115
|
' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',
|
|
104
116
|
' fs.renameSync(out + ".tmp", out);',
|
|
@@ -126,6 +138,7 @@ const ACTIVITY_SAMPLER_SCRIPT = [
|
|
|
126
138
|
' prevAt = at;',
|
|
127
139
|
' prevCpu = cpus;',
|
|
128
140
|
' record();',
|
|
141
|
+
' if (lastActivity !== notified && at - notifiedAt >= notifyEvery) notify();',
|
|
129
142
|
'}',
|
|
130
143
|
'record();',
|
|
131
144
|
'setInterval(() => { try { sample(); } catch {} }, interval);',
|
|
@@ -143,7 +156,7 @@ const EXIT_NOTIFY_SCRIPT = [
|
|
|
143
156
|
/** File-backed command supervisor. Beside the job it runs the activity sampler. It writes the exit code to job.exit and, for a foreground
|
|
144
157
|
* command, claims job.done; the daemon reads job.exit of a backgrounded job and publishes `exited`. */
|
|
145
158
|
export const BASH_JOB_SUPERVISOR_SCRIPT = [
|
|
146
|
-
'"$8" -e ' + JSON.stringify(ACTIVITY_SAMPLER_SCRIPT) + ' "$$" "$2" "$9" &',
|
|
159
|
+
'"$8" -e ' + JSON.stringify(ACTIVITY_SAMPLER_SCRIPT) + ' "$$" "$2" "$9" "${10:-}" "${11:-}" "${12:-}" &',
|
|
147
160
|
'sampler=$!',
|
|
148
161
|
'n=$(command -v nice)',
|
|
149
162
|
'${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e ' + JSON.stringify(LOG_COLLECTOR_SCRIPT) + ' "$2"',
|
|
@@ -229,12 +229,33 @@ export async function recordCreateRequestNode(requestKey, nodeId) {
|
|
|
229
229
|
* after a daemon restart resumes the same identity instead of minting another.
|
|
230
230
|
* Only the first caller binds: two API processes holding one unbound key race
|
|
231
231
|
* here, and each gets back the id the key actually names. */
|
|
232
|
-
export async function reserveCreateRequestNode(requestKey, nodeId) {
|
|
232
|
+
export async function reserveCreateRequestNode(requestKey, nodeId, owner) {
|
|
233
233
|
const db = await openDb();
|
|
234
|
-
await db.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL")
|
|
234
|
+
await db.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL")
|
|
235
|
+
.run(nodeId, owner, Date.now() + CREATE_LEASE_MS, requestKey);
|
|
235
236
|
const bound = await db.prepareUncached('SELECT node_id FROM create_requests WHERE request_key = ?').get(requestKey);
|
|
236
237
|
return bound?.node_id ?? null;
|
|
237
238
|
}
|
|
239
|
+
/** How long a create's lease lasts without renewal; its owner renews it every {@link CREATE_LEASE_RENEW_MS}. */
|
|
240
|
+
export const CREATE_LEASE_MS = 30_000;
|
|
241
|
+
export const CREATE_LEASE_RENEW_MS = 10_000;
|
|
242
|
+
/** Take over a bound, unfinished create whose owner's lease has lapsed (or never existed). True when `owner` now holds it. */
|
|
243
|
+
export async function claimCreateLease(requestKey, nodeId, owner) {
|
|
244
|
+
const now = Date.now();
|
|
245
|
+
const result = await (await openDb()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)")
|
|
246
|
+
.run(owner, now + CREATE_LEASE_MS, requestKey, nodeId, now);
|
|
247
|
+
return Number(result.changes) > 0;
|
|
248
|
+
}
|
|
249
|
+
/** Extend the lease while `owner` still holds it. */
|
|
250
|
+
export async function renewCreateLease(requestKey, owner) {
|
|
251
|
+
await (await openDb()).prepareUncached('UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?')
|
|
252
|
+
.run(Date.now() + CREATE_LEASE_MS, requestKey, owner);
|
|
253
|
+
}
|
|
254
|
+
/** Whether another owner's lease on the key is still unexpired. */
|
|
255
|
+
export async function createLeaseLive(requestKey) {
|
|
256
|
+
const row = await (await openDb()).prepareUncached('SELECT lease_expires_at FROM create_requests WHERE request_key = ?').get(requestKey);
|
|
257
|
+
return row?.lease_expires_at != null && Number(row.lease_expires_at) > Date.now();
|
|
258
|
+
}
|
|
238
259
|
export async function completeCreateRequest(requestKey, nodeId) {
|
|
239
260
|
await (await openDb()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(requestKey, nodeId);
|
|
240
261
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 23;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { crtrHome } from '../canvas/paths.js';
|
|
5
5
|
import { withCanvasWrite } from '../canvas/db.js';
|
|
6
|
+
import { reconcilePackages } from '../graph/package-reconcile.js';
|
|
6
7
|
import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
|
|
7
8
|
import { emitEvent } from '../events/emit.js';
|
|
8
9
|
import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
|
|
@@ -135,6 +136,8 @@ async function bindLatePerson(resolved) {
|
|
|
135
136
|
setPersonId(resolved.id);
|
|
136
137
|
await adoptInstallPerson(resolved.id);
|
|
137
138
|
const result = await retireLocalPerson();
|
|
139
|
+
// The boot reconcile was skipped while the person was unresolved.
|
|
140
|
+
await withCanvasWrite(async (db) => await reconcilePackages(db));
|
|
138
141
|
emitEvent({ level: 'info', event: 'daemon.person.resolved', fields: { person_id: resolved.id, source: resolved.source } });
|
|
139
142
|
emitEvent({ level: 'info', event: 'daemon.person.retired', fields: { person_id: result.person, retired: result.retired, columns: result.columns } });
|
|
140
143
|
}
|