code60-transmission-server 0.1.0-staging.6 → 0.1.1

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 +87 -308
  3. package/dist/src/acp.js +130 -0
  4. package/dist/src/contract.js +133 -0
  5. package/dist/src/engine.js +650 -0
  6. package/dist/src/linux.js +84 -0
  7. package/dist/src/main.js +81 -25
  8. package/dist/src/repository.js +94 -0
  9. package/dist/src/service.js +196 -0
  10. package/package.json +19 -35
  11. package/reference/openapi.json +1073 -0
  12. package/README.engine.md +0 -463
  13. package/dist/src/broker/filesystem.js +0 -385
  14. package/dist/src/broker/index.js +0 -734
  15. package/dist/src/broker/native/README.md +0 -207
  16. package/dist/src/broker/native/build.js +0 -46
  17. package/dist/src/broker/native/command-helper.c +0 -93
  18. package/dist/src/broker/native/fs-helper.c +0 -529
  19. package/dist/src/broker/native/git-helper.c +0 -205
  20. package/dist/src/broker/policy.js +0 -149
  21. package/dist/src/broker/startup-lock.js +0 -14
  22. package/dist/src/broker/types.js +0 -11
  23. package/dist/src/cli/configure.js +0 -193
  24. package/dist/src/cli/daemon.js +0 -369
  25. package/dist/src/cli/helpers.js +0 -112
  26. package/dist/src/cli/main.js +0 -189
  27. package/dist/src/cli/runtime-build.js +0 -38
  28. package/dist/src/config/coding-policy.js +0 -4
  29. package/dist/src/config/deployment.js +0 -182
  30. package/dist/src/config/documents.js +0 -29
  31. package/dist/src/config/profile-validation.js +0 -123
  32. package/dist/src/config/schema-graph.js +0 -237
  33. package/dist/src/config/schema-loader.js +0 -185
  34. package/dist/src/config/validation-pool.js +0 -105
  35. package/dist/src/config/validation-protocol.js +0 -1
  36. package/dist/src/config/validation-worker.js +0 -106
  37. package/dist/src/config/workflow-language.js +0 -9
  38. package/dist/src/config/workflow-schema.json +0 -545
  39. package/dist/src/config/workflow-types.js +0 -1
  40. package/dist/src/config/workflow-validation.js +0 -95
  41. package/dist/src/engine/budgets.js +0 -50
  42. package/dist/src/engine/clocks.js +0 -27
  43. package/dist/src/engine/commands.js +0 -472
  44. package/dist/src/engine/contracts.js +0 -11
  45. package/dist/src/engine/drain-state.js +0 -31
  46. package/dist/src/engine/effective-permissions.js +0 -120
  47. package/dist/src/engine/instruction-pins.js +0 -205
  48. package/dist/src/engine/retries.js +0 -50
  49. package/dist/src/engine/state.js +0 -1
  50. package/dist/src/engine/timing.js +0 -23
  51. package/dist/src/engine/tool-observations.js +0 -87
  52. package/dist/src/engine/workflow-engine.js +0 -1862
  53. package/dist/src/mcp/catalog.js +0 -71
  54. package/dist/src/mcp/main.js +0 -26
  55. package/dist/src/mcp/server.js +0 -147
  56. package/dist/src/runtime/codex-app-server.js +0 -91
  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 -11614
  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 -254
  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 -127
  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 -310
  94. package/dist/src/tools/developer.js +0 -351
  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,71 +0,0 @@
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
- }
@@ -1,26 +0,0 @@
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' }, toolset: { type: 'string', default: 'coding' } } });
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
- if (!['coding', 'admin'].includes(values.toolset))
12
- throw new Error('Invalid toolset.');
13
- const server = createWorkflowServer(port, readOperatorToken(file), values.toolset);
14
- const close = () => { void server.close(); };
15
- process.stdin.once('end', close);
16
- process.stdin.once('error', close);
17
- process.stdout.once('error', close);
18
- process.once('SIGINT', close);
19
- process.once('SIGTERM', close);
20
- await server.connect(new StdioServerTransport());
21
- }
22
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
23
- void main().catch(() => {
24
- process.stderr.write('Code60 MCP startup failed. Supply --port and --operator-token-file with an absolute private token path.\n');
25
- process.exitCode = 1;
26
- });
@@ -1,147 +0,0 @@
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
- 'For coding, check readiness then call start_coding_task with an existing repository or registered workspace and the task description. Results default to an uncommitted baseline-relative diff with command logs and check evidence.',
22
- 'Git-aware workspaces support standalone repositories and linked worktrees with at least one commit, including staged and unstaged starting edits. Resolve unfinished Git operations before starting. Explicit sourceTracking:false retains the legacy standalone, clean-worktree requirements.',
23
- 'For low-level workflows, discover runtimes and checks, register an authorized repository, and publish profiles before workflows.',
24
- 'Use latestVersionId to pin profiles in workflow source and to select a workflow version in create_run.',
25
- 'Call get_workflow_schema and get_workflow_example for authoring. The workflow version is the string "1".',
26
- 'Call get_runtime_configuration and use the selected provider credentialReferences ID in credentialRefs.provider.',
27
- 'POST tools take the engine request body under body and a caller-chosen idempotencyKey. Retry an uncertain outcome with the same arguments.',
28
- 'For conditional writes, read the target and pass its exact etag as ifMatch. Reassess the target after a conflict.',
29
- 'Results contain status, body and available receipt metadata. A 202 admits work. Inspect the run or poll get_operation for its outcome.',
30
- '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.',
31
- ].join(' ');
32
- function result(data, isError = false) {
33
- return { structuredContent: data, content: [{ type: 'text', text: JSON.stringify(data) }], isError };
34
- }
35
- async function callEngine(entry, args, port, token, signal) {
36
- if (!entry.validate(args))
37
- return result({ code: 'invalid_arguments', errors: entry.validate.errors?.map(issue => ({ path: issue.instancePath, code: issue.keyword, message: issue.message })) }, true);
38
- let path = entry.path;
39
- const query = new URLSearchParams();
40
- const headers = { authorization: 'Bearer ' + token };
41
- for (const { argument, parameter } of entry.parameters) {
42
- if (!Object.hasOwn(args, argument))
43
- continue;
44
- const value = String(args[argument]);
45
- if (parameter.in === 'path')
46
- path = path.replace('{' + parameter.name + '}', encodeURIComponent(value));
47
- else if (parameter.in === 'query')
48
- query.set(parameter.name, value);
49
- else {
50
- if (!/^[\x20-\x7e]+$/.test(value) || value.trim() !== value)
51
- return result({ code: 'invalid_arguments', detail: argument + ' must be a single printable HTTP header value without surrounding whitespace.' }, true);
52
- headers[parameter.name] = value;
53
- }
54
- }
55
- if (entry.method === 'POST')
56
- headers['content-type'] = 'application/json';
57
- try {
58
- // A direct socket to the configured loopback port. Never follow redirects or use an ambient proxy.
59
- const response = await new Promise((resolve, reject) => {
60
- const outgoing = request({ host: '127.0.0.1', port, agent: false, method: entry.method,
61
- path: '/api/v1' + path + (query.size ? '?' + query : ''), headers,
62
- signal: AbortSignal.any([signal, AbortSignal.timeout(60_000)]) }, resolve);
63
- outgoing.once('error', reject);
64
- outgoing.end(entry.method === 'POST' ? JSON.stringify(args.body) : undefined);
65
- });
66
- const status = response.statusCode;
67
- if (status >= 300 && status < 400) {
68
- response.destroy();
69
- return result({ code: 'engine_redirect', status, detail: 'The configured engine returned a redirect.' }, true);
70
- }
71
- const receipt = { status, body: await json(response) };
72
- if (response.headers.etag)
73
- receipt.etag = response.headers.etag;
74
- if (response.headers.location)
75
- receipt.location = response.headers.location;
76
- const replay = response.headers['idempotent-replay'];
77
- if (replay !== undefined)
78
- receipt.idempotentReplay = replay === 'true';
79
- if (JSON.stringify(receipt).includes(token))
80
- return result({ code: 'credential_in_response' }, true);
81
- return result(receipt, status >= 400);
82
- }
83
- catch {
84
- return result({ code: signal.aborted ? 'request_cancelled' : 'engine_unavailable',
85
- detail: 'The bridge could not read an engine receipt. Retry a command with its original key and arguments.' }, true);
86
- }
87
- }
88
- export function createWorkflowServer(port, token, toolset = 'admin') {
89
- const catalog = operatorCatalog();
90
- const discoveryTools = [
91
- { name: 'get_workflow_schema', description: 'Get the workflow language JSON Schema, including required fields and supported values.',
92
- inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
93
- { name: 'get_workflow_example', description: 'Get a minimal valid workflow. Replace the worker profile version placeholder before validation.',
94
- inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
95
- ];
96
- const codingNames = new Set(['get_coding_readiness', 'start_coding_task', 'get_run', 'get_coding_task_result', 'list_run_events', 'send_task_message', 'list_task_questions', 'answer_task_question', 'list_run_approvals', 'get_approval', 'decide_approval', 'pause_run', 'resume_run', 'cancel_run', 'recover_run', 'get_operation']);
97
- const managedControls = new Set(['pause_run', 'resume_run', 'cancel_run', ...(toolset === 'coding' ? ['decide_approval'] : [])]);
98
- const codingInstructions = 'Use get_coding_readiness first, then start_coding_task with a task description, repositoryPath or workspaceId, and a stable idempotencyKey. Coding tasks run in the current folder, preserve existing edits, and leave the result uncommitted. Follow get_run/list_run_events; answer pending questions and inspect get_coding_task_result for the run-only diff and check evidence. If checks are absent the result explicitly says unverified. Send guidance with send_task_message. Low-level workflow administration remains available with --toolset admin.';
99
- const server = new Server({ name: 'code60-workflows', version: '0.1.0' }, { capabilities: { tools: {}, resources: {} }, instructions: toolset === 'coding' ? codingInstructions : instructions });
100
- server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [
101
- ...(toolset === 'admin' ? discoveryTools : []),
102
- ...[...catalog.values()].filter(entry => toolset === 'admin' || codingNames.has(entry.tool.name)).map(entry => {
103
- const tool = structuredClone(entry.tool);
104
- if (managedControls.has(tool.name)) {
105
- tool.inputSchema.required = tool.inputSchema.required?.filter(name => name !== 'ifMatch') ?? [];
106
- tool.description += ' Omit ifMatch to let the bridge refresh versions during active execution; supply it for an exact conditional write.';
107
- }
108
- return tool;
109
- }),
110
- ] }));
111
- server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => {
112
- if (params.name === 'get_workflow_schema' || params.name === 'get_workflow_example') {
113
- if (Object.keys(params.arguments ?? {}).length)
114
- return result({ code: 'invalid_arguments' }, true);
115
- return result({ status: 200, body: params.name === 'get_workflow_schema' ? resources[0].value : example });
116
- }
117
- const entry = catalog.get(params.name);
118
- if (!entry)
119
- throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 operator tool.');
120
- const args = params.arguments ?? {};
121
- if (args.ifMatch === undefined && managedControls.has(params.name)) {
122
- return (async () => {
123
- const target = params.name === 'decide_approval' ? catalog.get('get_approval') : catalog.get('get_run');
124
- for (let attempt = 0;; attempt++) {
125
- const read = await callEngine(target, params.name === 'decide_approval' ? { approvalId: args.approvalId } : { runId: args.runId }, port, token, signal);
126
- const receipt = read.structuredContent;
127
- if (read.isError || !receipt?.etag)
128
- return read;
129
- const written = await callEngine(entry, { ...args, ifMatch: receipt.etag }, port, token, signal);
130
- // A failed precondition has no receipt or side effects. Retain the
131
- // caller's key/body, and never retry an uncertain transport outcome.
132
- if (written.structuredContent?.status !== 412 || attempt >= 15 || signal.aborted)
133
- return written;
134
- }
135
- })();
136
- }
137
- return callEngine(entry, args, port, token, signal);
138
- });
139
- server.setRequestHandler(ListResourcesRequestSchema, () => ({ resources: resources.map(({ value, ...info }) => info) }));
140
- server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => {
141
- const resource = resources.find(item => item.uri === params.uri);
142
- if (!resource)
143
- throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 workflow resource.');
144
- return { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: JSON.stringify(resource.value, null, 2) }] };
145
- });
146
- return server;
147
- }
@@ -1,91 +0,0 @@
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
- }
@@ -1,82 +0,0 @@
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
- }
@@ -1,221 +0,0 @@
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
- diagnostic: diagnostic => this.options.recordProviderDiagnostic?.({ binding: launch.binding, ...diagnostic }),
80
- settled: request => this.options.recordProviderSettled?.({ ...request, binding: launch.binding }),
81
- onFailure: () => {
82
- const current = this.#entries.get(launch.session.id);
83
- if (current && !current.stopping && !current.broken) {
84
- current.broken = true;
85
- void this.#failure(launch.session.id, 'runtime_provider_bookkeeping_failed').catch(() => { });
86
- }
87
- },
88
- });
89
- if (starting.cancelled)
90
- throw new Error('runtime_session_stopped');
91
- const state = mkdtempSync(join(realpathSync(this.options.stateDirectory), `${launch.session.id}-`));
92
- mkdirSync(join(state, 'tmp'), { mode: 0o700 });
93
- const modelPort = bridge?.clientConfiguration.modelPort ?? this.options.modelPort;
94
- const config = { ...pilotCodexConfig(modelPort), model: selected.model,
95
- ...(effort === undefined ? {} : { model_reasoning_effort: effort }),
96
- ...(bridge ? { 'model_providers.code60-pilot.http_headers': bridge.clientConfiguration.headers } : {}) };
97
- const codex = (this.options.createClient ?? (options => new ContainedCodexAppServer(options)))({
98
- executable: this.options.executable, stateDirectory: state, protocolPool: protocolPool(this.options.coordinator),
99
- modelPort, startupLockFd: this.options.startupLockFd, config
100
- });
101
- const bound = this.options.broker.bind(launch.binding);
102
- const runtime = new BrokeredCodexRuntime(codex, { ...bound, invoke: async (request) => {
103
- const result = await bound.invoke(request);
104
- entry.bookkeeping++;
105
- try {
106
- await this.options.recordTool?.(launch.binding, request, result);
107
- }
108
- finally {
109
- entry.bookkeeping--;
110
- }
111
- return this.options.runtimeToolResult ? this.options.runtimeToolResult(launch.binding, request, result) : result;
112
- } }, async (params) => {
113
- if (entry.stopping)
114
- return;
115
- const completed = params;
116
- if (completed.turn?.status !== 'completed') {
117
- await this.#failure(launch.session.id, 'runtime_turn_failed');
118
- return;
119
- }
120
- const text = completed.turn.items?.filter(item => item.type === 'agentMessage').at(-1)?.text;
121
- await this.#result(launch.session.id, typeof text === 'string' ? text : '');
122
- });
123
- const exit = codex.exited;
124
- const entry = { launch: structuredClone(launch), codex, runtime, busy: false, starting: true, broken: false, bookkeeping: 0, exit,
125
- ...(bridge ? { provider: bridge } : {}) };
126
- owner = entry;
127
- this.#entries.set(launch.session.id, entry);
128
- const failed = () => {
129
- if (entry.stopping || entry.broken)
130
- return;
131
- entry.broken = true;
132
- void this.#failure(launch.session.id, 'runtime_connection_lost').catch(() => { });
133
- };
134
- codex.on('protocolFailure', failed);
135
- runtime.on('completionFailure', failed);
136
- runtime.on('turnCompleted', () => { entry.busy = false; });
137
- await codex.initialize();
138
- const sections = launch.assignment.instructionSnapshot.sections;
139
- const started = await codex.startThread({ model: selected.model, modelProvider: 'code60-pilot', cwd: state, ephemeral: true,
140
- approvalPolicy: 'never', sandbox: 'read-only', environments: [], runtimeWorkspaceRoots: [], dynamicTools: runtime.dynamicTools,
141
- baseInstructions: sections.filter(section => section.origin === 'engine').map(section => section.content).join('\n\n'),
142
- developerInstructions: sections.filter(section => section.origin !== 'engine').map(section => section.content).join('\n\n') });
143
- if (!started.thread?.id)
144
- throw new Error('invalid_runtime_thread');
145
- entry.threadId = started.thread.id;
146
- entry.starting = false;
147
- }
148
- catch (error) {
149
- if (owner)
150
- owner.broken = true;
151
- if (owner)
152
- await this.stopEntry(owner);
153
- else
154
- await bridge?.close();
155
- throw error;
156
- }
157
- finally {
158
- this.#starting.delete(launch.session.id);
159
- finish();
160
- }
161
- }
162
- async turn(sessionId, instructions) {
163
- this.options.coordinator.assertOutsideTransaction();
164
- const entry = this.#entries.get(sessionId);
165
- if (!entry || !this.alive(sessionId) || !entry.threadId || entry.busy)
166
- throw new Error('runtime_session_unavailable');
167
- verifyWorkspaceInstructionSnapshot(entry.launch.workspaceInstructions);
168
- let workspace = entry.launch.workspaceInstructions.files.filter(file => file.selected).map(file => ({
169
- 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>`,
170
- }));
171
- const bounded = entry.launch.binding.configuredTools.includes('get_context');
172
- if (bounded) {
173
- let remaining = Math.max(0, (this.options.contextBytes ?? 65_536) - Buffer.byteLength(instructions));
174
- workspace = entry.guidanceDelivered ? [] : workspace.filter(item => { const bytes = Buffer.byteLength(item.text); if (bytes > remaining)
175
- return false; remaining -= bytes; return true; });
176
- }
177
- entry.busy = true;
178
- try {
179
- await entry.runtime.startTurn({ threadId: entry.threadId, environments: [], runtimeWorkspaceRoots: [],
180
- input: [...workspace, { type: 'text', text: instructions }] });
181
- if (bounded)
182
- entry.guidanceDelivered = true;
183
- }
184
- catch (error) {
185
- entry.broken = true;
186
- await this.stop(sessionId);
187
- throw error;
188
- }
189
- }
190
- flush(sessionId) { this.options.coordinator.assertOutsideTransaction(); this.#entries.get(sessionId)?.runtime.flushParked(); }
191
- async stop(sessionId) {
192
- this.options.coordinator.assertOutsideTransaction();
193
- const starting = this.#starting.get(sessionId);
194
- if (starting)
195
- starting.cancelled = true;
196
- const entry = this.#entries.get(sessionId);
197
- if (entry)
198
- await this.stopEntry(entry);
199
- if (starting)
200
- await starting.done;
201
- const late = this.#entries.get(sessionId);
202
- if (late)
203
- await this.stopEntry(late);
204
- }
205
- async stopEntry(entry) {
206
- if (!entry.stopping) {
207
- // Keep the physical-exit barrier counted before detach parks model work.
208
- entry.stopping = Promise.resolve().then(async () => {
209
- entry.runtime.detach();
210
- const closed = await Promise.allSettled([entry.codex.close(), entry.provider?.close() ?? Promise.resolve()]);
211
- await entry.runtime.settled();
212
- await entry.exit;
213
- const failure = closed.find(result => result.status === 'rejected');
214
- if (failure?.status === 'rejected')
215
- throw failure.reason;
216
- this.#entries.delete(entry.launch.session.id);
217
- });
218
- }
219
- await entry.stopping;
220
- }
221
- }