code60-transmission-server 0.0.0-stage → 0.1.0-staging.2

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 (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +291 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +104 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,25 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { openDeployment, parseStartupArguments } from './server/deployment.js';
3
+ /** No environment/home discovery, ambient credentials, shell, auto-build, or
4
+ * automatic provider login. Every input path must be explicitly supplied. */
5
+ export async function main(argv = process.argv.slice(2)) {
6
+ const deployment = await openDeployment(parseStartupArguments(argv));
7
+ let stopping;
8
+ const stop = () => {
9
+ stopping ??= deployment.close().catch(() => { process.stderr.write('Engine shutdown requires reconciliation.\n'); process.exitCode = 1; });
10
+ };
11
+ process.once('SIGINT', stop);
12
+ process.once('SIGTERM', stop);
13
+ try {
14
+ await deployment.listen();
15
+ }
16
+ catch (error) {
17
+ process.removeListener('SIGINT', stop);
18
+ process.removeListener('SIGTERM', stop);
19
+ await deployment.close();
20
+ throw error;
21
+ }
22
+ }
23
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
24
+ void main().catch(() => { process.stderr.write('Engine startup failed. Check the explicit private deployment configuration and writer barrier.\n'); process.exitCode = 1; });
25
+ }
@@ -0,0 +1,71 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import contract from '../server/api-contract.json' with { type: 'json' };
3
+ // Publish standalone JSON schemas so clients can validate without resolving the OpenAPI document.
4
+ function expandSchema(value) {
5
+ if (Array.isArray(value))
6
+ return value.map(expandSchema);
7
+ if (!value || typeof value !== 'object')
8
+ return value;
9
+ const schema = value;
10
+ if (typeof schema.$ref === 'string') {
11
+ const prefix = '#/components/schemas/';
12
+ const name = schema.$ref.slice(prefix.length);
13
+ if (!schema.$ref.startsWith(prefix) || !Object.hasOwn(contract.components.schemas, name))
14
+ throw new Error('Unknown API schema reference.');
15
+ const { $ref, ...siblings } = schema;
16
+ const target = contract.components.schemas[name];
17
+ return expandSchema({ ...target, ...siblings });
18
+ }
19
+ // OpenAPI discriminator mappings are redundant with the tagged JSON Schema branches.
20
+ const { discriminator, ...keywords } = schema;
21
+ return Object.fromEntries(Object.entries(keywords).map(([key, child]) => [key, expandSchema(child)]));
22
+ }
23
+ function resolveParameter(entry) {
24
+ if (!('$ref' in entry))
25
+ return entry;
26
+ const name = entry.$ref.split('/').at(-1);
27
+ return contract.components.parameters[name];
28
+ }
29
+ const headerArguments = { 'Idempotency-Key': 'idempotencyKey', 'If-Match': 'ifMatch' };
30
+ export function operatorCatalog() {
31
+ const catalog = new Map();
32
+ const ajv = new Ajv2020({ strict: false, ownProperties: true });
33
+ for (const [path, methods] of Object.entries(contract.paths)) {
34
+ for (const [method, operation] of Object.entries(methods)) {
35
+ if (!['operator', 'operator-or-scoped-adapter'].includes(operation['x-audience']))
36
+ continue;
37
+ if (method !== 'get' && method !== 'post')
38
+ throw new Error('Unsupported operator HTTP method.');
39
+ const parameters = [];
40
+ const properties = {};
41
+ const required = [];
42
+ for (const entry of operation.parameters ?? []) {
43
+ const parameter = resolveParameter(entry);
44
+ if (parameter.name === 'X-Session-Epoch')
45
+ continue;
46
+ const argument = parameter.in === 'header' ? headerArguments[parameter.name] : parameter.name;
47
+ if (!argument)
48
+ throw new Error('Unsupported operator header.');
49
+ parameters.push({ argument, parameter });
50
+ properties[argument] = { ...expandSchema(parameter.schema),
51
+ ...(parameter.description ? { description: parameter.description } : {}) };
52
+ if (parameter.required)
53
+ required.push(argument);
54
+ }
55
+ const inputSchema = { type: 'object', properties, required, additionalProperties: false };
56
+ // The engine validates the actual body and returns its authoritative Problem with paths and request ID.
57
+ if (operation.requestBody) {
58
+ properties.body = {};
59
+ required.push('body');
60
+ }
61
+ const validate = ajv.compile(structuredClone(inputSchema));
62
+ if (operation.requestBody)
63
+ properties.body = expandSchema(operation.requestBody.content['application/json'].schema);
64
+ const name = operation.operationId.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase());
65
+ const tool = { name, description: operation.summary, inputSchema,
66
+ annotations: { readOnlyHint: method === 'get' } };
67
+ catalog.set(name, { tool, method: method === 'get' ? 'GET' : 'POST', path, parameters, validate });
68
+ }
69
+ }
70
+ return catalog;
71
+ }
@@ -0,0 +1,24 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { readOperatorToken } from '../config/deployment.js';
5
+ import { createWorkflowServer } from './server.js';
6
+ export async function main(argv = process.argv.slice(2)) {
7
+ const { values } = parseArgs({ args: argv, options: { port: { type: 'string' }, 'operator-token-file': { type: 'string' } } });
8
+ const port = Number(values.port), file = values['operator-token-file'];
9
+ if (!file || !values.port || !/^[0-9]+$/.test(values.port) || port < 1 || port > 65535)
10
+ throw new Error('Invalid bridge configuration.');
11
+ const server = createWorkflowServer(port, readOperatorToken(file));
12
+ const close = () => { void server.close(); };
13
+ process.stdin.once('end', close);
14
+ process.stdin.once('error', close);
15
+ process.stdout.once('error', close);
16
+ process.once('SIGINT', close);
17
+ process.once('SIGTERM', close);
18
+ await server.connect(new StdioServerTransport());
19
+ }
20
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
21
+ void main().catch(() => {
22
+ process.stderr.write('Code60 MCP startup failed. Supply --port and --operator-token-file with an absolute private token path.\n');
23
+ process.exitCode = 1;
24
+ });
@@ -0,0 +1,104 @@
1
+ import { request } from 'node:http';
2
+ import { json } from 'node:stream/consumers';
3
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
+ import { CallToolRequestSchema, ErrorCode, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
+ import { workflowLanguageSchema } from '../config/workflow-language.js';
6
+ import { operatorCatalog } from './catalog.js';
7
+ const example = {
8
+ kind: 'Workflow', version: '1', metadata: { name: 'first-workflow' },
9
+ config: { 'agent-profiles': { worker: 'REPLACE_WITH_WORKER_VERSION_ID' } },
10
+ steps: [{ id: 'answer', instructions: [{ kind: 'inline', text: 'Return a JSON object with a message string.' }],
11
+ execution: { 'max-session-resets': 0, 'max-attempts-per-session': 2 },
12
+ exitArtifact: { schema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] } },
13
+ exitCriteria: { deterministic: { checks: [] } } }],
14
+ };
15
+ const resources = [
16
+ { uri: 'code60://workflow/schema', name: 'Workflow language schema', mimeType: 'application/schema+json', value: workflowLanguageSchema() },
17
+ { uri: 'code60://workflow/example', name: 'Minimal single-step workflow', mimeType: 'application/json', value: example },
18
+ ];
19
+ const instructions = [
20
+ 'Operate the configured local Code60 Transmission Server with its operator workspace scope.',
21
+ 'Discover runtimes and checks, register an authorized standalone Git repository, and publish profiles before workflows.',
22
+ 'Workspaces must be existing standalone Git repositories with a real .git directory, at least one commit, no linked worktrees, no stale lock files, and no hardlinked files in .git. Do not run git init or git commit inside a sandbox that blocks file deletion (which leaves hardlinked tmp_obj_* files in .git); have the user prepare the repository directly on disk or clone with --no-hardlinks.',
23
+ 'Use latestVersionId to pin profiles in workflow source and to select a workflow version in create_run.',
24
+ 'Read the workflow schema and example through resources/list and resources/read.',
25
+ 'POST tools take the engine request body under body and a caller-chosen idempotencyKey. Retry an uncertain outcome with the same arguments.',
26
+ 'For conditional writes, read the target and pass its exact etag as ifMatch. Reassess the target after a conflict.',
27
+ 'Results contain status, body and available receipt metadata. A 202 admits work. Inspect the run or poll get_operation for its outcome.',
28
+ 'For live events use follow=true, pass each nextCursor to the next call, and set waitSeconds up to 30. Save the run ID and cursor for reconnect.',
29
+ ].join(' ');
30
+ function result(data, isError = false) {
31
+ return { structuredContent: data, content: [{ type: 'text', text: JSON.stringify(data) }], isError };
32
+ }
33
+ async function callEngine(entry, args, port, token, signal) {
34
+ if (!entry.validate(args))
35
+ return result({ code: 'invalid_arguments', errors: entry.validate.errors?.map(issue => ({ path: issue.instancePath, code: issue.keyword, message: issue.message })) }, true);
36
+ let path = entry.path;
37
+ const query = new URLSearchParams();
38
+ const headers = { authorization: 'Bearer ' + token };
39
+ for (const { argument, parameter } of entry.parameters) {
40
+ if (!Object.hasOwn(args, argument))
41
+ continue;
42
+ const value = String(args[argument]);
43
+ if (parameter.in === 'path')
44
+ path = path.replace('{' + parameter.name + '}', encodeURIComponent(value));
45
+ else if (parameter.in === 'query')
46
+ query.set(parameter.name, value);
47
+ else {
48
+ if (!/^[\x20-\x7e]+$/.test(value) || value.trim() !== value)
49
+ return result({ code: 'invalid_arguments', detail: argument + ' must be a single printable HTTP header value without surrounding whitespace.' }, true);
50
+ headers[parameter.name] = value;
51
+ }
52
+ }
53
+ if (entry.method === 'POST')
54
+ headers['content-type'] = 'application/json';
55
+ try {
56
+ // A direct socket to the configured loopback port. Never follow redirects or use an ambient proxy.
57
+ const response = await new Promise((resolve, reject) => {
58
+ const outgoing = request({ host: '127.0.0.1', port, agent: false, method: entry.method,
59
+ path: '/api/v1' + path + (query.size ? '?' + query : ''), headers,
60
+ signal: AbortSignal.any([signal, AbortSignal.timeout(60_000)]) }, resolve);
61
+ outgoing.once('error', reject);
62
+ outgoing.end(entry.method === 'POST' ? JSON.stringify(args.body) : undefined);
63
+ });
64
+ const status = response.statusCode;
65
+ if (status >= 300 && status < 400) {
66
+ response.destroy();
67
+ return result({ code: 'engine_redirect', status, detail: 'The configured engine returned a redirect.' }, true);
68
+ }
69
+ const receipt = { status, body: await json(response) };
70
+ if (response.headers.etag)
71
+ receipt.etag = response.headers.etag;
72
+ if (response.headers.location)
73
+ receipt.location = response.headers.location;
74
+ const replay = response.headers['idempotent-replay'];
75
+ if (replay !== undefined)
76
+ receipt.idempotentReplay = replay === 'true';
77
+ if (JSON.stringify(receipt).includes(token))
78
+ return result({ code: 'credential_in_response' }, true);
79
+ return result(receipt, status >= 400);
80
+ }
81
+ catch {
82
+ return result({ code: signal.aborted ? 'request_cancelled' : 'engine_unavailable',
83
+ detail: 'The bridge could not read an engine receipt. Retry a command with its original key and arguments.' }, true);
84
+ }
85
+ }
86
+ export function createWorkflowServer(port, token) {
87
+ const catalog = operatorCatalog();
88
+ const server = new Server({ name: 'code60-workflows', version: '0.1.0' }, { capabilities: { tools: {}, resources: {} }, instructions });
89
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Array.from(catalog.values(), entry => entry.tool) }));
90
+ server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => {
91
+ const entry = catalog.get(params.name);
92
+ if (!entry)
93
+ throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 operator tool.');
94
+ return callEngine(entry, params.arguments ?? {}, port, token, signal);
95
+ });
96
+ server.setRequestHandler(ListResourcesRequestSchema, () => ({ resources: resources.map(({ value, ...info }) => info) }));
97
+ server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => {
98
+ const resource = resources.find(item => item.uri === params.uri);
99
+ if (!resource)
100
+ throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 workflow resource.');
101
+ return { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: JSON.stringify(resource.value, null, 2) }] };
102
+ });
103
+ return server;
104
+ }
@@ -0,0 +1,91 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import { isolatedRuntimeEnvironment, runtimeSeatbeltProfile } from './containment.js';
4
+ import { assertNoRuntimeInstructionAliases } from './workspace-view.js';
5
+ import { startupLockIdentity } from '../broker/startup-lock.js';
6
+ import { CodexProtocolClient } from './protocol-client.js';
7
+ function configValue(value) {
8
+ if (typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' && Number.isFinite(value))
9
+ return JSON.stringify(value);
10
+ if (Array.isArray(value))
11
+ return `[${value.map(configValue).join(', ')}]`;
12
+ if (value && typeof value === 'object')
13
+ return `{ ${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)} = ${configValue(item)}`).join(', ')} }`;
14
+ throw new Error('unsupported_runtime_config_value');
15
+ }
16
+ /** Trusted client API. Arbitrary app-server administrative methods are absent. */
17
+ export class ContainedCodexAppServer extends CodexProtocolClient {
18
+ #stateDirectory;
19
+ constructor(options) {
20
+ assertNoRuntimeInstructionAliases(options.stateDirectory);
21
+ const executable = realpathSync(options.executable);
22
+ if (options.startupLockFd !== undefined)
23
+ startupLockIdentity(options.startupLockFd);
24
+ const overrides = Object.entries(options.config).flatMap(([key, value]) => [
25
+ '-c', `${key}=${configValue(value)}`,
26
+ ]);
27
+ const child = spawn('/usr/bin/sandbox-exec', [
28
+ '-p', runtimeSeatbeltProfile({
29
+ executable, stateDirectory: options.stateDirectory, modelPort: options.modelPort,
30
+ }),
31
+ executable, ...overrides, 'app-server', '--listen', 'stdio://',
32
+ ], {
33
+ cwd: options.stateDirectory,
34
+ env: isolatedRuntimeEnvironment(options.stateDirectory),
35
+ stdio: ['pipe', 'pipe', 'pipe', ...(options.startupLockFd === undefined ? [] : [options.startupLockFd])],
36
+ }); // The first three streams are always pipes.
37
+ super(child, options.protocolPool ? { pool: options.protocolPool } : {});
38
+ this.#stateDirectory = options.stateDirectory;
39
+ }
40
+ startTurn(params) {
41
+ assertNoRuntimeInstructionAliases(this.#stateDirectory);
42
+ return super.startTurn(params);
43
+ }
44
+ }
45
+ export function pilotCodexConfig(modelPort) {
46
+ return {
47
+ model: 'gpt-5.3-codex',
48
+ model_provider: 'code60-pilot',
49
+ 'model_providers.code60-pilot.name': 'Code60 synthetic local model',
50
+ 'model_providers.code60-pilot.base_url': `http://127.0.0.1:${modelPort}/v1`,
51
+ 'model_providers.code60-pilot.wire_api': 'responses',
52
+ 'model_providers.code60-pilot.requires_openai_auth': false,
53
+ 'model_providers.code60-pilot.request_max_retries': 0,
54
+ 'model_providers.code60-pilot.stream_max_retries': 0,
55
+ approval_policy: 'never',
56
+ project_doc_max_bytes: 0,
57
+ include_permissions_instructions: false,
58
+ include_collaboration_mode_instructions: false,
59
+ include_apps_instructions: false,
60
+ include_environment_context: false,
61
+ 'tools.experimental_request_user_input.enabled': false,
62
+ 'tools.update_plan.enabled': false,
63
+ check_for_update_on_startup: false,
64
+ web_search: 'disabled',
65
+ 'analytics.enabled': false,
66
+ 'feedback.enabled': false,
67
+ 'skills.bundled.enabled': false,
68
+ 'skills.include_instructions': false,
69
+ 'features.shell_tool': false,
70
+ 'features.unified_exec': false,
71
+ 'features.apps': false,
72
+ 'features.connectors': false,
73
+ 'features.plugins': false,
74
+ 'features.hooks': false,
75
+ 'features.plugin_hooks': false,
76
+ 'features.multi_agent': false,
77
+ 'features.collab': false,
78
+ 'features.browser_use': false,
79
+ 'features.computer_use': false,
80
+ 'features.image_generation': false,
81
+ 'features.view_image': false,
82
+ 'features.code_mode': false,
83
+ 'features.js_repl': false,
84
+ 'features.memories': false,
85
+ 'features.memory_tool': false,
86
+ 'features.goals': false,
87
+ 'features.skip_host_skill_discovery': true,
88
+ 'features.responses_websockets': false,
89
+ 'features.responses_websockets_v2': false,
90
+ };
91
+ }
@@ -0,0 +1,82 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { dirname, isAbsolute } from 'node:path';
3
+ function quotedPath(path) {
4
+ if (!isAbsolute(path) || /[\u0000-\u001f]/u.test(path)) {
5
+ throw new Error('Containment paths must be absolute and contain no controls');
6
+ }
7
+ return JSON.stringify(path);
8
+ }
9
+ function ancestors(path) {
10
+ const result = new Set();
11
+ for (let current = dirname(path); current !== '/'; current = dirname(current))
12
+ result.add(current);
13
+ return [...result];
14
+ }
15
+ /**
16
+ * Fail-closed outer containment for a runtime that must never access a managed
17
+ * project directly. This is not authorization for native model tools.
18
+ */
19
+ export function runtimeSeatbeltProfile(options) {
20
+ if (!Number.isInteger(options.modelPort) || options.modelPort < 1 || options.modelPort > 65535) {
21
+ throw new Error('Invalid local model port');
22
+ }
23
+ const executable = quotedPath(realpathSync(options.executable));
24
+ const statePath = realpathSync(options.stateDirectory);
25
+ const state = quotedPath(statePath);
26
+ const stateFiles = [
27
+ '.sandbox_migration', 'installation_id',
28
+ ...['goals_1', 'logs_2', 'memories_1', 'queue_1', 'state_5'].flatMap(name => ['.sqlite', '.sqlite-wal', '.sqlite-shm'].map(suffix => name + suffix)),
29
+ ].map(name => `(literal ${quotedPath(statePath + '/' + name)})`).join('\n ');
30
+ const traversal = [...new Set([
31
+ ...ancestors(realpathSync(options.executable)), ...ancestors(statePath), '/dev',
32
+ ])].map(path => `(literal ${quotedPath(path)})`).join('\n ');
33
+ return `(version 1)
34
+ (deny default)
35
+ (deny file-test-existence)
36
+ (allow process-fork)
37
+ (allow process-info* (target same-sandbox))
38
+ (allow signal (target same-sandbox))
39
+ (allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))
40
+ (allow sysctl-read)
41
+ ; Approved trusted-runtime compatibility exception, metadata/existence only.
42
+ ; This is not model/tool authorization and grants no file data or directory listing.
43
+ (allow file-read-metadata file-test-existence
44
+ (subpath "/etc") (subpath "/private/etc"))
45
+ (allow file-read-metadata file-test-existence ${traversal} (subpath ${state})
46
+ (subpath ${quotedPath(dirname(dirname(realpathSync(options.executable))))}))
47
+ (allow file-read* file-test-existence
48
+ (literal "/")
49
+ (subpath "/usr")
50
+ (subpath "/bin")
51
+ (subpath "/sbin")
52
+ (subpath "/System")
53
+ (subpath "/Library/Apple")
54
+ (subpath "/private/var/db/dyld")
55
+ (literal "/dev/null")
56
+ (literal "/dev/urandom")
57
+ (literal "/dev/random")
58
+ (literal ${executable})
59
+ (literal ${state})
60
+ ${stateFiles}
61
+ (subpath ${quotedPath(statePath + '/tmp')})
62
+ (subpath ${quotedPath(statePath + '/sessions')}))
63
+ (allow file-write* (subpath ${state}) (literal "/dev/null"))
64
+ (allow process-exec (literal ${executable}))
65
+ (allow network-outbound (remote ip "localhost:${options.modelPort}"))
66
+ `;
67
+ }
68
+ export function isolatedRuntimeEnvironment(stateDirectory) {
69
+ const state = realpathSync(stateDirectory);
70
+ return {
71
+ HOME: state,
72
+ CODEX_HOME: state,
73
+ XDG_CONFIG_HOME: state + '/xdg/config',
74
+ XDG_CACHE_HOME: state + '/xdg/cache',
75
+ XDG_DATA_HOME: state + '/xdg/data',
76
+ TMPDIR: state + '/tmp',
77
+ PATH: '/usr/bin:/bin',
78
+ LANG: 'en_US.UTF-8',
79
+ LC_ALL: 'en_US.UTF-8',
80
+ NO_COLOR: '1',
81
+ };
82
+ }
@@ -0,0 +1,212 @@
1
+ import { lstatSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
+ import { ApiError } from '../server/errors.js';
4
+ import { ContainedCodexAppServer, pilotCodexConfig } from './codex-app-server.js';
5
+ import { protocolPool } from './protocol-pool.js';
6
+ import { BrokeredCodexRuntime } from './runtime-broker.js';
7
+ import { verifyWorkspaceInstructionSnapshot } from './workspace-view.js';
8
+ import { ProviderBridge } from './provider-bridge.js';
9
+ /** One real contained Codex process and fresh provider thread per engine
10
+ * session. There is no provider reconnect, ambient login or native tool path. */
11
+ export class CodexEngineDriver {
12
+ options;
13
+ #entries = new Map();
14
+ #starting = new Map();
15
+ #result;
16
+ #failure;
17
+ constructor(options) {
18
+ this.options = options;
19
+ options.coordinator.assertOutsideTransaction();
20
+ if (!isAbsolute(options.stateDirectory))
21
+ throw new ApiError(422, 'unsafe_runtime_directory', 'Runtime state requires a private absolute directory.');
22
+ const root = lstatSync(options.stateDirectory);
23
+ if (!root.isDirectory() || root.isSymbolicLink() || root.uid !== process.geteuid?.() || root.mode & 0o77)
24
+ throw new ApiError(422, 'unsafe_runtime_directory', 'Runtime state requires a private owned directory.');
25
+ }
26
+ onResult(callback) { this.#result = callback; }
27
+ onFailure(callback) { this.#failure = callback; }
28
+ alive(sessionId) {
29
+ const entry = this.#entries.get(sessionId);
30
+ return !!entry && !entry.broken && !entry.stopping && entry.codex.child.pid !== undefined &&
31
+ entry.codex.child.exitCode === null && entry.codex.child.signalCode === null;
32
+ }
33
+ active(sessionId) { return this.#entries.get(sessionId)?.busy ?? false; }
34
+ activeWork(runId) {
35
+ return [...this.#starting.values()].filter(start => start.runId === runId).length +
36
+ [...this.#entries.values()].reduce((sum, entry) => sum + (entry.launch.session.runId === runId ?
37
+ Number(!!(entry.starting || entry.stopping)) + entry.bookkeeping + entry.codex.activeWork + entry.runtime.activeWork + (entry.provider?.activeWork ?? 0) : 0), 0);
38
+ }
39
+ async start(launch) {
40
+ this.options.coordinator.assertOutsideTransaction();
41
+ if (!this.#result || !this.#failure)
42
+ throw new Error('driver_callbacks_required');
43
+ if (this.#entries.has(launch.session.id) || this.#starting.has(launch.session.id))
44
+ throw new Error('runtime_session_already_started');
45
+ const definition = launch.session.effectiveConfiguration.definition, selected = definition.runtime;
46
+ const provider = this.options.providers?.find(provider => provider.id === selected.provider);
47
+ const model = provider?.models.find(model => model.id === selected.model);
48
+ if (selected.runtimeId !== this.options.runtimeId ||
49
+ (provider ? !model || !this.options.credentials || !this.options.validation || !this.options.admitModel :
50
+ selected.provider !== this.options.providerId || !this.options.models.includes(selected.model)) ||
51
+ selected.effort !== undefined && !(model?.effortLevels ?? this.options.modelEfforts[selected.model])?.includes(selected.effort) ||
52
+ (provider ? !selected.credentialRefs?.provider || Object.keys(selected.credentialRefs).some(slot => slot !== 'provider') :
53
+ Object.keys(selected.credentialRefs ?? {}).length !== 0) ||
54
+ Object.keys(selected.options ?? {}).some(key => key !== 'artifactFormat') ||
55
+ selected.options?.artifactFormat !== undefined && !['json', 'yaml'].includes(String(selected.options.artifactFormat)))
56
+ throw new ApiError(422, 'unsupported_runtime_configuration', 'The selected runtime configuration is unavailable.');
57
+ verifyWorkspaceInstructionSnapshot(launch.workspaceInstructions);
58
+ const credential = provider ? this.options.credentials.describe(selected.credentialRefs.provider, provider.id, new URL(provider.endpoint).origin) : undefined;
59
+ const effort = selected.effort ?? model?.defaultEffort;
60
+ let finish;
61
+ const starting = { runId: launch.session.runId, cancelled: false, done: new Promise(resolve => { finish = resolve; }) };
62
+ this.#starting.set(launch.session.id, starting);
63
+ let bridge, owner;
64
+ try {
65
+ if (provider)
66
+ bridge = await ProviderBridge.open({
67
+ coordinator: this.options.coordinator, validation: this.options.validation, spoolRoot: this.options.stateDirectory,
68
+ runId: launch.session.runId, provider, model: selected.model, effort: effort, credential: credential,
69
+ admit: () => {
70
+ const current = this.#entries.get(launch.session.id);
71
+ if (starting.cancelled || !current || current.starting || current.stopping || current.broken || !current.busy || !current.runtime.modelActive)
72
+ throw new Error('runtime_model_held');
73
+ this.options.admitModel(launch.binding);
74
+ },
75
+ resolveCredential: () => this.options.credentials.resolve(credential, provider.id),
76
+ ...(this.options.createProviderTransport ? { createTransport: this.options.createProviderTransport } : {}),
77
+ started: request => this.options.recordProviderStarted?.({ ...request, binding: launch.binding, providerId: provider.id,
78
+ model: selected.model, effort: effort, credential: credential }),
79
+ settled: request => this.options.recordProviderSettled?.({ ...request, binding: launch.binding }),
80
+ onFailure: () => {
81
+ const current = this.#entries.get(launch.session.id);
82
+ if (current && !current.stopping && !current.broken) {
83
+ current.broken = true;
84
+ void this.#failure(launch.session.id, 'runtime_provider_bookkeeping_failed').catch(() => { });
85
+ }
86
+ },
87
+ });
88
+ if (starting.cancelled)
89
+ throw new Error('runtime_session_stopped');
90
+ const state = mkdtempSync(join(realpathSync(this.options.stateDirectory), `${launch.session.id}-`));
91
+ mkdirSync(join(state, 'tmp'), { mode: 0o700 });
92
+ const modelPort = bridge?.clientConfiguration.modelPort ?? this.options.modelPort;
93
+ const config = { ...pilotCodexConfig(modelPort), model: selected.model,
94
+ ...(effort === undefined ? {} : { model_reasoning_effort: effort }),
95
+ ...(bridge ? { 'model_providers.code60-pilot.http_headers': bridge.clientConfiguration.headers } : {}) };
96
+ const codex = (this.options.createClient ?? (options => new ContainedCodexAppServer(options)))({
97
+ executable: this.options.executable, stateDirectory: state, protocolPool: protocolPool(this.options.coordinator),
98
+ modelPort, startupLockFd: this.options.startupLockFd, config
99
+ });
100
+ const bound = this.options.broker.bind(launch.binding);
101
+ const runtime = new BrokeredCodexRuntime(codex, { ...bound, invoke: async (request) => {
102
+ const result = await bound.invoke(request);
103
+ entry.bookkeeping++;
104
+ try {
105
+ await this.options.recordTool?.(launch.binding, request, result);
106
+ }
107
+ finally {
108
+ entry.bookkeeping--;
109
+ }
110
+ return result;
111
+ } }, async (params) => {
112
+ if (entry.stopping)
113
+ return;
114
+ const completed = params;
115
+ if (completed.turn?.status !== 'completed') {
116
+ await this.#failure(launch.session.id, 'runtime_turn_failed');
117
+ return;
118
+ }
119
+ const text = completed.turn.items?.filter(item => item.type === 'agentMessage').at(-1)?.text;
120
+ await this.#result(launch.session.id, typeof text === 'string' ? text : '');
121
+ });
122
+ const exit = codex.exited;
123
+ const entry = { launch: structuredClone(launch), codex, runtime, busy: false, starting: true, broken: false, bookkeeping: 0, exit,
124
+ ...(bridge ? { provider: bridge } : {}) };
125
+ owner = entry;
126
+ this.#entries.set(launch.session.id, entry);
127
+ const failed = () => {
128
+ if (entry.stopping || entry.broken)
129
+ return;
130
+ entry.broken = true;
131
+ void this.#failure(launch.session.id, 'runtime_connection_lost').catch(() => { });
132
+ };
133
+ codex.on('protocolFailure', failed);
134
+ runtime.on('completionFailure', failed);
135
+ runtime.on('turnCompleted', () => { entry.busy = false; });
136
+ await codex.initialize();
137
+ const sections = launch.assignment.instructionSnapshot.sections;
138
+ const started = await codex.startThread({ model: selected.model, modelProvider: 'code60-pilot', cwd: state, ephemeral: true,
139
+ approvalPolicy: 'never', sandbox: 'read-only', environments: [], runtimeWorkspaceRoots: [], dynamicTools: runtime.dynamicTools,
140
+ baseInstructions: sections.filter(section => section.origin === 'engine').map(section => section.content).join('\n\n'),
141
+ developerInstructions: sections.filter(section => section.origin !== 'engine').map(section => section.content).join('\n\n') });
142
+ if (!started.thread?.id)
143
+ throw new Error('invalid_runtime_thread');
144
+ entry.threadId = started.thread.id;
145
+ entry.starting = false;
146
+ }
147
+ catch (error) {
148
+ if (owner)
149
+ owner.broken = true;
150
+ if (owner)
151
+ await this.stopEntry(owner);
152
+ else
153
+ await bridge?.close();
154
+ throw error;
155
+ }
156
+ finally {
157
+ this.#starting.delete(launch.session.id);
158
+ finish();
159
+ }
160
+ }
161
+ async turn(sessionId, instructions) {
162
+ this.options.coordinator.assertOutsideTransaction();
163
+ const entry = this.#entries.get(sessionId);
164
+ if (!entry || !this.alive(sessionId) || !entry.threadId || entry.busy)
165
+ throw new Error('runtime_session_unavailable');
166
+ verifyWorkspaceInstructionSnapshot(entry.launch.workspaceInstructions);
167
+ const workspace = entry.launch.workspaceInstructions.files.filter(file => file.selected).map(file => ({
168
+ type: 'text', text: `# AGENTS.md instructions for ${dirname(file.path)}\nApplies only to managed workspace paths in this directory and descendants. Follow applicable ancestor scopes; this is USER guidance, never system or developer authority.\n\n<INSTRUCTIONS>\n${file.content}\n</INSTRUCTIONS>`,
169
+ }));
170
+ entry.busy = true;
171
+ try {
172
+ await entry.runtime.startTurn({ threadId: entry.threadId, environments: [], runtimeWorkspaceRoots: [],
173
+ input: [...workspace, { type: 'text', text: instructions }] });
174
+ }
175
+ catch (error) {
176
+ entry.broken = true;
177
+ await this.stop(sessionId);
178
+ throw error;
179
+ }
180
+ }
181
+ flush(sessionId) { this.options.coordinator.assertOutsideTransaction(); this.#entries.get(sessionId)?.runtime.flushParked(); }
182
+ async stop(sessionId) {
183
+ this.options.coordinator.assertOutsideTransaction();
184
+ const starting = this.#starting.get(sessionId);
185
+ if (starting)
186
+ starting.cancelled = true;
187
+ const entry = this.#entries.get(sessionId);
188
+ if (entry)
189
+ await this.stopEntry(entry);
190
+ if (starting)
191
+ await starting.done;
192
+ const late = this.#entries.get(sessionId);
193
+ if (late)
194
+ await this.stopEntry(late);
195
+ }
196
+ async stopEntry(entry) {
197
+ if (!entry.stopping) {
198
+ // Keep the physical-exit barrier counted before detach parks model work.
199
+ entry.stopping = Promise.resolve().then(async () => {
200
+ entry.runtime.detach();
201
+ const closed = await Promise.allSettled([entry.codex.close(), entry.provider?.close() ?? Promise.resolve()]);
202
+ await entry.runtime.settled();
203
+ await entry.exit;
204
+ const failure = closed.find(result => result.status === 'rejected');
205
+ if (failure?.status === 'rejected')
206
+ throw failure.reason;
207
+ this.#entries.delete(entry.launch.session.id);
208
+ });
209
+ }
210
+ await entry.stopping;
211
+ }
212
+ }