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,355 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
- import { dirname, join, relative } from 'node:path';
4
- import { Ajv2020 } from 'ajv/dist/2020.js';
5
- import { digest } from '../broker/policy.js';
6
- import { BrokerError } from '../broker/types.js';
7
- import { assertCommandScope, CommandAdmissionError, CommandRunner } from './commands.js';
8
- const str = { type: 'string' }, num = { type: 'integer', minimum: 0 }, bool = { type: 'boolean' };
9
- const schema = (properties, required = []) => ({ type: 'object', properties: properties, required, additionalProperties: false });
10
- export const DEVELOPER_DEFINITIONS = new Map([
11
- ['read_file', { description: 'Read a UTF-8 file. Set startLine=1 to include its SHA-256 for apply_patch; endLine selects a range. Large results include a continuation line.', inputSchema: schema({ path: str, root: str, startLine: { type: 'integer', minimum: 1 }, endLine: { type: 'integer', minimum: 1 } }, ['path']) }],
12
- ['write_file', { description: 'Replace one UTF-8 file. Use apply_patch for precise edits and make_directory for new parent directories.', inputSchema: schema({ path: str, root: str, content: str }, ['path', 'content']) }],
13
- ['make_directory', { description: 'Create a project directory and missing parents within the assigned workspace.', inputSchema: schema({ path: str }, ['path']) }],
14
- ['apply_patch', { description: 'Precisely edit a file using its SHA-256 expectedDigest. Each oldText must occur exactly once; conflicts make no changes.', inputSchema: schema({ path: str, expectedDigest: { type: 'string', pattern: '^[a-f0-9]{64}$' }, edits: { type: 'array', minItems: 1, items: { type: 'object', properties: { oldText: { type: 'string', minLength: 1 }, newText: str }, required: ['oldText', 'newText'], additionalProperties: false } } }, ['path', 'expectedDigest', 'edits']) }],
15
- ['list_files', { description: 'List Git-tracked and nonignored source entries. Results are paginated; dependencies/build output are omitted.', inputSchema: schema({ path: str, root: str, cursor: num, limit: { type: 'integer', minimum: 1, maximum: 1000 } }) }],
16
- ['search_files', { description: 'Search source files for a literal substring, returning line numbers and a pagination cursor.', inputSchema: schema({ path: str, root: str, query: { type: 'string', minLength: 1, maxLength: 4096 }, caseSensitive: bool, cursor: num, limit: { type: 'integer', minimum: 1, maximum: 1000 } }, ['query']) }],
17
- ['delete_file', { description: 'Delete one assigned regular source file.', inputSchema: schema({ path: str, root: str }, ['path']) }],
18
- ['move_file', { description: 'Move one source file to an absent destination within the assigned root.', inputSchema: schema({ path: str, destination: str, root: str }, ['path', 'destination']) }],
19
- ['get_diff', { description: 'Read the run’s baseline-relative diff. Pre-existing edits are excluded. Use the returned byte cursor for more.', inputSchema: schema({ cursor: num, limit: { type: 'integer', minimum: 1, maximum: 262144 } }) }],
20
- ['run_command', { description: 'Run a shell command in the sandboxed project. Await by default; background returns a command ID. Await/stop writing commands before editing or submitting. Network follows deployment settings.', inputSchema: schema({ command: { type: 'string', minLength: 1, maxLength: 65536 }, cwd: { ...str, description: 'Existing directory relative to the registered project root. Omit or use "." for that root; "workspace" means a subdirectory literally named workspace. Missing directories return command_cwd_not_found.' }, env: { type: 'object', additionalProperties: str }, timeoutMs: { type: 'integer', minimum: 1, maximum: 86400000 }, readOnly: { ...bool, description: 'Set true for source read-only commands; required for verifier sessions.' }, background: bool }, ['command']) }],
21
- ['read_command_output', { description: 'Read paginated stdout/stderr and current exit status for your command.', inputSchema: schema({ commandId: str, stream: { enum: ['stdout', 'stderr'] }, cursor: num, limit: { type: 'integer', minimum: 1, maximum: 262144 } }, ['commandId']) }],
22
- ['write_command_input', { description: 'Write text to your running command. Set end=true after the final input to send EOF.', inputSchema: schema({ commandId: str, text: { type: 'string', maxLength: 65536 }, end: bool }, ['commandId', 'text']) }],
23
- ['stop_command', { description: 'Stop your command and wait for process/output settlement before returning.', inputSchema: schema({ commandId: str }, ['commandId']) }],
24
- ['ask_user', { description: 'Ask a necessary clarification and wait for an answer in this conversation; this does not submit a result or spend an attempt.', inputSchema: schema({ question: { type: 'string', minLength: 1, maxLength: 8192 } }, ['question']) }],
25
- ['report_blocker', { description: 'Report missing access, dependencies, or capabilities and wait for operator guidance.', inputSchema: schema({ question: { type: 'string', minLength: 1, maxLength: 8192 } }, ['question']) }],
26
- ['get_context', { description: 'Retrieve pinned guidance, inputs, schemas, artifacts, questions, or previous tool history. For guidance, omit guidancePath to list the manifest, then supply its path to read content.', inputSchema: schema({ kind: { enum: ['history', 'artifacts', 'inputs', 'messages', 'schema', 'schemas', 'questions', 'guidance'] }, guidancePath: str, artifactId: str, cursor: num, limit: { type: 'integer', minimum: 1, maximum: 65536 } }) }],
27
- ['get_capabilities', { description: 'Inspect your actual tools, filesystem permissions, network policy, and remaining session limits.', inputSchema: schema({}) }],
28
- ]);
29
- const hash = (value) => createHash('sha256').update(value).digest('hex');
30
- const readOnlyTools = new Set(['read_file', 'list_files', 'search_files', 'get_diff', 'get_context', 'get_capabilities', 'read_command_output']);
31
- export class DeveloperTools {
32
- options;
33
- validators = new Map([...DEVELOPER_DEFINITIONS].map(([name, d]) => [name, new Ajv2020({ strict: false }).compile(d.inputSchema)]));
34
- questions = new Map();
35
- pendingAnswers = new Map();
36
- constructor(options) {
37
- this.options = options;
38
- }
39
- registry() { return new Map([...DEVELOPER_DEFINITIONS].map(([name, definition]) => [name, { name, ...definition, ...(readOnlyTools.has(name) ? { readOnly: true } : {}), prepare: (input, binding) => this.prepare(name, input, binding) }])); }
40
- refreshInputWait(runId) {
41
- const run = this.options.store.find('runs', runId);
42
- if (!run)
43
- return;
44
- const pendingQuestionIds = this.listQuestions(runId).filter(q => q.state === 'pending').map(q => q.id);
45
- this.options.store.put('runs', { ...run, version: run.version + 1, updatedAt: new Date().toISOString(), inputWait: { status: pendingQuestionIds.length ? 'waiting' : 'none', pendingQuestionIds } });
46
- }
47
- waiting(runId) { return this.listQuestions(runId).some(q => q.state === 'pending'); }
48
- listQuestions(runId) { return this.options.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='worker_question' AND json_extract(body,'$.runId')=? ORDER BY rowid").all(runId).map(r => JSON.parse(r.body)); }
49
- answer(id, answer) {
50
- const q = this.options.store.private('worker_question', id);
51
- if (!q)
52
- throw new BrokerError('question_not_found', 404);
53
- if (q.state === 'answered') {
54
- if (q.answer !== answer)
55
- throw new BrokerError('question_answer_conflict');
56
- return q;
57
- }
58
- if (q.state !== 'pending')
59
- throw new BrokerError('question_conversation_unavailable');
60
- const next = { ...q, state: 'answered', answer };
61
- this.options.store.setPrivate('worker_question', id, next);
62
- this.refreshInputWait(q.runId);
63
- this.options.hold(q.runId, `input:${id}`, false);
64
- this.questions.get(id)?.(answer);
65
- this.questions.delete(id);
66
- this.options.wake(q.runId);
67
- return next;
68
- }
69
- async runtimeResult(binding, request, result) {
70
- if (!['ask_user', 'report_blocker'].includes(request.toolName) || !result.success)
71
- return result;
72
- const { questionId } = JSON.parse(result.text);
73
- const q = this.options.store.private('worker_question', questionId);
74
- if (!q || q.sessionId !== binding.sessionId || q.epoch !== binding.epoch)
75
- throw new BrokerError('question_not_assigned');
76
- if (q.state === 'answered')
77
- return { success: true, text: JSON.stringify({ questionId, answer: q.answer }) };
78
- const prior = this.pendingAnswers.get(q.id);
79
- if (prior)
80
- return prior;
81
- const signal = this.options.signal(binding.runId);
82
- const answer = new Promise(resolveAnswer => {
83
- const abort = () => {
84
- this.questions.delete(q.id);
85
- const run = this.options.store.find('runs', q.runId), plan = this.options.store.private('run_plan', q.runId);
86
- const cancelled = !!plan?.cancelOperationId || !!run && ['succeeded', 'failed', 'cancelled'].includes(run.state);
87
- if (cancelled) {
88
- this.options.store.setPrivate('worker_question', q.id, { ...q, state: 'cancelled' });
89
- this.refreshInputWait(q.runId);
90
- this.options.hold(q.runId, `input:${q.id}`, false);
91
- }
92
- resolveAnswer(cancelled ? 'Run cancelled.' : 'Conversation interrupted; this question remains pending for recovery.');
93
- };
94
- this.questions.set(q.id, value => { signal.removeEventListener('abort', abort); resolveAnswer(value); });
95
- signal.addEventListener('abort', abort, { once: true });
96
- if (signal.aborted)
97
- abort();
98
- });
99
- const pending = answer.then(answer => ({ success: true, text: JSON.stringify({ questionId, answer }) }));
100
- this.pendingAnswers.set(q.id, pending);
101
- void pending.then(() => this.pendingAnswers.delete(q.id), () => this.pendingAnswers.delete(q.id));
102
- return pending;
103
- }
104
- recoverQuestions() {
105
- for (const row of this.options.store.coordinator.db.prepare("SELECT id,body FROM engine_private WHERE scope='worker_question' AND json_extract(body,'$.state')='pending'").all()) {
106
- const q = JSON.parse(row.body);
107
- this.refreshInputWait(q.runId);
108
- this.options.hold(q.runId, `input:${q.id}`, true);
109
- }
110
- }
111
- async close() { for (const resolveQuestion of this.questions.values())
112
- resolveQuestion('Conversation interrupted; the operator question remains available for recovery.'); this.questions.clear(); }
113
- prepare(name, input, binding) {
114
- if (!binding || !this.validators.get(name)(input))
115
- throw new BrokerError('invalid_tool_arguments', 400);
116
- const context = this.options.resolveContext(binding), repository = this.options.workspaces.sourceRepository(binding.runId), args = input;
117
- if (!repository)
118
- throw new BrokerError('source_tracking_required', 422);
119
- if (args.root !== undefined && args.root !== 'workspace')
120
- throw new BrokerError('unassigned_tool_root', 403);
121
- const writing = ['write_file', 'make_directory', 'apply_patch', 'delete_file', 'move_file'].includes(name) || name === 'run_command' && !args.readOnly;
122
- if (writing && binding.role === 'verifier')
123
- throw new BrokerError('project_read_only', 403);
124
- if (name === 'run_command')
125
- assertCommandScope(binding, !writing);
126
- const paths = ['get_diff', 'run_command'].includes(name) ? ['.'] : typeof args.path === 'string' ? [args.path, ...(typeof args.destination === 'string' ? [args.destination] : [])] : [];
127
- const identities = () => {
128
- const resources = paths.map((path, index) => {
129
- const target = path === '.' ? repository.root : repository.safePath(path, writing, !['delete_file', 'move_file'].includes(name), ['delete_file', 'move_file'].includes(name));
130
- const stat = existsSync(target) ? lstatSync(target) : lstatSync(dirname(target));
131
- return { kind: 'filesystem', root: 'workspace', path: relative(repository.root, target) || '.', operation: name === 'delete_file' || name === 'move_file' && index === 0 ? 'delete' : writing ? 'write' : 'read', identityDigest: digest({ revision: this.options.workspaces.lease(binding.runId).knownRevisionId, target, device: stat.dev, inode: stat.ino, mode: stat.mode, size: stat.size, modified: stat.mtimeMs, changed: stat.ctimeMs }) };
132
- });
133
- if (name === 'run_command' && writing)
134
- resources.push({ ...resources[0], operation: 'read' }, { ...resources[0], operation: 'delete' });
135
- if (name === 'list_files' || name === 'search_files') {
136
- const base = String(args.path ?? '.');
137
- for (const entry of repository.sourceEntries())
138
- if (base === '.' || entry.path === base || entry.path.startsWith(base + '/'))
139
- resources.push({ kind: 'filesystem', root: 'workspace', path: entry.path, operation: 'read', identityDigest: digest(entry.identity) });
140
- }
141
- return resources;
142
- };
143
- const resources = identities();
144
- let used = false;
145
- return { resources, revalidate: () => { this.options.resolveContext(binding); return identities(); }, execute: async () => {
146
- if (used)
147
- throw new BrokerError('tool_effect_reused');
148
- used = true;
149
- this.options.resolveContext(binding);
150
- const result = (data) => ({ success: true, text: typeof data === 'string' ? data : JSON.stringify(data) });
151
- if (name === 'run_command') {
152
- try {
153
- const record = await this.options.runner.start(binding, args);
154
- return { success: record.state === 'running' || record.state === 'completed', text: JSON.stringify({ ...record, stdout: this.options.runner.output(record.id).text, stderr: this.options.runner.output(record.id, 'stderr').text }) };
155
- }
156
- catch (error) {
157
- if (!(error instanceof CommandAdmissionError))
158
- throw error;
159
- return { success: false, text: JSON.stringify({ code: error.code, commandStarted: false, recovery: error.code === 'workspace_command_active' ? 'Read or stop the existing command before starting another writer.' : error.code.startsWith('command_cwd_') ? 'Use an existing project-relative directory; omit cwd or use "." for the project root.' : 'Review command arguments and the capabilities reported by get_capabilities.' }) };
160
- }
161
- }
162
- if (name === 'read_command_output')
163
- return result(this.options.runner.output(String(args.commandId), args.stream, args.cursor, args.limit, binding));
164
- if (name === 'write_command_input') {
165
- this.options.runner.input(String(args.commandId), String(args.text), binding, Boolean(args.end));
166
- return result('Input written.');
167
- }
168
- if (name === 'stop_command')
169
- return result(await this.options.runner.stop(String(args.commandId), binding));
170
- if (name === 'ask_user' || name === 'report_blocker') {
171
- const q = { id: randomUUID(), runId: binding.runId, sessionId: binding.sessionId, epoch: binding.epoch, question: String(args.question), kind: name, state: 'pending', createdAt: new Date().toISOString() };
172
- this.options.store.setPrivate('worker_question', q.id, q);
173
- this.refreshInputWait(q.runId);
174
- this.options.hold(q.runId, `input:${q.id}`, true);
175
- this.options.store.event(q.runId, 'worker_question', 'question', q.id, { question: q.question, kind: q.kind });
176
- this.options.wake(binding.runId);
177
- return result({ questionId: q.id, state: 'pending' });
178
- }
179
- if (name === 'get_capabilities') {
180
- const session = this.options.store.get('sessions', binding.sessionId);
181
- return result({ tools: binding.configuredTools, permissions: session.effectiveConfiguration.effectivePermissions, commands: this.options.runner.settings, limits: session.limits, submissionsUsed: session.submissionsUsed });
182
- }
183
- if (name === 'get_context') {
184
- const access = this.options.store.private('session_access', binding.sessionId);
185
- const cursor = Number(args.cursor ?? 0), limit = Number(args.limit ?? 16_384);
186
- if (args.kind === 'guidance') {
187
- const files = this.options.store.private('run_plan', binding.runId)?.workspaceInstructions?.files.filter(f => f.selected) ?? [];
188
- if (typeof args.guidancePath === 'string') {
189
- const file = files.find(f => f.path === args.guidancePath);
190
- if (!file)
191
- throw new BrokerError('guidance_not_assigned', 404);
192
- const bytes = Buffer.from(file.content);
193
- return result({ path: file.path, sha256: file.sha256, content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
194
- }
195
- const selected = files.slice(cursor, cursor + 20);
196
- return result({ items: selected.map(f => ({ path: f.path, sha256: f.sha256, bytes: Buffer.byteLength(f.content) })), nextCursor: cursor + 20 < files.length ? cursor + 20 : null });
197
- }
198
- if (['schema', 'schemas', 'questions'].includes(String(args.kind))) {
199
- const authority = this.options.store.private('session_authority', binding.sessionId), plan = this.options.store.private('run_plan', binding.runId);
200
- const data = args.kind === 'schema' ? authority.outputSchema : args.kind === 'schemas' ? plan?.graph?.resources ?? [] : this.listQuestions(binding.runId);
201
- const bytes = Buffer.from(JSON.stringify(data));
202
- return result({ content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
203
- }
204
- if (args.kind === 'inputs' || args.kind === 'messages') {
205
- const data = args.kind === 'inputs' ? this.options.store.private('run_plan', binding.runId)?.inputs ?? null : this.options.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='task_message' AND json_extract(body,'$.runId')=? ORDER BY rowid").all(binding.runId).map(r => JSON.parse(r.body));
206
- const bytes = Buffer.from(JSON.stringify(data));
207
- return result({ content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
208
- }
209
- if (args.kind === 'artifacts' && typeof args.artifactId !== 'string') {
210
- const ids = access.inputArtifactIds.slice(cursor, cursor + 20);
211
- return result({ items: ids.map(id => { const a = this.options.store.get('artifacts', id); return { id: a.id, kind: a.kind, mediaType: a.document.mediaType, bytes: Buffer.byteLength(a.document.content) }; }), nextCursor: cursor + 20 < access.inputArtifactIds.length ? cursor + 20 : null });
212
- }
213
- if (typeof args.artifactId === 'string') {
214
- if (!access.inputArtifactIds.includes(args.artifactId))
215
- throw new BrokerError('artifact_not_assigned', 403);
216
- const artifact = this.options.store.get('artifacts', args.artifactId), bytes = Buffer.from(artifact.document.content), content = bytes.subarray(cursor, cursor + limit).toString('utf8');
217
- return result({ id: artifact.id, content, nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
218
- }
219
- const items = this.options.store.list('tool_history', { runId: binding.runId, after: Math.max(access.historyAfterSeq, cursor), through: access.historyThroughSeq, limit: Math.min(20, limit) });
220
- return result({ items: items.map(i => i.value), nextCursor: items.at(-1)?.seq ?? null });
221
- }
222
- if (name === 'get_diff') {
223
- const diff = this.options.workspaces.sourceResult(binding.runId), fd = openSync(diff.patchPath, constants.O_RDONLY | constants.O_NOFOLLOW), bytes = Buffer.alloc(Number(args.limit ?? 65_536)), cursor = Number(args.cursor ?? 0);
224
- let count;
225
- try {
226
- count = readSync(fd, bytes, 0, bytes.length, cursor);
227
- }
228
- finally {
229
- closeSync(fd);
230
- }
231
- return result({ ...diff, patchPath: undefined, patch: bytes.subarray(0, count).toString(), nextCursor: count ? cursor + count : null });
232
- }
233
- if (name === 'read_file') {
234
- const path = repository.safePath(String(args.path), false, true), captured = this.options.workspaces.blobs.capture(path, this.options.workspaces.sourceQuotas.fileBytes), fd = openSync(this.options.workspaces.blobs.path(captured.blob), constants.O_RDONLY | constants.O_NOFOLLOW), buffer = Buffer.alloc(65_536);
235
- let text = '', pending = '', line = 1, nextLine = null, done = false;
236
- const start = Number(args.startLine ?? 1), end = Number(args.endLine ?? Number.MAX_SAFE_INTEGER), decoder = new TextDecoder('utf-8', { fatal: true });
237
- try {
238
- for (;;) {
239
- const count = readSync(fd, buffer, 0, buffer.length, null);
240
- pending += decoder.decode(buffer.subarray(0, count), { stream: count > 0 });
241
- let newline;
242
- while ((newline = pending.indexOf('\n')) >= 0 || !count && pending.length) {
243
- const length = newline >= 0 ? newline + 1 : pending.length, value = pending.slice(0, length);
244
- pending = pending.slice(length);
245
- if (line >= start && line <= end) {
246
- if (Buffer.byteLength(text + value) > 65_536) {
247
- nextLine = line;
248
- done = true;
249
- break;
250
- }
251
- text += value;
252
- }
253
- line++;
254
- if (line > end) {
255
- nextLine = line;
256
- done = true;
257
- break;
258
- }
259
- }
260
- if (done || !count)
261
- break;
262
- if (pending.length > 262_144)
263
- throw new BrokerError('line_too_large_use_command', 422);
264
- }
265
- }
266
- finally {
267
- closeSync(fd);
268
- }
269
- const digest = captured.blob;
270
- return result(args.startLine || args.endLine || nextLine ? { content: text, startLine: start, nextLine, sha256: digest } : text);
271
- }
272
- if (name === 'list_files' || name === 'search_files') {
273
- const base = String(args.path ?? '.'), entries = repository.sourceEntries().filter(e => base === '.' || e.path === base || e.path.startsWith(base + '/')), cursor = Number(args.cursor ?? 0), limit = Number(args.limit ?? 200);
274
- if (name === 'list_files')
275
- return result({ entries: entries.slice(cursor, cursor + limit).map(({ path, type }) => ({ path, type })), nextCursor: cursor + limit < entries.length ? cursor + limit : null });
276
- const matches = [];
277
- let seen = 0, more = false;
278
- const needle = args.caseSensitive ? String(args.query) : String(args.query).toLowerCase();
279
- for (const entry of entries.filter(e => e.type === 'file')) {
280
- const fd = openSync(repository.safePath(entry.path), constants.O_RDONLY | constants.O_NOFOLLOW), buffer = Buffer.alloc(65_536), decoder = new TextDecoder('utf-8');
281
- let pending = '', line = 0;
282
- try {
283
- for (;;) {
284
- const count = readSync(fd, buffer, 0, buffer.length, null);
285
- pending += decoder.decode(buffer.subarray(0, count), { stream: count > 0 });
286
- let newline;
287
- while ((newline = pending.indexOf('\n')) >= 0 || !count && pending.length) {
288
- const length = newline >= 0 ? newline + 1 : pending.length, value = pending.slice(0, length);
289
- pending = pending.slice(length);
290
- line++;
291
- if ((args.caseSensitive ? value : value.toLowerCase()).includes(needle)) {
292
- if (seen++ >= cursor) {
293
- if (matches.length === limit) {
294
- more = true;
295
- break;
296
- }
297
- matches.push({ path: entry.path, line, text: value.slice(0, 4096).trimEnd() });
298
- }
299
- }
300
- }
301
- if (more || !count)
302
- break;
303
- if (pending.length > 262_144)
304
- pending = pending.slice(-needle.length);
305
- }
306
- }
307
- finally {
308
- closeSync(fd);
309
- }
310
- if (more)
311
- break;
312
- }
313
- return result({ matches, nextCursor: more ? cursor + matches.length : null });
314
- }
315
- return this.options.workspaces.sourceMutation(context, repo => {
316
- const rejected = (code) => ({ success: false, text: `broker:${code}` });
317
- const path = repo.safePath(String(args.path), true, ['apply_patch', 'write_file'].includes(name), ['delete_file', 'move_file'].includes(name)), atomicWrite = (content) => { const mode = existsSync(path) ? lstatSync(path).mode & 0o777 : 0o600, temporary = join(dirname(path), `.code60-${randomUUID()}`); try {
318
- writeFileSync(temporary, content, { flag: 'wx', mode });
319
- renameSync(temporary, path);
320
- }
321
- finally {
322
- if (existsSync(temporary))
323
- unlinkSync(temporary);
324
- } };
325
- if (name === 'make_directory')
326
- mkdirSync(path, { recursive: true, mode: 0o755 });
327
- else if (name === 'write_file')
328
- atomicWrite(String(args.content));
329
- else if (name === 'apply_patch') {
330
- let content = readFileSync(path, 'utf8');
331
- if (hash(content) !== args.expectedDigest)
332
- return rejected('patch_precondition_failed');
333
- for (const edit of args.edits) {
334
- const offset = content.indexOf(edit.oldText);
335
- if (offset < 0 || content.indexOf(edit.oldText, offset + 1) >= 0)
336
- return rejected('patch_match_not_unique');
337
- content = content.slice(0, offset) + edit.newText + content.slice(offset + edit.oldText.length);
338
- }
339
- atomicWrite(content);
340
- }
341
- else if (name === 'delete_file')
342
- unlinkSync(path);
343
- else if (name === 'move_file') {
344
- const destination = repo.safePath(String(args.destination), true);
345
- if (existsSync(destination))
346
- return rejected('destination_exists');
347
- renameSync(path, destination);
348
- }
349
- else
350
- throw new BrokerError('unsupported_tool');
351
- return result(name === 'write_file' ? 'File written.' : 'Source updated.');
352
- });
353
- } };
354
- }
355
- }
@@ -1,248 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { createSocket } from "node:dgram";
3
- import { connect, isIP } from "node:net";
4
- import { normalizeHost } from "../broker/policy.js";
5
- export class NetworkToolError extends Error {
6
- code;
7
- constructor(code) {
8
- super(code);
9
- this.code = code;
10
- }
11
- }
12
- const denied = () => { throw new NetworkToolError("invalid_dns_response"); };
13
- export function numericAddress(value) {
14
- const normalized = normalizeHost(value);
15
- if (!isIP(normalized) || normalized.startsWith("::ffff:"))
16
- throw new NetworkToolError("unsupported_numeric_address");
17
- return normalized;
18
- }
19
- function question(host, type) {
20
- const id = randomBytes(2).readUInt16BE(), header = Buffer.alloc(12);
21
- header.writeUInt16BE(id);
22
- header.writeUInt16BE(0x100, 2);
23
- header.writeUInt16BE(1, 4);
24
- const labels = host.split(".").flatMap(label => [Buffer.from([Buffer.byteLength(label)]), Buffer.from(label, "ascii")]);
25
- const suffix = Buffer.from([0, 0, type, 0, 1]);
26
- return { id, packet: Buffer.concat([header, ...labels, suffix]) };
27
- }
28
- function answer(packet, host, type, id) {
29
- if (packet.length < 12 || packet.length > 65535 || packet.readUInt16BE() !== id)
30
- return denied();
31
- const flags = packet.readUInt16BE(2);
32
- if (!(flags & 0x8000) || flags & 0x7800 || flags & 0xf || packet.readUInt16BE(4) !== 1)
33
- return denied();
34
- let offset = 12;
35
- const name = (start) => {
36
- const seen = new Set(), labels = [];
37
- let at = start, next = -1;
38
- for (let depth = 0; depth < 128; depth++) {
39
- if (at >= packet.length || seen.has(at))
40
- return denied();
41
- seen.add(at);
42
- const length = packet[at++];
43
- if ((length & 0xc0) === 0xc0) {
44
- if (at >= packet.length)
45
- return denied();
46
- const target = ((length & 0x3f) << 8) | packet[at++];
47
- if (target < 12 || target >= at - 2)
48
- return denied();
49
- if (next < 0)
50
- next = at;
51
- at = target;
52
- continue;
53
- }
54
- if (length & 0xc0 || length > 63 || at + length > packet.length)
55
- return denied();
56
- if (!length)
57
- return { value: labels.join(".").toLowerCase(), next: next < 0 ? at : next };
58
- if (packet.subarray(at, at + length).some(byte => byte >= 128))
59
- return denied();
60
- const label = packet.subarray(at, at + length).toString("ascii");
61
- if (!/^[a-zA-Z0-9_-]+$/.test(label))
62
- return denied();
63
- labels.push(label);
64
- at += length;
65
- if (labels.join(".").length > 253)
66
- return denied();
67
- }
68
- return denied();
69
- };
70
- const qname = name(offset);
71
- offset = qname.next;
72
- if (qname.value !== host || offset + 4 > packet.length || packet.readUInt16BE(offset) !== type || packet.readUInt16BE(offset + 2) !== 1)
73
- return denied();
74
- offset += 4;
75
- if (flags & 0x200)
76
- return { truncated: true, addresses: [], ttl: 0 };
77
- const answers = packet.readUInt16BE(6), total = answers + packet.readUInt16BE(8) + packet.readUInt16BE(10);
78
- if (total > 128)
79
- return denied();
80
- const aliases = new Map(), records = [];
81
- for (let index = 0; index < total; index++) {
82
- const owner = name(offset);
83
- offset = owner.next;
84
- if (offset + 10 > packet.length)
85
- return denied();
86
- const kind = packet.readUInt16BE(offset), klass = packet.readUInt16BE(offset + 2), ttl = packet.readUInt32BE(offset + 4);
87
- const size = packet.readUInt16BE(offset + 8);
88
- offset += 10;
89
- const end = offset + size;
90
- if (end > packet.length)
91
- return denied();
92
- if (index < answers && klass === 1) {
93
- if (kind === 5) {
94
- const target = name(offset);
95
- if (target.next !== end || aliases.has(owner.value))
96
- return denied();
97
- aliases.set(owner.value, { target: normalizeHost(target.value), ttl });
98
- }
99
- else if (kind === type && ((type === 1 && size === 4) || (type === 28 && size === 16))) {
100
- const raw = type === 1 ? [...packet.subarray(offset, end)].join(".") :
101
- Array.from({ length: 8 }, (_, i) => packet.readUInt16BE(offset + 2 * i).toString(16)).join(":");
102
- records.push({ owner: owner.value, address: numericAddress(raw), ttl });
103
- }
104
- }
105
- offset = end;
106
- }
107
- if (offset !== packet.length)
108
- return denied();
109
- let target = host, ttl = Infinity;
110
- const seen = new Set();
111
- while (aliases.has(target)) {
112
- if (seen.has(target) || seen.size >= 8 || records.some(record => record.owner === target))
113
- return denied();
114
- seen.add(target);
115
- const alias = aliases.get(target);
116
- target = alias.target;
117
- ttl = Math.min(ttl, alias.ttl);
118
- }
119
- const selected = records.filter(record => record.owner === target);
120
- if (selected.length > 16)
121
- return denied();
122
- return { truncated: false, addresses: selected.map(record => record.address),
123
- ttl: Math.min(ttl, ...selected.map(record => record.ttl)) };
124
- }
125
- /** Only call from an already claimed resolve effect. Constructor/parsing never
126
- * use system DNS, ambient resolver configuration, proxy or implicit fallback. */
127
- export class PinnedDnsResolver {
128
- endpoint;
129
- constructor(endpoint) {
130
- this.endpoint = Object.freeze({ address: numericAddress(endpoint.address), port: endpoint.port });
131
- if (!Number.isInteger(endpoint.port) || endpoint.port < 1 || endpoint.port > 65535)
132
- throw new NetworkToolError("invalid_dns_endpoint");
133
- }
134
- async resolve(hostname, signal) {
135
- const host = normalizeHost(hostname);
136
- if (isIP(host))
137
- throw new NetworkToolError("dns_requires_hostname");
138
- const addresses = new Set();
139
- let ttl = Infinity;
140
- for (const type of [1, 28]) {
141
- const query = question(host, type);
142
- let response = answer(await this.udp(query.packet, signal), host, type, query.id);
143
- if (response.truncated)
144
- response = answer(await this.tcp(query.packet, signal), host, type, query.id);
145
- if (response.truncated)
146
- throw new NetworkToolError("truncated_tcp_dns_response");
147
- for (const address of response.addresses)
148
- addresses.add(address);
149
- if (response.addresses.length)
150
- ttl = Math.min(ttl, response.ttl * 1000);
151
- }
152
- if (!addresses.size || addresses.size > 16 || !Number.isFinite(ttl) || ttl <= 0)
153
- throw new NetworkToolError("unusable_dns_answer");
154
- return { addresses: [...addresses].sort(), ttlMs: ttl };
155
- }
156
- udp(packet, signal) {
157
- return new Promise((resolve, reject) => {
158
- const family = isIP(this.endpoint.address), wildcard = family === 4 ? "0.0.0.0" : "::";
159
- const socket = createSocket({ type: family === 4 ? "udp4" : "udp6",
160
- lookup: (host, _options, callback) => {
161
- // Node uses this hook for its implicit local bind as well as connect.
162
- // Preserve the wildcard bind; the remote endpoint is not a local address.
163
- if (host !== wildcard && host !== this.endpoint.address)
164
- callback(new NetworkToolError("unsupported_numeric_address"), "", family);
165
- else
166
- callback(null, host, family);
167
- } });
168
- let done = false;
169
- const finish = (error, value) => {
170
- if (done)
171
- return;
172
- done = true;
173
- signal.removeEventListener("abort", abort);
174
- const settle = () => { error ? reject(error) : resolve(value); };
175
- socket.once("close", settle);
176
- try {
177
- socket.close();
178
- }
179
- catch {
180
- // An already-aborted unbound socket has no descriptor or close event.
181
- socket.removeListener("close", settle);
182
- settle();
183
- }
184
- };
185
- const abort = () => finish(new NetworkToolError("dns_aborted"));
186
- socket.on("error", error => finish(error));
187
- socket.on("message", (message, remote) => {
188
- if (numericAddress(remote.address) !== this.endpoint.address || remote.port !== this.endpoint.port)
189
- return finish(new NetworkToolError("dns_socket_changed"));
190
- finish(undefined, message);
191
- });
192
- if (signal.aborted) {
193
- finish(new NetworkToolError("dns_aborted"));
194
- return;
195
- }
196
- signal.addEventListener("abort", abort, { once: true });
197
- socket.connect(this.endpoint.port, this.endpoint.address, () => { if (!done)
198
- socket.send(packet, error => { if (error)
199
- finish(error); }); });
200
- });
201
- }
202
- tcp(packet, signal) {
203
- return new Promise((resolve, reject) => {
204
- const socket = connect({ host: this.endpoint.address, port: this.endpoint.port, family: isIP(this.endpoint.address), autoSelectFamily: false });
205
- let done = false, bytes = Buffer.alloc(0);
206
- const finish = (error, value) => {
207
- if (done)
208
- return;
209
- done = true;
210
- signal.removeEventListener("abort", abort);
211
- socket.once("close", () => { error ? reject(error) : resolve(value); });
212
- socket.destroy();
213
- };
214
- const abort = () => finish(new NetworkToolError("dns_aborted"));
215
- socket.on("error", error => finish(error));
216
- socket.on("end", () => finish(new NetworkToolError("short_dns_response")));
217
- socket.on("connect", () => {
218
- if (done)
219
- return;
220
- if (!socket.remoteAddress || numericAddress(socket.remoteAddress) !== this.endpoint.address || socket.remotePort !== this.endpoint.port) {
221
- finish(new NetworkToolError("dns_socket_changed"));
222
- return;
223
- }
224
- const prefix = Buffer.alloc(2);
225
- prefix.writeUInt16BE(packet.length);
226
- socket.write(Buffer.concat([prefix, packet]));
227
- });
228
- socket.on("data", chunk => {
229
- if (!Buffer.isBuffer(chunk))
230
- return finish(new NetworkToolError("invalid_dns_encoding"));
231
- if (bytes.length + chunk.length > 65537)
232
- return finish(new NetworkToolError("oversized_dns_response"));
233
- bytes = Buffer.concat([bytes, chunk]);
234
- if (bytes.length < 2)
235
- return;
236
- const length = bytes.readUInt16BE();
237
- if (length < 12 || bytes.length > length + 2)
238
- return finish(new NetworkToolError("invalid_dns_frame"));
239
- if (bytes.length === length + 2)
240
- finish(undefined, bytes.subarray(2));
241
- });
242
- if (signal.aborted)
243
- abort();
244
- else
245
- signal.addEventListener("abort", abort, { once: true });
246
- });
247
- }
248
- }
@@ -1,38 +0,0 @@
1
- import { digest } from "../broker/policy.js";
2
- export const HTTP_DEPLOYMENT_SCHEMA = {
3
- type: "object", properties: {
4
- dnsResolvers: { type: "array", maxItems: 1, items: { type: "object", properties: {
5
- address: { type: "string", minLength: 1 }, port: { type: "integer", minimum: 1, maximum: 65535 },
6
- }, required: ["address", "port"], additionalProperties: false } },
7
- timeoutMs: { type: "integer", minimum: 1, maximum: 30000 },
8
- maxBodyBytes: { type: "integer", minimum: 1, maximum: 1048576 },
9
- maxResponseBytes: { type: "integer", minimum: 1, maximum: 1048576 },
10
- resolutionTtlMs: { type: "integer", minimum: 1, maximum: 60000 },
11
- }, additionalProperties: false,
12
- };
13
- /** No new wire fields or protocol enums. Arguments bind HTTP semantics; existing
14
- * network resources bind original authority and every numeric socket target. */
15
- export function httpContractExamples() {
16
- const request = { url: "https://example.test/v1/items", method: "POST", body: '{"item":"owned"}' };
17
- const scope = { runId: "run_example", stepExecutionId: "step_example", sessionId: "session_example", epoch: 1,
18
- profileVersionId: "profile_example" };
19
- const resource = (protocol, host, port) => ({
20
- kind: "network", protocol, host, port, identityDigest: digest({ scope, request, protocol, host, port }),
21
- });
22
- const origin = resource("https", "example.test", 443);
23
- const action = (phase, resources, extra = {}) => ({
24
- clientActionId: `${phase}_example`, action: { toolId: "http_request", arguments: { phase, ...request, ...extra }, resources },
25
- });
26
- return {
27
- resolve: action("resolve", [origin, resource("udp", "127.0.0.1", 53053), resource("tcp", "127.0.0.1", 53053)]),
28
- send: action("send", [origin, resource("https", "192.0.2.10", 443), resource("https", "2001:db8::10", 443)], { resolutionId: "resolution_example" }),
29
- policy: { defaultEffect: "deny", rules: [
30
- { kind: "tool", toolId: "http_request", effect: "allow" },
31
- { kind: "network", protocol: "https", host: "example.test", port: 443, effect: "require_approval" },
32
- { kind: "network", protocol: "udp", host: "127.0.0.1", port: 53053, effect: "allow" },
33
- { kind: "network", protocol: "tcp", host: "127.0.0.1", port: 53053, effect: "allow" },
34
- { kind: "network", protocol: "https", host: "192.0.2.10", port: 443, effect: "allow" },
35
- { kind: "network", protocol: "https", host: "2001:db8::10", port: 443, effect: "allow" },
36
- ] },
37
- };
38
- }