@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
|
@@ -44,7 +44,6 @@ export function reconnectShouldGiveUp(row) {
|
|
|
44
44
|
return row === null || (row.status === 'done' && row.final_report != null);
|
|
45
45
|
}
|
|
46
46
|
export class BrokerClient extends EventEmitter {
|
|
47
|
-
nodeId;
|
|
48
47
|
transport;
|
|
49
48
|
closeEmitted = false;
|
|
50
49
|
/** Tracks live connect↔close state so {@link request} can fail fast on a
|
|
@@ -61,22 +60,31 @@ export class BrokerClient extends EventEmitter {
|
|
|
61
60
|
* Resolved by the matching `data` frame / rejected by the matching `error`
|
|
62
61
|
* frame in {@link onFrame}, the request's timeout, or transport teardown. */
|
|
63
62
|
pending = new Map();
|
|
63
|
+
/** `nodeId` is undefined only for a viewer whose node is still being created: it holds no transport until {@link bindTransport}, so
|
|
64
|
+
* every send is a no-op and every request rejects until then. */
|
|
64
65
|
constructor(nodeId, options = {}) {
|
|
65
66
|
super();
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
67
|
+
const transport = options.transport ?? (nodeId === undefined ? undefined : new SocketTransport(nodeId));
|
|
68
|
+
if (transport !== undefined)
|
|
69
|
+
this.bindTransport(transport);
|
|
70
|
+
}
|
|
71
|
+
/** Wire the transport once the node it reaches is known. */
|
|
72
|
+
bindTransport(transport) {
|
|
73
|
+
if (this.transport !== undefined)
|
|
74
|
+
throw new Error('BrokerClient already has a transport');
|
|
75
|
+
this.transport = transport;
|
|
76
|
+
transport.on('connect', () => {
|
|
69
77
|
this.closeEmitted = false;
|
|
70
78
|
this.connected = true;
|
|
71
79
|
this.lastTransportError = undefined;
|
|
72
80
|
this.emit('connect');
|
|
73
81
|
});
|
|
74
|
-
|
|
75
|
-
|
|
82
|
+
transport.on('frame', (frame) => this.onFrame(frame));
|
|
83
|
+
transport.on('error', (err) => {
|
|
76
84
|
this.lastTransportError = err.message;
|
|
77
85
|
this.emitError(err);
|
|
78
86
|
});
|
|
79
|
-
|
|
87
|
+
transport.on('close', () => this.onClose());
|
|
80
88
|
}
|
|
81
89
|
/** Issue a correlated read-op and resolve with the broker's `data` reply (or
|
|
82
90
|
* reject on the correlated `error`, a timeout, or transport teardown). Mints
|
|
@@ -112,22 +120,24 @@ export class BrokerClient extends EventEmitter {
|
|
|
112
120
|
* {@link BrokerUnavailableError} when the target has no reachable broker)
|
|
113
121
|
* on failure. Idempotent guard is the caller's job — call once. */
|
|
114
122
|
connect() {
|
|
115
|
-
this.transport
|
|
123
|
+
this.transport?.connect();
|
|
116
124
|
}
|
|
117
125
|
/** Re-establish the connection after a broker exit (a yield→revive cycle),
|
|
118
126
|
* to the SAME target. Resolves on `connect` (caller re-sends `hello`);
|
|
119
127
|
* rejects on a retryable dial failure. */
|
|
120
128
|
redial(options) {
|
|
129
|
+
if (this.transport === undefined)
|
|
130
|
+
return Promise.reject(new Error('no node to redial yet'));
|
|
121
131
|
return this.transport.redial(options);
|
|
122
132
|
}
|
|
123
133
|
/** Encode + send one client→broker frame. No-op on a dead/absent
|
|
124
134
|
* connection; never throws. */
|
|
125
135
|
send(frame) {
|
|
126
|
-
this.transport
|
|
136
|
+
this.transport?.send(frame);
|
|
127
137
|
}
|
|
128
138
|
/** Detach: tear down the transport. `close` fires → the caller tears down. */
|
|
129
139
|
close() {
|
|
130
|
-
this.transport
|
|
140
|
+
this.transport?.destroy();
|
|
131
141
|
}
|
|
132
142
|
onFrame(frame) {
|
|
133
143
|
// Correlated replies (read-ops + dequeue) are consumed by the pending-by-id
|
|
@@ -21,10 +21,10 @@
|
|
|
21
21
|
// serve the daemon-owned run executor in src/daemon/cron-run.ts.
|
|
22
22
|
import { withCanvasWrite, openDb } from './db.js';
|
|
23
23
|
import { capturePidIdentities, identitiesMatch, killProcessGroup } from './pid.js';
|
|
24
|
-
import { isProfilePaused } from '../profiles/manifest.js';
|
|
25
24
|
import { stopAppProcess } from '../spaces/process.js';
|
|
26
25
|
import { emitEvent } from '../events/emit.js';
|
|
27
26
|
import { personId } from './person.js';
|
|
27
|
+
import { deleteSandboxOfEndedNode } from '../runtime/runner/delete-sandboxes.js';
|
|
28
28
|
/** Ring bound for `cron_runs`: recordCronRun prunes each cron's history to
|
|
29
29
|
* its most recent this-many rows. */
|
|
30
30
|
export const CRON_RUN_RING = 20;
|
|
@@ -59,6 +59,8 @@ function cronFrom(r) {
|
|
|
59
59
|
expires_at: r['expires_at'] ?? null,
|
|
60
60
|
anchor_node: r['anchor_node'] ?? null,
|
|
61
61
|
cancel_on_wake: Number(r['cancel_on_wake']) !== 0,
|
|
62
|
+
deadline_body: r['deadline_body'] ?? null,
|
|
63
|
+
fires: Number(r['fires'] ?? 0),
|
|
62
64
|
cwd: r['cwd'],
|
|
63
65
|
env_json: r['env_json'] ?? null,
|
|
64
66
|
profile: r['profile'] ?? null,
|
|
@@ -198,9 +200,9 @@ async function insertCron(db, spec) {
|
|
|
198
200
|
await db.prepare(`INSERT INTO crons (
|
|
199
201
|
cron_id, name, created_by, grantee, sub, grant_id, scopes_json, origin_run_id, isolated, command, fire_at, recur, tz, expires_at,
|
|
200
202
|
anchor_node, cancel_on_wake, cwd, env_json, profile, scope,
|
|
201
|
-
run_timeout_s, overlap, on_output, sink, tier, created, updated, armed_from_exec
|
|
202
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
203
|
-
.run(spec.cron_id, spec.name, spec.created_by, spec.grantee ?? 'app:terminal', spec.sub ?? personId(), spec.grant_id ?? null, spec.scopes == null ? null : JSON.stringify(spec.scopes), spec.origin_run_id ?? null, spec.isolated ? 1 : 0, spec.command, spec.fire_at, spec.recur, spec.tz, spec.expires_at, spec.anchor_node, spec.cancel_on_wake ? 1 : 0, spec.cwd, spec.env_json, spec.profile, spec.scope, spec.run_timeout_s, spec.overlap, spec.on_output, spec.sink, spec.tier, now, now, spec.armed_from_exec ? 1 : 0);
|
|
203
|
+
run_timeout_s, overlap, on_output, sink, tier, created, updated, armed_from_exec, deadline_body
|
|
204
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
205
|
+
.run(spec.cron_id, spec.name, spec.created_by, spec.grantee ?? 'app:terminal', spec.sub ?? personId(), spec.grant_id ?? null, spec.scopes == null ? null : JSON.stringify(spec.scopes), spec.origin_run_id ?? null, spec.isolated ? 1 : 0, spec.command, spec.fire_at, spec.recur, spec.tz, spec.expires_at, spec.anchor_node, spec.cancel_on_wake ? 1 : 0, spec.cwd, spec.env_json, spec.profile, spec.scope, spec.run_timeout_s, spec.overlap, spec.on_output, spec.sink, spec.tier, now, now, spec.armed_from_exec ? 1 : 0, spec.deadline_body ?? null);
|
|
204
206
|
}
|
|
205
207
|
/** SELECT one cron by id. */
|
|
206
208
|
export async function getCron(cron_id) {
|
|
@@ -242,6 +244,8 @@ export async function cancelCron(cron_id, options) {
|
|
|
242
244
|
if (cron.run_state === 'running' && options?.preserveRunningProcess !== true)
|
|
243
245
|
killLeasedCronRun(cron);
|
|
244
246
|
await db.prepare('DELETE FROM crons WHERE cron_id = ?').run(cron_id);
|
|
247
|
+
if (cron.anchor_node !== null)
|
|
248
|
+
deleteSandboxOfEndedNode(cron.anchor_node);
|
|
245
249
|
return true;
|
|
246
250
|
});
|
|
247
251
|
}
|
|
@@ -294,11 +298,21 @@ export async function globalizeCronsForProfile(profileId) {
|
|
|
294
298
|
return ids;
|
|
295
299
|
});
|
|
296
300
|
}
|
|
301
|
+
/** A hosted cron ends after this many fires; no flag raises it (NL-1110). */
|
|
302
|
+
export const HOSTED_CRON_MAX_FIRES = 64;
|
|
303
|
+
/** Idle crons that have used all `max` fires; the due pass ends them whether paused or not (NL-1110). */
|
|
304
|
+
export async function cappedIdleCrons(max) {
|
|
305
|
+
return (await (await openDb()).prepare(`SELECT * FROM crons WHERE fires >= ? AND run_state = 'idle' ORDER BY cron_id`)
|
|
306
|
+
.all(max)).map(cronFrom);
|
|
307
|
+
}
|
|
297
308
|
/** DELETE one cron by id — one-shot consumption after its run settles.
|
|
298
309
|
* Returns whether a live row was removed, so a consumer racing an explicit
|
|
299
310
|
* cancel can no-op instead of double-settling. */
|
|
300
311
|
export async function consumeCron(cron_id) {
|
|
301
|
-
|
|
312
|
+
const gone = await (await openDb()).prepare('DELETE FROM crons WHERE cron_id = ? RETURNING anchor_node').get(cron_id);
|
|
313
|
+
if (gone !== undefined && gone.anchor_node !== null)
|
|
314
|
+
deleteSandboxOfEndedNode(gone.anchor_node);
|
|
315
|
+
return gone !== undefined;
|
|
302
316
|
}
|
|
303
317
|
/** UPDATE `state` (active|paused). Returns whether a row changed — pausing an
|
|
304
318
|
* already-paused cron (or a gone one) reports `false`. Pausing does NOT kill
|
|
@@ -376,7 +390,7 @@ export async function dueClockCrons(nowIso) {
|
|
|
376
390
|
return (await (await openDb()).prepare(`SELECT * FROM crons
|
|
377
391
|
WHERE state = 'active' AND run_state = 'idle' AND fire_at <= ?
|
|
378
392
|
ORDER BY fire_at, created, cron_id`)
|
|
379
|
-
.all(nowIso)).map(cronFrom)
|
|
393
|
+
.all(nowIso)).map(cronFrom);
|
|
380
394
|
}
|
|
381
395
|
/** Atomically acquire the idle run lease: flips `run_state` to 'running' and
|
|
382
396
|
* records lease/pid metadata, but ONLY if the row is still idle (the
|
|
@@ -390,12 +404,14 @@ export async function dueClockCrons(nowIso) {
|
|
|
390
404
|
*
|
|
391
405
|
* `outOfBand` stamps the lease as a `cron run` (manual verification) so the
|
|
392
406
|
* overlap pass leaves it alone — see `dueOverlapCrons`. */
|
|
393
|
-
export async function acquireCronRunLease(cron_id, leaseOwner, startedAtIso, outOfBand, executionId = null) {
|
|
407
|
+
export async function acquireCronRunLease(cron_id, leaseOwner, startedAtIso, outOfBand, executionId = null, maxFires = null) {
|
|
408
|
+
// With `maxFires`, the claim also counts the fire and is refused once the cron has used them all, in the same UPDATE.
|
|
409
|
+
const counted = maxFires !== null;
|
|
394
410
|
const res = await (await openDb()).prepare(`UPDATE crons
|
|
395
411
|
SET run_state = 'running', run_started_at = ?, run_pid = NULL, run_pid_identity = NULL,
|
|
396
|
-
run_lease_owner = ?, run_out_of_band = ?, run_execution_id = ?, updated = ?
|
|
397
|
-
WHERE cron_id = ? AND run_state = 'idle'`)
|
|
398
|
-
.run(startedAtIso, leaseOwner, outOfBand ? 1 : 0, executionId, new Date().toISOString(), cron_id);
|
|
412
|
+
run_lease_owner = ?, run_out_of_band = ?, run_execution_id = ?, updated = ?${counted ? ', fires = fires + 1' : ''}
|
|
413
|
+
WHERE cron_id = ? AND run_state = 'idle'${counted ? ' AND fires < ?' : ''}`)
|
|
414
|
+
.run(startedAtIso, leaseOwner, outOfBand ? 1 : 0, executionId, new Date().toISOString(), cron_id, ...(counted ? [maxFires] : []));
|
|
399
415
|
return Number(res.changes) > 0;
|
|
400
416
|
}
|
|
401
417
|
/** Attach the launcher's pid only to the run that claimed this lease. */
|
|
@@ -5,6 +5,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
5
5
|
import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
|
|
6
6
|
import { revokeNodeTokens } from './node-tokens.js';
|
|
7
7
|
import { clearPendingParkIn } from '../../daemon/park-pending.js';
|
|
8
|
+
import { deleteSandboxOfEndedNode } from '../runtime/runner/delete-sandboxes.js';
|
|
8
9
|
function now() {
|
|
9
10
|
return new Date().toISOString();
|
|
10
11
|
}
|
|
@@ -150,8 +151,10 @@ export async function endExecution(executionId, input) {
|
|
|
150
151
|
const at = now();
|
|
151
152
|
const ended = await db.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(at, at, input.reason, executionId);
|
|
152
153
|
await revokeNodeTokens(db, 'broker_process_id', executionId, at);
|
|
153
|
-
if (ended !== undefined)
|
|
154
|
+
if (ended !== undefined) {
|
|
154
155
|
await clearPendingParkIn(db, ended.node_id);
|
|
156
|
+
deleteSandboxOfEndedNode(ended.node_id);
|
|
157
|
+
}
|
|
155
158
|
return ended !== undefined;
|
|
156
159
|
});
|
|
157
160
|
}
|
|
@@ -176,8 +179,10 @@ export async function endLiveExecution(nodeId, input) {
|
|
|
176
179
|
const at = now();
|
|
177
180
|
const ended = await db.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(at, at, input.reason, nodeId);
|
|
178
181
|
await revokeNodeTokens(db, 'node_id', nodeId, at);
|
|
179
|
-
if (Number(ended.changes) > 0)
|
|
182
|
+
if (Number(ended.changes) > 0) {
|
|
180
183
|
await clearPendingParkIn(db, nodeId);
|
|
184
|
+
deleteSandboxOfEndedNode(nodeId);
|
|
185
|
+
}
|
|
181
186
|
return Number(ended.changes) === 1;
|
|
182
187
|
});
|
|
183
188
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 27;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -456,6 +456,9 @@ export async function parseArgv(params, tokens, options) {
|
|
|
456
456
|
throw parseArgvError('unknown_flag', `unknown flag: --${flagName}`, `--${flagName}`, undefined, 'Use --<flag-name> for declared flags only. Run -h for the schema.');
|
|
457
457
|
}
|
|
458
458
|
const key = flagNameToKey(flagName);
|
|
459
|
+
if (provided.has(key) && flagDef.type !== 'bool' && flagDef.repeatable !== true) {
|
|
460
|
+
throw parseArgvError('bad_invocation', `--${flagName} given twice; it takes one value`, `--${flagName}`, flagName, `Pass --${flagName} once.`);
|
|
461
|
+
}
|
|
459
462
|
provided.add(key);
|
|
460
463
|
if (flagDef.type === 'bool') {
|
|
461
464
|
if (inlineValue !== undefined) {
|
|
@@ -165,6 +165,21 @@ export async function consumeDeadlineOnWake(nodeId) {
|
|
|
165
165
|
}
|
|
166
166
|
});
|
|
167
167
|
}
|
|
168
|
+
/** A node deadline fell due: in one write, delete its row and queue its body to the anchor as urgent wake mail, which the
|
|
169
|
+
* lifecycle tick delivers by waking the node wherever it runs. No process runs. A row already gone (a wake consumed it, or
|
|
170
|
+
* a re-arm replaced it) delivers nothing. */
|
|
171
|
+
export async function deliverDueDeadline(cron) {
|
|
172
|
+
if (cron.anchor_node === null || cron.deadline_body === null)
|
|
173
|
+
throw new Error(`cron ${cron.cron_id} is not a node deadline`);
|
|
174
|
+
const anchor = cron.anchor_node;
|
|
175
|
+
const body = cron.deadline_body;
|
|
176
|
+
await withCanvasWrite(async (db) => {
|
|
177
|
+
const deleted = await db.prepare("DELETE FROM crons WHERE cron_id = ? AND state = 'active' AND run_state = 'idle'").run(cron.cron_id);
|
|
178
|
+
if (Number(deleted.changes) === 0)
|
|
179
|
+
return;
|
|
180
|
+
await insertNodeNotice(db, anchor, { body, label: 'deadline reached', tier: 'urgent', wake: 1 });
|
|
181
|
+
});
|
|
182
|
+
}
|
|
168
183
|
/** Queue one runtime notice to a node's inbox inside the caller's write transaction (no sender). */
|
|
169
184
|
export async function queueNodeNotice(db, nodeId, notice) {
|
|
170
185
|
const queued = await insertNodeNotice(db, nodeId, notice);
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
//
|
|
11
11
|
// persona.ts / broker-persona-guidance.ts deliver orchestratorContextNote() when a base node
|
|
12
12
|
// becomes an orchestrator after birth.
|
|
13
|
-
import { getNode, fullName, isSafeNodeId, subscriptionsOf, } from '../canvas/index.js';
|
|
13
|
+
import { getNode, latestExecutionForNode, fullName, isSafeNodeId, subscriptionsOf, } from '../canvas/index.js';
|
|
14
14
|
import { cadenceDisplay } from '../wake.js';
|
|
15
15
|
import { renderKnowledge, renderWorkspaceOpen } from '../substrate/delivery/render-boot.js';
|
|
16
16
|
import { situationalContextEnvelope } from './situational-context.js';
|
|
@@ -183,7 +183,7 @@ async function bearingsShell(nodeId, knowledge, workspaceContext) {
|
|
|
183
183
|
// nested card inside the outer envelope. Never routed through the visible
|
|
184
184
|
// chat/digest path. '' when nothing was ever set.
|
|
185
185
|
const situational = await situationalContextEnvelope(nodeId) ?? '';
|
|
186
|
-
const projectCtx = node?.cwd !== undefined ? buildProjectContextBlock(node.cwd) : '';
|
|
186
|
+
const projectCtx = node?.cwd !== undefined && (await latestExecutionForNode(nodeId))?.runner === 'process' ? buildProjectContextBlock(node.cwd) : ''; // reads this host
|
|
187
187
|
return [bearings.join('\n'), knowledge, workspaceContext, situational, projectCtx]
|
|
188
188
|
.filter((s) => s !== '')
|
|
189
189
|
.join('\n');
|
|
@@ -37,6 +37,7 @@ import { join } from 'node:path';
|
|
|
37
37
|
import { BROKER_RELEASED_MARKER, BROKER_RELAY_GENERATION, nodeRunDir } from '../canvas/paths.js';
|
|
38
38
|
import { openBeneath, writeFileBeneath, isAbsentOrRefused } from '../spaces/open-beneath.js';
|
|
39
39
|
import { emitEvent } from '../events/emit.js';
|
|
40
|
+
import { deleteSandboxOfEndedNode } from './runner/delete-sandboxes.js';
|
|
40
41
|
import { composeNodeOutcomeDocument } from './outcome-document.js';
|
|
41
42
|
import { afterCommit, withCanvasWrite } from '../canvas/db.js';
|
|
42
43
|
import { nodeObject } from '../graph/objects.js';
|
|
@@ -224,6 +225,8 @@ export async function transition(nodeId, event, opts) {
|
|
|
224
225
|
runStructuredRequestEffects(transitionResult.settlement.row);
|
|
225
226
|
if (event === 'finish' || event === 'park' || event === 'cancel')
|
|
226
227
|
await cancelCronsOnWake(nodeId);
|
|
228
|
+
if (event === 'finish' || event === 'cancel' || event === 'crash')
|
|
229
|
+
deleteSandboxOfEndedNode(nodeId);
|
|
227
230
|
return await getNode(nodeId);
|
|
228
231
|
}
|
|
229
232
|
/** The last relay generation published when it bound. Missing means no replacement has bound yet. */
|
|
@@ -253,32 +253,12 @@ async function decideReviveAsCaller(nodeId, opts, wakeParked) {
|
|
|
253
253
|
if (await blaxelEnvironmentOf(meta.profile_id ?? null) !== null)
|
|
254
254
|
await checkBilledWake(meta);
|
|
255
255
|
}
|
|
256
|
-
if (await fleet.has(nodeId)) {
|
|
257
|
-
// The node is already running, but the ROW may still say terminal: a reopen
|
|
258
|
-
// or a retask lands on a live broker, and only this transition puts the row
|
|
259
|
-
// back where its liveness already is. Both specs accept any prior status,
|
|
260
|
-
// so this is a no-op for a row that is already active.
|
|
261
|
-
await transition(nodeId, meta.intent === 'refresh' ? 'refresh-launch' : 'revive');
|
|
262
|
-
return {
|
|
263
|
-
parked: false,
|
|
264
|
-
result: {
|
|
265
|
-
window: null,
|
|
266
|
-
session: meta.tmux_session ?? null,
|
|
267
|
-
resumed: false,
|
|
268
|
-
outcome: 'already-live',
|
|
269
|
-
},
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
256
|
if (await fleet.isClaimed(nodeId)) {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
resumed: false,
|
|
279
|
-
outcome: 'already-live',
|
|
280
|
-
},
|
|
281
|
-
};
|
|
257
|
+
// A running broker's ROW may still say terminal: a reopen or a retask lands on a live broker, and only this transition puts the
|
|
258
|
+
// row back where its liveness already is. Both specs accept any prior status, so this is a no-op for a row already active.
|
|
259
|
+
if (await fleet.has(nodeId))
|
|
260
|
+
await transition(nodeId, meta.intent === 'refresh' ? 'refresh-launch' : 'revive');
|
|
261
|
+
return { parked: false, result: { window: null, session: meta.tmux_session ?? null, resumed: false, outcome: 'already-live' } };
|
|
282
262
|
}
|
|
283
263
|
// Focus may establish a viewport without establishing an engine. This exact
|
|
284
264
|
// row has no final latch and no fleet owner; returning before reservation is
|
|
@@ -31,7 +31,7 @@ function toInfo(raw) {
|
|
|
31
31
|
const url = raw.metadata.url;
|
|
32
32
|
if (!url)
|
|
33
33
|
throw new Error(`Blaxel sandbox ${raw.metadata.name} has no url`);
|
|
34
|
-
return { name: raw.metadata.name, url, state: raw.state ?? null, status: raw.status ?? null };
|
|
34
|
+
return { name: raw.metadata.name, url, state: raw.state ?? null, status: raw.status ?? null, image: raw.spec?.runtime?.image ?? null };
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
37
|
* The code and message of an error body. The sandbox gateway nests them (`{"error":{"code":"WORKLOAD_UNAVAILABLE","message":...}}`);
|
|
@@ -79,15 +79,22 @@ export function createBlaxelClient(config) {
|
|
|
79
79
|
config,
|
|
80
80
|
async createSandbox(spec) {
|
|
81
81
|
const ports = [...(spec.ports ?? [])].map((p) => ({ name: p.name, target: p.target, protocol: 'HTTP' }));
|
|
82
|
-
const body = { metadata: { name: spec.name }, spec: { runtime: { image: spec.image, memory: spec.memoryMb, ...(ports.length > 0 ? { ports } : {}) }, region: config.region
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
const body = { metadata: { name: spec.name }, spec: { runtime: { image: spec.image, memory: spec.memoryMb, ...(ports.length > 0 ? { ports } : {}) }, region: config.region,
|
|
83
|
+
// For a node that never finishes and a delete that failed. A process call into the sandbox restarts the idle time.
|
|
84
|
+
lifecycle: { expirationPolicies: [{ type: 'ttl-idle', value: '7d', action: 'delete' }] } } };
|
|
85
|
+
// A name held by a sandbox still being deleted (getSandbox reads DELETING/TERMINATED as null) frees once Blaxel removes it.
|
|
86
|
+
const deadline = Date.now() + (config.deletingWaitMs ?? 60_000);
|
|
87
|
+
for (;;) {
|
|
88
|
+
const { status, json } = await call(`${control}/sandboxes`, 'POST', body, [409]);
|
|
89
|
+
if (status !== 409)
|
|
90
|
+
return { ...toInfo(json), created: true };
|
|
85
91
|
const existing = await this.getSandbox(spec.name);
|
|
86
|
-
if (existing
|
|
87
|
-
|
|
88
|
-
|
|
92
|
+
if (existing !== null)
|
|
93
|
+
return { ...existing, created: false };
|
|
94
|
+
if (Date.now() >= deadline)
|
|
95
|
+
throw new Error(`Blaxel sandbox ${spec.name} is still being deleted; its name did not free in time`);
|
|
96
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
89
97
|
}
|
|
90
|
-
return { ...toInfo(json), created: true };
|
|
91
98
|
},
|
|
92
99
|
async getSandbox(name) {
|
|
93
100
|
const { status, json } = await call(`${control}/sandboxes/${encodeName(name)}`, 'GET', undefined, [404]);
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
// src/core/runtime/runner/blaxel/runner.ts — the Blaxel runner (design-fleet, Components: Runner; C-A2).
|
|
2
2
|
//
|
|
3
|
-
// One sandbox per node
|
|
3
|
+
// One sandbox per node, named by the node id and reused at every start, one process per execution
|
|
4
4
|
// named `broker-<execution id>`. That process runs the bootstrap, which installs the release and runs
|
|
5
5
|
// `crtr-sandbox-start`; the start script stays as the broker's parent. The runner never reads the sandbox's
|
|
6
6
|
// own status as the freeze signal: a frozen broker reads `running` from the process status. It reads the
|
|
7
7
|
// sandbox `state` (STANDBY while frozen; reading it does not wake the sandbox) only in `sandboxState`, for
|
|
8
8
|
// the freeze measurement. The process status goes through the sandbox and so wakes it: `status` of an idle execution never asks.
|
|
9
|
-
import { openDb } from '../../../canvas/db.js';
|
|
10
9
|
import { mintExecutionToken } from '../../../canvas/node-tokens.js';
|
|
11
10
|
import { BlaxelApiError, isWorkloadUnavailable } from './client.js';
|
|
12
11
|
/** The broker listens here inside the sandbox; the private preview forwards it (`wss://<preview>/view`). */
|
|
@@ -21,13 +20,12 @@ export const FAILURE_LINE = /^crtr-sandbox-start: failed (\S+)/m;
|
|
|
21
20
|
/** How much of a failed process's output `status` carries: enough for the boot phase lines and the error that ended the start. */
|
|
22
21
|
const FAILURE_OUTPUT_CHARS = 2000;
|
|
23
22
|
export const brokerProcessName = (executionId) => `broker-${executionId}`;
|
|
24
|
-
export const sandboxNameFor = (
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
23
|
+
export const sandboxNameFor = (nodeId) => nodeId;
|
|
24
|
+
export const cronProcessName = (runId) => `cron-${runId}`;
|
|
25
|
+
const CRON_POLL_MS = 2_000;
|
|
26
|
+
/** The user and release `bin` of `scripts/sandbox-bootstrap.sh` (`RUN_USER`, `$ROOT/current`). */
|
|
27
|
+
const RUN_USER = 'crtr';
|
|
28
|
+
const RELEASE_BIN = '/opt/crtr/current/bin';
|
|
31
29
|
function failureOf(process) {
|
|
32
30
|
const text = `${process.logs}\n${process.stderr}\n${process.stdout}`;
|
|
33
31
|
const output = (process.stderr || process.logs || process.stdout || '').trim().slice(-FAILURE_OUTPUT_CHARS);
|
|
@@ -38,7 +36,7 @@ export function createBlaxelRunner(deps) {
|
|
|
38
36
|
const stopGraceMs = (deps.stopGraceS ?? 10) * 1000;
|
|
39
37
|
const previewTokens = new Map();
|
|
40
38
|
async function sandboxOf(execution) {
|
|
41
|
-
return await client.getSandbox(sandboxNameFor(execution));
|
|
39
|
+
return await client.getSandbox(sandboxNameFor(execution.nodeId));
|
|
42
40
|
}
|
|
43
41
|
/** Stops any broker of the execution still in the sandbox (SIGTERM, then SIGKILL after the grace) and reports whether none is left. */
|
|
44
42
|
async function brokerGone(sandbox, executionId) {
|
|
@@ -53,9 +51,15 @@ export function createBlaxelRunner(deps) {
|
|
|
53
51
|
kind: 'blaxel',
|
|
54
52
|
async start(input) {
|
|
55
53
|
const context = await deps.launchContext(input);
|
|
56
|
-
const name = sandboxNameFor(input);
|
|
57
|
-
|
|
58
|
-
|
|
54
|
+
const name = sandboxNameFor(input.nodeId);
|
|
55
|
+
const spec = { name, image: context.image, memoryMb: context.memoryMb, ports: [{ name: VIEW_PREVIEW, target: BROKER_VIEW_PORT }] };
|
|
56
|
+
// "Name taken" means an earlier start created it: the client adopts it, files and all. One on an older image is replaced.
|
|
57
|
+
let sandbox = await client.createSandbox(spec);
|
|
58
|
+
if (sandbox.image !== context.image) {
|
|
59
|
+
await client.deleteSandbox(name);
|
|
60
|
+
previewTokens.delete(name);
|
|
61
|
+
sandbox = await client.createSandbox(spec);
|
|
62
|
+
}
|
|
59
63
|
const process = brokerProcessName(input.executionId);
|
|
60
64
|
// A repeated call (a reconciler whose lease was taken) finds the process and adopts it: no second token.
|
|
61
65
|
const existing = await client.getProcess(sandbox, process);
|
|
@@ -141,14 +145,11 @@ export function createBlaxelRunner(deps) {
|
|
|
141
145
|
}
|
|
142
146
|
},
|
|
143
147
|
async delete(nodeId) {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
},
|
|
147
|
-
async deleteExecution(execution) {
|
|
148
|
-
await client.deleteSandbox(sandboxNameFor(execution));
|
|
148
|
+
await client.deleteSandbox(sandboxNameFor(nodeId));
|
|
149
|
+
previewTokens.delete(sandboxNameFor(nodeId));
|
|
149
150
|
},
|
|
150
151
|
async viewerAddress(execution) {
|
|
151
|
-
const name = sandboxNameFor(execution);
|
|
152
|
+
const name = sandboxNameFor(execution.nodeId);
|
|
152
153
|
const cached = previewTokens.get(name);
|
|
153
154
|
if (cached && cached.expiresAt - Date.now() > 5 * 60_000)
|
|
154
155
|
return viewer(cached.url, cached.token);
|
|
@@ -158,6 +159,46 @@ export function createBlaxelRunner(deps) {
|
|
|
158
159
|
previewTokens.set(name, { url, token, expiresAt: expires.getTime() });
|
|
159
160
|
return viewer(url, token);
|
|
160
161
|
},
|
|
162
|
+
async cronRun(nodeId, run) {
|
|
163
|
+
const sandbox = await client.getSandbox(sandboxNameFor(nodeId));
|
|
164
|
+
if (sandbox === null)
|
|
165
|
+
throw new Error(`node ${nodeId} has no sandbox, so the cron cannot run; the scheduler never starts a node to get one`);
|
|
166
|
+
const name = cronProcessName(run.runId);
|
|
167
|
+
// A sandbox process runs as root; the command runs as the node's user, as the broker does (sandbox-bootstrap.sh), with the release's `crtr` on PATH.
|
|
168
|
+
const command = `exec nsenter -S "$(id -u ${RUN_USER})" -G "$(id -g ${RUN_USER})" bash -c "$CRTR_CRON_COMMAND"`;
|
|
169
|
+
const env = { ...run.env, CRTR_CRON_COMMAND: run.command, PATH: `${RELEASE_BIN}:/usr/local/bin:/usr/bin:/bin` };
|
|
170
|
+
// The process name fences the run id: a resend or a recovering control plane reads the first start instead of running the command again.
|
|
171
|
+
let process = await client.getProcess(sandbox, name)
|
|
172
|
+
?? await client.startProcess(sandbox, { name, command, workingDir: run.cwd, env, waitForCompletion: false });
|
|
173
|
+
// Counted from the fire's start, so a recovered run does not get a fresh timeout.
|
|
174
|
+
const deadline = run.startedAtMs + run.timeoutS * 1000;
|
|
175
|
+
while (process.status === 'running') {
|
|
176
|
+
if (Date.now() >= deadline) {
|
|
177
|
+
await client.killProcess(sandbox, name);
|
|
178
|
+
return { exitCode: null, timedOut: true, stdout: process.stdout, stderr: process.stderr };
|
|
179
|
+
}
|
|
180
|
+
await new Promise((resolve) => setTimeout(resolve, CRON_POLL_MS));
|
|
181
|
+
// A failed read (a 5xx, a dropped connection) is retried until the deadline: the process is still running in the sandbox.
|
|
182
|
+
let read;
|
|
183
|
+
try {
|
|
184
|
+
read = await client.getProcess(sandbox, name);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (read === null)
|
|
190
|
+
return { exitCode: null, timedOut: false, stdout: process.stdout, stderr: process.stderr, error: `process ${name} is gone from the sandbox, so its outcome is unknown` };
|
|
191
|
+
process = read;
|
|
192
|
+
}
|
|
193
|
+
if (process.status === 'completed' || process.status === 'failed')
|
|
194
|
+
return { exitCode: process.exitCode, timedOut: false, stdout: process.stdout, stderr: process.stderr };
|
|
195
|
+
return { exitCode: null, timedOut: false, stdout: process.stdout, stderr: process.stderr, error: `process ${name} was ${process.status} from outside the run` };
|
|
196
|
+
},
|
|
197
|
+
async cronCancel(nodeId, runId) {
|
|
198
|
+
const sandbox = await client.getSandbox(sandboxNameFor(nodeId));
|
|
199
|
+
if (sandbox !== null)
|
|
200
|
+
await client.killProcess(sandbox, cronProcessName(runId));
|
|
201
|
+
},
|
|
161
202
|
/** The sandbox `state` (`STANDBY` while frozen), read without waking it. Null when the sandbox is gone. Measurement only. */
|
|
162
203
|
async sandboxState(execution) {
|
|
163
204
|
return (await sandboxOf(execution))?.state ?? null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// A node's sandboxes go before its rows do. The executions rows are what
|
|
1
|
+
// A node's sandboxes go before its rows do. The executions rows are what show a node ran in one and they cascade away with
|
|
2
2
|
// the node, so a node row deleted first leaves a running, billed sandbox that nothing can find again (design-fleet, Runner: `delete(node)`
|
|
3
3
|
// on the Blaxel runner deletes the sandbox). Every path that deletes node rows calls this first.
|
|
4
|
-
import { openDb } from '../../canvas/db.js';
|
|
4
|
+
import { afterCommit, openDb, withCanvasWrite } from '../../canvas/db.js';
|
|
5
5
|
import { emitEvent } from '../../events/emit.js';
|
|
6
6
|
/** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
|
|
7
7
|
* those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
|
|
@@ -22,3 +22,19 @@ export async function deleteNodeSandboxes(nodeIds) {
|
|
|
22
22
|
}
|
|
23
23
|
return failed;
|
|
24
24
|
}
|
|
25
|
+
/** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
|
|
26
|
+
* (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
|
|
27
|
+
* wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
|
|
28
|
+
* takes, so no new execution can start in the sandbox between them. */
|
|
29
|
+
export function deleteSandboxOfEndedNode(nodeId) {
|
|
30
|
+
afterCommit(() => void withCanvasWrite(async (db) => {
|
|
31
|
+
const ended = await db.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
|
|
32
|
+
AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
|
|
33
|
+
AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
|
|
34
|
+
AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
|
|
35
|
+
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
|
|
36
|
+
FOR UPDATE OF n`).get(nodeId);
|
|
37
|
+
if (ended !== undefined)
|
|
38
|
+
await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
|
|
39
|
+
}).catch((error) => { emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id: nodeId, error }); }));
|
|
40
|
+
}
|
|
@@ -154,7 +154,7 @@ export const OPERATIONS = [
|
|
|
154
154
|
{ name: 'model_auth.cancel', method: 'POST', path: '/v1/model-auth/flows/:flow_id/cancel', classes: ['person', 'broker'], resource: 'none' },
|
|
155
155
|
{ name: 'model_auth.get', method: 'GET', path: '/v1/model-auth/flows/:flow_id', classes: ['person', 'broker'], resource: 'none' },
|
|
156
156
|
{ name: 'nodes.post.85', method: 'POST', path: '/v1/nodes', classes: ['person', 'broker', 'cron'], resource: 'node-own', scope: 'crtr:act' },
|
|
157
|
-
{ name: 'nodes.get.86', method: 'GET', path: '/v1/nodes', classes: ['person', 'broker'], resource: 'nodes-list' },
|
|
157
|
+
{ name: 'nodes.get.86', method: 'GET', path: '/v1/nodes', classes: ['person', 'broker', 'cron'], resource: 'nodes-list' },
|
|
158
158
|
{ name: 'nodes.post.87', method: 'POST', path: '/v1/nodes/revive-all', classes: ['person', 'broker'], resource: 'none' },
|
|
159
159
|
{ name: 'nodes.get.88', method: 'GET', path: '/v1/nodes/:id', classes: ['person', 'broker', 'cron', 'forwarded'], resource: 'node-read' },
|
|
160
160
|
{ name: 'nodes.get.89', method: 'GET', path: '/v1/nodes/:id/snapshot', classes: ['person', 'broker', 'cron'], resource: 'node-read' },
|
|
@@ -193,7 +193,7 @@ export const OPERATIONS = [
|
|
|
193
193
|
{ name: 'profile.env.list', method: 'GET', path: '/v1/profiles/:name/env', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
194
194
|
{ name: 'profile.env.set', method: 'PUT', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
195
195
|
{ name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
196
|
-
{ name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
|
|
196
|
+
{ name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
|
|
197
197
|
{ name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person'], resource: 'profile' },
|
|
198
198
|
{ name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
199
199
|
{ name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker'], resource: 'profile', stage: 'chat' },
|
|
@@ -7,24 +7,27 @@ import { CRON_RUN_RING, cancelCron, listCronRuns, parseCronSink } from '../../co
|
|
|
7
7
|
import { hasNoNaturalCycle } from '../../core/runtime/revive-all.js';
|
|
8
8
|
import { isParked } from '../../core/runtime/lifecycle.js';
|
|
9
9
|
import { enqueueNodeMail } from '../../core/feed/messages.js';
|
|
10
|
+
import { emitEvent } from '../../core/events/emit.js';
|
|
10
11
|
import { cadenceDisplay } from '../../core/wake.js';
|
|
11
|
-
import {
|
|
12
|
+
import { cronEnvironment, queueCronCancel } from './machine-fire.js';
|
|
13
|
+
import { runnerForEnvironment } from '../../core/runtime/runner/index.js';
|
|
12
14
|
const SENT = /^delivered: /;
|
|
13
15
|
const EMPTY_OK = (r) => r.exit_code === 0 && (r.stdout_head ?? '') === '';
|
|
14
16
|
/** Real runs only: the overlap pass writes a marker row that is not a run. */
|
|
15
17
|
function realRuns(runs) {
|
|
16
18
|
return runs.filter((r) => r.exit_code !== null || !(r.delivered ?? '').startsWith('skipped'));
|
|
17
19
|
}
|
|
18
|
-
function endedMessage(c, end, runs) {
|
|
20
|
+
function endedMessage(c, end, runs, toSink) {
|
|
19
21
|
const real = realRuns(runs);
|
|
20
22
|
// The run log keeps the last CRON_RUN_RING rows, so a full ring means the true count is unknown.
|
|
21
23
|
const full = runs.length >= CRON_RUN_RING;
|
|
22
24
|
const lastSent = real.find((r) => SENT.test(r.delivered ?? ''));
|
|
23
25
|
const cause = end.kind === 'expired'
|
|
24
26
|
? `expired at ${c.expires_at} and was deleted${c.held ? ' while held by exit 75; the pending occurrence never fired' : ''}`
|
|
25
|
-
: `
|
|
27
|
+
: end.kind === 'max_fires' ? `reached its maximum of ${end.max} fires and was deleted`
|
|
28
|
+
: `was canceled by ${end.by} and deleted`;
|
|
26
29
|
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
|
|
30
|
+
`Cron "${c.name}" (${c.cron_id}, ${c.recur != null ? cadenceDisplay(c.recur) : 'one-shot'}) ${cause}. ${toSink ? 'It was delivering to you, so nothing will wake you from it any more.' : 'It was anchored on you.'}`,
|
|
28
31
|
'',
|
|
29
32
|
`- runs made: ${full ? `at least ${real.length} (the run log keeps the last ${CRON_RUN_RING} entries)` : real.length}`,
|
|
30
33
|
lastSent !== undefined
|
|
@@ -39,7 +42,7 @@ function endedMessage(c, end, runs) {
|
|
|
39
42
|
if (real.length > 0 && real.every(EMPTY_OK)) {
|
|
40
43
|
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
44
|
}
|
|
42
|
-
return { label: `⏰ cron ${c.name} ${end.kind === '
|
|
45
|
+
return { label: `⏰ cron ${c.name} ${end.kind === 'canceled' ? 'canceled' : end.kind === 'max_fires' ? 'ended' : 'expired'}`, body: lines.join('\n') };
|
|
43
46
|
}
|
|
44
47
|
/** 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
48
|
async function runIsDeleting(node) {
|
|
@@ -55,21 +58,29 @@ export async function canTakeMail(node) {
|
|
|
55
58
|
* that can still take mail: gone, deleting, or finalized with no wake ahead. */
|
|
56
59
|
export async function endCron(c, end, options) {
|
|
57
60
|
const sink = parseCronSink(c.sink);
|
|
58
|
-
|
|
61
|
+
// A cron that used all its fires tells its anchor, whatever its output sink (NL-1110); every other end tells the node sink.
|
|
62
|
+
const targetId = end?.kind === 'max_fires' && c.anchor_node !== null ? c.anchor_node : sink?.kind === 'node' ? sink.node : null;
|
|
63
|
+
const target = targetId !== null ? await getNode(targetId) : null;
|
|
59
64
|
const notify = end !== null && target !== null && await canTakeMail(target);
|
|
60
|
-
// A run on a machine is not a local process the delete can signal
|
|
65
|
+
// A run on a machine or in a sandbox is not a local process the delete can signal. A machine is owed a cancel of that run id, delivered when the link is up
|
|
61
66
|
// (at once, or on reconnect), including for a `cron.run` the machine never received.
|
|
62
67
|
if (c.run_state === 'running' && c.run_execution_id !== null && options?.preserveRunningProcess !== true) {
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
65
|
-
await queueCronCancel(
|
|
68
|
+
const environment = await cronEnvironment(c);
|
|
69
|
+
if (environment?.kind === 'machine')
|
|
70
|
+
await queueCronCancel(environment.id, c.run_execution_id);
|
|
71
|
+
// A sandbox process is killed now; a Blaxel failure is logged and the delete goes ahead (the run timeout or recovery ends the process).
|
|
72
|
+
if (environment?.kind === 'blaxel' && c.anchor_node != null) {
|
|
73
|
+
await runnerForEnvironment('blaxel').cronCancel?.(c.anchor_node, c.run_execution_id).catch((error) => {
|
|
74
|
+
emitEvent({ level: 'error', event: 'cron.sandbox.cancel_failed', error, fields: { cron_id: c.cron_id, run_id: c.run_execution_id } });
|
|
75
|
+
});
|
|
76
|
+
}
|
|
66
77
|
}
|
|
67
78
|
return await withCanvasWrite(async () => {
|
|
68
79
|
const runs = notify ? await listCronRuns(c.cron_id) : [];
|
|
69
80
|
if (!await cancelCron(c.cron_id, options))
|
|
70
81
|
return false;
|
|
71
82
|
if (notify) {
|
|
72
|
-
const { label, body } = endedMessage(c, end, runs);
|
|
83
|
+
const { label, body } = endedMessage(c, end, runs, sink?.kind === 'node' && sink.node === target.node_id);
|
|
73
84
|
await enqueueNodeMail(target.node_id, {
|
|
74
85
|
kind: 'message', label, senderNodeId: null, bodyJson: { body }, urgency: 'normal', wake: 1,
|
|
75
86
|
idempotencyKey: `cron-ended:${c.cron_id}`,
|