@bubblebrain-ai/bubble 0.0.5 → 0.0.6

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 (38) hide show
  1. package/dist/agent/task-size.d.ts +9 -0
  2. package/dist/agent/task-size.js +33 -0
  3. package/dist/agent/tool-intent.d.ts +1 -0
  4. package/dist/agent/tool-intent.js +1 -1
  5. package/dist/agent.js +46 -2
  6. package/dist/orchestrator/default-hooks.js +80 -69
  7. package/dist/orchestrator/hooks.d.ts +5 -8
  8. package/dist/prompt/compose.js +3 -0
  9. package/dist/prompt/environment.js +2 -0
  10. package/dist/prompt/provider-prompts/deepseek.js +1 -2
  11. package/dist/prompt/provider-prompts/kimi.js +1 -2
  12. package/dist/prompt/reminders.d.ts +20 -3
  13. package/dist/prompt/reminders.js +43 -17
  14. package/dist/prompt/runtime.js +17 -23
  15. package/dist/provider.d.ts +10 -1
  16. package/dist/provider.js +87 -34
  17. package/dist/tools/bash.d.ts +2 -1
  18. package/dist/tools/bash.js +1 -1
  19. package/dist/tools/edit-apply.js +37 -6
  20. package/dist/tools/edit.d.ts +2 -1
  21. package/dist/tools/edit.js +18 -6
  22. package/dist/tools/file-state.d.ts +25 -0
  23. package/dist/tools/file-state.js +52 -0
  24. package/dist/tools/index.d.ts +2 -0
  25. package/dist/tools/index.js +6 -4
  26. package/dist/tools/read.d.ts +2 -1
  27. package/dist/tools/read.js +5 -1
  28. package/dist/tools/write.d.ts +4 -3
  29. package/dist/tools/write.js +133 -54
  30. package/dist/tui/display-history.d.ts +2 -0
  31. package/dist/tui/run.js +115 -23
  32. package/dist/tui/streaming-tool-args.d.ts +15 -0
  33. package/dist/tui/streaming-tool-args.js +30 -0
  34. package/dist/tui/tool-renderers/write-preview.d.ts +1 -1
  35. package/dist/tui/tool-renderers/write-preview.js +9 -1
  36. package/dist/tui/tool-renderers/write.js +13 -7
  37. package/dist/types.d.ts +15 -0
  38. package/package.json +1 -1
@@ -0,0 +1,9 @@
1
+ import type { ContentPart } from "../types.js";
2
+ /**
3
+ * Coarse "is this a small / focused task" classifier. Used to inject a hint
4
+ * that suppresses the default exploration-first protocol when the user's
5
+ * request is clearly a one-shot create or single-file tweak. Counterpart to
6
+ * `task-classifier.ts` which categorizes by *kind*, not *size*.
7
+ */
8
+ export type TaskSize = "small" | "normal";
9
+ export declare function classifyTaskSize(input: string | ContentPart[]): TaskSize;
@@ -0,0 +1,33 @@
1
+ // Two-part match: a "create" verb AND a "deliverable" noun in the same
2
+ // sentence is a strong signal of a focused, one-shot task.
3
+ const SMALL_TASK_VERBS = [
4
+ /\b(write|create|generate|make|draft|build|add)\b/i,
5
+ /帮我写|帮我创建|帮我生成|写(个|一个|一份)|新建一个|做(个|一个|一份)|生成(个|一个|一份)|搞(个|一个|一份)/i,
6
+ ];
7
+ const SMALL_TASK_NOUNS = [
8
+ /\b(file|page|component|script|snippet|function|class|test|html|css|js|ts|tsx|jsx|md|markdown|hello world)\b/i,
9
+ /(文件|页面|组件|脚本|片段|函数|类|测试|html|css|介绍|文章|页|说明|示例|demo)/i,
10
+ ];
11
+ function matchesSmallTaskPattern(text) {
12
+ return SMALL_TASK_VERBS.some((re) => re.test(text))
13
+ && SMALL_TASK_NOUNS.some((re) => re.test(text));
14
+ }
15
+ const LARGE_TASK_NEGATIONS = [
16
+ /\b(refactor|rewrite|migrate|overhaul|integrate|architect|review the codebase|whole project|across the codebase)\b/i,
17
+ /多个|批量|全部|所有|整个项目|整个仓库|架构|重构|端到端|跨模块/i,
18
+ ];
19
+ export function classifyTaskSize(input) {
20
+ const text = (typeof input === "string"
21
+ ? input
22
+ : input
23
+ .filter((part) => part.type === "text")
24
+ .map((part) => part.text)
25
+ .join("\n")).trim();
26
+ if (!text)
27
+ return "normal";
28
+ // Up to ~120 chars with a small-task verb+noun match and no negation: small.
29
+ if (text.length <= 120 && matchesSmallTaskPattern(text)) {
30
+ return LARGE_TASK_NEGATIONS.some((re) => re.test(text)) ? "normal" : "small";
31
+ }
32
+ return "normal";
33
+ }
@@ -32,3 +32,4 @@ export interface ParsedReadCommand {
32
32
  }
33
33
  export declare function parseSearchBashCommand(command: string): ParsedSearchCommand | undefined;
34
34
  export declare function parseReadBashCommand(command: string): ParsedReadCommand | undefined;
35
+ export declare function shellSplit(command: string): string[];
@@ -256,7 +256,7 @@ function parseLineCount(value) {
256
256
  const parsed = Number(value.replace(/^\+/, ""));
257
257
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
258
258
  }
259
- function shellSplit(command) {
259
+ export function shellSplit(command) {
260
260
  const tokens = [];
261
261
  let current = "";
262
262
  let quote = null;
package/dist/agent.js CHANGED
@@ -338,6 +338,9 @@ export class Agent {
338
338
  if (chunk.argumentsFull !== undefined) {
339
339
  currentToolCall.args = chunk.argumentsFull;
340
340
  }
341
+ if (chunk.argumentsCorrupt) {
342
+ currentToolCall.argsCorrupt = true;
343
+ }
341
344
  if (chunk.arguments) {
342
345
  yield {
343
346
  type: "tool_call_delta",
@@ -353,6 +356,7 @@ export class Agent {
353
356
  id: currentToolCall.id,
354
357
  name: currentToolCall.name,
355
358
  arguments: currentToolCall.args,
359
+ ...(currentToolCall.argsCorrupt ? { argsCorrupt: true } : {}),
356
360
  });
357
361
  yield {
358
362
  type: "tool_call_end",
@@ -405,10 +409,14 @@ export class Agent {
405
409
  for (let index = 0; index < assistantMsg.toolCalls.length; index++) {
406
410
  const tc = assistantMsg.toolCalls[index];
407
411
  try {
408
- parsedCalls.push({ ...tc, parsedArgs: JSON.parse(tc.arguments) });
412
+ parsedCalls.push({
413
+ ...tc,
414
+ parsedArgs: JSON.parse(tc.arguments),
415
+ ...(tc.argsCorrupt ? { argsCorrupt: true } : {}),
416
+ });
409
417
  }
410
418
  catch {
411
- parsedCalls.push({ ...tc, parsedArgs: {} });
419
+ parsedCalls.push({ ...tc, parsedArgs: {}, argsCorrupt: true });
412
420
  }
413
421
  }
414
422
  const executedResults = [];
@@ -1084,6 +1092,25 @@ export class Agent {
1084
1092
  isError: true,
1085
1093
  };
1086
1094
  }
1095
+ if (toolCall.argsCorrupt) {
1096
+ return {
1097
+ content: `Error: The arguments for "${toolCall.name}" failed to parse as JSON, indicating the tool call was truncated or malformed mid-stream. ` +
1098
+ `Re-issue the call with valid JSON arguments; do not assume the previous attempt ran.`,
1099
+ isError: true,
1100
+ status: "blocked",
1101
+ metadata: { kind: "security", reason: "args_corrupt" },
1102
+ };
1103
+ }
1104
+ const missingRequired = findMissingRequiredArgs(tool.parameters, toolCall.parsedArgs);
1105
+ if (missingRequired.length > 0) {
1106
+ return {
1107
+ content: `Error: Tool "${toolCall.name}" was called without required argument${missingRequired.length === 1 ? "" : "s"}: ${missingRequired.map((name) => `"${name}"`).join(", ")}. ` +
1108
+ `Re-issue the call with all required fields filled. Do not assume the previous attempt ran with default values.`,
1109
+ isError: true,
1110
+ status: "blocked",
1111
+ metadata: { kind: "security", reason: "missing_required_args", missing: missingRequired },
1112
+ };
1113
+ }
1087
1114
  try {
1088
1115
  return await tool.execute(toolCall.parsedArgs, {
1089
1116
  cwd,
@@ -1102,6 +1129,23 @@ export class Agent {
1102
1129
  }
1103
1130
  }
1104
1131
  }
1132
+ function findMissingRequiredArgs(schema, args) {
1133
+ const required = schema?.required;
1134
+ if (!required || required.length === 0)
1135
+ return [];
1136
+ const missing = [];
1137
+ for (const name of required) {
1138
+ const value = args ? args[name] : undefined;
1139
+ // Empty strings/arrays are intentionally allowed — writing an empty file
1140
+ // or passing an empty list can be legitimate. Only undefined/null counts
1141
+ // as "missing", because the observed failure mode is `finalArgs: "{}"`
1142
+ // where the field is entirely absent.
1143
+ if (value === undefined || value === null) {
1144
+ missing.push(name);
1145
+ }
1146
+ }
1147
+ return missing;
1148
+ }
1105
1149
  function estimateResidentChars(messages) {
1106
1150
  let total = 0;
1107
1151
  for (const message of messages) {
@@ -1,8 +1,9 @@
1
1
  import { classifyTask } from "../agent/task-classifier.js";
2
+ import { classifyTaskSize } from "../agent/task-size.js";
2
3
  import { EvidenceTracker } from "../agent/evidence-tracker.js";
3
4
  import { ExecutionGovernor } from "../agent/execution-governor.js";
4
5
  import { arbitrateToolCall } from "../agent/tool-arbiter.js";
5
- import { buildFinalizeOpportunityReminder, buildTaskSummaryReminder, buildVerificationFailureReminder, buildVerificationReminder, buildWorkflowPhaseReminder, } from "../prompt/reminders.js";
6
+ import { buildEditRetryEscalationReminder, buildRedundantReadReminder, buildSmallTaskHint, buildTaskSummaryReminder, buildWorkflowPhaseReminder, } from "../prompt/reminders.js";
6
7
  import { reminderForTaskType } from "../prompt/task-reminders.js";
7
8
  import { formatCoverageSummary, resolveWorkflowPhase } from "./workflow.js";
8
9
  export function createDefaultHooks() {
@@ -16,6 +17,13 @@ export function createDefaultHooks() {
16
17
  if (taskReminder) {
17
18
  ctx.queueReminder(taskReminder);
18
19
  }
20
+ // Small-task hint: counterweight to the default protocol's exploration
21
+ // bias, only fires once per run on focused one-shot requests like
22
+ // "写个 HTML 介绍元旦". Don't issue for the same input twice.
23
+ if (!ctx.state.smallTaskHintSent && classifyTaskSize(ctx.input) === "small") {
24
+ ctx.state.smallTaskHintSent = true;
25
+ ctx.queueReminder(buildSmallTaskHint());
26
+ }
19
27
  if (taskType === "security_investigation") {
20
28
  ctx.state.evidenceTracker = new EvidenceTracker();
21
29
  ctx.state.workflowPhase = "investigate";
@@ -75,21 +83,58 @@ export function createDefaultHooks() {
75
83
  }
76
84
  ctx.state.evidenceTracker?.observe(ctx.toolCall, ctx.result);
77
85
  ctx.state.governor?.afterToolResult(ctx.toolCall, ctx.result);
78
- if (isCodeWriteResult(ctx.toolCall, ctx.result)) {
79
- markCodeChanged(ctx.state);
80
- }
81
- else if (ctx.state.codeChanged && isVerificationAttempt(ctx.toolCall, ctx.result)) {
82
- ctx.state.verificationAttempted = true;
83
- if (isSuccessfulToolResult(ctx.result)) {
84
- ctx.state.verificationCompleted = true;
85
- ctx.state.verificationFailed = false;
86
+ // Edit/write retry-escalation: if the same tool with the same args
87
+ // failed twice in a row, models — especially thinking-heavy ones —
88
+ // can spiral on "identical content" / "not found" errors. Nudge them
89
+ // to change strategy.
90
+ if ((ctx.toolCall.name === "edit" || ctx.toolCall.name === "write") && ctx.result.isError) {
91
+ const hash = hashEditCall(ctx.toolCall);
92
+ const history = ctx.state.recentEditFailures ?? (ctx.state.recentEditFailures = []);
93
+ history.push(hash);
94
+ // Keep last 4 entries.
95
+ if (history.length > 4)
96
+ history.shift();
97
+ const len = history.length;
98
+ if (len >= 2 && history[len - 1] === history[len - 2] && !ctx.state.editRetryReminderSent) {
99
+ ctx.state.editRetryReminderSent = true;
100
+ const summary = ctx.result.content.split("\n")[0] || "";
101
+ ctx.queueReminder(buildEditRetryEscalationReminder(`Last failure: ${ctx.toolCall.name} on the same target with identical arguments. ${summary}`));
86
102
  }
87
- else {
88
- ctx.state.verificationCompleted = false;
89
- ctx.state.verificationFailed = true;
90
- ctx.state.finalizeReminderQueued = false;
103
+ }
104
+ else if ((ctx.toolCall.name === "edit" || ctx.toolCall.name === "write") && !ctx.result.isError) {
105
+ // Successful mutation resets the dedup state so a later, unrelated
106
+ // failure won't fire the reminder spuriously.
107
+ ctx.state.recentEditFailures = [];
108
+ ctx.state.editRetryReminderSent = false;
109
+ }
110
+ // Redundant-Read detection: same file path read twice within this turn.
111
+ // Soft single-shot reminder, governor handles cumulative read budgets.
112
+ if (ctx.toolCall.name === "read" && !ctx.result.isError) {
113
+ const rawPath = ctx.toolCall.parsedArgs?.path ?? ctx.toolCall.parsedArgs?.file_path;
114
+ const path = typeof rawPath === "string" ? rawPath : undefined;
115
+ if (path) {
116
+ const seen = ctx.state.recentReadPaths ?? (ctx.state.recentReadPaths = []);
117
+ const flagged = ctx.state.redundantReadReminded ?? (ctx.state.redundantReadReminded = new Set());
118
+ if (seen.includes(path) && !flagged.has(path)) {
119
+ flagged.add(path);
120
+ ctx.queueReminder(buildRedundantReadReminder(path));
121
+ }
122
+ seen.push(path);
123
+ if (seen.length > 16)
124
+ seen.shift();
91
125
  }
92
126
  }
127
+ if (isCodeWriteResult(ctx.toolCall, ctx.result)) {
128
+ markCodeChanged(ctx.state);
129
+ }
130
+ // Removed: active verification tracking. The previous design nagged the
131
+ // model every turn until it ran a recognised verification command, and
132
+ // narrowly accepted only test/lint commands — which meant ad-hoc python
133
+ // checks did not count, the nag never cleared, and reasoning models
134
+ // (DeepSeek v4-pro with hex-blindness) spiraled trying to "prove" the
135
+ // edit was correct. CC's approach is the opposite: verify when there
136
+ // is something real to verify, say so explicitly when there isn't, and
137
+ // trust the model to judge. We follow that.
93
138
  if (ctx.toolCall.name === "task") {
94
139
  ctx.queueReminder(buildTaskSummaryReminder());
95
140
  }
@@ -110,46 +155,17 @@ export function createDefaultHooks() {
110
155
  if (ctx.state.governor?.snapshot().searchFrozen && allSearchResultsWereLowSignal) {
111
156
  ctx.requestTextOnlyTurn("Search continuation has become low-yield. Summarize the strongest evidence already collected instead of continuing broad exploration.");
112
157
  }
113
- const changedThisTurn = ctx.toolResults.some((result) => result.metadata?.kind === "write" || result.metadata?.kind === "edit");
114
- if (changedThisTurn && !ctx.state.verificationAttempted && !ctx.state.verificationCompleted && !ctx.state.verificationReminderQueued) {
115
- ctx.state.verificationReminderQueued = true;
116
- ctx.queueReminder(buildVerificationReminder("The previous turn changed files and no verification evidence has been observed yet."));
117
- }
118
- if (ctx.state.codeChanged && ctx.state.verificationFailed && !ctx.state.verificationFailureReminderQueued) {
119
- ctx.state.verificationFailureReminderQueued = true;
120
- ctx.queueReminder(buildVerificationFailureReminder("A verification command or runtime check was attempted after file changes, but it did not pass."));
121
- }
122
- if (ctx.state.codeChanged && ctx.state.verificationCompleted && !ctx.state.finalizeReminderQueued) {
123
- ctx.state.finalizeReminderQueued = true;
124
- ctx.queueReminder(buildFinalizeOpportunityReminder("A relevant verification command or runtime check passed after file changes."));
125
- }
158
+ // Verification reminders intentionally removed. See afterToolCall.
126
159
  },
127
- afterTurn(ctx) {
128
- if (ctx.state.codeChanged && ctx.state.verificationFailed && !ctx.state.verificationFailureReminderSent) {
129
- ctx.state.verificationFailureReminderSent = true;
130
- ctx.state.forceContinuationReason = "Files were changed, but the latest verification evidence failed.";
131
- ctx.queueReminder(buildVerificationFailureReminder(ctx.state.forceContinuationReason));
132
- return;
133
- }
134
- if (ctx.state.codeChanged && !ctx.state.verificationAttempted && !ctx.state.verificationCompleted && !ctx.state.finalVerificationReminderSent) {
135
- ctx.state.finalVerificationReminderSent = true;
136
- ctx.state.forceContinuationReason = "Files were changed but no verification evidence was observed before the final answer.";
137
- ctx.queueReminder(buildVerificationReminder(ctx.state.forceContinuationReason));
138
- }
160
+ afterTurn() {
161
+ // Verification force-continuation removed. The model decides whether
162
+ // verification is meaningful for the task, per the system prompt.
139
163
  },
140
164
  },
141
165
  ];
142
166
  }
143
167
  function markCodeChanged(state) {
144
168
  state.codeChanged = true;
145
- state.verificationAttempted = false;
146
- state.verificationCompleted = false;
147
- state.verificationFailed = false;
148
- state.verificationReminderQueued = false;
149
- state.finalVerificationReminderSent = false;
150
- state.verificationFailureReminderQueued = false;
151
- state.verificationFailureReminderSent = false;
152
- state.finalizeReminderQueued = false;
153
169
  }
154
170
  function isCodeWriteResult(_toolCall, result) {
155
171
  if (result.isError || result.status === "blocked" || result.status === "command_error") {
@@ -157,31 +173,26 @@ function isCodeWriteResult(_toolCall, result) {
157
173
  }
158
174
  return result.metadata?.kind === "write" || result.metadata?.kind === "edit";
159
175
  }
160
- function isSuccessfulToolResult(result) {
161
- if (result.isError) {
162
- return false;
176
+ function hashEditCall(toolCall) {
177
+ // Cheap fingerprint that identifies "same edit/write call". JSON of the
178
+ // sorted parsed args is good enough — we only need stable equality between
179
+ // identical calls, not cryptographic strength.
180
+ try {
181
+ return `${toolCall.name}:${stableStringify(toolCall.parsedArgs)}`;
182
+ }
183
+ catch {
184
+ return `${toolCall.name}:${toolCall.arguments}`;
163
185
  }
164
- return result.status !== "blocked" && result.status !== "command_error" && result.status !== "timeout";
165
186
  }
166
- function isVerificationAttempt(toolCall, result) {
167
- if (toolCall.name === "lsp") {
168
- return true;
187
+ function stableStringify(value) {
188
+ if (Array.isArray(value)) {
189
+ return `[${value.map(stableStringify).join(",")}]`;
169
190
  }
170
- if (toolCall.name !== "bash") {
171
- return false;
191
+ if (value && typeof value === "object") {
192
+ const entries = Object.keys(value)
193
+ .sort()
194
+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
195
+ return `{${entries.join(",")}}`;
172
196
  }
173
- const command = typeof result.metadata?.command === "string"
174
- ? result.metadata.command
175
- : typeof toolCall.parsedArgs.command === "string"
176
- ? toolCall.parsedArgs.command
177
- : "";
178
- return isVerificationCommand(command);
179
- }
180
- function isVerificationCommand(command) {
181
- const normalized = command.trim().toLowerCase();
182
- return /\b(npm|pnpm|yarn|bun)\s+(test|run\s+(test|build|typecheck|lint|check|tsc)|exec\s+tsc)\b/.test(normalized)
183
- || /\b(npx|pnpm\s+exec|bunx)\s+(vitest|tsc|eslint|playwright)\b/.test(normalized)
184
- || /\b(python3?|uv\s+run\s+python3?|poetry\s+run\s+python3?)\s+(-m\s+)?(pytest|unittest|ruff|mypy)\b/.test(normalized)
185
- || /\b(make|cmake)\s+(test|check)\b/.test(normalized)
186
- || /\b(vitest|tsc|pytest|ruff|mypy|ctest|cargo\s+test|go\s+test|swift\s+test|mvn\s+test|gradle\s+test|\.\/gradlew\s+test)\b/.test(normalized);
197
+ return JSON.stringify(value ?? null);
187
198
  }
@@ -14,14 +14,11 @@ export interface TurnHookState {
14
14
  forceTextOnlyReason?: string;
15
15
  forceContinuationReason?: string;
16
16
  codeChanged?: boolean;
17
- verificationAttempted?: boolean;
18
- verificationCompleted?: boolean;
19
- verificationFailed?: boolean;
20
- verificationReminderQueued?: boolean;
21
- finalVerificationReminderSent?: boolean;
22
- verificationFailureReminderQueued?: boolean;
23
- verificationFailureReminderSent?: boolean;
24
- finalizeReminderQueued?: boolean;
17
+ smallTaskHintSent?: boolean;
18
+ recentEditFailures?: string[];
19
+ editRetryReminderSent?: boolean;
20
+ recentReadPaths?: string[];
21
+ redundantReadReminded?: Set<string>;
25
22
  taskBudget?: {
26
23
  total: number;
27
24
  spent: number;
@@ -79,6 +79,9 @@ function buildGuidelines(tools, extraGuidelines) {
79
79
  if (tools.includes("question")) {
80
80
  add("When the user is explicitly discussing, brainstorming, or shaping an approach instead of asking for immediate execution, use the question tool for targeted clarification or preference choices when it would materially improve the discussion; do not use it for generic permission-to-proceed questions");
81
81
  }
82
+ if (tools.includes("todo_write")) {
83
+ add("Use todo_write to plan any task that needs three or more concrete steps before you start. Mark each item completed as soon as it is done; do not batch updates");
84
+ }
82
85
  for (const item of extraGuidelines) {
83
86
  add(item);
84
87
  }
@@ -15,6 +15,7 @@ export const defaultToolSnippets = {
15
15
  close_agent: "Close or cancel a spawned subagent thread",
16
16
  question: "Ask the user structured questions when clarification or preference choices would materially improve the work",
17
17
  skill: "Load a named skill with specialized instructions and bundled resources",
18
+ todo_write: "Plan and track multi-step work. Mark each task completed as soon as it is done — do not batch.",
18
19
  };
19
20
  export const defaultToolNames = [
20
21
  "read",
@@ -32,6 +33,7 @@ export const defaultToolNames = [
32
33
  "close_agent",
33
34
  "question",
34
35
  "skill",
36
+ "todo_write",
35
37
  ];
36
38
  export function buildEnvironmentPrompt(options = {}) {
37
39
  const configuredProvider = options.configuredProvider ?? "unknown";
@@ -3,6 +3,5 @@ export function buildDeepSeekProviderPrompt(agentName) {
3
3
 
4
4
  Prefer short plans followed by concrete tool use. Avoid broad speculation.
5
5
  After each tool result, update your understanding before choosing the next action.
6
- Do not repeat equivalent searches unless the previous result changed the search space.
7
- When provider/API behavior is involved, inspect serialization and request-shape code before changing generic agent logic.`;
6
+ Do not repeat equivalent searches unless the previous result changed the search space.`;
8
7
  }
@@ -2,6 +2,5 @@ export function buildKimiProviderPrompt(agentName) {
2
2
  return `You are ${agentName}, a terminal coding agent running on a Kimi/Moonshot model.
3
3
 
4
4
  Keep tool use disciplined: pursue one concrete hypothesis at a time, read results carefully, and converge after evidence is sufficient.
5
- Do not fan out into many parallel search directions unless the task truly requires it.
6
- For tool-call or reasoning-mode issues, inspect message history serialization before changing unrelated agent behavior.`;
5
+ Do not fan out into many parallel search directions unless the task truly requires it.`;
7
6
  }
@@ -30,6 +30,23 @@ export declare function buildWorkflowPhaseReminder(input: {
30
30
  pending: string[];
31
31
  }): string;
32
32
  export declare function buildTaskSummaryReminder(): string;
33
- export declare function buildVerificationReminder(reason: string): string;
34
- export declare function buildVerificationFailureReminder(reason: string): string;
35
- export declare function buildFinalizeOpportunityReminder(reason: string): string;
33
+ /**
34
+ * Fired when the same edit/write tool call (identical tool name + args) has
35
+ * just failed for the second time in a row. Models — especially thinking-heavy
36
+ * ones — can otherwise spiral on `No changes made: identical content` or
37
+ * `oldText not found` because their internal reasoning convinces them they
38
+ * are typing the change correctly even though the JSON args arrive identical.
39
+ * This nudge forces a strategy change.
40
+ */
41
+ export declare function buildEditRetryEscalationReminder(reason: string): string;
42
+ /**
43
+ * Fired the FIRST time the model re-reads a file it already read in this turn.
44
+ * Soft — does not freeze the tool. Just prevents a 3rd / 4th re-read.
45
+ */
46
+ export declare function buildRedundantReadReminder(path: string): string;
47
+ /**
48
+ * Injected once at task start when the user's input looks like a small,
49
+ * focused task (e.g. "write an HTML page about X"). Counterweight to the
50
+ * default protocol which biases toward thorough exploration.
51
+ */
52
+ export declare function buildSmallTaskHint(): string;
@@ -171,33 +171,59 @@ Treat the task output as a bounded subtask result:
171
171
  - do not re-run the same exploratory search unless the subtask uncovered a concrete contradiction
172
172
  `);
173
173
  }
174
- export function buildVerificationReminder(reason) {
174
+ // Removed: buildVerificationReminder / buildVerificationFailureReminder.
175
+ // The verification reminder ladder pressured the model to run a "verification"
176
+ // after every file change. For models with hex-tokenization blind spots (e.g.
177
+ // DeepSeek v4-pro), this triggered death loops where the model wrote ad-hoc
178
+ // validation scripts that found the bug but could never fix it. CC trusts the
179
+ // model to decide when verification is meaningful; we follow that.
180
+ /**
181
+ * Fired when the same edit/write tool call (identical tool name + args) has
182
+ * just failed for the second time in a row. Models — especially thinking-heavy
183
+ * ones — can otherwise spiral on `No changes made: identical content` or
184
+ * `oldText not found` because their internal reasoning convinces them they
185
+ * are typing the change correctly even though the JSON args arrive identical.
186
+ * This nudge forces a strategy change.
187
+ */
188
+ export function buildEditRetryEscalationReminder(reason) {
175
189
  return wrapInSystemReminder(`
176
- Verification required before final answer.
190
+ The same edit/write call has failed twice with identical arguments.
177
191
 
178
192
  ${reason}
179
193
 
180
- You have changed files in this turn. Run the narrowest meaningful verification command or runtime check before finalizing.
181
- If verification truly cannot be run, state the concrete blocker and the residual risk.
194
+ Stop retrying the same call. Pick one of:
195
+ - Re-read the target file and compare the actual bytes to your intended oldText / newText. Trailing whitespace, unicode lookalikes, or off-by-one boundaries are common causes.
196
+ - If you intended to add a single character (e.g. fixing a 5-digit hex color to 6 digits), confirm that your newText string actually contains the added character before sending again.
197
+ - Use the write tool with overwrite=true and the full new content instead of edit — useful when the change spans many lines or the diff anchor is ambiguous. Existing files must be read or modified in this session before full-file replacement.
198
+ - If you cannot determine the cause, ask the user for clarification.
182
199
  `);
183
200
  }
184
- export function buildVerificationFailureReminder(reason) {
201
+ /**
202
+ * Fired the FIRST time the model re-reads a file it already read in this turn.
203
+ * Soft — does not freeze the tool. Just prevents a 3rd / 4th re-read.
204
+ */
205
+ export function buildRedundantReadReminder(path) {
185
206
  return wrapInSystemReminder(`
186
- Verification failed after file changes.
187
-
188
- ${reason}
189
-
190
- Do not finalize as complete while this failure is unresolved. Make one focused fix and rerun the most relevant verification.
191
- If you cannot fix it, explain the concrete blocker and the residual risk instead of claiming success.
207
+ You already read ${path} earlier in this turn. Use the content already in context rather than re-reading.
208
+ Only re-read this path if a subsequent tool call (edit/write/bash) modified it since.
192
209
  `);
193
210
  }
194
- export function buildFinalizeOpportunityReminder(reason) {
211
+ /**
212
+ * Injected once at task start when the user's input looks like a small,
213
+ * focused task (e.g. "write an HTML page about X"). Counterweight to the
214
+ * default protocol which biases toward thorough exploration.
215
+ */
216
+ export function buildSmallTaskHint() {
195
217
  return wrapInSystemReminder(`
196
- Completion checkpoint.
197
-
198
- ${reason}
218
+ This appears to be a small, focused task (short request, single deliverable, no integration ambiguity).
199
219
 
200
- If this satisfies the user's request, provide the final answer now.
201
- Continue using tools only if there is a concrete remaining requirement, failing check, or missing deliverable.
220
+ Prefer direct execution over exploration:
221
+ - If the target file path is given or obvious, use write/edit directly.
222
+ - Do not glob, read, or grep adjacent files unless the request explicitly references them.
223
+ - Do not pre-plan with todo_write for tasks that can be done in one or two tool calls.
224
+ - Skip the "investigate the codebase" step that applies to larger changes.
202
225
  `);
203
226
  }
227
+ // Removed: buildFinalizeOpportunityReminder. Was paired with the verification
228
+ // nag ladder. Without the ladder, "you can finalize now" advice is redundant —
229
+ // the model finalises whenever its own judgement says the task is done.
@@ -1,30 +1,24 @@
1
+ // Compact, prose-shaped guidelines. Each line is one rule. The set is kept
2
+ // short on purpose: a thinking-heavy model burns reasoning tokens on every
3
+ // rule it has to weigh per turn, and most behaviors should be background
4
+ // disposition, not active checklist items. Add to this list only when an
5
+ // observed failure cannot be addressed by an existing rule.
1
6
  const defaultGuidelines = [
2
- "Inspect relevant files, command output, or runtime state before making claims about code behavior",
3
- "Separate confirmed facts from inference when the evidence is incomplete",
4
- "Prefer runtime and call-chain evidence over README text or configuration names for behavior questions",
5
- "Before editing or writing files, read them first if they exist",
6
- "Use edit for targeted changes to existing files; use write for creating new files",
7
- "Edit only the files required for the requested change",
8
- "Prefer structured search tools over bash for repository searches whenever possible",
9
- "Do not repeat near-identical searches when they are not producing new evidence",
10
- "When investigating configuration or security questions, stop once the relevant load path, storage path, and exposure path are identified",
11
- "Use spawn_agent and wait_agent for bounded investigative subproblems instead of letting the main loop churn on repeated exploratory searches",
12
- "After code edits, run the narrowest meaningful verification command or explain why verification is not possible",
13
- "When finishing a coding task, report what changed, where it changed, verification results, and remaining risk",
14
- "Be concise in your responses",
7
+ "Ground decisions in the codebase: inspect relevant files, command output, or runtime state before making claims about behavior. Separate confirmed facts from inference when evidence is incomplete.",
8
+ "Choose the smallest coherent change. Edit only the files required for the requested change; do not refactor or improve adjacent code unprompted.",
9
+ "For modifications to existing code, read the file first. For brand-new files whose target path is known and does not exist, write directly without exploratory reading. Use edit for small targeted changes; use write with overwrite=true for intentional full-file replacement of an existing file. Never delete and recreate a file just to overwrite it.",
10
+ "Prefer structured tools (glob, grep, lsp, read) over bash for search and inspection. Do not repeat a near-identical search or re-read the same file unless new evidence changes the question.",
11
+ "If a tool fails, diagnose the error before switching tactics. Do not retry the identical call with identical arguments. After two equivalent failures, switch approach — re-read the file, use a different tool, rewrite the whole file with write overwrite=true, or ask the user.",
12
+ "Before reporting a task complete, verify it works when verification is meaningful and cheap — run the existing test, execute the script, check the output. If no test exists, the change is purely declarative (static HTML/markdown/config), or running the code is not practical, state that explicitly rather than inventing a verification step. Do not write throwaway validation scripts to prove correctness; if there is no real check to run, report the change and stop.",
15
13
  ];
16
14
  export function buildRuntimePrompt(options = {}) {
17
- const thinkingLevel = options.thinkingLevel ?? "off";
18
15
  const guidelines = dedupe(defaultGuidelines, options.guidelines ?? []);
19
- return `Current thinking level: ${thinkingLevel}
20
-
21
- Execution protocol:
22
- 1. Understand the user's requested outcome and current constraints.
23
- 2. Inspect the relevant files or state before making claims or edits.
24
- 3. Choose the smallest coherent change that solves the actual problem.
25
- 4. Edit only the necessary files.
26
- 5. Verify with the narrowest meaningful command or runtime check when possible.
27
- 6. Finish with changed files, verification results, and unresolved risk.
16
+ // The execution flow is stated as a single prose sentence rather than a
17
+ // numbered protocol. Numbered checklists prompt thinking models to walk
18
+ // each step explicitly in their reasoning every turn, even for trivial
19
+ // tasks multiplying latency without improving quality. Prose lets the
20
+ // protocol act as background disposition.
21
+ return `Work by understanding the requested outcome, grounding decisions in the codebase, making the smallest coherent change, and verifying when possible. Scale your effort to the task: a one-file create-or-edit deserves direct execution, not extensive pre-exploration.
28
22
 
29
23
  Guidelines:
30
24
  ${guidelines.map((item) => `- ${item}`).join("\n")}`;
@@ -5,6 +5,10 @@
5
5
  */
6
6
  import type { Provider, ProviderMessage, StreamChunk, ThinkingLevel } from "./types.js";
7
7
  type ReasoningContentEcho = "tool_calls" | "all";
8
+ export type ToolArgsMergeMode = "delta" | "snapshot";
9
+ export interface TranslateOpenAIStreamOptions {
10
+ toolArgsMergeMode?: ToolArgsMergeMode;
11
+ }
8
12
  export declare function toChatCompletionsMessage(message: ProviderMessage, options?: {
9
13
  reasoningContentEcho?: ReasoningContentEcho;
10
14
  }): Record<string, unknown>;
@@ -17,6 +21,11 @@ export interface ProviderInstanceOptions {
17
21
  }
18
22
  export declare function createUnavailableProvider(message: string): Provider;
19
23
  export declare function createProviderInstance(options: ProviderInstanceOptions): Provider;
24
+ export interface NormalizedToolArgs {
25
+ args: string;
26
+ corrupt: boolean;
27
+ }
28
+ export declare function normalizeToolArgsDetailed(raw: string): NormalizedToolArgs;
20
29
  export declare function normalizeToolArgs(raw: string): string;
21
30
  /**
22
31
  * Convert an OpenAI-compatible chat-completions stream into our internal StreamChunk events.
@@ -26,5 +35,5 @@ export declare function normalizeToolArgs(raw: string): string;
26
35
  * partial write previews before the tool executes. End events are still flushed
27
36
  * in index order to keep multi-call turns deterministic.
28
37
  */
29
- export declare function translateOpenAIStream(stream: AsyncIterable<any>): AsyncIterable<StreamChunk>;
38
+ export declare function translateOpenAIStream(stream: AsyncIterable<any>, options?: TranslateOpenAIStreamOptions): AsyncIterable<StreamChunk>;
30
39
  export {};