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,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,177 +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
- import { packageVersion } from '../cli/helpers.js';
8
- const example = {
9
- kind: 'Workflow', version: '1', metadata: { name: 'first-workflow' },
10
- config: { 'agent-profiles': { worker: 'REPLACE_WITH_WORKER_VERSION_ID' } },
11
- steps: [{ id: 'answer', instructions: [{ kind: 'inline', text: 'Return a JSON object with a message string.' }],
12
- execution: { 'max-session-resets': 0, 'max-attempts-per-session': 2 },
13
- exitArtifact: { schema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] } },
14
- exitCriteria: { deterministic: { checks: [] } } }],
15
- };
16
- const resources = [
17
- { uri: 'code60://workflow/schema', name: 'Workflow language schema', mimeType: 'application/schema+json', value: workflowLanguageSchema() },
18
- { uri: 'code60://workflow/example', name: 'Minimal single-step workflow', mimeType: 'application/json', value: example },
19
- ];
20
- const instructions = [
21
- 'Operate the configured local Code60 Transmission Server with its operator workspace scope.',
22
- '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.',
23
- '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.',
24
- 'For low-level workflows, discover runtimes and checks, register an authorized repository, and publish profiles before workflows.',
25
- 'Use latestVersionId to pin profiles in workflow source and to select a workflow version in create_run.',
26
- 'Call get_workflow_schema and get_workflow_example for authoring. The workflow version is the string "1".',
27
- 'Call get_runtime_configuration and use the selected provider credentialReferences ID in credentialRefs.provider.',
28
- 'POST tools take the engine request body under body and a caller-chosen idempotencyKey. Retry an uncertain outcome with the same arguments.',
29
- 'For conditional writes, read the target and pass its exact etag as ifMatch. Reassess the target after a conflict.',
30
- 'Results contain status, body and available receipt metadata. A 202 admits work. Inspect the run or poll get_operation for its outcome.',
31
- '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.',
32
- ].join(' ');
33
- function result(data, isError = false) {
34
- return { structuredContent: data, content: [{ type: 'text', text: JSON.stringify(data) }], isError };
35
- }
36
- async function callEngine(entry, args, port, token, signal) {
37
- if (!entry.validate(args))
38
- return result({ code: 'invalid_arguments', errors: entry.validate.errors?.map(issue => ({ path: issue.instancePath, code: issue.keyword, message: issue.message })) }, true);
39
- let path = entry.path;
40
- const query = new URLSearchParams();
41
- const headers = { authorization: 'Bearer ' + token };
42
- for (const { argument, parameter } of entry.parameters) {
43
- if (!Object.hasOwn(args, argument))
44
- continue;
45
- const value = String(args[argument]);
46
- if (parameter.in === 'path')
47
- path = path.replace('{' + parameter.name + '}', encodeURIComponent(value));
48
- else if (parameter.in === 'query')
49
- query.set(parameter.name, value);
50
- else {
51
- if (!/^[\x20-\x7e]+$/.test(value) || value.trim() !== value)
52
- return result({ code: 'invalid_arguments', detail: argument + ' must be a single printable HTTP header value without surrounding whitespace.' }, true);
53
- headers[parameter.name] = value;
54
- }
55
- }
56
- if (entry.method === 'POST')
57
- headers['content-type'] = 'application/json';
58
- try {
59
- // A direct socket to the configured loopback port. Never follow redirects or use an ambient proxy.
60
- const response = await new Promise((resolve, reject) => {
61
- const outgoing = request({ host: '127.0.0.1', port, agent: false, method: entry.method,
62
- path: '/api/v1' + path + (query.size ? '?' + query : ''), headers,
63
- signal: AbortSignal.any([signal, AbortSignal.timeout(60_000)]) }, resolve);
64
- outgoing.once('error', reject);
65
- outgoing.end(entry.method === 'POST' ? JSON.stringify(args.body) : undefined);
66
- });
67
- const status = response.statusCode;
68
- if (status >= 300 && status < 400) {
69
- response.destroy();
70
- return result({ code: 'engine_redirect', status, detail: 'The configured engine returned a redirect.' }, true);
71
- }
72
- const receipt = { status, body: await json(response) };
73
- if (response.headers.etag)
74
- receipt.etag = response.headers.etag;
75
- if (response.headers.location)
76
- receipt.location = response.headers.location;
77
- const replay = response.headers['idempotent-replay'];
78
- if (replay !== undefined)
79
- receipt.idempotentReplay = replay === 'true';
80
- if (JSON.stringify(receipt).includes(token))
81
- return result({ code: 'credential_in_response' }, true);
82
- return result(receipt, status >= 400);
83
- }
84
- catch {
85
- return result({ code: signal.aborted ? 'request_cancelled' : 'engine_unavailable',
86
- detail: 'The bridge could not read an engine receipt. Retry a command with its original key and arguments.' }, true);
87
- }
88
- }
89
- export function createWorkflowServer(port, token, toolset = 'admin') {
90
- const catalog = operatorCatalog();
91
- const discoveryTools = [
92
- { name: 'get_workflow_schema', description: 'Get the workflow language JSON Schema, including required fields and supported values.',
93
- inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
94
- { name: 'get_workflow_example', description: 'Get a minimal valid workflow. Replace the worker profile version placeholder before validation.',
95
- inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
96
- ];
97
- const workflowDescriptions = new Map([
98
- ['list_workflows', 'Find published workflows by name. Each latestVersionId can be used with start_workflow_run; read that definition with get_workflow_version before starting.'],
99
- ['get_workflow', 'Read a published workflow entry and its latestVersionId. This identifies the saved workflow, independently of the project it will run against.'],
100
- ['get_workflow_version', 'Read an immutable workflow definition, its pinned profiles, and packaged resources. Workspace file instructions, such as task.md, refer to the target project selected for the run.'],
101
- ['list_workspaces', 'Find registered target projects and their repository paths. Select the project containing the task and source to edit; the workflow-definition repository may be a different folder.'],
102
- ['get_workspace', 'Inspect a registered target project, its repositoryPath, and availability before starting a saved workflow.'],
103
- ['create_workspace', 'Register a Git project for a saved workflow. body.repositoryPath selects the target project, which may differ from the folder containing workflow JSON. Existing edits are supported by default; required task files must exist in this target project.'],
104
- ['list_run_artifacts', 'Find a run’s worker results, verifier verdicts, and check evidence. Use get_artifact to read a selected artifact.'],
105
- ['get_artifact', 'Read an authorized run artifact, including its worker result, semantic verifier verdict, or executable check evidence.'],
106
- ['list_run_events', 'Follow progress on the same run. Set follow=true and waitSeconds=30 to wait efficiently; pass the returned nextCursor on the next call. Keep following a requested task until it finishes or needs a user answer/approval; running is an intermediate state.'],
107
- ]);
108
- 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', ...workflowDescriptions.keys()]);
109
- const savedWorkflowTool = structuredClone(catalog.get('create_run').tool);
110
- savedWorkflowTool.name = 'start_workflow_run';
111
- savedWorkflowTool.description = 'Run an existing published workflow with its pinned worker/verifier profiles. Supply a stable idempotencyKey and body: {workflowVersionId, workspaceId}. Discover IDs with list_workflows/list_workspaces. Required workspace files must exist in that target project. Defaults to uncommitted working_tree results; set body.resultMode="commit" explicitly to commit. Returns a run ID to follow with get_run/list_run_events.';
112
- const managedControls = new Set(['pause_run', 'resume_run', 'cancel_run', ...(toolset === 'coding' ? ['decide_approval'] : [])]);
113
- const codingInstructions = [
114
- 'Use get_coding_readiness to check the coding setup.',
115
- 'For an existing published workflow, use list_workflows and list_workspaces, inspect get_workflow_version, then call start_workflow_run with body: {workflowVersionId, workspaceId} and a stable idempotencyKey. This preserves the workflow’s pinned profiles and separate verifier. It defaults to uncommitted working_tree results.',
116
- 'A workflow-definition folder and its target project can differ. Workspace instruction files such as task.md must be found in the selected workspace.repositoryPath; do not conclude they are absent by searching only the definition folder. If a required task file is actually missing in the target project, obtain the task before starting.',
117
- 'For a new ad hoc coding task, use start_coding_task with a task description and repositoryPath or workspaceId. This selects the built-in coding workflow; use start_workflow_run when asked to run an existing workflow.',
118
- 'Follow get_run/list_run_events; answer pending questions and inspect get_coding_task_result for the run-only diff and check evidence. If executable checks are absent the coding result says unverified; use list_run_artifacts/get_artifact to read semantic verifier verdicts. Send guidance with send_task_message.',
119
- 'The default tools run published workflows. Authoring and publishing workflow/profile versions require --toolset admin. Existing low-level tool calls remain compatible.',
120
- ].join(' ');
121
- const server = new Server({ name: 'code60-workflows', version: packageVersion() }, { capabilities: { tools: {}, resources: {} }, instructions: toolset === 'coding' ? codingInstructions : instructions });
122
- server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [
123
- ...(toolset === 'admin' ? discoveryTools : []),
124
- ...[...catalog.values()].filter(entry => toolset === 'admin' || codingNames.has(entry.tool.name)).map(entry => {
125
- const tool = structuredClone(entry.tool);
126
- if (toolset === 'coding' && workflowDescriptions.has(tool.name))
127
- tool.description = workflowDescriptions.get(tool.name);
128
- if (managedControls.has(tool.name)) {
129
- tool.inputSchema.required = tool.inputSchema.required?.filter(name => name !== 'ifMatch') ?? [];
130
- tool.description += ' Omit ifMatch to let the bridge refresh versions during active execution; supply it for an exact conditional write.';
131
- }
132
- return tool;
133
- }),
134
- ...(toolset === 'coding' ? [savedWorkflowTool] : []),
135
- ] }));
136
- server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => {
137
- if (params.name === 'get_workflow_schema' || params.name === 'get_workflow_example') {
138
- if (Object.keys(params.arguments ?? {}).length)
139
- return result({ code: 'invalid_arguments' }, true);
140
- return result({ status: 200, body: params.name === 'get_workflow_schema' ? resources[0].value : example });
141
- }
142
- const savedWorkflow = params.name === 'start_workflow_run';
143
- const entry = catalog.get(savedWorkflow ? 'create_run' : params.name);
144
- if (!entry)
145
- throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 operator tool.');
146
- let args = params.arguments ?? {};
147
- if (savedWorkflow && args.body && typeof args.body === 'object' && !Array.isArray(args.body)) {
148
- const body = args.body;
149
- args = { ...args, body: { ...body, resultMode: body.resultMode === undefined ? 'working_tree' : body.resultMode } };
150
- }
151
- if (args.ifMatch === undefined && managedControls.has(params.name)) {
152
- return (async () => {
153
- const target = params.name === 'decide_approval' ? catalog.get('get_approval') : catalog.get('get_run');
154
- for (let attempt = 0;; attempt++) {
155
- const read = await callEngine(target, params.name === 'decide_approval' ? { approvalId: args.approvalId } : { runId: args.runId }, port, token, signal);
156
- const receipt = read.structuredContent;
157
- if (read.isError || !receipt?.etag)
158
- return read;
159
- const written = await callEngine(entry, { ...args, ifMatch: receipt.etag }, port, token, signal);
160
- // A failed precondition has no receipt or side effects. Retain the
161
- // caller's key/body, and never retry an uncertain transport outcome.
162
- if (written.structuredContent?.status !== 412 || attempt >= 15 || signal.aborted)
163
- return written;
164
- }
165
- })();
166
- }
167
- return callEngine(entry, args, port, token, signal);
168
- });
169
- server.setRequestHandler(ListResourcesRequestSchema, () => ({ resources: resources.map(({ value, ...info }) => info) }));
170
- server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => {
171
- const resource = resources.find(item => item.uri === params.uri);
172
- if (!resource)
173
- throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 workflow resource.');
174
- return { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: JSON.stringify(resource.value, null, 2) }] };
175
- });
176
- return server;
177
- }
@@ -1,91 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { isolatedRuntimeEnvironment, runtimeSeatbeltProfile } from './containment.js';
3
- import { resolveCodexExecutable } from './codex-executable.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 = resolveCodexExecutable(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,50 +0,0 @@
1
- import { accessSync, closeSync, constants, openSync, readFileSync, readSync, realpathSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import { basename, dirname, join } from 'node:path';
4
- /** Resolve the official npm launcher without executing JavaScript outside containment. */
5
- export function resolveCodexExecutable(input) {
6
- const executable = realpathSync(input);
7
- if (basename(executable) !== 'codex.js' || basename(dirname(executable)) !== 'bin')
8
- return executable;
9
- const root = dirname(dirname(executable));
10
- let manifest;
11
- try {
12
- const value = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
13
- if (!value || typeof value !== 'object' || Array.isArray(value))
14
- return executable;
15
- manifest = value;
16
- }
17
- catch {
18
- return executable;
19
- }
20
- if (manifest.name !== '@openai/codex' || manifest.bin?.codex !== 'bin/codex.js')
21
- return executable;
22
- if (process.platform !== 'darwin' || !['arm64', 'x64'].includes(process.arch))
23
- throw new Error('Codex containment requires a supported macOS native executable.');
24
- const triple = `${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-apple-darwin`;
25
- const candidates = [];
26
- try {
27
- const require = createRequire(join(root, 'package.json'));
28
- candidates.push(join(dirname(require.resolve(`@openai/codex-darwin-${process.arch}/package.json`)), 'vendor', triple, 'bin', 'codex'));
29
- }
30
- catch { /* Older Codex distributions keep vendor inside the main package. */ }
31
- candidates.push(join(root, 'vendor', triple, 'bin', 'codex'));
32
- for (const candidate of candidates) {
33
- try {
34
- const path = realpathSync(candidate);
35
- accessSync(path, constants.X_OK);
36
- const fd = openSync(path, constants.O_RDONLY), magic = Buffer.alloc(4);
37
- try {
38
- if (readSync(fd, magic, 0, 4, 0) !== 4)
39
- continue;
40
- }
41
- finally {
42
- closeSync(fd);
43
- }
44
- if (['feedface', 'feedfacf', 'cefaedfe', 'cffaedfe', 'cafebabe', 'bebafeca', 'cafebabf', 'bfbafeca'].includes(magic.toString('hex')))
45
- return path;
46
- }
47
- catch { /* Try the other supported distribution layout. */ }
48
- }
49
- throw new Error('The Codex npm launcher has no executable macOS platform binary. Reinstall @openai/codex with optional dependencies, or select a native Codex executable.');
50
- }
@@ -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
- }