@workser/engine 0.1.0

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 (64) hide show
  1. package/NOTICE +8 -0
  2. package/README.md +70 -0
  3. package/dist/src/compact.d.ts +44 -0
  4. package/dist/src/compact.js +116 -0
  5. package/dist/src/engine.d.ts +84 -0
  6. package/dist/src/engine.js +142 -0
  7. package/dist/src/index.d.ts +13 -0
  8. package/dist/src/index.js +13 -0
  9. package/dist/src/model.d.ts +56 -0
  10. package/dist/src/model.js +153 -0
  11. package/dist/src/place/e2b.d.ts +76 -0
  12. package/dist/src/place/e2b.js +114 -0
  13. package/dist/src/place/env.d.ts +3 -0
  14. package/dist/src/place/env.js +14 -0
  15. package/dist/src/place/local.d.ts +33 -0
  16. package/dist/src/place/local.js +138 -0
  17. package/dist/src/prompts.d.ts +27 -0
  18. package/dist/src/prompts.js +108 -0
  19. package/dist/src/session.d.ts +115 -0
  20. package/dist/src/session.js +523 -0
  21. package/dist/src/tools/files.d.ts +9 -0
  22. package/dist/src/tools/files.js +209 -0
  23. package/dist/src/tools/patch.d.ts +49 -0
  24. package/dist/src/tools/patch.js +272 -0
  25. package/dist/src/tools/relay.d.ts +25 -0
  26. package/dist/src/tools/relay.js +82 -0
  27. package/dist/src/tools/search.d.ts +5 -0
  28. package/dist/src/tools/search.js +99 -0
  29. package/dist/src/tools/shell.d.ts +26 -0
  30. package/dist/src/tools/shell.js +123 -0
  31. package/dist/src/tools/types.d.ts +49 -0
  32. package/dist/src/tools/types.js +16 -0
  33. package/dist/src/tools/workser-tool.d.ts +39 -0
  34. package/dist/src/tools/workser-tool.js +51 -0
  35. package/dist/src/vendor.d.ts +4 -0
  36. package/dist/src/vendor.js +17 -0
  37. package/package.json +42 -0
  38. package/vendor/opencode-1.18.23/COMMIT +1 -0
  39. package/vendor/opencode-1.18.23/LICENSE +21 -0
  40. package/vendor/opencode-1.18.23/session/prompt/anthropic.txt +105 -0
  41. package/vendor/opencode-1.18.23/session/prompt/beast.txt +147 -0
  42. package/vendor/opencode-1.18.23/session/prompt/build-switch.txt +5 -0
  43. package/vendor/opencode-1.18.23/session/prompt/codex.txt +79 -0
  44. package/vendor/opencode-1.18.23/session/prompt/copilot-gpt-5.txt +143 -0
  45. package/vendor/opencode-1.18.23/session/prompt/default.txt +95 -0
  46. package/vendor/opencode-1.18.23/session/prompt/gemini.txt +155 -0
  47. package/vendor/opencode-1.18.23/session/prompt/gpt.txt +107 -0
  48. package/vendor/opencode-1.18.23/session/prompt/kimi.txt +95 -0
  49. package/vendor/opencode-1.18.23/session/prompt/meta.txt +65 -0
  50. package/vendor/opencode-1.18.23/session/prompt/plan-mode.txt +70 -0
  51. package/vendor/opencode-1.18.23/session/prompt/plan-reminder-anthropic.txt +67 -0
  52. package/vendor/opencode-1.18.23/session/prompt/plan.txt +26 -0
  53. package/vendor/opencode-1.18.23/session/prompt/trinity.txt +97 -0
  54. package/vendor/opencode-1.18.23/session/system.ts.ref +152 -0
  55. package/vendor/opencode-1.18.23/tool/apply_patch.txt +33 -0
  56. package/vendor/opencode-1.18.23/tool/edit-replace.ts +535 -0
  57. package/vendor/opencode-1.18.23/tool/edit.txt +10 -0
  58. package/vendor/opencode-1.18.23/tool/glob.txt +6 -0
  59. package/vendor/opencode-1.18.23/tool/grep.txt +8 -0
  60. package/vendor/opencode-1.18.23/tool/read.txt +14 -0
  61. package/vendor/opencode-1.18.23/tool/shell/prompt.ts.ref +293 -0
  62. package/vendor/opencode-1.18.23/tool/shell/shell.txt +21 -0
  63. package/vendor/opencode-1.18.23/tool/todowrite.txt +44 -0
  64. package/vendor/opencode-1.18.23/tool/write.txt +8 -0
@@ -0,0 +1,209 @@
1
+ import { vendored } from '../vendor.js';
2
+ import { replace } from '../../vendor/opencode-1.18.23/tool/edit-replace.js';
3
+ import { absolute, str } from './types.js';
4
+ const DEFAULT_READ_LIMIT = 2000;
5
+ const MAX_LINE_LENGTH = 2000;
6
+ const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)`;
7
+ const MAX_BYTES = 50 * 1024;
8
+ const MAX_BYTES_LABEL = `${MAX_BYTES / 1024} KB`;
9
+ async function exists(ctx, path) {
10
+ const parent = path.replace(/\/[^/]+\/?$/, '') || '/';
11
+ const name = path.replace(/\/+$/, '').split('/').pop();
12
+ try {
13
+ const entries = await ctx.place.list(parent);
14
+ const hit = entries.find((one) => one.name === name);
15
+ return hit ? (hit.type === 'dir' ? 'dir' : 'file') : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ function isBinary(bytes) {
22
+ const sample = bytes.subarray(0, 8000);
23
+ for (const byte of sample)
24
+ if (byte === 0)
25
+ return true;
26
+ return false;
27
+ }
28
+ /** Upstream `read`: numbered lines `N: text`, offset/limit, the same notes. */
29
+ export const readTool = {
30
+ name: 'read',
31
+ description: vendored('tool/read.txt'),
32
+ parameters: {
33
+ type: 'object',
34
+ properties: {
35
+ filePath: { type: 'string', description: 'The absolute path to the file or directory to read' },
36
+ offset: { type: 'integer', minimum: 0, description: 'The line number to start reading from (1-indexed)' },
37
+ limit: { type: 'integer', minimum: 0, description: 'The maximum number of lines to read (defaults to 2000)' },
38
+ },
39
+ required: ['filePath'],
40
+ },
41
+ async execute(args, ctx) {
42
+ const filepath = absolute(ctx.root, str(args.filePath, 'filePath'));
43
+ const limit = typeof args.limit === 'number' && args.limit > 0 ? args.limit : DEFAULT_READ_LIMIT;
44
+ const offset = typeof args.offset === 'number' && args.offset > 0 ? args.offset : 1;
45
+ const kind = await exists(ctx, filepath);
46
+ if (kind === 'dir') {
47
+ const items = (await ctx.place.list(filepath))
48
+ .map((one) => (one.type === 'dir' ? `${one.name}/` : one.name))
49
+ .sort((a, b) => a.localeCompare(b));
50
+ const start = offset - 1;
51
+ const sliced = items.slice(start, start + limit);
52
+ const truncated = start + sliced.length < items.length;
53
+ return {
54
+ title: filepath,
55
+ output: [
56
+ `<path>${filepath}</path>`,
57
+ `<type>directory</type>`,
58
+ `<entries>`,
59
+ sliced.join('\n'),
60
+ truncated
61
+ ? `\n(Showing ${sliced.length} of ${items.length} entries. Use 'offset' parameter to read beyond entry ${offset + sliced.length})`
62
+ : `\n(${items.length} entries)`,
63
+ `</entries>`,
64
+ ].join('\n'),
65
+ };
66
+ }
67
+ if (!kind)
68
+ throw new Error(`File not found: ${filepath}`);
69
+ const bytes = await ctx.place.readFile(filepath);
70
+ if (isBinary(bytes))
71
+ throw new Error(`Cannot read binary file: ${filepath}`);
72
+ const all = new TextDecoder().decode(bytes).split('\n');
73
+ if (all.length > 0 && all[all.length - 1] === '')
74
+ all.pop();
75
+ const count = all.length;
76
+ if (count < offset && !(count === 0 && offset === 1)) {
77
+ throw new Error(`Offset ${offset} is out of range for this file (${count} lines)`);
78
+ }
79
+ const raw = [];
80
+ let bytesOut = 0;
81
+ let cut = false;
82
+ for (const line of all.slice(offset - 1, offset - 1 + limit)) {
83
+ const shown = line.length > MAX_LINE_LENGTH ? line.substring(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX : line;
84
+ bytesOut += Buffer.byteLength(shown) + 1;
85
+ if (bytesOut > MAX_BYTES) {
86
+ cut = true;
87
+ break;
88
+ }
89
+ raw.push(shown);
90
+ }
91
+ const more = offset - 1 + raw.length < count;
92
+ let output = [`<path>${filepath}</path>`, `<type>file</type>`, '<content>\n'].join('\n');
93
+ output += raw.map((line, i) => `${i + offset}: ${line}`).join('\n');
94
+ const last = offset + raw.length - 1;
95
+ const next = last + 1;
96
+ if (cut)
97
+ output += `\n\n(Output capped at ${MAX_BYTES_LABEL}. Showing lines ${offset}-${last}. Use offset=${next} to continue.)`;
98
+ else if (more)
99
+ output += `\n\n(Showing lines ${offset}-${last} of ${count}. Use offset=${next} to continue.)`;
100
+ else
101
+ output += `\n\n(End of file - total ${count} lines)`;
102
+ output += '\n</content>';
103
+ ctx.read.add(filepath);
104
+ return { title: filepath, output };
105
+ },
106
+ };
107
+ /** Upstream `write`: whole-file write; asks for the `edit` permission. */
108
+ export const writeTool = {
109
+ name: 'write',
110
+ description: vendored('tool/write.txt'),
111
+ parameters: {
112
+ type: 'object',
113
+ properties: {
114
+ content: { type: 'string', description: 'The content to write to the file' },
115
+ filePath: { type: 'string', description: 'The absolute path to the file to write (must be absolute, not relative)' },
116
+ },
117
+ required: ['content', 'filePath'],
118
+ },
119
+ async execute(args, ctx) {
120
+ const filepath = absolute(ctx.root, str(args.filePath, 'filePath'));
121
+ const content = str(args.content, 'content');
122
+ const existed = (await exists(ctx, filepath)) === 'file';
123
+ await ctx.ask({ permission: 'edit', title: `Write ${filepath}`, detail: filepath, patterns: [filepath] });
124
+ await ctx.place.writeFile(filepath, content);
125
+ ctx.read.add(filepath);
126
+ return {
127
+ title: filepath,
128
+ output: 'Wrote file successfully.',
129
+ changed: [{ path: filepath, change: existed ? 'modified' : 'added' }],
130
+ };
131
+ },
132
+ };
133
+ /** Upstream `edit`: oldString → newString with upstream's own matching (vendored). */
134
+ export const editTool = {
135
+ name: 'edit',
136
+ description: vendored('tool/edit.txt'),
137
+ parameters: {
138
+ type: 'object',
139
+ properties: {
140
+ filePath: { type: 'string', description: 'The absolute path to the file to modify' },
141
+ oldString: { type: 'string', description: 'The text to replace' },
142
+ newString: { type: 'string', description: 'The text to replace it with (must be different from oldString)' },
143
+ replaceAll: { type: 'boolean', description: 'Replace all occurrences of oldString (default false)' },
144
+ },
145
+ required: ['filePath', 'oldString', 'newString'],
146
+ },
147
+ async execute(args, ctx) {
148
+ const filepath = absolute(ctx.root, str(args.filePath, 'filePath'));
149
+ const oldString = str(args.oldString, 'oldString');
150
+ const newString = str(args.newString, 'newString');
151
+ if (oldString === newString)
152
+ throw new Error('No changes to apply: oldString and newString are identical.');
153
+ const kind = await exists(ctx, filepath);
154
+ if (oldString === '' && kind !== 'file') {
155
+ await ctx.ask({ permission: 'edit', title: `Create ${filepath}`, detail: filepath, patterns: [filepath] });
156
+ await ctx.place.writeFile(filepath, newString);
157
+ return { title: filepath, output: 'Edit applied successfully.', changed: [{ path: filepath, change: 'added' }] };
158
+ }
159
+ if (!kind)
160
+ throw new Error(`File ${filepath} not found`);
161
+ if (kind === 'dir')
162
+ throw new Error(`Path is a directory, not a file: ${filepath}`);
163
+ const before = new TextDecoder().decode(await ctx.place.readFile(filepath));
164
+ const ending = before.includes('\r\n') ? '\r\n' : '\n';
165
+ const normal = before.replaceAll('\r\n', '\n');
166
+ const after = replace(normal, oldString.replaceAll('\r\n', '\n'), newString.replaceAll('\r\n', '\n'), args.replaceAll === true);
167
+ await ctx.ask({ permission: 'edit', title: `Edit ${filepath}`, detail: filepath, patterns: [filepath] });
168
+ await ctx.place.writeFile(filepath, ending === '\r\n' ? after.replaceAll('\n', '\r\n') : after);
169
+ ctx.read.add(filepath);
170
+ return { title: filepath, output: 'Edit applied successfully.', changed: [{ path: filepath, change: 'modified' }] };
171
+ },
172
+ };
173
+ /** Upstream `todowrite`: the plan as a list; returned as JSON like upstream. */
174
+ export const todoWriteTool = {
175
+ name: 'todowrite',
176
+ description: vendored('tool/todowrite.txt'),
177
+ parameters: {
178
+ type: 'object',
179
+ properties: {
180
+ todos: {
181
+ type: 'array',
182
+ description: 'The updated todo list',
183
+ items: {
184
+ type: 'object',
185
+ properties: {
186
+ content: { type: 'string', description: 'Brief description of the task' },
187
+ status: {
188
+ type: 'string',
189
+ enum: ['pending', 'in_progress', 'completed', 'cancelled'],
190
+ description: 'Current status of the task: pending, in_progress, completed, cancelled',
191
+ },
192
+ priority: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Priority level of the task: high, medium, low' },
193
+ id: { type: 'string', description: 'Unique identifier for the todo item' },
194
+ },
195
+ required: ['content', 'status'],
196
+ },
197
+ },
198
+ },
199
+ required: ['todos'],
200
+ },
201
+ async execute(args, ctx) {
202
+ const todos = Array.isArray(args.todos) ? args.todos : [];
203
+ ctx.todos.splice(0, ctx.todos.length, ...todos);
204
+ return {
205
+ title: `${todos.filter((one) => one.status !== 'completed').length} todos`,
206
+ output: JSON.stringify(todos, null, 2),
207
+ };
208
+ },
209
+ };
@@ -0,0 +1,49 @@
1
+ import { type ToolSpec } from './types.js';
2
+ /**
3
+ * Upstream's `apply_patch` (the tool OpenCode gives GPT models instead of
4
+ * `edit` and `write`): one patch in the stripped-down envelope its vendored
5
+ * description teaches —
6
+ *
7
+ * *** Begin Patch
8
+ * *** Add File: <path> then `+` lines
9
+ * *** Delete File: <path>
10
+ * *** Update File: <path> optional `*** Move to: <path>`, then `@@` chunks
11
+ * *** End Patch
12
+ *
13
+ * The parser and the matcher are ours (upstream's live in its Effect
14
+ * services); the format, the argument name (`patchText`) and the answer
15
+ * ("Success. Updated the following files: …") are upstream's. A patch is
16
+ * checked in full before anything is written, so a bad chunk changes nothing.
17
+ */
18
+ export type PatchOp = {
19
+ type: 'add';
20
+ path: string;
21
+ content: string;
22
+ } | {
23
+ type: 'delete';
24
+ path: string;
25
+ } | {
26
+ type: 'update';
27
+ path: string;
28
+ moveTo?: string;
29
+ chunks: PatchChunk[];
30
+ };
31
+ export interface PatchChunk {
32
+ /** Text after `@@`, used to find where the chunk starts. */
33
+ anchor: string;
34
+ /** Lines the file has now (context and removed), in order. */
35
+ old: string[];
36
+ /** Lines it should have (context and added), in order. */
37
+ next: string[];
38
+ /** `*** End of File`: the chunk ends at the end of the file. */
39
+ eof: boolean;
40
+ }
41
+ export declare class PatchError extends Error {
42
+ constructor(message: string);
43
+ }
44
+ export declare function parsePatch(text: string): PatchOp[];
45
+ /** Apply one file's chunks to its text. Throws a PatchError naming the chunk that doesn't fit. */
46
+ export declare function applyChunks(path: string, text: string, chunks: PatchChunk[]): string;
47
+ export declare const applyPatchTool: ToolSpec;
48
+ /** Upstream's rule (tool/registry.ts): GPT models (not gpt-4, not oss) get apply_patch instead of edit and write. */
49
+ export declare function usesPatch(modelId: string): boolean;
@@ -0,0 +1,272 @@
1
+ import { vendored } from '../vendor.js';
2
+ import { absolute, str } from './types.js';
3
+ export class PatchError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'PatchError';
7
+ }
8
+ }
9
+ export function parsePatch(text) {
10
+ const lines = text.replaceAll('\r\n', '\n').split('\n');
11
+ while (lines.length && lines[lines.length - 1].trim() === '')
12
+ lines.pop();
13
+ let i = 0;
14
+ while (i < lines.length && lines[i].trim() === '')
15
+ i++;
16
+ // Models sometimes wrap the patch in a heredoc or a code fence.
17
+ while (i < lines.length && /^(```|cat\s*<<|apply_patch\s*<<)/.test(lines[i].trim()))
18
+ i++;
19
+ if (lines[i]?.trim() !== '*** Begin Patch')
20
+ throw new PatchError("The patch must start with '*** Begin Patch'.");
21
+ i++;
22
+ const ops = [];
23
+ let ended = false;
24
+ while (i < lines.length) {
25
+ const line = lines[i];
26
+ if (line.trim() === '*** End Patch') {
27
+ ended = true;
28
+ break;
29
+ }
30
+ let match;
31
+ if ((match = line.match(/^\*\*\* Add File:\s*(.+)$/))) {
32
+ i++;
33
+ const body = [];
34
+ while (i < lines.length && !lines[i].startsWith('***')) {
35
+ const one = lines[i];
36
+ if (!one.startsWith('+'))
37
+ throw new PatchError(`Line ${i + 1}: every line of an added file starts with '+'.`);
38
+ body.push(one.slice(1));
39
+ i++;
40
+ }
41
+ ops.push({ type: 'add', path: match[1].trim(), content: body.length ? `${body.join('\n')}\n` : '' });
42
+ continue;
43
+ }
44
+ if ((match = line.match(/^\*\*\* Delete File:\s*(.+)$/))) {
45
+ ops.push({ type: 'delete', path: match[1].trim() });
46
+ i++;
47
+ continue;
48
+ }
49
+ if ((match = line.match(/^\*\*\* Update File:\s*(.+)$/))) {
50
+ const op = { type: 'update', path: match[1].trim(), chunks: [] };
51
+ i++;
52
+ const move = lines[i]?.match(/^\*\*\* Move to:\s*(.+)$/);
53
+ if (move) {
54
+ op.moveTo = move[1].trim();
55
+ i++;
56
+ }
57
+ let chunk = null;
58
+ const flush = () => {
59
+ if (chunk && (chunk.old.length || chunk.next.length))
60
+ op.chunks.push(chunk);
61
+ chunk = null;
62
+ };
63
+ while (i < lines.length) {
64
+ const one = lines[i];
65
+ if (one.trim() === '*** End of File') {
66
+ if (chunk)
67
+ chunk.eof = true;
68
+ i++;
69
+ continue;
70
+ }
71
+ if (one.startsWith('***'))
72
+ break;
73
+ if (one.startsWith('@@')) {
74
+ flush();
75
+ chunk = { anchor: one.slice(2).trim(), old: [], next: [], eof: false };
76
+ i++;
77
+ continue;
78
+ }
79
+ chunk ??= { anchor: '', old: [], next: [], eof: false };
80
+ const mark = one[0];
81
+ const rest = one.slice(1);
82
+ if (mark === '+')
83
+ chunk.next.push(rest);
84
+ else if (mark === '-')
85
+ chunk.old.push(rest);
86
+ else if (mark === ' ') {
87
+ chunk.old.push(rest);
88
+ chunk.next.push(rest);
89
+ }
90
+ else if (one === '') {
91
+ // A blank context line whose leading space was trimmed.
92
+ chunk.old.push('');
93
+ chunk.next.push('');
94
+ }
95
+ else {
96
+ throw new PatchError(`Line ${i + 1}: a changed line starts with ' ', '-' or '+'.`);
97
+ }
98
+ i++;
99
+ }
100
+ flush();
101
+ if (!op.chunks.length && !op.moveTo)
102
+ throw new PatchError(`'${op.path}': an update needs at least one change.`);
103
+ ops.push(op);
104
+ continue;
105
+ }
106
+ if (line.trim() === '') {
107
+ i++;
108
+ continue;
109
+ }
110
+ throw new PatchError(`Line ${i + 1}: expected '*** Add File', '*** Delete File', '*** Update File' or '*** End Patch'.`);
111
+ }
112
+ if (!ended)
113
+ throw new PatchError("The patch must end with '*** End Patch'.");
114
+ if (!ops.length)
115
+ throw new PatchError('The patch has no file operations.');
116
+ return ops;
117
+ }
118
+ /** Where `seek` starts in `lines` at or after `from`: exact, then ignoring trailing, then all spaces. */
119
+ function find(lines, seek, from, eof) {
120
+ if (seek.length === 0)
121
+ return eof ? lines.length : from;
122
+ const passes = [(a) => a, (a) => a.trimEnd(), (a) => a.trim()];
123
+ for (const norm of passes) {
124
+ const want = seek.map(norm);
125
+ const starts = eof ? [lines.length - seek.length] : range(from, lines.length - seek.length + 1);
126
+ for (const start of starts) {
127
+ if (start < 0)
128
+ continue;
129
+ let ok = true;
130
+ for (let k = 0; k < want.length; k++) {
131
+ if (norm(lines[start + k] ?? '') !== want[k]) {
132
+ ok = false;
133
+ break;
134
+ }
135
+ }
136
+ if (ok)
137
+ return start;
138
+ }
139
+ }
140
+ return -1;
141
+ }
142
+ function range(from, to) {
143
+ const out = [];
144
+ for (let n = from; n < to; n++)
145
+ out.push(n);
146
+ return out;
147
+ }
148
+ /** Apply one file's chunks to its text. Throws a PatchError naming the chunk that doesn't fit. */
149
+ export function applyChunks(path, text, chunks) {
150
+ const ending = text.includes('\r\n') ? '\r\n' : '\n';
151
+ const lines = text.replaceAll('\r\n', '\n').split('\n');
152
+ const trailing = lines.length > 0 && lines[lines.length - 1] === '';
153
+ if (trailing)
154
+ lines.pop();
155
+ let cursor = 0;
156
+ const edits = [];
157
+ for (const [n, chunk] of chunks.entries()) {
158
+ if (chunk.anchor) {
159
+ const at = find(lines, [chunk.anchor], cursor, false);
160
+ if (at >= 0)
161
+ cursor = at + (chunk.old[0]?.trim() === chunk.anchor.trim() ? 0 : 1);
162
+ }
163
+ let old = chunk.old;
164
+ let next = chunk.next;
165
+ let start = find(lines, old, cursor, chunk.eof);
166
+ if (start < 0 && old.length && old[old.length - 1] === '') {
167
+ // A trailing blank context line the file doesn't have.
168
+ old = old.slice(0, -1);
169
+ next = next[next.length - 1] === '' ? next.slice(0, -1) : next;
170
+ start = find(lines, old, cursor, chunk.eof);
171
+ }
172
+ if (start < 0) {
173
+ throw new PatchError(`Failed to find the lines of change ${n + 1} in ${path}:\n${chunk.old.slice(0, 8).join('\n')}`);
174
+ }
175
+ edits.push({ start, count: old.length, next });
176
+ cursor = start + old.length;
177
+ }
178
+ for (const edit of edits.reverse())
179
+ lines.splice(edit.start, edit.count, ...edit.next);
180
+ const joined = lines.join('\n') + (trailing || lines.length ? '\n' : '');
181
+ return ending === '\r\n' ? joined.replaceAll('\n', '\r\n') : joined;
182
+ }
183
+ async function kindOf(ctx, path) {
184
+ const parent = path.replace(/\/[^/]+\/?$/, '') || '/';
185
+ const name = path.replace(/\/+$/, '').split('/').pop();
186
+ try {
187
+ const hit = (await ctx.place.list(parent)).find((one) => one.name === name);
188
+ return hit ? (hit.type === 'dir' ? 'dir' : 'file') : null;
189
+ }
190
+ catch {
191
+ return null;
192
+ }
193
+ }
194
+ export const applyPatchTool = {
195
+ name: 'apply_patch',
196
+ description: vendored('tool/apply_patch.txt'),
197
+ parameters: {
198
+ type: 'object',
199
+ properties: {
200
+ patchText: { type: 'string', description: 'The full patch text that describes all changes to be made' },
201
+ },
202
+ required: ['patchText'],
203
+ },
204
+ async execute(args, ctx) {
205
+ const ops = parsePatch(str(args.patchText, 'patchText'));
206
+ // Check everything first: a patch lands whole or not at all.
207
+ const writes = [];
208
+ const deletes = [];
209
+ const summary = [];
210
+ for (const op of ops) {
211
+ const path = absolute(ctx.root, op.path);
212
+ if (op.type === 'add') {
213
+ if ((await kindOf(ctx, path)) === 'dir')
214
+ throw new PatchError(`${op.path} is a folder.`);
215
+ writes.push({ path, content: op.content, change: 'added' });
216
+ summary.push(`A ${op.path}`);
217
+ }
218
+ else if (op.type === 'delete') {
219
+ if ((await kindOf(ctx, path)) !== 'file')
220
+ throw new PatchError(`Failed to delete ${op.path}: no such file.`);
221
+ deletes.push(path);
222
+ summary.push(`D ${op.path}`);
223
+ }
224
+ else {
225
+ if ((await kindOf(ctx, path)) !== 'file')
226
+ throw new PatchError(`Failed to update ${op.path}: no such file.`);
227
+ const before = new TextDecoder().decode(await ctx.place.readFile(path));
228
+ const after = op.chunks.length ? applyChunks(op.path, before, op.chunks) : before;
229
+ if (op.moveTo) {
230
+ const target = absolute(ctx.root, op.moveTo);
231
+ writes.push({ path: target, content: after, change: 'added' });
232
+ deletes.push(path);
233
+ summary.push(`M ${op.moveTo}`);
234
+ }
235
+ else {
236
+ writes.push({ path, content: after, change: 'modified' });
237
+ summary.push(`M ${op.path}`);
238
+ }
239
+ }
240
+ }
241
+ const paths = [...writes.map((one) => one.path), ...deletes];
242
+ await ctx.ask({
243
+ permission: 'edit',
244
+ title: `Patch ${paths.length} file${paths.length === 1 ? '' : 's'}`,
245
+ detail: paths.join('\n'),
246
+ patterns: paths,
247
+ });
248
+ for (const one of writes) {
249
+ await ctx.place.writeFile(one.path, one.content);
250
+ ctx.read.add(one.path);
251
+ }
252
+ for (const path of deletes) {
253
+ const quoted = `'${path.replace(/'/g, `'\\''`)}'`;
254
+ const removed = await ctx.place.exec(`rm -f -- ${quoted}`, { timeoutMs: 30_000 });
255
+ if (removed.exitCode !== 0)
256
+ throw new PatchError(`Could not delete ${path}: ${removed.stderr.trim()}`);
257
+ }
258
+ return {
259
+ title: summary.join(', ').slice(0, 200),
260
+ output: `Success. Updated the following files:\n${summary.join('\n')}`,
261
+ changed: [
262
+ ...writes.map((one) => ({ path: one.path, change: one.change })),
263
+ ...deletes.map((path) => ({ path, change: 'deleted' })),
264
+ ],
265
+ };
266
+ },
267
+ };
268
+ /** Upstream's rule (tool/registry.ts): GPT models (not gpt-4, not oss) get apply_patch instead of edit and write. */
269
+ export function usesPatch(modelId) {
270
+ const id = modelId.split('/').pop() ?? modelId;
271
+ return id.includes('gpt-') && !id.includes('oss') && !id.includes('gpt-4');
272
+ }
@@ -0,0 +1,25 @@
1
+ import { type ToolSpec } from './types.js';
2
+ /**
3
+ * THE KEY RELAY FOR A LOOP THAT RUNS OUTSIDE THE MACHINE (plan "Sandbox key
4
+ * relay", the engine's own `E2BPlace` mode).
5
+ *
6
+ * In the runner's mode the grant lives in the runner's loopback broker on the
7
+ * machine, and the agent's commands call `$WORKSER_VAULT_RELAY/<host>/<path>`.
8
+ * When the loop runs in a Trigger.dev worker and the machine is only a Place,
9
+ * there is no broker on the machine to call — and the grant must not be put on
10
+ * the machine. So the worker itself makes the call: this tool sends the
11
+ * request from the loop's process, with the grant in a header the gateway reads
12
+ * (`x-workser-key-grant`), and the agent writes `{{vault:NAME}}` where a key
13
+ * goes, exactly as with the broker. The gateway does the rest (opens the
14
+ * grant, checks the run, swaps a key in only for its own host, takes any
15
+ * echoed key out of the answer). The agent never sees a key or the grant.
16
+ */
17
+ export interface KeyRelay {
18
+ /** `<gateway>/gateway/v1/key-relay` */
19
+ url: string;
20
+ /** Sealed to the gateway at dispatch; opaque here. */
21
+ grant: string;
22
+ /** The key names the agent may write as `{{vault:NAME}}`. */
23
+ names: string[];
24
+ }
25
+ export declare function vaultFetchTool(relay: KeyRelay, fetchFn?: typeof fetch): ToolSpec;
@@ -0,0 +1,82 @@
1
+ import { str } from './types.js';
2
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
3
+ const MAX_BODY_BYTES = 1024 * 1024;
4
+ const MAX_OUTPUT_CHARS = 50 * 1024;
5
+ const PLACEHOLDER = /\{\{vault:([A-Za-z0-9][A-Za-z0-9_.-]{0,79})\}\}/g;
6
+ /** Headers the caller may not set: the loop sets its own, the gateway does the keys. */
7
+ const FORBIDDEN_HEADERS = new Set(['host', 'cookie', 'content-length', 'transfer-encoding', 'connection', 'x-workser-key-grant', 'x-workser-broker-key']);
8
+ export function vaultFetchTool(relay, fetchFn = fetch) {
9
+ const names = relay.names.join(', ');
10
+ return {
11
+ name: 'vault_fetch',
12
+ description: `Call an API with one of the business's saved API keys without ever seeing the key. Write {{vault:NAME}} where the key goes ` +
13
+ `(a header such as Authorization: "Bearer {{vault:NAME}}", or a query value); it is filled in only for that key's own site. ` +
14
+ `Keys you may name: ${names || '(none)'}. Only https URLs; GET, POST, PUT, PATCH, DELETE. Do not put a key in a bash command: use this tool.`,
15
+ parameters: {
16
+ type: 'object',
17
+ properties: {
18
+ url: { type: 'string', description: 'The full https URL, e.g. https://api.stripe.com/v1/charges' },
19
+ method: { type: 'string', enum: METHODS, description: 'Default GET' },
20
+ headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Request headers; put {{vault:NAME}} where a key goes' },
21
+ body: { type: 'string', description: 'The request body, sent as is (never touched by the relay)' },
22
+ },
23
+ required: ['url'],
24
+ },
25
+ async execute(args, ctx) {
26
+ let target;
27
+ try {
28
+ target = new URL(str(args.url, 'url'));
29
+ }
30
+ catch {
31
+ throw new Error('url must be a full https URL.');
32
+ }
33
+ if (target.protocol !== 'https:' || target.username || target.password || target.port) {
34
+ throw new Error('Only plain https URLs (no credentials, no port) can go through the key relay.');
35
+ }
36
+ const host = target.hostname.toLowerCase();
37
+ if (!/^(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*$/.test(host))
38
+ throw new Error('The relay needs a site name, not an address.');
39
+ const method = typeof args.method === 'string' ? args.method.toUpperCase() : 'GET';
40
+ if (!METHODS.includes(method))
41
+ throw new Error(`method must be one of ${METHODS.join(', ')}.`);
42
+ const headers = {};
43
+ for (const [name, value] of Object.entries((args.headers ?? {}))) {
44
+ if (typeof value !== 'string')
45
+ continue;
46
+ if (FORBIDDEN_HEADERS.has(name.toLowerCase()))
47
+ throw new Error(`The ${name} header can't be set.`);
48
+ headers[name] = value;
49
+ }
50
+ // Only the names this job was granted; the gateway checks again.
51
+ const used = new Set();
52
+ for (const text of [...Object.values(headers), target.search]) {
53
+ for (const match of text.matchAll(PLACEHOLDER))
54
+ used.add(match[1]);
55
+ }
56
+ if (used.size === 0)
57
+ throw new Error('Name a key with {{vault:NAME}} in a header or the query; the relay is only for calls that use one.');
58
+ const unknown = [...used].filter((name) => !relay.names.includes(name));
59
+ if (unknown.length)
60
+ throw new Error(`No key named ${unknown.join(', ')} is shared with this job. Available: ${names || 'none'}.`);
61
+ const body = typeof args.body === 'string' ? args.body : '';
62
+ if (Buffer.byteLength(body) > MAX_BODY_BYTES)
63
+ throw new Error('The body is too large for this tool (1 MB at most).');
64
+ if (['GET', 'DELETE'].includes(method) && body)
65
+ throw new Error(`${method} takes no body.`);
66
+ const response = await fetchFn(`${relay.url.replace(/\/+$/, '')}/${host}${target.pathname}${target.search}`, {
67
+ method,
68
+ headers: { ...headers, 'x-workser-key-grant': relay.grant },
69
+ ...(body ? { body } : {}),
70
+ redirect: 'manual',
71
+ signal: ctx.signal,
72
+ });
73
+ const text = await response.text();
74
+ const shown = text.length > MAX_OUTPUT_CHARS ? `${text.slice(0, MAX_OUTPUT_CHARS)}\n(Output truncated to ${MAX_OUTPUT_CHARS} characters.)` : text;
75
+ const location = response.headers.get('location');
76
+ return {
77
+ title: `${method} ${host}${target.pathname}`.slice(0, 200),
78
+ output: [`HTTP ${response.status}`, location ? `Location: ${location} (redirects are not followed)` : '', shown].filter(Boolean).join('\n\n'),
79
+ };
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,5 @@
1
+ import { type ToolSpec } from './types.js';
2
+ /** Upstream `glob`: up to 100 absolute paths, newest first, the same notes. */
3
+ export declare const globTool: ToolSpec;
4
+ /** Upstream `grep`: "Found N matches", grouped by file, ` Line N: text`. */
5
+ export declare const grepTool: ToolSpec;