code60-transmission-server 0.0.0-stage → 0.1.0-staging.13
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/LICENSE +180 -0
- package/README.engine.md +463 -0
- package/README.md +376 -2
- package/dist/src/broker/filesystem.js +385 -0
- package/dist/src/broker/index.js +777 -0
- package/dist/src/broker/native/README.md +207 -0
- package/dist/src/broker/native/build.js +46 -0
- package/dist/src/broker/native/command-helper.c +93 -0
- package/dist/src/broker/native/fs-helper.c +529 -0
- package/dist/src/broker/native/git-helper.c +205 -0
- package/dist/src/broker/policy.js +149 -0
- package/dist/src/broker/startup-lock.js +14 -0
- package/dist/src/broker/types.js +11 -0
- package/dist/src/cli/configure.js +208 -0
- package/dist/src/cli/daemon.js +369 -0
- package/dist/src/cli/helpers.js +112 -0
- package/dist/src/cli/main.js +189 -0
- package/dist/src/cli/runtime-build.js +38 -0
- package/dist/src/config/coding-policy.js +4 -0
- package/dist/src/config/deployment.js +183 -0
- package/dist/src/config/documents.js +29 -0
- package/dist/src/config/profile-validation.js +129 -0
- package/dist/src/config/schema-graph.js +237 -0
- package/dist/src/config/schema-loader.js +185 -0
- package/dist/src/config/validation-pool.js +105 -0
- package/dist/src/config/validation-protocol.js +1 -0
- package/dist/src/config/validation-worker.js +106 -0
- package/dist/src/config/workflow-language.js +9 -0
- package/dist/src/config/workflow-schema.json +545 -0
- package/dist/src/config/workflow-types.js +1 -0
- package/dist/src/config/workflow-validation.js +95 -0
- package/dist/src/engine/budgets.js +50 -0
- package/dist/src/engine/clocks.js +27 -0
- package/dist/src/engine/commands.js +477 -0
- package/dist/src/engine/contracts.js +11 -0
- package/dist/src/engine/drain-state.js +31 -0
- package/dist/src/engine/effective-permissions.js +120 -0
- package/dist/src/engine/instruction-pins.js +205 -0
- package/dist/src/engine/retries.js +50 -0
- package/dist/src/engine/state.js +1 -0
- package/dist/src/engine/timing.js +23 -0
- package/dist/src/engine/tool-observations.js +87 -0
- package/dist/src/engine/workflow-engine.js +1864 -0
- package/dist/src/main.js +28 -0
- package/dist/src/mcp/catalog.js +71 -0
- package/dist/src/mcp/main.js +26 -0
- package/dist/src/mcp/server.js +177 -0
- package/dist/src/runtime/codex-app-server.js +91 -0
- package/dist/src/runtime/codex-executable.js +50 -0
- package/dist/src/runtime/containment.js +82 -0
- package/dist/src/runtime/engine-driver.js +221 -0
- package/dist/src/runtime/json-line-writer.js +192 -0
- package/dist/src/runtime/pinned-instruction-sources.js +24 -0
- package/dist/src/runtime/protocol-client.js +264 -0
- package/dist/src/runtime/protocol-pool.js +183 -0
- package/dist/src/runtime/protocol-projection.js +393 -0
- package/dist/src/runtime/protocol-types.js +1 -0
- package/dist/src/runtime/protocol-worker.js +18 -0
- package/dist/src/runtime/provider-bridge.js +290 -0
- package/dist/src/runtime/provider-credentials.js +41 -0
- package/dist/src/runtime/provider-transport.js +406 -0
- package/dist/src/runtime/runtime-broker.js +213 -0
- package/dist/src/runtime/workspace-instructions.js +120 -0
- package/dist/src/runtime/workspace-view.js +74 -0
- package/dist/src/server/api-contract.json +11637 -0
- package/dist/src/server/api-types.js +1 -0
- package/dist/src/server/application.js +44 -0
- package/dist/src/server/auth.js +67 -0
- package/dist/src/server/broker-handlers.js +242 -0
- package/dist/src/server/coding.js +281 -0
- package/dist/src/server/control-plane.js +50 -0
- package/dist/src/server/deployment.js +249 -0
- package/dist/src/server/errors.js +22 -0
- package/dist/src/server/history-handlers.js +130 -0
- package/dist/src/server/http.js +124 -0
- package/dist/src/server/paging.js +56 -0
- package/dist/src/server/publication.js +119 -0
- package/dist/src/server/tool-event-handler.js +77 -0
- package/dist/src/server/workspace-handlers.js +34 -0
- package/dist/src/storage/coordinator.js +224 -0
- package/dist/src/storage/startup-lock.js +71 -0
- package/dist/src/storage/store.js +167 -0
- package/dist/src/tools/check-worker.js +81 -0
- package/dist/src/tools/checks.js +117 -0
- package/dist/src/tools/command-check.js +34 -0
- package/dist/src/tools/commands.js +312 -0
- package/dist/src/tools/developer.js +355 -0
- package/dist/src/tools/dns.js +248 -0
- package/dist/src/tools/http-contract.js +38 -0
- package/dist/src/tools/http.js +358 -0
- package/dist/src/tools/index.js +194 -0
- package/dist/src/tools/worker-check.js +73 -0
- package/dist/src/workspaces/git.js +227 -0
- package/dist/src/workspaces/index.js +937 -0
- package/dist/src/workspaces/source.js +295 -0
- package/examples/deployment.local.json +22 -0
- package/package.json +71 -4
- package/scripts/postinstall.mjs +26 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { closeSync, constants, existsSync, mkdirSync, openSync, readSync, realpathSync, statSync, writeFileSync, writeSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, join } from 'node:path';
|
|
5
|
+
import { SourceRepository, within } from '../workspaces/source.js';
|
|
6
|
+
import { BrokerError } from '../broker/types.js';
|
|
7
|
+
import { digest, evaluatePolicy } from '../broker/policy.js';
|
|
8
|
+
import { isTrustedHelper } from '../cli/helpers.js';
|
|
9
|
+
export const DEFAULT_COMMAND_SETTINGS = { enabled: false, network: 'outbound', toolchainPaths: [], generatedPaths: ['node_modules', 'dist', 'build', 'coverage', '.cache', '.next', 'target', '.venv', 'tsconfig.tsbuildinfo', '.eslintcache'], timeoutMs: 600_000, maxOutputBytes: 67_108_864 };
|
|
10
|
+
/** A trusted refusal before any command intent, source gate, or process exists. */
|
|
11
|
+
export class CommandAdmissionError extends BrokerError {
|
|
12
|
+
}
|
|
13
|
+
const quote = (s) => JSON.stringify(s);
|
|
14
|
+
const groupAlive = (pid) => { try {
|
|
15
|
+
process.kill(-pid, 0);
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
if (e.code === 'ESRCH')
|
|
20
|
+
return false;
|
|
21
|
+
throw e;
|
|
22
|
+
} };
|
|
23
|
+
export function assertCommandScope(binding, readOnly) {
|
|
24
|
+
const operations = readOnly ? ['read'] : ['read', 'write', 'delete'];
|
|
25
|
+
for (const policy of [binding.permissions, binding.deploymentPermissions]) {
|
|
26
|
+
const rules = policy.rules.filter(r => r.kind === 'filesystem' && r.root === 'workspace');
|
|
27
|
+
for (const operation of operations) {
|
|
28
|
+
if (!rules.some(r => r.kind === 'filesystem' && r.path === '.' && r.recursive && r.effect !== 'deny' && r.operations.includes(operation)) ||
|
|
29
|
+
rules.some(r => r.kind === 'filesystem' && r.operations.includes(operation) && (r.effect === 'deny' || r.path !== '.' && r.effect === 'require_approval')))
|
|
30
|
+
throw new CommandAdmissionError('command_requires_whole_workspace_scope', 403);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** All process work remains owned until the process group and output writers settle. */
|
|
35
|
+
export class CommandRunner {
|
|
36
|
+
options;
|
|
37
|
+
running = new Map();
|
|
38
|
+
settings;
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.options = options;
|
|
41
|
+
this.settings = { ...DEFAULT_COMMAND_SETTINGS, ...options.settings };
|
|
42
|
+
mkdirSync(options.directory, { recursive: true, mode: 0o700 });
|
|
43
|
+
options.store.coordinator.atomic(() => { options.store.coordinator.db.prepare("UPDATE engine_private SET body=json_set(body,'$.state','uncertain','$.error','process_lost_requires_reconciliation') WHERE scope='command' AND json_extract(body,'$.state')='running'").run(); });
|
|
44
|
+
}
|
|
45
|
+
save(record) { this.options.store.setPrivate('command', record.id, record); }
|
|
46
|
+
get(id, binding) {
|
|
47
|
+
const record = this.options.store.private('command', id);
|
|
48
|
+
if (!record || binding && (record.runId !== binding.runId || record.sessionId !== binding.sessionId || record.epoch !== binding.epoch))
|
|
49
|
+
throw new BrokerError('command_not_assigned', 404);
|
|
50
|
+
return record;
|
|
51
|
+
}
|
|
52
|
+
records(runId) { return this.options.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='command' AND json_extract(body,'$.runId')=? ORDER BY rowid").all(runId).map(r => JSON.parse(r.body)); }
|
|
53
|
+
activeWork(runId) { return this.records(runId).filter(r => r.state === 'running' || r.state === 'uncertain').length; }
|
|
54
|
+
profile(repository, state, readOnly, generatedPaths, id) {
|
|
55
|
+
const nodeDirectory = dirname(realpathSync(process.execPath)), nodeRoot = basename(nodeDirectory) === 'bin' ? dirname(nodeDirectory) : nodeDirectory;
|
|
56
|
+
const toolchains = [...new Set(['/usr', '/bin', '/sbin', '/System', '/Library/Developer/CommandLineTools', '/Library/Apple', nodeRoot, ...this.settings.toolchainPaths.map(p => realpathSync(p))])];
|
|
57
|
+
const generated = generatedPaths.map(p => repository.safePath(p, true));
|
|
58
|
+
if (this.options.protectedPaths.some(p => within(repository.root, p) || within(p, repository.root)))
|
|
59
|
+
throw new BrokerError('protected_command_workspace', 403);
|
|
60
|
+
const protectedPaths = [...this.options.protectedPaths, repository.gitDirectory, repository.commonDirectory, join(repository.root, '.git')];
|
|
61
|
+
const rules = ['(version 1)', '(deny default)', '(allow process-fork)', '(allow process-info* (target same-sandbox))', '(allow signal (target same-sandbox))', '(allow sysctl-read)', '(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))',
|
|
62
|
+
`(allow mach-lookup (global-name ${quote(`code60.command.${id}.allow`)}))`, `(deny mach-lookup (global-name ${quote(`code60.command.${id}.deny`)}))`,
|
|
63
|
+
`(allow file-read* process-exec (literal ${quote(this.options.workspaces.commandHelperPath)}))`,
|
|
64
|
+
...(this.settings.network === 'outbound' ? ['(allow mach-lookup (global-name "com.apple.mDNSResponder") (global-name "com.apple.trustd") (global-name "com.apple.trustd.agent"))'] : []),
|
|
65
|
+
'(allow file-read-metadata file-test-existence)',
|
|
66
|
+
`(allow file-read* (literal "/") (subpath ${quote(repository.root)}) (subpath ${quote(repository.gitDirectory)}) (subpath ${quote(repository.commonDirectory)}) (subpath ${quote(state)}) ${toolchains.map(p => `(subpath ${quote(p)})`).join(' ')} (subpath "/private/var/db/dyld") (literal "/dev/null") (literal "/dev/urandom") (literal "/dev/random") (subpath "/etc") (subpath "/private/etc"))`,
|
|
67
|
+
`(allow process-exec ${[repository.root, ...toolchains].map(p => `(subpath ${quote(p)})`).join(' ')})`,
|
|
68
|
+
`(allow file-write* (subpath ${quote(state)}) (literal "/dev/null") ${readOnly ? generated.map(p => `(subpath ${quote(p)})`).join(' ') : `(subpath ${quote(repository.root)})`})`,
|
|
69
|
+
...protectedPaths.map(p => `(deny file-write* (require-all (subpath ${quote(p)}) (require-not (subpath ${quote(state)}))))`),
|
|
70
|
+
...this.options.protectedPaths.map(p => `(deny file-read-data (require-all (subpath ${quote(p)}) (require-not (subpath ${quote(state)})) (require-not (literal ${quote(this.options.workspaces.commandHelperPath)}))))`),
|
|
71
|
+
...(this.settings.network === 'outbound' ? ['(allow network-outbound)', '(allow network-bind (local ip "localhost:*"))', '(allow network-inbound (local ip "localhost:*"))'] : [])];
|
|
72
|
+
if (readOnly)
|
|
73
|
+
for (const entry of repository.sourceEntries())
|
|
74
|
+
rules.push(`(deny file-write* (literal ${quote(join(repository.root, entry.path))}))`);
|
|
75
|
+
return rules.join('\n');
|
|
76
|
+
}
|
|
77
|
+
async start(binding, request) {
|
|
78
|
+
if (binding.role !== 'worker' && !request.readOnly)
|
|
79
|
+
throw new CommandAdmissionError('project_read_only', 403);
|
|
80
|
+
if (!this.settings.enabled)
|
|
81
|
+
throw new CommandAdmissionError('commands_not_configured', 422);
|
|
82
|
+
if (!isTrustedHelper(this.options.workspaces.commandHelperPath))
|
|
83
|
+
throw new CommandAdmissionError('command_supervisor_unavailable', 422);
|
|
84
|
+
assertCommandScope(binding, request.readOnly ?? false);
|
|
85
|
+
if (typeof request.command !== 'string' || !request.command.trim() || request.command.length > 65_536 || request.command.includes('\0'))
|
|
86
|
+
throw new CommandAdmissionError('invalid_command', 400);
|
|
87
|
+
const timeoutMs = request.timeoutMs ?? this.settings.timeoutMs;
|
|
88
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 86_400_000)
|
|
89
|
+
throw new CommandAdmissionError('invalid_command_timeout', 400);
|
|
90
|
+
if (request.env && Object.entries(request.env).some(([k, v]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || typeof v !== 'string' || v.includes('\0') || /^(HOME|CODEX_HOME|XDG_.*|TMPDIR|DYLD_.*|LD_.*|PATH|GIT_.*)$/i.test(k)))
|
|
91
|
+
throw new CommandAdmissionError('invalid_command_environment', 400);
|
|
92
|
+
const repository = this.options.workspaces.sourceRepository(binding.runId);
|
|
93
|
+
if (!repository)
|
|
94
|
+
throw new CommandAdmissionError('source_tracking_required', 422);
|
|
95
|
+
let cwd;
|
|
96
|
+
try {
|
|
97
|
+
cwd = repository.safePath(request.cwd ?? '.', false, true);
|
|
98
|
+
if (!statSync(cwd).isDirectory())
|
|
99
|
+
throw new CommandAdmissionError('command_cwd_not_directory', 422);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
|
|
103
|
+
throw new CommandAdmissionError('command_cwd_not_found', 422);
|
|
104
|
+
if (['EACCES', 'EPERM'].includes(error.code ?? ''))
|
|
105
|
+
throw new CommandAdmissionError('command_cwd_forbidden', 403);
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const readOnly = request.readOnly ?? false;
|
|
109
|
+
if (this.records(binding.runId).some(r => r.state === 'running' && (!readOnly || !r.readOnly)))
|
|
110
|
+
throw new CommandAdmissionError('workspace_command_active');
|
|
111
|
+
const id = randomUUID(), state = join(this.options.directory, id);
|
|
112
|
+
mkdirSync(state, { mode: 0o700 });
|
|
113
|
+
mkdirSync(join(state, 'tmp'), { mode: 0o700 });
|
|
114
|
+
mkdirSync(join(state, 'cache'), { mode: 0o700 });
|
|
115
|
+
// Source read-only roles can still run builds when both authorities grant
|
|
116
|
+
// writes/deletes to specific declared generated directories. Never turn a
|
|
117
|
+
// grant to one cache into permission for every generated path.
|
|
118
|
+
const generated = this.settings.generatedPaths.filter(path => [binding.permissions, binding.deploymentPermissions].every(policy => ['write', 'delete'].every(operation => {
|
|
119
|
+
const rules = policy.rules.filter(r => r.kind === 'filesystem' && r.root === 'workspace' && r.operations.includes(operation));
|
|
120
|
+
return evaluatePolicy(policy, 'run_command', [{ kind: 'filesystem', root: 'workspace', path, operation: operation, identityDigest: 'sha256:' + '0'.repeat(64) }]) === 'allow' &&
|
|
121
|
+
rules.some(r => r.kind === 'filesystem' && r.effect === 'allow' && r.recursive && (r.path === '.' || r.path === path || path.startsWith(r.path + '/'))) &&
|
|
122
|
+
!rules.some(r => r.kind === 'filesystem' && r.effect !== 'allow' && r.path.startsWith(path + '/'));
|
|
123
|
+
})));
|
|
124
|
+
const profile = join(state, 'sandbox.sb');
|
|
125
|
+
writeFileSync(profile, this.profile(repository, state, readOnly, generated, id), { mode: 0o600 });
|
|
126
|
+
const before = this.options.workspaces.beginCommand(binding.runId, !readOnly);
|
|
127
|
+
const record = { id, runId: binding.runId, sessionId: binding.sessionId, epoch: binding.epoch, command: request.command, cwd: request.cwd ?? '.', readOnly, state: 'running', beforeRevisionId: before.id,
|
|
128
|
+
executionConfigurationDigest: digest({ settings: this.settings, environment: request.env ?? {}, shell: '/bin/sh' }),
|
|
129
|
+
stdoutBytes: 0, stderrBytes: 0, truncated: false, startedAt: new Date().toISOString() };
|
|
130
|
+
this.save(record);
|
|
131
|
+
const stdout = openSync(join(state, 'stdout'), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600), stderr = openSync(join(state, 'stderr'), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
|
|
132
|
+
let child;
|
|
133
|
+
try {
|
|
134
|
+
child = spawn(this.options.workspaces.commandHelperPath, [id, '/usr/bin/sandbox-exec', '-f', profile, this.options.workspaces.commandHelperPath, '--worker', '/bin/sh', '-c', request.command], { cwd, detached: true,
|
|
135
|
+
env: { HOME: state, TMPDIR: join(state, 'tmp'), XDG_CACHE_HOME: join(state, 'cache'), npm_config_cache: join(state, 'cache'), PATH: [...this.settings.toolchainPaths, dirname(realpathSync(process.execPath)), '/usr/bin', '/bin', '/usr/sbin', '/sbin'].join(':'), LANG: 'en_US.UTF-8', CI: '1', ...request.env },
|
|
136
|
+
stdio: ['pipe', 'pipe', 'pipe', this.options.startupLockFd ?? 'ignore', 'pipe'] });
|
|
137
|
+
}
|
|
138
|
+
catch (e) {
|
|
139
|
+
closeSync(stdout);
|
|
140
|
+
closeSync(stderr);
|
|
141
|
+
record.state = 'failed';
|
|
142
|
+
record.error = 'command_spawn_failed';
|
|
143
|
+
this.options.workspaces.settleCommand(binding.runId, !readOnly, before.id);
|
|
144
|
+
this.save(record);
|
|
145
|
+
throw e;
|
|
146
|
+
}
|
|
147
|
+
if (child.pid) {
|
|
148
|
+
record.pid = child.pid;
|
|
149
|
+
this.save(record);
|
|
150
|
+
}
|
|
151
|
+
let stopState, supervisedReady = false;
|
|
152
|
+
const signalStop = () => { if (child.pid)
|
|
153
|
+
try {
|
|
154
|
+
process.kill(-child.pid, 'SIGTERM');
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
if (e.code !== 'ESRCH')
|
|
158
|
+
throw e;
|
|
159
|
+
} };
|
|
160
|
+
const stop = (state = 'cancelled') => {
|
|
161
|
+
stopState ??= state;
|
|
162
|
+
if (supervisedReady)
|
|
163
|
+
signalStop();
|
|
164
|
+
};
|
|
165
|
+
const spool = (fd, key, chunk) => {
|
|
166
|
+
try {
|
|
167
|
+
const remaining = Math.max(0, this.settings.maxOutputBytes - record.stdoutBytes - record.stderrBytes), bytes = chunk.subarray(0, remaining);
|
|
168
|
+
let offset = 0;
|
|
169
|
+
while (offset < bytes.length)
|
|
170
|
+
offset += writeSync(fd, bytes, offset, bytes.length - offset);
|
|
171
|
+
record[key] += bytes.length;
|
|
172
|
+
if (bytes.length !== chunk.length)
|
|
173
|
+
record.truncated = true;
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
record.error = 'command_output_write_failed';
|
|
177
|
+
stop();
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
child.stdout.on('data', (b) => spool(stdout, 'stdoutBytes', b));
|
|
181
|
+
child.stderr.on('data', (b) => spool(stderr, 'stderrBytes', b));
|
|
182
|
+
child.stdin.on('error', () => { });
|
|
183
|
+
let proofText = '', proof;
|
|
184
|
+
const proofPipe = child.stdio[4];
|
|
185
|
+
proofPipe.on('data', (b) => {
|
|
186
|
+
if (proofText.length + b.length > 4096)
|
|
187
|
+
return;
|
|
188
|
+
proofText += b.toString('utf8');
|
|
189
|
+
let newline;
|
|
190
|
+
while ((newline = proofText.indexOf('\n')) >= 0) {
|
|
191
|
+
const line = proofText.slice(0, newline);
|
|
192
|
+
proofText = proofText.slice(newline + 1);
|
|
193
|
+
try {
|
|
194
|
+
const entry = JSON.parse(line);
|
|
195
|
+
if (entry.ready) {
|
|
196
|
+
supervisedReady = true;
|
|
197
|
+
if (stopState)
|
|
198
|
+
signalStop();
|
|
199
|
+
}
|
|
200
|
+
else
|
|
201
|
+
proof = entry;
|
|
202
|
+
}
|
|
203
|
+
catch { /* Missing valid settlement proof retains the lease. */ }
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
const signal = this.options.signal(binding.runId), abort = () => stop();
|
|
207
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
208
|
+
if (signal.aborted)
|
|
209
|
+
stop();
|
|
210
|
+
const timer = setTimeout(() => stop('timed_out'), timeoutMs);
|
|
211
|
+
const done = new Promise(resolveDone => {
|
|
212
|
+
child.once('error', () => { record.error = 'command_spawn_failed'; });
|
|
213
|
+
child.once('close', (code, signalName) => {
|
|
214
|
+
clearTimeout(timer);
|
|
215
|
+
signal.removeEventListener('abort', abort);
|
|
216
|
+
closeSync(stdout);
|
|
217
|
+
closeSync(stderr);
|
|
218
|
+
const finish = () => {
|
|
219
|
+
try {
|
|
220
|
+
if (record.error === 'command_spawn_failed') {
|
|
221
|
+
this.options.workspaces.settleCommand(binding.runId, !readOnly, before.id);
|
|
222
|
+
record.state = 'failed';
|
|
223
|
+
}
|
|
224
|
+
else if (!proof?.settled) {
|
|
225
|
+
record.state = 'uncertain';
|
|
226
|
+
record.error = 'command_process_proof_unavailable';
|
|
227
|
+
}
|
|
228
|
+
else if (child.pid && groupAlive(child.pid)) {
|
|
229
|
+
record.state = 'uncertain';
|
|
230
|
+
record.error = 'command_descendants_unsettled';
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
const after = this.options.workspaces.settleCommand(binding.runId, !readOnly, before.id);
|
|
234
|
+
record.afterRevisionId = after.id;
|
|
235
|
+
record.state = stopState ?? (proof.exitCode === 0 && !record.error ? 'completed' : 'failed');
|
|
236
|
+
code = proof.exitCode;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
record.state = 'uncertain';
|
|
241
|
+
record.error = 'command_source_reconciliation_failed';
|
|
242
|
+
}
|
|
243
|
+
record.exitCode = code;
|
|
244
|
+
record.signal = signalName;
|
|
245
|
+
record.completedAt = new Date().toISOString();
|
|
246
|
+
this.save(record);
|
|
247
|
+
this.running.delete(id);
|
|
248
|
+
this.options.wake(binding.runId);
|
|
249
|
+
resolveDone(record);
|
|
250
|
+
};
|
|
251
|
+
if (child.pid && groupAlive(child.pid)) {
|
|
252
|
+
try {
|
|
253
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
254
|
+
}
|
|
255
|
+
catch { /* uncertainty is retained */ }
|
|
256
|
+
setTimeout(finish, 100);
|
|
257
|
+
}
|
|
258
|
+
else
|
|
259
|
+
finish();
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
this.running.set(id, { record, child, done, stop });
|
|
263
|
+
return request.background ? { ...record } : done;
|
|
264
|
+
}
|
|
265
|
+
output(id, stream = 'stdout', cursor = 0, limit = 65_536, binding) {
|
|
266
|
+
const record = this.get(id, binding);
|
|
267
|
+
if (!['stdout', 'stderr'].includes(stream) || !Number.isSafeInteger(cursor) || cursor < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 262_144)
|
|
268
|
+
throw new BrokerError('invalid_output_cursor', 400);
|
|
269
|
+
const path = join(this.options.directory, id, stream);
|
|
270
|
+
if (!existsSync(path))
|
|
271
|
+
return { text: '', nextCursor: null, record };
|
|
272
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW), bytes = Buffer.alloc(limit);
|
|
273
|
+
let count;
|
|
274
|
+
try {
|
|
275
|
+
count = readSync(fd, bytes, 0, bytes.length, cursor);
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
closeSync(fd);
|
|
279
|
+
}
|
|
280
|
+
// Cursor counts bytes, so splitting a multibyte sequence is visible and never loses bytes.
|
|
281
|
+
return { text: bytes.subarray(0, count).toString('utf8'), dataBase64: bytes.subarray(0, count).toString('base64'), nextCursor: count ? cursor + count : null, record: this.running.get(id)?.record ?? record };
|
|
282
|
+
}
|
|
283
|
+
input(id, text, binding, end = false) { this.get(id, binding); const running = this.running.get(id); if (!running || running.child.stdin.destroyed || running.child.stdin.writableEnded || Buffer.byteLength(text) > 65_536)
|
|
284
|
+
throw new BrokerError('command_not_running'); running.child.stdin.write(text); if (end)
|
|
285
|
+
running.child.stdin.end(); }
|
|
286
|
+
async stop(id, binding) { this.get(id, binding); const running = this.running.get(id); if (!running)
|
|
287
|
+
return this.get(id, binding); running.stop(); return running.done; }
|
|
288
|
+
recoveryRequired(runId) { return this.records(runId).some(r => r.state === 'uncertain'); }
|
|
289
|
+
reconcile(runId) {
|
|
290
|
+
const uncertain = this.records(runId).filter(r => r.state === 'uncertain');
|
|
291
|
+
if (!uncertain.length)
|
|
292
|
+
return;
|
|
293
|
+
if (uncertain.some(r => r.error === 'command_process_proof_unavailable'))
|
|
294
|
+
throw new BrokerError('command_process_proof_unavailable', 409);
|
|
295
|
+
if (uncertain.some(r => this.running.has(r.id) || r.pid && groupAlive(r.pid)))
|
|
296
|
+
throw new BrokerError('command_descendants_unsettled');
|
|
297
|
+
const resolution = this.options.store.private('command_resolution', runId);
|
|
298
|
+
if (!resolution)
|
|
299
|
+
throw new BrokerError('command_resolution_required');
|
|
300
|
+
const writer = uncertain.find(r => !r.readOnly) ?? uncertain[0];
|
|
301
|
+
this.options.workspaces.resolveStoppedCommand(runId, writer.beforeRevisionId, resolution);
|
|
302
|
+
for (const record of uncertain) {
|
|
303
|
+
record.state = 'failed';
|
|
304
|
+
record.error = 'interrupted_command_explicitly_reconciled';
|
|
305
|
+
record.completedAt = new Date().toISOString();
|
|
306
|
+
record.afterRevisionId = this.options.workspaces.lease(runId).knownRevisionId;
|
|
307
|
+
this.save(record);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async close() { await Promise.all([...this.running.keys()].map(id => this.stop(id))); if ([...this.options.store.coordinator.db.prepare("SELECT id FROM engine_private WHERE scope='command' AND json_extract(body,'$.state')='uncertain'").all()].length)
|
|
311
|
+
throw new Error('command_work_requires_reconciliation'); }
|
|
312
|
+
}
|