@north-light/cli 0.3.669 → 0.3.671
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +2 -0
- package/dist/api/dto/execution-start.d.ts +7 -0
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/node/bash.js +3 -3
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/canvas/canvas.d.ts +10 -1
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/canvas/schema-pg/022-create-request-lease.sql +5 -0
- package/dist/core/canvas/schema-pg/023-machine-calls-job-stop.sql +7 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.d.ts +4 -0
- package/dist/core/runtime/broker/bash-job-launch.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/runner.js +2 -2
- 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/core/runtime/runner/types.d.ts +2 -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/messages.js +2 -2
- 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/remote-wake.js +2 -1
- 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/dist/pi-extensions/canvas-tool-guide.d.ts +3 -1
- package/dist/pi-extensions/canvas-tool-guide.js +4 -4
- 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/broker/bash-job-launch.js +4 -5
- package/packages/crouter-api/dist/core/runtime/revive-all.js +108 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +13 -2
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +140 -0
- package/packages/crouter-api/dist/daemon/cron/capture.js +50 -0
- package/packages/crouter-api/dist/daemon/cron/closed.js +108 -0
- package/packages/crouter-api/dist/daemon/cron/disposition.js +63 -0
- package/packages/crouter-api/dist/daemon/cron/ended.js +80 -0
- package/packages/crouter-api/dist/daemon/cron/escalation.js +136 -0
- package/packages/crouter-api/dist/daemon/cron/held.js +20 -0
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +177 -0
- package/packages/crouter-api/dist/daemon/cron/narrowed.js +34 -0
- package/packages/crouter-api/dist/daemon/cron/recurrence.js +38 -0
- package/packages/crouter-api/dist/daemon/cron/run-token.js +37 -0
- package/packages/crouter-api/dist/daemon/cron/settle.js +78 -0
- package/packages/crouter-api/dist/daemon/cron/sinks.js +70 -0
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-bootstrap.sh +4 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// src/daemon/cron/ended.ts — a cron that ends without its node sink having asked
|
|
2
|
+
// for it tells that node. A node that ended its turn waiting on a cron's
|
|
3
|
+
// delivery has no other wake source; a row that vanished silently strands it.
|
|
4
|
+
import { getNode } from '../../core/canvas/canvas.js';
|
|
5
|
+
import { withCanvasWrite } from '../../core/canvas/db.js';
|
|
6
|
+
import { CRON_RUN_RING, cancelCron, listCronRuns, parseCronSink } from '../../core/canvas/crons.js';
|
|
7
|
+
import { hasNoNaturalCycle } from '../../core/runtime/revive-all.js';
|
|
8
|
+
import { isParked } from '../../core/runtime/lifecycle.js';
|
|
9
|
+
import { enqueueNodeMail } from '../../core/feed/messages.js';
|
|
10
|
+
import { cadenceDisplay } from '../../core/wake.js';
|
|
11
|
+
import { machineEnvironmentOfCron, queueCronCancel } from './machine-fire.js';
|
|
12
|
+
const SENT = /^delivered: /;
|
|
13
|
+
const EMPTY_OK = (r) => r.exit_code === 0 && (r.stdout_head ?? '') === '';
|
|
14
|
+
/** Real runs only: the overlap pass writes a marker row that is not a run. */
|
|
15
|
+
function realRuns(runs) {
|
|
16
|
+
return runs.filter((r) => r.exit_code !== null || !(r.delivered ?? '').startsWith('skipped'));
|
|
17
|
+
}
|
|
18
|
+
function endedMessage(c, end, runs) {
|
|
19
|
+
const real = realRuns(runs);
|
|
20
|
+
// The run log keeps the last CRON_RUN_RING rows, so a full ring means the true count is unknown.
|
|
21
|
+
const full = runs.length >= CRON_RUN_RING;
|
|
22
|
+
const lastSent = real.find((r) => SENT.test(r.delivered ?? ''));
|
|
23
|
+
const cause = end.kind === 'expired'
|
|
24
|
+
? `expired at ${c.expires_at} and was deleted${c.held ? ' while held by exit 75; the pending occurrence never fired' : ''}`
|
|
25
|
+
: `was canceled by ${end.by} and deleted`;
|
|
26
|
+
const lines = [
|
|
27
|
+
`Cron "${c.name}" (${c.cron_id}, ${c.recur != null ? cadenceDisplay(c.recur) : 'one-shot'}) ${cause}. It was delivering to you, so nothing will wake you from it any more.`,
|
|
28
|
+
'',
|
|
29
|
+
`- runs made: ${full ? `at least ${real.length} (the run log keeps the last ${CRON_RUN_RING} entries)` : real.length}`,
|
|
30
|
+
lastSent !== undefined
|
|
31
|
+
? `- last delivery to you: ${lastSent.finished}`
|
|
32
|
+
: `- last delivery to you: ${full ? `none in its last ${real.length} runs` : 'never delivered'}`,
|
|
33
|
+
];
|
|
34
|
+
const last = real[0];
|
|
35
|
+
if (last !== undefined) {
|
|
36
|
+
const exit = last.exit_code === null ? 'no exit observed' : last.exit_code === -1 ? 'timed out' : `exit ${last.exit_code}`;
|
|
37
|
+
lines.push(`- last run: ${last.finished} — ${exit} — ${last.delivered ?? ''}`);
|
|
38
|
+
}
|
|
39
|
+
if (real.length > 0 && real.every(EMPTY_OK)) {
|
|
40
|
+
lines.push('', 'Every recorded run exited 0 with empty stdout, so the check may have been failing without saying so. A pipeline exits with its last stage, so `probe 2>&1 | grep … | jq …` hides a failed probe unless the command starts with `set -o pipefail`.');
|
|
41
|
+
}
|
|
42
|
+
return { label: `⏰ cron ${c.name} ${end.kind === 'expired' ? 'expired' : 'canceled'}`, body: lines.join('\n') };
|
|
43
|
+
}
|
|
44
|
+
/** enqueueNodeMail throws for a node whose run root is being deleted; a throw would roll back the delete and stall the whole due pass. */
|
|
45
|
+
async function runIsDeleting(node) {
|
|
46
|
+
return node.deleting_at != null || (node.run_id != null && (await getNode(node.run_id))?.deleting_at != null);
|
|
47
|
+
}
|
|
48
|
+
/** Can this node still take waking mail: not being deleted (nor its run root), and either has a cycle ahead or is parked. */
|
|
49
|
+
export async function canTakeMail(node) {
|
|
50
|
+
return !await runIsDeleting(node) && (!hasNoNaturalCycle(node) || isParked(node));
|
|
51
|
+
}
|
|
52
|
+
/** Delete `c` and, in the same write, mail its node sink the reason. Returns
|
|
53
|
+
* whether this call deleted the row. `end: null` deletes silently (the sink
|
|
54
|
+
* node canceled it itself). The notice is skipped when the sink is not a node
|
|
55
|
+
* that can still take mail: gone, deleting, or finalized with no wake ahead. */
|
|
56
|
+
export async function endCron(c, end, options) {
|
|
57
|
+
const sink = parseCronSink(c.sink);
|
|
58
|
+
const target = sink?.kind === 'node' ? await getNode(sink.node) : null;
|
|
59
|
+
const notify = end !== null && target !== null && await canTakeMail(target);
|
|
60
|
+
// A run on a machine is not a local process the delete can signal: owe the machine a cancel of that run id. It is delivered when the link is up
|
|
61
|
+
// (at once, or on reconnect), including for a `cron.run` the machine never received.
|
|
62
|
+
if (c.run_state === 'running' && c.run_execution_id !== null && options?.preserveRunningProcess !== true) {
|
|
63
|
+
const machine = await machineEnvironmentOfCron(c);
|
|
64
|
+
if (machine !== null)
|
|
65
|
+
await queueCronCancel(machine, c.run_execution_id);
|
|
66
|
+
}
|
|
67
|
+
return await withCanvasWrite(async () => {
|
|
68
|
+
const runs = notify ? await listCronRuns(c.cron_id) : [];
|
|
69
|
+
if (!await cancelCron(c.cron_id, options))
|
|
70
|
+
return false;
|
|
71
|
+
if (notify) {
|
|
72
|
+
const { label, body } = endedMessage(c, end, runs);
|
|
73
|
+
await enqueueNodeMail(target.node_id, {
|
|
74
|
+
kind: 'message', label, senderNodeId: null, bodyJson: { body }, urgency: 'normal', wake: 1,
|
|
75
|
+
idempotencyKey: `cron-ended:${c.cron_id}`,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// src/daemon/cron/escalation.ts — the cron failure path: pause the row and
|
|
2
|
+
// spawn a terminal node holding everything it needs to deal with the failure.
|
|
3
|
+
// Pausing IS the dedup — a paused row is never due, so nothing refires while
|
|
4
|
+
// the escalation node works.
|
|
5
|
+
import { getNode } from '../../core/canvas/canvas.js';
|
|
6
|
+
import { nodeAgentDir } from '../../core/canvas/node-agent-paths.js';
|
|
7
|
+
import { newNodeId } from '../../core/runtime/nodes.js';
|
|
8
|
+
import { fullName } from '../../core/canvas/labels.js';
|
|
9
|
+
import { listCronRuns, setCronState } from '../../core/canvas/crons.js';
|
|
10
|
+
import { emitEvent } from '../../core/events/emit.js';
|
|
11
|
+
import { spawnChild } from '../../core/runtime/spawn.js';
|
|
12
|
+
import { cronWakeOrigin } from '../../core/runtime/bearings.js';
|
|
13
|
+
import { cadenceDisplay } from '../../core/wake.js';
|
|
14
|
+
import { cronBirthPlacement, cronBirthPrincipalOf, resolveLiveProfileOrRoot } from './armed-context.js';
|
|
15
|
+
import { checkCronBirth } from './authority.js';
|
|
16
|
+
export function failureSummary(ctx, deliveryFailure) {
|
|
17
|
+
if (deliveryFailure !== null)
|
|
18
|
+
return deliveryFailure;
|
|
19
|
+
if (ctx.timedOut)
|
|
20
|
+
return `run timed out after ${ctx.runTimeoutS}s (killed; recorded exit -1)`;
|
|
21
|
+
if (ctx.processErrorMessage !== null)
|
|
22
|
+
return `run process error: ${ctx.processErrorMessage}`;
|
|
23
|
+
return `command exited ${ctx.exitCode ?? '(no exit observed)'}`;
|
|
24
|
+
}
|
|
25
|
+
/** The escalation node's kickoff: the cron's identity/config, this failure,
|
|
26
|
+
* the run-log ring, the creating-node reference, and a mandate that names its
|
|
27
|
+
* actual options (resume after verifying / cancel / ask the human). */
|
|
28
|
+
async function buildEscalationKickoff(c, ctx, deliveryFailure) {
|
|
29
|
+
const creator = c.created_by != null ? await getNode(c.created_by) : null;
|
|
30
|
+
const creatorLine = c.created_by == null
|
|
31
|
+
? 'created by: (no creating node recorded)'
|
|
32
|
+
: creator !== null
|
|
33
|
+
? `created by: node ${c.created_by} ("${fullName(creator)}") — still on the canvas; consider telling it what happened`
|
|
34
|
+
: `created by: node ${c.created_by} (now gone)`;
|
|
35
|
+
const schedule = c.recur != null ? `every ${cadenceDisplay(c.recur)}` : `one-shot at ${c.fire_at}`;
|
|
36
|
+
const priorRuns = (await listCronRuns(c.cron_id))
|
|
37
|
+
.slice(0, 10)
|
|
38
|
+
.map((r) => {
|
|
39
|
+
const exit = r.exit_code === null ? 'no exit' : `exit ${r.exit_code}`;
|
|
40
|
+
const head = (r.stderr_head ?? r.stdout_head ?? '').split('\n')[0]?.slice(0, 120) ?? '';
|
|
41
|
+
return `- ${r.started} — ${exit}, ${r.duration_ms}ms — ${r.delivered ?? ''}${head !== '' ? ` — ${head}` : ''}`;
|
|
42
|
+
});
|
|
43
|
+
return [
|
|
44
|
+
`A scheduled cron FAILED and has paused itself. You were spawned to deal with it.`,
|
|
45
|
+
'',
|
|
46
|
+
`- cron: "${c.name}" (${c.cron_id})`,
|
|
47
|
+
`- schedule: ${schedule}${c.tz != null ? ` (tz ${c.tz})` : ''}`,
|
|
48
|
+
`- context: cwd ${c.cwd}${c.profile != null ? `, profile ${c.profile}` : ''}`,
|
|
49
|
+
`- ${creatorLine}`,
|
|
50
|
+
`- this failure: ${failureSummary(ctx, deliveryFailure)}`,
|
|
51
|
+
'',
|
|
52
|
+
'## The command',
|
|
53
|
+
'',
|
|
54
|
+
'```bash',
|
|
55
|
+
c.command,
|
|
56
|
+
'```',
|
|
57
|
+
'',
|
|
58
|
+
'## This run',
|
|
59
|
+
'',
|
|
60
|
+
`- exit: ${ctx.timedOut ? '-1 (timeout)' : String(ctx.exitCode)}`,
|
|
61
|
+
`- stdout (head): ${ctx.stdoutHead === '' ? '(empty)' : ''}`,
|
|
62
|
+
...(ctx.stdoutHead !== '' ? ['```', ctx.stdoutHead, '```'] : []),
|
|
63
|
+
`- stderr (head): ${ctx.stderrHead === '' ? '(empty)' : ''}`,
|
|
64
|
+
...(ctx.stderrHead !== '' ? ['```', ctx.stderrHead, '```'] : []),
|
|
65
|
+
'',
|
|
66
|
+
'## Recent runs (most recent first, this failure not yet recorded)',
|
|
67
|
+
'',
|
|
68
|
+
...(priorRuns.length > 0 ? priorRuns : ['(no prior runs recorded)']),
|
|
69
|
+
'',
|
|
70
|
+
'## Your mandate',
|
|
71
|
+
'',
|
|
72
|
+
`Diagnose why it failed and decide what to do:`,
|
|
73
|
+
`- Transient or fixable: fix the environment/command context, verify with \`crtr cron run ${c.cron_id}\` (fires now, out of band, shows you the result), then \`crtr cron resume ${c.cron_id}\` to re-arm it.`,
|
|
74
|
+
`- Obsolete: \`crtr cron cancel ${c.cron_id}\`.`,
|
|
75
|
+
`- The user's call (or the fix needs a change you cannot make): \`crtr human send\`.`,
|
|
76
|
+
'',
|
|
77
|
+
'The cron stays paused until someone resumes it — nothing refires while you work.',
|
|
78
|
+
].join('\n');
|
|
79
|
+
}
|
|
80
|
+
/** Pause the cron and spawn the escalation node in the cron's originating
|
|
81
|
+
* profile (root fallback). Returns the run-log `delivered` string. Never
|
|
82
|
+
* throws: an escalation spawn failure is recorded and logged, the pause
|
|
83
|
+
* stands (the row must not keep refiring a broken command). */
|
|
84
|
+
export async function escalateFailure(c, ctx, deliveryFailure) {
|
|
85
|
+
await setCronState(c.cron_id, 'paused');
|
|
86
|
+
try {
|
|
87
|
+
// The escalation node is a birth of the cron's grant like any other: with the grant gone or
|
|
88
|
+
// narrowed there is nothing it may start, so the cron stays paused and says so.
|
|
89
|
+
const principal = cronBirthPrincipalOf(c);
|
|
90
|
+
const authority = await checkCronBirth(principal, { kind: 'general', cwd: c.cwd, profile: resolveLiveProfileOrRoot(c) });
|
|
91
|
+
if (!authority.allowed) {
|
|
92
|
+
emitEvent({ level: 'warn', event: 'cron.birth.refused', fields: { cron_id: c.cron_id, grant_id: c.grant_id, reason: authority.reason, stage: 'escalation' } });
|
|
93
|
+
return `failure: cron paused; no escalation node (refused: ${authority.reason})`;
|
|
94
|
+
}
|
|
95
|
+
const nodeId = await newNodeId();
|
|
96
|
+
const placement = await cronBirthPlacement({ ...principal, scopes: authority.scopes }, nodeId);
|
|
97
|
+
const res = await spawnChild({
|
|
98
|
+
nodeId, kind: 'general',
|
|
99
|
+
isolated: c.isolated,
|
|
100
|
+
cwd: c.isolated ? await nodeAgentDir(nodeId, c.grantee) : c.cwd,
|
|
101
|
+
prompt: await buildEscalationKickoff(c, ctx, deliveryFailure),
|
|
102
|
+
// The spec's word is TERMINAL: a node that deals with this failure and
|
|
103
|
+
// reaps. With no compatible creator it is a terminal root run of the cron's grant.
|
|
104
|
+
...placement,
|
|
105
|
+
readiness: 'launch',
|
|
106
|
+
profile: resolveLiveProfileOrRoot(c),
|
|
107
|
+
wakeOrigin: await cronWakeOrigin(c, 'node_birth'),
|
|
108
|
+
});
|
|
109
|
+
emitEvent({
|
|
110
|
+
level: 'info',
|
|
111
|
+
event: 'cron.failure.escalated',
|
|
112
|
+
fields: { cron_id: c.cron_id, name: c.name, escalation_node: res.node.node_id },
|
|
113
|
+
});
|
|
114
|
+
return `failure: cron paused, escalation node ${res.node.node_id} spawned`;
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
emitEvent({
|
|
118
|
+
level: 'error',
|
|
119
|
+
event: 'cron.escalation.spawn_failed',
|
|
120
|
+
error: err,
|
|
121
|
+
fields: { cron_id: c.cron_id, name: c.name },
|
|
122
|
+
});
|
|
123
|
+
return `failure: cron paused; escalation spawn failed: ${err.message}`;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** The delivery-failure line an escalated crashed ONE-SHOT carries: its side
|
|
127
|
+
* effects may already have landed in full, so a human/agent decides whether to
|
|
128
|
+
* redo it rather than the daemon re-firing it. */
|
|
129
|
+
export function crashedOneShotSummary(why) {
|
|
130
|
+
return [
|
|
131
|
+
`${why}.`,
|
|
132
|
+
'This is a ONE-SHOT, so it has been PAUSED rather than released: its side effects may have completed in full,',
|
|
133
|
+
'and re-firing would enact them a second time. Determine whether the work actually landed, then either',
|
|
134
|
+
'`crtr cron run` it to redo it deliberately, or `crtr cron cancel` it.',
|
|
135
|
+
].join(' ');
|
|
136
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { getCron } from '../../core/canvas/crons.js';
|
|
2
|
+
// Exit 75 parks an owed occurrence; the daemon honors the gate but does not implement it.
|
|
3
|
+
export const EXIT_HELD = 75;
|
|
4
|
+
export const HELD_DELIVERED = 'deferred (exit 75) — held for poke';
|
|
5
|
+
// A held one-shot without expiry is poke-only; leaving it past due would re-fire every tick.
|
|
6
|
+
const HELD_ONE_SHOT_FAR_FUTURE = '9999-12-31T23:59:59.999Z';
|
|
7
|
+
// Re-read `last_poke_at`: a poke can land while the gate check runs.
|
|
8
|
+
export async function decideHeldSettle(c, startedAtIso, finishedAtMs) {
|
|
9
|
+
const fresh = await getCron(c.cron_id);
|
|
10
|
+
if (fresh === null)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (fresh.state === 'active' && fresh.last_poke_at !== null && startedAtIso < fresh.last_poke_at) {
|
|
13
|
+
// A mid-run poke cannot unpark a lease, so re-due an active row; paused rows must remain parked.
|
|
14
|
+
return { kind: 'redue', nowIso: new Date(finishedAtMs).toISOString() };
|
|
15
|
+
}
|
|
16
|
+
if (c.recur != null) {
|
|
17
|
+
return { kind: 'park' };
|
|
18
|
+
}
|
|
19
|
+
return { kind: 'park', fireAt: fresh.expires_at ?? HELD_ONE_SHOT_FAR_FUTURE };
|
|
20
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// src/daemon/cron/machine-fire.ts — the control plane's side of a cron whose profile's environment is a machine (design-import I13).
|
|
2
|
+
// On a cloud role `startCron` sends such a cron to the machine as a leased `cron.run` call instead of spawning it here.
|
|
3
|
+
//
|
|
4
|
+
// Exactly once: the cron run id (`CRTR_RUN_ID`) is minted once per fire and every send of that fire carries it. The Mac records the id
|
|
5
|
+
// before it spawns (`machine-exec.ts`), so a send that follows a dropped link returns the first send's result instead of running the
|
|
6
|
+
// command again. A scheduled fire whose machine has no live link at its due time is not claimed at all and stays due. A fire that was
|
|
7
|
+
// claimed stays owed under its run id across an outage of any length: it is sent again until the machine answers, and a control plane
|
|
8
|
+
// that crashed after claiming picks the same run id up from the cron row (`resumeMachineFire`) instead of calling the run crashed.
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
11
|
+
import { openDb } from '../../core/canvas/db.js';
|
|
12
|
+
import { isCloudRole } from '../../core/canvas/person.js';
|
|
13
|
+
import { withCanvasWrite } from '../../core/canvas/db.js';
|
|
14
|
+
import { getNode } from '../../core/canvas/canvas.js';
|
|
15
|
+
import { callMachine } from '../../core/runtime/runner/machine/call.js';
|
|
16
|
+
import { machineEnvironmentOfNode } from '../../core/runtime/runner/machine/runner.js';
|
|
17
|
+
import { machineEnvironmentOfProfile } from '../../core/runtime/runner/machine/environment.js';
|
|
18
|
+
import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '../../core/runtime/runner/machine/ops.js';
|
|
19
|
+
import { environmentSecrets } from '../../core/secrets/environment-secrets.js';
|
|
20
|
+
import { profileInApp } from '../../core/secrets/environment-owner.js';
|
|
21
|
+
import { getCron } from '../../core/canvas/crons.js';
|
|
22
|
+
import { emitEvent } from '../../core/events/emit.js';
|
|
23
|
+
import { runTokenFor } from './run-token.js';
|
|
24
|
+
import { parseArmedEnv } from './armed-context.js';
|
|
25
|
+
import { CRON_OUTPUT_HEAD_BYTES } from './capture.js';
|
|
26
|
+
import { settleClosedRun, settleUnspawnedRun } from './closed.js';
|
|
27
|
+
import { clearLiveRun, registerLiveRun } from './live-runs.js';
|
|
28
|
+
import { advanceRecurrence } from './recurrence.js';
|
|
29
|
+
/** Seconds past the run's timeout a send waits for its answer. */
|
|
30
|
+
const ANSWER_SLACK_S = 15;
|
|
31
|
+
const RESEND_EVERY_MS = 2_000;
|
|
32
|
+
/** The machine environment a cron runs on, or null when it runs here (a Mac's own daemon, a cron with no profile, a Blaxel profile). */
|
|
33
|
+
export async function machineEnvironmentOfCron(c) {
|
|
34
|
+
if (!isCloudRole() || c.profile == null)
|
|
35
|
+
return null;
|
|
36
|
+
return await machineEnvironmentOfProfile(c.profile);
|
|
37
|
+
}
|
|
38
|
+
export async function machineLinkLive(environmentId) {
|
|
39
|
+
return (await (await openDb()).prepare('SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?').get(environmentId, new Date().toISOString())) !== undefined;
|
|
40
|
+
}
|
|
41
|
+
/** The env the machine adds to its own: the profile's and app's stored variables (never the deployment's, which are the control plane's), the armed `--env`, and the cron's ids. */
|
|
42
|
+
async function prepareRun(c, runId) {
|
|
43
|
+
const profile = c.profile;
|
|
44
|
+
const row = await (await openDb()).prepare('SELECT person FROM profiles WHERE id = ?').get(profile);
|
|
45
|
+
if (row === undefined)
|
|
46
|
+
throw new Error(`profile ${profile} of cron ${c.cron_id} is not in the control plane`);
|
|
47
|
+
const secrets = await environmentSecrets({ person: row.person, app: c.grantee, ownerProfile: profile, ownerProfileInApp: await profileInApp(profile, c.grantee), includeDeployment: false });
|
|
48
|
+
const isTerminal = c.grantee === 'app:terminal';
|
|
49
|
+
const anchor = c.anchor_node != null ? await getNode(c.anchor_node) : null;
|
|
50
|
+
const env = { ...secrets, ...parseArmedEnv(c.env_json), ...(isTerminal ? { CRTR_PROFILE_ID: profile } : {}), CRTR_CRON_ID: c.cron_id, CRTR_CRON_NAME: c.name, CRTR_RUN_ID: runId, CRTR_API_TOKEN: runTokenFor(runId),
|
|
51
|
+
...(c.anchor_node != null ? { CRTR_ANCHOR: c.anchor_node } : {}) };
|
|
52
|
+
return { env, grantee: c.grantee, profileId: profile, contextAnchor: anchor === null ? null : { node: anchor.node_id, grantee: anchor.grantee ?? c.grantee } };
|
|
53
|
+
}
|
|
54
|
+
/** One send of the fire: a leased `cron.run` call. Throws MachineOfflineError, MachineLostError or MachineCallFailedError. */
|
|
55
|
+
export async function sendCronRun(c, environmentId, runId, prepared) {
|
|
56
|
+
const waitMs = (c.run_timeout_s + ANSWER_SLACK_S) * 1000;
|
|
57
|
+
return await callMachine(environmentId, 'cron.run', { runId, cronId: c.cron_id, command: c.command, cwd: c.cwd, ...prepared, timeoutS: c.run_timeout_s,
|
|
58
|
+
leaseExpiresAt: new Date(Date.now() + waitMs).toISOString() }, { timeoutMs: waitMs });
|
|
59
|
+
}
|
|
60
|
+
/** Owe the machine a cancel of this run. The call is queued without a link check: an offline machine takes it when its link returns
|
|
61
|
+
* (the machine's own record of the run id decides whether that stops a running command or keeps a late `cron.run` from starting). */
|
|
62
|
+
export async function queueCronCancel(environmentId, runId) {
|
|
63
|
+
await queueMachineCall(environmentId, 'cron.cancel', { runId });
|
|
64
|
+
}
|
|
65
|
+
/** Owe the Mac a stop of this background job's process tree, queued the same way; a job the Mac no longer knows is a no-op there.
|
|
66
|
+
* Nothing is queued for a node that does not run on a machine environment. */
|
|
67
|
+
export async function queueJobStop(node, job) {
|
|
68
|
+
const environmentId = await machineEnvironmentOfNode(node);
|
|
69
|
+
if (environmentId !== null)
|
|
70
|
+
await queueMachineCall(environmentId, 'job.stop', { node, job });
|
|
71
|
+
}
|
|
72
|
+
async function queueMachineCall(environmentId, op, args) {
|
|
73
|
+
await withCanvasWrite(async (db) => {
|
|
74
|
+
await db.prepare('INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)')
|
|
75
|
+
.run(randomUUID(), environmentId, op, JSON.stringify(args), new Date().toISOString());
|
|
76
|
+
await db.prepare('SELECT pg_notify(?, ?)').get('crtr_signal', `machine:${environmentId}`);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** Fire `c` on its machine and settle the run. Resolves with the settled record, or null when the cron ended while the run was owed.
|
|
80
|
+
* The caller holds the cron's run lease and has already passed the authority and start checks; `admit` runs once the run is registered. */
|
|
81
|
+
export async function fireOnMachine(c, fire, admit) {
|
|
82
|
+
const { runId, outOfBand, startedAtIso, startedAtMs } = fire;
|
|
83
|
+
let prepared;
|
|
84
|
+
try {
|
|
85
|
+
if (c.isolated)
|
|
86
|
+
throw new Error('an isolated cron needs a root launcher, which a machine does not have');
|
|
87
|
+
prepared = await prepareRun(c, runId);
|
|
88
|
+
if (!outOfBand && c.recur != null) {
|
|
89
|
+
const recurrenceError = await advanceRecurrence(c, startedAtMs);
|
|
90
|
+
if (recurrenceError !== null)
|
|
91
|
+
throw recurrenceError;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
return await settleUnspawnedRun(c, { runId, outOfBand, startedAtIso, startedAtMs }, 'run could not be armed', err);
|
|
96
|
+
}
|
|
97
|
+
return await driveFire(c, fire, prepared, admit);
|
|
98
|
+
}
|
|
99
|
+
/** 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
|
|
100
|
+
* returns the stored result or joins the live run. A fresh id is never minted for this occurrence. Resolves with the settled record. */
|
|
101
|
+
export async function resumeMachineFire(c, environmentId) {
|
|
102
|
+
const runId = c.run_execution_id;
|
|
103
|
+
const startedAtIso = c.run_started_at;
|
|
104
|
+
const startedAtMs = Date.parse(startedAtIso);
|
|
105
|
+
const outOfBand = c.run_out_of_band;
|
|
106
|
+
const fire = { environmentId, runId, outOfBand, startedAtIso, startedAtMs };
|
|
107
|
+
let prepared;
|
|
108
|
+
try {
|
|
109
|
+
prepared = await prepareRun(c, runId);
|
|
110
|
+
// The crashed life may have died before it advanced the slot; advancing is idempotent (a recurrence already moved past this start stays).
|
|
111
|
+
if (!outOfBand && c.recur != null && Date.parse(c.fire_at) <= startedAtMs) {
|
|
112
|
+
const recurrenceError = await advanceRecurrence(c, startedAtMs);
|
|
113
|
+
if (recurrenceError !== null)
|
|
114
|
+
throw recurrenceError;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
return await settleUnspawnedRun(c, fire, 'run could not be armed', err);
|
|
119
|
+
}
|
|
120
|
+
return await driveFire(c, fire, prepared, () => undefined);
|
|
121
|
+
}
|
|
122
|
+
async function driveFire(c, fire, prepared, admit) {
|
|
123
|
+
const { environmentId, runId, outOfBand, startedAtIso, startedAtMs } = fire;
|
|
124
|
+
const live = { runId, replaced: false, selfCanceled: false, kill: () => {
|
|
125
|
+
void queueCronCancel(environmentId, runId).catch((error) => {
|
|
126
|
+
emitEvent({ level: 'error', event: 'cron.machine.cancel_failed', error, fields: { cron_id: c.cron_id, run_id: runId } });
|
|
127
|
+
});
|
|
128
|
+
} };
|
|
129
|
+
registerLiveRun(c.cron_id, live);
|
|
130
|
+
admit();
|
|
131
|
+
try {
|
|
132
|
+
let result = null;
|
|
133
|
+
let failure = null;
|
|
134
|
+
while (result === null && failure === null) {
|
|
135
|
+
try {
|
|
136
|
+
const answer = await sendCronRun(c, environmentId, runId, prepared);
|
|
137
|
+
if (answer.notStarted !== true) {
|
|
138
|
+
result = answer;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
emitEvent({ level: 'warn', event: 'cron.machine.resend', fields: { cron_id: c.cron_id, run_id: runId, why: answer.stderrHead } });
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error instanceof MachineCallFailedError) {
|
|
145
|
+
failure = error;
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
if (!(error instanceof MachineOfflineError) && !(error instanceof MachineLostError))
|
|
149
|
+
throw error;
|
|
150
|
+
// A manual run is answered at once: the person is waiting and nothing ran. A scheduled fire stays owed under its run id, for as long as it takes.
|
|
151
|
+
if (outOfBand && error instanceof MachineOfflineError) {
|
|
152
|
+
failure = error;
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
emitEvent({ level: 'warn', event: 'cron.machine.resend', fields: { cron_id: c.cron_id, run_id: runId, why: error.message } });
|
|
156
|
+
}
|
|
157
|
+
// The cron ended while this run was owed: its cancel is queued for the machine, and there is nothing left to settle against.
|
|
158
|
+
if (!live.selfCanceled && await getCron(c.cron_id) === null)
|
|
159
|
+
return null;
|
|
160
|
+
await delay(RESEND_EVERY_MS);
|
|
161
|
+
}
|
|
162
|
+
if (failure !== null)
|
|
163
|
+
return await settleUnspawnedRun(c, { runId, outOfBand, startedAtIso, startedAtMs }, 'run failed on the machine', failure);
|
|
164
|
+
const { exitCode, stdoutHead, stderrHead, durationMs, stdoutSha256 } = result;
|
|
165
|
+
const timedOut = exitCode === -1;
|
|
166
|
+
const processError = exitCode === null ? new Error((stderrHead ?? 'the machine reported no exit').slice(0, CRON_OUTPUT_HEAD_BYTES)) : null;
|
|
167
|
+
const wasReplaced = live.replaced;
|
|
168
|
+
const wasSelfCanceled = live.selfCanceled;
|
|
169
|
+
return await settleClosedRun(c, {
|
|
170
|
+
runId, outOfBand, startedAtIso, startedAtMs, finishedAtMs: startedAtMs + durationMs, code: timedOut ? null : exitCode, timedOut, processError,
|
|
171
|
+
stdoutHead: stdoutHead ?? '', stderrHead: stderrHead ?? '', stdoutSha256, wasReplaced, wasSelfCanceled,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
clearLiveRun(c.cron_id, runId);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// src/daemon/cron/narrowed.ts — a scheduled fire refused by the cron authority check that paused
|
|
2
|
+
// the cron. Whoever armed it is told, so the work does not stop silently. Scopes are never widened here.
|
|
3
|
+
import { getNode } from '../../core/canvas/canvas.js';
|
|
4
|
+
import { newNodeId } from '../../core/runtime/nodes.js';
|
|
5
|
+
import { resolveLiveProfileName } from './armed-context.js';
|
|
6
|
+
import { canTakeMail } from './ended.js';
|
|
7
|
+
/** The notice for a cron paused by a refused fire: mail to the node that armed it while that node can still take mail,
|
|
8
|
+
* otherwise a human ticket. `message` is the refusal. */
|
|
9
|
+
export async function narrowedNotice(c, message) {
|
|
10
|
+
const creator = c.created_by === null ? null : await getNode(c.created_by);
|
|
11
|
+
const body = [
|
|
12
|
+
`Cron "${c.name}" (${c.cron_id}) was paused: ${message}.`,
|
|
13
|
+
'',
|
|
14
|
+
'Its scheduled fire was refused by the authority check, so it did not run. The cron will not fire again until you act. Nothing was widened.',
|
|
15
|
+
'',
|
|
16
|
+
`- To keep it: fix what the refusal names (for a lost scope, restore it on the grant), then \`crtr cron resume ${c.cron_id}\`.`,
|
|
17
|
+
`- To drop it: \`crtr cron cancel ${c.cron_id}\`, and arm the cron again if the work still matters.`,
|
|
18
|
+
].join('\n');
|
|
19
|
+
const label = `⏰ cron ${c.name} paused: fire refused`;
|
|
20
|
+
// A waking mail to the node a cancel-on-wake cron is anchored to would delete this cron, so that one goes to a human.
|
|
21
|
+
const wakeWouldDelete = c.cancel_on_wake && c.anchor_node === creator?.node_id;
|
|
22
|
+
if (creator !== null && !wakeWouldDelete && await canTakeMail(creator)) {
|
|
23
|
+
return { kind: 'node', destinationNodeId: creator.node_id, senderNodeId: null, label, stdout: body, urgency: 'urgent' };
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
kind: 'action',
|
|
27
|
+
adapter: {
|
|
28
|
+
adapter: 'cron_human', cronId: c.cron_id, requestId: await newNodeId(), title: label,
|
|
29
|
+
summary: `A scheduled cron was paused because its fire was refused.`, sessionName: `cron ${c.name} (${c.cron_id})`,
|
|
30
|
+
profileName: resolveLiveProfileName(c) ?? null,
|
|
31
|
+
},
|
|
32
|
+
bodyJson: { stdout: body },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// src/daemon/cron/recurrence.ts — the crash-safe step before a scheduled run: a recurrence moves to its next slot.
|
|
2
|
+
import { advanceCron, setCronState } from '../../core/canvas/crons.js';
|
|
3
|
+
import { emitEvent } from '../../core/events/emit.js';
|
|
4
|
+
import { nextSlotAfter } from '../../core/wake.js';
|
|
5
|
+
/** Settle the schedule BEFORE the run: a recurrence advances to its next slot
|
|
6
|
+
* now, so a crash mid-run never re-fires this slot (the lease guards the
|
|
7
|
+
* intra-life overlap; the advanced fire_at guards the crash window).
|
|
8
|
+
*
|
|
9
|
+
* Returns the process error to hand `close` when the recurrence cannot be
|
|
10
|
+
* parsed, else null. That row can never be scheduled again as written — but
|
|
11
|
+
* DELETING it would destroy the user's config AND its whole run history with
|
|
12
|
+
* no record and no escalation, the one outcome the spec has no vocabulary for.
|
|
13
|
+
* It takes the failure path instead, so the row PAUSES and an escalation node
|
|
14
|
+
* arrives holding the parse error. `fire_at` is deliberately left past-due: a
|
|
15
|
+
* paused row is not due, and once someone fixes the recurrence a `cron resume`
|
|
16
|
+
* fires immediately. */
|
|
17
|
+
export async function advanceRecurrence(c, startedAtMs) {
|
|
18
|
+
let nextFire;
|
|
19
|
+
try {
|
|
20
|
+
nextFire = nextSlotAfter(c.recur, new Date(startedAtMs));
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
emitEvent({
|
|
24
|
+
level: 'error',
|
|
25
|
+
event: 'cron.recur.unparseable',
|
|
26
|
+
error: err,
|
|
27
|
+
fields: { cron_id: c.cron_id, name: c.name, recur: c.recur },
|
|
28
|
+
});
|
|
29
|
+
// Pause HERE, not only via the escalation: `fire_at` was never advanced, so
|
|
30
|
+
// an on_output='silent' row (whose failure path never escalates and never
|
|
31
|
+
// pauses) would otherwise re-fire this unschedulable command on every
|
|
32
|
+
// single tick, forever.
|
|
33
|
+
await setCronState(c.cron_id, 'paused');
|
|
34
|
+
return new Error(`unparseable recurrence ${JSON.stringify(c.recur)}: ${err.message} — this cron cannot be rescheduled until its recurrence is fixed (\`crtr cron cancel\` and re-arm it), so it has been paused.`);
|
|
35
|
+
}
|
|
36
|
+
await advanceCron(c.cron_id, nextFire);
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/daemon/cron/run-token.ts — the bearer a machine cron's `crtr` calls carry (proposal-mac-cli-auth, option R1).
|
|
2
|
+
// `crtr_run_<run id>.<hex HMAC of the run id under the secrets key>`: derived, never stored, so a resend of the same fire carries the same
|
|
3
|
+
// token. The control plane accepts it only while the cron row names that run as running, and answers as the same `cron` principal
|
|
4
|
+
// `run-socket.ts` builds for a local run.
|
|
5
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import { openDb } from '../../core/canvas/db.js';
|
|
7
|
+
import { getCron } from '../../core/canvas/crons.js';
|
|
8
|
+
import { loadSecretsKey } from '../../core/secrets/key.js';
|
|
9
|
+
export const RUN_TOKEN_PREFIX = 'crtr_run_';
|
|
10
|
+
const mac = (runId) => createHmac('sha256', loadSecretsKey().key).update(`cron-run:${runId}`).digest('hex');
|
|
11
|
+
export const runTokenFor = (runId) => `${RUN_TOKEN_PREFIX}${runId}.${mac(runId)}`;
|
|
12
|
+
/** The run id a well-formed token with a valid MAC names, else null. */
|
|
13
|
+
export function runIdOfToken(token) {
|
|
14
|
+
if (!token.startsWith(RUN_TOKEN_PREFIX))
|
|
15
|
+
return null;
|
|
16
|
+
const body = token.slice(RUN_TOKEN_PREFIX.length);
|
|
17
|
+
const dot = body.lastIndexOf('.');
|
|
18
|
+
if (dot <= 0)
|
|
19
|
+
return null;
|
|
20
|
+
const runId = body.slice(0, dot);
|
|
21
|
+
const given = Buffer.from(body.slice(dot + 1));
|
|
22
|
+
const expected = Buffer.from(mac(runId));
|
|
23
|
+
return given.length === expected.length && timingSafeEqual(given, expected) ? runId : null;
|
|
24
|
+
}
|
|
25
|
+
/** The cron principal of the run `token` names, or null when the token is invalid or the run is no longer the cron's running one. */
|
|
26
|
+
export async function cronPrincipalForRunToken(token) {
|
|
27
|
+
const runId = runIdOfToken(token);
|
|
28
|
+
if (runId === null)
|
|
29
|
+
return null;
|
|
30
|
+
const row = await (await openDb()).prepare("SELECT cron_id FROM crons WHERE run_execution_id = ? AND run_state = 'running'").get(runId);
|
|
31
|
+
const c = row === undefined ? null : await getCron(row.cron_id);
|
|
32
|
+
if (c === null || c.run_execution_id !== runId || c.run_state !== 'running')
|
|
33
|
+
return null;
|
|
34
|
+
// `uid` -1: no local peer. It is read only by the per-execution socket's own peer check and by broker-class handlers.
|
|
35
|
+
return { class: 'cron', kind: 'cron', cron: c.cron_id, app: c.grantee, sub: c.sub, grant: c.grant_id, scopes: c.scopes, execution: runId, from_exec: c.armed_from_exec,
|
|
36
|
+
origin_run: c.origin_run_id, isolated: c.isolated, anchor: c.anchor_node, uid: -1 };
|
|
37
|
+
}
|