@north-light/cli 0.3.708 → 0.3.709
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/crons.d.ts +3 -0
- package/dist/clients/attach/chrome/inbox-strip.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/chrome/status-line.d.ts +1 -1
- package/dist/clients/attach/chrome/status-line.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +4 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/overlays/graph.d.ts +3 -2
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +2 -0
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/render/doc-links.d.ts +1 -1
- package/dist/clients/attach/session/chrome-refresh.js +1 -1
- package/dist/clients/attach/session/connection.d.ts +10 -9
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/context.d.ts +1 -1
- package/dist/clients/attach/session/document-links.d.ts +1 -1
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/session/identity.d.ts +2 -0
- package/dist/clients/attach/session/identity.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/pane-tag.d.ts +3 -1
- package/dist/clients/attach/session/pane-tag.js +1 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +2 -2
- package/dist/clients/attach/session/teardown.js +9 -7
- package/dist/clients/attach/viewer.d.ts +7 -5
- package/dist/clients/attach/viewer.js +540 -538
- package/dist/commands/node/wait.js +2 -6
- package/dist/core/broker-client/client.d.ts +6 -3
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/crons.d.ts +11 -1
- package/dist/core/canvas/crons.js +14 -14
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
- package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command.js +5 -5
- package/dist/core/feed/messages.d.ts +5 -0
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/runtime/bearings.js +4 -4
- package/dist/core/runtime/boot-root.js +4 -4
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
- package/dist/core/runtime/runner/blaxel/client.js +1 -1
- package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
- package/dist/core/runtime/runner/types.d.ts +19 -3
- package/dist/daemon/api/bridge.d.ts +5 -0
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/handlers/crons.d.ts +2 -0
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/ended.d.ts +3 -0
- package/dist/daemon/cron/ended.js +2 -2
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/machine-fire.d.ts +9 -2
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/cron/passes.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
- package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +2 -1
- package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
- package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
- package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
- package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
- package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +7 -4
- package/packages/crouter-api/dist/clients/attach/viewer.js +77 -30
- package/packages/crouter-api/dist/commands/node/wait.js +2 -10
- package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
- package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
- package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command.js +3 -0
- package/packages/crouter-api/dist/core/feed/messages.js +15 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
- package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
- package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
- package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
- package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/core/runtime/starting-screen.d.ts +0 -12
- package/dist/core/runtime/starting-screen.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as v,cronOwnerAlive as p,ensureCronOwnerLease as D}from"./live-runs.js";import{crashedOneShotSummary as L,escalateFailure as C}from"./escalation.js";import{settleRun as I}from"./settle.js";import{adoptCronRunId as E,getCron as g,runningCrons as M,stopLeasedCronRun as S,setCronState as T,verifyLeasedCronRun as _}from"../../core/canvas/crons.js";import{claimReconcilerLease as H,releaseReconcilerLease as b,renewReconcilerLease as N}from"../../core/canvas/reconciler-leases.js";import{emitEvent as l}from"../../core/events/emit.js";import{openDb as $}from"../../core/canvas/db.js";import{cronEnvironment as k,fireInSandbox as G,resumeMachineFire as U}from"./machine-fire.js";const c="cron-recovery",f=3e4;async function B(e){const t=w();if(await H(c,e,t,f)===void 0)return;let n=!1;const r=s(async()=>{if(n)return!1;try{n=!await N(c,e,t,f)}catch{n=!0}return!n},"holds"),a=setInterval(()=>{r()},f/3);return a.unref(),{holds:r,release:s(async()=>{clearInterval(a),await b(c,e,t)},"release")}}s(B,"claimRecovery");async function F(e){const t=await g(e.cron_id);if(t===null||t.run_state!=="running"||t.run_execution_id!==e.run_execution_id||t.run_started_at!==e.run_started_at||t.run_lease_owner!==e.run_lease_owner||t.run_lease_owner!==null&&await p(t.run_lease_owner))return null;if(t.run_execution_id!==null)return t;const n=w();return await E(t,n)?{...t,run_execution_id:n}:null}s(F,"reverifyAbandoned");async function oe(e,t={}){await D();for(const n of await M()){if(n.run_lease_owner===v||n.run_lease_owner!==null&&await p(n.run_lease_owner))continue;const r=n.run_pid===null&&n.run_execution_id!==null?await k(n):null,a=r===null&&(n.run_pid===null||!_(n));if(r===null&&!a&&e-(n.run_started_at!=null?new Date(n.run_started_at).getTime():e)<n.run_timeout_s*1e3)continue;const o=await B(n.cron_id);if(o===void 0)continue;let i;try{i=await F(n)}catch(u){throw await o.release(),u}if(i===null){await o.release();continue}if(r!==null){P(i,r,t,o);continue}if(a){W(i,e,t,o);continue}K(i,e,t,o)}}s(oe,"recoverStaleCronLeases");function K(e,t,n,r){const a=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,o={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:-1,timedOut:!0,runTimeoutS:e.run_timeout_s,processErrorMessage:null,stdoutHead:"",stdoutSha256:h,stderrHead:`run timed out after ${e.run_timeout_s}s (recovered stale lease from a prior daemon instance)`},i=(async()=>{await r.holds()&&(await S(e),await V(e),await r.holds()&&await I(e,{outOfBand:!1,outcome:{kind:"disposed",ctx:o},record:{runId:o.runId,startedAtIso:o.startedAtIso,finishedAtMs:t,durationMs:t-a,exitCode:-1,stdoutHead:null,stderrHead:o.stderrHead},lease:{kind:"clear"}}))})().finally(()=>r.release());n.register?.(i),i.catch(u=>{l({level:"error",event:"cron.stale_lease.settle_failed",error:u,fields:{cron_id:e.cron_id}})})}s(K,"recoverTimedOutRun");function P(e,t,n,r){const a=(async()=>{await r.holds()&&await Y(e)&&(t.kind==="machine"?await U(e,t.id):await G(e,{runId:e.run_execution_id,outOfBand:e.run_out_of_band,startedAtIso:e.run_started_at,startedAtMs:Date.parse(e.run_started_at)},()=>{},!0))})().finally(()=>r.release());n.register?.(a),a.catch(o=>{l({level:"error",event:"cron.machine_resume.failed",error:o,fields:{cron_id:e.cron_id,run_id:e.run_execution_id}})})}s(P,"resumeMachineRun");async function Y(e){const t=await(await $()).prepare("UPDATE crons SET run_lease_owner = ?, updated = ? WHERE cron_id = ? AND run_state = 'running' AND run_execution_id = ? AND run_lease_owner IS NOT DISTINCT FROM ?").run(v,new Date().toISOString(),e.cron_id,e.run_execution_id,e.run_lease_owner);return Number(t.changes)>0}s(Y,"takeOverLease");async function V(e){if(!await y(e)&&(await S(e,"SIGKILL"),!await y(e)))throw new Error(`cron ${e.cron_id} run ${e.run_pid} survived SIGKILL`)}s(V,"awaitLeasedRunDeath");async function y(e){const t=Date.now()+O;for(;Date.now()<t;){if(!_(e))return!0;await R(x)}return!_(e)}s(y,"pollLeasedRunGone");function W(e,t,n,r){const a=e.recur==null,o=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,i=e.run_pid===null?"the daemon life that claimed this run ended before its launch pid was recorded \u2014 the command may have started and its outcome is unknown":"the daemon life that owned this run ended before it settled \u2014 the process is gone and its outcome was never observed",u={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:null,timedOut:!1,runTimeoutS:e.run_timeout_s,processErrorMessage:i,stdoutHead:"",stdoutSha256:h,stderrHead:`run outcome unobserved: ${i}`},m=(async()=>{let d=`crashed: ${i}${a?"":" \u2014 the next occurrence is unaffected"}`;if(a){if(!await r.holds())return;if(await T(e.cron_id,"paused"),e.on_output==="silent")d=`crashed: ${i} \u2014 one-shot paused, not re-fired (silent: not escalated)`;else{if(!await r.holds())return;d=`crashed one-shot: ${await C(e,u,L(i))}`}}await r.holds()&&(await I(e,{outOfBand:!1,outcome:{kind:"stated",delivered:d,paused:a},record:{runId:u.runId,startedAtIso:u.startedAtIso,finishedAtMs:t,durationMs:Math.max(0,t-o),exitCode:null,stdoutHead:null,stderrHead:u.stderrHead},lease:"release"}),l({level:"warn",event:"cron.run.unobserved",fields:{cron_id:e.cron_id,name:e.name,one_shot:a}}))})().finally(()=>r.release());n.register?.(m),m.catch(d=>{l({level:"error",event:"cron.crashed_run.settle_failed",error:d,fields:{cron_id:e.cron_id}})})}s(W,"settleCrashedRun");export{oe as recoverStaleCronLeases};
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { type MachineCronRunArgs, type MachineCronRunResult } from '../../core/runtime/runner/machine/ops.js';
|
|
2
2
|
import { type Cron, type CronRunRecord } from '../../core/canvas/crons.js';
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/** Where a cron runs off this process: its profile's machine or Blaxel environment on a cloud role, or null when it runs here (a Mac's own
|
|
4
|
+
* daemon, a local runtime, a cron with no profile). */
|
|
5
|
+
export declare function cronEnvironment(c: Cron): Promise<{
|
|
6
|
+
kind: 'machine' | 'blaxel';
|
|
7
|
+
id: string;
|
|
8
|
+
} | null>;
|
|
5
9
|
export declare function machineLinkLive(environmentId: string): Promise<boolean>;
|
|
6
10
|
/** What a machine cron's call carries beyond the command: the stored variables and armed env, and who the Mac rebuilds its run context for. */
|
|
7
11
|
type PreparedRun = Pick<MachineCronRunArgs, 'env' | 'grantee' | 'profileId' | 'contextAnchor'>;
|
|
@@ -26,4 +30,7 @@ export declare function fireOnMachine(c: Cron, fire: MachineFire, admit: () => v
|
|
|
26
30
|
/** A control plane that took a cron's run lease over from one that ended mid-fire: the same run id goes to the machine again, so the machine
|
|
27
31
|
* returns the stored result or joins the live run. A fresh id is never minted for this occurrence. Resolves with the settled record. */
|
|
28
32
|
export declare function resumeMachineFire(c: Cron, environmentId: string): Promise<CronRunRecord | null>;
|
|
33
|
+
/** Fire `c` in its anchor node's sandbox through the Blaxel runner and settle the run. The same run id names the sandbox process, so a
|
|
34
|
+
* control plane that recovers the run (`resume`) reads the first start instead of running the command again. */
|
|
35
|
+
export declare function fireInSandbox(c: Cron, fire: Omit<MachineFire, 'environmentId'>, admit: () => void, resume?: boolean): Promise<CronRunRecord | null>;
|
|
29
36
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=Object.defineProperty;var d=(e,n)=>P(e,"name",{value:n,configurable:!0});import{createHash as k,randomUUID as B}from"node:crypto";import{join as O}from"node:path";import{setTimeout as F}from"node:timers/promises";import{openDb as C}from"../../core/canvas/db.js";import{isCloudRole as j}from"../../core/canvas/person.js";import{withCanvasWrite as W}from"../../core/canvas/db.js";import{getNode as q}from"../../core/canvas/canvas.js";import{runnerForEnvironment as J}from"../../core/runtime/runner/index.js";import{callMachine as $}from"../../core/runtime/runner/machine/call.js";import{machineEnvironmentOfNode as K}from"../../core/runtime/runner/machine/runner.js";import{MachineCallFailedError as V,MachineLostError as X,MachineOfflineError as g}from"../../core/runtime/runner/machine/ops.js";import{environmentSecrets as Y}from"../../core/secrets/environment-secrets.js";import{profileInApp as z}from"../../core/secrets/environment-owner.js";import{getCron as G}from"../../core/canvas/crons.js";import{emitEvent as E}from"../../core/events/emit.js";import{runTokenFor as Q}from"./run-token.js";import{parseArmedEnv as Z}from"./armed-context.js";import{CRON_OUTPUT_HEAD_BYTES as v,formatCronOutputHead as ee}from"./capture.js";import{settleClosedRun as y,settleUnspawnedRun as h}from"./closed.js";import{clearLiveRun as T,registerLiveRun as x}from"./live-runs.js";import{advanceRecurrence as S}from"./recurrence.js";const ne=15,re=2e3;async function ye(e){return!j()||e.profile==null?null:await(await C()).prepare("SELECT e.object AS id, e.kind AS kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(e.profile)??null}d(ye,"cronEnvironment");async function Te(e){return await(await C()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,new Date().toISOString())!==void 0}d(Te,"machineLinkLive");async function A(e,n){const r=e.profile,i=await(await C()).prepare("SELECT person FROM profiles WHERE id = ?").get(r);if(i===void 0)throw new Error(`profile ${r} of cron ${e.cron_id} is not in the control plane`);const t=await Y({person:i.person,app:e.grantee,ownerProfile:r,ownerProfileInApp:await z(r,e.grantee),includeDeployment:!1}),o=e.grantee==="app:terminal",l=e.anchor_node!=null?await q(e.anchor_node):null;return{env:{...t,...Z(e.env_json),...o?{CRTR_PROFILE_ID:r}:{},CRTR_CRON_ID:e.cron_id,CRTR_CRON_NAME:e.name,CRTR_RUN_ID:n,CRTR_API_TOKEN:Q(n),...e.anchor_node!=null?{CRTR_ANCHOR:e.anchor_node}:{}},grantee:e.grantee,profileId:r,contextAnchor:l===null?null:{node:l.node_id,grantee:l.grantee??e.grantee}}}d(A,"prepareRun");async function te(e,n,r,i){const t=(e.run_timeout_s+ne)*1e3;return await $(n,"cron.run",{runId:r,cronId:e.cron_id,command:e.command,cwd:e.cwd,...i,timeoutS:e.run_timeout_s,leaseExpiresAt:new Date(Date.now()+t).toISOString()},{timeoutMs:t})}d(te,"sendCronRun");async function oe(e,n){await M(e,"cron.cancel",{runId:n})}d(oe,"queueCronCancel");async function xe(e,n){const r=await K(e);r!==null&&await M(r,"job.stop",{node:e,job:n})}d(xe,"queueJobStop");async function M(e,n,r){await W(async i=>{await i.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(B(),e,n,JSON.stringify(r),new Date().toISOString()),await i.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`)})}d(M,"queueMachineCall");async function Me(e,n,r){const{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l}=n;let c;try{if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a machine does not have");if(c=await A(e,i),!t&&e.recur!=null){const s=await S(e,l);if(s!==null)throw s}}catch(s){return await h(e,{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l},"run could not be armed",s)}return await N(e,n,c,r)}d(Me,"fireOnMachine");async function Ne(e,n){const r=e.run_execution_id,i=e.run_started_at,t=Date.parse(i),o=e.run_out_of_band,l={environmentId:n,runId:r,outOfBand:o,startedAtIso:i,startedAtMs:t};let c;try{if(c=await A(e,r),!o&&e.recur!=null&&Date.parse(e.fire_at)<=t){const s=await S(e,t);if(s!==null)throw s}}catch(s){return await h(e,l,"run could not be armed",s)}return await N(e,l,c,()=>{})}d(Ne,"resumeMachineFire");async function N(e,n,r,i){const{environmentId:t,runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s}=n,p={runId:o,replaced:!1,selfCanceled:!1,kill:d(()=>{oe(t,o).catch(_=>{E({level:"error",event:"cron.machine.cancel_failed",error:_,fields:{cron_id:e.cron_id,run_id:o}})})},"kill")};x(e.cron_id,p),i();try{let _=null,m=null;for(;_===null&&m===null;){try{const f=await te(e,t,o,r);if(f.notStarted!==!0){_=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.stderrHead}})}catch(f){if(f instanceof V){m=f;break}if(!(f instanceof g)&&!(f instanceof X))throw f;if(l&&f instanceof g){m=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.message}})}if(!p.selfCanceled&&await G(e.cron_id)===null)return null;await F(re)}if(m!==null)return await h(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s},"run failed on the machine",m);const{exitCode:a,stdoutHead:w,stderrHead:u,durationMs:R,stdoutSha256:D}=_,I=a===-1,L=a===null?new Error((u??"the machine reported no exit").slice(0,v)):null,H=p.replaced,U=p.selfCanceled;return await y(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s,finishedAtMs:s+R,code:I?null:a,timedOut:I,processError:L,stdoutHead:w??"",stderrHead:u??"",stdoutSha256:D,wasReplaced:H,wasSelfCanceled:U})}finally{T(e.cron_id,o)}}d(N,"driveFire");const b="/var/lib/crtr";async function be(e,n,r,i=!1){const{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c}=n;let s,p;try{if(p=J("blaxel"),p.cronRun===void 0||p.cronCancel===void 0)throw new Error("the registered Blaxel runner cannot run crons");const a=process.env.CRTR_PUBLIC_API_URL;if(!a)throw new Error("CRTR_PUBLIC_API_URL is not set, so a sandbox cron could not reach the API");if(e.anchor_node==null)throw new Error("a hosted cron runs in its anchor node's sandbox, and this cron has no anchor node");if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a sandbox does not have");const w=await A(e,t),u=w.contextAnchor;if(s={...w.env,CRTR_API_URL:a,HOME:O(b,"apps",e.grantee.replace(/^app:/,""),"home"),...u!==null?{CRTR_CONTEXT_DIR:O(b,"apps",u.grantee.replace(/^app:/,""),"nodes",u.node,"context")}:{}},!o&&e.recur!=null&&(!i||Date.parse(e.fire_at)<=c)){const R=await S(e,c);if(R!==null)throw R}}catch(a){return await h(e,n,"run could not be armed",a)}const _=e.anchor_node,m={runId:t,replaced:!1,selfCanceled:!1,kill:d(()=>{p.cronCancel(_,t).catch(a=>{E({level:"error",event:"cron.sandbox.cancel_failed",error:a,fields:{cron_id:e.cron_id,run_id:t}})})},"kill")};x(e.cron_id,m),r();try{let a;try{a=await p.cronRun(_,{runId:t,command:e.command,cwd:e.cwd,env:s,timeoutS:e.run_timeout_s,startedAtMs:c})}catch(u){return await h(e,n,"run failed in the sandbox",u)}const w=d(u=>u.length>v?ee(u.slice(0,v),!0):u,"head");return await y(e,{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c,finishedAtMs:Date.now(),code:a.exitCode,timedOut:a.timedOut,processError:a.error===void 0?null:new Error(a.error),stdoutHead:w(a.stdout),stderrHead:w(a.stderr),stdoutSha256:k("sha256").update(a.stdout).digest("hex"),wasReplaced:m.replaced,wasSelfCanceled:m.selfCanceled})}finally{T(e.cron_id,t)}}d(be,"fireInSandbox");export{ye as cronEnvironment,be as fireInSandbox,Me as fireOnMachine,Te as machineLinkLive,oe as queueCronCancel,xe as queueJobStop,Ne as resumeMachineFire,te as sendCronRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var o=(n,e)=>l(n,"name",{value:e,configurable:!0});import{randomUUID as f}from"node:crypto";import{cronDaemonInstanceId as u,liveRunFor as p}from"./live-runs.js";import{advanceCron as _,dueOverlapCrons as m,cappedIdleCrons as v,expiredIdleCrons as x,HOSTED_CRON_MAX_FIRES as a,listCronRuns as w,recordCronRun as C}from"../../core/canvas/crons.js";import{emitEvent as d}from"../../core/events/emit.js";import{nextSlotAfter as h}from"../../core/wake.js";import{endCron as c}from"./ended.js";const s="skipped (overlap=skip)";async function A(n){for(const e of await x(n))await c(e,{kind:"expired"})&&d({level:"info",event:"cron.expired",fields:{cron_id:e.cron_id,name:e.name,expires_at:e.expires_at}});for(const e of await v(a))await c(e,{kind:"max_fires",max:a})&&d({level:"info",event:"cron.max_fires",fields:{cron_id:e.cron_id,name:e.name,fires:e.fires}})}o(A,"expireDueCrons");async function k(n){return(await w(n))[0]?.delivered?.startsWith(s)===!0}o(k,"latestRunIsSkip");async function F(n,e){for(const r of await m(e)){if(r.overlap==="queue")continue;if(r.overlap==="skip"){let t;try{t=h(r.recur,new Date(n))}catch{continue}await _(r.cron_id,t),await k(r.cron_id)||await C({run_id:f(),cron_id:r.cron_id,started:e,finished:e,duration_ms:0,exit_code:null,stdout_head:null,stderr_head:null,delivered:`${s}: fire landed while the previous run was in flight (consecutive skips are not re-recorded until a run settles)`});continue}const i=p(r.cron_id);r.run_lease_owner===u&&i!==void 0&&!i.replaced&&(i.replaced=!0,i.kill())}}o(F,"applyOverlapPolicies");export{F as applyOverlapPolicies,A as expireDueCrons};
|
package/dist/daemon/cron-run.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
1
|
+
var Y=Object.defineProperty;var i=(e,m)=>Y(e,"name",{value:m,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as _,cronDaemonInstanceId as M,ensureCronOwnerLease as z,registerLiveRun as G}from"./cron/live-runs.js";import{closeCronExecution as J,openCronExecution as K}from"./cron/run-socket.js";import{appProcessSandboxed as Q}from"../core/spaces/process.js";import{nodeAgentDir as V}from"../core/canvas/paths.js";import{uidForApp as W}from"../core/spaces/users.js";import{buildArmedRunContext as Z}from"./cron/armed-context.js";import{asPerson as j}from"./reconcilers/node-lifecycle/node-person.js";import{isProfilePaused as ee}from"../core/profiles/manifest.js";import{ensureCronFolder as ne}from"./cron/folders.js";import{cronEnvironment as re,fireInSandbox as te,fireOnMachine as oe,machineLinkLive as ae}from"./cron/machine-fire.js";import{advanceRecurrence as U}from"./cron/recurrence.js";import{checkCronFire as ie,cronPrincipalOf as se}from"./cron/authority.js";import{refusalError as de}from"../core/ledger/index.js";import{startRefusal as le}from"../core/runtime/start-check.js";import{settleClosedRun as ue,settleUnspawnedRun as v}from"./cron/closed.js";import{settleRun as B}from"./cron/settle.js";import{applyOverlapPolicies as fe,expireDueCrons as me}from"./cron/passes.js";import{dueClockCrons as ce,acquireCronRunLease as pe,releaseCronRunLease as he,attachCronRunPid as _e,HOSTED_CRON_MAX_FIRES as we}from"../core/canvas/crons.js";import{emitEvent as $}from"../core/events/emit.js";import{deliverDueDeadline as Ce}from"../core/feed/messages.js";import{runAppCommand as ge}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as Qe}from"./cron/capture.js";import{cronDaemonInstanceId as We,markSelfCanceledCronRun as Ze}from"./cron/live-runs.js";import{recoverStaleCronLeases as en}from"./cron/lease-recovery.js";function ze(e,m){return F(e,m).settled}i(ze,"executeCron");function F(e,m){const{outOfBand:s}=m;let u=i(()=>{},"admit");const d=new Promise(t=>{u=t}),w=new Promise((t,a)=>{let p=!1;const r=X();let I=i(()=>{},"undo");const R=i(l=>{if(I(),!p){a(l);return}p=!1,he(e.cron_id,r).then(()=>a(l),f=>{$({level:"error",event:"cron.lease.release_failed",error:f,fields:{cron_id:e.cron_id}}),a(l)})},"fail");(async()=>{const l=Date.now(),f=new Date(l).toISOString(),C={runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l},D=await re(e),b=D?.kind==="machine"?D.id:null;if(b!==null&&!s&&!await ae(b)){t(null);return}if(await z(),!await pe(e.cron_id,M,f,s,r,D?.kind==="blaxel"?we:null)){t(null);return}p=!0;let c=await ie(se(e));if(c.allowed){e={...e,scopes:c.scopes};const n=await le({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(c={allowed:!1,reason:"limit_reached",message:de(n).message})}if(!c.allowed){try{if(!s&&e.recur!=null){const h=await U(e,l);if(h!==null)throw h}}catch(h){v(e,C,"run could not be armed",h).then(t,a);return}const n=Date.now();B(e,{outOfBand:s,outcome:{kind:"refused",reason:c.reason,message:c.message},record:{runId:r,startedAtIso:f,finishedAtMs:n,durationMs:n-l,exitCode:null,stdoutHead:null,stderrHead:`${c.reason}: ${c.message}`.slice(0,A)},lease:"release"}).then(t,a);return}if(D?.kind==="blaxel"){te(e,C,u).then(t,R);return}if(b!==null){oe(e,{environmentId:b,runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l},u).then(t,R);return}let H;try{if(e.isolated&&ne(e.grantee,e.cron_id),{env:H}=await Z(e,r),!s&&e.recur!=null){const n=await U(e,l);if(n!==null)throw n}}catch(n){v(e,C,"run could not be armed",n).then(t,a);return}let k=null,y=!1;const O={runId:r,replaced:!1,selfCanceled:!1,kill:i(()=>{k!==null?k():y=!0},"kill")};G(e.cron_id,O),I=i(()=>_(e.cron_id,r),"undo"),u();const g=Q()?{executionId:r,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await W(e.grantee),rebuilt:!1,refusal:null}:null,x=i(()=>{g!==null&&J(r)},"closeExecution");I=i(()=>{_(e.cron_id,r),x()},"undo"),i(async()=>(g!==null&&await K(g,e.cwd,e.profile),ge({command:e.command,cwd:e.cwd,env:H,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...g!==null?{cron:{executionId:r,...e.anchor_node===null||e.isolated?{}:{anchorDir:V(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:A})),"launch")().then(async n=>{if(n.pid===null){_(e.cron_id,r),x(),n.completion.then(o=>{v(e,C,"run failed to spawn",o.processError??new Error("bash did not provide a process id")).then(t,a)},a);return}I=i(()=>{_(e.cron_id,r),x(),n.terminate()},"undo");let h=!1;const P=i(()=>{n.completion.then(o=>{const T=O.replaced,N=O.selfCanceled,E=g?.refusal??null;if(_(e.cron_id,r),x(),h){t(null);return}if(E!==null&&!T){const L=Date.now(),q=S(o.stderr,o.stderrTruncated);B(e,{outOfBand:s,outcome:{kind:"refused",reason:E.reason,message:E.message},record:{runId:r,startedAtIso:f,finishedAtMs:L,durationMs:L-l,exitCode:o.exitCode,stdoutHead:S(o.stdout,o.stdoutTruncated)||null,stderrHead:`${E.reason}: ${E.message}
|
|
2
|
+
${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}ue(e,{runId:r,outOfBand:s,startedAtIso:f,startedAtMs:l,finishedAtMs:Date.now(),code:o.exitCode,timedOut:o.timedOut,processError:o.processError,stdoutHead:S(o.stdout,o.stdoutTruncated),stderrHead:S(o.stderr,o.stderrTruncated),stdoutSha256:o.stdoutSha256,wasReplaced:T,wasSelfCanceled:N}).then(t,a)},a)},"settleCommand");if(!await _e(e.cron_id,M,f,n.pid)&&!O.selfCanceled){h=!0,n.terminate(),P();return}k=n.terminate,y&&n.terminate(),P()},n=>{_(e.cron_id,r),x(),v(e,C,"run failed to spawn",n).then(t,a)}).catch(R)})().catch(R)});return w.then(u,u),{admitted:d,settled:w}}i(F,"startCron");async function Ge(e,m){const s=new Date(e).toISOString();await me(s),await fe(e,s);const u=[];for(const d of await ce(s)){if(d.anchor_node!=null&&m.held.has(d.anchor_node))continue;const w=await j(d.sub,async()=>ee(d.profile)?null:d.deadline_body!==null?await Ce(d).then(()=>null):F(d,{outOfBand:!1})).catch(r=>($({level:"error",event:"cron.fire_failed",error:r,fields:{cron_id:d.cron_id}}),null));if(w===null)continue;const{admitted:t,settled:a}=w,p=a.then(()=>{});p.catch(()=>{}),await t,u.push(p),m.register?.(p)}for(const d of u)d.catch(()=>{});return u}i(Ge,"runDueCrons");export{Qe as CRON_OUTPUT_HEAD_BYTES,We as cronDaemonInstanceId,ze as executeCron,Ze as markSelfCanceledCronRun,en as recoverStaleCronLeases,Ge as runDueCrons,F as startCron};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var z=Object.defineProperty;var o=(s,f)=>z(s,"name",{value:f,configurable:!0});import{randomUUID as K}from"node:crypto";import{WebSocket as g}from"ws";import{APIError as C}from"../../api/errors.js";import{emitEvent as q}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as H}from"../../api/runtime-version.js";import{crtrVersion as Q}from"../../shared/crtr-version.js";import{connectViewSocket as G}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as Z,LINK_MAX_PAYLOAD_BYTES as ee,parseFrame as ne}from"./frames.js";const te=1e3,re=6e4,oe=64*1024,se=4*1024*1024,ie=1024*1024,de=8*1024*1024,D=15e3,$=75e3;function ce(s){const f=new Map,h=o(()=>{for(;s.open()&&s.bufferedAmount<oe;){let a;for(const S of f)(a===void 0||S[1].bytes<a[1].bytes)&&(a=S);if(a===void 0)return;const[_,m]=a,{data:i,trace:d}=m.frames.shift();m.bytes-=i.length,m.paused!==void 0&&m.bytes<ie&&(m.paused.resume(),m.paused=void 0),m.frames.length===0&&f.delete(_),d?.dequeued(),s.send(i,d===void 0?h:()=>{d.sent(),h()})}},"pump");return{push(a,_,m="",i){if(!s.open())return;const d=f.get(m)??{frames:[],bytes:0};f.set(m,d),d.frames.push({data:a,...i===void 0?{}:{trace:i}}),d.bytes+=a.length,_!==void 0&&d.paused===void 0&&d.bytes>se&&(_.pause(),d.paused=_),h()},waiting:o(()=>[...f.values()].reduce((a,_)=>({bytes:a.bytes+_.bytes,frames:a.frames+_.frames.length}),{bytes:0,frames:0}),"waiting"),drop(a){f.delete(a)},forget(a){for(const _ of f.values())_.paused===a&&(_.paused=void 0)}}}o(ce,"createViewQueue");function ae(s,f){const h=new URL(`/v1/machines/${encodeURIComponent(f)}/link`,s);return h.protocol=h.protocol==="https:"?"wss:":h.protocol==="http:"?"ws:":h.protocol,h.toString()}o(ae,"linkUrl");function be(s){const f=s.backoffMinMs??te,h=s.backoffMaxMs??re,a=s.openView??G,_=s.silenceMs??$;let m=!1,i,d=f,S;const N=new Map,A=new Map,F=200,O=[],U=o(()=>{const l=i;for(;O.length>0&&l?.readyState===g.OPEN;)l.send(JSON.stringify({type:"exit",...O.shift()}))},"flushExits"),x=o((l,t)=>{q({level:"error",event:l,fields:{environment:s.environmentId},error:t})},"fault");let P;const J=o(()=>{if(m)return;if(P!==void 0){if(s.credential()===P){S=setTimeout(J,d),d=Math.min(d*2,h);return}P=void 0}const l=s.credential(),t=new g(ae(s.apiUrl,s.environmentId),{headers:{authorization:`Bearer ${l}`,[H]:Q()},maxPayload:ee,handshakeTimeout:$});i=t;const u=new Map,y=new Map,v=o(e=>{t.readyState===g.OPEN&&t.send(JSON.stringify(e))},"send"),w=ce({get bufferedAmount(){return t.bufferedAmount},open:o(()=>t.readyState===g.OPEN,"open"),send:o((e,n)=>t.send(e,n),"send")}),E=o((e,n,r)=>w.push(JSON.stringify(e),n,e.channel,r),"sendView"),b=o(e=>Math.round(e*10)/10,"round"),L=o(async e=>{const n=s.handlers[e.op];if(n===void 0){v({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const r=new AbortController,c=o(()=>r.abort(new Error("the machine link closed")),"onClose");t.once("close",c);try{v({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,r.signal)??null})}catch(k){v({type:"result",call_id:e.call_id,ok:!1,error:k instanceof Error?k.message:String(k)})}finally{t.off("close",c)}},"runCall"),Y=o(e=>{const n=performance.now(),r=o((p,M={})=>{q({level:"info",event:`daemon.timing.${p}`,node_id:e.node,fields:{channel:e.channel,...M}})},"mark");r("view_open_received",{link_buffered_bytes:t.bufferedAmount});const c=a(e.node);u.set(e.channel,c);const k=performance.now();r("view_open_started",{open_sync_ms:b(k-n)});let R;c.once("connect",()=>{const p=performance.now();R=p;const M=w.waiting(),I=t.bufferedAmount;t.readyState===g.OPEN&&t.send(JSON.stringify({type:"view.ready",channel:e.channel}),()=>r("view_ready_flushed",{send_ms:b(performance.now()-p),link_buffered_bytes:t.bufferedAmount})),r("view_ready_sent",{open_to_connect_ms:b(p-k),queued_bytes:M.bytes,queued_frames:M.frames,link_buffered_bytes_before:I,link_buffered_bytes_after:t.bufferedAmount})});let B=0,j=0,W=!1;c.on("data",p=>{let M;if(!W){const I=performance.now();B+=1,j+=p.length,B===1&&r("view_output_first_received",{bytes:p.length,since_ready_ms:R===void 0?null:b(I-R)}),p.includes(10)&&(W=!0,r("view_welcome_received",{chunks:B,bytes:j,queued_bytes:w.waiting().bytes,link_buffered_bytes:t.bufferedAmount}),M={dequeued:o(()=>r("view_welcome_dequeued",{queue_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"dequeued"),sent:o(()=>r("view_welcome_sent",{since_received_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"sent")})}E({type:"view.data",channel:e.channel,bytes:p.toString("base64")},c,M)}),c.once("error",p=>{R===void 0&&r("view_connect_failed",{open_to_error_ms:b(performance.now()-k),code:p.code??"unknown"}),w.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel,error:p.message})}),c.once("close",()=>{w.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel})})},"openChannel"),X=o((e,n)=>{const r=u.get(e);if(r===void 0||r.write(n))return;const c=(y.get(e)??0)+n.length;if(c>de){u.delete(e),y.delete(e),r.destroy(),E({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}y.has(e)||r.once("drain",()=>y.delete(e)),y.set(e,c)},"writeToChannel");let T;const V=o(()=>{T!==void 0&&clearTimeout(T),T=setTimeout(()=>{q({level:"warn",event:"daemon.machine_link.silent",fields:{environment:s.environmentId}}),t.terminate()},_)},"heard");t.on("open",()=>{d=f,V(),U(),s.onOpen?.()}),t.on("ping",V),t.on("message",e=>{V();const n=ne(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"job.reported":{const r=N.get(n.id);N.delete(n.id),n.error===void 0?r?.resolve():r?.reject(new C(n.error.status,n.error.code,n.error.message));return}case"turns.answer":A.get(n.id)?.(n.turns);return;case"view.open":Y(n);return;case"view.data":X(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const r=u.get(n.channel);u.delete(n.channel),r?.destroy(),w.drop(n.channel);return}default:return}}catch(r){x("daemon.machine_link.frame_failed",r)}}),t.on("unexpected-response",(e,n)=>{let r="";n.on("data",c=>{r+=c.toString("utf8")}).on("close",()=>{t.terminate(),x("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${r}`));try{n.statusCode===426&&s.onBehind?.(JSON.parse(r).error.message)}catch(c){x("daemon.machine_link.client_error",c)}})}),t.on("error",e=>x("daemon.machine_link.client_error",e)),t.on("close",e=>{T!==void 0&&clearTimeout(T);for(const n of u.values())n.destroy();u.clear(),i===t&&(i=void 0);for(const n of A.values())n(void 0);for(const[n,r]of N)N.delete(n),r.reject(new C(503,"machine_offline","the machine link closed before the job report was answered"));m||(e===Z&&(q({level:"error",event:"daemon.machine_link.revoked",fields:{environment:s.environmentId}}),P=l),S=setTimeout(J,d),d=Math.min(d*2,h))})},"connect");return J(),{stop(){m=!0,S!==void 0&&clearTimeout(S),i?.close()},connected:o(()=>i?.readyState===g.OPEN,"connected"),reportJob(l,t,u){const y=i;if(y?.readyState!==g.OPEN)return Promise.reject(new C(503,"machine_offline","the machine link is not open"));const v=K();return new Promise((w,E)=>{const b=setTimeout(()=>{N.delete(v),E(new C(504,"request_timeout","the control plane did not answer the job report"))},s.jobReportTimeoutMs??D);N.set(v,{resolve:o(()=>{clearTimeout(b),w()},"resolve"),reject:o(L=>{clearTimeout(b),E(L)},"reject")}),y.send(JSON.stringify({type:"job.report",id:v,node:l,job:t,request:u}))})},turns(l){const t=i;if(t?.readyState!==g.OPEN)return Promise.resolve(void 0);const u=K();return new Promise(y=>{const v=setTimeout(()=>w(void 0),s.jobReportTimeoutMs??D),w=o(E=>{clearTimeout(v),A.delete(u),y(E)},"answer");A.set(u,w),t.send(JSON.stringify({type:"turns",id:u,brokers:l}))})},reportWedge(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"wedge",...l}))},reportRunning(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"running",executions:l}))},reportExit(l){O.push(l),O.length>F&&O.shift(),U()}}}o(be,"startMachineLink");export{D as JOB_REPORT_TIMEOUT_MS,re as LINK_BACKOFF_MAX_MS,te as LINK_BACKOFF_MIN_MS,$ as LINK_SILENCE_MS,de as VIEW_WRITE_LIMIT_BYTES,ce as createViewQueue,ae as linkUrl,be as startMachineLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var l=(a,t)=>y(a,"name",{value:t,configurable:!0});import{filterAsync as h}from"../../core/async-array.js";import{openDb as A,withCanvasWrite as b}from"../../core/canvas/db.js";import{getNode as I}from"../../core/canvas/canvas.js";import{liveExecutionForNode as k}from"../../core/canvas/executions.js";import{claimFaultNudge as v,listPendingProviderRetries as g,readLiveTurn as E}from"../../core/canvas/recovery.js";import{probeOnline as R}from"../../core/runtime/connectivity.js";import{nextFaultRetry as N}from"../../core/runtime/fault-recovery.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isSafeNodeId as m}from"../../core/canvas/paths.js";import{runThrottledLane as L}from"./throttled-lane.js";import{asNodePerson as S}from"./node-lifecycle/node-person.js";import{wakeResident as T}from"./node-lifecycle/remote-wake.js";const u=2*6e4,F=15e3;function _(a){const{fault:t}=a;if(t.retry.nextAt!==void 0){const i=Date.parse(t.retry.nextAt);return Number.isFinite(i)?i:null}const n=Date.parse(a.updatedAt),o=N(t,n);return Number.isFinite(n)&&o!==null?n+o.delayMs:null}l(_,"dueAtMs");const x=6e4,C="fault-retry-backstop";class J{static{l(this,"FaultRetryBackstopReconciler")}deps;constructor(t={}){this.deps=t}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return Promise.resolve();const o=L(C,"",t,F,x,()=>this.scan(t,n)).then(()=>{}).catch(i=>{p.fresh(()=>{d({level:"warn",event:"fault_retry_backstop.scan_failed",error:i})})});return n.lifecycle.registerDetached(o),o}async scan(t,n){const o=await(this.deps.list??g)(),i=this.deps.busy??(async e=>(await E(e))?.busy===!0),c=await h(o,async e=>{if(!await n.fleet.has(e.nodeId)||await i(e.nodeId))return!1;const r=_(e);return r===null||t<r+u?!1:e.nudgedAt===null||t-Date.parse(e.nudgedAt)>=u});if(c.length===0)return;let f;for(const e of c){if(e.fault.kind==="connection"&&(f??=await(this.deps.probeOnline??(()=>R()))(),!f)||!await n.fleet.has(e.nodeId)||await i(e.nodeId)||!await b(async()=>await v(e.fault.faultId,t,u)))continue;const r=await k(e.nodeId),s=r!==null&&r.runner!=="process"&&r.state==="running"?await I(e.nodeId):null;(r===null||s===null?"woken":await S({node_id:s.node_id,sub:s.sub??null,profile_id:s.profile_id??null},()=>T(r)).catch(w=>(d({level:"warn",event:"fault_retry_backstop.wake_failed",...m(e.nodeId)?{node_id:e.nodeId}:{},error:w}),null)))!=="lost"&&(await(await A()).prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`fault_retry:${e.nodeId}`),p.fresh(()=>{d({level:"info",event:"fault_retry_backstop.nudged",...m(e.nodeId)?{node_id:e.nodeId}:{},fields:{kind:e.fault.kind,since:e.fault.since,overdue_ms:t-(_(e)??t)}})}))}}}export{F as FAULT_RETRY_SCAN_INTERVAL_MS,u as FAULT_RETRY_STALE_GRACE_MS,J as FaultRetryBackstopReconciler,_ as dueAtMs};
|
|
@@ -13,6 +13,6 @@ export declare class IdleSandboxReconciler {
|
|
|
13
13
|
run(now: number, ctx: {
|
|
14
14
|
lifecycle: DetachedWorkLifecycle;
|
|
15
15
|
}): void;
|
|
16
|
-
/** One pass. `deleteExecution` is the runner's delete by default; tests pass their own. */
|
|
16
|
+
/** One pass. `deleteExecution` is the runner's delete of the node's sandbox by default; tests pass their own. */
|
|
17
17
|
pass(now: number, lane?: LanePass, deleteExecution?: (execution: RunnerExecution) => Promise<void>): Promise<IdleSandboxResult>;
|
|
18
18
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var c=(a,n)=>p(a,"name",{value:n,configurable:!0});import{openDb as m}from"../../core/canvas/db.js";import{endExecution as u}from"../../core/canvas/executions.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as _}from"../../core/events/operation-id.js";import{runnerForExecution as f}from"../../core/runtime/runner/index.js";import{runThrottledLane as E}from"./throttled-lane.js";const N=60*6e4,D=10080*6e4,S=10*6e4,I=50;class R{static{c(this,"IdleSandboxReconciler")}run(n,i){if(!i.lifecycle.acceptsDetachedWork())return;const o=_.fresh(()=>E("idle-sandbox","",n,N,S,async t=>{await this.pass(n,t)})).then(()=>{}).catch(t=>{_.fresh(()=>d({level:"error",event:"idle_sandbox.failed",error:t}))});i.lifecycle.registerDetached(o)}async pass(n,i,o=async t=>{await f("blaxel").delete(t.nodeId)}){const t={deleted:0,failed:0},r=new Date(n-D).toISOString(),s=await m(),x=await s.prepare(`SELECT x.execution_id, x.node_id, x.attempt, x.sandbox_name FROM executions x
|
|
2
2
|
JOIN nodes n ON n.node_id = x.node_id
|
|
3
3
|
JOIN profiles p ON p.id = n.profile_id
|
|
4
4
|
JOIN environments e ON e.object = p.environment_id
|
|
5
5
|
WHERE x.runner = 'blaxel' AND x.state = 'running' AND x.idle_at IS NOT NULL AND x.idle_at::timestamptz < ?::timestamptz
|
|
6
6
|
AND e.kind = 'blaxel' AND EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = e.object)
|
|
7
|
-
ORDER BY x.idle_at LIMIT ?`).all(
|
|
7
|
+
ORDER BY x.idle_at LIMIT ?`).all(r,I);for(const e of x){if(i&&!await i.holds())break;try{if(await s.prepare("SELECT 1 AS idle FROM executions WHERE execution_id = ? AND state = 'running' AND idle_at IS NOT NULL AND idle_at::timestamptz < ?::timestamptz").get(e.execution_id,r)===void 0)continue;await o({executionId:e.execution_id,nodeId:e.node_id,attempt:Number(e.attempt),sandboxName:e.sandbox_name}),await u(e.execution_id,{reason:"lost"}),t.deleted+=1,d({level:"info",event:"idle_sandbox.deleted",node_id:e.node_id,fields:{execution_id:e.execution_id}})}catch(l){t.failed+=1,d({level:"warn",event:"idle_sandbox.delete_failed",node_id:e.node_id,error:l,fields:{execution_id:e.execution_id}})}}return t}}export{I as IDLE_SANDBOX_BUDGET,N as IDLE_SANDBOX_INTERVAL_MS,D as IDLE_SANDBOX_MAX_AGE_MS,R as IdleSandboxReconciler};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var h=Object.defineProperty;var a=(e,
|
|
2
|
-
${o.output}`));const c=await b(e);if(c!==null){const l=await O(c,
|
|
1
|
+
var h=Object.defineProperty;var a=(e,t)=>h(e,"name",{value:t,configurable:!0});import{liveExecutionForNode as _,endExecution as f,recordExecutionAwake as v,endLaunchingExecution as m,requestExecutionStop as x}from"../../../core/canvas/executions.js";import{openDb as E}from"../../../core/canvas/db.js";import{isCloudRole as g}from"../../../core/canvas/person-state.js";import{getRow as b}from"../../../core/canvas/index.js";import{fullName as k}from"../../../core/canvas/labels.js";import{publishNotice as y}from"../../../core/runtime/close.js";import{emitEvent as i}from"../../../core/events/emit.js";import{findRefusal as $,refusalError as A,refusedMark as L,writeCharge as N}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as R}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as S}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as I}from"../ledger-sandbox.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as C}from"../recipe-image.js";import{recordRespawnPolicy as O}from"./respawn-policy.js";import{recordLaunchFailure as T}from"./launch-failure.js";const P=45*6e4,U=12e4,W=a(()=>D(),"acceptedRelease");async function ne(e){return e===null||!g()?null:await R(e)}a(ne,"remoteMachineEnvironmentOf");async function ae(e){const t=await S(e);if(t===null)return;const r={scope:"call",payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,provider:"blaxel"},n=await $(r),s=await E();if(n===null){await s.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await s.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:n.limit.id,usd:n.usd,reset_at:n.reset_at,at:new Date().toISOString()}),e.node_id),await N({id:`refused:sandbox:${e.node_id}:${n.limit.id}:${n.month}`,kind:"sandbox",what:"wake",usd:null,payer:r.payer,funding:"bill",sub:r.sub,grantee:r.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:L(n)}),A(n)}a(ae,"checkBilledWake");class oe extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(t,r){super(`environment ${t} has no built image yet${r===null?"":` (${r})`}; the wake waits for the build.`),this.environmentId=t,this.imageError=r,this.name="EnvironmentImagePending"}}async function ie(e){return await C(e)}a(ie,"imageForWake");async function se(e){if(e.release!==W()){if(await x(e.nodeId,{afterTurn:!1,reason:"release"}),e.stopRequestedAt!==null)return"lost";const t=await u(e.runner).stop(e,{reason:"release"});return t.confirmed?(await f(e.executionId,{reason:"release"}),"lost"):(i({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:t.error}),"lost")}return await u(e.runner).wake(e)==="no_broker"?(await f(e.executionId,{reason:"lost"}),"lost"):(await I(e.executionId,Date.now()),await v(e.executionId),"woken")}a(se,"wakeResident");async function le(e){const t=await u(e.runner).status(e,{idle:e.idleAt!==null});if(t.state!=="gone"&&t.state!=="failed")return!1;const r=await f(e.executionId,{reason:"lost"});return r&&i({level:"warn",event:"execution.lost",node_id:e.nodeId}),r}a(le,"endRemoteExecutionIfGone");async function ue(e,t){const r=await _(e);if(r===null||r.state!=="launching"||r.runner==="process")return!1;const n=u(r.runner),s=t-Date.parse(r.startedAt),o=await n.status(r);if(o.state==="unknown")return!1;if(o.state==="running")return s<=P||!await m(r.executionId,{reason:"launch_timeout"})?!1:(await n.stop(r,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),i({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(o.state==="failed"){if(!await m(r.executionId,{reason:"launch_failed"}))return!1;const d=`the sandbox start script failed: ${o.reason}`;await T(r.executionId,new Error(o.output===void 0?d:`${d}
|
|
2
|
+
${o.output}`));const c=await b(e);if(c!==null){const l=await O(c,t);if(!l.exhausted)i({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:o.reason,consecutive_failures:l.failures}});else{const p=`Child crashed \u2014 ${k(c)} (${e}) failed ${l.failures} consecutive sandbox launches (${d}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;i({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:p,respawn_failures:l.failures}}}),await y(e,"notice.crash",p,{reason:"child-crashed",child:e})}}return await n.delete(r.nodeId),!0}if(s>U){if(!await m(r.executionId,{reason:"launch_lost"}))return!1;i({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(ue,"recoverLaunching");export{oe as EnvironmentImagePending,P as LAUNCH_DEADLINE_MS,U as LAUNCH_LOST_GRACE_MS,W as acceptedRelease,ae as checkBilledWake,le as endRemoteExecutionIfGone,ie as imageForWake,ue as recoverLaunching,ne as remoteMachineEnvironmentOf,se as wakeResident};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.709",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.709",
|
|
161
|
+
"@north-light/plugin": "0.3.709",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -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.68';
|
|
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`. */
|
|
@@ -36,7 +36,7 @@ function ageLabel(iso) {
|
|
|
36
36
|
return `${Math.floor(hours / 24)}d`;
|
|
37
37
|
}
|
|
38
38
|
export function createInboxStrip(s, hooks) {
|
|
39
|
-
const {
|
|
39
|
+
const { remote, canvasSource, tui, pal } = s;
|
|
40
40
|
const component = new Container();
|
|
41
41
|
let tickets = [];
|
|
42
42
|
let nodes = new Map();
|
|
@@ -44,7 +44,7 @@ export function createInboxStrip(s, hooks) {
|
|
|
44
44
|
let top = 0; // first visible ticket row
|
|
45
45
|
const rowLine = (t) => {
|
|
46
46
|
const origin = t.source.nodeId;
|
|
47
|
-
const from = origin !== undefined && origin !== nodeId
|
|
47
|
+
const from = origin !== undefined && origin !== s.nodeId
|
|
48
48
|
? ` · ${navLabel(nodes.get(origin) ?? null, origin)}`
|
|
49
49
|
: '';
|
|
50
50
|
return truncate(` ${YELLOW}⚑${RESET} ${t.title}${pal.faint(` · ${ageLabel(ticketTime(t))}${from}`)}`);
|
|
@@ -74,7 +74,7 @@ export function createInboxStrip(s, hooks) {
|
|
|
74
74
|
* same pass already fetched carries every field read here, so the full node
|
|
75
75
|
* list is read only by a source without one. */
|
|
76
76
|
const subtreeNodes = async (view) => {
|
|
77
|
-
const roster = view ?? await canvasSource.panelView?.(nodeId);
|
|
77
|
+
const roster = view ?? await canvasSource.panelView?.(s.nodeId);
|
|
78
78
|
const list = roster === undefined
|
|
79
79
|
? await canvasSource.listNodes()
|
|
80
80
|
: roster.nodes.map((n) => ({ node_id: n.node_id, name: n.name, kind: n.kind, status: n.status, ...(n.description ? { description: n.description } : {}) }));
|
|
@@ -84,7 +84,7 @@ export function createInboxStrip(s, hooks) {
|
|
|
84
84
|
if (out.has(id))
|
|
85
85
|
return;
|
|
86
86
|
const row = rows.get(id) ?? null;
|
|
87
|
-
if (id !== nodeId && row?.kind === 'human')
|
|
87
|
+
if (id !== s.nodeId && row?.kind === 'human')
|
|
88
88
|
return;
|
|
89
89
|
out.set(id, row);
|
|
90
90
|
const below = roster === undefined
|
|
@@ -93,7 +93,7 @@ export function createInboxStrip(s, hooks) {
|
|
|
93
93
|
for (const childId of below)
|
|
94
94
|
await visit(childId);
|
|
95
95
|
};
|
|
96
|
-
await visit(nodeId);
|
|
96
|
+
await visit(s.nodeId);
|
|
97
97
|
return out;
|
|
98
98
|
};
|
|
99
99
|
const refresh = async (view) => {
|
|
@@ -34,7 +34,7 @@ import { buildCanvasPanelLines } from './canvas-panels.js';
|
|
|
34
34
|
/** How long an armed `x` waits for its `y`. */
|
|
35
35
|
const ARM_TIMEOUT_MS = 15_000;
|
|
36
36
|
export function createRoster(s, hooks) {
|
|
37
|
-
const { editor, tui, pal,
|
|
37
|
+
const { editor, tui, pal, remote, role, canvasSource } = s;
|
|
38
38
|
// The node's app comes from the node row the viewer already holds; resolving it from canvas.db would open the db in this process.
|
|
39
39
|
const reports = s.containers.reports;
|
|
40
40
|
let items = [];
|
|
@@ -62,19 +62,19 @@ export function createRoster(s, hooks) {
|
|
|
62
62
|
}
|
|
63
63
|
tui.requestRender();
|
|
64
64
|
};
|
|
65
|
-
const listJobs = async () => (await cliClient().listBashJobs(nodeId)).map(toBashJobStatus);
|
|
65
|
+
const listJobs = async () => (await cliClient().listBashJobs(s.nodeId)).map(toBashJobStatus);
|
|
66
66
|
const refresh = async (view) => {
|
|
67
67
|
const crons = remote ? [] : await cliClient().listCrons();
|
|
68
|
-
const ownedCrons = crons.filter((cron) => cron.created_by === nodeId);
|
|
69
|
-
// Local-only, same gate as ownedCrons: a local nodeId collision must never leak background jobs.
|
|
68
|
+
const ownedCrons = crons.filter((cron) => cron.created_by === s.nodeId);
|
|
69
|
+
// Local-only, same gate as ownedCrons: a local s.nodeId collision must never leak background jobs.
|
|
70
70
|
const bashJobs = remote ? [] : await listJobs();
|
|
71
71
|
// Reviews this node is the origin of: the person still holds an open one, or
|
|
72
72
|
// the daemon is finishing a submitted one behind its companion. Local-only,
|
|
73
73
|
// like the crons above — a remote graph id has no local review surface.
|
|
74
74
|
const openReviews = remote ? [] : (await cliClient().listReviews({ state: 'open' })).reviews;
|
|
75
|
-
const reviews = openReviews.filter((review) => review.origin_node_id === nodeId);
|
|
75
|
+
const reviews = openReviews.filter((review) => review.origin_node_id === s.nodeId);
|
|
76
76
|
const others = remote ? undefined : { crons, reviews: openReviews, jobsOf: async (id) => (await cliClient().listBashJobs(id)).map(toBashJobStatus) };
|
|
77
|
-
const built = await buildCanvasPanelLines(nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others, view ?? await canvasSource.panelView?.(nodeId));
|
|
77
|
+
const built = await buildCanvasPanelLines(s.nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others, view ?? await canvasSource.panelView?.(s.nodeId));
|
|
78
78
|
items = built.items;
|
|
79
79
|
// After an in-place swap, land on the previously open node, which has taken
|
|
80
80
|
// the swapped-to node's place in this self-excluding roster.
|
|
@@ -152,7 +152,7 @@ export function createRoster(s, hooks) {
|
|
|
152
152
|
return;
|
|
153
153
|
disarmKill(false);
|
|
154
154
|
hooks.setNotice(`Stopping “${target.label}”…`);
|
|
155
|
-
execFile('crtr', ['node', 'bash', 'kill', target.jobId, '--node', nodeId], (err) => {
|
|
155
|
+
execFile('crtr', ['node', 'bash', 'kill', target.jobId, '--node', s.nodeId], (err) => {
|
|
156
156
|
hooks.setNotice(err === null ? `Stopped “${target.label}”.` : `Could not stop the job: ${err.message.split('\n')[0]}`);
|
|
157
157
|
hooks.requestChromeRefresh();
|
|
158
158
|
});
|
|
@@ -202,7 +202,7 @@ export function createRoster(s, hooks) {
|
|
|
202
202
|
return;
|
|
203
203
|
}
|
|
204
204
|
const id = item.nodeId;
|
|
205
|
-
if (id === nodeId) {
|
|
205
|
+
if (id === s.nodeId) {
|
|
206
206
|
exit();
|
|
207
207
|
return;
|
|
208
208
|
} // already viewing this one
|
|
@@ -24,7 +24,7 @@ import { viewerKeyHint } from './key-hint.js';
|
|
|
24
24
|
const NOTICE_CLEAR_MS = 3_000;
|
|
25
25
|
const formatTokens = (n) => n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k` : `${n}`;
|
|
26
26
|
export function createStatusLine(s, hooks) {
|
|
27
|
-
const { pal, tui,
|
|
27
|
+
const { pal, tui, remote } = s;
|
|
28
28
|
const footer = s.containers.footer;
|
|
29
29
|
let notice = '';
|
|
30
30
|
let noticeTimer;
|
|
@@ -25,7 +25,8 @@ export function createViewerCapabilities(input) {
|
|
|
25
25
|
return {
|
|
26
26
|
role,
|
|
27
27
|
remote,
|
|
28
|
-
|
|
28
|
+
// Lazy: a viewer whose node is still being created has no id yet, and reading one then is a bug the source must throw on.
|
|
29
|
+
get nodeId() { return input.nodeId; },
|
|
29
30
|
profileId: input.profileId,
|
|
30
31
|
permittedOperations,
|
|
31
32
|
permits: (operation) => permittedOperations.has(operation),
|
|
@@ -73,7 +73,18 @@ export class InputController {
|
|
|
73
73
|
send = (frame) => {
|
|
74
74
|
this.emitCommand(frame);
|
|
75
75
|
};
|
|
76
|
+
/** While the node is being created only these frames are accepted (prompts are held until the welcome; a `!` command is refused like a slash command); everything else needs the node. */
|
|
77
|
+
refuseStarting(frame) {
|
|
78
|
+
if (this.hooks.isStarting?.() !== true)
|
|
79
|
+
return false;
|
|
80
|
+
if (frame !== undefined && (frame.type === 'prompt' || frame.type === 'follow_up'))
|
|
81
|
+
return false;
|
|
82
|
+
this.notify('The node is starting — try again in a moment');
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
76
85
|
emitCommand(frame) {
|
|
86
|
+
if (this.refuseStarting(frame))
|
|
87
|
+
return false;
|
|
77
88
|
const operation = viewerOperationForFrame(frame);
|
|
78
89
|
const refusal = operation === undefined ? undefined : this.capabilities.refusal(operation);
|
|
79
90
|
if (refusal === undefined) {
|
|
@@ -84,6 +95,8 @@ export class InputController {
|
|
|
84
95
|
return false;
|
|
85
96
|
}
|
|
86
97
|
openBrokerPicker(open) {
|
|
98
|
+
if (this.refuseStarting())
|
|
99
|
+
return;
|
|
87
100
|
const refusal = this.capabilities.refusal('engine-drive');
|
|
88
101
|
if (refusal !== undefined) {
|
|
89
102
|
this.notify(refusal);
|
|
@@ -195,6 +208,8 @@ export class InputController {
|
|
|
195
208
|
const trimmed = text.trim();
|
|
196
209
|
if (!trimmed)
|
|
197
210
|
return;
|
|
211
|
+
if (isSlashCommand(trimmed) && this.refuseStarting())
|
|
212
|
+
return;
|
|
198
213
|
if (isSlashCommand(trimmed) && dispatchSlashCommand(trimmed, this.slashContext())) {
|
|
199
214
|
this.recordCommandUse(trimmed);
|
|
200
215
|
this.editor.setText('');
|
|
@@ -264,6 +279,8 @@ export class InputController {
|
|
|
264
279
|
this.clearPastedImages();
|
|
265
280
|
}
|
|
266
281
|
async handleDequeue() {
|
|
282
|
+
if (this.refuseStarting())
|
|
283
|
+
return;
|
|
267
284
|
const refusal = this.capabilities.refusal('dequeue');
|
|
268
285
|
if (refusal !== undefined) {
|
|
269
286
|
this.notify(refusal);
|
|
@@ -102,7 +102,7 @@ function graphRow(dto) {
|
|
|
102
102
|
}
|
|
103
103
|
export class GraphOverlay {
|
|
104
104
|
tui;
|
|
105
|
-
|
|
105
|
+
selfId;
|
|
106
106
|
getAsks;
|
|
107
107
|
palette;
|
|
108
108
|
bindings;
|
|
@@ -129,9 +129,9 @@ export class GraphOverlay {
|
|
|
129
129
|
* default and makes Enter/r/m/x no-op instead of shelling local lifecycle
|
|
130
130
|
* commands against a remote graph row. See the file header. */
|
|
131
131
|
remote;
|
|
132
|
-
constructor(tui,
|
|
132
|
+
constructor(tui, selfId, getAsks, palette, bindings, source, role = 'controller', onRefreshFailure = () => { }, onNotice = () => { }) {
|
|
133
133
|
this.tui = tui;
|
|
134
|
-
this.
|
|
134
|
+
this.selfId = selfId;
|
|
135
135
|
this.getAsks = getAsks;
|
|
136
136
|
this.palette = palette;
|
|
137
137
|
this.bindings = bindings;
|
|
@@ -141,6 +141,7 @@ export class GraphOverlay {
|
|
|
141
141
|
this.onNotice = onNotice;
|
|
142
142
|
this.remote = source instanceof RemoteCanvasSource;
|
|
143
143
|
}
|
|
144
|
+
get self() { return this.selfId(); }
|
|
144
145
|
setBindings(bindings) {
|
|
145
146
|
this.bindings = bindings;
|
|
146
147
|
if (this.handle !== undefined)
|
|
@@ -255,6 +255,15 @@ export class ChatView {
|
|
|
255
255
|
pendingSends = [];
|
|
256
256
|
/** Optional banner, above history and status in the viewport's flat source. */
|
|
257
257
|
bannerContainer;
|
|
258
|
+
/** Add one line to the banner after construction: a new root learns its id only when its create returns. */
|
|
259
|
+
setBannerHint(line) {
|
|
260
|
+
const banner = this.bannerContainer;
|
|
261
|
+
if (banner === undefined)
|
|
262
|
+
return;
|
|
263
|
+
banner.removeChild(banner.children[banner.children.length - 1]);
|
|
264
|
+
banner.addChild(new Text(line, 1, 0));
|
|
265
|
+
banner.addChild(new Spacer(1));
|
|
266
|
+
}
|
|
258
267
|
transcript;
|
|
259
268
|
/** Inline page blocks placed in this transcript, by page id — one block per
|
|
260
269
|
* page, so a `--replace` revision refreshes the block already on screen. */
|
|
@@ -17,7 +17,7 @@ export function isTransientDaemonFailure(error) {
|
|
|
17
17
|
return isDaemonTransportApiError(error) || (error instanceof APIError && error.status >= 500);
|
|
18
18
|
}
|
|
19
19
|
export function createChromeRefresh(ctx, hooks) {
|
|
20
|
-
const {
|
|
20
|
+
const { canvasSource } = ctx;
|
|
21
21
|
let asksMap = {};
|
|
22
22
|
let asksTimer;
|
|
23
23
|
let stopped = false;
|
|
@@ -63,6 +63,9 @@ export function createChromeRefresh(ctx, hooks) {
|
|
|
63
63
|
let chromeRefreshInFlight = false;
|
|
64
64
|
let chromeRefreshQueued = false;
|
|
65
65
|
const refresh = () => {
|
|
66
|
+
// A root still being created has no canvas tree to read; binding the node starts the first refresh.
|
|
67
|
+
if (ctx.nodeId === '')
|
|
68
|
+
return;
|
|
66
69
|
chromeRefreshQueued = true;
|
|
67
70
|
if (chromeRefreshInFlight)
|
|
68
71
|
return;
|
|
@@ -74,7 +77,7 @@ export function createChromeRefresh(ctx, hooks) {
|
|
|
74
77
|
const seqBefore = failureSeq;
|
|
75
78
|
try {
|
|
76
79
|
// One read of this node's tree feeds the panels, the inbox strip and the ask counts.
|
|
77
|
-
const view = await canvasSource.panelView?.(nodeId);
|
|
80
|
+
const view = await canvasSource.panelView?.(ctx.nodeId);
|
|
78
81
|
if (view !== undefined)
|
|
79
82
|
setAsks(view.counts);
|
|
80
83
|
await hooks.refreshRoster(view);
|
|
@@ -120,7 +123,7 @@ export function createChromeRefresh(ctx, hooks) {
|
|
|
120
123
|
// A remote canvas has no tree read: it climbs and counts node by node.
|
|
121
124
|
if (canvasSource.panelView === undefined)
|
|
122
125
|
void (async () => {
|
|
123
|
-
const root = await climbRootFromSource(nodeId);
|
|
126
|
+
const root = await climbRootFromSource(ctx.nodeId);
|
|
124
127
|
const counts = await canvasSource.ticketCountsForView(root);
|
|
125
128
|
if (JSON.stringify(counts) !== JSON.stringify(asksMap)) {
|
|
126
129
|
asksMap = counts;
|