@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,115 @@
1
+ import type { EngineEmit, EngineOutcome, EngineSession, EngineSessionState, Place, RunBrief, RunnerCommand, Ask, AskResult } from '@workser/runtime';
2
+ import { type CompactionBudget } from './compact.js';
3
+ import { type ToolSpec } from './tools/types.js';
4
+ export declare const ENGINE_NAME = "workser-core";
5
+ export interface CoreSessionOptions {
6
+ brief: RunBrief;
7
+ place: Place;
8
+ emit: EngineEmit;
9
+ /** Workser's OpenAI-compatible model route (the gateway). */
10
+ modelBaseUrl: string;
11
+ /** The run token — read on every call, so a rotation takes effect at once. */
12
+ modelKey: string | (() => string);
13
+ model?: string;
14
+ /** Ask the owner (the runner's `ask`); the answer comes back through `answer()`. */
15
+ ask?: (ask: Ask) => Promise<AskResult>;
16
+ fetch?: typeof fetch;
17
+ /** A model turn is one call; this caps calls per prompt (upstream has none; we do). */
18
+ maxSteps?: number;
19
+ /** Called after every model turn with the state to persist for a resume. */
20
+ onCheckpoint?: (state: EngineSessionState) => Promise<void> | void;
21
+ state?: EngineSessionState;
22
+ /**
23
+ * `task` (default): the job completes when its prompts' turns end.
24
+ * `session`: each prompt is a turn; `onTurnEnded` is told, and the job
25
+ * waits for the next message until `end()`.
26
+ */
27
+ mode?: 'task' | 'session';
28
+ onTurnEnded?: (summary: string) => Promise<void> | void;
29
+ /** Stream replies as `message.delta` events (default true). */
30
+ stream?: boolean;
31
+ /** When to prune and summarize the conversation. */
32
+ budget?: Partial<CompactionBudget>;
33
+ /** Which tool permissions ask the owner (default `['bash']`: file edits don't). */
34
+ askFor?: string[];
35
+ /** More tools beside upstream's (the key relay's `vault_fetch`, `workser_tool`). */
36
+ extraTools?: ToolSpec[];
37
+ /** Added to the system prompt when the extra tools need explaining. */
38
+ extraPrompt?: string;
39
+ }
40
+ /**
41
+ * OpenCode's agent loop, run where WE choose (plan D1, "loop in our service"):
42
+ * system prompt and environment block as upstream, upstream's tools with
43
+ * their own descriptions and schemas, and every file and shell action on the
44
+ * Place. One `prompt()` runs model turns until the model stops calling tools.
45
+ */
46
+ export declare class CoreSession implements EngineSession {
47
+ private readonly options;
48
+ readonly done: Promise<EngineOutcome>;
49
+ private settle;
50
+ private readonly messages;
51
+ private readonly read;
52
+ private readonly todos;
53
+ private readonly tools;
54
+ /** Tool results kept out of the record: call id → the line kept instead (see `ToolResult.recorded`). */
55
+ private readonly redacted;
56
+ private readonly pending;
57
+ private readonly queue;
58
+ private abort;
59
+ private stopReason;
60
+ private paused;
61
+ private unpause;
62
+ private working;
63
+ private finished;
64
+ private turn;
65
+ private stepSeq;
66
+ private root;
67
+ private shell;
68
+ private lastPromptTokens;
69
+ private compactions;
70
+ constructor(options: CoreSessionOptions);
71
+ /** The id `engine.session` names, so a restarted runner can resume this job. */
72
+ get id(): string;
73
+ private get mode();
74
+ private get budget();
75
+ get idle(): boolean;
76
+ private get model();
77
+ private key;
78
+ /** Set up the tools and the system prompt for this Place. */
79
+ open(): Promise<void>;
80
+ /** Run one prompt to the end of its turns. Several prompts queue. */
81
+ prompt(text: string): Promise<void>;
82
+ /**
83
+ * Pick a restored job back up. A job cut off mid-turn (the last thing is an
84
+ * owner message or a tool answer, or a tool call that never got one) goes
85
+ * on from there; a finished turn waits (session) or completes (task).
86
+ */
87
+ continue(): Promise<void>;
88
+ /** The prompts ran out: the job is done (task), or this turn is (session). */
89
+ private afterTurns;
90
+ /** Session mode: the owner said that's all (or it went quiet). */
91
+ end(reason?: string): Promise<void>;
92
+ private lastReply;
93
+ /** A new owner message. Returns at once; the turn runs on its own (like the runner's other engine). */
94
+ send(message: string): Promise<void>;
95
+ answer(command: RunnerCommand): Promise<void>;
96
+ stop(reason?: string): Promise<void>;
97
+ save(): Promise<EngineSessionState>;
98
+ /** The last prompt finished and nothing is queued: the job is done. */
99
+ complete(summary?: string): void;
100
+ private finish;
101
+ private chatTools;
102
+ private runTurns;
103
+ /** `message.delta` in pieces, not one event per token. */
104
+ private deltaWriter;
105
+ /**
106
+ * Keep the conversation inside the model's window: prune old tool output
107
+ * first, then summarize the middle (see compact.ts). A failed summary
108
+ * leaves the conversation as it was; the model route then says whether it
109
+ * still fits.
110
+ */
111
+ private compactIfNeeded;
112
+ private checkpoint;
113
+ private runTool;
114
+ private context;
115
+ }
@@ -0,0 +1,523 @@
1
+ import { chat, ModelError } from './model.js';
2
+ import { environmentPrompt, providerPrompt } from './prompts.js';
3
+ import { bashTool, ShellSession } from './tools/shell.js';
4
+ import { editTool, readTool, todoWriteTool, writeTool } from './tools/files.js';
5
+ import { applyPatchTool, usesPatch } from './tools/patch.js';
6
+ import { DEFAULT_BUDGET, cutPoint, overBudget, pruneToolOutputs, summaryRequest, withSummary, } from './compact.js';
7
+ import { globTool, grepTool } from './tools/search.js';
8
+ import { PermissionDenied } from './tools/types.js';
9
+ export const ENGINE_NAME = 'workser-core';
10
+ const STATE_VERSION = 2;
11
+ /** Deltas are sent in pieces of about this size or this often, not per token. */
12
+ const DELTA_FLUSH_CHARS = 200;
13
+ const DELTA_FLUSH_MS = 150;
14
+ const DEFAULT_MODEL = 'anthropic/claude-sonnet-4.5';
15
+ const MAX_OUTPUT_IN_EVENT = 4_000;
16
+ /**
17
+ * OpenCode's agent loop, run where WE choose (plan D1, "loop in our service"):
18
+ * system prompt and environment block as upstream, upstream's tools with
19
+ * their own descriptions and schemas, and every file and shell action on the
20
+ * Place. One `prompt()` runs model turns until the model stops calling tools.
21
+ */
22
+ export class CoreSession {
23
+ options;
24
+ done;
25
+ settle;
26
+ messages = [];
27
+ read = new Set();
28
+ todos = [];
29
+ tools;
30
+ /** Tool results kept out of the record: call id → the line kept instead (see `ToolResult.recorded`). */
31
+ redacted = new Map();
32
+ pending = new Map();
33
+ queue = [];
34
+ abort = new AbortController();
35
+ stopReason = null;
36
+ paused = null;
37
+ unpause = null;
38
+ working = false;
39
+ finished = false;
40
+ turn = 0;
41
+ stepSeq = 0;
42
+ root = '';
43
+ shell;
44
+ lastPromptTokens = 0;
45
+ compactions = 0;
46
+ constructor(options) {
47
+ this.options = options;
48
+ this.done = new Promise((resolve) => (this.settle = resolve));
49
+ this.tools = [];
50
+ const saved = options.state?.data;
51
+ if (saved?.messages)
52
+ this.messages.push(...saved.messages);
53
+ if (saved?.todos)
54
+ this.todos.push(...saved.todos);
55
+ for (const path of saved?.read ?? [])
56
+ this.read.add(path);
57
+ this.turn = saved?.turn ?? 0;
58
+ this.stepSeq = saved?.stepSeq ?? 0;
59
+ this.compactions = saved?.compactions ?? 0;
60
+ // The shell's state lives on the machine; a resumed job finds it again.
61
+ this.shell = new ShellSession(saved?.shell ?? (options.brief.run.id || randomId()), '/tmp');
62
+ }
63
+ /** The id `engine.session` names, so a restarted runner can resume this job. */
64
+ get id() {
65
+ return this.shell.id;
66
+ }
67
+ get mode() {
68
+ return this.options.mode ?? 'task';
69
+ }
70
+ get budget() {
71
+ const fromInput = Number(this.options.brief.run.input?.context_tokens);
72
+ return {
73
+ ...DEFAULT_BUDGET,
74
+ ...(Number.isFinite(fromInput) && fromInput >= 8_000 ? { contextTokens: fromInput } : {}),
75
+ ...(this.options.budget ?? {}),
76
+ };
77
+ }
78
+ get idle() {
79
+ return !this.working;
80
+ }
81
+ get model() {
82
+ const fromInput = this.options.brief.run.input?.model;
83
+ // Same rule as the runner's OpenCode engine: a plain `provider/model` id, else the default.
84
+ return this.options.model ?? (typeof fromInput === 'string' && /^[\w.:-]+\/[\w.:/-]+$/.test(fromInput) ? fromInput : DEFAULT_MODEL);
85
+ }
86
+ key() {
87
+ return typeof this.options.modelKey === 'function' ? this.options.modelKey() : this.options.modelKey;
88
+ }
89
+ /** Set up the tools and the system prompt for this Place. */
90
+ async open() {
91
+ const info = await this.options.place.info();
92
+ this.root = info.root;
93
+ // Upstream's rule: GPT models edit with apply_patch, everyone else with edit and write.
94
+ const editing = usesPatch(this.model) ? [applyPatchTool] : [writeTool, editTool];
95
+ this.tools.push(bashTool({ os: info.os, tmp: '/tmp', shell: this.shell }), readTool, ...editing, globTool, grepTool, todoWriteTool, ...(this.options.extraTools ?? []));
96
+ if (this.messages.length === 0) {
97
+ const isGit = (await this.options.place.exec('git rev-parse --is-inside-work-tree', { timeoutMs: 10_000 }))
98
+ .stdout.trim() === 'true';
99
+ this.messages.push({
100
+ role: 'system',
101
+ content: [
102
+ providerPrompt(this.model),
103
+ environmentPrompt({ modelId: this.model, root: this.root, isGit, os: info.os }),
104
+ ...(this.options.extraPrompt ? [this.options.extraPrompt] : []),
105
+ ].join('\n\n'),
106
+ });
107
+ }
108
+ }
109
+ /** Run one prompt to the end of its turns. Several prompts queue. */
110
+ async prompt(text) {
111
+ this.queue.push(text);
112
+ if (this.working)
113
+ return;
114
+ this.working = true;
115
+ try {
116
+ while (this.queue.length && !this.finished) {
117
+ this.messages.push({ role: 'user', content: this.queue.shift() });
118
+ await this.runTurns();
119
+ }
120
+ }
121
+ finally {
122
+ this.working = false;
123
+ }
124
+ await this.afterTurns();
125
+ }
126
+ /**
127
+ * Pick a restored job back up. A job cut off mid-turn (the last thing is an
128
+ * owner message or a tool answer, or a tool call that never got one) goes
129
+ * on from there; a finished turn waits (session) or completes (task).
130
+ */
131
+ async continue() {
132
+ const last = this.messages[this.messages.length - 1];
133
+ if (!last || this.finished)
134
+ return;
135
+ if (last.role === 'assistant' && last.tool_calls?.length) {
136
+ const answered = new Set(this.messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id));
137
+ for (const call of last.tool_calls) {
138
+ if (answered.has(call.id))
139
+ continue;
140
+ this.messages.push({
141
+ role: 'tool',
142
+ tool_call_id: call.id,
143
+ content: 'The job was restarted before this finished. Check the current state and run it again if it is still needed.',
144
+ });
145
+ }
146
+ }
147
+ const cutOff = this.messages[this.messages.length - 1].role !== 'assistant';
148
+ if (cutOff) {
149
+ this.working = true;
150
+ try {
151
+ await this.runTurns();
152
+ }
153
+ finally {
154
+ this.working = false;
155
+ }
156
+ }
157
+ await this.afterTurns();
158
+ }
159
+ /** The prompts ran out: the job is done (task), or this turn is (session). */
160
+ async afterTurns() {
161
+ if (this.finished || this.working || this.queue.length)
162
+ return;
163
+ const summary = this.lastReply();
164
+ if (this.mode === 'task') {
165
+ this.complete(summary);
166
+ return;
167
+ }
168
+ try {
169
+ await this.options.onTurnEnded?.(summary ?? '');
170
+ }
171
+ catch {
172
+ // The runner's own bookkeeping; the session stays open either way.
173
+ }
174
+ }
175
+ /** Session mode: the owner said that's all (or it went quiet). */
176
+ async end(reason = 'ended') {
177
+ if (this.finished)
178
+ return;
179
+ const summary = this.lastReply();
180
+ this.finish({ status: 'completed', ...(summary ? { summary } : {}), message: reason });
181
+ }
182
+ lastReply() {
183
+ const last = [...this.messages].reverse().find((one) => one.role === 'assistant' && one.content);
184
+ return last?.content?.slice(0, 20_000) ?? undefined;
185
+ }
186
+ /** A new owner message. Returns at once; the turn runs on its own (like the runner's other engine). */
187
+ async send(message) {
188
+ void this.prompt(message);
189
+ }
190
+ async answer(command) {
191
+ if (command.kind === 'pause') {
192
+ if (!this.paused)
193
+ this.paused = new Promise((resolve) => (this.unpause = resolve));
194
+ this.options.emit('run.paused', { reason: String(command.payload.reason ?? 'paused by the owner') });
195
+ return;
196
+ }
197
+ if (command.kind === 'resume') {
198
+ this.unpause?.();
199
+ this.paused = null;
200
+ this.unpause = null;
201
+ this.options.emit('run.resumed', {});
202
+ return;
203
+ }
204
+ if (command.kind === 'message' && typeof command.payload.text === 'string') {
205
+ void this.prompt(command.payload.text);
206
+ return;
207
+ }
208
+ if ((command.kind === 'approval' || command.kind === 'answer') && command.payload.approval_id) {
209
+ const waiting = this.pending.get(command.payload.approval_id);
210
+ if (!waiting)
211
+ return; // not ours, or already answered (second screen)
212
+ this.pending.delete(command.payload.approval_id);
213
+ waiting.resolve(command.kind === 'approval' ? command.payload.decision === 'approved' : true);
214
+ }
215
+ }
216
+ async stop(reason = 'stopped') {
217
+ if (this.finished)
218
+ return;
219
+ this.stopReason = reason;
220
+ this.abort.abort();
221
+ for (const [id, waiting] of this.pending) {
222
+ waiting.resolve(false);
223
+ this.pending.delete(id);
224
+ }
225
+ this.unpause?.();
226
+ this.finish({ status: 'cancelled', message: reason });
227
+ }
228
+ async save() {
229
+ return {
230
+ engine: ENGINE_NAME,
231
+ version: STATE_VERSION,
232
+ data: {
233
+ // A result that holds an outside message (a sign-in code) is saved as its short note, not whole.
234
+ messages: this.redacted.size
235
+ ? this.messages.map((m) => (m.role === 'tool' && m.tool_call_id && this.redacted.has(m.tool_call_id) ? { ...m, content: this.redacted.get(m.tool_call_id) } : m))
236
+ : this.messages,
237
+ todos: this.todos,
238
+ read: [...this.read],
239
+ turn: this.turn,
240
+ stepSeq: this.stepSeq,
241
+ shell: this.shell.id,
242
+ compactions: this.compactions,
243
+ },
244
+ };
245
+ }
246
+ /** The last prompt finished and nothing is queued: the job is done. */
247
+ complete(summary) {
248
+ this.finish({ status: 'completed', ...(summary ? { summary } : {}) });
249
+ }
250
+ finish(outcome) {
251
+ if (this.finished)
252
+ return;
253
+ this.finished = true;
254
+ this.settle(outcome);
255
+ }
256
+ chatTools() {
257
+ return this.tools.map((tool) => ({
258
+ type: 'function',
259
+ function: { name: tool.name, description: tool.description, parameters: tool.parameters },
260
+ }));
261
+ }
262
+ async runTurns() {
263
+ const max = this.options.maxSteps ?? 100;
264
+ for (let step = 0; step < max && !this.finished; step++) {
265
+ if (this.paused)
266
+ await this.paused;
267
+ if (this.finished)
268
+ return;
269
+ await this.compactIfNeeded();
270
+ if (this.finished)
271
+ return;
272
+ let result;
273
+ const messageId = `m${this.turn + 1}`;
274
+ const deltas = this.options.stream === false ? null : this.deltaWriter(messageId);
275
+ try {
276
+ result = await chat({
277
+ baseUrl: this.options.modelBaseUrl,
278
+ key: this.key(),
279
+ model: this.model,
280
+ messages: this.messages,
281
+ tools: this.chatTools(),
282
+ signal: this.abort.signal,
283
+ ...(this.options.fetch ? { fetch: this.options.fetch } : {}),
284
+ ...(deltas ? { onDelta: deltas.write } : {}),
285
+ });
286
+ deltas?.flush();
287
+ }
288
+ catch (error) {
289
+ deltas?.flush();
290
+ if (this.finished)
291
+ return;
292
+ const status = error instanceof ModelError ? error.status : 0;
293
+ this.finish({
294
+ status: 'failed',
295
+ error_kind: status === 402 ? 'insufficient_credits' : status === 403 ? 'model_refused' : 'model_error',
296
+ message: error?.message ?? String(error),
297
+ });
298
+ return;
299
+ }
300
+ this.turn += 1;
301
+ this.messages.push(result.message);
302
+ this.lastPromptTokens = Number(result.usage?.prompt_tokens ?? 0);
303
+ if (result.usage) {
304
+ this.options.emit('usage', {
305
+ model: this.model,
306
+ tokens_in: Number(result.usage.prompt_tokens ?? 0),
307
+ tokens_out: Number(result.usage.completion_tokens ?? 0),
308
+ ...(typeof result.usage.cost === 'number' ? { cost_usd: result.usage.cost } : {}),
309
+ });
310
+ }
311
+ if (result.message.content) {
312
+ this.options.emit('message', {
313
+ message_id: messageId,
314
+ role: 'assistant',
315
+ text: result.message.content.slice(0, 20_000),
316
+ });
317
+ }
318
+ const calls = result.message.tool_calls ?? [];
319
+ if (calls.length === 0) {
320
+ await this.checkpoint();
321
+ return;
322
+ }
323
+ for (const call of calls) {
324
+ if (this.finished)
325
+ return;
326
+ await this.runTool(call.id, call.function.name, call.function.arguments);
327
+ }
328
+ await this.checkpoint();
329
+ }
330
+ if (!this.finished) {
331
+ this.messages.push({ role: 'user', content: 'You have reached the step limit for this job. Stop and summarize what you did and what is left.' });
332
+ }
333
+ }
334
+ /** `message.delta` in pieces, not one event per token. */
335
+ deltaWriter(messageId) {
336
+ let buffer = '';
337
+ let timer = null;
338
+ const flush = () => {
339
+ if (timer)
340
+ clearTimeout(timer);
341
+ timer = null;
342
+ if (!buffer)
343
+ return;
344
+ this.options.emit('message.delta', { message_id: messageId, text: buffer });
345
+ buffer = '';
346
+ };
347
+ return {
348
+ write: (text) => {
349
+ buffer += text;
350
+ if (buffer.length >= DELTA_FLUSH_CHARS)
351
+ flush();
352
+ else
353
+ timer ??= setTimeout(flush, DELTA_FLUSH_MS);
354
+ },
355
+ flush,
356
+ };
357
+ }
358
+ /**
359
+ * Keep the conversation inside the model's window: prune old tool output
360
+ * first, then summarize the middle (see compact.ts). A failed summary
361
+ * leaves the conversation as it was; the model route then says whether it
362
+ * still fits.
363
+ */
364
+ async compactIfNeeded() {
365
+ const budget = this.budget;
366
+ if (!overBudget(this.messages, budget, this.lastPromptTokens))
367
+ return;
368
+ const cleared = pruneToolOutputs(this.messages, budget.keepToolTokens);
369
+ this.lastPromptTokens = 0; // the reported size is of the old conversation
370
+ if (!overBudget(this.messages, budget)) {
371
+ if (cleared)
372
+ this.options.emit('log', { level: 'info', text: `Cleared ${cleared} old tool results to keep the job in the model's window.` });
373
+ return;
374
+ }
375
+ const cut = cutPoint(this.messages, Math.floor(budget.contextTokens * 0.3));
376
+ if (cut < 0)
377
+ return;
378
+ try {
379
+ const result = await chat({
380
+ baseUrl: this.options.modelBaseUrl,
381
+ key: this.key(),
382
+ model: this.model,
383
+ messages: summaryRequest(this.messages.slice(2, cut)),
384
+ tools: [],
385
+ signal: this.abort.signal,
386
+ ...(this.options.fetch ? { fetch: this.options.fetch } : {}),
387
+ });
388
+ const summary = result.message.content?.trim();
389
+ if (!summary)
390
+ return;
391
+ if (result.usage) {
392
+ this.options.emit('usage', {
393
+ model: this.model,
394
+ tokens_in: Number(result.usage.prompt_tokens ?? 0),
395
+ tokens_out: Number(result.usage.completion_tokens ?? 0),
396
+ ...(typeof result.usage.cost === 'number' ? { cost_usd: result.usage.cost } : {}),
397
+ });
398
+ }
399
+ const next = withSummary(this.messages, cut, summary);
400
+ this.messages.splice(0, this.messages.length, ...next);
401
+ this.compactions += 1;
402
+ this.options.emit('log', { level: 'info', text: 'Summarized the earlier conversation to keep the job in the model\'s window.' });
403
+ await this.checkpoint();
404
+ }
405
+ catch (error) {
406
+ if (this.finished)
407
+ return;
408
+ this.options.emit('log', { level: 'warn', text: `Could not summarize the conversation: ${error?.message ?? error}` });
409
+ }
410
+ }
411
+ async checkpoint() {
412
+ if (!this.options.onCheckpoint)
413
+ return;
414
+ try {
415
+ await this.options.onCheckpoint(await this.save());
416
+ }
417
+ catch {
418
+ // A missed checkpoint costs a resume point, never the job.
419
+ }
420
+ }
421
+ async runTool(callId, name, rawArgs) {
422
+ const stepId = `s${++this.stepSeq}`;
423
+ const tool = this.tools.find((one) => one.name === name);
424
+ let args = {};
425
+ try {
426
+ args = rawArgs ? JSON.parse(rawArgs) : {};
427
+ }
428
+ catch {
429
+ args = {};
430
+ }
431
+ const started = Date.now();
432
+ this.options.emit('step.started', {
433
+ step_id: stepId,
434
+ title: titleOf(name, args),
435
+ tool: name,
436
+ input: trimArgs(args),
437
+ });
438
+ let output;
439
+ let recorded;
440
+ let status = 'ok';
441
+ if (!tool) {
442
+ output = `Unknown tool: ${name}`;
443
+ status = 'error';
444
+ }
445
+ else {
446
+ try {
447
+ const result = await tool.execute(args, this.context());
448
+ output = result.output;
449
+ recorded = result.recorded;
450
+ for (const changed of result.changed ?? []) {
451
+ this.options.emit('file.changed', { path: relativeTo(this.root, changed.path), change: changed.change });
452
+ }
453
+ }
454
+ catch (error) {
455
+ status = 'error';
456
+ output =
457
+ error instanceof PermissionDenied
458
+ ? `The user denied this action: ${error.message}`
459
+ : `Error: ${error?.message ?? String(error)}`;
460
+ }
461
+ }
462
+ this.messages.push({ role: 'tool', tool_call_id: callId, content: output });
463
+ if (recorded !== undefined)
464
+ this.redacted.set(callId, recorded);
465
+ this.options.emit('step.completed', {
466
+ step_id: stepId,
467
+ status,
468
+ output: { text: (recorded ?? output).slice(0, MAX_OUTPUT_IN_EVENT) },
469
+ ...(status === 'error' ? { error: output.slice(0, 4_000) } : {}),
470
+ duration_ms: Date.now() - started,
471
+ });
472
+ }
473
+ context() {
474
+ return {
475
+ place: this.options.place,
476
+ root: this.root,
477
+ read: this.read,
478
+ todos: this.todos,
479
+ signal: this.abort.signal,
480
+ ask: async (request) => {
481
+ if (!this.options.ask)
482
+ return; // no owner to ask: the default agent allows
483
+ // Like the runner's OpenCode config: file edits are allowed, only
484
+ // the destructive commands (tools/shell.ts) go to the owner.
485
+ if (!(this.options.askFor ?? ['bash']).includes(request.permission))
486
+ return;
487
+ const asked = await this.options.ask({
488
+ kind: 'permission',
489
+ title: request.title.slice(0, 300),
490
+ message: `The AI agent wants to ${request.permission === 'bash' ? 'run a command' : 'change a file'}:\n${request.detail.slice(0, 3_000)}`,
491
+ action_summary: request.detail.slice(0, 500),
492
+ payload: { permission: request.permission, patterns: request.patterns },
493
+ });
494
+ if (asked.status === 'approved' || asked.auto_approved)
495
+ return;
496
+ if (asked.status !== 'pending')
497
+ throw new PermissionDenied();
498
+ const allowed = await new Promise((resolve) => this.pending.set(asked.approval_id, { resolve }));
499
+ if (!allowed)
500
+ throw new PermissionDenied();
501
+ },
502
+ };
503
+ }
504
+ }
505
+ function randomId() {
506
+ return Math.random().toString(36).slice(2, 12);
507
+ }
508
+ function titleOf(name, args) {
509
+ const pick = (key) => (typeof args[key] === 'string' ? String(args[key]) : '');
510
+ const detail = name === 'bash' ? pick('description') || pick('command') : pick('filePath') || pick('pattern') || pick('path');
511
+ return `${name}${detail ? `: ${detail}` : ''}`.slice(0, 500);
512
+ }
513
+ function trimArgs(args) {
514
+ const out = {};
515
+ for (const [key, value] of Object.entries(args)) {
516
+ out[key] = typeof value === 'string' && value.length > 2_000 ? `${value.slice(0, 2_000)}… (${value.length} chars)` : value;
517
+ }
518
+ return out;
519
+ }
520
+ function relativeTo(root, path) {
521
+ const base = root.replace(/\/+$/, '');
522
+ return path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path;
523
+ }
@@ -0,0 +1,9 @@
1
+ import { type ToolSpec } from './types.js';
2
+ /** Upstream `read`: numbered lines `N: text`, offset/limit, the same notes. */
3
+ export declare const readTool: ToolSpec;
4
+ /** Upstream `write`: whole-file write; asks for the `edit` permission. */
5
+ export declare const writeTool: ToolSpec;
6
+ /** Upstream `edit`: oldString → newString with upstream's own matching (vendored). */
7
+ export declare const editTool: ToolSpec;
8
+ /** Upstream `todowrite`: the plan as a list; returned as JSON like upstream. */
9
+ export declare const todoWriteTool: ToolSpec;