Skip to content

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.

Phase 4: Structured args validation + Ollama format capability probe (v2.4.0)

PurpleDoubleD7595c9275ab8
diff --git a/src/api/agents/__tests__/args-validator.test.ts b/src/api/agents/__tests__/args-validator.test.ts
new file mode 100644
index 00000000..e07799ba
--- /dev/null
+++ b/src/api/agents/__tests__/args-validator.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest'
+import {
+ validateToolArgs,
+ formatValidationErrors,
+ type JsonSchema,
+} from '../args-validator'
+
+const strictStringSchema: JsonSchema = {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'search' },
+ maxResults: { type: 'number', description: 'max' },
+ },
+ required: ['query'],
+}
+
+describe('args-validator — validateToolArgs', () => {
+ it('accepts empty schema as advisory (valid)', () => {
+ const r = validateToolArgs({ whatever: 1 }, undefined as any)
+ expect(r.valid).toBe(true)
+ })
+
+ it('accepts valid args', () => {
+ const r = validateToolArgs({ query: 'hello', maxResults: 5 }, strictStringSchema)
+ expect(r.valid).toBe(true)
+ expect(r.errors).toEqual([])
+ })
+
+ it('reports missing required property', () => {
+ const r = validateToolArgs({ maxResults: 5 }, strictStringSchema)
+ expect(r.valid).toBe(false)
+ expect(r.errors).toHaveLength(1)
+ expect(r.errors[0].path).toBe('query')
+ expect(r.errors[0].message).toMatch(/required/)
+ })
+
+ it('reports wrong property type', () => {
+ const r = validateToolArgs({ query: 42 }, strictStringSchema)
+ expect(r.valid).toBe(false)
+ expect(r.errors[0].message).toMatch(/string/)
+ })
+
+ it('coerces string "5" → number 5 on number field', () => {
+ const r = validateToolArgs({ query: 'x', maxResults: '5' }, strictStringSchema)
+ expect(r.valid).toBe(true)
+ expect(r.coerced?.maxResults).toBe(5)
+ })
+
+ it('does not coerce unparseable string → number', () => {
+ const r = validateToolArgs({ query: 'x', maxResults: 'five' }, strictStringSchema)
+ expect(r.valid).toBe(false)
+ })
+
+ it('coerces "true" / "false" → boolean on boolean field', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { recursive: { type: 'boolean' }, path: { type: 'string' } },
+ required: ['path'],
+ }
+ const r = validateToolArgs({ path: 'x', recursive: 'true' }, schema)
+ expect(r.valid).toBe(true)
+ expect(r.coerced?.recursive).toBe(true)
+ })
+
+ it('enforces enum values', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { language: { type: 'string', enum: ['python', 'shell'] } },
+ required: [],
+ }
+ expect(validateToolArgs({ language: 'python' }, schema).valid).toBe(true)
+ const bad = validateToolArgs({ language: 'ruby' }, schema)
+ expect(bad.valid).toBe(false)
+ expect(bad.errors[0].message).toMatch(/one of/)
+ })
+
+ it('validates integer type strictly', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { n: { type: 'integer' } },
+ required: ['n'],
+ }
+ expect(validateToolArgs({ n: 5 }, schema).valid).toBe(true)
+ expect(validateToolArgs({ n: 5.5 }, schema).valid).toBe(false)
+ // String "5.5" will not coerce to integer.
+ expect(validateToolArgs({ n: '5.5' }, schema).valid).toBe(false)
+ // String "7" will coerce to integer.
+ const r = validateToolArgs({ n: '7' }, schema)
+ expect(r.valid).toBe(true)
+ expect(r.coerced?.n).toBe(7)
+ })
+
+ it('ignores unknown type keywords (advisory-only)', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { x: { type: 'weird-type' as any } },
+ required: [],
+ }
+ expect(validateToolArgs({ x: 'anything' }, schema).valid).toBe(true)
+ })
+
+ it('reports all errors, not just the first', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ a: { type: 'string' },
+ b: { type: 'number' },
+ },
+ required: ['a', 'b'],
+ }
+ const r = validateToolArgs({}, schema)
+ expect(r.valid).toBe(false)
+ expect(r.errors).toHaveLength(2)
+ })
+
+ it('handles null/undefined property values as missing', () => {
+ const r = validateToolArgs({ query: null }, strictStringSchema)
+ expect(r.valid).toBe(false)
+ })
+
+ it('does not fail on extra properties', () => {
+ const r = validateToolArgs({ query: 'x', extraKey: 42 }, strictStringSchema)
+ expect(r.valid).toBe(true)
+ })
+
+ it('validates array items shallowly', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { tags: { type: 'array', items: { type: 'string' } } },
+ required: ['tags'],
+ }
+ expect(validateToolArgs({ tags: ['a', 'b'] }, schema).valid).toBe(true)
+ const bad = validateToolArgs({ tags: ['a', 5] }, schema)
+ expect(bad.valid).toBe(false)
+ expect(bad.errors[0].path).toMatch(/tags\[1\]/)
+ })
+
+ it('coerces single value → one-element array for array-typed params', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: { tags: { type: 'array', items: { type: 'string' } } },
+ required: ['tags'],
+ }
+ const r = validateToolArgs({ tags: 'only-one' }, schema)
+ expect(r.valid).toBe(true)
+ expect(r.coerced?.tags).toEqual(['only-one'])
+ })
+})
+
+describe('args-validator — formatValidationErrors', () => {
+ it('returns empty string for no errors', () => {
+ expect(formatValidationErrors([])).toBe('')
+ })
+
+ it('joins errors with semicolons', () => {
+ const out = formatValidationErrors([
+ { path: 'query', message: "required property 'query' is missing" },
+ { path: 'maxResults', message: 'expected number' },
+ ])
+ expect(out).toMatch(/query/)
+ expect(out).toMatch(/maxResults/)
+ expect(out).toContain(';')
+ })
+
+ it('omits empty-path prefix', () => {
+ const out = formatValidationErrors([{ path: '', message: 'top-level not object' }])
+ expect(out).toBe('top-level not object')
+ })
+})
diff --git a/src/api/agents/__tests__/format-capability.test.ts b/src/api/agents/__tests__/format-capability.test.ts
new file mode 100644
index 00000000..a79f2fe1
--- /dev/null
+++ b/src/api/agents/__tests__/format-capability.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import {
+ getFormatCapability,
+ markFormatSupported,
+ markFormatUnsupported,
+ clearFormatCapability,
+ resetFormatCapabilityCache,
+ probeFormatSupport,
+} from '../format-capability'
+
+// Minimal localStorage polyfill — tests run under vitest node env where
+// localStorage is absent. The module itself gracefully no-ops without it,
+// but we want to validate cache behaviour, so we install a stub.
+const installLocalStorageStub = () => {
+ const store: Record<string, string> = {}
+ ;(globalThis as any).localStorage = {
+ getItem: (k: string) => (k in store ? store[k] : null),
+ setItem: (k: string, v: string) => {
+ store[k] = v
+ },
+ removeItem: (k: string) => {
+ delete store[k]
+ },
+ clear: () => {
+ for (const k of Object.keys(store)) delete store[k]
+ },
+ }
+}
+
+describe('format-capability — cache', () => {
+ beforeEach(() => {
+ installLocalStorageStub()
+ resetFormatCapabilityCache()
+ })
+
+ it('returns "unknown" for a model never probed', () => {
+ expect(getFormatCapability('qwen3:8b')).toBe('unknown')
+ })
+
+ it('records supported and returns "supported"', () => {
+ markFormatSupported('qwen3:8b')
+ expect(getFormatCapability('qwen3:8b')).toBe('supported')
+ })
+
+ it('records unsupported and returns "unsupported" within TTL', () => {
+ markFormatUnsupported('oldmodel:latest')
+ expect(getFormatCapability('oldmodel:latest')).toBe('unsupported')
+ })
+
+ it('treats unsupported entries older than TTL as "unknown" (re-probe)', () => {
+ const past = Date.now() - 25 * 60 * 60 * 1000 // 25h ago, past 24h TTL
+ ;(globalThis as any).localStorage.setItem(
+ 'lu-format-capability-v1',
+ JSON.stringify({ 'oldmodel:latest': { capability: 'unsupported', checkedAt: past } })
+ )
+ expect(getFormatCapability('oldmodel:latest')).toBe('unknown')
+ })
+
+ it('clearFormatCapability removes a single entry', () => {
+ markFormatSupported('a')
+ markFormatSupported('b')
+ clearFormatCapability('a')
+ expect(getFormatCapability('a')).toBe('unknown')
+ expect(getFormatCapability('b')).toBe('supported')
+ })
+
+ it('isolates models by name', () => {
+ markFormatSupported('a')
+ markFormatUnsupported('b')
+ expect(getFormatCapability('a')).toBe('supported')
+ expect(getFormatCapability('b')).toBe('unsupported')
+ })
+
+ it('survives corrupted cache gracefully', () => {
+ ;(globalThis as any).localStorage.setItem('lu-format-capability-v1', '{not-json')
+ expect(getFormatCapability('a')).toBe('unknown')
+ // And subsequent writes overwrite cleanly.
+ markFormatSupported('a')
+ expect(getFormatCapability('a')).toBe('supported')
+ })
+})
+
+describe('format-capability — probeFormatSupport', () => {
+ beforeEach(() => {
+ installLocalStorageStub()
+ resetFormatCapabilityCache()
+ })
+
+ it('marks supported on HTTP 200 with parseable JSON response', async () => {
+ const fetchStub = vi.fn(async () =>
+ new Response(JSON.stringify({ response: '{"ok":true}' }), { status: 200 })
+ ) as any
+ const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
+ expect(result).toBe('supported')
+ expect(getFormatCapability('m')).toBe('supported')
+ })
+
+ it('marks unsupported on HTTP 200 but non-JSON response text', async () => {
+ const fetchStub = vi.fn(async () =>
+ new Response(JSON.stringify({ response: 'hello, not JSON' }), { status: 200 })
+ ) as any
+ const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
+ expect(result).toBe('unsupported')
+ expect(getFormatCapability('m')).toBe('unsupported')
+ })
+
+ it('marks unsupported on HTTP error status', async () => {
+ const fetchStub = vi.fn(async () =>
+ new Response('{"error":"bad"}', { status: 500 })
+ ) as any
+ const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
+ expect(result).toBe('unsupported')
+ })
+
+ it('marks unsupported on abort (timeout)', async () => {
+ const fetchStub = vi.fn((_url, opts: any) => {
+ return new Promise((_resolve, reject) => {
+ opts?.signal?.addEventListener('abort', () => {
+ const err: any = new Error('aborted')
+ err.name = 'AbortError'
+ reject(err)
+ })
+ })
+ }) as any
+ const result = await probeFormatSupport('m', 'http://localhost:11434', fetchStub)
+ expect(result).toBe('unsupported')
+ expect(getFormatCapability('m')).toBe('unsupported')
+ }, 10000)
+
+ it('re-throws on non-abort network errors (does not corrupt cache)', async () => {
+ const fetchStub = vi.fn(async () => {
+ throw new Error('ECONNREFUSED')
+ }) as any
+ await expect(
+ probeFormatSupport('m', 'http://localhost:11434', fetchStub)
+ ).rejects.toThrow('ECONNREFUSED')
+ expect(getFormatCapability('m')).toBe('unknown')
+ })
+
+ it('strips trailing slash from base URL', async () => {
+ const fetchStub = vi.fn(async (url: string) => {
+ expect(url).toBe('http://localhost:11434/api/generate')
+ return new Response(JSON.stringify({ response: '{"ok":1}' }), { status: 200 })
+ }) as any
+ await probeFormatSupport('m', 'http://localhost:11434/', fetchStub)
+ expect(fetchStub).toHaveBeenCalled()
+ })
+})
diff --git a/src/api/agents/args-validator.ts b/src/api/agents/args-validator.ts
new file mode 100644
index 00000000..8e2b9206
--- /dev/null
+++ b/src/api/agents/args-validator.ts
@@ -0,0 +1,245 @@
+/**
+ * Phase 4 (v2.4.0) — Hand-rolled JSON-Schema validator for tool arguments.
+ *
+ * Complements (does NOT replace) src/lib/tool-call-repair.ts:
+ * 1. repairToolCallArgs() runs first on raw string args from the provider.
+ * 2. validateToolArgs() runs after repair, comparing against the tool's
+ * inputSchema.
+ * 3. If invalid, the executor feeds a structured error back to the model
+ * ("Field 'query' is required but was missing. Please retry.") rather
+ * than silently running with bad data.
+ *
+ * Deliberately minimal — no ajv or @hyperjump/json-schema dependency. The
+ * tool schemas we ship are a small subset of JSON Schema:
+ * - types: string, number, integer, boolean, array, object, null
+ * - required: string[]
+ * - properties: Record<string, Schema>
+ * - enum: unknown[]
+ * - items: Schema (array element type)
+ * - additionalProperties: ignored (we never fail on extras)
+ *
+ * Unknown keywords are treated as advisory and skipped, which matches the
+ * behaviour of most loose validators and keeps the LLM from getting
+ * bogged down by schema keywords it cannot reason about.
+ */
+
+export type JsonSchema = {
+ type?: string | string[]
+ properties?: Record<string, JsonSchema>
+ required?: string[]
+ items?: JsonSchema
+ enum?: unknown[]
+ /** Unused / advisory; retained so test fixtures can include them. */
+ description?: string
+ /** Allow pass-through for unknown keys. */
+ [key: string]: any
+}
+
+export type ValidationError = {
+ path: string
+ message: string
+}
+
+export type ValidationResult = {
+ valid: boolean
+ errors: ValidationError[]
+ /** Coerced args — typed-string → number when schema calls for it. */
+ coerced?: Record<string, any>
+}
+
+/**
+ * Validate tool args against an inputSchema. Returns a shallow-coerced copy
+ * (string → number/boolean where schema asks for it) so small-model
+ * mistakes like `{"maxResults": "5"}` do not fail downstream calls.
+ */
+export function validateToolArgs(
+ args: Record<string, any>,
+ schema: JsonSchema | undefined
+): ValidationResult {
+ const errors: ValidationError[] = []
+ if (!schema || typeof schema !== 'object') {
+ return { valid: true, errors: [], coerced: args }
+ }
+
+ // Top-level must be an object schema for tool args. If the schema declares a
+ // different type, fall back to advisory-only validation.
+ if (schema.type && !matchesType(args, schema.type)) {
+ errors.push({ path: '', message: `expected ${describeType(schema.type)} at top level` })
+ return { valid: false, errors }
+ }
+
+ const coerced: Record<string, any> = { ...(args ?? {}) }
+
+ // Required presence.
+ if (Array.isArray(schema.required)) {
+ for (const key of schema.required) {
+ if (coerced[key] === undefined || coerced[key] === null) {
+ errors.push({ path: key, message: `required property '${key}' is missing` })
+ }
+ }
+ }
+
+ // Per-property type / enum / array items.
+ if (schema.properties) {
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
+ if (!(key in coerced)) continue
+ const value = coerced[key]
+ const { errors: propErrors, coerced: coercedValue } = validatePropertyValue(
+ key,
+ value,
+ propSchema
+ )
+ errors.push(...propErrors)
+ if (propErrors.length === 0) coerced[key] = coercedValue
+ }
+ }
+
+ return { valid: errors.length === 0, errors, coerced }
+}
+
+/**
+ * Render validation errors into a short, model-friendly string suitable
+ * for feeding back into the next ReAct turn.
+ */
+export function formatValidationErrors(errors: ValidationError[]): string {
+ if (errors.length === 0) return ''
+ return errors
+ .map((e) => (e.path ? `${e.path}: ${e.message}` : e.message))
+ .join('; ')
+}
+
+// ─── Internals ───
+
+function validatePropertyValue(
+ path: string,
+ value: any,
+ schema: JsonSchema
+): { errors: ValidationError[]; coerced: any } {
+ const errors: ValidationError[] = []
+ let coerced = value
+
+ // Enum check first — if it matches an enum value, skip the type check.
+ if (Array.isArray(schema.enum)) {
+ if (!schema.enum.some((v) => deepEqual(v, value))) {
+ errors.push({
+ path,
+ message: `value must be one of: ${schema.enum.map((v) => JSON.stringify(v)).join(', ')}`,
+ })
+ }
+ }
+
+ if (schema.type) {
+ if (!matchesType(value, schema.type)) {
+ // Try safe coercion: "5" → 5 for number/integer, "true"/"false" → bool.
+ const attempt = tryCoerce(value, schema.type)
+ if (attempt.ok) {
+ coerced = attempt.value
+ } else {
+ errors.push({
+ path,
+ message: `expected ${describeType(schema.type)}, got ${describeActual(value)}`,
+ })
+ }
+ }
+ }
+
+ // Array item validation (shallow).
+ if (matchesType(coerced, 'array') && schema.items && Array.isArray(coerced)) {
+ const itemErrs: ValidationError[] = []
+ coerced.forEach((item, i) => {
+ const r = validatePropertyValue(`${path}[${i}]`, item, schema.items as JsonSchema)
+ itemErrs.push(...r.errors)
+ })
+ errors.push(...itemErrs)
+ }
+
+ return { errors, coerced }
+}
+
+function matchesType(value: any, type: string | string[]): boolean {
+ if (Array.isArray(type)) return type.some((t) => matchesType(value, t))
+ switch (type) {
+ case 'string':
+ return typeof value === 'string'
+ case 'number':
+ return typeof value === 'number' && Number.isFinite(value)
+ case 'integer':
+ return typeof value === 'number' && Number.isInteger(value)
+ case 'boolean':
+ return typeof value === 'boolean'
+ case 'array':
+ return Array.isArray(value)
+ case 'object':
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ case 'null':
+ return value === null
+ default:
+ // Unknown type keyword — don't fail on it.
+ return true
+ }
+}
+
+function describeType(type: string | string[]): string {
+ return Array.isArray(type) ? type.join(' | ') : type
+}
+
+function describeActual(value: any): string {
+ if (value === null) return 'null'
+ if (Array.isArray(value)) return 'array'
+ return typeof value
+}
+
+function tryCoerce(
+ value: any,
+ type: string | string[]
+): { ok: true; value: any } | { ok: false } {
+ if (Array.isArray(type)) {
+ for (const t of type) {
+ const r = tryCoerce(value, t)
+ if (r.ok) return r
+ }
+ return { ok: false }
+ }
+ if (type === 'number' || type === 'integer') {
+ if (typeof value === 'string') {
+ const n = Number(value.trim())
+ if (!Number.isNaN(n) && Number.isFinite(n)) {
+ if (type === 'integer' && !Number.isInteger(n)) return { ok: false }
+ return { ok: true, value: n }
+ }
+ }
+ return { ok: false }
+ }
+ if (type === 'boolean') {
+ if (value === 'true') return { ok: true, value: true }
+ if (value === 'false') return { ok: true, value: false }
+ return { ok: false }
+ }
+ if (type === 'string') {
+ // Deliberately NOT coercing numbers/booleans → strings. A string-typed
+ // param receiving a number is almost always a model mistake we want the
+ // retry loop to surface, not silently hide by stringifying.
+ return { ok: false }
+ }
+ if (type === 'array') {
+ // Allow single value → one-element array for array-typed params.
+ if (value !== undefined && value !== null) return { ok: true, value: [value] }
+ return { ok: false }
+ }
+ return { ok: false }
+}
+
+function deepEqual(a: unknown, b: unknown): boolean {
+ if (a === b) return true
+ if (typeof a !== typeof b) return false
+ if (a && b && typeof a === 'object') {
+ const aKeys = Object.keys(a)
+ const bKeys = Object.keys(b)
+ if (aKeys.length !== bKeys.length) return false
+ for (const k of aKeys) {
+ if (!deepEqual((a as any)[k], (b as any)[k])) return false
+ }
+ return true
+ }
+ return false
+}
diff --git a/src/api/agents/format-capability.ts b/src/api/agents/format-capability.ts
new file mode 100644
index 00000000..6deea141
--- /dev/null
+++ b/src/api/agents/format-capability.ts
@@ -0,0 +1,154 @@
+/**
+ * Phase 4 (v2.4.0) — Ollama `format` capability probe.
+ *
+ * Ollama supports a `format` request parameter for constrained JSON output
+ * (`format: "json"` or, as of 0.5+, `format: <JSON-Schema>` for strict
+ * structured output). Support varies by MODEL, not by server version:
+ * - Most modern models (Qwen 3, Llama 3.1+, Gemma 3/4) handle it cleanly.
+ * - Some older quants crash, refuse, or hang the daemon when given it.
+ *
+ * To stay safe we probe per-model the first time we would use `format`,
+ * cache the result in localStorage, and silently fall back to unconstrained
+ * generation on failure.
+ *
+ * This module is deliberately pure + side-effect-light — it exposes a probe
+ * entry point and two cache helpers. Actual probing is done by the caller
+ * (ollama-provider) with a tiny request under a short timeout.
+ */
+
+const STORAGE_KEY = 'lu-format-capability-v1'
+/** How long a cached negative-probe result is considered valid. */
+const NEGATIVE_TTL_MS = 24 * 60 * 60 * 1000
+
+export type FormatCapability = 'supported' | 'unsupported' | 'unknown'
+
+type CacheEntry = {
+ capability: 'supported' | 'unsupported'
+ checkedAt: number
+}
+
+type CacheShape = Record<string, CacheEntry>
+
+function loadCache(): CacheShape {
+ try {
+ if (typeof localStorage === 'undefined') return {}
+ const raw = localStorage.getItem(STORAGE_KEY)
+ if (!raw) return {}
+ const parsed = JSON.parse(raw)
+ return parsed && typeof parsed === 'object' ? parsed : {}
+ } catch {
+ return {}
+ }
+}
+
+function saveCache(cache: CacheShape): void {
+ try {
+ if (typeof localStorage === 'undefined') return
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(cache))
+ } catch {
+ // Quota errors etc. — swallowed; capability will re-probe next session.
+ }
+}
+
+/**
+ * Returns the cached capability for a model. 'unknown' means the caller
+ * should probe before sending `format`. Negative results older than
+ * NEGATIVE_TTL_MS are treated as 'unknown' so models that once failed can
+ * be re-tried (Ollama upgrades, model re-quantisation, etc.).
+ */
+export function getFormatCapability(model: string): FormatCapability {
+ const cache = loadCache()
+ const entry = cache[model]
+ if (!entry) return 'unknown'
+ if (entry.capability === 'supported') return 'supported'
+ if (Date.now() - entry.checkedAt > NEGATIVE_TTL_MS) return 'unknown'
+ return 'unsupported'
+}
+
+/** Mark a model as supporting `format`. Sticky — retained indefinitely. */
+export function markFormatSupported(model: string): void {
+ const cache = loadCache()
+ cache[model] = { capability: 'supported', checkedAt: Date.now() }
+ saveCache(cache)
+}
+
+/**
+ * Mark a model as NOT supporting `format`. Expires after NEGATIVE_TTL_MS
+ * so infra upgrades can be picked up without manual cache clears.
+ */
+export function markFormatUnsupported(model: string): void {
+ const cache = loadCache()
+ cache[model] = { capability: 'unsupported', checkedAt: Date.now() }
+ saveCache(cache)
+}
+
+/** Drop the cache entry for a model (forces re-probe next use). */
+export function clearFormatCapability(model: string): void {
+ const cache = loadCache()
+ delete cache[model]
+ saveCache(cache)
+}
+
+/** Debug / test helper — wipe the entire capability cache. */
+export function resetFormatCapabilityCache(): void {
+ saveCache({})
+}
+
+/**
+ * Probe a model for `format` support. The probe sends a minimal
+ * /api/generate request with `format: "json"`, a 3-second abort timeout,
+ * and a trivial prompt that must return valid JSON.
+ *
+ * The probe is deliberately tolerant: a non-JSON response is treated as
+ * unsupported, a timeout as unsupported, a network error re-throws so the
+ * caller can distinguish transport issues from model issues.
+ */
+export async function probeFormatSupport(
+ model: string,
+ ollamaBaseUrl: string,
+ fetchImpl: typeof fetch = fetch
+): Promise<'supported' | 'unsupported'> {
+ const url = `${ollamaBaseUrl.replace(/\/$/, '')}/api/generate`
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), 3000)
+ try {
+ const res = await fetchImpl(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ signal: controller.signal,
+ body: JSON.stringify({
+ model,
+ prompt: 'Return the JSON object {"ok":true} and nothing else.',
+ stream: false,
+ format: 'json',
+ options: { temperature: 0, num_predict: 32 },
+ }),
+ })
+ clearTimeout(timer)
+ if (!res.ok) {
+ markFormatUnsupported(model)
+ return 'unsupported'
+ }
+ const data = await res.json().catch(() => null)
+ const text: string = data?.response ?? ''
+ try {
+ const parsed = JSON.parse(text)
+ if (parsed && typeof parsed === 'object') {
+ markFormatSupported(model)
+ return 'supported'
+ }
+ } catch {
+ // Not JSON — model ignored the format param.
+ }
+ markFormatUnsupported(model)
+ return 'unsupported'
+ } catch (err) {
+ clearTimeout(timer)
+ if ((err as DOMException)?.name === 'AbortError') {
+ markFormatUnsupported(model)
+ return 'unsupported'
+ }
+ // Network / transport — leave cache alone and surface the error.
+ throw err
+ }
+}