code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.16

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.
Files changed (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +36 -345
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +60 -0
  5. package/dist/src/engine.js +481 -0
  6. package/dist/src/main.js +70 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +423 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -1,34 +0,0 @@
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
- }
@@ -1,312 +0,0 @@
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
- }