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

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 (36) hide show
  1. package/README.engine.md +64 -2
  2. package/README.md +66 -5
  3. package/dist/src/broker/native/README.md +15 -0
  4. package/dist/src/broker/native/build.js +3 -0
  5. package/dist/src/broker/native/command-helper.c +93 -0
  6. package/dist/src/cli/configure.js +193 -0
  7. package/dist/src/cli/daemon.js +5 -1
  8. package/dist/src/cli/helpers.js +12 -4
  9. package/dist/src/cli/main.js +12 -3
  10. package/dist/src/cli/runtime-build.js +38 -0
  11. package/dist/src/config/coding-policy.js +4 -0
  12. package/dist/src/config/deployment.js +26 -10
  13. package/dist/src/config/workflow-schema.json +11 -0
  14. package/dist/src/engine/commands.js +35 -4
  15. package/dist/src/engine/workflow-engine.js +70 -15
  16. package/dist/src/main.js +4 -1
  17. package/dist/src/mcp/main.js +4 -2
  18. package/dist/src/mcp/server.js +37 -6
  19. package/dist/src/runtime/engine-driver.js +11 -2
  20. package/dist/src/runtime/provider-bridge.js +4 -2
  21. package/dist/src/runtime/provider-transport.js +7 -5
  22. package/dist/src/server/api-contract.json +530 -2
  23. package/dist/src/server/application.js +9 -3
  24. package/dist/src/server/coding.js +254 -0
  25. package/dist/src/server/deployment.js +18 -6
  26. package/dist/src/server/history-handlers.js +16 -2
  27. package/dist/src/server/workspace-handlers.js +1 -1
  28. package/dist/src/tools/checks.js +12 -1
  29. package/dist/src/tools/command-check.js +34 -0
  30. package/dist/src/tools/commands.js +310 -0
  31. package/dist/src/tools/developer.js +351 -0
  32. package/dist/src/tools/index.js +19 -2
  33. package/dist/src/workspaces/index.js +244 -22
  34. package/dist/src/workspaces/source.js +295 -0
  35. package/package.json +4 -2
  36. package/scripts/postinstall.mjs +2 -1
@@ -0,0 +1,351 @@
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
+ export class DeveloperTools {
31
+ options;
32
+ validators = new Map([...DEVELOPER_DEFINITIONS].map(([name, d]) => [name, new Ajv2020({ strict: false }).compile(d.inputSchema)]));
33
+ questions = new Map();
34
+ pendingAnswers = new Map();
35
+ constructor(options) {
36
+ this.options = options;
37
+ }
38
+ registry() { return new Map([...DEVELOPER_DEFINITIONS].map(([name, definition]) => [name, { name, ...definition, prepare: (input, binding) => this.prepare(name, input, binding) }])); }
39
+ refreshInputWait(runId) {
40
+ const run = this.options.store.find('runs', runId);
41
+ if (!run)
42
+ return;
43
+ const pendingQuestionIds = this.listQuestions(runId).filter(q => q.state === 'pending').map(q => q.id);
44
+ this.options.store.put('runs', { ...run, version: run.version + 1, updatedAt: new Date().toISOString(), inputWait: { status: pendingQuestionIds.length ? 'waiting' : 'none', pendingQuestionIds } });
45
+ }
46
+ waiting(runId) { return this.listQuestions(runId).some(q => q.state === 'pending'); }
47
+ 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)); }
48
+ answer(id, answer) {
49
+ const q = this.options.store.private('worker_question', id);
50
+ if (!q)
51
+ throw new BrokerError('question_not_found', 404);
52
+ if (q.state === 'answered') {
53
+ if (q.answer !== answer)
54
+ throw new BrokerError('question_answer_conflict');
55
+ return q;
56
+ }
57
+ if (q.state !== 'pending')
58
+ throw new BrokerError('question_conversation_unavailable');
59
+ const next = { ...q, state: 'answered', answer };
60
+ this.options.store.setPrivate('worker_question', id, next);
61
+ this.refreshInputWait(q.runId);
62
+ this.options.hold(q.runId, `input:${id}`, false);
63
+ this.questions.get(id)?.(answer);
64
+ this.questions.delete(id);
65
+ this.options.wake(q.runId);
66
+ return next;
67
+ }
68
+ async runtimeResult(binding, request, result) {
69
+ if (!['ask_user', 'report_blocker'].includes(request.toolName) || !result.success)
70
+ return result;
71
+ const { questionId } = JSON.parse(result.text);
72
+ const q = this.options.store.private('worker_question', questionId);
73
+ if (!q || q.sessionId !== binding.sessionId || q.epoch !== binding.epoch)
74
+ throw new BrokerError('question_not_assigned');
75
+ if (q.state === 'answered')
76
+ return { success: true, text: JSON.stringify({ questionId, answer: q.answer }) };
77
+ const prior = this.pendingAnswers.get(q.id);
78
+ if (prior)
79
+ return prior;
80
+ const signal = this.options.signal(binding.runId);
81
+ const answer = new Promise(resolveAnswer => {
82
+ const abort = () => {
83
+ this.questions.delete(q.id);
84
+ const run = this.options.store.find('runs', q.runId), plan = this.options.store.private('run_plan', q.runId);
85
+ const cancelled = !!plan?.cancelOperationId || !!run && ['succeeded', 'failed', 'cancelled'].includes(run.state);
86
+ if (cancelled) {
87
+ this.options.store.setPrivate('worker_question', q.id, { ...q, state: 'cancelled' });
88
+ this.refreshInputWait(q.runId);
89
+ this.options.hold(q.runId, `input:${q.id}`, false);
90
+ }
91
+ resolveAnswer(cancelled ? 'Run cancelled.' : 'Conversation interrupted; this question remains pending for recovery.');
92
+ };
93
+ this.questions.set(q.id, value => { signal.removeEventListener('abort', abort); resolveAnswer(value); });
94
+ signal.addEventListener('abort', abort, { once: true });
95
+ if (signal.aborted)
96
+ abort();
97
+ });
98
+ const pending = answer.then(answer => ({ success: true, text: JSON.stringify({ questionId, answer }) }));
99
+ this.pendingAnswers.set(q.id, pending);
100
+ void pending.then(() => this.pendingAnswers.delete(q.id), () => this.pendingAnswers.delete(q.id));
101
+ return pending;
102
+ }
103
+ recoverQuestions() {
104
+ 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()) {
105
+ const q = JSON.parse(row.body);
106
+ this.refreshInputWait(q.runId);
107
+ this.options.hold(q.runId, `input:${q.id}`, true);
108
+ }
109
+ }
110
+ async close() { for (const resolveQuestion of this.questions.values())
111
+ resolveQuestion('Conversation interrupted; the operator question remains available for recovery.'); this.questions.clear(); }
112
+ prepare(name, input, binding) {
113
+ if (!binding || !this.validators.get(name)(input))
114
+ throw new BrokerError('invalid_tool_arguments', 400);
115
+ const context = this.options.resolveContext(binding), repository = this.options.workspaces.sourceRepository(binding.runId), args = input;
116
+ if (!repository)
117
+ throw new BrokerError('source_tracking_required', 422);
118
+ if (args.root !== undefined && args.root !== 'workspace')
119
+ throw new BrokerError('unassigned_tool_root', 403);
120
+ const writing = ['write_file', 'make_directory', 'apply_patch', 'delete_file', 'move_file'].includes(name) || name === 'run_command' && !args.readOnly;
121
+ if (name === 'run_command')
122
+ assertCommandScope(binding, !writing);
123
+ const paths = ['get_diff', 'run_command'].includes(name) ? ['.'] : typeof args.path === 'string' ? [args.path, ...(typeof args.destination === 'string' ? [args.destination] : [])] : [];
124
+ const identities = () => {
125
+ const resources = paths.map((path, index) => {
126
+ const target = path === '.' ? repository.root : repository.safePath(path, writing, !['delete_file', 'move_file'].includes(name), ['delete_file', 'move_file'].includes(name));
127
+ const stat = existsSync(target) ? lstatSync(target) : lstatSync(dirname(target));
128
+ 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 }) };
129
+ });
130
+ if (name === 'run_command' && writing)
131
+ resources.push({ ...resources[0], operation: 'read' }, { ...resources[0], operation: 'delete' });
132
+ if (name === 'list_files' || name === 'search_files') {
133
+ const base = String(args.path ?? '.');
134
+ for (const entry of repository.sourceEntries())
135
+ if (base === '.' || entry.path === base || entry.path.startsWith(base + '/'))
136
+ resources.push({ kind: 'filesystem', root: 'workspace', path: entry.path, operation: 'read', identityDigest: digest(entry.identity) });
137
+ }
138
+ return resources;
139
+ };
140
+ const resources = identities();
141
+ let used = false;
142
+ return { resources, revalidate: () => { this.options.resolveContext(binding); return identities(); }, execute: async () => {
143
+ if (used)
144
+ throw new BrokerError('tool_effect_reused');
145
+ used = true;
146
+ this.options.resolveContext(binding);
147
+ const result = (data) => ({ success: true, text: typeof data === 'string' ? data : JSON.stringify(data) });
148
+ if (name === 'run_command') {
149
+ try {
150
+ const record = await this.options.runner.start(binding, args);
151
+ 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 }) };
152
+ }
153
+ catch (error) {
154
+ if (!(error instanceof CommandAdmissionError))
155
+ throw error;
156
+ 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.' }) };
157
+ }
158
+ }
159
+ if (name === 'read_command_output')
160
+ return result(this.options.runner.output(String(args.commandId), args.stream, args.cursor, args.limit, binding));
161
+ if (name === 'write_command_input') {
162
+ this.options.runner.input(String(args.commandId), String(args.text), binding, Boolean(args.end));
163
+ return result('Input written.');
164
+ }
165
+ if (name === 'stop_command')
166
+ return result(await this.options.runner.stop(String(args.commandId), binding));
167
+ if (name === 'ask_user' || name === 'report_blocker') {
168
+ 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() };
169
+ this.options.store.setPrivate('worker_question', q.id, q);
170
+ this.refreshInputWait(q.runId);
171
+ this.options.hold(q.runId, `input:${q.id}`, true);
172
+ this.options.store.event(q.runId, 'worker_question', 'question', q.id, { question: q.question, kind: q.kind });
173
+ this.options.wake(binding.runId);
174
+ return result({ questionId: q.id, state: 'pending' });
175
+ }
176
+ if (name === 'get_capabilities') {
177
+ const session = this.options.store.get('sessions', binding.sessionId);
178
+ return result({ tools: binding.configuredTools, permissions: session.effectiveConfiguration.effectivePermissions, commands: this.options.runner.settings, limits: session.limits, submissionsUsed: session.submissionsUsed });
179
+ }
180
+ if (name === 'get_context') {
181
+ const access = this.options.store.private('session_access', binding.sessionId);
182
+ const cursor = Number(args.cursor ?? 0), limit = Number(args.limit ?? 16_384);
183
+ if (args.kind === 'guidance') {
184
+ const files = this.options.store.private('run_plan', binding.runId)?.workspaceInstructions?.files.filter(f => f.selected) ?? [];
185
+ if (typeof args.guidancePath === 'string') {
186
+ const file = files.find(f => f.path === args.guidancePath);
187
+ if (!file)
188
+ throw new BrokerError('guidance_not_assigned', 404);
189
+ const bytes = Buffer.from(file.content);
190
+ return result({ path: file.path, sha256: file.sha256, content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
191
+ }
192
+ const selected = files.slice(cursor, cursor + 20);
193
+ 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 });
194
+ }
195
+ if (['schema', 'schemas', 'questions'].includes(String(args.kind))) {
196
+ const authority = this.options.store.private('session_authority', binding.sessionId), plan = this.options.store.private('run_plan', binding.runId);
197
+ const data = args.kind === 'schema' ? authority.outputSchema : args.kind === 'schemas' ? plan?.graph?.resources ?? [] : this.listQuestions(binding.runId);
198
+ const bytes = Buffer.from(JSON.stringify(data));
199
+ return result({ content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
200
+ }
201
+ if (args.kind === 'inputs' || args.kind === 'messages') {
202
+ 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));
203
+ const bytes = Buffer.from(JSON.stringify(data));
204
+ return result({ content: bytes.subarray(cursor, cursor + limit).toString(), nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
205
+ }
206
+ if (args.kind === 'artifacts') {
207
+ const ids = access.inputArtifactIds.slice(cursor, cursor + 20);
208
+ 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 });
209
+ }
210
+ if (typeof args.artifactId === 'string') {
211
+ if (!access.inputArtifactIds.includes(args.artifactId))
212
+ throw new BrokerError('artifact_not_assigned', 403);
213
+ const artifact = this.options.store.get('artifacts', args.artifactId), bytes = Buffer.from(artifact.document.content), content = bytes.subarray(cursor, cursor + limit).toString('utf8');
214
+ return result({ id: artifact.id, content, nextCursor: cursor + limit < bytes.length ? cursor + limit : null });
215
+ }
216
+ 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) });
217
+ return result({ items: items.map(i => i.value), nextCursor: items.at(-1)?.seq ?? null });
218
+ }
219
+ if (name === 'get_diff') {
220
+ 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);
221
+ let count;
222
+ try {
223
+ count = readSync(fd, bytes, 0, bytes.length, cursor);
224
+ }
225
+ finally {
226
+ closeSync(fd);
227
+ }
228
+ return result({ ...diff, patchPath: undefined, patch: bytes.subarray(0, count).toString(), nextCursor: count ? cursor + count : null });
229
+ }
230
+ if (name === 'read_file') {
231
+ 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);
232
+ let text = '', pending = '', line = 1, nextLine = null, done = false;
233
+ const start = Number(args.startLine ?? 1), end = Number(args.endLine ?? Number.MAX_SAFE_INTEGER), decoder = new TextDecoder('utf-8', { fatal: true });
234
+ try {
235
+ for (;;) {
236
+ const count = readSync(fd, buffer, 0, buffer.length, null);
237
+ pending += decoder.decode(buffer.subarray(0, count), { stream: count > 0 });
238
+ let newline;
239
+ while ((newline = pending.indexOf('\n')) >= 0 || !count && pending.length) {
240
+ const length = newline >= 0 ? newline + 1 : pending.length, value = pending.slice(0, length);
241
+ pending = pending.slice(length);
242
+ if (line >= start && line <= end) {
243
+ if (Buffer.byteLength(text + value) > 65_536) {
244
+ nextLine = line;
245
+ done = true;
246
+ break;
247
+ }
248
+ text += value;
249
+ }
250
+ line++;
251
+ if (line > end) {
252
+ nextLine = line;
253
+ done = true;
254
+ break;
255
+ }
256
+ }
257
+ if (done || !count)
258
+ break;
259
+ if (pending.length > 262_144)
260
+ throw new BrokerError('line_too_large_use_command', 422);
261
+ }
262
+ }
263
+ finally {
264
+ closeSync(fd);
265
+ }
266
+ const digest = captured.blob;
267
+ return result(args.startLine || args.endLine || nextLine ? { content: text, startLine: start, nextLine, sha256: digest } : text);
268
+ }
269
+ if (name === 'list_files' || name === 'search_files') {
270
+ 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);
271
+ if (name === 'list_files')
272
+ return result({ entries: entries.slice(cursor, cursor + limit).map(({ path, type }) => ({ path, type })), nextCursor: cursor + limit < entries.length ? cursor + limit : null });
273
+ const matches = [];
274
+ let seen = 0, more = false;
275
+ const needle = args.caseSensitive ? String(args.query) : String(args.query).toLowerCase();
276
+ for (const entry of entries.filter(e => e.type === 'file')) {
277
+ const fd = openSync(repository.safePath(entry.path), constants.O_RDONLY | constants.O_NOFOLLOW), buffer = Buffer.alloc(65_536), decoder = new TextDecoder('utf-8');
278
+ let pending = '', line = 0;
279
+ try {
280
+ for (;;) {
281
+ const count = readSync(fd, buffer, 0, buffer.length, null);
282
+ pending += decoder.decode(buffer.subarray(0, count), { stream: count > 0 });
283
+ let newline;
284
+ while ((newline = pending.indexOf('\n')) >= 0 || !count && pending.length) {
285
+ const length = newline >= 0 ? newline + 1 : pending.length, value = pending.slice(0, length);
286
+ pending = pending.slice(length);
287
+ line++;
288
+ if ((args.caseSensitive ? value : value.toLowerCase()).includes(needle)) {
289
+ if (seen++ >= cursor) {
290
+ if (matches.length === limit) {
291
+ more = true;
292
+ break;
293
+ }
294
+ matches.push({ path: entry.path, line, text: value.slice(0, 4096).trimEnd() });
295
+ }
296
+ }
297
+ }
298
+ if (more || !count)
299
+ break;
300
+ if (pending.length > 262_144)
301
+ pending = pending.slice(-needle.length);
302
+ }
303
+ }
304
+ finally {
305
+ closeSync(fd);
306
+ }
307
+ if (more)
308
+ break;
309
+ }
310
+ return result({ matches, nextCursor: more ? cursor + matches.length : null });
311
+ }
312
+ return this.options.workspaces.sourceMutation(context, repo => {
313
+ 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 {
314
+ writeFileSync(temporary, content, { flag: 'wx', mode });
315
+ renameSync(temporary, path);
316
+ }
317
+ finally {
318
+ if (existsSync(temporary))
319
+ unlinkSync(temporary);
320
+ } };
321
+ if (name === 'make_directory')
322
+ mkdirSync(path, { recursive: true, mode: 0o755 });
323
+ else if (name === 'write_file')
324
+ atomicWrite(String(args.content));
325
+ else if (name === 'apply_patch') {
326
+ let content = readFileSync(path, 'utf8');
327
+ if (hash(content) !== args.expectedDigest)
328
+ throw new BrokerError('patch_precondition_failed', 409);
329
+ for (const edit of args.edits) {
330
+ const offset = content.indexOf(edit.oldText);
331
+ if (offset < 0 || content.indexOf(edit.oldText, offset + 1) >= 0)
332
+ throw new BrokerError('patch_match_not_unique', 409);
333
+ content = content.slice(0, offset) + edit.newText + content.slice(offset + edit.oldText.length);
334
+ }
335
+ atomicWrite(content);
336
+ }
337
+ else if (name === 'delete_file')
338
+ unlinkSync(path);
339
+ else if (name === 'move_file') {
340
+ const destination = repo.safePath(String(args.destination), true);
341
+ if (existsSync(destination))
342
+ throw new BrokerError('destination_exists', 409);
343
+ renameSync(path, destination);
344
+ }
345
+ else
346
+ throw new BrokerError('unsupported_tool');
347
+ return result(name === 'write_file' ? 'File written.' : 'Source updated.');
348
+ });
349
+ } };
350
+ }
351
+ }
@@ -69,6 +69,10 @@ export class ToolFactory {
69
69
  (refs.authorization !== undefined && (!refs.authorization || !this.options.http?.credentials)))
70
70
  throw new BrokerError("unsupported_tool_configuration", 422);
71
71
  }
72
+ else if (this.options.extensions?.has(name) && !filesystemToolDefinitions().has(name)) {
73
+ if (Object.keys(configuration).length || Object.keys(refs).length)
74
+ throw new BrokerError('unsupported_tool_configuration', 422);
75
+ }
72
76
  else {
73
77
  if (Object.keys(refs).length || Object.keys(configuration).some(key => !["root", "rootId", "scratchIndex"].includes(key)) ||
74
78
  (configuration.root !== undefined && !["workspace", "scratch", "deployment"].includes(String(configuration.root))) ||
@@ -82,9 +86,10 @@ export class ToolFactory {
82
86
  return jsonCopy(tool);
83
87
  }
84
88
  toolConfigurations() {
85
- return [...filesystemToolDefinitions().keys()].map(toolId => ({ toolId, configurationSchema: jsonCopy(FILE_TOOL_CONFIGURATION_SCHEMA), credentialSlots: [] }))
89
+ const extensions = [...(this.options.extensions?.keys() ?? [])].filter(name => !filesystemToolDefinitions().has(name)).map(toolId => ({ toolId, configurationSchema: { type: 'object', additionalProperties: false }, credentialSlots: [] }));
90
+ return extensions.concat([...filesystemToolDefinitions().keys()].map(toolId => ({ toolId, configurationSchema: jsonCopy(FILE_TOOL_CONFIGURATION_SCHEMA), credentialSlots: [] }))
86
91
  .concat([{ toolId: this.http.name, configurationSchema: jsonCopy(HTTP_TOOL_CONFIGURATION_SCHEMA),
87
- credentialSlots: this.options.http?.credentials ? ["authorization"] : [] }]);
92
+ credentialSlots: this.options.http?.credentials ? ["authorization"] : [] }]));
88
93
  }
89
94
  /** Pure registry for the global broker, available before a session exists. */
90
95
  registry() { return this.create(); }
@@ -143,6 +148,18 @@ export class ToolFactory {
143
148
  this.configuration(context, this.http.name);
144
149
  return this.wrap(this.http.prepare(input, binding), binding, context);
145
150
  } });
151
+ for (const [name, extension] of this.options.extensions ?? []) {
152
+ const legacy = tools.get(name);
153
+ tools.set(name, { ...extension, prepare: (input, binding) => {
154
+ if (!binding)
155
+ throw new BrokerError('missing_trusted_binding');
156
+ const context = this.context(binding, expected), configuration = this.configuration(context, name).configuration;
157
+ const root = input && typeof input === 'object' && !Array.isArray(input) ? input.root : undefined;
158
+ if (legacy && (!this.options.workspaces.sourceRepository(binding.runId) || root && root !== 'workspace' || configuration.root && configuration.root !== 'workspace'))
159
+ return legacy.prepare(input, binding);
160
+ return extension.prepare(input, binding);
161
+ } });
162
+ }
146
163
  return tools;
147
164
  }
148
165
  wrap(prepared, binding, context, close, mutation) {