code60-transmission-server 0.1.0-staging.3 → 0.1.0-staging.6
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/README.engine.md +64 -2
- package/README.md +66 -5
- package/dist/src/broker/native/README.md +15 -0
- package/dist/src/broker/native/build.js +3 -0
- package/dist/src/broker/native/command-helper.c +93 -0
- package/dist/src/cli/configure.js +193 -0
- package/dist/src/cli/daemon.js +5 -1
- package/dist/src/cli/helpers.js +12 -4
- package/dist/src/cli/main.js +12 -3
- package/dist/src/cli/runtime-build.js +38 -0
- package/dist/src/config/coding-policy.js +4 -0
- package/dist/src/config/deployment.js +26 -10
- package/dist/src/config/workflow-schema.json +11 -0
- package/dist/src/engine/commands.js +35 -4
- package/dist/src/engine/workflow-engine.js +70 -15
- package/dist/src/main.js +4 -1
- package/dist/src/mcp/main.js +4 -2
- package/dist/src/mcp/server.js +37 -6
- package/dist/src/runtime/engine-driver.js +11 -2
- package/dist/src/runtime/provider-bridge.js +4 -2
- package/dist/src/runtime/provider-transport.js +7 -5
- package/dist/src/server/api-contract.json +530 -2
- package/dist/src/server/application.js +9 -3
- package/dist/src/server/coding.js +254 -0
- package/dist/src/server/deployment.js +18 -6
- package/dist/src/server/history-handlers.js +16 -2
- package/dist/src/server/workspace-handlers.js +1 -1
- package/dist/src/tools/checks.js +12 -1
- package/dist/src/tools/command-check.js +34 -0
- package/dist/src/tools/commands.js +310 -0
- package/dist/src/tools/developer.js +351 -0
- package/dist/src/tools/index.js +19 -2
- package/dist/src/workspaces/index.js +244 -22
- package/dist/src/workspaces/source.js +295 -0
- package/package.json +4 -2
- package/scripts/postinstall.mjs +2 -1
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { accessSync, constants, existsSync, lstatSync, mkdtempSync, openSync, closeSync, readFileSync, readSync, realpathSync, rmSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, join } from 'node:path';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { DEVELOPER_DEFINITIONS } from '../tools/developer.js';
|
|
5
|
+
import { createCommandCheck } from '../tools/command-check.js';
|
|
6
|
+
import { ContainedCodexAppServer, pilotCodexConfig } from '../runtime/codex-app-server.js';
|
|
7
|
+
import { canonical } from '../broker/policy.js';
|
|
8
|
+
import { ApiError } from './errors.js';
|
|
9
|
+
import { isTrustedHelper } from '../cli/helpers.js';
|
|
10
|
+
import { commandIdentity } from './control-plane.js';
|
|
11
|
+
import { missingCodingPermissions } from '../config/coding-policy.js';
|
|
12
|
+
export const CODING_MIGRATION = { id: 'coding.v1', sql: `
|
|
13
|
+
CREATE INDEX coding_command_run ON engine_private(json_extract(body,'$.runId')) WHERE scope='command';
|
|
14
|
+
CREATE INDEX coding_question_run ON engine_private(json_extract(body,'$.runId')) WHERE scope='worker_question';
|
|
15
|
+
CREATE INDEX coding_message_run ON engine_private(json_extract(body,'$.runId')) WHERE scope='task_message';
|
|
16
|
+
CREATE INDEX coding_task_setup ON engine_private(json_extract(body,'$.identity')) WHERE scope='coding_setup';
|
|
17
|
+
` };
|
|
18
|
+
export function codingReadiness(configuration, runner) {
|
|
19
|
+
const issues = [];
|
|
20
|
+
if (!configuration.runtime.enabled)
|
|
21
|
+
issues.push({ code: 'runtime_disabled', action: 'Run code60 configure to select an executable and provider.' });
|
|
22
|
+
try {
|
|
23
|
+
accessSync(configuration.runtime.executable, constants.X_OK);
|
|
24
|
+
if (!lstatSync(realpathSync(configuration.runtime.executable)).isFile())
|
|
25
|
+
throw new Error();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
issues.push({ code: 'runtime_executable_unavailable', action: 'Configure the absolute path to an installed Codex executable.' });
|
|
29
|
+
}
|
|
30
|
+
if (!existsSync('/usr/bin/sandbox-exec'))
|
|
31
|
+
issues.push({ code: 'containment_unavailable', action: 'Use a supported macOS installation.' });
|
|
32
|
+
if (!runner?.settings.enabled)
|
|
33
|
+
issues.push({ code: 'commands_disabled', action: 'Run code60 configure to enable the coding command preset.' });
|
|
34
|
+
if (runner && !isTrustedHelper(runner.options.workspaces.commandHelperPath))
|
|
35
|
+
issues.push({ code: 'command_supervisor_unavailable', action: 'Build or reinstall Code60 native helpers.' });
|
|
36
|
+
if (missingCodingPermissions(configuration.deploymentPolicy).length)
|
|
37
|
+
issues.push({ code: 'coding_permissions_missing', action: 'Stop the engine and run code60 configure --coding-only to grant the coding preset without replacing provider settings.' });
|
|
38
|
+
for (const credential of configuration.providerCredentials ?? [])
|
|
39
|
+
try {
|
|
40
|
+
accessSync(credential.file, constants.R_OK);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
issues.push({ code: 'credential_file_unavailable', action: `Restore the configured credential file for reference ${credential.referenceId}.` });
|
|
44
|
+
}
|
|
45
|
+
return { ready: issues.length === 0, issues, providerAuthentication: 'not_checked', providerVerificationAction: 'code60 doctor --check-provider', runtime: configuration.runtime.executable, commands: runner?.settings ?? null,
|
|
46
|
+
network: runner?.settings.network, sourceLimits: runner?.options.workspaces.sourceQuotas, resultMode: 'working_tree', toolset: 'coding' };
|
|
47
|
+
}
|
|
48
|
+
export class CodingService {
|
|
49
|
+
options;
|
|
50
|
+
readinessCache;
|
|
51
|
+
setups = new Map();
|
|
52
|
+
constructor(options) {
|
|
53
|
+
this.options = options;
|
|
54
|
+
for (const row of options.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='coding_check'").all())
|
|
55
|
+
this.registerCheck(JSON.parse(row.body));
|
|
56
|
+
}
|
|
57
|
+
readiness() {
|
|
58
|
+
if (this.readinessCache && this.readinessCache.until > Date.now())
|
|
59
|
+
return this.readinessCache.result;
|
|
60
|
+
const result = (async () => {
|
|
61
|
+
const report = codingReadiness(this.options.configuration, this.options.runner);
|
|
62
|
+
if (!report.ready)
|
|
63
|
+
return report;
|
|
64
|
+
const state = mkdtempSync(join(dirname(this.options.runner.options.directory), 'readiness-'));
|
|
65
|
+
let client;
|
|
66
|
+
try {
|
|
67
|
+
client = new ContainedCodexAppServer({ executable: this.options.configuration.runtime.executable, stateDirectory: state, modelPort: this.options.configuration.runtime.modelPort, config: pilotCodexConfig(this.options.configuration.runtime.modelPort), ...(this.options.runner.options.startupLockFd === undefined ? {} : { startupLockFd: this.options.runner.options.startupLockFd }) });
|
|
68
|
+
await client.initialize();
|
|
69
|
+
return { ...report, appServerCompatibility: 'verified' };
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return { ...report, ready: false, appServerCompatibility: 'failed', issues: [...report.issues, { code: 'app_server_handshake_failed', action: 'Run code60 doctor and check Codex app-server compatibility.' }] };
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
await client?.close();
|
|
76
|
+
rmSync(state, { recursive: true, force: true });
|
|
77
|
+
}
|
|
78
|
+
})();
|
|
79
|
+
this.readinessCache = { until: Date.now() + 60_000, result };
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
registerCheck(check) { this.options.checks.register(createCommandCheck(check, this.options)); }
|
|
83
|
+
run(context, id) { const run = this.options.store.get('runs', id); this.options.auth.assertWorkspace(context.principal, run.workspaceId); return run; }
|
|
84
|
+
handlers() {
|
|
85
|
+
return new Map([
|
|
86
|
+
['getCodingReadiness', async () => ({ status: 200, headers: {}, body: await this.readiness() })],
|
|
87
|
+
['startCodingTask', context => this.start(context)],
|
|
88
|
+
['getCodingTaskResult', context => {
|
|
89
|
+
const run = this.run(context, context.params.runId), lease = this.options.workspaces.lease(run.id);
|
|
90
|
+
const recovery = this.options.runner.recoveryRequired(run.id) ? this.options.workspaces.recoveryPreview(run.id) : undefined;
|
|
91
|
+
const summary = this.options.workspaces.sourceResult(run.id, recovery?.revisionId ?? lease.knownRevisionId), fd = openSync(summary.patchPath, constants.O_RDONLY | constants.O_NOFOLLOW), cursor = Number(context.query.cursor ?? 0), limit = Number(context.query.limit ?? 65_536);
|
|
92
|
+
if (!Number.isSafeInteger(cursor) || cursor < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 262_144) {
|
|
93
|
+
closeSync(fd);
|
|
94
|
+
throw new ApiError(400, 'invalid_cursor', 'Use a nonnegative byte cursor and a limit up to 262144.');
|
|
95
|
+
}
|
|
96
|
+
const bytes = Buffer.alloc(limit);
|
|
97
|
+
let count;
|
|
98
|
+
try {
|
|
99
|
+
count = readSync(fd, bytes, 0, bytes.length, cursor);
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
closeSync(fd);
|
|
103
|
+
}
|
|
104
|
+
const evidence = this.options.store.list('artifacts', { runId: run.id, limit: Number.MAX_SAFE_INTEGER }).map(r => r.value).filter(a => a.kind === 'check_evidence');
|
|
105
|
+
const setup = this.options.store.private('coding_task', run.id), checks = setup?.checkIds ?? [];
|
|
106
|
+
let commandOutput;
|
|
107
|
+
if (context.query.commandId) {
|
|
108
|
+
const command = this.options.runner.get(context.query.commandId);
|
|
109
|
+
if (command.runId !== run.id)
|
|
110
|
+
throw new ApiError(404, 'not_found', 'Command not found in this task.');
|
|
111
|
+
commandOutput = this.options.runner.output(command.id, context.query.stream, Number(context.query.outputCursor ?? 0), Number(context.query.outputLimit ?? 65_536));
|
|
112
|
+
}
|
|
113
|
+
return { status: 200, headers: {}, body: { runId: run.id, state: run.state, resultMode: run.resultMode ?? 'commit', ...summary, patchPath: undefined, patch: bytes.subarray(0, count).toString(), nextCursor: count === limit ? cursor + count : null,
|
|
114
|
+
...(commandOutput === undefined ? {} : { commandOutput }), ...(recovery ? { recovery: { ...recovery, actions: ['preserve_changes', 'rollback'], instruction: 'Provide commandResolution in recover_run after reviewing this diff.' } } : {}), verification: checks.length ? run.state === 'succeeded' ? 'verified' : 'pending_or_failed' : 'unverified', checks, evidence, providerDiagnostics: this.options.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER }).flatMap(({ value }) => { const d = this.options.store.private('provider_diagnostic', value.id); return d ? [d] : []; }), commands: this.options.runner.records(run.id), questions: this.options.developer.listQuestions(run.id) } };
|
|
115
|
+
}],
|
|
116
|
+
['sendTaskMessage', context => {
|
|
117
|
+
const run = this.run(context, context.params.runId);
|
|
118
|
+
if (['succeeded', 'failed', 'cancelled'].includes(run.state))
|
|
119
|
+
throw new ApiError(409, 'task_finished', 'Start a follow-up task for a completed run.');
|
|
120
|
+
return this.options.store.command(commandIdentity(context, `/runs/${run.id}/messages`), () => {
|
|
121
|
+
const message = { id: randomUUID(), runId: run.id, text: context.body.text, delivered: false, createdAt: new Date().toISOString() };
|
|
122
|
+
this.options.store.setPrivate('task_message', message.id, message);
|
|
123
|
+
this.options.store.event(run.id, 'task_message', 'message', message.id, {});
|
|
124
|
+
this.options.store.coordinator.afterCommit(() => this.options.wake(run.id));
|
|
125
|
+
return { status: 202, headers: {}, body: message };
|
|
126
|
+
});
|
|
127
|
+
}],
|
|
128
|
+
['listTaskQuestions', context => { const run = this.run(context, context.params.runId); return { status: 200, headers: {}, body: { items: this.options.developer.listQuestions(run.id) } }; }],
|
|
129
|
+
['answerTaskQuestion', context => {
|
|
130
|
+
const question = this.options.store.private('worker_question', context.params.questionId);
|
|
131
|
+
if (!question)
|
|
132
|
+
throw new ApiError(404, 'not_found', 'Question not found.');
|
|
133
|
+
this.run(context, question.runId);
|
|
134
|
+
const identity = commandIdentity(context, `/questions/${question.id}/answers`), prior = this.options.store.receipt(identity);
|
|
135
|
+
if (prior)
|
|
136
|
+
return { receipt: prior, replay: true };
|
|
137
|
+
const body = this.options.developer.answer(question.id, context.body.answer), receipt = { status: 202, headers: {}, body };
|
|
138
|
+
this.options.store.saveReceipt(identity, receipt);
|
|
139
|
+
return receipt;
|
|
140
|
+
}],
|
|
141
|
+
]);
|
|
142
|
+
}
|
|
143
|
+
start(context) {
|
|
144
|
+
const identity = commandIdentity(context, '/coding-tasks'), key = JSON.stringify([identity.principal, identity.key]), prior = this.options.store.receipt(identity);
|
|
145
|
+
if (prior)
|
|
146
|
+
return Promise.resolve({ receipt: prior, replay: true });
|
|
147
|
+
const pending = this.setups.get(key);
|
|
148
|
+
if (pending)
|
|
149
|
+
return pending.then(() => this.start(context));
|
|
150
|
+
const promise = this.create(context);
|
|
151
|
+
this.setups.set(key, promise);
|
|
152
|
+
void promise.then(() => this.setups.delete(key), () => this.setups.delete(key));
|
|
153
|
+
return promise;
|
|
154
|
+
}
|
|
155
|
+
async create(context) {
|
|
156
|
+
const { store, publication, configuration, workspaces } = this.options, body = context.body, identity = commandIdentity(context, '/coding-tasks');
|
|
157
|
+
const readiness = await this.readiness();
|
|
158
|
+
if (!readiness.ready)
|
|
159
|
+
throw new ApiError(422, 'coding_setup_required', 'Run code60 configure and code60 doctor before starting coding tasks.');
|
|
160
|
+
const requestDigest = createHash('sha256').update(canonical(identity.body)).digest('hex'), setupId = createHash('sha256').update(canonical([identity.principal, identity.key])).digest('hex');
|
|
161
|
+
let setup = store.private('coding_setup', setupId) ?? { identity: setupId, digest: requestDigest };
|
|
162
|
+
if (setup.digest !== requestDigest)
|
|
163
|
+
throw new ApiError(409, 'idempotency_conflict', 'Use the original task arguments with this key.');
|
|
164
|
+
// Run admission and its receipt are atomic. A crash before saving the outer
|
|
165
|
+
// task receipt must replay that admission before touching its live lease.
|
|
166
|
+
if (setup.workspaceId && setup.workflowVersionId) {
|
|
167
|
+
const input = { workspaceId: setup.workspaceId, workflowVersionId: setup.workflowVersionId, resultMode: body.resultMode ?? 'working_tree', inputs: { task: body.task, data: body.inputs ?? null }, inputArtifacts: body.inputArtifacts ?? [] };
|
|
168
|
+
const admitted = store.receipt({ ...identity, path: '/api/v1/runs', key: `${setupId}:run`, body: input });
|
|
169
|
+
if (admitted) {
|
|
170
|
+
const run = admitted.body;
|
|
171
|
+
store.setPrivate('coding_task', run.id, { task: body.task, checkIds: setup.checkIds ?? [] });
|
|
172
|
+
store.saveReceipt(identity, admitted);
|
|
173
|
+
return admitted;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const save = () => store.setPrivate('coding_setup', setupId, setup);
|
|
177
|
+
save();
|
|
178
|
+
if (!setup.workspaceId) {
|
|
179
|
+
if (body.workspaceId) {
|
|
180
|
+
this.options.auth.assertWorkspace(context.principal, body.workspaceId);
|
|
181
|
+
setup.workspaceId = workspaces.get(body.workspaceId).id;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
if (!body.repositoryPath || !context.principal.workspaceIds.includes('*'))
|
|
185
|
+
throw new ApiError(403, 'workspace_registration_forbidden', 'An unrestricted operator must select a repositoryPath or register an authorized workspace first.');
|
|
186
|
+
let root;
|
|
187
|
+
try {
|
|
188
|
+
root = realpathSync(body.repositoryPath);
|
|
189
|
+
if (!lstatSync(root).isDirectory())
|
|
190
|
+
throw new Error('not_a_directory');
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
const denied = ['EACCES', 'EPERM'].includes(error.code ?? '');
|
|
194
|
+
throw new ApiError(denied ? 403 : 422, denied ? 'repository_path_forbidden' : 'repository_path_unavailable', 'Select an existing, accessible repository root.');
|
|
195
|
+
}
|
|
196
|
+
const existing = workspaces.list().find(w => w.repositoryPath === root);
|
|
197
|
+
setup.workspaceId = existing?.id ?? workspaces.register({ name: basename(root), repositoryPath: root, scratchPaths: [], sourceTracking: true }).id;
|
|
198
|
+
}
|
|
199
|
+
save();
|
|
200
|
+
}
|
|
201
|
+
this.options.auth.assertWorkspace(context.principal, setup.workspaceId);
|
|
202
|
+
workspaces.enableSourceTracking(setup.workspaceId);
|
|
203
|
+
const root = workspaces.get(setup.workspaceId).repositoryPath;
|
|
204
|
+
const definitions = body.checks ?? this.detectChecks(root, setupId);
|
|
205
|
+
setup.checkIds = definitions.map(check => { const definition = { ...check, id: `task_${setupId.slice(0, 16)}_${check.id}` }; store.setPrivate('coding_check', definition.id, definition); this.registerCheck(definition); return definition.id; });
|
|
206
|
+
save();
|
|
207
|
+
const command = (path, suffix) => ({ principal: context.principal.id, method: 'POST', path, key: `${setupId}:${suffix}`, body: {} });
|
|
208
|
+
if (!setup.profileVersionId) {
|
|
209
|
+
if (body.profileVersionId)
|
|
210
|
+
setup.profileVersionId = body.profileVersionId;
|
|
211
|
+
else {
|
|
212
|
+
const provider = configuration.providers?.[0], model = provider?.models[0], localModel = configuration.runtime.models[0];
|
|
213
|
+
const credential = provider ? configuration.providerCredentials?.find(c => c.providerId === provider.id) : undefined;
|
|
214
|
+
const input = { name: 'Coding worker', initialVersion: { definition: { role: 'worker', runtime: { runtimeId: 'codex-local', provider: provider?.id ?? 'code60-local', model: model?.id ?? localModel.id,
|
|
215
|
+
...(model ? { effort: model.defaultEffort } : localModel.effortLevels[0] ? { effort: localModel.effortLevels[0] } : {}), options: { artifactFormat: 'json' }, credentialRefs: credential ? { provider: credential.referenceId } : {} },
|
|
216
|
+
tools: [...DEVELOPER_DEFINITIONS.keys()].map(toolId => ({ toolId, configuration: {} })), permissions: { defaultEffect: 'deny', rules: [{ kind: 'tool', toolId: '*', effect: 'allow' }, { kind: 'filesystem', root: 'workspace', path: '.', recursive: true, operations: ['read', 'write', 'delete'], effect: 'allow' }] },
|
|
217
|
+
instructions: [{ kind: 'inline', text: 'Complete the user task supplied in inputs.task. Inspect the project, reproduce the issue, make precise edits, and run relevant checks. Use ask_user only when a missing answer blocks progress. Await or stop every command before submitting. Preserve pre-existing edits. Finish with a JSON object containing summary. Passing checks and the baseline-relative diff are recorded by the engine; do not claim unexecuted checks passed.' }] }, resources: [] } };
|
|
218
|
+
const created = await publication.createProfile({ ...command('/agent-profiles', 'profile'), body: input }, input, context.signal);
|
|
219
|
+
setup.profileVersionId = created.receipt.body.latestVersionId;
|
|
220
|
+
}
|
|
221
|
+
save();
|
|
222
|
+
}
|
|
223
|
+
if (!setup.workflowVersionId) {
|
|
224
|
+
const source = { kind: 'Workflow', version: '1', metadata: { name: 'Coding task' }, config: { timeout: { duration: '30m', 'on-timeout': 'block' }, 'agent-profiles': { worker: setup.profileVersionId } }, steps: [{ id: 'implement', execution: { 'max-session-resets': 2, 'max-attempts-per-session': 10, session: { timeout: { duration: '15m', 'on-timeout': 'reset-session' } } }, instructions: [{ kind: 'inline', text: 'Solve inputs.task in the current project. The final JSON summary is accepted only after the configured executable checks pass.' }], exitArtifact: { schema: { type: 'object', required: ['summary'], properties: { summary: { type: 'string', minLength: 1 } }, additionalProperties: false } }, exitCriteria: { deterministic: { checks: setup.checkIds } } }] };
|
|
225
|
+
const input = { name: 'Coding task', initialVersion: { source: { format: 'json', content: JSON.stringify(source) } } };
|
|
226
|
+
const created = await publication.createWorkflow({ ...command('/workflows', 'workflow'), body: input }, input, this.options.checks.list().map(c => c.name), context.signal);
|
|
227
|
+
setup.workflowVersionId = created.receipt.body.latestVersionId;
|
|
228
|
+
save();
|
|
229
|
+
}
|
|
230
|
+
const input = { workspaceId: setup.workspaceId, workflowVersionId: setup.workflowVersionId, resultMode: body.resultMode ?? 'working_tree', inputs: { task: body.task, data: body.inputs ?? null }, inputArtifacts: body.inputArtifacts ?? [] };
|
|
231
|
+
const result = await this.options.commands.createRun({ ...context, body: input, header: name => name.toLowerCase() === 'idempotency-key' ? `${setupId}:run` : context.header(name) });
|
|
232
|
+
const receipt = 'receipt' in result ? result.receipt : result, run = receipt.body;
|
|
233
|
+
store.setPrivate('coding_task', run.id, { task: body.task, checkIds: setup.checkIds });
|
|
234
|
+
store.saveReceipt(identity, receipt);
|
|
235
|
+
return receipt;
|
|
236
|
+
}
|
|
237
|
+
detectChecks(root, id) {
|
|
238
|
+
if (!existsSync(join(root, 'package.json')))
|
|
239
|
+
return [];
|
|
240
|
+
let pkg;
|
|
241
|
+
try {
|
|
242
|
+
pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
243
|
+
if (!pkg || typeof pkg !== 'object' || pkg.packageManager !== undefined && typeof pkg.packageManager !== 'string' || pkg.scripts !== undefined && (typeof pkg.scripts !== 'object' || pkg.scripts === null || Array.isArray(pkg.scripts)))
|
|
244
|
+
throw new Error();
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
throw new ApiError(422, 'invalid_project_manifest', 'Supply explicit check commands to repair package.json, or checks: [] for an explicitly unverified task.');
|
|
248
|
+
}
|
|
249
|
+
const manager = pkg.packageManager?.split('@')[0] ?? (existsSync(join(root, 'pnpm-lock.yaml')) ? 'pnpm' : existsSync(join(root, 'yarn.lock')) ? 'yarn' : 'npm');
|
|
250
|
+
if (!['npm', 'pnpm', 'yarn', 'bun'].includes(manager))
|
|
251
|
+
throw new ApiError(422, 'unknown_package_manager', 'Supply explicit check commands for this package manager.');
|
|
252
|
+
return ['typecheck', 'lint', 'test', 'build'].filter(name => pkg.scripts?.[name]).map(name => ({ id: name, description: `Project ${name}`, version: createHash('sha256').update(`${id}:${manager}:${pkg.scripts[name]}`).digest('hex'), command: `${manager} run ${name}`, env: { CI: '1' }, timeoutMs: 600_000 }));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import Database from 'better-sqlite3';
|
|
2
|
+
import { CommandRunner, DEFAULT_COMMAND_SETTINGS } from '../tools/commands.js';
|
|
3
|
+
import { DeveloperTools } from '../tools/developer.js';
|
|
4
|
+
import { createCommandCheck } from '../tools/command-check.js';
|
|
5
|
+
import { CODING_MIGRATION } from './coding.js';
|
|
2
6
|
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, realpathSync } from 'node:fs';
|
|
3
7
|
import { isAbsolute, join } from 'node:path';
|
|
4
8
|
import { ActionBroker, BROKER_MIGRATION } from '../broker/index.js';
|
|
@@ -17,7 +21,7 @@ import { ToolFactory } from '../tools/index.js';
|
|
|
17
21
|
import { TrustedCheckRegistry } from '../tools/checks.js';
|
|
18
22
|
import { AdminHttpFetcher } from '../tools/http.js';
|
|
19
23
|
import { createPureArtifactCheck } from '../tools/worker-check.js';
|
|
20
|
-
import { WorkspaceService, WORKSPACE_MIGRATION } from '../workspaces/index.js';
|
|
24
|
+
import { WorkspaceService, WORKSPACE_MIGRATION, WORKSPACE_SOURCE_MIGRATION } from '../workspaces/index.js';
|
|
21
25
|
import { createApplication } from './application.js';
|
|
22
26
|
import { AuthService } from './auth.js';
|
|
23
27
|
import { ApiError } from './errors.js';
|
|
@@ -107,7 +111,7 @@ export async function openDeployment(input, ports = {}) {
|
|
|
107
111
|
db = (ports.openDatabase ?? (path => new Database(path)))(databasePath);
|
|
108
112
|
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
|
|
109
113
|
const coordinator = new SqliteCoordinator(db);
|
|
110
|
-
coordinator.migrate([ENGINE_MIGRATION, BROKER_MIGRATION, WORKSPACE_MIGRATION]);
|
|
114
|
+
coordinator.migrate([ENGINE_MIGRATION, BROKER_MIGRATION, WORKSPACE_MIGRATION, WORKSPACE_SOURCE_MIGRATION, CODING_MIGRATION]);
|
|
111
115
|
const store = new EngineStore(coordinator);
|
|
112
116
|
validation = new ValidationPool(coordinator);
|
|
113
117
|
const configuration = await loadDeploymentConfiguration(input.configurationFile, validation);
|
|
@@ -124,11 +128,13 @@ export async function openDeployment(input, ports = {}) {
|
|
|
124
128
|
}
|
|
125
129
|
const snapshotDirectory = stateChild(lock.directory, 'snapshots'), runtimeDirectory = stateChild(lock.directory, 'runtimes');
|
|
126
130
|
workspaces = (ports.createWorkspaces ?? (options => new WorkspaceService(options)))({
|
|
127
|
-
coordinator, helperPath: input.fsHelperPath, gitHelperPath: input.gitHelperPath, snapshotDirectory,
|
|
131
|
+
coordinator, helperPath: input.fsHelperPath, gitHelperPath: input.gitHelperPath, snapshotDirectory, generatedPaths: configuration.commands?.generatedPaths ?? DEFAULT_COMMAND_SETTINGS.generatedPaths, ...(configuration.sourceQuotas ? { sourceQuotas: { entries: 100000, fileBytes: 1073741824, totalBytes: 10737418240, ...configuration.sourceQuotas } } : {}),
|
|
128
132
|
startupLockFd: lock.fd, protectedRootFds: [lock.directoryFd], deploymentRoots, recover: true,
|
|
129
133
|
});
|
|
130
134
|
const ownedWorkspaces = workspaces;
|
|
131
|
-
const
|
|
135
|
+
const runner = new CommandRunner({ store, workspaces, directory: stateChild(lock.directory, 'commands'), settings: configuration.commands ?? {}, protectedPaths: [lock.directory, realpathSync(join(input.fsHelperPath, '..', '..', '..')), realpathSync(input.configurationFile), realpathSync(input.operatorTokenFile), ...(configuration.providerCredentials ?? []).map(c => realpathSync(c.file))], startupLockFd: lock.fd, signal: id => application.engine.signal(id), wake: id => application.engine.wake(id) });
|
|
136
|
+
const developer = new DeveloperTools({ store, workspaces, runner, resolveContext: binding => application.engine.context(binding), signal: id => application.engine.signal(id), hold: (id, name, held) => broker.setHold(id, name, held), wake: id => application.engine.wake(id) });
|
|
137
|
+
const tools = new ToolFactory({ coordinator, workspaces, extensions: developer.registry(), resolveContext: binding => application.engine.context(binding),
|
|
132
138
|
resolveConfiguration: (context, toolId) => {
|
|
133
139
|
const session = store.get('sessions', context.binding.sessionId);
|
|
134
140
|
const selected = session.effectiveConfiguration.definition.tools.find(tool => tool.toolId === toolId);
|
|
@@ -165,13 +171,15 @@ export async function openDeployment(input, ports = {}) {
|
|
|
165
171
|
};
|
|
166
172
|
const pins = new InstructionPins(store, publication, { engineInstructions, readWorkspace: (runId, path) => {
|
|
167
173
|
relativePath(path);
|
|
174
|
+
if (typeof ownedWorkspaces.instructionSource === 'function')
|
|
175
|
+
return ownedWorkspaces.instructionSource(runId, path);
|
|
168
176
|
const source = sources(runId).find(source => source.path === path);
|
|
169
177
|
if (!source)
|
|
170
178
|
throw new ApiError(422, 'invalid_instruction_source', 'Workspace instruction source is unavailable.');
|
|
171
179
|
return Buffer.from(source.content);
|
|
172
180
|
} });
|
|
173
181
|
const checks = new TrustedCheckRegistry({ coordinator,
|
|
174
|
-
checks: configuration.checks.map(check => createPureArtifactCheck(check, { coordinator })),
|
|
182
|
+
checks: configuration.checks.map(check => 'command' in check ? createCommandCheck(check, { runner, store, assignEvidence: (id, artifactId) => application.engine.addInput(id, artifactId) }) : createPureArtifactCheck(check, { coordinator })),
|
|
175
183
|
validateRequest: request => {
|
|
176
184
|
const lease = ownedWorkspaces.lease(request.runId), artifact = store.get('artifacts', request.artifactId);
|
|
177
185
|
if (lease.id !== request.leaseId || lease.state !== 'active' || lease.knownRevisionId !== request.workspaceRevisionId ||
|
|
@@ -180,6 +188,7 @@ export async function openDeployment(input, ports = {}) {
|
|
|
180
188
|
throw new Error('stale_check_assignment');
|
|
181
189
|
} });
|
|
182
190
|
const driver = (ports.createDriver ?? (options => new CodexEngineDriver(options)))({
|
|
191
|
+
contextBytes: configuration.contextBytes ?? 65_536,
|
|
183
192
|
coordinator, broker, stateDirectory: runtimeDirectory, executable: configuration.runtime.executable,
|
|
184
193
|
runtimeId: LOCAL_RUNTIME_ID, providerId: LOCAL_PROVIDER_ID, modelPort: configuration.runtime.modelPort,
|
|
185
194
|
models: configuration.runtime.enabled ? configuration.runtime.models.map(model => model.id) : [],
|
|
@@ -195,6 +204,7 @@ export async function openDeployment(input, ports = {}) {
|
|
|
195
204
|
binding: { runId: binding.runId, sessionId: binding.sessionId, epoch: binding.epoch, stepExecutionId: binding.stepExecutionId,
|
|
196
205
|
profileVersionId: binding.profileVersionId, role: binding.role }, state: 'started', startedAt: new Date().toISOString() });
|
|
197
206
|
}),
|
|
207
|
+
recordProviderDiagnostic: diagnostic => store.setPrivate('provider_diagnostic', diagnostic.binding.sessionId, { ...diagnostic, at: new Date().toISOString() }),
|
|
198
208
|
recordProviderSettled: input => coordinator.atomic(() => {
|
|
199
209
|
const original = store.private('provider_request', input.id);
|
|
200
210
|
if (!original || original.state !== 'started' || original.binding.sessionId !== input.binding.sessionId ||
|
|
@@ -203,15 +213,17 @@ export async function openDeployment(input, ports = {}) {
|
|
|
203
213
|
store.setPrivate('provider_request', input.id, { ...original, state: input.outcome, settledAt: new Date().toISOString() });
|
|
204
214
|
coordinator.afterCommit(() => application.engine.wake(input.binding.runId));
|
|
205
215
|
}),
|
|
216
|
+
runtimeToolResult: (binding, request, result) => developer.runtimeResult(binding, request, result),
|
|
206
217
|
async recordTool(binding, request, result) {
|
|
207
218
|
coordinator.atomic(() => { observations.terminal(binding, request.invocationId, result); application.engine.projection.syncSql(binding.runId); });
|
|
208
219
|
application.engine.wake(binding.runId);
|
|
209
220
|
},
|
|
210
221
|
});
|
|
211
|
-
application = createApplication({ store, auth, publication, validation, broker, workspaces, pins, schemas, checks, driver,
|
|
222
|
+
application = createApplication({ store, auth, publication, validation, broker, workspaces, pins, schemas, checks, driver, coding: { runner, developer, configuration },
|
|
212
223
|
deploymentPolicy: configuration.deploymentPolicy, workspaceInstructions: runId => workspaceInstructionsFromSources(sources(runId)) });
|
|
213
224
|
application.engine.restoreInterrupted();
|
|
214
225
|
let listening;
|
|
226
|
+
developer.recoverQuestions();
|
|
215
227
|
const readyApplication = application;
|
|
216
228
|
return { ...application, configuration, tools, broker, store, validation, driver,
|
|
217
229
|
listen() {
|
|
@@ -2,8 +2,22 @@ import { EngineStore } from '../storage/store.js';
|
|
|
2
2
|
import { AuthService } from './auth.js';
|
|
3
3
|
import { Paging } from './paging.js';
|
|
4
4
|
import { ApiError } from './errors.js';
|
|
5
|
+
import { durationMs } from '../engine/timing.js';
|
|
5
6
|
export function historyHandlers(store, auth, paging) {
|
|
6
7
|
const handlers = new Map();
|
|
8
|
+
const publicRun = (value) => {
|
|
9
|
+
if (value.state !== 'cancelled' || value.executionControl.status !== 'paused' || value.executionControl.pausedAt)
|
|
10
|
+
return value;
|
|
11
|
+
// Older cancellations discarded the pause metadata required by the wire
|
|
12
|
+
// schema. Project it from the durable cancellation receipt without rewriting
|
|
13
|
+
// historical records or inventing a resumable continuation for a terminal run.
|
|
14
|
+
const operation = store.list('operations', { runId: value.id, limit: Number.MAX_SAFE_INTEGER }).map(r => r.value).find(op => op.kind === 'cancel');
|
|
15
|
+
if (!operation)
|
|
16
|
+
return value;
|
|
17
|
+
return { ...value, executionControl: { continuationState: 'interrupted', pauseOperationId: operation.id, requestedAt: operation.createdAt,
|
|
18
|
+
graceDeadlineAt: new Date(Date.parse(operation.createdAt) + durationMs(value.policy.pauseGracePeriod ?? '30s')).toISOString(),
|
|
19
|
+
...value.executionControl, pausedAt: value.completedAt ?? operation.updatedAt } };
|
|
20
|
+
};
|
|
7
21
|
const run = (context, id) => {
|
|
8
22
|
const value = store.get('runs', id);
|
|
9
23
|
auth.assertWorkspace(context.principal, value.workspaceId);
|
|
@@ -24,7 +38,7 @@ export function historyHandlers(store, auth, paging) {
|
|
|
24
38
|
return store.coordinator.db.prepare(`SELECT body,seq FROM engine_resources WHERE kind='runs' AND seq>?
|
|
25
39
|
AND (EXISTS(SELECT 1 FROM json_each(?) WHERE value='*') OR json_extract(body,'$.workspaceId') IN (SELECT value FROM json_each(?)))
|
|
26
40
|
ORDER BY seq LIMIT ?`).all(after, scope, scope, limit)
|
|
27
|
-
.map(row => ({ value: JSON.parse(row.body), seq: row.seq }));
|
|
41
|
+
.map(row => ({ value: publicRun(JSON.parse(row.body)), seq: row.seq }));
|
|
28
42
|
}) }));
|
|
29
43
|
const collections = [
|
|
30
44
|
['listRunStepExecutions', 'steps'], ['listRunSessions', 'sessions'], ['listRunSubmissions', 'submissions'],
|
|
@@ -49,7 +63,7 @@ export function historyHandlers(store, auth, paging) {
|
|
|
49
63
|
run(context, runId);
|
|
50
64
|
if (context.principal.audience === 'adapter' && (kind !== 'artifacts' || !access(context, runId).inputArtifactIds.includes(id)))
|
|
51
65
|
throw new ApiError(403, 'assignment_forbidden', 'Artifact is not in the current assignment.');
|
|
52
|
-
return { status: 200, headers: { ETag: store.etag(kind, id) }, body };
|
|
66
|
+
return { status: 200, headers: { ETag: store.etag(kind, id) }, body: kind === 'runs' ? publicRun(body) : body };
|
|
53
67
|
});
|
|
54
68
|
handlers.set('getSessionAssignment', context => {
|
|
55
69
|
if (context.principal.audience !== 'adapter' || context.principal.sessionId !== context.params.sessionId)
|
|
@@ -24,7 +24,7 @@ export function workspaceHandlers(store, workspaces, auth, paging) {
|
|
|
24
24
|
if (!context.principal.workspaceIds.includes('*'))
|
|
25
25
|
throw new ApiError(403, 'workspace_registration_forbidden', 'Workspace registration requires an unrestricted operator.');
|
|
26
26
|
let receipt;
|
|
27
|
-
workspaces.register(context.body, { onAdmittedSql(body) {
|
|
27
|
+
workspaces.register({ sourceTracking: true, ...context.body }, { onAdmittedSql(body) {
|
|
28
28
|
receipt = { status: 201, headers: { Location: `/api/v1/workspaces/${body.id}`, ETag: etag(body) }, body };
|
|
29
29
|
store.saveReceipt(identity, receipt);
|
|
30
30
|
} });
|
package/dist/src/tools/checks.js
CHANGED
|
@@ -21,7 +21,7 @@ export class TrustedCheckRegistry {
|
|
|
21
21
|
}
|
|
22
22
|
if (check.parametersSchema !== undefined)
|
|
23
23
|
canonical(check.parametersSchema);
|
|
24
|
-
this.checks.set(check.id, Object.freeze({ id: check.id, description: check.description, version: check.version,
|
|
24
|
+
this.checks.set(check.id, Object.freeze({ id: check.id, description: check.description, version: check.version, ...(check.timeoutMs === undefined ? {} : { timeoutMs: check.timeoutMs }),
|
|
25
25
|
...(check.parametersSchema === undefined ? {} : { parametersSchema: jsonCopy(check.parametersSchema) }),
|
|
26
26
|
execute: (request, signal) => this.execute(check, request, signal) }));
|
|
27
27
|
}
|
|
@@ -31,6 +31,17 @@ export class TrustedCheckRegistry {
|
|
|
31
31
|
...(check.parametersSchema === undefined ? {} : { parametersSchema: jsonCopy(check.parametersSchema) }) }));
|
|
32
32
|
}
|
|
33
33
|
get(id) { return this.checks.get(id); }
|
|
34
|
+
register(check) {
|
|
35
|
+
if (!check.id || !check.description || !check.version || typeof check.execute !== 'function')
|
|
36
|
+
throw new CheckRegistryError('invalid_check_registration');
|
|
37
|
+
const prior = this.checks.get(check.id);
|
|
38
|
+
if (prior) {
|
|
39
|
+
if (prior.version !== check.version)
|
|
40
|
+
throw new CheckRegistryError('check_version_conflict');
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
this.checks.set(check.id, Object.freeze({ ...check, execute: (request, signal) => this.execute(check, request, signal) }));
|
|
44
|
+
}
|
|
34
45
|
preflight(ids) {
|
|
35
46
|
if (new Set(ids).size !== ids.length || ids.some(id => !this.checks.has(id)))
|
|
36
47
|
throw new CheckRegistryError("unknown_named_check");
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
export function createCommandCheck(definition, options) {
|
|
3
|
+
const pinned = structuredClone(definition), definitionDigest = createHash('sha256').update(JSON.stringify(pinned)).digest('hex');
|
|
4
|
+
return { id: pinned.id, description: pinned.description, version: pinned.version, timeoutMs: pinned.timeoutMs ?? 600_000,
|
|
5
|
+
async execute(request, signal) {
|
|
6
|
+
const submission = options.store.list('submissions', { runId: request.runId, limit: Number.MAX_SAFE_INTEGER }).find(s => s.value.artifactId === request.artifactId)?.value;
|
|
7
|
+
if (!submission || signal.aborted)
|
|
8
|
+
return { status: 'infrastructure_error', code: 'check_assignment_unavailable', retryable: false, explanation: 'The exact candidate is unavailable.' };
|
|
9
|
+
const authority = options.store.private('session_authority', submission.sessionId);
|
|
10
|
+
const command = await options.runner.start(authority.binding, { command: pinned.command, ...(pinned.cwd === undefined ? {} : { cwd: pinned.cwd }), ...(pinned.env === undefined ? {} : { env: pinned.env }), timeoutMs: Math.max(1, Math.min(pinned.timeoutMs ?? 600_000, request.deadlineAt - Date.now())), readOnly: true, background: true });
|
|
11
|
+
const abort = () => { void options.runner.stop(command.id); };
|
|
12
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
13
|
+
let record = options.runner.get(command.id);
|
|
14
|
+
try {
|
|
15
|
+
while (record.state === 'running') {
|
|
16
|
+
await new Promise(resolve => setTimeout(resolve, 25));
|
|
17
|
+
record = options.runner.get(command.id);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
signal.removeEventListener('abort', abort);
|
|
22
|
+
}
|
|
23
|
+
const stdout = options.runner.output(record.id, 'stdout', 0, 16_384).text, stderr = options.runner.output(record.id, 'stderr', 0, 16_384).text;
|
|
24
|
+
const content = JSON.stringify({ checkId: pinned.id, definitionDigest, environment: pinned.env ?? {}, workspaceRevisionId: request.workspaceRevisionId, command: record, stdout, stderr });
|
|
25
|
+
const id = randomUUID();
|
|
26
|
+
options.store.put('artifacts', { id, runId: request.runId, stepExecutionId: request.stepExecutionId, kind: 'check_evidence', document: { mediaType: 'application/json', content }, contentDigest: createHash('sha256').update(content).digest('hex'), state: 'accepted', createdAt: new Date().toISOString() }, { runId: request.runId, immutable: true });
|
|
27
|
+
options.assignEvidence(submission.sessionId, id);
|
|
28
|
+
options.store.setPrivate('check_evidence', `${request.runId}:${request.workspaceRevisionId}:${pinned.id}`, { artifactId: id, definitionDigest, commandId: record.id, status: record.state === 'completed' ? 'pass' : 'fail' });
|
|
29
|
+
options.store.event(request.runId, 'check_completed', 'artifact', id, { checkId: pinned.id, commandId: record.id, workspaceRevisionId: request.workspaceRevisionId, status: record.state });
|
|
30
|
+
if (record.state === 'uncertain')
|
|
31
|
+
return { status: 'infrastructure_error', code: 'check_process_uncertain', retryable: false, explanation: 'Command settlement requires reconciliation.' };
|
|
32
|
+
return { status: record.state === 'completed' ? 'pass' : 'fail', evidenceArtifactIds: [id], explanation: `${pinned.description}: ${record.state}, exit ${record.exitCode}.\n${stderr || stdout || '(No output)'}` };
|
|
33
|
+
} };
|
|
34
|
+
}
|