@north-light/cli 0.3.672 → 0.3.673
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/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/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,120 @@
|
|
|
1
|
+
// `GET /v1/executions/:execution_id/start` — everything a sandbox's start script needs to build the broker's local files.
|
|
2
|
+
// Authorized in the handler: the node token's node must own the execution, and the execution must still be starting or running
|
|
3
|
+
// (D76: a late start by a reconciler whose lease was taken fails here).
|
|
4
|
+
import { ApiError } from '../../../api/errors.js';
|
|
5
|
+
import { getNode } from '../../../core/canvas/canvas.js';
|
|
6
|
+
import { openDb } from '../../../core/canvas/db.js';
|
|
7
|
+
import { blobStore } from '../../../core/blobs/index.js';
|
|
8
|
+
import { presignGet, releaseSignerFromEnv } from '../../../core/secrets/blaxel-launch.js';
|
|
9
|
+
import { grantedProviderIds, isProviderBundleRow } from '../../../core/grants/mirror.js';
|
|
10
|
+
import { profileMetadataEnv } from '../../../core/runtime/spawn-env.js';
|
|
11
|
+
import { localEnvironmentSecrets } from '../../../core/secrets/environment-owner.js';
|
|
12
|
+
import { environmentOfNode, recipeOf } from '../environment-of.js';
|
|
13
|
+
import { mintInstallationToken } from './git-credential.js';
|
|
14
|
+
export async function plugins(person, app) {
|
|
15
|
+
const db = await openDb();
|
|
16
|
+
// A plugin is installed into an app: the node gets the rows of its own app, for every profile of that app.
|
|
17
|
+
const byName = new Map((await db.prepare(`SELECT owner_key, name, version, source_marketplace, source_path FROM scope_plugins
|
|
18
|
+
WHERE person = ? AND enabled = 1 AND owner_key = ? ORDER BY name`).all(person, app)).map((row) => [row.name, row]));
|
|
19
|
+
const out = [];
|
|
20
|
+
const granted = await grantedProviderIds(person);
|
|
21
|
+
for (const row of byName.values()) {
|
|
22
|
+
// A directory provider bundle has no source to hand over: the sandbox's CLI gets its command descriptions from `GET /v1/providers/tools` and calls through `POST /v1/provider/call`.
|
|
23
|
+
if (isProviderBundleRow(row, granted))
|
|
24
|
+
continue;
|
|
25
|
+
if (row.source_path !== null) {
|
|
26
|
+
out.push({ name: row.name, source: { path: row.source_path }, version: row.version });
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (row.source_marketplace === null)
|
|
30
|
+
throw new ApiError(500, 'plugin_source_missing', `plugin ${row.name} names neither a marketplace nor a path`);
|
|
31
|
+
const market = await db.prepare('SELECT url, ref FROM scope_marketplaces WHERE person = ? AND owner_key = ? AND name = ?').get(person, row.owner_key, row.source_marketplace);
|
|
32
|
+
out.push({ name: row.name, source: { marketplace: { url: market?.url ?? null, ref: market?.ref ?? null } }, version: row.version });
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
const ARCHIVE_URL_TTL_S = 900;
|
|
37
|
+
/** The node's imported archive while its blob exists: a signed URL and the run's path map (the run is in the blob key). Unpacking is a fact about a sandbox
|
|
38
|
+
* (the start script keeps its own marker), so every start names the archive, a replacement sandbox's included; `unpacked_at` stays the first unpack's time,
|
|
39
|
+
* which storage maintenance counts its 30 days from. An archive deleted after that is no longer named and a fresh sandbox starts like any cloud node; one
|
|
40
|
+
* that is gone before any sandbox unpacked it is an error, never a silent empty start. */
|
|
41
|
+
async function importFiles(nodeId) {
|
|
42
|
+
const db = await openDb();
|
|
43
|
+
const row = await db.prepare('SELECT blob_key, unpacked_at FROM import_node_files WHERE node = ?').get(nodeId);
|
|
44
|
+
if (row === undefined)
|
|
45
|
+
return null;
|
|
46
|
+
if (!(await (await blobStore()).list(row.blob_key)).includes(row.blob_key)) {
|
|
47
|
+
if (row.unpacked_at !== null)
|
|
48
|
+
return null;
|
|
49
|
+
throw new ApiError(500, 'import_files_missing', `the imported archive ${row.blob_key} of ${nodeId} is gone and no sandbox unpacked it`);
|
|
50
|
+
}
|
|
51
|
+
const run = /^imports\/([^/]+)\/node-files\//.exec(row.blob_key)?.[1];
|
|
52
|
+
if (run === undefined)
|
|
53
|
+
throw new ApiError(500, 'import_files_invalid', `import_node_files names ${row.blob_key} for ${nodeId}, which is no imports/<run>/node-files key`);
|
|
54
|
+
const map = await db.prepare("SELECT source_value, target_value FROM import_id_map WHERE run_id = ? AND kind = 'path' ORDER BY source_value").all(run);
|
|
55
|
+
return { url: presignGet(releaseSignerFromEnv(), row.blob_key, ARCHIVE_URL_TTL_S), path_map: map.map((m) => ({ from: m.source_value, to: m.target_value })) };
|
|
56
|
+
}
|
|
57
|
+
async function ownedExecution(ctx) {
|
|
58
|
+
const { principal } = ctx;
|
|
59
|
+
if (principal.class !== 'broker')
|
|
60
|
+
throw new ApiError(403, 'broker_only', 'this route is called with a node token');
|
|
61
|
+
const executionId = ctx.params['execution_id'] ?? '';
|
|
62
|
+
const db = await openDb();
|
|
63
|
+
const exec = await db.prepare('SELECT node_id, state FROM executions WHERE execution_id = ?').get(executionId);
|
|
64
|
+
if (exec === undefined || exec.node_id !== principal.node)
|
|
65
|
+
throw new ApiError(403, 'not_your_execution', `execution ${executionId} is not an execution of this node`);
|
|
66
|
+
if (exec.state !== 'launching' && exec.state !== 'running')
|
|
67
|
+
throw new ApiError(403, 'execution_ended', `execution ${executionId} is ${exec.state}`);
|
|
68
|
+
return principal.node;
|
|
69
|
+
}
|
|
70
|
+
/** The start script reports its unpack; a second report, or a node with no row, changes nothing. */
|
|
71
|
+
async function handleImportUnpacked(ctx) {
|
|
72
|
+
const node = await ownedExecution(ctx);
|
|
73
|
+
const db = await openDb();
|
|
74
|
+
await db.prepare('UPDATE import_node_files SET unpacked_at = ? WHERE node = ? AND unpacked_at IS NULL').run(new Date().toISOString(), node);
|
|
75
|
+
return { status: 200, body: {} };
|
|
76
|
+
}
|
|
77
|
+
/** The start bundle of an execution: what a sandbox's start script reads, or the control plane carries to a machine in its `start` call. */
|
|
78
|
+
export async function buildStartBundle(input) {
|
|
79
|
+
const db = await openDb();
|
|
80
|
+
const node = await getNode(input.nodeId);
|
|
81
|
+
if (node === null)
|
|
82
|
+
throw new ApiError(404, 'node_not_found', `no node ${input.nodeId}`);
|
|
83
|
+
const settings = await db.prepare('SELECT plugins_revision FROM person_settings WHERE person = ?').get(input.sub);
|
|
84
|
+
const environmentId = await environmentOfNode(node.profile_id ?? null);
|
|
85
|
+
const recipe = await recipeOf(environmentId);
|
|
86
|
+
// The commit author comes from the person's GitHub link; only an environment with recipe repositories has one to ask for.
|
|
87
|
+
const repositories = recipe?.repositories.map((r) => r.github_full_name) ?? [];
|
|
88
|
+
const gitIdentity = repositories.length === 0 ? null : (await mintInstallationToken(input.sub, repositories)).author;
|
|
89
|
+
const body = {
|
|
90
|
+
launch: JSON.parse(input.launchJson),
|
|
91
|
+
node: { id: node.node_id, app: input.app, cwd: node.cwd, profile: node.profile_id ?? null, isolated: node.isolated === true, environment_id: environmentId },
|
|
92
|
+
recipe,
|
|
93
|
+
git_identity: gitIdentity,
|
|
94
|
+
plugins_revision: settings === undefined ? 0 : Number(settings.plugins_revision),
|
|
95
|
+
plugins: await plugins(input.sub, input.app),
|
|
96
|
+
import_node_files: await importFiles(node.node_id),
|
|
97
|
+
// The Mac has no database: the control plane reads the environment's rows here, as `buildBrokerEnv` does for a process on this host.
|
|
98
|
+
...(input.runner === 'machine' ? { machine_env: { ...profileMetadataEnv(node.profile_id ?? null), ...await localEnvironmentSecrets(node.profile_id ?? null, input.app) } } : {}),
|
|
99
|
+
};
|
|
100
|
+
return body;
|
|
101
|
+
}
|
|
102
|
+
async function handleStart(ctx) {
|
|
103
|
+
const { principal } = ctx;
|
|
104
|
+
if (principal.class !== 'broker')
|
|
105
|
+
throw new ApiError(403, 'broker_only', 'the start bundle is read with a node token');
|
|
106
|
+
const executionId = ctx.params['execution_id'] ?? '';
|
|
107
|
+
const db = await openDb();
|
|
108
|
+
const exec = await db.prepare('SELECT node_id, state, launch_json, runner FROM executions WHERE execution_id = ?').get(executionId);
|
|
109
|
+
if (exec === undefined || exec.node_id !== principal.node)
|
|
110
|
+
throw new ApiError(403, 'not_your_execution', `execution ${executionId} is not an execution of this node`);
|
|
111
|
+
if (exec.state !== 'launching' && exec.state !== 'running')
|
|
112
|
+
throw new ApiError(403, 'execution_ended', `execution ${executionId} is ${exec.state}`);
|
|
113
|
+
if (exec.launch_json === null)
|
|
114
|
+
throw new ApiError(409, 'launch_missing', `execution ${executionId} carries no launch recipe`);
|
|
115
|
+
return { status: 200, body: await buildStartBundle({ nodeId: principal.node, app: principal.app, sub: principal.sub, launchJson: exec.launch_json, runner: exec.runner }) };
|
|
116
|
+
}
|
|
117
|
+
export const executionStartRoutes = [
|
|
118
|
+
{ method: 'GET', pattern: '/v1/executions/:execution_id/start', handler: handleStart },
|
|
119
|
+
{ method: 'POST', pattern: '/v1/executions/:execution_id/import-unpacked', handler: handleImportUnpacked },
|
|
120
|
+
];
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { appendRotatingRecord } from '../../../core/log.js';
|
|
3
|
+
import { jobDir } from '../../../core/canvas/paths.js';
|
|
4
|
+
import { parseNodeTelemetryRecord, writeNodeTelemetryRecord } from './telemetry-record.js';
|
|
5
|
+
import { openDb } from '../../../core/canvas/db.js';
|
|
6
|
+
import { reportDocumentBody } from '../../../core/feed/inbox.js';
|
|
7
|
+
import { reportRefNodeId } from '../../../shared/inbox-entry-body.js';
|
|
8
|
+
import { writeNodeRecap } from '../../../core/canvas/node-recap.js';
|
|
9
|
+
import { markStopSignal, consumeStopSignals, clearStopSignals } from '../../../core/runtime/stop-signals.js';
|
|
10
|
+
import { notFound, usage } from '../../../core/errors.js';
|
|
11
|
+
import { blobStore } from '../../../core/blobs/index.js';
|
|
12
|
+
import { requireCurrentExecution } from './broker-recovery.js';
|
|
13
|
+
async function body(ctx) {
|
|
14
|
+
if (ctx.body === null || typeof ctx.body !== 'object' || Array.isArray(ctx.body))
|
|
15
|
+
throw usage('node record requires a JSON object');
|
|
16
|
+
const value = ctx.body;
|
|
17
|
+
await requireCurrentExecution(ctx.params['id'], value['expected_execution_id']);
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function text(value, name) {
|
|
21
|
+
if (typeof value !== 'string')
|
|
22
|
+
throw usage(`${name} must be a string`);
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
/** The rows of `upload_uses` the node's run holds a blob for: where the broker puts the file, the hash it is named by,
|
|
26
|
+
* and its blob key (`attachments/<run root node>/<sha256>`). */
|
|
27
|
+
export async function runAttachments(nodeId) {
|
|
28
|
+
const db = await openDb();
|
|
29
|
+
const node = await db.prepare('SELECT run_id FROM nodes WHERE node_id = ?').get(nodeId);
|
|
30
|
+
if (node === undefined)
|
|
31
|
+
throw notFound('node not found');
|
|
32
|
+
if (node.run_id === null)
|
|
33
|
+
return [];
|
|
34
|
+
const rows = await db.prepare('SELECT path, blob_key FROM upload_uses WHERE run_id = ? AND blob_key IS NOT NULL ORDER BY path').all(node.run_id);
|
|
35
|
+
return rows.map((row) => ({ ...row, sha256: row.blob_key.slice(row.blob_key.lastIndexOf('/') + 1) }));
|
|
36
|
+
}
|
|
37
|
+
export const nodeRecordRoutes = [
|
|
38
|
+
{ method: 'POST', pattern: '/v1/nodes/:id/records/log', handler: async (ctx) => {
|
|
39
|
+
const record = text((await body(ctx))['record'], 'record');
|
|
40
|
+
return { status: 200, body: { appended: appendRotatingRecord(join(jobDir(ctx.params['id']), 'log.jsonl'), record) } };
|
|
41
|
+
} },
|
|
42
|
+
{ method: 'PUT', pattern: '/v1/nodes/:id/records/telemetry', handler: async (ctx) => {
|
|
43
|
+
writeNodeTelemetryRecord(ctx.params['id'], parseNodeTelemetryRecord(await body(ctx)));
|
|
44
|
+
return { status: 204 };
|
|
45
|
+
} },
|
|
46
|
+
{ method: 'GET', pattern: '/v1/nodes/:id/attachments', handler: async (ctx) => ({ status: 200, body: { attachments: (await runAttachments(ctx.params['id'])).map(({ path, sha256 }) => ({ path, sha256 })) } }) },
|
|
47
|
+
{ method: 'GET', pattern: '/v1/nodes/:id/attachments/:sha256', handler: async (ctx) => {
|
|
48
|
+
const sha256 = ctx.params['sha256'];
|
|
49
|
+
const file = (await runAttachments(ctx.params['id'])).find((use) => use.sha256 === sha256);
|
|
50
|
+
if (file === undefined)
|
|
51
|
+
throw notFound('attachment not found');
|
|
52
|
+
const bytes = await (await blobStore()).get(file.blob_key);
|
|
53
|
+
if (bytes === null)
|
|
54
|
+
throw notFound('attachment not found');
|
|
55
|
+
return { status: 200, rawBody: bytes, headers: { 'content-type': 'application/octet-stream' } };
|
|
56
|
+
} },
|
|
57
|
+
{ method: 'PUT', pattern: '/v1/nodes/:id/records/summaries', handler: async (ctx) => {
|
|
58
|
+
const value = await body(ctx);
|
|
59
|
+
const db = await openDb();
|
|
60
|
+
for (const [field, column] of [['tool_summaries', 'tool_summaries_json'], ['turn_replies', 'turn_replies_json']]) {
|
|
61
|
+
const record = value[field];
|
|
62
|
+
if (record === undefined)
|
|
63
|
+
continue;
|
|
64
|
+
if (record === null || typeof record !== 'object' || Array.isArray(record))
|
|
65
|
+
throw usage(`${field} must be an object`);
|
|
66
|
+
await db.prepare(`UPDATE nodes SET ${column} = ? WHERE node_id = ?`).run(JSON.stringify(record), ctx.params['id']);
|
|
67
|
+
}
|
|
68
|
+
return { status: 204 };
|
|
69
|
+
} },
|
|
70
|
+
{ method: 'PUT', pattern: '/v1/nodes/:id/records/recap', handler: async (ctx) => {
|
|
71
|
+
writeNodeRecap(ctx.params['id'], text((await body(ctx))['briefing'], 'briefing'));
|
|
72
|
+
return { status: 204 };
|
|
73
|
+
} },
|
|
74
|
+
{ method: 'GET', pattern: '/v1/nodes/:id/records/inbox', handler: async (ctx) => {
|
|
75
|
+
const nodeId = ctx.params['id'];
|
|
76
|
+
const ref = ctx.query.get('ref');
|
|
77
|
+
await requireCurrentExecution(nodeId, ctx.query.get('execution_id'));
|
|
78
|
+
if (ref === null || reportRefNodeId(ref) === undefined)
|
|
79
|
+
throw usage('ref must be a report handle');
|
|
80
|
+
const delivery = await (await openDb()).prepare(`SELECT m.object_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
81
|
+
WHERE d.destination_id = ? AND d.state = 'handed_off'
|
|
82
|
+
AND d.claim_owner = ? AND d.canceled_at IS NULL AND m.body_ref = ? LIMIT 1`)
|
|
83
|
+
.get(nodeId, ctx.query.get('execution_id'), ref);
|
|
84
|
+
if (delivery === undefined)
|
|
85
|
+
throw notFound('report was not delivered to this node');
|
|
86
|
+
const content = delivery.object_id === null ? null : await reportDocumentBody(delivery.object_id);
|
|
87
|
+
if (content === null)
|
|
88
|
+
throw notFound('report not found');
|
|
89
|
+
return { status: 200, body: { content } };
|
|
90
|
+
} },
|
|
91
|
+
{ method: 'GET', pattern: '/v1/nodes/:id/records/passive', handler: async (ctx) => {
|
|
92
|
+
const ref = ctx.query.get('ref');
|
|
93
|
+
if (ref === null || ref === '')
|
|
94
|
+
throw usage('ref must be a direct-message spill path for this node');
|
|
95
|
+
const row = await (await openDb()).prepare(`SELECT m.body_json ->> 'body_full' AS body FROM messages m JOIN deliveries d ON d.message_id = m.message_id
|
|
96
|
+
WHERE d.destination_id = ? AND m.body_ref = ? LIMIT 1`).get(ctx.params['id'], ref);
|
|
97
|
+
if (row === undefined || row.body === null)
|
|
98
|
+
throw notFound('passive message not found');
|
|
99
|
+
return { status: 200, body: { content: row.body } };
|
|
100
|
+
} },
|
|
101
|
+
{ method: 'POST', pattern: '/v1/nodes/:id/records/pushed-final', handler: async (ctx) => {
|
|
102
|
+
const value = await body(ctx);
|
|
103
|
+
if (value['action'] === 'mark')
|
|
104
|
+
markStopSignal(ctx.params['id'], 'pushedFinal', text(value['expected_execution_id'], 'expected_execution_id'));
|
|
105
|
+
else if (value['action'] === 'clear')
|
|
106
|
+
clearStopSignals(ctx.params['id']);
|
|
107
|
+
else if (value['action'] === 'consume')
|
|
108
|
+
return { status: 200, body: consumeStopSignals(ctx.params['id'], text(value['expected_execution_id'], 'expected_execution_id')) };
|
|
109
|
+
else
|
|
110
|
+
throw usage('action must be mark, clear or consume');
|
|
111
|
+
return { status: 200, body: { pushedFinal: false } };
|
|
112
|
+
} },
|
|
113
|
+
];
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { jobDir } from '../../../core/canvas/paths.js';
|
|
4
|
+
import { usage } from '../../../core/errors.js';
|
|
5
|
+
export function parseNodeTelemetryRecord(value) {
|
|
6
|
+
const { tokens_in, tokens_out, context_tokens, last_activity, model, updated_at } = value;
|
|
7
|
+
if (typeof tokens_in !== 'number' || !Number.isFinite(tokens_in) || tokens_in < 0 ||
|
|
8
|
+
typeof tokens_out !== 'number' || !Number.isFinite(tokens_out) || tokens_out < 0 ||
|
|
9
|
+
(context_tokens !== null && (typeof context_tokens !== 'number' || !Number.isFinite(context_tokens) || context_tokens < 0)) ||
|
|
10
|
+
(last_activity !== null && typeof last_activity !== 'string') ||
|
|
11
|
+
typeof model !== 'string' || typeof updated_at !== 'string' || Number.isNaN(Date.parse(updated_at))) {
|
|
12
|
+
throw usage('invalid telemetry');
|
|
13
|
+
}
|
|
14
|
+
return { tokens_in, tokens_out, context_tokens: context_tokens,
|
|
15
|
+
last_activity: last_activity, model, updated_at };
|
|
16
|
+
}
|
|
17
|
+
/** Merge nullable live gauges with the last usable node-local values. */
|
|
18
|
+
export function writeNodeTelemetryRecord(nodeId, record) {
|
|
19
|
+
const dir = jobDir(nodeId);
|
|
20
|
+
const path = join(dir, 'telemetry.json');
|
|
21
|
+
let existing = {};
|
|
22
|
+
try {
|
|
23
|
+
existing = JSON.parse(readFileSync(path, 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (!(error instanceof SyntaxError) && error.code !== 'ENOENT')
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
mkdirSync(dir, { recursive: true });
|
|
30
|
+
writeFileSync(path, JSON.stringify({ tokens_in: record.tokens_in, tokens_out: record.tokens_out,
|
|
31
|
+
context_tokens: record.context_tokens ?? existing['context_tokens'],
|
|
32
|
+
last_activity: record.last_activity ?? existing['last_activity'],
|
|
33
|
+
model: record.model || existing['model'] || '', updated_at: record.updated_at }, null, 2), 'utf8');
|
|
34
|
+
}
|
|
@@ -216,7 +216,7 @@ export class HeldLink extends EventEmitter {
|
|
|
216
216
|
}
|
|
217
217
|
async function withNotify(callId, state, result, environmentId, generation, requireCurrent) {
|
|
218
218
|
const db = await openDb();
|
|
219
|
-
const settled = await db.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at =
|
|
219
|
+
const settled = await db.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
|
|
220
220
|
WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
|
|
221
221
|
${requireCurrent ? 'AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)' : ''}`)
|
|
222
222
|
.run(state, JSON.stringify(result), new Date().toISOString(), callId, environmentId, generation, ...(requireCurrent ? [environmentId, generation] : []));
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Is a review companion still working? This is what a deferred submit waits on.
|
|
2
|
+
//
|
|
3
|
+
// Two facts, both already maintained by the runtime, and neither one enough
|
|
4
|
+
// alone:
|
|
5
|
+
//
|
|
6
|
+
// - MID-TURN — the recovery store's live-turn witness. A cleared turn reads
|
|
7
|
+
// false without consulting a node-local runtime file.
|
|
8
|
+
// - QUEUED — an undelivered non-deferred inbox entry. Comments are pushed to
|
|
9
|
+
// the companion as inbox messages, so the ordinary rhythm is: the human
|
|
10
|
+
// comments, the entry lands, the companion's turn starts a moment later.
|
|
11
|
+
// Between those two moments the busy marker is cold while the companion is
|
|
12
|
+
// unmistakably about to work, and submitting into that gap kills the edit
|
|
13
|
+
// the wait exists to protect.
|
|
14
|
+
import { readLiveTurn } from '../../core/canvas/recovery.js';
|
|
15
|
+
import { hasUnseenWakeMail } from '../../core/canvas/deliveries.js';
|
|
16
|
+
/** Is the companion inside a turn right now? */
|
|
17
|
+
export async function companionMidTurn(nodeId) {
|
|
18
|
+
return (await readLiveTurn(nodeId))?.busy ?? false;
|
|
19
|
+
}
|
|
20
|
+
/** Does the companion hold work it has not yet consumed? A deferred entry is
|
|
21
|
+
* excluded for the same reason the settlement policy excludes it: it never
|
|
22
|
+
* starts a turn of its own. */
|
|
23
|
+
export async function companionHasQueuedWork(nodeId) {
|
|
24
|
+
return await hasUnseenWakeMail(nodeId);
|
|
25
|
+
}
|
|
26
|
+
/** Would submitting right now step on the companion's work? */
|
|
27
|
+
export async function companionStillWorking(nodeId) {
|
|
28
|
+
return await companionMidTurn(nodeId) || await companionHasQueuedWork(nodeId);
|
|
29
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Render the immutable approval fact as plain prose. It is delivered as an
|
|
2
|
+
* inbox entry, so the inbox card is its envelope — a nested `<runtime>` card
|
|
3
|
+
* here would reach the model escaped and the attached view as raw markup. */
|
|
4
|
+
export function renderApprovalMessage(review, resultPath) {
|
|
5
|
+
const summary = review.document_name !== null
|
|
6
|
+
? review.changed
|
|
7
|
+
? `The user reviewed and approved \`${review.document_name}\`. Their edits are saved as a new revision; re-read it with \`crtr canvas read ${review.document_name}\` before continuing. Review conversation: node \`${review.companion_node_id}\`.`
|
|
8
|
+
: `The user reviewed and approved \`${review.document_name}\`. The document was not modified.`
|
|
9
|
+
: review.changed
|
|
10
|
+
? `The user reviewed and approved \`${review.file}\`. The document changed during review; re-read it before continuing. Review conversation: node \`${review.companion_node_id}\`.`
|
|
11
|
+
: `The user reviewed and approved \`${review.file}\`. The document was not modified.`;
|
|
12
|
+
return `${summary}\n\nDurable review result: ${resultPath}`;
|
|
13
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { withCanvasWrite } from '../../core/canvas/db.js';
|
|
2
|
+
import { get as getBody } from '../../core/graph/bodies.js';
|
|
3
|
+
import { documentById, editDocument, heads } from '../../core/graph/documents.js';
|
|
4
|
+
import { readerFor } from '../../core/graph/reader.js';
|
|
5
|
+
import { warmDocumentWatchers } from '../api/reader.js';
|
|
6
|
+
import { checkoutsForCwd } from '../../core/graph/repo-sync/repos.js';
|
|
7
|
+
import { snapshotCommentsLocked } from '../../core/review/comments.js';
|
|
8
|
+
import { readReviewSource } from '../../core/review/document.js';
|
|
9
|
+
import { projectReviewCancellation, projectReviewResult, buildReviewResult } from '../../core/review/project.js';
|
|
10
|
+
import { signalReviewActivity } from '../../core/review/signal.js';
|
|
11
|
+
import { clearReviewSubmit, getReview, getReviewByCompanion, requestReviewSubmit, requireVisibleReview } from '../../core/review/store.js';
|
|
12
|
+
import { ReviewOperationError } from '../../core/review/types.js';
|
|
13
|
+
import { settleHumanRequest } from '../human/settle.js';
|
|
14
|
+
import { retireCompanion } from '../companion-retire.js';
|
|
15
|
+
import { companionHasQueuedWork, companionMidTurn, companionStillWorking } from './companion.js';
|
|
16
|
+
import { renderApprovalMessage } from './deliver.js';
|
|
17
|
+
function now() { return new Date().toISOString(); }
|
|
18
|
+
function terminalConflict(review, requested) {
|
|
19
|
+
throw new ReviewOperationError('review_terminal', 'review already has a terminal outcome', { state: review.state, requested, review });
|
|
20
|
+
}
|
|
21
|
+
function approvedResult(review) {
|
|
22
|
+
if (review.result_json === null)
|
|
23
|
+
throw new Error(`approved review lacks its immutable result: ${review.review_id}`);
|
|
24
|
+
return JSON.parse(review.result_json);
|
|
25
|
+
}
|
|
26
|
+
function resultPath(review) { return `${review.review_dir}/result.json`; }
|
|
27
|
+
function effects(result) {
|
|
28
|
+
return {
|
|
29
|
+
project: async (request) => { await projectReviewResult(await requireVisibleReview(request.request_id), result); },
|
|
30
|
+
retire: async (nodeId, outcome) => { await retireCompanion(nodeId, outcome); },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** A runtime notice, not the person's words: `human-answer` would make attached
|
|
34
|
+
* views render this body as a message the person typed. */
|
|
35
|
+
function approvalNotification(review) {
|
|
36
|
+
return {
|
|
37
|
+
label: 'review approved by the user',
|
|
38
|
+
disposition: null,
|
|
39
|
+
body_json: { review_id: review.review_id, result_path: resultPath(review), body: renderApprovalMessage(review, resultPath(review)) },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function cancellationNotification(review, reason, disposition) {
|
|
43
|
+
const dismissed = disposition === 'dismissed';
|
|
44
|
+
return {
|
|
45
|
+
label: dismissed ? 'review dismissed' : 'review canceled',
|
|
46
|
+
disposition: 'human-canceled',
|
|
47
|
+
body_json: { review_id: review.review_id, disposition, body: dismissed ? `The review of \`${review.document_name ?? review.file}\` was dismissed without approval.` : `The review of \`${review.document_name ?? review.file}\` was canceled${reason === '' ? '' : ` — ${reason}`}.` },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A document review's edits become a new revision, authored by the person, made from the heads
|
|
52
|
+
* the review was snapshotted from. The document moving meanwhile refuses the save as
|
|
53
|
+
* `stale_revision`; the same text already at the single head (a concurrent submit of this
|
|
54
|
+
* review won) counts as saved.
|
|
55
|
+
*/
|
|
56
|
+
async function saveReviewedDocument(db, review, text) {
|
|
57
|
+
if (review.document_id === null || review.document_base === null)
|
|
58
|
+
return;
|
|
59
|
+
const reposFn = async (cwd, person) => await checkoutsForCwd(db, cwd, person);
|
|
60
|
+
const doc = await documentById(db, review.document_id);
|
|
61
|
+
const reader = await readerFor(db, { class: 'person' }, reposFn);
|
|
62
|
+
const saved = await editDocument(db, reader, doc, { body: text }, `edited in review ${review.review_id}`, review.document_base, {}, reposFn);
|
|
63
|
+
if (!('stale' in saved))
|
|
64
|
+
return;
|
|
65
|
+
const current = await heads(db, doc);
|
|
66
|
+
if (current.length === 1 && await getBody(db, current[0].body_hash) === text)
|
|
67
|
+
return;
|
|
68
|
+
throw new ReviewOperationError('stale_revision', `${review.document_name ?? doc.name} changed since the review began; the reviewed text was not saved`, {
|
|
69
|
+
review_id: review.review_id,
|
|
70
|
+
document: review.document_name ?? doc.name,
|
|
71
|
+
base: review.document_base,
|
|
72
|
+
heads_key: saved.stale.heads_key,
|
|
73
|
+
revision: saved.stale.revision,
|
|
74
|
+
next: `Read the current revision with \`crtr canvas read ${doc.id}\`, then start a new review of it.`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async function approveReview(initial) {
|
|
78
|
+
if (initial.state === 'canceled')
|
|
79
|
+
return terminalConflict(initial, 'submit');
|
|
80
|
+
if (initial.state === 'approved')
|
|
81
|
+
return { outcome: 'already_settled', record: initial, result: approvedResult(initial) };
|
|
82
|
+
const source = await readReviewSource(initial.file, 'submit');
|
|
83
|
+
if (initial.document_id !== null)
|
|
84
|
+
await warmDocumentWatchers(initial.document_id); // git lookups before the write opens
|
|
85
|
+
const { result, resultJson } = await withCanvasWrite(async (db) => {
|
|
86
|
+
const review = await requireVisibleReview(initial.review_id);
|
|
87
|
+
if (review.state === 'canceled')
|
|
88
|
+
return terminalConflict(review, 'submit');
|
|
89
|
+
if (review.state === 'approved')
|
|
90
|
+
return { result: approvedResult(review), resultJson: review.result_json };
|
|
91
|
+
const snapshot = await snapshotCommentsLocked(db, review.review_id);
|
|
92
|
+
const result = buildReviewResult(review, snapshot, source.sha256, now());
|
|
93
|
+
if (result.changed)
|
|
94
|
+
await saveReviewedDocument(db, review, new TextDecoder('utf-8').decode(source.bytes));
|
|
95
|
+
return { result, resultJson: JSON.stringify(result) };
|
|
96
|
+
});
|
|
97
|
+
const settled = await settleHumanRequest({
|
|
98
|
+
request_id: initial.review_id,
|
|
99
|
+
outcome: 'approved',
|
|
100
|
+
result_json: resultJson,
|
|
101
|
+
notification: approvalNotification({ ...initial, changed: result.changed }),
|
|
102
|
+
post_commit: effects(result),
|
|
103
|
+
});
|
|
104
|
+
if (settled.outcome === 'settled')
|
|
105
|
+
signalReviewActivity();
|
|
106
|
+
const record = await requireVisibleReview(initial.review_id);
|
|
107
|
+
if (settled.outcome === 'already_settled' && record.state !== 'approved')
|
|
108
|
+
return terminalConflict(record, 'submit');
|
|
109
|
+
return { outcome: settled.outcome, record, result: settled.outcome === 'settled' ? result : approvedResult(record) };
|
|
110
|
+
}
|
|
111
|
+
export async function submitReviewApproval(reviewId) {
|
|
112
|
+
const review = await requireVisibleReview(reviewId);
|
|
113
|
+
if (review.state === 'canceled')
|
|
114
|
+
return terminalConflict(review, 'submit');
|
|
115
|
+
if (review.state === 'open' && await companionStillWorking(review.companion_node_id)) {
|
|
116
|
+
if (await requestReviewSubmit(reviewId, now()))
|
|
117
|
+
signalReviewActivity();
|
|
118
|
+
return { outcome: 'awaiting_companion', record: await requireVisibleReview(reviewId) };
|
|
119
|
+
}
|
|
120
|
+
return approveReview(review);
|
|
121
|
+
}
|
|
122
|
+
export async function completeRequestedSubmit(reviewId, opts) {
|
|
123
|
+
const review = await getReview(reviewId);
|
|
124
|
+
if (review === null || review.state !== 'open' || review.submit_requested_at === null)
|
|
125
|
+
return null;
|
|
126
|
+
if (await companionHasQueuedWork(review.companion_node_id))
|
|
127
|
+
return null;
|
|
128
|
+
if (!opts.atCompanionTurnEnd && await companionMidTurn(review.companion_node_id))
|
|
129
|
+
return null;
|
|
130
|
+
try {
|
|
131
|
+
return await approveReview(review);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// A refused save leaves the review open with no submit pending, rather than retried every tick.
|
|
135
|
+
if (error instanceof ReviewOperationError && error.code === 'stale_revision') {
|
|
136
|
+
await clearReviewSubmit(reviewId);
|
|
137
|
+
signalReviewActivity();
|
|
138
|
+
}
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export async function completeCompanionRequestedSubmit(companionNodeId) {
|
|
143
|
+
const review = await getReviewByCompanion(companionNodeId);
|
|
144
|
+
return review === null ? null : completeRequestedSubmit(review.review_id, { atCompanionTurnEnd: true });
|
|
145
|
+
}
|
|
146
|
+
export async function cancelReview(reviewId, args = {}) {
|
|
147
|
+
const review = await requireVisibleReview(reviewId);
|
|
148
|
+
if (review.state === 'approved')
|
|
149
|
+
return terminalConflict(review, 'cancel');
|
|
150
|
+
const at = now();
|
|
151
|
+
const reason = args.reason ?? '';
|
|
152
|
+
const disposition = args.disposition ?? 'canceled';
|
|
153
|
+
const resultJson = JSON.stringify({ schema: 'humanloop.cancel/v1', kind: 'canceled', canceledAt: at, ...(reason === '' ? {} : { reason }), ...(args.actor === undefined ? {} : { actor: args.actor }), ...(disposition === 'dismissed' ? { disposition } : {}) });
|
|
154
|
+
const settled = await settleHumanRequest({
|
|
155
|
+
request_id: reviewId,
|
|
156
|
+
outcome: disposition === 'dismissed' ? 'dismissed' : 'canceled',
|
|
157
|
+
result_json: resultJson,
|
|
158
|
+
notification: cancellationNotification(review, reason, disposition),
|
|
159
|
+
post_commit: {
|
|
160
|
+
project: async (request) => { await projectReviewCancellation(await requireVisibleReview(request.request_id), JSON.parse(resultJson)); },
|
|
161
|
+
retire: async (nodeId, outcome) => { await retireCompanion(nodeId, outcome); },
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
if (settled.outcome === 'settled')
|
|
165
|
+
signalReviewActivity();
|
|
166
|
+
const record = await requireVisibleReview(reviewId);
|
|
167
|
+
if (settled.outcome === 'already_settled' && record.state === 'approved')
|
|
168
|
+
return terminalConflict(record, 'cancel');
|
|
169
|
+
return { outcome: settled.outcome, record };
|
|
170
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.673",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.673",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.673",
|
|
31
|
+
"@north-light/identity": "0.3.673"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.673",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.673",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.673",
|
|
32
|
+
"@north-light/plugin": "0.3.673",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -10667,17 +10667,17 @@
|
|
|
10667
10667
|
},
|
|
10668
10668
|
"packages/crouter-api": {
|
|
10669
10669
|
"name": "@north-light/api",
|
|
10670
|
-
"version": "0.3.
|
|
10670
|
+
"version": "0.3.673",
|
|
10671
10671
|
"license": "UNLICENSED"
|
|
10672
10672
|
},
|
|
10673
10673
|
"packages/crouter-env-docker": {
|
|
10674
10674
|
"name": "@north-light/env-docker",
|
|
10675
|
-
"version": "0.3.
|
|
10675
|
+
"version": "0.3.673",
|
|
10676
10676
|
"license": "UNLICENSED"
|
|
10677
10677
|
},
|
|
10678
10678
|
"packages/crouter-identity": {
|
|
10679
10679
|
"name": "@north-light/identity",
|
|
10680
|
-
"version": "0.3.
|
|
10680
|
+
"version": "0.3.673",
|
|
10681
10681
|
"license": "UNLICENSED",
|
|
10682
10682
|
"dependencies": {
|
|
10683
10683
|
"jose": "^6.2.1"
|
|
@@ -10685,21 +10685,21 @@
|
|
|
10685
10685
|
},
|
|
10686
10686
|
"packages/crouter-plugin": {
|
|
10687
10687
|
"name": "@north-light/plugin",
|
|
10688
|
-
"version": "0.3.
|
|
10688
|
+
"version": "0.3.673",
|
|
10689
10689
|
"license": "UNLICENSED",
|
|
10690
10690
|
"dependencies": {
|
|
10691
|
-
"@north-light/api": "0.3.
|
|
10692
|
-
"@north-light/identity": "0.3.
|
|
10691
|
+
"@north-light/api": "0.3.673",
|
|
10692
|
+
"@north-light/identity": "0.3.673"
|
|
10693
10693
|
}
|
|
10694
10694
|
},
|
|
10695
10695
|
"packages/crouter-sdk": {
|
|
10696
10696
|
"name": "@north-light/sdk",
|
|
10697
|
-
"version": "0.3.
|
|
10697
|
+
"version": "0.3.673",
|
|
10698
10698
|
"license": "UNLICENSED",
|
|
10699
10699
|
"dependencies": {
|
|
10700
|
-
"@north-light/api": "0.3.
|
|
10701
|
-
"@north-light/identity": "0.3.
|
|
10702
|
-
"@north-light/plugin": "0.3.
|
|
10700
|
+
"@north-light/api": "0.3.673",
|
|
10701
|
+
"@north-light/identity": "0.3.673",
|
|
10702
|
+
"@north-light/plugin": "0.3.673",
|
|
10703
10703
|
"jose": "^6.2.1"
|
|
10704
10704
|
},
|
|
10705
10705
|
"bin": {
|