@causyne/agent 1.20.12 → 1.20.14

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 (72) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/SmartTools.js +33 -0
  4. package/src/SmartTools.ts +37 -0
  5. package/src/acp/client.js +157 -4
  6. package/src/acp/client.ts +152 -5
  7. package/src/agentLoop.js +857 -178
  8. package/src/agentLoop.ts +865 -183
  9. package/src/browser/browserRuntime.js +8 -1
  10. package/src/browser/browserRuntime.ts +8 -1
  11. package/src/browser/causyneBrowser.js +20 -4
  12. package/src/browser/causyneBrowser.ts +20 -4
  13. package/src/browser/urlPolicy.js +35 -0
  14. package/src/browser/urlPolicy.ts +34 -0
  15. package/src/cliMode.js +6 -2
  16. package/src/commands.js +14 -0
  17. package/src/contextManager.d.ts +1 -0
  18. package/src/core/contextCompactor.js +277 -0
  19. package/src/core/contextCompactor.ts +353 -0
  20. package/src/decideTools.js +157 -0
  21. package/src/decideTools.ts +195 -0
  22. package/src/decisionPolicy.js +5 -3
  23. package/src/decisionPolicy.ts +5 -3
  24. package/src/implementationPlan.js +284 -0
  25. package/src/implementationPlan.ts +275 -0
  26. package/src/observer/coldObserver.js +10 -4
  27. package/src/observer/coldObserver.ts +15 -7
  28. package/src/observer/evidence.js +11 -5
  29. package/src/observer/evidence.ts +13 -6
  30. package/src/observer.js +196 -0
  31. package/src/observer.ts +287 -0
  32. package/src/providers/acp.js +362 -109
  33. package/src/providers/acp.ts +359 -111
  34. package/src/providers/antigravity.js +133 -105
  35. package/src/providers/antigravity.ts +130 -109
  36. package/src/providers/base.d.ts +3 -0
  37. package/src/providers/budgetEnforcer.js +13 -0
  38. package/src/providers/budgetEnforcer.ts +13 -3
  39. package/src/provisioning/capabilityProvisioner.js +14 -10
  40. package/src/sandbox.js +4 -2
  41. package/src/saveTools.js +146 -0
  42. package/src/saveTools.ts +169 -0
  43. package/src/session/cachePressure.js +77 -0
  44. package/src/session/cachePressure.ts +122 -0
  45. package/src/smartToolsUse.js +69 -12
  46. package/src/smartToolsUse.ts +103 -12
  47. package/src/taskShape.js +7 -7
  48. package/src/taskShape.ts +7 -7
  49. package/src/timeMachine.js +55 -20
  50. package/src/timeMachine.ts +64 -20
  51. package/src/toolPacks.js +217 -310
  52. package/src/toolPacks.ts +505 -0
  53. package/src/tools/deferredMcpSearch.js +21 -13
  54. package/src/tools/deferredMcpSearch.ts +23 -15
  55. package/src/tools/updatePlan.js +2 -2
  56. package/src/tools/updatePlan.ts +2 -2
  57. package/src/toolsList.js +203 -0
  58. package/src/toolsList.ts +224 -0
  59. package/src/tui/chatRenderer.js +49 -14
  60. package/src/tui/codeStreamRenderer.js +16 -5
  61. package/src/tui/codeStreamRenderer.ts +14 -4
  62. package/src/tui/prompt.js +4 -2
  63. package/src/tui/sessionSidebar.js +10 -2
  64. package/src/tui/sessionSidebar.ts +10 -3
  65. package/src/tui/stageSurface.js +27 -1
  66. package/src/tui/text.d.ts +1 -0
  67. package/src/tui/turnRail.js +274 -0
  68. package/src/tui/turnRail.ts +334 -0
  69. package/src/types/contracts.ts +103 -0
  70. package/src/verificationPlan.js +141 -0
  71. package/src/verificationPlan.ts +166 -0
  72. package/src/toolPacks.d.ts +0 -10
package/src/agentLoop.ts CHANGED
@@ -8,7 +8,7 @@ import { pruneSessions as pruneEmbodimentSessions, describeSession } from './emb
8
8
  import { WorkspacePerception } from './perception.js';
9
9
  import { audioFormatForMimeType } from './providers/base.js';
10
10
  import { TaskBuffer } from './taskBuffer.js';
11
- import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
11
+ import { TOOL_DEFINITIONS, getDynamicTools, getSearchableToolDefinitions, resolveTool, canonicalToolName } from './tools/registry.js';
12
12
  import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
13
13
  import { validateToolArguments } from './tools/argumentValidation.js';
14
14
  import { Sandbox } from './sandbox.js';
@@ -22,7 +22,8 @@ import { getMemoryContextString } from './memory.js';
22
22
  import { MemoryManager } from './memoryManager.js';
23
23
  import { cortexDb } from './cortex/vectorDb.js';
24
24
  import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
25
- import { analyzeTask, buildTaskBrief, packsFromShape } from './taskShape.js';
25
+ import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
26
+ import { analyzeTask, buildTaskBrief } from './taskShape.js';
26
27
  import {
27
28
  lookupPlan,
28
29
  recordPlan,
@@ -37,27 +38,38 @@ import {
37
38
  import { routedConfig } from './modelRouter.js';
38
39
  import { assessStep, isThrashing } from './uncertainty.js';
39
40
  import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
41
+ import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks } from './implementationPlan.js';
40
42
  import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
41
43
  import { AGENT_USER_POLICY } from './agentPolicy.js';
42
44
  import { VFETracker } from './vfeTracker.js';
43
45
  import { coldObserver } from './observer/coldObserver.js';
44
- import { TimeMachine, recoveryUserMessage } from './timeMachine.js';
46
+ import { isVerificationCommand } from './observer/evidence.js';
47
+ import { CausyneObserver, defaultObserver } from './observer.js';
48
+ import type { Observation } from './observer.js';
49
+ import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
50
+ import type { RecoveryDecision } from './timeMachine.js';
45
51
  import {
46
- routePacks,
47
52
  packForTool,
48
53
  isCoreTool,
49
54
  isGameIntent,
50
55
  isWebIntent,
51
- getPackCatalogue,
52
56
  PACK_PLAYBOOKS,
53
57
  PACKS
54
58
  } from './toolPacks.js';
55
59
  import {
56
60
  determineToolScope,
57
- filterSuppressedPacks,
58
61
  resolveLazyPlaybooks,
62
+ refineToolDecision,
59
63
  SmartToolsGovernor
60
64
  } from './smartToolsUse.js';
65
+ import { buildToolsList, renderToolsList, omittedCustomCount } from './toolsList.js';
66
+ import type { ToolListEntry } from './toolsList.js';
67
+ import { assessVerification } from './verificationPlan.js';
68
+ import { SmartTools } from './SmartTools.js';
69
+ import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
70
+ import type { DecideToolsInput } from './decideTools.js';
71
+ import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
72
+ import type { AdmissionResult } from './saveTools.js';
61
73
  import {
62
74
  resolveCharPool,
63
75
  measureMessages,
@@ -130,10 +142,11 @@ export interface AgentLoopOptions {
130
142
  export function isActionableTaskPrompt(text: string): boolean {
131
143
  const t = (text || '').trim();
132
144
  if (!t) return false;
133
- const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
145
+ const pureGreeting = /^(hi|hello|hey|yo|halo|hai|p|assalamu['a]?[l]?aikum|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
134
146
  if (pureGreeting) return false;
135
- const actionKeywords = /\b(create|build|make|write|code|implement|fix|optimize|refactor|generate|add|setup|install|run|open|launch|start|play|serve|preview|deploy|delete|remove|update|change|test|review|inspect|search|find|download)\b/i;
136
- return actionKeywords.test(t);
147
+ const actionKeywords = /\b(continue|resume|proceed|lanjut\w*|create|build|make|write|code|implement|fix|optimize|refactor|generate|add|setup|install|run|open|launch|start|play|serve|preview|deploy|delete|remove|update|change|test|review|inspect|search|find|download|buat\w*|bikin\w*|perbaik\w*|tambah\w*|ubah\w*|hapus\w*|jalan\w*|pasang\w*|analis\w*|cek\w*|rancang\w*|desain\w*|kerjakan\w*|tolong\w*|bantu\w*|ganti\w*|tulis\w*|kembangkan\w*)\b/i;
148
+ if (actionKeywords.test(t)) return true;
149
+ return false; // Length alone does not turn an information question into an execution order.
137
150
  }
138
151
 
139
152
  export function isGenericHandoffResponse(text: string): boolean {
@@ -170,12 +183,19 @@ export function isCodeAuthoringTaskPrompt(text: string): boolean {
170
183
  const t = (text || '').trim();
171
184
  if (!t) return false;
172
185
  if (isExecutionOrLaunchTaskPrompt(t)) return false;
173
- return /\b(create|build|make|write|code|implement|generate|game|3js|threejs|three\.js|app)\b/i.test(t);
186
+ return /\b(create|build|make|write|code|implement|generate|game|3js|three?\.?js|three?js|app)\b/i.test(t);
174
187
  }
175
188
 
176
189
  export function isDirectGameTask(text: string): boolean {
177
- return /\b(three\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
178
- && !/\b(godot|unity|unreal|full engine)\b/i.test(text);
190
+ return isDirectGameTaskDecision(text);
191
+ }
192
+
193
+ export function isProviderPlanOrQuotaRefusal(text: string): boolean {
194
+ if (!text || typeof text !== 'string') return false;
195
+ const trimmed = text.trim();
196
+ if (!trimmed || trimmed.length > 320) return false;
197
+ if (/^upgrade your plan to continue\.?$/i.test(trimmed)) return true;
198
+ return /\b(upgrade your plan to continue|insufficient[_ ]quota|credit balance is too low|billing hard limit|quota exceeded for|plan limit reached|subscription required to continue)\b/i.test(trimmed);
179
199
  }
180
200
 
181
201
  /**
@@ -276,7 +296,7 @@ Follow the selected project's existing style and architecture. Check dependencie
276
296
  - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
277
297
 
278
298
  # Operational Guidelines & Communication
279
- - **Language Reflection**: Dynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language without mentioning language policies.
299
+ - **Strict Mandatory English Only Directive**: Operate, reason, plan, and communicate STRICTLY and EXCLUSIVELY in the English language across all thoughts, plan steps, and responses, regardless of the language used in the user's prompt. The use of non-English languages (including Indonesian) is strictly and permanently forbidden anywhere in agent responses, plans, or thoughts.
280
300
  - **Ruthless Conciseness**: Answer concisely with fewer than 4 lines unless detail is requested. No preambles ("Okay, I will now...") or postambles ("I have finished..."). One-word answers are best for simple questions.
281
301
  - **Evidence-Based Recovery Reports**: State only observed tool results and checks. Never claim a failed task was fixed without a passing check. Keep failure reports brief; if the user requests a detailed report, write it to a Markdown file in their selected workspace and give its path instead of dumping it into chat.
282
302
  - **Status Updates**: For substantial work, give brief progress notes while using tools. Use a tool when it contributes to the task, and report what it actually returned.
@@ -285,7 +305,7 @@ Follow the selected project's existing style and architecture. Check dependencie
285
305
  - **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
286
306
 
287
307
  # Task Management & Planning
288
- - Use update_plan to create a visible implementation checklist before complex implementation. Create atomic, verb-led, verifiable steps and keep exactly one step in progress.
308
+ - Use update_plan to create a visible implementation checklist before complex implementation. Create atomic, verb-led, verifiable steps in English and keep exactly one step in progress.
289
309
  - Return known tool calls together when their arguments are already available. Calls execute in order: a checklist update, file write, and readback of that path can share one response. Wait for results before choosing arguments that depend on their contents.
290
310
  - Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
291
311
  - Reconcile and close the todo list when all goal tasks are done. If the user asks you to implement, do not output a separate text-based plan. Just build and display the todo list.
@@ -310,15 +330,15 @@ Follow the selected project's existing style and architecture. Check dependencie
310
330
  - **Runnable Code**: Ensure generated code can be run immediately. Add all necessary imports, dependencies, and scaffolding (e.g. requirements.txt) if building from scratch.
311
331
 
312
332
  # Git Workflow & Best Practices
313
- - When asked to commit changes, start by gathering information: run \`git status\`, \`git diff HEAD\`, and \`git log -n 3\` to match commit style. Combine these shell commands to save steps.
314
- - Always propose a draft commit message. Prefer messages that are clear, concise, and focused more on "why" and less
333
+ - When asked to commit changes, use strictly a plain, ultra-short single-word or minimal tag (e.g. 'fix', 'update', 'build'). Never write descriptive sentences, feature narratives, bullet points, or commentary in git commit messages or push sections.
334
+ - Zero feature explanations or commentary on commit subject lines.
315
335
 
316
336
  # Security & Constraints (Causyne Architecture)
317
337
  - **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
318
338
  - **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
319
339
  - **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
320
340
  - **Sandboxing**: Keep workspace checks and hard safety blocks active. In Mode C, ordinary in-scope edits and tool calls do not need approval; deleting an entire file or directory does. Removing or replacing lines while editing a file is not whole-file deletion.
321
- - **SSRF Protection**: Do not fetch internal IPs (127.0.0.1, 169.254.x.x, 10.x.x.x).
341
+ - **SSRF Protection**: Do not fetch cloud metadata services (169.254.169.254, metadata.google.internal) or private LAN ranges. Local development servers on loopback (localhost, 127.0.0.1, ::1) are authorized for local web/app verification.
322
342
 
323
343
  # ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
324
344
  You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
@@ -430,6 +450,13 @@ You are Kimi — a model powered by KDA (Kimi Delta Attention) with a massive co
430
450
  - When reading large files, synthesize the global context. Do not lose track of the big picture.`;
431
451
  }
432
452
 
453
+ if (p === 'antigravity') {
454
+ return `ANTIGRAVITY PEER COLLABORATION:
455
+ You are collaborating through the Antigravity high-performance local peer environment.
456
+ - Formulate precise, atomic actions and avoid repetitive back-and-forth chatter.
457
+ - Maintain rigorous execution standards: verify code syntax, inspect file changes, and avoid claiming completion without verified evidence.`;
458
+ }
459
+
433
460
  return "";
434
461
  }
435
462
 
@@ -519,6 +546,10 @@ export function explainNetworkError(error: any, config: any = {}) {
519
546
  // the same way the classifier does, so the two can never drift apart.
520
547
  const NETWORK_ERROR_TYPE = "network_error";
521
548
 
549
+ class RetryConsentCheckpoint extends Error {
550
+ constructor() { super('Peer paused after three failed attempts; explicit retry approval is required.'); }
551
+ }
552
+
522
553
  export class AgentLoop {
523
554
  // Task state is assembled across the constructor and helpers below. This
524
555
  // signature keeps those reads and writes explicitly dynamic while each field
@@ -578,6 +609,7 @@ export class AgentLoop {
578
609
  this._decisionResolved = true;
579
610
  this._implementationPlan = [];
580
611
  this._implementationPlanRequired = false;
612
+ this._implementationPlanSeeded = false;
581
613
  // A delegated subagent can tighten these two ceilings. They are applied
582
614
  // after every config refresh so run() cannot accidentally replace a
583
615
  // worker's declared bounds with the parent tier defaults.
@@ -605,6 +637,17 @@ export class AgentLoop {
605
637
  // Unlock sequence drives append-only tool ordering, which is what keeps the
606
638
  // prompt-cache prefix intact when a pack loads mid-task.
607
639
  this.unlockOrder = [];
640
+ // Pipeline stage 4. It wraps the three collections above rather than
641
+ // replacing them, so every existing reader keeps seeing the same state.
642
+ this.smartTools = new SmartTools();
643
+ this.savedTools = new SavedTools({ packs: this.unlockedPacks, tools: this.unlockedTools, order: this.unlockOrder });
644
+ this.toolsListEntries = null;
645
+ this.toolsListText = '';
646
+ this._savedToolsRestored = false;
647
+ this._pendingConsent = null;
648
+ this._recoveryNote = null;
649
+ this._verificationNudges = 0;
650
+ this._verificationPlanFired = false;
608
651
  this.workspaceContext = null;
609
652
  this.activeSubproject = null;
610
653
  this.taskShape = null;
@@ -639,10 +682,12 @@ export class AgentLoop {
639
682
  // V5: Context compaction tracking
640
683
  this._lastCompactionIndex = null;
641
684
  this.timeMachine = new TimeMachine();
685
+ this.observer = defaultObserver;
642
686
  this.isInitialized = false;
643
687
  this.taskTemperature = 0.1; // Default
644
688
  // Set only on a delegated subagent loop; null means "the full catalogue".
645
689
  this.toolScope = null;
690
+ this._inModelCall = false;
646
691
  }
647
692
 
648
693
  /** True when this loop's own conversation scope has a standing approval. */
@@ -697,21 +742,165 @@ export class AgentLoop {
697
742
  * invalidates the cache for the tools, the system prompt and every message.
698
743
  */
699
744
  unlockPack(packName: string) {
700
- if (!packName || this.unlockedPacks.has(packName)) return false;
701
- this.unlockedPacks.add(packName);
702
- this.unlockOrder.push(packName);
703
- return true;
745
+ return this.savedTools.admitPack(packName);
746
+ }
747
+
748
+ /**
749
+ * Pipeline stage 1. The list every provider is shown first: every tool the
750
+ * agent owns, one dense line each. Built once per conversation so the text is
751
+ * byte-stable and stays in the cached prompt prefix.
752
+ */
753
+ async ensureToolsList(eligible?: Array<{ name: string; description?: string }>): Promise<void> {
754
+ const definitions = eligible ?? await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
755
+ grantAllTools: true, allowedTools: this.sandbox.allowedTools, deniedTools: this.config.deniedTools
756
+ });
757
+ const scoped = this.toolScope instanceof Set && this.toolScope.size > 0
758
+ ? definitions.filter((definition: { name: string }) => this.toolScope.has(definition.name)) : definitions;
759
+ this.toolsListEntries = buildToolsList(scoped);
760
+ this.toolsListText = renderToolsList(this.toolsListEntries);
761
+ }
762
+
763
+ /**
764
+ * Stages 2-4 in one place: decide which listed tools the work needs, let
765
+ * SmartTools bound and shape that, then save what is admitted. Every way a
766
+ * tool can become needed — intent, a model request, an accepted plan,
767
+ * verification, recovery — comes through here, so there is one rule.
768
+ */
769
+ routeTools(input: Omit<DecideToolsInput, 'list'>): AdmissionResult {
770
+ const list: readonly ToolListEntry[] = this.toolsListEntries ?? buildToolsList();
771
+ const decision = decideTools({ ...input, list });
772
+ const refined = this.smartTools.refine(decision, {
773
+ planRequired: this._implementationPlanRequired,
774
+ decisionRequired: this._decisionRequirement.required && !this._decisionResolved,
775
+ admittedTools: this.unlockedTools,
776
+ admittedPacks: this.unlockedPacks
777
+ });
778
+ const added = this.savedTools.admit(refined);
779
+ if (added.addedTools.length > 0 || added.addedPacks.length > 0) {
780
+ this.persistSavedTools();
781
+ auditLog.log({ event: 'tools_admitted', taskId: this.taskId, source: refined.source, route: refined.route,
782
+ tools: added.addedTools.slice(0, 24), packs: added.addedPacks });
783
+ this.debugLog(`[tools] ${refined.source}: +${added.addedTools.length} tools, packs [${added.addedPacks.join(', ')}] (${refined.reasons.join('; ')})`);
784
+ }
785
+ return added;
786
+ }
787
+
788
+ async searchableTools(): Promise<Array<{ name: string; description?: string }>> {
789
+ const eligible = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
790
+ grantAllTools: true, allowedTools: this.sandbox.allowedTools, deniedTools: this.config.deniedTools
791
+ });
792
+ return this.toolScope instanceof Set && this.toolScope.size > 0
793
+ ? eligible.filter((tool: { name: string }) => this.toolScope.has(tool.name)) : eligible;
794
+ }
795
+
796
+ /** A resumed conversation starts with the tools it already earned. */
797
+ restoreSavedTools(): void {
798
+ if (this._savedToolsRestored) return;
799
+ this._savedToolsRestored = true;
800
+ const key = this.memoryManager?.sessionId
801
+ ? `${this.memoryManager.sessionId}\0${path.resolve(this.workspaceRoot)}` : null;
802
+ if (!key) return;
803
+ const state = readSavedTools(key);
804
+ if (state) {
805
+ const eligible = new Set((this.toolsListEntries ?? []).map((entry: ToolListEntry) => entry.name));
806
+ // Restore names, not whole-pack permissions or obsolete definitions.
807
+ this.savedTools.restore({ tools: state.tools.filter((name) => eligible.has(name)), packs: [], order: [] });
808
+ }
809
+ }
810
+
811
+ persistSavedTools(): void {
812
+ const key = this.memoryManager?.sessionId
813
+ ? `${this.memoryManager.sessionId}\0${path.resolve(this.workspaceRoot)}` : null;
814
+ if (key) writeSavedTools(key, this.savedTools.toState());
815
+ }
816
+
817
+ /**
818
+ * Apply a TimeMachine verdict. The agent may spend three attempts alone; the
819
+ * next three are the user's to grant. A `consent` verdict is therefore put to
820
+ * the user, and only an explicit approval lets the task continue.
821
+ */
822
+ async handleRecovery(recovery: RecoveryDecision, tool: string): Promise<{ stop: boolean; guidance: string }> {
823
+ if (recovery.kind === 'replan') {
824
+ this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
825
+ return { stop: false, guidance: recovery.guidance };
826
+ }
827
+ if (recovery.kind === 'consent') {
828
+ const remaining = recovery.maxAttempts - recovery.attempt;
829
+ if (await this.askRetryConsent(recovery, tool)) {
830
+ this.timeMachine.grantExtension(recovery.issueKey);
831
+ this.emitEvent({ type: 'status', message: `Retry limit extended: ${remaining} more attempts allowed for ${tool}.` });
832
+ auditLog.log({ event: 'retry_extension_granted', taskId: this.taskId, tool, attempt: recovery.attempt });
833
+ return { stop: false, guidance: `The user approved ${remaining} more attempts. Change approach completely; do not repeat the failed edit or command. Review the last successful step and the failing evidence before acting.` };
834
+ }
835
+ this.stopRequested = true;
836
+ auditLog.log({ event: 'retry_extension_declined', taskId: this.taskId, tool, attempt: recovery.attempt });
837
+ this.emitEvent({ type: 'error', message: recoveryUserMessage({ ...recovery, kind: 'stop' }, tool) });
838
+ return { stop: true, guidance: recovery.guidance };
839
+ }
840
+ if (recovery.kind === 'stop' || recovery.kind === 'human') {
841
+ this.stopRequested = true;
842
+ this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, tool) });
843
+ return { stop: true, guidance: recovery.guidance };
844
+ }
845
+ return { stop: false, guidance: recovery.guidance };
846
+ }
847
+
848
+ /** True only on an explicit "allow". A custom answer, a dismissal or no UI at all is a no. */
849
+ async askRetryConsent(recovery: RecoveryDecision, tool: string): Promise<boolean> {
850
+ const remaining = recovery.maxAttempts - recovery.attempt;
851
+ const answer = await this.requestDecision({
852
+ id: randomUUID(),
853
+ kind: 'workflow',
854
+ header: 'More attempts?',
855
+ question: `${tool} failed ${recovery.attempt} times (${recovery.failureClass || 'unclassified'}). Allow up to ${remaining} more attempts?`,
856
+ reason: `Each further attempt repeats similar edits and checks and costs more time and tokens. The hard limit is ${recovery.maxAttempts} attempts.`,
857
+ options: [
858
+ { id: 'allow', label: `Allow ${remaining} more`, description: 'Continue with a completely different approach. Stops for good at the limit.' },
859
+ { id: 'stop', label: 'Stop and report', description: 'End the task now with an evidence-based report of what failed.' }
860
+ ],
861
+ allowCustom: true,
862
+ ephemeral: true
863
+ });
864
+ return Boolean(answer && answer.optionId === 'allow');
704
865
  }
705
866
 
706
867
  recordWebArtifact(candidate: unknown): void {
707
868
  if (typeof candidate !== 'string' || !isScannableFile(candidate)) return;
869
+ const lower = candidate.toLowerCase();
870
+ // Exclude test files, spec files, python scripts, and backend code from invalidating web verification
871
+ if (/\b(?:test|spec|bench|unittest)\b/i.test(lower) || /\.(py|sh|rb|go|rs|json|ya?ml|md|sql)$/i.test(lower)) {
872
+ return;
873
+ }
708
874
  const expanded = candidate.startsWith('~/')
709
875
  ? path.join(os.homedir(), candidate.slice(2))
710
876
  : candidate;
711
877
  this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
712
878
  this.webVerificationScheduled = false;
713
- this.webVerificationState.browserActUsed = false;
714
- this.webVerificationState.screenshotTaken = false;
879
+ // Only reset browserActUsed if an actual DOM/HTML document changed
880
+ if (/\.html?$/i.test(lower)) {
881
+ this.webVerificationState.browserActUsed = false;
882
+ this.webVerificationState.screenshotTaken = false;
883
+ }
884
+ }
885
+
886
+ recordInspectedWebFile(candidate: unknown): void {
887
+ if (typeof candidate !== 'string' || !candidate.trim()) return;
888
+ const matches = candidate.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [candidate];
889
+ for (const rawMatch of matches) {
890
+ if (!isScannableFile(rawMatch)) continue;
891
+ const expanded = rawMatch.startsWith('~/')
892
+ ? path.join(os.homedir(), rawMatch.slice(2))
893
+ : rawMatch;
894
+ const resolved = path.resolve(this.workspaceRoot, expanded);
895
+ try {
896
+ if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
897
+ this.webArtifacts.add(resolved);
898
+ this.webVerificationState.htmlInspected = true;
899
+ }
900
+ } catch {
901
+ // ignore non-existent paths in shell commands
902
+ }
903
+ }
715
904
  }
716
905
 
717
906
  /**
@@ -1053,7 +1242,9 @@ export class AgentLoop {
1053
1242
  const id = `peer-file:${randomUUID()}:${tool}`;
1054
1243
  if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
1055
1244
  if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1056
- this.efficiencyBudget.recordAction();
1245
+ if (!this._inModelCall) {
1246
+ this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
1247
+ }
1057
1248
  let result: { success: boolean; error?: string; output?: string };
1058
1249
  if (tool === 'fs_read') {
1059
1250
  // ACP expects the actual requested text, not the host tool's paging
@@ -1119,8 +1310,24 @@ export class AgentLoop {
1119
1310
  }
1120
1311
  }
1121
1312
 
1122
- updateImplementationPlan(update: any) {
1123
- this._implementationPlan = update.plan.map((item: any) => ({ ...item }));
1313
+ updateImplementationPlan(update: any, options: { seeded?: boolean } = {}) {
1314
+ const nextPlan = update.plan.map((item: any) => ({ ...item }));
1315
+ const prevText = this._implementationPlan.map((item: any) => item.step).join('\n');
1316
+ const prevKey = JSON.stringify(this._implementationPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1317
+ const nextKey = JSON.stringify(nextPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1318
+ this._implementationPlan = nextPlan;
1319
+ if (options.seeded !== undefined) {
1320
+ this._implementationPlanSeeded = Boolean(options.seeded);
1321
+ } else {
1322
+ this._implementationPlanSeeded = false;
1323
+ }
1324
+ if (prevKey === nextKey) return;
1325
+ // A plan the model or user wrote names what the work needs. When its steps
1326
+ // change, go back to the list and decide again; status-only changes do not.
1327
+ if (!options.seeded) {
1328
+ const nextText = nextPlan.map((item: any) => item.step).join('\n');
1329
+ if (nextText !== prevText) this.routeTools({ source: 'plan', text: nextText });
1330
+ }
1124
1331
  this.emitEvent({
1125
1332
  type: 'agent_plan',
1126
1333
  explanation: update.explanation || '',
@@ -1133,11 +1340,64 @@ export class AgentLoop {
1133
1340
  });
1134
1341
  }
1135
1342
 
1343
+ seedTaskPhasePlanIfEmpty(): void {
1344
+ if (this._implementationPlan.length > 0) {
1345
+ this.emitEvent({
1346
+ type: 'agent_plan',
1347
+ explanation: this.taskShape?.archetypeLabel || 'Current Phase Plan',
1348
+ plan: this._implementationPlan.map((item: any) => ({ status: item.status, text: item.step, id: item.id }))
1349
+ });
1350
+ return;
1351
+ }
1352
+ const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
1353
+ if (!isActionableTaskPrompt(prompt)) return;
1354
+ const phases = this.taskShape?.phases;
1355
+ const effectivePhases = Array.isArray(phases) && phases.length >= 2
1356
+ ? phases
1357
+ : [
1358
+ { name: 'Research & Structure' },
1359
+ { name: 'Implementation' },
1360
+ { name: 'Verification & Quality Check' }
1361
+ ];
1362
+ const plan = effectivePhases.map((phase: any, idx: number) => ({
1363
+ id: `phase-${idx + 1}`,
1364
+ step: String(phase.name || `Step ${idx + 1}`).trim(),
1365
+ status: (idx === 0 ? 'in_progress' : 'pending') as 'in_progress' | 'pending'
1366
+ }));
1367
+ this.updateImplementationPlan({ explanation: this.taskShape?.archetypeLabel || 'Initial Phase Plan', plan }, { seeded: true });
1368
+ }
1369
+
1370
+ advanceImplementationPlanProgress(kind: 'mutation' | 'verification' | 'complete') {
1371
+ if (!Array.isArray(this._implementationPlan) || this._implementationPlan.length === 0) return;
1372
+ const keepSeeded = Boolean(this._implementationPlanSeeded);
1373
+ if (kind === 'complete') {
1374
+ if (this._implementationPlan.every((item: any) => item.status === 'completed')) return;
1375
+ this.updateImplementationPlan({
1376
+ explanation: 'Task completed.',
1377
+ plan: this._implementationPlan.map((item: any) => ({ ...item, status: 'completed' }))
1378
+ }, { seeded: keepSeeded });
1379
+ return;
1380
+ }
1381
+ if (this._implementationPlan.length < 2) return;
1382
+ const activeIndex = this._implementationPlan.findIndex((item: any) => item.status === 'in_progress');
1383
+ const currentIndex = activeIndex >= 0 ? activeIndex : 0;
1384
+ const lastIndex = this._implementationPlan.length - 1;
1385
+ const targetIndex = kind === 'verification'
1386
+ ? lastIndex
1387
+ : Math.min(currentIndex + 1, Math.max(0, lastIndex - 1));
1388
+ if (targetIndex <= currentIndex) return;
1389
+ const nextPlan = this._implementationPlan.map((item: any, idx: number) => ({
1390
+ ...item,
1391
+ status: idx < targetIndex ? 'completed' : idx === targetIndex ? 'in_progress' : 'pending'
1392
+ }));
1393
+ this.updateImplementationPlan({ explanation: '', plan: nextPlan }, { seeded: keepSeeded });
1394
+ }
1395
+
1136
1396
  async requestDecision(request: any) {
1137
1397
  const fingerprint = createHash('sha256')
1138
1398
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
1139
1399
  .digest('hex');
1140
- const remembered = this._decisionAnswers.get(fingerprint);
1400
+ const remembered = request.ephemeral === true ? null : this._decisionAnswers.get(fingerprint);
1141
1401
  if (remembered) return remembered;
1142
1402
 
1143
1403
  this.emitEvent({ type: 'decision_request', request });
@@ -1153,8 +1413,10 @@ export class AgentLoop {
1153
1413
  label: answer.label.trim(),
1154
1414
  custom: answer.custom === true
1155
1415
  };
1156
- this._decisionAnswers.set(fingerprint, normalized);
1416
+ if (request.ephemeral !== true) this._decisionAnswers.set(fingerprint, normalized);
1157
1417
  if (request.kind === 'architecture') this._decisionResolved = true;
1418
+ // The user's answer can change what the work needs (a framework, a medium).
1419
+ if (request.ephemeral !== true) this.routeTools({ source: 'plan', text: normalized.label });
1158
1420
  this.emitEvent({ type: 'decision_result', request, answer: normalized });
1159
1421
  auditLog.log({ event: 'decision_answered', taskId: this.taskId, kind: request.kind, custom: normalized.custom });
1160
1422
  return normalized;
@@ -1165,7 +1427,7 @@ export class AgentLoop {
1165
1427
  if (this._decisionRequirement.required && !this._decisionResolved) {
1166
1428
  return 'ARCHITECTURE_DECISION_REQUIRED: Before changing the system, call request_decision with kind "architecture", 2-4 concrete options, their consequences, and a clear reason. Do not ask about routine details; this checkpoint exists because the current request crosses a durable architecture boundary.';
1167
1429
  }
1168
- if (this._implementationPlanRequired && this._implementationPlan.length === 0) {
1430
+ if (this._implementationPlanRequired && (this._implementationPlan.length === 0 || this._implementationPlanSeeded)) {
1169
1431
  return 'IMPLEMENTATION_PLAN_REQUIRED: Call update_plan with atomic, verifiable steps and exactly one in_progress step before mutating this complex task.';
1170
1432
  }
1171
1433
  return null;
@@ -1307,7 +1569,10 @@ export class AgentLoop {
1307
1569
  this._lessonSimilarity = 0;
1308
1570
  this._lastToolResult = null;
1309
1571
  this._paradigmShiftPending = false;
1310
- this._implementationPlan = [];
1572
+ if (!Array.isArray(this._implementationPlan) || this._implementationPlan.length === 0) {
1573
+ this._implementationPlan = [];
1574
+ this._implementationPlanSeeded = false;
1575
+ }
1311
1576
  this._decisionAnswers = new Map();
1312
1577
  this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
1313
1578
  this._decisionResolved = !this._decisionRequirement.required;
@@ -1330,28 +1595,11 @@ export class AgentLoop {
1330
1595
  // measured budget without making the checkpoint undiscoverable.
1331
1596
  if (this._decisionRequirement.required) this.unlockedTools.add('request_decision');
1332
1597
 
1333
- // SmartToolsUse preloads likely tools but never changes a delegated
1334
- // subagent's permission scope. A task's intent is a routing hint, not an
1335
- // authorization boundary: later tool_search results must remain usable.
1336
- const smartScope = determineToolScope(this.userPrompt, this.taskShape);
1337
- if (smartScope.toolScope) {
1338
- for (const tool of smartScope.toolScope) this.unlockedTools.add(tool);
1339
- this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
1340
- }
1341
-
1342
- // Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
1343
- const scored = packsFromShape(this.taskShape);
1344
- const fallback = routePacks(this.userPrompt, this.workspaceContext);
1345
- const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
1346
- for (const pack of candidatePacks) {
1347
- if (pack === 'game' && isDirectGameTask(this.userPrompt)) continue;
1348
- this.unlockPack(pack);
1349
- }
1350
-
1351
1598
  // Reuse a known route before the first model call. Exact keyword-set
1352
1599
  // matches are always eligible; fuzzy reuse requires at least medium task
1353
1600
  // classification confidence because APC's threshold study shows that
1354
1601
  // aggressive fuzzy hits trade accuracy for speed.
1602
+ const cachedTools: string[] = [];
1355
1603
  try {
1356
1604
  this._planMatch = lookupPlan({
1357
1605
  prompt: this.userPrompt,
@@ -1363,9 +1611,7 @@ export class AgentLoop {
1363
1611
  this._planSimilarity = this._planMatch.similarity;
1364
1612
  for (const step of this._planMatch.template.steps || []) {
1365
1613
  if (!step.ok || !resolveTool(step.tool)) continue;
1366
- this.unlockedTools.add(step.tool);
1367
- const pack = packForTool(step.tool);
1368
- if (pack) this.unlockPack(pack);
1614
+ cachedTools.push(step.tool);
1369
1615
  }
1370
1616
  this.debugLog(
1371
1617
  `plan cache ${this._planMatch.matchType || 'fuzzy'} hit `
@@ -1378,9 +1624,26 @@ export class AgentLoop {
1378
1624
  this.debugLog(`plan cache lookup skipped: ${e.message}`);
1379
1625
  }
1380
1626
 
1627
+ // The tool pipeline. ToolsList is built first so every provider can be
1628
+ // shown it; decideTools picks from it, SmartTools bounds the choice, and
1629
+ // saveTools records it. Intent is a routing hint, never an authorization
1630
+ // boundary: a delegated subagent's toolScope still applies afterwards, and
1631
+ // later tool_search results stay usable.
1632
+ await this.ensureToolsList();
1633
+ this.restoreSavedTools();
1634
+ this.routeTools({
1635
+ source: 'intent',
1636
+ prompt: this.userPrompt,
1637
+ taskShape: this.taskShape,
1638
+ workspace: this.workspaceContext,
1639
+ cachedTools
1640
+ });
1641
+
1381
1642
  this.debugLog(`task shape: ${this.taskShape.archetype} (${this.taskShape.confidence} confidence)`);
1382
1643
  }
1383
1644
 
1645
+ this.seedTaskPhasePlanIfEmpty();
1646
+
1384
1647
  if (!this.isInitialized) {
1385
1648
  const activeTier = this.activeTier;
1386
1649
  const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
@@ -1540,25 +1803,31 @@ export class AgentLoop {
1540
1803
  // Fresh per task. A digest from a previous task would point at a step
1541
1804
  // number the model can no longer see, which is worse than paying twice.
1542
1805
  this._observationDigests = new Map();
1806
+ this.consecutiveThinkingSteps = 0;
1807
+ this.consecutiveBlockedActions = 0;
1543
1808
  this.consecutiveCommands = 0;
1544
1809
  this.circuitBreakerUnlocked = false;
1545
1810
  this.recentActionSignatures = [];
1546
1811
  this.consecutiveReadOnlySteps = 0;
1547
1812
  this.stallGuard.reset();
1548
1813
  this.smartToolsGovernor.reset();
1549
- this._smartToolsNudge = null;
1550
- this.tokenTracker.resetTask();
1551
- const turnArchetype = determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype;
1814
+ this._pendingConsent = null;
1815
+ this._recoveryNote = null;
1816
+ this._verificationNudges = 0;
1817
+ this._verificationPlanFired = false;
1818
+ const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
1819
+ if (!this.currentTaskPrompt && this.userPrompt) {
1820
+ this.currentTaskPrompt = this.userPrompt;
1821
+ }
1822
+ const turnArchetype = determineToolScope(effectivePrompt, this.taskShape).archetype;
1552
1823
  const efficiency = this.config.efficiency || {};
1553
1824
  const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0
1554
1825
  ? (this.taskTokenLimit as number)
1555
1826
  : this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && (this.tokenTracker.budget.maxTokensPerTask as number) > 0
1556
1827
  ? (this.tokenTracker.budget.maxTokensPerTask as number)
1557
- : Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
1558
- ? efficiency.maxTaskTokens
1559
- : Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1560
- ? efficiency.maxTurnTokens
1561
- : tokenLimitFor(turnArchetype);
1828
+ : Number.isFinite(efficiency.maxTaskTokens) && (efficiency.maxTaskTokens as number) > 0
1829
+ ? (efficiency.maxTaskTokens as number)
1830
+ : tokenLimitFor(turnArchetype);
1562
1831
  this.efficiencyBudget = new UnifiedBudgetEnforcer(
1563
1832
  Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
1564
1833
  ? efficiency.maxTurnTokens
@@ -1571,6 +1840,8 @@ export class AgentLoop {
1571
1840
  let mediaExplorationRecoveries = 0;
1572
1841
  let reasoningOnlyRecoveries = 0;
1573
1842
  let planHandoffRecoveries = 0;
1843
+ let incompleteTurnContinuations = 0;
1844
+ let toolRoutingRecoveries = 0;
1574
1845
 
1575
1846
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1576
1847
  while (!this.stopRequested) {
@@ -1589,6 +1860,10 @@ export class AgentLoop {
1589
1860
  this.messages.push({ role: 'system', content: this._smartToolsNudge });
1590
1861
  this._smartToolsNudge = null;
1591
1862
  }
1863
+ if (this._recoveryNote) {
1864
+ this.messages.push({ role: 'system', content: this._recoveryNote });
1865
+ this._recoveryNote = null;
1866
+ }
1592
1867
  // --- V8 MEMORY ARCHITECTURE: DECAY → WINDOW → REAL COMPACTION ---
1593
1868
  // The window is no longer only a view over an ever-growing array. Old
1594
1869
  // tool payloads decay into stubs, and anything amputated is physically
@@ -1666,7 +1941,9 @@ export class AgentLoop {
1666
1941
  if (dropped.length > 0) {
1667
1942
  const compactSummary = buildRecoverableDroppedSummary(
1668
1943
  dropped,
1669
- buildStructuralSummary(dropped) || describeDroppedMessages(dropped)
1944
+ buildCodexStyleSummary(dropped, this.currentTaskPrompt || this.userPrompt)
1945
+ || buildStructuralSummary(dropped)
1946
+ || describeDroppedMessages(dropped)
1670
1947
  );
1671
1948
  const removed = compactInPlace(this.messages, splitIndex, compactSummary);
1672
1949
  this._lastCompactionIndex = null;
@@ -1694,30 +1971,19 @@ export class AgentLoop {
1694
1971
 
1695
1972
  // Resolve the active toolset before assembling the prompt: the task
1696
1973
  // brief only cites tools the model can actually see right now.
1697
- // Providers with native schema deferral (Anthropic: `defer_loading` +
1698
- // `tool_search_tool_regex`) keep the whole core in context for free —
1699
- // the API holds the schemas server-side and expands them on demand,
1700
- // with no discovery round trip. Every OTHER provider was serialising
1701
- // all 24 core schemas into every request. There, ship the small resident
1702
- // set and let `tool_search` — the same mechanism that already
1703
- // unlocks packs — fetch the rest.
1704
- const residentOnly = this.llm.supportsToolSearch?.() !== true;
1705
- let dynamicTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
1706
- unlockedPacks: this.unlockedPacks,
1707
- unlockedTools: this.unlockedTools,
1708
- unlockOrder: this.unlockOrder,
1709
- grantAllTools: this.config.grantAllTools === true,
1974
+ // All transports receive the same compact catalog and selected host
1975
+ // schemas. Peer-native tools and native schema deferral remain provider
1976
+ // features; neither changes host authorization or schema selection.
1977
+ const eligibleTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
1978
+ grantAllTools: true,
1710
1979
  allowedTools: this.sandbox.allowedTools,
1711
- deniedTools: this.config.deniedTools,
1712
- residentOnly
1980
+ deniedTools: this.config.deniedTools
1713
1981
  });
1714
- // A delegated subagent runs with a declared toolScope. Enforcing it
1715
- // here — the one place the catalogue is assembled — is what makes the
1716
- // scope real; the previous implementation accepted the argument and
1717
- // ignored it entirely (finding D-7).
1718
- if (this.toolScope instanceof Set && this.toolScope.size > 0) {
1719
- dynamicTools = dynamicTools.filter((t: any) => this.toolScope.has(t.name));
1720
- }
1982
+ await this.ensureToolsList(eligibleTools);
1983
+ const permittedTools = this.toolScope instanceof Set && this.toolScope.size > 0
1984
+ ? eligibleTools.filter((tool: { name: string }) => this.toolScope.has(tool.name)) : eligibleTools;
1985
+ const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks,
1986
+ this.config.grantAllTools === true);
1721
1987
  const dynamicToolNames = dynamicTools.map((t: any) => t.name);
1722
1988
 
1723
1989
  // Dynamically inject the absolute latest System context
@@ -1725,7 +1991,21 @@ export class AgentLoop {
1725
1991
  const allowedPaths = this.sandbox.grantAllAccess
1726
1992
  ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
1727
1993
  : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
1728
- const providerPrompt = getProviderSpecificPrompt(this.config.provider);
1994
+ const baseProviderPrompt = getProviderSpecificPrompt(this.config.provider);
1995
+ const sensoryAwareness = this.llm.supportsVision
1996
+ ? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
1997
+ You have native multimodal vision perception. You can perceive rendered images, screenshots, and visual outputs directly.
1998
+ - For Web, UI, 3D, and visual design tasks: You MUST visually verify your work (using browser_act snapshot/screenshot or view_image) and actively cross-reference visual output against the codebase.
1999
+ - If visual rendering reveals visual bugs, layout misalignment, or runtime glitches, you must fix the code and re-verify before claiming completion.`
2000
+ : `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
2001
+ You are operating in a text-and-code modality without direct image pixel rendering.
2002
+ - For Web, UI, 3D, and visual tasks: Do NOT attempt raw visual inspection expecting image perception. Instead, verify programmatically:
2003
+ 1. Inspect the rendered DOM structure, computed hierarchy, and elements via browser_act (scrape / snapshot).
2004
+ 2. Check for JavaScript console and runtime errors (browser_act runtimeErrors).
2005
+ 3. Validate syntax and runtime integrity with code_verify_syntax and unit tests.
2006
+ 4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2007
+ - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2008
+ const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
1729
2009
  const memoryContext = getMemoryContextString();
1730
2010
 
1731
2011
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
@@ -1786,8 +2066,10 @@ export class AgentLoop {
1786
2066
  lazyPlaybookResult.microAnnouncements
1787
2067
  ].filter(Boolean).join('\n\n');
1788
2068
  auditLog.log({ event: 'smart_tools_context', taskId: this.taskId, step: this.stepsCompleted,
1789
- archetype: determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype,
2069
+ archetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1790
2070
  toolCount: dynamicTools.length, toolSchemaChars: JSON.stringify(dynamicTools).length,
2071
+ catalogTools: this.toolsListEntries?.length || 0, catalogChars: this.toolsListText.length,
2072
+ selectedToolCount: this.unlockedTools.size,
1791
2073
  playbookDomains: lazyPlaybookResult.activePlaybookDomains,
1792
2074
  playbookChars: activePlaybooks.length, planCacheHit: Boolean(this._planMatch) });
1793
2075
 
@@ -1841,7 +2123,7 @@ export class AgentLoop {
1841
2123
  // is stable within a task and gets its own breakpoint.
1842
2124
  {
1843
2125
  role: 'system',
1844
- content: `${taskBrief ? taskBrief + '\n\n' : ''}${getPackCatalogue(this.unlockedPacks)}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
2126
+ content: `${taskBrief ? taskBrief + '\n\n' : ''}${this.toolsListText || renderToolsList(buildToolsList())}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
1845
2127
  cacheAnchor: true
1846
2128
  },
1847
2129
  // [3] per-task STATIC context — provider activation, detected design,
@@ -1924,6 +2206,7 @@ export class AgentLoop {
1924
2206
  ];
1925
2207
  this.debugLog('request had no user/tool message; re-anchored before sending');
1926
2208
  }
2209
+ this._contextChars = measureMessages(prunedMessages);
1927
2210
 
1928
2211
  // BUDGET CEILING, CHECKED BEFORE SPENDING RATHER THAN AFTER.
1929
2212
  //
@@ -1947,8 +2230,10 @@ export class AgentLoop {
1947
2230
  taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity,
1948
2231
  dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
1949
2232
  ) : Infinity;
1950
- const remainingBudget = Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens());
1951
- if (remainingBudget <= 0) {
2233
+ const remainingBudget = hardBudget
2234
+ ? Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens())
2235
+ : Infinity;
2236
+ if (hardBudget && remainingBudget <= 0) {
1952
2237
  this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
1953
2238
  break;
1954
2239
  }
@@ -1959,28 +2244,59 @@ export class AgentLoop {
1959
2244
  }
1960
2245
  const affordability = this.tokenTracker.canAffordAnotherStep();
1961
2246
  if (!affordability.allowed) {
1962
- this.emitEvent({ type: 'budget_warning', message: affordability.reason });
1963
- this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
1964
- // A plan that was offered and did NOT carry the task through loses
1965
- // rank, so a stale template stops being suggested forever. Only the
1966
- // denominator moves here — recordPlan() is what awards a win.
1967
- if (this._offeredPlanId) {
1968
- try { recordMiss(this._offeredPlanId); } catch (e: any) { /* never block a stop */ }
2247
+ if (hardBudget) {
2248
+ this.emitEvent({ type: 'budget_warning', message: affordability.reason });
2249
+ this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
2250
+ if (this._offeredPlanId) {
2251
+ try { recordMiss(this._offeredPlanId); } catch (e: any) { /* never block a stop */ }
2252
+ }
2253
+ auditLog.log({
2254
+ event: 'task_stopped_on_budget', taskId: this.taskId,
2255
+ used: affordability.used, limit: affordability.limit, projected: affordability.projected
2256
+ });
2257
+ break;
2258
+ } else {
2259
+ // Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
2260
+ pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2261
+ shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2262
+ pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2263
+ this.efficiencyBudget?.extendBudget?.(1_000_000, 50);
1969
2264
  }
1970
- auditLog.log({
1971
- event: 'task_stopped_on_budget', taskId: this.taskId,
1972
- used: affordability.used, limit: affordability.limit, projected: affordability.projected
1973
- });
1974
- break;
1975
2265
  }
1976
2266
 
1977
2267
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
1978
2268
  // could reference the tools actually in context.
1979
2269
  let hasStreamedChunk = false;
2270
+ let streamedTextAccumulated = '';
2271
+ let hasStructuredToolPlan = this._implementationPlan.length > 0 && !this._implementationPlanSeeded;
1980
2272
  const streamingCode = new StreamingCodePreview();
1981
2273
  const nativeCodeObserver = new NativeCodeObserver(this.workspaceRoot, event => this.emitEvent(event));
1982
2274
  let reasoningAccumulated = '';
2275
+ let segmentReasoning = '';
1983
2276
  let thoughtStartedAt = 0;
2277
+ let nativeMutationCount = 0;
2278
+ let nativeExplorationCount = 0;
2279
+ const completedNativeActionIds = new Set<string>();
2280
+ const observedNativeTerminalIds = new Set<string>();
2281
+ const finalizeReasoningSegment = (): void => {
2282
+ if (!segmentReasoning) return;
2283
+ const content = segmentReasoning;
2284
+ const elapsedMs = thoughtStartedAt ? Math.max(1, Date.now() - thoughtStartedAt) : 0;
2285
+ segmentReasoning = '';
2286
+ thoughtStartedAt = 0;
2287
+ if (!hasStructuredToolPlan) {
2288
+ const extracted = extractLivePlanFromText(content, true);
2289
+ if (extracted) {
2290
+ this.updateImplementationPlan(extracted);
2291
+ }
2292
+ }
2293
+ this.emitEvent({
2294
+ type: 'agent_reasoning',
2295
+ content,
2296
+ streaming: false,
2297
+ elapsedMs
2298
+ });
2299
+ };
1984
2300
 
1985
2301
  this.emitEvent({ type: 'status', message: 'Thinking…' });
1986
2302
  this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
@@ -1989,14 +2305,16 @@ export class AgentLoop {
1989
2305
  const nativeControl = new AbortController();
1990
2306
  let nativeCheckpoint: EfficiencyCheckpoint | null = null;
1991
2307
  const invocation = ++modelCallIndex;
2308
+ this._inModelCall = true;
1992
2309
  const response = await this.llm.chat(prunedMessages, {
1993
2310
  taskId: this.taskId,
1994
2311
  conversationId: this.memoryManager?.sessionId || this.taskId,
1995
2312
  taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
1996
2313
  taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
1997
- maxTokensThisCall: Number.isFinite(remainingBudget) ? remainingBudget : undefined,
2314
+ hardBudget: hardBudget,
2315
+ maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
1998
2316
  tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
1999
- tokenLimit: Number.isFinite(remainingBudget) && remainingBudget > 0
2317
+ tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
2000
2318
  ? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
2001
2319
  maxNativeActions: this.efficiencyBudget.getRemainingActions(),
2002
2320
  workspaceRoot: this.workspaceRoot,
@@ -2010,13 +2328,28 @@ export class AgentLoop {
2010
2328
  coreToolCount: dynamicTools.filter((t: any) => isCoreTool(t.name)).length,
2011
2329
  signal: this.abortController?.signal
2012
2330
  ? AbortSignal.any([this.abortController.signal, nativeControl.signal]) : nativeControl.signal,
2331
+ onPlanUpdate: (rawPlan: unknown) => {
2332
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
2333
+ const normalized = normalizePeerPlanEntries(rawPlan);
2334
+ if (normalized) {
2335
+ hasStructuredToolPlan = true;
2336
+ this.updateImplementationPlan(normalized);
2337
+ }
2338
+ },
2013
2339
  onReasoningChunk: (chunk: string) => {
2014
2340
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
2015
2341
  if (!thoughtStartedAt) thoughtStartedAt = Date.now();
2016
2342
  reasoningAccumulated += chunk;
2343
+ segmentReasoning += chunk;
2344
+ if (!hasStructuredToolPlan && chunk.includes('\n')) {
2345
+ const extracted = extractLivePlanFromText(segmentReasoning, false);
2346
+ if (extracted) {
2347
+ this.updateImplementationPlan(extracted);
2348
+ }
2349
+ }
2017
2350
  this.emitEvent({
2018
2351
  type: 'agent_reasoning',
2019
- content: reasoningAccumulated,
2352
+ content: segmentReasoning,
2020
2353
  delta: chunk,
2021
2354
  streaming: true,
2022
2355
  elapsedMs: Date.now() - thoughtStartedAt
@@ -2024,28 +2357,141 @@ export class AgentLoop {
2024
2357
  },
2025
2358
  onChunk: (_chunk: string) => {
2026
2359
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
2360
+ finalizeReasoningSegment();
2361
+ streamedTextAccumulated += _chunk;
2027
2362
  if (!hasStreamedChunk) {
2028
2363
  hasStreamedChunk = true;
2029
2364
  this.emitEvent({ type: 'status', message: 'Responding…' });
2030
2365
  this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
2031
2366
  }
2367
+ if ((streamedTextAccumulated.includes('<tool_call>') || (!hasStructuredToolPlan && _chunk.includes('\n')))) {
2368
+ const extracted = extractLivePlanFromText(streamedTextAccumulated, false);
2369
+ if (extracted) {
2370
+ if (streamedTextAccumulated.includes('<tool_call>')) hasStructuredToolPlan = true;
2371
+ this.updateImplementationPlan(extracted);
2372
+ }
2373
+ }
2032
2374
  const preview = streamingCode.accept(_chunk);
2033
- if (preview) this.emitEvent(preview);
2375
+ if (preview) {
2376
+ this.emitEvent(preview);
2377
+ } else {
2378
+ const cleanProse = stripThinkBlocks(stripToolCallMarkup(streamedTextAccumulated));
2379
+ if (cleanProse && !cleanProse.startsWith('```')) {
2380
+ this.emitEvent({
2381
+ type: 'agent_message',
2382
+ content: cleanProse,
2383
+ delta: _chunk,
2384
+ streaming: true
2385
+ });
2386
+ }
2387
+ }
2034
2388
  },
2035
2389
  onNativeAction: (action: any) => {
2036
2390
  if (this.stopRequested || this.abortController?.signal?.aborted) return;
2037
2391
  if (!action || typeof action.name !== 'string') return;
2392
+ finalizeReasoningSegment();
2393
+ const actionPlan = normalizePeerPlanEntries(action.parameters);
2394
+ if (actionPlan) {
2395
+ hasStructuredToolPlan = true;
2396
+ this.updateImplementationPlan(actionPlan);
2397
+ }
2398
+ const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
2399
+ if (!isChecklistTool && this._implementationPlan.length === 0) {
2400
+ this.seedTaskPhasePlanIfEmpty();
2401
+ }
2038
2402
  auditLog.log({ event: 'native_action', taskId: this.taskId,
2039
2403
  provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2040
2404
  ...(action.id ? { actionId: action.id } : {}) });
2041
- if (action.status === 'running') {
2405
+ if (action.status === 'running' && !isChecklistTool) {
2042
2406
  try {
2043
2407
  this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
2044
2408
  } catch (error: unknown) {
2045
- if (error instanceof EfficiencyCheckpoint) { nativeCheckpoint = error; nativeControl.abort(); }
2409
+ if (error instanceof EfficiencyCheckpoint) {
2410
+ finalizeReasoningSegment();
2411
+ nativeCheckpoint = error;
2412
+ nativeControl.abort();
2413
+ }
2046
2414
  return;
2047
2415
  }
2048
2416
  }
2417
+ if (action.status === 'completed' && action.id && !isChecklistTool) {
2418
+ completedNativeActionIds.add(String(action.id));
2419
+ }
2420
+ const isCompleted = action.status === 'completed';
2421
+ const isFailed = action.status === 'failed';
2422
+ const actionArgs: Record<string, unknown> = {
2423
+ ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
2424
+ path: action.parameters?.path || action.parameters?.Path || action.parameters?.filePath || action.detail || '',
2425
+ command: action.parameters?.command || action.parameters?.cmd || (['bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes(action.name.toLowerCase()) ? action.detail : '')
2426
+ };
2427
+ const terminalId = action.id ? String(action.id) : '';
2428
+ const freshTerminal = !terminalId || !observedNativeTerminalIds.has(terminalId);
2429
+ if ((isCompleted || isFailed) && !isChecklistTool && freshTerminal && !this._pendingConsent) {
2430
+ if (terminalId) observedNativeTerminalIds.add(terminalId);
2431
+ const actionOutcome = {
2432
+ success: isCompleted,
2433
+ ...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
2434
+ };
2435
+ coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
2436
+ const recovery = this.timeMachine.observe(
2437
+ action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId)
2438
+ );
2439
+ // Pause now, not at the end of a potentially long peer turn.
2440
+ // An abort is a yield checkpoint, not a user denial or task success.
2441
+ if (recovery.kind === 'consent') {
2442
+ this._pendingConsent ??= { recovery, tool: action.name };
2443
+ nativeControl.abort();
2444
+ } else if (!this._pendingConsent && recovery.kind === 'replan') {
2445
+ this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
2446
+ } else if (!this._pendingConsent && (recovery.kind === 'stop' || recovery.kind === 'human')) {
2447
+ this.stopRequested = true;
2448
+ nativeControl.abort();
2449
+ this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, action.name) });
2450
+ }
2451
+ const phaseNudge = this.smartToolsGovernor.observe(action.name, actionArgs, actionOutcome);
2452
+ if (phaseNudge) this._smartToolsNudge = phaseNudge;
2453
+ else if (this.smartToolsGovernor.snapshot().phase === 'execution') this._smartToolsNudge = null;
2454
+ }
2455
+ if (isCompleted && !isChecklistTool) {
2456
+ const lowerName = action.name.toLowerCase();
2457
+ const rawDetail = String(action.detail || '');
2458
+ const lowerDetail = rawDetail.toLowerCase();
2459
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)) {
2460
+ nativeMutationCount++;
2461
+ if (nativeMutationCount === 1 && this._implementationPlanSeeded) {
2462
+ this.advanceImplementationPlanProgress('mutation');
2463
+ } else if (nativeMutationCount % 2 === 0) {
2464
+ this.advanceImplementationPlanProgress('mutation');
2465
+ }
2466
+ } else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2467
+ this.webVerificationState.browserActUsed = true;
2468
+ this.advanceImplementationPlanProgress('verification');
2469
+ } else if (lowerName === 'fs_read' && /\.(png|jpg|jpeg|webp)$/i.test(lowerDetail)) {
2470
+ this.advanceImplementationPlanProgress('verification');
2471
+ } else if (['fs_read', 'read_file', 'read', 'sysrun', 'bash', 'execute', 'run_command'].includes(lowerName)) {
2472
+ nativeExplorationCount++;
2473
+ if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2474
+ this.recordInspectedWebFile(rawDetail);
2475
+ }
2476
+ if (this._implementationPlanSeeded && nativeExplorationCount === 2) {
2477
+ const activeIdx = this._implementationPlan.findIndex((item: any) => item.status === 'in_progress');
2478
+ if (activeIdx === 0) {
2479
+ this.advanceImplementationPlanProgress('mutation');
2480
+ }
2481
+ }
2482
+ }
2483
+ if ((['screenshot', 'vision_inspect_ui'].includes(lowerName) ||
2484
+ (/\.(png|jpg|jpeg|webp)$/i.test(lowerDetail) && ['fs_read', 'read', 'read_file', 'view_file', 'view_image'].includes(lowerName))) &&
2485
+ this.llm.supportsVision) {
2486
+ this.webVerificationState.screenshotTaken = true;
2487
+ }
2488
+ if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
2489
+ this.webVerificationState.browserActUsed = true;
2490
+ }
2491
+ if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
2492
+ this.webVerificationState.htmlInspected = true;
2493
+ }
2494
+ }
2049
2495
  const nativeCode = codeProgressFromAction(
2050
2496
  action.name,
2051
2497
  { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
@@ -2054,6 +2500,9 @@ export class AgentLoop {
2054
2500
  action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working',
2055
2501
  'provider'
2056
2502
  );
2503
+ if (nativeCode || action.status === 'completed' || action.status === 'failed') {
2504
+ finalizeReasoningSegment();
2505
+ }
2057
2506
  if (nativeCode) {
2058
2507
  this.emitEvent(nativeCode);
2059
2508
  nativeCodeObserver.handle(nativeCode);
@@ -2064,20 +2513,45 @@ export class AgentLoop {
2064
2513
  const detail = action.detail ? ` ${action.detail}` : '';
2065
2514
  if (action.status === 'running') {
2066
2515
  this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
2067
- this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
2068
2516
  } else if (action.status === 'completed') {
2517
+ this.emitEvent({ type: 'status', message: '' });
2069
2518
  this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `${this.config.provider || 'Provider'} ${action.name}${detail}` });
2070
2519
  } else if (action.status === 'failed') {
2520
+ this.emitEvent({ type: 'status', message: '' });
2071
2521
  this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
2072
2522
  }
2073
2523
  }
2074
2524
  }).catch((error: unknown) => {
2075
- if (nativeCheckpoint && error && typeof error === 'object' && 'partialUsage' in error) {
2076
- Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
2525
+ if (this._pendingConsent) {
2526
+ this.stepsCompleted += completedNativeActionIds.size;
2527
+ const checkpoint = new RetryConsentCheckpoint();
2528
+ if (error && typeof error === 'object' && 'partialUsage' in error) {
2529
+ Object.assign(checkpoint, { partialUsage: error.partialUsage });
2530
+ }
2531
+ throw checkpoint;
2532
+ }
2533
+ if (nativeCheckpoint) {
2534
+ if (completedNativeActionIds.size > 0) {
2535
+ this.stepsCompleted += completedNativeActionIds.size;
2536
+ }
2537
+ if (reasoningAccumulated) {
2538
+ this.messages.push({
2539
+ role: 'assistant',
2540
+ content: 'Turn paused at efficiency checkpoint.',
2541
+ reasoning_content: reasoningAccumulated
2542
+ });
2543
+ }
2544
+ if (error && typeof error === 'object' && 'partialUsage' in error) {
2545
+ Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
2546
+ }
2077
2547
  }
2078
2548
  throw nativeCheckpoint || error;
2079
2549
  })
2080
- .finally(() => nativeCodeObserver.dispose());
2550
+ .finally(() => {
2551
+ finalizeReasoningSegment();
2552
+ nativeCodeObserver.dispose();
2553
+ this._inModelCall = false;
2554
+ });
2081
2555
  this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
2082
2556
 
2083
2557
  if (this.stopRequested || this.abortController?.signal?.aborted) {
@@ -2088,6 +2562,11 @@ export class AgentLoop {
2088
2562
  const finalCodePreview = streamingCode.flush();
2089
2563
  if (finalCodePreview) this.emitEvent(finalCodePreview);
2090
2564
 
2565
+ if (this._pendingConsent) {
2566
+ this.stepsCompleted += completedNativeActionIds.size;
2567
+ throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2568
+ }
2569
+
2091
2570
  // The call came back. Whatever went wrong before is no longer
2092
2571
  // consecutive — without this reset, one failure at step 2 and another
2093
2572
  // at step 200 would count toward the same ceiling and stop a task that
@@ -2117,6 +2596,7 @@ export class AgentLoop {
2117
2596
  uncachedPromptTokens: response.usage.uncachedPromptTokens,
2118
2597
  noncachedTokens: noncachedTokens(response.usage),
2119
2598
  measurement: response.usage.measurement || 'unspecified',
2599
+ measurementScope: response.usage.measurementScope || 'unspecified',
2120
2600
  cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
2121
2601
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
2122
2602
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
@@ -2172,7 +2652,7 @@ export class AgentLoop {
2172
2652
 
2173
2653
  // The host owns verification policy. A model cannot substitute repeated
2174
2654
  // HTTP checks for rendering, and adapters must not contradict this gate.
2175
- if (!response.toolCalls?.length && !this.webVerificationScheduled
2655
+ if (!response.toolCalls?.length && !response.toolRoutingError && !this.webVerificationScheduled
2176
2656
  && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
2177
2657
  && isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
2178
2658
  && !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
@@ -2223,15 +2703,23 @@ export class AgentLoop {
2223
2703
  } else if (reasoningAccumulated) {
2224
2704
  assistantMsg.reasoning_content = reasoningAccumulated;
2225
2705
  }
2226
- const finalReasoning = response.reasoningContent || reasoningAccumulated;
2227
- if (finalReasoning) {
2706
+ if (!reasoningAccumulated && response.reasoningContent) {
2228
2707
  this.emitEvent({
2229
2708
  type: 'agent_reasoning',
2230
- content: finalReasoning,
2709
+ content: response.reasoningContent,
2231
2710
  streaming: false,
2232
- elapsedMs: thoughtStartedAt ? Date.now() - thoughtStartedAt : 0
2711
+ elapsedMs: 0
2233
2712
  });
2234
2713
  }
2714
+ if (!hasStructuredToolPlan) {
2715
+ const fallbackPlan = extractLivePlanFromText(
2716
+ `${response.reasoningContent || ''}\n${response.content || ''}`,
2717
+ true
2718
+ );
2719
+ if (fallbackPlan) {
2720
+ this.updateImplementationPlan(fallbackPlan);
2721
+ }
2722
+ }
2235
2723
  // Kept verbatim on the turn. A thinking-enabled model that gets its own
2236
2724
  // thinking blocks back is continuing a thought; one that does not is
2237
2725
  // starting over, and with tool_use in the same turn the API can reject
@@ -2255,6 +2743,11 @@ export class AgentLoop {
2255
2743
  if (hasExternalActions) {
2256
2744
  this.stepsCompleted += completedExternalActions.length;
2257
2745
  for (const extAction of completedExternalActions) {
2746
+ const extPlan = normalizePeerPlanEntries(extAction.parameters);
2747
+ if (extPlan) {
2748
+ hasStructuredToolPlan = true;
2749
+ this.updateImplementationPlan(extPlan);
2750
+ }
2258
2751
  const actionName = String(extAction.name || '').toLowerCase();
2259
2752
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
2260
2753
  if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
@@ -2265,9 +2758,9 @@ export class AgentLoop {
2265
2758
  // has reached a vision-capable provider.
2266
2759
  // A native action label alone carries no rendered-page evidence.
2267
2760
  // The shared host inspection below verifies its resulting artifacts.
2268
- if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content'].includes(actionName) && detailPath) {
2269
- if (/\.(html|htm|css|jsx|tsx|vue|svelte)$/i.test(detailPath)) {
2270
- this.webVerificationState.htmlInspected = true;
2761
+ if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content', 'sysrun', 'bash'].includes(actionName) && detailPath) {
2762
+ if (/\.(html|htm|css|jsx|tsx|vue|svelte)\b/i.test(detailPath)) {
2763
+ this.recordInspectedWebFile(detailPath);
2271
2764
  }
2272
2765
  }
2273
2766
  }
@@ -2275,11 +2768,41 @@ export class AgentLoop {
2275
2768
 
2276
2769
  // If no tool calls, check if the agent is just thinking/planning or actually done
2277
2770
  if (!response.toolCalls || response.toolCalls.length === 0) {
2771
+ if (response.toolRoutingError) {
2772
+ const name = response.toolRoutingError.tool;
2773
+ if (toolRoutingRecoveries++ >= 1) {
2774
+ this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${name} through its native channel. Work remains unfinished.` });
2775
+ this.memoryManager.saveHistory(this.messages);
2776
+ break;
2777
+ }
2778
+ this.messages.push({ role: 'system', content:
2779
+ `[TOOL ROUTING REPAIR] ${name} is a Causyne host tool, not a peer-native function. `
2780
+ + `Return a complete <tool_call>{"name":${JSON.stringify(name)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
2781
+ + 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
2782
+ + 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
2783
+ this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${name}…` });
2784
+ auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: name });
2785
+ this.memoryManager.saveHistory(this.messages);
2786
+ continue;
2787
+ }
2278
2788
  const contentText = response.content || '';
2279
2789
  const lower = contentText.toLowerCase();
2280
2790
  const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2281
2791
  const isActionable = isActionableTaskPrompt(taskPrompt);
2282
2792
 
2793
+ if (!hasExternalActions && isProviderPlanOrQuotaRefusal(contentText)) {
2794
+ this.messages.pop();
2795
+ if (this.stepsCompleted === 0 && this.messages[this.messages.length - 1]?.role === 'user') {
2796
+ this.messages.pop();
2797
+ }
2798
+ this.emitEvent({
2799
+ type: 'error',
2800
+ message: `Provider plan or quota limit reached: ${contentText.trim()}`
2801
+ });
2802
+ this.memoryManager.saveHistory(this.messages);
2803
+ break;
2804
+ }
2805
+
2283
2806
  // A peer may have completed searches or a plan artifact while still
2284
2807
  // waiting for its own UI's Proceed button. Those actions do not
2285
2808
  // satisfy an implementation request in the enclosing Causyne loop.
@@ -2307,19 +2830,23 @@ export class AgentLoop {
2307
2830
  break;
2308
2831
  }
2309
2832
 
2833
+ if (hasExternalActions) {
2834
+ this.consecutiveThinkingSteps = 0;
2835
+ }
2836
+
2310
2837
  // A native workspace action already changed the workspace. Do not
2311
2838
  // demand a Causyne tool call for the same work, and do not treat the
2312
2839
  // turn as a no-op.
2313
- if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 2) {
2840
+ if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 3) {
2314
2841
  this.consecutiveThinkingSteps++;
2315
2842
  const blocked = failedExternalActions
2316
2843
  .map((a: any) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
2317
2844
  .join(', ');
2318
- this.emitEvent({ type: 'status', message: 'Native action blocked; switching to Causyne tools...' });
2319
- this.emitEvent({ type: 'agent_activity', activity: 'Retrying blocked action through Causyne…' });
2845
+ this.emitEvent({ type: 'status', message: 'Inspecting the failed native action before continuing...' });
2846
+ this.emitEvent({ type: 'agent_activity', activity: 'Checking the action failure…' });
2320
2847
  this.messages.push({
2321
2848
  role: 'system',
2322
- content: `[SYSTEM NOTICE: Your native action(s) were blocked: ${blocked}. Do not retry native terminal or browser tools. Instead use Causyne's XML tool call format, for example <tool_call>{"name": "sysRun", "arguments": {"command": "..."}}</tool_call>.]`
2849
+ content: `[SYSTEM NOTICE: Your native action(s) were blocked: ${blocked}. All file reads, writes, copies, and screenshot outputs must stay strictly inside the active workspace directory (${this.workspaceRoot}). Never read, copy (cp/mv), or write files in /tmp or outside the workspace root — write screenshots and temporary files directly to a path inside ${this.workspaceRoot} (for example ${path.join(this.workspaceRoot, 'preview.png')}), or invoke Causyne host tools using plain-text <tool_call>{"name": "browser_act", "arguments": {...}}</tool_call>.]`
2323
2850
  });
2324
2851
  this.memoryManager.saveHistory(this.messages);
2325
2852
  continue;
@@ -2377,25 +2904,28 @@ export class AgentLoop {
2377
2904
  continue;
2378
2905
  }
2379
2906
 
2380
- if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && this.consecutiveThinkingSteps < 3) {
2381
- this.consecutiveThinkingSteps++;
2907
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations < 3) {
2908
+ incompleteTurnContinuations++;
2382
2909
  if (response.content) {
2383
2910
  this.emitEvent({ type: 'agent_message', content: response.content });
2384
2911
  }
2912
+ const blockedNote = failedExternalActions.length > 0
2913
+ ? ` Note: ${failedExternalActions.map((a: any) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`).join(', ')} failed. Use their actual error results to choose the next step; honor user denials and the configured workspace policy without assuming a path-related cause.`
2914
+ : '';
2385
2915
  this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
2386
2916
  this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
2387
2917
  this.messages.push({
2388
2918
  role: 'system',
2389
2919
  content: isIncompleteTurn
2390
- ? '[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.]'
2391
- : '[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.]'
2920
+ ? `[SYSTEM NOTICE: Your previous turn ended while the task was still in progress. Continue immediately from where you left off and execute the remaining steps to complete the task.${blockedNote}]`
2921
+ : `[SYSTEM NOTICE: You announced the next step without executing it. Continue immediately from where you left off and execute the remaining file edits or tool calls to complete the task.${blockedNote}]`
2392
2922
  });
2393
2923
  this.memoryManager.saveHistory(this.messages);
2394
2924
  continue;
2395
2925
  }
2396
2926
 
2397
- if (hasExternalActions) {
2398
- this.consecutiveThinkingSteps = 0;
2927
+ if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
2928
+ incompleteTurnContinuations = 0;
2399
2929
  }
2400
2930
 
2401
2931
  if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
@@ -2405,7 +2935,7 @@ export class AgentLoop {
2405
2935
  this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
2406
2936
  this.messages.push({
2407
2937
  role: 'system',
2408
- content: `[SYSTEM NOTICE: An action or task was requested ("${taskPrompt}"), but no tools were called. Please invoke the appropriate tool by outputting: <tool_call>{"name": "tool_name", "arguments": {...}}</tool_call> to execute the task.]`
2938
+ content: `[SYSTEM NOTICE: An action or task was requested ("${taskPrompt}"), but no successful tool activity was observed in this turn. Use a tool available through your native channel or request an advertised Causyne host tool using a complete <tool_call>{"name": "tool_name", "arguments": {...}}</tool_call> in assistant text, then yield for its result. Do not invoke a host-only tool as a native function or repeat completed work.]`
2409
2939
  });
2410
2940
  this.memoryManager.saveHistory(this.messages);
2411
2941
  continue;
@@ -2419,6 +2949,18 @@ export class AgentLoop {
2419
2949
  break;
2420
2950
  }
2421
2951
 
2952
+ if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
2953
+ if (!contentText.trim()) {
2954
+ this.messages.pop();
2955
+ }
2956
+ this.emitEvent({
2957
+ type: 'error',
2958
+ message: 'The task stopped before completion after repeated blocked or incomplete turns. Work remains unfinished.'
2959
+ });
2960
+ this.memoryManager.saveHistory(this.messages);
2961
+ break;
2962
+ }
2963
+
2422
2964
  // --- COMPLETION GUARDS ---
2423
2965
  // Two hard rules learned the expensive way:
2424
2966
  // 1. Match on word boundaries. Substring matching made 'ui' fire on
@@ -2571,10 +3113,37 @@ export class AgentLoop {
2571
3113
  // Tool availability and a completed plan are not evidence of visual
2572
3114
  // inspection. A failed browser/capture attempt must not become a
2573
3115
  // successful task merely because the provider says "verified".
3116
+ const outcomes = coldObserver.getToolOutcomes(this.taskId);
3117
+ const hasBrowserActOutcome = outcomes.some(
3118
+ (o) => o.tool === 'browser_act' && o.success !== false
3119
+ );
3120
+ const hasPassingTests = outcomes.some(
3121
+ (o) => o.success && (isVerificationCommand(o.command || o.tool || '') || /\b(?:test|unittest|vitest|jest|pytest)\b/i.test(o.command || ''))
3122
+ ) || (Array.isArray(this._planSteps) && this._planSteps.some(s => s.success && /test/i.test(s.tool)));
3123
+
3124
+ let observerVerified = false;
3125
+ try {
3126
+ const observation = this.observer.evaluate({
3127
+ taskId: this.taskId,
3128
+ workspaceRoot: this.workspaceRoot,
3129
+ userGoal: this.currentTaskPrompt || this.userPrompt || '',
3130
+ agentClaim: response.content || '',
3131
+ toolHistory: outcomes
3132
+ });
3133
+ if (observation.verified || observation.status === 'verified') {
3134
+ observerVerified = true;
3135
+ }
3136
+ } catch {
3137
+ // fail-open
3138
+ }
3139
+
2574
3140
  const isVerified = Boolean(
2575
3141
  this.webVerificationState.browserActUsed ||
3142
+ hasBrowserActOutcome ||
2576
3143
  this.webVerificationState.screenshotTaken ||
2577
- (!browserReady && this.webVerificationState.htmlInspected)
3144
+ (!browserReady && this.webVerificationState.htmlInspected) ||
3145
+ hasPassingTests ||
3146
+ observerVerified
2578
3147
  );
2579
3148
  if (isWebTask && !browserReady && this.webVerificationState.htmlInspected
2580
3149
  && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
@@ -2590,6 +3159,29 @@ export class AgentLoop {
2590
3159
  break;
2591
3160
  }
2592
3161
 
3162
+ // Assess actual outcomes again after every verification attempt. A
3163
+ // one-shot reminder must not turn missing evidence into completion.
3164
+ if (this.stepsCompleted > 0 && !isWebTask) {
3165
+ const assessment = assessVerification({
3166
+ archetype: this.taskShape?.archetype,
3167
+ outcomes: coldObserver.getToolOutcomes(this.taskId),
3168
+ skip: ['web']
3169
+ });
3170
+ if (assessment.gaps.length > 0) {
3171
+ const domain = assessment.gaps[0]!.domain;
3172
+ const recovery = this.timeMachine.observe(`verification_${domain}`, {}, {
3173
+ success: false, error: 'Required outcome evidence is missing'
3174
+ }, coldObserver.getToolOutcomes(this.taskId));
3175
+ this.routeTools({ source: 'verification', requested: assessment.gaps.flatMap((gap) => [...gap.tools]) });
3176
+ const verdict = await this.handleRecovery(recovery, `Verification (${domain})`);
3177
+ if (verdict.stop) break;
3178
+ this.emitEvent({ type: 'status', message: `Verification check: ${assessment.gaps[0]!.need}` });
3179
+ this.messages.push({ role: 'system', content: `${assessment.directive} ${verdict.guidance}` });
3180
+ this.memoryManager.saveHistory(this.messages);
3181
+ continue;
3182
+ }
3183
+ }
3184
+
2593
3185
  // Cold Observer: Overconfidence & Loop Verification Check
2594
3186
  {
2595
3187
  try {
@@ -2597,7 +3189,7 @@ export class AgentLoop {
2597
3189
  taskId: this.taskId,
2598
3190
  userPrompt: this.currentTaskPrompt || this.userPrompt || '',
2599
3191
  agentClaim: response.content || '',
2600
- toolHistory: [],
3192
+ toolHistory: coldObserver.getToolOutcomes(this.taskId),
2601
3193
  stepsCompleted: this.stepsCompleted
2602
3194
  });
2603
3195
 
@@ -2606,14 +3198,11 @@ export class AgentLoop {
2606
3198
  success: false, error: coldAudit.discrepancy
2607
3199
  }, coldObserver.getToolOutcomes(this.taskId));
2608
3200
  this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
2609
- if (recovery.kind === 'stop') {
2610
- this.stopRequested = true;
2611
- this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, 'Verification') });
2612
- break;
2613
- }
3201
+ const verdict = await this.handleRecovery(recovery, 'Verification');
3202
+ if (verdict.stop) break;
2614
3203
  this.messages.push({
2615
3204
  role: 'system',
2616
- content: `${coldAudit.coldDirective} ${recovery.guidance}`
3205
+ content: `${coldAudit.coldDirective} ${verdict.guidance}`
2617
3206
  });
2618
3207
  this.memoryManager.saveHistory(this.messages);
2619
3208
  continue;
@@ -2623,6 +3212,31 @@ export class AgentLoop {
2623
3212
  }
2624
3213
  }
2625
3214
 
3215
+ // Unified Observer: Phase 7 progress and verification evaluation
3216
+ {
3217
+ try {
3218
+ const observation = this.observer.evaluate({
3219
+ taskId: this.taskId,
3220
+ workspaceRoot: this.workspaceRoot,
3221
+ userGoal: this.currentTaskPrompt || this.userPrompt || '',
3222
+ agentClaim: response.content || '',
3223
+ toolHistory: coldObserver.getToolOutcomes(this.taskId)
3224
+ });
3225
+
3226
+ if (observation.status === 'ready-to-verify' && !this._verificationPlanFired) {
3227
+ this.emitEvent({ type: 'status', message: `Observer: ${observation.message || 'Deliverables require verification check.'}` });
3228
+ this.messages.push({
3229
+ role: 'system',
3230
+ content: `[OBSERVER VERIFICATION]: ${observation.message || 'Deliverables require verification.'} Next action: ${observation.nextAction || 'Run tests or build to verify.'}`
3231
+ });
3232
+ this.memoryManager.saveHistory(this.messages);
3233
+ continue;
3234
+ }
3235
+ } catch (_err: any) {
3236
+ // Observer fail-open
3237
+ }
3238
+ }
3239
+
2626
3240
  if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
2627
3241
  const currentDesktopPictures = readMacDesktopPictures();
2628
3242
  if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
@@ -2635,6 +3249,9 @@ export class AgentLoop {
2635
3249
  if (response.content) {
2636
3250
  this.emitEvent({ type: 'agent_message', content: response.content });
2637
3251
  }
3252
+ if (this.stepsCompleted > 0) {
3253
+ this.advanceImplementationPlanProgress('complete');
3254
+ }
2638
3255
  this.emitEvent({ type: 'status', message: 'Task completed.' });
2639
3256
  this.memoryManager.saveHistory(this.messages); // Save final state
2640
3257
 
@@ -2962,12 +3579,15 @@ export class AgentLoop {
2962
3579
  continue;
2963
3580
  }
2964
3581
 
2965
- if (!isCoreTool(functionName) && !this.unlockedTools.has(functionName)) {
3582
+ if (!this.unlockedTools.has(functionName)) {
3583
+ // Calling a listed tool by name is a request for it. Its pack comes
3584
+ // with it so the matching playbook arrives when it becomes relevant.
2966
3585
  const pack = packForTool(functionName);
2967
- if (this.unlockPack(pack)) {
2968
- this.debugLog(`unlocked capability pack "${pack}" for ${functionName}`);
2969
- }
2970
- this.unlockedTools.add(functionName);
3586
+ this.routeTools({
3587
+ source: 'request',
3588
+ requested: [functionName],
3589
+ requestedPacks: []
3590
+ });
2971
3591
  }
2972
3592
 
2973
3593
  const validationErrors = this.validateToolArgs(functionName, args);
@@ -3180,13 +3800,15 @@ export class AgentLoop {
3180
3800
  this.emitEvent({ type: 'step_error', tool: functionName,
3181
3801
  error: `${errorType}: ${failure.error} (${recovery.attempt}/${recovery.maxAttempts})`,
3182
3802
  toolCallId: toolCall.id });
3803
+ const verdict = await this.handleRecovery(recovery, functionName);
3183
3804
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
3184
3805
  name: functionName, content: JSON.stringify({ ...failure,
3185
- errorType, timeMachine: recovery.guidance,
3806
+ errorType, timeMachine: verdict.guidance,
3186
3807
  ...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
3187
3808
  this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
3188
3809
  this.memoryManager.saveHistory(this.messages);
3189
- if (errorType === 'fatal' || recovery.kind === 'stop' || recovery.kind === 'human') {
3810
+ if (verdict.stop) break;
3811
+ if (errorType === 'fatal') {
3190
3812
  this.stopRequested = true;
3191
3813
  this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
3192
3814
  break;
@@ -3226,14 +3848,32 @@ export class AgentLoop {
3226
3848
  }
3227
3849
  }
3228
3850
 
3229
- if (['screenshot', 'vision_inspect_ui'].includes(functionName) && this.llm.supportsVision !== false && result?.success === true && result?._is_image_marker === true) {
3851
+ const imageCanReachModel = Boolean(this.llm.supportsVision && result?._is_image_marker === true
3852
+ && typeof result.base64 === 'string' && result.base64.length > 0);
3853
+ if (['screenshot', 'vision_inspect_ui', 'view_image'].includes(functionName) && result?.success === true && imageCanReachModel) {
3230
3854
  this.webVerificationState.screenshotTaken = true;
3231
3855
  }
3232
3856
  if (functionName === 'browser_act' && result?.success === true) {
3857
+ this.advanceImplementationPlanProgress('verification');
3233
3858
  const browserResults = Array.isArray(result.data) ? result.data : [];
3234
- if (browserResults.some((item: any) => ['snapshot', 'scrape'].includes(item?.action)
3235
- && Array.isArray(item?.data?.runtimeErrors) && item.data.runtimeErrors.length === 0)) {
3859
+ const allRuntimeErrors = browserResults.flatMap((item: any) =>
3860
+ Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []
3861
+ );
3862
+ const hasValidBrowserAction = browserResults.some((item: any) =>
3863
+ ['preview', 'snapshot', 'scrape', 'screenshot'].includes(item?.action)
3864
+ );
3865
+ if (allRuntimeErrors.length === 0 && (hasValidBrowserAction || result.url || result.tabId)) {
3236
3866
  this.webVerificationState.browserActUsed = true;
3867
+ } else if (allRuntimeErrors.length > 0) {
3868
+ this.webVerificationState.browserActUsed = false;
3869
+ this.emitEvent({
3870
+ type: 'status',
3871
+ message: `⚠️ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
3872
+ });
3873
+ this.messages.push({
3874
+ role: 'system',
3875
+ content: `[BROWSER RUNTIME ERRORS DETECTED: The page encountered runtime error(s) during preview:\n${allRuntimeErrors.slice(0, 5).join('\n')}\nYou MUST inspect your code, fix these runtime bugs, and re-verify before the task can be completed.]`
3876
+ });
3237
3877
  }
3238
3878
  }
3239
3879
 
@@ -3243,21 +3883,15 @@ export class AgentLoop {
3243
3883
  // is written only after post-hook review, so a formatter that rejects
3244
3884
  // a write is remembered as a failure rather than a success.
3245
3885
  const observedResult = result?._is_image_marker === true
3246
- ? { success: true, _is_image_marker: true, filename: result.filename, mimeType: result.mimeType }
3886
+ ? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
3247
3887
  : result;
3248
3888
  coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
3249
3889
  const recovery = this.timeMachine.observe(
3250
3890
  functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
3251
3891
  );
3252
- if (recovery.kind === 'replan') {
3253
- this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
3254
- }
3255
- if (recovery.kind === 'stop' || recovery.kind === 'human') {
3256
- this.stopRequested = true;
3257
- this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
3258
- }
3892
+ const verdict = await this.handleRecovery(recovery, functionName);
3259
3893
  if (result && (result.success === false || typeof result.error === 'string')) {
3260
- result = { ...result, timeMachine: recovery.guidance };
3894
+ result = { ...result, timeMachine: verdict.guidance };
3261
3895
  }
3262
3896
  if (this.stopRequested) {
3263
3897
  this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
@@ -3269,12 +3903,11 @@ export class AgentLoop {
3269
3903
  // PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
3270
3904
  // The control fields are stripped before the result reaches the LLM.
3271
3905
  if (result && (result._unlock_tools || result._unlock_packs)) {
3272
- for (const packName of result._unlock_packs || []) {
3273
- this.unlockPack(packName);
3274
- }
3275
- for (const toolName of result._unlock_tools || []) {
3276
- this.unlockedTools.add(toolName);
3277
- }
3906
+ this.routeTools({
3907
+ source: 'request',
3908
+ requested: (result._unlock_tools || []).filter((name: string) => resolveTool(name)),
3909
+ requestedPacks: result._unlock_packs || []
3910
+ });
3278
3911
  delete result._unlock_tools;
3279
3912
  delete result._unlock_packs;
3280
3913
  this.debugLog(`capability packs loaded: ${[...this.unlockedPacks].join(', ') || 'core only'}`);
@@ -3286,8 +3919,11 @@ export class AgentLoop {
3286
3919
  if (codeAction) this.emitEvent({ ...codeAction,
3287
3920
  phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
3288
3921
 
3922
+ const eventResult = result?._is_image_marker
3923
+ ? { success: result.success !== false && !result.error, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
3924
+ : result;
3289
3925
  this.emitEvent({ type: result?.success === false || typeof result?.error === 'string' ? 'step_error' : 'step_complete',
3290
- tool: functionName, result: result._is_image_marker ? '[IMAGE DATA]' : result, toolCallId: toolCall.id });
3926
+ tool: functionName, result: eventResult, toolCallId: toolCall.id });
3291
3927
  this.stepsCompleted++;
3292
3928
 
3293
3929
  // The procedure, as it actually ran. Tool name plus a whitelisted
@@ -3413,11 +4049,14 @@ export class AgentLoop {
3413
4049
  if (result && result._is_image_marker) {
3414
4050
  if (!this.llm.supportsVision) {
3415
4051
  // Fallback when vision streaming payload is not active on model
4052
+ const outputNote = typeof result.output === 'string' && result.output.trim()
4053
+ ? `\nDetails:\n${result.output.trim()}`
4054
+ : '';
3416
4055
  this.messages.push({
3417
4056
  role: 'tool',
3418
4057
  tool_call_id: toolCall.id,
3419
4058
  name: functionName,
3420
- content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
4059
+ content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]${outputNote}`
3421
4060
  });
3422
4061
  } else {
3423
4062
  // Provider-specific format.
@@ -3584,21 +4223,53 @@ export class AgentLoop {
3584
4223
  }
3585
4224
  }
3586
4225
  }
3587
- if (e instanceof EfficiencyCheckpoint) {
3588
- this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
4226
+ if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
4227
+ const pending = this._pendingConsent;
4228
+ this._pendingConsent = null;
4229
+ this.messages.push({ role: 'assistant', content:
4230
+ `Execution paused: ${pending.tool} failed ${pending.recovery.attempt} times. Keep completed work; do not replay earlier actions.` });
4231
+ this.memoryManager.saveHistory(this.messages);
4232
+ const verdict = await this.handleRecovery(pending.recovery, pending.tool);
4233
+ if (verdict.stop) break;
4234
+ this.messages.push({ role: 'system', content: verdict.guidance });
3589
4235
  this.memoryManager.saveHistory(this.messages);
4236
+ continue;
4237
+ }
4238
+ if (e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens' && incompleteTurnContinuations < 5) {
4239
+ incompleteTurnContinuations++;
3590
4240
  this.emitEvent({ type: 'budget_warning', message: e.message });
3591
- auditLog.log({ event: 'efficiency_checkpoint', taskId: this.taskId, reason: e.reason,
3592
- ...this.efficiencyBudget.snapshot() });
3593
- break;
4241
+ auditLog.log({
4242
+ event: 'efficiency_checkpoint',
4243
+ taskId: this.taskId,
4244
+ reason: e.reason,
4245
+ ...this.efficiencyBudget.snapshot()
4246
+ });
4247
+ this.efficiencyBudget.extendBudget?.(1_000_000, 50);
4248
+ compactSessionMessages(this.messages, {
4249
+ keepRecentTurns: 4,
4250
+ taskId: this.taskId,
4251
+ originalPrompt: this.currentTaskPrompt || this.userPrompt
4252
+ });
4253
+ this.emitEvent({ type: 'status', message: 'Continuing task execution from efficiency checkpoint…' });
4254
+ this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
4255
+ this.messages.push({
4256
+ role: 'system',
4257
+ content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Session history and files on disk are preserved. Do NOT repeat completed setup, inspections, or scans. Continue immediately from where you left off, implement the remaining features, and verify completion now.]`
4258
+ });
4259
+ this.memoryManager.saveHistory(this.messages);
4260
+ continue;
3594
4261
  }
3595
- if (e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
3596
- || e?.code === 'AGY_NATIVE_ACTION_BUDGET' || e?.code === 'AGY_DESKTOP_TASK_LIMIT') {
4262
+ if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
4263
+ || e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
3597
4264
  this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
3598
4265
  this.memoryManager.saveHistory(this.messages);
3599
4266
  this.emitEvent({ type: 'budget_warning', message: e.message });
3600
- auditLog.log({ event: 'task_stopped_on_budget', taskId: this.taskId,
3601
- used: this.tokenTracker.taskTokens, limit: e.tokenLimit || this.tokenTracker.budget?.maxTokensPerTask || 0 });
4267
+ auditLog.log({
4268
+ event: 'efficiency_checkpoint',
4269
+ taskId: this.taskId,
4270
+ reason: (e as any)?.reason || (e as any)?.code,
4271
+ ...this.efficiencyBudget.snapshot()
4272
+ });
3602
4273
  break;
3603
4274
  }
3604
4275
  if (e?.code === 'PROVIDER_REASONING_ONLY' && e.continuationSafe === true && reasoningOnlyRecoveries++ === 0) {
@@ -3716,17 +4387,25 @@ export class AgentLoop {
3716
4387
  // must not generate a second (and misleading) success event here.
3717
4388
  }
3718
4389
 
3719
- async waitForApproval(toolCallId: string) {
3720
-
3721
- return new Promise((resolve) => {
3722
- this.pendingApprovals.set(toolCallId, resolve);
3723
-
3724
- // Safety timeout: If user doesn't respond in 1 hour, auto-deny.
3725
- setTimeout(() => {
3726
- if (this.pendingApprovals.has(toolCallId)) {
3727
- this.handleApprovalResponse(toolCallId, false);
3728
- }
3729
- }, 3600000);
4390
+ async waitForApproval(toolCallId: string): Promise<boolean> {
4391
+ const signal = this.abortController?.signal;
4392
+ if (this.stopRequested || signal?.aborted) return false;
4393
+ return new Promise<boolean>((resolve) => {
4394
+ let settled = false;
4395
+ const finish = (approved: boolean): void => {
4396
+ if (settled) return;
4397
+ settled = true;
4398
+ clearTimeout(timer);
4399
+ signal?.removeEventListener('abort', onAbort);
4400
+ this.pendingApprovals.delete(toolCallId);
4401
+ resolve(approved === true);
4402
+ };
4403
+ const onAbort = (): void => finish(false);
4404
+ const timer = setTimeout(() => finish(false), 3600000);
4405
+ timer.unref();
4406
+ this.pendingApprovals.set(toolCallId, finish);
4407
+ signal?.addEventListener('abort', onAbort, { once: true });
4408
+ if (signal?.aborted) finish(false);
3730
4409
  });
3731
4410
  }
3732
4411
 
@@ -3761,6 +4440,9 @@ export class AgentLoop {
3761
4440
  if (spent > 0) return 'fatal';
3762
4441
  const msg = (error.message || '').toLowerCase();
3763
4442
 
4443
+ if (msg.includes('free usage limit') || msg.includes('subscribe to opencode') || msg.includes('opencode.ai/go') || msg.includes('insufficient_quota') || msg.includes('credit balance is too low')) {
4444
+ return 'fatal';
4445
+ }
3764
4446
  if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
3765
4447
  return 'syntax_error';
3766
4448
  }