The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(agent): one strategy and one call-recovery chain for every loop (CA K1-K3)
purplecc0fd10608e7
diff --git a/src/api/agents/__tests__/sub-agent-prompt-transport.test.ts b/src/api/agents/__tests__/sub-agent-prompt-transport.test.tsnew file mode 100644index 00000000..d45eab04--- /dev/null+++ b/src/api/agents/__tests__/sub-agent-prompt-transport.test.ts@@ -0,0 +1,94 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++// CA K3: a sub-agent on a local model without native tool calling used to get+// a native `tools` payload, ignore it and hand back its intentions as the+// result. It now runs on the same transport verdict as both tabs.++const chatWithTools = vi.fn()+const toolExecute = vi.fn(async () => 'hello from notes')++const READ_DEF = {+ name: 'file_read',+ description: 'read a file',+ inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },+ category: 'filesystem',+ source: 'builtin',+}++let strategy: 'native' | 'hermes_xml' = 'hermes_xml'++vi.mock('../../../stores/modelStore', () => ({+ useModelStore: { getState: () => ({ activeModel: 'ollama::tiny', models: [] }) },+}))+vi.mock('../../providers', () => ({+ getProviderForModel: (name: string) => ({ provider: { chatWithTools }, modelId: name.split('::')[1] ?? name }),+}))+vi.mock('../../../lib/agent-strategy', () => ({+ resolveToolCallingStrategy: async (name: string) => ({+ strategy,+ modelToUse: name.split('::')[1] ?? name,+ modelId: name.split('::')[1] ?? name,+ providerId: 'ollama',+ provider: { chatWithTools },+ }),+}))+vi.mock('../../mcp/tool-registry', () => ({+ toolRegistry: {+ getAll: () => [READ_DEF],+ resolveExecutable: (name: string) => (name === 'file_read' ? READ_DEF : undefined),+ execute: (...args: unknown[]) => toolExecute(...(args as [])),+ getPermissionLevelWithOverrides: () => 'auto',+ },+}))+vi.mock('../../../stores/permissionStore', () => ({+ usePermissionStore: { getState: () => ({ getEffectivePermissions: () => ({}), perToolOverrides: {} }) },+}))+vi.mock('../../../stores/toolAuditStore', () => ({+ useToolAuditStore: { getState: () => ({ record: () => 'audit-1', complete: () => {} }) },+}))++import { defaultSubAgentRunner, SUB_AGENT_BUDGET } from '../sub-agent'+import { AgentBudget } from '../budget'+import type { ChatMessage } from '../../providers/types'++const run = { conversationId: 'c1', mode: 'bypass' } as never++describe('sub-agent on the prompt transport (CA K3)', () => {+ beforeEach(() => {+ chatWithTools.mockReset()+ toolExecute.mockClear()+ })++ it('offers the tools in the prompt, runs a <tool_call> and answers', async () => {+ strategy = 'hermes_xml'+ chatWithTools+ .mockResolvedValueOnce({ content: '<tool_call>{"name": "file_read", "arguments": {"path": "notes.txt"}}</tool_call>', toolCalls: [] })+ .mockResolvedValueOnce({ content: 'The note says hello.', toolCalls: [] })++ const out = await defaultSubAgentRunner('read notes.txt', '', { budget: new AgentBudget({ ...SUB_AGENT_BUDGET }), run })++ expect(out).toBe('The note says hello.')+ expect(toolExecute).toHaveBeenCalledOnce()+ const [, firstMessages, firstTools] = chatWithTools.mock.calls[0] as [string, ChatMessage[], unknown[]]+ expect(firstTools).toEqual([])+ expect(String(firstMessages[0].content)).toContain('file_read')+ // The result went back as text, not in the native `tool` role.+ const [, secondMessages] = chatWithTools.mock.calls[1] as [string, ChatMessage[]]+ expect(secondMessages.some((m) => m.role === 'tool')).toBe(false)+ expect(secondMessages.some((m) => m.role === 'user' && String(m.content).includes('hello from notes'))).toBe(true)+ })++ it('lifts a prose call on the native transport too', async () => {+ strategy = 'native'+ chatWithTools+ .mockResolvedValueOnce({ content: 'file_read(path="notes.txt")', toolCalls: [] })+ .mockResolvedValueOnce({ content: 'Done.', toolCalls: [] })++ const out = await defaultSubAgentRunner('read notes.txt', '', { budget: new AgentBudget({ ...SUB_AGENT_BUDGET }), run })++ expect(out).toBe('Done.')+ expect(toolExecute).toHaveBeenCalledOnce()+ const [, , nativeTools] = chatWithTools.mock.calls[0] as [string, ChatMessage[], unknown[]]+ expect(nativeTools).toHaveLength(1)+ })+})diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.tsindex 832773bc..20f0d959 100644--- a/src/api/agents/sub-agent.ts+++ b/src/api/agents/sub-agent.ts@@ -32,6 +32,8 @@ import { laneOf, currentLaneFacts, type RunLane } from '../../lib/run-lane-of-mo// Einstiegspunkte dieser Datei hängen am `delegate_task`-Executor, den erst// registerBuiltinTools() verdrahtet.import { toolRegistry } from '../mcp/tool-registry'+import { buildHermesToolCall, buildHermesToolPrompt, buildHermesToolResult, hasToolCallTags, parseHermesToolCalls, stripToolCallTags } from '../hermes-tool-calling'+import { recoverTurnCalls } from '../../lib/agent-core/recover'import type { MCPToolDefinition, ToolArgs } from '../mcp/types'import type { ChatMessage } from '../providers/types'import type { AgentToolCall } from '../../types/agent-mode'@@ -507,7 +509,21 @@ export async function defaultSubAgentRunner(}const laufmodell = wahl.modelif (!laufmodell) return 'Error: No active model configured.'- const { provider, modelId } = getProviderForModel(laufmodell)+ // CA K3: the same transport verdict as both tabs. A local model without+ // native tool calling (hermes_xml) used to get a native `tools` payload+ // here, ignored it and answered in prose: the sub-agent did nothing and+ // reported its intentions as the result. A resolver that cannot run (a+ // test double without the model list, an offline Ollama) keeps the old+ // native transport rather than failing the delegation.+ let { provider, modelId } = getProviderForModel(laufmodell)+ let promptTransport = false+ try {+ const { resolveToolCallingStrategy } = await import('../../lib/agent-strategy')+ const resolved = await resolveToolCallingStrategy(laufmodell)+ provider = resolved.provider+ modelId = resolved.modelToUse+ promptTransport = resolved.strategy === 'hermes_xml'+ } catch { /* native, as before */ }const tools: MCPToolDefinition[] = toolRegistry.getAll()@@ -524,7 +540,9 @@ export async function defaultSubAgentRunner(const messages: ChatMessage[] = [{role: 'system',- content: buildSubAgentSystemPrompt(),+ content: promptTransport+ ? `${buildSubAgentSystemPrompt()}\n\n${buildHermesToolPrompt(tools)}`+ : buildSubAgentSystemPrompt(),},{role: 'user',@@ -587,7 +605,20 @@ export async function defaultSubAgentRunner(// the user stopped, and that is paid compute the product promised would// not happen ("Stop means stop"). Threading the same signal the tool// gates already use into the request makes the abort reach the wire.- const turn = await provider.chatWithTools(modelId, messages, llmTools, { signal: gates.abortSignal })+ const raw = await provider.chatWithTools(modelId, messages, promptTransport ? [] : llmTools, { signal: gates.abortSignal })+ // The calls of this turn, wherever the model put them: native, <tool_call>+ // tags on the prompt transport, JSON or prose in the answer, or the+ // reasoning channel. One chain for every loop (lib/agent-core/recover.ts).+ const tagged = promptTransport && hasToolCallTags(raw.content || '')+ const recovered = recoverTurnCalls({+ toolCalls: tagged+ ? parseHermesToolCalls(raw.content || '').map((tc) => ({ function: { name: tc.name, arguments: tc.arguments } }))+ : raw.toolCalls ?? [],+ content: tagged ? stripToolCallTags(raw.content || '') : raw.content || '',+ thinking: raw.thinking,+ tools,+ })+ const turn = { ...raw, content: recovered.content, toolCalls: recovered.toolCalls }// What a sub-agent returns becomes a TOOL RESULT in the parent's context,// so leaked reasoning floods the run it was supposed to shorten (2.6.7// Denk-Audit, Loch 11). Same settlement as every visible surface.@@ -650,6 +681,26 @@ export async function defaultSubAgentRunner({ abortSignal: gates.abortSignal },)+ if (promptTransport) {+ // The prompt transport speaks in text both ways: a strict chat template+ // has no branch for the native `tool` role (same rule as useCodex).+ results.forEach((r, i) => {+ const tc = turn.toolCalls[i]+ messages.push({ role: 'assistant', content: buildHermesToolCall(tc.function.name, tc.function.arguments) })+ messages.push({+ role: 'user',+ content: buildHermesToolResult(+ tc.function.name,+ clampTaskResult(+ (r.result !== undefined ? stripSourcesMarker(r.result) : undefined) ?? gates.refusals.get(r.id) ?? r.error ?? '(no output)',+ ),+ ),+ })+ })+ if (tasks && options.taskId) tasks.getState().update(options.taskId, { messages: [...messages] })+ continue+ }+messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls })// Map each result back to its ORIGINATING call by index. executeParallel// preserves input order (results[i] <-> requests[i] <-> turn.toolCalls[i]),diff --git a/src/hooks/codex/__tests__/hermes-zweig-liest-json-aufrufe.test.ts b/src/hooks/codex/__tests__/hermes-zweig-liest-json-aufrufe.test.tsindex 0204a0f7..f88b0816 100644--- a/src/hooks/codex/__tests__/hermes-zweig-liest-json-aufrufe.test.ts+++ b/src/hooks/codex/__tests__/hermes-zweig-liest-json-aufrufe.test.ts@@ -29,6 +29,6 @@ describe('a tool call written as a json block, on the prompt transport', () => {const from = src.indexOf('const raw = hermesTurn.content')const hermes = src.slice(from, src.indexOf('overflowRetries = 0', from))expect(from).toBeGreaterThan(0)- expect(hermes).toContain('recoverKnownToolCallsFromContent(')+ expect(hermes).toContain('recoverTurnCalls(')})})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex d1cadc6c..24764a4a 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -49,7 +49,7 @@ import { stripVisionFeedbackMessages, reportMultimodalRefusal } from '../lib/visimport { log } from '../lib/logger'import { gatePlanTool, planToolAllowed } from '../lib/plan-gate'import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'-import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, repairToolCall, toolCallsFromReasoning } from '../lib/loose-tool-parse'+import { recoverTurnCalls } from '../lib/agent-core/recover'import { isMediaTool, mediaCallSucceeded } from '../lib/media-result'import { mediaTurnCaps, droppedMediaNote } from '../lib/media-turn-caps'import { isLocalModelByName } from '../api/agents/model-locality'@@ -171,7 +171,7 @@ import { capHiddenToolHistory } from './codex/hidden-history'// derselbe, und zwei Wortlaute fuer einen abgeschnittenen Zug waeren zwei// Stellen, von denen eine gepflegt wird.import { codexCutoffNote, dropCutOffCall } from './codex/turn-cutoff'-import { asString, errorText, isRecord, prop } from '../types/json-guards'+import { asString, errorText, prop } from '../types/json-guards'import type { ToolArgs } from '../api/mcp/types'import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'import { buildChatSystemPrompt } from '../lib/system-prompt'@@ -2483,52 +2483,27 @@ export function useAgentChat() {// preserved as a `reflection` block so it renders above the tool// calls in chronological order. Only the final-turn content (no// tool_calls) becomes the message body.- const knownToolNames = toolRegistry.getAll().map((t) => t.name)-- // Canonicalize near-miss tool names (2026-06-03): gemma4 emitted a- // NATIVE call to `video_generation` (not `video_generate`) → "Unknown- // tool" → it gave up. Map such close misses to the registered name.- if (toolCalls.length > 0) {- const tools = toolRegistry.getAll()- toolCalls = toolCalls.map((tc) => {- const fixed = repairToolCall(tc.function.name, isRecord(tc.function.arguments) ? tc.function.arguments : {}, tools)- return fixed.name === tc.function.name ? tc : { ...tc, function: { ...tc.function, name: fixed.name, arguments: fixed.arguments } }- })- }-- // Loose tool-call fallback (2026-06-03): weak local models often- // WRITE the call into their answer text instead of using the structured- // tool_calls channel — gemma4:e4b answers in prose; qwen2.5-coder:14b- // wrote `image_generate(prompt="…")` as plain text and never emitted a- // real call, so the image/video flow never fired. If the native/Hermes- // channel produced nothing, lift any recognizable call out of the- // content (known tool names only) and strip it from the visible prose.- if (toolCalls.length === 0 && turnContent.trim()) {- const loose = parseLooseToolCalls(turnContent, knownToolNames)- if (loose.calls.length > 0) {- toolCalls = loose.calls.map((c) => ({ function: { name: c.name, arguments: c.arguments } }))- turnContent = stripMatchedCalls(turnContent, loose.matched)- log.info('agent.loose_tool_call_recovered', { count: toolCalls.length, names: toolCalls.map((t) => t.function.name) })- }- }-- // C59 A3: the calls sat in the reasoning channel and the answer is- // empty (a server that took the model for a thinking model).+ // One recovery chain for every loop (CA K2, lib/agent-core/recover.ts):+ // repaired native names (gemma4 `video_generation`, GH #147 generic+ // `function`), JSON in the answer, prose calls like+ // `image_generate(prompt="…")` (qwen2.5-coder:14b, gemma4:e4b), calls+ // stuck in the reasoning channel (C59 A3), and the call text cleaned+ // out of the visible answer. Known tool names only.{- const fromReasoning = toolCallsFromReasoning(turnThinking, turnContent, toolCalls.length, [...knownToolNames, ...(compactRun ? [TOOL_SEARCH] : [])])- if (fromReasoning.length) {- toolCalls = fromReasoning.map((c) => ({ function: { name: c.name, arguments: c.arguments } }))- log.info('agent.reasoning_tool_call_recovered', { count: toolCalls.length, names: toolCalls.map((t) => t.function.name) })+ const recovered = recoverTurnCalls({+ toolCalls,+ content: turnContent,+ thinking: turnThinking,+ tools: toolRegistry.getAll(),+ extraNames: compactRun ? [TOOL_SEARCH] : [],+ })+ toolCalls = recovered.toolCalls+ turnContent = recovered.content+ if (recovered.source !== 'native' && recovered.source !== 'none') {+ log.info('agent.tool_call_recovered', { from: recovered.source, count: toolCalls.length, names: toolCalls.map((t) => t.function.name) })}}- // Clean any tool-call text the model echoed into its prose (the owner- // 2026-06-04) — raw JSON like {"name":"image_generate",…} was leaking- // into the chat as a "notes"/JSON block. Runs even when a proper native- // call was emitted alongside the echo. Tool args/results stay in the- // agent's internal history; this only cleans the visible bubble.- turnContent = stripToolCallText(turnContent, knownToolNames)-// A turn cut off by the token limit: its last call may stop halfway// (dropCutOffCall). Checked after the loose fallback, which reads the// same cut text.diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 6aaa73fc..41ad0b4d 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -13,11 +13,11 @@ import { useSettingsStore } from '../stores/settingsStore'import { useChatStore, flushChatPersist } from '../stores/chatStore'import { buildSamplingRequest } from '../lib/sampling'import { endTurnDurably } from '../stores/durability'-import { getProviderForModel, getProviderIdFromModel } from '../api/providers'+import { getProviderIdFromModel } from '../api/providers'+import { resolveToolCallingStrategy } from '../lib/agent-strategy'import { markToolsUnsupported } from '../api/tool-capability'import { toolRegistry } from '../api/mcp'import { usePermissionStore } from '../stores/permissionStore'-import { toolStrategyFor } from '../lib/tool-support'import { allowedInReadOnlyTurn } from '../lib/mutating-tools'import { applyGoalCommand } from '../lib/goal-command'import {@@ -67,7 +67,7 @@ import { useStagedChangesStore, flushStagedPersist } from '../stores/stagedChangimport { log } from '../lib/logger'import type { AgentToolCall } from '../types/agent-mode'import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'-import { isCompatProviderId, speaksOpenAIProtocol } from '../api/providers/compat-id'+import { speaksOpenAIProtocol } from '../api/providers/compat-id'import type { ChatMessage, ToolCall, ToolCallProgress, ToolDefinition } from '../api/providers/types'import { useRunActivityStore, toolProgressActivity, waitBeforeRetry } from '../stores/runActivityStore'import { executeParallel, applyResultToToolCall, resultFailed, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'@@ -126,7 +126,7 @@ import { createLivePaint } from './codex/live-paint'import { seedEstimatedUsage, reportTurnUsage } from './codex/turn-usage'import { lastRequestUsageNotice, requestUsageTracker } from '../lib/request-usage'import { shouldDowngradeThinking, engineDeniedThinking } from './codex/thinking-downgrade'-import { recoverToolCallsFromContent, recoverKnownToolCallsFromContent, recoverToolCallsFromReasoning } from './codex/tool-call-recovery'+import { recoverTurnCalls } from '../lib/agent-core/recover'import { codexStallVerdict } from './codex/stall-verdict'import { createStagedWriter } from './codex/staged-writes'import { codexCutoffNote, dropCutOffCall } from './codex/turn-cutoff'@@ -138,19 +138,6 @@ import { gatePlanTool, codePlanAllowed, planNudgeDue, PLAN_NUDGE } from '../lib/import { newVerifyState, recordVerifyRound, verifyNudgeDue, VERIFY_NUDGE } from '../lib/verify-nudge'import { withSelfControlTools } from '../lib/settings-tool-names'-/** A name the model wrote in its text is a call only when it is one of the- * agent's tools, after the usual name repair (GH #147). */-function isCodexTool(name: string, args: Record<string, unknown>): boolean {- const tools = toolRegistry.getAll()- const repaired = repairToolCall(name, args, tools).name- return tools.some((t) => t.name === repaired)-}--/** Every name a call lifted out of the reasoning channel may carry (C59 A3). */-function codexKnownNames(): string[] {- return [...toolRegistry.getAll().map((t) => t.name), TOOL_SEARCH]-}-// Why a run ended, or was pushed on, belongs in the support log. This used to// be a no-op, and a run that never finished its task left nothing to read on// the user's machine: which guard ended each run was unknowable. The run-shaping tags go out as warn,@@ -740,31 +727,13 @@ export function useCodex() {const addBlock = blockSink.addconst updateBlockById = blockSink.update- // Resolve provider- const { provider, modelId } = getProviderForModel(activeModel)- const providerId = getProviderIdFromModel(activeModel)- // Every non-Ollama provider used to be hardcoded to 'native' here, which- // ignored both the server's `supports_tools` answer and the cache of models- // a previous run watched reject a `tools` payload. The request went out- // anyway, came back 405, and the negative expired 24 h later so the user- // paid for the same discovery again. toolStrategyFor applies the same- // precedence the dropdown and the Agent toggle use.- const pickerMeta = useModelStore.getState().models.find((m) => m.name === activeModel)- let strategy = toolStrategyFor({- name: activeModel,- supportsTools: pickerMeta && pickerMeta.type === 'text' ? pickerMeta.supportsTools : undefined,- })- // The registry already stripped the `provider::` prefix when it resolved- // the client; re-splitting the name here was a second copy of that rule.- const modelToUse = modelId- // G37b (R21d wire proof, 2026-08-08): the picker row is silent for the- // managed built-in engine (useModels synthesizes its rows without ever- // running listModels), so ask the server itself before the first request.- // Only a hard `false` downgrades to the prompt transport; cloud endpoints- // answer without a network call.- if (strategy === 'native' && (providerId === 'openai' || isCompatProviderId(providerId)) && provider.serverToolSupport) {- if ((await provider.serverToolSupport(modelToUse)) === false) strategy = 'hermes_xml'- }+ // Resolve provider + tool calling strategy (CA K1): the one resolution+ // every surface uses (Agent tab, workflows, voice, sub-agents). This tab+ // used to carry its own copy without the Ollama half: no template fix+ // (a fixable model ran on the prompt transport here and natively in the+ // Agent tab) and no /api/show overlay (a model whose template cannot+ // parse tools still got a native payload). One function, one verdict.+ const { strategy, modelToUse, modelId, providerId, provider } = await resolveToolCallingStrategy(activeModel)// C59 A2: a local model up to ~35B gets the compact profile (short tool// list, one-line descriptions, tool_search). Native transport only: the// Hermes prompt is built once and cannot grow mid-run.@@ -1265,8 +1234,10 @@ export function useCodex() {await ensureBuiltinAgentCtx(modelToUse)} catch { /* run with whatever the engine has */ }+ // Keyed on the raw id, like the Agent tab: an Ollama agent variant+ // (`<model>-agent`) has no picker row and no context entry of its own.const numCtx: number = await resolveAgentNumCtx(- modelToUse, providerId, settings.contextWindowOverride, activeModel,+ modelId, providerId, settings.contextWindowOverride, activeModel,)try {@@ -1782,10 +1753,10 @@ export function useCodex() {// Werkzeugaufrufe, die im Fliesstext stehen — und die Prosa, die dabei// stehen bleiben MUSS: hooks/codex/tool-call-recovery.ts.{- const recovered = recoverToolCallsFromContent(toolCalls, turnContent)+ const recovered = recoverTurnCalls({ toolCalls, content: turnContent, thinking: turn.thinking, tools: toolRegistry.getAll(), extraNames: [TOOL_SEARCH] })toolCalls = recovered.toolCallsturnContent = recovered.content- toolCalls = recoverToolCallsFromReasoning(toolCalls, turnContent, turn.thinking, codexKnownNames())+ if (recovered.source !== 'native' && recovered.source !== 'none') diagLog('calls-recovered', { from: recovered.source, count: toolCalls.length })}} else {// ── Streaming path for OpenAI-compat / Anthropic / LU Cloud ──@@ -1830,10 +1801,10 @@ export function useCodex() {// only when every name in it is a tool this agent has, so example// JSON in an explanation is never run.{- const recovered = recoverKnownToolCallsFromContent(toolCalls, turnContent, isCodexTool)+ const recovered = recoverTurnCalls({ toolCalls, content: turnContent, thinking: turn.thinking, tools: toolRegistry.getAll(), extraNames: [TOOL_SEARCH] })toolCalls = recovered.toolCallsturnContent = recovered.content- toolCalls = recoverToolCallsFromReasoning(toolCalls, turnContent, turn.thinking, codexKnownNames())+ if (recovered.source !== 'native' && recovered.source !== 'none') diagLog('calls-recovered', { from: recovered.source, count: toolCalls.length })}if (keepThinking && turn.thinking) {thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinking@@ -1978,10 +1949,10 @@ export function useCodex() {}))turnContent = stripToolCallTags(raw)} else {- // Kein <tool_call>-Tag, aber vielleicht ein ```json-Aufruf: dieselbe- // Wiederherstellung wie in den beiden Zweigen darueber, nur fuer- // bekannte Werkzeuge (T1-Nachttest 3.0.9).- const recovered = recoverKnownToolCallsFromContent([], raw, isCodexTool)+ // Kein <tool_call>-Tag, aber vielleicht ein ```json- oder ein+ // Prosa-Aufruf: dieselbe Kette wie in den Zweigen darueber, nur+ // fuer bekannte Werkzeuge (T1-Nachttest 3.0.9, CA K2).+ const recovered = recoverTurnCalls({ toolCalls: [], content: raw, thinking: hermesTurn.thinking, tools: toolRegistry.getAll(), extraNames: [TOOL_SEARCH] })toolCalls = recovered.toolCallsturnContent = recovered.content}diff --git a/src/lib/__tests__/prompt-environment-render.test.ts b/src/lib/__tests__/prompt-environment-render.test.tsindex 2d49bd64..2c1e28d4 100644--- a/src/lib/__tests__/prompt-environment-render.test.ts+++ b/src/lib/__tests__/prompt-environment-render.test.ts@@ -130,7 +130,8 @@ describe('the sub-agent prompt carries both halves', () => {const runnerAt = sub.indexOf('export async function defaultSubAgentRunner')expect(runnerAt).toBeGreaterThan(-1)const runner = sub.slice(runnerAt)- expect(runner).toContain('content: buildSubAgentSystemPrompt(),')+ // CA K3: on the prompt transport the tool block follows the same prompt.+ expect(runner).toMatch(/content: promptTransport\s*\?\s*`\$\{buildSubAgentSystemPrompt\(\)\}[^`]*`\s*:\s*buildSubAgentSystemPrompt\(\),/)expect(runner).not.toContain("'You are a focused sub-agent.")})})diff --git a/src/lib/__tests__/tool-call-hardening.test.ts b/src/lib/__tests__/tool-call-hardening.test.tsindex 5a6ba536..7b8f011c 100644--- a/src/lib/__tests__/tool-call-hardening.test.ts+++ b/src/lib/__tests__/tool-call-hardening.test.ts@@ -81,7 +81,10 @@ describe('a call stranded in the reasoning channel', () => {it('both loops call it', () => {const src = (p: string) => readFileSync(resolve(__dirname, '..', '..', p), 'utf8')- expect(src('hooks/useAgentChat.ts')).toMatch(/toolCallsFromReasoning\(turnThinking, turnContent, toolCalls\.length/)- expect(src('hooks/useCodex.ts').match(/recoverToolCallsFromReasoning\(toolCalls, turnContent, turn\.thinking/g)?.length).toBe(2)+ // CA K2: both loops run the one chain (lib/agent-core/recover.ts), which+ // ends with the reasoning step, and hand it the turn's thinking.+ expect(src('hooks/useAgentChat.ts')).toMatch(/recoverTurnCalls\(\{[\s\S]{0,120}thinking: turnThinking/)+ expect(src('hooks/useCodex.ts').match(/recoverTurnCalls\(\{ toolCalls, content: turnContent, thinking: turn\.thinking/g)?.length).toBe(2)+ expect(src('lib/agent-core/recover.ts')).toContain('toolCallsFromReasoning(')})})diff --git a/src/lib/agent-core/__tests__/recover.test.ts b/src/lib/agent-core/__tests__/recover.test.tsnew file mode 100644index 00000000..b3e920d9--- /dev/null+++ b/src/lib/agent-core/__tests__/recover.test.ts@@ -0,0 +1,87 @@+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'+import { recoverTurnCalls } from '../recover'++const tools = [+ { name: 'file_read', inputSchema: { properties: { path: {} }, required: ['path'] } },+ { name: 'file_write', inputSchema: { properties: { path: {}, content: {} }, required: ['path', 'content'] } },+ { name: 'shell_execute', inputSchema: { properties: { command: {} }, required: ['command'] } },+ { name: 'video_generate', inputSchema: { properties: { prompt: {} }, required: ['prompt'] } },+]++const names = (r: ReturnType<typeof recoverTurnCalls>) => r.toolCalls.map((c) => c.function.name)++describe('one recovery chain for every loop (CA K2)', () => {+ it('keeps native calls and repairs a near-miss name', () => {+ const r = recoverTurnCalls({+ toolCalls: [{ function: { name: 'video_generation', arguments: { prompt: 'a cat' } } }],+ content: '',+ tools,+ })+ expect(names(r)).toEqual(['video_generate'])+ expect(r.source).toBe('native')+ })++ it('resolves a generic "function" call from its arguments (GH #147)', () => {+ const r = recoverTurnCalls({+ toolCalls: [{ function: { name: 'function', arguments: { command: 'ls' } } }],+ content: '',+ tools,+ })+ expect(names(r)).toEqual(['shell_execute'])+ })++ it('lifts a fenced JSON call out of the answer and leaves the prose', () => {+ const content = 'I will read it now.\n```json\n{"name": "file_read", "arguments": {"path": "notes.txt"}}\n```'+ const r = recoverTurnCalls({ toolCalls: [], content, tools })+ expect(names(r)).toEqual(['file_read'])+ expect(r.source).toBe('content')+ expect(r.content).toContain('I will read it now.')+ expect(r.content).not.toContain('"name"')+ })++ it('lifts a prose call the Code tab used to miss', () => {+ const r = recoverTurnCalls({ toolCalls: [], content: 'file_read(path="src/math.ts")', tools })+ expect(names(r)).toEqual(['file_read'])+ expect(r.toolCalls[0].function.arguments).toEqual({ path: 'src/math.ts' })+ expect(r.source).toBe('content')+ })++ it('never runs example JSON that names an unknown tool', () => {+ const content = 'For example:\n```json\n{"name": "delete_everything", "arguments": {}}\n```'+ const r = recoverTurnCalls({ toolCalls: [], content, tools })+ expect(r.toolCalls).toEqual([])+ expect(r.source).toBe('none')+ })++ it('takes a call stuck in the reasoning channel only when the answer is empty', () => {+ const thinking = '<tool_call>{"name": "file_read", "arguments": {"path": "a.txt"}}</tool_call>'+ expect(names(recoverTurnCalls({ toolCalls: [], content: '', thinking, tools }))).toEqual(['file_read'])+ expect(recoverTurnCalls({ toolCalls: [], content: 'Done.', thinking, tools }).toolCalls).toEqual([])+ })++ it('accepts extra names such as tool_search in a compact run', () => {+ const thinking = '<tool_call>{"name": "tool_search", "arguments": {"query": "rename files"}}</tool_call>'+ const r = recoverTurnCalls({ toolCalls: [], content: '', thinking, tools, extraNames: ['tool_search'] })+ expect(names(r)).toEqual(['tool_search'])+ })++ it('cleans a JSON echo next to a native call', () => {+ const r = recoverTurnCalls({+ toolCalls: [{ id: 'a', function: { name: 'file_read', arguments: { path: 'x' } } }],+ content: 'Reading.\n{"name": "file_read", "arguments": {"path": "x"}}',+ tools,+ })+ expect(r.toolCalls).toHaveLength(1)+ expect(r.content).not.toContain('"name"')+ })++ it('is the one chain the Agent tab, the Code tab and the sub-agent run', () => {+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')+ expect(src('hooks/useAgentChat.ts')).toContain('recoverTurnCalls(')+ expect(src('hooks/useCodex.ts').match(/recoverTurnCalls\(/g)?.length).toBeGreaterThanOrEqual(3)+ expect(src('api/agents/sub-agent.ts')).toContain('recoverTurnCalls(')+ expect(src('hooks/useAgentChat.ts')).not.toContain('parseLooseToolCalls(')+ })+})diff --git a/src/lib/agent-core/recover.ts b/src/lib/agent-core/recover.tsnew file mode 100644index 00000000..2a4e4fd9--- /dev/null+++ b/src/lib/agent-core/recover.ts@@ -0,0 +1,117 @@+/**+ * One recovery chain for the calls of a model turn (CA K2).+ *+ * The Agent tab, the Code tab and the sub-agent each grew their own copy of+ * "where else could the calls be": the Agent tab lifted prose calls+ * (`file_read(path="a.ts")`) but not fenced JSON, the Code tab lifted fenced+ * JSON but not prose calls, and the sub-agent lifted nothing. A small local+ * model that writes its call the "other" way worked in one tab and stopped on+ * prose in the next. Every loop now runs this one function after its+ * transport produced (calls, content, thinking).+ *+ * The order is the safety property, and each step only runs while the turn+ * still has no call:+ * 1. native calls, names repaired (`video_generation` → `video_generate`,+ * a generic `function` resolved from its arguments; GH #147)+ * 2. fenced / bare JSON in the answer (qwen2.5-coder), known tools only+ * 3. prose calls `name(k="v")`, Hermes tags, `functions.x` (gemma, qwen 14B)+ * 4. calls stuck in the reasoning channel while the answer is empty+ * (llama.cpp #20809; C59 A3), structured forms only+ * Then the visible answer is cleaned of call text that is still in it. Every+ * lifted call must name a tool of this run: example JSON in an explanation is+ * never executed.+ */+import type { ToolCall } from '../../api/providers/types'+import { recoverKnownToolCallsFromContent } from '../../hooks/codex/tool-call-recovery'+import {+ parseLooseToolCalls,+ repairToolCall,+ stripMatchedCalls,+ stripToolCallText,+ toolCallsFromReasoning,+} from '../loose-tool-parse'++interface ToolShape {+ name: string+ inputSchema?: { properties?: Record<string, unknown>; required?: string[] }+}++export type RecoverySource = 'native' | 'content' | 'reasoning' | 'none'++export interface RecoverInput {+ toolCalls: ToolCall[]+ content: string+ thinking?: string+ /** The tools this run may call (names and schemas, for the name repair). */+ tools: readonly ToolShape[]+ /** Extra names a lifted call may carry that are not in `tools`+ * (e.g. `tool_search` in a compact run). */+ extraNames?: readonly string[]+}++export interface RecoverOutput {+ toolCalls: ToolCall[]+ content: string+ source: RecoverySource+}++function isRecord(v: unknown): v is Record<string, unknown> {+ return !!v && typeof v === 'object' && !Array.isArray(v)+}++export function recoverTurnCalls(input: RecoverInput): RecoverOutput {+ const tools = input.tools as ToolShape[]+ const known = [...tools.map((t) => t.name), ...(input.extraNames ?? [])]+ const isKnown = (name: string, args: Record<string, unknown>) =>+ known.includes(repairToolCall(name, args, tools).name) || known.includes(name)++ let toolCalls = input.toolCalls+ let content = input.content ?? ''+ let source: RecoverySource = toolCalls.length > 0 ? 'native' : 'none'++ // 1. Repair the names of native calls.+ if (toolCalls.length > 0) {+ toolCalls = toolCalls.map((tc) => {+ const raw = tc.function?.name ?? ''+ const args = isRecord(tc.function?.arguments) ? tc.function.arguments : {}+ const fixed = repairToolCall(raw, args, tools)+ return fixed.name === raw ? tc : { ...tc, function: { ...tc.function, name: fixed.name, arguments: fixed.arguments } }+ })+ }++ // 2. JSON in the answer (also strips a JSON echo next to native calls).+ if (content) {+ const recovered = recoverKnownToolCallsFromContent(toolCalls, content, isKnown)+ if (toolCalls.length === 0 && recovered.toolCalls.length > 0) source = 'content'+ toolCalls = recovered.toolCalls.map((tc) => {+ const args = isRecord(tc.function.arguments) ? tc.function.arguments : {}+ const fixed = repairToolCall(tc.function.name, args, tools)+ return fixed.name === tc.function.name ? tc : { ...tc, function: { ...tc.function, name: fixed.name, arguments: fixed.arguments } }+ })+ content = recovered.content+ }++ // 3. Prose calls.+ if (toolCalls.length === 0 && content.trim()) {+ const loose = parseLooseToolCalls(content, known)+ if (loose.calls.length > 0) {+ toolCalls = loose.calls.map((c) => ({ function: { name: c.name, arguments: c.arguments } }))+ content = stripMatchedCalls(content, loose.matched)+ source = 'content'+ }+ }++ // 4. Calls in the reasoning channel.+ if (toolCalls.length === 0) {+ const lifted = toolCallsFromReasoning(input.thinking ?? '', content, 0, known)+ if (lifted.length > 0) {+ toolCalls = lifted.map((c) => ({ function: { name: c.name, arguments: c.arguments } }))+ source = 'reasoning'+ }+ }++ // Clean call text the model echoed into its prose.+ if (content) content = stripToolCallText(content, known)++ return { toolCalls, content, source }+}diff --git a/src/lib/tool-call-repair.ts b/src/lib/tool-call-repair.tsindex 21b6b2b9..9457ea00 100644--- a/src/lib/tool-call-repair.ts+++ b/src/lib/tool-call-repair.ts@@ -438,7 +438,12 @@ export function extractToolCallsWithRanges(content: string): {if (argStr) {// Try to parse as JSONconst parsed = repairJson(`{${argStr}}`)+ const keyword = keywordArgs(argStr)if (isRecord(parsed)) args = parsed+ // `file_read(path="src/math.ts")`: Python-style keywords are no JSON,+ // and the fallback below used to turn the whole text into+ // {query: 'path="src/math.ts'} (CA K2, found by the shared chain's test).+ else if (keyword) args = keywordelse {// Simple single-argument: treat as the first required paramargs = { query: argStr.replace(/^["']|["']$/g, '') }@@ -451,6 +456,20 @@ export function extractToolCallsWithRanges(content: string): {return { calls, ranges }}+/** `key="v", n=3, ok=true` → object, or null when the text has no keyword. */+function keywordArgs(text: string): Record<string, unknown> | null {+ const kw = /([A-Za-z_]\w*)\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|true|false|null|-?\d+(?:\.\d+)?)/g+ const out: Record<string, unknown> = {}+ let m: RegExpExecArray | null+ while ((m = kw.exec(text)) !== null) {+ const v = m[2]+ out[m[1]] = v === 'true' ? true : v === 'false' ? false : v === 'null' ? null+ : /^-?\d/.test(v) ? Number(v)+ : v.slice(1, -1).replace(/\\(["'\\])/g, '$1')+ }+ return Object.keys(out).length > 0 ? out : null+}+/*** Scan backwards from `fromIdx` and return the index of the nearest* preceding `{` that is NOT inside a string. Returns -1 if none found.