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.

tech(M-any): MCP-, Workflow- und ComfyUI-Schicht typisieren (163 `any` raus)

Davidb2447cf1b8e7
diff --git a/src/api/__tests__/comfyui-combo-schema.test.ts b/src/api/__tests__/comfyui-combo-schema.test.ts
index bd637d71..fe4bcb49 100644
--- a/src/api/__tests__/comfyui-combo-schema.test.ts
+++ b/src/api/__tests__/comfyui-combo-schema.test.ts
@@ -229,11 +229,14 @@ describe('the box answer that killed the video discovery', () => {
sampler: 'euler', scheduler: 'normal', steps: 20, cfgScale: 8,
width: 512, height: 512, seed: 1, frames: 16, fps: 8,
} as Parameters<typeof buildAnimateDiffWorkflow>[0])
+ // The builder returns a typed ComfyApiGraph now — no cast needed, and a
+ // renamed input is a compile error rather than a silent undefined.
const loader = Object.values(workflow).find(
- (n) => (n as { class_type?: string }).class_type === 'ADE_LoadAnimateDiffModel',
- ) as { inputs: { model_name: string } }
- expect(loader.inputs.model_name).toBe(MOTION_LIGHTNING)
- expect(loader.inputs.model_name).not.toBe('C')
+ (n) => n.class_type === 'ADE_LoadAnimateDiffModel',
+ )
+ expect(loader).toBeDefined()
+ expect(loader?.inputs?.model_name).toBe(MOTION_LIGHTNING)
+ expect(loader?.inputs?.model_name).not.toBe('C')
})
it('the AnimateDiff models reach the workflow builder from the newer schema', async () => {
diff --git a/src/api/__tests__/framepack-vae.test.ts b/src/api/__tests__/framepack-vae.test.ts
index 8a413c00..c3d1fe78 100644
--- a/src/api/__tests__/framepack-vae.test.ts
+++ b/src/api/__tests__/framepack-vae.test.ts
@@ -110,16 +110,19 @@ describe('the built FramePack graph', () => {
it('loads the 1.0 VAE, and both the encode and the decode read that one node', async () => {
const wf = await buildDynamicWorkflow(params as never)
- const vaeNodes = Object.entries(wf).filter(([, v]) => (v as { class_type: string }).class_type === 'VAELoader')
+ // buildDynamicWorkflow returns a typed ComfyApiGraph now, so these read
+ // real fields instead of casting each node back into a hand-written shape.
+ const vaeNodes = Object.entries(wf).filter(([, v]) => v.class_type === 'VAELoader')
expect(vaeNodes).toHaveLength(1)
const [vaeId, vaeNode] = vaeNodes[0]
- expect((vaeNode as { inputs: { vae_name: string } }).inputs.vae_name).toBe(VAE_10)
+ expect(vaeNode.inputs?.vae_name).toBe(VAE_10)
// One VAE for the whole graph: encoding the start frame with a different
// VAE than the decode uses would be the same channel mismatch, one node on.
for (const cls of ['VAEEncode', 'VAEDecode', 'VAEDecodeTiled']) {
- for (const [, node] of Object.entries(wf).filter(([, v]) => (v as { class_type: string }).class_type === cls)) {
- expect((node as { inputs: { vae: [string, number] } }).inputs.vae[0]).toBe(vaeId)
+ for (const [, node] of Object.entries(wf).filter(([, v]) => v.class_type === cls)) {
+ const vae = node.inputs?.vae
+ expect(Array.isArray(vae) && vae[0]).toBe(vaeId)
}
}
})
diff --git a/src/api/__tests__/local-op-workflows.test.ts b/src/api/__tests__/local-op-workflows.test.ts
index bc8c5564..1622f47c 100644
--- a/src/api/__tests__/local-op-workflows.test.ts
+++ b/src/api/__tests__/local-op-workflows.test.ts
@@ -12,19 +12,16 @@ import {
type LocalOpParams,
} from '../dynamic-workflow'
import { classifyModel, galleryTypeForFile, resolveLocalOpPick, type ClassifiedModel } from '../comfyui'
+import type { ComfyApiGraph, ComfyApiNode } from '../../types/comfy-graph'
/**
- * 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`.
+ * The builders now declare their own graph shape (types/comfy-graph.ts), so
+ * the assertions below read THAT type instead of a local stand-in — a renamed
+ * key or a builder that stops emitting `inputs` at all is a compile error here,
+ * not an `undefined === undefined` that quietly passes.
*/
-interface ComfyNode {
- class_type: string
- inputs: Record<string, unknown>
-}
-type ComfyGraph = Record<string, ComfyNode>
+type ComfyNode = ComfyApiNode
+type ComfyGraph = ComfyApiGraph
/** The node of this class_type — fails loudly when the graph has none. */
function nodeOfType(wf: ComfyGraph, classType: string): ComfyNode {
@@ -35,7 +32,7 @@ function nodeOfType(wf: ComfyGraph, classType: string): ComfyNode {
/** A numeric input, checked rather than assumed. */
function numInput(node: ComfyNode, key: string): number {
- const v = node.inputs[key]
+ const v = node.inputs?.[key]
if (typeof v !== 'number') {
throw new Error(`${node.class_type}.inputs.${key} is not a number: ${String(v)}`)
}
@@ -44,7 +41,7 @@ function numInput(node: ComfyNode, key: string): number {
/** An array input (a ComfyUI link `[nodeId, slot]`, or a literal list). */
function arrInput(node: ComfyNode, key: string): unknown[] {
- const v = node.inputs[key]
+ const v = node.inputs?.[key]
if (!Array.isArray(v)) {
throw new Error(`${node.class_type}.inputs.${key} is not an array: ${String(v)}`)
}
@@ -136,8 +133,8 @@ describe('buildMusicWorkflow', () => {
expect(types).toContain('EmptyAceStepLatentAudio')
expect(types).toContain('VAEDecodeAudio')
expect(types).toContain('SaveAudioMP3')
- expect(nodeOfType(wf, 'EmptyAceStepLatentAudio').inputs.seconds).toBe(45)
- expect(nodeOfType(wf, 'TextEncodeAceStepAudio').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', () => {
@@ -176,7 +173,7 @@ describe('buildS2VWorkflow', () => {
for (const t of ['LoadAudio', 'AudioEncoderLoader', 'AudioEncoderEncode', 'WanSoundImageToVideo', 'CreateVideo', 'SaveVideo']) {
expect(types).toContain(t)
}
- expect(nodeOfType(wf, 'CreateVideo').inputs.audio).toBeTruthy()
+ expect(nodeOfType(wf, 'CreateVideo').inputs?.audio).toBeTruthy()
const s2vNode = nodeOfType(wf, 'WanSoundImageToVideo')
// length stays on the 4k+1 grid
expect((numInput(s2vNode, 'length') - 1) % 4).toBe(0)
@@ -216,10 +213,10 @@ describe('buildMotionWorkflow', () => {
expect(types).toContain(t)
}
const trim = nodeOfType(wf, 'TrimVideoLatent')
- expect(Array.isArray(trim.inputs.trim_amount)).toBe(true)
+ expect(Array.isArray(trim.inputs?.trim_amount)).toBe(true)
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])
+ expect(nodeOfType(wf, 'CreateVideo').inputs?.audio).toEqual([components, 1])
})
it('routes VACE models through WanVaceToVideo with the skeleton as control video', () => {
diff --git a/src/api/__tests__/workflows-validation.test.ts b/src/api/__tests__/workflows-validation.test.ts
index b1c41ff3..3a1661fe 100644
--- a/src/api/__tests__/workflows-validation.test.ts
+++ b/src/api/__tests__/workflows-validation.test.ts
@@ -112,12 +112,12 @@ it('injects LU dimensions into a legacy ImageResizeKJv2 workflow', async () => {
'wan',
)
- expect(injected['16'].inputs.width).toBe(832)
- expect(injected['16'].inputs.height).toBe(480)
+ expect(injected['16'].inputs?.width).toBe(832)
+ expect(injected['16'].inputs?.height).toBe(480)
// WanImageToVideo must remain connected to the resize node.
- expect(injected['9'].inputs.width).toEqual(['16', 1])
- expect(injected['9'].inputs.height).toEqual(['16', 2])
+ expect(injected['9'].inputs?.width).toEqual(['16', 1])
+ expect(injected['9'].inputs?.height).toEqual(['16', 2])
})
describe('injectParameters — source image', () => {
@@ -157,12 +157,12 @@ it('injects LU dimensions into a legacy ImageResizeKJv2 workflow', async () => {
'wan' as ModelType,
)
- expect(result['12'].inputs.image).toBe(
+ expect(result['12'].inputs?.image).toBe(
'lu-selected-image.png',
)
// Injection works on a cloned workflow.
- expect(workflow['12'].inputs.image).toBe(
+ expect(workflow['12'].inputs?.image).toBe(
'placeholder.png',
)
})
@@ -184,7 +184,7 @@ it('injects LU dimensions into a legacy ImageResizeKJv2 workflow', async () => {
'wan' as ModelType,
)
- expect(result['27'].inputs.image).toBe(
+ expect(result['27'].inputs?.image).toBe(
'lu-selected-image.png',
)
})
diff --git a/src/api/comfyui-graph.ts b/src/api/comfyui-graph.ts
index 82a77117..e8e7d938 100644
--- a/src/api/comfyui-graph.ts
+++ b/src/api/comfyui-graph.ts
@@ -17,6 +17,8 @@
* Namen, damit kein Aufrufer und kein Test seinen Importpfad ändern muss.
*/
+import type { ComfyApiNode, ComfyLinkRef } from '../types/comfy-graph'
+
// ─── Output filename slug (David 2026-06-11) ───
//
// Generated media used to be `locally_uncensored_00123_.png` /
@@ -59,10 +61,10 @@ export function promptFilenamePrefix(prompt: string | undefined, isVideo: boolea
* the node's own defaults except tile_size, halved for the low-VRAM cards
* this exists for. Image decodes stay on plain VAEDecode. */
export function videoDecodeNode(
- samplesRef: [string, number],
- vaeRef: [string, number],
+ samplesRef: ComfyLinkRef,
+ vaeRef: ComfyLinkRef,
hasTiled: boolean,
-): Record<string, any> {
+): ComfyApiNode {
return hasTiled
? {
class_type: 'VAEDecodeTiled',
diff --git a/src/api/comfyui-nodes.ts b/src/api/comfyui-nodes.ts
index f30f5dfb..8925621a 100644
--- a/src/api/comfyui-nodes.ts
+++ b/src/api/comfyui-nodes.ts
@@ -9,12 +9,22 @@ import { readComboOptions } from './comfyui-enum'
// nicht, also ist ein ganz normaler statischer Import hier die ehrliche Form.
import { classifyModel, MODEL_TYPE_DEFAULTS } from './comfyui'
import type { ModelType } from './comfyui'
+import type { ComfyInputValue } from '../types/comfy-graph'
// ─── Types ───
+/**
+ * One node's declared inputs, straight from ComfyUI's `/object_info`.
+ *
+ * Each value is an input SPEC, not a value, and its shape depends on the node
+ * and on the ComfyUI version: `["INT", { default: 20 }]`, `[["euler","dpmpp_2m"]]`
+ * (legacy combo) or `["COMBO", { options: [...] }]` (current). Nothing here may
+ * assume which — `readComboOptions` (comfyui-enum.ts) is the one reader that
+ * knows all three shapes, and it takes `unknown` for exactly that reason.
+ */
export interface NodeInputSpec {
- required: Record<string, any>
- optional?: Record<string, any>
+ required: Record<string, ComfyInputValue>
+ optional?: Record<string, ComfyInputValue>
}
export interface NodeMetadata {
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index dfbfde7a..79d0cc31 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -9,6 +9,8 @@ import { resolveRunSeed } from '../lib/run-seed'
// verdeckt hat. Beide sind reine Graph-Bausteine und wohnen jetzt in
// comfyui-graph.ts, das nichts importiert.
import { videoDecodeNode, promptFilenamePrefix } from './comfyui-graph'
+import type { ComfyApiGraph, ComfyApiNode, ComfyHistoryEntry } from '../types/comfy-graph'
+import { isRecord, asString, asRecordArray } from '../types/json-guards'
// Audit W-T2: der Katalog kam bis eben per `await import('./discover')` in
// getKnownFileSizes() herein, „to break the cycle at runtime". Die
// Bundle-Daten gehören weder hierher noch nach discover.ts — sie liegen
@@ -788,7 +790,7 @@ async function getKnownFileSizes(): Promise<Map<string, { subfolder: string; exp
if (_knownFileSizes) return _knownFileSizes
_knownFileSizes = new Map()
for (const bundle of [...getImageBundles(), ...getVideoBundles()]) {
- for (const f of (bundle as any).files) {
+ for (const f of bundle.files) {
if (f.filename && f.sizeGB && f.subfolder) {
_knownFileSizes.set(f.filename, {
subfolder: f.subfolder,
@@ -1526,8 +1528,8 @@ async function findAnimateDiffModel(): Promise<string> {
// ─── Workflow Submission ───
-export async function submitWorkflow(workflow: Record<string, any>, clientId?: string): Promise<string> {
- const payload: Record<string, any> = { prompt: workflow }
+export async function submitWorkflow(workflow: ComfyApiGraph, clientId?: string): Promise<string> {
+ const payload: Record<string, unknown> = { prompt: workflow }
if (clientId) payload.client_id = clientId
// Use localFetch (Rust proxy in Tauri, direct fetch in dev). The previous
// direct-only fetch broke for any ComfyUI not started by LU itself —
@@ -1550,14 +1552,23 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: s
const rawText = await res.text().catch(() => '')
let errMsg = `HTTP ${res.status}`
try {
- const errData = JSON.parse(rawText)
+ // ComfyUI's rejection body. Foreign JSON: `error` is a string on some
+ // versions and an `{ message }` on others, and `node_errors` is only
+ // present for a validation failure — so every read is narrowed.
+ const errData: unknown = JSON.parse(rawText)
const parts: string[] = []
- if (typeof errData.error === 'string') parts.push(errData.error)
- else if (errData.error?.message) parts.push(errData.error.message)
- if (errData.node_errors) {
- for (const [nodeId, data] of Object.entries(errData.node_errors) as [string, any][]) {
- const errs = data.errors?.map((e: any) => e.message || e.details).join(', ') || 'unknown'
- parts.push(`Node ${nodeId} (${data.class_type || '?'}): ${errs}`)
+ const rawErr = isRecord(errData) ? errData.error : undefined
+ const topLevel = asString(rawErr) ?? (isRecord(rawErr) ? asString(rawErr.message) : undefined)
+ if (topLevel) parts.push(topLevel)
+ const nodeErrors = isRecord(errData) ? errData.node_errors : undefined
+ if (isRecord(nodeErrors)) {
+ for (const [nodeId, data] of Object.entries(nodeErrors)) {
+ const errs = asRecordArray(isRecord(data) ? data.errors : undefined)
+ .map((e) => asString(e.message) ?? asString(e.details) ?? '')
+ .filter(Boolean)
+ .join(', ') || 'unknown'
+ const cls = (isRecord(data) ? asString(data.class_type) : undefined) ?? '?'
+ parts.push(`Node ${nodeId} (${cls}): ${errs}`)
}
}
if (parts.length > 0) errMsg = parts.join(' | ')
@@ -1567,8 +1578,10 @@ export async function submitWorkflow(workflow: Record<string, any>, clientId?: s
log.error('comfyui.workflow_rejected', { errMsg, workflow: JSON.stringify(workflow).slice(0, 2000) })
throw new Error(`ComfyUI rejected workflow: ${errMsg}`)
}
- const data = await res.json()
- return data.prompt_id
+ const data: unknown = await res.json()
+ const promptId = isRecord(data) ? asString(data.prompt_id) : undefined
+ if (!promptId) throw new Error('ComfyUI accepted the workflow but returned no prompt_id.')
+ return promptId
}
export async function cancelGeneration(): Promise<void> {
@@ -1678,7 +1691,7 @@ export async function freeMemory(): Promise<void> {
} catch { /* best effort */ }
}
-export async function getHistory(promptId: string): Promise<any> {
+export async function getHistory(promptId: string): Promise<ComfyHistoryEntry | null> {
try {
// localFetch routes through Rust proxy in Tauri to dodge CORS — same
// reason as submitWorkflow above. Without this, a user-run ComfyUI
@@ -1686,8 +1699,9 @@ export async function getHistory(promptId: string): Promise<any> {
// would silently 0-out and the UI hangs in "generating…" forever.
const res = await localFetch(comfyuiUrl(`/history/${promptId}`), { timeoutMs: COMFY_POLL_TIMEOUT_MS })
if (!res.ok) return null
- const data = await res.json()
- return data[promptId] ?? null
+ const data: unknown = await res.json()
+ const entry = isRecord(data) ? data[promptId] : undefined
+ return isRecord(entry) ? entry : null
} catch {
return null
}
@@ -1918,7 +1932,7 @@ export function snapToVideoGrid(width: number, height: number): { width: number;
// ─── Image Workflow: SDXL/SD (CheckpointLoaderSimple) ───
-export function buildSDXLImgWorkflow(params: GenerateParams): Record<string, any> {
+export function buildSDXLImgWorkflow(params: GenerateParams): ComfyApiGraph {
validateParams(params)
const seed = getSeed(params.seed)
return {
@@ -1947,7 +1961,7 @@ export function buildSDXLImgWorkflow(params: GenerateParams): Record<string, any
* as GGUF). The city96 pack's `UnetLoaderGGUF` reads them. Same rule as the
* dynamic builder's addUnetLoader; this legacy path still carries the VRAM
* handoff and the agent's video tool. */
-async function unetLoaderNode(model: string): Promise<Record<string, any>> {
+async function unetLoaderNode(model: string): Promise<ComfyApiNode> {
if (!model.toLowerCase().endsWith('.gguf')) {
return { class_type: 'UNETLoader', inputs: { unet_name: model, weight_dtype: 'default' } }
}
@@ -1959,7 +1973,7 @@ async function unetLoaderNode(model: string): Promise<Record<string, any>> {
return { class_type: 'UnetLoaderGGUF', inputs: { unet_name: model } }
}
-export async function buildFluxImgWorkflow(params: GenerateParams): Promise<Record<string, any>> {
+export async function buildFluxImgWorkflow(params: GenerateParams): Promise<ComfyApiGraph> {
validateParams(params)
const seed = getSeed(params.seed)
const modelType = classifyModel(params.model)
@@ -1991,14 +2005,14 @@ export async function buildFluxImgWorkflow(params: GenerateParams): Promise<Reco
// ─── Auto-select Image Workflow ───
-export async function buildTxt2ImgWorkflow(params: GenerateParams, modelType: ModelType): Promise<Record<string, any>> {
+export async function buildTxt2ImgWorkflow(params: GenerateParams, modelType: ModelType): Promise<ComfyApiGraph> {
if (modelType === 'flux' || modelType === 'flux2') return buildFluxImgWorkflow(params)
return buildSDXLImgWorkflow(params)
}
// ─── Video Workflow: Wan 2.1/2.2 (Hunyuan latent space) ───
-export async function buildWanVideoWorkflow(params: VideoParams): Promise<Record<string, any>> {
+export async function buildWanVideoWorkflow(params: VideoParams): Promise<ComfyApiGraph> {
validateVideoParams(params)
const seed = getSeed(params.seed)
@@ -2011,7 +2025,7 @@ export async function buildWanVideoWorkflow(params: VideoParams): Promise<Record
const clip = await findMatchingCLIP('wan')
const hasTiledDecode = await nodeExists('VAEDecodeTiled')
- const workflow: Record<string, any> = {
+ const workflow: ComfyApiGraph = {
'1': { class_type: 'CLIPLoader', inputs: { clip_name: clip, type: 'wan', device: 'default' } },
'2': await unetLoaderNode(params.model),
'3': { class_type: 'VAELoader', inputs: { vae_name: vae } },
@@ -2050,7 +2064,7 @@ export async function buildWanVideoWorkflow(params: VideoParams): Promise<Record
// ─── Video Workflow: AnimateDiff ───
-export async function buildAnimateDiffWorkflow(params: VideoParams): Promise<Record<string, any>> {
+export async function buildAnimateDiffWorkflow(params: VideoParams): Promise<ComfyApiGraph> {
validateVideoParams(params)
const seed = getSeed(params.seed)
const motionModel = await findAnimateDiffModel()
@@ -2059,7 +2073,7 @@ export async function buildAnimateDiffWorkflow(params: VideoParams): Promise<Rec
const hasVHS = await nodeExists('VHS_VideoCombine')
const hasTiledDecode = await nodeExists('VAEDecodeTiled')
- const workflow: Record<string, any> = {
+ const workflow: ComfyApiGraph = {
'1': { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: params.model } },
'2': { class_type: 'ADE_LoadAnimateDiffModel', inputs: { model_name: motionModel } },
'3': { class_type: 'ADE_ApplyAnimateDiffModelSimple', inputs: { motion_model: ['2', 0] } },
@@ -2104,7 +2118,7 @@ export async function buildAnimateDiffWorkflow(params: VideoParams): Promise<Rec
// ─── Auto-select Video Workflow ───
-export async function buildTxt2VidWorkflow(params: VideoParams, backend: VideoBackend): Promise<Record<string, any>> {
+export async function buildTxt2VidWorkflow(params: VideoParams, backend: VideoBackend): Promise<ComfyApiGraph> {
switch (backend) {
case 'wan': return buildWanVideoWorkflow(params)
case 'animatediff': return buildAnimateDiffWorkflow(params)
diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.ts
index 2729b24f..542f5d3d 100644
--- a/src/api/dynamic-workflow.ts
+++ b/src/api/dynamic-workflow.ts
@@ -9,7 +9,44 @@ import {
detectAvailableModels,
type CategorizedNodes,
type AvailableModels,
+ type NodeMetadata,
} from './comfyui-nodes'
+import type { ComfyApiGraph, ComfyInputValue, ComfyNodeInputs } from '../types/comfy-graph'
+
+/**
+ * The `/object_info` node table as the LANE builders use it: they only ever ask
+ * whether a node class is installed, never what its schema says, so a presence
+ * map is the honest parameter type. `buildDynamicWorkflow` itself keeps the
+ * full `Record<string, NodeMetadata>` from getAllNodeInfo(), because it does
+ * read schemas (RMBG, the I2V conditioning node, LoraLoader's combo).
+ */
+type NodePresence = Record<string, unknown>
+
+/**
+ * Split one `/object_info` input spec into the two halves every caller wants.
+ *
+ * ComfyUI writes a spec as `[typeName, config]` (current) or `[[options]]`
+ * (legacy combo). Neither half is guaranteed, and a custom node can put
+ * anything there, so both come back optional. Combo OPTIONS are not read here
+ * — `readComboOptions` is the single reader that knows all three shapes.
+ */
+function specParts(spec: ComfyInputValue | undefined): {
+ typeName?: string
+ config?: { [k: string]: ComfyInputValue }
+} {
+ if (!Array.isArray(spec)) return {}
+ const head = spec[0]
+ const cfg = spec[1]
+ return {
+ typeName: typeof head === 'string' ? head : undefined,
+ config: typeof cfg === 'object' && cfg !== null && !Array.isArray(cfg) ? cfg : undefined,
+ }
+}
+
+/** The `default` a widget spec declares, or undefined when it declares none. */
+function specDefault(spec: ComfyInputValue | undefined): ComfyInputValue | undefined {
+ return specParts(spec).config?.default
+}
// promptFilenamePrefix und videoDecodeNode wohnen in comfyui-graph.ts (siehe
// dort). Re-Export, damit bestehende Importpfade unverändert bleiben.
@@ -348,7 +385,7 @@ function resolveOneLora(req: string, installed: string[]): string | null {
export async function buildDynamicWorkflow(
params: GenerateParams | VideoParams,
modelType?: ModelType,
-): Promise<Record<string, any>> {
+): Promise<ComfyApiGraph> {
const type = modelType || classifyModel(params.model)
const isVideo = 'frames' in params
const videoParams = params as VideoParams
@@ -411,7 +448,7 @@ export async function buildDynamicWorkflow(
// ─── Standard Strategies (UNET/Checkpoint → CLIP → Latent → KSampler → VAEDecode) ───
- const workflow: Record<string, any> = {}
+ const workflow: ComfyApiGraph = {}
let n = 1 // node counter
// ─── Phase 1: Model Loading ───
@@ -852,10 +889,10 @@ export async function buildDynamicWorkflow(
}
const loadId = String(n++)
workflow[loadId] = { class_type: 'LoadImage', inputs: { image: (params as GenerateParams).inputImage } }
- const required = (meta.input?.required ?? {}) as Record<string, any[]>
- const optional = (meta.input?.optional ?? {}) as Record<string, any[]>
+ const required = meta.input?.required ?? {}
+ const optional = meta.input?.optional ?? {}
const decl = { ...required, ...optional }
- const inputs: Record<string, any> = {}
+ const inputs: ComfyNodeInputs = {}
if (decl.positive) inputs.positive = positiveRef
if (decl.negative) inputs.negative = negativeRef
if (decl.vae) inputs.vae = [vaeSourceId, vaeOutputSlot]
@@ -874,7 +911,10 @@ export async function buildDynamicWorkflow(
if (inputs[key] !== undefined) continue
const combo = readComboOptions(spec)
if (combo && combo.length) inputs[key] = combo[0]
- else if (spec[1] && typeof spec[1] === 'object' && 'default' in spec[1]) inputs[key] = spec[1].default
+ else {
+ const dflt = specDefault(spec)
+ if (dflt !== undefined) inputs[key] = dflt
+ }
}
const i2vId = String(n++)
workflow[i2vId] = { class_type: i2vNode, inputs, _meta: { title: 'I2V conditioning' } }
@@ -990,8 +1030,8 @@ export async function buildDynamicWorkflow(
// (`rmbgMeta`) so the graph stays valid across RMBG versions instead of pinning
// input names/enums we'd have to guess. The `background` widget is nudged toward
// a transparent/alpha option so the result is a real RGBA cutout, not a matte.
-function buildRemoveBgWorkflow(params: GenerateParams, rmbgMeta: any): Record<string, any> {
- const workflow: Record<string, any> = {}
+function buildRemoveBgWorkflow(params: GenerateParams, rmbgMeta: NodeMetadata): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
workflow['1'] = { class_type: 'LoadImage', inputs: { image: params.inputImage } }
// Fill BOTH required AND optional widgets from the live schema. ComfyUI-RMBG
@@ -999,9 +1039,9 @@ function buildRemoveBgWorkflow(params: GenerateParams, rmbgMeta: any): Record<st
// in INPUT_TYPES but its Python reads them as plain kwargs, so omitting them
// throws "Error in batch processing: 'process_res' (RMBG)". Defaulting every
// widget from object_info keeps the graph valid across RMBG versions.
- const required: Record<string, any> = rmbgMeta?.input?.required ?? {}
- const optional: Record<string, any> = rmbgMeta?.input?.optional ?? {}
- const rmbgInputs: Record<string, any> = { image: ['1', 0] }
+ const required = rmbgMeta.input?.required ?? {}
+ const optional = rmbgMeta.input?.optional ?? {}
+ const rmbgInputs: ComfyNodeInputs = { image: ['1', 0] }
for (const [name, spec] of Object.entries({ ...required, ...optional })) {
if (name === 'image') continue
const d = rmbgWidgetDefault(name, spec)
@@ -1023,9 +1063,13 @@ function buildRemoveBgWorkflow(params: GenerateParams, rmbgMeta: any): Record<st
// declared default / first entry. Primitives → their declared default. A
// non-widget connection input (some other IMAGE/MASK) can't be auto-wired, so
// skip it — ComfyUI surfaces a clear error rather than us guessing wrong.
-function rmbgWidgetDefault(name: string, spec: any): { set: boolean; value?: any } {
- const t = Array.isArray(spec) ? spec[0] : spec
- const cfg = Array.isArray(spec) ? spec[1] : undefined
+function rmbgWidgetDefault(
+ name: string,
+ spec: ComfyInputValue | undefined,
+): { set: boolean; value?: ComfyInputValue } {
+ const { typeName, config: cfg } = specParts(spec)
+ // A bare (non-array) spec is its own type marker — RMBG has shipped both.
+ const t = typeName ?? (Array.isArray(spec) ? undefined : spec)
// Both dropdown schemas, through the shared reader: a node that declares its
// combos the newer way (["COMBO", {options: [...]}]) used to fall through to
// "not a widget" here, and RMBG then rejected the graph for the missing
@@ -1045,7 +1089,7 @@ function rmbgWidgetDefault(name: string, spec: any): { set: boolean; value?: any
}
-function addVideoOutput(workflow: Record<string, any>, n: number, decodeId: string, fps: number, nodes: CategorizedNodes, prompt?: string): number {
+function addVideoOutput(workflow: ComfyApiGraph, n: number, decodeId: string, fps: number, nodes: CategorizedNodes, prompt?: string): number {
const saveId = String(n++)
const prefix = promptFilenamePrefix(prompt, true)
if (nodes.videoSavers.includes('VHS_VideoCombine')) {
@@ -1074,8 +1118,8 @@ function addVideoOutput(workflow: Record<string, any>, n: number, decodeId: stri
// known-wrong graph around invites someone to just reopen the gate. Git history
// has it if the lane is ever rebuilt, which needs a real generate to land.
-function buildSVDWorkflow(params: VideoParams, seed: number, nodes: CategorizedNodes): Record<string, any> {
- const workflow: Record<string, any> = {}
+function buildSVDWorkflow(params: VideoParams, seed: number, nodes: CategorizedNodes): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
let n = 1
const loaderId = String(n++)
@@ -1142,8 +1186,8 @@ export function snapWanLength(frames: number): number {
* the source into the generation size, so the first frame matches the still
* instead of being squished — the same fix proven on the SVD path.
*/
-function buildWan22Workflow(params: VideoParams, seed: number, nodes: CategorizedNodes, allNodes: Record<string, any>): Record<string, any> {
- const workflow: Record<string, any> = {}
+function buildWan22Workflow(params: VideoParams, seed: number, nodes: CategorizedNodes, allNodes: NodePresence): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
let n = 1
// Wan 2.2 dims snap to 32 (VAE spatial grid); length to 4k+1 (temporal stride 4).
@@ -1187,7 +1231,7 @@ function buildWan22Workflow(params: VideoParams, seed: number, nodes: Categorize
workflow[shiftId] = { class_type: 'ModelSamplingSD3', inputs: { model: [wanModelSrc, 0], shift: 8.0 } }
// Unified latent: a start_image is attached ONLY for an I2V request.
- const latentInputs: Record<string, any> = { vae: [vaeId, 0], width, height, length, batch_size: 1 }
+ const latentInputs: ComfyNodeInputs = { vae: [vaeId, 0], width, height, length, batch_size: 1 }
if (params.inputImage) {
const imageId = String(n++)
const scaleId = String(n++)
@@ -1248,7 +1292,7 @@ export interface LocalOpParams {
const UPDATE_COMFY_HINT =
'Update ComfyUI (Settings, AI Backends, Update ComfyUI), restart it, then generate again.'
-function requireNodes(allNodes: Record<string, any>, needed: string[], lane: string): void {
+function requireNodes(allNodes: NodePresence, needed: string[], lane: string): void {
const missing = needed.filter((n) => !allNodes[n])
if (missing.length > 0) {
throw new WorkflowUnavailableError(
@@ -1260,7 +1304,7 @@ function requireNodes(allNodes: Record<string, any>, needed: string[], lane: str
/** UNET loader that understands GGUF quants: .gguf files load through the
* city96 GGUF pack's UnetLoaderGGUF, everything else through core UNETLoader. */
-function addUnetLoader(workflow: Record<string, any>, id: string, model: string, allNodes: Record<string, any>): void {
+function addUnetLoader(workflow: ComfyApiGraph, id: string, model: string, allNodes: NodePresence): void {
if (model.toLowerCase().endsWith('.gguf')) {
if (!allNodes['UnetLoaderGGUF']) {
throw new WorkflowUnavailableError(
@@ -1281,17 +1325,17 @@ function addUnetLoader(workflow: Record<string, any>, id: string, model: string,
* nodes (same family as the lanes themselves — present on any core new
* enough to run them). */
function addVideoWithAudioOutput(
- workflow: Record<string, any>,
+ workflow: ComfyApiGraph,
n: number,
decodeId: string,
fps: number,
audioSrc: [string, number] | null,
- allNodes: Record<string, any>,
+ allNodes: NodePresence,
prompt?: string,
): number {
requireNodes(allNodes, ['CreateVideo', 'SaveVideo'], 'This video output')
const createId = String(n++)
- const inputs: Record<string, any> = { images: [decodeId, 0], fps }
+ const inputs: ComfyNodeInputs = { images: [decodeId, 0], fps }
if (audioSrc) inputs.audio = audioSrc
workflow[createId] = { class_type: 'CreateVideo', inputs }
const saveId = String(n++)
@@ -1310,8 +1354,8 @@ function addVideoWithAudioOutput(
* the negative prompt (cheap), 1.5 zero-outs the positive instead — its
* encoder runs an LLM pass that would double the cost for no benefit.
*/
-export function buildMusicWorkflow(params: LocalOpParams, seed: number, allNodes: Record<string, any>): Record<string, any> {
- const workflow: Record<string, any> = {}
+export function buildMusicWorkflow(params: LocalOpParams, seed: number, allNodes: NodePresence): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
let n = 1
const isAce15 = /1[._-]?5/.test(params.model.toLowerCase().replace(/\.safetensors$/, '').replace(/^.*ace[_-]?step/, ''))
const encodeNode = isAce15 ? 'TextEncodeAceStepAudio1.5' : 'TextEncodeAceStepAudio'
@@ -1388,8 +1432,8 @@ export function buildMusicWorkflow(params: LocalOpParams, seed: number, allNodes
* a silent talking-head clip is useless. Uses the Wan 2.1 VAE + UMT5 encoder
* (the S2V-14B pairing from the official release).
*/
-export function buildS2VWorkflow(params: LocalOpParams, seed: number, allNodes: Record<string, any>): Record<string, any> {
- const workflow: Record<string, any> = {}
+export function buildS2VWorkflow(params: LocalOpParams, seed: number, allNodes: NodePresence): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
let n = 1
requireNodes(
allNodes,
@@ -1462,8 +1506,8 @@ export function buildS2VWorkflow(params: LocalOpParams, seed: number, allNodes:
* onnxruntime path works on every Windows box, no GPU wheel roulette).
* The driving clip's own audio is carried over into the result.
*/
-export function buildMotionWorkflow(params: LocalOpParams, seed: number, allNodes: Record<string, any>): Record<string, any> {
- const workflow: Record<string, any> = {}
+export function buildMotionWorkflow(params: LocalOpParams, seed: number, allNodes: NodePresence): ComfyApiGraph {
+ const workflow: ComfyApiGraph = {}
let n = 1
requireNodes(allNodes, ['LoadVideo', 'GetVideoComponents'], 'Motion control')
if (!allNodes['DWPreprocessor']) {
@@ -1559,7 +1603,7 @@ export function buildMotionWorkflow(params: LocalOpParams, seed: number, allNode
/** Entry point for the specialized local lanes — fetches the live node
* catalogue once and dispatches to the lane's builder. */
-export async function buildLocalOpWorkflow(params: LocalOpParams): Promise<Record<string, any>> {
+export async function buildLocalOpWorkflow(params: LocalOpParams): Promise<ComfyApiGraph> {
const allNodes = await getAllNodeInfo()
const seed = resolveRunSeed(params.seed)
switch (params.op) {
@@ -1569,8 +1613,8 @@ export async function buildLocalOpWorkflow(params: LocalOpParams): Promise<Recor
}
}
-async function buildFramePackWorkflow(params: VideoParams, seed: number, nodes: CategorizedNodes): Promise<Record<string, any>> {
- const workflow: Record<string, any> = {}
+async function buildFramePackWorkflow(params: VideoParams, seed: number, nodes: CategorizedNodes): Promise<ComfyApiGraph> {
+ const workflow: ComfyApiGraph = {}
let n = 1
const modelId = String(n++)
diff --git a/src/api/mcp/__tests__/external-client.test.ts b/src/api/mcp/__tests__/external-client.test.ts
index 66611d66..debd4ecf 100644
--- a/src/api/mcp/__tests__/external-client.test.ts
+++ b/src/api/mcp/__tests__/external-client.test.ts
@@ -14,17 +14,25 @@ import { MCPExternalClient } from '../external-client'
import type { MCPServerConfig } from '../types'
class Emitter {
- private handlers: Record<string, ((data: any) => void)[]> = {}
- on(event: string, fn: (data: any) => void) {
+ private handlers: Record<string, ((data: string) => void)[]> = {}
+ on(event: string, fn: (data: string) => void) {
;(this.handlers[event] ||= []).push(fn)
}
- emit(event: string, data?: any) {
+ emit(event: string, data = '') {
for (const fn of this.handlers[event] || []) fn(data)
}
}
+/** One JSON-RPC request line as the fake server sees it. */
+interface FakeRequest {
+ jsonrpc?: string
+ id?: number
+ method?: string
+ params?: { arguments?: Record<string, unknown> }
+}
+
/** Server behaviour a single test wants: id/method → response line. */
-type Responder = (req: any) => string | null
+type Responder = (req: FakeRequest) => string | null
let lastServer: FakeServer | null = null
let killCount = 0
@@ -104,7 +112,7 @@ const goodServer: Responder = (req) => {
return JSON.stringify({
jsonrpc: '2.0',
id: req.id,
- result: { content: [{ type: 'text', text: `sunny in ${req.params.arguments.city}` }] },
+ result: { content: [{ type: 'text', text: `sunny in ${String(req.params?.arguments?.city)}` }] },
})
}
return null
@@ -164,6 +172,54 @@ describe('connecting to an external server', () => {
await expect(client.callTool('get_forecast', { city: 'Atlantis' })).rejects.toThrow('unknown city')
})
+ /**
+ * A server that does not follow JSON-RPC still FAILED, and the only wrong
+ * answer is to call it a success.
+ *
+ * `if (response.error)` was true for any truthy value, so a bare-string error
+ * was at least rejected (with an unusable `Error: undefined`). Narrowing the
+ * field to a record turned exactly those lines into `resolve(undefined)` —
+ * the model was told the tool had run. The rule pinned here: any PRESENT
+ * error rejects, and the server's own text is what comes out.
+ */
+ it('rejects when `error` is a bare string, not a record', async () => {
+ const client = new MCPExternalClient(config)
+ await client.connect()
+ responder = (req) => JSON.stringify({ jsonrpc: '2.0', id: req.id, error: 'server exploded' })
+
+ await expect(client.callTool('get_forecast', { city: 'Atlantis' })).rejects.toThrow('server exploded')
+ })
+
+ it('rejects when `error` is a non-string primitive', async () => {
+ const client = new MCPExternalClient(config)
+ await client.connect()
+ responder = (req) => JSON.stringify({ jsonrpc: '2.0', id: req.id, error: 500 })
+
+ await expect(client.callTool('get_forecast', { city: 'Atlantis' })).rejects.toThrow('500')
+ })
+
+ it('rejects when `error` is a record without a message, naming what came back', async () => {
+ const client = new MCPExternalClient(config)
+ await client.connect()
+ responder = (req) => JSON.stringify({ jsonrpc: '2.0', id: req.id, error: { code: -32601 } })
+
+ await expect(client.callTool('get_forecast', { city: 'Atlantis' })).rejects.toThrow('-32601')
+ })
+
+ it('NEGATIVE CONTROL: `error: null` is not an error — the result still resolves', async () => {
+ const client = new MCPExternalClient(config)
+ await client.connect()
+ responder = (req) =>
+ JSON.stringify({
+ jsonrpc: '2.0',
+ id: req.id,
+ error: null,
+ result: { content: [{ type: 'text', text: 'still fine' }] },
+ })
+
+ expect(await client.callTool('get_forecast', { city: 'Berlin' })).toBe('still fine')
+ })
+
it('refuses to call a tool before connecting', async () => {
await expect(new MCPExternalClient(config).callTool('get_forecast', {})).rejects.toThrow('Not connected')
})
diff --git a/src/api/mcp/__tests__/shell-honours-stop.test.ts b/src/api/mcp/__tests__/shell-honours-stop.test.ts
index cc8d020f..3105ee71 100644
--- a/src/api/mcp/__tests__/shell-honours-stop.test.ts
+++ b/src/api/mcp/__tests__/shell-honours-stop.test.ts
@@ -21,10 +21,10 @@ import { readFileSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
-const backendCalls: { cmd: string; body: any }[] = []
+const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
vi.mock('../../backend', () => ({
- backendCall: vi.fn(async (cmd: string, body: any) => {
+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
backendCalls.push({ cmd, body })
if (cmd === 'shell_execute') return { stdout: 'ran', stderr: '', exitCode: 0 }
if (cmd === 'shell_task_start') return { id: 'task-1' }
@@ -41,6 +41,22 @@ vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
import { registerBuiltinTools } from '../builtin-tools'
import { ToolRegistry } from '../tool-registry'
+import type { AgentRunContext } from '../../agent-context'
+
+/** A complete run context — the shape the executors are really handed. */
+function makeRun(over: Partial<AgentRunContext> = {}): AgentRunContext {
+ return {
+ token: 'test-run',
+ chatId: null,
+ conversationId: null,
+ workspace: null,
+ artifactMode: false,
+ readOnlyShellTurn: false,
+ mode: null,
+ artifacts: [],
+ ...over,
+ }
+}
const registry = new ToolRegistry()
registerBuiltinTools(registry)
@@ -68,7 +84,7 @@ describe('shell_execute honours the run\'s Stop', () => {
it('reads the signal off the run object too, for a nested sub-agent loop', async () => {
const ctrl = new AbortController()
ctrl.abort()
- await registry.execute('shell_execute', { command: 'ls' }, 1, { abortSignal: ctrl.signal } as any)
+ await registry.execute('shell_execute', { command: 'ls' }, 1, makeRun({ abortSignal: ctrl.signal }))
expect(ran()).toHaveLength(0)
})
diff --git a/src/api/mcp/__tests__/tool-merge-redirect.test.ts b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
index 50cfec73..7dc28570 100644
--- a/src/api/mcp/__tests__/tool-merge-redirect.test.ts
+++ b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
@@ -12,10 +12,10 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
-const backendCalls: { cmd: string; body: any }[] = []
+const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
vi.mock('../../backend', () => ({
- backendCall: vi.fn(async (cmd: string, body: any) => {
+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
backendCalls.push({ cmd, body })
if (cmd === 'shell_execute') {
return { stdout: '# branch.head master\n', stderr: '', exitCode: 0 }
@@ -35,6 +35,7 @@ vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
import { runRetiredTool, RETIRED_TOOL_NAMES, registerBuiltinTools } from '../builtin-tools'
import { ToolRegistry } from '../tool-registry'
import { DEFAULT_PERMISSIONS } from '../types'
+import type { ToolArgs } from '../types'
import { setReadOnlyShellTurn } from '../../agent-context'
beforeEach(() => {
@@ -91,7 +92,7 @@ describe('the read-only gate lives at the executor now', () => {
describe('shell_execute refuses by COMMAND on a read-only turn (E7 priority)', () => {
const registry = new ToolRegistry()
registerBuiltinTools(registry)
- const shell = (args: Record<string, any>) => registry.execute('shell_execute', args)
+ const shell = (args: ToolArgs) => registry.execute('shell_execute', args)
it('the reviewer can still look at the diff', async () => {
setReadOnlyShellTurn(true)
@@ -139,7 +140,7 @@ describe('retired names survive the step executor (executeParallel)', () => {
registerBuiltinTools(registry)
const runtime = {
getTool: (name: string) => registry.resolveExecutable(name),
- execute: ((name: string, args: Record<string, any>) => registry.execute(name, args)) as any,
+ execute: (name: string, args: ToolArgs) => registry.execute(name, args),
// awaitApproval is required (audit AGT-1); this fixture exercises the
// redirect path, not the gate.
awaitApproval: async () => true,
diff --git a/src/api/mcp/__tests__/tool-registry-external.test.ts b/src/api/mcp/__tests__/tool-registry-external.test.ts
index 22b6b5ee..373da033 100644
--- a/src/api/mcp/__tests__/tool-registry-external.test.ts
+++ b/src/api/mcp/__tests__/tool-registry-external.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest'
import { ToolRegistry } from '../tool-registry'
import { commandCandidatesForPlatform } from '../external-client'
-import type { MCPToolDefinition, PermissionMap } from '../types'
+import type { MCPToolDefinition, PermissionMap, ToolArgs } from '../types'
const fullPerms: PermissionMap = {
filesystem: 'auto',
@@ -26,7 +26,7 @@ const mkTool = (name: string, extra: Partial<MCPToolDefinition> = {}): MCPToolDe
describe('ToolRegistry — registerExternal name binding', () => {
it('routes each tool call to the right tool name via the two-arg executor', async () => {
const registry = new ToolRegistry()
- const calls: { name: string; args: any }[] = []
+ const calls: { name: string; args: ToolArgs }[] = []
registry.registerExternal(
'srv1',
[mkTool('search'), mkTool('read'), mkTool('write')],
@@ -43,7 +43,7 @@ describe('ToolRegistry — registerExternal name binding', () => {
it('supports legacy single-arg executor (backcompat)', async () => {
const registry = new ToolRegistry()
- const legacy = vi.fn(async (_args: Record<string, any>) => 'legacy-ok')
+ const legacy = vi.fn(async (_args: ToolArgs) => 'legacy-ok')
registry.registerExternal('srv2', [mkTool('only')], legacy)
expect(await registry.execute('only', {})).toBe('legacy-ok')
expect(legacy).toHaveBeenCalledOnce()
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 877d02af..9ae0f10c 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1,6 +1,10 @@
// Built-in tool definitions + executors — replaces hardcoded AGENT_TOOL_DEFS
-import type { JSONSchemaProp, MCPToolDefinition } from './types'
+import type { JSONSchemaProp, MCPToolDefinition, ToolArgs } from './types'
+import type {
+ ShellExecResult, FsReadResult, FsWriteResult, FsListResult, FsSearchResult,
+ WebSearchResult, WebFetchResult, ProcessListResult, ScreenshotResult, CurrentTimeResult,
+} from '../../types/bridge'
import type { ToolRegistry } from './tool-registry'
import { backendCall, fetchExternal } from '../backend'
import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
@@ -17,6 +21,8 @@ import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, get
import { pathToFileUrl } from '../../lib/local-media-url'
import { RETIRED_MUTATING_NAMES } from '../../lib/retired-tools'
import { resolveMlxModel, defaultMlxImageModel } from '../../lib/mlx-model-match'
+import type { Runner } from '../agents/test-runner'
+import type { VramHandoffArgs } from '../vram-handoff'
/**
* Helper: current chat id (+ folder workspace) as a fragment to spread into
@@ -41,6 +47,34 @@ function chatCtx(run?: AgentRunContext): { chatId?: string; workingDirectory?: s
return { chatId: id }
}
+/**
+ * Argument readers.
+ *
+ * A tool's `args` come from the MODEL: the declared `inputSchema` is a hint in
+ * a prompt, not a contract anything enforces before the executor runs. So a
+ * `path` can arrive as a number and `background` as the string "false". These
+ * three are the only sanctioned way into that object — each one checks the
+ * type it promises instead of trusting the schema.
+ */
+function argString(args: ToolArgs, ...keys: string[]): string {
+ for (const key of keys) {
+ const v = args[key]
+ if (typeof v === 'string' && v) return v
+ }
+ return ''
+}
+
+function argNumber(args: ToolArgs, key: string): number | undefined {
+ const v = args[key]
+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined
+}
+
+/** `undefined` rather than '' — for the many payload fields that mean "unset". */
+function argOptString(args: ToolArgs, key: string): string | undefined {
+ const v = args[key]
+ return typeof v === 'string' && v ? v : undefined
+}
+
// ── Tool Definitions ────────────────────────────────────────────
/**
@@ -412,10 +446,10 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
// ── Executors ────────────────────────────────────────────────────
-async function executeWebSearch(args: Record<string, any>): Promise<string> {
+async function executeWebSearch(args: ToolArgs): Promise<string> {
const { useSettingsStore } = await import('../../stores/settingsStore')
const searchSettings = useSettingsStore.getState().settings
- const data = await backendCall('web_search', {
+ const data = await backendCall<WebSearchResult>('web_search', {
query: args.query,
count: args.maxResults || 5,
provider: searchSettings.searchProvider || 'auto',
@@ -424,7 +458,7 @@ async function executeWebSearch(args: Record<string, any>): Promise<string> {
})
if (Array.isArray(data.results) && data.results.length > 0) {
const lines = data.results
- .map((r: any, i: number) => `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`)
+ .map((r, i) => `${i + 1}. ${r.title}\n ${r.url}\n ${r.snippet}`)
.join('\n\n')
// When the configured paid provider failed we still return free-tier
// results, but say why the configured one didn't answer — a silently
@@ -441,8 +475,8 @@ async function executeWebSearch(args: Record<string, any>): Promise<string> {
return JSON.stringify(data)
}
-async function executeWebFetch(args: Record<string, any>): Promise<string> {
- const url = args.url
+async function executeWebFetch(args: ToolArgs): Promise<string> {
+ const url = argString(args, 'url')
if (!url) return 'Error: No URL provided'
// Preferred path: use the Rust `web_fetch` command which strips HTML
@@ -451,10 +485,7 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {
// ~4 000 chars of a half-cleaned body — that's why the agent kept
// complaining it "only sees the header" of the page.
try {
- const data = await backendCall<{ url: string; status: number; contentType: string; title: string; text: string; truncated: boolean }>(
- 'web_fetch',
- { url }
- )
+ const data = await backendCall<WebFetchResult>('web_fetch', { url })
const parts: string[] = []
if (data.title) parts.push(`Title: ${data.title}`)
parts.push(`URL: ${data.url}`)
@@ -467,7 +498,7 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {
// Fallback: legacy fetchExternal + htmlToText (used in browser / dev mode
// where the Rust command isn't reachable).
try {
- const maxLength = args.maxLength || 24000
+ const maxLength = argNumber(args, 'maxLength') || 24000
const html = await fetchExternal(url)
const text = htmlToText(html)
if (text.length > maxLength) return text.substring(0, maxLength) + '\n\n[...truncated]'
@@ -478,8 +509,8 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {
}
}
-async function executeFileRead(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
- const data = await backendCall('fs_read', { path: args.path, ...chatCtx(run) })
+async function executeFileRead(args: ToolArgs, run?: AgentRunContext): Promise<string> {
+ const data = await backendCall<FsReadResult>('fs_read', { path: args.path, ...chatCtx(run) })
// A binary file comes back as a marker with its size, never as content.
// Handing the model raw bytes-as-text is a corruption trap: it treats them as
// content and a later file_write persists that string, mangling the file.
@@ -494,7 +525,7 @@ async function executeFileRead(args: Record<string, any>, run?: AgentRunContext)
}
/** Last path segment, defaulting to file.txt. */
-function artifactBaseName(p: any): string {
+function artifactBaseName(p: unknown): string {
const raw = typeof p === 'string' && p.trim() ? p.trim() : 'file.txt'
return raw.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || 'file.txt'
}
@@ -514,7 +545,7 @@ function mimeForName(name: string): string {
return map[ext] || 'text/plain'
}
-async function executeFileWrite(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeFileWrite(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const content = typeof args.content === 'string' ? args.content : String(args.content ?? '')
// Plain-chat artifact mode (ChatGPT-style, David 2026-06-12): in the NORMAL
// chat, a "file write" must NOT touch disk — capture it so it renders inline
@@ -525,7 +556,7 @@ async function executeFileWrite(args: Record<string, any>, run?: AgentRunContext
captureChatArtifact(name, content, mimeForName(name), run)
return `Created "${name}" (${formatBytes(content.length)}). It is shown to the user right here in the chat with a preview and a Download button — nothing was written to disk. Do not call file_read on it; just tell the user it's ready.`
}
- const data = await backendCall('fs_write', { path: args.path, content, ...chatCtx(run) })
+ const data = await backendCall<FsWriteResult>('fs_write', { path: args.path, content, ...chatCtx(run) })
// Rust returns {status: 'saved'|'unchanged', path: <absolute>, bytes}. Surface
// the real path so the model (and the file-change event) knows WHERE the write
// landed — especially important when chatId is None and Rust routes a relative
@@ -537,23 +568,23 @@ async function executeFileWrite(args: Record<string, any>, run?: AgentRunContext
return JSON.stringify(data)
}
-async function executeFileEdit(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeFileEdit(args: ToolArgs, run?: AgentRunContext): Promise<string> {
// Plain-chat artifact mode has no files on disk — file_edit makes no sense
// there. Steer to file_write (which captures a document artifact) instead of
// silently reaching into the agent sandbox.
if (isChatArtifactMode(run)) {
return 'file_edit is not available in plain chat (there are no files on disk here). Use file_write to create or replace a document.'
}
- const path = typeof args.path === 'string' ? args.path : ''
+ const path = argString(args, 'path')
if (!path) return 'Error: file_edit requires a "path".'
- const oldString = typeof args.old_string === 'string' ? args.old_string : ''
- const newString = typeof args.new_string === 'string' ? args.new_string : ''
+ const oldString = argString(args, 'old_string')
+ const newString = argString(args, 'new_string')
// Read the CURRENT content (workspace-aware). file_edit only edits an
// existing text file — for a new file the model must use file_write.
- let data: any
+ let data: FsReadResult
try {
- data = await backendCall('fs_read', { path, ...chatCtx(run) })
+ data = await backendCall<FsReadResult>('fs_read', { path, ...chatCtx(run) })
} catch (e) {
return `Error: file_edit could not read ${path}: ${e instanceof Error ? e.message : String(e)}. To create a new file use file_write.`
}
@@ -576,14 +607,14 @@ async function executeFileEdit(args: Record<string, any>, run?: AgentRunContext)
}
}
- const w = await backendCall('fs_write', { path, content: res.content, ...chatCtx(run) })
+ const w = await backendCall<FsWriteResult>('fs_write', { path, content: res.content, ...chatCtx(run) })
if (w.status === 'saved' && w.path) return `Edited ${w.path} (1 replacement).`
if (w.status === 'unchanged' && w.path) return `No change written to ${w.path} (content already matched).`
return JSON.stringify(w)
}
-async function executeFileList(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
- const data = await backendCall('fs_list', {
+async function executeFileList(args: ToolArgs, run?: AgentRunContext): Promise<string> {
+ const data = await backendCall<FsListResult>('fs_list', {
path: args.path,
recursive: args.recursive || false,
pattern: args.pattern || null,
@@ -598,14 +629,14 @@ async function executeFileList(args: Record<string, any>, run?: AgentRunContext)
})
if (Array.isArray(data.entries)) {
return data.entries
- .map((e: any) => `${e.isDir ? '[DIR]' : ''} ${e.name} (${formatBytes(e.size)}) ${e.path}`)
+ .map((e) => `${e.isDir ? '[DIR]' : ''} ${e.name} (${formatBytes(e.size)}) ${e.path}`)
.join('\n')
}
return JSON.stringify(data)
}
-async function executeFileSearch(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
- const data = await backendCall('fs_search', {
+async function executeFileSearch(args: ToolArgs, run?: AgentRunContext): Promise<string> {
+ const data = await backendCall<FsSearchResult>('fs_search', {
path: args.path,
pattern: args.pattern,
max_results: args.maxResults || 50,
@@ -613,8 +644,8 @@ async function executeFileSearch(args: Record<string, any>, run?: AgentRunContex
})
if (Array.isArray(data.results)) {
return data.results
- .map((r: any) => {
- const matches = r.matches?.map((m: any) => ` L${m.line}: ${m.text}`).join('\n') || ''
+ .map((r) => {
+ const matches = r.matches?.map((m) => ` L${m.line}: ${m.text}`).join('\n') || ''
return `${r.file}\n${matches}`
})
.join('\n\n')
@@ -623,7 +654,7 @@ async function executeFileSearch(args: Record<string, any>, run?: AgentRunContex
}
async function executeShellExecute(
- args: Record<string, any>,
+ args: ToolArgs,
run?: AgentRunContext,
signal?: AbortSignal,
): Promise<string> {
@@ -640,18 +671,18 @@ async function executeShellExecute(
const abort = signal ?? run?.abortSignal
if (abort?.aborted) return 'Cancelled: the user stopped the run before this command started.'
// Background-task actions: the three shell_task_* tools folded in (2.6.6).
- const task = typeof args.task === 'string' ? args.task : ''
+ const task = argString(args, 'task')
if (task === 'list') return executeShellTaskList()
if (task === 'status' || task === 'kill') {
if (task === 'kill' && isReadOnlyShellTurn(run)) {
return 'Refused: this turn is read-only (/review, Code-Review Mode or Plan mode); killing a task changes state.'
}
- const id = args.task_id ?? args.id
+ const id = argString(args, 'task_id', 'id')
if (!id) return `shell_execute: task "${task}" needs a task_id.`
return task === 'status' ? executeShellTaskStatus({ id }) : executeShellTaskKill({ id })
}
- const command = typeof args.command === 'string' ? args.command.trim() : ''
+ const command = argString(args, 'command').trim()
if (!command) return 'shell_execute: `command` is required (or pass task: "status" | "list" | "kill").'
const { rejectShellCommand, commandTimeoutMs, commandKind, isReadOnlyCommand } = await import(
@@ -672,14 +703,14 @@ async function executeShellExecute(
// An explicit timeout wins; otherwise a recognised test run keeps the old
// run_tests budget (300 s) instead of the shell default.
- const timeout = args.timeout || commandTimeoutMs(command, 120000)
- const data = await backendCall('shell_execute', {
+ const timeout = argNumber(args, 'timeout') || commandTimeoutMs(command, 120000)
+ const data = await backendCall<ShellExecResult>('shell_execute', {
command,
args: args.args || null,
cwd: args.cwd || null,
timeout,
shell: args.shell || null,
- stdin: typeof args.stdin === 'string' && args.stdin ? args.stdin : null,
+ stdin: argOptString(args, 'stdin') ?? null,
...chatCtx(run),
})
const output = data.stdout || ''
@@ -718,7 +749,7 @@ async function executeShellExecute(
}
async function executeCodeExecute(
- args: Record<string, any>,
+ args: ToolArgs,
run?: AgentRunContext,
signal?: AbortSignal,
): Promise<string> {
@@ -726,7 +757,7 @@ async function executeCodeExecute(
if ((signal ?? run?.abortSignal)?.aborted) {
return 'Cancelled: the user stopped the run before this code ran.'
}
- const data = await backendCall('execute_code', { code: args.code, timeout: 30000, ...chatCtx(run) })
+ const data = await backendCall<ShellExecResult>('execute_code', { code: args.code, timeout: 30000, ...chatCtx(run) })
const output = data.stdout || ''
const err = data.stderr || ''
if (data.timedOut) return `Timed out.\n${err}`
@@ -734,8 +765,13 @@ async function executeCodeExecute(
return output || (err ? `stderr: ${err}` : 'Done.')
}
-async function runShell(command: string, cwd: string | undefined, timeout = 60000, run?: AgentRunContext) {
- return backendCall('shell_execute', {
+async function runShell(
+ command: string,
+ cwd: string | undefined,
+ timeout = 60000,
+ run?: AgentRunContext,
+): Promise<ShellExecResult> {
+ return backendCall<ShellExecResult>('shell_execute', {
command,
args: null,
cwd: cwd || null,
@@ -746,14 +782,18 @@ async function runShell(command: string, cwd: string | undefined, timeout = 6000
}
async function executeShellExecuteBg(
- args: Record<string, any>,
+ args: ToolArgs,
run?: AgentRunContext,
signal?: AbortSignal,
): Promise<string> {
const { bgStart, bgKill } = await import('../agents/bg-tasks')
// Thread the chat context through, or the task starts in LU's own directory
// instead of the workspace the foreground shell tool uses.
- const { id } = await bgStart({ command: args.command, cwd: args.cwd, ...chatCtx(run) })
+ const { id } = await bgStart({
+ command: argString(args, 'command'),
+ cwd: argOptString(args, 'cwd'),
+ ...chatCtx(run),
+ })
// A detached task outlives the turn that started it BY DESIGN, but it must
// not outlive the user pressing Stop: nothing polls it after the run ends, so
// an unattended `npm run build`/deploy script would keep writing to the repo
@@ -770,18 +810,19 @@ async function executeShellExecuteBg(
return `Task started: ${id}. Use shell_task_status to poll, shell_task_kill to cancel.`
}
-async function executeShellTaskStatus(args: Record<string, any>): Promise<string> {
+async function executeShellTaskStatus(args: ToolArgs): Promise<string> {
const { bgStatus, renderBgStatusOneLine } = await import('../agents/bg-tasks')
- const s = await bgStatus(args.id)
+ const s = await bgStatus(argString(args, 'id'))
const head = renderBgStatusOneLine(s)
const tail = s.output_tail ? `\n---\n${s.output_tail}` : ''
return `${head}${tail}`
}
-async function executeShellTaskKill(args: Record<string, any>): Promise<string> {
+async function executeShellTaskKill(args: ToolArgs): Promise<string> {
const { bgKill } = await import('../agents/bg-tasks')
- const r = await bgKill(args.id)
- return r.cancelled ? `Cancelled ${args.id}.` : `${args.id}: already finished.`
+ const id = argString(args, 'id')
+ const r = await bgKill(id)
+ return r.cancelled ? `Cancelled ${id}.` : `${id}: already finished.`
}
async function executeShellTaskList(): Promise<string> {
@@ -791,9 +832,9 @@ async function executeShellTaskList(): Promise<string> {
return tasks.map(renderBgStatusOneLine).join('\n')
}
-async function executeGitStatus(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGitStatus(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { parseGitStatus, renderGitStatus } = await import('../agents/git-tools')
- const data = await runShell('git status --porcelain=2 --branch', args.cwd, undefined, run)
+ const data = await runShell('git status --porcelain=2 --branch', argOptString(args, 'cwd'), undefined, run)
if (data.exitCode && data.exitCode !== 0) {
return `git_status failed: ${data.stderr || data.stdout || `exit ${data.exitCode}`}`
}
@@ -801,15 +842,20 @@ async function executeGitStatus(args: Record<string, any>, run?: AgentRunContext
return renderGitStatus(parsed)
}
-async function executeGitCommit(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGitCommit(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { buildGitCommitCommand } = await import('../agents/git-tools')
+ // `files` is shell-quoted per entry downstream, so a non-string in the list
+ // would have been interpolated as "[object Object]" into a `git add`.
+ const files = Array.isArray(args.files)
+ ? args.files.filter((f): f is string => typeof f === 'string')
+ : undefined
const cmd = buildGitCommitCommand({
- message: args.message,
- files: Array.isArray(args.files) ? args.files : undefined,
+ message: argString(args, 'message'),
+ files,
allTracked: !!args.allTracked,
})
if (!cmd) return 'git_commit: a non-empty `message` is required.'
- const data = await runShell(cmd, args.cwd, undefined, run)
+ const data = await runShell(cmd, argOptString(args, 'cwd'), undefined, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `git_commit failed (exit ${data.exitCode}):\n${output}`
@@ -818,14 +864,16 @@ async function executeGitCommit(args: Record<string, any>, run?: AgentRunContext
return m ? `Committed on ${m[1]} as ${m[2]}.\n${output}` : output
}
-async function executeGitPush(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGitPush(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { shellQuote } = await import('../agents/git-tools')
const flags: string[] = []
if (args.setUpstream) flags.push('-u')
- if (args.remote) flags.push(shellQuote(args.remote))
- if (args.branch) flags.push(shellQuote(args.branch))
+ const remote = argOptString(args, 'remote')
+ if (remote) flags.push(shellQuote(remote))
+ const branch = argOptString(args, 'branch')
+ if (branch) flags.push(shellQuote(branch))
const cmd = `git push ${flags.join(' ')}`.trim()
- const data = await runShell(cmd, args.cwd, 120000, run)
+ const data = await runShell(cmd, argOptString(args, 'cwd'), 120000, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `git_push failed (exit ${data.exitCode}):\n${output}`
@@ -833,11 +881,12 @@ async function executeGitPush(args: Record<string, any>, run?: AgentRunContext):
return output || 'git push: ok.'
}
-async function executeGitLog(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGitLog(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { parseGitLog } = await import('../agents/git-tools')
- const limit = typeof args.limit === 'number' ? Math.max(1, Math.min(200, args.limit)) : 20
+ const rawLimit = argNumber(args, 'limit')
+ const limit = rawLimit === undefined ? 20 : Math.max(1, Math.min(200, rawLimit))
const cmd = `git log --oneline -n ${limit}`
- const data = await runShell(cmd, args.cwd, undefined, run)
+ const data = await runShell(cmd, argOptString(args, 'cwd'), undefined, run)
if (data.exitCode && data.exitCode !== 0) {
return `git_log failed: ${data.stderr || data.stdout || `exit ${data.exitCode}`}`
}
@@ -846,13 +895,13 @@ async function executeGitLog(args: Record<string, any>, run?: AgentRunContext):
return entries.map((e) => `${e.sha} ${e.subject}`).join('\n')
}
-async function executeGitDiff(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGitDiff(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { shellQuote } = await import('../agents/git-tools')
const parts = ['git', 'diff']
if (args.staged) parts.push('--cached')
if (args.ref) parts.push(shellQuote(String(args.ref)))
if (args.path) parts.push('--', shellQuote(String(args.path)))
- const data = await runShell(parts.join(' '), args.cwd, 120000, run)
+ const data = await runShell(parts.join(' '), argOptString(args, 'cwd'), 120000, run)
if (data.exitCode && data.exitCode !== 0 && data.exitCode !== 1) {
return `git_diff failed: ${data.stderr || `exit ${data.exitCode}`}`
}
@@ -861,9 +910,9 @@ async function executeGitDiff(args: Record<string, any>, run?: AgentRunContext):
return out.length > 16000 ? `${out.slice(0, 16000)}\n…(truncated)` : out
}
-async function executeProjectInit(args: Record<string, any>): Promise<string> {
+async function executeProjectInit(args: ToolArgs): Promise<string> {
const { findRecipe, renderInitPlan, listRecipes } = await import('../agents/project-init')
- const recipeId = typeof args.recipe === 'string' ? args.recipe.trim() : ''
+ const recipeId = argString(args, 'recipe').trim()
if (!recipeId) {
const list = listRecipes()
return [
@@ -881,7 +930,7 @@ async function executeProjectInit(args: Record<string, any>): Promise<string> {
return renderInitPlan(recipe)
}
-async function executePrResume(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executePrResume(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { parsePrUrl, normalisePrJson, renderPrResume } = await import('../agents/pr-resume')
const { shellQuote } = await import('../agents/git-tools')
const loc = parsePrUrl(String(args.url ?? ''))
@@ -892,14 +941,14 @@ async function executePrResume(args: Record<string, any>, run?: AgentRunContext)
const repo = shellQuote(`${loc.owner}/${loc.repo}`)
const view = await runShell(
`gh pr view ${loc.number} --repo ${repo} --json title,body,state,headRefName,baseRefName,author,comments`,
- args.cwd,
+ argOptString(args, 'cwd'),
60000,
run,
)
if (view.exitCode && view.exitCode !== 0) {
return `pr_resume: gh pr view failed (exit ${view.exitCode}): ${view.stderr || view.stdout || ''}`
}
- let raw: any
+ let raw: unknown
try {
raw = JSON.parse(view.stdout || '{}')
} catch (e) {
@@ -908,7 +957,7 @@ async function executePrResume(args: Record<string, any>, run?: AgentRunContext)
const meta = normalisePrJson(raw, String(args.url))
const diff = await runShell(
`gh pr diff ${loc.number} --repo ${repo}`,
- args.cwd,
+ argOptString(args, 'cwd'),
60000,
run,
)
@@ -918,15 +967,15 @@ async function executePrResume(args: Record<string, any>, run?: AgentRunContext)
})
}
-async function executeGhPrCreate(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeGhPrCreate(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { buildGhPrCreateCommand } = await import('../agents/git-tools')
const cmd = buildGhPrCreateCommand({
- title: args.title,
- body: args.body ?? '',
- base: args.base,
+ title: argString(args, 'title'),
+ body: argString(args, 'body'),
+ base: argOptString(args, 'base'),
})
if (!cmd) return 'gh_pr_create: a non-empty `title` is required.'
- const data = await runShell(cmd, args.cwd, 60000, run)
+ const data = await runShell(cmd, argOptString(args, 'cwd'), 60000, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `gh_pr_create failed (exit ${data.exitCode}):\n${output}`
@@ -936,18 +985,18 @@ async function executeGhPrCreate(args: Record<string, any>, run?: AgentRunContex
return urlMatch ? `Opened PR: ${urlMatch[0]}\n${output}` : output
}
-async function executeRunTests(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeRunTests(args: ToolArgs, run?: AgentRunContext): Promise<string> {
const { commandForRunner, detectRunnerFromFiles, parseForRunner, renderResult } =
await import('../agents/test-runner')
- let runner = args.runner as Runner | undefined
- let command = typeof args.command === 'string' ? args.command : ''
+ let runner = argRunner(args)
+ let command = argString(args, 'command')
if (!command) {
if (!runner) {
// List the workspace root to find a config marker.
try {
- const listing = await backendCall('fs_list', {
+ const listing = await backendCall<FsListResult>('fs_list', {
path: '.',
recursive: false,
...chatCtx(run),
@@ -957,14 +1006,14 @@ async function executeRunTests(args: Record<string, any>, run?: AgentRunContext)
// empty command → "could not detect a test runner" for every project,
// so the advertised auto-detect never once fired.
const names: string[] = Array.isArray(listing.entries)
- ? listing.entries.map((it: any) => String(it.name ?? '')).filter(Boolean)
+ ? listing.entries.map((it) => it.name).filter(Boolean)
: []
runner = detectRunnerFromFiles(names)
} catch {
runner = 'unknown'
}
}
- command = commandForRunner(runner as Runner)
+ command = commandForRunner(runner ?? 'unknown')
}
if (!command) {
return 'run_tests: could not detect a test runner. Pass `command` or `runner` explicitly.'
@@ -974,11 +1023,11 @@ async function executeRunTests(args: Record<string, any>, run?: AgentRunContext)
command,
args: null,
cwd: args.cwd || null,
- timeout: args.timeout || 300000,
+ timeout: argNumber(args, 'timeout') || 300000,
shell: null,
...chatCtx(run),
}
- const data = await backendCall('shell_execute', shellArgs)
+ const data = await backendCall<ShellExecResult>('shell_execute', shellArgs)
if (data.timedOut) {
return `Test run timed out after ${shellArgs.timeout / 1000}s. Partial output:\n${(data.stdout || '').slice(-2000)}`
}
@@ -986,33 +1035,53 @@ async function executeRunTests(args: Record<string, any>, run?: AgentRunContext)
const parsed = parseForRunner(runner ?? 'unknown', combined)
return renderResult(parsed)
}
-type Runner = 'vitest' | 'cargo' | 'pytest' | 'jest' | 'unknown'
+/**
+ * `runner` as the model may send it. A value the runner list does not know
+ * becomes 'unknown', which `commandForRunner` maps to the empty command — the
+ * same refusal an unrecognised string produced before, now without an `as`
+ * that let any string through as a Runner.
+ */
+function argRunner(args: ToolArgs): Runner | undefined {
+ const v = args.runner
+ if (!v) return undefined // absent: auto-detect from the workspace, as before
+ if (typeof v === 'string') {
+ switch (v) {
+ case 'vitest':
+ case 'cargo':
+ case 'pytest':
+ case 'jest':
+ case 'unknown':
+ return v
+ }
+ }
+ return 'unknown'
+}
async function executeSystemInfo(): Promise<string> {
- const data = await backendCall('system_info', {})
+ const data = await backendCall<Record<string, unknown>>('system_info', {})
return Object.entries(data).map(([k, v]) => `${k}: ${v}`).join('\n')
}
async function executeProcessList(): Promise<string> {
- const data = await backendCall('process_list', {})
+ const data = await backendCall<ProcessListResult>('process_list', {})
if (Array.isArray(data.processes)) {
return data.processes
.slice(0, 30)
- .map((p: any) => `${p.name} (PID: ${p.pid}) — ${formatBytes(p.memory)} RAM, ${p.cpu?.toFixed(1)}% CPU`)
+ .map((p) => `${p.name} (PID: ${p.pid}) — ${formatBytes(p.memory)} RAM, ${p.cpu?.toFixed(1)}% CPU`)
.join('\n')
}
return JSON.stringify(data)
}
async function executeScreenshot(): Promise<string> {
- const data = await backendCall('screenshot', {})
+ const data = await backendCall<ScreenshotResult>('screenshot', {})
if (data.image) {
return `[Screenshot captured: base64 PNG, ${Math.round(data.image.length / 1024)}KB]`
}
return JSON.stringify(data)
}
-async function executeImageGenerate(args: Record<string, any>): Promise<string> {
+async function executeImageGenerate(args: ToolArgs): Promise<string> {
// Feature EE (v2.5.0): the whole generation flow now goes through the VRAM
// hand-off orchestrator. It resolves the image model (args.model or first
// installed), decides whether the resident local text model has to be evicted
@@ -1021,12 +1090,10 @@ async function executeImageGenerate(args: Record<string, any>): Promise<string>
// model afterwards. The returned string keeps the EXACT F1 contract —
// `Image generated: <file> (prompt: "...")\n<comfyui /view URL>` — so
// ToolCallBlock renders it inline and useAgentChat feeds it back unchanged.
- const prompt = args.prompt || args.description || ''
- if (!prompt) return 'Error: No prompt provided for image generation.'
- const settings = (args.settings && typeof args.settings === 'object') ? args.settings : {}
- const flat: Record<string, any> = {}
- for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
- const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+ const rawPrompt = args.prompt || args.description || ''
+ if (!rawPrompt) return 'Error: No prompt provided for image generation.'
+ const prompt = String(rawPrompt)
+ const merged = mergeMediaArgs(args)
// Hard rule: on macOS, local image generation is Apple MLX only — ComfyUI
// never runs there (see isMlxImageHost() / useCreate.ts's MLX image
@@ -1045,7 +1112,7 @@ async function executeImageGenerate(args: Record<string, any>): Promise<string>
return vramHandoffGenerate('image', merged)
}
-async function executeVideoGenerate(args: Record<string, any>): Promise<string> {
+async function executeVideoGenerate(args: ToolArgs): Promise<string> {
// Feature EE (v2.5.0): text-to-video via the same hand-off orchestrator.
// Picks the first installed video model (or args.model), detects the video
// backend (Wan / AnimateDiff), evicts the local text model from VRAM if it
@@ -1057,10 +1124,7 @@ async function executeVideoGenerate(args: Record<string, any>): Promise<string>
// defaults a gentle-motion prompt for video, normalizes a snake_case
// input_image alias, and falls back to the last generated image — so the
// "animate the image you just made" chain works even with a sloppy call.
- const settings = (args.settings && typeof args.settings === 'object') ? args.settings : {}
- const flat: Record<string, any> = {}
- for (const [k, v] of Object.entries(args)) if (k !== 'settings' && v !== undefined) flat[k] = v
- const merged: Record<string, any> = { ...settings, ...flat } // explicit flat args win; undefined never clobbers settings
+ const merged = mergeMediaArgs(args)
// Hard rule: on macOS, local video generation is Apple MLX only — ComfyUI
// never runs there. Route around vram-handoff entirely (no VRAM juggling —
@@ -1096,7 +1160,7 @@ function sleep(ms: number): Promise<void> {
* renders it inline; only the url is a local blob: URL instead of a ComfyUI
* /view URL.
*/
-async function executeImageGenerateMlx(prompt: string, merged: Record<string, any>): Promise<string> {
+async function executeImageGenerateMlx(prompt: string, merged: VramHandoffArgs): Promise<string> {
let installed: MlxImageModel[]
try {
installed = (await listMlxImageModels()).filter((m) => m.installed)
@@ -1160,7 +1224,7 @@ async function executeImageGenerateMlx(prompt: string, merged: Record<string, an
* "init_image not found: ...", the same honest-rejection shape this codebase
* uses for every other unsupported value, rather than silently ignoring it.
*/
-async function executeVideoGenerateMlx(prompt: string, merged: Record<string, any>): Promise<string> {
+async function executeVideoGenerateMlx(prompt: string, merged: VramHandoffArgs): Promise<string> {
let status: Awaited<ReturnType<typeof getVideoStatus>>
try {
status = await getVideoStatus()
@@ -1242,7 +1306,7 @@ async function executeVideoGenerateMlx(prompt: string, merged: Record<string, an
return 'Video generation timed out after 60 minutes; the generation was stopped.'
}
-async function executeTodoWrite(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+async function executeTodoWrite(args: ToolArgs, run?: AgentRunContext): Promise<string> {
// Purely conversation state: no backend call, no permission gate, nothing
// that can fail on a machine. The one real failure is having no conversation
// to attach the plan to, which happens when a tool runs outside a loop.
@@ -1259,12 +1323,9 @@ async function executeTodoWrite(args: Record<string, any>, run?: AgentRunContext
return summarizeTodos(todos)
}
-async function executeGetCurrentTime(_args: Record<string, any>): Promise<string> {
+async function executeGetCurrentTime(_args: ToolArgs): Promise<string> {
try {
- const data = await backendCall<{ unix: number; iso_local: string; iso_utc: string; timezone: string; timezone_offset: number }>(
- 'get_current_time',
- {},
- )
+ const data = await backendCall<CurrentTimeResult>('get_current_time', {})
return `Local: ${data.iso_local} ${data.timezone}\nUTC: ${data.iso_utc}\nUnix: ${data.unix}`
} catch (e) {
return `Error: ${e instanceof Error ? e.message : String(e)}`
@@ -1273,8 +1334,8 @@ async function executeGetCurrentTime(_args: Record<string, any>): Promise<string
let _workflowDepth = 0
-async function executeRunWorkflow(args: Record<string, any>): Promise<string> {
- const workflowName = args.name
+async function executeRunWorkflow(args: ToolArgs): Promise<string> {
+ const workflowName = argString(args, 'name')
if (!workflowName) return 'Error: No workflow name provided'
if (_workflowDepth >= 5) return 'Error: Maximum workflow nesting depth (5) exceeded'
@@ -1317,6 +1378,29 @@ async function executeRunWorkflow(args: Record<string, any>): Promise<string> {
// ── Helpers ─────────────────────────────────────────────────────
+/**
+ * Fold a media tool's call into the one settings object the generation
+ * pipeline takes: the nested `settings` first, then the flat top-level args on
+ * top (an explicit flat argument wins; `undefined` never clobbers a setting).
+ *
+ * The result is a `VramHandoffArgs`, whose named fields the pipeline reads
+ * with its own `typeof` guards and whose index signature carries everything
+ * else. The keys are copied one by one rather than spread because a spread
+ * would have to claim the arbitrary foreign values match the named fields;
+ * writing through the index signature claims nothing that isn't true.
+ */
+function mergeMediaArgs(args: ToolArgs): VramHandoffArgs {
+ const rawSettings = args.settings
+ const settings: Record<string, unknown> =
+ rawSettings && typeof rawSettings === 'object' ? { ...rawSettings } : {}
+ const merged: VramHandoffArgs = {}
+ for (const [k, v] of Object.entries(settings)) merged[k] = v
+ for (const [k, v] of Object.entries(args)) {
+ if (k !== 'settings' && v !== undefined) merged[k] = v
+ }
+ return merged
+}
+
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
@@ -1362,7 +1446,7 @@ function htmlToText(html: string): string {
const EXECUTOR_MAP: Record<
string,
- (args: Record<string, any>, run?: AgentRunContext, signal?: AbortSignal) => Promise<string>
+ (args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal) => Promise<string>
> = {
todo_write: executeTodoWrite,
web_search: executeWebSearch,
@@ -1425,7 +1509,7 @@ const RETIRED_HINT: Record<string, string> = {
shell_task_list: 'shell_execute with task: "list"',
}
-const RETIRED_EXECUTORS: Record<string, (args: Record<string, any>, run?: AgentRunContext) => Promise<string>> = {
+const RETIRED_EXECUTORS: Record<string, (args: ToolArgs, run?: AgentRunContext) => Promise<string>> = {
git_status: executeGitStatus,
git_log: executeGitLog,
git_diff: executeGitDiff,
@@ -1465,7 +1549,7 @@ export const RETIRED_EXECUTOR_NAMES: ReadonlySet<string> = new Set(Object.keys(R
*/
export async function runRetiredTool(
name: string,
- args: Record<string, any>,
+ args: ToolArgs,
run?: AgentRunContext,
): Promise<string | null> {
const exec = RETIRED_EXECUTORS[name]
diff --git a/src/api/mcp/external-client.ts b/src/api/mcp/external-client.ts
index e0496aa4..18b45f54 100644
--- a/src/api/mcp/external-client.ts
+++ b/src/api/mcp/external-client.ts
@@ -5,22 +5,107 @@
* and communicate via stdin/stdout JSON-RPC 2.0.
*/
-import type { MCPToolDefinition, MCPServerConfig } from './types'
+import type { Child } from '@tauri-apps/plugin-shell'
+import type { MCPToolDefinition, MCPServerConfig, ToolArgs } from './types'
import { log } from '../../lib/logger'
+import { isRecord, prop, asString, asNumber, asRecordArray, errorText } from '../../types/json-guards'
+
+// ── JSON-RPC message types ──────────────────────────────────────
+//
+// Everything arriving on stdout was written by a THIRD-PARTY process. The
+// request side we build ourselves and can type exactly; the response side is
+// `unknown` until `parseJsonRpcResponse` below has looked at it.
-// JSON-RPC message types
interface JsonRpcRequest {
jsonrpc: '2.0'
id: number
method: string
- params?: any
+ params?: unknown
}
interface JsonRpcResponse {
jsonrpc: '2.0'
- id: number
- result?: any
- error?: { code: number; message: string; data?: any }
+ /** Absent on a notification — the server may talk without being asked. */
+ id?: number
+ result?: unknown
+ error?: { code: number; message: string; data?: unknown }
+}
+
+/**
+ * Human-readable text for whatever a server put in `error`.
+ *
+ * The spec says an object with a `message`; real servers also send a bare
+ * string, and one sends a number. Since this text is the ONLY thing the user
+ * ever learns about the failure, a non-conforming value is rendered rather
+ * than discarded — that is strictly better than the `Error: undefined` the
+ * pre-typing code produced for exactly these lines.
+ */
+function jsonRpcErrorMessage(raw: unknown): string {
+ if (isRecord(raw)) {
+ const msg = asString(raw.message)
+ if (msg) return msg
+ }
+ return errorText(raw) || 'MCP server reported an error'
+}
+
+/**
+ * Narrow one parsed stdout line to a JSON-RPC response, or give up.
+ *
+ * Only the fields this client actually reads are required to be well-formed:
+ * an `id` that can address a pending request, and an `error` — which is
+ * honoured whenever it is PRESENT, whatever its shape. That is the load-bearing
+ * rule here: a server that answers `"error": "boom"` has failed, and treating
+ * the line as anything but a rejection would resolve the pending request with
+ * `undefined` and tell the model the tool ran. Only `undefined`/`null` — i.e.
+ * no error at all — is a success.
+ *
+ * Anything that is not a record, or carries no usable `id`, is a notification
+ * or noise and is ignored.
+ */
+function parseJsonRpcResponse(v: unknown): JsonRpcResponse | null {
+ if (!isRecord(v)) return null
+ const id = asNumber(v.id)
+ const rawError = v.error
+ let error: JsonRpcResponse['error']
+ if (rawError != null) {
+ error = {
+ code: (isRecord(rawError) ? asNumber(rawError.code) : undefined) ?? 0,
+ message: jsonRpcErrorMessage(rawError),
+ data: isRecord(rawError) ? rawError.data : rawError,
+ }
+ }
+ return { jsonrpc: '2.0', id, result: v.result, error }
+}
+
+/**
+ * Does this look like the JSON-Schema object a tool's `inputSchema` must be?
+ *
+ * Checked at the boundary: it is an object, its `type` says `'object'`, its
+ * `properties` is an object, and `required` — when present — is an array of
+ * strings. The property schemas INSIDE are deliberately not re-validated:
+ * `inputSchema` is forwarded verbatim to the model as the tool's `parameters`,
+ * and a real MCP server may legitimately use `anyOf` / `oneOf` / `$ref`, which
+ * `JSONSchemaProp` does not model. Rewriting those would change what the model
+ * is told the tool takes; dropping them would be worse.
+ *
+ * A server that sends a string, an array or a `properties: []` there gets the
+ * empty schema below instead — previously that value went straight into the
+ * prompt.
+ */
+function isToolInputSchema(v: unknown): v is MCPToolDefinition['inputSchema'] {
+ if (!isRecord(v)) return false
+ if (v.type !== 'object') return false
+ if (!isRecord(v.properties)) return false
+ if (v.required !== undefined
+ && !(Array.isArray(v.required) && v.required.every((r) => typeof r === 'string'))) return false
+ return true
+}
+
+/** The schema a tool gets when the server did not send a usable one. */
+const EMPTY_INPUT_SCHEMA: MCPToolDefinition['inputSchema'] = {
+ type: 'object',
+ properties: {},
+ required: [],
}
export class MCPExternalClient {
@@ -32,10 +117,10 @@ export class MCPExternalClient {
* server failed to connect with "Cannot read properties of undefined
* (reading 'write')".
*/
- private child: any = null
+ private child: Child | null = null
private requestId = 0
private pendingRequests = new Map<number, {
- resolve: (value: any) => void
+ resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}>()
@@ -133,14 +218,24 @@ export class MCPExternalClient {
// Discover tools
const toolsResult = await this.sendRequest('tools/list', {})
- const tools: MCPToolDefinition[] = (toolsResult.tools || []).map((t: any) => ({
- name: t.name,
- description: t.description || '',
- inputSchema: t.inputSchema || { type: 'object', properties: {}, required: [] },
- category: 'workflow' as const, // External tools default to workflow category
- source: 'external' as const,
- serverId: this.config.id,
- }))
+ const tools: MCPToolDefinition[] = []
+ for (const t of asRecordArray(prop(toolsResult, 'tools'))) {
+ const toolName = asString(t.name)
+ // A tool with no name cannot be looked up, called or unregistered — it
+ // used to land in the registry under the key `undefined`.
+ if (!toolName) {
+ log.warn(`[MCP:${this.config.name}] ignoring a tool with no name in tools/list`)
+ continue
+ }
+ tools.push({
+ name: toolName,
+ description: asString(t.description) || '',
+ inputSchema: isToolInputSchema(t.inputSchema) ? t.inputSchema : EMPTY_INPUT_SCHEMA,
+ category: 'workflow', // External tools default to workflow category
+ source: 'external',
+ serverId: this.config.id,
+ })
+ }
this.registered = true
return tools
@@ -157,17 +252,19 @@ export class MCPExternalClient {
}
}
- async callTool(name: string, args: Record<string, any>): Promise<string> {
+ async callTool(name: string, args: ToolArgs): Promise<string> {
if (!this.connected) throw new Error('Not connected')
const result = await this.sendRequest('tools/call', { name, arguments: args })
- // MCP returns content array
- if (Array.isArray(result.content)) {
- return result.content
- .map((c: any) => {
- if (c.type === 'text') return c.text
- if (c.type === 'image') return `[Image: ${c.mimeType}]`
+ // MCP returns a content array of `{ type, ... }` blocks.
+ const content = prop(result, 'content')
+ if (Array.isArray(content)) {
+ return content
+ .map((c: unknown) => {
+ const type = prop(c, 'type')
+ if (type === 'text') return asString(prop(c, 'text')) ?? ''
+ if (type === 'image') return `[Image: ${String(prop(c, 'mimeType'))}]`
return JSON.stringify(c)
})
.join('\n')
@@ -195,7 +292,7 @@ export class MCPExternalClient {
// ── Private ─────────────────────────────────────────────────
- private sendRequest(method: string, params?: any): Promise<any> {
+ private sendRequest(method: string, params?: unknown): Promise<unknown> {
return new Promise((resolve, reject) => {
if (!this.child) {
reject(new Error('Not connected'))
@@ -236,20 +333,24 @@ export class MCPExternalClient {
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
+ let parsed: unknown
try {
- const response: JsonRpcResponse = JSON.parse(trimmed)
- const pending = this.pendingRequests.get(response.id)
- if (pending) {
- this.pendingRequests.delete(response.id)
- clearTimeout(pending.timer)
- if (response.error) {
- pending.reject(new Error(response.error.message))
- } else {
- pending.resolve(response.result)
- }
- }
+ parsed = JSON.parse(trimmed)
} catch {
- // Not JSON — might be a notification, ignore
+ // Not JSON — a server that logs to stdout, ignore.
+ continue
+ }
+ const response = parseJsonRpcResponse(parsed)
+ if (!response || response.id === undefined) continue // notification or noise
+ const pending = this.pendingRequests.get(response.id)
+ if (pending) {
+ this.pendingRequests.delete(response.id)
+ clearTimeout(pending.timer)
+ if (response.error) {
+ pending.reject(new Error(response.error.message))
+ } else {
+ pending.resolve(response.result)
+ }
}
}
}
diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.ts
index b27f4fa2..1ade4040 100644
--- a/src/api/mcp/tool-registry.ts
+++ b/src/api/mcp/tool-registry.ts
@@ -1,6 +1,6 @@
// Dynamic Tool Registry — MCP-shaped, replaces hardcoded AGENT_TOOL_DEFS
-import type { MCPToolDefinition, PermissionMap, PermissionLevel } from './types'
+import type { MCPToolDefinition, PermissionMap, PermissionLevel, ToolArgs } from './types'
import type { OllamaTool } from '../../types/agent-mode'
import type { ToolDefinition } from '../providers/types'
import { MUTATING_TOOLS } from '../../lib/mutating-tools'
@@ -15,18 +15,30 @@ import type { AgentRunContext } from '../agent-context'
* goalposts mid-call. Tools that do not care simply ignore it.
*/
type ToolExecutor = (
- args: Record<string, any>,
+ args: ToolArgs,
run?: AgentRunContext,
signal?: AbortSignal,
) => Promise<string>
/** The pre-2.6.6 shape, still accepted from external servers and tests. */
-type LegacyToolExecutor = (args: Record<string, any>) => Promise<string>
+type LegacyToolExecutor = (args: ToolArgs) => Promise<string>
/**
* External-tool executor gets the tool name too, because one MCP server
* owns many tools and routes by name. The registry wraps it into a
* per-tool ToolExecutor closure so the Map lookup stays {name → executor}.
*/
-type ExternalToolExecutor = (toolName: string, args: Record<string, any>) => Promise<string>
+type ExternalToolExecutor = (toolName: string, args: ToolArgs) => Promise<string>
+
+/**
+ * The flat shape the Hermes/XML tool prompt wants: the definition's own
+ * JSON-Schema under `parameters`, no wrapper. `any` here meant the prompt
+ * builder could be handed anything at all — including `undefined` — and the
+ * `<tools>` block would have silently advertised a tool with no parameters.
+ */
+export interface HermesToolDef {
+ name: string
+ description: string
+ parameters: MCPToolDefinition['inputSchema']
+}
interface RegisteredTool {
definition: MCPToolDefinition
@@ -70,14 +82,14 @@ export class ToolRegistry {
* Warnung weg.
*/
private retiredRunner:
- | ((name: string, args: Record<string, any>, run?: AgentRunContext) => Promise<string | null>)
+ | ((name: string, args: ToolArgs, run?: AgentRunContext) => Promise<string | null>)
| null = null
// ── Registration ──────────────────────────────────────────────
/** Siehe `retiredRunner`. Wird von registerBuiltinTools() verdrahtet. */
setRetiredRunner(
- run: (name: string, args: Record<string, any>, run?: AgentRunContext) => Promise<string | null>,
+ run: (name: string, args: ToolArgs, run?: AgentRunContext) => Promise<string | null>,
) {
this.retiredRunner = run
}
@@ -128,7 +140,7 @@ export class ToolRegistry {
continue
}
const bound: ToolExecutor = isTwoArg
- ? (args: Record<string, any>) =>
+ ? (args: ToolArgs) =>
(executor as ExternalToolExecutor)(name, args)
: (executor as LegacyToolExecutor)
this.tools.set(name, {
@@ -209,7 +221,7 @@ export class ToolRegistry {
async execute(
name: string,
- args: Record<string, any>,
+ args: ToolArgs,
maxRetries = 1,
run?: AgentRunContext,
signal?: AbortSignal,
@@ -290,7 +302,7 @@ export class ToolRegistry {
}))
}
- toHermesToolDefs(permissions: PermissionMap): { name: string; description: string; parameters: any }[] {
+ toHermesToolDefs(permissions: PermissionMap): HermesToolDef[] {
return this.getAvailableTools(permissions).map(t => ({
name: t.name,
description: t.description,
diff --git a/src/api/mcp/types.ts b/src/api/mcp/types.ts
index eb7c9073..c091b63e 100644
--- a/src/api/mcp/types.ts
+++ b/src/api/mcp/types.ts
@@ -67,3 +67,14 @@ export interface MCPServerConfig {
env?: Record<string, string>
enabled: boolean
}
+
+/**
+ * The argument object a tool executor receives.
+ *
+ * These values come from the MODEL, not from us: a JSON object the LLM emitted
+ * (or a retried/repaired variant of it). Nothing about the declared
+ * `inputSchema` is enforced before the executor runs, so every field is
+ * genuinely of unknown type until the executor checks it — which is exactly
+ * what `unknown` says and what `any` used to hide.
+ */
+export type ToolArgs = Record<string, unknown>
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 43c558ec..4ad20f58 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -45,6 +45,7 @@
*/
import { backendCall, ollamaUrl, localFetch, isOllamaLocal, isWindows } from './backend'
+import type { ComfyApiGraph } from '../types/comfy-graph'
import { listRunningModels, loadModel, unloadModel } from './ollama'
import { startBundledEngine } from './engine'
import { useSettingsStore } from '../stores/settingsStore'
@@ -633,7 +634,7 @@ function cancelledFor(seq: number): boolean {
* reloaded into the same VRAM by the hand-off's finally. Both sides could OOM.
*/
async function submitCancellable(
- workflow: Record<string, unknown>,
+ workflow: ComfyApiGraph,
seq: number,
): Promise<string | typeof CANCELLED> {
if (cancelledFor(seq)) return CANCELLED
diff --git a/src/api/workflows.ts b/src/api/workflows.ts
index 282f1a5d..636d672b 100644
--- a/src/api/workflows.ts
+++ b/src/api/workflows.ts
@@ -11,57 +11,65 @@ import type {
WorkflowSource,
ParameterMap,
} from '../types/workflows'
+import type {
+ ComfyApiGraph, ComfyApiNode, ComfyInputValue, ComfyNodeInputs,
+ ComfyWebGraph, ComfyWebNode,
+} from '../types/comfy-graph'
+import {
+ apiNodes, isComfyApiGraph, isComfyWebGraph, isComfyWebNode,
+ inputNumber, linkTarget,
+} from '../types/comfy-graph'
+import { prop } from '../types/json-guards'
// ─── Validation ───
-
-// A node of the API-format graph. The JSON arrives from a file the user picked
-// or a download, so no field is guaranteed; every walk over a graph narrows
-// through this guard before it reads one.
-interface WorkflowNode {
- class_type?: string
- inputs?: Record<string, any>
-}
-
-function isWorkflowNode(value: unknown): value is WorkflowNode {
- return !!value && typeof value === 'object'
-}
-
-export function validateWorkflowJson(json: unknown): json is Record<string, any> {
+//
+// The JSON walked here arrives from a file the user picked or a download, so
+// no field is guaranteed. The shapes and the guards live in
+// types/comfy-graph.ts; nothing below reads a field it has not narrowed first.
+
+/**
+ * Accepts either ComfyUI graph format. Kept as a predicate over the API shape
+ * because that is what every caller goes on to build; a web-format file passes
+ * here and is converted by `resolveWorkflowJson` before it is used.
+ */
+export function validateWorkflowJson(json: unknown): json is ComfyApiGraph {
if (!json || typeof json !== 'object' || Array.isArray(json)) return false
- const obj = json as Record<string, any>
// API format: { "1": { class_type: "...", inputs: {...} }, ... }
- if (Object.values(obj).some(
- (node) => node && typeof node === 'object' && typeof node.class_type === 'string'
- )) return true
+ if (isComfyApiGraph(json)) return true
// Web/UI format: { nodes: [...], links: [...] }
- if (Array.isArray(obj.nodes) && obj.nodes.some((n: any) => n && typeof n.type === 'string')) return true
- return false
+ return isComfyWebGraph(json)
}
// Convert ComfyUI web/UI format to API format
-function convertWebToApiFormat(webWorkflow: Record<string, any>): Record<string, any> {
- const nodes: any[] = webWorkflow.nodes
- const links: any[] = webWorkflow.links || []
- const apiWorkflow: Record<string, any> = {}
+function convertWebToApiFormat(webWorkflow: ComfyWebGraph): ComfyApiGraph {
+ const links: unknown[] = Array.isArray(webWorkflow.links) ? webWorkflow.links : []
+ const apiWorkflow: ComfyApiGraph = {}
// Build link lookup: linkId -> { sourceNodeId, sourceSlot }
const linkMap: Record<number, { sourceNodeId: number; sourceSlot: number }> = {}
for (const link of links) {
// link format: [linkId, sourceNodeId, sourceSlot, targetNodeId, targetSlot, type]
if (Array.isArray(link) && link.length >= 4) {
- linkMap[link[0]] = { sourceNodeId: link[1], sourceSlot: link[2] }
+ const [id, sourceNodeId, sourceSlot] = link
+ if (typeof id === 'number' && typeof sourceNodeId === 'number' && typeof sourceSlot === 'number') {
+ linkMap[id] = { sourceNodeId, sourceSlot }
+ }
}
}
- for (const node of nodes) {
- if (!node || !node.type || typeof node.id !== 'number') continue
- const inputs: Record<string, any> = {}
+ for (const raw of webWorkflow.nodes) {
+ // A canvas graph can hold a malformed entry; the rest still converts.
+ if (!isComfyWebNode(raw) || !raw.type) continue
+ const node: ComfyWebNode = raw
+ const inputs: Record<string, ComfyInputValue> = {}
// Process connected inputs (from links - these are reliable)
if (Array.isArray(node.inputs)) {
for (const input of node.inputs) {
- if (input.link != null && linkMap[input.link]) {
- const { sourceNodeId, sourceSlot } = linkMap[input.link]
+ if (!input || typeof input.name !== 'string') continue
+ const linkId = input.link
+ if (linkId != null && linkMap[linkId]) {
+ const { sourceNodeId, sourceSlot } = linkMap[linkId]
inputs[input.name] = [String(sourceNodeId), sourceSlot]
}
}
@@ -70,8 +78,8 @@ function convertWebToApiFormat(webWorkflow: Record<string, any>): Record<string,
// Map widget_values using ComfyUI's object_info-based approach:
// We map ONLY for node types we understand well. For unknown nodes,
// we skip widget values and let injectParameters handle the important ones.
- const ct = node.type as string
- const widgetValues = node.widgets_values || []
+ const ct = node.type
+ const widgetValues = Array.isArray(node.widgets_values) ? node.widgets_values : []
mapWidgetValues(ct, widgetValues, inputs, node)
apiWorkflow[String(node.id)] = {
@@ -85,7 +93,12 @@ function convertWebToApiFormat(webWorkflow: Record<string, any>): Record<string,
// Map widget_values to named inputs. Conservative: only map what we're sure about.
// injectParameters will override model/prompt/seed/steps/cfg/etc. anyway.
-function mapWidgetValues(classType: string, values: any[], inputs: Record<string, any>, node?: any) {
+function mapWidgetValues(
+ classType: string,
+ values: ComfyInputValue[],
+ inputs: Record<string, ComfyInputValue>,
+ node?: ComfyWebNode,
+) {
if (!values || values.length === 0) return
// For nodes where widget order is well-known and stable:
@@ -162,11 +175,12 @@ function mapWidgetValues(classType: string, values: any[], inputs: Record<string
// For unknown node types: try to use node.widgets if available
// to map by name, otherwise skip widget values entirely.
// injectParameters handles the critical params.
- if (node?.widgets) {
+ if (Array.isArray(node?.widgets)) {
for (let i = 0; i < Math.min(values.length, node.widgets.length); i++) {
const widgetName = node.widgets[i]?.name
- if (widgetName && values[i] != null) {
- inputs[widgetName] = values[i]
+ const value = values[i]
+ if (widgetName && value != null) {
+ inputs[widgetName] = value
}
}
}
@@ -206,14 +220,13 @@ export function extractSearchTerms(modelName: string, modelType: ModelType): str
// ─── Parameter Auto-Detection ───
-export function autoDetectParameterMap(workflow: Record<string, any>): ParameterMap {
+export function autoDetectParameterMap(workflow: ComfyApiGraph): ParameterMap {
const map: ParameterMap = {}
- let ksamplerNode: any = null
+ let ksamplerNode: ComfyApiNode | null = null
- for (const [nodeId, node] of Object.entries(workflow)) {
- if (!node || typeof node !== 'object') continue
- const ct = node.class_type as string
+ for (const [nodeId, node] of apiNodes(workflow)) {
+ const ct = node.class_type
if (ct === 'KSampler' || ct === 'KSamplerAdvanced') {
ksamplerNode = node
map.seed = { nodeId, inputKey: 'seed' }
@@ -226,17 +239,15 @@ export function autoDetectParameterMap(workflow: Record<string, any>): Parameter
}
if (ksamplerNode?.inputs) {
- const posConn = ksamplerNode.inputs.positive
- const negConn = ksamplerNode.inputs.negative
- if (Array.isArray(posConn)) {
- const posNodeId = String(posConn[0])
+ const posNodeId = linkTarget(ksamplerNode.inputs.positive)
+ const negNodeId = linkTarget(ksamplerNode.inputs.negative)
+ if (posNodeId !== undefined) {
const posNode = workflow[posNodeId]
if (posNode?.class_type === 'CLIPTextEncode') {
map.positivePrompt = { nodeId: posNodeId, inputKey: 'text' }
}
}
- if (Array.isArray(negConn)) {
- const negNodeId = String(negConn[0])
+ if (negNodeId !== undefined) {
const negNode = workflow[negNodeId]
if (negNode?.class_type === 'CLIPTextEncode') {
map.negativePrompt = { nodeId: negNodeId, inputKey: 'text' }
@@ -244,9 +255,8 @@ export function autoDetectParameterMap(workflow: Record<string, any>): Parameter
}
}
- for (const [nodeId, node] of Object.entries(workflow)) {
- if (!node || typeof node !== 'object') continue
- const ct = node.class_type as string
+ for (const [nodeId, node] of apiNodes(workflow)) {
+ const ct = node.class_type
switch (ct) {
case 'CheckpointLoaderSimple':
@@ -277,14 +287,14 @@ export function autoDetectParameterMap(workflow: Record<string, any>): Parameter
map.frames = { nodeId, inputKey: 'length' }
break
case 'ImageResizeKJv2':
- if (!map.width && typeof node.inputs?.width === 'number') {
+ if (!map.width && inputNumber(node, 'width') !== undefined) {
map.width = {
nodeId,
inputKey: 'width',
}
}
- if (!map.height && typeof node.inputs?.height === 'number') {
+ if (!map.height && inputNumber(node, 'height') !== undefined) {
map.height = {
nodeId,
inputKey: 'height',
@@ -301,8 +311,8 @@ export function autoDetectParameterMap(workflow: Record<string, any>): Parameter
}
if (!map.positivePrompt) {
- const clipNodes = Object.entries(workflow).filter(
- ([, n]) => n?.class_type === 'CLIPTextEncode'
+ const clipNodes = apiNodes(workflow).filter(
+ ([, n]) => n.class_type === 'CLIPTextEncode'
)
if (clipNodes.length >= 1) {
map.positivePrompt = { nodeId: clipNodes[0][0], inputKey: 'text' }
@@ -318,18 +328,27 @@ export function autoDetectParameterMap(workflow: Record<string, any>): Parameter
// ─── Parameter Injection ───
export async function injectParameters(
- workflow: Record<string, any>,
+ workflow: ComfyApiGraph,
paramMap: ParameterMap,
params: GenerateParams | VideoParams,
modelType: ModelType
-): Promise<Record<string, any>> {
- const wf = JSON.parse(JSON.stringify(workflow))
-
- const inject = (mapping: { nodeId: string; inputKey: string } | undefined, value: any) => {
+): Promise<ComfyApiGraph> {
+ // Deep clone: the caller's template must not be mutated. A JSON round-trip
+ // of a ComfyApiGraph is a ComfyApiGraph by construction.
+ const wf: ComfyApiGraph = JSON.parse(JSON.stringify(workflow))
+
+ const inject = (
+ mapping: { nodeId: string; inputKey: string } | undefined,
+ value: ComfyInputValue | undefined,
+ ) => {
if (!mapping) return
const node = wf[mapping.nodeId]
if (node?.inputs) {
- node.inputs[mapping.inputKey] = value
+ // Assigning undefined is deliberate and load-bearing: JSON.stringify
+ // drops the key, so the node falls back to ComfyUI's own default rather
+ // than keeping the template's value.
+ const inputs: ComfyNodeInputs = node.inputs
+ inputs[mapping.inputKey] = value
}
}
@@ -346,12 +365,11 @@ export async function injectParameters(
// detection. Locate their source resize node at generation time so
// users do not have to remove and re-import the workflow.
if (!widthMapping || !heightMapping) {
- const resizeEntry = Object.entries(wf).find(
+ const resizeEntry = apiNodes(wf).find(
([, node]) =>
- isWorkflowNode(node) &&
node.class_type === 'ImageResizeKJv2' &&
- typeof node.inputs?.width === 'number' &&
- typeof node.inputs?.height === 'number',
+ inputNumber(node, 'width') !== undefined &&
+ inputNumber(node, 'height') !== undefined,
)
if (resizeEntry) {
@@ -390,8 +408,8 @@ export async function injectParameters(
// persisted parameterMap. Detect their LoadImage node at generation time
// so users do not have to remove and re-import those workflows.
if (!inputImageMapping) {
- const loadImageEntry = Object.entries(wf).find(
- ([, node]) => isWorkflowNode(node) && node.class_type === 'LoadImage',
+ const loadImageEntry = apiNodes(wf).find(
+ ([, node]) => node.class_type === 'LoadImage',
)
if (loadImageEntry) {
@@ -411,20 +429,19 @@ export async function injectParameters(
// A VHS_VideoCombine left on save_output:false writes the clip to
// ComfyUI's temp folder, where the gallery cannot play it back.
- for (const node of Object.values(wf)) {
- if (isWorkflowNode(node) && node.class_type === 'VHS_VideoCombine' && node.inputs) {
+ for (const [, node] of apiNodes(wf)) {
+ if (node.class_type === 'VHS_VideoCombine' && node.inputs) {
node.inputs.save_output = true
}
}
}
- log.info('[workflows] Injected workflow nodes', { nodes: Object.entries(wf).map(([id, n]: [string, any]) =>
+ log.info('[workflows] Injected workflow nodes', { nodes: apiNodes(wf).map(([id, n]) =>
`${id}: ${n.class_type} (${Object.keys(n.inputs || {}).join(', ')})`
).join(' | ') })
// Auto-resolve VAE and CLIP loaders with real model files
- for (const node of Object.values(wf)) {
- if (!isWorkflowNode(node)) continue
+ for (const [, node] of apiNodes(wf)) {
const ct = node.class_type
try {
if (ct === 'VAELoader' && node.inputs) {
@@ -449,10 +466,8 @@ export async function injectParameters(
// ─── Detect workflow mode ───
-function detectWorkflowMode(workflow: Record<string, any>): 'image' | 'video' | 'both' {
- const classTypes = Object.values(workflow)
- .filter((n) => n && typeof n === 'object')
- .map((n) => n.class_type as string)
+function detectWorkflowMode(workflow: ComfyApiGraph): 'image' | 'video' | 'both' {
+ const classTypes = apiNodes(workflow).map(([, n]) => n.class_type)
const hasVideo = classTypes.some((ct) =>
['EmptyHunyuanLatentVideo', 'ADE_LoadAnimateDiffModel', 'VHS_VideoCombine', 'SaveAnimatedWEBP'].includes(ct)
@@ -468,10 +483,8 @@ function detectWorkflowMode(workflow: Record<string, any>): 'image' | 'video' |
// ─── Detect compatible model types from workflow ───
-function detectModelTypes(workflow: Record<string, any>): ModelType[] {
- const classTypes = Object.values(workflow)
- .filter((n) => n && typeof n === 'object')
- .map((n) => n.class_type as string)
+function detectModelTypes(workflow: ComfyApiGraph): ModelType[] {
+ const classTypes = apiNodes(workflow).map(([, n]) => n.class_type)
const types: ModelType[] = []
@@ -498,7 +511,7 @@ function detectModelTypes(workflow: Record<string, any>): ModelType[] {
// ─── Fetch workflow from URL (supports JSON and ZIP) ───
-export async function fetchWorkflowFromUrl(url: string, apiKey?: string): Promise<Record<string, any>> {
+export async function fetchWorkflowFromUrl(url: string, apiKey?: string): Promise<ComfyApiGraph> {
// Append CivitAI API key if provided and URL is from CivitAI (any host —
// civitai.com or a mirror like civitai.red, GitHub #53).
let finalUrl = url
@@ -561,47 +574,38 @@ export async function fetchWorkflowFromUrl(url: string, apiKey?: string): Promis
throw new Error('Invalid workflow format. Expected ComfyUI API or web format.')
}
-// Try to extract a valid API-format workflow from various JSON structures
-function resolveWorkflowJson(json: any): Record<string, any> | null {
- if (!json || typeof json !== 'object') return null
+/**
+ * Try to extract a valid API-format workflow from the various JSON structures
+ * a downloaded or exported ComfyUI file can be wrapped in. `json` is whatever
+ * `JSON.parse` produced, so every branch narrows before it reads.
+ */
+function resolveWorkflowJson(json: unknown): ComfyApiGraph | null {
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return null
// Direct API format
- if (isApiFormat(json)) return json
+ if (isComfyApiGraph(json)) return json
// Web/UI format → convert
- if (isWebFormat(json)) return convertWebToApiFormat(json)
+ if (isComfyWebGraph(json)) return convertWebToApiFormat(json)
- // Wrapped in "prompt" or "workflow" key
+ // Wrapped in "prompt" / "workflow" / "output". The ComfyUI export wrapper
+ // `{ extra: {...}, prompt: {...} }` is the same 'prompt' branch — it used to
+ // have its own line that additionally demanded `extra`, i.e. a strict subset.
for (const key of ['prompt', 'workflow', 'output']) {
- if (json[key]) {
- if (isApiFormat(json[key])) return json[key]
- if (isWebFormat(json[key])) return convertWebToApiFormat(json[key])
- }
+ const inner = prop(json, key)
+ if (!inner) continue
+ if (isComfyApiGraph(inner)) return inner
+ if (isComfyWebGraph(inner)) return convertWebToApiFormat(inner)
}
- // Extra wrapper from ComfyUI export: { "extra": {...}, "prompt": {...} }
- if (json.extra && json.prompt && isApiFormat(json.prompt)) return json.prompt
-
return null
}
-function isApiFormat(obj: any): boolean {
- if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return false
- return Object.values(obj).some(
- (node: any) => node && typeof node === 'object' && typeof node.class_type === 'string'
- )
-}
-
-function isWebFormat(obj: any): boolean {
- if (!obj || typeof obj !== 'object') return false
- return Array.isArray(obj.nodes) && obj.nodes.some((n: any) => n && typeof n.type === 'string')
-}
-
// ─── Parse imported workflow into a template ───
export function parseImportedWorkflow(
name: string,
- workflow: Record<string, any>,
+ workflow: ComfyApiGraph,
source: WorkflowSource = 'manual',
sourceUrl?: string,
description?: string,
diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.ts
index dec64b70..1e70e2f1 100644
--- a/src/lib/workflow-engine.ts
+++ b/src/lib/workflow-engine.ts
@@ -22,6 +22,7 @@ import { useMemoryStore } from '../stores/memoryStore'
// verbliebenen Aufrufer bestehen.
import { toolRegistry } from '../api/mcp/tool-registry'
import { DEFAULT_PERMISSIONS } from '../api/mcp/types'
+import type { ToolArgs } from '../api/mcp/types'
import { streamProviderTurn } from './provider-stream'
import { settleThinking } from './thinking-stripper'
import { buildHermesToolPrompt, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
@@ -275,7 +276,12 @@ export class WorkflowEngine {
} else {
// Hermes XML
const hermesSystem = buildHermesToolPrompt(
- allowedTools.map(t => ({ name: t.function.name, description: t.function.description, parameters: t.function.parameters as any, permission: 'auto' as const }))
+ allowedTools.map(t => ({
+ name: t.function.name,
+ description: t.function.description,
+ parameters: t.function.parameters,
+ permission: 'auto' as const,
+ }))
)
const hermesMessages = [{ role: 'system' as const, content: hermesSystem }, ...messages]
// G32b: through the provider, not Ollama's /api/chat. hermes_xml is
@@ -330,7 +336,7 @@ export class WorkflowEngine {
if (!step.toolName) throw new Error('Tool step missing toolName')
// Build args from static + templates
- const args: Record<string, any> = { ...(step.toolArgs || {}) }
+ const args: ToolArgs = { ...(step.toolArgs || {}) }
if (step.toolArgTemplates) {
for (const [key, template] of Object.entries(step.toolArgTemplates)) {
args[key] = interpolate(template, this.variables)
diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.ts
index e4483ff2..80a9b43a 100644
--- a/src/types/agent-mode.ts
+++ b/src/types/agent-mode.ts
@@ -33,10 +33,17 @@ export interface OllamaTool {
function: {
name: string
description: string
+ /**
+ * The registry copies `MCPToolDefinition.inputSchema` in here verbatim
+ * (tool-registry.toOllamaTools), so the property map carries the same
+ * JSONSchemaProp shape rather than an untyped bag — which is what let the
+ * Hermes prompt builder be handed this object behind an `as any`.
+ */
parameters: {
type: 'object'
- properties: Record<string, any>
+ properties: Record<string, JSONSchemaProp>
required: string[]
+ additionalProperties?: boolean
}
}
}
diff --git a/src/types/agent-workflows.ts b/src/types/agent-workflows.ts
index dc7bc9aa..3e88198a 100644
--- a/src/types/agent-workflows.ts
+++ b/src/types/agent-workflows.ts
@@ -23,7 +23,10 @@ export interface WorkflowStep {
// tool step: execute specific tool
toolName?: string
- toolArgs?: Record<string, any>
+ /** Static args merged with the interpolated `toolArgTemplates` at run time.
+ * Same `unknown`-valued shape the tool executors receive (mcp/types.ToolArgs)
+ * — a saved workflow's args are JSON the user or an import wrote. */
+ toolArgs?: Record<string, unknown>
toolArgTemplates?: Record<string, string> // supports {{variable}} interpolation
// condition step: branch based on output
@@ -86,7 +89,7 @@ export interface StepResult {
error?: string
toolCalls?: Array<{
name: string
- args: Record<string, any>
+ args: Record<string, unknown>
result: string
}>
}
diff --git a/src/types/bridge.ts b/src/types/bridge.ts
new file mode 100644
index 00000000..39cd7255
--- /dev/null
+++ b/src/types/bridge.ts
@@ -0,0 +1,122 @@
+/**
+ * Reply shapes of the Rust bridge commands the tool layer calls.
+ *
+ * These describe code we own: each interface below was read off the
+ * `serde_json::json!` literal that produces it in `src-tauri/src/commands/`,
+ * and a field is optional here exactly when Rust can omit it (a binary
+ * `fs_read` carries `bytes` and no `content`, for instance).
+ *
+ * That is why these are declarations rather than runtime guards: unlike an MCP
+ * server or a ComfyUI graph, the producer is in this repository and changes to
+ * it are changes to this file. Foreign JSON still goes through
+ * `src/types/json-guards.ts`.
+ *
+ * Type-only module — no imports, no runtime code, cannot join an import cycle.
+ */
+
+/** `shell_execute`, `execute_code` — commands/shell.rs, commands/agent.rs. */
+export interface ShellExecResult {
+ stdout: string
+ stderr: string
+ /** `status.code()`, or -1 when the child was killed or timed out. */
+ exitCode: number
+ timedOut: boolean
+}
+
+/** `fs_read` — commands/filesystem.rs. Binary files carry `bytes`, no `content`. */
+export interface FsReadResult {
+ content?: string
+ encoding: 'utf8' | 'binary' | 'base64'
+ bytes?: number
+}
+
+/** `fs_write` — commands/filesystem.rs. */
+export interface FsWriteResult {
+ status: 'saved' | 'unchanged'
+ path: string
+ bytes: number
+}
+
+/** One `fs_list` entry — commands/filesystem.rs. */
+export interface FsEntry {
+ name: string
+ path: string
+ size: number
+ isDir: boolean
+ /** Unix seconds; 0 when the metadata read failed. */
+ modified: number
+}
+
+export interface FsListResult {
+ entries: FsEntry[]
+ count?: number
+}
+
+/** `fs_search` — one matching line inside one file. */
+export interface FsSearchMatch {
+ line: number
+ text: string
+}
+
+export interface FsSearchHit {
+ file: string
+ matches?: FsSearchMatch[]
+}
+
+export interface FsSearchResult {
+ results: FsSearchHit[]
+}
+
+/** `web_search` — commands/web.rs. `results` is absent on a hard failure. */
+export interface WebSearchHit {
+ title: string
+ url: string
+ snippet: string
+}
+
+export interface WebSearchResult {
+ results?: WebSearchHit[]
+ provider?: string
+ /** Set when the CONFIGURED provider failed and a free fallback answered. */
+ providerError?: string
+ error?: string
+}
+
+/** `web_fetch` — the aggressively stripped page body. */
+export interface WebFetchResult {
+ url: string
+ status: number
+ contentType: string
+ title: string
+ text: string
+ truncated: boolean
+}
+
+/** `process_list` — one running process. */
+export interface ProcessInfo {
+ name: string
+ pid: number
+ memory: number
+ cpu: number
+}
+
+export interface ProcessListResult {
+ processes: ProcessInfo[]
+ count?: number
+}
+
+/** `screenshot` — base64 PNG payload. */
+export interface ScreenshotResult {
+ image?: string
+ format?: string
+ encoding?: string
+}
+
+/** `get_current_time`. */
+export interface CurrentTimeResult {
+ unix: number
+ iso_local: string
+ iso_utc: string
+ timezone: string
+ timezone_offset: number
+}
diff --git a/src/types/comfy-graph.ts b/src/types/comfy-graph.ts
new file mode 100644
index 00000000..dd791340
--- /dev/null
+++ b/src/types/comfy-graph.ts
@@ -0,0 +1,230 @@
+/**
+ * The two ComfyUI graph formats, plus the guards that turn a downloaded or
+ * user-picked JSON file into one of them.
+ *
+ * This is foreign data in the strongest sense in this app: a `.json` the user
+ * dropped in, a CivitAI download, a `.png` with a workflow in its metadata.
+ * Nothing about its shape is guaranteed, so every walk over a graph narrows
+ * through the guards below before it reads a field.
+ *
+ * Two formats exist and they are NOT interchangeable:
+ *
+ * - **API format** — what `/prompt` accepts and what this app builds:
+ * `{ "3": { class_type: "KSampler", inputs: { seed: 1, model: ["4", 0] } } }`.
+ * Node ids are the object keys (strings), and an input is either a literal
+ * or a `[sourceNodeId, slotIndex]` link.
+ *
+ * - **Web/UI format** — what the ComfyUI canvas saves: `{ nodes: [...],
+ * links: [...] }`, node ids numeric, inputs positional
+ * (`widgets_values`) and connections in a separate link table.
+ * `convertWebToApiFormat` in api/workflows.ts turns one into the other.
+ *
+ * Type-only plus pure guards, no imports — a leaf module that cannot join an
+ * import cycle.
+ */
+
+// ── API format ──────────────────────────────────────────────────
+
+/** A reference to another node's output: `[nodeId, slotIndex]`. */
+export type ComfyLinkRef = [string, number]
+
+/**
+ * Anything that may sit in a node's `inputs`. Literals and links cover
+ * everything ComfyUI itself emits; the array/object arms exist because custom
+ * nodes do store structured widget state there.
+ */
+export type ComfyInputValue =
+ | string
+ | number
+ | boolean
+ | null
+ | ComfyInputValue[]
+ | { [key: string]: ComfyInputValue }
+
+/**
+ * A node's `inputs` map.
+ *
+ * `undefined` is a member on purpose and it is load-bearing: injection writes
+ * `undefined` for a mapped-but-unset parameter, and `JSON.stringify` then drops
+ * the key from the `/prompt` payload so ComfyUI applies the node's own default
+ * — which is not the same as leaving the template's value in place.
+ */
+export type ComfyNodeInputs = Record<string, ComfyInputValue | undefined>
+
+/**
+ * One node of an API-format graph.
+ *
+ * `inputs` is optional because a downloaded graph really can carry a node
+ * without it — the guard below only promises a `class_type`. Read fields
+ * through `nodeInput` / `inputString` / `inputNumber`, which re-check.
+ */
+export interface ComfyApiNode {
+ class_type: string
+ inputs?: ComfyNodeInputs
+ /** ComfyUI's own round-trip metadata; present in saved graphs, ignored here. */
+ _meta?: { title?: string }
+}
+
+/**
+ * An API-format graph as it arrives — node ids are the keys.
+ *
+ * `Partial` in spirit rather than in types: a downloaded file can hold junk
+ * under some key, so readers use `apiNodes()` below instead of iterating the
+ * record directly.
+ */
+export type ComfyApiGraph = Record<string, ComfyApiNode>
+
+// ── Web / UI format ─────────────────────────────────────────────
+
+/** One declared input socket of a canvas node. */
+export interface ComfyWebInput {
+ name: string
+ type?: string
+ /** Link id into the graph's `links` table, or null when unconnected. */
+ link?: number | null
+}
+
+export interface ComfyWebNode {
+ id: number
+ type: string
+ inputs?: ComfyWebInput[]
+ /** Positional widget state — order is per node class and undocumented.
+ * Plain parsed JSON, hence ComfyInputValue rather than unknown. */
+ widgets_values?: ComfyInputValue[]
+ /** Named widget slots, when the canvas saved them — lets an unknown node
+ * type still have its widget values mapped by name. */
+ widgets?: { name?: string }[]
+ title?: string
+}
+
+/** `[linkId, sourceNodeId, sourceSlot, targetNodeId, targetSlot, type]`. */
+export type ComfyWebLink = [number, number, number, number, number, string?]
+
+export interface ComfyWebGraph {
+ nodes: ComfyWebNode[]
+ links?: unknown[]
+}
+
+
+
+// ── Guards ──────────────────────────────────────────────────────
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
+}
+
+/** A single API-format node: a `class_type` string is the whole signature. */
+export function isComfyApiNode(v: unknown): v is ComfyApiNode {
+ return isPlainObject(v) && typeof v.class_type === 'string'
+}
+
+/**
+ * A `[nodeId, slot]` link reference. ComfyUI writes the node id as a string,
+ * but hand-edited and older graphs carry a number — both are accepted, and
+ * `linkTarget` below normalises to the string form the API wants.
+ */
+export function isComfyLinkRef(v: unknown): v is [string | number, number] {
+ return Array.isArray(v)
+ && v.length >= 2
+ && (typeof v[0] === 'string' || typeof v[0] === 'number')
+ && typeof v[1] === 'number'
+}
+
+/** The node id a link points at, or undefined when this is not a link. */
+export function linkTarget(v: unknown): string | undefined {
+ return isComfyLinkRef(v) ? String(v[0]) : undefined
+}
+
+/**
+ * The `[id, node]` pairs of an API-format graph, skipping anything that is not
+ * a node. Iterate this rather than `Object.entries(graph)` — a graph file can
+ * carry `extra`, `version` or a stray comment key next to the real nodes.
+ */
+export function apiNodes(graph: unknown): [string, ComfyApiNode][] {
+ if (!isPlainObject(graph)) return []
+ const out: [string, ComfyApiNode][] = []
+ for (const [id, node] of Object.entries(graph)) {
+ if (isComfyApiNode(node)) out.push([id, node])
+ }
+ return out
+}
+
+/** Is this the API format `/prompt` accepts? At least one real node. */
+export function isComfyApiGraph(v: unknown): v is ComfyApiGraph {
+ return isPlainObject(v) && Object.values(v).some(isComfyApiNode)
+}
+
+/** One canvas node — a numeric id and a class name. */
+export function isComfyWebNode(v: unknown): v is ComfyWebNode {
+ return isPlainObject(v) && typeof v.type === 'string' && typeof v.id === 'number'
+}
+
+/**
+ * Is this the canvas save format? Matches the historical check exactly: a
+ * `nodes` array holding at least one entry with a string `type`. (Node ids are
+ * verified per node by `isComfyWebNode` at conversion time, because a graph
+ * with one malformed node should still convert the rest.)
+ */
+export function isComfyWebGraph(v: unknown): v is ComfyWebGraph {
+ return isPlainObject(v)
+ && Array.isArray(v.nodes)
+ && v.nodes.some((n) => isPlainObject(n) && typeof n.type === 'string')
+}
+
+/** Read one input of a node without asserting anything about its type. */
+export function nodeInput(node: ComfyApiNode | undefined, key: string): ComfyInputValue | undefined {
+ const inputs = node?.inputs
+ if (typeof inputs !== 'object' || inputs === null || Array.isArray(inputs)) return undefined
+ return inputs[key]
+}
+
+/** An input as a string, or undefined — model names, prompts, filenames. */
+export function inputString(node: ComfyApiNode | undefined, key: string): string | undefined {
+ const v = nodeInput(node, key)
+ return typeof v === 'string' ? v : undefined
+}
+
+/** An input as a finite number, or undefined — steps, cfg, width, seed. */
+export function inputNumber(node: ComfyApiNode | undefined, key: string): number | undefined {
+ const v = nodeInput(node, key)
+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined
+}
+
+
+// ── /history ────────────────────────────────────────────────────
+
+/**
+ * One entry of ComfyUI's `/history/<promptId>` response.
+ *
+ * Only the parts this app reads are modelled, and every one of them is
+ * optional because a half-written entry (the render is still going) genuinely
+ * omits them. `outputs` stays `unknown` per node: what a node posts depends on
+ * the node — `extractComfyOutputFiles` in api/comfyui.ts is the reader that
+ * walks it, and it narrows as it goes.
+ */
+export interface ComfyHistoryEntry {
+ status?: {
+ status_str?: string
+ completed?: boolean
+ /** `[eventName, payload]` pairs — execution_start / execution_success / … */
+ messages?: [string, ComfyExecutionMessage][]
+ }
+ outputs?: Record<string, unknown>
+ prompt?: unknown
+}
+
+/**
+ * The payload half of a `/history` status message. The named fields are the
+ * ones this app surfaces to the user when a render fails (they come from
+ * ComfyUI's `execution_error` event); the index signature keeps every other
+ * field ComfyUI sends readable without pretending we know its type.
+ */
+export interface ComfyExecutionMessage {
+ exception_message?: string
+ exception_type?: string
+ node_id?: string
+ node_type?: string
+ message?: string
+ timestamp?: number
+ [key: string]: unknown
+}
diff --git a/src/types/json-guards.ts b/src/types/json-guards.ts
new file mode 100644
index 00000000..eca5a8d8
--- /dev/null
+++ b/src/types/json-guards.ts
@@ -0,0 +1,94 @@
+/**
+ * Boundary guards for data this app did NOT produce.
+ *
+ * Three foreign sources meet the frontend and all three arrive shapeless:
+ * - the Tauri bridge (`backendCall` / `invoke` hand back whatever Rust
+ * serialised — the generic parameter is a claim, not a check),
+ * - ComfyUI over HTTP (`/prompt`, `/history`, `/object_info`, and the
+ * user-authored workflow JSON that gets dropped into the app),
+ * - MCP servers (a third-party process answering `tools/list`).
+ *
+ * The rule these helpers exist to enforce: check before you claim. `isRecord`
+ * before a property read, `Array.isArray` before an iteration, `typeof` before
+ * a value is handed on as a string or a number. Past the guard everything is
+ * typed; nothing here casts.
+ *
+ * Deliberately dependency-free — no imports at all, so it stays a leaf module
+ * and can never take part in an import cycle.
+ *
+ * (`src/api/providers/wire.ts` does the same job for the three chat-completion
+ * HTTP APIs. It is kept separate on purpose: that file also carries the wire
+ * *shapes* of Ollama/OpenAI/Anthropic, which have nothing to do with the
+ * bridge, and importing it here would tie the MCP layer to the providers.)
+ */
+
+/** 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 [] — non-strings are dropped, not stringified. */
+export function asStringArray(v: unknown): string[] {
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
+}
+
+/**
+ * A string OR a number that a JSON producer wrote as one when the other was
+ * meant — ComfyUI node ids are the standing example (`"3"` in a saved graph,
+ * `3` in a fresh one). Numbers are normalised to their decimal text.
+ */
+export function asIdString(v: unknown): string | undefined {
+ if (typeof v === 'string') return v
+ if (typeof v === 'number' && Number.isFinite(v)) return String(v)
+ return undefined
+}
+
+/**
+ * Best-effort human text for a value of unknown shape — used where a foreign
+ * error field could be a string, an `{ message }`, or an arbitrary object.
+ * Returns '' for null/undefined so callers can test truthiness.
+ */
+export function errorText(v: unknown): string {
+ if (v == null) return ''
+ if (typeof v === 'string') return v
+ if (v instanceof Error) return v.message
+ const msg = prop(v, 'message')
+ if (typeof msg === 'string') return msg
+ try {
+ return JSON.stringify(v) ?? String(v)
+ } catch {
+ return String(v)
+ }
+}
diff --git a/src/types/workflows.ts b/src/types/workflows.ts
index 497609f3..9c7cc8a5 100644
--- a/src/types/workflows.ts
+++ b/src/types/workflows.ts
@@ -1,4 +1,5 @@
import type { ModelType } from '../api/comfyui'
+import type { ComfyApiGraph } from './comfy-graph'
export type WorkflowSource = 'civitai' | 'manual'
@@ -46,7 +47,7 @@ export interface WorkflowTemplate {
sourceUrl?: string
modelTypes: ModelType[]
mode: 'image' | 'video' | 'both'
- workflow: Record<string, any>
+ workflow: ComfyApiGraph
parameterMap: ParameterMap
installedAt: number
thumbnailUrl?: string
@@ -61,5 +62,5 @@ export interface WorkflowSearchResult {
modelTypes: ModelType[]
mode: 'image' | 'video' | 'both'
downloadUrl?: string
- rawWorkflow?: Record<string, any>
+ rawWorkflow?: ComfyApiGraph
}