@vibgrate/cli 2026.801.1 → 2026.803.3
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-JTA4YWMQ.js +24 -0
- package/dist/{agent-4DAECASW.js.map → agent-JTA4YWMQ.js.map} +1 -1
- package/dist/baseline-2V7PKA7Q.js +9 -0
- package/dist/{baseline-4BDH4F2W.js.map → baseline-2V7PKA7Q.js.map} +1 -1
- package/dist/{chunk-76TDXGGF.js → chunk-3Q3ZXJZP.js} +218 -51
- package/dist/chunk-3Q3ZXJZP.js.map +1 -0
- package/dist/{chunk-G7W4MFPZ.js → chunk-4ACXDVON.js} +4 -4
- package/dist/{chunk-G7W4MFPZ.js.map → chunk-4ACXDVON.js.map} +1 -1
- package/dist/{chunk-E6H2F2XF.js → chunk-6DFV4WCQ.js} +3 -3
- package/dist/{chunk-E6H2F2XF.js.map → chunk-6DFV4WCQ.js.map} +1 -1
- package/dist/{chunk-FF5ZQ6KI.js → chunk-6JP7HGIF.js} +4 -4
- package/dist/{chunk-FF5ZQ6KI.js.map → chunk-6JP7HGIF.js.map} +1 -1
- package/dist/chunk-7KNFG44U.js +6 -0
- package/dist/{chunk-TGDHOAXX.js.map → chunk-7KNFG44U.js.map} +1 -1
- package/dist/{chunk-T6DRYOMT.js → chunk-CPLG4GFB.js} +4 -4
- package/dist/{chunk-T6DRYOMT.js.map → chunk-CPLG4GFB.js.map} +1 -1
- package/dist/{chunk-SDG242R4.js → chunk-HC44772H.js} +132 -365
- package/dist/chunk-HC44772H.js.map +1 -0
- package/dist/{chunk-MPP4S4OE.js → chunk-K6Q6HTFD.js} +32 -11
- package/dist/chunk-K6Q6HTFD.js.map +1 -0
- package/dist/{chunk-7G5S5KZN.js → chunk-KUZLILN3.js} +16 -3
- package/dist/chunk-KUZLILN3.js.map +1 -0
- package/dist/{chunk-XEJJGDGX.js → chunk-KYX2YCXT.js} +134 -9
- package/dist/chunk-KYX2YCXT.js.map +1 -0
- package/dist/{chunk-V2QK3IUY.js → chunk-L5PUNO3T.js} +4 -4
- package/dist/{chunk-V2QK3IUY.js.map → chunk-L5PUNO3T.js.map} +1 -1
- package/dist/{chunk-7PVCHLR2.js → chunk-M452MRWI.js} +109 -10
- package/dist/chunk-M452MRWI.js.map +1 -0
- package/dist/{chunk-WIDZ5IE7.js → chunk-M7773OUN.js} +14 -7
- package/dist/chunk-M7773OUN.js.map +1 -0
- package/dist/{chunk-XRN7DQGR.js → chunk-NJFQCDGA.js} +3 -3
- package/dist/{chunk-XRN7DQGR.js.map → chunk-NJFQCDGA.js.map} +1 -1
- package/dist/{chunk-BNEHDLVZ.js → chunk-NSWEJPLV.js} +129 -20
- package/dist/chunk-NSWEJPLV.js.map +1 -0
- package/dist/{chunk-JLWI2JGA.js → chunk-NUZM7UOR.js} +117 -6
- package/dist/chunk-NUZM7UOR.js.map +1 -0
- package/dist/{chunk-B3OMGYZZ.js → chunk-PXM3VZYR.js} +4 -4
- package/dist/{chunk-B3OMGYZZ.js.map → chunk-PXM3VZYR.js.map} +1 -1
- package/dist/chunk-QMME6TB4.js +457 -0
- package/dist/chunk-QMME6TB4.js.map +1 -0
- package/dist/{chunk-G25STLE7.js → chunk-SJFBXCII.js} +30 -3
- package/dist/chunk-SJFBXCII.js.map +1 -0
- package/dist/{chunk-A43I2AJ4.js → chunk-TM5XQY3L.js} +3 -3
- package/dist/{chunk-A43I2AJ4.js.map → chunk-TM5XQY3L.js.map} +1 -1
- package/dist/{chunk-KL65SSR7.js → chunk-TNADGCOX.js} +323 -152
- package/dist/chunk-TNADGCOX.js.map +1 -0
- package/dist/{chunk-V3X3DBZL.js → chunk-UXR7FBE3.js} +6 -6
- package/dist/{chunk-V3X3DBZL.js.map → chunk-UXR7FBE3.js.map} +1 -1
- package/dist/{chunk-IPICO2RV.js → chunk-VIWZ4QT7.js} +14 -3
- package/dist/chunk-VIWZ4QT7.js.map +1 -0
- package/dist/{chunk-IRCYOTRG.js → chunk-WGPS3NZQ.js} +240 -13
- package/dist/chunk-WGPS3NZQ.js.map +1 -0
- package/dist/{chunk-I6RBAIS3.js → chunk-XK5LKOBF.js} +4 -4
- package/dist/{chunk-I6RBAIS3.js.map → chunk-XK5LKOBF.js.map} +1 -1
- package/dist/cli.js +796 -359
- package/dist/cli.js.map +1 -1
- package/dist/ensure-map-TAVYMPEG.js +29 -0
- package/dist/{ensure-map-SMWHKOUY.js.map → ensure-map-TAVYMPEG.js.map} +1 -1
- package/dist/{graph-backend-I4I72J4W.js → graph-backend-WF4LGBGD.js} +5 -5
- package/dist/{graph-backend-I4I72J4W.js.map → graph-backend-WF4LGBGD.js.map} +1 -1
- package/dist/index.d.ts +143 -7
- package/dist/index.js +17 -16
- package/dist/index.js.map +1 -1
- package/dist/{interactive-TMQR6TXM.js → interactive-6PN237LX.js} +49 -32
- package/dist/interactive-6PN237LX.js.map +1 -0
- package/dist/load-T2FOJUPI.js +10 -0
- package/dist/{load-E3OTM7BS.js.map → load-T2FOJUPI.js.map} +1 -1
- package/dist/model-manager-GJ2YSTSK.js +1 -1
- package/dist/{run-outcome-QWLNBASF.js → run-outcome-AMIKAASL.js} +6 -6
- package/dist/{run-outcome-QWLNBASF.js.map → run-outcome-AMIKAASL.js.map} +1 -1
- package/dist/runtime-session-QAVOPSSH.js +20 -0
- package/dist/{runtime-session-UQ7UVAPL.js.map → runtime-session-QAVOPSSH.js.map} +1 -1
- package/dist/session-SCHQQTHN.js +15 -0
- package/dist/{session-MG6BJVAG.js.map → session-SCHQQTHN.js.map} +1 -1
- package/dist/session-store-F7NX7SZN.js +4 -0
- package/dist/{session-store-SQECEXUU.js.map → session-store-F7NX7SZN.js.map} +1 -1
- package/dist/{stream-json-GM44SP7L.js → stream-json-A6K2MONY.js} +48 -16
- package/dist/stream-json-A6K2MONY.js.map +1 -0
- package/dist/{vg-mcp-bridge-3WFC7LGE.js → vg-mcp-bridge-3TSFOL4V.js} +13 -11
- package/dist/vg-mcp-bridge-3TSFOL4V.js.map +1 -0
- package/dist/{vgd-ZUSBEVUL.js → vgd-B67JCNJP.js} +9 -9
- package/dist/vgd-B67JCNJP.js.map +1 -0
- package/package.json +1 -1
- package/dist/agent-4DAECASW.js +0 -22
- package/dist/baseline-4BDH4F2W.js +0 -9
- package/dist/chunk-76TDXGGF.js.map +0 -1
- package/dist/chunk-7G5S5KZN.js.map +0 -1
- package/dist/chunk-7PVCHLR2.js.map +0 -1
- package/dist/chunk-BNEHDLVZ.js.map +0 -1
- package/dist/chunk-G25STLE7.js.map +0 -1
- package/dist/chunk-IPICO2RV.js.map +0 -1
- package/dist/chunk-IRCYOTRG.js.map +0 -1
- package/dist/chunk-JLWI2JGA.js.map +0 -1
- package/dist/chunk-KL65SSR7.js.map +0 -1
- package/dist/chunk-MPP4S4OE.js.map +0 -1
- package/dist/chunk-SDG242R4.js.map +0 -1
- package/dist/chunk-TGDHOAXX.js +0 -6
- package/dist/chunk-WIDZ5IE7.js.map +0 -1
- package/dist/chunk-XEJJGDGX.js.map +0 -1
- package/dist/chunk-ZKNB4YH4.js +0 -102
- package/dist/chunk-ZKNB4YH4.js.map +0 -1
- package/dist/ensure-map-SMWHKOUY.js +0 -28
- package/dist/interactive-TMQR6TXM.js.map +0 -1
- package/dist/load-E3OTM7BS.js +0 -10
- package/dist/runtime-session-UQ7UVAPL.js +0 -20
- package/dist/session-MG6BJVAG.js +0 -13
- package/dist/session-store-SQECEXUU.js +0 -4
- package/dist/stream-json-GM44SP7L.js.map +0 -1
- package/dist/vg-mcp-bridge-3WFC7LGE.js.map +0 -1
- package/dist/vgd-ZUSBEVUL.js.map +0 -1
|
@@ -1,21 +1,43 @@
|
|
|
1
|
-
import { refreshIfStale } from './chunk-
|
|
2
|
-
import { TOOLS, renderToolResult, warmEmbedderInBackground, countTokens } from './chunk-
|
|
3
|
-
import { sanitizeClient, recordSaving, SAVINGS_TOOLS, PER_FILE_TOKENS } from './chunk-
|
|
4
|
-
import { loadGraphPreferIndex } from './chunk-
|
|
5
|
-
import { mapFileStat, renderHtml, renderReport } from './chunk-
|
|
6
|
-
import { VERSION } from './chunk-
|
|
7
|
-
import { parseGraph, slimGraphForExport, serializeGraph } from './chunk-
|
|
1
|
+
import { refreshIfStale } from './chunk-UXR7FBE3.js';
|
|
2
|
+
import { listedToolNames, budgetSuffix, TOOLS, renderToolResult, warmEmbedderInBackground, countTokens } from './chunk-M452MRWI.js';
|
|
3
|
+
import { sanitizeClient, recordSaving, SAVINGS_TOOLS, PER_FILE_TOKENS } from './chunk-K6Q6HTFD.js';
|
|
4
|
+
import { loadGraphPreferIndex } from './chunk-CPLG4GFB.js';
|
|
5
|
+
import { mapFileStat, renderHtml, renderReport } from './chunk-3Q3ZXJZP.js';
|
|
6
|
+
import { VERSION } from './chunk-7KNFG44U.js';
|
|
7
|
+
import { parseGraph, slimGraphForExport, serializeGraph } from './chunk-QMME6TB4.js';
|
|
8
8
|
import * as fs from 'fs';
|
|
9
9
|
import * as path from 'path';
|
|
10
10
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
11
11
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
12
12
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
13
13
|
|
|
14
|
+
var WATCH_SKIP_NAMES = /* @__PURE__ */ new Set([
|
|
15
|
+
".git",
|
|
16
|
+
"node_modules",
|
|
17
|
+
".vibgrate",
|
|
18
|
+
"dist",
|
|
19
|
+
"build",
|
|
20
|
+
"out",
|
|
21
|
+
"coverage",
|
|
22
|
+
".next",
|
|
23
|
+
"target",
|
|
24
|
+
"__pycache__",
|
|
25
|
+
".venv",
|
|
26
|
+
"venv"
|
|
27
|
+
]);
|
|
28
|
+
function isRelevantChange(filename) {
|
|
29
|
+
if (filename.split(path.sep).some((p) => WATCH_SKIP_NAMES.has(p))) return false;
|
|
30
|
+
if (filename.includes(`${path.sep}.vibgrate${path.sep}`) || filename.startsWith(".vibgrate")) return false;
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/mcp/server.ts
|
|
14
35
|
var PROBE_INTERVAL_MS = 2e3;
|
|
15
36
|
var MAX_PROBE_INTERVAL_MS = 3e4;
|
|
16
37
|
var PROBE_DUTY_FACTOR = 20;
|
|
17
38
|
var REFRESH_BUDGET_MS = 100;
|
|
18
39
|
var FAILURE_COOLDOWN_MS = 6e4;
|
|
40
|
+
var WATCH_DEBOUNCE_MS = 400;
|
|
19
41
|
var GraphSource = class {
|
|
20
42
|
constructor(graphPath, refresh = false, tuning = {}) {
|
|
21
43
|
this.graphPath = graphPath;
|
|
@@ -37,6 +59,16 @@ var GraphSource = class {
|
|
|
37
59
|
/** Self-tuned: grows with measured probe/rebuild cost so huge repos aren't penalized. */
|
|
38
60
|
probeIntervalMs = PROBE_INTERVAL_MS;
|
|
39
61
|
refreshImpl;
|
|
62
|
+
/**
|
|
63
|
+
* Files seen changing since the last COMMITTED refresh (watcher events,
|
|
64
|
+
* filename → last-seen ms). Entries are cleared only after a refresh that
|
|
65
|
+
* started at-or-after their last event completes with 'fresh'/'refreshed' —
|
|
66
|
+
* a change landing mid-refresh stays pending, so the staleness signal can
|
|
67
|
+
* be a false positive but never a false negative.
|
|
68
|
+
*/
|
|
69
|
+
pendingChanges = /* @__PURE__ */ new Map();
|
|
70
|
+
watcher = null;
|
|
71
|
+
watchTimer = null;
|
|
40
72
|
/** Current graph: auto-refreshed if the tree drifted, reloaded if the file changed. */
|
|
41
73
|
async get() {
|
|
42
74
|
if (this.refresh) await this.maybeRefresh();
|
|
@@ -58,8 +90,14 @@ var GraphSource = class {
|
|
|
58
90
|
const interval = this.tuning.probeIntervalMs ?? this.probeIntervalMs;
|
|
59
91
|
if (now < this.failedUntil || now - this.lastProbeAt < interval) return;
|
|
60
92
|
this.lastProbeAt = now;
|
|
93
|
+
const startedAt = now;
|
|
61
94
|
this.inflight = this.refreshImpl(this.root, { graphPath: this.graphPath }).then((r) => {
|
|
62
95
|
if (r.status === "error") this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;
|
|
96
|
+
if (r.status === "fresh" || r.status === "refreshed") {
|
|
97
|
+
for (const [file, seenAt] of this.pendingChanges) {
|
|
98
|
+
if (seenAt <= startedAt) this.pendingChanges.delete(file);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
63
101
|
const cost = r.status === "refreshed" && typeof r.ms === "number" ? Math.max(r.ms, Date.now() - now) : Date.now() - now;
|
|
64
102
|
this.probeIntervalMs = Math.min(
|
|
65
103
|
MAX_PROBE_INTERVAL_MS,
|
|
@@ -73,6 +111,64 @@ var GraphSource = class {
|
|
|
73
111
|
}
|
|
74
112
|
await Promise.race([this.inflight, sleep(this.tuning.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);
|
|
75
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Record a source change (watcher event, or a test). Arms the next probe to
|
|
116
|
+
* run immediately (bypassing the self-tuned interval — a real event is not a
|
|
117
|
+
* poll) and schedules a debounced background refresh so the rebuild happens
|
|
118
|
+
* BETWEEN tool calls instead of on the next call's 100 ms budget.
|
|
119
|
+
*/
|
|
120
|
+
notePendingChange(filename) {
|
|
121
|
+
this.pendingChanges.set(filename, Date.now());
|
|
122
|
+
this.lastProbeAt = 0;
|
|
123
|
+
this.failedUntil = 0;
|
|
124
|
+
if (!this.refresh) return;
|
|
125
|
+
if (this.watchTimer) clearTimeout(this.watchTimer);
|
|
126
|
+
this.watchTimer = setTimeout(() => {
|
|
127
|
+
this.watchTimer = null;
|
|
128
|
+
void this.maybeRefresh();
|
|
129
|
+
}, WATCH_DEBOUNCE_MS);
|
|
130
|
+
this.watchTimer.unref?.();
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Event-driven freshness (the serve-loop watcher): a recursive `fs.watch`
|
|
134
|
+
* on the workspace feeds `notePendingChange`, so a save triggers a rebuild
|
|
135
|
+
* in ~WATCH_DEBOUNCE_MS instead of waiting out the 2–30 s poll. The poll
|
|
136
|
+
* stays armed as the fallback — on filesystems where recursive watch fails
|
|
137
|
+
* (some containers/NFS) this returns false and behaviour is unchanged.
|
|
138
|
+
*/
|
|
139
|
+
startWatching() {
|
|
140
|
+
if (this.watcher) return true;
|
|
141
|
+
try {
|
|
142
|
+
this.watcher = fs.watch(this.root, { recursive: true }, (_event, filename) => {
|
|
143
|
+
if (!filename) return;
|
|
144
|
+
if (!isRelevantChange(filename)) return;
|
|
145
|
+
this.notePendingChange(filename);
|
|
146
|
+
});
|
|
147
|
+
this.watcher.unref?.();
|
|
148
|
+
return true;
|
|
149
|
+
} catch {
|
|
150
|
+
this.watcher = null;
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
stopWatching() {
|
|
155
|
+
this.watcher?.close();
|
|
156
|
+
this.watcher = null;
|
|
157
|
+
if (this.watchTimer) clearTimeout(this.watchTimer);
|
|
158
|
+
this.watchTimer = null;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* In-band staleness signal for tool responses: what has changed since the
|
|
162
|
+
* last committed refresh. Null when the map is current (the common case —
|
|
163
|
+
* responses carry zero overhead then).
|
|
164
|
+
*/
|
|
165
|
+
stalenessNote() {
|
|
166
|
+
const n = this.pendingChanges.size;
|
|
167
|
+
if (n === 0) return null;
|
|
168
|
+
const names = [...this.pendingChanges.keys()].sort().slice(0, 3);
|
|
169
|
+
const more = n > names.length ? `, +${n - names.length} more` : "";
|
|
170
|
+
return `map freshness: ${n} file(s) changed since the last rebuild (${names.join(", ")}${more}) \u2014 auto-refresh pending; symbol locations may have shifted`;
|
|
171
|
+
}
|
|
76
172
|
};
|
|
77
173
|
function createServer(source, opts = {}) {
|
|
78
174
|
const { savings = false, shareStats = false, local = false, dedup = false, stats } = opts;
|
|
@@ -89,14 +185,23 @@ function createServer(source, opts = {}) {
|
|
|
89
185
|
instructions: 'vg is a code map. Use search_symbols to find a known name or literal string fast \u2014 a multi-word/quoted phrase runs a complete literal sweep and reports totalTextMatches, so reach for it instead of grep even for plain-string "find every occurrence" lookups. Use orient/query_graph for meaning: symptoms, relationships, and what-breaks-if. Responses are concise by default; pass response_format:"detailed" only when a node proves load-bearing. Navigate as little as possible: one good search/query usually locates the code. As soon as you have the file and line, read that file and make the edit \u2014 do not call further graph tools unless the edit fails or the match was wrong. For how-do-I-use-this-library questions call resolve_library once, then library_docs with the returned targetId and a focused query: the docs are official and matched to the version THIS project has installed (drift-annotated) \u2014 prefer them over web search or training-data recall when they conflict. Skip them for language built-ins or APIs already shown in context. If two library_docs calls have not surfaced the section you need, read the package source under node_modules instead of searching again.'
|
|
90
186
|
}
|
|
91
187
|
);
|
|
92
|
-
server.setRequestHandler(ListToolsRequestSchema, async () =>
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
|
|
188
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
189
|
+
const listed = new Set(listedToolNames(opts.toolSurface));
|
|
190
|
+
let budget = "";
|
|
191
|
+
try {
|
|
192
|
+
const graph = await source.get();
|
|
193
|
+
budget = budgetSuffix(new Set(graph.nodes.map((n) => n.file)).size);
|
|
194
|
+
} catch {
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
tools: TOOLS.filter((t) => listed.has(t.name)).map((t) => ({
|
|
198
|
+
name: t.name,
|
|
199
|
+
description: t.name === "orient" && budget ? `${t.description}${budget}` : t.description,
|
|
200
|
+
inputSchema: t.inputSchema,
|
|
201
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
202
|
+
}))
|
|
203
|
+
};
|
|
204
|
+
});
|
|
100
205
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
101
206
|
const tool = TOOLS.find((t) => t.name === request.params.name);
|
|
102
207
|
if (!tool) {
|
|
@@ -113,11 +218,14 @@ function createServer(source, opts = {}) {
|
|
|
113
218
|
const startedAt = Date.now();
|
|
114
219
|
try {
|
|
115
220
|
const args = request.params.arguments ?? {};
|
|
116
|
-
const result = await tool.handler(graph, args, { root, local, dedup, seen });
|
|
221
|
+
const result = await tool.handler(graph, args, { root, local, dedup, seen, graphPath: source.graphPath });
|
|
117
222
|
const ms = Date.now() - startedAt;
|
|
118
223
|
stats?.record({ ...measureCall(tool.name, result), client: sanitizeClient(detectClient(server)), ms });
|
|
119
224
|
if (record) recordUsage(root, tool.name, result, detectClient(server), ms);
|
|
120
|
-
|
|
225
|
+
const rendered = renderToolResult(result);
|
|
226
|
+
const staleness = source.stalenessNote();
|
|
227
|
+
if (staleness) rendered.content = [...rendered.content ?? [], { type: "text", text: `[${staleness}]` }];
|
|
228
|
+
return rendered;
|
|
121
229
|
} catch (err) {
|
|
122
230
|
stats?.record({
|
|
123
231
|
tool: tool.name,
|
|
@@ -134,6 +242,7 @@ function createServer(source, opts = {}) {
|
|
|
134
242
|
}
|
|
135
243
|
async function serveStdio(graphPath, opts = {}) {
|
|
136
244
|
const source = new GraphSource(graphPath, opts.refresh !== false, { root: opts.root });
|
|
245
|
+
if (opts.refresh !== false && opts.watch !== false) source.startWatching();
|
|
137
246
|
const server = createServer(source, opts);
|
|
138
247
|
warmEmbedderInBackground(opts.local);
|
|
139
248
|
await server.connect(new StdioServerTransport());
|
|
@@ -421,6 +530,6 @@ function spdx(ctx) {
|
|
|
421
530
|
return JSON.stringify(doc, null, 2) + "\n";
|
|
422
531
|
}
|
|
423
532
|
|
|
424
|
-
export { GraphSource, createServer, exportGraph, formatForExt, serveStdio };
|
|
425
|
-
//# sourceMappingURL=chunk-
|
|
426
|
-
//# sourceMappingURL=chunk-
|
|
533
|
+
export { GraphSource, createServer, exportGraph, formatForExt, isRelevantChange, serveStdio };
|
|
534
|
+
//# sourceMappingURL=chunk-NSWEJPLV.js.map
|
|
535
|
+
//# sourceMappingURL=chunk-NSWEJPLV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engine/watch-filter.ts","../src/mcp/server.ts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jG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC","file":"chunk-NSWEJPLV.js","sourcesContent":["import * as path from 'node:path';\n\n/**\n * Shared change-event filter for the two file watchers (`vg watch` and the\n * serve-loop watcher in mcp/server.ts): which filesystem events are real\n * source changes, and which are dependency/artifact/VCS noise that must never\n * trigger a rebuild — including vg's own artifacts, or every build would\n * re-trigger itself.\n */\nexport const WATCH_SKIP_NAMES = new Set([\n '.git',\n 'node_modules',\n '.vibgrate',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.next',\n 'target',\n '__pycache__',\n '.venv',\n 'venv',\n]);\n\n/** True when a watch event's filename is a change worth rebuilding for. */\nexport function isRelevantChange(filename: string): boolean {\n if (filename.split(path.sep).some((p) => WATCH_SKIP_NAMES.has(p))) return false;\n if (filename.includes(`${path.sep}.vibgrate${path.sep}`) || filename.startsWith('.vibgrate')) return false;\n return true;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { parseGraph } from '../engine/serialize.js';\nimport { mapFileStat } from '../engine/snapshot.js';\nimport { loadGraphPreferIndex } from '../engine/index-db.js';\nimport { refreshIfStale } from '../engine/refresh.js';\nimport { TOOLS, budgetSuffix, listedToolNames, warmEmbedderInBackground, type ToolSurface } from './tools.js';\nimport { isRelevantChange } from '../engine/watch-filter.js';\nimport { renderToolResult } from './response.js';\nimport { recordSaving, sanitizeClient, PER_FILE_TOKENS, SAVINGS_TOOLS, type Outcome } from '../engine/savings.js';\nimport type { SessionStats } from './serve-stats.js';\nimport { countTokens } from '../engine/tokens.js';\nimport { VERSION } from '../version.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * The local `vg serve` MCP server. Self-contained and offline. Freshness is\n * two-layered, with no filesystem watcher (freshness only matters at the\n * moment of a query, so we check on read instead of watching):\n *\n * 1. **Hot reload** — `graph.json` is re-read whenever its mtime changes, so a\n * rebuild from ANY source (a foreground `vg`, another serve process, CI)\n * is picked up on the next tool call.\n * 2. **Auto-refresh** (default on) — each tool call runs a debounced, stat-only\n * freshness probe against the last build's snapshot; if the working tree\n * drifted, an incremental rebuild runs in-process (cross-process locked,\n * single-flight). The call waits only a **micro-budget** so a warm probe can\n * land without stalling MCP tools — otherwise it answers from the current\n * map while the rebuild finishes for a later call (hot-reload picks it up).\n *\n * Every tool remains read-only and auto-approvable; the refresh only rewrites\n * vg's own artifacts under `.vibgrate/`, never user code.\n */\n\n/** Min gap between freshness probes — bounds stat-walk cost under bursty tool calls. */\nconst PROBE_INTERVAL_MS = 2000;\n/** Ceiling for the self-tuned probe interval on very large repos. */\nconst MAX_PROBE_INTERVAL_MS = 30_000;\n/** Probe/rebuild may consume at most ~1/PROBE_DUTY_FACTOR of serve wall-time (20 → ≤5%). */\nconst PROBE_DUTY_FACTOR = 20;\n/**\n * How long a tool call waits for an in-flight refresh before answering from\n * the current map. Kept deliberately small: MCP tool latency is sub-10ms on\n * warm maps, and a multi-second budget (the previous 5s ceiling matched\n * `git rev-parse`'s spawn timeout) turned every sequential tool call during a\n * large-repo rebuild into a multi-second stall — measured as TypeScript p50\n * ~5.2s on the release benchmark for the `vg-cli-public` corpus entry.\n * Warm probes still finish inside this window; heavy rebuilds never should.\n */\nexport const REFRESH_BUDGET_MS = 100;\n/** After a refresh failure (e.g. read-only checkout), don't retry for this long. */\nconst FAILURE_COOLDOWN_MS = 60_000;\n/** Settle time between a watcher event and the background refresh it triggers. */\nconst WATCH_DEBOUNCE_MS = 400;\n\nexport type RefreshImpl = typeof refreshIfStale;\n\nexport interface GraphSourceTuning {\n probeIntervalMs?: number;\n refreshBudgetMs?: number;\n /**\n * Workspace root for freshness probes. Prefer passing this explicitly —\n * deriving it from `graphPath` via `dirname` twice only works for the legacy\n * `root/.vibgrate/graph.json` layout, not the global branch-keyed store.\n */\n root?: string;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n}\n\nexport interface ServeOptions {\n /** Record local, counts-only usage savings (opt-in). */\n savings?: boolean;\n /**\n * Periodically upload the counts-only ledger to Vibgrate (opt-in; off by\n * default). Implies recording. The upload itself is driven by the serve\n * command (see commands/serve.ts + engine/stats-share.ts); here it just also\n * turns recording on so there's something to send.\n */\n shareStats?: boolean;\n /** Air-gapped mode (no model downloads). */\n local?: boolean;\n /** Collapse repeat heavy relation lists within a session (opt-in). */\n dedup?: boolean;\n /** Auto-refresh the map when the working tree drifts (default true). */\n refresh?: boolean;\n /**\n * Event-driven refresh: recursive fs.watch on the workspace so a save\n * rebuilds in ~400 ms instead of waiting out the freshness poll (default\n * true when refresh is on; `--no-watch` opts out). Where recursive watch is\n * unavailable the poll silently remains the only mechanism.\n */\n watch?: boolean;\n /**\n * Workspace root (project directory). When set, freshness probes and tools\n * use this instead of inferring root from the graph path.\n */\n root?: string;\n /**\n * In-memory session stats behind the live `vg serve` status display. Always\n * safe to pass: nothing recorded here is persisted or uploaded — it dies with\n * the process (the opt-in ledger above is a separate concern).\n */\n stats?: SessionStats;\n /**\n * Listing surface (`--surface hot` / `--tools a,b`). Filters ONLY what\n * `tools/list` advertises; every tool stays callable so behaviour is\n * byte-identical across surfaces. See `listedToolNames` in ./tools.ts.\n */\n toolSurface?: ToolSurface;\n}\n\nexport class GraphSource {\n private cachedMtimeMs = -1;\n private cached: VgGraph | null = null;\n /** Project root used for freshness probes and rebuilds. */\n readonly root: string;\n private lastProbeAt = 0;\n private failedUntil = 0;\n private inflight: Promise<void> | null = null;\n /** Self-tuned: grows with measured probe/rebuild cost so huge repos aren't penalized. */\n private probeIntervalMs = PROBE_INTERVAL_MS;\n private readonly refreshImpl: RefreshImpl;\n /**\n * Files seen changing since the last COMMITTED refresh (watcher events,\n * filename → last-seen ms). Entries are cleared only after a refresh that\n * started at-or-after their last event completes with 'fresh'/'refreshed' —\n * a change landing mid-refresh stays pending, so the staleness signal can\n * be a false positive but never a false negative.\n */\n private readonly pendingChanges = new Map<string, number>();\n private watcher: fs.FSWatcher | null = null;\n private watchTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n readonly graphPath: string,\n private readonly refresh = false,\n /** Timing / root overrides (production passes `root`; tests may pass more). */\n private readonly tuning: GraphSourceTuning = {},\n ) {\n // Prefer an explicit root. Fallback assumes legacy `root/.vibgrate/graph.json`\n // (dirname twice); wrong for the global store — callers should pass `root`.\n this.root = tuning.root ?? path.dirname(path.dirname(graphPath));\n this.refreshImpl = tuning.refreshImpl ?? refreshIfStale;\n }\n\n /** Current graph: auto-refreshed if the tree drifted, reloaded if the file changed. */\n async get(): Promise<VgGraph> {\n if (this.refresh) await this.maybeRefresh();\n // JSON when present, else the standalone snapshot (global-store mode);\n // throws if neither exists → surfaced as tool error.\n const stat = mapFileStat(this.graphPath);\n if (stat.mtimeMs !== this.cachedMtimeMs || !this.cached) {\n // Prefer SQLite reconstruct when corpusHash matches (scale past JSON parse).\n const preferred = loadGraphPreferIndex(this.root, this.graphPath);\n this.cached = preferred\n ? preferred.graph\n : parseGraph(fs.readFileSync(this.graphPath, 'utf8'));\n this.cachedMtimeMs = stat.mtimeMs;\n }\n return this.cached;\n }\n\n /**\n * Debounced, single-flight refresh. Never throws — a refresh problem must\n * degrade to \"answer from the current map\", not break the tool call.\n */\n private async maybeRefresh(): Promise<void> {\n const now = Date.now();\n if (!this.inflight) {\n const interval = this.tuning.probeIntervalMs ?? this.probeIntervalMs;\n if (now < this.failedUntil || now - this.lastProbeAt < interval) return;\n this.lastProbeAt = now;\n const startedAt = now;\n this.inflight = this.refreshImpl(this.root, { graphPath: this.graphPath })\n .then((r) => {\n if (r.status === 'error') this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n // A COMMITTED outcome (map verified fresh, or rebuilt) clears the\n // pending set — but only entries whose last event predates the\n // refresh start. 'locked'/'error'/'no-snapshot' clear nothing:\n // the map may still be behind those changes.\n if (r.status === 'fresh' || r.status === 'refreshed') {\n for (const [file, seenAt] of this.pendingChanges) {\n if (seenAt <= startedAt) this.pendingChanges.delete(file);\n }\n }\n // Self-tune off the full wall cost of *every* outcome — including a\n // multi-second incremental rebuild. Previously only probe-only\n // outcomes (fresh/no-snapshot/locked) backed off, so a 20s rebuild\n // of a large repo re-armed after the 2s floor and every sequential\n // tool call blocked on the refresh budget for the whole suite.\n const cost =\n r.status === 'refreshed' && typeof r.ms === 'number' ? Math.max(r.ms, Date.now() - now) : Date.now() - now;\n this.probeIntervalMs = Math.min(\n MAX_PROBE_INTERVAL_MS,\n Math.max(PROBE_INTERVAL_MS, cost * PROBE_DUTY_FACTOR),\n );\n })\n .catch(() => {\n this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n })\n .finally(() => {\n this.inflight = null;\n });\n }\n await Promise.race([this.inflight, sleep(this.tuning.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);\n }\n\n /**\n * Record a source change (watcher event, or a test). Arms the next probe to\n * run immediately (bypassing the self-tuned interval — a real event is not a\n * poll) and schedules a debounced background refresh so the rebuild happens\n * BETWEEN tool calls instead of on the next call's 100 ms budget.\n */\n notePendingChange(filename: string): void {\n this.pendingChanges.set(filename, Date.now());\n this.lastProbeAt = 0;\n this.failedUntil = 0;\n if (!this.refresh) return;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = setTimeout(() => {\n this.watchTimer = null;\n void this.maybeRefresh();\n }, WATCH_DEBOUNCE_MS);\n this.watchTimer.unref?.();\n }\n\n /**\n * Event-driven freshness (the serve-loop watcher): a recursive `fs.watch`\n * on the workspace feeds `notePendingChange`, so a save triggers a rebuild\n * in ~WATCH_DEBOUNCE_MS instead of waiting out the 2–30 s poll. The poll\n * stays armed as the fallback — on filesystems where recursive watch fails\n * (some containers/NFS) this returns false and behaviour is unchanged.\n */\n startWatching(): boolean {\n if (this.watcher) return true;\n try {\n this.watcher = fs.watch(this.root, { recursive: true }, (_event, filename) => {\n if (!filename) return;\n if (!isRelevantChange(filename)) return;\n this.notePendingChange(filename);\n });\n this.watcher.unref?.();\n return true;\n } catch {\n this.watcher = null;\n return false;\n }\n }\n\n stopWatching(): void {\n this.watcher?.close();\n this.watcher = null;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = null;\n }\n\n /**\n * In-band staleness signal for tool responses: what has changed since the\n * last committed refresh. Null when the map is current (the common case —\n * responses carry zero overhead then).\n */\n stalenessNote(): string | null {\n const n = this.pendingChanges.size;\n if (n === 0) return null;\n const names = [...this.pendingChanges.keys()].sort().slice(0, 3);\n const more = n > names.length ? `, +${n - names.length} more` : '';\n return `map freshness: ${n} file(s) changed since the last rebuild (${names.join(', ')}${more}) — auto-refresh pending; symbol locations may have shifted`;\n }\n}\n\nexport function createServer(source: GraphSource, opts: ServeOptions = {}): Server {\n const { savings = false, shareStats = false, local = false, dedup = false, stats } = opts;\n // Recording feeds both the local `vg savings` report and the opt-in upload, so\n // enabling either turns it on. Absent both, `vg serve` records nothing.\n const record = savings || shareStats;\n // Prefer GraphSource's explicit root (set by serve from the project cwd).\n const root = opts.root ?? source.root;\n // Per-session memory of node ids whose full detail was already returned — the\n // basis for opt-in cross-call dedup (`--dedup`). Scoped to this server\n // instance so it never leaks across sessions. Node ids are content-addressed\n // (blake3 of content), so an edited node gets a new id and is never falsely\n // treated as already-seen — dedup is stale-safe by construction.\n const seen = new Set<string>();\n const server = new Server(\n { name: 'vg', version: VERSION },\n {\n capabilities: { tools: {} },\n // Routing guidance once at the server level (hosts that surface\n // `instructions` get it at zero per-step schema cost): the flashlight\n // vs the map.\n instructions:\n 'vg is a code map. Use search_symbols to find a known name or literal string fast — ' +\n 'a multi-word/quoted phrase runs a complete literal sweep and reports totalTextMatches, ' +\n 'so reach for it instead of grep even for plain-string \"find every occurrence\" lookups. ' +\n 'Use orient/query_graph for meaning: symptoms, relationships, and what-breaks-if. ' +\n 'Responses are concise by default; pass response_format:\"detailed\" only when a node proves load-bearing. ' +\n // Stop-discipline: the failure mode on a focused task is over-navigation\n // — one more query, one more get_node — which re-bills the whole context\n // every step. One good navigation call usually locates the code.\n 'Navigate as little as possible: one good search/query usually locates the code. ' +\n 'As soon as you have the file and line, read that file and make the edit — ' +\n 'do not call further graph tools unless the edit fails or the match was wrong. ' +\n // Library docs: position against web search (version-correct beats\n // SEO results), and give a stopping rule so a thin doc doesn't turn\n // into an open-ended search loop.\n 'For how-do-I-use-this-library questions call resolve_library once, then library_docs ' +\n 'with the returned targetId and a focused query: the docs are official and matched to ' +\n 'the version THIS project has installed (drift-annotated) — prefer them over web search ' +\n 'or training-data recall when they conflict. Skip them for language built-ins or APIs ' +\n 'already shown in context. If two library_docs calls have not surfaced the section you ' +\n 'need, read the package source under node_modules instead of searching again.',\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const listed = new Set(listedToolNames(opts.toolSurface));\n // Repo-size call budget on orient's listed description: the stop-discipline\n // where the model decides, priced once per list, not per step. Best-effort —\n // when no map is loadable yet the description ships without the line.\n let budget = '';\n try {\n const graph = await source.get();\n budget = budgetSuffix(new Set(graph.nodes.map((n) => n.file)).size);\n } catch {\n /* no map yet — plain description */\n }\n return {\n tools: TOOLS.filter((t) => listed.has(t.name)).map((t) => ({\n name: t.name,\n description: t.name === 'orient' && budget ? `${t.description}${budget}` : t.description,\n inputSchema: t.inputSchema,\n annotations: { readOnlyHint: true, openWorldHint: false },\n })),\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = TOOLS.find((t) => t.name === request.params.name);\n if (!tool) {\n return errorResult(`unknown tool \"${request.params.name}\"`);\n }\n let graph: VgGraph;\n try {\n graph = await source.get();\n } catch {\n return errorResult(\n 'no code map found. Run `vg` in the project to build .vibgrate/graph.json, then retry.',\n );\n }\n const startedAt = Date.now();\n try {\n const args = (request.params.arguments ?? {}) as Record<string, unknown>;\n const result = await tool.handler(graph, args, { root, local, dedup, seen, graphPath: source.graphPath });\n const ms = Date.now() - startedAt;\n // Live, in-memory session stats for the serve status display — always on\n // when a serve process passed them (nothing leaves the process).\n stats?.record({ ...measureCall(tool.name, result), client: sanitizeClient(detectClient(server)), ms });\n // Opt-in, counts-only usage ledger: one entry per navigation call, with its\n // outcome, the grep-baseline token counts, and — so `vg savings` can show\n // the command-vs-MCP split and which AI is calling — the source (`mcp`) and\n // the client detected from the initialize handshake.\n if (record) recordUsage(root, tool.name, result, detectClient(server), ms);\n // Compact → clamp to the token ceiling → compact-serialise. See ./response.ts.\n const rendered = renderToolResult(result);\n // In-band staleness (serve-loop watcher): when the working tree has\n // drifted past the served map, say so ON the response — the agent is the\n // one acting on possibly-moved symbols, and stderr never reaches it.\n // Zero overhead when the map is current (the overwhelmingly common case).\n const staleness = source.stalenessNote();\n if (staleness) rendered.content = [...(rendered.content ?? []), { type: 'text', text: `[${staleness}]` }];\n return rendered;\n } catch (err) {\n // A failed call still counts in the live display — as a miss, so the\n // operator sees trouble instead of a silently frozen dashboard.\n stats?.record({\n tool: tool.name,\n client: sanitizeClient(detectClient(server)),\n outcome: 'miss',\n ms: Date.now() - startedAt,\n vgTokens: 0,\n baselineTokens: 0,\n });\n return errorResult(`tool \"${tool.name}\" failed: ${(err as Error).message}`);\n }\n });\n\n return server;\n}\n\nexport async function serveStdio(graphPath: string, opts: ServeOptions = {}): Promise<void> {\n const source = new GraphSource(graphPath, opts.refresh !== false, { root: opts.root });\n if (opts.refresh !== false && opts.watch !== false) source.startWatching();\n const server = createServer(source, opts);\n // Start the semantic-model warm-up as soon as the server boots, so the first\n // orient/query_graph doesn't pay a cold download. Non-blocking: navigation\n // answers lexically until the model is ready, then upgrades to semantic.\n warmEmbedderInBackground(opts.local);\n await server.connect(new StdioServerTransport());\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.(); // never keep the server process alive just for the budget timer\n });\n}\n\n/**\n * Append a counts-only usage entry for a navigation call: which tool, how it\n * resolved (complete/partial/miss), and — for the grep-baseline tools — the\n * tokens vg spent vs the grep/read baseline it replaced.\n *\n * `vgTokens` is the size of the payload vg ACTUALLY returned — the rendered text\n * block the model receives and re-pays on every subsequent turn — measured with\n * the same token counter the budget uses. It is deliberately NOT read from a\n * `tokensEstimate` field: only query_graph's rarely-used *detailed* mode ever\n * set that (get_node never did), so the old code recorded nothing under normal\n * concise usage and `vg savings` always reported \"recording is off\".\n */\nexport function recordUsage(root: string, tool: string, result: unknown, client?: string, ms?: number): void {\n recordSaving(\n root,\n { ...measureCall(tool, result), source: 'mcp', client: sanitizeClient(client), ...(ms !== undefined ? { ms } : {}) },\n Date.now(),\n );\n}\n\n/**\n * Measure one tool call for the ledger and the live session stats: its outcome\n * plus — for the grep-baseline tools only — the context tokens vg returned and\n * the baseline they replaced (other tools report zeros, meaning \"no baseline\").\n */\nfunction measureCall(tool: string, result: unknown): { tool: string; outcome: Outcome; vgTokens: number; baselineTokens: number } {\n const outcome = classifyOutcome(result);\n let vgTokens = 0;\n let baselineTokens = 0;\n if (SAVINGS_TOOLS.has(tool) && result && typeof result === 'object') {\n vgTokens = countTokens(renderedText(renderToolResult(result)));\n // Grep/read baseline: ~PER_FILE_TOKENS per distinct file the answer points\n // at — the files a grep/read agent would have had to open to learn the same\n // thing. query_graph surfaces them as `matches[].file`; get_node as its own\n // `file` plus the files of the callers/callees it returned in one call.\n baselineTokens = referencedFiles(result).size * PER_FILE_TOKENS;\n }\n return { tool, outcome, vgTokens, baselineTokens };\n}\n\n/**\n * The coarse client label from the MCP `initialize` handshake, if the host sent\n * `clientInfo`. Read defensively — `getClientVersion()` exists on the SDK Server\n * once initialized, but we never want telemetry bookkeeping to throw. Returns\n * undefined when unknown (then sanitized to `'unknown'`).\n */\nfunction detectClient(server: Server): string | undefined {\n try {\n const info = (server as { getClientVersion?: () => { name?: string } | undefined }).getClientVersion?.();\n return typeof info?.name === 'string' ? info.name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bucket a tool result into complete / partial / miss. A `miss` is an answer\n * that found nothing (no match, not-found, not-connected, or an empty listing);\n * a `partial` found results but capped or paginated some of them; everything\n * else is `complete`. Note that a legitimately empty `affected`/`covers` (e.g.\n * \"nothing depends on this\") is a successful answer, not a miss — only the\n * primary discovery signals below mark a miss.\n */\nfunction classifyOutcome(result: unknown): Outcome {\n if (Array.isArray(result)) return result.length === 0 ? 'miss' : 'complete';\n if (!result || typeof result !== 'object') return 'miss';\n const r = result as Record<string, unknown>;\n if (typeof r.error === 'string' && r.error) return 'miss'; // not_found / ambiguous / unresolved\n if (r.connected === false) return 'miss'; // find_path\n if (Array.isArray(r.matches) && r.matches.length === 0) return 'miss'; // query_graph / search_symbols\n return isPartial(r) ? 'partial' : 'complete';\n}\n\n/** True when a hit left results on the table: paginated, or a capped relation list. */\nfunction isPartial(r: Record<string, unknown>): boolean {\n if (r.moreAvailable === true) return true;\n if (r._truncated && typeof r._truncated === 'object') return true;\n // A `<name>Total` greater than the length of its sibling `<name>` array means\n // the array was capped (e.g. get_node's callsTotal vs the shown calls).\n for (const [key, value] of Object.entries(r)) {\n if (typeof value !== 'number' || !key.endsWith('Total')) continue;\n const base = key.slice(0, -'Total'.length);\n const shown = Array.isArray(r[base]) ? (r[base] as unknown[]).length : 0;\n if (value > shown) return true;\n }\n return false;\n}\n\n/** The text block of a rendered tool result — what the model is billed for. */\nfunction renderedText(rendered: CallToolResult): string {\n const block = rendered.content?.find((b) => b.type === 'text');\n return block && 'text' in block && typeof block.text === 'string' ? block.text : '';\n}\n\n/** Distinct files a navigation result points at (its grep/read baseline set). */\nfunction referencedFiles(result: unknown): Set<string> {\n const r = result as { file?: unknown; matches?: unknown; calls?: unknown; calledBy?: unknown };\n const files = new Set<string>();\n if (typeof r.file === 'string' && r.file) files.add(r.file);\n for (const m of asArray(r.matches)) {\n const f = (m as { file?: unknown }).file;\n if (typeof f === 'string' && f) files.add(f);\n }\n // get_node's calls/calledBy are qualified names of the form `path:symbol`; the\n // path prefix is the file a grep/read agent would open to inspect that edge.\n for (const name of [...asArray(r.calls), ...asArray(r.calledBy)]) {\n if (typeof name !== 'string') continue;\n const i = name.indexOf(':');\n if (i > 0) files.add(name.slice(0, i));\n }\n return files;\n}\n\nfunction asArray(v: unknown): unknown[] {\n return Array.isArray(v) ? v : [];\n}\n\nfunction errorResult(message: string) {\n return { content: [{ type: 'text', text: message }], isError: true };\n}\n","import { serializeGraph, slimGraphForExport } from './serialize.js';\nimport { renderReport } from './report.js';\nimport { renderHtml } from './html.js';\nimport type { DepRecord } from './drift.js';\nimport type { LocalModel } from './models.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Above this node count, JSON export defaults to compact (no pretty-print). */\nexport const COMPACT_JSON_NODES = 5_000;\n\n/**\n * Deterministic exporters (VG-CLI-SPEC §4.2). One `vg export <file>` verb, format\n * inferred from the extension. Live graph-DB push is deliberately out (a file\n * import covers the same need offline). CycloneDX/SPDX power the SBOM/AI-BOM seam\n * (VG-LOCAL-MODELS §9.4).\n */\n\nexport type ExportFormat =\n | 'json'\n | 'ndjson'\n | 'graphml'\n | 'dot'\n | 'cypher'\n | 'sql'\n | 'md'\n | 'html'\n | 'cyclonedx'\n | 'spdx';\n\nexport function formatForExt(ext: string): ExportFormat | null {\n switch (ext.toLowerCase()) {\n case '.json':\n return 'json';\n case '.ndjson':\n return 'ndjson';\n case '.graphml':\n return 'graphml';\n case '.dot':\n case '.gv':\n return 'dot';\n case '.cypher':\n return 'cypher';\n case '.sql':\n return 'sql';\n case '.md':\n return 'md';\n case '.html':\n return 'html';\n default:\n return null;\n }\n}\n\nexport interface ExportContext {\n graph: VgGraph;\n deps?: DepRecord[];\n models?: LocalModel[];\n generatedAt: string;\n /** Force compact JSON (no indent). Default: auto when nodes > COMPACT_JSON_NODES. */\n compact?: boolean;\n /** Drop area members + grounding for smaller artifacts. */\n slim?: boolean;\n}\n\nexport function exportGraph(format: ExportFormat, ctx: ExportContext): string {\n const graph = ctx.slim ? slimGraphForExport(ctx.graph) : ctx.graph;\n const compact =\n ctx.compact === true ||\n (ctx.compact !== false && format === 'json' && graph.meta.counts.nodes > COMPACT_JSON_NODES);\n\n switch (format) {\n case 'json':\n return serializeGraph(graph, { compact });\n case 'md':\n return renderReport(graph);\n case 'html':\n return renderHtml(graph);\n case 'ndjson':\n return ndjson(graph);\n case 'graphml':\n return graphml(graph);\n case 'dot':\n return dot(graph);\n case 'cypher':\n return cypher(graph);\n case 'sql':\n return sql({ ...ctx, graph });\n case 'cyclonedx':\n return cyclonedx({ ...ctx, graph });\n case 'spdx':\n return spdx({ ...ctx, graph });\n }\n}\n\nfunction ndjson(graph: VgGraph): string {\n // Facts stream if present, else the node stream — one JSON object per line.\n const rows = graph.facts && graph.facts.length ? graph.facts : graph.nodes;\n return rows.map((r) => JSON.stringify(r)).join('\\n') + '\\n';\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nfunction graphml(graph: VgGraph): string {\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push('<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">');\n lines.push(' <key id=\"name\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>');\n lines.push(' <key id=\"kind\" for=\"node\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file\" for=\"node\" attr.name=\"file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"ekind\" for=\"edge\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <graph edgedefault=\"directed\">');\n for (const n of graph.nodes) {\n lines.push(` <node id=\"${esc(n.id)}\"><data key=\"name\">${esc(n.qualifiedName)}</data><data key=\"kind\">${esc(n.kind)}</data><data key=\"file\">${esc(n.file)}</data></node>`);\n }\n for (const e of graph.edges) {\n lines.push(` <edge source=\"${esc(e.src)}\" target=\"${esc(e.dst)}\"><data key=\"ekind\">${esc(e.kind)}</data></edge>`);\n }\n lines.push(' </graph>');\n lines.push('</graphml>');\n return lines.join('\\n') + '\\n';\n}\n\nfunction dot(graph: VgGraph): string {\n const lines: string[] = ['digraph vg {'];\n for (const n of graph.nodes) lines.push(` \"${n.id}\" [label=\"${dotEsc(n.qualifiedName)}\"];`);\n for (const e of graph.edges) lines.push(` \"${e.src}\" -> \"${e.dst}\" [label=\"${e.kind}\"];`);\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\nfunction dotEsc(s: string): string {\n return s.replace(/\"/g, '\\\\\"');\n}\n\nfunction cypher(graph: VgGraph): string {\n const lines: string[] = [];\n for (const n of graph.nodes) {\n lines.push(\n `CREATE (:\\`${cypherLabel(n.kind)}\\` {id:${q(n.id)}, name:${q(n.qualifiedName)}, file:${q(n.file)}});`,\n );\n }\n for (const e of graph.edges) {\n lines.push(\n `MATCH (a {id:${q(e.src)}}),(b {id:${q(e.dst)}}) CREATE (a)-[:\\`${cypherLabel(e.kind)}\\`]->(b);`,\n );\n }\n return lines.join('\\n') + '\\n';\n}\nfunction cypherLabel(s: string): string {\n return s.replace(/[^A-Za-z0-9_]/g, '_');\n}\nfunction q(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Portable SQL fact-DB (VG-CLI-SPEC §4.2, agent-consumption). Emits deterministic\n * DDL + INSERT text — NOT a native driver — that loads identically into BOTH\n * sqlite3 and duckdb (`sqlite3 map.db < map.sql` / `duckdb map.db < map.sql`).\n * Text keeps the CLI dependency-free, offline, and byte-diffable; an identical\n * graph yields identical bytes. An agent can then run e.g.\n * SELECT src, dst FROM edges WHERE epistemic = 'observed' AND confidence >= 0.9;\n * Determinism: single transaction, `CREATE TABLE IF NOT EXISTS`, rows emitted in\n * the graph's own (already-sorted) array order, single quotes doubled, NULL for\n * absent optionals, booleans as 0/1, and no timestamp but the graph's generatedAt.\n */\nfunction sql(ctx: ExportContext): string {\n const graph = ctx.graph;\n const lines: string[] = [];\n lines.push('BEGIN;');\n\n // meta — provenance / toolchain fingerprint (key/value; agent can read the corpus hash).\n lines.push('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);');\n const meta: [string, string | null][] = [\n ['schemaVersion', graph.schemaVersion],\n ['generatedAt', ctx.generatedAt],\n ['corpusHash', graph.provenance.corpusHash],\n ['tool', graph.provenance.tool],\n ['toolVersion', graph.provenance.version],\n ['resolver', graph.provenance.resolver.join(',')],\n ['fingerprint', graph.provenance.toolchain?.fingerprint ?? null],\n ];\n for (const [k, v] of meta) lines.push(`INSERT INTO meta VALUES (${sqlStr(k)}, ${sqlStr(v)});`);\n\n // nodes\n lines.push(\n 'CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY, kind TEXT, name TEXT, qualified_name TEXT, file TEXT, span_start INTEGER, span_end INTEGER, lang TEXT, visibility TEXT, signature TEXT, importance REAL, area INTEGER, is_hub INTEGER, tested INTEGER, coverage REAL);',\n );\n for (const n of graph.nodes) {\n lines.push(\n `INSERT INTO nodes VALUES (${sqlStr(n.id)}, ${sqlStr(n.kind)}, ${sqlStr(n.name)}, ${sqlStr(n.qualifiedName)}, ${sqlStr(n.file)}, ${sqlNum(n.span.start)}, ${sqlNum(n.span.end)}, ${sqlStr(n.lang)}, ${sqlStr(n.visibility)}, ${sqlStr(n.signature)}, ${sqlNum(n.importance)}, ${sqlNum(n.area)}, ${sqlBool(n.isHub)}, ${sqlBool(n.tested)}, ${sqlNum(n.coverage)});`,\n );\n }\n\n // edges — the epistemic column is the point: SELECT ... WHERE epistemic='observed'.\n lines.push(\n 'CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY, kind TEXT, src TEXT, dst TEXT, resolution TEXT, confidence REAL, epistemic TEXT, surprise REAL, \"count\" INTEGER);',\n );\n for (const e of graph.edges) {\n lines.push(\n `INSERT INTO edges VALUES (${sqlStr(e.id)}, ${sqlStr(e.kind)}, ${sqlStr(e.src)}, ${sqlStr(e.dst)}, ${sqlStr(e.resolution)}, ${sqlNum(e.confidence)}, ${sqlStr(e.epistemic)}, ${sqlNum(e.surprise)}, ${sqlNum(e.count)});`,\n );\n }\n\n // areas (+ members)\n lines.push('CREATE TABLE IF NOT EXISTS areas (id INTEGER PRIMARY KEY, label TEXT, size INTEGER, cohesion REAL, external_edges INTEGER);');\n lines.push('CREATE TABLE IF NOT EXISTS area_members (area_id INTEGER, node_id TEXT);');\n for (const a of graph.areas) {\n lines.push(`INSERT INTO areas VALUES (${sqlNum(a.id)}, ${sqlStr(a.label)}, ${sqlNum(a.size)}, ${sqlNum(a.cohesion)}, ${sqlNum(a.externalEdges)});`);\n for (const m of a.members) lines.push(`INSERT INTO area_members VALUES (${sqlNum(a.id)}, ${sqlStr(m)});`);\n }\n\n // facts (+ subjects, evidence) when the graph carried them.\n if (graph.facts && graph.facts.length) {\n lines.push('CREATE TABLE IF NOT EXISTS facts (id TEXT PRIMARY KEY, kind TEXT, predicate_json TEXT, derived_by TEXT, confidence TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_subjects (fact_id TEXT, node_id TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_evidence (fact_id TEXT, file TEXT, span_start INTEGER, span_end INTEGER);');\n for (const f of graph.facts) {\n lines.push(`INSERT INTO facts VALUES (${sqlStr(f.id)}, ${sqlStr(f.kind)}, ${sqlStr(JSON.stringify(f.predicate))}, ${sqlStr(f.derivedBy)}, ${sqlStr(f.confidence)});`);\n for (const s of f.subjectIds) lines.push(`INSERT INTO fact_subjects VALUES (${sqlStr(f.id)}, ${sqlStr(s)});`);\n for (const ev of f.evidence) lines.push(`INSERT INTO fact_evidence VALUES (${sqlStr(f.id)}, ${sqlStr(ev.file)}, ${sqlNum(ev.span.start)}, ${sqlNum(ev.span.end)});`);\n }\n }\n\n lines.push('COMMIT;');\n return lines.join('\\n') + '\\n';\n}\n\n/** SQL string literal (single quotes doubled) or NULL for absent values. */\nfunction sqlStr(v: string | null | undefined): string {\n if (v == null) return 'NULL';\n return `'${v.replace(/'/g, \"''\")}'`;\n}\n/** Numeric literal or NULL for absent values. */\nfunction sqlNum(v: number | null | undefined): string {\n return v == null || !Number.isFinite(v) ? 'NULL' : String(v);\n}\n/** Boolean as 0/1, NULL when unknown (e.g. an unanalyzable node's `tested`). */\nfunction sqlBool(v: boolean | null | undefined): string {\n return v == null ? 'NULL' : v ? '1' : '0';\n}\n\nfunction cyclonedx(ctx: ExportContext): string {\n // CycloneDX 1.6 JSON — dependencies as library components + local models as\n // machine-learning-model components (AI-BOM). Deterministic ordering; no\n // timestamps beyond the pinned generatedAt.\n const components: unknown[] = [];\n for (const d of ctx.deps ?? []) {\n components.push({\n type: 'library',\n name: d.name,\n version: d.installed ?? d.declared,\n purl: d.ecosystem === 'npm' ? `pkg:npm/${d.name}@${d.installed ?? ''}` : undefined,\n });\n }\n for (const m of ctx.models ?? []) {\n components.push({ type: 'machine-learning-model', name: m.name, properties: [{ name: 'vg:runtime', value: m.runtime }] });\n }\n const bom = {\n bomFormat: 'CycloneDX',\n specVersion: '1.6',\n metadata: { timestamp: ctx.generatedAt, tools: [{ name: 'vg', version: ctx.graph.provenance.version }] },\n components,\n };\n return JSON.stringify(bom, null, 2) + '\\n';\n}\n\nfunction spdx(ctx: ExportContext): string {\n const packages = (ctx.deps ?? []).map((d) => ({\n SPDXID: `SPDXRef-Package-${cypherLabel(d.name)}`,\n name: d.name,\n versionInfo: d.installed ?? d.declared,\n downloadLocation: 'NOASSERTION',\n }));\n const doc = {\n spdxVersion: 'SPDX-2.3',\n dataLicense: 'CC0-1.0',\n SPDXID: 'SPDXRef-DOCUMENT',\n name: 'vg-sbom',\n creationInfo: { created: ctx.generatedAt, creators: [`Tool: vg-${ctx.graph.provenance.version}`] },\n packages,\n };\n return JSON.stringify(doc, null, 2) + '\\n';\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { managerFromProviderId, formatManagerBadgeLine } from './chunk-WHJMS7XC.js';
|
|
2
|
-
import { MockProvider, LocalLlamaProvider, OPENAI_COMPATIBLE, OllamaProvider, OpenAiCompatibleProvider } from './chunk-G25STLE7.js';
|
|
3
1
|
import { resolveGgufPath } from './chunk-7AVYKZEM.js';
|
|
4
|
-
import {
|
|
2
|
+
import { managerFromProviderId, formatManagerBadgeLine } from './chunk-WHJMS7XC.js';
|
|
3
|
+
import { lookupModelCapabilities } from './chunk-WGPS3NZQ.js';
|
|
4
|
+
import { MockProvider, LocalLlamaProvider, OPENAI_COMPATIBLE, OllamaProvider, OpenAiCompatibleProvider } from './chunk-SJFBXCII.js';
|
|
5
|
+
import { CliError, ExitCode } from './chunk-TNADGCOX.js';
|
|
5
6
|
import { discoverModels } from './chunk-CQDUBAQY.js';
|
|
6
7
|
import * as fs from 'fs';
|
|
7
8
|
import * as os from 'os';
|
|
@@ -144,6 +145,115 @@ function titleCase(id) {
|
|
|
144
145
|
return id.replace(/[-_]/g, " ").replace(/\b\w/g, (ch) => ch.toUpperCase());
|
|
145
146
|
}
|
|
146
147
|
|
|
148
|
+
// src/code/text-tool-protocol.ts
|
|
149
|
+
var TAG_RE = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
|
|
150
|
+
var FENCE_RE = /```(?:tool_call|tool|json)?\s*\n?([\s\S]*?)```/g;
|
|
151
|
+
function toToolCall(blob, index) {
|
|
152
|
+
let parsed;
|
|
153
|
+
try {
|
|
154
|
+
parsed = JSON.parse(blob);
|
|
155
|
+
} catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.name !== "string" || !parsed.name) return null;
|
|
159
|
+
const args = parsed.arguments ?? parsed.parameters ?? parsed.input ?? {};
|
|
160
|
+
return {
|
|
161
|
+
id: `text_${index}`,
|
|
162
|
+
name: parsed.name,
|
|
163
|
+
arguments: args && typeof args === "object" && !Array.isArray(args) ? args : {}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function parseTextToolCalls(text) {
|
|
167
|
+
const calls = [];
|
|
168
|
+
let cleaned = text ?? "";
|
|
169
|
+
cleaned = cleaned.replace(TAG_RE, (whole, body) => {
|
|
170
|
+
const call = toToolCall(body, calls.length);
|
|
171
|
+
if (!call) return whole;
|
|
172
|
+
calls.push(call);
|
|
173
|
+
return "";
|
|
174
|
+
});
|
|
175
|
+
if (calls.length === 0) {
|
|
176
|
+
cleaned = cleaned.replace(FENCE_RE, (whole, body) => {
|
|
177
|
+
const call = toToolCall(body.trim(), calls.length);
|
|
178
|
+
if (!call) return whole;
|
|
179
|
+
calls.push(call);
|
|
180
|
+
return "";
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
if (calls.length === 0) {
|
|
184
|
+
const t = cleaned.trim();
|
|
185
|
+
if (t.startsWith("{") && t.endsWith("}")) {
|
|
186
|
+
const call = toToolCall(t, 0);
|
|
187
|
+
if (call) {
|
|
188
|
+
calls.push(call);
|
|
189
|
+
cleaned = "";
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return { calls, text: cleaned.trim() };
|
|
194
|
+
}
|
|
195
|
+
function textToolProtocolInstruction(tools) {
|
|
196
|
+
const lines = tools.map((t) => {
|
|
197
|
+
const params = JSON.stringify(t.parameters?.properties ?? {});
|
|
198
|
+
return `- ${t.name}: ${t.description.split("\n")[0]} \xB7 arguments schema: ${params}`;
|
|
199
|
+
});
|
|
200
|
+
return [
|
|
201
|
+
"",
|
|
202
|
+
"## Tool calling (text protocol)",
|
|
203
|
+
"This runtime has no native function-calling. To use a tool, reply with ONLY:",
|
|
204
|
+
'<tool_call>{"name": "<tool name>", "arguments": { \u2026 }}</tool_call>',
|
|
205
|
+
"One tool call per reply. Wait for the tool result before the next call.",
|
|
206
|
+
"When the task is complete, call the `finish` tool with your Markdown summary.",
|
|
207
|
+
"Available tools:",
|
|
208
|
+
...lines
|
|
209
|
+
].join("\n");
|
|
210
|
+
}
|
|
211
|
+
function flattenToolRounds(messages) {
|
|
212
|
+
return messages.map((m) => {
|
|
213
|
+
if (m.role === "assistant" && m.toolCalls?.length) {
|
|
214
|
+
const rendered = m.toolCalls.map((c) => `<tool_call>${JSON.stringify({ name: c.name, arguments: c.arguments })}</tool_call>`).join("\n");
|
|
215
|
+
return { role: "assistant", content: [m.content, rendered].filter(Boolean).join("\n") };
|
|
216
|
+
}
|
|
217
|
+
if (m.role === "tool") {
|
|
218
|
+
return { role: "user", content: `Tool result for ${m.name}:
|
|
219
|
+
${m.content}` };
|
|
220
|
+
}
|
|
221
|
+
return m;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
function withToolCallFallback(provider, caps) {
|
|
225
|
+
return {
|
|
226
|
+
id: provider.id,
|
|
227
|
+
label: provider.label,
|
|
228
|
+
local: provider.local,
|
|
229
|
+
model: provider.model,
|
|
230
|
+
supportsTools: provider.supportsTools,
|
|
231
|
+
async chat(messages, opts = {}) {
|
|
232
|
+
const native = provider.supportsTools !== false && caps?.nativeTools !== false;
|
|
233
|
+
if (native || !opts.tools?.length) {
|
|
234
|
+
const result2 = await provider.chat(messages, opts);
|
|
235
|
+
if ((!result2.toolCalls || result2.toolCalls.length === 0) && result2.text) {
|
|
236
|
+
const rescued = parseTextToolCalls(result2.text);
|
|
237
|
+
if (rescued.calls.length) return { ...result2, text: rescued.text, toolCalls: rescued.calls };
|
|
238
|
+
}
|
|
239
|
+
return result2;
|
|
240
|
+
}
|
|
241
|
+
const instruction = textToolProtocolInstruction(opts.tools);
|
|
242
|
+
const flattened = flattenToolRounds(messages);
|
|
243
|
+
const withProtocol = flattened.map(
|
|
244
|
+
(m, i) => i === 0 && m.role === "system" ? { role: "system", content: m.content + "\n" + instruction } : m
|
|
245
|
+
);
|
|
246
|
+
if (withProtocol[0]?.role !== "system") {
|
|
247
|
+
withProtocol.unshift({ role: "system", content: instruction });
|
|
248
|
+
}
|
|
249
|
+
const result = await provider.chat(withProtocol, { ...opts, tools: void 0 });
|
|
250
|
+
const parsed = parseTextToolCalls(result.text ?? "");
|
|
251
|
+
if (parsed.calls.length) return { ...result, text: parsed.text, toolCalls: parsed.calls };
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
147
257
|
// src/code/router.ts
|
|
148
258
|
var HOSTED_IDS = /* @__PURE__ */ new Set(["vibgrate-relay", "openrouter", "litellm", "openai", "together"]);
|
|
149
259
|
function resolveProviders(opts, deps = {}) {
|
|
@@ -219,7 +329,8 @@ function resolveProviders(opts, deps = {}) {
|
|
|
219
329
|
ExitCode.NOT_FOUND
|
|
220
330
|
);
|
|
221
331
|
}
|
|
222
|
-
function finish(
|
|
332
|
+
function finish(rawProviders, reason) {
|
|
333
|
+
const providers = rawProviders.map((p) => withToolCallFallback(p, lookupModelCapabilities(p.model)));
|
|
223
334
|
const primary = providers[0];
|
|
224
335
|
const manager = managerFromProviderId(primary?.id);
|
|
225
336
|
return {
|
|
@@ -322,5 +433,5 @@ function basename(p) {
|
|
|
322
433
|
}
|
|
323
434
|
|
|
324
435
|
export { fetchCatalog, resolveProviders, topProviders };
|
|
325
|
-
//# sourceMappingURL=chunk-
|
|
326
|
-
//# sourceMappingURL=chunk-
|
|
436
|
+
//# sourceMappingURL=chunk-NUZM7UOR.js.map
|
|
437
|
+
//# sourceMappingURL=chunk-NUZM7UOR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/code/catalog.ts","../src/code/text-tool-protocol.ts","../src/code/router.ts"],"names":["result","locals"],"mappings":";;;;;;;;;;AA+CA,IAAM,eAAA,GAA0C;AAAA,EAC9C,SAAA,EAAW,oBAAA;AAAA,EACX,MAAA,EAAQ,cAAA;AAAA,EACR,MAAA,EAAQ,YAAA;AAAA,EACR,MAAA,EAAQ,iBAAA;AAAA,EACR,YAAA,EAAc,cAAA;AAAA,EACd,QAAA,EA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,EAA4C;AAChE,EAAA,IAAI;AACF,IAAA,OAAO,QAAA,EAAS;AAAA,EAClB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAAS,SAAS,CAAA,EAAmB;AACnC,EAAA,OAAO,CAAA,CAAE,QAAQ,KAAA,EAAO,GAAG,EAAE,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,EAAI,IAAK,CAAA;AACnD","file":"chunk-NUZM7UOR.js","sourcesContent":["/**\n * Live model catalog for the `vg code` guided picker (VG-CLI-CODE §8).\n *\n * The guided flow offers the developer the current top providers and models\n * without us hard-coding a list that goes stale. OpenRouter publishes a public,\n * key-free catalog at `/api/v1/models`; we fetch it, group by provider, rank\n * coding-friendly models first, and cache it per-user with a TTL so repeat runs\n * are instant and offline runs still work. If the network and cache both fail we\n * fall back to a tiny curated provider list plus the always-available\n * \"enter a model slug yourself\" escape hatch — the picker is never empty.\n *\n * Pure over its injected `fetch`, `now`, and cache, so the parse/group/rank\n * logic is unit-testable with no network.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nexport interface CatalogModel {\n /** Full slug, e.g. `anthropic/claude-3.5-sonnet`. */\n id: string;\n name: string;\n /** Provider segment, e.g. `anthropic`. */\n provider: string;\n contextLength?: number;\n /** USD per 1M prompt tokens (derived from OpenRouter's per-token price). */\n promptPricePerM?: number;\n completionPricePerM?: number;\n}\n\nexport interface ProviderGroup {\n /** Provider id, e.g. `anthropic`. */\n id: string;\n /** Friendly label, e.g. `Anthropic (Claude)`. */\n label: string;\n models: CatalogModel[];\n}\n\nexport interface Catalog {\n providers: ProviderGroup[];\n /** true when served from network, false when from cache or the curated fallback. */\n fresh: boolean;\n source: 'network' | 'cache' | 'fallback';\n}\n\n/** Provider display names + the order we surface them (the \"top providers\" list). */\nconst PROVIDER_LABELS: Record<string, string> = {\n anthropic: 'Anthropic (Claude)',\n openai: 'OpenAI (GPT)',\n 'x-ai': 'xAI (Grok)',\n google: 'Google (Gemini)',\n 'meta-llama': 'Meta (Llama)',\n deepseek: 'DeepSeek',\n mistralai: 'Mistral',\n qwen: 'Qwen',\n};\nconst FEATURED_ORDER = Object.keys(PROVIDER_LABELS);\n\nconst OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models';\n/** Cache freshness window: a day is plenty; model lists move slowly. */\nconst CACHE_TTL_MS = 24 * 60 * 60 * 1000;\n\nexport interface FetchCatalogOptions {\n fetchImpl?: typeof fetch;\n now?: () => number;\n /** Bypass and refresh from network. */\n noCache?: boolean;\n /** Never touch the network (offline / --local): cache or curated only. */\n offline?: boolean;\n timeoutMs?: number;\n}\n\n/** The per-user catalog cache file (shared across repos, like the model cache). */\nexport function catalogCachePath(): string {\n const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');\n return path.join(base, 'vibgrate', 'catalog', 'openrouter-models.json');\n}\n\nexport async function fetchCatalog(options: FetchCatalogOptions = {}): Promise<Catalog> {\n const now = options.now ?? (() => 0);\n const fetchImpl = options.fetchImpl ?? fetch;\n\n // Serve from a warm cache when allowed.\n if (!options.noCache) {\n const cached = readCache();\n if (cached && (options.offline || now() - cached.ts < CACHE_TTL_MS)) {\n return { providers: groupModels(cached.models), fresh: false, source: 'cache' };\n }\n }\n if (options.offline) {\n const cached = readCache();\n if (cached) return { providers: groupModels(cached.models), fresh: false, source: 'cache' };\n return { providers: curatedFallback(), fresh: false, source: 'fallback' };\n }\n\n // Fetch fresh.\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 8000);\n let raw: unknown;\n try {\n const res = await fetchImpl(OPENROUTER_MODELS_URL, { signal: controller.signal });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n raw = await res.json();\n } finally {\n clearTimeout(timer);\n }\n const models = parseModels(raw);\n if (models.length === 0) throw new Error('empty catalog');\n writeCache(models, now());\n return { providers: groupModels(models), fresh: true, source: 'network' };\n } catch {\n // Network failed → cache → curated.\n const cached = readCache();\n if (cached) return { providers: groupModels(cached.models), fresh: false, source: 'cache' };\n return { providers: curatedFallback(), fresh: false, source: 'fallback' };\n }\n}\n\n/** Parse OpenRouter's `/models` payload into our shape (defensive about fields). */\nexport function parseModels(raw: unknown): CatalogModel[] {\n const data = (raw as { data?: unknown[] })?.data;\n if (!Array.isArray(data)) return [];\n const out: CatalogModel[] = [];\n for (const entry of data) {\n const e = entry as {\n id?: unknown;\n name?: unknown;\n context_length?: unknown;\n pricing?: { prompt?: unknown; completion?: unknown };\n };\n if (typeof e.id !== 'string' || !e.id.includes('/')) continue;\n const provider = e.id.split('/')[0];\n out.push({\n id: e.id,\n name: typeof e.name === 'string' ? e.name : e.id,\n provider,\n contextLength: numeric(e.context_length),\n promptPricePerM: perMillion(e.pricing?.prompt),\n completionPricePerM: perMillion(e.pricing?.completion),\n });\n }\n return out;\n}\n\n/** Group models by provider, featured providers first, coding models first within each. */\nexport function groupModels(models: CatalogModel[]): ProviderGroup[] {\n const byProvider = new Map<string, CatalogModel[]>();\n for (const m of models) {\n const list = byProvider.get(m.provider) ?? [];\n list.push(m);\n byProvider.set(m.provider, list);\n }\n const groups: ProviderGroup[] = [];\n for (const [id, list] of byProvider) {\n groups.push({ id, label: PROVIDER_LABELS[id] ?? titleCase(id), models: list.sort(rankModels) });\n }\n // Featured providers in our order first, then the rest alphabetically.\n groups.sort((a, b) => {\n const ia = FEATURED_ORDER.indexOf(a.id);\n const ib = FEATURED_ORDER.indexOf(b.id);\n if (ia !== -1 || ib !== -1) return (ia === -1 ? 1e9 : ia) - (ib === -1 ? 1e9 : ib);\n return a.label.localeCompare(b.label);\n });\n return groups;\n}\n\n/** Coding-oriented models first, then larger context, then name — a helpful default order. */\nfunction rankModels(a: CatalogModel, b: CatalogModel): number {\n const ca = isCoding(a) ? 0 : 1;\n const cb = isCoding(b) ? 0 : 1;\n if (ca !== cb) return ca - cb;\n const la = a.contextLength ?? 0;\n const lb = b.contextLength ?? 0;\n if (la !== lb) return lb - la;\n return a.id.localeCompare(b.id);\n}\n\nfunction isCoding(m: CatalogModel): boolean {\n return /cod(e|er|ing)/i.test(m.id) || /cod(e|er|ing)/i.test(m.name);\n}\n\n/** Top N providers (the guided picker's first screen). */\nexport function topProviders(catalog: Catalog, n = 6): ProviderGroup[] {\n return catalog.providers.slice(0, n);\n}\n\ninterface CacheShape {\n ts: number;\n models: CatalogModel[];\n}\n\nfunction readCache(): CacheShape | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(catalogCachePath(), 'utf8')) as CacheShape;\n if (Array.isArray(parsed.models) && typeof parsed.ts === 'number') return parsed;\n } catch {\n /* no cache */\n }\n return null;\n}\n\nfunction writeCache(models: CatalogModel[], ts: number): void {\n try {\n const file = catalogCachePath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, JSON.stringify({ ts, models }));\n } catch {\n /* cache is best-effort */\n }\n}\n\n/**\n * A minimal, honestly-labelled offline fallback: just the provider names, so the\n * picker still works with no network and no cache. Model ids are intentionally\n * NOT hard-coded (they go stale) — the flow always offers \"enter a model slug\".\n */\nfunction curatedFallback(): ProviderGroup[] {\n return FEATURED_ORDER.map((id) => ({ id, label: PROVIDER_LABELS[id], models: [] }));\n}\n\nfunction numeric(v: unknown): number | undefined {\n const n = typeof v === 'string' ? Number(v) : typeof v === 'number' ? v : NaN;\n return Number.isFinite(n) ? n : undefined;\n}\n\n/** OpenRouter prices are USD *per token* as strings; convert to per-million. */\nfunction perMillion(v: unknown): number | undefined {\n const n = numeric(v);\n if (n === undefined) return undefined;\n return Math.round(n * 1_000_000 * 1000) / 1000;\n}\n\nfunction titleCase(id: string): string {\n return id.replace(/[-_]/g, ' ').replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n}\n","/**\n * Text-based tool-call protocol fallback (model-agnostic agent robustness).\n *\n * The agent loop speaks native (OpenAI-shaped) function calling, but many\n * backends can't: the embedded llama.cpp host has no tool API at all, and a\n * large share of local models served by Ollama / LM Studio either ignore the\n * native `tools` field or emit their chat-template tool markup — Hermes/Qwen\n * `<tool_call>{…}</tool_call>` tags — as plain assistant text. Leading OSS\n * agents (Cline, Roo Code, Aider) solve this with a *prompt-described* tool\n * protocol parsed from text; this module gives `vg code` the same floor, so the\n * core agent works with whatever model is picked underneath.\n *\n * Two layers, both provider-neutral and unit-tested:\n * - {@link parseTextToolCalls} — recover tool calls a model wrote as text\n * (`<tool_call>` tags, fenced ```tool_call blocks, or a bare JSON object\n * with `name` + `arguments`). Used as a *rescue* on every provider, so a\n * model that ignores native function calling still drives the loop.\n * - {@link withToolCallFallback} — a Provider decorator. For backends that\n * declare `supportsTools: false` it renders the tool list into the system\n * prompt, serializes prior tool rounds as text the model can read, and\n * parses the reply. For native backends it passes through and only rescues.\n */\n\nimport type { ChatMessage, ChatOptions, Provider, ProviderResult, ToolCall, ToolSpec } from './types.js';\n\n/** Formats we can recover a tool call from, in order of specificity. */\nconst TAG_RE = /<tool_call>\\s*([\\s\\S]*?)\\s*<\\/tool_call>/g;\nconst FENCE_RE = /```(?:tool_call|tool|json)?\\s*\\n?([\\s\\S]*?)```/g;\n\ninterface RawCall {\n name?: unknown;\n arguments?: unknown;\n parameters?: unknown;\n input?: unknown;\n}\n\n/** Parse one candidate JSON blob into a ToolCall, or null when it isn't one. */\nfunction toToolCall(blob: string, index: number): ToolCall | null {\n let parsed: RawCall;\n try {\n parsed = JSON.parse(blob) as RawCall;\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== 'object' || typeof parsed.name !== 'string' || !parsed.name) return null;\n const args = parsed.arguments ?? parsed.parameters ?? parsed.input ?? {};\n return {\n id: `text_${index}`,\n name: parsed.name,\n arguments: args && typeof args === 'object' && !Array.isArray(args) ? (args as Record<string, unknown>) : {},\n };\n}\n\n/**\n * Extract tool calls a model emitted as plain text, returning the calls plus\n * the text with the call markup removed (what remains is the user-facing\n * prose, if any). Order of attempts: `<tool_call>` tags, then fenced blocks,\n * then one bare top-level JSON object. Anything that doesn't parse into a\n * `{name, arguments}` shape is left in the text untouched.\n */\nexport function parseTextToolCalls(text: string): { calls: ToolCall[]; text: string } {\n const calls: ToolCall[] = [];\n let cleaned = text ?? '';\n\n cleaned = cleaned.replace(TAG_RE, (whole, body: string) => {\n const call = toToolCall(body, calls.length);\n if (!call) return whole;\n calls.push(call);\n return '';\n });\n\n if (calls.length === 0) {\n cleaned = cleaned.replace(FENCE_RE, (whole, body: string) => {\n const call = toToolCall(body.trim(), calls.length);\n if (!call) return whole;\n calls.push(call);\n return '';\n });\n }\n\n if (calls.length === 0) {\n const t = cleaned.trim();\n if (t.startsWith('{') && t.endsWith('}')) {\n const call = toToolCall(t, 0);\n if (call) {\n calls.push(call);\n cleaned = '';\n }\n }\n }\n\n return { calls, text: cleaned.trim() };\n}\n\n/** The prompt block that teaches a non-tool-calling model the call format. */\nexport function textToolProtocolInstruction(tools: ToolSpec[]): string {\n const lines = tools.map((t) => {\n const params = JSON.stringify(t.parameters?.properties ?? {});\n return `- ${t.name}: ${t.description.split('\\n')[0]} · arguments schema: ${params}`;\n });\n return [\n '',\n '## Tool calling (text protocol)',\n 'This runtime has no native function-calling. To use a tool, reply with ONLY:',\n '<tool_call>{\"name\": \"<tool name>\", \"arguments\": { … }}</tool_call>',\n 'One tool call per reply. Wait for the tool result before the next call.',\n 'When the task is complete, call the `finish` tool with your Markdown summary.',\n 'Available tools:',\n ...lines,\n ].join('\\n');\n}\n\n/** Serialize a tool round into text for backends that lack tool roles. */\nfunction flattenToolRounds(messages: ChatMessage[]): ChatMessage[] {\n return messages.map((m): ChatMessage => {\n if (m.role === 'assistant' && m.toolCalls?.length) {\n const rendered = m.toolCalls\n .map((c) => `<tool_call>${JSON.stringify({ name: c.name, arguments: c.arguments })}</tool_call>`)\n .join('\\n');\n return { role: 'assistant', content: [m.content, rendered].filter(Boolean).join('\\n') };\n }\n if (m.role === 'tool') {\n return { role: 'user', content: `Tool result for ${m.name}:\\n${m.content}` };\n }\n return m;\n });\n}\n\n/**\n * Wrap a provider so the agent loop's tool calling works regardless of the\n * backend's native capability:\n * - `supportsTools === false` (embedded llama.cpp), or a model the\n * capability registry knows cannot tool-call natively: inject the text\n * protocol into the system prompt, flatten tool rounds to text, parse the\n * reply.\n * - native backends: call through unchanged; when the model returned no\n * native tool calls but its text contains parseable tool markup, rescue it.\n * Idempotent-safe: wrapping a wrapped provider changes nothing observable.\n */\nexport function withToolCallFallback(\n provider: Provider,\n caps?: { nativeTools: boolean | null },\n): Provider {\n return {\n id: provider.id,\n label: provider.label,\n local: provider.local,\n model: provider.model,\n supportsTools: provider.supportsTools,\n async chat(messages: ChatMessage[], opts: ChatOptions = {}): Promise<ProviderResult> {\n const native = provider.supportsTools !== false && caps?.nativeTools !== false;\n if (native || !opts.tools?.length) {\n const result = await provider.chat(messages, opts);\n if ((!result.toolCalls || result.toolCalls.length === 0) && result.text) {\n const rescued = parseTextToolCalls(result.text);\n if (rescued.calls.length) return { ...result, text: rescued.text, toolCalls: rescued.calls };\n }\n return result;\n }\n\n // Text-protocol path: teach the format, flatten history, parse the reply.\n const instruction = textToolProtocolInstruction(opts.tools);\n const flattened = flattenToolRounds(messages);\n const withProtocol: ChatMessage[] = flattened.map((m, i) =>\n i === 0 && m.role === 'system' ? { role: 'system', content: m.content + '\\n' + instruction } : m,\n );\n if (withProtocol[0]?.role !== 'system') {\n withProtocol.unshift({ role: 'system', content: instruction });\n }\n const result = await provider.chat(withProtocol, { ...opts, tools: undefined });\n const parsed = parseTextToolCalls(result.text ?? '');\n if (parsed.calls.length) return { ...result, text: parsed.text, toolCalls: parsed.calls };\n return result;\n },\n };\n}\n","/**\n * Model routing for `vg code` (VG-CLI-CODE §5.2).\n *\n * The \"best in breed\" story is an ordered set of backends with automatic\n * fallback — the OpenRouter/LiteLLM model — expressed as a *scheduling* decision\n * the session can execute: try the preferred provider, and on a transport\n * failure fall through to the next available one. This resolver is pure over its\n * injected inputs (flags, environment, the discovered local fleet), so it is\n * fully testable, and it holds two hard rules from the guardrails:\n *\n * - **No surprise egress or install.** With no explicit selection it picks a\n * backend only from signals already present (a configured hosted key, or a\n * model already pulled locally). It never dials a default cloud endpoint you\n * didn't configure, and never triggers an install to pick a default.\n * - **`--local` stays local.** Under `--local` only on-device backends are\n * eligible; if none are available it fails with an actionable message rather\n * than silently reaching the network.\n * - **Code Modes stay on the Vibgrate manager.** When {@link RouteOptions.codeMode}\n * is set, routing is fail-closed to embedded llama.cpp (first-party GGUF).\n * Ollama / LM Studio are never auto-selected for Code Modes.\n */\n\nimport { CliError, ExitCode } from '../util/exit.js';\nimport { discoverModels, type LocalModel } from '../engine/models.js';\nimport { resolveGgufPath } from '../runtime/resolve-gguf.js';\nimport {\n formatManagerBadgeLine,\n managerFromProviderId,\n type ModelManagerId,\n} from '../runtime/model-manager.js';\nimport {\n LocalLlamaProvider,\n MockProvider,\n OllamaProvider,\n OpenAiCompatibleProvider,\n OPENAI_COMPATIBLE,\n type OpenAiCompatibleConfig,\n} from './providers.js';\nimport { withToolCallFallback } from './text-tool-protocol.js';\nimport { lookupModelCapabilities } from './model-capabilities.js';\nimport type { Provider } from './types.js';\n\nexport interface RouteOptions {\n /** Explicit `--provider` (vibgrate-relay, ollama, lmstudio, foundry-local, openrouter, litellm, openai, together, llama-cpp). */\n provider?: string;\n /** Explicit `--model`. */\n model?: string;\n /** `--local`: on-device backends only. */\n local?: boolean;\n /** `--yes`: consent to a first-use install (only relevant to llama-cpp). */\n consent?: boolean;\n /** Path to a gguf for the llama-cpp backend. */\n modelPath?: string;\n /**\n * Prefer embedded llama.cpp when a GGUF is resolvable (Code Mode preferredInference).\n * When false, Ollama may be tried first (VG_PREFER_OLLAMA).\n */\n preferEmbedded?: boolean;\n /**\n * Code Mode path (spark|flow|forge): fail-closed to the Vibgrate model manager.\n * Never auto-routes to Ollama / LM Studio / hosted.\n */\n codeMode?: boolean;\n /** A scripted reply → force the deterministic MockProvider (tests/`--mock`). */\n mockReply?: string;\n}\n\nexport interface RouteDeps {\n env?: NodeJS.ProcessEnv;\n discover?: () => LocalModel[];\n}\n\nexport interface RouteResult {\n /** Providers to try in order; the session falls through on transport failure. */\n providers: Provider[];\n /** A short, human explanation of the choice (for the run header / --json). */\n reason: string;\n /** Manager identity for the primary provider (badge / UX). */\n manager: ModelManagerId;\n /** e.g. \"[Vibgrate] Code Mode · first-party model manager …\" */\n managerLine: string;\n}\n\nconst HOSTED_IDS = new Set(['vibgrate-relay', 'openrouter', 'litellm', 'openai', 'together']);\n\n/** Resolve the ordered provider list for a run. Throws an actionable CliError when nothing is eligible. */\nexport function resolveProviders(opts: RouteOptions, deps: RouteDeps = {}): RouteResult {\n const env = deps.env ?? process.env;\n const discover = deps.discover ?? discoverModels;\n\n // Deterministic offline floor — used by tests, the benchmark, and `--mock`.\n if (opts.mockReply !== undefined) {\n const providers = [new MockProvider(opts.model ?? 'mock-1', opts.mockReply)];\n return finish(providers, 'mock provider (scripted, offline)');\n }\n\n // Code Modes: Vibgrate manager only (embedded GGUF). No third-party auto-route.\n // Even when code.ts pins provider=llama-cpp, never chain Ollama/LM Studio — a\n // grammar or load failure must surface the real error, not \"couldn't reach Ollama\".\n if (opts.codeMode && (!opts.provider || opts.provider === 'llama-cpp' || opts.provider === 'vibgrate')) {\n const gguf = resolveGgufPath({\n modelPath: opts.modelPath || env.VG_CODE_MODEL_PATH,\n modelRef: opts.model,\n env,\n discover,\n });\n if (!gguf) {\n throw new CliError(\n 'Code Mode needs the Vibgrate model manager weights on disk. Run `vg models install spark|flow|forge` (or pass --model-path to a GGUF). Custom Ollama/LM Studio backends are only used when you set --provider explicitly.',\n ExitCode.NOT_FOUND,\n );\n }\n const providers = [\n new LocalLlamaProvider(opts.model ?? basename(gguf.path), gguf.path, undefined, !!opts.consent),\n ];\n return finish(providers, `Code Mode → Vibgrate model manager (embedded llama.cpp · ${gguf.path})`);\n }\n\n // Explicit provider wins.\n if (opts.provider) {\n const provider = buildExplicit(opts.provider, opts, env, discover);\n // Code Mode + explicit custom backend (ollama, lmstudio, …): still no surprise chain.\n if (opts.codeMode) {\n return finish([provider], `Code Mode → explicit --provider ${opts.provider} (no auto-fallback)`);\n }\n // Custom path: only fall through to other *local* adapters when --local, never LM Studio unless chosen.\n const fallbacks =\n opts.local || provider.local\n ? localFallbacks(opts, env, discover, provider.id, { allowLmStudio: opts.provider === 'lmstudio' })\n : [];\n return finish([provider, ...fallbacks], `explicit --provider ${opts.provider}`);\n }\n\n // --local: on-device only, in preference order (embedded → ollama; no surprise LM Studio).\n if (opts.local) {\n const locals = localFallbacks(opts, env, discover, '', { allowLmStudio: false });\n if (locals.length === 0) {\n throw new CliError(\n 'no local model backend available for --local. Install a Code Mode (`vg models install spark`), start Ollama (`ollama serve` + pull), or point --provider llama-cpp at a gguf. See `vg models`.',\n ExitCode.NOT_FOUND,\n );\n }\n return finish(locals, '--local (on-device backends only)');\n }\n\n // No explicit selection: choose from signals already present, best first.\n // 1) Vibgrate Relay — the first-party hosted router, preferred when the user\n // has signed in. Nothing is dialled without their token, so this stays inside\n // the no-surprise-egress rule above.\n if (env.VIBGRATE_RELAY_TOKEN) {\n const model = resolveHostedModel(opts, env, 'vibgrate-relay');\n const primary = buildHosted('vibgrate-relay', model);\n return finish(\n [primary, ...localFallbacks(opts, env, discover, 'vibgrate-relay', { allowLmStudio: false })],\n 'VIBGRATE_RELAY_TOKEN is set → Vibgrate Relay (with local fallback)',\n );\n }\n // 2) Another configured hosted router key.\n if (env.OPENROUTER_API_KEY) {\n const model = resolveHostedModel(opts, env, 'openrouter');\n const primary = buildHosted('openrouter', model);\n return finish(\n [primary, ...localFallbacks(opts, env, discover, 'openrouter', { allowLmStudio: false })],\n 'OPENROUTER_API_KEY is set → OpenRouter (with local fallback)',\n );\n }\n // 3) A locally-pulled model (embedded first; never auto LM Studio).\n const locals = localFallbacks(opts, env, discover, '', { allowLmStudio: false });\n if (locals.length) return finish(locals, 'a local model is available → on-device (no key needed)');\n // 4) Any other configured hosted key.\n for (const id of ['litellm', 'openai', 'together'] as const) {\n const keyEnv = OPENAI_COMPATIBLE[id].apiKeyEnv;\n if (keyEnv && env[keyEnv]) {\n const model = resolveHostedModel(opts, env, id);\n return finish([buildHosted(id, model)], `${keyEnv} is set → ${OPENAI_COMPATIBLE[id].label}`);\n }\n }\n\n throw new CliError(\n 'no model backend configured. Do one of: sign in to Vibgrate Relay (VIBGRATE_RELAY_TOKEN), set OPENROUTER_API_KEY for the hosted router, run `vg models install spark` for the Vibgrate manager, run Ollama locally, or use --local with a local model. Set the model with --model or VG_CODE_MODEL.',\n ExitCode.NOT_FOUND,\n );\n}\n\nfunction finish(rawProviders: Provider[], reason: string): RouteResult {\n // Every backend gets the tool-call fallback: native providers are passed\n // through (with a text-markup rescue), backends without native function\n // calling (embedded llama.cpp) — and models the capability registry knows\n // cannot tool-call natively — get the prompt-described text protocol. This\n // is what makes the agent work with whatever model is picked underneath.\n const providers = rawProviders.map((p) => withToolCallFallback(p, lookupModelCapabilities(p.model)));\n const primary = providers[0];\n const manager = managerFromProviderId(primary?.id);\n return {\n providers,\n reason,\n manager,\n managerLine: formatManagerBadgeLine(manager, primary?.model),\n };\n}\n\nfunction buildExplicit(id: string, opts: RouteOptions, env: NodeJS.ProcessEnv, discover: () => LocalModel[]): Provider {\n if (id === 'ollama') return new OllamaProvider(resolveLocalModel(opts, discover, 'ollama'), env.OLLAMA_HOST);\n if (id === 'llama-cpp' || id === 'vibgrate') {\n const resolved = resolveGgufPath({\n modelPath: opts.modelPath || env.VG_CODE_MODEL_PATH,\n modelRef: opts.model,\n env,\n discover,\n });\n if (!resolved) {\n throw new CliError(\n '--provider llama-cpp needs a GGUF: pass --model-path, set VG_CODE_MODEL_PATH, or run `vg models install` so the weight store has a catalogued gguf. See `vg models`.',\n ExitCode.USAGE_ERROR,\n );\n }\n return new LocalLlamaProvider(opts.model ?? basename(resolved.path), resolved.path, undefined, !!opts.consent);\n }\n if (id === 'lmstudio') return buildHosted('lmstudio', resolveHostedModel(opts, env, 'lmstudio'));\n if (id === 'foundry-local' || id === 'foundry') {\n return buildHosted('foundry-local', resolveHostedModel(opts, env, 'foundry-local'));\n }\n if (HOSTED_IDS.has(id)) return buildHosted(id, resolveHostedModel(opts, env, id));\n throw new CliError(\n `unknown --provider \"${id}\". Known: vibgrate-relay, ollama, lmstudio, foundry-local, openrouter, litellm, openai, together, llama-cpp.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction buildHosted(id: string, model: string): OpenAiCompatibleProvider {\n const base = OPENAI_COMPATIBLE[id];\n const config: OpenAiCompatibleConfig = { ...base, id };\n return new OpenAiCompatibleProvider(model, config);\n}\n\ninterface LocalFallbackOpts {\n /** Only include LM Studio when the user explicitly asked for it. */\n allowLmStudio: boolean;\n}\n\n/** On-device backends in preference order, skipping the one already chosen as primary. */\nfunction localFallbacks(\n opts: RouteOptions,\n env: NodeJS.ProcessEnv,\n discover: () => LocalModel[],\n exclude: string,\n fb: LocalFallbackOpts,\n): Provider[] {\n const out: Provider[] = [];\n const models = safeDiscover(discover);\n\n // Approach B default: when a GGUF is already on disk, embedded is primary local.\n // Opt out with VG_PREFER_OLLAMA=1 if the user wants Ollama first.\n const preferOllama =\n env.VG_PREFER_OLLAMA === '1' ||\n env.VIBGRATE_PREFER_OLLAMA === '1' ||\n opts.preferEmbedded === false;\n const gguf =\n exclude === 'llama-cpp' || exclude === 'vibgrate'\n ? null\n : resolveGgufPath({\n modelPath: opts.modelPath || env.VG_CODE_MODEL_PATH,\n modelRef: opts.model,\n env,\n discover: () => models,\n });\n\n if (gguf && !preferOllama) {\n out.push(new LocalLlamaProvider(opts.model ?? basename(gguf.path), gguf.path, undefined, !!opts.consent));\n }\n\n const ollamaModel = opts.model ?? firstOfRuntime(models, 'ollama');\n if (exclude !== 'ollama' && ollamaModel) out.push(new OllamaProvider(ollamaModel, env.OLLAMA_HOST));\n\n // LM Studio only when explicitly allowed (user chose --provider lmstudio).\n if (fb.allowLmStudio && exclude !== 'lmstudio') {\n const lmModel = opts.model ?? firstOfRuntime(models, 'lm-studio');\n if (lmModel) out.push(buildHosted('lmstudio', lmModel));\n }\n\n // Foundry Local when server/env is configured.\n if (exclude !== 'foundry-local' && exclude !== 'foundry' && (env.FOUNDRY_LOCAL_BASE_URL || env.VG_CODE_PROVIDER === 'foundry-local')) {\n try {\n const m = opts.model || env.VG_CODE_MODEL;\n if (m) out.push(buildHosted('foundry-local', m));\n } catch {\n /* skip if no model */\n }\n }\n\n // Embedded last if user forced Ollama-first but GGUF still available.\n if (gguf && !out.some((p) => p.id === 'llama-cpp')) {\n out.push(new LocalLlamaProvider(opts.model ?? basename(gguf.path), gguf.path, undefined, !!opts.consent));\n }\n return out;\n}\n\nfunction resolveLocalModel(opts: RouteOptions, discover: () => LocalModel[], runtime: LocalModel['runtime']): string {\n if (opts.model) return opts.model;\n const found = firstOfRuntime(safeDiscover(discover), runtime);\n if (found) return found;\n throw new CliError(`--provider ${runtime} needs a model. Pull one (\\`ollama pull <model>\\`) then re-run, or pass --model. See \\`vg models\\`.`, ExitCode.NOT_FOUND);\n}\n\nfunction resolveHostedModel(opts: RouteOptions, env: NodeJS.ProcessEnv, id: string): string {\n const model = opts.model || env.VG_CODE_MODEL;\n if (model) return model;\n throw new CliError(\n `${OPENAI_COMPATIBLE[id].label} needs a model id — pass --model (e.g. a current best-in-breed coding model) or set VG_CODE_MODEL. We don't hard-code a model so you always pick the current best one.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction firstOfRuntime(models: LocalModel[], runtime: LocalModel['runtime']): string | undefined {\n // Deterministic: discoverModels() already returns a sorted list.\n const m = models.find((x) => x.runtime === runtime);\n return m?.name;\n}\n\nfunction safeDiscover(discover: () => LocalModel[]): LocalModel[] {\n try {\n return discover();\n } catch {\n return [];\n }\n}\n\nfunction basename(p: string): string {\n return p.replace(/\\\\/g, '/').split('/').pop() ?? p;\n}\n"]}
|