@north-light/cli 0.3.670 → 0.3.672
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/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +5 -5
- 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/blaxel/image-build.js +13 -5
- 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
- package/scripts/sandbox-start.mjs +8 -1
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// revive-all — resume EVERY disconnected node in one shot.
|
|
2
|
+
//
|
|
3
|
+
// After a mass-disconnect event (a reboot, a killed login/tmux session, a mass
|
|
4
|
+
// crash, or the daemon being down a while) many nodes end up with their
|
|
5
|
+
// canvas.db row + saved conversation intact but NO broker engine running. The
|
|
6
|
+
// daemon recovers active|idle rows during its row-driven supervision tick and
|
|
7
|
+
// from broker exit events during its own epoch, but it deliberately never touches
|
|
8
|
+
// terminal/dormant states, so the operator is left reviving survivors one id at
|
|
9
|
+
// a time.
|
|
10
|
+
//
|
|
11
|
+
// This module is the single sweep: `listDisconnected` selects every DISCONNECTED
|
|
12
|
+
// node (engine not running, but a resumable saved session exists), and
|
|
13
|
+
// `reviveAll` RESUMEs each via reviveNode — the only sanctioned launcher, which
|
|
14
|
+
// self-guards the double-spawn. The selection predicate (`isDisconnected`) is
|
|
15
|
+
// pure so the scope rules are unit-testable without booting a single process.
|
|
16
|
+
import { listNodes, getNode } from '../canvas/index.js';
|
|
17
|
+
import { recordedPidLiveness } from '../canvas/pid.js';
|
|
18
|
+
import { reviveNode } from './revive.js';
|
|
19
|
+
import { filterAsync } from '../async-array.js';
|
|
20
|
+
/** Statuses a node lands in DELIBERATELY: a worker that finished its own work
|
|
21
|
+
* (`done`) or a node a human closed/reaped (`canceled`). The daemon never
|
|
22
|
+
* auto-revives these (see reapDeadResidue in crtrd.ts), and revive-all leaves
|
|
23
|
+
* them alone too — resurrecting finished and closed conversations en masse would
|
|
24
|
+
* flood the canvas with work nobody asked to reopen. `dead` is NOT here: a crash
|
|
25
|
+
* is involuntary, so it is swept. (Silas, 2026-06-13: no opt-in to include these
|
|
26
|
+
* — the exclusion is unconditional.) */
|
|
27
|
+
export const TERMINAL_BY_CHOICE = ['done', 'canceled'];
|
|
28
|
+
/** True when `meta` has no natural future cycle ahead of it. A frozen row is
|
|
29
|
+
* excluded because its mark records a thaw cycle already owed. */
|
|
30
|
+
export function hasNoNaturalCycle(meta) {
|
|
31
|
+
return meta.frozen_at == null && (meta.final_report != null || TERMINAL_BY_CHOICE.includes(meta.status));
|
|
32
|
+
}
|
|
33
|
+
/** True when `meta`'s engine is NOT running but it has a resumable saved session
|
|
34
|
+
* — the precise "disconnected" predicate.
|
|
35
|
+
*
|
|
36
|
+
* - engine not running: no live `pi_pid` (a dead/absent broker pid).
|
|
37
|
+
* - reconnectable: a captured pi session marker (`pi_session_file` or
|
|
38
|
+
* `pi_session_id`) — without one there is nothing to reopen. reviveNode
|
|
39
|
+
* resumes by the `.jsonl` path when it still exists, else relaunches fresh (a
|
|
40
|
+
* bare `pi_session_id` alone does not resume — the broker preflight rejects
|
|
41
|
+
* it — so such a node comes back fresh).
|
|
42
|
+
* - `human`-kind rows are the `crtr human` bridge, never a pi engine, so they
|
|
43
|
+
* are never "disconnected" (mirrors the daemon's superviseTick carve-out).
|
|
44
|
+
* - unfrozen terminal-by-choice (`done`/`canceled`) is excluded.
|
|
45
|
+
* - a node that already pushed its FINAL REPORT (`final_report` set) FINISHED
|
|
46
|
+
* its own work — it is excluded regardless of status. A crash mid-reap can
|
|
47
|
+
* leave it `dead` (not terminal-by-choice) with its report already committed;
|
|
48
|
+
* resurrecting it as `active` strands it re-reviving forever and cannot
|
|
49
|
+
* re-reap (the stuck-node incident). Mass revive must never resurrect
|
|
50
|
+
* finished work; an explicit `node lifecycle revive <id>` still can.
|
|
51
|
+
*
|
|
52
|
+
* Pure: the liveness probe is injected so scope is unit-testable without real
|
|
53
|
+
* processes. */
|
|
54
|
+
export function isDisconnected(meta, isAlive) {
|
|
55
|
+
if (meta.kind === 'human')
|
|
56
|
+
return false;
|
|
57
|
+
if (isAlive(meta.pi_pid))
|
|
58
|
+
return false; // engine running → connected
|
|
59
|
+
if (meta.pi_session_id == null && meta.pi_session_file == null)
|
|
60
|
+
return false; // nothing to resume
|
|
61
|
+
if (hasNoNaturalCycle(meta))
|
|
62
|
+
return false; // finished its own work, or terminal-by-choice — never mass-revive
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
/** Every disconnected node on the canvas — the set a revive-all WOULD relaunch.
|
|
66
|
+
* This is the PREVIEW: it has no side effects, so the command can list the
|
|
67
|
+
* candidates and gate on confirmation before any engine is launched. */
|
|
68
|
+
export async function listDisconnected() {
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const row of await listNodes()) {
|
|
71
|
+
const meta = await getNode(row.node_id);
|
|
72
|
+
// IDENTITY-aware AND requires CONFIRMED alive: a bare isPidAlive would
|
|
73
|
+
// misread a recycled pi_pid as "engine running" and SKIP the node, so it
|
|
74
|
+
// never reaches reviveNode's own identity-aware double-launch guard
|
|
75
|
+
// guard. `dead` OR `indeterminate` both count as disconnected/eligible
|
|
76
|
+
// here — only a
|
|
77
|
+
// positively confirmed-alive read is treated as "still connected".
|
|
78
|
+
if (meta !== null && isDisconnected(meta, (pid) => recordedPidLiveness(pid, meta.pi_pid_identity) === 'alive'))
|
|
79
|
+
out.push(meta);
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
/** RESUME every disconnected node. reviveNode is the ONLY sanctioned launcher
|
|
84
|
+
* and self-guards the double-spawn (a node whose broker pid is already live is a
|
|
85
|
+
* no-op), so this is a thin orchestrator over `listDisconnected`: revive each
|
|
86
|
+
* with resume:true. One failing node never aborts the sweep — its error is
|
|
87
|
+
* collected and the rest proceed. */
|
|
88
|
+
export async function reviveAll(include = async () => true) {
|
|
89
|
+
const result = { revived: [], failed: [], frozen: [] };
|
|
90
|
+
for (const meta of (await filterAsync(await listDisconnected(), include))) {
|
|
91
|
+
try {
|
|
92
|
+
// Reconnecting a disconnected broker is recovery, not a wake — a node
|
|
93
|
+
// waiting on an armed deadline keeps it across the sweep. A sweep over a
|
|
94
|
+
// whole canvas is the likeliest way to meet the cap, and every node in it
|
|
95
|
+
// is one the daemon wants back: freeze the overflow and let the tick
|
|
96
|
+
// bring them up as slots free.
|
|
97
|
+
const outcome = (await reviveNode(meta.node_id, { resume: true, recovery: true, capacity: 'freeze' })).outcome;
|
|
98
|
+
if (outcome === 'frozen')
|
|
99
|
+
result.frozen.push(meta.node_id);
|
|
100
|
+
else
|
|
101
|
+
result.revived.push(meta.node_id);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
result.failed.push({ node_id: meta.node_id, error: err.message });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
@@ -20,8 +20,14 @@ export const RECIPE_PI_AGENT_DIR = '/var/lib/crtr/recipe-pi-agent';
|
|
|
20
20
|
const PI_VERSION = '1.1.0';
|
|
21
21
|
export const SETUP_SCRIPT_FILE = 'recipe-setup.sh';
|
|
22
22
|
export const REPOS_DIR = 'repos';
|
|
23
|
+
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
24
|
+
export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
|
|
25
|
+
export const SETUP_FAILED_FILE = '/work/.crtr/setup-failed';
|
|
23
26
|
const shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
24
27
|
const lines = (text) => (text ?? '').split('\n').map((l) => l.trim()).filter((l) => l !== '');
|
|
28
|
+
/** A RUN step that cannot fail the build (Blaxel hangs on a failed step and its build log is unreadable): its output goes to `SETUP_LOG_FILE` and a
|
|
29
|
+
* failure appends `<label> exited <status>` to `SETUP_FAILED_FILE`, which the sandbox start script refuses to start on. */
|
|
30
|
+
const guarded = (label, command) => `RUN { ${command}; } >> ${SETUP_LOG_FILE} 2>&1 || echo ${shellQuote(label)} "exited $?" >> ${SETUP_FAILED_FILE}`;
|
|
25
31
|
/** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
|
|
26
32
|
* Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
|
|
27
33
|
* the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
|
|
@@ -34,20 +40,22 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
34
40
|
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
35
41
|
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /work/.crtr ${RECIPE_PI_AGENT_DIR} && chown -R ${RUN_USER} /work /var/lib/crtr`,
|
|
36
42
|
];
|
|
37
|
-
const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...base.slice(1),
|
|
43
|
+
const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
|
|
38
44
|
// An empty `repos/` is not in the zip, and a COPY of a missing directory fails the build.
|
|
39
45
|
if (recipe.repositories.length > 0)
|
|
40
46
|
out.push(`COPY --chown=${RUN_USER} ${REPOS_DIR}/ /work/`);
|
|
41
47
|
if (packages.length > 0)
|
|
42
|
-
out.push(`
|
|
48
|
+
out.push(guarded('npm install pi', `npm install -g @earendil-works/pi-coding-agent@${PI_VERSION}`));
|
|
43
49
|
if (hasScript)
|
|
44
50
|
out.push(`COPY ${SETUP_SCRIPT_FILE} /tmp/${SETUP_SCRIPT_FILE}`);
|
|
45
51
|
out.push('WORKDIR /work');
|
|
46
52
|
for (const source of packages)
|
|
47
|
-
out.push(`
|
|
53
|
+
out.push(guarded(`pi install ${source}`, `HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${RECIPE_PI_AGENT_DIR} pi install ${shellQuote(source)}`));
|
|
54
|
+
// Blaxel never reports a failed Docker step: the image stays BUILDING until the timeout, and its build log is not readable. So a failing script must not fail
|
|
55
|
+
// the step. Its output and exit status are kept in the image (`SETUP_LOG_FILE`, `SETUP_FAILED_FILE`) and the sandbox start script refuses to start with them.
|
|
48
56
|
if (hasScript)
|
|
49
|
-
out.push(`
|
|
50
|
-
out.push(`
|
|
57
|
+
out.push(guarded('setup script', `bash /tmp/${SETUP_SCRIPT_FILE}`));
|
|
58
|
+
out.push(guarded('finalize', `echo ${Math.trunc(revision)} > /work/.crtr/recipe-revision && chown -R ${RUN_USER} /work /home/${RUN_USER} /var/lib/crtr`));
|
|
51
59
|
out.push('', ...base);
|
|
52
60
|
for (const dir of ['/work', `/home/${RUN_USER}`, '/usr/local', '/var/lib/crtr', '/usr', '/etc', '/lib'])
|
|
53
61
|
out.push(`COPY --from=build ${dir} ${dir}`);
|
|
@@ -11,7 +11,7 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
|
|
|
11
11
|
/** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
|
|
12
12
|
* 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
|
|
13
13
|
export const MACHINE_CALL_TIMEOUT_S = {
|
|
14
|
-
start: 60, wake: 15, stop: 15, status: 15, 'status.all': 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15,
|
|
14
|
+
start: 60, wake: 15, stop: 15, status: 15, 'status.all': 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 15,
|
|
15
15
|
'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60,
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel',
|
|
1
|
+
export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
|
|
2
2
|
'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'];
|
|
3
3
|
/** No live link row for the environment: the caller leaves its work pending and retries on its own backoff. */
|
|
4
4
|
export class MachineOfflineError extends Error {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Daemon-owned surfaces for one node's background bash jobs: a job is a canvas row
|
|
2
2
|
// (see core/graph/jobs.ts); its process runs under the broker's supervisor, which
|
|
3
3
|
// reports pgid, activity, output and exit through `report`.
|
|
4
|
+
import { queueJobStop } from '../../cron/machine-fire.js';
|
|
4
5
|
import { killBashJobObject, recordBashJobObject } from '../../../core/spaces/stop.js';
|
|
5
6
|
import { readerFor } from '../reader.js';
|
|
6
7
|
import { join } from 'node:path';
|
|
@@ -218,7 +219,7 @@ async function handleStop(ctx) {
|
|
|
218
219
|
const job = (await runningJobs(await openDb(), nodeId)).find((candidate) => candidate.jobId === jobId);
|
|
219
220
|
if (job === undefined)
|
|
220
221
|
throw new ApiError(404, 'job_not_found', `no running background job ${jobId} for ${nodeId}`);
|
|
221
|
-
// A sandbox job is stopped where it runs:
|
|
222
|
+
// A sandbox job is stopped where it runs: a `job.stop` machine call is queued once the row ends.
|
|
222
223
|
const remote = await ownerRunsRemotely(await openDb(), nodeId);
|
|
223
224
|
if (!remote && (job.pgid === null || job.pgidIdentity === null))
|
|
224
225
|
throw new ApiError(409, 'job_not_stoppable', `job ${jobId} reported no trusted process identity`);
|
|
@@ -228,6 +229,16 @@ async function handleStop(ctx) {
|
|
|
228
229
|
const reader = await readerFor(db, ctx);
|
|
229
230
|
return reader.class === 'person' ? reader.person : reader.class === 'app' ? reader.app : reader.node;
|
|
230
231
|
});
|
|
232
|
+
// The row has ended, so a failed queue cannot be reported as a failed kill: say the process may still be running.
|
|
233
|
+
let stopQueueError;
|
|
234
|
+
if (remote) {
|
|
235
|
+
try {
|
|
236
|
+
await queueJobStop(nodeId, jobId);
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
stopQueueError = err instanceof Error ? err.message : String(err);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
231
242
|
const node = await getNode(nodeId);
|
|
232
243
|
if (node !== null && !isBrokerLive(node)) {
|
|
233
244
|
try {
|
|
@@ -235,7 +246,7 @@ async function handleStop(ctx) {
|
|
|
235
246
|
}
|
|
236
247
|
catch { /* the notice remains durable */ }
|
|
237
248
|
}
|
|
238
|
-
const result = { node_id: nodeId, job_id: jobId, signaled, ...(remote ? { stop_pending_on_machine: true } : {}) };
|
|
249
|
+
const result = { node_id: nodeId, job_id: jobId, signaled, ...(remote ? { stop_pending_on_machine: true } : {}), ...(stopQueueError === undefined ? {} : { stop_queue_error: stopQueueError }) };
|
|
239
250
|
return { status: 200, body: result };
|
|
240
251
|
}
|
|
241
252
|
/** The broker backgrounded a command: record it as the node's job row (id = job id). */
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { envHomeOverride } from '../../shared/env.js';
|
|
2
|
+
import { loadProfileManifest, lookupProfile } from '../../core/profiles/manifest.js';
|
|
3
|
+
import { localEnvironmentSecrets } from '../../core/secrets/environment-owner.js';
|
|
4
|
+
import { ADMITTED_HOST_PATH_ENV, buildOperationalEnvBase } from '../../core/runtime/spawn-env.js';
|
|
5
|
+
import { getNode } from '../../core/canvas/canvas.js';
|
|
6
|
+
import { contextDir } from '../../core/canvas/paths.js';
|
|
7
|
+
import { appendRunEvent } from '../../core/runs/events.js';
|
|
8
|
+
import { payerOfGrant } from '../../core/grants/mirror.js';
|
|
9
|
+
import { scopeAllowed } from '../../core/scopes.js';
|
|
10
|
+
import { cronPrincipalOf } from './authority.js';
|
|
11
|
+
import { personId } from '../../core/canvas/person.js';
|
|
12
|
+
/** The cron's profile, re-validated now and returned in canonical id form.
|
|
13
|
+
*
|
|
14
|
+
* A DELETED profile is the spec's root fallback: null. An UNREADABLE one is
|
|
15
|
+
* not — the profile is still there, so running as root would execute the
|
|
16
|
+
* command under an identity nobody armed, with the profile's own env store and
|
|
17
|
+
* purview silently replaced. That throws, and the run fails loudly once
|
|
18
|
+
* instead of running wrong on every tick. */
|
|
19
|
+
export function resolveLiveProfile(c) {
|
|
20
|
+
if (c.profile == null)
|
|
21
|
+
return null;
|
|
22
|
+
let lookup;
|
|
23
|
+
try {
|
|
24
|
+
lookup = lookupProfile(c.profile);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null; // an ambiguous NAME resolves no better than a deleted profile
|
|
28
|
+
}
|
|
29
|
+
if (lookup.kind === 'resolved')
|
|
30
|
+
return lookup.entry.profileId;
|
|
31
|
+
if (lookup.kind === 'absent')
|
|
32
|
+
return null;
|
|
33
|
+
throw new ArmedContextError(`the armed profile "${c.profile}" is still on this host but its manifest could not be read (${lookup.manifestPath}) — running as root would silently give this cron a different identity, env store, and purview. Repair the manifest, or re-arm the cron under a profile that resolves.`);
|
|
34
|
+
}
|
|
35
|
+
export function cronBirthPrincipalOf(c) {
|
|
36
|
+
return { ...cronPrincipalOf(c), cron_id: c.cron_id, origin_run_id: c.origin_run_id, isolated: c.isolated, creator: c.created_by };
|
|
37
|
+
}
|
|
38
|
+
export async function cronBirthPlacement(p, nodeId) {
|
|
39
|
+
const creator = p.creator === null ? null : await getNode(p.creator);
|
|
40
|
+
if (creator !== null && p.origin_run_id !== null && creator.run_id === p.origin_run_id &&
|
|
41
|
+
(await getNode(p.origin_run_id))?.deleting_at == null &&
|
|
42
|
+
creator.grantee === p.grantee && (creator.sub ?? personId()) === p.sub && (creator.grant_id ?? null) === p.grant_id &&
|
|
43
|
+
(p.scopes === null ? creator.scopes == null : p.scopes.every((scope) => scopeAllowed(creator.scopes, scope)))) {
|
|
44
|
+
return { parent: creator.node_id, ...(p.scopes === null ? {} : { scopes: [...p.scopes] }) };
|
|
45
|
+
}
|
|
46
|
+
const bounded = p.scopes === null ? {} : { scopes: [...p.scopes] };
|
|
47
|
+
// Every root birth carries the checked principal as its run (the terminal included), so the node
|
|
48
|
+
// keeps exactly the grant and sub that were checked, whatever the terminal grant is by the time it spawns.
|
|
49
|
+
// A null grant_id (a terminal cron on a runtime with no issuer) stays null.
|
|
50
|
+
return {
|
|
51
|
+
root: true, rootLifecycle: 'terminal', ...bounded,
|
|
52
|
+
run: { grantee: p.grantee, sub: p.sub, grant_id: p.grant_id, client_id: null, metadata_json: JSON.stringify(p.cron_id === null ? { exec: true } : { cron_id: p.cron_id }),
|
|
53
|
+
run_id: nodeId, event_cursor: 1,
|
|
54
|
+
usage_json: JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) },
|
|
55
|
+
// A node born with an explicit `run` does not get its `run.started` event from the spawner.
|
|
56
|
+
withinCreate: async (db, row) => {
|
|
57
|
+
await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: await payerOfGrant(p.grant_id), usage: JSON.parse(row.usage_json) });
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
// The escalation node must still report an unreadable manifest, so its own spawn falls back to root.
|
|
62
|
+
export function resolveLiveProfileOrRoot(c) {
|
|
63
|
+
try {
|
|
64
|
+
return resolveLiveProfile(c);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export function resolveLiveProfileName(c) {
|
|
71
|
+
if (c.profile == null)
|
|
72
|
+
return undefined;
|
|
73
|
+
try {
|
|
74
|
+
return loadProfileManifest(c.profile).manifest.name;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** A stored context cannot be rebuilt; the run fails rather than running under a context nobody armed. */
|
|
81
|
+
export class ArmedContextError extends Error {
|
|
82
|
+
constructor(message) {
|
|
83
|
+
super(message);
|
|
84
|
+
this.name = 'ArmedContextError';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Invalid snapshots are corruption: dropping `--env` would run under an environment nobody armed, so fail instead.
|
|
88
|
+
export function parseArmedEnv(envJson) {
|
|
89
|
+
if (envJson == null)
|
|
90
|
+
return {};
|
|
91
|
+
let parsed;
|
|
92
|
+
try {
|
|
93
|
+
parsed = JSON.parse(envJson);
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
throw new ArmedContextError(`the armed env snapshot is not valid JSON (${err.message}) — this cron's stored env_json is corrupt, so the run would silently drop every armed variable. Re-arm the cron with a valid --env.`);
|
|
97
|
+
}
|
|
98
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
99
|
+
throw new ArmedContextError("the armed env snapshot is not a JSON object — this cron's stored env_json is corrupt. Re-arm the cron with a valid --env.");
|
|
100
|
+
}
|
|
101
|
+
const extraEnv = {};
|
|
102
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
103
|
+
if (typeof v !== 'string') {
|
|
104
|
+
throw new ArmedContextError(`the armed env snapshot's value for "${k}" is not a string — this cron's stored env_json is corrupt, so the run would silently drop that variable. Re-arm the cron with a valid --env.`);
|
|
105
|
+
}
|
|
106
|
+
extraEnv[k] = v;
|
|
107
|
+
}
|
|
108
|
+
return extraEnv;
|
|
109
|
+
}
|
|
110
|
+
/** Rebuild the armed context. Corrupt snapshots and unreadable profiles fail rather than silently changing its identity or environment. */
|
|
111
|
+
export async function buildArmedRunContext(c, runId) {
|
|
112
|
+
const extraEnv = parseArmedEnv(c.env_json);
|
|
113
|
+
const isTerminal = c.grantee === 'app:terminal';
|
|
114
|
+
const profileId = isTerminal ? resolveLiveProfile(c) : null;
|
|
115
|
+
const operationalEnv = buildOperationalEnvBase({ targetCwd: c.cwd, targetProfileId: profileId, skipSpawnAllow: !isTerminal });
|
|
116
|
+
const env = {
|
|
117
|
+
...operationalEnv,
|
|
118
|
+
...await localEnvironmentSecrets(profileId, c.grantee),
|
|
119
|
+
...extraEnv,
|
|
120
|
+
...(profileId !== null ? { CRTR_PROFILE_ID: profileId } : {}),
|
|
121
|
+
CRTR_CRON_ID: c.cron_id,
|
|
122
|
+
CRTR_CRON_NAME: c.name,
|
|
123
|
+
CRTR_RUN_ID: runId,
|
|
124
|
+
};
|
|
125
|
+
// Preserve the daemon identity: otherwise child `crtr` resolves the default canvas.
|
|
126
|
+
const canvasHomeOverride = envHomeOverride();
|
|
127
|
+
if (canvasHomeOverride !== undefined && canvasHomeOverride !== '') {
|
|
128
|
+
env['CRTR_HOME'] = canvasHomeOverride;
|
|
129
|
+
}
|
|
130
|
+
if (c.anchor_node != null) {
|
|
131
|
+
env['CRTR_ANCHOR'] = c.anchor_node;
|
|
132
|
+
// The anchor node's own context dir, as nodeEnv() gives the node itself. An
|
|
133
|
+
// unanchored cron has no node, so it gets none — and a vanished anchor gets none either.
|
|
134
|
+
const anchor = await getNode(c.anchor_node);
|
|
135
|
+
if (anchor !== null)
|
|
136
|
+
env['CRTR_CONTEXT_DIR'] = contextDir(anchor.node_id, anchor.grantee);
|
|
137
|
+
}
|
|
138
|
+
env[ADMITTED_HOST_PATH_ENV] = operationalEnv[ADMITTED_HOST_PATH_ENV];
|
|
139
|
+
return { profileId, env };
|
|
140
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// src/daemon/cron/capture.ts — output capture for a cron run's child process,
|
|
2
|
+
// plus the timing/hash constants the capture and kill mechanics share.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
/** Output head caps for the run log (spec: "capped, e.g. 4KB"). */
|
|
5
|
+
export const CRON_OUTPUT_HEAD_BYTES = 4 * 1024;
|
|
6
|
+
/** Bound between the run-timeout SIGTERM and a forced SIGKILL escalation, so
|
|
7
|
+
* a signal-trapping command cannot stall teardown's detached drain. */
|
|
8
|
+
export const CRON_KILL_GRACE_MS = 2000;
|
|
9
|
+
/** Poll interval while waiting for a SIGTERMed stale-lease run to actually die
|
|
10
|
+
* (each probe is a `ps` call, so this is deliberately coarse). */
|
|
11
|
+
export const CRON_DEATH_POLL_MS = 250;
|
|
12
|
+
/** sha256 of empty stdout — the change-detection hash a run that produced no
|
|
13
|
+
* output carries (a failed spawn, a recovered stale lease). */
|
|
14
|
+
export const EMPTY_STDOUT_SHA256 = createHash('sha256').update('').digest('hex');
|
|
15
|
+
/** A byte-capped capture of one output stream's head. Bytes are buffered and
|
|
16
|
+
* decoded exactly once, at the end — decoding per chunk both mis-measured the
|
|
17
|
+
* cap (UTF-16 code units, not bytes) and corrupted any multi-byte sequence
|
|
18
|
+
* that straddled a chunk boundary. Truncation is MARKED, never silent: a
|
|
19
|
+
* clipped body reads as complete output to whoever receives the delivery. */
|
|
20
|
+
export function newHeadCapture(headBytes = CRON_OUTPUT_HEAD_BYTES) {
|
|
21
|
+
const chunks = [];
|
|
22
|
+
let bytes = 0;
|
|
23
|
+
let wasTruncated = false;
|
|
24
|
+
return {
|
|
25
|
+
take(chunk) {
|
|
26
|
+
const room = headBytes - bytes;
|
|
27
|
+
if (room <= 0) {
|
|
28
|
+
wasTruncated = true;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (chunk.length > room) {
|
|
32
|
+
chunks.push(chunk.subarray(0, room));
|
|
33
|
+
bytes = headBytes;
|
|
34
|
+
wasTruncated = true;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
chunks.push(chunk);
|
|
38
|
+
bytes += chunk.length;
|
|
39
|
+
},
|
|
40
|
+
decode() {
|
|
41
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
42
|
+
},
|
|
43
|
+
truncated() {
|
|
44
|
+
return wasTruncated;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function formatCronOutputHead(text, truncated) {
|
|
49
|
+
return truncated ? `${text}\n[… output truncated at ${CRON_OUTPUT_HEAD_BYTES} bytes]` : text;
|
|
50
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// src/daemon/cron/closed.ts — settling one run that ended: the record of a CLOSED run and the two ways it settles (observed exit,
|
|
2
|
+
// or a launch that never produced a child). Shared by the local executor (cron-run.ts) and the machine dispatcher (machine-fire.ts).
|
|
3
|
+
import { CRON_OUTPUT_HEAD_BYTES, EMPTY_STDOUT_SHA256 } from './capture.js';
|
|
4
|
+
import { decideHeldSettle, EXIT_HELD, HELD_DELIVERED } from './held.js';
|
|
5
|
+
import { settleRun } from './settle.js';
|
|
6
|
+
/** Settle one closed child: choose the outcome (replaced short-circuit, owed
|
|
7
|
+
* gate, or the full disposition), then hand it to the one settle tail. */
|
|
8
|
+
export async function settleClosedRun(c, run) {
|
|
9
|
+
const { runId, outOfBand, startedAtIso, finishedAtMs, code, timedOut, processError } = run;
|
|
10
|
+
// The owed-gate branch (exit 75): a peer of the wasReplaced short-circuit —
|
|
11
|
+
// skip disposition entirely (no delivery, no escalation, no pause, no
|
|
12
|
+
// on-change hash, no one-shot consumption) and settle the row's held state
|
|
13
|
+
// with the lease release instead. The exclusions are deliberate: a manual
|
|
14
|
+
// `cron run` must not change scheduling state; a timeout-killed or
|
|
15
|
+
// launch-failed run is a real failure even if a stray 75 surfaces; a replaced
|
|
16
|
+
// or self-canceled run's existing short-circuits win.
|
|
17
|
+
const heldDeferred = !outOfBand &&
|
|
18
|
+
!timedOut &&
|
|
19
|
+
processError == null &&
|
|
20
|
+
code === EXIT_HELD &&
|
|
21
|
+
!run.wasReplaced &&
|
|
22
|
+
!run.wasSelfCanceled;
|
|
23
|
+
let outcome;
|
|
24
|
+
let lease;
|
|
25
|
+
if (run.wasReplaced) {
|
|
26
|
+
// Record it, no disposition, no escalation, and leave `held` untouched
|
|
27
|
+
// (the gate is still unresolved).
|
|
28
|
+
outcome = { kind: 'stated', delivered: 'replaced (overlap=replace)' };
|
|
29
|
+
lease = 'release';
|
|
30
|
+
}
|
|
31
|
+
else if (heldDeferred) {
|
|
32
|
+
// The occurrence is NOT spent — even a one-shot is retained (like a paused
|
|
33
|
+
// escalated one-shot is). Park/re-due and the lease release are one write.
|
|
34
|
+
// A row canceled mid-run has nothing to settle.
|
|
35
|
+
outcome = { kind: 'stated', delivered: HELD_DELIVERED };
|
|
36
|
+
lease = await decideHeldSettle(c, startedAtIso, finishedAtMs) ?? 'release';
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
outcome = {
|
|
40
|
+
kind: 'disposed',
|
|
41
|
+
ctx: {
|
|
42
|
+
runId,
|
|
43
|
+
startedAtIso,
|
|
44
|
+
exitCode: timedOut ? -1 : code,
|
|
45
|
+
timedOut,
|
|
46
|
+
runTimeoutS: c.run_timeout_s,
|
|
47
|
+
processErrorMessage: processError != null ? processError.message : null,
|
|
48
|
+
stdoutHead: run.stdoutHead,
|
|
49
|
+
stdoutSha256: run.stdoutSha256,
|
|
50
|
+
stderrHead: run.stderrHead,
|
|
51
|
+
},
|
|
52
|
+
selfCanceled: run.wasSelfCanceled,
|
|
53
|
+
};
|
|
54
|
+
// An ordinary scheduled disposition settlement resolves the gate, so it
|
|
55
|
+
// unparks a held row; an out-of-band run leaves `held` untouched.
|
|
56
|
+
lease = outOfBand ? 'release' : { kind: 'clear' };
|
|
57
|
+
}
|
|
58
|
+
return settleRun(c, {
|
|
59
|
+
outOfBand,
|
|
60
|
+
outcome,
|
|
61
|
+
record: {
|
|
62
|
+
runId,
|
|
63
|
+
startedAtIso,
|
|
64
|
+
finishedAtMs,
|
|
65
|
+
durationMs: finishedAtMs - run.startedAtMs,
|
|
66
|
+
exitCode: timedOut ? -1 : code,
|
|
67
|
+
stdoutHead: run.stdoutHead === '' ? null : run.stdoutHead,
|
|
68
|
+
stderrHead: processError != null
|
|
69
|
+
? `run process error: ${processError.message}`.slice(0, CRON_OUTPUT_HEAD_BYTES)
|
|
70
|
+
: run.stderrHead === ''
|
|
71
|
+
? null
|
|
72
|
+
: run.stderrHead,
|
|
73
|
+
},
|
|
74
|
+
lease,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** Settle a claimed run that failed before its launched child could be observed. */
|
|
78
|
+
export function settleUnspawnedRun(c, run, lead, err) {
|
|
79
|
+
const finishedAtMs = Date.now();
|
|
80
|
+
const stderrHead = `${lead}: ${err.message}`.slice(0, CRON_OUTPUT_HEAD_BYTES);
|
|
81
|
+
return settleRun(c, {
|
|
82
|
+
outOfBand: run.outOfBand,
|
|
83
|
+
outcome: {
|
|
84
|
+
kind: 'disposed',
|
|
85
|
+
ctx: {
|
|
86
|
+
runId: run.runId,
|
|
87
|
+
startedAtIso: run.startedAtIso,
|
|
88
|
+
exitCode: null,
|
|
89
|
+
timedOut: false,
|
|
90
|
+
runTimeoutS: c.run_timeout_s,
|
|
91
|
+
processErrorMessage: err.message,
|
|
92
|
+
stdoutHead: '',
|
|
93
|
+
stdoutSha256: EMPTY_STDOUT_SHA256,
|
|
94
|
+
stderrHead,
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
record: {
|
|
98
|
+
runId: run.runId,
|
|
99
|
+
startedAtIso: run.startedAtIso,
|
|
100
|
+
finishedAtMs,
|
|
101
|
+
durationMs: finishedAtMs - run.startedAtMs,
|
|
102
|
+
exitCode: null,
|
|
103
|
+
stdoutHead: null,
|
|
104
|
+
stderrHead,
|
|
105
|
+
},
|
|
106
|
+
lease: 'release',
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { getCron, setCronLastOutputHash } from '../../core/canvas/crons.js';
|
|
2
|
+
import { escalateFailure, failureSummary } from './escalation.js';
|
|
3
|
+
import { resolveCronSink } from './sinks.js';
|
|
4
|
+
export async function disposeSettledRun(c, ctx, outOfBand, selfCanceled = false) {
|
|
5
|
+
const disposition = await disposeRun(c, ctx, outOfBand, selfCanceled);
|
|
6
|
+
// The on-change baseline moves only once the output was actually handled; a refused
|
|
7
|
+
// birth leaves the previous baseline so the same output delivers when consent returns.
|
|
8
|
+
// `cron run` compares but never rewrites the scheduled baseline.
|
|
9
|
+
if (!disposition.refused && !outOfBand && c.on_output === 'on-change') {
|
|
10
|
+
const fresh = await getCron(c.cron_id);
|
|
11
|
+
if (fresh !== null && fresh.on_output === 'on-change')
|
|
12
|
+
await setCronLastOutputHash(c.cron_id, ctx.stdoutSha256);
|
|
13
|
+
}
|
|
14
|
+
return disposition;
|
|
15
|
+
}
|
|
16
|
+
async function disposeRun(c, ctx, outOfBand, selfCanceled = false) {
|
|
17
|
+
const prefix = outOfBand ? 'out-of-band: ' : '';
|
|
18
|
+
// A self-cancel still delivers its already-produced output; an external cancellation does not.
|
|
19
|
+
const fresh = await getCron(c.cron_id);
|
|
20
|
+
if (fresh === null && !selfCanceled)
|
|
21
|
+
return { delivered: `${prefix}cron canceled mid-run — nothing delivered`, paused: false };
|
|
22
|
+
const effective = fresh ?? c;
|
|
23
|
+
const failed = ctx.timedOut || ctx.processErrorMessage !== null || ctx.exitCode !== 0;
|
|
24
|
+
let changed = true;
|
|
25
|
+
if (effective.on_output === 'on-change')
|
|
26
|
+
changed = effective.last_output_hash !== ctx.stdoutSha256;
|
|
27
|
+
if (failed) {
|
|
28
|
+
if (effective.on_output === 'silent')
|
|
29
|
+
return { delivered: `${prefix}silent`, paused: false };
|
|
30
|
+
if (outOfBand)
|
|
31
|
+
return { delivered: `out-of-band: ${failureSummary(ctx, null)} — not escalated`, paused: false };
|
|
32
|
+
return { delivered: await escalateFailure(effective, ctx, null), paused: true };
|
|
33
|
+
}
|
|
34
|
+
switch (effective.on_output) {
|
|
35
|
+
case 'silent':
|
|
36
|
+
return { delivered: `${prefix}silent`, paused: false };
|
|
37
|
+
case 'on-failure':
|
|
38
|
+
return { delivered: `${prefix}ok — nothing to deliver (on-failure)`, paused: false };
|
|
39
|
+
case 'on-change':
|
|
40
|
+
if (!changed)
|
|
41
|
+
return { delivered: `${prefix}unchanged — not delivered (on-change)`, paused: false };
|
|
42
|
+
return resolveOrEscalate(effective, ctx, outOfBand, prefix);
|
|
43
|
+
case 'always':
|
|
44
|
+
return resolveOrEscalate(effective, ctx, outOfBand, prefix);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function resolveOrEscalate(c, ctx, outOfBand, prefix) {
|
|
48
|
+
if (ctx.stdoutHead.trim() === '') {
|
|
49
|
+
return { delivered: `${prefix}empty stdout — nothing delivered`, paused: false };
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const obligation = await resolveCronSink(c, ctx.runId, ctx.stdoutHead);
|
|
53
|
+
return obligation.kind === 'none'
|
|
54
|
+
? { delivered: `${prefix}${obligation.delivered}`, paused: false, ...(obligation.refused === true ? { refused: true } : {}) }
|
|
55
|
+
: { delivered: '', paused: false, obligation };
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
const why = `delivery failed: ${err.message}`;
|
|
59
|
+
if (outOfBand)
|
|
60
|
+
return { delivered: `out-of-band: ${why} — not escalated`, paused: false };
|
|
61
|
+
return { delivered: await escalateFailure(c, ctx, why), paused: true };
|
|
62
|
+
}
|
|
63
|
+
}
|