The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): a brace in the code being written made the tool call vanish
purple388fe302958c
diff --git a/src/lib/__tests__/loose-tool-parse.test.ts b/src/lib/__tests__/loose-tool-parse.test.tsindex a90934f9..712dffab 100644--- a/src/lib/__tests__/loose-tool-parse.test.ts+++ b/src/lib/__tests__/loose-tool-parse.test.ts@@ -334,3 +334,43 @@ describe('stripToolCallText — leftover Hermes tags', () => {expect(stripToolCallText(code, KN)).toContain('const a = 1')})})++// ── Code inside the arguments (2026-07-28) ──────────────────────────+//+// The brace scanners counted braces inside JSON STRINGS as structure. A+// file_write whose content holds a regex, a half-open CSS block or a stray+// closing brace therefore either vanished (no candidate — the model believes+// it wrote the file, nothing happened) or was cut one brace early, so the+// arguments arrived wrong. Small local models writing code is the single most+// common use of this loose path.+describe('parseLooseToolCalls — braces inside the content string', () => {+ it('keeps the call when the content holds a lone opening brace', () => {+ const text = '{"name":"file_write","arguments":{"path":"a.js","content":"const re = /\\\\{/"}}'+ const r = parseLooseToolCalls(text, KNOWN)+ expect(r.calls).toHaveLength(1)+ expect(r.calls[0].name).toBe('file_write')+ expect(r.calls[0].arguments.path).toBe('a.js')+ })++ it('keeps the call when the content holds a lone closing brace', () => {+ const text = '{"name":"file_write","arguments":{"path":"a.js","content":"} // end of block"}}'+ const r = parseLooseToolCalls(text, KNOWN)+ expect(r.calls).toHaveLength(1)+ expect(r.calls[0].arguments.content).toBe('} // end of block')+ })++ it('keeps an unfinished CSS block intact', () => {+ const text = '{"name":"file_write","arguments":{"path":"a.css","content":"a { color: red"}}'+ const r = parseLooseToolCalls(text, KNOWN)+ expect(r.calls).toHaveLength(1)+ expect(r.calls[0].arguments.content).toBe('a { color: red')+ })++ it('handles the bare-name form with deeply nested arguments', () => {+ const text = 'file_write {"path":"cfg.json","content":"{\\"a\\":{\\"b\\":{\\"c\\":1}}}"}'+ const r = parseLooseToolCalls(text, KNOWN)+ expect(r.calls).toHaveLength(1)+ expect(r.calls[0].arguments.path).toBe('cfg.json')+ expect(r.matched[0]).toContain('file_write')+ })+})diff --git a/src/lib/json-scan.ts b/src/lib/json-scan.tsnew file mode 100644index 00000000..ee9af23e--- /dev/null+++ b/src/lib/json-scan.ts@@ -0,0 +1,70 @@+/**+ * Balanced-object scanning for LOOSE model output (2026-07-28).+ *+ * Small local models wrap their JSON in prose and, worse, put code inside it.+ * A depth counter that ignores string literals therefore miscounts on the very+ * payload the agent uses most: a `file_write` whose content holds a regex+ * (`/\{/`), a CSS rule cut mid-block, or a stray closing brace. Measured+ * against the old scanners: a lone `{` inside the content made the tool call+ * VANISH (zero candidates — the model thinks it wrote the file, nothing+ * happened), and a lone `}` truncated the object one brace early so the+ * arguments came out wrong.+ *+ * Everything here is string- and escape-aware, so braces inside JSON strings+ * are text, not structure.+ */++/** Walk from `from` to the balanced end of the object that starts there. */+export function balancedObjectAt(text: string, from: number): { text: string; end: number } | null {+ let i = from+ while (i < text.length && text[i] !== '{') {+ if (!/\s/.test(text[i])) return null // something other than whitespace first+ i+++ }+ if (i >= text.length) return null++ let depth = 0+ let inString = false+ let escaped = false+ for (let j = i; j < text.length; j++) {+ const ch = text[j]+ if (escaped) { escaped = false; continue }+ if (ch === '\\') { escaped = inString; continue }+ if (ch === '"') { inString = !inString; continue }+ if (inString) continue+ if (ch === '{') depth+++ else if (ch === '}') {+ depth--+ if (depth === 0) return { text: text.slice(i, j + 1), end: j + 1 }+ }+ }+ return null // never closed+}++/** Every top-level balanced object in `text`, outermost only. */+export function findBalancedObjects(text: string): string[] {+ const out: string[] = []+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== '{') continue+ const obj = balancedObjectAt(text, i)+ if (!obj) continue+ out.push(obj.text)+ i = obj.end - 1 // skip past it; nested objects are part of this one+ }+ return out+}++/** First balanced object in `text` that actually parses as JSON. */+export function extractJsonObject(text: string): any | null {+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== '{') continue+ const obj = balancedObjectAt(text, i)+ if (!obj) continue+ try {+ return JSON.parse(obj.text)+ } catch {+ // Not the object we want — keep looking from the next brace.+ }+ }+ return null+}diff --git a/src/lib/loose-tool-parse.ts b/src/lib/loose-tool-parse.tsindex 34d57215..9bf3b43d 100644--- a/src/lib/loose-tool-parse.ts+++ b/src/lib/loose-tool-parse.ts@@ -19,6 +19,7 @@* it from the visible answer (we don't want the raw `foo(...)` echoed as prose).*/+import { findBalancedObjects, balancedObjectAt } from './json-scan'import { repairJson } from './tool-call-repair'import { parseHermesToolCalls } from '../api/hermes-tool-calling'@@ -77,25 +78,13 @@ function parseCallArgs(inner: string): Record<string, unknown> {/** Find bare/fenced JSON objects that name a known tool: {"name":"X","arguments":{…}}. */function parseJsonObjectCalls(text: string, known: Set<string>): { call: LooseToolCall; snippet: string }[] {const calls: { call: LooseToolCall; snippet: string }[] = []- // Scan every top-level-ish {...} candidate. Cheap brace-scan; repairJson- // tolerates trailing commas / single quotes / unquoted keys.- const candidates: string[] = []- let depth = 0- let start = -1- for (let i = 0; i < text.length; i++) {- const c = text[i]- if (c === '{') {- if (depth === 0) start = i- depth++- } else if (c === '}') {- depth--- if (depth === 0 && start >= 0) {- candidates.push(text.slice(start, i + 1))- start = -1- }- if (depth < 0) depth = 0- }- }+ // Every top-level {...} candidate; repairJson tolerates trailing commas /+ // single quotes / unquoted keys. The scan is string-aware (json-scan.ts):+ // the old depth counter treated braces INSIDE a JSON string as structure, so+ // a file_write whose content held a regex or a half-open block either lost+ // its closing brace (candidate never emitted, call silently dropped) or+ // closed one brace early (wrong arguments).+ const candidates: string[] = findBalancedObjects(text)for (const cand of candidates) {if (!/["']?(?:name|tool|tool_name|tool_call|function)["']?\s*[:=]/.test(cand)) continueconst parsed = repairJson(cand) as Record<string, any> | null@@ -177,16 +166,25 @@ export function parseLooseToolCalls(text: string, known: string[]): LooseParseRe// `[file_read {"path": "/package.json"}]`. Require a non-empty object so a// stray `tool {}` or prose brace isn't misread as a call.for (const name of knownSet) {- const re = new RegExp(`\\[?\\s*\\b${escapeRe(name)}\\b\\s*(\\{(?:[^{}]|\\{[^{}]*\\})*\\})\\s*\\]?`, 'g')+ // Locate the bare name, then take the BALANCED object after it. The old+ // regex could only express one level of nesting, so `{"a":{"b":{"c":1}}}`+ // and any content string with braces fell outside it.+ const nameRe = new RegExp(`\\[?\\s*\\b${escapeRe(name)}\\b\\s*(?=\\{)`, 'g')let m: RegExpExecArray | null- while ((m = re.exec(text)) !== null) {- const parsed = repairJson(m[1]) as Record<string, any> | null+ while ((m = nameRe.exec(text)) !== null) {+ const obj = balancedObjectAt(text, m.index + m[0].length)+ if (!obj) continue+ nameRe.lastIndex = obj.end // never rescan inside the object we just took+ const parsed = repairJson(obj.text) as Record<string, any> | nullif (!parsed || typeof parsed !== 'object') continue// The brace may BE the args, or wrap them under arguments/parameters.const inner = parsed.arguments ?? parsed.parameters ?? parsed.args ?? parsed.paramsconst args = inner && typeof inner === 'object' ? inner : parsedif (args && typeof args === 'object' && Object.keys(args).length > 0) {- push({ name, arguments: args as Record<string, unknown> }, m[0])+ let end = obj.end+ const closer = text.slice(end).match(/^\s*\]/)+ if (closer) end += closer[0].length+ push({ name, arguments: args as Record<string, unknown> }, text.slice(m.index, end))}}}diff --git a/src/lib/memory-extraction.ts b/src/lib/memory-extraction.tsindex a76b991d..7724c4e8 100644--- a/src/lib/memory-extraction.ts+++ b/src/lib/memory-extraction.ts@@ -11,6 +11,7 @@* - reference: Pointers to external resources, tools, URLs*/+import { extractJsonObject } from './json-scan'import type { MemoryType } from '../types/agent-mode'export interface ExtractedMemory {@@ -75,45 +76,6 @@ Analyze this exchange. What (if anything) should be remembered?`* Parse the LLM's extraction response. Handles models that wrap JSON in* markdown code blocks or add preamble text.*/-/**- * First balanced JSON object in `text` that actually parses.- *- * The old `/\{[\s\S]*\}/` was greedy: it spanned from the FIRST brace to the- * LAST one, so a single brace in the model's prose ("Here is the analysis- * {see below}: {...}") swallowed the real object and JSON.parse threw. Small- * local models wrap their JSON in prose constantly, and the two callers fail- * in opposite, silent ways — extraction saves nothing, resolution adds a- * duplicate instead of merging. Walking the braces (string- and escape-aware)- * finds the real object regardless of what surrounds it.- */-function extractJsonObject(text: string): any | null {- for (let i = 0; i < text.length; i++) {- if (text[i] !== '{') continue- let depth = 0- let inString = false- let escaped = false- for (let j = i; j < text.length; j++) {- const ch = text[j]- if (escaped) { escaped = false; continue }- if (ch === '\\') { escaped = inString; continue }- if (ch === '"') { inString = !inString; continue }- if (inString) continue- if (ch === '{') depth++- else if (ch === '}') {- depth--- if (depth === 0) {- try {- return JSON.parse(text.slice(i, j + 1))- } catch {- break // not the object we want — try the next opening brace- }- }- }- }- }- return null-}-export function parseExtractionResponse(response: string): ExtractionResult {const fallback: ExtractionResult = { shouldSave: false, memories: [] }