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
tech(M-any): Provider-Schicht typisieren — 182 `any` raus, 7 echte Fehler mit
David0e740f60c6bf
diff --git a/src/api/__tests__/local-op-workflows.test.ts b/src/api/__tests__/local-op-workflows.test.tsindex ebb98480..bc8c5564 100644--- a/src/api/__tests__/local-op-workflows.test.ts+++ b/src/api/__tests__/local-op-workflows.test.ts@@ -13,7 +13,46 @@ import {} from '../dynamic-workflow'import { classifyModel, galleryTypeForFile, resolveLocalOpPick, type ClassifiedModel } from '../comfyui'-const FULL_NODES: Record<string, any> = Object.fromEntries(+/**+ * One node of a ComfyUI prompt graph, the way the builders under test emit it.+ * The builders are still declared `Record<string, any>` (dynamic-workflow.ts+ * is another agent's file this round), so the shape is pinned HERE: every+ * assertion below now reads a checked field instead of an `any` that would+ * have swallowed a renamed key as `undefined === undefined`.+ */+interface ComfyNode {+ class_type: string+ inputs: Record<string, unknown>+}+type ComfyGraph = Record<string, ComfyNode>++/** The node of this class_type — fails loudly when the graph has none. */+function nodeOfType(wf: ComfyGraph, classType: string): ComfyNode {+ const node = Object.values(wf).find(n => n.class_type === classType)+ if (!node) throw new Error(`graph has no ${classType} node`)+ return node+}++/** A numeric input, checked rather than assumed. */+function numInput(node: ComfyNode, key: string): number {+ const v = node.inputs[key]+ if (typeof v !== 'number') {+ throw new Error(`${node.class_type}.inputs.${key} is not a number: ${String(v)}`)+ }+ return v+}++/** An array input (a ComfyUI link `[nodeId, slot]`, or a literal list). */+function arrInput(node: ComfyNode, key: string): unknown[] {+ const v = node.inputs[key]+ if (!Array.isArray(v)) {+ throw new Error(`${node.class_type}.inputs.${key} is not an array: ${String(v)}`)+ }+ return v+}++/** The presence map getAllNodeInfo() feeds the builders — keys only. */+const FULL_NODES: Record<string, object> = Object.fromEntries(['TextEncodeAceStepAudio', 'EmptyAceStepLatentAudio','TextEncodeAceStepAudio1.5', 'EmptyAceStep1.5LatentAudio',@@ -33,7 +72,7 @@ const nodesWithout = (...names: string[]) => {return copy}-const classTypes = (wf: Record<string, any>) => Object.values(wf).map((n: any) => n.class_type)+const classTypes = (wf: ComfyGraph) => Object.values(wf).map(n => n.class_type)const baseParams = (over: Partial<LocalOpParams>): LocalOpParams => ({op: 'music',@@ -90,21 +129,19 @@ describe('resolveLocalOpPick', () => {describe('buildMusicWorkflow', () => {it('builds the v1 ACE graph (checkpoint, encode, latent, mp3 save)', () => {- const wf = buildMusicWorkflow(baseParams({ seconds: 45, lyrics: 'la la' }), 7, FULL_NODES)+ const wf: ComfyGraph = buildMusicWorkflow(baseParams({ seconds: 45, lyrics: 'la la' }), 7, FULL_NODES)const types = classTypes(wf)expect(types).toContain('CheckpointLoaderSimple')expect(types).toContain('TextEncodeAceStepAudio')expect(types).toContain('EmptyAceStepLatentAudio')expect(types).toContain('VAEDecodeAudio')expect(types).toContain('SaveAudioMP3')- const latent = Object.values(wf).find((n: any) => n.class_type === 'EmptyAceStepLatentAudio') as any- expect(latent.inputs.seconds).toBe(45)- const enc = Object.values(wf).find((n: any) => n.class_type === 'TextEncodeAceStepAudio') as any- expect(enc.inputs.lyrics).toBe('la la')+ expect(nodeOfType(wf, 'EmptyAceStepLatentAudio').inputs.seconds).toBe(45)+ expect(nodeOfType(wf, 'TextEncodeAceStepAudio').inputs.lyrics).toBe('la la')})it('routes ACE 1.5 checkpoints through the 1.5 node pair with a zeroed negative', () => {- const wf = buildMusicWorkflow(+ const wf: ComfyGraph = buildMusicWorkflow(baseParams({ model: 'ace_step_1.5_turbo_aio.safetensors', seconds: 60 }), 7, FULL_NODES)const types = classTypes(wf)expect(types).toContain('TextEncodeAceStepAudio1.5')@@ -134,20 +171,19 @@ describe('buildS2VWorkflow', () => {})it('wires audio embeddings into the S2V conditioner and muxes the voice into the mp4', () => {- const wf = buildS2VWorkflow(s2v(), 7, FULL_NODES)+ const wf: ComfyGraph = buildS2VWorkflow(s2v(), 7, FULL_NODES)const types = classTypes(wf)for (const t of ['LoadAudio', 'AudioEncoderLoader', 'AudioEncoderEncode', 'WanSoundImageToVideo', 'CreateVideo', 'SaveVideo']) {expect(types).toContain(t)}- const create = Object.values(wf).find((n: any) => n.class_type === 'CreateVideo') as any- expect(create.inputs.audio).toBeTruthy()- const s2vNode = Object.values(wf).find((n: any) => n.class_type === 'WanSoundImageToVideo') as any+ expect(nodeOfType(wf, 'CreateVideo').inputs.audio).toBeTruthy()+ const s2vNode = nodeOfType(wf, 'WanSoundImageToVideo')// length stays on the 4k+1 grid- expect((s2vNode.inputs.length - 1) % 4).toBe(0)+ expect((numInput(s2vNode, 'length') - 1) % 4).toBe(0)})it('loads .gguf quants through the GGUF pack and hints its install when missing', () => {- const wf = buildS2VWorkflow(s2v({ model: 'Wan2.2-S2V-14B-Q4_K_M.gguf' }), 7, FULL_NODES)+ const wf: ComfyGraph = buildS2VWorkflow(s2v({ model: 'Wan2.2-S2V-14B-Q4_K_M.gguf' }), 7, FULL_NODES)expect(classTypes(wf)).toContain('UnetLoaderGGUF')try {buildS2VWorkflow(s2v({ model: 'Wan2.2-S2V-14B-Q4_K_M.gguf' }), 7, nodesWithout('UnetLoaderGGUF'))@@ -174,21 +210,20 @@ describe('buildMotionWorkflow', () => {})it('builds the Animate graph: DWPose skeleton in, trimmed latent out, driving audio carried over', () => {- const wf = buildMotionWorkflow(motion(), 7, FULL_NODES)+ const wf: ComfyGraph = buildMotionWorkflow(motion(), 7, FULL_NODES)const types = classTypes(wf)for (const t of ['LoadVideo', 'GetVideoComponents', 'DWPreprocessor', 'WanAnimateToVideo', 'TrimVideoLatent', 'CreateVideo']) {expect(types).toContain(t)}- const trim = Object.values(wf).find((n: any) => n.class_type === 'TrimVideoLatent') as any+ const trim = nodeOfType(wf, 'TrimVideoLatent')expect(Array.isArray(trim.inputs.trim_amount)).toBe(true)- expect(trim.inputs.trim_amount[1]).toBe(3)- const create = Object.values(wf).find((n: any) => n.class_type === 'CreateVideo') as any- const components = Object.entries(wf).find(([, n]: [string, any]) => n.class_type === 'GetVideoComponents')![0]- expect(create.inputs.audio).toEqual([components, 1])+ expect(arrInput(trim, 'trim_amount')[1]).toBe(3)+ const components = Object.entries(wf).find(([, n]) => n.class_type === 'GetVideoComponents')![0]+ expect(nodeOfType(wf, 'CreateVideo').inputs.audio).toEqual([components, 1])})it('routes VACE models through WanVaceToVideo with the skeleton as control video', () => {- const wf = buildMotionWorkflow(motion({ model: 'wan2.1_vace_1.3B_fp16.safetensors' }), 7, FULL_NODES)+ const wf: ComfyGraph = buildMotionWorkflow(motion({ model: 'wan2.1_vace_1.3B_fp16.safetensors' }), 7, FULL_NODES)const types = classTypes(wf)expect(types).toContain('WanVaceToVideo')expect(types).not.toContain('WanAnimateToVideo')diff --git a/src/api/__tests__/provider-openai.test.ts b/src/api/__tests__/provider-openai.test.tsindex 7d03b7be..d3111e6f 100644--- a/src/api/__tests__/provider-openai.test.ts+++ b/src/api/__tests__/provider-openai.test.ts@@ -7,7 +7,9 @@import { describe, it, expect, vi, beforeEach } from 'vitest'import { OpenAIProvider } from '../providers/openai-provider'import { ProviderError } from '../providers/types'-import type { ProviderConfig, ToolDefinition } from '../providers/types'+import type { ProviderConfig, ToolDefinition, ChatMessage, ChatOptions } from '../providers/types'+import type { OpenAIChatRequest } from '../providers/openai-provider'+import { sentJson, asProviderError, stubBrowserWindow, type FetchArgs } from './provider-test-support'function makeConfig(overrides: Partial<ProviderConfig> = {}): ProviderConfig {return {@@ -76,9 +78,7 @@ describe('OpenAIProvider', () => {// durchgreifen kann (dann mockable via globalThis.fetch).describe('Bug K — probeContextFromServer (LM Studio Enhanced API)', () => {beforeEach(() => {- if (typeof (globalThis as any).window === 'undefined') {- (globalThis as any).window = {}- }+ stubBrowserWindow()})afterEach(() => {vi.restoreAllMocks()@@ -93,7 +93,7 @@ describe('OpenAIProvider', () => {// Modell-Name darf KEIN Match in guessContextFromName ausloesen, damit// wir bewiesen kriegen dass der Probe-Pfad lief (sonst koennte 131072// auch aus der Heuristik kommen).- vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: any) => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: FetchArgs[0]) => {const u = url.toString()if (u.includes('/api/v0/models/custom-undocumented-model')) {return new Response(JSON.stringify({@@ -114,7 +114,7 @@ describe('OpenAIProvider', () => {isLocal: true,}))// vLLM exposes max_model_len, not max_context_length- vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: any) => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: FetchArgs[0]) => {const u = url.toString()if (u.includes('/api/v0/models/')) {return new Response('', { status: 404 })@@ -135,7 +135,7 @@ describe('OpenAIProvider', () => {baseUrl: 'http://localhost:8080/v1',isLocal: true,}))- vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: any) => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: FetchArgs[0]) => {const u = url.toString()if (u.includes('/api/v0/models/')) return new Response('', { status: 404 })if (u.includes('/v1/models/llama-server-model')) {@@ -175,7 +175,7 @@ describe('OpenAIProvider', () => {baseUrl: 'http://localhost:1234/v1',isLocal: true,}))- vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: any) => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url: FetchArgs[0]) => {const u = url.toString()if (u.endsWith('/v1/models')) {return new Response(JSON.stringify({@@ -204,7 +204,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e).toBeInstanceOf(ProviderError)expect(e.code).toBe('auth')}@@ -219,7 +220,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e).toBeInstanceOf(ProviderError)expect(e.code).toBe('rate_limit')expect(e.provider).toBe('openai')@@ -235,7 +237,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e).toBeInstanceOf(ProviderError)expect(e.code).toBe('not_found')}@@ -266,7 +269,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e).toBeInstanceOf(ProviderError)expect(e.code).toBe('lmstudio_runtime_missing')expect(e.message).toMatch(/runtime/i)@@ -289,7 +293,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('lmstudio_runtime_missing')}vi.restoreAllMocks()@@ -306,7 +311,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).not.toBe('lmstudio_runtime_missing')expect(e.message).toBe('Bad request: missing model')}@@ -418,7 +424,7 @@ describe('OpenAIProvider', () => {)// gpt-4o context = 128000; an absurd budget must be clamped into the window.await provider.chatWithTools('gpt-4o', [{ role: 'user', content: 'hi' }], [], { maxTokens: 999999 })- const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)+ const sent = sentJson<OpenAIChatRequest>(fetchSpy.mock.calls)expect(sent.max_tokens).toBeGreaterThan(0)expect(sent.max_tokens).toBeLessThanOrEqual(128000)vi.restoreAllMocks()@@ -434,7 +440,7 @@ describe('OpenAIProvider', () => {// No options → previously omitted max_tokens, so DeepInfra over-defaulted the// completion and 400'd. Now it must send a positive, in-window budget.await provider.chatWithTools('gpt-4o', [{ role: 'user', content: 'hi' }], [])- const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)+ const sent = sentJson<OpenAIChatRequest>(fetchSpy.mock.calls)expect(sent.max_tokens).toBeGreaterThan(0)expect(sent.max_tokens).toBeLessThanOrEqual(128000)vi.restoreAllMocks()@@ -455,8 +461,8 @@ describe('OpenAIProvider', () => {async function maxTokensFor(model: string,- messages: any[],- options?: any,+ messages: ChatMessage[],+ options?: ChatOptions,): Promise<number> {const provider = new OpenAIProvider(makeConfig())const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(@@ -465,9 +471,9 @@ describe('OpenAIProvider', () => {}), { status: 200 }))await provider.chatWithTools(model, messages, [], options)- const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)+ const sent = sentJson<OpenAIChatRequest>(fetchSpy.mock.calls)vi.restoreAllMocks()- return sent.max_tokens+ return sent.max_tokens ?? 0}it('does not starve max_tokens to the 256 floor because of an image (CS-1)', async () => {@@ -519,7 +525,7 @@ describe('OpenAIProvider', () => {it('still sends the full base64 image on the wire and does not mutate the messages (CS-1)', async () => {const provider = new OpenAIProvider(makeConfig())const data = base64Payload(20)- const messages: any[] = [{+ const messages: ChatMessage[] = [{role: 'user',content: 'look',images: [{ data, mimeType: 'image/png' }],@@ -530,11 +536,15 @@ describe('OpenAIProvider', () => {}), { status: 200 }))await provider.chatWithTools('mixtral-8x7b-32768', messages, [])- const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)- const part = sent.messages.at(-1).content.find((p: any) => p.type === 'image_url')- expect(part.image_url.url).toBe(`data:image/png;base64,${data}`)+ const sent = sentJson<OpenAIChatRequest>(fetchSpy.mock.calls)+ const lastContent = sent.messages.at(-1)?.content+ // A message with images must be sent as a content-part array, never a+ // bare string — asserting that is the point of the test.+ if (!Array.isArray(lastContent)) throw new Error('expected content parts')+ const part = lastContent.find(p => p.type === 'image_url')+ expect(part?.image_url?.url).toBe(`data:image/png;base64,${data}`)// The estimator must be read-only.- expect(messages[0].images[0].data).toBe(data)+ expect(messages[0].images?.[0].data).toBe(data)vi.restoreAllMocks()})@@ -606,7 +616,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('auth')expect(e.message).toBe('LU Cloud is in closed beta (Max plan only)')}@@ -621,7 +632,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('rate_limit')expect(e.message).toBe('monthly credit budget exhausted')}@@ -634,7 +646,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('auth')expect(e.message).toMatch(/Invalid API key/)}@@ -642,7 +655,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('rate_limit')expect(e.message).toMatch(/Rate limited/)}@@ -764,7 +778,8 @@ describe('OpenAIProvider', () => {try {await provider.chatWithTools('some-model', [{ role: 'user', content: 'hi' }], toolDef)expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e).toBeInstanceOf(ProviderError)expect(e.code).toBe('tools_unsupported')expect(e.message).toMatch(/tool/i)@@ -780,7 +795,8 @@ describe('OpenAIProvider', () => {try {await provider.chatWithTools('some-model', [{ role: 'user', content: 'hi' }], toolDef)expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('tools_unsupported')expect(e.message).toMatch(/Function calling is not supported/)}@@ -793,7 +809,8 @@ describe('OpenAIProvider', () => {try {await provider.listModels()expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).not.toBe('tools_unsupported')}vi.restoreAllMocks()@@ -807,7 +824,8 @@ describe('OpenAIProvider', () => {try {await provider.chatWithTools('some-model', [{ role: 'user', content: 'hi' }], toolDef)expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).not.toBe('tools_unsupported')}vi.restoreAllMocks()@@ -829,7 +847,8 @@ describe('OpenAIProvider', () => {try {await provider.chatWithTools('hermes-3-70b', [{ role: 'user', content: 'hi' }], toolDef)expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('tools_unsupported')expect(e.message).toMatch(/can't run tools/)}@@ -848,7 +867,8 @@ describe('OpenAIProvider', () => {try {await provider.chatWithTools('mythomax-l2-13b', [{ role: 'user', content: 'hi' }], toolDef)expect.fail('Should have thrown')- } catch (e: any) {+ } catch (thrown) {+ const e = asProviderError(thrown)expect(e.code).toBe('vision_unsupported')expect(e.message).toMatch(/can't read images/)}diff --git a/src/api/__tests__/provider-test-support.ts b/src/api/__tests__/provider-test-support.tsnew file mode 100644index 00000000..911fd62e--- /dev/null+++ b/src/api/__tests__/provider-test-support.ts@@ -0,0 +1,89 @@+/**+ * Shared typing helpers for the provider tests.+ *+ * Not a test file — the vitest include glob only matches names ending in+ * `.test.ts` — just the three moves every provider test used to make with `any`:+ *+ * 1. reading back the request body a fetch spy captured,+ * 2. narrowing a caught error before asserting on its fields,+ * 3. giving backend.ts's `isTauri()` a `window` to look at under node.+ *+ * The point of (1) is that the caller names the PRODUCTION request type+ * (`OpenAIChatRequest`, `MessagesBody`, `OllamaChatRequest`). A fixture read+ * as `any` notices nothing when a provider renames a field; read as the+ * exported request interface, the assertion stops compiling.+ */++import { ProviderError } from '../providers/types'+import { isRecord } from '../providers/wire'++/** One recorded `fetch` call: `[input, init?]`, whatever the mock lib names them. */+type RecordedCall = readonly unknown[]++/**+ * The JSON body of a captured fetch call, typed as the request interface the+ * production code builds. Throws (failing the test loudly) when that call was+ * never made or carried no string body — the two ways an `as any` read used to+ * turn into a confusing `undefined` further down the assertion.+ */+export function sentJson<T>(calls: readonly RecordedCall[], call = 0): T {+ const init = calls[call]?.[1]+ const body = isRecord(init) ? init.body : undefined+ if (typeof body !== 'string') {+ throw new Error(+ `expected fetch call #${call} to carry a JSON string body, ` ++ `got ${calls.length} call(s) and body of type ${typeof body}`,+ )+ }+ return JSON.parse(body) as T+}++/** How many calls the spy recorded — for the `.length` assertions. */+export function callUrl(calls: readonly RecordedCall[], call = 0): string {+ const input = calls[call]?.[0]+ return typeof input === 'string' ? input : String(input)+}++/**+ * Narrow a caught value to ProviderError with a real `instanceof` check, so+ * `err.code` / `err.status` are read off a checked type instead of `any`.+ * A non-ProviderError throw fails the test here rather than silently+ * satisfying an `expect(e.code).toBe(undefined)`.+ */+export function asProviderError(e: unknown): ProviderError {+ if (!(e instanceof ProviderError)) {+ throw new Error(`expected a ProviderError, got: ${describeThrown(e)}`)+ }+ return e+}++/** Same, for the paths that throw a plain Error. */+export function asError(e: unknown): Error {+ if (!(e instanceof Error)) {+ throw new Error(`expected an Error, got: ${describeThrown(e)}`)+ }+ return e+}++function describeThrown(e: unknown): string {+ if (e instanceof Error) return `${e.name}: ${e.message}`+ return typeof e === 'object' ? JSON.stringify(e) : String(e)+}++/**+ * backend.ts's `isTauri()` probes `window.__TAURI_INTERNALS__`. Under the node+ * test environment there is no `window` at all, so the probe throws instead of+ * returning false and the provider never reaches the mockable `globalThis.fetch`.+ * An empty object is enough to make it answer "not Tauri".+ */+export function stubBrowserWindow(): void {+ // Reflect, not a cast: the DOM lib types `globalThis.window` as a full+ // `Window`, so any direct assignment needs an `as any` to get an empty+ // object past it — which is exactly the escape hatch this file removes.+ if (typeof Reflect.get(globalThis, 'window') === 'undefined') {+ Reflect.set(globalThis, 'window', {})+ }+}++/** The argument list `globalThis.fetch` is called with, for mock signatures. */+export type FetchArgs = Parameters<typeof fetch>diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex b47b4b92..08dba970 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -1,12 +1,36 @@import type { OllamaModel, PullProgress } from "../types/models"+import type { ToolCall, ToolDefinition } from "./providers/types"import { ollamaUrl, localFetch, localFetchStream, isTauri } from "./backend"+import type { OllamaWireToolCall } from "./providers/wire"+import { isRecord, prop, asString, asStringArray, asRecordArray } from "./providers/wire"import { log } from "../lib/logger"+/**+ * One entry of Ollama's `/api/tags` response.+ *+ * The identity fields mirror `OllamaModel` because the mapper below spreads+ * the entry straight through, exactly as it always has — this type documents+ * that spread instead of hiding it behind `any`. `capabilities` is the one+ * field we do NOT trust: it only appeared in newer Ollama builds, so it stays+ * `unknown` and is checked with `Array.isArray` before it is read.+ */+type OllamaTagsEntry = Omit<+ OllamaModel,+ 'type' | 'provider' | 'providerName' | 'contextLength' | 'supportsTools'+> & { capabilities?: unknown }+export async function listModels(): Promise<OllamaModel[]> {const res = await localFetch(ollamaUrl("/tags"))if (!res.ok) throw new Error("Failed to fetch models")- const data = await res.json()- return (data.models || []).map((m: any) => ({+ const data: unknown = await res.json()+ // Boundary check: `models` must be an array before anything iterates it.+ // A body that is not shaped that way yields an empty list, which is what+ // the old `data.models || []` did for a missing field.+ const rawModels = prop(data, 'models')+ const entries: OllamaTagsEntry[] = Array.isArray(rawModels)+ ? (rawModels as OllamaTagsEntry[])+ : []+ return entries.map((m) => ({...m,type: "text" as const,// /api/tags states this per model. Without the mapping the field arrives as@@ -28,13 +52,20 @@ export async function listModels(): Promise<OllamaModel[]> {}))}-export async function showModel(name: string) {+/**+ * Raw `/api/show` metadata. Ollama's payload differs per architecture+ * (`llama.context_length` vs `gemma2.context_length` vs …), so there is no+ * fixed shape to promise — a checked record is the honest return type, and+ * every reader below probes it field by field.+ */+export async function showModel(name: string): Promise<Record<string, unknown>> {const res = await localFetch(ollamaUrl("/show"), {method: "POST",body: JSON.stringify({ name }),})if (!res.ok) throw new Error("Failed to show model")- return res.json()+ const body: unknown = await res.json()+ return isRecord(body) ? body : {}}export async function getModelContext(name: string): Promise<number> {@@ -42,7 +73,7 @@ export async function getModelContext(name: string): Promise<number> {const info = await showModel(name)// Try model_info fields (various architectures use different keys)- const modelInfo = info?.model_info || {}+ const modelInfo: Record<string, unknown> = isRecord(info.model_info) ? info.model_info : {}const contextFromInfo =modelInfo["general.context_length"] ||// Architecture-specific keys (gemma2.context_length, llama.context_length, etc.)@@ -53,9 +84,9 @@ export async function getModelContext(name: string): Promise<number> {}// Try parameters (can be a string like "num_ctx 8192" or an object)- const params = info?.parameters+ const params: unknown = info.parametersif (params) {- if (typeof params === 'object' && params.num_ctx) {+ if (isRecord(params) && params.num_ctx) {return Number(params.num_ctx)}if (typeof params === 'string') {@@ -130,8 +161,8 @@ export async function chatStream(// Agent Mode: chat with tool calling supportexport async function chatStreamWithTools(model: string,- messages: { role: string; content: string; tool_calls?: any[] }[],- tools: { type: string; function: { name: string; description: string; parameters: any } }[],+ messages: { role: string; content: string; tool_calls?: ToolCall[] }[],+ tools: ToolDefinition[],options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},signal?: AbortSignal): Promise<Response> {@@ -159,10 +190,10 @@ export async function chatStreamWithTools(// Agent Mode: non-streaming tool call (more reliable for detecting tool calls)export async function chatWithTools(model: string,- messages: { role: string; content: string; tool_calls?: any[] }[],- tools: { type: string; function: { name: string; description: string; parameters: any } }[],+ messages: { role: string; content: string; tool_calls?: ToolCall[] }[],+ tools: ToolDefinition[],options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},-): Promise<{ content: string; tool_calls?: any[] }> {+): Promise<{ content: string; tool_calls?: OllamaWireToolCall[] }> {// v2.4.6 Bug L: see chatStream() above — same num_gpu:99 removal.const res = await localFetch(ollamaUrl("/chat"), {method: "POST",@@ -178,10 +209,15 @@ export async function chatWithTools(throw new Error("Failed to start agent chat")}}- const data = await res.json()+ const data: unknown = await res.json()+ // Foreign body: read `message.content` / `message.tool_calls` through the+ // boundary helpers rather than trusting the optional-chain to have found+ // the shape it was written for.+ const message = prop(data, 'message')+ const toolCalls = prop(message, 'tool_calls')return {- content: data.message?.content || '',- tool_calls: data.message?.tool_calls,+ content: asString(prop(message, 'content')) || '',+ tool_calls: Array.isArray(toolCalls) ? (toolCalls as OllamaWireToolCall[]) : undefined,}}@@ -250,8 +286,10 @@ export async function listRunningModels(): Promise<string[]> {try {const res = await localFetch(ollamaUrl("/ps"))if (!res.ok) return []- const data = await res.json()- return (data.models || []).map((m: any) => m.name || m.model)+ const data: unknown = await res.json()+ return asRecordArray(prop(data, 'models'))+ .map((m) => asString(m.name) || asString(m.model))+ .filter((n): n is string => !!n)} catch {return []}@@ -277,8 +315,8 @@ export async function getModelCapabilities(model: string): Promise<string[]> {timeoutMs: 8000,})if (!res.ok) { _capCache.set(model, []); return [] }- const data = await res.json()- const caps: string[] = Array.isArray(data?.capabilities) ? data.capabilities : []+ const data: unknown = await res.json()+ const caps: string[] = asStringArray(prop(data, 'capabilities'))_capCache.set(model, caps)return caps} catch {diff --git a/src/api/providers/__tests__/anthropic-cache-control.test.ts b/src/api/providers/__tests__/anthropic-cache-control.test.tsindex a53b3ad6..620bc1e4 100644--- a/src/api/providers/__tests__/anthropic-cache-control.test.ts+++ b/src/api/providers/__tests__/anthropic-cache-control.test.ts@@ -12,6 +12,11 @@import { describe, it, expect, vi, afterEach } from 'vitest'import { AnthropicProvider } from '../anthropic-provider'import type { ChatMessage, ChatStreamChunk, ProviderConfig, ToolDefinition } from '../types'+import type {+ MessagesBody, AnthropicRequestMessage, AnthropicRequestBlock,+ AnthropicTextBlock, AnthropicToolSpec,+} from '../anthropic-provider'+import type { FetchArgs } from '../../__tests__/provider-test-support'const EPHEMERAL = { type: 'ephemeral' }@@ -34,7 +39,7 @@ function tool(name: string): ToolDefinition {}/** Every JSON path in the body that carries a cache_control marker. */-function markerPaths(value: any, path = '$'): string[] {+function markerPaths(value: unknown, path = '$'): string[] {if (Array.isArray(value)) {return value.flatMap((v, i) => markerPaths(v, `${path}[${i}]`))}@@ -52,24 +57,68 @@ function markerPaths(value: any, path = '$'): string[] {/** Non-streaming path (chatWithTools): capture every request body sent. */function captureJson() {- const bodies: any[] = []+ // Typed as the provider's own request interface: a renamed field in+ // MessagesBody breaks the assertions below instead of reading `undefined`.+ const bodies: MessagesBody[] = []const headers: Record<string, string>[] = []- vi.stubGlobal('fetch', vi.fn(async (_url: any, init: any) => {- bodies.push(JSON.parse(init.body))- headers.push(init.headers)- return {- ok: true,- json: async () => ({ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 9, output_tokens: 2 } }),- } as any+ vi.stubGlobal('fetch', vi.fn(async (_url: FetchArgs[0], init: FetchArgs[1]) => {+ bodies.push(capturedBody(init))+ headers.push(capturedHeaders(init))+ return new Response(+ JSON.stringify({ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 9, output_tokens: 2 } }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ )}))return { bodies, headers }}+/** The JSON body of a captured fetch init, as the provider's request type. */+function capturedBody(init: FetchArgs[1]): MessagesBody {+ const body = init?.body+ if (typeof body !== 'string') throw new Error('capture had no JSON body')+ return JSON.parse(body) as MessagesBody+}++/**+ * The block array of a wire message. A cache marker can only ride on a block,+ * so a message still carrying a bare string means the promotion in+ * applyCacheControl did not happen — a failure, not something to skip past.+ */+function blocksOf(msg: AnthropicRequestMessage): AnthropicRequestBlock[] {+ if (typeof msg.content === 'string') {+ throw new Error(`message content was never promoted to blocks: ${msg.content}`)+ }+ return msg.content+}++/** Same for the system parameter, which starts life as a plain string. */+function systemBlocks(body: MessagesBody): AnthropicTextBlock[] {+ if (typeof body.system !== 'object') {+ throw new Error(`system was never promoted to blocks: ${String(body.system)}`)+ }+ return body.system+}++/** The tool specs of a request that is supposed to carry some. */+function toolsOf(body: MessagesBody): AnthropicToolSpec[] {+ if (!body.tools) throw new Error('request carried no tools')+ return body.tools+}++/** The plain-object headers this provider always sends. */+function capturedHeaders(init: FetchArgs[1]): Record<string, string> {+ const h = init?.headers+ if (!h || typeof h !== 'object' || Array.isArray(h) || h instanceof Headers) {+ throw new Error('expected a plain headers object')+ }+ return h as Record<string, string>+}+/** Streaming path (chatStream): capture bodies, answer with a minimal SSE turn. */function captureSse() {- const bodies: any[] = []- vi.stubGlobal('fetch', vi.fn(async (_url: any, init: any) => {- bodies.push(JSON.parse(init.body))+ const bodies: MessagesBody[] = []+ vi.stubGlobal('fetch', vi.fn(async (_url: FetchArgs[0], init: FetchArgs[1]) => {+ bodies.push(capturedBody(init))return new Response(['data: {"type":"message_start","message":{"id":"m1","usage":{"input_tokens":9,"output_tokens":1}}}\n\n',@@ -113,9 +162,10 @@ describe('A8 cache_control placement', () => {])// 2. LAST tool definition onlyexpect(body.tools).toHaveLength(2)- expect(body.tools[0].cache_control).toBeUndefined()- expect(body.tools[1].name).toBe('write')- expect(body.tools[1].cache_control).toEqual(EPHEMERAL)+ const tools = toolsOf(body)+ expect(tools[0].cache_control).toBeUndefined()+ expect(tools[1].name).toBe('write')+ expect(tools[1].cache_control).toEqual(EPHEMERAL)// 3. last stable message = the previous round's assistant turnexpect(body.messages).toHaveLength(3)expect(body.messages[1].role).toBe('assistant')@@ -143,9 +193,9 @@ describe('A8 cache_control placement', () => {const body = bodies[0]expect(body.stream).toBe(true)- expect(body.system[0].cache_control).toEqual(EPHEMERAL)- expect(body.tools[1].cache_control).toEqual(EPHEMERAL)- expect(body.messages[1].content[0].cache_control).toEqual(EPHEMERAL)+ expect(systemBlocks(body)[0].cache_control).toEqual(EPHEMERAL)+ expect(toolsOf(body)[1].cache_control).toEqual(EPHEMERAL)+ expect(blocksOf(body.messages[1])[0].cache_control).toEqual(EPHEMERAL)expect(markerPaths(body)).toHaveLength(3)})@@ -171,9 +221,18 @@ describe('A8 cache_control placement', () => {await provider.chatWithTools('claude-haiku-4-5-20251001', conversation(rounds), [tool('read')])}- const marked = bodies.map((b: any) => {+ const marked = bodies.map(b => {const i = b.messages.length - 2- return { index: i, total: b.messages.length, text: b.messages[i].content[0].text }+ const content = b.messages[i].content+ // The marked history turn must have been promoted to a block array —+ // that promotion is what gives the marker something to ride on.+ if (!Array.isArray(content)) throw new Error('history turn was not promoted to blocks')+ const first = content[0]+ return {+ index: i,+ total: b.messages.length,+ text: first.type === 'text' ? first.text : undefined,+ }})// rounds=1 -> 3 wire messages, rounds=2 -> 5, and so on: always index n-2,@@ -241,12 +300,12 @@ describe('A8 cache_control placement', () => {const body = bodies[0]// The vision turn really is a block array, and no image block was stamped.- expect(body.messages[0].content[0].type).toBe('image')+ expect(blocksOf(body.messages[0])[0].type).toBe('image')expect(markerPaths(body)).toHaveLength(3)for (const path of markerPaths(body)) {expect(path).not.toMatch(/messages\[0\]/)}- expect(body.messages[1].content[0].cache_control).toEqual(EPHEMERAL)+ expect(blocksOf(body.messages[1])[0].cache_control).toEqual(EPHEMERAL)})it('the agent tool path marks the settled tool_use turn, not the fresh tool results', async () => {@@ -273,10 +332,11 @@ describe('A8 cache_control placement', () => {expect(body.messages).toHaveLength(3)const stable = body.messages[1]expect(stable.role).toBe('assistant')- expect(stable.content[stable.content.length - 1].type).toBe('tool_use')- expect(stable.content[stable.content.length - 1].cache_control).toEqual(EPHEMERAL)+ const stableBlocks = blocksOf(stable)+ expect(stableBlocks[stableBlocks.length - 1].type).toBe('tool_use')+ expect(stableBlocks[stableBlocks.length - 1].cache_control).toEqual(EPHEMERAL)// The just-arrived tool results are the volatile tail, so no marker.- for (const block of body.messages[2].content) {+ for (const block of blocksOf(body.messages[2])) {expect(block.cache_control).toBeUndefined()}expect(markerPaths(body)).toHaveLength(3)diff --git a/src/api/providers/__tests__/anthropic-convert.test.ts b/src/api/providers/__tests__/anthropic-convert.test.tsindex c9d54a7b..44b35a6e 100644--- a/src/api/providers/__tests__/anthropic-convert.test.ts+++ b/src/api/providers/__tests__/anthropic-convert.test.ts@@ -8,19 +8,25 @@import { describe, it, expect, vi, afterEach } from 'vitest'import { AnthropicProvider } from '../anthropic-provider'import type { ChatMessage } from '../types'+import type { MessagesBody, AnthropicRequestBlock } from '../anthropic-provider'+import type { FetchArgs } from '../../__tests__/provider-test-support'function providerWithCapturedBody() {const provider = new AnthropicProvider({id: 'anthropic', name: 'Anthropic', enabled: true,baseUrl: 'https://api.anthropic.com', apiKey: 'sk-test', isLocal: false,})- const bodies: any[] = []- vi.stubGlobal('fetch', vi.fn(async (_url: any, init: any) => {- bodies.push(JSON.parse(init.body))- return {- ok: true,- json: async () => ({ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 12, output_tokens: 3 } }),- } as any+ // Typed as the provider's own request interface, so a renamed field in+ // MessagesBody breaks this test instead of silently reading `undefined`.+ const bodies: MessagesBody[] = []+ vi.stubGlobal('fetch', vi.fn(async (_url: FetchArgs[0], init: FetchArgs[1]) => {+ const body = init?.body+ if (typeof body !== 'string') throw new Error('capture had no JSON body')+ bodies.push(JSON.parse(body) as MessagesBody)+ return new Response(+ JSON.stringify({ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 12, output_tokens: 3 } }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ )}))return { provider, bodies }}@@ -49,7 +55,9 @@ describe('AnthropicProvider message conversion (audit B7)', () => {const resultMsg = sent[2]expect(resultMsg.role).toBe('user')expect(Array.isArray(resultMsg.content)).toBe(true)- const ids = resultMsg.content.map((b: any) => b.tool_use_id)+ const blocks: AnthropicRequestBlock[] =+ typeof resultMsg.content === 'string' ? [] : resultMsg.content+ const ids = blocks.map(b => (b.type === 'tool_result' ? b.tool_use_id : undefined))expect(ids).toEqual(['toolu_1', 'toolu_2'])})diff --git a/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts b/src/api/providers/__tests__/anthropic-thinking-and-errors.test.tsindex 0bb57129..2db37095 100644--- a/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts+++ b/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts@@ -27,22 +27,25 @@ import { describe, it, expect, vi, afterEach } from 'vitest'const localFetch = vi.fn()const localFetchStream = vi.fn()-const ensureProxyAllowsHost = vi.fn(async () => {})+const ensureProxyAllowsHost = vi.fn<(baseUrl: string) => Promise<void>>(async () => {})vi.mock('../../backend', async () => {const actual = await vi.importActual<typeof import('../../backend')>('../../backend')return {...actual,isTauri: () => false,- localFetch: (...a: any[]) => localFetch(...a),- localFetchStream: (...a: any[]) => localFetchStream(...a),- ensureProxyAllowsHost: (...a: any[]) => ensureProxyAllowsHost(...(a as [])),+ localFetch: (...a: Parameters<typeof actual.localFetch>) => localFetch(...a),+ localFetchStream: (...a: Parameters<typeof actual.localFetchStream>) => localFetchStream(...a),+ ensureProxyAllowsHost: (...a: Parameters<typeof actual.ensureProxyAllowsHost>) =>+ ensureProxyAllowsHost(...a),}})import { AnthropicProvider } from '../anthropic-provider'import { ProviderError } from '../types'import type { ProviderConfig, ChatStreamChunk } from '../types'+import type { MessagesBody } from '../anthropic-provider'+import { isRecord } from '../wire'function config(overrides: Partial<ProviderConfig> = {}): ProviderConfig {return {@@ -60,8 +63,20 @@ function sse(events: string[]): Response {const STOP = 'event: message_stop\ndata: {"type":"message_stop"}\n\n'-function sentBody(mock: { mock: { calls: any[][] } }, call = 0): any {- return JSON.parse(String(mock.mock.calls[call]?.[1]?.body ?? '{}'))+/**+ * The request body of a captured call, read as the provider's own request+ * interface: a rename in MessagesBody breaks the assertions below rather than+ * turning them into `undefined === undefined`.+ */+function thinkingOf(body: MessagesBody): { type: 'enabled'; budget_tokens: number } {+ if (!body.thinking) throw new Error('request carried no thinking block')+ return body.thinking+}++function sentBody(mock: { mock: { calls: readonly (readonly unknown[])[] } }, call = 0): MessagesBody {+ const init = mock.mock.calls[call]?.[1]+ const body = isRecord(init) ? init.body : undefined+ return JSON.parse(typeof body === 'string' ? body : '{}') as MessagesBody}async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {@@ -87,9 +102,9 @@ describe('Extended Thinking sends a body the API can accept', () => {const body = sentBody(fetchMock)expect(body.thinking).toEqual({ type: 'enabled', budget_tokens: expect.any(Number) })- expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)+ expect(body.max_tokens).toBeGreaterThan(thinkingOf(body).budget_tokens)// The API's own floor for a reasoning budget.- expect(body.thinking.budget_tokens).toBeGreaterThanOrEqual(1024)+ expect(thinkingOf(body).budget_tokens).toBeGreaterThanOrEqual(1024)})it('drops temperature / top_p / top_k, which thinking forbids', async () => {@@ -146,8 +161,8 @@ describe('Extended Thinking sends a body the API can accept', () => {const body = sentBody(fetchMock)expect(body.max_tokens).toBe(20000)- expect(body.thinking.budget_tokens).toBeLessThanOrEqual(10000)- expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)+ expect(thinkingOf(body).budget_tokens).toBeLessThanOrEqual(10000)+ expect(body.max_tokens).toBeGreaterThan(thinkingOf(body).budget_tokens)})it('applies to the non-streaming tool path as well', async () => {@@ -164,7 +179,7 @@ describe('Extended Thinking sends a body the API can accept', () => {)const body = sentBody(fetchMock)- expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)+ expect(body.max_tokens).toBeGreaterThan(thinkingOf(body).budget_tokens)expect(body).not.toHaveProperty('temperature')expect(fetchMock).toHaveBeenCalledTimes(1)})diff --git a/src/api/providers/__tests__/ollama-capabilities.test.ts b/src/api/providers/__tests__/ollama-capabilities.test.tsindex 68220982..5e6e7591 100644--- a/src/api/providers/__tests__/ollama-capabilities.test.ts+++ b/src/api/providers/__tests__/ollama-capabilities.test.ts@@ -25,6 +25,14 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { readFileSync } from 'node:fs'import { fileURLToPath } from 'node:url'import { dirname, resolve } from 'node:path'+import type { ProviderClient, ProviderConfig } from '../types'++/** The one match, or a loud failure — `find` returning undefined must not+ * quietly satisfy a `.toBeUndefined()` assertion about a FIELD. */+function found<T>(v: T | undefined, what: string): T {+ if (v === undefined) throw new Error(`no entry matching ${what}`)+ return v+}const src = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../ollama-provider.ts'),@@ -44,7 +52,10 @@ const TAGS = {],}-let provider: any+/** The constructor shape this test resolves out of the dynamic import. */+type OllamaCtor = new (config: ProviderConfig) => ProviderClient++let provider: ProviderClientbeforeEach(async () => {vi.resetModules()@@ -55,8 +66,10 @@ beforeEach(async () => {isTauri: () => false,}))const mod = await import('../ollama-provider')- const Ctor = mod.OllamaProvider ?? Object.values(mod).find((v: any) => typeof v === 'function')- provider = new (Ctor as any)({ id: 'ollama', name: 'Ollama', baseUrl: 'http://127.0.0.1:11434', apiKey: '', enabled: true, isLocal: true })+ const Ctor: OllamaCtor =+ mod.OllamaProvider ??+ (Object.values(mod).find(v => typeof v === 'function') as OllamaCtor)+ provider = new Ctor({ id: 'ollama', name: 'Ollama', baseUrl: 'http://127.0.0.1:11434', apiKey: '', enabled: true, isLocal: true })})afterEach(() => { vi.doUnmock('../../backend'); vi.resetModules() })@@ -64,7 +77,7 @@ afterEach(() => { vi.doUnmock('../../backend'); vi.resetModules() })describe('listModels carries the tool capability through', () => {it('a model that declares tools comes back as supportsTools true', async () => {const models = await provider.listModels()- const m = models.find((x: any) => x.name === 'qwen2.5-coder:14b')+ const m = found(models.find(x => x.name === 'qwen2.5-coder:14b'), 'qwen2.5-coder:14b')expect(m.supportsTools).toBe(true)})@@ -73,7 +86,7 @@ describe('listModels carries the tool capability through', () => {// decision to the family list, and the family list says yes because the// name contains 'qwen3'.const models = await provider.listModels()- const m = models.find((x: any) => x.name.includes('DevQuasar'))+ const m = found(models.find(x => x.name.includes('DevQuasar')), 'DevQuasar')expect(m.supportsTools).toBe(false)expect(m.supportsTools).not.toBeUndefined()})@@ -82,7 +95,7 @@ describe('listModels carries the tool capability through', () => {// Deliberately not `false`: no answer must not read as a denial, or every// model on an older server would be pushed onto the hermes path.const models = await provider.listModels()- const m = models.find((x: any) => x.name === 'legacy-model:7b')+ const m = found(models.find(x => x.name === 'legacy-model:7b'), 'legacy-model:7b')expect(m.supportsTools).toBeUndefined()})})diff --git a/src/api/providers/__tests__/openai-lan-capabilities.test.ts b/src/api/providers/__tests__/openai-lan-capabilities.test.tsindex 82f6119a..146c8231 100644--- a/src/api/providers/__tests__/openai-lan-capabilities.test.ts+++ b/src/api/providers/__tests__/openai-lan-capabilities.test.ts@@ -16,6 +16,7 @@* Run: npx vitest run src/api/providers/__tests__/openai-lan-capabilities.test.ts*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ProviderConfig } from '../types'// Answer shapes taken from a real LM Studio 0.3.x on the Mac, 2026-08-07.const STANDARD = {@@ -45,7 +46,7 @@ let enhancedAvailable: boolean// llama.cpp's real shape with chat_template_caps.let propsAnswer: Record<string, unknown> | null-async function makeProvider(config: Record<string, unknown>) {+async function makeProvider(config: ProviderConfig) {vi.resetModules()requested = []vi.doMock('../../backend', () => ({@@ -69,7 +70,7 @@ async function makeProvider(config: Record<string, unknown>) {explainDeadEngine: (e: unknown) => e,}))const mod = await import('../openai-provider')- return new mod.OpenAIProvider(config as any)+ return new mod.OpenAIProvider(config)}beforeEach(() => { enhancedAvailable = true; propsAnswer = null })@@ -84,7 +85,7 @@ describe('the LAN branch derives supportsTools from the enhanced listing', () =>it('a model declaring tool_use comes back true', async () => {const p = await makeProvider({ id: 'openai', name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- expect(models.find((m: any) => m.id === 'qwen2.5-0.5b-instruct')!.supportsTools).toBe(true)+ expect(models.find(m => m.id === 'qwen2.5-0.5b-instruct')!.supportsTools).toBe(true)})it('a model WITHOUT tool_use comes back FALSE, not the optimistic default', async () => {@@ -93,14 +94,14 @@ describe('the LAN branch derives supportsTools from the enhanced listing', () =>// already disclaimed.const p = await makeProvider({ id: 'openai', name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- expect(models.find((m: any) => m.id === 'tinystories-33m')!.supportsTools).toBe(false)+ expect(models.find(m => m.id === 'tinystories-33m')!.supportsTools).toBe(false)})it('an entry without a capabilities array falls back to the old default', async () => {// No answer must not read as a denial (same rule as the Ollama G26 fix).const p = await makeProvider({ id: 'openai', name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- expect(models.find((m: any) => m.id === 'legacy-model')!.supportsTools).toBe(true)+ expect(models.find(m => m.id === 'legacy-model')!.supportsTools).toBe(true)})it('NEGATIVE CONTROL: a backend without enhanced API or /props stays optimistic', async () => {@@ -108,7 +109,7 @@ describe('the LAN branch derives supportsTools from the enhanced listing', () =>enhancedAvailable = falseconst p = await makeProvider({ id: 'openai', name: 'vLLM', baseUrl: 'http://localhost:1234/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- for (const m of models) expect((m as any).supportsTools).toBe(true)+ for (const m of models) expect(m.supportsTools).toBe(true)})})@@ -124,25 +125,25 @@ describe('G37: llama.cpp /props decides when the enhanced listing says nothing',it('supports_tools false on /props downgrades every model of that server', async () => {enhancedAvailable = falsepropsAnswer = LLAMA_PROPS_NO_TOOLS- const p = await makeProvider({ id: 'builtin', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })+ const p = await makeProvider({ id: 'openai', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- for (const m of models) expect((m as any).supportsTools).toBe(false)+ for (const m of models) expect(m.supportsTools).toBe(false)})it('supports_tools true on /props keeps native (llama.cpp with a tool template)', async () => {enhancedAvailable = falsepropsAnswer = LLAMA_PROPS_TOOLS- const p = await makeProvider({ id: 'builtin', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })+ const p = await makeProvider({ id: 'openai', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- for (const m of models) expect((m as any).supportsTools).toBe(true)+ for (const m of models) expect(m.supportsTools).toBe(true)})it('a props answer without the field means nobody said: optimistic default', async () => {enhancedAvailable = falsepropsAnswer = { build_info: 'b1', model_path: '/x.gguf' }- const p = await makeProvider({ id: 'builtin', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })+ const p = await makeProvider({ id: 'openai', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- for (const m of models) expect((m as any).supportsTools).toBe(true)+ for (const m of models) expect(m.supportsTools).toBe(true)})it('NEGATIVE CONTROL: the enhanced listing wins, /props is not even asked', async () => {@@ -151,7 +152,7 @@ describe('G37: llama.cpp /props decides when the enhanced listing says nothing',propsAnswer = LLAMA_PROPS_NO_TOOLSconst p = await makeProvider({ id: 'openai', name: 'LM Studio', baseUrl: 'http://localhost:1234/v1', apiKey: '', enabled: true, isLocal: true })const models = await p.listModels()- expect(models.find((m: any) => m.id === 'qwen2.5-0.5b-instruct')!.supportsTools).toBe(true)+ expect(models.find(m => m.id === 'qwen2.5-0.5b-instruct')!.supportsTools).toBe(true)expect(requested.some(u => u.endsWith('/props'))).toBe(false)})})@@ -163,7 +164,7 @@ describe('G37b: serverToolSupport answers the same question at send time', () =>it('llama.cpp /props false answers false, and the cache pays one request for the whole run', async () => {enhancedAvailable = falsepropsAnswer = { chat_template_caps: { supports_tools: false } }- const p = await makeProvider({ id: 'builtin', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })+ const p = await makeProvider({ id: 'openai', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })expect(await p.serverToolSupport('any-gguf')).toBe(false)expect(await p.serverToolSupport('another-gguf')).toBe(false)expect(requested.filter(u => u.endsWith('/props')).length).toBe(1)@@ -195,7 +196,7 @@ describe('G37b: serverToolSupport answers the same question at send time', () =>it('listModels and serverToolSupport share the cache: one /props total', async () => {enhancedAvailable = falsepropsAnswer = { chat_template_caps: { supports_tools: false } }- const p = await makeProvider({ id: 'builtin', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })+ const p = await makeProvider({ id: 'openai', name: 'Built-in Engine', baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', enabled: true, isLocal: true })await p.listModels()expect(await p.serverToolSupport('any-gguf')).toBe(false)expect(requested.filter(u => u.endsWith('/props')).length).toBe(1)@@ -213,8 +214,8 @@ describe('NEGATIVE CONTROL: cloud endpoints are untouched', () => {] })}))const models = await p.listModels()- expect(models.find((m: any) => m.id === 'gpt-4o')!.supportsTools).toBe(true)- expect(models.find((m: any) => m.id === 'roleplay-model')!.supportsTools).toBe(false)+ expect(models.find(m => m.id === 'gpt-4o')!.supportsTools).toBe(true)+ expect(models.find(m => m.id === 'roleplay-model')!.supportsTools).toBe(false)expect(requested.some(u => u.includes('/api/v0'))).toBe(false)})})diff --git a/src/api/providers/__tests__/openai-probe-guards.test.ts b/src/api/providers/__tests__/openai-probe-guards.test.tsindex 88128be5..86aa5489 100644--- a/src/api/providers/__tests__/openai-probe-guards.test.ts+++ b/src/api/providers/__tests__/openai-probe-guards.test.ts@@ -22,8 +22,8 @@ vi.mock('../../backend', async () => {return {...actual,isTauri: () => false,- localFetch: (...a: any[]) => localFetch(...a),- localFetchStream: (...a: any[]) => localFetchStream(...a),+ localFetch: (...a: Parameters<typeof import('../../backend').localFetch>) => localFetch(...a),+ localFetchStream: (...a: Parameters<typeof import('../../backend').localFetchStream>) => localFetchStream(...a),ensureProxyAllowsHost: async () => {},}})diff --git a/src/api/providers/__tests__/openai-template-thinking.test.ts b/src/api/providers/__tests__/openai-template-thinking.test.tsindex c5bc5a42..85c5d7fa 100644--- a/src/api/providers/__tests__/openai-template-thinking.test.ts+++ b/src/api/providers/__tests__/openai-template-thinking.test.ts@@ -28,15 +28,24 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { readFileSync } from 'node:fs'import { fileURLToPath } from 'node:url'import { dirname, join } from 'node:path'+import type { ProviderConfig, ChatStreamChunk } from '../types'+import type { OpenAIChatRequest } from '../openai-provider'+import type { FetchArgs } from '../../__tests__/provider-test-support'const streamBody = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'-let sent: { url: string; body: Record<string, any> }[]+/** The init shape both backend helpers are called with in this file. */+type CapturedInit = { method?: string; headers?: Record<string, string>; body?: string }++let sent: { url: string; body: OpenAIChatRequest }[]/** Status the fake server answers with, one entry per request in order. */let statuses: number[]-function answer(url: string, init: any) {- const body = JSON.parse(init.body as string)+function answer(url: string, init: CapturedInit) {+ if (typeof init.body !== 'string') throw new Error('request had no JSON body')+ // Read as the provider's own request interface, so a renamed field breaks+ // the assertions instead of quietly comparing undefined to undefined.+ const body = JSON.parse(init.body) as OpenAIChatRequestsent.push({ url, body })const status = statuses.shift() ?? 200if (status !== 200) {@@ -46,13 +55,13 @@ function answer(url: string, init: any) {return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })}-async function makeProvider(config: Record<string, unknown>) {+async function makeProvider(config: ProviderConfig) {vi.resetModules()sent = []statuses = []vi.doMock('../../backend', () => ({- localFetch: vi.fn(async (url: string, init: any) => answer(url, init)),- localFetchStream: vi.fn(async (url: string, init: any) => answer(url, init)),+ localFetch: vi.fn(async (url: string, init: CapturedInit) => answer(url, init)),+ localFetchStream: vi.fn(async (url: string, init: CapturedInit) => answer(url, init)),backendCall: vi.fn(),isPrivateOrLanHost: (host: string) => host === 'localhost' || host === '127.0.0.1',isDirectFetchAllowed: () => true,@@ -67,23 +76,28 @@ async function makeProvider(config: Record<string, unknown>) {isManagedBuiltinSlot: () => false,}))const mod = await import('../openai-provider')- return new mod.OpenAIProvider(config as any)+ return new mod.OpenAIProvider(config)}-const BUILTIN = {+const BUILTIN: ProviderConfig = {id: 'openai', name: 'Built-in Engine', apiKey: '', enabled: true,baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true,}-const CLOUD = {+const CLOUD: ProviderConfig = {id: 'openai', name: 'OpenAI', apiKey: 'sk-test', enabled: true,baseUrl: 'https://api.openai.com/v1', isLocal: false,}-async function drain(gen: AsyncGenerator<any>) {+async function drain(gen: AsyncGenerator<ChatStreamChunk>) {for await (const _ of gen) { /* the fetch only fires on the first next() */ }}-beforeEach(() => { vi.spyOn(globalThis, 'fetch').mockImplementation(((url: any, init: any) => answer(String(url), init)) as any) })+beforeEach(() => {+ vi.spyOn(globalThis, 'fetch').mockImplementation(+ async (url: FetchArgs[0], init: FetchArgs[1]) =>+ answer(String(url), { body: typeof init?.body === 'string' ? init.body : undefined }),+ )+})afterEach(() => {vi.doUnmock('../../backend')vi.doUnmock('../../builtin-ensure')diff --git a/src/api/providers/__tests__/system-message-first.test.ts b/src/api/providers/__tests__/system-message-first.test.tsindex c4a02a1c..698f9626 100644--- a/src/api/providers/__tests__/system-message-first.test.ts+++ b/src/api/providers/__tests__/system-message-first.test.ts@@ -30,6 +30,19 @@ import { describe, it, expect, vi, afterEach } from 'vitest'import { normalizeSystemMessages } from '../normalize-system'import { groupHistory } from '../../../lib/group-chat'import type { Message } from '../../../types/chat'+import type { ChatMessage } from '../types'+import type { OpenAIChatRequest } from '../openai-provider'+import type { OllamaChatRequest } from '../ollama-provider'++/** The init shape both backend helpers are called with in this file. */+type CapturedInit = { method?: string; headers?: Record<string, string>; body?: string }++/** Read a captured body as the request type the provider builds, so a renamed+ * field breaks these assertions instead of turning them into undefined. */+function captured<T>(init: CapturedInit): T {+ if (typeof init.body !== 'string') throw new Error('capture had no JSON body')+ return JSON.parse(init.body) as T+}// ── The guard the shipped chat templates actually contain ──────@@ -43,7 +56,7 @@ function jinjaGate(messages: { role: string }[]): void {// The history the reporter had: an agent turn with tools, and a second system// block injected behind the first user message. This is what dies today.-const CRASHING_HISTORY = [+const CRASHING_HISTORY: ChatMessage[] = [{ role: 'system', content: 'You are a helpful agent.' },{ role: 'user', content: 'List the files in my project.' },{ role: 'system', content: 'Available tools: file_list, file_read.' },@@ -140,10 +153,10 @@ describe('normalizeSystemMessages', () => {// ── The wire: what the local engines actually receive ──────────-const backendMock = (capture: (url: string, init: any) => Response) => ({+const backendMock = (capture: (url: string, init: CapturedInit) => Response) => ({isTauri: () => false,- localFetch: vi.fn(async (url: string, init: any) => capture(url, init)),- localFetchStream: vi.fn(async (url: string, init: any) => capture(url, init)),+ localFetch: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),+ localFetchStream: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,backendCall: vi.fn(),isPrivateOrLanHost: () => true,@@ -161,10 +174,12 @@ afterEach(() => {describe('the body that leaves for a local engine', () => {it('Ollama chatStream sends one system message, first', async () => {vi.resetModules()- let sent: any = null+ // An array, not a `let`: a push keeps the captured body's real type+ // instead of letting control-flow analysis collapse it to `never`.+ const captures: OllamaChatRequest[] = []vi.doMock('../../backend', () =>backendMock((_url, init) => {- sent = JSON.parse(init.body)+ captures.push(captured<OllamaChatRequest>(init))return new Response('{"message":{"content":"ok"},"done":true}\n')}),)@@ -173,18 +188,20 @@ describe('the body that leaves for a local engine', () => {id: 'ollama', name: 'Ollama', enabled: true,baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,})- for await (const chunk of p.chatStream('qwen3:8b', CRASHING_HISTORY as any)) { void chunk }- expect(sent.messages.filter((m: any) => m.role === 'system')).toHaveLength(1)+ for await (const chunk of p.chatStream('qwen3:8b', CRASHING_HISTORY)) { void chunk }+ expect(captures).toHaveLength(1)+ const sent = captures[0]+ expect(sent.messages.filter(m => m.role === 'system')).toHaveLength(1)expect(sent.messages[0].role).toBe('system')expect(() => jinjaGate(sent.messages)).not.toThrow()})it('Ollama chatWithTools sends one system message, first', async () => {vi.resetModules()- let sent: any = null+ const captures: OllamaChatRequest[] = []vi.doMock('../../backend', () =>backendMock((_url, init) => {- sent = JSON.parse(init.body)+ captures.push(captured<OllamaChatRequest>(init))return new Response(JSON.stringify({ message: { content: 'ok' } }), {headers: { 'Content-Type': 'application/json' },})@@ -195,18 +212,20 @@ describe('the body that leaves for a local engine', () => {id: 'ollama', name: 'Ollama', enabled: true,baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,})- await p.chatWithTools('qwen3:8b', CRASHING_HISTORY as any, [])+ await p.chatWithTools('qwen3:8b', CRASHING_HISTORY, [])+ expect(captures).toHaveLength(1)+ const sent = captures[0]expect(() => jinjaGate(sent.messages)).not.toThrow()expect(sent.messages[0].content).toContain('Available tools: file_list, file_read.')})it('the built-in engine (OpenAI-compatible) gets one system message, first', async () => {vi.resetModules()- let sent: any = null+ const captures: OpenAIChatRequest[] = []vi.doMock('../../backend', () =>backendMock((url, init) => {if (url.includes('/chat/completions')) {- sent = JSON.parse(init.body)+ captures.push(captured<OpenAIChatRequest>(init))return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }),{ headers: { 'Content-Type': 'application/json' } },@@ -225,8 +244,10 @@ describe('the body that leaves for a local engine', () => {id: 'openai', name: 'Built-in Engine', enabled: true,baseUrl: 'http://127.0.0.1:8127/v1', apiKey: '', isLocal: true, managed: true,})- await p.chatWithTools('qwen3-8b', CRASHING_HISTORY as any, [])- expect(sent.messages.filter((m: any) => m.role === 'system')).toHaveLength(1)+ await p.chatWithTools('qwen3-8b', CRASHING_HISTORY, [])+ expect(captures).toHaveLength(1)+ const sent = captures[0]+ expect(sent.messages.filter(m => m.role === 'system')).toHaveLength(1)expect(sent.messages[0].role).toBe('system')expect(() => jinjaGate(sent.messages)).not.toThrow()})diff --git a/src/api/providers/__tests__/template-contract.test.ts b/src/api/providers/__tests__/template-contract.test.tsindex 32cc6d3e..ab3a4f04 100644--- a/src/api/providers/__tests__/template-contract.test.ts+++ b/src/api/providers/__tests__/template-contract.test.ts@@ -37,6 +37,20 @@ import { applyTemplateContract } from '../normalize-system'import { groupHistory, groupSystemPrompt } from '../../../lib/group-chat'import { isTemplateRefusal, explainSendRefusal } from '../../../lib/template-refusal'import type { Message } from '../../../types/chat'+import type { ChatMessage, ProviderConfig, ToolDefinition } from '../types'+import type { OpenAIChatRequest } from '../openai-provider'+import type { OllamaChatRequest } from '../ollama-provider'++/** The init shape both backend helpers are called with in this file. */+type CapturedInit = { method?: string; headers?: Record<string, string>; body?: string }++/** Read a captured request body as the request type the provider builds, so a+ * renamed field in the provider breaks these assertions instead of quietly+ * turning them into `undefined === undefined`. */+function captured<T>(init: CapturedInit): T {+ if (typeof init.body !== 'string') throw new Error('capture had no JSON body')+ return JSON.parse(init.body) as T+}// ── The guard Gemma 3 actually contains ────────────────────────@@ -66,7 +80,7 @@ const TOLERANT = { toolRole: 'native', alternate: false } as const// Weg 1 of the counter-check, copied from logs/wire-b3-12-agent-round2.json:// the agent's own history after one approved file_write, on the prompt// transport, with no `tools` field in the request.-const AGENT_AFTER_A_TOOL = [+const AGENT_AFTER_A_TOOL: ChatMessage[] = [{ role: 'system', content: 'You are a function calling AI model. <tools>...</tools>' },{ role: 'user', content: 'Create a file called notes.txt containing the word hello, then read it back.' },{@@ -205,10 +219,10 @@ describe('the template contract', () => {// ── 2. Which endpoint gets which contract ──────────────────────-const backendMock = (capture: (url: string, init: any) => Response, opts?: { lan?: boolean }) => ({+const backendMock = (capture: (url: string, init: CapturedInit) => Response, opts?: { lan?: boolean }) => ({isTauri: () => false,- localFetch: vi.fn(async (url: string, init: any) => capture(url, init)),- localFetchStream: vi.fn(async (url: string, init: any) => capture(url, init)),+ localFetch: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),+ localFetchStream: vi.fn(async (url: string, init: CapturedInit) => capture(url, init)),ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,backendCall: vi.fn(),isPrivateOrLanHost: () => opts?.lan !== false,@@ -223,15 +237,15 @@ const okJson = (body: unknown) =>async function sendVia(config: { baseUrl: string; isLocal: boolean; managed?: boolean },- tools: any[],+ tools: ToolDefinition[],lan: boolean,-): Promise<any> {+): Promise<OpenAIChatRequest> {vi.resetModules()- let sent: any = null+ let sent: OpenAIChatRequest | null = nullvi.doMock('../../backend', () =>backendMock((url, init) => {if (url.includes('/chat/completions')) {- sent = JSON.parse(init.body)+ sent = captured<OpenAIChatRequest>(init)return okJson({ choices: [{ message: { content: 'ok' } }] })}return new Response('{}', { status: 404 })@@ -243,10 +257,12 @@ async function sendVia(isManagedBuiltinSlot: () => config.managed === true,}))const { OpenAIProvider } = await import('../openai-provider')- const p = new OpenAIProvider({+ const providerConfig: ProviderConfig = {id: 'openai', name: 'test', enabled: true, apiKey: '', ...config,- } as any)- await p.chatWithTools('m', AGENT_AFTER_A_TOOL as any, tools as any)+ }+ const p = new OpenAIProvider(providerConfig)+ await p.chatWithTools('m', AGENT_AFTER_A_TOOL, tools)+ if (!sent) throw new Error('no /chat/completions request was captured')return sent}@@ -262,7 +278,7 @@ describe('the body that leaves for each kind of endpoint', () => {{ baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true }, [], true,)expect(sent.tools).toBeUndefined()- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)+ expect(sent.messages.some(m => m.role === 'tool')).toBe(false)expect(() => gemmaGate(sent.messages)).not.toThrow()})@@ -270,7 +286,7 @@ describe('the body that leaves for each kind of endpoint', () => {const sent = await sendVia({ baseUrl: 'http://localhost:1234/v1', isLocal: true }, [], true,)- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)+ expect(sent.messages.some(m => m.role === 'tool')).toBe(false)expect(() => gemmaGate(sent.messages)).not.toThrow()})@@ -285,7 +301,7 @@ describe('the body that leaves for each kind of endpoint', () => {true,)expect(sent.tools).toHaveLength(1)- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)+ expect(sent.messages.some(m => m.role === 'tool')).toBe(true)expect(sent.messages[2].tool_calls).toHaveLength(1)})@@ -295,17 +311,19 @@ describe('the body that leaves for each kind of endpoint', () => {const sent = await sendVia({ baseUrl: 'https://api.example-cloud.com/v1', isLocal: false }, [], false,)- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)+ expect(sent.messages.some(m => m.role === 'tool')).toBe(true)expect(sent.messages[3].tool_call_id).toBe('call_1')- expect(sent.messages[2].tool_calls[0].id).toBe('call_1')+ expect(sent.messages[2].tool_calls?.[0].id).toBe('call_1')})it('Ollama chatStream, which never carries tools, gets the tolerant sequence', async () => {vi.resetModules()- let sent: any = null+ // An array, not a `let`: TypeScript resets no narrowing on a push, so the+ // captured body keeps its real type instead of collapsing to `never`.+ const captures: OllamaChatRequest[] = []vi.doMock('../../backend', () =>backendMock((_url, init) => {- sent = JSON.parse(init.body)+ captures.push(captured<OllamaChatRequest>(init))return new Response('{"message":{"content":"ok"},"done":true}\n')}),)@@ -314,17 +332,19 @@ describe('the body that leaves for each kind of endpoint', () => {id: 'ollama', name: 'Ollama', enabled: true,baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,})- for await (const chunk of p.chatStream('gemma3:4b', AGENT_AFTER_A_TOOL as any)) { void chunk }- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(false)- expect(() => gemmaGate(sent.messages)).not.toThrow()+ for await (const chunk of p.chatStream('gemma3:4b', AGENT_AFTER_A_TOOL)) { void chunk }+ expect(captures).toHaveLength(1)+ const streamed = captures[0]+ expect(streamed.messages.some(m => m.role === 'tool')).toBe(false)+ expect(() => gemmaGate(streamed.messages)).not.toThrow()})it('Ollama chatWithTools with a real tools payload keeps the tool role', async () => {vi.resetModules()- let sent: any = null+ const captures: OllamaChatRequest[] = []vi.doMock('../../backend', () =>backendMock((_url, init) => {- sent = JSON.parse(init.body)+ captures.push(captured<OllamaChatRequest>(init))return okJson({ message: { content: 'ok' } })}),)@@ -333,10 +353,11 @@ describe('the body that leaves for each kind of endpoint', () => {id: 'ollama', name: 'Ollama', enabled: true,baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,})- await p.chatWithTools('qwen3:8b', AGENT_AFTER_A_TOOL as any, [+ await p.chatWithTools('qwen3:8b', AGENT_AFTER_A_TOOL, [{ type: 'function', function: { name: 'file_write', description: '', parameters: { type: 'object', properties: {}, required: [] } } },- ] as any)- expect(sent.messages.some((m: any) => m.role === 'tool')).toBe(true)+ ])+ expect(captures).toHaveLength(1)+ expect(captures[0].messages.some(m => m.role === 'tool')).toBe(true)})})diff --git a/src/api/providers/__tests__/transient-retry.test.ts b/src/api/providers/__tests__/transient-retry.test.tsindex 2ba80b27..6ab8aa79 100644--- a/src/api/providers/__tests__/transient-retry.test.ts+++ b/src/api/providers/__tests__/transient-retry.test.ts@@ -18,6 +18,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest'import {sendWithTransientRetry, MAX_TRANSIENT_ATTEMPTS, MAX_SILENT_RETRY_WAIT_MS,} from '../retry'+import { asProviderError } from '../../__tests__/provider-test-support'import { OpenAIProvider } from '../openai-provider'import type { ProviderConfig, ChatStreamChunk } from '../types'@@ -195,9 +196,9 @@ describe('the chat send path retries a throttle', () => {vi.stubGlobal('fetch', fetchMock)const running = drain(new OpenAIProvider(openAIConfig())- .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }])).then(() => null, (e: any) => e)+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }])).then(() => null, (e: unknown) => e)await vi.advanceTimersByTimeAsync(5000)- const err = await running+ const err = asProviderError(await running)expect(fetchMock).toHaveBeenCalledTimes(MAX_TRANSIENT_ATTEMPTS)expect(err.code).toBe('rate_limit')diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.tsindex a62b7b4f..df9a2eb4 100644--- a/src/api/providers/anthropic-provider.ts+++ b/src/api/providers/anthropic-provider.ts@@ -21,34 +21,17 @@ import {localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed,hostnameOf, ensureProxyAllowsHost,} from '../backend'+import {+ parseAnthropicStreamEvent, parseAnthropicMessageResponse, isRecord, prop, asString,+} from './wire'// ── Anthropic API Types ────────────────────────────────────────--interface AnthropicStreamEvent {- type: string- index?: number- content_block?: { type: string; id?: string; name?: string; input?: any; text?: string }- delta?: { type: string; text?: string; partial_json?: string; thinking?: string }- message?: { id: string; usage?: { input_tokens: number; output_tokens: number } }- // message_delta events carry cumulative output usage at the event top level.- usage?: { input_tokens?: number; output_tokens?: number }- // `event: error` on an otherwise healthy HTTP-200 stream. Anthropic sends it- // for overloaded_error / api_error when the failure happens AFTER the- // response headers are out.- error?: { type?: string; message?: string }-}--interface AnthropicResponse {- content: {- type: 'text' | 'tool_use'- text?: string- id?: string- name?: string- input?: Record<string, any>- }[]- stop_reason?: string- usage?: { input_tokens: number; output_tokens: number }-}+//+// Incoming shapes and their checked parsers live in ./wire. They used to be+// declared here and asserted onto `parseSSEWithEvents<T>` / `res.json()`,+// which is how `delta` ended up read through four separate `as any` casts in+// the stream loop below: the declared `delta` had no `stop_reason`, so the one+// place that needs it had to lie about the type to get at it.// ── Known Claude models ────────────────────────────────────────@@ -79,10 +62,72 @@ const CLAUDE_MODELS: ProviderModel[] = [// write a fresh entry on every step and never read one back, because A1// decay and A3 compaction still rewrite the tail of the history.-/** A /v1/messages body under construction. The wire mixes strings, numbers,- * nested objects and content-block arrays, so the value type stays open —- * named once here rather than restated on every signature. */-type MessagesBody = Record<string, any>+// ── Request shapes (what we SEND) ──────────────────────────────++/** Any request block may carry a cache breakpoint — see applyCacheControl. */+export interface CacheControlled {+ cache_control?: { type: 'ephemeral' }+}++export interface AnthropicTextBlock extends CacheControlled {+ type: 'text'+ text: string+}+export interface AnthropicImageBlock extends CacheControlled {+ type: 'image'+ source: { type: 'base64'; media_type: string; data: string }+}+export interface AnthropicToolUseBlock extends CacheControlled {+ type: 'tool_use'+ id: string+ name: string+ input: Record<string, unknown>+}+export interface AnthropicToolResultBlock extends CacheControlled {+ type: 'tool_result'+ tool_use_id: string+ content: string+}++export type AnthropicRequestBlock =+ | AnthropicTextBlock+ | AnthropicImageBlock+ | AnthropicToolUseBlock+ | AnthropicToolResultBlock++export interface AnthropicRequestMessage {+ role: 'user' | 'assistant'+ content: string | AnthropicRequestBlock[]+}++export interface AnthropicToolSpec extends CacheControlled {+ name: string+ description: string+ input_schema: ToolDefinition['function']['parameters']+}++/**+ * A /v1/messages body under construction.+ *+ * Every optional field here is one that some code path adds and another+ * deletes again (`thinking` on the 400-retry, the three sampling knobs when+ * thinking turns on). Under the old `Record<string, any>` a misspelt key in+ * either direction compiled: the field would simply never be added, or never+ * removed, and the request would go out wrong with nothing to notice it.+ */+export interface MessagesBody {+ model: string+ messages: AnthropicRequestMessage[]+ max_tokens: number+ stream?: boolean+ /** A plain string until applyCacheControl promotes it to a cached block. */+ system?: string | AnthropicTextBlock[]+ temperature?: number+ top_p?: number+ top_k?: number+ tools?: AnthropicToolSpec[]+ thinking?: { type: 'enabled'; budget_tokens: number }+}/** The init every transport in this file accepts: plain `fetch`, and the two* proxy-aware helpers in backend.ts. */@@ -102,7 +147,7 @@ const DEFAULT_THINKING_BUDGET = 5000const MIN_ANSWER_TOKENS = 2048/** A message content as blocks, so a marker has something to ride on. */-function asContentBlocks(content: string | Record<string, any>[]): Record<string, any>[] {+function asContentBlocks(content: string | AnthropicRequestBlock[]): AnthropicRequestBlock[] {return typeof content === 'string' ? [{ type: 'text', text: content }] : content}@@ -120,11 +165,12 @@ function applyCacheControl(body: MessagesBody): void {body.system = [{ type: 'text', text: body.system, cache_control: { ...CACHE_CONTROL } }]}- const messages: Record<string, any>[] = body.messages+ const messages = body.messagesif (messages.length >= 2) {const stable = messages[messages.length - 2]- stable.content = asContentBlocks(stable.content)- const lastBlock = stable.content[stable.content.length - 1]+ const blocks = asContentBlocks(stable.content)+ stable.content = blocks+ const lastBlock = blocks[blocks.length - 1]if (lastBlock) lastBlock.cache_control = { ...CACHE_CONTROL }}}@@ -233,7 +279,7 @@ export class AnthropicProvider implements ProviderClient {private applyThinking(body: MessagesBody, options?: ChatOptions): void {if (options?.thinking !== true) return- const ceiling: number = body.max_tokens+ const ceiling = body.max_tokensconst budget = Math.max(1024, Math.min(DEFAULT_THINKING_BUDGET, Math.floor(ceiling / 2)))body.thinking = { type: 'enabled', budget_tokens: budget }// max_tokens covers thinking AND the answer, so it must have room for both.@@ -315,8 +361,11 @@ export class AnthropicProvider implements ProviderClient {let outputTokens = 0try {- for await (const { data } of parseSSEWithEvents<AnthropicStreamEvent>(res, { onIdle: guard.abort })) {+ // Boundary: the SSE payloads are foreign, so each event is walked with+ // checked reads instead of being asserted into a declared shape.+ for await (const { data: raw } of parseSSEWithEvents<unknown>(res, { onIdle: guard.abort })) {if (options?.signal?.aborted) break+ const data = parseAnthropicStreamEvent(raw)switch (data.type) {case 'error': {@@ -352,8 +401,15 @@ export class AnthropicProvider implements ProviderClient {}case 'content_block_start': {- if (data.content_block?.type === 'tool_use') {- toolUseBlocks.set(data.index!, {+ // `index` keys the accumulator that content_block_delta later+ // appends to. It used to be read through a non-null assertion, so+ // an event without one silently opened a block under the key+ // `undefined` — and every delta then looked it up under a real+ // number and found nothing, dropping the whole tool call. Skipping+ // the block is the same outcome the lookup already produced, minus+ // the poisoned map entry.+ if (data.content_block?.type === 'tool_use' && data.index !== undefined) {+ toolUseBlocks.set(data.index, {id: data.content_block.id || '',name: data.content_block.name || '',input: '',@@ -363,16 +419,17 @@ export class AnthropicProvider implements ProviderClient {}case 'content_block_delta': {- const dtype = (data.delta as any)?.type- if (dtype === 'text_delta' && (data.delta as any).text) {- yield { content: (data.delta as any).text, done: false }- } else if (dtype === 'thinking_delta' && (data.delta as any).thinking) {+ const delta = data.delta+ const dtype = delta?.type+ if (dtype === 'text_delta' && delta?.text) {+ yield { content: delta.text, done: false }+ } else if (dtype === 'thinking_delta' && delta?.thinking) {// Claude Extended Thinking stream — route to `thinking` so the// ThinkingBlock UI picks it up (same field as Ollama's native).- yield { content: '', thinking: (data.delta as any).thinking, done: false }- } else if (dtype === 'input_json_delta' && (data.delta as any).partial_json) {- const block = toolUseBlocks.get(data.index!)- if (block) block.input += (data.delta as any).partial_json+ yield { content: '', thinking: delta.thinking, done: false }+ } else if (dtype === 'input_json_delta' && delta?.partial_json && data.index !== undefined) {+ const block = toolUseBlocks.get(data.index)+ if (block) block.input += delta.partial_json}break}@@ -381,7 +438,7 @@ export class AnthropicProvider implements ProviderClient {// End of message — flush tool calls. Map Anthropic's stop_reason// onto the unified finishReason ('max_tokens' → 'length', the key// the chat layer uses to explain thought-only/truncated turns).- const stopReason = (data.delta as any)?.stop_reason as string | undefined+ const stopReason = data.delta?.stop_reasonif (data.usage?.output_tokens) outputTokens = data.usage.output_tokensconst toolCalls = this.flushToolUseBlocks(toolUseBlocks)yield {@@ -474,7 +531,11 @@ export class AnthropicProvider implements ProviderClient {throw await this.parseError(res)}- const data: AnthropicResponse = await res.json()+ // Boundary: checked parse, not `as AnthropicResponse`. The old assertion+ // also declared `content` non-optional and then iterated it — a body+ // without one (an error shape from a proxy fronting this endpoint) threw+ // a bare TypeError instead of an empty turn.+ const data = parseAnthropicMessageResponse(await res.json())let content = ''const toolCalls: ToolCall[] = []@@ -486,8 +547,11 @@ export class AnthropicProvider implements ProviderClient {toolCalls.push({id: block.id,function: {- name: block.name!,- arguments: (typeof block.input === 'object' && block.input) ? block.input : {},+ // `name!` used to assert a field the same interface declared+ // optional. A tool_use block without one now dispatches on '',+ // which fails as a lookup instead of as an undefined property.+ name: block.name ?? '',+ arguments: isRecord(block.input) ? block.input : {},},})}@@ -534,10 +598,10 @@ export class AnthropicProvider implements ProviderClient {private convertMessages(messages: ChatMessage[]): {system: string- anthropicMessages: Record<string, any>[]+ anthropicMessages: AnthropicRequestMessage[]} {let system = ''- const anthropicMessages: Record<string, any>[] = []+ const anthropicMessages: AnthropicRequestMessage[] = []for (const msg of messages) {if (msg.role === 'system') {@@ -561,7 +625,7 @@ export class AnthropicProvider implements ProviderClient {if (msg.role === 'assistant' && msg.tool_calls?.length) {// Assistant with tool calls → include tool_use content blocks- const content: any[] = []+ const content: AnthropicRequestBlock[] = []if (msg.content) content.push({ type: 'text', text: msg.content })for (const tc of msg.tool_calls) {content.push({@@ -577,7 +641,7 @@ export class AnthropicProvider implements ProviderClient {// Regular user/assistant message — with optional imagesif (msg.images?.length && msg.role === 'user') {- const content: any[] = []+ const content: AnthropicRequestBlock[] = []for (const img of msg.images) {content.push({type: 'image',@@ -598,9 +662,8 @@ export class AnthropicProvider implements ProviderClient {// to arrive in ONE user message. The old string-only merge left two// parallel tool calls as two consecutive user messages, which the API// rejects — so any multi-tool batch broke the whole Anthropic agent path.- const asBlocks = (content: string | Record<string, any>[]): Record<string, any>[] =>- typeof content === 'string' ? [{ type: 'text', text: content }] : content- const merged: Record<string, any>[] = []+ const asBlocks = asContentBlocks+ const merged: AnthropicRequestMessage[] = []for (const msg of anthropicMessages) {const last = merged[merged.length - 1]if (!last || last.role !== msg.role) {@@ -624,8 +687,15 @@ export class AnthropicProvider implements ProviderClient {const calls: ToolCall[] = []for (const [, block] of blocks) {- let args: Record<string, any> = {}- try { args = JSON.parse(block.input) } catch { /* empty */ }+ // `input` is JSON text assembled from input_json_delta fragments. It can+ // decode to a non-object (a truncated stream, or a model that emitted+ // `null`) — the old annotation promised a Record and would have handed+ // `null` straight to the tool dispatcher.+ let args: Record<string, unknown> = {}+ try {+ const parsed: unknown = JSON.parse(block.input)+ if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>+ } catch { /* empty */ }calls.push({id: block.id,@@ -643,8 +713,9 @@ export class AnthropicProvider implements ProviderClient {let code: string = 'network'try {- const data = await res.json()- if (data.error?.message) message = data.error.message+ const data: unknown = await res.json()+ const serverMessage = asString(prop(prop(data, 'error'), 'message'))+ if (serverMessage) message = serverMessage} catch { /* use default */ }if (res.status === 401 || res.status === 403) {diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex fb0aad19..850cd540 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -15,11 +15,45 @@ import { parseNDJSONStream } from '../stream'import { idleAbortGuard, isStreamIdleTimeout, STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'import { applyTemplateContract } from './normalize-system'+import type { OllamaWireToolCall } from './wire'+import { isRecord, prop, asString, asNumber, asRecordArray } from './wire'// ── Ollama-specific types ──────────────────────────────────────+/**+ * What we SEND. Separate from the wire types in `./wire`, which describe what+ * the server sends back: this payload is ours, so it gets a real shape rather+ * than a `Record<string, any>` bag that would swallow a typo in a field name.+ */+export interface OllamaRequestOptions {+ temperature?: number+ top_p?: number+ top_k?: number+ num_predict?: number+ num_ctx?: number+}++export interface OllamaRequestMessage {+ role: string+ content: string+ /** base64 payloads only — Ollama takes the data, not our {data,mimeType}. */+ images?: string[]+ tool_calls?: ToolCall[]+}++export interface OllamaChatRequest {+ model: string+ messages: OllamaRequestMessage[]+ stream: boolean+ keep_alive: string+ tools?: ToolDefinition[]+ options?: OllamaRequestOptions+ /** Tri-state; deleted again on the 400-retry, hence optional. */+ think?: boolean+}+interface OllamaChatChunk {- message?: { content: string; thinking?: string; tool_calls?: { function: { name: string; arguments: Record<string, any> } }[] }+ message?: { content?: string; thinking?: string; tool_calls?: OllamaWireToolCall[] }done?: boolean// Why generation ended ('stop' | 'length' | 'load' | …), final chunk only.done_reason?: string@@ -95,12 +129,12 @@ export class OllamaProvider implements ProviderClient {toolRole: 'text',alternate: true,}).map(m => {- const msg: Record<string, any> = { role: m.role, content: m.content }+ const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.images?.length) msg.images = m.images.map(img => img.data)return msg})- const body: Record<string, any> = {+ const body: OllamaChatRequest = {model,messages: ollamaMessages,stream: true,@@ -116,7 +150,7 @@ export class OllamaProvider implements ProviderClient {// Laptop + gemma3:4b). Letting Ollama do its own VRAM-aware layer// placement restores CLI parity on tight cards and is a no-op on// cards with headroom.- const ollamaOptions: Record<string, any> = {}+ const ollamaOptions: OllamaRequestOptions = {}if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperatureif (options?.topP !== undefined) ollamaOptions.top_p = options.topPif (options?.topK !== undefined) ollamaOptions.top_k = options.topK@@ -198,8 +232,18 @@ export class OllamaProvider implements ProviderClient {throw new Error(`Ollama: ${errLine}`)}+ // `arguments` arrives as `unknown` from the wire because Ollama is+ // not the only thing that answers on this endpoint: llama.cpp-based+ // and proxied servers send the field as a JSON *string*, and this+ // path used to hand that string on as `Record<string, any>` — a lie+ // `any` was covering for. repairToolCallArgs is the same+ // normalization the non-streaming path below already performs; for a+ // real object it returns the object untouched.const toolCalls: ToolCall[] | undefined = chunk.message?.tool_calls?.map(tc => ({- function: { name: tc.function.name, arguments: tc.function.arguments },+ function: {+ name: tc.function?.name ?? '',+ arguments: repairToolCallArgs(tc.function?.arguments),+ },}))if (chunk.done) sawDone = true@@ -254,13 +298,13 @@ export class OllamaProvider implements ProviderClient {toolRole: tools.length > 0 ? 'native' : 'text',alternate: tools.length === 0,}).map(m => {- const msg: Record<string, any> = { role: m.role, content: m.content }+ const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.tool_calls) msg.tool_calls = m.tool_callsif (m.images?.length) msg.images = m.images.map(img => img.data)return msg})- const body: Record<string, any> = {+ const body: OllamaChatRequest = {model,messages: ollamaMessages,tools,@@ -270,7 +314,7 @@ export class OllamaProvider implements ProviderClient {}// v2.4.6 Bug L: see chatStream() above — same num_gpu:99 removal.- const ollamaOptions: Record<string, any> = {}+ const ollamaOptions: OllamaRequestOptions = {}if (options?.temperature !== undefined) ollamaOptions.temperature = options.temperatureif (options?.topP !== undefined) ollamaOptions.top_p = options.topPif (options?.topK !== undefined) ollamaOptions.top_k = options.topK@@ -288,8 +332,9 @@ export class OllamaProvider implements ProviderClient {if (options?.thinking === true) body.think = trueelse if (options?.thinking === false) body.think = false- const fetchOptions = (bodyObj: Record<string, any>): any => {- const opts: any = {+ type LocalFetchInit = NonNullable<Parameters<typeof localFetch>[1]>+ const fetchOptions = (bodyObj: OllamaChatRequest): LocalFetchInit => {+ const opts: LocalFetchInit = {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(bodyObj),@@ -308,28 +353,39 @@ export class OllamaProvider implements ProviderClient {throw await this.buildError(res, 'Tool calling failed', model)}- const data = await res.json()- let toolCalls: ToolCall[] = (data.message?.tool_calls || []).map((tc: any) => ({- function: { name: tc.function.name, arguments: repairToolCallArgs(tc.function.arguments) },- }))+ // Boundary: everything below reads a body we did not produce, so each+ // field is checked on the way out of `unknown` instead of being asserted+ // into a shape.+ const data: unknown = await res.json()+ const message = prop(data, 'message')+ const content = asString(prop(message, 'content')) || ''+ let toolCalls: ToolCall[] = asRecordArray(prop(message, 'tool_calls')).map(tc => {+ const fn = prop(tc, 'function')+ return {+ function: {+ name: asString(prop(fn, 'name')) ?? '',+ arguments: repairToolCallArgs(isRecord(fn) ? fn.arguments : undefined),+ },+ }+ })// If no tool calls found but content looks like a tool call, try to extract- if (toolCalls.length === 0 && data.message?.content) {- const extracted = extractToolCallsFromContent(data.message.content)+ if (toolCalls.length === 0 && content) {+ const extracted = extractToolCallsFromContent(content)if (extracted.length > 0) {toolCalls = extracted.map(tc => ({ function: tc }))}}return {- content: data.message?.content || '',- thinking: data.message?.thinking || '',+ content,+ thinking: asString(prop(message, 'thinking')) || '',toolCalls,// Real token usage from the non-streaming response, same fields// chatStream() already forwards — without them the agent TokenCounter// falls back to a char/4 estimate for every Ollama tool turn.- promptEvalCount: data.prompt_eval_count,- evalCount: data.eval_count,+ promptEvalCount: asNumber(prop(data, 'prompt_eval_count')),+ evalCount: asNumber(prop(data, 'eval_count')),}}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 597d87bb..d834f3e4 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -23,6 +23,10 @@ import { parseRetryAfter } from '../../lib/http-status'import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'import { applyTemplateContract } from './normalize-system'+import {+ parseOpenAIStreamChunk, parseOpenAIChatResponse,+ prop, asString, asNumber, asBoolean, asRecordArray,+} from './wire'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared// host helpers in backend.ts. A direct webview fetch only works for hosts the@@ -32,41 +36,73 @@ import { applyTemplateContract } from './normalize-system'// probing), which must not follow the transport decision.// ── OpenAI API Types ───────────────────────────────────────────+//+// What comes BACK lives in ./wire, behind checked parsers. It used to be+// declared here as two hand-rolled interfaces asserted onto `JSON.parse` and+// `res.json()`, and both said things the code itself knew to be false: the+// tool-call delta declared `index: number` as required while the accumulator+// right below it falls back to `keyForUnindexedDelta` precisely because+// servers omit it, and `choices` was typed as a one-element tuple.-interface OpenAIStreamChunk {- choices?: [{- delta?: {- content?: string- // Native reasoning channel — DeepInfra (LU Cloud) reasoning models- // stream thinking as `reasoning_content`, some as `reasoning`.- reasoning_content?: string- reasoning?: string- tool_calls?: {- index: number- id?: string- function?: { name?: string; arguments?: string }- }[]- }- finish_reason?: string | null- }]+/**+ * What we SEND to `/v1/chat/completions`.+ *+ * A real shape, not a `Record<string, any>` bag: the ladder in `sendChat`+ * reads and deletes four of these fields by name, and under `any` a typo in+ * one of those names would have compiled into a request that silently kept+ * the parameter the server just refused.+ */+export interface OpenAIContentPart {+ type: 'text' | 'image_url'+ text?: string+ image_url?: { url: string }}-interface OpenAIResponse {- choices?: [{- message?: {- content?: string- reasoning_content?: string- reasoning?: string- tool_calls?: {- id: string- type: 'function'- function: { name: string; arguments: string }- }[]- }- finish_reason?: string- }]+export interface OpenAIRequestToolCall {+ id: string+ type: 'function'+ function: { name: string; arguments: string }}+export interface OpenAIRequestMessage {+ role: ChatMessage['role']+ content: string | OpenAIContentPart[]+ tool_calls?: OpenAIRequestToolCall[]+ tool_call_id?: string+}++export interface OpenAIChatRequest {+ model: string+ messages: OpenAIRequestMessage[]+ stream: boolean+ temperature?: number+ top_p?: number+ max_tokens?: number+ tools?: ToolDefinition[]+ tool_choice?: 'auto' | 'none' | 'required'+ /** 'high' | 'minimal' | 'none' — stepped down, then deleted, by sendChat. */+ reasoning_effort?: string+ chat_template_kwargs?: Record<string, unknown>+ stream_options?: { include_usage: boolean }+}++/**+ * The two transports this provider posts through: the browser `fetch` and+ * `localFetch`/`localFetchStream` (Rust proxy). Both satisfy this narrower+ * signature, which is what removes the `fetcher as any` casts that used to+ * bridge them — a cast that would equally have accepted a function taking no+ * arguments at all.+ */+type ChatFetcher = (+ url: string,+ init: {+ method?: string+ headers?: Record<string, string>+ body?: string+ signal?: AbortSignal+ },+) => Promise<Response>+interface OpenAIModelEntry {id: stringobject: string@@ -87,6 +123,32 @@ interface OpenAIModelEntry {think?: 'toggle' | 'always' | 'never'}+/**+ * Build a catalogue entry out of one `/v1/models` element, checking every+ * field on the way. `think` is validated against the three values the rest of+ * the app switches on — a server sending anything else must not smuggle a+ * fourth mode into the model picker.+ */+function toModelEntry(m: Record<string, unknown>): OpenAIModelEntry {+ const think = asString(m.think)+ return {+ // A catalogue row with no string id is unusable downstream (it keys+ // KNOWN_CONTEXT and every heuristic); '' keeps the row and keeps+ // guessContextFromName from being handed a non-string.+ id: asString(m.id) ?? '',+ object: asString(m.object) ?? 'model',+ created: asNumber(m.created),+ owned_by: asString(m.owned_by),+ name: asString(m.name),+ context_length: asNumber(m.context_length),+ input_modalities: Array.isArray(m.input_modalities)+ ? m.input_modalities.filter((x): x is string => typeof x === 'string')+ : undefined,+ supports_tools: asBoolean(m.supports_tools),+ think: think === 'toggle' || think === 'always' || think === 'never' ? think : undefined,+ }+}+// ── Known context lengths for popular models ───────────────────const KNOWN_CONTEXT: Record<string, number> = {@@ -215,7 +277,7 @@ function measurePayload(value: unknown): { chars: number; images: number } {return ''}if (val && typeof val === 'object' && !Array.isArray(val)) {- const part = val as Record<string, any>+ const part = val as Record<string, unknown>if (part.type === 'image_url') {images++return { type: 'image_url' }@@ -403,9 +465,9 @@ export class OpenAIProvider implements ProviderClient {*/private async sendChat(model: string,- body: Record<string, any>,+ body: OpenAIChatRequest,signal: AbortSignal | undefined,- fetcher: (url: string, init: any) => Promise<Response>,+ fetcher: ChatFetcher,): Promise<Response> {// Sanierungspfad: a throttle or a gateway hiccup is not the request's// fault, and the user used to read the raw status line for it. The retry@@ -422,7 +484,7 @@ export class OpenAIProvider implements ProviderClient {)const refused = (res: Response) => !res.ok && (res.status === 400 || res.status === 422)- const asked = body.reasoning_effort as string | undefined+ const asked = body.reasoning_effortconst lane: 'on' | 'off' | undefined =asked === undefined ? undefined : asked === 'high' ? 'on' : 'off'@@ -459,7 +521,7 @@ export class OpenAIProvider implements ProviderClient {}if (res.ok && lane) {- const survived = body.reasoning_effort as string | undefined+ const survived = body.reasoning_effortif (survived === undefined) this.rememberEffort(model, lane, 'omit')else if (survived !== asked) this.rememberEffort(model, lane, 'minimal')}@@ -509,7 +571,7 @@ export class OpenAIProvider implements ProviderClient {*/private async applyMaxTokens(model: string,- body: Record<string, any>,+ body: OpenAIChatRequest,options?: ChatOptions,): Promise<void> {const requested = options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 0@@ -549,7 +611,7 @@ export class OpenAIProvider implements ProviderClient {messages: ChatMessage[],options?: ChatOptions,): AsyncGenerator<ChatStreamChunk> {- const body: Record<string, any> = {+ const body: OpenAIChatRequest = {model,// Bug B3: one system message, first. The built-in engine and LM Studio// render the model's own Jinja template, which raises "System message@@ -600,7 +662,7 @@ export class OpenAIProvider implements ProviderClient {const guard = idleAbortGuard(options?.signal)let res: Responsetry {- res = await this.sendChat(model, body, guard.signal, fetcher as any)+ res = await this.sendChat(model, body, guard.signal, fetcher)if (!res.ok) throw await this.parseError(res)} catch (err) {// Nothing to watch — drop the listener on the caller's signal here, the@@ -633,12 +695,14 @@ export class OpenAIProvider implements ProviderClient {return}- let chunk: OpenAIStreamChunk+ let raw: unknowntry {- chunk = JSON.parse(event.data)+ raw = JSON.parse(event.data)} catch {continue}+ // Boundary: from here on every field has been checked, not asserted.+ const chunk = parseOpenAIStreamChunk(raw)// LM Studio (and some OpenAI-compat servers) report a mid-stream failure// as a 200 response carrying an SSE error chunk ({ error: { message } } or@@ -648,14 +712,18 @@ export class OpenAIProvider implements ProviderClient {// thrown error so the chat layer can map it to a friendly message (e.g.// the #67 image-on-text-model case). Verified live: LM Studio + image on a// text-only model returns `event: error` with HTTP 200 (2026-06-21).- const streamErr = (chunk as { error?: { message?: string } | string }).error+ const streamErr = chunk.errorif (streamErr) {- throw new Error(typeof streamErr === 'string' ? streamErr : (streamErr.message || 'Streaming error'))+ throw new Error(+ typeof streamErr === 'string'+ ? streamErr+ : (asString(prop(streamErr, 'message')) || 'Streaming error'),+ )}// Real token usage — the include_usage final chunk carries `usage` with// an empty choices[], so capture it BEFORE the choice guard below.- const u = (chunk as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage+ const u = chunk.usageif (u) {promptTokens = u.prompt_tokens || promptTokenscompletionTokens = u.completion_tokens || completionTokens@@ -745,7 +813,7 @@ export class OpenAIProvider implements ProviderClient {tools: ToolDefinition[],options?: ChatOptions,): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number; thinking?: string }> {- const body: Record<string, any> = {+ const body: OpenAIChatRequest = {model,// Bug B3: same invariant as chatStream, see providers/normalize-system.ts.messages: this.templateContract(messages, tools.length > 0).map(m => this.toOpenAIMessage(m)),@@ -773,31 +841,34 @@ export class OpenAIProvider implements ProviderClient {if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)const fetcher = this.useLocalProxy ? localFetch : fetch- const res = await this.sendChat(model, body, options?.signal, fetcher as any)+ const res = await this.sendChat(model, body, options?.signal, fetcher)if (!res.ok) {throw await this.parseError(res, tools.length > 0)}- const data: OpenAIResponse = await res.json()- const choice = data.choices?.[0]+ // Boundary: the body is foreign, so it goes through the checked parser+ // rather than an `as OpenAIResponse` that would break on the first+ // tool-call the server sends without a `function` object.+ const data = parseOpenAIChatResponse(await res.json())+ const message = data.message- const toolCalls: ToolCall[] = (choice?.message?.tool_calls || []).map(tc => ({+ const toolCalls: ToolCall[] = (message?.tool_calls || []).map(tc => ({id: tc.id,function: {- name: tc.function.name,- arguments: this.safeParseArgs(tc.function.arguments),+ name: tc.function?.name ?? '',+ arguments: this.safeParseArgs(tc.function?.arguments ?? ''),},}))// Real consumed-context usage (non-streaming response carries it directly).- const usage = (data as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage+ const usage = data.usagereturn {- content: choice?.message?.content || '',+ content: message?.content || '',toolCalls,promptEvalCount: usage?.prompt_tokens,evalCount: usage?.completion_tokens,- thinking: choice?.message?.reasoning_content || choice?.message?.reasoning || undefined,+ thinking: message?.reasoning_content || message?.reasoning || undefined,}}@@ -806,14 +877,18 @@ export class OpenAIProvider implements ProviderClient {const fetcher = this.useLocalProxy ? localFetch : fetchconst res = await fetcher(`${this.baseUrl}/models`, {headers: this.headers,- } as any)+ })if (!res.ok) {throw await this.parseError(res)}- const data = await res.json()- const models: OpenAIModelEntry[] = data.data || data.models || []+ const body: unknown = await res.json()+ // Both spellings are in the wild (`data` in the OpenAI spec, `models` on+ // some compat servers); anything that is not an array of objects yields+ // an empty catalogue instead of blowing up the model picker.+ const rawList = prop(body, 'data') ?? prop(body, 'models')+ const models: OpenAIModelEntry[] = asRecordArray(rawList).map(toModelEntry)// Bug K: fuer lokale Backends (LM Studio etc.) probe das wahre// Context-Limit vom Server. Sonst zeigen wir 8K obwohl das Modell 32K+@@ -873,7 +948,7 @@ export class OpenAIProvider implements ProviderClient {const fetcher = this.useLocalProxy ? localFetch : fetchconst res = await fetcher(`${this.baseUrl}/models`, {headers: this.headers,- } as any)+ })return res.ok} catch {return false@@ -1128,18 +1203,18 @@ export class OpenAIProvider implements ProviderClient {// ── Message conversion ───────────────────────────────────────- private toOpenAIMessage(msg: ChatMessage): Record<string, any> {+ private toOpenAIMessage(msg: ChatMessage): OpenAIRequestMessage {// If message has images, use content array format- let content: any = msg.content+ let content: string | OpenAIContentPart[] = msg.contentif (msg.images?.length && msg.role === 'user') {- const parts: any[] = []+ const parts: OpenAIContentPart[] = []for (const img of msg.images) {parts.push({ type: 'image_url', image_url: { url: `data:${img.mimeType};base64,${img.data}` } })}parts.push({ type: 'text', text: msg.content })content = parts}- const m: Record<string, any> = { role: msg.role, content }+ const m: OpenAIRequestMessage = { role: msg.role, content }if (msg.tool_calls) {m.tool_calls = msg.tool_calls.map(tc => ({@@ -1180,13 +1255,24 @@ export class OpenAIProvider implements ProviderClient {return calls}- private safeParseArgs(args: string): Record<string, any> {+ /**+ * A tool call's `arguments` is a JSON *string* on the wire and the caller is+ * a language model, so nothing guarantees it decodes to an object. The+ * happy path used to return whatever JSON.parse produced under a+ * `Record<string, any>` annotation — `"null"` therefore handed `null` to+ * every downstream `args.foo` read, and `"[1,2]"` / `"42"` handed on a+ * value with none of the promised keys. Both branches now apply the same+ * object check the repair branch always had.+ */+ private safeParseArgs(args: string): Record<string, unknown> {try {- return JSON.parse(args)+ const parsed: unknown = JSON.parse(args)+ if (parsed && typeof parsed === 'object') return parsed as Record<string, unknown>} catch {- const repaired = repairJson(args)- return repaired && typeof repaired === 'object' ? repaired : {}+ // fall through to the repair path below}+ const repaired: unknown = repairJson(args)+ return repaired && typeof repaired === 'object' ? repaired as Record<string, unknown> : {}}// ── Error parsing ────────────────────────────────────────────diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex 64888b92..53a5ef33 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -129,7 +129,7 @@ export interface ToolCall {id?: string // OpenAI requires this, Ollama doesn'tfunction: {name: string- arguments: Record<string, any>+ arguments: Record<string, unknown>}}@@ -190,7 +190,7 @@ export interface ToolDefinition {description: stringparameters: {type: 'object'- properties: Record<string, any>+ properties: Record<string, unknown>required: string[]}}diff --git a/src/api/providers/wire.ts b/src/api/providers/wire.tsnew file mode 100644index 00000000..f430a574--- /dev/null+++ b/src/api/providers/wire.ts@@ -0,0 +1,382 @@+/**+ * Wire shapes and boundary guards for the three foreign HTTP APIs the+ * providers talk to (Ollama, OpenAI-compatible, Anthropic).+ *+ * Everything in here describes data we did NOT produce. `res.json()` hands+ * back `unknown`; the helpers below are the only sanctioned way to walk into+ * it. They check before they claim: `isRecord` before a property read,+ * `Array.isArray` before an iteration, `typeof` before a string/number is+ * handed on. That is the difference between "the server said so" and "we+ * assumed so and it happened to hold".+ *+ * Deliberately dependency-free (no zod, no imports from the providers) so it+ * stays a leaf module and cannot participate in an import cycle.+ */++// ── Primitive accessors ────────────────────────────────────────++/** True for a plain object we may index. Arrays and null are rejected. */+export function isRecord(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v)+}++/** Read a property without asserting anything about the container. */+export function prop(v: unknown, key: string): unknown {+ return isRecord(v) ? v[key] : undefined+}++/** Follow a property path, giving up (undefined) at the first non-record. */+export function propPath(v: unknown, ...keys: string[]): unknown {+ let cur: unknown = v+ for (const k of keys) {+ if (!isRecord(cur)) return undefined+ cur = cur[k]+ }+ return cur+}++export function asString(v: unknown): string | undefined {+ return typeof v === 'string' ? v : undefined+}++export function asNumber(v: unknown): number | undefined {+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined+}++export function asBoolean(v: unknown): boolean | undefined {+ return typeof v === 'boolean' ? v : undefined+}++/** Array of records, or [] — the shape every "list" endpoint claims to send. */+export function asRecordArray(v: unknown): Record<string, unknown>[] {+ return Array.isArray(v) ? v.filter(isRecord) : []+}++/** Array of strings, or [] — e.g. Ollama's `capabilities`. */+export function asStringArray(v: unknown): string[] {+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []+}++// ── Ollama: /api/chat ──────────────────────────────────────────++/**+ * A tool call as Ollama emits it. `arguments` arrives as an already-parsed+ * object (unlike OpenAI, which sends a JSON string), so it is only ever+ * `unknown` until a caller decides what it wants from it.+ */+export interface OllamaWireToolCall {+ function?: {+ name?: string+ arguments?: unknown+ }+}++/** One NDJSON line of Ollama's streaming `/api/chat` response. */+export interface OllamaChatChunk {+ message?: {+ content?: string+ thinking?: string+ tool_calls?: OllamaWireToolCall[]+ }+ done?: boolean+ done_reason?: string+ eval_count?: number+ prompt_eval_count?: number+ eval_duration?: number+ error?: string+}++/** Parse one NDJSON line into the fields we actually read, checking each. */+export function parseOllamaChatChunk(raw: unknown): OllamaChatChunk {+ const msg = prop(raw, 'message')+ const toolCalls = prop(msg, 'tool_calls')+ return {+ message: isRecord(msg)+ ? {+ content: asString(msg.content),+ thinking: asString(msg.thinking),+ tool_calls: Array.isArray(toolCalls)+ ? toolCalls.filter(isRecord).map((tc): OllamaWireToolCall => {+ const fn = prop(tc, 'function')+ return isRecord(fn)+ ? { function: { name: asString(fn.name), arguments: fn.arguments } }+ : {}+ })+ : undefined,+ }+ : undefined,+ done: asBoolean(prop(raw, 'done')),+ done_reason: asString(prop(raw, 'done_reason')),+ eval_count: asNumber(prop(raw, 'eval_count')),+ prompt_eval_count: asNumber(prop(raw, 'prompt_eval_count')),+ eval_duration: asNumber(prop(raw, 'eval_duration')),+ error: asString(prop(raw, 'error')),+ }+}++// ── OpenAI-compatible: /v1/chat/completions ────────────────────++/**+ * One tool-call delta of an OpenAI SSE stream. Every field is optional on+ * purpose: the protocol splits a single call across many chunks — the first+ * carries `id`/`function.name`, the rest only append to+ * `function.arguments`, and `index` is the only thing tying them together.+ */+export interface OpenAIToolCallDelta {+ index?: number+ id?: string+ type?: string+ function?: {+ name?: string+ /** JSON *text*, streamed in fragments. Never an object. */+ arguments?: string+ }+}++/** The non-streaming form: `arguments` is complete JSON text. */+export interface OpenAIToolCall {+ id?: string+ type?: string+ function?: {+ name?: string+ arguments?: string+ }+}++export interface OpenAIUsage {+ prompt_tokens?: number+ completion_tokens?: number+ total_tokens?: number+}++/** `choices[].delta` of a streaming chunk. */+export interface OpenAIStreamDelta {+ role?: string+ content?: string+ /** Non-standard but widely used: DeepSeek/vLLM/LM Studio reasoning output. */+ reasoning_content?: string+ /** OpenRouter's spelling of the same thing. */+ reasoning?: string+ tool_calls?: OpenAIToolCallDelta[]+}++export interface OpenAIStreamChunk {+ choices?: {+ delta?: OpenAIStreamDelta+ finish_reason?: string | null+ }[]+ usage?: OpenAIUsage+ error?: unknown+}++function parseToolCallDeltas(v: unknown): OpenAIToolCallDelta[] | undefined {+ if (!Array.isArray(v)) return undefined+ return v.filter(isRecord).map((tc): OpenAIToolCallDelta => {+ const fn = prop(tc, 'function')+ return {+ index: asNumber(tc.index),+ id: asString(tc.id),+ type: asString(tc.type),+ function: isRecord(fn)+ ? { name: asString(fn.name), arguments: asString(fn.arguments) }+ : undefined,+ }+ })+}++/** Parse one `data:` payload of an OpenAI-compatible SSE stream. */+export function parseOpenAIStreamChunk(raw: unknown): OpenAIStreamChunk {+ const choices = prop(raw, 'choices')+ const usage = prop(raw, 'usage')+ return {+ choices: Array.isArray(choices)+ ? choices.filter(isRecord).map((c) => {+ const delta = prop(c, 'delta')+ const finish = c.finish_reason+ return {+ delta: isRecord(delta)+ ? {+ role: asString(delta.role),+ content: asString(delta.content),+ reasoning_content: asString(delta.reasoning_content),+ reasoning: asString(delta.reasoning),+ tool_calls: parseToolCallDeltas(delta.tool_calls),+ }+ : undefined,+ finish_reason: typeof finish === 'string' ? finish : null,+ }+ })+ : undefined,+ usage: isRecord(usage)+ ? {+ prompt_tokens: asNumber(usage.prompt_tokens),+ completion_tokens: asNumber(usage.completion_tokens),+ total_tokens: asNumber(usage.total_tokens),+ }+ : undefined,+ error: prop(raw, 'error'),+ }+}++/** `choices[0].message` of a non-streaming completion. */+export interface OpenAIResponseMessage {+ content?: string+ reasoning_content?: string+ reasoning?: string+ tool_calls?: OpenAIToolCall[]+}++export interface OpenAIChatResponse {+ message?: OpenAIResponseMessage+ finish_reason?: string+ usage?: OpenAIUsage+}++/** Parse a non-streaming `/v1/chat/completions` body. */+export function parseOpenAIChatResponse(raw: unknown): OpenAIChatResponse {+ const choice = asRecordArray(prop(raw, 'choices'))[0]+ const message = prop(choice, 'message')+ const usage = prop(raw, 'usage')+ const toolCalls = prop(message, 'tool_calls')+ return {+ message: isRecord(message)+ ? {+ content: asString(message.content),+ reasoning_content: asString(message.reasoning_content),+ reasoning: asString(message.reasoning),+ tool_calls: Array.isArray(toolCalls)+ ? toolCalls.filter(isRecord).map((tc): OpenAIToolCall => {+ const fn = prop(tc, 'function')+ return {+ id: asString(tc.id),+ type: asString(tc.type),+ function: isRecord(fn)+ ? { name: asString(fn.name), arguments: asString(fn.arguments) }+ : undefined,+ }+ })+ : undefined,+ }+ : undefined,+ finish_reason: asString(prop(choice, 'finish_reason')),+ usage: isRecord(usage)+ ? {+ prompt_tokens: asNumber(usage.prompt_tokens),+ completion_tokens: asNumber(usage.completion_tokens),+ total_tokens: asNumber(usage.total_tokens),+ }+ : undefined,+ }+}++// ── Anthropic: /v1/messages ────────────────────────────────────++/**+ * One SSE event of Anthropic's streaming Messages API. The interesting+ * fields live at three different depths depending on `type`, which is why+ * this stays a flat optional bag rather than a discriminated union: the+ * provider reads them defensively and a new event type must not throw.+ */+export interface AnthropicStreamEvent {+ type?: string+ index?: number+ /** `content_block_start` — the block being opened. */+ content_block?: {+ type?: string+ id?: string+ name?: string+ }+ /** `content_block_delta` — the payload appended to that block. */+ delta?: {+ type?: string+ text?: string+ thinking?: string+ partial_json?: string+ stop_reason?: string+ }+ /** `message_start` carries input tokens, `message_delta` the output count. */+ message?: {+ usage?: AnthropicUsage+ }+ usage?: AnthropicUsage+ error?: {+ type?: string+ message?: string+ }+}++export interface AnthropicUsage {+ input_tokens?: number+ output_tokens?: number+}++function parseAnthropicUsage(v: unknown): AnthropicUsage | undefined {+ if (!isRecord(v)) return undefined+ return {+ input_tokens: asNumber(v.input_tokens),+ output_tokens: asNumber(v.output_tokens),+ }+}++/** Parse one `data:` payload of an Anthropic SSE stream. */+export function parseAnthropicStreamEvent(raw: unknown): AnthropicStreamEvent {+ const block = prop(raw, 'content_block')+ const delta = prop(raw, 'delta')+ const message = prop(raw, 'message')+ const error = prop(raw, 'error')+ return {+ type: asString(prop(raw, 'type')),+ index: asNumber(prop(raw, 'index')),+ content_block: isRecord(block)+ ? { type: asString(block.type), id: asString(block.id), name: asString(block.name) }+ : undefined,+ delta: isRecord(delta)+ ? {+ type: asString(delta.type),+ text: asString(delta.text),+ thinking: asString(delta.thinking),+ partial_json: asString(delta.partial_json),+ stop_reason: asString(delta.stop_reason),+ }+ : undefined,+ message: isRecord(message)+ ? { usage: parseAnthropicUsage(message.usage) }+ : undefined,+ usage: parseAnthropicUsage(prop(raw, 'usage')),+ error: isRecord(error)+ ? { type: asString(error.type), message: asString(error.message) }+ : undefined,+ }+}++/** One entry of a non-streaming `/v1/messages` `content` array. */+export interface AnthropicContentBlock {+ type?: string+ text?: string+ thinking?: string+ id?: string+ name?: string+ input?: unknown+}++export interface AnthropicMessageResponse {+ content: AnthropicContentBlock[]+ stop_reason?: string+ usage?: AnthropicUsage+}++/** Parse a non-streaming `/v1/messages` body. */+export function parseAnthropicMessageResponse(raw: unknown): AnthropicMessageResponse {+ return {+ content: asRecordArray(prop(raw, 'content')).map((b): AnthropicContentBlock => ({+ type: asString(b.type),+ text: asString(b.text),+ thinking: asString(b.thinking),+ id: asString(b.id),+ name: asString(b.name),+ input: b.input,+ })),+ stop_reason: asString(prop(raw, 'stop_reason')),+ usage: parseAnthropicUsage(prop(raw, 'usage')),+ }+}diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 158d1666..8df92495 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -1817,7 +1817,14 @@ export function useCodex() {// workDir=D:/Pictures/foo, p=D:/Pictures/foo/bar.html →// D:/Pictures/foo/D:/Pictures/foo/bar.html// which then grew further on retry as the model re-emitted the path.- if ((toolName === 'file_read' || toolName === 'file_write' || toolName === 'file_edit' || toolName === 'file_list' || toolName === 'file_search') && toolArgs.path) {+ // `path` is whatever the MODEL put in the tool call, so it is only a+ // string when the model made it one. The old annotation asserted it+ // (`const p: string = toolArgs.path` on an `any`), and a call that+ // sent a number or an object went straight into `p.startsWith` and+ // threw a TypeError out of the tool loop. Checking it here lets such+ // a call reach the tool, which rejects it with its own message.+ // The truthiness of the old guard is kept: '' still skips.+ if ((toolName === 'file_read' || toolName === 'file_write' || toolName === 'file_edit' || toolName === 'file_list' || toolName === 'file_search') && typeof toolArgs.path === 'string' && toolArgs.path) {const p: string = toolArgs.pathconst isAbsolute =/^[a-zA-Z]:[/\\]/.test(p) || // Windows drive letter: C:/ D:\ etc.