7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(tools): repair double-encoded arguments below the top level (#794)
OhOkThisIsFine8f99a2b52f47
diff --git a/server/src/__tests__/lib/tool-args.test.ts b/server/src/__tests__/lib/tool-args.test.tsindex 7475fd82..7a45cfca 100644--- a/server/src/__tests__/lib/tool-args.test.ts+++ b/server/src/__tests__/lib/tool-args.test.ts@@ -66,6 +66,93 @@ describe('repairToolArguments', () => {});});+// The same model that stringifies a top-level array stringifies a nested one.+// The repair walks the whole value now, re-applying the identical gate at each+// level: depth adds reach, never latitude.+const NESTED_SCHEMA = {+ type: 'object',+ properties: {+ label: { type: 'string' },+ config: {+ type: 'object',+ properties: {+ tags: { type: 'array' },+ note: { type: 'string' },+ nested: { type: 'object', properties: { deep: { type: 'array' } } },+ },+ },+ plan: {+ type: 'array',+ items: { type: 'object', properties: { steps: { type: 'array' }, name: { type: 'string' } } },+ },+ },+};++describe('repairToolArguments — nested values', () => {+ it('decodes an array nested inside an object parameter', () => {+ const broken = JSON.stringify({ config: { tags: '["a","b"]' } });+ const repaired = JSON.parse(repairToolArguments(broken, NESTED_SCHEMA));+ expect(repaired.config.tags).toEqual(['a', 'b']);+ });++ it('decodes through an object that was itself double-encoded', () => {+ // Both levels broken at once, which is what these models actually emit.+ const broken = JSON.stringify({ config: '{"tags": "[\\"a\\"]"}' });+ const repaired = JSON.parse(repairToolArguments(broken, NESTED_SCHEMA));+ expect(repaired.config.tags).toEqual(['a']);+ });++ it('descends more than two levels', () => {+ const broken = JSON.stringify({ config: { nested: { deep: '[1,2,3]' } } });+ const repaired = JSON.parse(repairToolArguments(broken, NESTED_SCHEMA));+ expect(repaired.config.nested.deep).toEqual([1, 2, 3]);+ });++ it('decodes inside array elements via the items schema', () => {+ const broken = JSON.stringify({ plan: [{ name: 'a', steps: '["one","two"]' }] });+ const repaired = JSON.parse(repairToolArguments(broken, NESTED_SCHEMA));+ expect(repaired.plan[0].steps).toEqual(['one', 'two']);+ expect(repaired.plan[0].name).toBe('a');+ });++ it('still never touches a nested string-typed parameter', () => {+ const args = JSON.stringify({ config: { note: '["literal text"]' } });+ expect(repairToolArguments(args, NESTED_SCHEMA)).toBe(args);+ });++ it('still leaves a nested type mismatch alone', () => {+ const args = JSON.stringify({ config: { tags: '{"not":"an array"}' } });+ expect(repairToolArguments(args, NESTED_SCHEMA)).toBe(args);+ });++ it('leaves a nested key the schema does not describe alone', () => {+ const args = JSON.stringify({ config: { unknown: '["a"]' } });+ expect(repairToolArguments(args, NESTED_SCHEMA)).toBe(args);+ });++ it('leaves array elements alone when the schema has no items', () => {+ // PLAN_SCHEMA's `plan` is a bare {type:'array'} — nothing describes an+ // element, so nothing justifies decoding one.+ const args = JSON.stringify({ plan: [{ steps: '["one"]' }] });+ expect(repairToolArguments(args, PLAN_SCHEMA)).toBe(args);+ });++ it('is still byte-identical when a nested value needs nothing', () => {+ const good = JSON.stringify({ config: { tags: ['a'], note: 'x' }, plan: [{ name: 'a', steps: [] }] });+ expect(repairToolArguments(good, NESTED_SCHEMA)).toBe(good);+ });++ it('survives a self-referential schema without recursing forever', () => {+ // A $ref-expanded recursive schema is a cycle; the walk follows the DATA,+ // which is finite, so the schema's cycle is harmless.+ const cyclic: any = { type: 'object', properties: { child: null, items: { type: 'array' } } };+ cyclic.properties.child = cyclic;+ const broken = JSON.stringify({ child: { child: { items: '[1]' } } });+ const repaired = JSON.parse(repairToolArguments(broken, cyclic));+ expect(repaired.child.child.items).toEqual([1]);+ });+});+describe('toolSchemaMap', () => {it('maps function tools by name and skips non-function/unnamed entries', () => {const map = toolSchemaMap([diff --git a/server/src/lib/tool-args.ts b/server/src/lib/tool-args.tsindex 0ed55105..8c019360 100644--- a/server/src/lib/tool-args.ts+++ b/server/src/lib/tool-args.ts@@ -11,12 +11,23 @@// parameter whose schema says "string" is never touched, even if it looks// like JSON.//+// The walk is recursive. A model that stringifies a top-level array+// stringifies a nested one too, and a repair that stopped at the top level+// left `{"config": {"tags": "[\"a\"]"}}` broken for the client. Each level+// re-applies the identical gate, so depth adds reach without adding latitude:+// still never a guess, still never a coercion, still nothing invented.+//// Also handles whole-arguments double encoding (the arguments field itself// being a JSON-encoded string of a JSON object), which needs no schema.interface JsonSchemaish {type?: string;properties?: Record<string, JsonSchemaish>;+ // `items` lets the walk descend into arrays. A tuple form (an array of+ // per-position schemas) is deliberately not followed: matching a decoded+ // element to its position is exactly the kind of inference that turns a+ // repair into a guess.+ items?: JsonSchemaish;}/**@@ -54,31 +65,97 @@ export function repairToolArguments(args: string, paramSchema?: JsonSchemaish):return changed ? JSON.stringify(parsed) : args;}- const props = paramSchema?.properties;- if (props) {- const obj = parsed as Record<string, unknown>;- for (const [key, value] of Object.entries(obj)) {- if (typeof value !== 'string') continue;- const want = props[key]?.type;- if (want !== 'array' && want !== 'object') continue;- const trimmed = value.trim();- if (!(trimmed.startsWith('[') || trimmed.startsWith('{'))) continue;- try {- const inner = JSON.parse(trimmed);- const isMatch = want === 'array'- ? Array.isArray(inner)- : inner !== null && typeof inner === 'object' && !Array.isArray(inner);- if (isMatch) {- obj[key] = inner;+ if (repairInPlace(parsed, paramSchema)) changed = true;++ return changed ? JSON.stringify(parsed) : args;+}++/**+ * Decode `value` against the schema node that describes it, or return+ * `undefined` to mean "leave it alone".+ *+ * The gate is the whole design: the schema must say `array` or `object`, and+ * the string must parse to exactly that. A parameter whose schema says+ * `string` is never touched even when it looks like JSON, an absent or+ * type-less schema node is never guessed at, and a mismatch is left as-is+ * rather than coerced.+ */+function decodeIfSchemaSays(value: string, schema: JsonSchemaish | undefined): unknown | undefined {+ const want = schema?.type;+ if (want !== 'array' && want !== 'object') return undefined;+ const trimmed = value.trim();+ if (!(trimmed.startsWith('[') || trimmed.startsWith('{'))) return undefined;+ try {+ const inner = JSON.parse(trimmed);+ const isMatch = want === 'array'+ ? Array.isArray(inner)+ : inner !== null && typeof inner === 'object' && !Array.isArray(inner);+ return isMatch ? inner : undefined;+ } catch {+ // Not actually JSON — leave the string alone.+ return undefined;+ }+}++/**+ * Walk a decoded value alongside its schema, decoding double-encoded strings+ * wherever the schema is unambiguous. Mutates `node` in place (it is always a+ * fresh JSON.parse result, never a caller's object) and reports whether+ * anything changed.+ *+ * Recursion is the point: the same model that stringifies a top-level array+ * stringifies a nested one, and until now only the top level was repaired, so+ * `{"config": {"tags": "[\"a\"]"}}` reached the client still broken. Each+ * level re-applies the identical gate, so depth adds reach without loosening+ * the rule — a newly decoded value is itself walked, since a doubly-wrapped+ * payload is exactly what the models that do this produce.+ */+function repairInPlace(node: unknown, schema: JsonSchemaish | undefined): boolean {+ if (node === null || typeof node !== 'object') return false;++ let changed = false;++ if (Array.isArray(node)) {+ // One `items` schema describes every element; a tuple schema is skipped+ // by the type on JsonSchemaish.+ const itemSchema = schema?.items;+ if (!itemSchema) return false;+ for (let i = 0; i < node.length; i++) {+ const value = node[i];+ if (typeof value === 'string') {+ const decoded = decodeIfSchemaSays(value, itemSchema);+ if (decoded !== undefined) {+ node[i] = decoded;changed = true;+ repairInPlace(decoded, itemSchema);}- } catch {- // Not actually JSON — leave the string alone.+ } else if (repairInPlace(value, itemSchema)) {+ changed = true;}}+ return changed;}- return changed ? JSON.stringify(parsed) : args;+ const props = schema?.properties;+ if (!props) return false;++ const obj = node as Record<string, unknown>;+ for (const [key, value] of Object.entries(obj)) {+ const child = props[key];+ if (!child) continue; // Unknown key — no schema to justify a change.+ if (typeof value === 'string') {+ const decoded = decodeIfSchemaSays(value, child);+ if (decoded !== undefined) {+ obj[key] = decoded;+ changed = true;+ repairInPlace(decoded, child);+ }+ } else if (repairInPlace(value, child)) {+ changed = true;+ }+ }++ return changed;}/**