@workser/engine 0.1.13 → 0.1.15

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 (50) hide show
  1. package/NOTICE +2 -2
  2. package/README.md +2 -2
  3. package/dist/src/index.d.ts +2 -1
  4. package/dist/src/index.js +2 -1
  5. package/dist/src/model.d.ts +6 -0
  6. package/dist/src/prompts.js +2 -0
  7. package/dist/src/session.d.ts +19 -0
  8. package/dist/src/session.js +68 -20
  9. package/dist/src/tools/files.d.ts +9 -1
  10. package/dist/src/tools/files.js +63 -7
  11. package/dist/src/tools/repair.d.ts +26 -0
  12. package/dist/src/tools/repair.js +136 -0
  13. package/dist/src/tools/shell.d.ts +8 -5
  14. package/dist/src/tools/shell.js +9 -9
  15. package/dist/src/tools/workser-tool.d.ts +12 -0
  16. package/dist/src/tools/workser-tool.js +29 -2
  17. package/dist/src/vendor.d.ts +1 -1
  18. package/dist/src/vendor.js +1 -1
  19. package/package.json +2 -2
  20. package/vendor/opencode-1.19.5/COMMIT +1 -0
  21. package/vendor/opencode-1.19.5/session/prompt/gpt-astra.txt +46 -0
  22. package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/system.ts.ref +2 -0
  23. package/vendor/opencode-1.18.23/COMMIT +0 -1
  24. package/vendor/opencode-1.18.23/session/prompt/copilot-gpt-5.txt +0 -143
  25. package/vendor/opencode-1.18.23/session/prompt/plan-reminder-anthropic.txt +0 -67
  26. /package/dist/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/edit-replace.d.ts +0 -0
  27. /package/dist/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/edit-replace.js +0 -0
  28. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/LICENSE +0 -0
  29. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/anthropic.txt +0 -0
  30. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/beast.txt +0 -0
  31. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/build-switch.txt +0 -0
  32. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/codex.txt +0 -0
  33. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/default.txt +0 -0
  34. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/gemini.txt +0 -0
  35. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/gpt.txt +0 -0
  36. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/kimi.txt +0 -0
  37. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/meta.txt +0 -0
  38. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/plan-mode.txt +0 -0
  39. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/plan.txt +0 -0
  40. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/session/prompt/trinity.txt +0 -0
  41. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/apply_patch.txt +0 -0
  42. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/edit-replace.ts +0 -0
  43. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/edit.txt +0 -0
  44. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/glob.txt +0 -0
  45. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/grep.txt +0 -0
  46. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/read.txt +0 -0
  47. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/shell/prompt.ts.ref +0 -0
  48. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/shell/shell.txt +0 -0
  49. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/todowrite.txt +0 -0
  50. /package/vendor/{opencode-1.18.23 → opencode-1.19.5}/tool/write.txt +0 -0
package/NOTICE CHANGED
@@ -1,6 +1,6 @@
1
1
  This package contains material from OpenCode (https://github.com/sst/opencode),
2
- version v1.18.23 (commit ef2880f379129aa048be9e9353e30aa168d42c17),
3
- Copyright (c) 2025 opencode, used under the MIT License (vendor/opencode-1.18.23/LICENSE).
2
+ version v1.19.5 (commit 810c0eba1a7348036f8bdf61e6632d0c36c6876c),
3
+ Copyright (c) 2025 opencode, used under the MIT License (vendor/opencode-1.19.5/LICENSE).
4
4
 
5
5
  Vendored, unmodified: the system prompts (session/prompt/*.txt), the tool
6
6
  descriptions (tool/*.txt, tool/shell/shell.txt), the shell prompt builder
package/README.md CHANGED
@@ -9,7 +9,7 @@ key (the run token) never goes there.
9
9
 
10
10
  ## What is OpenCode's here
11
11
 
12
- Vendored from OpenCode **v1.18.23** (MIT, `vendor/opencode-1.18.23/`, see
12
+ Vendored from OpenCode **v1.19.5** (MIT, `vendor/opencode-1.19.5/`, see
13
13
  `NOTICE`), unmodified:
14
14
 
15
15
  - the system prompts (`session/prompt/*.txt`), chosen per model exactly like
@@ -54,7 +54,7 @@ an engine too (`start`, `resume(state)`, `send`, `answer`, `stop`, `save`).
54
54
  ## Production pieces
55
55
 
56
56
  - `apply_patch` for GPT models (upstream's rule); `edit` + `write` for the rest.
57
- - A persistent shell: exported variables and the folder carry between `bash` calls.
57
+ - A persistent shell: exported variables carry between `bash` calls; every command starts in the project folder (or its `workdir`).
58
58
  - Streaming: `message.delta` events as the model writes.
59
59
  - Compaction: old tool output cleared, then the middle summarized, at 80 % of the context budget (`input.context_tokens`, default 128k).
60
60
  - Session mode (`mode: 'session'`) and `continue()` for a job restored from a checkpoint.
@@ -1,5 +1,5 @@
1
1
  export { CoreEngine, runEngine, promptOf, serviceExtras, type CoreEngineOptions, type RunEngineInput, type RunnerLike } from './engine.js';
2
- export { CoreSession, ENGINE_NAME, type CoreSessionOptions } from './session.js';
2
+ export { CoreSession, ENGINE_NAME, READ_ONLY_NUDGE, READ_ONLY_TURNS, usageEvent, type CoreSessionOptions } from './session.js';
3
3
  export { LocalPlace } from './place/local.js';
4
4
  export { E2BPlace, connectE2BPlace, type E2BSandboxLike } from './place/e2b.js';
5
5
  export { OPENCODE_VERSION } from './vendor.js';
@@ -11,3 +11,4 @@ export { DEFAULT_BUDGET, COST_COMPACT_TOKENS, compactAt, estimateTokens, pruneTo
11
11
  export { vaultFetchTool, type KeyRelay } from './tools/relay.js';
12
12
  export { workserTool, type ToolsClient } from './tools/workser-tool.js';
13
13
  export { withCommandEnv } from './place/env.js';
14
+ export { repairArgs, parseLoose, TOOL_ALIASES, type Repaired } from './tools/repair.js';
package/dist/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { CoreEngine, runEngine, promptOf, serviceExtras } from './engine.js';
2
- export { CoreSession, ENGINE_NAME } from './session.js';
2
+ export { CoreSession, ENGINE_NAME, READ_ONLY_NUDGE, READ_ONLY_TURNS, usageEvent } from './session.js';
3
3
  export { LocalPlace } from './place/local.js';
4
4
  export { E2BPlace, connectE2BPlace } from './place/e2b.js';
5
5
  export { OPENCODE_VERSION } from './vendor.js';
@@ -11,3 +11,4 @@ export { DEFAULT_BUDGET, COST_COMPACT_TOKENS, compactAt, estimateTokens, pruneTo
11
11
  export { vaultFetchTool } from './tools/relay.js';
12
12
  export { workserTool } from './tools/workser-tool.js';
13
13
  export { withCommandEnv } from './place/env.js';
14
+ export { repairArgs, parseLoose, TOOL_ALIASES } from './tools/repair.js';
@@ -33,6 +33,12 @@ export interface ChatResult {
33
33
  prompt_tokens?: number;
34
34
  completion_tokens?: number;
35
35
  cost?: number;
36
+ prompt_tokens_details?: {
37
+ cached_tokens?: number;
38
+ };
39
+ completion_tokens_details?: {
40
+ reasoning_tokens?: number;
41
+ };
36
42
  };
37
43
  }
38
44
  export declare class ModelError extends Error {
@@ -14,6 +14,8 @@ export function providerPrompt(modelId) {
14
14
  if (id.includes('gpt-4') || id.includes('o1') || id.includes('o3'))
15
15
  return vendored('session/prompt/beast.txt');
16
16
  if (id.includes('gpt')) {
17
+ if (id.includes('gpt-6'))
18
+ return vendored('session/prompt/gpt-astra.txt');
17
19
  return id.includes('codex') ? vendored('session/prompt/codex.txt') : vendored('session/prompt/gpt.txt');
18
20
  }
19
21
  if (id.includes('gemini-'))
@@ -1,4 +1,5 @@
1
1
  import type { EngineEmit, EngineOutcome, EngineSession, EngineSessionState, Place, RunBrief, RunnerCommand, Ask, AskResult } from '@workser/runtime';
2
+ import { type ChatResult } from './model.js';
2
3
  import { type CompactionBudget } from './compact.js';
3
4
  import { type ToolSpec } from './tools/types.js';
4
5
  export declare const ENGINE_NAME = "workser-core";
@@ -63,6 +64,9 @@ export declare class CoreSession implements EngineSession {
63
64
  private finished;
64
65
  private turn;
65
66
  private stepSeq;
67
+ /** Turns in a row that changed no file (`READ_ONLY_NUDGE`), and whether this one did. */
68
+ private turnsWithoutChange;
69
+ private changedThisTurn;
66
70
  private root;
67
71
  private shell;
68
72
  private lastPromptTokens;
@@ -111,7 +115,22 @@ export declare class CoreSession implements EngineSession {
111
115
  private compactIfNeeded;
112
116
  private checkpoint;
113
117
  private runTool;
118
+ /**
119
+ * READ ENOUGH, NOW WRITE (owner 12 Nov trace: a job read and re-planned for 20 minutes, about 5k tokens of reasoning
120
+ * a turn, and changed no file). After `READ_ONLY_TURNS` turns in a row that changed no file, the last tool result
121
+ * of the turn carries one line saying so. Said again only after as many more such turns.
122
+ */
123
+ private nudgeIfOnlyReading;
114
124
  private context;
115
125
  }
116
126
  /** What an ask says the AI agent wants to do, by permission (`mcp`: a connected MCP server's tool, from the runner). */
117
127
  export declare function askVerb(permission: string): string;
128
+ /** Turns in a row with no file changed before the job is told to write. */
129
+ export declare const READ_ONLY_TURNS = 8;
130
+ export declare const READ_ONLY_NUDGE: string;
131
+ /**
132
+ * One model turn's use, as the `usage` event: tokens, the provider's charge, and (when the route says) the prompt
133
+ * tokens read from its cache and the hidden reasoning tokens. Owner 12 Nov: a trace showed no cache reads on
134
+ * 40–50k-token calls only because these counts were dropped here, so nobody could tell whether caching worked.
135
+ */
136
+ export declare function usageEvent(model: string, usage: NonNullable<ChatResult['usage']>): Record<string, unknown>;
@@ -5,6 +5,7 @@ import { editTool, readTool, todoWriteTool, writeTool } from './tools/files.js';
5
5
  import { applyPatchTool, usesPatch } from './tools/patch.js';
6
6
  import { DEFAULT_BUDGET, compactAt, cutPoint, overBudget, pruneToolOutputs, shortenOldArguments, summaryRequest, withSummary, } from './compact.js';
7
7
  import { globTool, grepTool } from './tools/search.js';
8
+ import { repairArgs, TOOL_ALIASES } from './tools/repair.js';
8
9
  import { PermissionDenied } from './tools/types.js';
9
10
  export const ENGINE_NAME = 'workser-core';
10
11
  const STATE_VERSION = 2;
@@ -42,6 +43,9 @@ export class CoreSession {
42
43
  finished = false;
43
44
  turn = 0;
44
45
  stepSeq = 0;
46
+ /** Turns in a row that changed no file (`READ_ONLY_NUDGE`), and whether this one did. */
47
+ turnsWithoutChange = 0;
48
+ changedThisTurn = false;
45
49
  root = '';
46
50
  shell;
47
51
  lastPromptTokens = 0;
@@ -308,12 +312,7 @@ export class CoreSession {
308
312
  this.messages.push(result.message);
309
313
  this.lastPromptTokens = Number(result.usage?.prompt_tokens ?? 0);
310
314
  if (result.usage) {
311
- this.options.emit('usage', {
312
- model: this.model,
313
- tokens_in: Number(result.usage.prompt_tokens ?? 0),
314
- tokens_out: Number(result.usage.completion_tokens ?? 0),
315
- ...(typeof result.usage.cost === 'number' ? { cost_usd: result.usage.cost } : {}),
316
- });
315
+ this.options.emit('usage', usageEvent(this.model, result.usage));
317
316
  }
318
317
  if (result.message.content) {
319
318
  this.options.emit('message', {
@@ -327,11 +326,13 @@ export class CoreSession {
327
326
  await this.checkpoint();
328
327
  return;
329
328
  }
329
+ this.changedThisTurn = false;
330
330
  for (const call of calls) {
331
331
  if (this.finished)
332
332
  return;
333
333
  await this.runTool(call.id, call.function.name, call.function.arguments);
334
334
  }
335
+ this.nudgeIfOnlyReading();
335
336
  await this.checkpoint();
336
337
  }
337
338
  if (!this.finished) {
@@ -404,12 +405,7 @@ export class CoreSession {
404
405
  if (!summary)
405
406
  return;
406
407
  if (result.usage) {
407
- this.options.emit('usage', {
408
- model: this.model,
409
- tokens_in: Number(result.usage.prompt_tokens ?? 0),
410
- tokens_out: Number(result.usage.completion_tokens ?? 0),
411
- ...(typeof result.usage.cost === 'number' ? { cost_usd: result.usage.cost } : {}),
412
- });
408
+ this.options.emit('usage', usageEvent(this.model, result.usage));
413
409
  }
414
410
  const next = withSummary(this.messages, cut, summary);
415
411
  this.messages.splice(0, this.messages.length, ...next);
@@ -435,14 +431,16 @@ export class CoreSession {
435
431
  }
436
432
  async runTool(callId, name, rawArgs) {
437
433
  const stepId = `s${++this.stepSeq}`;
438
- const tool = this.tools.find((one) => one.name === name);
439
- let args = {};
440
- try {
441
- args = rawArgs ? JSON.parse(rawArgs) : {};
442
- }
443
- catch {
444
- args = {};
445
- }
434
+ // A name from another harness runs the tool it means (tools/repair.ts), and the result says which one ran.
435
+ const alias = this.tools.some((one) => one.name === name) ? undefined : TOOL_ALIASES[name];
436
+ const tool = this.tools.find((one) => one.name === (alias ?? name));
437
+ // Input repaired where the tool's schema makes it unambiguous; input that can't be read never runs as `{}`.
438
+ const input = repairArgs(rawArgs, tool?.parameters);
439
+ const args = input.ok ? input.args : {};
440
+ const notes = [
441
+ ...(alias && tool ? [`(Ran ${alias}: there is no tool named ${name}. Call ${alias} next time.)`] : []),
442
+ ...(input.ok && input.repaired.length ? [`(Input fixed to match the tool: ${input.repaired.slice(0, 6).join('; ')}.)`] : []),
443
+ ];
446
444
  const started = Date.now();
447
445
  this.options.emit('step.started', {
448
446
  step_id: stepId,
@@ -457,11 +455,17 @@ export class CoreSession {
457
455
  output = `Unknown tool: ${name}`;
458
456
  status = 'error';
459
457
  }
458
+ else if (!input.ok) {
459
+ output = `Error: ${input.error}`;
460
+ status = 'error';
461
+ }
460
462
  else {
461
463
  try {
462
464
  const result = await tool.execute(args, this.context());
463
465
  output = result.output;
464
466
  recorded = result.recorded;
467
+ if ((result.changed?.length ?? 0) > 0 || CHANGING_TOOLS.has(tool.name))
468
+ this.changedThisTurn = true;
465
469
  for (const changed of result.changed ?? []) {
466
470
  this.options.emit('file.changed', { path: relativeTo(this.root, changed.path), change: changed.change });
467
471
  }
@@ -474,6 +478,8 @@ export class CoreSession {
474
478
  : `Error: ${error?.message ?? String(error)}`;
475
479
  }
476
480
  }
481
+ if (notes.length)
482
+ output = `${output}\n\n${notes.join('\n')}`;
477
483
  this.messages.push({ role: 'tool', tool_call_id: callId, content: output });
478
484
  if (recorded !== undefined)
479
485
  this.redacted.set(callId, recorded);
@@ -485,6 +491,24 @@ export class CoreSession {
485
491
  duration_ms: Date.now() - started,
486
492
  });
487
493
  }
494
+ /**
495
+ * READ ENOUGH, NOW WRITE (owner 12 Nov trace: a job read and re-planned for 20 minutes, about 5k tokens of reasoning
496
+ * a turn, and changed no file). After `READ_ONLY_TURNS` turns in a row that changed no file, the last tool result
497
+ * of the turn carries one line saying so. Said again only after as many more such turns.
498
+ */
499
+ nudgeIfOnlyReading() {
500
+ if (this.changedThisTurn) {
501
+ this.turnsWithoutChange = 0;
502
+ return;
503
+ }
504
+ this.turnsWithoutChange += 1;
505
+ if (this.turnsWithoutChange < READ_ONLY_TURNS)
506
+ return;
507
+ this.turnsWithoutChange = 0;
508
+ const last = [...this.messages].reverse().find((one) => one.role === 'tool');
509
+ if (last && typeof last.content === 'string')
510
+ last.content = `${last.content}\n\n${READ_ONLY_NUDGE}`;
511
+ }
488
512
  context() {
489
513
  return {
490
514
  place: this.options.place,
@@ -544,3 +568,27 @@ function relativeTo(root, path) {
544
568
  const base = root.replace(/\/+$/, '');
545
569
  return path.startsWith(`${base}/`) ? path.slice(base.length + 1) : path;
546
570
  }
571
+ /** Tools that change a file in the job's folder (a turn with one is not "only reading"). */
572
+ const CHANGING_TOOLS = new Set(['write', 'edit', 'apply_patch']);
573
+ /** Turns in a row with no file changed before the job is told to write. */
574
+ export const READ_ONLY_TURNS = 8;
575
+ export const READ_ONLY_NUDGE = `(Workser: ${READ_ONLY_TURNS} turns in a row without changing a file. If this task needs code, you have read enough: ` +
576
+ "put your plan in todowrite once if it is not there yet, then write the code now, one file at a time, and run it after. " +
577
+ "Don't re-plan the whole task again each turn, and don't re-read files you have already read. If the task is only to look into something, say what you found.)";
578
+ /**
579
+ * One model turn's use, as the `usage` event: tokens, the provider's charge, and (when the route says) the prompt
580
+ * tokens read from its cache and the hidden reasoning tokens. Owner 12 Nov: a trace showed no cache reads on
581
+ * 40–50k-token calls only because these counts were dropped here, so nobody could tell whether caching worked.
582
+ */
583
+ export function usageEvent(model, usage) {
584
+ const cached = usage.prompt_tokens_details?.cached_tokens;
585
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens;
586
+ return {
587
+ model,
588
+ tokens_in: Number(usage.prompt_tokens ?? 0),
589
+ tokens_out: Number(usage.completion_tokens ?? 0),
590
+ ...(typeof usage.cost === 'number' ? { cost_usd: usage.cost } : {}),
591
+ ...(typeof cached === 'number' ? { cached_tokens_in: cached } : {}),
592
+ ...(typeof reasoning === 'number' ? { reasoning_tokens: reasoning } : {}),
593
+ };
594
+ }
@@ -1,4 +1,4 @@
1
- import { type ToolSpec } from './types.js';
1
+ import { type ToolContext, type ToolSpec } from './types.js';
2
2
  /** Upstream `read`: numbered lines `N: text`, offset/limit, the same notes. */
3
3
  export declare const readTool: ToolSpec;
4
4
  /** Upstream `write`: whole-file write; asks for the `edit` permission. */
@@ -7,3 +7,11 @@ export declare const writeTool: ToolSpec;
7
7
  export declare const editTool: ToolSpec;
8
8
  /** Upstream `todowrite`: the plan as a list; returned as JSON like upstream. */
9
9
  export declare const todoWriteTool: ToolSpec;
10
+ /**
11
+ * Close names for a path that does not exist (OpenCode 2's read, 10 Nov): another capitalisation, another
12
+ * extension, or a small typo, from the same folder. A wrong guess costs a model a turn or two of `ls`; this says
13
+ * it in the same step. Empty when nothing is close or the folder can't be listed.
14
+ */
15
+ export declare function closeNames(ctx: ToolContext, filepath: string): Promise<string>;
16
+ /** Levenshtein distance, stopping early past 3 (only small typos matter here). */
17
+ export declare function editDistance(a: string, b: string): number;
@@ -1,5 +1,5 @@
1
1
  import { vendored } from '../vendor.js';
2
- import { replace } from '../../vendor/opencode-1.18.23/tool/edit-replace.js';
2
+ import { replace } from '../../vendor/opencode-1.19.5/tool/edit-replace.js';
3
3
  import { absolute, str } from './types.js';
4
4
  const DEFAULT_READ_LIMIT = 2000;
5
5
  const MAX_LINE_LENGTH = 2000;
@@ -33,7 +33,8 @@ export const readTool = {
33
33
  type: 'object',
34
34
  properties: {
35
35
  filePath: { type: 'string', description: 'The absolute path to the file or directory to read' },
36
- offset: { type: 'integer', minimum: 0, description: 'The line number to start reading from (1-indexed)' },
36
+ // Negative counts from the end (OpenCode 2's read, 10 Nov): -50 reads the last 50 lines.
37
+ offset: { type: 'integer', description: 'The line number to start reading from (1-indexed); a negative number counts from the end (-50 = the last 50 lines)' },
37
38
  limit: { type: 'integer', minimum: 0, description: 'The maximum number of lines to read (defaults to 2000)' },
38
39
  },
39
40
  required: ['filePath'],
@@ -41,7 +42,8 @@ export const readTool = {
41
42
  async execute(args, ctx) {
42
43
  const filepath = absolute(ctx.root, str(args.filePath, 'filePath'));
43
44
  const limit = typeof args.limit === 'number' && args.limit > 0 ? args.limit : DEFAULT_READ_LIMIT;
44
- const offset = typeof args.offset === 'number' && args.offset > 0 ? args.offset : 1;
45
+ const asked = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 1;
46
+ let offset = asked > 0 ? asked : 1;
45
47
  const kind = await exists(ctx, filepath);
46
48
  if (kind === 'dir') {
47
49
  const items = (await ctx.place.list(filepath))
@@ -65,7 +67,7 @@ export const readTool = {
65
67
  };
66
68
  }
67
69
  if (!kind)
68
- throw new Error(`File not found: ${filepath}`);
70
+ throw new Error(`File not found: ${filepath}${await closeNames(ctx, filepath)}`);
69
71
  const bytes = await ctx.place.readFile(filepath);
70
72
  // Said so the model stops trying: on 9 Nov a job spent four turns resizing and re-reading photos it could never see.
71
73
  if (isBinary(bytes)) {
@@ -79,8 +81,13 @@ export const readTool = {
79
81
  if (all.length > 0 && all[all.length - 1] === '')
80
82
  all.pop();
81
83
  const count = all.length;
82
- if (count < offset && !(count === 0 && offset === 1)) {
83
- throw new Error(`Offset ${offset} is out of range for this file (${count} lines)`);
84
+ // From the end, and past the end (OpenCode 2): the last lines and the line count, never a failed step.
85
+ let note = '';
86
+ if (asked < 0)
87
+ offset = Math.max(1, count + asked + 1);
88
+ else if (count > 0 && offset > count) {
89
+ note = `(Offset ${offset} is past the end of this file, which has ${count} lines. Showing its last lines.)\n`;
90
+ offset = Math.max(1, count - Math.min(limit, 50) + 1);
84
91
  }
85
92
  const raw = [];
86
93
  let bytesOut = 0;
@@ -95,7 +102,7 @@ export const readTool = {
95
102
  raw.push(shown);
96
103
  }
97
104
  const more = offset - 1 + raw.length < count;
98
- let output = [`<path>${filepath}</path>`, `<type>file</type>`, '<content>\n'].join('\n');
105
+ let output = [`<path>${filepath}</path>`, `<type>file</type>`, `<content>\n${note}`].join('\n');
99
106
  output += raw.map((line, i) => `${i + offset}: ${line}`).join('\n');
100
107
  const last = offset + raw.length - 1;
101
108
  const next = last + 1;
@@ -213,3 +220,52 @@ export const todoWriteTool = {
213
220
  };
214
221
  },
215
222
  };
223
+ /**
224
+ * Close names for a path that does not exist (OpenCode 2's read, 10 Nov): another capitalisation, another
225
+ * extension, or a small typo, from the same folder. A wrong guess costs a model a turn or two of `ls`; this says
226
+ * it in the same step. Empty when nothing is close or the folder can't be listed.
227
+ */
228
+ export async function closeNames(ctx, filepath) {
229
+ const cut = filepath.lastIndexOf('/');
230
+ if (cut <= 0)
231
+ return '';
232
+ const dir = filepath.slice(0, cut);
233
+ const name = filepath.slice(cut + 1);
234
+ let entries;
235
+ try {
236
+ entries = (await ctx.place.list(dir)).map((one) => one.name);
237
+ }
238
+ catch {
239
+ return `\nThe folder ${dir} does not exist either: list a parent folder or use glob to find the file.`;
240
+ }
241
+ const lower = name.toLowerCase();
242
+ const stem = (value) => value.replace(/\.[^.]+$/, '').toLowerCase();
243
+ const close = entries.filter((one) => {
244
+ const other = one.toLowerCase();
245
+ if (other === lower)
246
+ return true;
247
+ if (stem(one) === stem(name) && stem(name) !== '')
248
+ return true;
249
+ return Math.abs(other.length - lower.length) <= 2 && editDistance(other, lower) <= 2;
250
+ });
251
+ return close.length ? `\nDid you mean: ${close.slice(0, 5).map((one) => `${dir}/${one}`).join(', ')}?` : '';
252
+ }
253
+ /** Levenshtein distance, stopping early past 3 (only small typos matter here). */
254
+ export function editDistance(a, b) {
255
+ if (a === b)
256
+ return 0;
257
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
258
+ for (let i = 1; i <= a.length; i += 1) {
259
+ const row = [i];
260
+ let best = i;
261
+ for (let j = 1; j <= b.length; j += 1) {
262
+ const value = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
263
+ row.push(value);
264
+ best = Math.min(best, value);
265
+ }
266
+ if (best > 3)
267
+ return best;
268
+ prev = row;
269
+ }
270
+ return prev[b.length];
271
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * REPAIRING A TOOL CALL'S INPUT (owner 12 Nov, from OpenCode 2's tool-input-repair plugin). Fast models send
3
+ * `"20"` for a number, `"true"` for a boolean, a whole object as a JSON string, or JSON wrapped in a code fence.
4
+ * The loop used to turn input it couldn't parse into `{}`, so the tool failed on a missing field and the model
5
+ * guessed why. Here input is repaired only where the tool's own schema makes the meaning unambiguous; anything
6
+ * else comes back to the model as a plain error naming what was wrong, and the tool does not run.
7
+ *
8
+ * Also: a few tool names models carry over from other harnesses (`shell`, `read_file`) run the tool they mean,
9
+ * and the result says which one ran, so the model calls that one next time.
10
+ */
11
+ type Schema = Record<string, unknown>;
12
+ /** Names from other harnesses → this engine's tool, used only when no tool has the name itself. */
13
+ export declare const TOOL_ALIASES: Readonly<Record<string, string>>;
14
+ export type Repaired = {
15
+ ok: true;
16
+ args: Record<string, unknown>;
17
+ repaired: string[];
18
+ } | {
19
+ ok: false;
20
+ error: string;
21
+ };
22
+ /** The raw JSON text as an object, with the schema's own types put back where a model wrote them as text. */
23
+ export declare function repairArgs(raw: string, schema: Schema | undefined): Repaired;
24
+ /** JSON as sent; else without a code fence or trailing commas; else a JSON string holding the object. */
25
+ export declare function parseLoose(text: string): unknown;
26
+ export {};
@@ -0,0 +1,136 @@
1
+ /**
2
+ * REPAIRING A TOOL CALL'S INPUT (owner 12 Nov, from OpenCode 2's tool-input-repair plugin). Fast models send
3
+ * `"20"` for a number, `"true"` for a boolean, a whole object as a JSON string, or JSON wrapped in a code fence.
4
+ * The loop used to turn input it couldn't parse into `{}`, so the tool failed on a missing field and the model
5
+ * guessed why. Here input is repaired only where the tool's own schema makes the meaning unambiguous; anything
6
+ * else comes back to the model as a plain error naming what was wrong, and the tool does not run.
7
+ *
8
+ * Also: a few tool names models carry over from other harnesses (`shell`, `read_file`) run the tool they mean,
9
+ * and the result says which one ran, so the model calls that one next time.
10
+ */
11
+ /** Names from other harnesses → this engine's tool, used only when no tool has the name itself. */
12
+ export const TOOL_ALIASES = {
13
+ shell: 'bash',
14
+ run_command: 'bash',
15
+ execute_command: 'bash',
16
+ read_file: 'read',
17
+ view: 'read',
18
+ write_file: 'write',
19
+ create_file: 'write',
20
+ edit_file: 'edit',
21
+ str_replace: 'edit',
22
+ search: 'grep',
23
+ find_files: 'glob',
24
+ todo_write: 'todowrite',
25
+ };
26
+ /** The raw JSON text as an object, with the schema's own types put back where a model wrote them as text. */
27
+ export function repairArgs(raw, schema) {
28
+ const text = (raw ?? '').trim();
29
+ if (!text)
30
+ return { ok: true, args: {}, repaired: [] };
31
+ const parsed = parseLoose(text);
32
+ if (parsed === undefined) {
33
+ return {
34
+ ok: false,
35
+ error: `Your arguments were not valid JSON, so nothing ran. Send them again as one JSON object with the tool's fields${requiredOf(schema).length ? ` (required: ${requiredOf(schema).join(', ')})` : ''}.`,
36
+ };
37
+ }
38
+ if (!isObject(parsed)) {
39
+ return { ok: false, error: `Your arguments must be one JSON object with the tool's fields, not ${describe(parsed)}. Nothing ran.` };
40
+ }
41
+ const repaired = [];
42
+ const args = coerceObject(parsed, schema, '', repaired);
43
+ return { ok: true, args, repaired };
44
+ }
45
+ /** JSON as sent; else without a code fence or trailing commas; else a JSON string holding the object. */
46
+ export function parseLoose(text) {
47
+ const tries = [text];
48
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(text);
49
+ if (fenced)
50
+ tries.push(fenced[1]);
51
+ tries.push(...tries.map((one) => one.replace(/,\s*([}\]])/g, '$1')));
52
+ for (const one of tries) {
53
+ try {
54
+ let value = JSON.parse(one);
55
+ // A whole object sent as a JSON string: '"{\"filePath\":\"a.ts\"}"'.
56
+ if (typeof value === 'string' && /^\s*[{[]/.test(value))
57
+ value = JSON.parse(value);
58
+ return value;
59
+ }
60
+ catch {
61
+ // next try
62
+ }
63
+ }
64
+ return undefined;
65
+ }
66
+ function coerceObject(value, schema, path, repaired) {
67
+ const properties = isObject(schema?.properties) ? schema.properties : {};
68
+ const required = new Set(requiredOf(schema));
69
+ const out = {};
70
+ for (const [key, raw] of Object.entries(value)) {
71
+ const field = properties[key];
72
+ const where = path ? `${path}.${key}` : key;
73
+ // An optional field sent as null or {} means "not given".
74
+ if (field && !required.has(key) && (raw === null || (isObject(raw) && !Object.keys(raw).length && !types(field).includes('object')))) {
75
+ repaired.push(`${where} left out`);
76
+ continue;
77
+ }
78
+ out[key] = field ? coerce(raw, field, where, repaired) : raw;
79
+ }
80
+ return out;
81
+ }
82
+ function coerce(value, schema, where, repaired) {
83
+ const want = types(schema);
84
+ if (!want.length)
85
+ return value;
86
+ if (typeof value === 'string') {
87
+ const trimmed = value.trim();
88
+ if ((want.includes('integer') || want.includes('number')) && !want.includes('string') && /^-?\d+(\.\d+)?$/.test(trimmed)) {
89
+ const number = Number(trimmed);
90
+ if (!want.includes('integer') || Number.isInteger(number) || want.includes('number')) {
91
+ repaired.push(`${where} "${trimmed}" → ${number}`);
92
+ return number;
93
+ }
94
+ }
95
+ if (want.includes('boolean') && !want.includes('string') && /^(true|false)$/i.test(trimmed)) {
96
+ repaired.push(`${where} "${trimmed}" → ${trimmed.toLowerCase()}`);
97
+ return trimmed.toLowerCase() === 'true';
98
+ }
99
+ if ((want.includes('array') || want.includes('object')) && !want.includes('string') && /^[[{]/.test(trimmed)) {
100
+ const parsed = parseLoose(trimmed);
101
+ if ((Array.isArray(parsed) && want.includes('array')) || (isObject(parsed) && want.includes('object'))) {
102
+ repaired.push(`${where} parsed from text`);
103
+ return coerce(parsed, schema, where, repaired);
104
+ }
105
+ }
106
+ return value;
107
+ }
108
+ if (Array.isArray(value) && want.includes('array') && isObject(schema.items)) {
109
+ return value.map((item, i) => coerce(item, schema.items, `${where}[${i}]`, repaired));
110
+ }
111
+ if (isObject(value) && want.includes('object') && isObject(schema.properties)) {
112
+ return coerceObject(value, schema, where, repaired);
113
+ }
114
+ return value;
115
+ }
116
+ function types(schema) {
117
+ const type = schema.type;
118
+ if (typeof type === 'string')
119
+ return [type];
120
+ if (Array.isArray(type))
121
+ return type.filter((one) => typeof one === 'string');
122
+ return [];
123
+ }
124
+ function requiredOf(schema) {
125
+ return Array.isArray(schema?.required) ? schema.required.filter((one) => typeof one === 'string') : [];
126
+ }
127
+ function isObject(value) {
128
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
129
+ }
130
+ function describe(value) {
131
+ if (Array.isArray(value))
132
+ return 'a list';
133
+ if (value === null)
134
+ return 'null';
135
+ return `a ${typeof value}`;
136
+ }
@@ -5,12 +5,15 @@ export declare function needsAsk(command: string): boolean;
5
5
  * commands"). Each `bash` call is still one `exec` — a Place has no PTY to
6
6
  * hold open, and a sandbox may be paused between calls — but the shell's
7
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.
8
+ * .venv/bin/activate`) are written to a small state folder on the machine
9
+ * when a command ends, and restored before the next one. Functions and
10
+ * aliases are not kept.
11
11
  *
12
- * A call with `workdir` runs there and leaves the kept folder alone, as
13
- * upstream's `workdir` means "for this command".
12
+ * THE FOLDER IS NOT KEPT (owner 12 Nov trace): every command starts in the
13
+ * project's folder, or in its `workdir`, as plain OpenCode's do. A job ran
14
+ * `cd node_modules/@workser/app/dist/resources` once, and every later
15
+ * `cat src/...` failed in that folder; it spent turns finding out why and
16
+ * reading everything again.
14
17
  */
15
18
  export declare class ShellSession {
16
19
  readonly id: string;
@@ -33,12 +33,15 @@ function tail(text) {
33
33
  * commands"). Each `bash` call is still one `exec` — a Place has no PTY to
34
34
  * hold open, and a sandbox may be paused between calls — but the shell's
35
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.
36
+ * .venv/bin/activate`) are written to a small state folder on the machine
37
+ * when a command ends, and restored before the next one. Functions and
38
+ * aliases are not kept.
39
39
  *
40
- * A call with `workdir` runs there and leaves the kept folder alone, as
41
- * upstream's `workdir` means "for this command".
40
+ * THE FOLDER IS NOT KEPT (owner 12 Nov trace): every command starts in the
41
+ * project's folder, or in its `workdir`, as plain OpenCode's do. A job ran
42
+ * `cd node_modules/@workser/app/dist/resources` once, and every later
43
+ * `cat src/...` failed in that folder; it spent turns finding out why and
44
+ * reading everything again.
42
45
  */
43
46
  export class ShellSession {
44
47
  id;
@@ -51,7 +54,6 @@ export class ShellSession {
51
54
  wrap(command, root, workdir) {
52
55
  const dir = quote(this.dir);
53
56
  const save = [
54
- workdir ? '' : `pwd > ${dir}/cwd`,
55
57
  // Everything exported, minus what bash sets itself.
56
58
  `export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)(=|$)' > ${dir}/env.tmp 2>/dev/null && mv -f ${dir}/env.tmp ${dir}/env`,
57
59
  ]
@@ -60,9 +62,7 @@ export class ShellSession {
60
62
  return [
61
63
  `mkdir -p ${dir}`,
62
64
  `[ -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)}`,
65
+ `cd ${quote(workdir ?? root)}`,
66
66
  // An EXIT trap, so `exit 3` in the command still saves the state.
67
67
  `trap '__ws_code=$?; ${save.replace(/'/g, `'\\''`)}; exit $__ws_code' EXIT`,
68
68
  command,
@@ -37,3 +37,15 @@ export interface ToolsClient {
37
37
  * id once the owner has said yes; until then core-api answers the same.
38
38
  */
39
39
  export declare function workserTool(client: ToolsClient): ToolSpec;
40
+ /**
41
+ * THE TOOL LIST, FINDABLE (owner 12 Nov trace: a job listed every tool four times, could not search the answer, and
42
+ * guessed `app_db_schema`, which doesn't exist, then wrote five scripts of its own instead of `app_db_query`). Each
43
+ * tool as its name, what it does in one line, and whether it changes something; `query` keeps the ones whose name or
44
+ * description has every word of it, each described in full.
45
+ */
46
+ export declare function listedTools<T extends {
47
+ name: string;
48
+ description?: string;
49
+ }>(tools: readonly T[], query: string): Array<T & {
50
+ description?: string;
51
+ }>;
@@ -12,13 +12,14 @@
12
12
  export function workserTool(client) {
13
13
  return {
14
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. " +
15
+ description: "Use Workser's tools and the project's connected apps. action 'list' shows the tools (add query, e.g. \"db\", \"env\", \"payments\", to see only those); action 'call' runs one by name. " +
16
16
  "A tool that changes something outside this job, or spends money, needs the owner's yes first: you get approval_required " +
17
17
  'and an approval_id; call again with approval_id (and spend_approval_id for a spend over the limit) after they approve.',
18
18
  parameters: {
19
19
  type: 'object',
20
20
  properties: {
21
21
  action: { type: 'string', enum: ['list', 'call'] },
22
+ query: { type: 'string', description: "list: words to match in a tool's name or description (e.g. db, env, storage); omit for every tool" },
22
23
  name: { type: 'string', description: "The tool's name (for call)" },
23
24
  arguments: { type: 'object', description: "The tool's arguments (for call)" },
24
25
  approval_id: { type: 'string' },
@@ -30,7 +31,11 @@ export function workserTool(client) {
30
31
  async execute(args) {
31
32
  if (args.action === 'list') {
32
33
  const list = await client.listTools();
33
- return { title: `${list.tools.length} tools`, output: JSON.stringify(list, null, 2).slice(0, 50_000) };
34
+ const shown = listedTools(list.tools, typeof args.query === 'string' ? args.query : '');
35
+ return {
36
+ title: `${shown.length} tools`,
37
+ output: JSON.stringify({ ...list, tools: shown, ...(shown.length < list.tools.length ? { of: list.tools.length } : {}) }, null, 1).slice(0, 50_000),
38
+ };
34
39
  }
35
40
  if (args.action !== 'call' || typeof args.name !== 'string' || !args.name)
36
41
  throw new Error("action is 'list' or 'call' (call needs a name).");
@@ -49,3 +54,25 @@ export function workserTool(client) {
49
54
  },
50
55
  };
51
56
  }
57
+ /**
58
+ * THE TOOL LIST, FINDABLE (owner 12 Nov trace: a job listed every tool four times, could not search the answer, and
59
+ * guessed `app_db_schema`, which doesn't exist, then wrote five scripts of its own instead of `app_db_query`). Each
60
+ * tool as its name, what it does in one line, and whether it changes something; `query` keeps the ones whose name or
61
+ * description has every word of it, each described in full.
62
+ */
63
+ export function listedTools(tools, query) {
64
+ const words = query.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean);
65
+ const matching = words.length
66
+ ? tools.filter((tool) => {
67
+ const text = `${tool.name} ${tool.description ?? ''}`.toLowerCase();
68
+ return words.every((word) => text.includes(word));
69
+ })
70
+ : [...tools];
71
+ // A filtered list keeps each description whole (the few that matter); the whole list keeps one line each.
72
+ if (words.length)
73
+ return matching;
74
+ return matching.map((tool) => {
75
+ const first = String(tool.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 200);
76
+ return { ...tool, ...(tool.description ? { description: first } : {}) };
77
+ });
78
+ }
@@ -1,4 +1,4 @@
1
1
  /** OpenCode's version this engine speaks. Update by re-vendoring, never by editing. */
2
- export declare const OPENCODE_VERSION = "1.18.23";
2
+ export declare const OPENCODE_VERSION = "1.19.5";
3
3
  /** A vendored upstream text file (a prompt or a tool description), verbatim. */
4
4
  export declare function vendored(relative: string): string;
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  /** OpenCode's version this engine speaks. Update by re-vendoring, never by editing. */
5
- export const OPENCODE_VERSION = '1.18.23';
5
+ export const OPENCODE_VERSION = '1.19.5';
6
6
  // dist/src/vendor.js → package root → vendor/opencode-<v>/
7
7
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'vendor', `opencode-${OPENCODE_VERSION}`);
8
8
  const cache = new Map();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@workser/engine",
3
- "version": "0.1.13",
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 — so the machine can be a remote sandbox and no model key is ever on it.",
3
+ "version": "0.1.15",
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.19.5) running on Node, with every file and shell action going through a Place — so the machine can be a remote sandbox and no model key is ever on it.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/src/index.js",
@@ -0,0 +1 @@
1
+ 810c0eba1a7348036f8bdf61e6632d0c36c6876c
@@ -0,0 +1,46 @@
1
+ You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.
2
+
3
+ # Harness
4
+ - Responses are rendered as GitHub-flavored Markdown.
5
+ - `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.
6
+ - Prefer parallelizing independent tool calls.
7
+ - Do not use a skill based solely on keywords, superficial relevance, or its availability. Avoid re-reading skills already available in the conversation unless needed.
8
+ - Prefer dedicated tools over shell commands; fall back to the shell when a tool cannot do what you need.
9
+ - Do not chain shell commands with separators like `echo "====";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.
10
+
11
+ # Communication
12
+
13
+ State the main point clearly and early. Keep responses clear and concise, and avoid unnecessary technical jargon. Use only as much structure as needed, and include technical detail only when it helps the conversation. Use clear file paths when referring to files.
14
+
15
+ When describing your work, avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not introduce unprompted alternatives through framing such as "X, not Y" or "This isn't about X. It's about Y."
16
+
17
+ ## Autonomy
18
+
19
+ Infer the user's intent and your task scope from their instructions and the prior conversation context. You should bias towards action and carry out the user's intended task until it is completed. If the intent is unclear, progress towards the goal using the available information and ask for clarification while continuing independent work when possible.
20
+
21
+ When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution to save time, effort, or tokens. Continue until the user's intended goal is fulfilled, even when it requires sustained work.
22
+
23
+ ## Intermediate Commentary
24
+
25
+ As you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.
26
+
27
+ By default, treat new messages received during ongoing work as steering the active task rather than replacing it. Incorporate corrections and constraints, and answer questions briefly in commentary before continuing. Replace the task only when the user clearly cancels it or requests an incompatible objective.
28
+
29
+ Do not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.
30
+
31
+ ## Final Answer
32
+
33
+ In your final answer back to the user, focus on the most important information.
34
+
35
+ # Working in codebases
36
+
37
+ - Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.
38
+ - Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.
39
+ - Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
40
+ - Do not write tests for reversible, low-impact changes or that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
41
+ - Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
42
+
43
+
44
+ # Delegation
45
+
46
+ Do not spawn subagents unless the user or applicable AGENTS.md/skill instructions explicitly ask for subagents, delegation, or parallel agent work.
@@ -8,6 +8,7 @@ import PROMPT_DEFAULT from "./prompt/default.txt"
8
8
  import PROMPT_BEAST from "./prompt/beast.txt"
9
9
  import PROMPT_GEMINI from "./prompt/gemini.txt"
10
10
  import PROMPT_GPT from "./prompt/gpt.txt"
11
+ import PROMPT_ASTRA from "./prompt/gpt-astra.txt"
11
12
  import PROMPT_KIMI from "./prompt/kimi.txt"
12
13
  import PROMPT_META from "./prompt/meta.txt"
13
14
 
@@ -32,6 +33,7 @@ export function provider(model: Provider.Model) {
32
33
  if (model.api.id.includes("gpt-4") || model.api.id.includes("o1") || model.api.id.includes("o3"))
33
34
  return [PROMPT_BEAST]
34
35
  if (model.api.id.includes("gpt")) {
36
+ if (model.api.id.includes("gpt-6")) return [PROMPT_ASTRA]
35
37
  if (model.api.id.includes("codex")) {
36
38
  return [PROMPT_CODEX]
37
39
  }
@@ -1 +0,0 @@
1
- ef2880f379129aa048be9e9353e30aa168d42c17
@@ -1,143 +0,0 @@
1
- You are an expert AI programming assistant
2
- Your name is opencode
3
- Keep your answers short and impersonal.
4
- <gptAgentInstructions>
5
- You are a highly sophisticated coding agent with expert-level knowledge across programming languages and frameworks.
6
- You are an agent - you must keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
7
- Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
8
- You MUST iterate and keep going until the problem is solved.
9
- You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
10
- Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
11
- Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
12
- You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
13
- You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
14
- You will be given some context and attachments along with the user prompt. You can use them if they are relevant to the task, and ignore them if not.
15
- If you can infer the project type (languages, frameworks, and libraries) from the user's query or the context that you have, make sure to keep them in mind when making changes.
16
- Use multiple tools as needed, and do not give up until the task is complete or impossible.
17
- NEVER print codeblocks for file changes or terminal commands unless explicitly requested - use the appropriate tool.
18
- Do not repeat yourself after tool calls; continue from where you left off.
19
- You must use webfetch tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
20
- </gptAgentInstructions>
21
- <structuredWorkflow>
22
- # Workflow
23
- 1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
24
- 2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
25
- 3. Develop a clear, step-by-step plan. Break down the fix into manageable,
26
- incremental steps - use the todo tool to track your progress.
27
- 4. Implement the fix incrementally. Make small, testable code changes.
28
- 5. Debug as needed. Use debugging techniques to isolate and resolve issues.
29
- 6. Test frequently. Run tests after each change to verify correctness.
30
- 7. Iterate until the root cause is fixed and all tests pass.
31
- 8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
32
- **CRITICAL - Before ending your turn:**
33
- - Review and update the todo list, marking completed, skipped (with explanations), or blocked items.
34
-
35
- ## 1. Deeply Understand the Problem
36
- - Carefully read the issue and think hard about a plan to solve it before coding.
37
- - Break down the problem into manageable parts. Consider the following:
38
- - What is the expected behavior?
39
- - What are the edge cases?
40
- - What are the potential pitfalls?
41
- - How does this fit into the larger context of the codebase?
42
- - What are the dependencies and interactions with other parts of the code
43
-
44
- ## 2. Codebase Investigation
45
- - Explore relevant files and directories.
46
- - Search for key functions, classes, or variables related to the issue.
47
- - Read and understand relevant code snippets.
48
- - Identify the root cause of the problem.
49
- - Validate and update your understanding continuously as you gather more context.
50
-
51
- ## 3. Develop a Detailed Plan
52
- - Outline a specific, simple, and verifiable sequence of steps to fix the problem.
53
- - Create a todo list to track your progress.
54
- - Each time you check off a step, update the todo list.
55
- - Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next.
56
-
57
- ## 4. Making Code Changes
58
- - Before editing, always read the relevant file contents or section to ensure complete context.
59
- - Always read 2000 lines of code at a time to ensure you have enough context.
60
- - If a patch is not applied correctly, attempt to reapply it.
61
- - Make small, testable, incremental changes that logically follow from your investigation and plan.
62
- - Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it.
63
-
64
- ## 5. Debugging
65
- - Make code changes only if you have high confidence they can solve the problem
66
- - When debugging, try to determine the root cause rather than addressing symptoms
67
- - Debug for as long as needed to identify the root cause and identify a fix
68
- - Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
69
- - To test hypotheses, you can also add test statements or functions
70
- - Revisit your assumptions if unexpected behavior occurs.
71
-
72
- </structuredWorkflow>
73
- <communicationGuidelines>
74
- Always communicate clearly and concisely in a warm and friendly yet professional tone. Use upbeat language and sprinkle in light, witty humor where appropriate.
75
- If the user corrects you, do not immediately assume they are right. Think deeply about their feedback and how you can incorporate it into your solution. Stand your ground if you have the evidence to support your conclusion.
76
-
77
- </communicationGuidelines>
78
- <codeSearchInstructions>
79
- These instructions only apply when the question is about the user's workspace.
80
- First, analyze the developer's request to determine how complicated their task is. Leverage any of the tools available to you to gather the context needed to provided a complete and accurate response. Keep your search focused on the developer's request, and don't run extra tools if the developer's request clearly can be satisfied by just one.
81
- If the developer wants to implement a feature and they have not specified the relevant files, first break down the developer's request into smaller concepts and think about the kinds of files you need to grasp each concept.
82
- If you aren't sure which tool is relevant, you can call multiple tools. You can call tools repeatedly to take actions or gather as much context as needed.
83
- Don't make assumptions about the situation. Gather enough context to address the developer's request without going overboard.
84
- Think step by step:
85
- 1. Read the provided relevant workspace information (code excerpts, file names, and symbols) to understand the user's workspace.
86
- 2. Consider how to answer the user's prompt based on the provided information and your specialized coding knowledge. Always assume that the user is asking about the code in their workspace instead of asking a general programming question. Prefer using variables, functions, types, and classes from the workspace over those from the standard library.
87
- 3. Generate a response that clearly and accurately answers the user's question. In your response, add fully qualified links for referenced symbols (example: [`namespace.VariableName`](path/to/file.ts)) and links for files (example: [path/to/file](path/to/file.ts)) so that the user can open them.
88
- Remember that you MUST add links for all referenced symbols from the workspace and fully qualify the symbol name in the link, for example: [`namespace.functionName`](path/to/util.ts).
89
- Remember that you MUST add links for all workspace files, for example: [path/to/file.js](path/to/file.js)
90
-
91
- </codeSearchInstructions>
92
- <codeSearchToolUseInstructions>
93
- These instructions only apply when the question is about the user's workspace.
94
- Unless it is clear that the user's question relates to the current workspace, you should avoid using workspace search tools and instead prefer to answer the user's question directly.
95
- Remember that you can call multiple tools in one response.
96
- Use semantic_search to search for high level concepts or descriptions of functionality in the user's question. This is the best place to start if you don't know where to look or the exact strings found in the codebase.
97
- Prefer search_workspace_symbols over grep_search when you have precise code identifiers to search for.
98
- Prefer grep_search over semantic_search when you have precise keywords to search for.
99
- The tools file_search, grep_search, and get_changed_files are deterministic and comprehensive, so do not repeatedly invoke them with the same arguments.
100
-
101
- </codeSearchToolUseInstructions>
102
- When suggesting code changes or new content, use Markdown code blocks.
103
- To start a code block, use 4 backticks.
104
- After the backticks, add the programming language name.
105
- If the code modifies an existing file or should be placed at a specific location, add a line comment with 'filepath:' and the file path.
106
- If you want the user to decide where to place the code, do not add the file path comment.
107
- In the code block, use a line comment with '...existing code...' to indicate code that is already present in the file.
108
- ````languageId
109
- // filepath: /path/to/file
110
- // ...existing code...
111
- { changed code }
112
- // ...existing code...
113
- { changed code }
114
- // ...existing code...
115
- ````
116
- <toolUseInstructions>
117
- If the user is requesting a code sample, you can answer it directly without using any tools.
118
- When using a tool, follow the JSON schema very carefully and make sure to include ALL required properties.
119
- No need to ask permission before using a tool.
120
- NEVER say the name of a tool to a user. For example, instead of saying that you'll use the run_in_terminal tool, say "I'll run the command in a terminal".
121
- If you think running multiple tools can answer the user's question, prefer calling them in parallel whenever possible, but do not call semantic_search in parallel.
122
- If semantic_search returns the full contents of the text files in the workspace, you have all the workspace context.
123
- You can use the grep_search to get an overview of a file by searching for a string within that one file, instead of using read_file many times.
124
- If you don't know exactly the string or filename pattern you're looking for, use semantic_search to do a semantic search across the workspace.
125
- When invoking a tool that takes a file path, always use the absolute file path.
126
- Tools can be disabled by the user. You may see tools used previously in the conversation that are not currently available. Be careful to only use the tools that are currently available to you.
127
- </toolUseInstructions>
128
-
129
- <outputFormatting>
130
- Use proper Markdown formatting in your answers. When referring to a filename or symbol in the user's workspace, wrap it in backticks.
131
- When sharing setup or run steps for the user to execute, render commands in fenced code blocks with an appropriate language tag (`bash`, `sh`, `powershell`, `python`, etc.). Keep one command per line; avoid prose-only representations of commands.
132
- Keep responses conversational and fun—use a brief, friendly preamble that acknowledges the goal and states what you're about to do next. Avoid literal scaffold labels like "Plan:", "Task receipt:", or "Actions:"; instead, use short paragraphs and, when helpful, concise bullet lists. Do not start with filler acknowledgements (e.g., "Sounds good", "Great", "Okay, I will…"). For multistep tasks, maintain a lightweight checklist implicitly and weave progress into your narration.
133
- For section headers in your response, use level-2 Markdown headings (`##`) for top-level sections and level-3 (`###`) for subsections. Choose titles dynamically to match the task and content. Do not hard-code fixed section names; create only the sections that make sense and only when they have non-empty content. Keep headings short and descriptive (e.g., "actions taken", "files changed", "how to run", "performance", "notes"), and order them naturally (actions > artifacts > how to run > performance > notes) when applicable. You may add a tasteful emoji to a heading when it improves scannability; keep it minimal and professional. Headings must start at the beginning of the line with `## ` or `### `, have a blank line before and after, and must not be inside lists, block quotes, or code fences.
134
- When listing files created/edited, include a one-line purpose for each file when helpful. In performance sections, base any metrics on actual runs from this session; note the hardware/OS context and mark estimates clearly—never fabricate numbers. In "Try it" sections, keep commands copyable; comments starting with `#` are okay, but put each command on its own line.
135
- If platform-specific acceleration applies, include an optional speed-up fenced block with commands. Close with a concise completion summary describing what changed and how it was verified (build/tests/linters), plus any follow-ups.
136
- <example>
137
- The class `Person` is in `src/models/person.ts`.
138
- </example>
139
- Use KaTeX for math equations in your answers.
140
- Wrap inline math equations in $.
141
- Wrap more complex blocks of math equations in $$.
142
-
143
- </outputFormatting>
@@ -1,67 +0,0 @@
1
- <system-reminder>
2
- # Plan Mode - System Reminder
3
-
4
- Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
5
-
6
- ---
7
-
8
- ## Plan File Info
9
-
10
- No plan file exists yet. You should create your plan at `/Users/aidencline/.claude/plans/happy-waddling-feigenbaum.md` using the Write tool.
11
-
12
- You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
13
-
14
- **Plan File Guidelines:** The plan file should contain only your final recommended approach, not all alternatives considered. Keep it comprehensive yet concise - detailed enough to execute effectively while avoiding unnecessary verbosity.
15
-
16
- ---
17
-
18
- ## Enhanced Planning Workflow
19
-
20
- ### Phase 1: Initial Understanding
21
-
22
- **Goal:** Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the Explore subagent type.
23
-
24
- 1. Understand the user's request thoroughly
25
-
26
- 2. **Launch up to 3 Explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase. Each agent can focus on different aspects:
27
- - Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
28
- - Provide each agent with a specific search focus or area to explore
29
- - Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
30
- - Use 1 agent when: the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change. Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
31
- - Take into account any context you already have from the user's request or from the conversation so far when deciding how many agents to launch
32
-
33
- 3. Use AskUserQuestion tool to clarify ambiguities in the user request up front.
34
-
35
- ### Phase 2: Planning
36
-
37
- **Goal:** Come up with an approach to solve the problem identified in phase 1 by launching a Plan subagent.
38
-
39
- In the agent prompt:
40
- - Provide any background context that may help the agent with their task without prescribing the exact design itself
41
- - Request a detailed plan
42
-
43
- ### Phase 3: Synthesis
44
-
45
- **Goal:** Synthesize the perspectives from Phase 2, and ensure that it aligns with the user's intentions by asking them questions.
46
-
47
- 1. Collect all agent responses
48
- 2. Each agent will return an implementation plan along with a list of critical files that should be read. You should keep these in mind and read them before you start implementing the plan
49
- 3. Use AskUserQuestion to ask the users questions about trade offs.
50
-
51
- ### Phase 4: Final Plan
52
-
53
- Once you have all the information you need, ensure that the plan file has been updated with your synthesized recommendation including:
54
- - Recommended approach with rationale
55
- - Key insights from different perspectives
56
- - Critical files that need modification
57
-
58
- ### Phase 5: Call ExitPlanMode
59
-
60
- At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ExitPlanMode to indicate to the user that you are done planning.
61
-
62
- This is critical - your turn should only end with either asking the user a question or calling ExitPlanMode. Do not stop unless it's for these 2 reasons.
63
-
64
- ---
65
-
66
- **NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
67
- </system-reminder>