@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,153 @@
1
+ export class ModelError extends Error {
2
+ status;
3
+ constructor(message, status) {
4
+ super(message);
5
+ this.status = status;
6
+ this.name = 'ModelError';
7
+ }
8
+ }
9
+ export async function chat(input) {
10
+ const doFetch = input.fetch ?? fetch;
11
+ const url = `${input.baseUrl.replace(/\/+$/, '')}/chat/completions`;
12
+ const stream = Boolean(input.onDelta);
13
+ let lastError;
14
+ for (let attempt = 0; attempt < 3; attempt++) {
15
+ let res;
16
+ try {
17
+ res = await doFetch(url, {
18
+ method: 'POST',
19
+ headers: { authorization: `Bearer ${input.key}`, 'content-type': 'application/json' },
20
+ body: JSON.stringify({
21
+ model: input.model,
22
+ messages: input.messages,
23
+ ...(input.tools.length ? { tools: input.tools, tool_choice: 'auto' } : {}),
24
+ usage: { include: true },
25
+ ...(stream ? { stream: true, stream_options: { include_usage: true } } : {}),
26
+ }),
27
+ ...(input.signal ? { signal: input.signal } : {}),
28
+ });
29
+ }
30
+ catch (error) {
31
+ if (error?.name === 'AbortError')
32
+ throw error;
33
+ lastError = error;
34
+ await new Promise((r) => setTimeout(r, 500 * (attempt + 1)));
35
+ continue;
36
+ }
37
+ if (res.status >= 500 || res.status === 429) {
38
+ await res.text().catch(() => '');
39
+ lastError = new ModelError(`The model route answered ${res.status}.`, res.status);
40
+ await new Promise((r) => setTimeout(r, 500 * (attempt + 1)));
41
+ continue;
42
+ }
43
+ const type = res.headers.get('content-type') ?? '';
44
+ if (res.ok && stream && type.includes('text/event-stream') && res.body) {
45
+ // Once text has reached the owner, a retry would say it twice: a
46
+ // stream that breaks midway is an error, not a retry.
47
+ return readStream(res.body, input.onDelta, res.status);
48
+ }
49
+ const text = await res.text();
50
+ let body = null;
51
+ try {
52
+ body = text ? JSON.parse(text) : null;
53
+ }
54
+ catch {
55
+ body = null;
56
+ }
57
+ if (!res.ok) {
58
+ throw new ModelError(body?.error?.message ?? `The model route answered ${res.status}.`, res.status);
59
+ }
60
+ const choice = body?.choices?.[0];
61
+ if (!choice?.message)
62
+ throw new ModelError('The model answered with no message.', res.status);
63
+ if (choice.message.content && input.onDelta)
64
+ input.onDelta(choice.message.content);
65
+ return {
66
+ message: {
67
+ role: 'assistant',
68
+ content: choice.message.content ?? null,
69
+ ...(Array.isArray(choice.message.tool_calls) && choice.message.tool_calls.length
70
+ ? { tool_calls: choice.message.tool_calls }
71
+ : {}),
72
+ },
73
+ finishReason: choice.finish_reason ?? null,
74
+ ...(body.usage ? { usage: body.usage } : {}),
75
+ };
76
+ }
77
+ throw lastError instanceof Error ? lastError : new ModelError('The model route could not be reached.', 0);
78
+ }
79
+ /** An OpenAI-compatible SSE stream, put back together into one message. */
80
+ async function readStream(body, onDelta, status) {
81
+ const reader = body.getReader();
82
+ const decoder = new TextDecoder();
83
+ let buffer = '';
84
+ let content = '';
85
+ let finishReason = null;
86
+ let usage;
87
+ const calls = [];
88
+ let sawChoice = false;
89
+ const handle = (data) => {
90
+ if (data === '[DONE]')
91
+ return;
92
+ let chunk;
93
+ try {
94
+ chunk = JSON.parse(data);
95
+ }
96
+ catch {
97
+ return;
98
+ }
99
+ if (chunk?.error)
100
+ throw new ModelError(chunk.error.message ?? 'The model stream failed.', status);
101
+ if (chunk?.usage)
102
+ usage = chunk.usage;
103
+ const choice = chunk?.choices?.[0];
104
+ if (!choice)
105
+ return;
106
+ sawChoice = true;
107
+ if (choice.finish_reason)
108
+ finishReason = choice.finish_reason;
109
+ const delta = choice.delta ?? {};
110
+ if (typeof delta.content === 'string' && delta.content) {
111
+ content += delta.content;
112
+ onDelta(delta.content);
113
+ }
114
+ for (const part of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
115
+ const index = typeof part.index === 'number' ? part.index : calls.length;
116
+ const call = (calls[index] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
117
+ if (part.id)
118
+ call.id = part.id;
119
+ if (part.function?.name)
120
+ call.function.name += part.function.name;
121
+ if (part.function?.arguments)
122
+ call.function.arguments += part.function.arguments;
123
+ }
124
+ };
125
+ for (;;) {
126
+ const { done, value } = await reader.read();
127
+ if (done)
128
+ break;
129
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n?/g, '\n');
130
+ let cut;
131
+ while ((cut = buffer.indexOf('\n\n')) >= 0) {
132
+ const block = buffer.slice(0, cut);
133
+ buffer = buffer.slice(cut + 2);
134
+ const data = block
135
+ .split('\n')
136
+ .filter((line) => line.startsWith('data:'))
137
+ .map((line) => line.slice(5).trim())
138
+ .join('\n');
139
+ if (data)
140
+ handle(data);
141
+ }
142
+ }
143
+ if (buffer.trim().startsWith('data:'))
144
+ handle(buffer.trim().slice(5).trim());
145
+ if (!sawChoice)
146
+ throw new ModelError('The model answered with no message.', status);
147
+ const toolCalls = calls.filter(Boolean).map((call, i) => ({ ...call, id: call.id || `call_${i}` }));
148
+ return {
149
+ message: { role: 'assistant', content: content || null, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) },
150
+ finishReason,
151
+ ...(usage ? { usage } : {}),
152
+ };
153
+ }
@@ -0,0 +1,76 @@
1
+ import type { ExecOptions, ExecResult, GitStatus, Place, PlaceEntry, PlaceInfo, RunPlace } from '@workser/runtime';
2
+ /**
3
+ * The parts of an `e2b` Sandbox this Place uses. Structural, so the engine
4
+ * builds and tests without the `e2b` package; production passes a real
5
+ * `Sandbox` (see `connectE2BPlace`).
6
+ */
7
+ export interface E2BSandboxLike {
8
+ sandboxId: string;
9
+ commands: {
10
+ run(cmd: string, opts?: {
11
+ cwd?: string;
12
+ envs?: Record<string, string>;
13
+ timeoutMs?: number;
14
+ onStdout?: (data: string) => void;
15
+ onStderr?: (data: string) => void;
16
+ }): Promise<{
17
+ exitCode: number;
18
+ stdout: string;
19
+ stderr: string;
20
+ }>;
21
+ };
22
+ files: {
23
+ read(path: string, opts?: {
24
+ format?: 'bytes' | 'text';
25
+ }): Promise<Uint8Array | string>;
26
+ write(path: string, data: string | ArrayBuffer | Uint8Array): Promise<unknown>;
27
+ list(path: string): Promise<Array<{
28
+ name: string;
29
+ path: string;
30
+ type?: string;
31
+ size?: number;
32
+ }>>;
33
+ };
34
+ getHost?(port: number): string;
35
+ pause?(): Promise<unknown>;
36
+ }
37
+ /**
38
+ * A remote E2B machine (a project sandbox or the project's cloud computer) as
39
+ * a Place — the "loop in our service" mode. The engine runs in our worker; the
40
+ * files and commands are on the machine; the model key never goes there.
41
+ */
42
+ export declare class E2BPlace implements Place {
43
+ private readonly sandbox;
44
+ readonly root: string;
45
+ private readonly place;
46
+ private readonly reconnect?;
47
+ constructor(sandbox: E2BSandboxLike, root: string, place?: RunPlace, reconnect?: (() => Promise<E2BSandboxLike>) | undefined);
48
+ private inside;
49
+ info(): Promise<PlaceInfo>;
50
+ exec(command: string, options?: ExecOptions): Promise<ExecResult>;
51
+ readFile(path: string): Promise<Uint8Array>;
52
+ writeFile(path: string, content: Uint8Array | string): Promise<void>;
53
+ list(path: string): Promise<PlaceEntry[]>;
54
+ gitStatus(cwd?: string): Promise<GitStatus>;
55
+ gitDiff(options?: {
56
+ cwd?: string;
57
+ base?: string;
58
+ paths?: string[];
59
+ }): Promise<string>;
60
+ previewUrl(port: number): Promise<string>;
61
+ pause(): Promise<void>;
62
+ resume(): Promise<void>;
63
+ snapshot(): Promise<{
64
+ snapshot_id: string;
65
+ }>;
66
+ }
67
+ /**
68
+ * Connect to a running (or paused) E2B sandbox by id. Needs the `e2b`
69
+ * package and an E2B key in OUR worker's environment — never on the machine.
70
+ */
71
+ export declare function connectE2BPlace(input: {
72
+ sandboxId: string;
73
+ root: string;
74
+ place?: RunPlace;
75
+ apiKey?: string;
76
+ }): Promise<E2BPlace>;
@@ -0,0 +1,114 @@
1
+ import { parseGitStatus } from './local.js';
2
+ /**
3
+ * A remote E2B machine (a project sandbox or the project's cloud computer) as
4
+ * a Place — the "loop in our service" mode. The engine runs in our worker; the
5
+ * files and commands are on the machine; the model key never goes there.
6
+ */
7
+ export class E2BPlace {
8
+ sandbox;
9
+ root;
10
+ place;
11
+ reconnect;
12
+ constructor(sandbox, root, place = 'sandbox', reconnect) {
13
+ this.sandbox = sandbox;
14
+ this.root = root;
15
+ this.place = place;
16
+ this.reconnect = reconnect;
17
+ }
18
+ inside(path) {
19
+ const full = path.startsWith('/') ? normalize(path) : normalize(`${this.root}/${path}`);
20
+ if (full !== this.root && !full.startsWith(`${this.root}/`)) {
21
+ throw new Error(`Path is outside the workspace: ${path}`);
22
+ }
23
+ return full;
24
+ }
25
+ async info() {
26
+ return { place: this.place, root: this.root, os: 'linux', tools: ['git', 'rg'], canPause: true, canSnapshot: false };
27
+ }
28
+ async exec(command, options = {}) {
29
+ const started = Date.now();
30
+ try {
31
+ const result = await this.sandbox.commands.run(command, {
32
+ cwd: options.cwd ? this.inside(options.cwd) : this.root,
33
+ ...(options.env ? { envs: options.env } : {}),
34
+ ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),
35
+ onStdout: (text) => options.onOutput?.({ stream: 'stdout', text }),
36
+ onStderr: (text) => options.onOutput?.({ stream: 'stderr', text }),
37
+ });
38
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr, timedOut: false, durationMs: Date.now() - started };
39
+ }
40
+ catch (error) {
41
+ // The e2b SDK throws for a non-zero exit (CommandExitError carries the
42
+ // result) and for a timeout.
43
+ const e = error;
44
+ const timedOut = /timeout/i.test(`${e.name ?? ''} ${e.message ?? ''}`);
45
+ return {
46
+ exitCode: typeof e.exitCode === 'number' ? e.exitCode : -1,
47
+ stdout: e.stdout ?? '',
48
+ stderr: e.stderr ?? e.message ?? String(error),
49
+ timedOut,
50
+ durationMs: Date.now() - started,
51
+ };
52
+ }
53
+ }
54
+ async readFile(path) {
55
+ const data = await this.sandbox.files.read(this.inside(path), { format: 'bytes' });
56
+ return typeof data === 'string' ? new TextEncoder().encode(data) : data;
57
+ }
58
+ async writeFile(path, content) {
59
+ await this.sandbox.files.write(this.inside(path), content);
60
+ }
61
+ async list(path) {
62
+ const entries = await this.sandbox.files.list(this.inside(path));
63
+ return entries.map((one) => ({
64
+ name: one.name,
65
+ path: one.path,
66
+ type: one.type === 'dir' ? 'dir' : 'file',
67
+ ...(typeof one.size === 'number' ? { size: one.size } : {}),
68
+ }));
69
+ }
70
+ async gitStatus(cwd) {
71
+ return parseGitStatus((await this.exec('git status --porcelain=v1 -b', cwd ? { cwd } : {})).stdout);
72
+ }
73
+ async gitDiff(options = {}) {
74
+ const paths = (options.paths ?? []).map((one) => `'${one.replace(/'/g, `'\\''`)}'`).join(' ');
75
+ return (await this.exec(`git diff ${options.base ?? ''} -- ${paths}`.trim(), options.cwd ? { cwd: options.cwd } : {})).stdout;
76
+ }
77
+ async previewUrl(port) {
78
+ if (!this.sandbox.getHost)
79
+ throw new Error('This machine has no preview host.');
80
+ return `https://${this.sandbox.getHost(port)}`;
81
+ }
82
+ async pause() {
83
+ await this.sandbox.pause?.();
84
+ }
85
+ async resume() {
86
+ if (this.reconnect)
87
+ Object.assign(this, { sandbox: await this.reconnect() });
88
+ }
89
+ async snapshot() {
90
+ throw new Error('Snapshots are taken by the cloud computer service, not the engine.');
91
+ }
92
+ }
93
+ /**
94
+ * Connect to a running (or paused) E2B sandbox by id. Needs the `e2b`
95
+ * package and an E2B key in OUR worker's environment — never on the machine.
96
+ */
97
+ export async function connectE2BPlace(input) {
98
+ const moduleName = 'e2b';
99
+ const { Sandbox } = (await import(moduleName));
100
+ const connect = () => Sandbox.connect(input.sandboxId, input.apiKey ? { apiKey: input.apiKey } : {});
101
+ return new E2BPlace(await connect(), input.root, input.place ?? 'sandbox', connect);
102
+ }
103
+ function normalize(path) {
104
+ const out = [];
105
+ for (const part of path.split('/')) {
106
+ if (!part || part === '.')
107
+ continue;
108
+ if (part === '..')
109
+ out.pop();
110
+ else
111
+ out.push(part);
112
+ }
113
+ return `/${out.join('/')}`;
114
+ }
@@ -0,0 +1,3 @@
1
+ import type { Place } from '@workser/runtime';
2
+ /** The Place with extra variables on every command (names and ids, never a key). */
3
+ export declare function withCommandEnv(place: Place, env: Record<string, string>): Place;
@@ -0,0 +1,14 @@
1
+ /** The Place with extra variables on every command (names and ids, never a key). */
2
+ export function withCommandEnv(place, env) {
3
+ if (Object.keys(env).length === 0)
4
+ return place;
5
+ return new Proxy(place, {
6
+ get(target, prop, receiver) {
7
+ if (prop === 'exec') {
8
+ return (command, options = {}) => target.exec(command, { ...options, env: { ...env, ...(options.env ?? {}) } });
9
+ }
10
+ const value = Reflect.get(target, prop, receiver);
11
+ return typeof value === 'function' ? value.bind(target) : value;
12
+ },
13
+ });
14
+ }
@@ -0,0 +1,33 @@
1
+ import type { ExecOptions, ExecResult, GitStatus, Place, PlaceEntry, PlaceInfo } from '@workser/runtime';
2
+ /**
3
+ * A folder on this machine as a Place. For tests and for running the engine
4
+ * next to the files; the production shape is `E2BPlace` (the loop in our
5
+ * service, the files on a remote machine).
6
+ *
7
+ * Every path is resolved inside `root`: a path that would leave it is refused,
8
+ * whatever the model asked for.
9
+ */
10
+ export declare class LocalPlace implements Place {
11
+ private readonly env;
12
+ readonly root: string;
13
+ constructor(root: string, env?: Record<string, string>);
14
+ private inside;
15
+ info(): Promise<PlaceInfo>;
16
+ exec(command: string, options?: ExecOptions): Promise<ExecResult>;
17
+ readFile(path: string): Promise<Uint8Array>;
18
+ writeFile(path: string, content: Uint8Array | string): Promise<void>;
19
+ list(path: string): Promise<PlaceEntry[]>;
20
+ gitStatus(cwd?: string): Promise<GitStatus>;
21
+ gitDiff(options?: {
22
+ cwd?: string;
23
+ base?: string;
24
+ paths?: string[];
25
+ }): Promise<string>;
26
+ previewUrl(port: number): Promise<string>;
27
+ pause(): Promise<void>;
28
+ resume(): Promise<void>;
29
+ snapshot(): Promise<{
30
+ snapshot_id: string;
31
+ }>;
32
+ }
33
+ export declare function parseGitStatus(text: string): GitStatus;
@@ -0,0 +1,138 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
+ /**
5
+ * A folder on this machine as a Place. For tests and for running the engine
6
+ * next to the files; the production shape is `E2BPlace` (the loop in our
7
+ * service, the files on a remote machine).
8
+ *
9
+ * Every path is resolved inside `root`: a path that would leave it is refused,
10
+ * whatever the model asked for.
11
+ */
12
+ export class LocalPlace {
13
+ env;
14
+ root;
15
+ constructor(root, env = {}) {
16
+ this.env = env;
17
+ this.root = resolve(root);
18
+ }
19
+ inside(path) {
20
+ const full = isAbsolute(path) ? resolve(path) : resolve(this.root, path);
21
+ const rel = relative(this.root, full);
22
+ if (rel.startsWith('..') || isAbsolute(rel)) {
23
+ throw new Error(`Path is outside the workspace: ${path}`);
24
+ }
25
+ return full;
26
+ }
27
+ async info() {
28
+ return {
29
+ place: 'sandbox',
30
+ root: this.root,
31
+ os: process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'darwin' : 'linux',
32
+ tools: ['git', 'rg'],
33
+ canPause: false,
34
+ canSnapshot: false,
35
+ };
36
+ }
37
+ exec(command, options = {}) {
38
+ const started = Date.now();
39
+ const cwd = options.cwd ? this.inside(options.cwd) : this.root;
40
+ return new Promise((done) => {
41
+ const child = spawn('bash', ['-c', command], {
42
+ cwd,
43
+ env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '', ...this.env, ...(options.env ?? {}) },
44
+ stdio: ['pipe', 'pipe', 'pipe'],
45
+ });
46
+ let stdout = '';
47
+ let stderr = '';
48
+ let timedOut = false;
49
+ const timer = options.timeoutMs
50
+ ? setTimeout(() => {
51
+ timedOut = true;
52
+ child.kill('SIGKILL');
53
+ }, options.timeoutMs)
54
+ : null;
55
+ const onAbort = () => child.kill('SIGKILL');
56
+ options.signal?.addEventListener('abort', onAbort, { once: true });
57
+ child.stdout.on('data', (chunk) => {
58
+ const text = chunk.toString('utf8');
59
+ stdout += text;
60
+ options.onOutput?.({ stream: 'stdout', text });
61
+ });
62
+ child.stderr.on('data', (chunk) => {
63
+ const text = chunk.toString('utf8');
64
+ stderr += text;
65
+ options.onOutput?.({ stream: 'stderr', text });
66
+ });
67
+ if (options.stdin)
68
+ child.stdin.write(options.stdin);
69
+ child.stdin.end();
70
+ child.on('close', (code) => {
71
+ if (timer)
72
+ clearTimeout(timer);
73
+ options.signal?.removeEventListener('abort', onAbort);
74
+ done({ exitCode: code ?? -1, stdout, stderr, timedOut, durationMs: Date.now() - started });
75
+ });
76
+ child.on('error', (error) => {
77
+ if (timer)
78
+ clearTimeout(timer);
79
+ done({ exitCode: -1, stdout, stderr: stderr + error.message, timedOut, durationMs: Date.now() - started });
80
+ });
81
+ });
82
+ }
83
+ async readFile(path) {
84
+ return readFile(this.inside(path));
85
+ }
86
+ async writeFile(path, content) {
87
+ const full = this.inside(path);
88
+ await mkdir(dirname(full), { recursive: true });
89
+ await writeFile(full, content);
90
+ }
91
+ async list(path) {
92
+ const full = this.inside(path);
93
+ const names = await readdir(full, { withFileTypes: true });
94
+ const out = [];
95
+ for (const entry of names) {
96
+ const entryPath = join(full, entry.name);
97
+ const type = entry.isDirectory() ? 'dir' : entry.isSymbolicLink() ? 'link' : 'file';
98
+ let size;
99
+ if (type === 'file')
100
+ size = (await stat(entryPath).catch(() => null))?.size;
101
+ out.push({ name: entry.name, path: entryPath, type, ...(size !== undefined ? { size } : {}) });
102
+ }
103
+ return out;
104
+ }
105
+ async gitStatus(cwd) {
106
+ const result = await this.exec('git status --porcelain=v1 -b', cwd ? { cwd } : {});
107
+ return parseGitStatus(result.stdout);
108
+ }
109
+ async gitDiff(options = {}) {
110
+ const paths = (options.paths ?? []).map((one) => `'${one.replace(/'/g, `'\\''`)}'`).join(' ');
111
+ const result = await this.exec(`git diff ${options.base ?? ''} -- ${paths}`.trim(), options.cwd ? { cwd: options.cwd } : {});
112
+ return result.stdout;
113
+ }
114
+ async previewUrl(port) {
115
+ return `http://127.0.0.1:${port}`;
116
+ }
117
+ async pause() { }
118
+ async resume() { }
119
+ async snapshot() {
120
+ throw new Error('A local folder has no snapshots.');
121
+ }
122
+ }
123
+ export function parseGitStatus(text) {
124
+ const lines = text.split('\n').filter(Boolean);
125
+ let branch = null;
126
+ const files = [];
127
+ for (const line of lines) {
128
+ if (line.startsWith('## ')) {
129
+ branch = line.slice(3).split('...')[0]?.trim() || null;
130
+ continue;
131
+ }
132
+ const code = line.slice(0, 2);
133
+ const path = line.slice(3).split(' -> ').pop() ?? '';
134
+ const change = code === '??' ? 'untracked' : code.includes('D') ? 'deleted' : code.includes('R') ? 'renamed' : code.includes('A') ? 'added' : 'modified';
135
+ files.push({ path, change });
136
+ }
137
+ return { branch, clean: files.length === 0, files };
138
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The system prompt OpenCode would send for this model — the same choice as
3
+ * upstream `SystemPrompt.provider()` (session/system.ts, vendored as
4
+ * system.ts.ref), with the same files. Model behaviour should match plain
5
+ * OpenCode, which is the yardstick (plan Phase 6).
6
+ */
7
+ export declare function providerPrompt(modelId: string): string;
8
+ /** Upstream's `<env>` block (SystemPrompt.environment), for the Place's machine. */
9
+ export declare function environmentPrompt(input: {
10
+ modelId: string;
11
+ root: string;
12
+ isGit: boolean;
13
+ os: string;
14
+ date?: Date;
15
+ }): string;
16
+ export declare const SHELL_MAX_LINES = 2000;
17
+ export declare const SHELL_MAX_BYTES: number;
18
+ export declare const SHELL_DEFAULT_TIMEOUT_MS: number;
19
+ /**
20
+ * The bash tool's description, rendered the way upstream renders it for bash
21
+ * (tool/shell/prompt.ts `render('bash', …)`, vendored for reference). The
22
+ * strings below are copied from that file's bash profile unchanged.
23
+ */
24
+ export declare function bashDescription(input: {
25
+ os: string;
26
+ tmp: string;
27
+ }): string;
@@ -0,0 +1,108 @@
1
+ import { vendored } from './vendor.js';
2
+ /**
3
+ * The system prompt OpenCode would send for this model — the same choice as
4
+ * upstream `SystemPrompt.provider()` (session/system.ts, vendored as
5
+ * system.ts.ref), with the same files. Model behaviour should match plain
6
+ * OpenCode, which is the yardstick (plan Phase 6).
7
+ */
8
+ export function providerPrompt(modelId) {
9
+ const id = modelId.split('/').pop() ?? modelId;
10
+ if (id.includes('muse')) {
11
+ const name = id.includes('muse-glimmer') ? 'Muse Glimmer' : 'Muse Spark';
12
+ return vendored('session/prompt/meta.txt').replaceAll('{{MODEL_NAME}}', name);
13
+ }
14
+ if (id.includes('gpt-4') || id.includes('o1') || id.includes('o3'))
15
+ return vendored('session/prompt/beast.txt');
16
+ if (id.includes('gpt')) {
17
+ return id.includes('codex') ? vendored('session/prompt/codex.txt') : vendored('session/prompt/gpt.txt');
18
+ }
19
+ if (id.includes('gemini-'))
20
+ return vendored('session/prompt/gemini.txt');
21
+ if (id.includes('claude'))
22
+ return vendored('session/prompt/anthropic.txt');
23
+ if (id.toLowerCase().includes('trinity'))
24
+ return vendored('session/prompt/trinity.txt');
25
+ if (id.toLowerCase().includes('kimi') || modelId.startsWith('moonshotai'))
26
+ return vendored('session/prompt/kimi.txt');
27
+ return vendored('session/prompt/default.txt');
28
+ }
29
+ /** Upstream's `<env>` block (SystemPrompt.environment), for the Place's machine. */
30
+ export function environmentPrompt(input) {
31
+ const id = input.modelId.split('/').pop() ?? input.modelId;
32
+ return [
33
+ `You are powered by the model named ${id}. The exact model ID is ${input.modelId}`,
34
+ `Here is some useful information about the environment you are running in:`,
35
+ `<env>`,
36
+ ` Working directory: ${input.root}`,
37
+ ` Workspace root folder: ${input.root}`,
38
+ ` Is directory a git repo: ${input.isGit ? 'yes' : 'no'}`,
39
+ ` Platform: ${input.os}`,
40
+ ` Today's date: ${(input.date ?? new Date()).toDateString()}`,
41
+ `</env>`,
42
+ ].join('\n');
43
+ }
44
+ export const SHELL_MAX_LINES = 2000;
45
+ export const SHELL_MAX_BYTES = 50 * 1024;
46
+ export const SHELL_DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
47
+ /**
48
+ * The bash tool's description, rendered the way upstream renders it for bash
49
+ * (tool/shell/prompt.ts `render('bash', …)`, vendored for reference). The
50
+ * strings below are copied from that file's bash profile unchanged.
51
+ */
52
+ export function bashDescription(input) {
53
+ const chain = "If the commands depend on each other and must run sequentially, use a single Bash call with '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead.";
54
+ const commandSection = `Before executing the command, please follow these steps:
55
+
56
+ 1. Directory Verification:
57
+ - If the command will create new directories or files, first use \`ls\` to verify the parent directory exists and is the correct location
58
+ - For example, before running "mkdir foo/bar", first use \`ls foo\` to check that "foo" exists and is the intended parent directory
59
+
60
+ 2. Command Execution:
61
+ - Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
62
+ - Examples of proper quoting:
63
+ - mkdir "/Users/name/My Documents" (correct)
64
+ - mkdir /Users/name/My Documents (incorrect - will fail)
65
+ - python "/path/with spaces/script.py" (correct)
66
+ - python /path/with spaces/script.py (incorrect - will fail)
67
+ - After ensuring proper quoting, execute the command.
68
+ - Capture the output of the command.
69
+
70
+ Usage notes:
71
+ - The command argument is required.
72
+ - You can specify an optional timeout in milliseconds. If not specified, commands will time out after ${SHELL_DEFAULT_TIMEOUT_MS}ms.
73
+ - If the output exceeds ${SHELL_MAX_LINES} lines or ${SHELL_MAX_BYTES} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use \`head\`, \`tail\`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.
74
+
75
+ - Avoid using Bash with the \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
76
+ - File search: Use Glob (NOT find or ls)
77
+ - Content search: Use Grep (NOT grep or rg)
78
+ - Read files: Use Read (NOT cat/head/tail)
79
+ - Edit files: Use Edit (NOT sed/awk)
80
+ - Write files: Use Write (NOT echo >/cat <<EOF)
81
+ - Communication: Output text directly (NOT echo/printf)
82
+ - When issuing multiple commands:
83
+ - If the commands are independent and can run in parallel, make multiple bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two bash tool calls in parallel.
84
+ - ${chain}
85
+ - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
86
+ - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
87
+ - AVOID using \`cd <directory> && <command>\`. Use the \`workdir\` parameter to change directories instead.
88
+ <good-example>
89
+ Use workdir="/foo/bar" with command: pytest tests
90
+ </good-example>
91
+ <bad-example>
92
+ cd /foo/bar && pytest tests
93
+ </bad-example>`;
94
+ const values = {
95
+ intro: 'Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.',
96
+ os: input.os,
97
+ shell: 'bash',
98
+ tmp: input.tmp,
99
+ workdirSection: 'All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.',
100
+ commandSection,
101
+ };
102
+ return vendored('tool/shell/shell.txt').replace(/\$\{(\w+)\}/g, (_, key) => {
103
+ const value = values[key];
104
+ if (value === undefined)
105
+ throw new Error(`Missing shell prompt value: ${key}`);
106
+ return value;
107
+ });
108
+ }