@north-light/cli 0.3.672 → 0.3.674
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/execution-start.d.ts +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/core/pool-credential-store.d.ts +4 -0
- package/dist/core/pool-credential-store.js +1 -1
- package/dist/core/runtime/provider-credential-gate.d.ts +2 -2
- package/dist/core/runtime/provider-credential-gate.js +2 -2
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -1
- package/dist/core/runtime/spawn.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/subscription-state.d.ts +2 -0
- package/dist/core/subscription-state.js +1 -1
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/plan.d.ts +4 -0
- package/dist/core/substrate/delivery/plan.js +2 -2
- package/dist/daemon/api/handlers/broker-ops.d.ts +12 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/execution-start.d.ts +9 -1
- package/dist/daemon/api/handlers/execution-start.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/machine-link/holder.js +4 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +44 -25
- package/packages/crouter-api/dist/core/review/document.js +143 -0
- package/packages/crouter-api/dist/core/review/project.js +45 -0
- package/packages/crouter-api/dist/core/runtime/launch-recipe.js +45 -0
- package/packages/crouter-api/dist/core/runtime/provider-credential-gate.js +4 -4
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +96 -0
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +170 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +11 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +88 -3
- package/packages/crouter-api/dist/core/runtime/stop-signals.js +46 -0
- package/packages/crouter-api/dist/core/secrets/blaxel-launch.js +104 -0
- package/packages/crouter-api/dist/core/subscription-state.js +18 -2
- package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +24 -3
- package/packages/crouter-api/dist/core/substrate/delivery/plan.js +2 -0
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +701 -0
- package/packages/crouter-api/dist/daemon/api/handlers/execution-start.js +120 -0
- package/packages/crouter-api/dist/daemon/api/handlers/node-records.js +113 -0
- package/packages/crouter-api/dist/daemon/api/handlers/telemetry-record.js +34 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/review/companion.js +29 -0
- package/packages/crouter-api/dist/daemon/review/deliver.js +13 -0
- package/packages/crouter-api/dist/daemon/review/finish.js +170 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { statSync } from 'node:fs';
|
|
3
|
+
import { isBlobRequestPath, readRequestFileIfPresent } from '../human/request-files.js';
|
|
4
|
+
import { documentLines } from '../document-lines.js';
|
|
5
|
+
import { COMMENT_QUOTE_MAX, ReviewOperationError, } from './types.js';
|
|
6
|
+
const REVIEW_SOURCE_MAX_BYTES = 2 * 1024 * 1024;
|
|
7
|
+
function sourceUnreadable(file, phase, reason) {
|
|
8
|
+
throw new ReviewOperationError('source_unreadable', 'review source is unreadable', { phase, reason, file });
|
|
9
|
+
}
|
|
10
|
+
/** Read the reviewed document once, preserving the exact bytes used for its digest. */
|
|
11
|
+
export async function readReviewSource(file, phase = 'submit') {
|
|
12
|
+
if (!isBlobRequestPath(file)) {
|
|
13
|
+
let size;
|
|
14
|
+
try {
|
|
15
|
+
const stat = statSync(file);
|
|
16
|
+
if (!stat.isFile())
|
|
17
|
+
return sourceUnreadable(file, phase, 'unreadable');
|
|
18
|
+
size = stat.size;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
return sourceUnreadable(file, phase, error.code === 'ENOENT' ? 'missing' : 'unreadable');
|
|
22
|
+
}
|
|
23
|
+
if (size > REVIEW_SOURCE_MAX_BYTES)
|
|
24
|
+
return sourceUnreadable(file, phase, 'too_large');
|
|
25
|
+
}
|
|
26
|
+
let bytes;
|
|
27
|
+
try {
|
|
28
|
+
bytes = await readRequestFileIfPresent(file);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return sourceUnreadable(file, phase, 'unreadable');
|
|
32
|
+
}
|
|
33
|
+
if (bytes === null)
|
|
34
|
+
return sourceUnreadable(file, phase, 'missing');
|
|
35
|
+
if (bytes.length > REVIEW_SOURCE_MAX_BYTES)
|
|
36
|
+
return sourceUnreadable(file, phase, 'too_large');
|
|
37
|
+
if (bytes.includes(0))
|
|
38
|
+
return sourceUnreadable(file, phase, 'binary');
|
|
39
|
+
let text;
|
|
40
|
+
try {
|
|
41
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return sourceUnreadable(file, phase, 'binary');
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
bytes,
|
|
48
|
+
sha256: createHash('sha256').update(bytes).digest('hex'),
|
|
49
|
+
lines: documentLines(text),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
async function requireDocumentSource(review, expected_doc_hash) {
|
|
53
|
+
const source = await readReviewSource(review.file, 'comment');
|
|
54
|
+
if (source.sha256 !== expected_doc_hash) {
|
|
55
|
+
throw new ReviewOperationError('stale_document', 'review document changed since it was rendered', {
|
|
56
|
+
reason: 'document_changed',
|
|
57
|
+
expected_sha256: expected_doc_hash,
|
|
58
|
+
actual_sha256: source.sha256,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (source.sha256 !== review.anchor_base_sha256) {
|
|
62
|
+
throw new ReviewOperationError('stale_document', 'review comment ranges have not been remapped to the current document', {
|
|
63
|
+
reason: 'anchor_base_stale',
|
|
64
|
+
expected_sha256: review.anchor_base_sha256,
|
|
65
|
+
actual_sha256: source.sha256,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return source;
|
|
69
|
+
}
|
|
70
|
+
/** Require both the caller's rendered source and the persisted range coordinate base to be current. */
|
|
71
|
+
export async function requireCurrentDocument(review, expected_doc_hash) {
|
|
72
|
+
return requireDocumentSource(review, expected_doc_hash);
|
|
73
|
+
}
|
|
74
|
+
/** Verify a create-time source precondition from the review row held by the caller's canvas write transaction. */
|
|
75
|
+
export async function requireCurrentDocumentLocked(db, review_id, expected_doc_hash) {
|
|
76
|
+
const review = await db.prepare("SELECT file, anchor_base_sha256 FROM human_requests WHERE request_id = ? AND kind = 'review' AND state = 'open'").get(review_id);
|
|
77
|
+
if (review === undefined) {
|
|
78
|
+
throw new ReviewOperationError('unknown_review', 'review was not found', { received: review_id });
|
|
79
|
+
}
|
|
80
|
+
return requireDocumentSource(review, expected_doc_hash);
|
|
81
|
+
}
|
|
82
|
+
/** Reject malformed ranges rather than normalizing them into a different anchor. */
|
|
83
|
+
export function validateAnchorShape(anchor) {
|
|
84
|
+
const violations = [];
|
|
85
|
+
const hasStart = anchor.col_start !== undefined;
|
|
86
|
+
const hasEnd = anchor.col_end !== undefined;
|
|
87
|
+
if (!Number.isSafeInteger(anchor.line) || anchor.line < 1)
|
|
88
|
+
violations.push('line must be a positive integer');
|
|
89
|
+
if (!Number.isSafeInteger(anchor.end_line) || anchor.end_line < 1)
|
|
90
|
+
violations.push('end_line must be a positive integer');
|
|
91
|
+
if (Number.isSafeInteger(anchor.line) && Number.isSafeInteger(anchor.end_line) && anchor.end_line < anchor.line) {
|
|
92
|
+
violations.push('end_line must be greater than or equal to line');
|
|
93
|
+
}
|
|
94
|
+
if (hasStart !== hasEnd)
|
|
95
|
+
violations.push('col_start and col_end must be provided together');
|
|
96
|
+
if (hasStart && (!Number.isSafeInteger(anchor.col_start) || anchor.col_start < 0))
|
|
97
|
+
violations.push('col_start must be a non-negative integer');
|
|
98
|
+
if (hasEnd && (!Number.isSafeInteger(anchor.col_end) || anchor.col_end < 0))
|
|
99
|
+
violations.push('col_end must be a non-negative integer');
|
|
100
|
+
if (hasStart
|
|
101
|
+
&& hasEnd
|
|
102
|
+
&& anchor.line === anchor.end_line
|
|
103
|
+
&& Number.isSafeInteger(anchor.col_start)
|
|
104
|
+
&& Number.isSafeInteger(anchor.col_end)
|
|
105
|
+
&& anchor.col_end <= anchor.col_start) {
|
|
106
|
+
violations.push('col_end must be greater than col_start for a single-line anchor');
|
|
107
|
+
}
|
|
108
|
+
if (anchor.quote !== undefined && typeof anchor.quote !== 'string')
|
|
109
|
+
violations.push('quote must be a string');
|
|
110
|
+
if (typeof anchor.quote === 'string' && Buffer.byteLength(anchor.quote, 'utf8') > COMMENT_QUOTE_MAX) {
|
|
111
|
+
violations.push(`quote exceeds ${COMMENT_QUOTE_MAX} bytes`);
|
|
112
|
+
}
|
|
113
|
+
if (violations.length > 0) {
|
|
114
|
+
throw new ReviewOperationError('invalid_anchor', 'comment anchor is invalid', { violations });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function isUtf8Boundary(bytes, offset) {
|
|
118
|
+
return offset === bytes.length || (bytes[offset] & 0xc0) !== 0x80;
|
|
119
|
+
}
|
|
120
|
+
/** Capture the full source range used to render an anchor, without silently clamping it. */
|
|
121
|
+
export function captureAnchorText(lines, anchor) {
|
|
122
|
+
validateAnchorShape(anchor);
|
|
123
|
+
if (anchor.line > lines.length || anchor.end_line > lines.length) {
|
|
124
|
+
throw new ReviewOperationError('anchor_out_of_range', 'comment anchor exceeds the reviewed document', {
|
|
125
|
+
line_count: lines.length,
|
|
126
|
+
requested: { line: anchor.line, end_line: anchor.end_line },
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
if (anchor.col_start !== undefined && anchor.col_end !== undefined) {
|
|
130
|
+
const startLine = Buffer.from(lines[anchor.line - 1], 'utf8');
|
|
131
|
+
const endLine = Buffer.from(lines[anchor.end_line - 1], 'utf8');
|
|
132
|
+
if (anchor.col_start > startLine.length
|
|
133
|
+
|| anchor.col_end > endLine.length
|
|
134
|
+
|| !isUtf8Boundary(startLine, anchor.col_start)
|
|
135
|
+
|| !isUtf8Boundary(endLine, anchor.col_end)) {
|
|
136
|
+
throw new ReviewOperationError('anchor_out_of_range', 'comment anchor columns exceed the reviewed document', {
|
|
137
|
+
line_count: lines.length,
|
|
138
|
+
requested: { line: anchor.line, end_line: anchor.end_line },
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return lines.slice(anchor.line - 1, anchor.end_line).join('\n');
|
|
143
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { atomicWriteJson } from '../human/convention.js';
|
|
2
|
+
import { isCloudRole } from '../canvas/person.js';
|
|
3
|
+
import { writeRequestFile } from '../human/request-files.js';
|
|
4
|
+
/** Build the immutable approval result from the review row and one comment snapshot. */
|
|
5
|
+
export function buildReviewResult(review, snapshot, approvedSha256, at) {
|
|
6
|
+
return {
|
|
7
|
+
schema: 'humanloop.review-response/v1',
|
|
8
|
+
review_id: review.review_id,
|
|
9
|
+
file: review.file,
|
|
10
|
+
submitted: true,
|
|
11
|
+
approved: true,
|
|
12
|
+
changed: approvedSha256 !== review.baseline_sha256,
|
|
13
|
+
baseline_sha256: review.baseline_sha256,
|
|
14
|
+
approved_sha256: approvedSha256,
|
|
15
|
+
companion_node_id: review.companion_node_id,
|
|
16
|
+
comments_total: snapshot.total,
|
|
17
|
+
comments_unresolved: snapshot.unresolved,
|
|
18
|
+
comments: snapshot.comments,
|
|
19
|
+
submittedAt: at,
|
|
20
|
+
savedAt: at,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const json = (data) => JSON.stringify(data, null, 2) + '\n';
|
|
24
|
+
/** Project every terminal review from its SQL row; no ticket bridge participates. A file in the review directory goes
|
|
25
|
+
* where the directory is (the blob store for a `requests/…` prefix); an `output_path` is always a local file. A cloud role
|
|
26
|
+
* never writes an external path: an imported row keeps its `output_path` as history and projects only its own blobs. */
|
|
27
|
+
export async function projectReviewResult(review, result) {
|
|
28
|
+
const resultPath = `${review.review_dir}/result.json`;
|
|
29
|
+
await writeRequestFile(resultPath, json(result));
|
|
30
|
+
const external = isCloudRole() ? null : review.output_path;
|
|
31
|
+
const output = external ?? `${review.review_dir}/feedback.json`;
|
|
32
|
+
if (output !== resultPath) {
|
|
33
|
+
if (external === null)
|
|
34
|
+
await writeRequestFile(output, json(result));
|
|
35
|
+
else
|
|
36
|
+
atomicWriteJson(output, result);
|
|
37
|
+
}
|
|
38
|
+
return { destinations: output === resultPath ? [resultPath] : [resultPath, output] };
|
|
39
|
+
}
|
|
40
|
+
/** Cancellation has no review approval payload but still receives a durable projection. */
|
|
41
|
+
export async function projectReviewCancellation(review, result) {
|
|
42
|
+
const resultPath = `${review.review_dir}/result.json`;
|
|
43
|
+
await writeRequestFile(resultPath, json(result));
|
|
44
|
+
return { destinations: [resultPath] };
|
|
45
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// The restart rule for a yield. A running broker can start the next cycle itself unless the launch
|
|
2
|
+
// spec the node would be built with now differs from the one it was built with in anything but the
|
|
3
|
+
// model. The compared fields are the ones the warm pool keys on (warm-pool.ts `warmRecipeKey`):
|
|
4
|
+
// working directory, profile, tools, extensions, system prompt and the launch env.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { KICKOFF_ORIGIN_ENV } from './stamp/protocol.js';
|
|
7
|
+
/** Env the running process re-reads or is given at the start of every cycle, so a change in them is not a launch change. */
|
|
8
|
+
const CYCLE_ENV = new Set([
|
|
9
|
+
'CRTR_KIND', 'CRTR_MODE', 'CRTR_LIFECYCLE', 'CRTR_CYCLES', 'CRTR_MODEL_INTENT', 'CRTR_MODEL_EXACT',
|
|
10
|
+
'CRTR_EXECUTION_ID', 'CRTR_SUBTREE', 'CRTR_KICKOFF_MESSAGE_IDS', 'CRTR_NODE_DEADLINE_AT', KICKOFF_ORIGIN_ENV,
|
|
11
|
+
]);
|
|
12
|
+
/** The env a running broker re-applies at the start of each cycle (and deletes when the next launch spec no longer carries it). */
|
|
13
|
+
export const CYCLE_APPLIED_ENV = ['CRTR_KIND', 'CRTR_MODE', 'CRTR_LIFECYCLE', 'CRTR_CYCLES', 'CRTR_MODEL_INTENT', 'CRTR_NODE_DEADLINE_AT'];
|
|
14
|
+
function argvValues(argv, flag) {
|
|
15
|
+
const values = [];
|
|
16
|
+
for (let i = 0; i < argv.length; i++)
|
|
17
|
+
if (argv[i] === flag && i + 1 < argv.length)
|
|
18
|
+
values.push(argv[++i]);
|
|
19
|
+
return values;
|
|
20
|
+
}
|
|
21
|
+
/** Digest of everything in a launch invocation that a running broker cannot change in place. */
|
|
22
|
+
export function launchRecipeKey(inv) {
|
|
23
|
+
const env = Object.entries(inv.env).filter(([name]) => !CYCLE_ENV.has(name)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
24
|
+
const canonical = JSON.stringify([
|
|
25
|
+
inv.env['CRTR_NODE_CWD'] ?? null,
|
|
26
|
+
inv.env['CRTR_PROFILE_ID'] ?? null,
|
|
27
|
+
argvValues(inv.argv, '--tools'),
|
|
28
|
+
argvValues(inv.argv, '-e'),
|
|
29
|
+
argvValues(inv.argv, '--append-system-prompt'),
|
|
30
|
+
env,
|
|
31
|
+
inv.configSnapshot ?? null,
|
|
32
|
+
inv.scopes ?? null,
|
|
33
|
+
]);
|
|
34
|
+
return createHash('sha256').update(canonical).digest('hex').slice(0, 32);
|
|
35
|
+
}
|
|
36
|
+
/** Whether the process launched from `runningLaunchJson` can start a cycle for `next` without restarting. */
|
|
37
|
+
export function cycleCompatible(runningLaunchJson, nextLaunchJson) {
|
|
38
|
+
if (runningLaunchJson === null)
|
|
39
|
+
return false;
|
|
40
|
+
const running = JSON.parse(runningLaunchJson);
|
|
41
|
+
const next = JSON.parse(nextLaunchJson);
|
|
42
|
+
if (!Array.isArray(running.argv) || running.env === undefined || !Array.isArray(next.argv) || next.env === undefined)
|
|
43
|
+
return false;
|
|
44
|
+
return launchRecipeKey(running) === launchRecipeKey(next);
|
|
45
|
+
}
|
|
@@ -5,9 +5,9 @@ import { cliClient } from '../../commands/api-client.js';
|
|
|
5
5
|
import { hasProviderCredential } from '../provider-credential.js';
|
|
6
6
|
import { piAgentDir } from './package-health.js';
|
|
7
7
|
import { PROVIDER_ENV_KEYS } from './spawn-env.js';
|
|
8
|
-
let
|
|
9
|
-
/** The daemon, which owns the rows, registers its row-backed
|
|
10
|
-
export function registerGateCredentialStore(
|
|
8
|
+
let daemonSnapshot;
|
|
9
|
+
/** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
|
|
10
|
+
export function registerGateCredentialStore(snapshot) { daemonSnapshot = snapshot; }
|
|
11
11
|
/** Reads through to `store` once per provider (and one `list`) for the life of this wrapper. `ModelRuntime.create` asks for the same
|
|
12
12
|
* provider's credential many times while it builds its availability snapshot, and each ask is a database round trip. Writes are refused:
|
|
13
13
|
* this view exists for one read-only check. */
|
|
@@ -37,7 +37,7 @@ export async function hasConfiguredProviderCredential(profileEnvNames) {
|
|
|
37
37
|
}
|
|
38
38
|
const agentDir = piAgentDir();
|
|
39
39
|
const runtime = await ModelRuntime.create({
|
|
40
|
-
credentials: readOnceStore(
|
|
40
|
+
credentials: daemonSnapshot === undefined ? readOnceStore(new ApiCredentialStore(() => cliClient(), true)) : await daemonSnapshot(),
|
|
41
41
|
modelsPath: join(agentDir, 'models.json'),
|
|
42
42
|
});
|
|
43
43
|
return await hasProviderCredential(runtime, new ModelRegistry(runtime));
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// src/core/runtime/runner/blaxel/release-image.ts — the release image: one Blaxel sandbox image per crouter release, with the release unpacked in it.
|
|
2
|
+
//
|
|
3
|
+
// Without it every fresh sandbox of an environment with no recipe starts from `blaxel/base-image`, then at boot installs ripgrep and downloads,
|
|
4
|
+
// checks and unpacks the 48 MiB release (scripts/sandbox-bootstrap.sh). The release image carries all of that, so `sandbox-bootstrap.sh` finds
|
|
5
|
+
// `/opt/crtr/releases/<version>` complete and skips both. It is built where the release is published (the fleet-deploy `build` job for the gate's
|
|
6
|
+
// workspace, `accept` for production's: scripts/sandbox-release-image.mjs) from the same `runtime.tar.gz` the bootstrap would download, and found by
|
|
7
|
+
// the control plane through a pointer object next to the tarball, `releases/<version>/sandbox-image.json`. No pointer means no image: the launch
|
|
8
|
+
// falls back to the stock image and the download, as before.
|
|
9
|
+
//
|
|
10
|
+
// The image holds no secret and nothing per-person or per-environment (plugins and the start bundle depend on the person and arrive at boot).
|
|
11
|
+
// Daemon-free: the CI script imports this from `dist/`.
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { copyFileSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { buildImage, NODE_BASE_IMAGE, removeBuildDir, RUN_USER, SANDBOX_API_IMAGE } from './image-build.js';
|
|
17
|
+
/** Where the bootstrap keeps releases. Keep in step with `ROOT` in scripts/sandbox-bootstrap.sh. */
|
|
18
|
+
export const RELEASES_DIR = '/opt/crtr/releases';
|
|
19
|
+
/** Written into an unpacked release by the bootstrap and by this image: the sha256 of the tarball it came from. The bootstrap trusts a present release only when this equals the sha the wake names. */
|
|
20
|
+
export const RELEASE_SHA_FILE = '.sha256';
|
|
21
|
+
/** Written last into an unpacked release: it is complete. */
|
|
22
|
+
export const RELEASE_COMPLETE_FILE = '.complete';
|
|
23
|
+
export const RELEASE_TARBALL_FILE = 'runtime.tar.gz';
|
|
24
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
25
|
+
const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/;
|
|
26
|
+
/** The pointer object's key in the release bucket, beside `runtime.tar.gz` and its sha256. */
|
|
27
|
+
export const releaseImageKey = (version) => `releases/${version}/sandbox-image.json`;
|
|
28
|
+
/** The Blaxel image name of a release: `0.3.668-delivery.1` -> `crtr-release-0-3-668-delivery-1`. Every release has its own image, so a release's image is deleted by name. */
|
|
29
|
+
export function releaseImageName(version) {
|
|
30
|
+
if (!VERSION.test(version))
|
|
31
|
+
throw new Error(`${JSON.stringify(version)} is not a release version`);
|
|
32
|
+
const name = `crtr-release-${version.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
|
33
|
+
if (name.length > 63)
|
|
34
|
+
throw new Error(`image name ${name} is longer than 63 characters`);
|
|
35
|
+
return name;
|
|
36
|
+
}
|
|
37
|
+
/** The Dockerfile of a release image. Pure. Two stages: the release is unpacked in the first, so the tarball is in no layer of the final image.
|
|
38
|
+
* The base is the recipe image's (node, sandbox-api, the `crtr` user), plus `ripgrep` (pi's grep tool) and `python3` (the stock image has it). */
|
|
39
|
+
export function releaseImageDockerfile(version, sha256) {
|
|
40
|
+
if (!SHA256.test(sha256))
|
|
41
|
+
throw new Error('sha256 must be 64 lowercase hex characters');
|
|
42
|
+
releaseImageName(version); // validates the version; it is spliced into shell below
|
|
43
|
+
const dir = `${RELEASES_DIR}/${version}`;
|
|
44
|
+
return [
|
|
45
|
+
`FROM ${NODE_BASE_IMAGE} AS release`,
|
|
46
|
+
`COPY ${RELEASE_TARBALL_FILE} /tmp/${RELEASE_TARBALL_FILE}`,
|
|
47
|
+
`RUN mkdir -p ${dir} && tar -xzf /tmp/${RELEASE_TARBALL_FILE} -C ${dir} && echo ${sha256} > ${dir}/${RELEASE_SHA_FILE} && : > ${dir}/${RELEASE_COMPLETE_FILE}`,
|
|
48
|
+
'',
|
|
49
|
+
`FROM ${NODE_BASE_IMAGE}`,
|
|
50
|
+
'RUN apk add --no-cache bash git curl ripgrep python3',
|
|
51
|
+
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
52
|
+
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${RUN_USER} /run/crtr /var/lib/crtr /work`,
|
|
53
|
+
'COPY --from=release /opt/crtr /opt/crtr',
|
|
54
|
+
'WORKDIR /work',
|
|
55
|
+
'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',
|
|
56
|
+
'',
|
|
57
|
+
].join('\n');
|
|
58
|
+
}
|
|
59
|
+
export function releaseImagePointerText(pointer) {
|
|
60
|
+
return `${JSON.stringify(pointer)}\n`;
|
|
61
|
+
}
|
|
62
|
+
/** The image a pointer names for `release` and the tarball `sha256` the wake carries. Throws on a malformed pointer, one for another release, or one built from another tarball: none is a reason to launch silently from the stock image. */
|
|
63
|
+
export function parseReleaseImagePointer(text, release, sha256) {
|
|
64
|
+
let value;
|
|
65
|
+
try {
|
|
66
|
+
value = JSON.parse(text);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new Error(`${releaseImageKey(release)} is not JSON`);
|
|
70
|
+
}
|
|
71
|
+
const pointer = value;
|
|
72
|
+
if (pointer === null || typeof pointer !== 'object' || typeof pointer.release !== 'string' || typeof pointer.sha256 !== 'string' || typeof pointer.image !== 'string' || pointer.image === '') {
|
|
73
|
+
throw new Error(`${releaseImageKey(release)} must hold {release, sha256, image}`);
|
|
74
|
+
}
|
|
75
|
+
if (pointer.release !== release)
|
|
76
|
+
throw new Error(`${releaseImageKey(release)} names release ${pointer.release}`);
|
|
77
|
+
if (pointer.sha256 !== sha256)
|
|
78
|
+
throw new Error(`${releaseImageKey(release)} was built from tarball ${pointer.sha256}, not ${sha256}`);
|
|
79
|
+
return pointer.image;
|
|
80
|
+
}
|
|
81
|
+
/** Builds the release's image in the workspace `config` names and returns its pointer. */
|
|
82
|
+
export async function buildReleaseImage(config, input, options = {}) {
|
|
83
|
+
const actual = createHash('sha256').update(readFileSync(input.tarball)).digest('hex');
|
|
84
|
+
if (actual !== input.sha256)
|
|
85
|
+
throw new Error(`${input.tarball} has sha256 ${actual}, not ${input.sha256}`);
|
|
86
|
+
const dir = mkdtempSync(join(tmpdir(), 'crtr-release-image-'));
|
|
87
|
+
try {
|
|
88
|
+
copyFileSync(input.tarball, join(dir, RELEASE_TARBALL_FILE));
|
|
89
|
+
writeFileSync(join(dir, 'Dockerfile'), releaseImageDockerfile(input.release, input.sha256));
|
|
90
|
+
const built = await buildImage(config, releaseImageName(input.release), dir, options);
|
|
91
|
+
return { pointer: { release: input.release, sha256: input.sha256, image: built.ref }, built };
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
removeBuildDir(dir);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// src/core/runtime/runner/blaxel/runner.ts — the Blaxel runner (design-fleet, Components: Runner; C-A2).
|
|
2
|
+
//
|
|
3
|
+
// One sandbox per node attempt (`executions.sandbox_name`, `<node id>-<attempt>`), one process per execution
|
|
4
|
+
// named `broker-<execution id>`. That process runs the bootstrap, which installs the release and runs
|
|
5
|
+
// `crtr-sandbox-start`; the start script stays as the broker's parent. The runner never reads the sandbox's
|
|
6
|
+
// own status as the freeze signal: a frozen broker reads `running` from the process status. It reads the
|
|
7
|
+
// sandbox `state` (STANDBY while frozen; reading it does not wake the sandbox) only in `sandboxState`, for
|
|
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
|
+
import { mintExecutionToken } from '../../../canvas/node-tokens.js';
|
|
11
|
+
import { BlaxelApiError, isWorkloadUnavailable } from './client.js';
|
|
12
|
+
/** The broker listens here inside the sandbox; the private preview forwards it (`wss://<preview>/view`). */
|
|
13
|
+
export const BROKER_VIEW_PORT = 4180;
|
|
14
|
+
const VIEW_PREVIEW = 'view';
|
|
15
|
+
/** Where the bootstrap keeps the newest release it installed; the wake script is run from here. */
|
|
16
|
+
export const WAKE_COMMAND = 'node /opt/crtr/current/scripts/sandbox-start.mjs --wake';
|
|
17
|
+
/** `crtr-sandbox-start --wake` exits with this when no broker of the execution runs. */
|
|
18
|
+
export const EXIT_NO_BROKER = 3;
|
|
19
|
+
/** A failing start script prints a last line `crtr-sandbox-start: failed <reason>`; `status` reports the reason. */
|
|
20
|
+
export const FAILURE_LINE = /^crtr-sandbox-start: failed (\S+)/m;
|
|
21
|
+
/** How much of a failed process's output `status` carries: enough for the boot phase lines and the error that ended the start. */
|
|
22
|
+
const FAILURE_OUTPUT_CHARS = 2000;
|
|
23
|
+
export const brokerProcessName = (executionId) => `broker-${executionId}`;
|
|
24
|
+
export const sandboxNameFor = (execution) => execution.sandboxName ?? `${execution.nodeId}-${execution.attempt}`;
|
|
25
|
+
/** Every execution of a node that ran in a sandbox has one, named by `sandboxNameFor`: `start` creates it under that name and nothing
|
|
26
|
+
* writes `executions.sandbox_name`, so the column is null on every row and the name is `<node id>-<attempt>`. */
|
|
27
|
+
async function defaultSandboxNames(nodeId) {
|
|
28
|
+
const rows = await (await openDb()).prepare("SELECT execution_id, attempt, sandbox_name FROM executions WHERE node_id = ? AND runner = 'blaxel'").all(nodeId);
|
|
29
|
+
return [...new Set(rows.map((row) => sandboxNameFor({ executionId: row.execution_id, nodeId, attempt: Number(row.attempt), sandboxName: row.sandbox_name })))];
|
|
30
|
+
}
|
|
31
|
+
function failureOf(process) {
|
|
32
|
+
const text = `${process.logs}\n${process.stderr}\n${process.stdout}`;
|
|
33
|
+
const output = (process.stderr || process.logs || process.stdout || '').trim().slice(-FAILURE_OUTPUT_CHARS);
|
|
34
|
+
return { state: 'failed', reason: FAILURE_LINE.exec(text)?.[1] ?? 'start_failed', code: process.exitCode, ...(output === '' ? {} : { output }) };
|
|
35
|
+
}
|
|
36
|
+
export function createBlaxelRunner(deps) {
|
|
37
|
+
const { client } = deps;
|
|
38
|
+
const stopGraceMs = (deps.stopGraceS ?? 10) * 1000;
|
|
39
|
+
const previewTokens = new Map();
|
|
40
|
+
async function sandboxOf(execution) {
|
|
41
|
+
return await client.getSandbox(sandboxNameFor(execution));
|
|
42
|
+
}
|
|
43
|
+
/** Stops any broker of the execution still in the sandbox (SIGTERM, then SIGKILL after the grace) and reports whether none is left. */
|
|
44
|
+
async function brokerGone(sandbox, executionId) {
|
|
45
|
+
if (!/^[A-Za-z0-9_-]+$/.test(executionId))
|
|
46
|
+
throw new Error(`execution id ${JSON.stringify(executionId)} is not safe to name in a command`);
|
|
47
|
+
// A broker's argv is `broker-cli.js ... --epoch <execution> <node>`; `[b]` keeps the pattern from matching this command's own command line.
|
|
48
|
+
const graceS = Math.max(1, Math.ceil(stopGraceMs / 1000));
|
|
49
|
+
const command = `p='[b]roker-cli\\.js .*--epoch ${executionId}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${graceS * 5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;
|
|
50
|
+
return (await client.exec(sandbox, `stop-${executionId}-${Date.now()}`, command, graceS + 20)).exitCode === 0;
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
kind: 'blaxel',
|
|
54
|
+
async start(input) {
|
|
55
|
+
const context = await deps.launchContext(input);
|
|
56
|
+
const name = sandboxNameFor(input);
|
|
57
|
+
// "Name taken" means a previous attempt created it: the client adopts it.
|
|
58
|
+
const sandbox = await client.createSandbox({ name, image: context.image, memoryMb: context.memoryMb, ports: [{ name: VIEW_PREVIEW, target: BROKER_VIEW_PORT }] });
|
|
59
|
+
const process = brokerProcessName(input.executionId);
|
|
60
|
+
// A repeated call (a reconciler whose lease was taken) finds the process and adopts it: no second token.
|
|
61
|
+
const existing = await client.getProcess(sandbox, process);
|
|
62
|
+
if (existing?.status === 'running')
|
|
63
|
+
return { pid: null, exited: null };
|
|
64
|
+
await client.ensurePreview(name, VIEW_PREVIEW, BROKER_VIEW_PORT);
|
|
65
|
+
const token = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
|
|
66
|
+
// Reserved names win over a secret that tries to override them.
|
|
67
|
+
const env = { ...context.secrets,
|
|
68
|
+
CRTR_API_URL: context.apiUrl, CRTR_EXECUTION_ID: input.executionId, CRTR_NODE_TOKEN: token,
|
|
69
|
+
CRTR_RELEASE: input.release, CRTR_RELEASE_URL: context.releaseUrl, CRTR_RELEASE_SHA256: context.releaseSha256 };
|
|
70
|
+
await client.startProcess(sandbox, { name: process, command: deps.bootstrap(), env, waitForCompletion: false });
|
|
71
|
+
return { pid: null, exited: null };
|
|
72
|
+
},
|
|
73
|
+
async wake(execution) {
|
|
74
|
+
const sandbox = await sandboxOf(execution);
|
|
75
|
+
if (sandbox === null)
|
|
76
|
+
return 'no_broker';
|
|
77
|
+
// One process call thaws the sandbox and signals the broker; it carries no token.
|
|
78
|
+
try {
|
|
79
|
+
const result = await client.exec(sandbox, `wake-${execution.executionId}-${Date.now()}`, `${WAKE_COMMAND} ${execution.executionId}`, 30);
|
|
80
|
+
if (result.exitCode === 0)
|
|
81
|
+
return 'signalled';
|
|
82
|
+
if (result.exitCode === EXIT_NO_BROKER)
|
|
83
|
+
return 'no_broker';
|
|
84
|
+
throw new Error(`wake of ${execution.executionId} failed (exit ${result.exitCode}): ${(result.stderr || result.logs).slice(0, 300)}`);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (isWorkloadUnavailable(error))
|
|
88
|
+
return 'no_broker';
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
async stop(execution, _options) {
|
|
93
|
+
try {
|
|
94
|
+
const sandbox = await sandboxOf(execution);
|
|
95
|
+
if (sandbox === null)
|
|
96
|
+
return { confirmed: true };
|
|
97
|
+
const name = brokerProcessName(execution.executionId);
|
|
98
|
+
const running = async () => (await client.getProcess(sandbox, name))?.status === 'running';
|
|
99
|
+
if (await running()) {
|
|
100
|
+
// The tracked process is the start script (the bootstrap execs into it): SIGTERM reaches the broker through its handler.
|
|
101
|
+
await client.stopProcess(sandbox, name);
|
|
102
|
+
const deadline = Date.now() + stopGraceMs;
|
|
103
|
+
while (Date.now() < deadline && await running())
|
|
104
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
105
|
+
if (await running())
|
|
106
|
+
await client.killProcess(sandbox, name);
|
|
107
|
+
if (await running())
|
|
108
|
+
return { confirmed: false };
|
|
109
|
+
}
|
|
110
|
+
// A killed start script leaves its broker behind, so the answer is the broker's absence, not the process status.
|
|
111
|
+
return { confirmed: await brokerGone(sandbox, execution.executionId) };
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (isWorkloadUnavailable(error))
|
|
115
|
+
return { confirmed: true };
|
|
116
|
+
return { confirmed: false, error: error instanceof Error ? error : new Error(String(error)) };
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
async status(execution, options) {
|
|
120
|
+
try {
|
|
121
|
+
const sandbox = await sandboxOf(execution);
|
|
122
|
+
if (sandbox === null)
|
|
123
|
+
return { state: 'gone' };
|
|
124
|
+
// An idle broker's sandbox is frozen or freezing, and a request through it counts as activity that keeps it awake:
|
|
125
|
+
// the control plane's answer that the sandbox exists is all that is asked. A broker lost inside it is found at the next wake.
|
|
126
|
+
if (options?.idle === true)
|
|
127
|
+
return { state: 'running', pid: null };
|
|
128
|
+
const process = await client.getProcess(sandbox, brokerProcessName(execution.executionId));
|
|
129
|
+
if (process === null)
|
|
130
|
+
return { state: 'gone' };
|
|
131
|
+
if (process.status === 'running')
|
|
132
|
+
return { state: 'running', pid: null };
|
|
133
|
+
if (process.status === 'failed' || (process.status === 'completed' && process.exitCode !== 0))
|
|
134
|
+
return failureOf(process);
|
|
135
|
+
return { state: 'gone' };
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (isWorkloadUnavailable(error))
|
|
139
|
+
return { state: 'gone' };
|
|
140
|
+
return { state: 'unknown', error: error instanceof Error ? error.message : String(error) };
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
async delete(nodeId) {
|
|
144
|
+
for (const name of await (deps.sandboxNamesForNode ?? defaultSandboxNames)(nodeId))
|
|
145
|
+
await client.deleteSandbox(name);
|
|
146
|
+
},
|
|
147
|
+
async deleteExecution(execution) {
|
|
148
|
+
await client.deleteSandbox(sandboxNameFor(execution));
|
|
149
|
+
},
|
|
150
|
+
async viewerAddress(execution) {
|
|
151
|
+
const name = sandboxNameFor(execution);
|
|
152
|
+
const cached = previewTokens.get(name);
|
|
153
|
+
if (cached && cached.expiresAt - Date.now() > 5 * 60_000)
|
|
154
|
+
return viewer(cached.url, cached.token);
|
|
155
|
+
const url = await client.ensurePreview(name, VIEW_PREVIEW, BROKER_VIEW_PORT);
|
|
156
|
+
const expires = new Date(Date.now() + 60 * 60_000);
|
|
157
|
+
const { token } = await client.createPreviewToken(name, VIEW_PREVIEW, expires);
|
|
158
|
+
previewTokens.set(name, { url, token, expiresAt: expires.getTime() });
|
|
159
|
+
return viewer(url, token);
|
|
160
|
+
},
|
|
161
|
+
/** The sandbox `state` (`STANDBY` while frozen), read without waking it. Null when the sandbox is gone. Measurement only. */
|
|
162
|
+
async sandboxState(execution) {
|
|
163
|
+
return (await sandboxOf(execution))?.state ?? null;
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function viewer(previewUrl, token) {
|
|
168
|
+
return { kind: 'wss', url: `${previewUrl.replace(/^https:/, 'wss:')}/view`, headers: { 'x-blaxel-preview-token': token } };
|
|
169
|
+
}
|
|
170
|
+
export { BlaxelApiError };
|
|
@@ -16,7 +16,9 @@ export const MACHINE_CALL_TIMEOUT_S = {
|
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
18
18
|
const REREAD_MS = 1000;
|
|
19
|
-
|
|
19
|
+
/** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
|
|
20
|
+
* so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
|
|
21
|
+
export async function enqueueMachineCall(environmentId, op, args) {
|
|
20
22
|
const callId = randomUUID();
|
|
21
23
|
const now = new Date().toISOString();
|
|
22
24
|
const queued = await withCanvasWrite(async (db) => {
|
|
@@ -29,6 +31,13 @@ export async function callMachine(environmentId, op, args, options = {}) {
|
|
|
29
31
|
});
|
|
30
32
|
if (!queued)
|
|
31
33
|
throw new MachineOfflineError(environmentId, 'no live link');
|
|
34
|
+
return callId;
|
|
35
|
+
}
|
|
36
|
+
export async function callMachine(environmentId, op, args, options = {}) {
|
|
37
|
+
return await awaitMachineCall(environmentId, op, await enqueueMachineCall(environmentId, op, args), options);
|
|
38
|
+
}
|
|
39
|
+
/** Wait for the holder's answer to a queued call. */
|
|
40
|
+
export async function awaitMachineCall(environmentId, op, callId, options = {}) {
|
|
32
41
|
const deadline = Date.now() + (options.timeoutMs ?? MACHINE_CALL_TIMEOUT_S[op] * 1000);
|
|
33
42
|
// A settle signalled before the subscription is in place is caught by the first read below, which comes after it.
|
|
34
43
|
let wake;
|
|
@@ -86,7 +95,7 @@ async function waitForCall(environmentId, op, callId, deadline, rereadMs, pause)
|
|
|
86
95
|
/** Fail an open call as `machine_lost` when a holder claimed it, else `machine_offline` (never sent). Returns the claimed generation
|
|
87
96
|
* the row had (null: never claimed), or undefined when the call was already settled, which the caller reads again. */
|
|
88
97
|
async function failOpenCall(callId, message) {
|
|
89
|
-
const failed = await (await openDb()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
|
|
98
|
+
const failed = await (await openDb()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
|
|
90
99
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
91
100
|
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`)
|
|
92
101
|
.get(new Date().toISOString(), JSON.stringify({ code: 'machine_offline', message, sent: false }), JSON.stringify({ code: 'machine_lost', message }), callId);
|