@causyne/agent 1.20.118 → 1.20.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
package/src/agentLoop.js CHANGED
@@ -6,6 +6,9 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
6
6
  import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
7
  import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
8
  import { normalizeAgentFailure } from './agent/providerFailure.js';
9
+ import { classifyAgentError, getRetryHintForError } from './agent/errorClassifier.js';
10
+ import { isActionableTaskPrompt, isGenericHandoffResponse, isDesktopWallpaperChangePrompt, isExecutionOrLaunchTaskPrompt, isCodeAuthoringTaskPrompt, extractSkillIdFromPrompt, isDirectGameTask, isProviderPlanOrQuotaRefusal, isMidTaskProgressText } from './agent/promptIntent.js';
11
+ import { validateAndNormalizeToolArgs } from './agent/toolArgValidator.js';
9
12
  import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
10
13
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
11
14
  import { createHash, randomUUID } from 'crypto';
@@ -16,6 +19,7 @@ import { WorkspacePerception } from './perception.js';
16
19
  import { audioFormatForMimeType } from './providers/base.js';
17
20
  import { TaskBuffer } from './taskBuffer.js';
18
21
  import { TOOL_DEFINITIONS, getDynamicTools, getSearchableToolDefinitions, resolveTool, canonicalToolName } from './tools/registry.js';
22
+ import { scanAndAdaptToolsForProvider } from './tools/toolScanner.js';
19
23
  import { selfRepairToolCall, generateSelfRepairDiagnostic } from './tools/toolSelfRepair.js';
20
24
  import { validateToolArguments } from './tools/argumentValidation.js';
21
25
  import { Sandbox } from './sandbox.js';
@@ -40,7 +44,7 @@ import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js'
40
44
  import { AGENT_USER_POLICY } from './agentPolicy.js';
41
45
  import { VFETracker } from './vfeTracker.js';
42
46
  import { coldObserver } from './observer/coldObserver.js';
43
- import { isRenderedNativeBrowserAction, isVerificationCommand } from './observer/evidence.js';
47
+ import { inspectBrowserToolEvidence, isRenderedNativeBrowserAction, isVerificationCommand } from './observer/evidence.js';
44
48
  import { CausyneObserver, defaultObserver, extractClaimedLocalUrls } from './observer.js';
45
49
  import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
46
50
  import { packForTool, isCoreTool, isGameIntent, isWebIntent, PACK_PLAYBOOKS, PACKS } from './toolPacks.js';
@@ -48,7 +52,7 @@ import { determineToolScope, resolveLazyPlaybooks, refineToolDecision, SmartTool
48
52
  import { buildToolsList, renderToolsList, omittedCustomCount } from './toolsList.js';
49
53
  import { assessVerification } from './verificationPlan.js';
50
54
  import { SmartTools } from './SmartTools.js';
51
- import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
55
+ import { decideTools } from './decideTools.js';
52
56
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
53
57
  import { CHARS_PER_TOKEN, resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
54
58
  // Provider imports
@@ -97,46 +101,7 @@ function spillErrorField(result) {
97
101
  const error = nonEmptyErrorText(result);
98
102
  return error !== undefined ? { error: error.slice(0, 500) } : {};
99
103
  }
100
- export function isActionableTaskPrompt(text) {
101
- const t = (text || '').trim();
102
- if (!t)
103
- return false;
104
- // A no-execution request can be satisfied by analysis without mandatory tool calls.
105
- if (isNoExecutionPrompt(t))
106
- return false;
107
- const pureGreeting = /^(hi|hello|hey|yo|halo|hai|p|assalamu['a]?[l]?aikum|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
108
- if (pureGreeting)
109
- return false;
110
- 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;
111
- if (actionKeywords.test(t))
112
- return true;
113
- return false; // Length alone does not turn an information question into an execution order.
114
- }
115
- export function isGenericHandoffResponse(text) {
116
- const answer = (text || '').trim();
117
- if (!answer || answer.length > 500)
118
- return false;
119
- const lower = answer.toLowerCase();
120
- const handoff = /\b(let me know what you would like to do next|what would you like me to do next|how (can|may) i help|what can i help you with|feel free to (ask|tell me))\b/i.test(lower);
121
- const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
122
- return handoff && !verifiedOutcome;
123
- }
124
- export function isDesktopWallpaperChangePrompt(text) {
125
- const t = (text || '').trim();
126
- if (!t)
127
- return false;
128
- // Explanatory questions or prompts that explicitly forbid execution are never wallpaper mutation requests
129
- if (isNoExecutionPrompt(t) || isReadOnlyOrExplanatoryPrompt(t))
130
- return false;
131
- if (/^(?:why|how|what|does|can\s+you\s+explain|explain|tell\s+me|show\s+me\s+how)\b/i.test(t))
132
- return false;
133
- if (/\b(?:why|how)\s+does\b/i.test(t))
134
- return false;
135
- // Debugging wallpaper-related source or regexes is not a request to mutate macOS.
136
- if (/\b(?:test|review|audit|analy[sz]e|debug|refactor|inspect|explain|write|implement)\b[\s\S]{0,140}\b(?:regex|code|source|logic|verification|readback|function|script|test)\b/i.test(t))
137
- return false;
138
- return /\b(?:change|set|switch|replace)\s+(?:(?:my|the|this|current|desktop|mac|macos)\s+){0,4}(?:desktop picture|wallpaper|desktop background)\b/i.test(t);
139
- }
104
+ export { isActionableTaskPrompt, isGenericHandoffResponse, isDesktopWallpaperChangePrompt, isExecutionOrLaunchTaskPrompt, isCodeAuthoringTaskPrompt, extractSkillIdFromPrompt, isDirectGameTask, isProviderPlanOrQuotaRefusal, isMidTaskProgressText };
140
105
  function readMacDesktopPictures() {
141
106
  try {
142
107
  return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
@@ -147,160 +112,6 @@ function readMacDesktopPictures() {
147
112
  return null;
148
113
  }
149
114
  }
150
- export function isExecutionOrLaunchTaskPrompt(text) {
151
- const t = (text || '').trim();
152
- if (!t)
153
- return false;
154
- return /\b(open|launch|start|run|play|serve|preview)\b/i.test(t)
155
- && !/\b(create|build|make|write|code|implement|generate|refactor)\b/i.test(t);
156
- }
157
- export function isCodeAuthoringTaskPrompt(text) {
158
- const t = (text || '').trim();
159
- if (!t)
160
- return false;
161
- if (isExecutionOrLaunchTaskPrompt(t))
162
- return false;
163
- return /\b(create|build|make|write|code|implement|generate|game|3js|three?\.?js|three?js|app)\b/i.test(t);
164
- }
165
- export function extractSkillIdFromPrompt(prompt) {
166
- const text = String(prompt || '').trim();
167
- if (!text)
168
- return '';
169
- const stopWords = new Set([
170
- 'the', 'a', 'an', 'this', 'that', 'from', 'in', 'with',
171
- 'using', 'for', 'to', 'by', 'and', 'or', 'of'
172
- ]);
173
- const leadingTrim = new Set(['`', '"', "'", '(', '[']);
174
- const trailingTrim = new Set(['`', '"', "'", ')', ',', '.', ';', ':', '!', '?', ']', '\\']);
175
- const cleanCandidate = (raw) => {
176
- const trimmed = raw.trim();
177
- let start = 0;
178
- let end = trimmed.length;
179
- while (start < end && leadingTrim.has(trimmed[start]))
180
- start++;
181
- while (end > start && trailingTrim.has(trimmed[end - 1]))
182
- end--;
183
- const stripped = trimmed.slice(start, end);
184
- if (!stripped || stopWords.has(stripped.toLowerCase()))
185
- return '';
186
- if (/^(?:fs_read_skill|fs_read_skil|read_skill|read_skil|tool_search)$/i.test(stripped)) {
187
- return '';
188
- }
189
- return stripped;
190
- };
191
- const isFileExt = (candidate) => /\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|json|html|css|gradle|apk|aab|dex)$/i.test(candidate);
192
- const cuedSlashMatch = text.match(/(?:\bskill_id|\bskill|\bfs_read_skil{1,2})(?:\s*[:=]\s*|\s+)[`"']?([a-zA-Z0-9][a-zA-Z0-9_.-]{0,80}\/[a-zA-Z0-9][a-zA-Z0-9_.-]{0,120})[`"']?/i);
193
- if (cuedSlashMatch?.[1]) {
194
- const candidate = cleanCandidate(cuedSlashMatch[1]);
195
- if (candidate && !isFileExt(candidate)) {
196
- return candidate;
197
- }
198
- }
199
- for (const m of text.matchAll(/\b([a-zA-Z0-9][a-zA-Z0-9_.-]{0,80}\/[a-zA-Z0-9][a-zA-Z0-9_.-]{0,120})\b/g)) {
200
- const candidate = cleanCandidate(m[1] || '');
201
- if (candidate && !isFileExt(candidate)) {
202
- return candidate;
203
- }
204
- }
205
- const explicitQuotedMatch = text.match(/(?:\bskill_id|\bskill)(?:\s*[:=]\s*|\s+)(?:the\s+)?[`"']([^`"'\n\r]{2,120})[`"']/i);
206
- if (explicitQuotedMatch?.[1]) {
207
- const candidate = cleanCandidate(explicitQuotedMatch[1]);
208
- if (candidate)
209
- return candidate;
210
- }
211
- const bareMatch = text.match(/(?:\bskill_id\s*[:=]\s*|\bskill\s*[:=]\s*|\bskill\s+(?:called\s+|named\s+)?)([a-zA-Z0-9][a-zA-Z0-9_.-]{1,120})/i);
212
- if (bareMatch?.[1]) {
213
- const candidate = cleanCandidate(bareMatch[1]);
214
- if (candidate)
215
- return candidate;
216
- }
217
- return '';
218
- }
219
- export function isDirectGameTask(text) {
220
- return isDirectGameTaskDecision(text);
221
- }
222
- export function isProviderPlanOrQuotaRefusal(text) {
223
- if (!text || typeof text !== 'string')
224
- return false;
225
- const trimmed = text.trim();
226
- if (!trimmed || trimmed.length > 320)
227
- return false;
228
- if (/^upgrade your plan to continue\.?$/i.test(trimmed))
229
- return true;
230
- 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);
231
- }
232
- /**
233
- * Detects when an agent response is an intermediate mid-task progress note or
234
- * transition announcement (e.g. "Real assets verified. Writing the Tesla-style
235
- * redesign now." or "Let me look at the newer assets... Pulling their real
236
- * stills and confirming embeddability.") rather than a finished answer.
237
- */
238
- export function isMidTaskProgressText(text) {
239
- if (!text || typeof text !== 'string')
240
- return false;
241
- const trimmed = text.trim();
242
- if (!trimmed || trimmed.length > 480)
243
- return false;
244
- const lower = trimmed.toLowerCase();
245
- if (lower.includes('?') ||
246
- lower.includes('let me know') ||
247
- lower.includes('how can i help') ||
248
- lower.includes('how may i help') ||
249
- lower.includes('how can i assist') ||
250
- lower.includes('what would you like') ||
251
- lower.includes('what can i help') ||
252
- lower.includes('feel free to')) {
253
- return false;
254
- }
255
- if (trimmed.includes('```'))
256
- return false;
257
- const sentences = trimmed
258
- .split(/(?:(?<=[.!])\s+|\n+)/)
259
- .map(s => s.trim())
260
- .filter(Boolean);
261
- const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
262
- const lastLower = lastSentence.toLowerCase();
263
- if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
264
- return true;
265
- }
266
- const intentPrefixes = [
267
- 'let me ',
268
- "i'll ",
269
- 'i will ',
270
- 'now i ',
271
- 'now let me ',
272
- "now i'll ",
273
- 'now i will ',
274
- 'next, i ',
275
- 'next i ',
276
- "next, i'll ",
277
- "next i'll ",
278
- 'first, i ',
279
- 'first i ',
280
- 'let us ',
281
- "let's ",
282
- 'i shall ',
283
- 'we will ',
284
- "we'll ",
285
- 'i am going to ',
286
- "i'm going to ",
287
- 'going to '
288
- ];
289
- if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || (trimmed.length <= 280 && lower.startsWith(prefix)))) {
290
- if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
291
- return true;
292
- }
293
- }
294
- const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
295
- if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
296
- return true;
297
- }
298
- const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
299
- if (actionNowSuffix.test(lastSentence)) {
300
- return true;
301
- }
302
- return false;
303
- }
304
115
  const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
305
116
 
306
117
  ${PEER_COLLABORATION_POLICY}
@@ -403,9 +214,10 @@ You possess native reverse engineering capabilities powered by the Reverse Engin
403
214
  5. **Multiple Emulators/Devices**: When multiple devices or emulators are connected, specify \`-s <serial>\` (e.g. \`adb -s emulator-5554 ...\`) or set \`export ANDROID_SERIAL=<serial>\`.
404
215
 
405
216
  # Universal Tool Calling & Registry Discipline
406
- 1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
407
- 2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
408
- 3. **Automated Buffer & Self-Correction**: Causyne runs a Universal Tool Buffer with self-repair capabilities. If a tool returns a \`selfRepairGuidance\` result indicating missing or invalid parameters, immediately read the \`expectedParameters\` and re-invoke the tool with the corrected arguments.
217
+ 1. **Strict Root Registry Adherence**: Invoke ONLY tools registered in the active Causyne catalogue (native, plugin, or MCP) or permitted connected-peer capabilities across ACP/Antigravity/Pi. Use exact canonical parameter names and required fields defined in each tool schema without inventing or renaming parameters.
218
+ 2. **Pre-Flight Universal Schema Scan (\`toolsScan\`)**: Before dispatching schemas to any provider API, Causyne scans and compiles every tool declaration into that provider's dialect without reducing or altering underlying tool capability. When an adapted schema asks for a JSON-encoded string on an object, array, or union parameter (e.g. multi-file paths or free-form properties), pass valid JSON so the runtime buffer decodes it transparently to its native type.
219
+ 3. **Universal Self-Repair Buffer (\`toolsSelfRepair\`)**: Every tool call is filtered through \`toolsSelfRepair\`, which heals malformed JSON, decodes adapted free-form/polymorphic values, resolves parameter aliases, coerces types recursively, and emits structured \`selfRepairGuidance\` (\`expectedParameters\`) on incomplete invocations. Always read \`expectedParameters\` and re-invoke with the corrected arguments.
220
+ 4. **Valid JSON Formatting**: Never emit raw unescaped newlines, single-quoted keys, or trailing commas inside tool call JSON strings.
409
221
 
410
222
  # Completion
411
223
  Answer directly when no tool is needed. For action tasks, continue until the authorized work is done or a real blocker is evidenced; then report the verified outcome or blocker concisely.
@@ -601,10 +413,20 @@ export class AgentLoop {
601
413
  ? options.workspaceRoot
602
414
  : process.cwd();
603
415
  this.autonomyOverride = null;
416
+ this.providerOverride = typeof options.provider === 'string' && options.provider.trim()
417
+ ? options.provider.trim()
418
+ : null;
419
+ this.modelOverride = typeof options.model === 'string' && options.model.trim()
420
+ ? options.model.trim()
421
+ : null;
604
422
  this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
605
423
  ? options.approvalScope
606
424
  : processApprovalScope;
607
425
  this.config = loadConfig();
426
+ if (this.providerOverride)
427
+ this.config.provider = this.providerOverride;
428
+ if (this.modelOverride)
429
+ this.config.model = this.modelOverride;
608
430
  this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
609
431
  // Retire spilled tool outputs past their retention window. Fire-and-forget
610
432
  // at task start rather than on a timer: nothing may run in the background
@@ -662,6 +484,8 @@ export class AgentLoop {
662
484
  this.stallGuard = new StallGuardController();
663
485
  this.smartToolsGovernor = new SmartToolsGovernor(4);
664
486
  this._smartToolsNudge = null;
487
+ this.activeFreeFormPaths = new Map();
488
+ this._lastToolsScanKey = '';
665
489
  // Sovereign Progressive Disclosure: which capability packs have entered the
666
490
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
667
491
  this.unlockedPacks = new Set();
@@ -1654,6 +1478,10 @@ export class AgentLoop {
1654
1478
  this.config = loadConfig();
1655
1479
  if (this.autonomyOverride)
1656
1480
  this.config.autonomyMode = this.autonomyOverride;
1481
+ if (this.providerOverride)
1482
+ this.config.provider = this.providerOverride;
1483
+ if (this.modelOverride)
1484
+ this.config.model = this.modelOverride;
1657
1485
  if (typeof this.initializeProvider === 'function') {
1658
1486
  const nextProvider = this.initializeProvider();
1659
1487
  if (nextProvider) {
@@ -2295,6 +2123,21 @@ export class AgentLoop {
2295
2123
  ? eligibleTools.filter((tool) => this.toolScope.has(tool.name)) : eligibleTools;
2296
2124
  const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks, this.config.grantAllTools === true);
2297
2125
  const dynamicToolNames = dynamicTools.map((t) => t.name);
2126
+ // Pre-flight universal schema audit (toolsScan): verify dialect readiness and cache
2127
+ // adapted free-form/polymorphic paths for lossless decoding inside toolsSelfRepair.
2128
+ const activeProviderName = String(this.config?.provider || 'openai');
2129
+ const scanKey = `${activeProviderName}:${dynamicToolNames.join(',')}`;
2130
+ if (scanKey !== this._lastToolsScanKey) {
2131
+ const preflightScan = scanAndAdaptToolsForProvider(dynamicTools, activeProviderName);
2132
+ this.activeFreeFormPaths = preflightScan.freeFormPaths;
2133
+ this._lastToolsScanKey = scanKey;
2134
+ if (preflightScan.repairedCount > 0) {
2135
+ this.debugLog(`[toolsScan] Pre-flight compiled ${preflightScan.repairedCount}/${preflightScan.totalTools} schemas for '${activeProviderName}' (universalReady=${preflightScan.universalReady})`);
2136
+ }
2137
+ if (!preflightScan.universalReady) {
2138
+ this.debugLog(`[toolsScan] Residual compatibility issues on '${activeProviderName}': ${preflightScan.residualIssues.slice(0, 5).map((issue) => `${issue.tool}:${issue.code}`).join(', ')}`);
2139
+ }
2140
+ }
2298
2141
  // Dynamically inject the absolute latest System context
2299
2142
  const autonomyMode = this.config.autonomyMode || 'C';
2300
2143
  const allowedPaths = this.sandbox.grantAllAccess
@@ -3924,7 +3767,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
3924
3767
  const tool = resolveTool(functionName);
3925
3768
  const toolSchema = tool?.schema?.parameters || tool?.schema?.input_schema;
3926
3769
  const repair = selfRepairToolCall(toolCall, toolSchema, {
3927
- cwd: this.workspaceRoot || process.cwd()
3770
+ cwd: this.workspaceRoot || process.cwd(),
3771
+ freeFormPaths: this.activeFreeFormPaths?.get(functionName)
3928
3772
  });
3929
3773
  if (repair.error) {
3930
3774
  this.messages.push({
@@ -4439,14 +4283,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4439
4283
  if (functionName === 'browser_act' && result?.success === true) {
4440
4284
  const hasExplicitPlanInBatch = Array.isArray(response.toolCalls)
4441
4285
  && response.toolCalls.some((c) => canonicalToolName(c?.function?.name || '') === 'update_plan');
4442
- if (!hasExplicitPlanInBatch) {
4443
- this.advanceImplementationPlanProgress('verification');
4444
- }
4445
- const browserResults = Array.isArray(result.data) ? result.data : [];
4446
- const allRuntimeErrors = browserResults.flatMap((item) => Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []);
4447
- const hasValidBrowserAction = browserResults.some((item) => ['preview', 'snapshot', 'scrape', 'screenshot'].includes(item?.action));
4448
- if (allRuntimeErrors.length === 0 && (hasValidBrowserAction || result.url || result.tabId)) {
4286
+ const { verified, runtimeErrors: allRuntimeErrors } = inspectBrowserToolEvidence(result);
4287
+ if (verified) {
4449
4288
  this.webVerificationState.browserActUsed = true;
4289
+ if (!hasExplicitPlanInBatch)
4290
+ this.advanceImplementationPlanProgress('verification');
4450
4291
  }
4451
4292
  else if (allRuntimeErrors.length > 0) {
4452
4293
  this.webVerificationState.browserActUsed = false;
@@ -5008,69 +4849,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
5008
4849
  }
5009
4850
  // V5: Classify errors for intelligent retry decisions
5010
4851
  classifyError(error) {
5011
- if (error?.code === 'PROVIDER_NO_PROGRESS')
5012
- return 'fatal';
5013
- if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
5014
- || error?.code === 'AGY_NATIVE_ACTION_BUDGET'
5015
- || error?.code === 'AGY_DESKTOP_TASK_LIMIT')
5016
- return 'fatal';
5017
- // A provider may have charged for completed steps before the turn failed.
5018
- // Replaying that turn can repeat actions and spend the same tokens again.
5019
- const spent = Number(error?.partialUsage?.promptTokens || 0)
5020
- + Number(error?.partialUsage?.completionTokens || 0);
5021
- if (spent > 0)
5022
- return 'fatal';
5023
- const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
5024
- if (error?.name === 'OpenRouterPrivacyConstraintError'
5025
- || msg.includes('matching the privacy policy')
5026
- || msg.includes('data_collection=')) {
5027
- return 'fatal';
5028
- }
5029
- 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')) {
5030
- return 'fatal';
5031
- }
5032
- if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
5033
- return 'syntax_error';
5034
- }
5035
- if (msg.includes('enoent') || msg.includes('no such file') || msg.includes('not found') || msg.includes('does not exist')) {
5036
- return 'path_not_found';
5037
- }
5038
- if (msg.includes('econnrefused') || msg.includes('econnreset') || msg.includes('etimedout') || msg.includes('fetch failed') || msg.includes('network')) {
5039
- return "network_error";
5040
- }
5041
- if (msg.includes('rate limit') || msg.includes('429') || msg.includes('too many requests') || msg.includes('quota')) {
5042
- return 'rate_limit';
5043
- }
5044
- if (msg.includes('eacces') || msg.includes('permission denied') || msg.includes('eperm')) {
5045
- return 'permission_denied';
5046
- }
5047
- if (msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('api key')) {
5048
- return 'auth_error';
5049
- }
5050
- if (msg.includes('400') || msg.includes('invalid_parameter') || msg.includes('invalid_request') || msg.includes('required property') || msg.includes('bad request')) {
5051
- return 'invalid_request_error';
5052
- }
5053
- if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
5054
- return 'fatal';
5055
- }
5056
- if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5057
- return 'fatal';
5058
- }
5059
- return 'unknown_error';
4852
+ return classifyAgentError(error);
5060
4853
  }
5061
4854
  // V5: Provide actionable retry hints per error type
5062
4855
  getRetryHint(errorType) {
5063
- const hints = {
5064
- 'syntax_error': 'Check your command syntax or JSON structure. Ensure quotes are balanced.',
5065
- 'path_not_found': 'The file or directory does not exist. Use fs.list to verify the path first, or create it with fs.write/mkdir.',
5066
- ["network_error"]: "Network connectivity issue. Wait a moment and retry. If persistent, check if the URL is correct.",
5067
- 'rate_limit': 'API rate limit hit. Wait 5-10 seconds before retrying.',
5068
- 'permission_denied': 'Permission denied. Check if the path is within allowed workspace paths. Try a different directory.',
5069
- 'auth_error': 'Authentication failed. Do NOT retry — the API key may be invalid.',
5070
- 'invalid_request_error': 'API request format error (400 Bad Request). Do NOT retry — check model parameter compliance.',
5071
- 'unknown_error': 'An unexpected error occurred. Try a different approach entirely.'
5072
- };
5073
- return hints[errorType] || hints['unknown_error'];
4856
+ return getRetryHintForError(errorType);
5074
4857
  }
5075
4858
  async runPreToolUse(toolName, args, toolCallId) {
5076
4859
  return runConfiguredHooks({
@@ -5096,89 +4879,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
5096
4879
  }
5097
4880
  // V5: Validate tool call arguments before execution
5098
4881
  validateToolArgs(toolName, args) {
5099
- if (!args || typeof args !== 'object') {
5100
- return 'Tool arguments must be a JSON object';
5101
- }
5102
- const baseDir = this.workspaceRoot || process.cwd();
5103
- const resolveOne = (raw) => {
5104
- const val = raw.trim();
5105
- if (!val || /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val)) {
5106
- return null;
5107
- }
5108
- if (val === '~' || val.startsWith('~/') || val.startsWith('~\\')) {
5109
- return val.replace(/^~(?=$|[\\/])/, os.homedir());
5110
- }
5111
- if (!path.isAbsolute(val)) {
5112
- return path.resolve(baseDir, val);
5113
- }
5114
- return val;
5115
- };
5116
- // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
5117
- const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
5118
- if (toolName !== 'fs_read_skill') {
5119
- const pathFields = [
5120
- 'path', 'searchPath', 'cwd', 'directory',
5121
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
5122
- 'targetFile', 'outputFile', 'outputPath',
5123
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5124
- ];
5125
- for (const field of pathFields) {
5126
- if (args[field] && typeof args[field] === 'string') {
5127
- const resolved = resolveOne(args[field]);
5128
- if (resolved !== null) {
5129
- args[field] = resolved;
5130
- }
5131
- }
5132
- }
5133
- if (Array.isArray(args.target_directories)) {
5134
- args.target_directories = args.target_directories.map((entry) => {
5135
- if (typeof entry !== 'string')
5136
- return entry;
5137
- return resolveOne(entry) ?? entry;
5138
- });
5139
- }
5140
- }
5141
- // 2. Terminal commands must have a command string
5142
- if ((toolName === 'sysRun' || toolName === 'sysRunBg') && !args.command) {
5143
- return 'Missing required "command" argument';
5144
- }
5145
- // 3. File write must have a path AND content.
5146
- //
5147
- // These branches were dead: canonicalToolName() (called on every tool name
5148
- // before this runs) normalises '.'→'_', so `toolName` is 'fs_write', never
5149
- // 'fs.write'. The old 'fs.write' / 'codebase.search' / 'web.search' literals
5150
- // could never match, so the model's missing-argument mistakes reached the
5151
- // tool as runtime exceptions instead of a corrective message. Matched on the
5152
- // canonical names now, and fs_write's `content` is actually checked (the old
5153
- // comment said "must have content" but the code only looked at `path`).
5154
- if (toolName === 'fs_write' && !args.path) {
5155
- return 'Missing required "path" argument';
5156
- }
5157
- if (toolName === 'fs_write' && args.content === undefined) {
5158
- return 'Missing required "content" argument';
5159
- }
5160
- // 4. Search must have a query
5161
- if ((toolName === 'codebase_search' || toolName === 'web_search') && !args.query) {
5162
- return 'Missing required "query" argument';
5163
- }
5164
- // 5. Tool search must have a query, pack, or names array
5165
- if (toolName === 'tool_search') {
5166
- const q = typeof args.query === 'string'
5167
- ? args.query.trim()
5168
- : (Array.isArray(args.query) ? args.query.map(String).join(' ').trim() : '');
5169
- const p = typeof args.pack === 'string' ? args.pack.trim() : '';
5170
- const n = Array.isArray(args.names) && args.names.length > 0;
5171
- if (!q && !p && !n) {
5172
- return 'Missing required "query" or "pack" argument';
5173
- }
5174
- }
5175
- // 6. Skill reader must have a non-empty skill_id
5176
- if (toolName === 'fs_read_skill') {
5177
- const sid = typeof args.skill_id === 'string' ? args.skill_id.trim() : '';
5178
- if (!sid) {
5179
- return 'Missing required "skill_id" argument';
5180
- }
5181
- }
5182
- return null; // No validation errors
4882
+ return validateAndNormalizeToolArgs(toolName, args, this.workspaceRoot || process.cwd());
5183
4883
  }
5184
4884
  }