@causyne/agent 1.20.13 → 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.
- package/package.json +1 -1
- package/src/SmartTools.js +33 -0
- package/src/SmartTools.ts +37 -0
- package/src/acp/client.js +157 -4
- package/src/acp/client.ts +152 -5
- package/src/agentLoop.js +857 -178
- package/src/agentLoop.ts +865 -183
- package/src/browser/browserRuntime.js +8 -1
- package/src/browser/browserRuntime.ts +8 -1
- package/src/browser/causyneBrowser.js +20 -4
- package/src/browser/causyneBrowser.ts +20 -4
- package/src/browser/urlPolicy.js +35 -0
- package/src/browser/urlPolicy.ts +34 -0
- package/src/cliMode.js +6 -2
- package/src/commands.js +14 -0
- package/src/contextManager.d.ts +1 -0
- package/src/core/contextCompactor.js +277 -0
- package/src/core/contextCompactor.ts +353 -0
- package/src/decideTools.js +157 -0
- package/src/decideTools.ts +195 -0
- package/src/decisionPolicy.js +5 -3
- package/src/decisionPolicy.ts +5 -3
- package/src/implementationPlan.js +284 -0
- package/src/implementationPlan.ts +275 -0
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +15 -7
- package/src/observer/evidence.js +11 -5
- package/src/observer/evidence.ts +13 -6
- package/src/observer.js +196 -0
- package/src/observer.ts +287 -0
- package/src/providers/acp.js +362 -109
- package/src/providers/acp.ts +359 -111
- package/src/providers/antigravity.js +133 -105
- package/src/providers/antigravity.ts +130 -109
- package/src/providers/base.d.ts +3 -0
- package/src/providers/budgetEnforcer.js +13 -0
- package/src/providers/budgetEnforcer.ts +13 -3
- package/src/provisioning/capabilityProvisioner.js +14 -10
- package/src/sandbox.js +4 -2
- package/src/saveTools.js +146 -0
- package/src/saveTools.ts +169 -0
- package/src/session/cachePressure.js +77 -0
- package/src/session/cachePressure.ts +122 -0
- package/src/smartToolsUse.js +69 -12
- package/src/smartToolsUse.ts +103 -12
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/timeMachine.js +55 -20
- package/src/timeMachine.ts +64 -20
- package/src/toolPacks.js +217 -310
- package/src/toolPacks.ts +505 -0
- package/src/tools/deferredMcpSearch.js +21 -13
- package/src/tools/deferredMcpSearch.ts +23 -15
- package/src/tools/updatePlan.js +2 -2
- package/src/tools/updatePlan.ts +2 -2
- package/src/toolsList.js +203 -0
- package/src/toolsList.ts +224 -0
- package/src/tui/chatRenderer.js +49 -14
- package/src/tui/codeStreamRenderer.js +16 -5
- package/src/tui/codeStreamRenderer.ts +14 -4
- package/src/tui/prompt.js +4 -2
- package/src/tui/sessionSidebar.js +10 -2
- package/src/tui/sessionSidebar.ts +10 -3
- package/src/tui/stageSurface.js +27 -1
- package/src/tui/text.d.ts +1 -0
- package/src/tui/turnRail.js +274 -0
- package/src/tui/turnRail.ts +334 -0
- package/src/types/contracts.ts +103 -0
- package/src/verificationPlan.js +141 -0
- package/src/verificationPlan.ts +166 -0
- package/src/toolPacks.d.ts +0 -10
package/src/agentLoop.js
CHANGED
|
@@ -7,7 +7,7 @@ import { pruneSessions as pruneEmbodimentSessions, describeSession } from './emb
|
|
|
7
7
|
import { WorkspacePerception } from './perception.js';
|
|
8
8
|
import { audioFormatForMimeType } from './providers/base.js';
|
|
9
9
|
import { TaskBuffer } from './taskBuffer.js';
|
|
10
|
-
import { TOOL_DEFINITIONS, getDynamicTools, resolveTool, canonicalToolName } from './tools/registry.js';
|
|
10
|
+
import { TOOL_DEFINITIONS, getDynamicTools, getSearchableToolDefinitions, resolveTool, canonicalToolName } from './tools/registry.js';
|
|
11
11
|
import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
|
|
12
12
|
import { validateToolArguments } from './tools/argumentValidation.js';
|
|
13
13
|
import { Sandbox } from './sandbox.js';
|
|
@@ -20,18 +20,27 @@ import { getMemoryContextString } from './memory.js';
|
|
|
20
20
|
import { MemoryManager } from './memoryManager.js';
|
|
21
21
|
import { cortexDb } from './cortex/vectorDb.js';
|
|
22
22
|
import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
|
|
23
|
-
import {
|
|
23
|
+
import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
|
|
24
|
+
import { analyzeTask, buildTaskBrief } from './taskShape.js';
|
|
24
25
|
import { lookupPlan, recordPlan, recordPlanAsync, recordMiss, renderPlanHint, toStep, recordAPCPipelineLatency, lookupAlternativeStep, failureClass } from './planCache.js';
|
|
25
26
|
import { routedConfig } from './modelRouter.js';
|
|
26
27
|
import { assessStep, isThrashing } from './uncertainty.js';
|
|
27
28
|
import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
|
|
29
|
+
import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks } from './implementationPlan.js';
|
|
28
30
|
import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
|
|
29
31
|
import { AGENT_USER_POLICY } from './agentPolicy.js';
|
|
30
32
|
import { VFETracker } from './vfeTracker.js';
|
|
31
33
|
import { coldObserver } from './observer/coldObserver.js';
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
34
|
+
import { isVerificationCommand } from './observer/evidence.js';
|
|
35
|
+
import { CausyneObserver, defaultObserver } from './observer.js';
|
|
36
|
+
import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
|
|
37
|
+
import { packForTool, isCoreTool, isGameIntent, isWebIntent, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
|
|
38
|
+
import { determineToolScope, resolveLazyPlaybooks, refineToolDecision, SmartToolsGovernor } from './smartToolsUse.js';
|
|
39
|
+
import { buildToolsList, renderToolsList, omittedCustomCount } from './toolsList.js';
|
|
40
|
+
import { assessVerification } from './verificationPlan.js';
|
|
41
|
+
import { SmartTools } from './SmartTools.js';
|
|
42
|
+
import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
|
|
43
|
+
import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
|
|
35
44
|
import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
|
|
36
45
|
// Provider imports
|
|
37
46
|
import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
|
|
@@ -56,11 +65,13 @@ export function isActionableTaskPrompt(text) {
|
|
|
56
65
|
const t = (text || '').trim();
|
|
57
66
|
if (!t)
|
|
58
67
|
return false;
|
|
59
|
-
const pureGreeting = /^(hi|hello|hey|yo|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
68
|
+
const pureGreeting = /^(hi|hello|hey|yo|halo|hai|p|assalamu['a]?[l]?aikum|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
|
|
60
69
|
if (pureGreeting)
|
|
61
70
|
return false;
|
|
62
|
-
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;
|
|
63
|
-
|
|
71
|
+
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;
|
|
72
|
+
if (actionKeywords.test(t))
|
|
73
|
+
return true;
|
|
74
|
+
return false; // Length alone does not turn an information question into an execution order.
|
|
64
75
|
}
|
|
65
76
|
export function isGenericHandoffResponse(text) {
|
|
66
77
|
const answer = (text || '').trim();
|
|
@@ -97,11 +108,20 @@ export function isCodeAuthoringTaskPrompt(text) {
|
|
|
97
108
|
return false;
|
|
98
109
|
if (isExecutionOrLaunchTaskPrompt(t))
|
|
99
110
|
return false;
|
|
100
|
-
return /\b(create|build|make|write|code|implement|generate|game|3js|
|
|
111
|
+
return /\b(create|build|make|write|code|implement|generate|game|3js|three?\.?js|three?js|app)\b/i.test(t);
|
|
101
112
|
}
|
|
102
113
|
export function isDirectGameTask(text) {
|
|
103
|
-
return
|
|
104
|
-
|
|
114
|
+
return isDirectGameTaskDecision(text);
|
|
115
|
+
}
|
|
116
|
+
export function isProviderPlanOrQuotaRefusal(text) {
|
|
117
|
+
if (!text || typeof text !== 'string')
|
|
118
|
+
return false;
|
|
119
|
+
const trimmed = text.trim();
|
|
120
|
+
if (!trimmed || trimmed.length > 320)
|
|
121
|
+
return false;
|
|
122
|
+
if (/^upgrade your plan to continue\.?$/i.test(trimmed))
|
|
123
|
+
return true;
|
|
124
|
+
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);
|
|
105
125
|
}
|
|
106
126
|
/**
|
|
107
127
|
* Detects when an agent response is an intermediate mid-task progress note or
|
|
@@ -193,7 +213,7 @@ Follow the selected project's existing style and architecture. Check dependencie
|
|
|
193
213
|
- Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
|
|
194
214
|
|
|
195
215
|
# Operational Guidelines & Communication
|
|
196
|
-
- **
|
|
216
|
+
- **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.
|
|
197
217
|
- **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.
|
|
198
218
|
- **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.
|
|
199
219
|
- **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.
|
|
@@ -202,7 +222,7 @@ Follow the selected project's existing style and architecture. Check dependencie
|
|
|
202
222
|
- **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
|
|
203
223
|
|
|
204
224
|
# Task Management & Planning
|
|
205
|
-
- 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.
|
|
225
|
+
- 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.
|
|
206
226
|
- 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.
|
|
207
227
|
- Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
|
|
208
228
|
- 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.
|
|
@@ -227,15 +247,15 @@ Follow the selected project's existing style and architecture. Check dependencie
|
|
|
227
247
|
- **Runnable Code**: Ensure generated code can be run immediately. Add all necessary imports, dependencies, and scaffolding (e.g. requirements.txt) if building from scratch.
|
|
228
248
|
|
|
229
249
|
# Git Workflow & Best Practices
|
|
230
|
-
- When asked to commit changes,
|
|
231
|
-
-
|
|
250
|
+
- 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.
|
|
251
|
+
- Zero feature explanations or commentary on commit subject lines.
|
|
232
252
|
|
|
233
253
|
# Security & Constraints (Causyne Architecture)
|
|
234
254
|
- **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
|
|
235
255
|
- **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
|
|
236
256
|
- **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
|
|
237
257
|
- **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.
|
|
238
|
-
- **SSRF Protection**: Do not fetch
|
|
258
|
+
- **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.
|
|
239
259
|
|
|
240
260
|
# ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
|
|
241
261
|
You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
|
|
@@ -335,6 +355,12 @@ You are Kimi — a model powered by KDA (Kimi Delta Attention) with a massive co
|
|
|
335
355
|
- Leverage your massive memory to reason holistically about the entire codebase structure before making surgical edits.
|
|
336
356
|
- You excel at end-to-end programming and agentic task decomposition.
|
|
337
357
|
- When reading large files, synthesize the global context. Do not lose track of the big picture.`;
|
|
358
|
+
}
|
|
359
|
+
if (p === 'antigravity') {
|
|
360
|
+
return `ANTIGRAVITY PEER COLLABORATION:
|
|
361
|
+
You are collaborating through the Antigravity high-performance local peer environment.
|
|
362
|
+
- Formulate precise, atomic actions and avoid repetitive back-and-forth chatter.
|
|
363
|
+
- Maintain rigorous execution standards: verify code syntax, inspect file changes, and avoid claiming completion without verified evidence.`;
|
|
338
364
|
}
|
|
339
365
|
return "";
|
|
340
366
|
}
|
|
@@ -421,6 +447,9 @@ export function explainNetworkError(error, config = {}) {
|
|
|
421
447
|
// classifyError() returns this for every connection-level failure. Assembled
|
|
422
448
|
// the same way the classifier does, so the two can never drift apart.
|
|
423
449
|
const NETWORK_ERROR_TYPE = "network_error";
|
|
450
|
+
class RetryConsentCheckpoint extends Error {
|
|
451
|
+
constructor() { super('Peer paused after three failed attempts; explicit retry approval is required.'); }
|
|
452
|
+
}
|
|
424
453
|
export class AgentLoop {
|
|
425
454
|
/**
|
|
426
455
|
* How many times in a row the same class of failure may repeat before the
|
|
@@ -482,6 +511,7 @@ export class AgentLoop {
|
|
|
482
511
|
this._decisionResolved = true;
|
|
483
512
|
this._implementationPlan = [];
|
|
484
513
|
this._implementationPlanRequired = false;
|
|
514
|
+
this._implementationPlanSeeded = false;
|
|
485
515
|
// A delegated subagent can tighten these two ceilings. They are applied
|
|
486
516
|
// after every config refresh so run() cannot accidentally replace a
|
|
487
517
|
// worker's declared bounds with the parent tier defaults.
|
|
@@ -506,6 +536,17 @@ export class AgentLoop {
|
|
|
506
536
|
// Unlock sequence drives append-only tool ordering, which is what keeps the
|
|
507
537
|
// prompt-cache prefix intact when a pack loads mid-task.
|
|
508
538
|
this.unlockOrder = [];
|
|
539
|
+
// Pipeline stage 4. It wraps the three collections above rather than
|
|
540
|
+
// replacing them, so every existing reader keeps seeing the same state.
|
|
541
|
+
this.smartTools = new SmartTools();
|
|
542
|
+
this.savedTools = new SavedTools({ packs: this.unlockedPacks, tools: this.unlockedTools, order: this.unlockOrder });
|
|
543
|
+
this.toolsListEntries = null;
|
|
544
|
+
this.toolsListText = '';
|
|
545
|
+
this._savedToolsRestored = false;
|
|
546
|
+
this._pendingConsent = null;
|
|
547
|
+
this._recoveryNote = null;
|
|
548
|
+
this._verificationNudges = 0;
|
|
549
|
+
this._verificationPlanFired = false;
|
|
509
550
|
this.workspaceContext = null;
|
|
510
551
|
this.activeSubproject = null;
|
|
511
552
|
this.taskShape = null;
|
|
@@ -536,10 +577,12 @@ export class AgentLoop {
|
|
|
536
577
|
// V5: Context compaction tracking
|
|
537
578
|
this._lastCompactionIndex = null;
|
|
538
579
|
this.timeMachine = new TimeMachine();
|
|
580
|
+
this.observer = defaultObserver;
|
|
539
581
|
this.isInitialized = false;
|
|
540
582
|
this.taskTemperature = 0.1; // Default
|
|
541
583
|
// Set only on a delegated subagent loop; null means "the full catalogue".
|
|
542
584
|
this.toolScope = null;
|
|
585
|
+
this._inModelCall = false;
|
|
543
586
|
}
|
|
544
587
|
/** True when this loop's own conversation scope has a standing approval. */
|
|
545
588
|
isAlwaysAllowed(toolName) {
|
|
@@ -590,22 +633,163 @@ export class AgentLoop {
|
|
|
590
633
|
* invalidates the cache for the tools, the system prompt and every message.
|
|
591
634
|
*/
|
|
592
635
|
unlockPack(packName) {
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
636
|
+
return this.savedTools.admitPack(packName);
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Pipeline stage 1. The list every provider is shown first: every tool the
|
|
640
|
+
* agent owns, one dense line each. Built once per conversation so the text is
|
|
641
|
+
* byte-stable and stays in the cached prompt prefix.
|
|
642
|
+
*/
|
|
643
|
+
async ensureToolsList(eligible) {
|
|
644
|
+
const definitions = eligible ?? await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
|
|
645
|
+
grantAllTools: true, allowedTools: this.sandbox.allowedTools, deniedTools: this.config.deniedTools
|
|
646
|
+
});
|
|
647
|
+
const scoped = this.toolScope instanceof Set && this.toolScope.size > 0
|
|
648
|
+
? definitions.filter((definition) => this.toolScope.has(definition.name)) : definitions;
|
|
649
|
+
this.toolsListEntries = buildToolsList(scoped);
|
|
650
|
+
this.toolsListText = renderToolsList(this.toolsListEntries);
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Stages 2-4 in one place: decide which listed tools the work needs, let
|
|
654
|
+
* SmartTools bound and shape that, then save what is admitted. Every way a
|
|
655
|
+
* tool can become needed — intent, a model request, an accepted plan,
|
|
656
|
+
* verification, recovery — comes through here, so there is one rule.
|
|
657
|
+
*/
|
|
658
|
+
routeTools(input) {
|
|
659
|
+
const list = this.toolsListEntries ?? buildToolsList();
|
|
660
|
+
const decision = decideTools({ ...input, list });
|
|
661
|
+
const refined = this.smartTools.refine(decision, {
|
|
662
|
+
planRequired: this._implementationPlanRequired,
|
|
663
|
+
decisionRequired: this._decisionRequirement.required && !this._decisionResolved,
|
|
664
|
+
admittedTools: this.unlockedTools,
|
|
665
|
+
admittedPacks: this.unlockedPacks
|
|
666
|
+
});
|
|
667
|
+
const added = this.savedTools.admit(refined);
|
|
668
|
+
if (added.addedTools.length > 0 || added.addedPacks.length > 0) {
|
|
669
|
+
this.persistSavedTools();
|
|
670
|
+
auditLog.log({ event: 'tools_admitted', taskId: this.taskId, source: refined.source, route: refined.route,
|
|
671
|
+
tools: added.addedTools.slice(0, 24), packs: added.addedPacks });
|
|
672
|
+
this.debugLog(`[tools] ${refined.source}: +${added.addedTools.length} tools, packs [${added.addedPacks.join(', ')}] (${refined.reasons.join('; ')})`);
|
|
673
|
+
}
|
|
674
|
+
return added;
|
|
675
|
+
}
|
|
676
|
+
async searchableTools() {
|
|
677
|
+
const eligible = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
|
|
678
|
+
grantAllTools: true, allowedTools: this.sandbox.allowedTools, deniedTools: this.config.deniedTools
|
|
679
|
+
});
|
|
680
|
+
return this.toolScope instanceof Set && this.toolScope.size > 0
|
|
681
|
+
? eligible.filter((tool) => this.toolScope.has(tool.name)) : eligible;
|
|
682
|
+
}
|
|
683
|
+
/** A resumed conversation starts with the tools it already earned. */
|
|
684
|
+
restoreSavedTools() {
|
|
685
|
+
if (this._savedToolsRestored)
|
|
686
|
+
return;
|
|
687
|
+
this._savedToolsRestored = true;
|
|
688
|
+
const key = this.memoryManager?.sessionId
|
|
689
|
+
? `${this.memoryManager.sessionId}\0${path.resolve(this.workspaceRoot)}` : null;
|
|
690
|
+
if (!key)
|
|
691
|
+
return;
|
|
692
|
+
const state = readSavedTools(key);
|
|
693
|
+
if (state) {
|
|
694
|
+
const eligible = new Set((this.toolsListEntries ?? []).map((entry) => entry.name));
|
|
695
|
+
// Restore names, not whole-pack permissions or obsolete definitions.
|
|
696
|
+
this.savedTools.restore({ tools: state.tools.filter((name) => eligible.has(name)), packs: [], order: [] });
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
persistSavedTools() {
|
|
700
|
+
const key = this.memoryManager?.sessionId
|
|
701
|
+
? `${this.memoryManager.sessionId}\0${path.resolve(this.workspaceRoot)}` : null;
|
|
702
|
+
if (key)
|
|
703
|
+
writeSavedTools(key, this.savedTools.toState());
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Apply a TimeMachine verdict. The agent may spend three attempts alone; the
|
|
707
|
+
* next three are the user's to grant. A `consent` verdict is therefore put to
|
|
708
|
+
* the user, and only an explicit approval lets the task continue.
|
|
709
|
+
*/
|
|
710
|
+
async handleRecovery(recovery, tool) {
|
|
711
|
+
if (recovery.kind === 'replan') {
|
|
712
|
+
this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
|
|
713
|
+
return { stop: false, guidance: recovery.guidance };
|
|
714
|
+
}
|
|
715
|
+
if (recovery.kind === 'consent') {
|
|
716
|
+
const remaining = recovery.maxAttempts - recovery.attempt;
|
|
717
|
+
if (await this.askRetryConsent(recovery, tool)) {
|
|
718
|
+
this.timeMachine.grantExtension(recovery.issueKey);
|
|
719
|
+
this.emitEvent({ type: 'status', message: `Retry limit extended: ${remaining} more attempts allowed for ${tool}.` });
|
|
720
|
+
auditLog.log({ event: 'retry_extension_granted', taskId: this.taskId, tool, attempt: recovery.attempt });
|
|
721
|
+
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.` };
|
|
722
|
+
}
|
|
723
|
+
this.stopRequested = true;
|
|
724
|
+
auditLog.log({ event: 'retry_extension_declined', taskId: this.taskId, tool, attempt: recovery.attempt });
|
|
725
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage({ ...recovery, kind: 'stop' }, tool) });
|
|
726
|
+
return { stop: true, guidance: recovery.guidance };
|
|
727
|
+
}
|
|
728
|
+
if (recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
729
|
+
this.stopRequested = true;
|
|
730
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, tool) });
|
|
731
|
+
return { stop: true, guidance: recovery.guidance };
|
|
732
|
+
}
|
|
733
|
+
return { stop: false, guidance: recovery.guidance };
|
|
734
|
+
}
|
|
735
|
+
/** True only on an explicit "allow". A custom answer, a dismissal or no UI at all is a no. */
|
|
736
|
+
async askRetryConsent(recovery, tool) {
|
|
737
|
+
const remaining = recovery.maxAttempts - recovery.attempt;
|
|
738
|
+
const answer = await this.requestDecision({
|
|
739
|
+
id: randomUUID(),
|
|
740
|
+
kind: 'workflow',
|
|
741
|
+
header: 'More attempts?',
|
|
742
|
+
question: `${tool} failed ${recovery.attempt} times (${recovery.failureClass || 'unclassified'}). Allow up to ${remaining} more attempts?`,
|
|
743
|
+
reason: `Each further attempt repeats similar edits and checks and costs more time and tokens. The hard limit is ${recovery.maxAttempts} attempts.`,
|
|
744
|
+
options: [
|
|
745
|
+
{ id: 'allow', label: `Allow ${remaining} more`, description: 'Continue with a completely different approach. Stops for good at the limit.' },
|
|
746
|
+
{ id: 'stop', label: 'Stop and report', description: 'End the task now with an evidence-based report of what failed.' }
|
|
747
|
+
],
|
|
748
|
+
allowCustom: true,
|
|
749
|
+
ephemeral: true
|
|
750
|
+
});
|
|
751
|
+
return Boolean(answer && answer.optionId === 'allow');
|
|
598
752
|
}
|
|
599
753
|
recordWebArtifact(candidate) {
|
|
600
754
|
if (typeof candidate !== 'string' || !isScannableFile(candidate))
|
|
601
755
|
return;
|
|
756
|
+
const lower = candidate.toLowerCase();
|
|
757
|
+
// Exclude test files, spec files, python scripts, and backend code from invalidating web verification
|
|
758
|
+
if (/\b(?:test|spec|bench|unittest)\b/i.test(lower) || /\.(py|sh|rb|go|rs|json|ya?ml|md|sql)$/i.test(lower)) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
602
761
|
const expanded = candidate.startsWith('~/')
|
|
603
762
|
? path.join(os.homedir(), candidate.slice(2))
|
|
604
763
|
: candidate;
|
|
605
764
|
this.webArtifacts.add(path.resolve(this.workspaceRoot, expanded));
|
|
606
765
|
this.webVerificationScheduled = false;
|
|
607
|
-
|
|
608
|
-
|
|
766
|
+
// Only reset browserActUsed if an actual DOM/HTML document changed
|
|
767
|
+
if (/\.html?$/i.test(lower)) {
|
|
768
|
+
this.webVerificationState.browserActUsed = false;
|
|
769
|
+
this.webVerificationState.screenshotTaken = false;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
recordInspectedWebFile(candidate) {
|
|
773
|
+
if (typeof candidate !== 'string' || !candidate.trim())
|
|
774
|
+
return;
|
|
775
|
+
const matches = candidate.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [candidate];
|
|
776
|
+
for (const rawMatch of matches) {
|
|
777
|
+
if (!isScannableFile(rawMatch))
|
|
778
|
+
continue;
|
|
779
|
+
const expanded = rawMatch.startsWith('~/')
|
|
780
|
+
? path.join(os.homedir(), rawMatch.slice(2))
|
|
781
|
+
: rawMatch;
|
|
782
|
+
const resolved = path.resolve(this.workspaceRoot, expanded);
|
|
783
|
+
try {
|
|
784
|
+
if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
|
|
785
|
+
this.webArtifacts.add(resolved);
|
|
786
|
+
this.webVerificationState.htmlInspected = true;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
// ignore non-existent paths in shell commands
|
|
791
|
+
}
|
|
792
|
+
}
|
|
609
793
|
}
|
|
610
794
|
/**
|
|
611
795
|
* Build the parts of the system context that are constant for a whole task.
|
|
@@ -969,7 +1153,9 @@ export class AgentLoop {
|
|
|
969
1153
|
throw new Error('The requested ACP file operation was not authorized');
|
|
970
1154
|
if (tool === 'fs_write')
|
|
971
1155
|
captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
|
|
972
|
-
this.
|
|
1156
|
+
if (!this._inModelCall) {
|
|
1157
|
+
this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
|
|
1158
|
+
}
|
|
973
1159
|
let result;
|
|
974
1160
|
if (tool === 'fs_read') {
|
|
975
1161
|
// ACP expects the actual requested text, not the host tool's paging
|
|
@@ -1036,8 +1222,27 @@ export class AgentLoop {
|
|
|
1036
1222
|
this.pendingApprovals.delete(toolCallId);
|
|
1037
1223
|
}
|
|
1038
1224
|
}
|
|
1039
|
-
updateImplementationPlan(update) {
|
|
1040
|
-
|
|
1225
|
+
updateImplementationPlan(update, options = {}) {
|
|
1226
|
+
const nextPlan = update.plan.map((item) => ({ ...item }));
|
|
1227
|
+
const prevText = this._implementationPlan.map((item) => item.step).join('\n');
|
|
1228
|
+
const prevKey = JSON.stringify(this._implementationPlan.map((item) => ({ id: item.id, step: item.step, status: item.status })));
|
|
1229
|
+
const nextKey = JSON.stringify(nextPlan.map((item) => ({ id: item.id, step: item.step, status: item.status })));
|
|
1230
|
+
this._implementationPlan = nextPlan;
|
|
1231
|
+
if (options.seeded !== undefined) {
|
|
1232
|
+
this._implementationPlanSeeded = Boolean(options.seeded);
|
|
1233
|
+
}
|
|
1234
|
+
else {
|
|
1235
|
+
this._implementationPlanSeeded = false;
|
|
1236
|
+
}
|
|
1237
|
+
if (prevKey === nextKey)
|
|
1238
|
+
return;
|
|
1239
|
+
// A plan the model or user wrote names what the work needs. When its steps
|
|
1240
|
+
// change, go back to the list and decide again; status-only changes do not.
|
|
1241
|
+
if (!options.seeded) {
|
|
1242
|
+
const nextText = nextPlan.map((item) => item.step).join('\n');
|
|
1243
|
+
if (nextText !== prevText)
|
|
1244
|
+
this.routeTools({ source: 'plan', text: nextText });
|
|
1245
|
+
}
|
|
1041
1246
|
this.emitEvent({
|
|
1042
1247
|
type: 'agent_plan',
|
|
1043
1248
|
explanation: update.explanation || '',
|
|
@@ -1049,11 +1254,67 @@ export class AgentLoop {
|
|
|
1049
1254
|
completed: this._implementationPlan.filter((item) => item.status === 'completed').length
|
|
1050
1255
|
});
|
|
1051
1256
|
}
|
|
1257
|
+
seedTaskPhasePlanIfEmpty() {
|
|
1258
|
+
if (this._implementationPlan.length > 0) {
|
|
1259
|
+
this.emitEvent({
|
|
1260
|
+
type: 'agent_plan',
|
|
1261
|
+
explanation: this.taskShape?.archetypeLabel || 'Current Phase Plan',
|
|
1262
|
+
plan: this._implementationPlan.map((item) => ({ status: item.status, text: item.step, id: item.id }))
|
|
1263
|
+
});
|
|
1264
|
+
return;
|
|
1265
|
+
}
|
|
1266
|
+
const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1267
|
+
if (!isActionableTaskPrompt(prompt))
|
|
1268
|
+
return;
|
|
1269
|
+
const phases = this.taskShape?.phases;
|
|
1270
|
+
const effectivePhases = Array.isArray(phases) && phases.length >= 2
|
|
1271
|
+
? phases
|
|
1272
|
+
: [
|
|
1273
|
+
{ name: 'Research & Structure' },
|
|
1274
|
+
{ name: 'Implementation' },
|
|
1275
|
+
{ name: 'Verification & Quality Check' }
|
|
1276
|
+
];
|
|
1277
|
+
const plan = effectivePhases.map((phase, idx) => ({
|
|
1278
|
+
id: `phase-${idx + 1}`,
|
|
1279
|
+
step: String(phase.name || `Step ${idx + 1}`).trim(),
|
|
1280
|
+
status: (idx === 0 ? 'in_progress' : 'pending')
|
|
1281
|
+
}));
|
|
1282
|
+
this.updateImplementationPlan({ explanation: this.taskShape?.archetypeLabel || 'Initial Phase Plan', plan }, { seeded: true });
|
|
1283
|
+
}
|
|
1284
|
+
advanceImplementationPlanProgress(kind) {
|
|
1285
|
+
if (!Array.isArray(this._implementationPlan) || this._implementationPlan.length === 0)
|
|
1286
|
+
return;
|
|
1287
|
+
const keepSeeded = Boolean(this._implementationPlanSeeded);
|
|
1288
|
+
if (kind === 'complete') {
|
|
1289
|
+
if (this._implementationPlan.every((item) => item.status === 'completed'))
|
|
1290
|
+
return;
|
|
1291
|
+
this.updateImplementationPlan({
|
|
1292
|
+
explanation: 'Task completed.',
|
|
1293
|
+
plan: this._implementationPlan.map((item) => ({ ...item, status: 'completed' }))
|
|
1294
|
+
}, { seeded: keepSeeded });
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
if (this._implementationPlan.length < 2)
|
|
1298
|
+
return;
|
|
1299
|
+
const activeIndex = this._implementationPlan.findIndex((item) => item.status === 'in_progress');
|
|
1300
|
+
const currentIndex = activeIndex >= 0 ? activeIndex : 0;
|
|
1301
|
+
const lastIndex = this._implementationPlan.length - 1;
|
|
1302
|
+
const targetIndex = kind === 'verification'
|
|
1303
|
+
? lastIndex
|
|
1304
|
+
: Math.min(currentIndex + 1, Math.max(0, lastIndex - 1));
|
|
1305
|
+
if (targetIndex <= currentIndex)
|
|
1306
|
+
return;
|
|
1307
|
+
const nextPlan = this._implementationPlan.map((item, idx) => ({
|
|
1308
|
+
...item,
|
|
1309
|
+
status: idx < targetIndex ? 'completed' : idx === targetIndex ? 'in_progress' : 'pending'
|
|
1310
|
+
}));
|
|
1311
|
+
this.updateImplementationPlan({ explanation: '', plan: nextPlan }, { seeded: keepSeeded });
|
|
1312
|
+
}
|
|
1052
1313
|
async requestDecision(request) {
|
|
1053
1314
|
const fingerprint = createHash('sha256')
|
|
1054
1315
|
.update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option) => option.id) }))
|
|
1055
1316
|
.digest('hex');
|
|
1056
|
-
const remembered = this._decisionAnswers.get(fingerprint);
|
|
1317
|
+
const remembered = request.ephemeral === true ? null : this._decisionAnswers.get(fingerprint);
|
|
1057
1318
|
if (remembered)
|
|
1058
1319
|
return remembered;
|
|
1059
1320
|
this.emitEvent({ type: 'decision_request', request });
|
|
@@ -1069,9 +1330,13 @@ export class AgentLoop {
|
|
|
1069
1330
|
label: answer.label.trim(),
|
|
1070
1331
|
custom: answer.custom === true
|
|
1071
1332
|
};
|
|
1072
|
-
|
|
1333
|
+
if (request.ephemeral !== true)
|
|
1334
|
+
this._decisionAnswers.set(fingerprint, normalized);
|
|
1073
1335
|
if (request.kind === 'architecture')
|
|
1074
1336
|
this._decisionResolved = true;
|
|
1337
|
+
// The user's answer can change what the work needs (a framework, a medium).
|
|
1338
|
+
if (request.ephemeral !== true)
|
|
1339
|
+
this.routeTools({ source: 'plan', text: normalized.label });
|
|
1075
1340
|
this.emitEvent({ type: 'decision_result', request, answer: normalized });
|
|
1076
1341
|
auditLog.log({ event: 'decision_answered', taskId: this.taskId, kind: request.kind, custom: normalized.custom });
|
|
1077
1342
|
return normalized;
|
|
@@ -1082,7 +1347,7 @@ export class AgentLoop {
|
|
|
1082
1347
|
if (this._decisionRequirement.required && !this._decisionResolved) {
|
|
1083
1348
|
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.';
|
|
1084
1349
|
}
|
|
1085
|
-
if (this._implementationPlanRequired && this._implementationPlan.length === 0) {
|
|
1350
|
+
if (this._implementationPlanRequired && (this._implementationPlan.length === 0 || this._implementationPlanSeeded)) {
|
|
1086
1351
|
return 'IMPLEMENTATION_PLAN_REQUIRED: Call update_plan with atomic, verifiable steps and exactly one in_progress step before mutating this complex task.';
|
|
1087
1352
|
}
|
|
1088
1353
|
return null;
|
|
@@ -1221,7 +1486,10 @@ export class AgentLoop {
|
|
|
1221
1486
|
this._lessonSimilarity = 0;
|
|
1222
1487
|
this._lastToolResult = null;
|
|
1223
1488
|
this._paradigmShiftPending = false;
|
|
1224
|
-
this._implementationPlan
|
|
1489
|
+
if (!Array.isArray(this._implementationPlan) || this._implementationPlan.length === 0) {
|
|
1490
|
+
this._implementationPlan = [];
|
|
1491
|
+
this._implementationPlanSeeded = false;
|
|
1492
|
+
}
|
|
1225
1493
|
this._decisionAnswers = new Map();
|
|
1226
1494
|
this._decisionRequirement = assessDecisionRequirement(this.userPrompt || '');
|
|
1227
1495
|
this._decisionResolved = !this._decisionRequirement.required;
|
|
@@ -1240,28 +1508,11 @@ export class AgentLoop {
|
|
|
1240
1508
|
// measured budget without making the checkpoint undiscoverable.
|
|
1241
1509
|
if (this._decisionRequirement.required)
|
|
1242
1510
|
this.unlockedTools.add('request_decision');
|
|
1243
|
-
// SmartToolsUse preloads likely tools but never changes a delegated
|
|
1244
|
-
// subagent's permission scope. A task's intent is a routing hint, not an
|
|
1245
|
-
// authorization boundary: later tool_search results must remain usable.
|
|
1246
|
-
const smartScope = determineToolScope(this.userPrompt, this.taskShape);
|
|
1247
|
-
if (smartScope.toolScope) {
|
|
1248
|
-
for (const tool of smartScope.toolScope)
|
|
1249
|
-
this.unlockedTools.add(tool);
|
|
1250
|
-
this.debugLog(`[SmartToolsUse] preloaded ${smartScope.toolScope.size} tools (${smartScope.archetype})`);
|
|
1251
|
-
}
|
|
1252
|
-
// Scored routing, with the regex router as a safety net, filtered by SmartToolsUse suppression
|
|
1253
|
-
const scored = packsFromShape(this.taskShape);
|
|
1254
|
-
const fallback = routePacks(this.userPrompt, this.workspaceContext);
|
|
1255
|
-
const candidatePacks = filterSuppressedPacks([...scored, ...fallback], this.userPrompt);
|
|
1256
|
-
for (const pack of candidatePacks) {
|
|
1257
|
-
if (pack === 'game' && isDirectGameTask(this.userPrompt))
|
|
1258
|
-
continue;
|
|
1259
|
-
this.unlockPack(pack);
|
|
1260
|
-
}
|
|
1261
1511
|
// Reuse a known route before the first model call. Exact keyword-set
|
|
1262
1512
|
// matches are always eligible; fuzzy reuse requires at least medium task
|
|
1263
1513
|
// classification confidence because APC's threshold study shows that
|
|
1264
1514
|
// aggressive fuzzy hits trade accuracy for speed.
|
|
1515
|
+
const cachedTools = [];
|
|
1265
1516
|
try {
|
|
1266
1517
|
this._planMatch = lookupPlan({
|
|
1267
1518
|
prompt: this.userPrompt,
|
|
@@ -1274,10 +1525,7 @@ export class AgentLoop {
|
|
|
1274
1525
|
for (const step of this._planMatch.template.steps || []) {
|
|
1275
1526
|
if (!step.ok || !resolveTool(step.tool))
|
|
1276
1527
|
continue;
|
|
1277
|
-
|
|
1278
|
-
const pack = packForTool(step.tool);
|
|
1279
|
-
if (pack)
|
|
1280
|
-
this.unlockPack(pack);
|
|
1528
|
+
cachedTools.push(step.tool);
|
|
1281
1529
|
}
|
|
1282
1530
|
this.debugLog(`plan cache ${this._planMatch.matchType || 'fuzzy'} hit `
|
|
1283
1531
|
+ `${(this._planMatch.similarity * 100).toFixed(0)}% `
|
|
@@ -1288,8 +1536,23 @@ export class AgentLoop {
|
|
|
1288
1536
|
catch (e) {
|
|
1289
1537
|
this.debugLog(`plan cache lookup skipped: ${e.message}`);
|
|
1290
1538
|
}
|
|
1539
|
+
// The tool pipeline. ToolsList is built first so every provider can be
|
|
1540
|
+
// shown it; decideTools picks from it, SmartTools bounds the choice, and
|
|
1541
|
+
// saveTools records it. Intent is a routing hint, never an authorization
|
|
1542
|
+
// boundary: a delegated subagent's toolScope still applies afterwards, and
|
|
1543
|
+
// later tool_search results stay usable.
|
|
1544
|
+
await this.ensureToolsList();
|
|
1545
|
+
this.restoreSavedTools();
|
|
1546
|
+
this.routeTools({
|
|
1547
|
+
source: 'intent',
|
|
1548
|
+
prompt: this.userPrompt,
|
|
1549
|
+
taskShape: this.taskShape,
|
|
1550
|
+
workspace: this.workspaceContext,
|
|
1551
|
+
cachedTools
|
|
1552
|
+
});
|
|
1291
1553
|
this.debugLog(`task shape: ${this.taskShape.archetype} (${this.taskShape.confidence} confidence)`);
|
|
1292
1554
|
}
|
|
1555
|
+
this.seedTaskPhasePlanIfEmpty();
|
|
1293
1556
|
if (!this.isInitialized) {
|
|
1294
1557
|
const activeTier = this.activeTier;
|
|
1295
1558
|
const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
|
|
@@ -1441,15 +1704,23 @@ export class AgentLoop {
|
|
|
1441
1704
|
// Fresh per task. A digest from a previous task would point at a step
|
|
1442
1705
|
// number the model can no longer see, which is worse than paying twice.
|
|
1443
1706
|
this._observationDigests = new Map();
|
|
1707
|
+
this.consecutiveThinkingSteps = 0;
|
|
1708
|
+
this.consecutiveBlockedActions = 0;
|
|
1444
1709
|
this.consecutiveCommands = 0;
|
|
1445
1710
|
this.circuitBreakerUnlocked = false;
|
|
1446
1711
|
this.recentActionSignatures = [];
|
|
1447
1712
|
this.consecutiveReadOnlySteps = 0;
|
|
1448
1713
|
this.stallGuard.reset();
|
|
1449
1714
|
this.smartToolsGovernor.reset();
|
|
1450
|
-
this.
|
|
1451
|
-
this.
|
|
1452
|
-
|
|
1715
|
+
this._pendingConsent = null;
|
|
1716
|
+
this._recoveryNote = null;
|
|
1717
|
+
this._verificationNudges = 0;
|
|
1718
|
+
this._verificationPlanFired = false;
|
|
1719
|
+
const effectivePrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
1720
|
+
if (!this.currentTaskPrompt && this.userPrompt) {
|
|
1721
|
+
this.currentTaskPrompt = this.userPrompt;
|
|
1722
|
+
}
|
|
1723
|
+
const turnArchetype = determineToolScope(effectivePrompt, this.taskShape).archetype;
|
|
1453
1724
|
const efficiency = this.config.efficiency || {};
|
|
1454
1725
|
const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
|
|
1455
1726
|
? this.taskTokenLimit
|
|
@@ -1457,9 +1728,7 @@ export class AgentLoop {
|
|
|
1457
1728
|
? this.tokenTracker.budget.maxTokensPerTask
|
|
1458
1729
|
: Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
|
|
1459
1730
|
? efficiency.maxTaskTokens
|
|
1460
|
-
:
|
|
1461
|
-
? efficiency.maxTurnTokens
|
|
1462
|
-
: tokenLimitFor(turnArchetype);
|
|
1731
|
+
: tokenLimitFor(turnArchetype);
|
|
1463
1732
|
this.efficiencyBudget = new UnifiedBudgetEnforcer(Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
|
|
1464
1733
|
? efficiency.maxTurnTokens
|
|
1465
1734
|
: turnTokenLimitFor(turnArchetype), Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype), taskTokenCeiling);
|
|
@@ -1468,6 +1737,8 @@ export class AgentLoop {
|
|
|
1468
1737
|
let mediaExplorationRecoveries = 0;
|
|
1469
1738
|
let reasoningOnlyRecoveries = 0;
|
|
1470
1739
|
let planHandoffRecoveries = 0;
|
|
1740
|
+
let incompleteTurnContinuations = 0;
|
|
1741
|
+
let toolRoutingRecoveries = 0;
|
|
1471
1742
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1472
1743
|
while (!this.stopRequested) {
|
|
1473
1744
|
if (this.stopRequested) {
|
|
@@ -1484,6 +1755,10 @@ export class AgentLoop {
|
|
|
1484
1755
|
this.messages.push({ role: 'system', content: this._smartToolsNudge });
|
|
1485
1756
|
this._smartToolsNudge = null;
|
|
1486
1757
|
}
|
|
1758
|
+
if (this._recoveryNote) {
|
|
1759
|
+
this.messages.push({ role: 'system', content: this._recoveryNote });
|
|
1760
|
+
this._recoveryNote = null;
|
|
1761
|
+
}
|
|
1487
1762
|
// --- V8 MEMORY ARCHITECTURE: DECAY → WINDOW → REAL COMPACTION ---
|
|
1488
1763
|
// The window is no longer only a view over an ever-growing array. Old
|
|
1489
1764
|
// tool payloads decay into stubs, and anything amputated is physically
|
|
@@ -1557,7 +1832,9 @@ export class AgentLoop {
|
|
|
1557
1832
|
if (splitIndex >= 1) {
|
|
1558
1833
|
const dropped = this.messages.slice(1, splitIndex + 1);
|
|
1559
1834
|
if (dropped.length > 0) {
|
|
1560
|
-
const compactSummary = buildRecoverableDroppedSummary(dropped,
|
|
1835
|
+
const compactSummary = buildRecoverableDroppedSummary(dropped, buildCodexStyleSummary(dropped, this.currentTaskPrompt || this.userPrompt)
|
|
1836
|
+
|| buildStructuralSummary(dropped)
|
|
1837
|
+
|| describeDroppedMessages(dropped));
|
|
1561
1838
|
const removed = compactInPlace(this.messages, splitIndex, compactSummary);
|
|
1562
1839
|
this._lastCompactionIndex = null;
|
|
1563
1840
|
this.debugLog(`compacted ${removed} messages out of the live context`);
|
|
@@ -1583,37 +1860,39 @@ export class AgentLoop {
|
|
|
1583
1860
|
}
|
|
1584
1861
|
// Resolve the active toolset before assembling the prompt: the task
|
|
1585
1862
|
// brief only cites tools the model can actually see right now.
|
|
1586
|
-
//
|
|
1587
|
-
//
|
|
1588
|
-
//
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
// set and let `tool_search` — the same mechanism that already
|
|
1592
|
-
// unlocks packs — fetch the rest.
|
|
1593
|
-
const residentOnly = this.llm.supportsToolSearch?.() !== true;
|
|
1594
|
-
let dynamicTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
|
|
1595
|
-
unlockedPacks: this.unlockedPacks,
|
|
1596
|
-
unlockedTools: this.unlockedTools,
|
|
1597
|
-
unlockOrder: this.unlockOrder,
|
|
1598
|
-
grantAllTools: this.config.grantAllTools === true,
|
|
1863
|
+
// All transports receive the same compact catalog and selected host
|
|
1864
|
+
// schemas. Peer-native tools and native schema deferral remain provider
|
|
1865
|
+
// features; neither changes host authorization or schema selection.
|
|
1866
|
+
const eligibleTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
|
|
1867
|
+
grantAllTools: true,
|
|
1599
1868
|
allowedTools: this.sandbox.allowedTools,
|
|
1600
|
-
deniedTools: this.config.deniedTools
|
|
1601
|
-
residentOnly
|
|
1869
|
+
deniedTools: this.config.deniedTools
|
|
1602
1870
|
});
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
if (this.toolScope instanceof Set && this.toolScope.size > 0) {
|
|
1608
|
-
dynamicTools = dynamicTools.filter((t) => this.toolScope.has(t.name));
|
|
1609
|
-
}
|
|
1871
|
+
await this.ensureToolsList(eligibleTools);
|
|
1872
|
+
const permittedTools = this.toolScope instanceof Set && this.toolScope.size > 0
|
|
1873
|
+
? eligibleTools.filter((tool) => this.toolScope.has(tool.name)) : eligibleTools;
|
|
1874
|
+
const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks, this.config.grantAllTools === true);
|
|
1610
1875
|
const dynamicToolNames = dynamicTools.map((t) => t.name);
|
|
1611
1876
|
// Dynamically inject the absolute latest System context
|
|
1612
1877
|
const autonomyMode = this.config.autonomyMode || 'C';
|
|
1613
1878
|
const allowedPaths = this.sandbox.grantAllAccess
|
|
1614
1879
|
? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
|
|
1615
1880
|
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
|
|
1616
|
-
const
|
|
1881
|
+
const baseProviderPrompt = getProviderSpecificPrompt(this.config.provider);
|
|
1882
|
+
const sensoryAwareness = this.llm.supportsVision
|
|
1883
|
+
? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
|
|
1884
|
+
You have native multimodal vision perception. You can perceive rendered images, screenshots, and visual outputs directly.
|
|
1885
|
+
- 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.
|
|
1886
|
+
- If visual rendering reveals visual bugs, layout misalignment, or runtime glitches, you must fix the code and re-verify before claiming completion.`
|
|
1887
|
+
: `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
|
|
1888
|
+
You are operating in a text-and-code modality without direct image pixel rendering.
|
|
1889
|
+
- For Web, UI, 3D, and visual tasks: Do NOT attempt raw visual inspection expecting image perception. Instead, verify programmatically:
|
|
1890
|
+
1. Inspect the rendered DOM structure, computed hierarchy, and elements via browser_act (scrape / snapshot).
|
|
1891
|
+
2. Check for JavaScript console and runtime errors (browser_act runtimeErrors).
|
|
1892
|
+
3. Validate syntax and runtime integrity with code_verify_syntax and unit tests.
|
|
1893
|
+
4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
|
|
1894
|
+
- For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
|
|
1895
|
+
const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
|
|
1617
1896
|
const memoryContext = getMemoryContextString();
|
|
1618
1897
|
// --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
|
|
1619
1898
|
// Cortex retrieval, design detection, creative-pattern lookup and the
|
|
@@ -1667,8 +1946,10 @@ export class AgentLoop {
|
|
|
1667
1946
|
lazyPlaybookResult.microAnnouncements
|
|
1668
1947
|
].filter(Boolean).join('\n\n');
|
|
1669
1948
|
auditLog.log({ event: 'smart_tools_context', taskId: this.taskId, step: this.stepsCompleted,
|
|
1670
|
-
archetype: determineToolScope(this.currentTaskPrompt || '', this.taskShape).archetype,
|
|
1949
|
+
archetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
1671
1950
|
toolCount: dynamicTools.length, toolSchemaChars: JSON.stringify(dynamicTools).length,
|
|
1951
|
+
catalogTools: this.toolsListEntries?.length || 0, catalogChars: this.toolsListText.length,
|
|
1952
|
+
selectedToolCount: this.unlockedTools.size,
|
|
1672
1953
|
playbookDomains: lazyPlaybookResult.activePlaybookDomains,
|
|
1673
1954
|
playbookChars: activePlaybooks.length, planCacheHit: Boolean(this._planMatch) });
|
|
1674
1955
|
// The task brief turns "here are 28 tools" into "here is the order to
|
|
@@ -1719,7 +2000,7 @@ export class AgentLoop {
|
|
|
1719
2000
|
// is stable within a task and gets its own breakpoint.
|
|
1720
2001
|
{
|
|
1721
2002
|
role: 'system',
|
|
1722
|
-
content: `${taskBrief ? taskBrief + '\n\n' : ''}${
|
|
2003
|
+
content: `${taskBrief ? taskBrief + '\n\n' : ''}${this.toolsListText || renderToolsList(buildToolsList())}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
|
|
1723
2004
|
cacheAnchor: true
|
|
1724
2005
|
},
|
|
1725
2006
|
// [3] per-task STATIC context — provider activation, detected design,
|
|
@@ -1796,6 +2077,7 @@ export class AgentLoop {
|
|
|
1796
2077
|
];
|
|
1797
2078
|
this.debugLog('request had no user/tool message; re-anchored before sending');
|
|
1798
2079
|
}
|
|
2080
|
+
this._contextChars = measureMessages(prunedMessages);
|
|
1799
2081
|
// BUDGET CEILING, CHECKED BEFORE SPENDING RATHER THAN AFTER.
|
|
1800
2082
|
//
|
|
1801
2083
|
// trackUsage() below stops the loop once the ceiling has ALREADY been
|
|
@@ -1815,8 +2097,10 @@ export class AgentLoop {
|
|
|
1815
2097
|
? (await this.tokenTracker.getDailyUsage()).totalTokens : 0;
|
|
1816
2098
|
const configuredRemainingBudget = hardBudget
|
|
1817
2099
|
? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
|
|
1818
|
-
const remainingBudget =
|
|
1819
|
-
|
|
2100
|
+
const remainingBudget = hardBudget
|
|
2101
|
+
? Math.min(configuredRemainingBudget, this.efficiencyBudget.getRemainingTokens())
|
|
2102
|
+
: Infinity;
|
|
2103
|
+
if (hardBudget && remainingBudget <= 0) {
|
|
1820
2104
|
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
1821
2105
|
break;
|
|
1822
2106
|
}
|
|
@@ -1827,44 +2111,79 @@ export class AgentLoop {
|
|
|
1827
2111
|
}
|
|
1828
2112
|
const affordability = this.tokenTracker.canAffordAnotherStep();
|
|
1829
2113
|
if (!affordability.allowed) {
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
2114
|
+
if (hardBudget) {
|
|
2115
|
+
this.emitEvent({ type: 'budget_warning', message: affordability.reason });
|
|
2116
|
+
this.emitEvent({ type: 'notice', message: 'Stopped before the token ceiling. Nothing was truncated mid-step.' });
|
|
2117
|
+
if (this._offeredPlanId) {
|
|
2118
|
+
try {
|
|
2119
|
+
recordMiss(this._offeredPlanId);
|
|
2120
|
+
}
|
|
2121
|
+
catch (e) { /* never block a stop */ }
|
|
1838
2122
|
}
|
|
1839
|
-
|
|
2123
|
+
auditLog.log({
|
|
2124
|
+
event: 'task_stopped_on_budget', taskId: this.taskId,
|
|
2125
|
+
used: affordability.used, limit: affordability.limit, projected: affordability.projected
|
|
2126
|
+
});
|
|
2127
|
+
break;
|
|
2128
|
+
}
|
|
2129
|
+
else {
|
|
2130
|
+
// Proactive history compaction rather than artificial abort (OpenCode / SWE-agent pattern)
|
|
2131
|
+
pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
|
|
2132
|
+
shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
2133
|
+
pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
2134
|
+
this.efficiencyBudget?.extendBudget?.(1_000_000, 50);
|
|
1840
2135
|
}
|
|
1841
|
-
auditLog.log({
|
|
1842
|
-
event: 'task_stopped_on_budget', taskId: this.taskId,
|
|
1843
|
-
used: affordability.used, limit: affordability.limit, projected: affordability.projected
|
|
1844
|
-
});
|
|
1845
|
-
break;
|
|
1846
2136
|
}
|
|
1847
2137
|
// 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
|
|
1848
2138
|
// could reference the tools actually in context.
|
|
1849
2139
|
let hasStreamedChunk = false;
|
|
2140
|
+
let streamedTextAccumulated = '';
|
|
2141
|
+
let hasStructuredToolPlan = this._implementationPlan.length > 0 && !this._implementationPlanSeeded;
|
|
1850
2142
|
const streamingCode = new StreamingCodePreview();
|
|
1851
2143
|
const nativeCodeObserver = new NativeCodeObserver(this.workspaceRoot, event => this.emitEvent(event));
|
|
1852
2144
|
let reasoningAccumulated = '';
|
|
2145
|
+
let segmentReasoning = '';
|
|
1853
2146
|
let thoughtStartedAt = 0;
|
|
2147
|
+
let nativeMutationCount = 0;
|
|
2148
|
+
let nativeExplorationCount = 0;
|
|
2149
|
+
const completedNativeActionIds = new Set();
|
|
2150
|
+
const observedNativeTerminalIds = new Set();
|
|
2151
|
+
const finalizeReasoningSegment = () => {
|
|
2152
|
+
if (!segmentReasoning)
|
|
2153
|
+
return;
|
|
2154
|
+
const content = segmentReasoning;
|
|
2155
|
+
const elapsedMs = thoughtStartedAt ? Math.max(1, Date.now() - thoughtStartedAt) : 0;
|
|
2156
|
+
segmentReasoning = '';
|
|
2157
|
+
thoughtStartedAt = 0;
|
|
2158
|
+
if (!hasStructuredToolPlan) {
|
|
2159
|
+
const extracted = extractLivePlanFromText(content, true);
|
|
2160
|
+
if (extracted) {
|
|
2161
|
+
this.updateImplementationPlan(extracted);
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
this.emitEvent({
|
|
2165
|
+
type: 'agent_reasoning',
|
|
2166
|
+
content,
|
|
2167
|
+
streaming: false,
|
|
2168
|
+
elapsedMs
|
|
2169
|
+
});
|
|
2170
|
+
};
|
|
1854
2171
|
this.emitEvent({ type: 'status', message: 'Thinking…' });
|
|
1855
2172
|
this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
|
|
1856
2173
|
const planStepStart = performance.now();
|
|
1857
2174
|
const nativeControl = new AbortController();
|
|
1858
2175
|
let nativeCheckpoint = null;
|
|
1859
2176
|
const invocation = ++modelCallIndex;
|
|
2177
|
+
this._inModelCall = true;
|
|
1860
2178
|
const response = await this.llm.chat(prunedMessages, {
|
|
1861
2179
|
taskId: this.taskId,
|
|
1862
2180
|
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
1863
2181
|
taskIntent: isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
1864
2182
|
taskArchetype: determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
1865
|
-
|
|
2183
|
+
hardBudget: hardBudget,
|
|
2184
|
+
maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
|
|
1866
2185
|
tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
1867
|
-
tokenLimit: Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
2186
|
+
tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
1868
2187
|
? Math.min(this.efficiencyBudget.maxTurnTokens, remainingBudget) : this.efficiencyBudget.maxTurnTokens,
|
|
1869
2188
|
maxNativeActions: this.efficiencyBudget.getRemainingActions(),
|
|
1870
2189
|
workspaceRoot: this.workspaceRoot,
|
|
@@ -1878,15 +2197,31 @@ export class AgentLoop {
|
|
|
1878
2197
|
coreToolCount: dynamicTools.filter((t) => isCoreTool(t.name)).length,
|
|
1879
2198
|
signal: this.abortController?.signal
|
|
1880
2199
|
? AbortSignal.any([this.abortController.signal, nativeControl.signal]) : nativeControl.signal,
|
|
2200
|
+
onPlanUpdate: (rawPlan) => {
|
|
2201
|
+
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
2202
|
+
return;
|
|
2203
|
+
const normalized = normalizePeerPlanEntries(rawPlan);
|
|
2204
|
+
if (normalized) {
|
|
2205
|
+
hasStructuredToolPlan = true;
|
|
2206
|
+
this.updateImplementationPlan(normalized);
|
|
2207
|
+
}
|
|
2208
|
+
},
|
|
1881
2209
|
onReasoningChunk: (chunk) => {
|
|
1882
2210
|
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1883
2211
|
return;
|
|
1884
2212
|
if (!thoughtStartedAt)
|
|
1885
2213
|
thoughtStartedAt = Date.now();
|
|
1886
2214
|
reasoningAccumulated += chunk;
|
|
2215
|
+
segmentReasoning += chunk;
|
|
2216
|
+
if (!hasStructuredToolPlan && chunk.includes('\n')) {
|
|
2217
|
+
const extracted = extractLivePlanFromText(segmentReasoning, false);
|
|
2218
|
+
if (extracted) {
|
|
2219
|
+
this.updateImplementationPlan(extracted);
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
1887
2222
|
this.emitEvent({
|
|
1888
2223
|
type: 'agent_reasoning',
|
|
1889
|
-
content:
|
|
2224
|
+
content: segmentReasoning,
|
|
1890
2225
|
delta: chunk,
|
|
1891
2226
|
streaming: true,
|
|
1892
2227
|
elapsedMs: Date.now() - thoughtStartedAt
|
|
@@ -1895,37 +2230,158 @@ export class AgentLoop {
|
|
|
1895
2230
|
onChunk: (_chunk) => {
|
|
1896
2231
|
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1897
2232
|
return;
|
|
2233
|
+
finalizeReasoningSegment();
|
|
2234
|
+
streamedTextAccumulated += _chunk;
|
|
1898
2235
|
if (!hasStreamedChunk) {
|
|
1899
2236
|
hasStreamedChunk = true;
|
|
1900
2237
|
this.emitEvent({ type: 'status', message: 'Responding…' });
|
|
1901
2238
|
this.emitEvent({ type: 'agent_activity', activity: 'Responding…' });
|
|
1902
2239
|
}
|
|
2240
|
+
if ((streamedTextAccumulated.includes('<tool_call>') || (!hasStructuredToolPlan && _chunk.includes('\n')))) {
|
|
2241
|
+
const extracted = extractLivePlanFromText(streamedTextAccumulated, false);
|
|
2242
|
+
if (extracted) {
|
|
2243
|
+
if (streamedTextAccumulated.includes('<tool_call>'))
|
|
2244
|
+
hasStructuredToolPlan = true;
|
|
2245
|
+
this.updateImplementationPlan(extracted);
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
1903
2248
|
const preview = streamingCode.accept(_chunk);
|
|
1904
|
-
if (preview)
|
|
2249
|
+
if (preview) {
|
|
1905
2250
|
this.emitEvent(preview);
|
|
2251
|
+
}
|
|
2252
|
+
else {
|
|
2253
|
+
const cleanProse = stripThinkBlocks(stripToolCallMarkup(streamedTextAccumulated));
|
|
2254
|
+
if (cleanProse && !cleanProse.startsWith('```')) {
|
|
2255
|
+
this.emitEvent({
|
|
2256
|
+
type: 'agent_message',
|
|
2257
|
+
content: cleanProse,
|
|
2258
|
+
delta: _chunk,
|
|
2259
|
+
streaming: true
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
1906
2263
|
},
|
|
1907
2264
|
onNativeAction: (action) => {
|
|
1908
2265
|
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1909
2266
|
return;
|
|
1910
2267
|
if (!action || typeof action.name !== 'string')
|
|
1911
2268
|
return;
|
|
2269
|
+
finalizeReasoningSegment();
|
|
2270
|
+
const actionPlan = normalizePeerPlanEntries(action.parameters);
|
|
2271
|
+
if (actionPlan) {
|
|
2272
|
+
hasStructuredToolPlan = true;
|
|
2273
|
+
this.updateImplementationPlan(actionPlan);
|
|
2274
|
+
}
|
|
2275
|
+
const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
|
|
2276
|
+
if (!isChecklistTool && this._implementationPlan.length === 0) {
|
|
2277
|
+
this.seedTaskPhasePlanIfEmpty();
|
|
2278
|
+
}
|
|
1912
2279
|
auditLog.log({ event: 'native_action', taskId: this.taskId,
|
|
1913
2280
|
provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
|
|
1914
2281
|
...(action.id ? { actionId: action.id } : {}) });
|
|
1915
|
-
if (action.status === 'running') {
|
|
2282
|
+
if (action.status === 'running' && !isChecklistTool) {
|
|
1916
2283
|
try {
|
|
1917
2284
|
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
1918
2285
|
}
|
|
1919
2286
|
catch (error) {
|
|
1920
2287
|
if (error instanceof EfficiencyCheckpoint) {
|
|
2288
|
+
finalizeReasoningSegment();
|
|
1921
2289
|
nativeCheckpoint = error;
|
|
1922
2290
|
nativeControl.abort();
|
|
1923
2291
|
}
|
|
1924
2292
|
return;
|
|
1925
2293
|
}
|
|
1926
2294
|
}
|
|
2295
|
+
if (action.status === 'completed' && action.id && !isChecklistTool) {
|
|
2296
|
+
completedNativeActionIds.add(String(action.id));
|
|
2297
|
+
}
|
|
2298
|
+
const isCompleted = action.status === 'completed';
|
|
2299
|
+
const isFailed = action.status === 'failed';
|
|
2300
|
+
const actionArgs = {
|
|
2301
|
+
...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
|
|
2302
|
+
path: action.parameters?.path || action.parameters?.Path || action.parameters?.filePath || action.detail || '',
|
|
2303
|
+
command: action.parameters?.command || action.parameters?.cmd || (['bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes(action.name.toLowerCase()) ? action.detail : '')
|
|
2304
|
+
};
|
|
2305
|
+
const terminalId = action.id ? String(action.id) : '';
|
|
2306
|
+
const freshTerminal = !terminalId || !observedNativeTerminalIds.has(terminalId);
|
|
2307
|
+
if ((isCompleted || isFailed) && !isChecklistTool && freshTerminal && !this._pendingConsent) {
|
|
2308
|
+
if (terminalId)
|
|
2309
|
+
observedNativeTerminalIds.add(terminalId);
|
|
2310
|
+
const actionOutcome = {
|
|
2311
|
+
success: isCompleted,
|
|
2312
|
+
...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
|
|
2313
|
+
};
|
|
2314
|
+
coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
|
|
2315
|
+
const recovery = this.timeMachine.observe(action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId));
|
|
2316
|
+
// Pause now, not at the end of a potentially long peer turn.
|
|
2317
|
+
// An abort is a yield checkpoint, not a user denial or task success.
|
|
2318
|
+
if (recovery.kind === 'consent') {
|
|
2319
|
+
this._pendingConsent ??= { recovery, tool: action.name };
|
|
2320
|
+
nativeControl.abort();
|
|
2321
|
+
}
|
|
2322
|
+
else if (!this._pendingConsent && recovery.kind === 'replan') {
|
|
2323
|
+
this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
|
|
2324
|
+
}
|
|
2325
|
+
else if (!this._pendingConsent && (recovery.kind === 'stop' || recovery.kind === 'human')) {
|
|
2326
|
+
this.stopRequested = true;
|
|
2327
|
+
nativeControl.abort();
|
|
2328
|
+
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, action.name) });
|
|
2329
|
+
}
|
|
2330
|
+
const phaseNudge = this.smartToolsGovernor.observe(action.name, actionArgs, actionOutcome);
|
|
2331
|
+
if (phaseNudge)
|
|
2332
|
+
this._smartToolsNudge = phaseNudge;
|
|
2333
|
+
else if (this.smartToolsGovernor.snapshot().phase === 'execution')
|
|
2334
|
+
this._smartToolsNudge = null;
|
|
2335
|
+
}
|
|
2336
|
+
if (isCompleted && !isChecklistTool) {
|
|
2337
|
+
const lowerName = action.name.toLowerCase();
|
|
2338
|
+
const rawDetail = String(action.detail || '');
|
|
2339
|
+
const lowerDetail = rawDetail.toLowerCase();
|
|
2340
|
+
if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)) {
|
|
2341
|
+
nativeMutationCount++;
|
|
2342
|
+
if (nativeMutationCount === 1 && this._implementationPlanSeeded) {
|
|
2343
|
+
this.advanceImplementationPlanProgress('mutation');
|
|
2344
|
+
}
|
|
2345
|
+
else if (nativeMutationCount % 2 === 0) {
|
|
2346
|
+
this.advanceImplementationPlanProgress('mutation');
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
else if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
|
|
2350
|
+
this.webVerificationState.browserActUsed = true;
|
|
2351
|
+
this.advanceImplementationPlanProgress('verification');
|
|
2352
|
+
}
|
|
2353
|
+
else if (lowerName === 'fs_read' && /\.(png|jpg|jpeg|webp)$/i.test(lowerDetail)) {
|
|
2354
|
+
this.advanceImplementationPlanProgress('verification');
|
|
2355
|
+
}
|
|
2356
|
+
else if (['fs_read', 'read_file', 'read', 'sysrun', 'bash', 'execute', 'run_command'].includes(lowerName)) {
|
|
2357
|
+
nativeExplorationCount++;
|
|
2358
|
+
if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
|
|
2359
|
+
this.recordInspectedWebFile(rawDetail);
|
|
2360
|
+
}
|
|
2361
|
+
if (this._implementationPlanSeeded && nativeExplorationCount === 2) {
|
|
2362
|
+
const activeIdx = this._implementationPlan.findIndex((item) => item.status === 'in_progress');
|
|
2363
|
+
if (activeIdx === 0) {
|
|
2364
|
+
this.advanceImplementationPlanProgress('mutation');
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
if ((['screenshot', 'vision_inspect_ui'].includes(lowerName) ||
|
|
2369
|
+
(/\.(png|jpg|jpeg|webp)$/i.test(lowerDetail) && ['fs_read', 'read', 'read_file', 'view_file', 'view_image'].includes(lowerName))) &&
|
|
2370
|
+
this.llm.supportsVision) {
|
|
2371
|
+
this.webVerificationState.screenshotTaken = true;
|
|
2372
|
+
}
|
|
2373
|
+
if (['browse', 'browser_act', 'preview', 'snapshot', 'scrape', 'web_fetch'].includes(lowerName)) {
|
|
2374
|
+
this.webVerificationState.browserActUsed = true;
|
|
2375
|
+
}
|
|
2376
|
+
if (/\.(html?|css|jsx|tsx|vue|svelte)\b/i.test(rawDetail)) {
|
|
2377
|
+
this.webVerificationState.htmlInspected = true;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
1927
2380
|
const nativeCode = codeProgressFromAction(action.name, { ...(action.parameters && typeof action.parameters === 'object' ? action.parameters : {}),
|
|
1928
2381
|
path: action.parameters?.path || action.parameters?.Path || action.detail || '' }, `provider:${action.name}:${action.detail || ''}`, action.status === 'completed' ? 'done' : action.status === 'failed' ? 'failed' : 'working', 'provider');
|
|
2382
|
+
if (nativeCode || action.status === 'completed' || action.status === 'failed') {
|
|
2383
|
+
finalizeReasoningSegment();
|
|
2384
|
+
}
|
|
1929
2385
|
if (nativeCode) {
|
|
1930
2386
|
this.emitEvent(nativeCode);
|
|
1931
2387
|
nativeCodeObserver.handle(nativeCode);
|
|
@@ -1936,22 +2392,47 @@ export class AgentLoop {
|
|
|
1936
2392
|
const detail = action.detail ? ` ${action.detail}` : '';
|
|
1937
2393
|
if (action.status === 'running') {
|
|
1938
2394
|
this.emitEvent({ type: 'status', message: `Acting: ${action.name}${detail}` });
|
|
1939
|
-
this.emitEvent({ type: 'agent_activity', activity: `Acting: ${action.name}${detail}` });
|
|
1940
2395
|
}
|
|
1941
2396
|
else if (action.status === 'completed') {
|
|
2397
|
+
this.emitEvent({ type: 'status', message: '' });
|
|
1942
2398
|
this.emitEvent({ type: 'notice', tone: 'muted', nativeStep: true, message: `${this.config.provider || 'Provider'} ${action.name}${detail}` });
|
|
1943
2399
|
}
|
|
1944
2400
|
else if (action.status === 'failed') {
|
|
2401
|
+
this.emitEvent({ type: 'status', message: '' });
|
|
1945
2402
|
this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
|
|
1946
2403
|
}
|
|
1947
2404
|
}
|
|
1948
2405
|
}).catch((error) => {
|
|
1949
|
-
if (
|
|
1950
|
-
|
|
2406
|
+
if (this._pendingConsent) {
|
|
2407
|
+
this.stepsCompleted += completedNativeActionIds.size;
|
|
2408
|
+
const checkpoint = new RetryConsentCheckpoint();
|
|
2409
|
+
if (error && typeof error === 'object' && 'partialUsage' in error) {
|
|
2410
|
+
Object.assign(checkpoint, { partialUsage: error.partialUsage });
|
|
2411
|
+
}
|
|
2412
|
+
throw checkpoint;
|
|
2413
|
+
}
|
|
2414
|
+
if (nativeCheckpoint) {
|
|
2415
|
+
if (completedNativeActionIds.size > 0) {
|
|
2416
|
+
this.stepsCompleted += completedNativeActionIds.size;
|
|
2417
|
+
}
|
|
2418
|
+
if (reasoningAccumulated) {
|
|
2419
|
+
this.messages.push({
|
|
2420
|
+
role: 'assistant',
|
|
2421
|
+
content: 'Turn paused at efficiency checkpoint.',
|
|
2422
|
+
reasoning_content: reasoningAccumulated
|
|
2423
|
+
});
|
|
2424
|
+
}
|
|
2425
|
+
if (error && typeof error === 'object' && 'partialUsage' in error) {
|
|
2426
|
+
Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
|
|
2427
|
+
}
|
|
1951
2428
|
}
|
|
1952
2429
|
throw nativeCheckpoint || error;
|
|
1953
2430
|
})
|
|
1954
|
-
.finally(() =>
|
|
2431
|
+
.finally(() => {
|
|
2432
|
+
finalizeReasoningSegment();
|
|
2433
|
+
nativeCodeObserver.dispose();
|
|
2434
|
+
this._inModelCall = false;
|
|
2435
|
+
});
|
|
1955
2436
|
this._totalPlanMs = (this._totalPlanMs || 0) + (performance.now() - planStepStart);
|
|
1956
2437
|
if (this.stopRequested || this.abortController?.signal?.aborted) {
|
|
1957
2438
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
@@ -1960,6 +2441,10 @@ export class AgentLoop {
|
|
|
1960
2441
|
const finalCodePreview = streamingCode.flush();
|
|
1961
2442
|
if (finalCodePreview)
|
|
1962
2443
|
this.emitEvent(finalCodePreview);
|
|
2444
|
+
if (this._pendingConsent) {
|
|
2445
|
+
this.stepsCompleted += completedNativeActionIds.size;
|
|
2446
|
+
throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
|
|
2447
|
+
}
|
|
1963
2448
|
// The call came back. Whatever went wrong before is no longer
|
|
1964
2449
|
// consecutive — without this reset, one failure at step 2 and another
|
|
1965
2450
|
// at step 200 would count toward the same ceiling and stop a task that
|
|
@@ -1982,6 +2467,7 @@ export class AgentLoop {
|
|
|
1982
2467
|
uncachedPromptTokens: response.usage.uncachedPromptTokens,
|
|
1983
2468
|
noncachedTokens: noncachedTokens(response.usage),
|
|
1984
2469
|
measurement: response.usage.measurement || 'unspecified',
|
|
2470
|
+
measurementScope: response.usage.measurementScope || 'unspecified',
|
|
1985
2471
|
cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
|
|
1986
2472
|
costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
|
|
1987
2473
|
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
@@ -2027,7 +2513,7 @@ export class AgentLoop {
|
|
|
2027
2513
|
}
|
|
2028
2514
|
// The host owns verification policy. A model cannot substitute repeated
|
|
2029
2515
|
// HTTP checks for rendering, and adapters must not contradict this gate.
|
|
2030
|
-
if (!response.toolCalls?.length && !this.webVerificationScheduled
|
|
2516
|
+
if (!response.toolCalls?.length && !response.toolRoutingError && !this.webVerificationScheduled
|
|
2031
2517
|
&& !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
|
|
2032
2518
|
&& isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
|
|
2033
2519
|
&& !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
|
|
@@ -2081,15 +2567,20 @@ export class AgentLoop {
|
|
|
2081
2567
|
else if (reasoningAccumulated) {
|
|
2082
2568
|
assistantMsg.reasoning_content = reasoningAccumulated;
|
|
2083
2569
|
}
|
|
2084
|
-
|
|
2085
|
-
if (finalReasoning) {
|
|
2570
|
+
if (!reasoningAccumulated && response.reasoningContent) {
|
|
2086
2571
|
this.emitEvent({
|
|
2087
2572
|
type: 'agent_reasoning',
|
|
2088
|
-
content:
|
|
2573
|
+
content: response.reasoningContent,
|
|
2089
2574
|
streaming: false,
|
|
2090
|
-
elapsedMs:
|
|
2575
|
+
elapsedMs: 0
|
|
2091
2576
|
});
|
|
2092
2577
|
}
|
|
2578
|
+
if (!hasStructuredToolPlan) {
|
|
2579
|
+
const fallbackPlan = extractLivePlanFromText(`${response.reasoningContent || ''}\n${response.content || ''}`, true);
|
|
2580
|
+
if (fallbackPlan) {
|
|
2581
|
+
this.updateImplementationPlan(fallbackPlan);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2093
2584
|
// Kept verbatim on the turn. A thinking-enabled model that gets its own
|
|
2094
2585
|
// thinking blocks back is continuing a thought; one that does not is
|
|
2095
2586
|
// starting over, and with tool_use in the same turn the API can reject
|
|
@@ -2110,6 +2601,11 @@ export class AgentLoop {
|
|
|
2110
2601
|
if (hasExternalActions) {
|
|
2111
2602
|
this.stepsCompleted += completedExternalActions.length;
|
|
2112
2603
|
for (const extAction of completedExternalActions) {
|
|
2604
|
+
const extPlan = normalizePeerPlanEntries(extAction.parameters);
|
|
2605
|
+
if (extPlan) {
|
|
2606
|
+
hasStructuredToolPlan = true;
|
|
2607
|
+
this.updateImplementationPlan(extPlan);
|
|
2608
|
+
}
|
|
2113
2609
|
const actionName = String(extAction.name || '').toLowerCase();
|
|
2114
2610
|
const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
|
|
2115
2611
|
if (['write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content', 'fs_write', 'fs_edit', 'multiedit'].includes(actionName) && detailPath) {
|
|
@@ -2120,19 +2616,47 @@ export class AgentLoop {
|
|
|
2120
2616
|
// has reached a vision-capable provider.
|
|
2121
2617
|
// A native action label alone carries no rendered-page evidence.
|
|
2122
2618
|
// The shared host inspection below verifies its resulting artifacts.
|
|
2123
|
-
if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content'].includes(actionName) && detailPath) {
|
|
2124
|
-
if (/\.(html|htm|css|jsx|tsx|vue|svelte)
|
|
2125
|
-
this.
|
|
2619
|
+
if (['fs_read', 'read_file', 'view_file', 'viewfile', 'view_file_content', 'sysrun', 'bash'].includes(actionName) && detailPath) {
|
|
2620
|
+
if (/\.(html|htm|css|jsx|tsx|vue|svelte)\b/i.test(detailPath)) {
|
|
2621
|
+
this.recordInspectedWebFile(detailPath);
|
|
2126
2622
|
}
|
|
2127
2623
|
}
|
|
2128
2624
|
}
|
|
2129
2625
|
}
|
|
2130
2626
|
// If no tool calls, check if the agent is just thinking/planning or actually done
|
|
2131
2627
|
if (!response.toolCalls || response.toolCalls.length === 0) {
|
|
2628
|
+
if (response.toolRoutingError) {
|
|
2629
|
+
const name = response.toolRoutingError.tool;
|
|
2630
|
+
if (toolRoutingRecoveries++ >= 1) {
|
|
2631
|
+
this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${name} through its native channel. Work remains unfinished.` });
|
|
2632
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2633
|
+
break;
|
|
2634
|
+
}
|
|
2635
|
+
this.messages.push({ role: 'system', content: `[TOOL ROUTING REPAIR] ${name} is a Causyne host tool, not a peer-native function. `
|
|
2636
|
+
+ `Return a complete <tool_call>{"name":${JSON.stringify(name)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
|
|
2637
|
+
+ 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
|
|
2638
|
+
+ 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
|
|
2639
|
+
this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${name}…` });
|
|
2640
|
+
auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: name });
|
|
2641
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2642
|
+
continue;
|
|
2643
|
+
}
|
|
2132
2644
|
const contentText = response.content || '';
|
|
2133
2645
|
const lower = contentText.toLowerCase();
|
|
2134
2646
|
const taskPrompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
2135
2647
|
const isActionable = isActionableTaskPrompt(taskPrompt);
|
|
2648
|
+
if (!hasExternalActions && isProviderPlanOrQuotaRefusal(contentText)) {
|
|
2649
|
+
this.messages.pop();
|
|
2650
|
+
if (this.stepsCompleted === 0 && this.messages[this.messages.length - 1]?.role === 'user') {
|
|
2651
|
+
this.messages.pop();
|
|
2652
|
+
}
|
|
2653
|
+
this.emitEvent({
|
|
2654
|
+
type: 'error',
|
|
2655
|
+
message: `Provider plan or quota limit reached: ${contentText.trim()}`
|
|
2656
|
+
});
|
|
2657
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2658
|
+
break;
|
|
2659
|
+
}
|
|
2136
2660
|
// A peer may have completed searches or a plan artifact while still
|
|
2137
2661
|
// waiting for its own UI's Proceed button. Those actions do not
|
|
2138
2662
|
// satisfy an implementation request in the enclosing Causyne loop.
|
|
@@ -2157,19 +2681,22 @@ export class AgentLoop {
|
|
|
2157
2681
|
this.memoryManager.saveHistory(this.messages);
|
|
2158
2682
|
break;
|
|
2159
2683
|
}
|
|
2684
|
+
if (hasExternalActions) {
|
|
2685
|
+
this.consecutiveThinkingSteps = 0;
|
|
2686
|
+
}
|
|
2160
2687
|
// A native workspace action already changed the workspace. Do not
|
|
2161
2688
|
// demand a Causyne tool call for the same work, and do not treat the
|
|
2162
2689
|
// turn as a no-op.
|
|
2163
|
-
if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps <
|
|
2690
|
+
if (!hasExternalActions && failedExternalActions.length > 0 && this.consecutiveThinkingSteps < 3) {
|
|
2164
2691
|
this.consecutiveThinkingSteps++;
|
|
2165
2692
|
const blocked = failedExternalActions
|
|
2166
2693
|
.map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
|
|
2167
2694
|
.join(', ');
|
|
2168
|
-
this.emitEvent({ type: 'status', message: '
|
|
2169
|
-
this.emitEvent({ type: 'agent_activity', activity: '
|
|
2695
|
+
this.emitEvent({ type: 'status', message: 'Inspecting the failed native action before continuing...' });
|
|
2696
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Checking the action failure…' });
|
|
2170
2697
|
this.messages.push({
|
|
2171
2698
|
role: 'system',
|
|
2172
|
-
content: `[SYSTEM NOTICE: Your native action(s) were blocked: ${blocked}.
|
|
2699
|
+
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>.]`
|
|
2173
2700
|
});
|
|
2174
2701
|
this.memoryManager.saveHistory(this.messages);
|
|
2175
2702
|
continue;
|
|
@@ -2222,24 +2749,27 @@ export class AgentLoop {
|
|
|
2222
2749
|
this.memoryManager.saveHistory(this.messages);
|
|
2223
2750
|
continue;
|
|
2224
2751
|
}
|
|
2225
|
-
if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) &&
|
|
2226
|
-
|
|
2752
|
+
if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations < 3) {
|
|
2753
|
+
incompleteTurnContinuations++;
|
|
2227
2754
|
if (response.content) {
|
|
2228
2755
|
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
2229
2756
|
}
|
|
2757
|
+
const blockedNote = failedExternalActions.length > 0
|
|
2758
|
+
? ` Note: ${failedExternalActions.map((a) => `${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.`
|
|
2759
|
+
: '';
|
|
2230
2760
|
this.emitEvent({ type: 'status', message: 'Continuing task execution...' });
|
|
2231
2761
|
this.emitEvent({ type: 'agent_activity', activity: 'Continuing mid-task execution…' });
|
|
2232
2762
|
this.messages.push({
|
|
2233
2763
|
role: 'system',
|
|
2234
2764
|
content: isIncompleteTurn
|
|
2235
|
-
?
|
|
2236
|
-
:
|
|
2765
|
+
? `[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}]`
|
|
2766
|
+
: `[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}]`
|
|
2237
2767
|
});
|
|
2238
2768
|
this.memoryManager.saveHistory(this.messages);
|
|
2239
2769
|
continue;
|
|
2240
2770
|
}
|
|
2241
|
-
if (hasExternalActions) {
|
|
2242
|
-
|
|
2771
|
+
if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
|
|
2772
|
+
incompleteTurnContinuations = 0;
|
|
2243
2773
|
}
|
|
2244
2774
|
if (!hasExternalActions && this.stepsCompleted === 0 && this.consecutiveThinkingSteps < 2) {
|
|
2245
2775
|
if (isActionable || lower.includes('turn completed') || lower.includes('no output produced') || !contentText.trim()) {
|
|
@@ -2248,7 +2778,7 @@ export class AgentLoop {
|
|
|
2248
2778
|
this.emitEvent({ type: 'agent_activity', activity: 'Nudging agent to invoke tools…' });
|
|
2249
2779
|
this.messages.push({
|
|
2250
2780
|
role: 'system',
|
|
2251
|
-
content: `[SYSTEM NOTICE: An action or task was requested ("${taskPrompt}"), but no
|
|
2781
|
+
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.]`
|
|
2252
2782
|
});
|
|
2253
2783
|
this.memoryManager.saveHistory(this.messages);
|
|
2254
2784
|
continue;
|
|
@@ -2260,6 +2790,17 @@ export class AgentLoop {
|
|
|
2260
2790
|
this.memoryManager.saveHistory(this.messages);
|
|
2261
2791
|
break;
|
|
2262
2792
|
}
|
|
2793
|
+
if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
|
|
2794
|
+
if (!contentText.trim()) {
|
|
2795
|
+
this.messages.pop();
|
|
2796
|
+
}
|
|
2797
|
+
this.emitEvent({
|
|
2798
|
+
type: 'error',
|
|
2799
|
+
message: 'The task stopped before completion after repeated blocked or incomplete turns. Work remains unfinished.'
|
|
2800
|
+
});
|
|
2801
|
+
this.memoryManager.saveHistory(this.messages);
|
|
2802
|
+
break;
|
|
2803
|
+
}
|
|
2263
2804
|
// --- COMPLETION GUARDS ---
|
|
2264
2805
|
// Two hard rules learned the expensive way:
|
|
2265
2806
|
// 1. Match on word boundaries. Substring matching made 'ui' fire on
|
|
@@ -2408,9 +2949,31 @@ export class AgentLoop {
|
|
|
2408
2949
|
// Tool availability and a completed plan are not evidence of visual
|
|
2409
2950
|
// inspection. A failed browser/capture attempt must not become a
|
|
2410
2951
|
// successful task merely because the provider says "verified".
|
|
2952
|
+
const outcomes = coldObserver.getToolOutcomes(this.taskId);
|
|
2953
|
+
const hasBrowserActOutcome = outcomes.some((o) => o.tool === 'browser_act' && o.success !== false);
|
|
2954
|
+
const hasPassingTests = outcomes.some((o) => o.success && (isVerificationCommand(o.command || o.tool || '') || /\b(?:test|unittest|vitest|jest|pytest)\b/i.test(o.command || ''))) || (Array.isArray(this._planSteps) && this._planSteps.some(s => s.success && /test/i.test(s.tool)));
|
|
2955
|
+
let observerVerified = false;
|
|
2956
|
+
try {
|
|
2957
|
+
const observation = this.observer.evaluate({
|
|
2958
|
+
taskId: this.taskId,
|
|
2959
|
+
workspaceRoot: this.workspaceRoot,
|
|
2960
|
+
userGoal: this.currentTaskPrompt || this.userPrompt || '',
|
|
2961
|
+
agentClaim: response.content || '',
|
|
2962
|
+
toolHistory: outcomes
|
|
2963
|
+
});
|
|
2964
|
+
if (observation.verified || observation.status === 'verified') {
|
|
2965
|
+
observerVerified = true;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
catch {
|
|
2969
|
+
// fail-open
|
|
2970
|
+
}
|
|
2411
2971
|
const isVerified = Boolean(this.webVerificationState.browserActUsed ||
|
|
2972
|
+
hasBrowserActOutcome ||
|
|
2412
2973
|
this.webVerificationState.screenshotTaken ||
|
|
2413
|
-
(!browserReady && this.webVerificationState.htmlInspected)
|
|
2974
|
+
(!browserReady && this.webVerificationState.htmlInspected) ||
|
|
2975
|
+
hasPassingTests ||
|
|
2976
|
+
observerVerified);
|
|
2414
2977
|
if (isWebTask && !browserReady && this.webVerificationState.htmlInspected
|
|
2415
2978
|
&& !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken) {
|
|
2416
2979
|
this.emitEvent({ type: 'notice', message: 'Source inspection completed. Rendered-page and visual verification were not performed because the browser runtime is unavailable.' });
|
|
@@ -2424,6 +2987,29 @@ export class AgentLoop {
|
|
|
2424
2987
|
this.memoryManager.saveHistory(this.messages);
|
|
2425
2988
|
break;
|
|
2426
2989
|
}
|
|
2990
|
+
// Assess actual outcomes again after every verification attempt. A
|
|
2991
|
+
// one-shot reminder must not turn missing evidence into completion.
|
|
2992
|
+
if (this.stepsCompleted > 0 && !isWebTask) {
|
|
2993
|
+
const assessment = assessVerification({
|
|
2994
|
+
archetype: this.taskShape?.archetype,
|
|
2995
|
+
outcomes: coldObserver.getToolOutcomes(this.taskId),
|
|
2996
|
+
skip: ['web']
|
|
2997
|
+
});
|
|
2998
|
+
if (assessment.gaps.length > 0) {
|
|
2999
|
+
const domain = assessment.gaps[0].domain;
|
|
3000
|
+
const recovery = this.timeMachine.observe(`verification_${domain}`, {}, {
|
|
3001
|
+
success: false, error: 'Required outcome evidence is missing'
|
|
3002
|
+
}, coldObserver.getToolOutcomes(this.taskId));
|
|
3003
|
+
this.routeTools({ source: 'verification', requested: assessment.gaps.flatMap((gap) => [...gap.tools]) });
|
|
3004
|
+
const verdict = await this.handleRecovery(recovery, `Verification (${domain})`);
|
|
3005
|
+
if (verdict.stop)
|
|
3006
|
+
break;
|
|
3007
|
+
this.emitEvent({ type: 'status', message: `Verification check: ${assessment.gaps[0].need}` });
|
|
3008
|
+
this.messages.push({ role: 'system', content: `${assessment.directive} ${verdict.guidance}` });
|
|
3009
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3010
|
+
continue;
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
2427
3013
|
// Cold Observer: Overconfidence & Loop Verification Check
|
|
2428
3014
|
{
|
|
2429
3015
|
try {
|
|
@@ -2431,7 +3017,7 @@ export class AgentLoop {
|
|
|
2431
3017
|
taskId: this.taskId,
|
|
2432
3018
|
userPrompt: this.currentTaskPrompt || this.userPrompt || '',
|
|
2433
3019
|
agentClaim: response.content || '',
|
|
2434
|
-
toolHistory:
|
|
3020
|
+
toolHistory: coldObserver.getToolOutcomes(this.taskId),
|
|
2435
3021
|
stepsCompleted: this.stepsCompleted
|
|
2436
3022
|
});
|
|
2437
3023
|
if (coldAudit.overconfident) {
|
|
@@ -2439,14 +3025,12 @@ export class AgentLoop {
|
|
|
2439
3025
|
success: false, error: coldAudit.discrepancy
|
|
2440
3026
|
}, coldObserver.getToolOutcomes(this.taskId));
|
|
2441
3027
|
this.emitEvent({ type: 'status', message: `Cold Observer: ${coldAudit.discrepancy}` });
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, 'Verification') });
|
|
3028
|
+
const verdict = await this.handleRecovery(recovery, 'Verification');
|
|
3029
|
+
if (verdict.stop)
|
|
2445
3030
|
break;
|
|
2446
|
-
}
|
|
2447
3031
|
this.messages.push({
|
|
2448
3032
|
role: 'system',
|
|
2449
|
-
content: `${coldAudit.coldDirective} ${
|
|
3033
|
+
content: `${coldAudit.coldDirective} ${verdict.guidance}`
|
|
2450
3034
|
});
|
|
2451
3035
|
this.memoryManager.saveHistory(this.messages);
|
|
2452
3036
|
continue;
|
|
@@ -2456,6 +3040,30 @@ export class AgentLoop {
|
|
|
2456
3040
|
// Cold observer fail-open
|
|
2457
3041
|
}
|
|
2458
3042
|
}
|
|
3043
|
+
// Unified Observer: Phase 7 progress and verification evaluation
|
|
3044
|
+
{
|
|
3045
|
+
try {
|
|
3046
|
+
const observation = this.observer.evaluate({
|
|
3047
|
+
taskId: this.taskId,
|
|
3048
|
+
workspaceRoot: this.workspaceRoot,
|
|
3049
|
+
userGoal: this.currentTaskPrompt || this.userPrompt || '',
|
|
3050
|
+
agentClaim: response.content || '',
|
|
3051
|
+
toolHistory: coldObserver.getToolOutcomes(this.taskId)
|
|
3052
|
+
});
|
|
3053
|
+
if (observation.status === 'ready-to-verify' && !this._verificationPlanFired) {
|
|
3054
|
+
this.emitEvent({ type: 'status', message: `Observer: ${observation.message || 'Deliverables require verification check.'}` });
|
|
3055
|
+
this.messages.push({
|
|
3056
|
+
role: 'system',
|
|
3057
|
+
content: `[OBSERVER VERIFICATION]: ${observation.message || 'Deliverables require verification.'} Next action: ${observation.nextAction || 'Run tests or build to verify.'}`
|
|
3058
|
+
});
|
|
3059
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3060
|
+
continue;
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
catch (_err) {
|
|
3064
|
+
// Observer fail-open
|
|
3065
|
+
}
|
|
3066
|
+
}
|
|
2459
3067
|
if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
|
|
2460
3068
|
const currentDesktopPictures = readMacDesktopPictures();
|
|
2461
3069
|
if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
|
|
@@ -2467,6 +3075,9 @@ export class AgentLoop {
|
|
|
2467
3075
|
if (response.content) {
|
|
2468
3076
|
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
2469
3077
|
}
|
|
3078
|
+
if (this.stepsCompleted > 0) {
|
|
3079
|
+
this.advanceImplementationPlanProgress('complete');
|
|
3080
|
+
}
|
|
2470
3081
|
this.emitEvent({ type: 'status', message: 'Task completed.' });
|
|
2471
3082
|
this.memoryManager.saveHistory(this.messages); // Save final state
|
|
2472
3083
|
// The task worked. Keep the route so the next one like it does not
|
|
@@ -2767,12 +3378,15 @@ export class AgentLoop {
|
|
|
2767
3378
|
});
|
|
2768
3379
|
continue;
|
|
2769
3380
|
}
|
|
2770
|
-
if (!
|
|
3381
|
+
if (!this.unlockedTools.has(functionName)) {
|
|
3382
|
+
// Calling a listed tool by name is a request for it. Its pack comes
|
|
3383
|
+
// with it so the matching playbook arrives when it becomes relevant.
|
|
2771
3384
|
const pack = packForTool(functionName);
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
3385
|
+
this.routeTools({
|
|
3386
|
+
source: 'request',
|
|
3387
|
+
requested: [functionName],
|
|
3388
|
+
requestedPacks: []
|
|
3389
|
+
});
|
|
2776
3390
|
}
|
|
2777
3391
|
const validationErrors = this.validateToolArgs(functionName, args);
|
|
2778
3392
|
if (validationErrors) {
|
|
@@ -2967,13 +3581,16 @@ export class AgentLoop {
|
|
|
2967
3581
|
this.emitEvent({ type: 'step_error', tool: functionName,
|
|
2968
3582
|
error: `${errorType}: ${failure.error} (${recovery.attempt}/${recovery.maxAttempts})`,
|
|
2969
3583
|
toolCallId: toolCall.id });
|
|
3584
|
+
const verdict = await this.handleRecovery(recovery, functionName);
|
|
2970
3585
|
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
2971
3586
|
name: functionName, content: JSON.stringify({ ...failure,
|
|
2972
|
-
errorType, timeMachine:
|
|
3587
|
+
errorType, timeMachine: verdict.guidance,
|
|
2973
3588
|
...(alternativeRoute ? { apcReplanAlternative: alternativeRoute.suggestedTool, apcReplanReason: alternativeRoute.reason } : {}) }) });
|
|
2974
3589
|
this.stallGuard.observeCall(functionName, args || {}, failure, toolCall.id, true);
|
|
2975
3590
|
this.memoryManager.saveHistory(this.messages);
|
|
2976
|
-
if (
|
|
3591
|
+
if (verdict.stop)
|
|
3592
|
+
break;
|
|
3593
|
+
if (errorType === 'fatal') {
|
|
2977
3594
|
this.stopRequested = true;
|
|
2978
3595
|
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
2979
3596
|
break;
|
|
@@ -3008,15 +3625,30 @@ export class AgentLoop {
|
|
|
3008
3625
|
this.webVerificationState.htmlInspected = true;
|
|
3009
3626
|
}
|
|
3010
3627
|
}
|
|
3011
|
-
|
|
3628
|
+
const imageCanReachModel = Boolean(this.llm.supportsVision && result?._is_image_marker === true
|
|
3629
|
+
&& typeof result.base64 === 'string' && result.base64.length > 0);
|
|
3630
|
+
if (['screenshot', 'vision_inspect_ui', 'view_image'].includes(functionName) && result?.success === true && imageCanReachModel) {
|
|
3012
3631
|
this.webVerificationState.screenshotTaken = true;
|
|
3013
3632
|
}
|
|
3014
3633
|
if (functionName === 'browser_act' && result?.success === true) {
|
|
3634
|
+
this.advanceImplementationPlanProgress('verification');
|
|
3015
3635
|
const browserResults = Array.isArray(result.data) ? result.data : [];
|
|
3016
|
-
|
|
3017
|
-
|
|
3636
|
+
const allRuntimeErrors = browserResults.flatMap((item) => Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []);
|
|
3637
|
+
const hasValidBrowserAction = browserResults.some((item) => ['preview', 'snapshot', 'scrape', 'screenshot'].includes(item?.action));
|
|
3638
|
+
if (allRuntimeErrors.length === 0 && (hasValidBrowserAction || result.url || result.tabId)) {
|
|
3018
3639
|
this.webVerificationState.browserActUsed = true;
|
|
3019
3640
|
}
|
|
3641
|
+
else if (allRuntimeErrors.length > 0) {
|
|
3642
|
+
this.webVerificationState.browserActUsed = false;
|
|
3643
|
+
this.emitEvent({
|
|
3644
|
+
type: 'status',
|
|
3645
|
+
message: `⚠️ Browser runtime error(s) detected: ${allRuntimeErrors[0]}`
|
|
3646
|
+
});
|
|
3647
|
+
this.messages.push({
|
|
3648
|
+
role: 'system',
|
|
3649
|
+
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.]`
|
|
3650
|
+
});
|
|
3651
|
+
}
|
|
3020
3652
|
}
|
|
3021
3653
|
if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName))
|
|
3022
3654
|
clearSysRunCache();
|
|
@@ -3024,19 +3656,13 @@ export class AgentLoop {
|
|
|
3024
3656
|
// is written only after post-hook review, so a formatter that rejects
|
|
3025
3657
|
// a write is remembered as a failure rather than a success.
|
|
3026
3658
|
const observedResult = result?._is_image_marker === true
|
|
3027
|
-
? { success: true, _is_image_marker: true, filename: result.filename, mimeType: result.mimeType }
|
|
3659
|
+
? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
|
|
3028
3660
|
: result;
|
|
3029
3661
|
coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
|
|
3030
3662
|
const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
|
|
3031
|
-
|
|
3032
|
-
this.emitEvent({ type: 'status', message: `TimeMachine: approach change after ${recovery.attempt} failed attempts.` });
|
|
3033
|
-
}
|
|
3034
|
-
if (recovery.kind === 'stop' || recovery.kind === 'human') {
|
|
3035
|
-
this.stopRequested = true;
|
|
3036
|
-
this.emitEvent({ type: 'error', message: recoveryUserMessage(recovery, functionName) });
|
|
3037
|
-
}
|
|
3663
|
+
const verdict = await this.handleRecovery(recovery, functionName);
|
|
3038
3664
|
if (result && (result.success === false || typeof result.error === 'string')) {
|
|
3039
|
-
result = { ...result, timeMachine:
|
|
3665
|
+
result = { ...result, timeMachine: verdict.guidance };
|
|
3040
3666
|
}
|
|
3041
3667
|
if (this.stopRequested) {
|
|
3042
3668
|
this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
|
|
@@ -3047,12 +3673,11 @@ export class AgentLoop {
|
|
|
3047
3673
|
// PROGRESSIVE DISCLOSURE: honour unlock signals from tool_search.
|
|
3048
3674
|
// The control fields are stripped before the result reaches the LLM.
|
|
3049
3675
|
if (result && (result._unlock_tools || result._unlock_packs)) {
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
}
|
|
3676
|
+
this.routeTools({
|
|
3677
|
+
source: 'request',
|
|
3678
|
+
requested: (result._unlock_tools || []).filter((name) => resolveTool(name)),
|
|
3679
|
+
requestedPacks: result._unlock_packs || []
|
|
3680
|
+
});
|
|
3056
3681
|
delete result._unlock_tools;
|
|
3057
3682
|
delete result._unlock_packs;
|
|
3058
3683
|
this.debugLog(`capability packs loaded: ${[...this.unlockedPacks].join(', ') || 'core only'}`);
|
|
@@ -3062,8 +3687,11 @@ export class AgentLoop {
|
|
|
3062
3687
|
if (codeAction)
|
|
3063
3688
|
this.emitEvent({ ...codeAction,
|
|
3064
3689
|
phase: result?.success === false || typeof result?.error === 'string' ? 'failed' : 'done' });
|
|
3690
|
+
const eventResult = result?._is_image_marker
|
|
3691
|
+
? { success: result.success !== false && !result.error, output: result.output || `Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'})` }
|
|
3692
|
+
: result;
|
|
3065
3693
|
this.emitEvent({ type: result?.success === false || typeof result?.error === 'string' ? 'step_error' : 'step_complete',
|
|
3066
|
-
tool: functionName, result:
|
|
3694
|
+
tool: functionName, result: eventResult, toolCallId: toolCall.id });
|
|
3067
3695
|
this.stepsCompleted++;
|
|
3068
3696
|
// The procedure, as it actually ran. Tool name plus a whitelisted
|
|
3069
3697
|
// action token only — planCache.toStep() reads no paths, arguments or
|
|
@@ -3180,11 +3808,14 @@ export class AgentLoop {
|
|
|
3180
3808
|
if (result && result._is_image_marker) {
|
|
3181
3809
|
if (!this.llm.supportsVision) {
|
|
3182
3810
|
// Fallback when vision streaming payload is not active on model
|
|
3811
|
+
const outputNote = typeof result.output === 'string' && result.output.trim()
|
|
3812
|
+
? `\nDetails:\n${result.output.trim()}`
|
|
3813
|
+
: '';
|
|
3183
3814
|
this.messages.push({
|
|
3184
3815
|
role: 'tool',
|
|
3185
3816
|
tool_call_id: toolCall.id,
|
|
3186
3817
|
name: functionName,
|
|
3187
|
-
content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]`
|
|
3818
|
+
content: `[Image captured: ${result.filename || 'image'} (${result.mimeType || 'image/png'}). This provider cannot receive image pixels; visual inspection was not completed.]${outputNote}`
|
|
3188
3819
|
});
|
|
3189
3820
|
}
|
|
3190
3821
|
else {
|
|
@@ -3342,21 +3973,53 @@ export class AgentLoop {
|
|
|
3342
3973
|
}
|
|
3343
3974
|
}
|
|
3344
3975
|
}
|
|
3345
|
-
if (e instanceof
|
|
3346
|
-
|
|
3976
|
+
if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
|
|
3977
|
+
const pending = this._pendingConsent;
|
|
3978
|
+
this._pendingConsent = null;
|
|
3979
|
+
this.messages.push({ role: 'assistant', content: `Execution paused: ${pending.tool} failed ${pending.recovery.attempt} times. Keep completed work; do not replay earlier actions.` });
|
|
3347
3980
|
this.memoryManager.saveHistory(this.messages);
|
|
3981
|
+
const verdict = await this.handleRecovery(pending.recovery, pending.tool);
|
|
3982
|
+
if (verdict.stop)
|
|
3983
|
+
break;
|
|
3984
|
+
this.messages.push({ role: 'system', content: verdict.guidance });
|
|
3985
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3986
|
+
continue;
|
|
3987
|
+
}
|
|
3988
|
+
if (e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens' && incompleteTurnContinuations < 5) {
|
|
3989
|
+
incompleteTurnContinuations++;
|
|
3348
3990
|
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
3349
|
-
auditLog.log({
|
|
3350
|
-
|
|
3351
|
-
|
|
3991
|
+
auditLog.log({
|
|
3992
|
+
event: 'efficiency_checkpoint',
|
|
3993
|
+
taskId: this.taskId,
|
|
3994
|
+
reason: e.reason,
|
|
3995
|
+
...this.efficiencyBudget.snapshot()
|
|
3996
|
+
});
|
|
3997
|
+
this.efficiencyBudget.extendBudget?.(1_000_000, 50);
|
|
3998
|
+
compactSessionMessages(this.messages, {
|
|
3999
|
+
keepRecentTurns: 4,
|
|
4000
|
+
taskId: this.taskId,
|
|
4001
|
+
originalPrompt: this.currentTaskPrompt || this.userPrompt
|
|
4002
|
+
});
|
|
4003
|
+
this.emitEvent({ type: 'status', message: 'Continuing task execution from efficiency checkpoint…' });
|
|
4004
|
+
this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
|
|
4005
|
+
this.messages.push({
|
|
4006
|
+
role: 'system',
|
|
4007
|
+
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.]`
|
|
4008
|
+
});
|
|
4009
|
+
this.memoryManager.saveHistory(this.messages);
|
|
4010
|
+
continue;
|
|
3352
4011
|
}
|
|
3353
|
-
if (e
|
|
3354
|
-
|| e?.code === '
|
|
4012
|
+
if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
4013
|
+
|| e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
|
|
3355
4014
|
this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
|
|
3356
4015
|
this.memoryManager.saveHistory(this.messages);
|
|
3357
4016
|
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
3358
|
-
auditLog.log({
|
|
3359
|
-
|
|
4017
|
+
auditLog.log({
|
|
4018
|
+
event: 'efficiency_checkpoint',
|
|
4019
|
+
taskId: this.taskId,
|
|
4020
|
+
reason: e?.reason || e?.code,
|
|
4021
|
+
...this.efficiencyBudget.snapshot()
|
|
4022
|
+
});
|
|
3360
4023
|
break;
|
|
3361
4024
|
}
|
|
3362
4025
|
if (e?.code === 'PROVIDER_REASONING_ONLY' && e.continuationSafe === true && reasoningOnlyRecoveries++ === 0) {
|
|
@@ -3462,14 +4125,27 @@ export class AgentLoop {
|
|
|
3462
4125
|
// must not generate a second (and misleading) success event here.
|
|
3463
4126
|
}
|
|
3464
4127
|
async waitForApproval(toolCallId) {
|
|
4128
|
+
const signal = this.abortController?.signal;
|
|
4129
|
+
if (this.stopRequested || signal?.aborted)
|
|
4130
|
+
return false;
|
|
3465
4131
|
return new Promise((resolve) => {
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
4132
|
+
let settled = false;
|
|
4133
|
+
const finish = (approved) => {
|
|
4134
|
+
if (settled)
|
|
4135
|
+
return;
|
|
4136
|
+
settled = true;
|
|
4137
|
+
clearTimeout(timer);
|
|
4138
|
+
signal?.removeEventListener('abort', onAbort);
|
|
4139
|
+
this.pendingApprovals.delete(toolCallId);
|
|
4140
|
+
resolve(approved === true);
|
|
4141
|
+
};
|
|
4142
|
+
const onAbort = () => finish(false);
|
|
4143
|
+
const timer = setTimeout(() => finish(false), 3600000);
|
|
4144
|
+
timer.unref();
|
|
4145
|
+
this.pendingApprovals.set(toolCallId, finish);
|
|
4146
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
4147
|
+
if (signal?.aborted)
|
|
4148
|
+
finish(false);
|
|
3473
4149
|
});
|
|
3474
4150
|
}
|
|
3475
4151
|
/**
|
|
@@ -3505,6 +4181,9 @@ export class AgentLoop {
|
|
|
3505
4181
|
if (spent > 0)
|
|
3506
4182
|
return 'fatal';
|
|
3507
4183
|
const msg = (error.message || '').toLowerCase();
|
|
4184
|
+
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')) {
|
|
4185
|
+
return 'fatal';
|
|
4186
|
+
}
|
|
3508
4187
|
if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
|
|
3509
4188
|
return 'syntax_error';
|
|
3510
4189
|
}
|