@vibgrate/cli 2026.806.2 → 2026.807.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-DSC3EQLT.js → agent-K3J6EHLI.js} +11 -11
- package/dist/{agent-DSC3EQLT.js.map → agent-K3J6EHLI.js.map} +1 -1
- package/dist/{baseline-KVCXVZFQ.js → baseline-IAFWF2ET.js} +3 -3
- package/dist/{baseline-KVCXVZFQ.js.map → baseline-IAFWF2ET.js.map} +1 -1
- package/dist/{chunk-VTJAPNJO.js → chunk-2HAJCW7Z.js} +4 -4
- package/dist/{chunk-VTJAPNJO.js.map → chunk-2HAJCW7Z.js.map} +1 -1
- package/dist/{chunk-ZMSTSEGR.js → chunk-2M6B5V2U.js} +3 -3
- package/dist/{chunk-ZMSTSEGR.js.map → chunk-2M6B5V2U.js.map} +1 -1
- package/dist/{chunk-QDKFGLI3.js → chunk-5ESL76CM.js} +6 -6
- package/dist/{chunk-QDKFGLI3.js.map → chunk-5ESL76CM.js.map} +1 -1
- package/dist/{chunk-EW2ZMFUC.js → chunk-7CYFCSY2.js} +4 -4
- package/dist/{chunk-EW2ZMFUC.js.map → chunk-7CYFCSY2.js.map} +1 -1
- package/dist/{chunk-SI4D7DYF.js → chunk-ADP6ITGF.js} +44 -8
- package/dist/chunk-ADP6ITGF.js.map +1 -0
- package/dist/{chunk-TOVVTZTM.js → chunk-EJUMV5HU.js} +3 -3
- package/dist/{chunk-TOVVTZTM.js.map → chunk-EJUMV5HU.js.map} +1 -1
- package/dist/{chunk-HV4CKBXT.js → chunk-EXOYSXH6.js} +3 -3
- package/dist/{chunk-HV4CKBXT.js.map → chunk-EXOYSXH6.js.map} +1 -1
- package/dist/{chunk-7C5UKIXD.js → chunk-FOKURZL3.js} +4 -4
- package/dist/{chunk-7C5UKIXD.js.map → chunk-FOKURZL3.js.map} +1 -1
- package/dist/{chunk-ZPPDKHGL.js → chunk-G4KO5W6H.js} +7 -7
- package/dist/{chunk-ZPPDKHGL.js.map → chunk-G4KO5W6H.js.map} +1 -1
- package/dist/{chunk-455ZJQQ4.js → chunk-GQ2EQXBG.js} +5 -5
- package/dist/{chunk-455ZJQQ4.js.map → chunk-GQ2EQXBG.js.map} +1 -1
- package/dist/chunk-ITY2NPIQ.js +6 -0
- package/dist/{chunk-K6MLOGU4.js.map → chunk-ITY2NPIQ.js.map} +1 -1
- package/dist/{chunk-SBVZGEOB.js → chunk-JFCCJWXD.js} +3 -3
- package/dist/{chunk-SBVZGEOB.js.map → chunk-JFCCJWXD.js.map} +1 -1
- package/dist/{chunk-RL6MHAOK.js → chunk-KEIMMCS5.js} +4 -4
- package/dist/{chunk-RL6MHAOK.js.map → chunk-KEIMMCS5.js.map} +1 -1
- package/dist/{chunk-KYRH3567.js → chunk-LS7GZBKP.js} +3 -3
- package/dist/{chunk-KYRH3567.js.map → chunk-LS7GZBKP.js.map} +1 -1
- package/dist/{chunk-IQJUFRZZ.js → chunk-N5EP5ZR2.js} +5 -5
- package/dist/{chunk-IQJUFRZZ.js.map → chunk-N5EP5ZR2.js.map} +1 -1
- package/dist/{chunk-D2VEJHPC.js → chunk-NWX4VUFS.js} +7 -7
- package/dist/{chunk-D2VEJHPC.js.map → chunk-NWX4VUFS.js.map} +1 -1
- package/dist/{chunk-KAOSPAFK.js → chunk-PT2XQTSK.js} +5 -5
- package/dist/{chunk-KAOSPAFK.js.map → chunk-PT2XQTSK.js.map} +1 -1
- package/dist/{chunk-CBPDYYIH.js → chunk-QXIWQ2WG.js} +4 -4
- package/dist/{chunk-CBPDYYIH.js.map → chunk-QXIWQ2WG.js.map} +1 -1
- package/dist/{chunk-6L6V77HW.js → chunk-VNAOFA6X.js} +8 -8
- package/dist/{chunk-6L6V77HW.js.map → chunk-VNAOFA6X.js.map} +1 -1
- package/dist/{chunk-I2JNLAKW.js → chunk-VQVLY63G.js} +43 -12
- package/dist/chunk-VQVLY63G.js.map +1 -0
- package/dist/{chunk-6XKDAYYR.js → chunk-XSHGXGVJ.js} +4 -4
- package/dist/{chunk-6XKDAYYR.js.map → chunk-XSHGXGVJ.js.map} +1 -1
- package/dist/{chunk-KUZLILN3.js → chunk-Z7FM3ETS.js} +18 -4
- package/dist/chunk-Z7FM3ETS.js.map +1 -0
- package/dist/cli.js +44 -44
- package/dist/cli.js.map +1 -1
- package/dist/embed-worker-main.js +3 -3
- package/dist/{ensure-map-5E5TFPXJ.js → ensure-map-TYMYYIJE.js} +12 -12
- package/dist/{ensure-map-5E5TFPXJ.js.map → ensure-map-TYMYYIJE.js.map} +1 -1
- package/dist/graph-backend-5YOWNHHG.js +13 -0
- package/dist/{graph-backend-GQZXMNRI.js.map → graph-backend-5YOWNHHG.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +11 -11
- package/dist/{interactive-7EZHEBHQ.js → interactive-YEMXHGBO.js} +23 -23
- package/dist/{interactive-7EZHEBHQ.js.map → interactive-YEMXHGBO.js.map} +1 -1
- package/dist/load-IIWVYUN7.js +9 -0
- package/dist/{load-QBVKCWZT.js.map → load-IIWVYUN7.js.map} +1 -1
- package/dist/{run-outcome-NQAU6DOA.js → run-outcome-2JO55QCC.js} +5 -5
- package/dist/{run-outcome-NQAU6DOA.js.map → run-outcome-2JO55QCC.js.map} +1 -1
- package/dist/runtime-session-HFKGKQV7.js +20 -0
- package/dist/{runtime-session-ZPGU4PGW.js.map → runtime-session-HFKGKQV7.js.map} +1 -1
- package/dist/session-5LFX4U2E.js +15 -0
- package/dist/{session-QNSYTLLJ.js.map → session-5LFX4U2E.js.map} +1 -1
- package/dist/session-store-KGONLWHN.js +4 -0
- package/dist/{session-store-F7NX7SZN.js.map → session-store-KGONLWHN.js.map} +1 -1
- package/dist/{stream-json-5WFD6HRO.js → stream-json-DUCFTBUF.js} +11 -11
- package/dist/{stream-json-5WFD6HRO.js.map → stream-json-DUCFTBUF.js.map} +1 -1
- package/dist/{vg-mcp-bridge-VTGXA6CO.js → vg-mcp-bridge-4KPDQUFN.js} +8 -8
- package/dist/{vg-mcp-bridge-VTGXA6CO.js.map → vg-mcp-bridge-4KPDQUFN.js.map} +1 -1
- package/dist/{vgd-54GEZWBI.js → vgd-LFHQ4GWC.js} +8 -8
- package/dist/vgd-LFHQ4GWC.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-I2JNLAKW.js.map +0 -1
- package/dist/chunk-K6MLOGU4.js +0 -6
- package/dist/chunk-KUZLILN3.js.map +0 -1
- package/dist/chunk-SI4D7DYF.js.map +0 -1
- package/dist/graph-backend-GQZXMNRI.js +0 -13
- package/dist/load-QBVKCWZT.js +0 -9
- package/dist/runtime-session-ZPGU4PGW.js +0 -20
- package/dist/session-QNSYTLLJ.js +0 -15
- package/dist/session-store-F7NX7SZN.js +0 -4
- package/dist/vgd-54GEZWBI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/code/prompt.ts","../src/code/apply.ts","../src/code/diff.ts","../src/code/providers.ts"],"names":["i","j"],"mappings":";;;AAoBO,IAAM,kBAAA,GAAqB;AAAA,EAChC,6EAAA;AAAA,EACA,wFAAA;AAAA,EACA,qEAAA;AAAA,EACA,EAAA;AAAA,EACA,mEAAA;AAAA,EACA,EAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,+BAAA;AAAA,EACA,SAAA;AAAA,EACA,qBAAA;AAAA,EACA,iBAAA;AAAA,EACA,EAAA;AAAA,EACA,qFAAA;AAAA,EACA,wBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,YAAA;AAAA,EACA,6CAAA;AAAA,EACA,EAAA;AAAA,EACA;AACF,CAAA,CAAE,KAAK,IAAI,CAAA;AAWJ,SAAS,cAAc,OAAA,EAAqC;AACjE,EAAA,OAAO;AAAA,IACL,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,kBAAA,EAAmB;AAAA,IAC9C,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,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MAER;AACA,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,IAAA,CAAK,SAAS,WAAM,aAAA,CAAe,CAAA,CAAY,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,IACnH;AAAA,EACF;AACF","file":"chunk-ADP6ITGF.js","sourcesContent":["/**\n * Prompt assembly with cache-stable ordering (VG-CLI-CODE §5.1).\n *\n * The fast coding tools lean hard on prompt caching — cached tokens are roughly\n * an order of magnitude cheaper and skip re-encoding, so hit-rate is a\n * first-class speed lever. A cache only helps if the *prefix* is byte-stable\n * across turns, which makes prompt ordering a scheduling constraint, not a\n * cosmetic choice: put the invariant material (the instruction contract + the\n * repo-derived context) first and the volatile turn-specific ask last. This\n * module is the single place that ordering is enforced, so every provider\n * inherits it.\n */\n\nimport type { ChatMessage, CodeContext } from './types.js';\n\n/**\n * The system contract for the planner. Intentionally fixed (no interpolation)\n * so it is a perfectly stable cache prefix. It pins the edit *format* the\n * deterministic applier expects — the model's only job is to emit these blocks.\n */\nexport const CODE_SYSTEM_PROMPT = [\n 'You are a precise code-editing assistant operating inside the Vibgrate CLI.',\n 'You are given repository context derived from a deterministic code graph, then a task.',\n 'Propose the smallest correct change. Do not restate unchanged code.',\n '',\n 'Reply ONLY with edit blocks in this exact format, one per change:',\n '',\n '<path/to/file>',\n '<<<<<<< SEARCH',\n '<exact current lines to find>',\n '=======',\n '<replacement lines>',\n '>>>>>>> REPLACE',\n '',\n 'The SEARCH text must match the current file (whitespace differences are tolerated).',\n 'To add a new file use:',\n 'CREATE <path/to/file>',\n '<full file body>',\n 'END CREATE',\n 'To remove a file use: DELETE <path/to/file>',\n '',\n 'Respect every hard constraint in the context. Keep edits minimal and self-consistent.',\n].join('\\n');\n\n/**\n * Build the chat messages for a planning turn, in cache-stable order:\n * 1. system contract (fixed)\n * 2. repository context (stable for the repo/turn — the big, reusable prefix)\n * 3. the task instruction (volatile — always last)\n *\n * Keeping the volatile instruction in its own trailing user turn maximizes the\n * reusable prefix when the same repo is edited across multiple asks.\n */\nexport function buildMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: CODE_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Now produce the edit blocks for: ${context.instruction}` },\n ];\n}\n\n/**\n * The system contract for the agentic loop (tool-calling). Fixed text → stable\n * cache prefix. Full coding agent (Claude Code / Codex / Cline / OpenHands class):\n * free tool use, Markdown answers, edits only via tools — never a forced edit IR.\n */\nexport const AGENT_SYSTEM_PROMPT = [\n 'You are VG Code — a full coding agent in a real repository (parity with Claude Code / Codex / Cline / OpenHands).',\n 'You handle every intent: questions, locate/search, design discussion, and multi-file edits. The host never forces an edit format on your turn — you choose tools.',\n 'Most requests change application source. Prefer editing code under packages/src, not package manifests,',\n 'unless the user asks for dependency or packaging work.',\n '',\n 'You receive a Task Capsule (ranked symbols + source slices) as first-turn evidence. Use it;',\n 'it does not replace tools when you need more context.',\n '',\n 'Tools: search_code (graph + literal string/URL sweep — like workspace Find), read_file, list_files, graph_impact,',\n 'library_docs, edit_file, create_file, delete_file, apply_patch, run_command, set_progress, inspect_task,',\n 'inspect_change, verify_change, ask_user, finish, abort.',\n '',\n 'You also always have the local Vibgrate AI Context MCP tools (namespaced',\n 'mcp__vibgrate__*): search_symbols, query_graph, orient, get_node, impact_of,',\n 'library_docs, check_drift, and the rest of `vg serve`. Prefer them for deep',\n 'graph navigation, docs, and drift. Project MCP servers may add more mcp__* tools.',\n '',\n '## How to work',\n '- Search or read before you edit. Never invent file contents.',\n '- Smallest correct change; check graph_impact / mcp__vibgrate__impact_of before touching shared hubs.',\n '- edit_file SEARCH must match current file (whitespace-flexible). Prefer apply_patch for multi-file edits.',\n '- Run tests or build when useful; use verify_change after multi-file work.',\n '- For multi-step tasks, call set_progress early with a short plan; mark items done as you complete them.',\n '- Mutating tools and shell need user approval — adapt if declined.',\n '',\n '## Answers and task space',\n '- Call finish with a Markdown summary: what you did or found, key `file:line` refs, next steps.',\n '- Q&A / locate / explain: use search_code (pass the exact needle, e.g. stripe or \"stripe\"), then finish with Markdown.',\n '- Do not invent PatchIR, dummy edits, or raw JSON as the user-facing answer. Edits only via edit_file / apply_patch tools.',\n '',\n '## When stuck',\n '- If intent, scope, or trade-off is ambiguous, call ask_user with one clear question (optional options).',\n '- Prefer ask_user over abort when the user can unblock you. Do not guess product requirements.',\n '- abort only when the request is impossible after clarification or lookup.',\n '',\n 'Never dump raw JSON schemas, PatchIR templates, or tool wire formats as the user-facing answer.',\n].join('\\n');\n\n/** Build the opening messages for an agent run: system contract + graph-grounded context + task. */\nexport function buildAgentMessages(context: CodeContext): ChatMessage[] {\n return [\n { role: 'system', content: AGENT_SYSTEM_PROMPT },\n { role: 'user', content: context.rendered },\n { role: 'user', content: `Task: ${context.instruction}` },\n ];\n}\n","/**\n * The deterministic fast-apply merge engine (VG-CLI-CODE §4).\n *\n * Speed in the fast coding tools comes from letting the planner emit a *terse*\n * edit instead of rewriting a whole file; correctness comes from applying that\n * edit **deterministically and scoped**, never by letting the model free-hand\n * the merge. This module is that deterministic floor: it parses the\n * search/replace edit form and applies it with three escalating match\n * strategies — exact, whitespace-flexible, then graph-span-scoped — so an\n * ambiguous SEARCH is resolved to the symbol the planner actually named rather\n * than the first textual hit. No model is required to apply an edit; a hosted\n * fast-apply model is only ever an *acceleration* over this same contract.\n *\n * Everything here is pure and deterministic: identical (content, edit) always\n * yields the identical outcome, which is what makes it unit- and\n * benchmark-testable offline.\n */\n\nimport type { CodeEdit, EditOutcome } from './types.js';\n\n/** A symbol span the graph knows about, used to disambiguate a SEARCH match. */\nexport interface SymbolSpan {\n /** Qualified name, matched against `anchorSymbol`. */\n qualifiedName: string;\n file: string;\n /** 1-based inclusive line range. */\n start: number;\n end: number;\n}\n\n/**\n * Parse a model's reply into structured edits. The accepted form is the\n * widely-supported search/replace block (robust to surrounding prose and code\n * fences), plus explicit whole-file create/delete markers:\n *\n * ```\n * path/to/file.ts\n * <<<<<<< SEARCH\n * old code\n * =======\n * new code\n * >>>>>>> REPLACE\n * ```\n *\n * `CREATE path/to/new.ts` … `END CREATE` wraps a new file's whole body;\n * `DELETE path/to/gone.ts` removes a file. Parsing is forgiving of blank lines\n * and fences but strict about the block markers, so a malformed block surfaces\n * as an `invalid` outcome at apply time rather than silently corrupting a file.\n */\nexport function parseEdits(text: string): CodeEdit[] {\n const edits: CodeEdit[] = [];\n const lines = text.split('\\n');\n let i = 0;\n let pendingFile = '';\n\n const isFence = (s: string): boolean => /^\\s*```/.test(s);\n\n while (i < lines.length) {\n const line = lines[i];\n\n // Whole-file create: `CREATE <path>` … `END CREATE`.\n const create = /^\\s*CREATE\\s+(\\S.*?)\\s*$/.exec(line);\n if (create) {\n const file = create[1];\n const body: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*END CREATE\\s*$/.test(lines[i])) {\n if (!isFence(lines[i])) body.push(lines[i]);\n i++;\n }\n i++; // consume END CREATE\n edits.push({ op: 'create', file, content: body.join('\\n') });\n pendingFile = '';\n continue;\n }\n\n // Whole-file delete: `DELETE <path>`.\n const del = /^\\s*DELETE\\s+(\\S.*?)\\s*$/.exec(line);\n if (del) {\n edits.push({ op: 'delete', file: del[1] });\n i++;\n pendingFile = '';\n continue;\n }\n\n // Search/replace block. The file path is the most recent non-fence,\n // non-blank line before the SEARCH marker (or an inline `path` on it).\n if (/^\\s*<{5,}\\s*SEARCH/.test(line)) {\n const file = pendingFile;\n const search: string[] = [];\n const replace: string[] = [];\n i++;\n while (i < lines.length && !/^\\s*={5,}\\s*$/.test(lines[i])) {\n search.push(lines[i]);\n i++;\n }\n i++; // consume =======\n while (i < lines.length && !/^\\s*>{5,}\\s*REPLACE/.test(lines[i])) {\n replace.push(lines[i]);\n i++;\n }\n i++; // consume >>>>>>> REPLACE\n edits.push({\n op: 'replace',\n file,\n search: search.join('\\n'),\n replace: replace.join('\\n'),\n anchorSymbol: undefined,\n });\n continue;\n }\n\n // Track the most recent file-path candidate: a lone token that looks like a\n // path (has a slash or a file extension) and isn't a fence/marker.\n const trimmed = line.trim();\n if (trimmed && !isFence(line) && looksLikePath(trimmed)) pendingFile = trimmed.replace(/[:`]+$/, '');\n i++;\n }\n\n return edits;\n}\n\nfunction looksLikePath(s: string): boolean {\n if (/\\s/.test(s.replace(/:$/, ''))) return false; // paths don't contain spaces\n return /\\//.test(s) || /\\.[A-Za-z0-9]{1,8}:?$/.test(s);\n}\n\n/**\n * Apply a single edit to a file's current content (or `null` when the file does\n * not exist). Pure: returns the new content and an outcome; never touches disk.\n * The `spans` are the graph's symbol spans for this file — when a SEARCH is\n * textually ambiguous, a match inside the `anchorSymbol` span wins, which is how\n * the graph makes a terse edit land where the planner meant it to.\n */\nexport function applyEdit(\n content: string | null,\n edit: CodeEdit,\n spans: SymbolSpan[] = [],\n): { content: string | null; outcome: EditOutcome } {\n if (edit.op === 'create') {\n if (content !== null && content !== edit.content) {\n return { content, outcome: { edit, status: 'conflict', reason: `${edit.file} already exists — refusing to overwrite it with a create; use a replace edit instead` } };\n }\n return { content: edit.content, outcome: { edit, status: content === edit.content ? 'no-op' : 'applied', matchedBy: 'exact' } };\n }\n\n if (edit.op === 'delete') {\n if (content === null) return { content: null, outcome: { edit, status: 'no-op', reason: `${edit.file} does not exist — nothing to delete` } };\n return { content: null, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n }\n\n // op === 'replace'\n if (content === null) {\n return { content: null, outcome: { edit, status: 'not-found', reason: `${edit.file} does not exist — a replace needs an existing file (did you mean CREATE ${edit.file}?)` } };\n }\n if (edit.search === '') {\n // Empty SEARCH means \"prepend\" only when the file is empty; otherwise it is\n // ambiguous and we refuse rather than guess a location.\n if (content === '') return { content: edit.replace, outcome: { edit, status: 'applied', matchedBy: 'exact' } };\n return { content, outcome: { edit, status: 'invalid', reason: 'empty SEARCH on a non-empty file is ambiguous — quote the exact lines to replace' } };\n }\n if (edit.search === edit.replace) {\n return { content, outcome: { edit, status: 'no-op', reason: 'SEARCH and REPLACE are identical — no change' } };\n }\n\n const located = locate(content, edit.search, edit.anchorSymbol, spans, edit.file);\n if (located.kind === 'none') {\n return { content, outcome: { edit, status: 'not-found', reason: `the SEARCH text was not found in ${edit.file} — it must match the current file exactly (whitespace-flexible)` } };\n }\n if (located.kind === 'ambiguous') {\n return {\n content,\n outcome: {\n edit,\n status: 'ambiguous',\n reason: `the SEARCH text matches ${located.count} places in ${edit.file} — add more surrounding lines, or name the symbol so the graph can disambiguate`,\n },\n };\n }\n const next = content.slice(0, located.from) + edit.replace + content.slice(located.to);\n return { content: next, outcome: { edit, status: 'applied', matchedBy: located.matchedBy } };\n}\n\n/**\n * Apply a set of edits across a set of files. `read(file)` returns current\n * content or `null`. Edits are applied in the order given, threading each\n * file's evolving content so two edits to the same file compose. Returns, per\n * file, its before/after content and the per-edit outcomes — the dry-run\n * product the session turns into diffs. Deterministic given a deterministic\n * `read`.\n */\nexport function applyEdits(\n edits: CodeEdit[],\n read: (file: string) => string | null,\n spansByFile: (file: string) => SymbolSpan[] = () => [],\n): Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }> {\n const state = new Map<string, { before: string | null; after: string | null; outcomes: EditOutcome[] }>();\n for (const edit of edits) {\n let entry = state.get(edit.file);\n if (!entry) {\n const before = read(edit.file);\n entry = { before, after: before, outcomes: [] };\n state.set(edit.file, entry);\n }\n const { content, outcome } = applyEdit(entry.after, edit, spansByFile(edit.file));\n entry.after = content;\n entry.outcomes.push(outcome);\n }\n return state;\n}\n\ntype Located =\n | { kind: 'unique'; from: number; to: number; matchedBy: 'exact' | 'whitespace' | 'graph-span' }\n | { kind: 'ambiguous'; count: number }\n | { kind: 'none' };\n\n/**\n * Find the SEARCH text in the content. Escalates: (1) exact substring; (2)\n * whitespace-flexible (indentation/trailing-space differences tolerated); and\n * when either is ambiguous, (3) narrow to the `anchorSymbol`'s graph span so the\n * intended occurrence wins. Line-oriented so offsets map back to real edits.\n */\nfunction locate(content: string, search: string, anchor: string | undefined, spans: SymbolSpan[], file: string): Located {\n const exact = allIndexes(content, search);\n if (exact.length === 1) return { kind: 'unique', from: exact[0], to: exact[0] + search.length, matchedBy: 'exact' };\n if (exact.length > 1) {\n const scoped = scopeToAnchor(content, exact.map((from) => ({ from, to: from + search.length })), anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: exact.length };\n }\n\n // Whitespace-flexible: compare with runs of whitespace collapsed and each\n // line trimmed, then map the match back to real character offsets.\n const flex = flexIndexes(content, search);\n if (flex.length === 1) return { kind: 'unique', from: flex[0].from, to: flex[0].to, matchedBy: 'whitespace' };\n if (flex.length > 1) {\n const scoped = scopeToAnchor(content, flex, anchor, spans, file);\n if (scoped) return { ...scoped, matchedBy: 'graph-span' };\n return { kind: 'ambiguous', count: flex.length };\n }\n return { kind: 'none' };\n}\n\n/** Every start index of `needle` in `hay` (non-overlapping left-to-right). */\nfunction allIndexes(hay: string, needle: string): number[] {\n const out: number[] = [];\n if (needle === '') return out;\n let from = 0;\n for (;;) {\n const idx = hay.indexOf(needle, from);\n if (idx === -1) break;\n out.push(idx);\n from = idx + needle.length;\n }\n return out;\n}\n\n/**\n * Whitespace-flexible match: align the search's trimmed non-empty lines against\n * the content's lines, tolerating indentation and trailing-whitespace drift\n * (the single most common reason an otherwise-correct terse edit fails to\n * apply). Returns real character offset ranges for each full-block match.\n */\nfunction flexIndexes(content: string, search: string): { from: number; to: number }[] {\n const cLines = content.split('\\n');\n const sLines = search.split('\\n');\n // Trim a possible leading/trailing blank line from the search block.\n while (sLines.length && sLines[0].trim() === '') sLines.shift();\n while (sLines.length && sLines[sLines.length - 1].trim() === '') sLines.pop();\n if (sLines.length === 0) return [];\n const sNorm = sLines.map((l) => l.trim());\n\n // Precompute char offset of the start of each content line.\n const lineStart: number[] = [];\n let acc = 0;\n for (const l of cLines) {\n lineStart.push(acc);\n acc += l.length + 1; // +1 for the '\\n'\n }\n\n const out: { from: number; to: number }[] = [];\n for (let i = 0; i + sNorm.length <= cLines.length; i++) {\n let ok = true;\n for (let j = 0; j < sNorm.length; j++) {\n if (cLines[i + j].trim() !== sNorm[j]) {\n ok = false;\n break;\n }\n }\n if (!ok) continue;\n const from = lineStart[i];\n const lastLine = i + sNorm.length - 1;\n const to = lineStart[lastLine] + cLines[lastLine].length; // end of the last matched line (exclusive of '\\n')\n out.push({ from, to });\n }\n return out;\n}\n\n/** If exactly one candidate falls inside the anchor symbol's span, pick it. */\nfunction scopeToAnchor(\n content: string,\n candidates: { from: number; to: number }[],\n anchor: string | undefined,\n spans: SymbolSpan[],\n file: string,\n): { kind: 'unique'; from: number; to: number } | null {\n if (!anchor) return null;\n const span = spans.find((s) => s.file === file && s.qualifiedName === anchor);\n if (!span) return null;\n const lineOf = lineIndexer(content);\n const inside = candidates.filter((c) => {\n const line = lineOf(c.from); // 1-based\n return line >= span.start && line <= span.end;\n });\n if (inside.length === 1) return { kind: 'unique', from: inside[0].from, to: inside[0].to };\n return null;\n}\n\n/** Returns a function mapping a char offset → 1-based line number. */\nfunction lineIndexer(content: string): (offset: number) => number {\n const starts: number[] = [0];\n for (let i = 0; i < content.length; i++) if (content[i] === '\\n') starts.push(i + 1);\n return (offset: number) => {\n // binary search for the greatest line start <= offset\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (starts[mid] <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n };\n}\n","/**\n * Deterministic unified diff (VG-CLI-CODE §4.3).\n *\n * A `vg code` dry-run shows the human/agent exactly what would change *before*\n * anything is written — the \"inspect the proposal\" half of the governance\n * lifecycle. This is a small, dependency-free Myers-style line diff producing\n * standard unified-diff hunks. Identical (before, after) always renders the\n * identical text, so the dry-run output is stable and diff-able in tests and\n * benchmarks.\n */\n\n/** Render a unified diff for one file. Returns '' when there is no change. */\nexport function unifiedDiff(before: string | null, after: string | null, file: string, context = 3): string {\n if (before === after) return '';\n if (before === null) return newFileDiff(after ?? '', file);\n if (after === null) return deletedFileDiff(before, file);\n\n const a = splitLines(before);\n const b = splitLines(after);\n const ops = diffLines(a, b);\n const hunks = groupHunks(ops, context);\n if (hunks.length === 0) return '';\n\n const out: string[] = [`--- a/${file}`, `+++ b/${file}`];\n for (const h of hunks) {\n out.push(`@@ -${h.aStart},${h.aLen} +${h.bStart},${h.bLen} @@`);\n for (const line of h.lines) out.push(line);\n }\n return out.join('\\n');\n}\n\n/**\n * Whole-file create/delete bodies larger than this are summarized instead of\n * line-dumped. Small files stay fully visible for review; large page deletes\n * (hundreds/thousands of lines) only need path + line count in the transcript.\n */\nconst FULL_BODY_LINE_CAP = 40;\n\nfunction newFileDiff(after: string, file: string): string {\n const lines = splitLines(after);\n const out = [`--- /dev/null`, `+++ b/${file}`, `@@ -0,0 +1,${lines.length} @@`];\n if (lines.length > FULL_BODY_LINE_CAP) {\n out.push(`+… ${lines.length} lines added …`);\n return out.join('\\n');\n }\n for (const l of lines) out.push(`+${l}`);\n return out.join('\\n');\n}\n\nfunction deletedFileDiff(before: string, file: string): string {\n const lines = splitLines(before);\n const n = lines.length;\n const out = [`--- a/${file}`, `+++ /dev/null`, `@@ -1,${n} +0,0 @@`];\n // No — we do not need the full body in the panel when a page is deleted.\n // Undo still keeps FileChange.before; approval is path-only for delete_file.\n if (n > FULL_BODY_LINE_CAP) {\n out.push(`-… ${n} lines deleted …`);\n return out.join('\\n');\n }\n for (const l of lines) out.push(`-${l}`);\n return out.join('\\n');\n}\n\nfunction splitLines(s: string): string[] {\n if (s === '') return [];\n const lines = s.split('\\n');\n // A trailing newline yields a final '' element — drop it so line counts match.\n if (lines.length && lines[lines.length - 1] === '') lines.pop();\n return lines;\n}\n\ntype Op = { tag: 'eq' | 'del' | 'add'; line: string };\n\n/**\n * Line diff via LCS (dynamic programming). O(n·m) space is fine for source\n * files; the deterministic backtrace (favouring deletions before additions on\n * ties) keeps output stable.\n */\nfunction diffLines(a: string[], b: string[]): Op[] {\n const n = a.length;\n const m = b.length;\n const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);\n }\n }\n const ops: Op[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n ops.push({ tag: 'eq', line: a[i] });\n i++;\n j++;\n } else if (dp[i + 1][j] >= dp[i][j + 1]) {\n ops.push({ tag: 'del', line: a[i] });\n i++;\n } else {\n ops.push({ tag: 'add', line: b[j] });\n j++;\n }\n }\n while (i < n) ops.push({ tag: 'del', line: a[i++] });\n while (j < m) ops.push({ tag: 'add', line: b[j++] });\n return ops;\n}\n\ninterface Hunk {\n aStart: number;\n aLen: number;\n bStart: number;\n bLen: number;\n lines: string[];\n}\n\n/** Group the op stream into unified-diff hunks with `context` equal lines around changes. */\nfunction groupHunks(ops: Op[], context: number): Hunk[] {\n // Index of each op that is a change (del/add).\n const changeIdx = ops.map((o, i) => (o.tag === 'eq' ? -1 : i)).filter((i) => i >= 0);\n if (changeIdx.length === 0) return [];\n\n // Merge change indices into windows that share context.\n const windows: [number, number][] = [];\n let start = Math.max(0, changeIdx[0] - context);\n let end = Math.min(ops.length - 1, changeIdx[0] + context);\n for (let k = 1; k < changeIdx.length; k++) {\n const cs = Math.max(0, changeIdx[k] - context);\n const ce = Math.min(ops.length - 1, changeIdx[k] + context);\n if (cs <= end + 1) {\n end = ce;\n } else {\n windows.push([start, end]);\n start = cs;\n end = ce;\n }\n }\n windows.push([start, end]);\n\n const hunks: Hunk[] = [];\n // Running 1-based line numbers into a and b.\n let aLine = 1;\n let bLine = 1;\n let idx = 0;\n for (const [ws, we] of windows) {\n // advance line counters up to window start\n while (idx < ws) {\n const o = ops[idx];\n if (o.tag !== 'add') aLine++;\n if (o.tag !== 'del') bLine++;\n idx++;\n }\n const hunk: Hunk = { aStart: aLine, aLen: 0, bStart: bLine, bLen: 0, lines: [] };\n for (let k = ws; k <= we; k++) {\n const o = ops[k];\n if (o.tag === 'eq') {\n hunk.lines.push(` ${o.line}`);\n hunk.aLen++;\n hunk.bLen++;\n aLine++;\n bLine++;\n } else if (o.tag === 'del') {\n hunk.lines.push(`-${o.line}`);\n hunk.aLen++;\n aLine++;\n } else {\n hunk.lines.push(`+${o.line}`);\n hunk.bLen++;\n bLine++;\n }\n idx = k + 1;\n }\n // A hunk that starts at line 1 with zero length should report start 0.\n if (hunk.aLen === 0) hunk.aStart = Math.max(0, hunk.aStart - 1);\n if (hunk.bLen === 0) hunk.bStart = Math.max(0, hunk.bStart - 1);\n hunks.push(hunk);\n }\n return hunks;\n}\n\n/**\n * Count +/− lines in a unified diff. Whole-file create/delete summaries\n * (`+… N lines added …` / `-… N lines deleted …`) use the hunk header for the\n * true line count so the rollup stays accurate when bodies are compacted.\n */\nexport function countDiffStats(diff: string): { added: number; removed: number } {\n if (!diff) return { added: 0, removed: 0 };\n\n const isWholeDelete = /^\\+\\+\\+ \\/dev\\/null$/m.test(diff);\n const isWholeCreate = /^--- \\/dev\\/null$/m.test(diff);\n if (isWholeDelete) {\n const m = diff.match(/@@ -(\\d+)(?:,(\\d+))? \\+0(?:,0)? @@/);\n if (m) {\n const n = m[2] != null ? Number(m[2]) : Number(m[1]) || 0;\n return { added: 0, removed: Number.isFinite(n) ? n : 0 };\n }\n }\n if (isWholeCreate) {\n const m = diff.match(/@@ -0(?:,0)? \\+(\\d+)(?:,(\\d+))? @@/);\n if (m) {\n const n = m[2] != null ? Number(m[2]) : Number(m[1]) || 0;\n return { added: Number.isFinite(n) ? n : 0, removed: 0 };\n }\n }\n\n let added = 0;\n let removed = 0;\n for (const line of diff.split('\\n')) {\n if (line.startsWith('+') && !line.startsWith('+++')) added++;\n else if (line.startsWith('-') && !line.startsWith('---')) removed++;\n }\n return { added, removed };\n}\n\n/** A compact one-line changeset summary: `+adds -dels across N file(s)`. */\nexport function summarizeDiffs(diffs: { file: string; diff: string }[]): string {\n let adds = 0;\n let dels = 0;\n let touched = 0;\n for (const { diff } of diffs) {\n if (!diff) continue;\n touched++;\n const { added, removed } = countDiffStats(diff);\n adds += added;\n dels += removed;\n }\n return `+${adds} -${dels} across ${touched} file(s)`;\n}\n","/**\n * Model backends for `vg code` (VG-CLI-CODE §5).\n *\n * Every backend implements the same {@link Provider} contract, so the router and\n * session are provider-agnostic. Three families:\n * - **local HTTP** — Ollama and LM Studio, reached over `fetch` on localhost;\n * no package, no key, no egress. Selected under `--local`.\n * - **hosted HTTP** — any OpenAI-compatible endpoint (OpenRouter, LiteLLM,\n * Together, a self-hosted gateway, …). One shape covers the \"best in breed\n * router\" story: an ordered model list with automatic fallback lives in the\n * router, not here. Keys come from the environment only and are never logged.\n * - **local inference** — a llama.cpp binding loaded on demand via\n * {@link ensurePackage}; this is the one path that may install a package on\n * first use, and only with consent. Model weights are never auto-downloaded.\n *\n * A deterministic {@link MockProvider} backs the tests, the offline benchmark,\n * and the `--mock` flag, so the whole loop runs end-to-end with no network.\n */\n\nimport { ensurePackage, ensureUnavailableMessage } from './ensure.js';\nimport type { ChatMessage, ChatOptions, Provider, ProviderResult, ToolCall, ToolSpec } from './types.js';\n\n/* ------------------------------------------------------------------ *\\\n * Tool-calling wire helpers (shared by the HTTP providers)\n\\* ------------------------------------------------------------------ */\n\n/** Map our ChatMessage union to OpenAI-compatible wire messages (tool calls included). */\nfunction openAiMessages(messages: ChatMessage[]): unknown[] {\n return messages.map((m) => {\n if (m.role === 'tool') return { role: 'tool', tool_call_id: m.toolCallId, name: m.name, content: m.content };\n if (m.role === 'assistant' && m.toolCalls?.length) {\n return {\n role: 'assistant',\n content: m.content || null,\n tool_calls: m.toolCalls.map((t) => ({ id: t.id, type: 'function', function: { name: t.name, arguments: JSON.stringify(t.arguments) } })),\n };\n }\n // Multimodal user turn → OpenAI content-part array (text + data-URI images).\n if (m.role === 'user' && m.images?.length) {\n return {\n role: 'user',\n content: [\n { type: 'text', text: m.content },\n ...m.images.map((img) => ({\n type: 'image_url',\n image_url: { url: `data:${img.mediaType};base64,${img.dataBase64}` },\n })),\n ],\n };\n }\n return { role: m.role, content: m.content };\n });\n}\n\n/** Ollama's chat shape: images ride as a base64 array on the message itself. */\nfunction ollamaMessages(messages: ChatMessage[]): unknown[] {\n return openAiMessages(messages).map((wire, i) => {\n const m = messages[i];\n if (m.role === 'user' && m.images?.length) {\n return { role: 'user', content: m.content, images: m.images.map((img) => img.dataBase64) };\n }\n return wire;\n });\n}\n\n/** OpenAI-compatible `tools` array from our specs. */\nfunction openAiTools(tools: ToolSpec[] | undefined): unknown[] | undefined {\n if (!tools?.length) return undefined;\n return tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));\n}\n\n/** Parse OpenAI-shaped tool_calls, tolerating a malformed arguments string. */\nfunction parseToolCalls(raw: unknown, synthesizePrefix = 'call'): ToolCall[] {\n const calls = raw as { id?: string; function?: { name?: string; arguments?: unknown } }[] | undefined;\n if (!Array.isArray(calls)) return [];\n return calls.map((c, i) => ({\n id: typeof c.id === 'string' && c.id ? c.id : `${synthesizePrefix}_${i}`,\n name: c.function?.name ?? 'unknown',\n arguments: coerceArgs(c.function?.arguments),\n }));\n}\n\nfunction coerceArgs(raw: unknown): Record<string, unknown> {\n if (raw && typeof raw === 'object') return raw as Record<string, unknown>;\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/** Redact anything that looks like a credential before it can reach a log/error. */\nexport function redactSecrets(s: string): string {\n return s\n .replace(/\\b(sk|xoxb|ghp|gho|glpat|AKIA)[-_][A-Za-z0-9-_]{6,}/g, '$1-***redacted***')\n .replace(/Bearer\\s+[A-Za-z0-9._-]{8,}/gi, 'Bearer ***redacted***');\n}\n\n/** Common HTTP-completion error shaping: actionable, internals-free (GUARDRAILS §1.3). */\nfunction httpError(label: string, status: number, hint: string): Error {\n return new Error(`${label} returned HTTP ${status} — ${hint}`);\n}\n\n/**\n * The server's own account of what went wrong, when it gave one. An\n * OpenAI-compatible error body is `{ error: { message } }` or `{ error: '…' }`;\n * the Vibgrate Relay adds `detail` (the upstream's verbatim reason) and\n * `correlation_id`. Guessing a hint from the status code alone turns an\n * actionable \"insufficient credits\" or \"no endpoints match your data policy\"\n * into \"check the model id\" — so prefer the body whenever it carries text.\n * Total and defensive: any parse failure just yields null and the caller\n * falls back to its hint.\n */\n/**\n * A `detail` is the upstream's verbatim reason, and upstream reasons are JSON\n * envelopes more often than sentences. Rendered as-is one fills the panel with\n * braces and then gets cut mid-token by the 400-char cap\n * (`\"requested_providers\":[\"goo`), burying the sentence that explains the\n * failure. Lift that sentence out, and spell out the provider lists a routing\n * refusal carries. Total — a non-envelope string comes back untouched, so a\n * plain-prose detail is never mangled.\n */\nexport function unwrapNestedErrorJson(text: string): string {\n const trimmed = (text ?? '').trim();\n if (!trimmed.startsWith('{')) return trimmed;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return trimmed;\n }\n const obj = (parsed ?? {}) as { error?: unknown; message?: unknown };\n const err = obj.error;\n const errObj = (typeof err === 'object' && err ? err : {}) as { message?: unknown; metadata?: unknown };\n const message =\n typeof err === 'string' ? err : typeof errObj.message === 'string' ? errObj.message : typeof obj.message === 'string' ? obj.message : null;\n if (!message?.trim()) return trimmed;\n const metadata = (typeof errObj.metadata === 'object' && errObj.metadata ? errObj.metadata : {}) as {\n requested_providers?: unknown;\n available_providers?: unknown;\n };\n const names = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && !!v.trim()) : [];\n const requested = names(metadata.requested_providers);\n const available = names(metadata.available_providers);\n const parts = [message.trim()];\n // OpenRouter's own meaning, which is easy to get backwards: `requested` is\n // what the routing was RESTRICTED to, `available` is who actually serves the\n // model. Labelling `available` as \"permitted\" sent debugging the wrong way.\n if (requested.length) parts.push(`routing was restricted to: ${requested.join(', ')}`);\n if (available.length) parts.push(`this model is served by: ${available.join(', ')}`);\n return parts.join(' — ');\n}\n\nexport function relayErrorDetail(body: string): string | null {\n if (!body) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return nonJsonErrorDetail(body);\n }\n const obj = parsed as { error?: unknown; detail?: unknown; message?: unknown; correlation_id?: unknown };\n const err = obj?.error;\n const errObj = (typeof err === 'object' && err ? err : {}) as { message?: unknown; detail?: unknown; correlation_id?: unknown };\n const message =\n typeof err === 'string'\n ? err\n : typeof errObj.message === 'string'\n ? errObj.message\n : typeof obj?.message === 'string'\n ? obj.message\n : null;\n const detailValue = typeof obj?.detail === 'string' ? obj.detail : typeof errObj.detail === 'string' ? errObj.detail : null;\n const detail = detailValue && detailValue.trim() ? unwrapNestedErrorJson(detailValue) : null;\n const parts = [message, detail].filter((p): p is string => !!p && p.trim().length > 0);\n if (!parts.length) return null;\n const correlationId = typeof obj?.correlation_id === 'string' && obj.correlation_id\n ? obj.correlation_id\n : typeof errObj.correlation_id === 'string' && errObj.correlation_id\n ? errObj.correlation_id\n : null;\n const id = correlationId ? ` (correlation id ${correlationId})` : '';\n return `${[...new Set(parts)].join(' — ').slice(0, 400)}${id}`;\n}\n\n/**\n * A non-JSON body — an HTML error page from a CDN or proxy sitting in front of\n * the endpoint, a plain-text proxy notice. A short one is still more\n * informative than nothing; a long one is noise EXCEPT for its `<title>`\n * (\"502 Bad Gateway\", \"Worker threw exception\"), which is the whole story.\n * Without that salvage the caller falls back to a status-code guess and blames\n * the model id for what is really an infrastructure failure.\n */\nfunction nonJsonErrorDetail(body: string): string | null {\n const text = body.trim();\n if (!text) return null;\n if (text.length <= 200) return text;\n const title = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(text)?.[1]?.replace(/\\s+/g, ' ').trim();\n if (title) return title.slice(0, 200);\n // Cloudflare renders its worker/gateway failures as \"Error 1101\"-style codes.\n const code = /\\bError\\s+\\d{3,4}\\b/.exec(text)?.[0];\n return code ?? null;\n}\n\n/**\n * What to suggest for a failing status when the server said nothing useful.\n * A gateway status (502/503/504) means the request never reached the model, or\n * never came back from it — the model id is not the suspect there, and saying\n * it is sends people editing a `--model` flag that was correct all along.\n */\nexport function statusHint(status: number, model: string, apiKeyEnv: string | undefined): string {\n if (status === 401 || status === 403) return `the key in ${apiKeyEnv ?? '(none)'} was rejected — check it has access to \"${model}\"`;\n if (status === 402) return 'the account behind this endpoint is out of credit — top it up, or switch backend with --provider / --local';\n if (status === 404) return `this endpoint has no model \"${model}\" — check the id (\\`vg models catalog\\`) and the base URL`;\n if (status === 408 || status === 504) return 'the request timed out before the model replied — retry, shorten the task, or use --local';\n if (status === 429) return 'rate limited — wait and retry, or switch backend with --provider / --local';\n if (status >= 500) return `the endpoint failed to serve the request — this is an upstream/gateway failure, not the model id \"${model}\"; retry, or use --provider / --local if it persists`;\n return `check the model id \"${model}\" and the endpoint`;\n}\n\n/** Yield newline-delimited lines from a streamed response body. */\nasync function* streamLines(res: Response): AsyncGenerator<string> {\n const reader = res.body?.getReader();\n if (!reader) return;\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n while ((idx = buf.indexOf('\\n')) >= 0) {\n const line = buf.slice(0, idx).trim();\n buf = buf.slice(idx + 1);\n if (line) yield line;\n }\n }\n if (buf.trim()) yield buf.trim();\n}\n\n/** Accumulate an OpenAI-compatible SSE stream into text + tool calls + usage. */\nexport function accumulateOpenAiDelta(\n acc: {\n text: string;\n tools: Map<number, { id?: string; name?: string; args: string }>;\n usage: { promptTokens?: number; completionTokens?: number };\n /** Last non-null `finish_reason` seen — 'length' means the cap cut the reply. */\n finishReason?: string;\n },\n chunk: unknown,\n onToken?: (t: string) => void,\n): void {\n const c = chunk as { choices?: { delta?: { content?: string; tool_calls?: { index?: number; id?: string; function?: { name?: string; arguments?: string } }[] }; finish_reason?: string | null }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const reason = c.choices?.[0]?.finish_reason;\n if (typeof reason === 'string' && reason) acc.finishReason = reason;\n const delta = c.choices?.[0]?.delta;\n if (delta?.content) {\n acc.text += delta.content;\n onToken?.(delta.content);\n }\n for (const tc of delta?.tool_calls ?? []) {\n const idx = tc.index ?? 0;\n const e = acc.tools.get(idx) ?? { args: '' };\n if (tc.id) e.id = tc.id;\n if (tc.function?.name) e.name = tc.function.name;\n if (tc.function?.arguments) e.args += tc.function.arguments;\n acc.tools.set(idx, e);\n }\n if (c.usage) {\n acc.usage.promptTokens = c.usage.prompt_tokens;\n acc.usage.completionTokens = c.usage.completion_tokens;\n }\n}\n\n/** Turn accumulated OpenAI tool-call fragments into ToolCalls. */\nfunction finalizeTools(tools: Map<number, { id?: string; name?: string; args: string }>): ToolCall[] {\n return [...tools.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([i, e]) => ({ id: e.id ?? `call_${i}`, name: e.name ?? 'unknown', arguments: coerceArgs(e.args) }));\n}\n\nasync function postJson(url: string, body: unknown, headers: Record<string, string>, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Deterministic mock (tests / offline / --mock)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A provider that returns a fixed, scripted reply — the deterministic floor that\n * lets the entire `vg code` loop run offline. Used by tests, the benchmark, and\n * the `--mock` flag (which reads the scripted edit blocks from a file).\n */\nexport class MockProvider implements Provider {\n readonly id = 'mock';\n readonly label = 'Mock (deterministic)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly reply: string,\n ) {}\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n return { text: this.reply, model: this.model, provider: this.id };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Ollama (local, no key)\n\\* ------------------------------------------------------------------ */\n\nexport class OllamaProvider implements Provider {\n readonly id = 'ollama';\n readonly label = 'Ollama (local)';\n readonly local = true;\n constructor(\n readonly model: string,\n private readonly host = process.env.OLLAMA_HOST || 'http://127.0.0.1:11434',\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const streaming = !!(opts.stream && opts.onToken);\n let res: Response;\n try {\n res = await postJson(\n `${this.host.replace(/\\/$/, '')}/api/chat`,\n { model: this.model, messages: ollamaMessages(messages), stream: streaming, tools: openAiTools(opts.tools), options: { temperature: opts.temperature ?? 0 } },\n {},\n opts.timeoutMs ?? 120_000,\n );\n } catch {\n throw new Error(`couldn't reach Ollama at ${this.host} — is \\`ollama serve\\` running? (start it, or pass --provider to use a different backend)`);\n }\n if (!res.ok) throw httpError('Ollama', res.status, res.status === 404 ? `model \"${this.model}\" isn't pulled — run \\`ollama pull ${this.model}\\` or pick another with --model` : 'check `ollama serve` and the model name');\n\n if (streaming) {\n let text = '';\n let toolCallsRaw: unknown;\n let truncated = false;\n const usage: { promptTokens?: number; completionTokens?: number } = {};\n for await (const line of streamLines(res)) {\n try {\n const obj = JSON.parse(line) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number; done_reason?: string };\n const delta = obj.message?.content;\n if (delta) {\n text += delta;\n opts.onToken?.(delta);\n }\n if (obj.message?.tool_calls) toolCallsRaw = obj.message.tool_calls;\n if (typeof obj.prompt_eval_count === 'number') usage.promptTokens = obj.prompt_eval_count;\n if (typeof obj.eval_count === 'number') usage.completionTokens = obj.eval_count;\n // Ollama's spelling of finish_reason: 'length' means num_predict cut it.\n if (obj.done_reason === 'length') truncated = true;\n } catch {\n /* skip a malformed line */\n }\n }\n return { text, model: this.model, provider: this.id, toolCalls: parseToolCalls(toolCallsRaw), usage, truncated };\n }\n\n const data = (await res.json()) as { message?: { content?: string; tool_calls?: unknown }; prompt_eval_count?: number; eval_count?: number; done_reason?: string };\n return {\n text: data.message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(data.message?.tool_calls),\n usage: { promptTokens: data.prompt_eval_count, completionTokens: data.eval_count },\n truncated: data.done_reason === 'length',\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * OpenAI-compatible (LM Studio, OpenRouter, LiteLLM, …)\n\\* ------------------------------------------------------------------ */\n\nexport interface OpenAiCompatibleConfig {\n /** Base URL, e.g. `https://openrouter.ai/api/v1` or `http://127.0.0.1:1234/v1`. */\n baseUrl: string;\n /** Env var name holding the API key (never the key itself). Absent for local. */\n apiKeyEnv?: string;\n /** Whether this endpoint is on-device (LM Studio) vs hosted. */\n local: boolean;\n /** Display label. */\n label: string;\n id: string;\n}\n\nexport class OpenAiCompatibleProvider implements Provider {\n readonly id: string;\n readonly label: string;\n readonly local: boolean;\n constructor(\n readonly model: string,\n private readonly config: OpenAiCompatibleConfig,\n ) {\n this.id = config.id;\n this.label = config.label;\n this.local = config.local;\n }\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const headers: Record<string, string> = {};\n if (this.config.apiKeyEnv) {\n const key = process.env[this.config.apiKeyEnv];\n if (!key) {\n throw new Error(`${this.label} needs an API key in ${this.config.apiKeyEnv} — set it in your environment (never pass keys as flags), or use --local for an on-device backend.`);\n }\n headers.authorization = `Bearer ${key}`;\n }\n const streaming = !!(opts.stream && opts.onToken);\n const url = `${this.config.baseUrl.replace(/\\/$/, '')}/chat/completions`;\n const body = {\n model: this.model,\n messages: openAiMessages(messages),\n tools: openAiTools(opts.tools),\n temperature: opts.temperature ?? 0,\n max_tokens: opts.maxTokens,\n stream: streaming,\n ...(streaming ? { stream_options: { include_usage: true } } : {}),\n };\n let res: Response;\n try {\n res = await postJson(url, body, headers, opts.timeoutMs ?? 120_000);\n } catch {\n throw new Error(`couldn't reach ${this.label} at ${this.config.baseUrl} — check the endpoint is up (or use --local).`);\n }\n if (!res.ok) {\n const detail = relayErrorDetail(await res.text().catch(() => ''));\n const hint = detail ?? statusHint(res.status, this.model, this.config.apiKeyEnv);\n throw httpError(this.label, res.status, hint);\n }\n\n if (streaming) {\n const acc = { text: '', tools: new Map<number, { id?: string; name?: string; args: string }>(), usage: {} as { promptTokens?: number; completionTokens?: number }, finishReason: undefined as string | undefined };\n for await (const line of streamLines(res)) {\n if (!line.startsWith('data:')) continue;\n const payload = line.slice(5).trim();\n if (payload === '[DONE]') break;\n try {\n accumulateOpenAiDelta(acc, JSON.parse(payload), opts.onToken);\n } catch {\n /* skip a malformed chunk */\n }\n }\n const tools = finalizeTools(acc.tools);\n return { text: acc.text, model: this.model, provider: this.id, toolCalls: tools.length ? tools : undefined, usage: acc.usage, truncated: acc.finishReason === 'length' };\n }\n const data = (await res.json()) as { choices?: { message?: { content?: string; tool_calls?: unknown }; finish_reason?: string | null }[]; usage?: { prompt_tokens?: number; completion_tokens?: number } };\n const message = data.choices?.[0]?.message;\n return {\n text: message?.content ?? '',\n model: this.model,\n provider: this.id,\n toolCalls: parseToolCalls(message?.tool_calls),\n usage: { promptTokens: data.usage?.prompt_tokens, completionTokens: data.usage?.completion_tokens },\n truncated: data.choices?.[0]?.finish_reason === 'length',\n };\n }\n}\n\n/* ------------------------------------------------------------------ *\\\n * Scripted provider (agent-loop tests / offline demos)\n\\* ------------------------------------------------------------------ */\n\n/**\n * Returns a queued sequence of {@link ProviderResult}s — one per turn — so the\n * agentic loop can be driven deterministically offline: script the tool calls\n * the \"model\" makes (read → search → edit → run → finish) and assert what the\n * agent did. Ignores the incoming messages by design.\n */\nexport class ScriptedProvider implements Provider {\n readonly id = 'scripted';\n readonly label = 'Scripted (deterministic)';\n readonly local = true;\n private turn = 0;\n constructor(\n readonly model: string,\n private readonly steps: Array<{ text?: string; toolCalls?: ToolCall[]; truncated?: boolean }>,\n ) {}\n // Match Provider.chat so tests can wrap/spy with the full signature.\n async chat(_messages?: ChatMessage[], _opts?: ChatOptions): Promise<ProviderResult> {\n const step = this.steps[Math.min(this.turn, this.steps.length - 1)];\n this.turn++;\n return { text: step.text ?? '', model: this.model, provider: this.id, toolCalls: step.toolCalls, truncated: step.truncated };\n }\n}\n\n/** The catalogue of known OpenAI-compatible endpoints, keyed by short id. */\nexport const OPENAI_COMPATIBLE: Record<string, Omit<OpenAiCompatibleConfig, 'label' | 'id'> & { label: string }> = {\n /**\n * Vibgrate Relay — the first-party hosted router. OpenAI-compatible, so it\n * needs no bespoke client. Reached with a Vibgrate token rather than a\n * provider key; the base URL is overridable for staging and self-hosting.\n */\n 'vibgrate-relay': {\n baseUrl: process.env.VIBGRATE_RELAY_URL || 'https://api.vibgrate.com/relay/v1',\n apiKeyEnv: 'VIBGRATE_RELAY_TOKEN',\n local: false,\n label: 'Vibgrate Relay',\n },\n openrouter: { baseUrl: 'https://openrouter.ai/api/v1', apiKeyEnv: 'OPENROUTER_API_KEY', local: false, label: 'OpenRouter' },\n litellm: { baseUrl: process.env.LITELLM_BASE_URL || 'http://127.0.0.1:4000', apiKeyEnv: 'LITELLM_API_KEY', local: false, label: 'LiteLLM' },\n openai: { baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'OPENAI_API_KEY', local: false, label: 'OpenAI' },\n together: { baseUrl: 'https://api.together.xyz/v1', apiKeyEnv: 'TOGETHER_API_KEY', local: false, label: 'Together' },\n /**\n * VS Code language models (Copilot Chat etc.) via the extension's loopback\n * OpenAI-compatible proxy. Base URL is injected as VSCODE_LM_BASE_URL at spawn.\n */\n 'vscode-lm': {\n baseUrl: process.env.VSCODE_LM_BASE_URL || 'http://127.0.0.1:0/v1',\n local: true,\n label: 'VS Code Language Model',\n },\n lmstudio: { baseUrl: process.env.LMSTUDIO_BASE_URL || 'http://127.0.0.1:1234/v1', local: true, label: 'LM Studio (local)' },\n /**\n * Microsoft Foundry Local — OpenAI-compatible local endpoint (Windows NPU/GPU).\n * Default port matches current Foundry Local docs; override with FOUNDRY_LOCAL_BASE_URL.\n */\n 'foundry-local': {\n baseUrl: process.env.FOUNDRY_LOCAL_BASE_URL || 'http://127.0.0.1:5272/v1',\n local: true,\n label: 'Foundry Local',\n },\n};\n\n/* ------------------------------------------------------------------ *\\\n * Local llama.cpp (installs a package on first use, with consent)\n\\* ------------------------------------------------------------------ */\n\n/**\n * A fully-local inference backend backed by the dual-mode llm-host (ADR-005)\n * and `node-llama-cpp`. Install runtime deps via `vg models install` (or pass\n * consent so ensurePackage can run once). Model *weights* are never fetched\n * automatically: `modelPath` must point at a gguf the user already has.\n */\nexport class LocalLlamaProvider implements Provider {\n readonly id = 'llama-cpp';\n /** Surfaced as the Vibgrate model manager (embedded llama.cpp). */\n readonly label = 'Vibgrate (local)';\n readonly local = true;\n /**\n * The embedded host has no native function-calling API — the router wraps\n * this provider in the text tool protocol (text-tool-protocol.ts) so the\n * agent loop still gets structured tool calls.\n */\n readonly supportsTools = false;\n /** Process-wide warm binding + path (best-in-breed: no reload per turn). */\n private static warmBinding: unknown | null = null;\n private static warmHost: import('../runtime/llm-host/embedded.js').EmbeddedLlmHost | null = null;\n private static warmPath: string | null = null;\n\n constructor(\n readonly model: string,\n private readonly modelPath: string,\n private readonly ensure: typeof ensurePackage = ensurePackage,\n private readonly consent = false,\n /** Override isolation (default: env / embedded). */\n private readonly isolation: 'embedded' | 'process' = 'embedded',\n private readonly processEndpoint?: string,\n ) {}\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const {\n createLlmHost,\n EmbeddedLlmHost,\n resolveInferenceIsolation,\n acquireHostSession,\n generateOnSession,\n evictIdleSessions,\n } = await import('../runtime/llm-host/index.js');\n const isolation = resolveInferenceIsolation(this.isolation);\n try {\n const chatMessages = messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n }));\n const genOpts = {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n };\n\n if (isolation === 'process') {\n const host = createLlmHost({ isolation: 'process', endpoint: this.processEndpoint });\n await host.load(this.modelPath);\n const out = await host.generate(chatMessages, genOpts);\n return { text: out.text, model: this.model, provider: this.id };\n }\n\n // Warm path: reuse binding + session across turns.\n if (!LocalLlamaProvider.warmBinding) {\n const res = await this.ensure('node-llama-cpp@^3', { consent: this.consent, onUnavailable: () => {} });\n if (!res.module) {\n throw new Error(ensureUnavailableMessage(res.reason ?? 'no-consent', 'node-llama-cpp', res.detail));\n }\n LocalLlamaProvider.warmBinding = res.module;\n }\n evictIdleSessions(2);\n\n // Prefer direct session API for metrics-rich generate.\n const session = await acquireHostSession(LocalLlamaProvider.warmBinding, this.modelPath);\n const report = await generateOnSession(session, chatMessages, genOpts);\n // Real-ish usage for the panel meter. Never report draftAcceptedChars as\n // tokens — that is a char count of a speculative draft, not model usage\n // (it produced footers like \"56 tokens\" for multi-paragraph answers).\n const promptTokens = report.kvPlan?.totalTokens;\n const completionTokens = report.text ? Math.max(1, Math.ceil(report.text.length / 4)) : undefined;\n return {\n text: report.text,\n model: this.model,\n provider: this.id,\n usage: {\n ...(typeof promptTokens === 'number' && promptTokens > 0 ? { promptTokens } : {}),\n ...(completionTokens != null ? { completionTokens } : {}),\n },\n };\n } catch (e) {\n // Fall back to EmbeddedLlmHost once if session path fails.\n try {\n if (LocalLlamaProvider.warmBinding) {\n if (\n !LocalLlamaProvider.warmHost ||\n LocalLlamaProvider.warmPath !== this.modelPath\n ) {\n const host = createLlmHost({\n isolation: 'embedded',\n binding: LocalLlamaProvider.warmBinding,\n preferGrammar: !!opts.grammar,\n });\n if (host instanceof EmbeddedLlmHost) {\n LocalLlamaProvider.warmHost = host;\n LocalLlamaProvider.warmPath = this.modelPath;\n await host.load(this.modelPath);\n }\n }\n if (LocalLlamaProvider.warmHost) {\n const out = await LocalLlamaProvider.warmHost.generate(\n messages.map((m) => ({\n role: (m.role === 'tool' ? 'user' : m.role) as 'system' | 'user' | 'assistant',\n content: m.content,\n })),\n {\n temperature: opts.temperature ?? 0,\n maxTokens: opts.maxTokens,\n grammar: opts.grammar,\n requireGrammar: opts.requireGrammar,\n identifierTrie: opts.identifierTrie,\n annotateUnknownIdentifiers: !!opts.identifierTrie,\n draftCandidates: opts.draftCandidates,\n promptSegments: opts.promptSegments,\n },\n );\n return { text: out.text, model: this.model, provider: this.id };\n }\n }\n } catch {\n /* rethrow outer */\n }\n throw new Error(`local llama.cpp inference failed for ${this.modelPath} — ${redactSecrets((e as Error).message)}`);\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { startVgdServer } from './chunk-
|
|
1
|
+
import { startVgdServer } from './chunk-2HAJCW7Z.js';
|
|
2
2
|
import { vgdIsRunning, vgdRequest } from './chunk-RBIRXQR6.js';
|
|
3
3
|
|
|
4
4
|
// src/code/runtime-session.ts
|
|
@@ -78,5 +78,5 @@ function noneSession() {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
export { startCodeRuntimeSession };
|
|
81
|
-
//# sourceMappingURL=chunk-
|
|
82
|
-
//# sourceMappingURL=chunk-
|
|
81
|
+
//# sourceMappingURL=chunk-EJUMV5HU.js.map
|
|
82
|
+
//# sourceMappingURL=chunk-EJUMV5HU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/code/runtime-session.ts"],"names":[],"mappings":";;;;AA4CA,eAAsB,wBAAwB,OAAA,EAA6D;AACzG,EAAA,MAAM,aAAa,OAAA,CAAQ,UAAA;AAC3B,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,KAAc,CAAC,OAAgB,YAAA,CAAa,EAAE,UAAA,EAAY,EAAA,EAAI,CAAA,CAAA;AACxF,EAAA,MAAM,OAAA,GAAU,QAAQ,OAAA,IAAW,UAAA;AACnC,EAAA,MA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AM,WAAA,IAAe,GAAA,cAAiB,GAAA,CAAI,SAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IACN,KAAK,OAAA,CAAQ,GAAA;AAAA,IACb,SAAA;AAAA,IACA,YAAY,MAAA,CAAO,UAAA;AAAA,IACnB,KAAA,EAAO,CAAA,aAAA,CAAA;AAAA,IACP,MAAM,OAAA,GAAU;AACd,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,IAAI;AACF,QAAA,MAAM,OAAO,KAAA,EAAM;AAAA,MACrB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,GACF;AACF;AAEA,SAAS,WAAA,GAAkC;AACzC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAA;AAAA,IACN,GAAA,EAAK,MAAA;AAAA,IACL,SAAA,EAAW,MAAA;AAAA,IACX,UAAA,EAAY,MAAA;AAAA,IACZ,KAAA,EAAO,EAAA;AAAA,IACP,MAAM,OAAA,GAAU;AAAA,IAEhB;AAAA,GACF;AACF","file":"chunk-EJUMV5HU.js","sourcesContent":["/**\n * Session boundary between VG Code and the Fusion Runtime daemon (`vgd`).\n *\n * Replaces the old {@link GraphProcess} (`vg serve` child) for the interactive\n * coding REPL. Behaviour:\n *\n * 1. If a local vgd is already running — register this workspace and leave the\n * daemon running when the session ends (unregister only).\n * 2. Otherwise — start an **in-process** vgd for the life of the session and\n * tear it down on dispose. No second OS process, no `vg serve` spawn.\n *\n * Never throws: a failure to attach degrades to “no runtime session” and the\n * agent continues with the in-process graph only (same safety as GraphProcess).\n */\n\nimport { startVgdServer, vgdIsRunning, vgdRequest, type VgdServer } from '../runtime/vgd/index.js';\nimport type { WorkspaceRecord } from '../runtime/vgd/protocol.js';\n\nexport type RuntimeSessionKind = 'attached' | 'owned' | 'none';\n\nexport interface RuntimeSessionOptions {\n root: string;\n /** Override socket path (tests). */\n socketPath?: string;\n /** Injectable connect/start hooks (tests). */\n isRunning?: (socketPath?: string) => Promise<boolean>;\n request?: typeof vgdRequest;\n startServer?: (opts: { socketPath?: string }) => Promise<VgdServer>;\n}\n\nexport interface CodeRuntimeSession {\n readonly kind: RuntimeSessionKind;\n /** Daemon pid when known (attached status or owned process). */\n readonly pid: number | undefined;\n readonly workspace: WorkspaceRecord | undefined;\n readonly socketPath: string | undefined;\n /** Human label for the REPL intro line. */\n readonly label: string;\n dispose(): Promise<void>;\n}\n\n/**\n * Attach VG Code to vgd for one coding session. Always resolves (never throws).\n */\nexport async function startCodeRuntimeSession(options: RuntimeSessionOptions): Promise<CodeRuntimeSession> {\n const socketPath = options.socketPath;\n const isRunning = options.isRunning ?? ((sp?: string) => vgdIsRunning({ socketPath: sp }));\n const request = options.request ?? vgdRequest;\n const startServer = options.startServer ?? ((opts: { socketPath?: string }) => startVgdServer(opts));\n\n try {\n if (await isRunning(socketPath)) {\n return await attachExisting(options.root, socketPath, request);\n }\n return await startOwned(options.root, socketPath, startServer, request);\n } catch {\n return noneSession();\n }\n}\n\nasync function attachExisting(\n root: string,\n socketPath: string | undefined,\n request: typeof vgdRequest,\n): Promise<CodeRuntimeSession> {\n const clientOpts = { socketPath };\n const reg = await request({ op: 'register', root }, clientOpts);\n if (!reg.ok || !('workspace' in reg)) return noneSession();\n const status = await request({ op: 'status' }, clientOpts).catch(() => null);\n const pid = status && status.ok && 'pid' in status ? status.pid : undefined;\n let disposed = false;\n return {\n kind: 'attached',\n pid,\n workspace: reg.workspace,\n socketPath: status && status.ok && 'socketPath' in status ? status.socketPath : socketPath,\n label: pid != null ? `vgd ${pid}` : 'vgd',\n async dispose() {\n if (disposed) return;\n disposed = true;\n try {\n await request({ op: 'unregister', root }, clientOpts);\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\nasync function startOwned(\n root: string,\n socketPath: string | undefined,\n startServer: (opts: { socketPath?: string }) => Promise<VgdServer>,\n request: typeof vgdRequest,\n): Promise<CodeRuntimeSession> {\n const server = await startServer({ socketPath });\n const clientOpts = { socketPath: server.socketPath };\n let workspace: WorkspaceRecord | undefined;\n try {\n const reg = await request({ op: 'register', root }, clientOpts);\n if (reg.ok && 'workspace' in reg) workspace = reg.workspace;\n } catch {\n /* registry optional for an empty session */\n }\n let disposed = false;\n return {\n kind: 'owned',\n pid: process.pid,\n workspace,\n socketPath: server.socketPath,\n label: `vgd (session)`,\n async dispose() {\n if (disposed) return;\n disposed = true;\n try {\n await server.close();\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\nfunction noneSession(): CodeRuntimeSession {\n return {\n kind: 'none',\n pid: undefined,\n workspace: undefined,\n socketPath: undefined,\n label: '',\n async dispose() {\n /* no-op */\n },\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { vgdRequest } from './chunk-RBIRXQR6.js';
|
|
2
2
|
import { resolveOne } from './chunk-J7LKEB2R.js';
|
|
3
|
-
import { impactOf, queryGraph } from './chunk-
|
|
3
|
+
import { impactOf, queryGraph } from './chunk-7CYFCSY2.js';
|
|
4
4
|
|
|
5
5
|
// src/code/graph-backend.ts
|
|
6
6
|
function localGraphBackend(graph) {
|
|
@@ -132,5 +132,5 @@ function resolveSymbolId(graph, symbol) {
|
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
export { localGraphBackend, resolveGraphBackend, vgdGraphBackend };
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
136
|
-
//# sourceMappingURL=chunk-
|
|
135
|
+
//# sourceMappingURL=chunk-EXOYSXH6.js.map
|
|
136
|
+
//# sourceMappingURL=chunk-EXOYSXH6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/code/graph-backend.ts"],"names":[],"mappings":";;;;;AA2DO,SAAS,kBAAkB,KAAA,EAA8B;AAC9D,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,OAAA;AAAA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A;AACrB","file":"chunk-HV4CKBXT.js","sourcesContent":["/**\n * Graph query backend for the agent tool layer (Fusion Runtime).\n *\n * Tools prefer a warm ActiveGraph in vgd when a daemon session is attached;\n * otherwise they fall back to the in-process {@link VgGraph}. Failures never\n * surface to the model as transport errors — they degrade to local query.\n */\n\nimport { queryGraph } from '../engine/query.js';\nimport { impactOf } from '../engine/impact.js';\nimport { resolveOne } from '../engine/lookup.js';\nimport { vgdRequest, type VgdClientOptions } from '../runtime/vgd/client.js';\nimport type { VgdRequest } from '../runtime/vgd/protocol.js';\nimport type { VgGraph } from '../schema.js';\n\nexport type GraphBackendSource = 'local' | 'vgd';\n\nexport interface GraphSearchHit {\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n score: number;\n why: string;\n signature?: string | null;\n}\n\nexport interface GraphImpactHit {\n id: string;\n name: string;\n kind: string;\n file: string;\n line: number;\n depth: number;\n confidence: number;\n}\n\nexport interface GraphImpactResult {\n root: { id: string; name: string };\n depth: number;\n affected: GraphImpactHit[];\n direct: number;\n transitive: number;\n source: GraphBackendSource;\n}\n\nexport interface GraphSearchResult {\n matches: GraphSearchHit[];\n source: GraphBackendSource;\n}\n\nexport interface GraphBackend {\n readonly source: GraphBackendSource;\n search(query: string, opts?: { limit?: number }): Promise<GraphSearchResult>;\n impact(symbol: string, opts?: { depth?: number }): Promise<GraphImpactResult | null>;\n}\n\n/** Pure in-process backend over a loaded graph. */\nexport function localGraphBackend(graph: VgGraph): GraphBackend {\n return {\n source: 'local',\n async search(query, opts) {\n const res = queryGraph(graph, query, { budget: 1500, limit: opts?.limit ?? 10 });\n return {\n source: 'local',\n matches: res.matches.map((m) => ({\n id: m.node.id,\n qualifiedName: m.node.qualifiedName,\n kind: m.node.kind,\n file: m.node.file,\n line: m.node.span?.start ?? 0,\n score: m.score,\n why: m.why,\n signature: m.node.signature ?? null,\n })),\n };\n },\n async impact(symbol, opts) {\n const node = resolveSymbolId(graph, symbol);\n if (!node) return null;\n const imp = impactOf(graph, node, { depth: opts?.depth ?? 4 });\n return {\n source: 'local',\n root: imp.root,\n depth: imp.depth,\n affected: imp.affected.map((a) => ({\n id: a.id,\n name: a.name,\n kind: a.kind,\n file: a.file,\n line: a.line,\n depth: a.depth,\n confidence: a.confidence,\n })),\n direct: imp.direct,\n transitive: imp.transitive,\n };\n },\n };\n}\n\nexport interface VgdGraphBackendOptions {\n repositoryId: string;\n gitRef?: string;\n socketPath?: string;\n /** Always required for fall back when vgd has no slot or is down. */\n fallback: VgGraph;\n request?: (req: VgdRequest, opts?: VgdClientOptions) => Promise<unknown>;\n}\n\n/**\n * Prefer vgd query/impact; on any failure or empty daemon state, use local.\n * The returned `source` reflects which path answered.\n */\nexport function vgdGraphBackend(options: VgdGraphBackendOptions): GraphBackend {\n const local = localGraphBackend(options.fallback);\n const request = options.request ?? ((req, opts) => vgdRequest(req, opts));\n const clientOpts: VgdClientOptions = { socketPath: options.socketPath };\n\n return {\n source: 'vgd',\n async search(query, opts) {\n try {\n const res = (await request(\n {\n op: 'query-graph',\n repositoryId: options.repositoryId,\n query,\n limit: opts?.limit ?? 10,\n gitRef: options.gitRef,\n },\n clientOpts,\n )) as {\n ok?: boolean;\n matches?: Array<{\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n score: number;\n why: string;\n }>;\n };\n if (res?.ok && Array.isArray(res.matches)) {\n return {\n source: 'vgd',\n matches: res.matches.map((m) => ({\n id: m.id,\n qualifiedName: m.qualifiedName,\n kind: m.kind,\n file: m.file,\n line: m.line,\n score: m.score,\n why: m.why,\n signature: null,\n })),\n };\n }\n } catch {\n /* fall through */\n }\n return local.search(query, opts);\n },\n async impact(symbol, opts) {\n try {\n const res = (await request(\n {\n op: 'impact-of',\n repositoryId: options.repositoryId,\n symbol,\n depth: opts?.depth ?? 4,\n gitRef: options.gitRef,\n },\n clientOpts,\n )) as {\n ok?: boolean;\n root?: { id: string; name: string };\n depth?: number;\n affected?: GraphImpactHit[];\n direct?: number;\n transitive?: number;\n };\n if (res?.ok && res.root && Array.isArray(res.affected)) {\n return {\n source: 'vgd',\n root: res.root,\n depth: res.depth ?? opts?.depth ?? 4,\n affected: res.affected,\n direct: res.direct ?? 0,\n transitive: res.transitive ?? 0,\n };\n }\n } catch {\n /* fall through */\n }\n return local.impact(symbol, opts);\n },\n };\n}\n\n/**\n * Pick a backend: vgd when repositoryId + socket are known, else local.\n */\nexport function resolveGraphBackend(input: {\n graph: VgGraph;\n repositoryId?: string | null;\n gitRef?: string | null;\n socketPath?: string | null;\n}): GraphBackend {\n if (input.repositoryId && input.socketPath) {\n return vgdGraphBackend({\n repositoryId: input.repositoryId,\n gitRef: input.gitRef ?? undefined,\n socketPath: input.socketPath,\n fallback: input.graph,\n });\n }\n return localGraphBackend(input.graph);\n}\n\nfunction resolveSymbolId(graph: VgGraph, symbol: string): string | null {\n if (graph.nodes.some((n) => n.id === symbol)) return symbol;\n const hit = resolveOne(graph, symbol);\n if (hit.node?.id) return hit.node.id;\n if (hit.candidates.length === 1 && hit.candidates[0]?.id) return hit.candidates[0].id;\n const q = symbol.toLowerCase();\n const byQn = graph.nodes.find((n) => n.qualifiedName?.toLowerCase() === q || n.name?.toLowerCase() === q);\n return byQn?.id ?? null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/code/graph-backend.ts"],"names":[],"mappings":";;;;;AA2DO,SAAS,kBAAkB,KAAA,EAA8B;AAC9D,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,OAAA;AAAA,IACR,MAAM,MAAA,CAAO,KAAA,EAAO,IAAA,EAAM;AACxB,MAAA,MAAM,GAAA,GAAM,UAAA,CAAW,KAAA,EAAO,KAAA,EAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,KAAA,IAAS,EAAA,EAAI,CAAA;AAC/E,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,OAAA;AAAA,QACR,OAAA,EAAS,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,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AA,IAAU,MAAA;AAAA,MACxB,YAAY,KAAA,CAAM,UAAA;AAAA,MAClB,UAAU,KAAA,CAAM;AAAA,KACjB,CAAA;AAAA,EACH;AACA,EAAA,OAAO,iBAAA,CAAkB,MAAM,KAAK,CAAA;AACtC;AAEA,SAAS,eAAA,CAAgB,OAAgB,MAAA,EAA+B;AACtE,EAAA,IAAI,KAAA,CAAM,MAAM,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,EAAA,KAAO,MAAM,CAAA,EAAG,OAAO,MAAA;AACrD,EAAA,MAAM,GAAA,GAAM,UAAA,CAAW,KAAA,EAAO,MAAM,CAAA;AACpC,EAAA,IAAI,GAAA,CAAI,IAAA,EAAM,EAAA,EAAI,OAAO,IAAI,IAAA,CAAK,EAAA;AAClC,EAAA,IAAI,GAAA,CAAI,UAAA,CAAW,MAAA,KAAW,CAAA,IAAK,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA,EAAG,EAAA,EAAI,OAAO,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA,CAAE,EAAA;AACnF,EAAA,MAAM,CAAA,GAAI,OAAO,WAAA,EAAY;AAC7B,EAAA,MAAM,IAAA,GAAO,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,aAAA,EAAe,WAAA,OAAkB,CAAA,IAAK,CAAA,CAAE,IAAA,EAAM,WAAA,OAAkB,CAAC,CAAA;AACxG,EAAA,OAAO,MAAM,EAAA,IAAM,IAAA;AACrB","file":"chunk-EXOYSXH6.js","sourcesContent":["/**\n * Graph query backend for the agent tool layer (Fusion Runtime).\n *\n * Tools prefer a warm ActiveGraph in vgd when a daemon session is attached;\n * otherwise they fall back to the in-process {@link VgGraph}. Failures never\n * surface to the model as transport errors — they degrade to local query.\n */\n\nimport { queryGraph } from '../engine/query.js';\nimport { impactOf } from '../engine/impact.js';\nimport { resolveOne } from '../engine/lookup.js';\nimport { vgdRequest, type VgdClientOptions } from '../runtime/vgd/client.js';\nimport type { VgdRequest } from '../runtime/vgd/protocol.js';\nimport type { VgGraph } from '../schema.js';\n\nexport type GraphBackendSource = 'local' | 'vgd';\n\nexport interface GraphSearchHit {\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n score: number;\n why: string;\n signature?: string | null;\n}\n\nexport interface GraphImpactHit {\n id: string;\n name: string;\n kind: string;\n file: string;\n line: number;\n depth: number;\n confidence: number;\n}\n\nexport interface GraphImpactResult {\n root: { id: string; name: string };\n depth: number;\n affected: GraphImpactHit[];\n direct: number;\n transitive: number;\n source: GraphBackendSource;\n}\n\nexport interface GraphSearchResult {\n matches: GraphSearchHit[];\n source: GraphBackendSource;\n}\n\nexport interface GraphBackend {\n readonly source: GraphBackendSource;\n search(query: string, opts?: { limit?: number }): Promise<GraphSearchResult>;\n impact(symbol: string, opts?: { depth?: number }): Promise<GraphImpactResult | null>;\n}\n\n/** Pure in-process backend over a loaded graph. */\nexport function localGraphBackend(graph: VgGraph): GraphBackend {\n return {\n source: 'local',\n async search(query, opts) {\n const res = queryGraph(graph, query, { budget: 1500, limit: opts?.limit ?? 10 });\n return {\n source: 'local',\n matches: res.matches.map((m) => ({\n id: m.node.id,\n qualifiedName: m.node.qualifiedName,\n kind: m.node.kind,\n file: m.node.file,\n line: m.node.span?.start ?? 0,\n score: m.score,\n why: m.why,\n signature: m.node.signature ?? null,\n })),\n };\n },\n async impact(symbol, opts) {\n const node = resolveSymbolId(graph, symbol);\n if (!node) return null;\n const imp = impactOf(graph, node, { depth: opts?.depth ?? 4 });\n return {\n source: 'local',\n root: imp.root,\n depth: imp.depth,\n affected: imp.affected.map((a) => ({\n id: a.id,\n name: a.name,\n kind: a.kind,\n file: a.file,\n line: a.line,\n depth: a.depth,\n confidence: a.confidence,\n })),\n direct: imp.direct,\n transitive: imp.transitive,\n };\n },\n };\n}\n\nexport interface VgdGraphBackendOptions {\n repositoryId: string;\n gitRef?: string;\n socketPath?: string;\n /** Always required for fall back when vgd has no slot or is down. */\n fallback: VgGraph;\n request?: (req: VgdRequest, opts?: VgdClientOptions) => Promise<unknown>;\n}\n\n/**\n * Prefer vgd query/impact; on any failure or empty daemon state, use local.\n * The returned `source` reflects which path answered.\n */\nexport function vgdGraphBackend(options: VgdGraphBackendOptions): GraphBackend {\n const local = localGraphBackend(options.fallback);\n const request = options.request ?? ((req, opts) => vgdRequest(req, opts));\n const clientOpts: VgdClientOptions = { socketPath: options.socketPath };\n\n return {\n source: 'vgd',\n async search(query, opts) {\n try {\n const res = (await request(\n {\n op: 'query-graph',\n repositoryId: options.repositoryId,\n query,\n limit: opts?.limit ?? 10,\n gitRef: options.gitRef,\n },\n clientOpts,\n )) as {\n ok?: boolean;\n matches?: Array<{\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n score: number;\n why: string;\n }>;\n };\n if (res?.ok && Array.isArray(res.matches)) {\n return {\n source: 'vgd',\n matches: res.matches.map((m) => ({\n id: m.id,\n qualifiedName: m.qualifiedName,\n kind: m.kind,\n file: m.file,\n line: m.line,\n score: m.score,\n why: m.why,\n signature: null,\n })),\n };\n }\n } catch {\n /* fall through */\n }\n return local.search(query, opts);\n },\n async impact(symbol, opts) {\n try {\n const res = (await request(\n {\n op: 'impact-of',\n repositoryId: options.repositoryId,\n symbol,\n depth: opts?.depth ?? 4,\n gitRef: options.gitRef,\n },\n clientOpts,\n )) as {\n ok?: boolean;\n root?: { id: string; name: string };\n depth?: number;\n affected?: GraphImpactHit[];\n direct?: number;\n transitive?: number;\n };\n if (res?.ok && res.root && Array.isArray(res.affected)) {\n return {\n source: 'vgd',\n root: res.root,\n depth: res.depth ?? opts?.depth ?? 4,\n affected: res.affected,\n direct: res.direct ?? 0,\n transitive: res.transitive ?? 0,\n };\n }\n } catch {\n /* fall through */\n }\n return local.impact(symbol, opts);\n },\n };\n}\n\n/**\n * Pick a backend: vgd when repositoryId + socket are known, else local.\n */\nexport function resolveGraphBackend(input: {\n graph: VgGraph;\n repositoryId?: string | null;\n gitRef?: string | null;\n socketPath?: string | null;\n}): GraphBackend {\n if (input.repositoryId && input.socketPath) {\n return vgdGraphBackend({\n repositoryId: input.repositoryId,\n gitRef: input.gitRef ?? undefined,\n socketPath: input.socketPath,\n fallback: input.graph,\n });\n }\n return localGraphBackend(input.graph);\n}\n\nfunction resolveSymbolId(graph: VgGraph, symbol: string): string | null {\n if (graph.nodes.some((n) => n.id === symbol)) return symbol;\n const hit = resolveOne(graph, symbol);\n if (hit.node?.id) return hit.node.id;\n if (hit.candidates.length === 1 && hit.candidates[0]?.id) return hit.candidates[0].id;\n const q = symbol.toLowerCase();\n const byQn = graph.nodes.find((n) => n.qualifiedName?.toLowerCase() === q || n.name?.toLowerCase() === q);\n return byQn?.id ?? null;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { indexFor, queryGraph, impactOf, conceptMapLines, extractLiteralNeedles } from './chunk-
|
|
2
|
-
import { cacheDir } from './chunk-
|
|
1
|
+
import { indexFor, queryGraph, impactOf, conceptMapLines, extractLiteralNeedles } from './chunk-7CYFCSY2.js';
|
|
2
|
+
import { cacheDir } from './chunk-2M6B5V2U.js';
|
|
3
3
|
import { hashString } from './chunk-JFGYT6BI.js';
|
|
4
4
|
import * as fs from 'fs';
|
|
5
5
|
import * as path from 'path';
|
|
@@ -640,5 +640,5 @@ function estimateTokens2(text) {
|
|
|
640
640
|
}
|
|
641
641
|
|
|
642
642
|
export { CAPSULE_COMPILER_ID, CAPSULE_RANKING_VERSION, CLI_TOOL_ALIASES, PER_FILE_TOKENS, SAVINGS_TOOLS, TASK_CAPSULE_SCHEMA_VERSION, buildCodeContext, buildTaskCapsule, capsuleToCodeContext, clearSavings, readModelSavings, readSavings, readUsage, recordCliCall, recordSaving, sanitizeClient, savingsLedgerPath, savingsRecorded, summarizeCapsule };
|
|
643
|
-
//# sourceMappingURL=chunk-
|
|
644
|
-
//# sourceMappingURL=chunk-
|
|
643
|
+
//# sourceMappingURL=chunk-FOKURZL3.js.map
|
|
644
|
+
//# sourceMappingURL=chunk-FOKURZL3.js.map
|