@qmediat.io/gemini-code-context-mcp 1.0.2 → 1.2.0

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/auth/credentials-store.d.ts.map +1 -1
  3. package/dist/auth/credentials-store.js +8 -2
  4. package/dist/auth/credentials-store.js.map +1 -1
  5. package/dist/cache/cache-manager.d.ts +31 -0
  6. package/dist/cache/cache-manager.d.ts.map +1 -1
  7. package/dist/cache/cache-manager.js +105 -0
  8. package/dist/cache/cache-manager.js.map +1 -1
  9. package/dist/cache/ttl-watcher.d.ts +2 -0
  10. package/dist/cache/ttl-watcher.d.ts.map +1 -1
  11. package/dist/cache/ttl-watcher.js +60 -25
  12. package/dist/cache/ttl-watcher.js.map +1 -1
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +5 -1
  15. package/dist/config.js.map +1 -1
  16. package/dist/gemini/models.d.ts.map +1 -1
  17. package/dist/gemini/models.js +34 -25
  18. package/dist/gemini/models.js.map +1 -1
  19. package/dist/indexer/globs.d.ts +24 -1
  20. package/dist/indexer/globs.d.ts.map +1 -1
  21. package/dist/indexer/globs.js +70 -4
  22. package/dist/indexer/globs.js.map +1 -1
  23. package/dist/indexer/workspace-validation.d.ts +54 -0
  24. package/dist/indexer/workspace-validation.d.ts.map +1 -0
  25. package/dist/indexer/workspace-validation.js +206 -0
  26. package/dist/indexer/workspace-validation.js.map +1 -0
  27. package/dist/manifest/db.d.ts +50 -0
  28. package/dist/manifest/db.d.ts.map +1 -1
  29. package/dist/manifest/db.js +74 -1
  30. package/dist/manifest/db.js.map +1 -1
  31. package/dist/server.d.ts.map +1 -1
  32. package/dist/server.js +7 -0
  33. package/dist/server.js.map +1 -1
  34. package/dist/tools/ask.tool.d.ts +25 -1
  35. package/dist/tools/ask.tool.d.ts.map +1 -1
  36. package/dist/tools/ask.tool.js +267 -27
  37. package/dist/tools/ask.tool.js.map +1 -1
  38. package/dist/tools/code.tool.d.ts +24 -1
  39. package/dist/tools/code.tool.d.ts.map +1 -1
  40. package/dist/tools/code.tool.js +188 -31
  41. package/dist/tools/code.tool.js.map +1 -1
  42. package/dist/tools/registry.d.ts +37 -6
  43. package/dist/tools/registry.d.ts.map +1 -1
  44. package/dist/tools/registry.js +30 -6
  45. package/dist/tools/registry.js.map +1 -1
  46. package/dist/tools/reindex.tool.d.ts.map +1 -1
  47. package/dist/tools/reindex.tool.js +10 -0
  48. package/dist/tools/reindex.tool.js.map +1 -1
  49. package/dist/tools/shared/thinking.d.ts +63 -0
  50. package/dist/tools/shared/thinking.d.ts.map +1 -0
  51. package/dist/tools/shared/thinking.js +62 -0
  52. package/dist/tools/shared/thinking.js.map +1 -0
  53. package/dist/utils/cost-estimator.d.ts +21 -0
  54. package/dist/utils/cost-estimator.d.ts.map +1 -1
  55. package/dist/utils/cost-estimator.js +43 -6
  56. package/dist/utils/cost-estimator.js.map +1 -1
  57. package/package.json +3 -3
@@ -7,6 +7,7 @@
7
7
  import { mkdirSync } from 'node:fs';
8
8
  import { dirname } from 'node:path';
9
9
  import Database from 'better-sqlite3';
10
+ import { logger } from '../utils/logger.js';
10
11
  import { manifestDbPath, qmediatStateDir } from '../utils/paths.js';
11
12
  const SCHEMA_VERSION = '1';
12
13
  /** Inlined schema — kept in sync with `schema.sql` (the .sql file is the human-readable source of truth). */
@@ -64,7 +65,11 @@ function rowToWorkspace(row) {
64
65
  if (Array.isArray(parsed))
65
66
  fileIds = parsed.filter((v) => typeof v === 'string');
66
67
  }
67
- catch {
68
+ catch (err) {
69
+ // Corruption is silent to the runtime (file_ids is currently write-only
70
+ // and slated for removal in T16), but surface it in logs so users
71
+ // debugging manifest issues get a signal instead of an empty array.
72
+ logger.warn(`manifest: failed to parse workspaces.file_ids for ${String(row.workspace_root)}: ${String(err)}; defaulting to []`);
68
73
  fileIds = [];
69
74
  }
70
75
  return {
@@ -188,6 +193,74 @@ export class ManifestDb {
188
193
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
189
194
  .run(metric.workspaceRoot, metric.toolName, metric.model, metric.cachedTokens, metric.uncachedTokens, metric.costUsdMicro, metric.durationMs, metric.occurredAt);
190
195
  }
196
+ /**
197
+ * Atomically check the daily budget and — if there's headroom — reserve
198
+ * an estimate against it, so concurrent tool calls can't all pass the
199
+ * pre-check and then collectively overshoot the cap.
200
+ *
201
+ * Implemented as a `BEGIN IMMEDIATE`-backed SQLite transaction:
202
+ *
203
+ * 1. SUM existing `cost_usd_micro` since UTC midnight (includes
204
+ * previously-reserved but not yet finalized rows, so concurrent
205
+ * reservations see each other).
206
+ * 2. If `spent + estimate > cap`, rollback and return `rejected`.
207
+ * 3. Otherwise INSERT a row with the estimate. The caller receives its
208
+ * primary-key `id` and is expected to later `finalizeBudgetReservation`
209
+ * (on successful call) or `cancelBudgetReservation` (on failure).
210
+ *
211
+ * `dailyBudgetMicros` of `Number.POSITIVE_INFINITY` disables the check and
212
+ * should not be passed here — the caller should branch on `Number.isFinite`
213
+ * and skip the reservation entirely (plain `insertUsageMetric` after the
214
+ * call is enough when there's no cap).
215
+ */
216
+ reserveBudget(args) {
217
+ const startOfUtcDay = new Date(args.nowMs);
218
+ startOfUtcDay.setUTCHours(0, 0, 0, 0);
219
+ const startMs = startOfUtcDay.getTime();
220
+ const run = this.db.transaction(() => {
221
+ const row = this.db
222
+ .prepare('SELECT COALESCE(SUM(cost_usd_micro), 0) AS total FROM usage_metrics WHERE occurred_at >= ?')
223
+ .get(startMs);
224
+ const spent = row.total ?? 0;
225
+ if (spent + args.estimatedCostMicros > args.dailyBudgetMicros) {
226
+ return {
227
+ rejected: true,
228
+ spentMicros: spent,
229
+ capMicros: args.dailyBudgetMicros,
230
+ estimateMicros: args.estimatedCostMicros,
231
+ };
232
+ }
233
+ const result = this.db
234
+ .prepare(`INSERT INTO usage_metrics(
235
+ workspace_root, tool_name, model, cached_tokens, uncached_tokens,
236
+ cost_usd_micro, duration_ms, occurred_at
237
+ ) VALUES (?, ?, ?, 0, 0, ?, 0, ?)`)
238
+ .run(args.workspaceRoot, args.toolName, args.model, args.estimatedCostMicros, args.nowMs);
239
+ return { id: Number(result.lastInsertRowid) };
240
+ });
241
+ // `immediate` mode acquires a reserved lock at BEGIN so a second process
242
+ // reaching `BEGIN IMMEDIATE` is serialised. Prevents two concurrent
243
+ // MCP instances both passing the SUM check on the same headroom.
244
+ return run.immediate();
245
+ }
246
+ /**
247
+ * Replace the placeholder values on a reservation row with the measured
248
+ * cost and token counts after a tool call completes successfully.
249
+ */
250
+ finalizeBudgetReservation(reservationId, data) {
251
+ this.db
252
+ .prepare(`UPDATE usage_metrics
253
+ SET cached_tokens = ?, uncached_tokens = ?, cost_usd_micro = ?, duration_ms = ?
254
+ WHERE id = ?`)
255
+ .run(data.cachedTokens, data.uncachedTokens, data.costUsdMicro, data.durationMs, reservationId);
256
+ }
257
+ /**
258
+ * Drop a reservation row when the tool call failed before producing any
259
+ * billable output. Idempotent — calling with an unknown id is a no-op.
260
+ */
261
+ cancelBudgetReservation(reservationId) {
262
+ this.db.prepare('DELETE FROM usage_metrics WHERE id = ?').run(reservationId);
263
+ }
191
264
  /** Sum costs spent today (UTC) in USD micros. */
192
265
  todaysCostMicros(nowMs) {
193
266
  const startOfUtcDay = new Date(nowMs);
@@ -1 +1 @@
1
- {"version":3,"file":"db.js","sourceRoot":"","sources":["../../src/manifest/db.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,QAA2C,MAAM,gBAAgB,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpE,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B,6GAA6G;AAC7G,MAAM,UAAU,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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C,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,wCAAwC,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC/E,CAAC;IAED,iDAAiD;IACjD,gBAAgB,CAAC,KAAa;QAC5B,MAAM,aAAa,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;QACtC,aAAa,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QACtC,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE;aAChB,OAAO,CACN,4FAA4F,CAC7F;aACA,GAAG,CAAC,aAAa,CAAC,OAAO,EAAE,CAAsB,CAAC;QACrD,OAAO,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,kEAAkE;IAClE,cAAc,CAAC,aAAqB;QAOlC,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE;aAChB,OAAO,CACN;;;;;qDAK6C,CAC9C;aACA,GAAG,CAAC,aAAa,CAKnB,CAAC;QAEF,MAAM,OAAO,GAAG,IAAI,CAAC,EAAE;aACpB,OAAO,CACN;uDAC+C,CAChD;aACA,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAsB,CAAC;QAE1E,OAAO;YACL,SAAS,EAAE,GAAG,CAAC,UAAU;YACzB,iBAAiB,EAAE,GAAG,CAAC,YAAY;YACnC,mBAAmB,EAAE,GAAG,CAAC,cAAc;YACvC,eAAe,EAAE,GAAG,CAAC,UAAU;YAC/B,iBAAiB,EAAE,OAAO,CAAC,KAAK;SACjC,CAAC;IACJ,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;GAEG;AA2CH,wBAAsB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CA8F/C"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;GAEG;AA2CH,wBAAsB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAsG/C"}
package/dist/server.js CHANGED
@@ -34,6 +34,13 @@ const SERVER_VERSION = (() => {
34
34
  export async function runServer() {
35
35
  const config = loadConfig();
36
36
  logger.info(`starting ${SERVER_NAME} v${SERVER_VERSION} (auth: ${config.auth.source}, key: ${config.auth.keyFingerprint}, default model: ${config.defaultModel})`);
37
+ // Preflight every tool's input schema before we accept a single request.
38
+ // If a tool has a malformed Zod schema (non-object root, etc.) we'd rather
39
+ // crash here with a clear message than register a half-broken MCP endpoint
40
+ // that appears healthy but rejects tool lookups on the client side.
41
+ for (const tool of TOOLS) {
42
+ buildToolInputSchema(tool);
43
+ }
37
44
  const manifest = new ManifestDb();
38
45
  const client = createGeminiClient(config.auth.profile);
39
46
  const ttlWatcher = new TtlWatcher(client, manifest);
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EACL,qBAAqB,EAErB,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAGL,oBAAoB,EACpB,WAAW,GACZ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,M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OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC;IAEF,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE;QAC1B,KAAK,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;QAC3B,KAAK,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC,CAAC,CAAC;IAEH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,CAAC,IAAI,CAAC,8BAA8B,CAAC,CAAC;AAC9C,CAAC"}
@@ -7,13 +7,15 @@
7
7
  */
8
8
  import { z } from 'zod';
9
9
  import { type ToolDefinition } from './registry.js';
10
- export declare const askInputSchema: z.ZodObject<{
10
+ export declare const askInputSchema: z.ZodEffects<z.ZodObject<{
11
11
  prompt: z.ZodString;
12
12
  workspace: z.ZodOptional<z.ZodString>;
13
13
  model: z.ZodOptional<z.ZodString>;
14
14
  includeGlobs: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
15
15
  excludeGlobs: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
16
16
  noCache: z.ZodOptional<z.ZodBoolean>;
17
+ thinkingBudget: z.ZodOptional<z.ZodNumber>;
18
+ thinkingLevel: z.ZodOptional<z.ZodEnum<["MINIMAL", "LOW", "MEDIUM", "HIGH"]>>;
17
19
  }, "strip", z.ZodTypeAny, {
18
20
  prompt: string;
19
21
  model?: string | undefined;
@@ -21,6 +23,8 @@ export declare const askInputSchema: z.ZodObject<{
21
23
  includeGlobs?: string[] | undefined;
22
24
  excludeGlobs?: string[] | undefined;
23
25
  noCache?: boolean | undefined;
26
+ thinkingBudget?: number | undefined;
27
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
24
28
  }, {
25
29
  prompt: string;
26
30
  model?: string | undefined;
@@ -28,6 +32,26 @@ export declare const askInputSchema: z.ZodObject<{
28
32
  includeGlobs?: string[] | undefined;
29
33
  excludeGlobs?: string[] | undefined;
30
34
  noCache?: boolean | undefined;
35
+ thinkingBudget?: number | undefined;
36
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
37
+ }>, {
38
+ prompt: string;
39
+ model?: string | undefined;
40
+ workspace?: string | undefined;
41
+ includeGlobs?: string[] | undefined;
42
+ excludeGlobs?: string[] | undefined;
43
+ noCache?: boolean | undefined;
44
+ thinkingBudget?: number | undefined;
45
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
46
+ }, {
47
+ prompt: string;
48
+ model?: string | undefined;
49
+ workspace?: string | undefined;
50
+ includeGlobs?: string[] | undefined;
51
+ excludeGlobs?: string[] | undefined;
52
+ noCache?: boolean | undefined;
53
+ thinkingBudget?: number | undefined;
54
+ thinkingLevel?: "MINIMAL" | "LOW" | "MEDIUM" | "HIGH" | undefined;
31
55
  }>;
32
56
  export type AskInput = z.infer<typeof askInputSchema>;
33
57
  export declare const askTool: ToolDefinition<AskInput>;
@@ -1 +1 @@
1
- {"version":3,"file":"ask.tool.d.ts","sourceRoot":"","sources":["../../src/tools/ask.tool.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAWxB,OAAO,EAAE,KAAK,cAAc,EAA2B,MAAM,eAAe,CAAC;AAK7E,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;EAqBzB,CAAC;AAEH,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD,eAAO,MAAM,OAAO,EAAE,cAAc,CAAC,QAAQ,CA6M5C,CAAC"}
1
+ {"version":3,"file":"ask.tool.d.ts","sourceRoot":"","sources":["../../src/tools/ask.tool.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAWxB,OAAO,EAAE,KAAK,cAAc,EAA2B,MAAM,eAAe,CAAC;AAmC7E,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8CvB,CAAC;AAEL,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD,eAAO,MAAM,OAAO,EAAE,cAAc,CAAC,QAAQ,CA0Z5C,CAAC"}
@@ -8,15 +8,44 @@
8
8
  import { createHash } from 'node:crypto';
9
9
  import { resolve } from 'node:path';
10
10
  import { z } from 'zod';
11
- import { invalidateWorkspaceCache, isStaleCacheError, prepareContext, } from '../cache/cache-manager.js';
11
+ import { isStaleCacheError, markCacheStale, prepareContext } from '../cache/cache-manager.js';
12
12
  import { resolveModel } from '../gemini/models.js';
13
13
  import { scanWorkspace } from '../indexer/workspace-scanner.js';
14
- import { estimateCostUsd, toMicrosUsd } from '../utils/cost-estimator.js';
14
+ import { WorkspaceValidationError, validateWorkspacePath, } from '../indexer/workspace-validation.js';
15
+ import { estimateCostUsd, estimatePreCallCostUsd, toMicrosUsd } from '../utils/cost-estimator.js';
15
16
  import { logger } from '../utils/logger.js';
16
17
  import { createProgressEmitter } from '../utils/progress.js';
17
18
  import { errorResult, textResult } from './registry.js';
19
+ import { THINKING_LEVELS, THINKING_LEVEL_RESERVE } from './shared/thinking.js';
18
20
  const SYSTEM_INSTRUCTION_Q_AND_A = 'You are a senior software engineer analysing a codebase. Be precise, reference specific file paths and line numbers, and cite evidence from the provided files rather than guessing. If the answer is not derivable from the context, say so.';
19
- export const askInputSchema = z.object({
21
+ /**
22
+ * Hard cap on Gemini's response size for `ask`. Used both as the
23
+ * `maxOutputTokens` field on the generateContent config (so the model
24
+ * actually stops there) and as the `expectedOutputTokens` value passed to
25
+ * `estimatePreCallCostUsd` for the budget reservation. Coupling them is
26
+ * the point: the reservation becomes a true upper bound, not a guess that
27
+ * can be exceeded silently. Q&A answers rarely need more than ~8k tokens;
28
+ * if the resolved model advertises a smaller limit, we use that instead.
29
+ */
30
+ const ASK_MAX_OUTPUT_TOKENS_DEFAULT = 8192;
31
+ /**
32
+ * Sentinel value in our internal normalisation for "user did not pass
33
+ * thinkingBudget". We translate this into an OMITTED `thinkingBudget`
34
+ * field on the wire — Gemini then uses each model's native default, which
35
+ * per Google's Gemini 3 guide (https://ai.google.dev/gemini-api/docs/gemini-3)
36
+ * is HIGH-dynamic on Gemini 3 Pro. Google flags explicit `thinkingBudget`
37
+ * as the "legacy" path on Gemini 3 ("may result in unexpected performance"),
38
+ * and we empirically observed Gemini 3 Pro hanging on low positive budgets
39
+ * with cached content active (see docs/KNOWN-DEFICITS.md). Omitting the
40
+ * field sidesteps both issues while still letting power users opt into
41
+ * explicit budgets on Gemini 2.5 or for cost-bounded deep-dives.
42
+ */
43
+ const THINKING_BUDGET_MODEL_DEFAULT = null;
44
+ // `THINKING_LEVELS` + `THINKING_LEVEL_RESERVE` live in `./shared/thinking.ts`
45
+ // so both `ask` and `code` share a single source of truth — when Google
46
+ // publishes per-tier token budgets, one edit propagates to both tools.
47
+ export const askInputSchema = z
48
+ .object({
20
49
  prompt: z.string().min(1).describe('The question or analysis request.'),
21
50
  workspace: z
22
51
  .string()
@@ -35,6 +64,25 @@ export const askInputSchema = z.object({
35
64
  .boolean()
36
65
  .optional()
37
66
  .describe('Skip the context cache and embed files inline (slower, more expensive).'),
67
+ thinkingBudget: z
68
+ .number()
69
+ .int()
70
+ .min(-1)
71
+ .max(65_536)
72
+ .optional()
73
+ .describe("Explicit reasoning-token cap. OMIT to use each model's native default — recommended on Gemini 3 (Google flags explicit `thinkingBudget` as 'legacy'). Pass a value only when you need a specific cap: `-1` = legacy dynamic, `0` = disable thinking (rejected by Gemini 3 Pro), positive integer = fixed cap. CAVEAT on Gemini 3 Pro: low positive values (empirically ≤256 with cached content) can cause the API to hang — use `-1` or ≥4096 if you must bound it there. For discrete-tier control on Gemini 3 use `thinkingLevel` instead — the two are mutually exclusive."),
74
+ thinkingLevel: z
75
+ .enum(THINKING_LEVELS)
76
+ .optional()
77
+ .describe("Discrete reasoning tier for Gemini 3 family models — Google's recommended knob on those (ai.google.dev/gemini-api/docs/gemini-3). Values: `MINIMAL` (Flash-Lite only), `LOW`, `MEDIUM`, `HIGH` (Gemini 3 Pro's default). Gemini 2.5 models do NOT support this — use `thinkingBudget` instead. Mutually exclusive with `thinkingBudget`: passing both returns a validation error before we even hit Gemini (Gemini itself also rejects with 400 'cannot use both thinking_level and the legacy thinking_budget parameter')."),
78
+ })
79
+ .refine((data) => !(data.thinkingBudget !== undefined && data.thinkingLevel !== undefined), {
80
+ message: 'Cannot specify both `thinkingBudget` and `thinkingLevel` — they are mutually exclusive. Gemini rejects the combination with 400. Choose one: `thinkingLevel` (recommended for Gemini 3) or `thinkingBudget` (required on Gemini 2.5).',
81
+ // `path: []` (root-level error) reflects that the violation is the
82
+ // RELATION between two fields, not a problem with either field
83
+ // individually. MCP clients that render per-field errors won't
84
+ // misattribute the issue to `thinkingLevel` alone.
85
+ path: [],
38
86
  });
39
87
  export const askTool = {
40
88
  name: 'ask',
@@ -45,15 +93,24 @@ export const askTool = {
45
93
  const started = Date.now();
46
94
  const workspaceRoot = resolve(input.workspace ?? process.cwd());
47
95
  const model = input.model ?? ctx.config.defaultModel;
48
- // Budget cap check.
49
- if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
50
- const spentToday = ctx.manifest.todaysCostMicros(Date.now()) / 1_000_000;
51
- if (spentToday >= ctx.config.dailyBudgetUsd) {
52
- return errorResult(`Daily budget cap reached ($${spentToday.toFixed(4)} ≥ $${ctx.config.dailyBudgetUsd.toFixed(2)}). Calls will resume after UTC midnight, or raise \`GEMINI_DAILY_BUDGET_USD\`.`);
53
- }
54
- }
96
+ let reservationId = null;
55
97
  const emitter = createProgressEmitter(ctx.server, ctx.progressToken);
56
98
  try {
99
+ // Workspace path validation lives INSIDE the try so a
100
+ // `WorkspaceValidationError` is reported as a regular tool error
101
+ // (errorResult, "ask failed: …") rather than an unhandled tool
102
+ // exception logged by the server-level handler. Both arrive at the
103
+ // user as text, but only the inside-try path keeps logs tidy and the
104
+ // user-facing prefix consistent with other validation failures.
105
+ try {
106
+ validateWorkspacePath(workspaceRoot);
107
+ }
108
+ catch (err) {
109
+ if (err instanceof WorkspaceValidationError) {
110
+ return errorResult(`ask: ${err.message}`);
111
+ }
112
+ throw err;
113
+ }
57
114
  emitter.emit(`resolving model '${model}'…`);
58
115
  const resolved = await resolveModel(model, ctx.client);
59
116
  emitter.emit(`scanning workspace ${workspaceRoot}…`);
@@ -63,6 +120,89 @@ export const askTool = {
63
120
  maxFiles: ctx.config.maxFilesPerWorkspace,
64
121
  maxFileSizeBytes: ctx.config.maxFileSizeBytes,
65
122
  });
123
+ // Hard cap on output tokens: bound the reservation estimate and the
124
+ // actual generateContent request to the same value, so the budget
125
+ // reservation is a TRUE upper bound (Copilot review C6). If the
126
+ // resolved model's advertised limit is smaller than our default,
127
+ // honour that — Gemini would clamp it anyway.
128
+ const maxOutputTokens = typeof resolved.outputTokenLimit === 'number' && resolved.outputTokenLimit > 0
129
+ ? Math.min(ASK_MAX_OUTPUT_TOKENS_DEFAULT, resolved.outputTokenLimit)
130
+ : ASK_MAX_OUTPUT_TOKENS_DEFAULT;
131
+ // Single source of truth for "is the caller driving reasoning via the
132
+ // discrete-tier knob?". Three downstream call sites branch on this
133
+ // (cost estimate, emitter, thinkingConfig build) — extracting to a
134
+ // named const keeps them in lockstep and makes future additions hard
135
+ // to forget.
136
+ const usingThinkingLevel = input.thinkingLevel !== undefined;
137
+ // Normalise thinkingBudget:
138
+ // undefined → null (model-default path — `thinkingBudget` OMITTED on wire)
139
+ // -1 → -1 (explicit legacy dynamic; kept for Gemini 2.5 and
140
+ // power-users who want to force the legacy path)
141
+ // 0 → 0 (thinking disabled; Gemini 3 Pro will 400 here)
142
+ // N > 0 → clamp to [0, maxOutputTokens - 1024] — the thinking
143
+ // pool is carved out of the candidate-output allowance,
144
+ // so reserving ≥1024 tokens for the answer prevents 400s
145
+ // when a caller passes N ≥ maxOutputTokens.
146
+ //
147
+ // Schema `.refine()` guarantees `thinkingBudget` and `thinkingLevel`
148
+ // are never both set, so we handle them in two mutually-exclusive
149
+ // branches below.
150
+ const rawThinkingBudget = input.thinkingBudget;
151
+ const effectiveThinkingBudget = rawThinkingBudget === undefined
152
+ ? THINKING_BUDGET_MODEL_DEFAULT
153
+ : rawThinkingBudget === -1
154
+ ? -1
155
+ : rawThinkingBudget > 0
156
+ ? Math.max(0, Math.min(rawThinkingBudget, maxOutputTokens - 1024))
157
+ : 0;
158
+ // Cost-estimate thinking-token reserve — tier-aware when the caller
159
+ // uses `thinkingLevel`, worst-case when they use `thinkingBudget: -1`
160
+ // or omit both fields (Gemini 3 Pro always spends thinking tokens per
161
+ // Google's docs, so we reserve dynamic-thinking headroom there too).
162
+ // When the caller passes an explicit positive `thinkingBudget`, we
163
+ // reserve only that much. Keeps `GEMINI_DAILY_BUDGET_USD` a TRUE
164
+ // upper bound on completed spend without false-rejecting callers
165
+ // who legitimately use a low tier (see `THINKING_LEVEL_RESERVE`
166
+ // rationale above).
167
+ //
168
+ // We dereference `input.thinkingLevel` directly (rather than via
169
+ // `usingThinkingLevel`) so TypeScript narrows the type inside the
170
+ // ternary — `THINKING_LEVEL_RESERVE[undefined]` would be a compile
171
+ // error. The `?? worst-case` fallback handles the HIGH tier (which
172
+ // maps to `null` in the reserve table to mean "use the dynamic cap").
173
+ const thinkingTokensForEstimate = input.thinkingLevel !== undefined
174
+ ? (THINKING_LEVEL_RESERVE[input.thinkingLevel] ?? Math.max(0, maxOutputTokens - 1024))
175
+ : effectiveThinkingBudget === null || effectiveThinkingBudget === -1
176
+ ? Math.max(0, maxOutputTokens - 1024)
177
+ : effectiveThinkingBudget;
178
+ // Atomic budget reservation. Happens AFTER scan (so the estimate is
179
+ // accurate) but BEFORE any billable upload or generateContent call.
180
+ // Concurrent tool calls cannot all pass a pre-check and then
181
+ // collectively overshoot the cap: `reserveBudget` uses a
182
+ // `BEGIN IMMEDIATE` SQLite transaction that serialises check-and-insert.
183
+ if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
184
+ const workspaceBytes = scan.files.reduce((sum, f) => sum + f.size, 0);
185
+ const estimateUsd = estimatePreCallCostUsd({
186
+ model: resolved.resolved,
187
+ workspaceBytes,
188
+ promptChars: input.prompt.length,
189
+ expectedOutputTokens: maxOutputTokens,
190
+ thinkingTokens: thinkingTokensForEstimate,
191
+ });
192
+ const reserve = ctx.manifest.reserveBudget({
193
+ workspaceRoot,
194
+ toolName: 'ask',
195
+ model: resolved.resolved,
196
+ estimatedCostMicros: toMicrosUsd(estimateUsd),
197
+ dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
198
+ nowMs: Date.now(),
199
+ });
200
+ if ('rejected' in reserve) {
201
+ const spentUsd = reserve.spentMicros / 1_000_000;
202
+ return errorResult(`Daily budget cap would be exceeded: spent $${spentUsd.toFixed(4)} + estimate $${estimateUsd.toFixed(4)} > cap $${ctx.config.dailyBudgetUsd.toFixed(2)}. Retry after UTC midnight, or raise \`GEMINI_DAILY_BUDGET_USD\`.`);
203
+ }
204
+ reservationId = reserve.id;
205
+ }
66
206
  const systemPromptHash = createHash('sha256')
67
207
  .update(SYSTEM_INSTRUCTION_Q_AND_A)
68
208
  .digest('hex')
@@ -79,14 +219,60 @@ export const askTool = {
79
219
  emitter,
80
220
  allowCaching: !input.noCache && scan.files.length > 0,
81
221
  });
82
- emitter.emit('generating response…');
222
+ emitter.emit(usingThinkingLevel
223
+ ? `generating response (thinking-level=${input.thinkingLevel})…`
224
+ : effectiveThinkingBudget === null
225
+ ? 'generating response (thinking=model-default)…'
226
+ : effectiveThinkingBudget === -1
227
+ ? 'generating response (thinking=dynamic)…'
228
+ : `generating response (thinking=${effectiveThinkingBudget})…`);
83
229
  // Gemini rejects `generateContent({cachedContent, systemInstruction})` with 400:
84
230
  // "CachedContent can not be used with GenerateContent request setting
85
231
  // system_instruction, tools or tool_config. Move those values to CachedContent."
86
232
  // The system instruction was already baked into the cache at build time
87
233
  // (see cache-manager.ts:322 `cacheConfig.systemInstruction`), so we must
88
234
  // OMIT it on the generate call when a cached context is active.
89
- const buildConfig = (cacheId) => cacheId ? { cachedContent: cacheId } : { systemInstruction: SYSTEM_INSTRUCTION_Q_AND_A };
235
+ // `thinkingConfig` is NOT one of the forbidden fields — it is a
236
+ // per-request reasoning control and travels with every call regardless
237
+ // of cache state. We always set `includeThoughts: true` so callers see
238
+ // Gemini's reasoning digest in the response.
239
+ //
240
+ // Three mutually-exclusive reasoning-control paths (enforced by
241
+ // schema `.refine()`):
242
+ // a) `thinkingLevel` set → pass it through to the SDK enum. Google's
243
+ // recommended path on Gemini 3. Rejected by Gemini 2.5 family.
244
+ // b) `thinkingBudget` set (non-null after normalisation) → legacy
245
+ // budget path. Required on Gemini 2.5; flagged as "legacy" on
246
+ // Gemini 3 but still supported.
247
+ // c) neither set → omit both fields, keep only `includeThoughts`.
248
+ // Model uses its native default (HIGH-dynamic on Gemini 3 Pro).
249
+ //
250
+ // `maxOutputTokens` is set on every generateContent call so the budget
251
+ // reservation's `expectedOutputTokens` (derived from the same value) is
252
+ // a true upper bound — without this cap, a runaway response could
253
+ // exceed the reserved estimate and silently overshoot `dailyBudgetUsd`.
254
+ // Cast to `ThinkingLevel` rather than indexing the runtime enum object
255
+ // (`ThinkingLevel[input.thinkingLevel]`). For string enums the value
256
+ // IS the member name, so passing `"HIGH"` as `ThinkingLevel` is
257
+ // semantically identical at runtime — but it survives SDK renames:
258
+ // if a future `@google/genai` release renames a member, the literal
259
+ // string reaches Gemini's wire, which 400s with a clear message
260
+ // instead of silently becoming `undefined` at the indexing step.
261
+ const thinkingConfig = usingThinkingLevel
262
+ ? {
263
+ thinkingLevel: input.thinkingLevel,
264
+ includeThoughts: true,
265
+ }
266
+ : effectiveThinkingBudget === null
267
+ ? { includeThoughts: true }
268
+ : { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
269
+ const buildConfig = (cacheId) => cacheId
270
+ ? { cachedContent: cacheId, thinkingConfig, maxOutputTokens }
271
+ : {
272
+ systemInstruction: SYSTEM_INSTRUCTION_Q_AND_A,
273
+ thinkingConfig,
274
+ maxOutputTokens,
275
+ };
90
276
  const buildContents = (cacheId, inline) => cacheId ? input.prompt : [...inline, { role: 'user', parts: [{ text: input.prompt }] }];
91
277
  // Track the prepared-context used for the FINAL successful call. Starts
92
278
  // pointing at the initial ctxPrep; retry branch below reassigns to the
@@ -110,11 +296,11 @@ export const askTool = {
110
296
  if (activePrep.cacheId && isStaleCacheError(err)) {
111
297
  logger.warn(`Gemini rejected cached content ${activePrep.cacheId}; invalidating and retrying once.`);
112
298
  try {
113
- await invalidateWorkspaceCache({
114
- client: ctx.client,
115
- manifest: ctx.manifest,
116
- workspaceRoot,
117
- });
299
+ // Reset the cache pointer only — keep `files` rows so the rebuild
300
+ // can reuse uploaded files via content-hash dedup instead of
301
+ // re-uploading. The Gemini-side cache is already dead (that's
302
+ // what triggered this branch), so no `caches.delete` needed.
303
+ markCacheStale({ manifest: ctx.manifest, workspaceRoot });
118
304
  const rebuilt = await prepareContext({
119
305
  client: ctx.client,
120
306
  manifest: ctx.manifest,
@@ -150,6 +336,20 @@ export const askTool = {
150
336
  ctx.ttlWatcher.markHot(workspaceRoot, activePrep.cacheId, ctx.config.cacheTtlSeconds);
151
337
  }
152
338
  const text = response.text ?? '';
339
+ // Extract Gemini's thinking summary when `includeThoughts: true` is set.
340
+ // Parts flagged `thought: true` carry the model's internal reasoning
341
+ // digest — useful for the caller to see *why* an answer was given.
342
+ // We cap the joined summary at 1200 chars so it never dominates the
343
+ // MCP response payload (matches `code.tool.ts` behaviour).
344
+ const thoughtTexts = [];
345
+ for (const cand of response.candidates ?? []) {
346
+ for (const part of cand.content?.parts ?? []) {
347
+ if (part.thought === true && typeof part.text === 'string') {
348
+ thoughtTexts.push(part.text);
349
+ }
350
+ }
351
+ }
352
+ const thinkingSummary = thoughtTexts.length > 0 ? thoughtTexts.join('\n').slice(0, 1200) : null;
153
353
  const usage = response.usageMetadata;
154
354
  const cached = typeof usage?.cachedContentTokenCount === 'number' ? usage.cachedContentTokenCount : 0;
155
355
  const inputTotal = typeof usage?.promptTokenCount === 'number' ? usage.promptTokenCount : 0;
@@ -165,16 +365,39 @@ export const askTool = {
165
365
  });
166
366
  const costMicros = toMicrosUsd(cost);
167
367
  const durationMs = Date.now() - started;
168
- ctx.manifest.insertUsageMetric({
169
- workspaceRoot,
170
- toolName: 'ask',
171
- model: resolved.resolved,
172
- cachedTokens: cached,
173
- uncachedTokens: uncached,
174
- costUsdMicro: costMicros,
175
- durationMs,
176
- occurredAt: Date.now(),
177
- });
368
+ if (reservationId !== null) {
369
+ // The finalize UPDATE on a row we just inserted should be infallible
370
+ // in practice, but a disk-full / lock-contention edge could throw.
371
+ // If it does, we'd rather keep the reservation row (estimate stays
372
+ // billed, slight overcharge) than let the outer catch CANCEL it
373
+ // — cancelling would erase any record of this billable, completed
374
+ // call. Either way, drop `reservationId` so the outer catch doesn't
375
+ // touch it.
376
+ try {
377
+ ctx.manifest.finalizeBudgetReservation(reservationId, {
378
+ cachedTokens: cached,
379
+ uncachedTokens: uncached,
380
+ costUsdMicro: costMicros,
381
+ durationMs,
382
+ });
383
+ }
384
+ catch (finalizeErr) {
385
+ logger.error(`ask: finalizeBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate (${costMicros} micros). Error: ${String(finalizeErr)}`);
386
+ }
387
+ reservationId = null;
388
+ }
389
+ else {
390
+ ctx.manifest.insertUsageMetric({
391
+ workspaceRoot,
392
+ toolName: 'ask',
393
+ model: resolved.resolved,
394
+ cachedTokens: cached,
395
+ uncachedTokens: uncached,
396
+ costUsdMicro: costMicros,
397
+ durationMs,
398
+ occurredAt: Date.now(),
399
+ });
400
+ }
178
401
  if (scan.truncated) {
179
402
  logger.warn(`workspace ${workspaceRoot} contains more files than GEMINI_CODE_CONTEXT_MAX_FILES (${ctx.config.maxFilesPerWorkspace}); the tail was dropped before indexing.`);
180
403
  }
@@ -183,6 +406,8 @@ export const askTool = {
183
406
  requestedModel: resolved.requested,
184
407
  fallbackApplied: resolved.fallbackApplied,
185
408
  contextWindow: resolved.inputTokenLimit,
409
+ thinkingBudget: effectiveThinkingBudget,
410
+ thinkingLevel: input.thinkingLevel ?? null,
186
411
  cachedTokens: cached,
187
412
  uncachedTokens: uncached,
188
413
  outputTokens: output,
@@ -201,11 +426,26 @@ export const askTool = {
201
426
  workspaceTruncated: scan.truncated,
202
427
  maxFilesCap: ctx.config.maxFilesPerWorkspace,
203
428
  durationMs,
429
+ ...(thinkingSummary ? { thinkingSummary } : {}),
204
430
  };
205
431
  return textResult(text, metadata);
206
432
  }
207
433
  catch (err) {
208
434
  logger.error(`ask failed: ${String(err)}`);
435
+ // Release any unconsumed budget reservation so the failed call's
436
+ // estimate doesn't eat into future headroom for today. Wrap in its
437
+ // own try/catch — better-sqlite3 can throw SQLITE_BUSY or I/O errors
438
+ // and we must not let a rollback-time DB failure replace the real
439
+ // tool error the user is waiting on.
440
+ if (reservationId !== null) {
441
+ try {
442
+ ctx.manifest.cancelBudgetReservation(reservationId);
443
+ }
444
+ catch (cancelErr) {
445
+ logger.error(`ask: cancelBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate. Error: ${String(cancelErr)}`);
446
+ }
447
+ reservationId = null;
448
+ }
209
449
  return errorResult(`ask failed: ${err instanceof Error ? err.message : String(err)}`);
210
450
  }
211
451
  finally {