@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,99 @@
1
+ import { vendored } from '../vendor.js';
2
+ import { absolute, str } from './types.js';
3
+ const LIMIT = 100;
4
+ const MAX_LINE_LENGTH = 2000;
5
+ function quote(value) {
6
+ return `'${value.replace(/'/g, `'\\''`)}'`;
7
+ }
8
+ /** Upstream `glob`: up to 100 absolute paths, newest first, the same notes. */
9
+ export const globTool = {
10
+ name: 'glob',
11
+ description: vendored('tool/glob.txt'),
12
+ parameters: {
13
+ type: 'object',
14
+ properties: {
15
+ pattern: { type: 'string', description: 'The glob pattern to match files against' },
16
+ path: {
17
+ type: 'string',
18
+ description: 'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',
19
+ },
20
+ },
21
+ required: ['pattern'],
22
+ },
23
+ async execute(args, ctx) {
24
+ const pattern = str(args.pattern, 'pattern');
25
+ const search = typeof args.path === 'string' && args.path ? absolute(ctx.root, args.path) : ctx.root;
26
+ const result = await ctx.place.exec(
27
+ // ripgrep, as upstream; plain `find` where a machine has no rg.
28
+ `if command -v rg >/dev/null 2>&1; then rg --files --hidden --glob '!.git' --glob ${quote(pattern)} --sortr modified . 2>/dev/null; ` +
29
+ `else find . -type f -not -path './.git/*' \\( -path ${quote(`./${pattern.replace(/^\.\//, '')}`)} -o -name ${quote(pattern)} \\) 2>/dev/null; fi | head -n ${LIMIT}`, { cwd: search, timeoutMs: 60_000, signal: ctx.signal });
30
+ const files = result.stdout.split('\n').map((one) => one.trim()).filter(Boolean).map((one) => absolute(search, one.replace(/^\.\//, '')));
31
+ const output = [];
32
+ if (files.length === 0)
33
+ output.push('No files found');
34
+ else {
35
+ output.push(...files);
36
+ if (files.length === LIMIT) {
37
+ output.push('');
38
+ output.push(`(Results are truncated: showing first ${LIMIT} results. Consider using a more specific path or pattern.)`);
39
+ }
40
+ }
41
+ return { title: search, output: output.join('\n') };
42
+ },
43
+ };
44
+ /** Upstream `grep`: "Found N matches", grouped by file, ` Line N: text`. */
45
+ export const grepTool = {
46
+ name: 'grep',
47
+ description: vendored('tool/grep.txt'),
48
+ parameters: {
49
+ type: 'object',
50
+ properties: {
51
+ pattern: { type: 'string', description: 'The regex pattern to search for in file contents' },
52
+ path: { type: 'string', description: 'The directory to search in. Defaults to the current working directory.' },
53
+ include: { type: 'string', description: 'File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")' },
54
+ },
55
+ required: ['pattern'],
56
+ },
57
+ async execute(args, ctx) {
58
+ const pattern = str(args.pattern, 'pattern');
59
+ const search = typeof args.path === 'string' && args.path ? absolute(ctx.root, args.path) : ctx.root;
60
+ const include = typeof args.include === 'string' && args.include ? ` --glob ${quote(args.include)}` : '';
61
+ const result = await ctx.place.exec(`if command -v rg >/dev/null 2>&1; then rg -n --no-heading --with-filename --hidden --glob '!.git'${include} -e ${quote(pattern)} . 2>/dev/null; ` +
62
+ `else grep -rnE --exclude-dir=.git${typeof args.include === 'string' && args.include ? ` --include=${quote(args.include)}` : ''} -e ${quote(pattern)} . 2>/dev/null; fi | head -n ${LIMIT + 1}`, { cwd: search, timeoutMs: 60_000, signal: ctx.signal });
63
+ const rows = result.stdout
64
+ .split('\n')
65
+ .filter(Boolean)
66
+ .map((line) => {
67
+ const match = /^(.*?):(\d+):(.*)$/.exec(line);
68
+ if (!match)
69
+ return null;
70
+ const text = match[3] ?? '';
71
+ return {
72
+ path: absolute(search, (match[1] ?? '').replace(/^\.\//, '')),
73
+ line: Number(match[2]),
74
+ text: text.length > MAX_LINE_LENGTH ? `${text.slice(0, MAX_LINE_LENGTH)}...` : text,
75
+ };
76
+ })
77
+ .filter((one) => one !== null);
78
+ if (rows.length === 0)
79
+ return { title: pattern, output: 'No files found' };
80
+ const truncated = rows.length > LIMIT;
81
+ const final = rows.slice(0, LIMIT);
82
+ const output = [`Found ${final.length} matches${truncated ? ' (more matches available)' : ''}`];
83
+ let current = '';
84
+ for (const match of final) {
85
+ if (current !== match.path) {
86
+ if (current !== '')
87
+ output.push('');
88
+ current = match.path;
89
+ output.push(`${match.path}:`);
90
+ }
91
+ output.push(` Line ${match.line}: ${match.text}`);
92
+ }
93
+ if (truncated) {
94
+ output.push('');
95
+ output.push('(Results truncated. Consider using a more specific path or pattern.)');
96
+ }
97
+ return { title: pattern, output: output.join('\n') };
98
+ },
99
+ };
@@ -0,0 +1,26 @@
1
+ import { type ToolSpec } from './types.js';
2
+ export declare function needsAsk(command: string): boolean;
3
+ /**
4
+ * A PERSISTENT SHELL over a Place (plan: "a shell that persists between
5
+ * commands"). Each `bash` call is still one `exec` — a Place has no PTY to
6
+ * hold open, and a sandbox may be paused between calls — but the shell's
7
+ * state rides between them: exported variables (`export`, `source
8
+ * .venv/bin/activate`) and the working folder (`cd`) are written to a small
9
+ * state folder on the machine when a command ends, and restored before the
10
+ * next one. Functions and aliases are not kept.
11
+ *
12
+ * A call with `workdir` runs there and leaves the kept folder alone, as
13
+ * upstream's `workdir` means "for this command".
14
+ */
15
+ export declare class ShellSession {
16
+ readonly id: string;
17
+ readonly dir: string;
18
+ constructor(id: string, tmp: string);
19
+ /** The command wrapped so the shell's state comes in before and goes out after. */
20
+ wrap(command: string, root: string, workdir: string | null): string;
21
+ }
22
+ export declare function bashTool(input: {
23
+ os: string;
24
+ tmp: string;
25
+ shell?: ShellSession;
26
+ }): ToolSpec;
@@ -0,0 +1,123 @@
1
+ import { bashDescription, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_BYTES, SHELL_MAX_LINES } from '../prompts.js';
2
+ import { absolute, str } from './types.js';
3
+ /**
4
+ * Commands that ask the owner first. The same short list the runner's
5
+ * OpenCode config asks on (workser-runner opencode.ts), so a job behaves the
6
+ * same in both modes. Everything else runs, as upstream's default agent does.
7
+ */
8
+ const ASK_FIRST = [
9
+ /(^|[;&|]\s*)sudo\s/,
10
+ /\brm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\b/,
11
+ /\bgit\s+push\b/,
12
+ /\bgit\s+reset\s+--hard\b/,
13
+ ];
14
+ export function needsAsk(command) {
15
+ return ASK_FIRST.some((pattern) => pattern.test(command));
16
+ }
17
+ function tail(text) {
18
+ let lines = text.split('\n');
19
+ let cut = false;
20
+ if (lines.length > SHELL_MAX_LINES) {
21
+ lines = lines.slice(-SHELL_MAX_LINES);
22
+ cut = true;
23
+ }
24
+ let out = lines.join('\n');
25
+ if (Buffer.byteLength(out) > SHELL_MAX_BYTES) {
26
+ out = Buffer.from(out).subarray(-SHELL_MAX_BYTES).toString('utf8');
27
+ cut = true;
28
+ }
29
+ return { text: out, cut };
30
+ }
31
+ /**
32
+ * A PERSISTENT SHELL over a Place (plan: "a shell that persists between
33
+ * commands"). Each `bash` call is still one `exec` — a Place has no PTY to
34
+ * hold open, and a sandbox may be paused between calls — but the shell's
35
+ * state rides between them: exported variables (`export`, `source
36
+ * .venv/bin/activate`) and the working folder (`cd`) are written to a small
37
+ * state folder on the machine when a command ends, and restored before the
38
+ * next one. Functions and aliases are not kept.
39
+ *
40
+ * A call with `workdir` runs there and leaves the kept folder alone, as
41
+ * upstream's `workdir` means "for this command".
42
+ */
43
+ export class ShellSession {
44
+ id;
45
+ dir;
46
+ constructor(id, tmp) {
47
+ this.id = id;
48
+ this.dir = `${tmp.replace(/\/+$/, '')}/workser-shell-${id.replace(/[^A-Za-z0-9_-]/g, '')}`;
49
+ }
50
+ /** The command wrapped so the shell's state comes in before and goes out after. */
51
+ wrap(command, root, workdir) {
52
+ const dir = quote(this.dir);
53
+ const save = [
54
+ workdir ? '' : `pwd > ${dir}/cwd`,
55
+ // Everything exported, minus what bash sets itself.
56
+ `export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)(=|$)' > ${dir}/env.tmp 2>/dev/null && mv -f ${dir}/env.tmp ${dir}/env`,
57
+ ]
58
+ .filter(Boolean)
59
+ .join('; ');
60
+ return [
61
+ `mkdir -p ${dir}`,
62
+ `[ -f ${dir}/env ] && . ${dir}/env >/dev/null 2>&1`,
63
+ workdir
64
+ ? `cd ${quote(workdir)}`
65
+ : `cd "$(cat ${dir}/cwd 2>/dev/null || echo ${quote(root)})" 2>/dev/null || cd ${quote(root)}`,
66
+ // An EXIT trap, so `exit 3` in the command still saves the state.
67
+ `trap '__ws_code=$?; ${save.replace(/'/g, `'\\''`)}; exit $__ws_code' EXIT`,
68
+ command,
69
+ ].join('\n');
70
+ }
71
+ }
72
+ function quote(value) {
73
+ return `'${value.replace(/'/g, `'\\''`)}'`;
74
+ }
75
+ export function bashTool(input) {
76
+ return {
77
+ name: 'bash',
78
+ description: bashDescription(input),
79
+ parameters: {
80
+ type: 'object',
81
+ properties: {
82
+ command: { type: 'string', description: 'The command to execute' },
83
+ timeout: { type: 'integer', exclusiveMinimum: 0, description: 'Optional timeout in milliseconds' },
84
+ workdir: {
85
+ type: 'string',
86
+ description: "The working directory to run the command in. Defaults to the current directory. Use this instead of 'cd' commands.",
87
+ },
88
+ description: {
89
+ type: 'string',
90
+ description: 'Clear, concise description of what this command does in 5-10 words.',
91
+ },
92
+ },
93
+ required: ['command'],
94
+ },
95
+ async execute(args, ctx) {
96
+ const command = str(args.command, 'command');
97
+ const timeout = typeof args.timeout === 'number' && args.timeout > 0 ? args.timeout : SHELL_DEFAULT_TIMEOUT_MS;
98
+ const workdir = typeof args.workdir === 'string' && args.workdir ? absolute(ctx.root, args.workdir) : null;
99
+ const cwd = workdir ?? ctx.root;
100
+ if (needsAsk(command)) {
101
+ await ctx.ask({ permission: 'bash', title: `Run: ${command.slice(0, 200)}`, detail: command, patterns: [command] });
102
+ }
103
+ const shell = input.shell;
104
+ const result = await ctx.place.exec(shell ? shell.wrap(command, ctx.root, workdir) : command, {
105
+ cwd,
106
+ timeoutMs: timeout,
107
+ signal: ctx.signal,
108
+ });
109
+ const combined = [result.stdout, result.stderr].filter(Boolean).join(result.stdout && result.stderr ? '\n' : '');
110
+ const { text, cut } = tail(combined);
111
+ let output = text;
112
+ if (cut)
113
+ output = `(Output truncated to the last ${SHELL_MAX_LINES} lines / ${SHELL_MAX_BYTES} bytes.)\n${output}`;
114
+ if (result.timedOut) {
115
+ output += `\n\nshell tool terminated command after exceeding timeout ${timeout} ms. If this command is expected to take longer and is not waiting for interactive input, retry with a larger timeout value in milliseconds.`;
116
+ }
117
+ else if (result.exitCode !== 0) {
118
+ output += `\n\nExit code: ${result.exitCode}`;
119
+ }
120
+ return { title: String(args.description ?? command).slice(0, 200), output: output || '(no output)' };
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,49 @@
1
+ import type { Place } from '@workser/runtime';
2
+ export interface ToolContext {
3
+ place: Place;
4
+ root: string;
5
+ /** Ask the owner; resolves when allowed, rejects with PermissionDenied when not. */
6
+ ask(request: {
7
+ permission: string;
8
+ title: string;
9
+ detail: string;
10
+ patterns: string[];
11
+ }): Promise<void>;
12
+ /** Files the model has read this session (write/edit of an existing file needs one). */
13
+ read: Set<string>;
14
+ todos: Todo[];
15
+ signal: AbortSignal;
16
+ }
17
+ export interface Todo {
18
+ content: string;
19
+ status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
20
+ priority?: 'high' | 'medium' | 'low';
21
+ id?: string;
22
+ }
23
+ export interface ToolResult {
24
+ title: string;
25
+ output: string;
26
+ /**
27
+ * What the job record and the saved state keep INSTEAD of `output`, for a result that holds an
28
+ * outside message (a sign-in code, a link). The model still gets `output` for its next step; the
29
+ * `step.completed` event and a checkpoint carry this line only.
30
+ */
31
+ recorded?: string;
32
+ /** Files this call changed, for `file.changed`. */
33
+ changed?: Array<{
34
+ path: string;
35
+ change: 'added' | 'modified' | 'deleted';
36
+ }>;
37
+ }
38
+ export interface ToolSpec {
39
+ name: string;
40
+ description: string;
41
+ /** JSON Schema for the arguments — the same fields and descriptions as upstream. */
42
+ parameters: Record<string, unknown>;
43
+ execute(args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
44
+ }
45
+ export declare class PermissionDenied extends Error {
46
+ constructor(message?: string);
47
+ }
48
+ export declare function absolute(root: string, path: string): string;
49
+ export declare function str(value: unknown, name: string): string;
@@ -0,0 +1,16 @@
1
+ export class PermissionDenied extends Error {
2
+ constructor(message = 'The owner did not allow this.') {
3
+ super(message);
4
+ this.name = 'PermissionDenied';
5
+ }
6
+ }
7
+ export function absolute(root, path) {
8
+ if (path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path))
9
+ return path;
10
+ return `${root.replace(/\/+$/, '')}/${path}`;
11
+ }
12
+ export function str(value, name) {
13
+ if (typeof value !== 'string')
14
+ throw new Error(`${name} is required`);
15
+ return value;
16
+ }
@@ -0,0 +1,39 @@
1
+ import type { ToolSpec } from './types.js';
2
+ /** The slice of the SDK's RunnerClient this uses. */
3
+ export interface ToolsClient {
4
+ listTools(): Promise<{
5
+ tools: Array<{
6
+ name: string;
7
+ source?: string;
8
+ description?: string;
9
+ side_effect?: boolean;
10
+ spends?: boolean;
11
+ }>;
12
+ ask_before_paying_usd?: number;
13
+ }>;
14
+ callTool(name: string, call?: {
15
+ arguments?: Record<string, unknown>;
16
+ approval_id?: string;
17
+ amount_usd?: number;
18
+ spend_approval_id?: string;
19
+ }): Promise<{
20
+ status: 'ok' | 'approval_required';
21
+ result?: unknown;
22
+ approval_id?: string;
23
+ kind?: string;
24
+ message?: string;
25
+ private_output?: boolean;
26
+ }>;
27
+ }
28
+ /**
29
+ * `workser tool list|call` for a loop that runs outside the machine: the
30
+ * run's tools (Workser's own and the project's connected apps) through the
31
+ * run's client, which holds the run token in the loop's process, not on the
32
+ * machine. In the runner's mode the agent's commands run `workser tool` against
33
+ * the runner's broker; here there is no broker on the machine to reach.
34
+ *
35
+ * A side effect or a big spend comes back `approval_required` with an approval
36
+ * id (core-api has already asked the owner). The model calls again with that
37
+ * id once the owner has said yes; until then core-api answers the same.
38
+ */
39
+ export declare function workserTool(client: ToolsClient): ToolSpec;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `workser tool list|call` for a loop that runs outside the machine: the
3
+ * run's tools (Workser's own and the project's connected apps) through the
4
+ * run's client, which holds the run token in the loop's process, not on the
5
+ * machine. In the runner's mode the agent's commands run `workser tool` against
6
+ * the runner's broker; here there is no broker on the machine to reach.
7
+ *
8
+ * A side effect or a big spend comes back `approval_required` with an approval
9
+ * id (core-api has already asked the owner). The model calls again with that
10
+ * id once the owner has said yes; until then core-api answers the same.
11
+ */
12
+ export function workserTool(client) {
13
+ return {
14
+ name: 'workser_tool',
15
+ description: "Use Workser's tools and the project's connected apps. action 'list' shows the tools; action 'call' runs one by name. " +
16
+ "A tool that changes something outside this job, or spends money, needs the owner's yes first: you get approval_required " +
17
+ 'and an approval_id; call again with approval_id (and spend_approval_id for a spend over the limit) after they approve.',
18
+ parameters: {
19
+ type: 'object',
20
+ properties: {
21
+ action: { type: 'string', enum: ['list', 'call'] },
22
+ name: { type: 'string', description: "The tool's name (for call)" },
23
+ arguments: { type: 'object', description: "The tool's arguments (for call)" },
24
+ approval_id: { type: 'string' },
25
+ amount_usd: { type: 'number', description: 'How much a spending tool will spend, in dollars' },
26
+ spend_approval_id: { type: 'string' },
27
+ },
28
+ required: ['action'],
29
+ },
30
+ async execute(args) {
31
+ if (args.action === 'list') {
32
+ const list = await client.listTools();
33
+ return { title: `${list.tools.length} tools`, output: JSON.stringify(list, null, 2).slice(0, 50_000) };
34
+ }
35
+ if (args.action !== 'call' || typeof args.name !== 'string' || !args.name)
36
+ throw new Error("action is 'list' or 'call' (call needs a name).");
37
+ const out = await client.callTool(args.name, {
38
+ ...(args.arguments && typeof args.arguments === 'object' ? { arguments: args.arguments } : {}),
39
+ ...(typeof args.approval_id === 'string' ? { approval_id: args.approval_id } : {}),
40
+ ...(typeof args.amount_usd === 'number' ? { amount_usd: args.amount_usd } : {}),
41
+ ...(typeof args.spend_approval_id === 'string' ? { spend_approval_id: args.spend_approval_id } : {}),
42
+ });
43
+ return {
44
+ title: `${args.name}: ${out.status}`,
45
+ output: JSON.stringify(out, null, 2).slice(0, 50_000),
46
+ // A result with an outside message in it (a sign-in code): the model sees it, the record does not keep it.
47
+ ...(out.private_output ? { recorded: JSON.stringify({ status: out.status, tool: args.name, note: 'The message contents are not kept in the job record.' }) } : {}),
48
+ };
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,4 @@
1
+ /** OpenCode's version this engine speaks. Update by re-vendoring, never by editing. */
2
+ export declare const OPENCODE_VERSION = "1.18.23";
3
+ /** A vendored upstream text file (a prompt or a tool description), verbatim. */
4
+ export declare function vendored(relative: string): string;
@@ -0,0 +1,17 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /** OpenCode's version this engine speaks. Update by re-vendoring, never by editing. */
5
+ export const OPENCODE_VERSION = '1.18.23';
6
+ // dist/src/vendor.js → package root → vendor/opencode-<v>/
7
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'vendor', `opencode-${OPENCODE_VERSION}`);
8
+ const cache = new Map();
9
+ /** A vendored upstream text file (a prompt or a tool description), verbatim. */
10
+ export function vendored(relative) {
11
+ let text = cache.get(relative);
12
+ if (text === undefined) {
13
+ text = readFileSync(join(ROOT, relative), 'utf8');
14
+ cache.set(relative, text);
15
+ }
16
+ return text;
17
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@workser/engine",
3
+ "version": "0.1.0",
4
+ "description": "Workser's coding engine for the 'loop in our service' mode: OpenCode's agent contract (its prompts, tool schemas and edit semantics, vendored from v1.18.23) running on Node, with every file and shell action going through a Place \u2014 so the machine can be a remote sandbox and no model key is ever on it.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/src/index.js",
8
+ "types": "./dist/src/index.d.ts",
9
+ "files": [
10
+ "dist/src",
11
+ "vendor",
12
+ "NOTICE",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "typecheck": "tsc -p tsconfig.json --noEmit",
21
+ "test": "rm -rf dist && tsc -p tsconfig.json && node --test dist/test/*.test.js",
22
+ "prepublishOnly": "rm -rf dist && NODE_OPTIONS=--max-old-space-size=3072 tsc -p tsconfig.json"
23
+ },
24
+ "dependencies": {
25
+ "@workser/runtime": "^0.1.0"
26
+ },
27
+ "peerDependencies": {
28
+ "e2b": ">=1"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "e2b": {
32
+ "optional": true
33
+ }
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^20.19.43",
37
+ "typescript": "^5.9.3"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }
@@ -0,0 +1 @@
1
+ ef2880f379129aa048be9e9353e30aa168d42c17
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 opencode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,105 @@
1
+ You are OpenCode, the best coding agent on the planet.
2
+
3
+ You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
4
+
5
+ IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
6
+
7
+ If the user asks for help or wants to give feedback inform them of the following:
8
+ - ctrl+p to list available actions
9
+ - To give feedback, users should report the issue at
10
+ https://github.com/anomalyco/opencode
11
+
12
+ When the user directly asks about OpenCode (eg. "can OpenCode do...", "does OpenCode have..."), or asks in second person (eg. "are you able...", "can you do..."), or asks how to use a specific OpenCode feature (eg. implement a hook, write a slash command, or install an MCP server), use the WebFetch tool to gather information to answer the question from OpenCode docs. The list of available docs is available at https://opencode.ai/docs
13
+
14
+ # Tone and style
15
+ - Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
16
+ - Your output will be displayed on a command line interface. Your responses should be short and concise. You can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
17
+ - Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
18
+ - NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
19
+
20
+ # Professional objectivity
21
+ Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if OpenCode honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs.
22
+
23
+ # Task Management
24
+ You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
25
+ These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
26
+
27
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
28
+
29
+ Examples:
30
+
31
+ <example>
32
+ user: Run the build and fix any type errors
33
+ assistant: I'm going to use the TodoWrite tool to write the following items to the todo list:
34
+ - Run the build
35
+ - Fix any type errors
36
+
37
+ I'm now going to run the build using Bash.
38
+
39
+ Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list.
40
+
41
+ marking the first todo as in_progress
42
+
43
+ Let me start working on the first item...
44
+
45
+ The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
46
+ ..
47
+ ..
48
+ </example>
49
+ In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
50
+
51
+ <example>
52
+ user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
53
+ assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task.
54
+ Adding the following todos to the todo list:
55
+ 1. Research existing metrics tracking in the codebase
56
+ 2. Design the metrics collection system
57
+ 3. Implement core metrics tracking functionality
58
+ 4. Create export functionality for different formats
59
+
60
+ Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
61
+
62
+ I'm going to search for any existing metrics or telemetry code in the project.
63
+
64
+ I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
65
+
66
+ [Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
67
+ </example>
68
+
69
+
70
+ # Doing tasks
71
+ The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
72
+ -
73
+ - Use the TodoWrite tool to plan the task if required
74
+
75
+ - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
76
+
77
+
78
+ # Tool usage policy
79
+ - When doing file search, prefer to use the Task tool in order to reduce context usage.
80
+ - You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
81
+
82
+ - When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
83
+ - You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
84
+ - If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple Task tool calls.
85
+ - Use specialized tools instead of bash commands when possible, as this provides a better user experience. For file operations, use dedicated tools: Read for reading files instead of cat/head/tail, Edit for editing instead of sed/awk, and Write for creating files instead of cat with heredoc or echo redirection. Reserve bash tools exclusively for actual system commands and terminal operations that require shell execution. NEVER use bash echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
86
+ - VERY IMPORTANT: When exploring the codebase to gather context or to answer a question that is not a needle query for a specific file/class/function, it is CRITICAL that you use the Task tool instead of running search commands directly.
87
+ <example>
88
+ user: Where are errors from the client handled?
89
+ assistant: [Uses the Task tool to find the files that handle client errors instead of using Glob or Grep directly]
90
+ </example>
91
+ <example>
92
+ user: What is the codebase structure?
93
+ assistant: [Uses the Task tool]
94
+ </example>
95
+
96
+ IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
97
+
98
+ # Code References
99
+
100
+ When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
101
+
102
+ <example>
103
+ user: Where are errors from the client handled?
104
+ assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
105
+ </example>