@qmediat.io/gemini-code-context-mcp 1.4.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +26 -3
  3. package/dist/config.d.ts +23 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +9 -0
  6. package/dist/config.js.map +1 -1
  7. package/dist/gemini/client.d.ts.map +1 -1
  8. package/dist/gemini/client.js +11 -0
  9. package/dist/gemini/client.js.map +1 -1
  10. package/dist/gemini/retry.d.ts +63 -0
  11. package/dist/gemini/retry.d.ts.map +1 -0
  12. package/dist/gemini/retry.js +103 -0
  13. package/dist/gemini/retry.js.map +1 -0
  14. package/dist/indexer/globs.d.ts +106 -0
  15. package/dist/indexer/globs.d.ts.map +1 -1
  16. package/dist/indexer/globs.js +151 -11
  17. package/dist/indexer/globs.js.map +1 -1
  18. package/dist/tools/agentic/sandbox.d.ts +55 -0
  19. package/dist/tools/agentic/sandbox.d.ts.map +1 -0
  20. package/dist/tools/agentic/sandbox.js +272 -0
  21. package/dist/tools/agentic/sandbox.js.map +1 -0
  22. package/dist/tools/agentic/workspace-tools.d.ts +104 -0
  23. package/dist/tools/agentic/workspace-tools.d.ts.map +1 -0
  24. package/dist/tools/agentic/workspace-tools.js +518 -0
  25. package/dist/tools/agentic/workspace-tools.js.map +1 -0
  26. package/dist/tools/ask-agentic.tool.d.ts +85 -0
  27. package/dist/tools/ask-agentic.tool.d.ts.map +1 -0
  28. package/dist/tools/ask-agentic.tool.js +739 -0
  29. package/dist/tools/ask-agentic.tool.js.map +1 -0
  30. package/dist/tools/ask.tool.d.ts +12 -12
  31. package/dist/tools/ask.tool.d.ts.map +1 -1
  32. package/dist/tools/ask.tool.js +537 -477
  33. package/dist/tools/ask.tool.js.map +1 -1
  34. package/dist/tools/code.tool.d.ts +8 -8
  35. package/dist/tools/code.tool.d.ts.map +1 -1
  36. package/dist/tools/code.tool.js +472 -423
  37. package/dist/tools/code.tool.js.map +1 -1
  38. package/dist/tools/index.d.ts.map +1 -1
  39. package/dist/tools/index.js +2 -0
  40. package/dist/tools/index.js.map +1 -1
  41. package/dist/tools/registry.d.ts +1 -1
  42. package/dist/tools/registry.d.ts.map +1 -1
  43. package/dist/tools/registry.js +8 -2
  44. package/dist/tools/registry.js.map +1 -1
  45. package/package.json +2 -2
@@ -12,6 +12,7 @@ import { resolve } from 'node:path';
12
12
  import { z } from 'zod';
13
13
  import { isStaleCacheError, markCacheStale, prepareContext } from '../cache/cache-manager.js';
14
14
  import { resolveModel } from '../gemini/models.js';
15
+ import { withNetworkRetry } from '../gemini/retry.js';
15
16
  import { scanWorkspace } from '../indexer/workspace-scanner.js';
16
17
  import { WorkspaceValidationError, validateWorkspacePath, } from '../indexer/workspace-validation.js';
17
18
  import { estimateCostUsd, estimatePreCallCostUsd, toMicrosUsd } from '../utils/cost-estimator.js';
@@ -75,8 +76,14 @@ export const codeInputSchema = z
75
76
  .min(1)
76
77
  .optional()
77
78
  .describe("Per-call opt-in cap on response length (tokens). OMIT for auto — Gemini uses its model-default cap (per Google docs, equal to the model's advertised `outputTokenLimit`: 65,536 for Gemini 3.x / 2.5 Pro-tier; see ai.google.dev/gemini-api/docs/models/gemini-2.5-pro). Pass a smaller value to bound a specific call (e.g. `maxOutputTokens: 16384` for a tight code-review summary). Values larger than the resolved model's limit are clamped. Operators who want EVERY call at full model capacity set `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true` at MCP-host level — that env override is still beaten by this per-call field."),
78
- includeGlobs: z.array(z.string()).optional(),
79
- excludeGlobs: z.array(z.string()).optional(),
79
+ includeGlobs: z
80
+ .array(z.string())
81
+ .optional()
82
+ .describe('Additional file extensions or filenames to include.'),
83
+ excludeGlobs: z
84
+ .array(z.string())
85
+ .optional()
86
+ .describe('Additional patterns to exclude. Supports three shapes: (1) directory names or path prefixes (`node_modules`, `src/vendor`, `./dist/`, `.vercel/`), (2) literal filenames exact-match, including bare dot-prefixed names (`pr27-diff.txt`, `foo.bar.baz`, `.env`, `.map`, `.tsbuildinfo`), (3) extension globs that match via endsWith (`*.tsbuildinfo`, `*.map`). Bare dot-prefixed names like `.env` are treated as exact filename literals — write `*.env` for extension semantics. Paths are POSIX-normalised (backslashes → `/`, leading `./` and trailing `/` stripped). Case-insensitive. No mid-string `*` / `**` / `?` — split into dir + extension patterns if needed.'),
80
87
  })
81
88
  .refine((data) => !(data.thinkingBudget !== undefined && data.thinkingLevel !== undefined), {
82
89
  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).',
@@ -125,461 +132,503 @@ export const codeTool = {
125
132
  async execute(input, ctx) {
126
133
  const started = Date.now();
127
134
  const workspaceRoot = resolve(input.workspace ?? process.cwd());
128
- const modelRequest = input.model ?? 'latest-pro-thinking';
129
- const expectEdits = input.expectEdits ?? true;
130
- const codeExecution = input.codeExecution ?? false;
131
- // Schema `.refine()` guarantees `thinkingBudget` and `thinkingLevel` are
132
- // never both set. `usingThinkingLevel` is a single source of truth for
133
- // the "is the caller driving reasoning via the discrete-tier knob?"
134
- // predicate — used by the cost estimate, the emitter message, and the
135
- // thinkingConfig shape below.
136
- const usingThinkingLevel = input.thinkingLevel !== undefined;
137
- // `code` keeps its pre-existing default of 16_384 for the `thinkingBudget`
138
- // path (strong reasoning for coding out of the box — coding tasks
139
- // genuinely benefit from it and callers rarely want to disable thinking).
140
- // When the caller uses `thinkingLevel` instead, `thinkingBudget` stays
141
- // undefined and we take the level branch below.
142
- const thinkingBudget = usingThinkingLevel ? undefined : (input.thinkingBudget ?? 16_384);
143
- let reservationId = null;
144
- // `-1` signals "no reservation held". Mirror of ask.tool.ts.
145
- let throttleReservationId = -1;
146
- // Canonical resolved-model string for retry-hint seeding (T22a).
147
- // See ask.tool.ts for rationale.
148
- let resolvedModelKey = null;
149
- const emitter = createProgressEmitter(ctx.server, ctx.progressToken);
135
+ return executeCodeBody(input, ctx, workspaceRoot, started);
136
+ },
137
+ };
138
+ async function executeCodeBody(input, ctx, workspaceRoot, started) {
139
+ const modelRequest = input.model ?? 'latest-pro-thinking';
140
+ const expectEdits = input.expectEdits ?? true;
141
+ const codeExecution = input.codeExecution ?? false;
142
+ // Schema `.refine()` guarantees `thinkingBudget` and `thinkingLevel` are
143
+ // never both set. `usingThinkingLevel` is a single source of truth for
144
+ // the "is the caller driving reasoning via the discrete-tier knob?"
145
+ // predicate — used by the cost estimate, the emitter message, and the
146
+ // thinkingConfig shape below.
147
+ const usingThinkingLevel = input.thinkingLevel !== undefined;
148
+ // `code` keeps its pre-existing default of 16_384 for the `thinkingBudget`
149
+ // path (strong reasoning for coding out of the box — coding tasks
150
+ // genuinely benefit from it and callers rarely want to disable thinking).
151
+ // When the caller uses `thinkingLevel` instead, `thinkingBudget` stays
152
+ // undefined and we take the level branch below.
153
+ const thinkingBudget = usingThinkingLevel ? undefined : (input.thinkingBudget ?? 16_384);
154
+ let reservationId = null;
155
+ // `-1` signals "no reservation held". Mirror of ask.tool.ts.
156
+ let throttleReservationId = -1;
157
+ // Canonical resolved-model string for retry-hint seeding (T22a).
158
+ // See ask.tool.ts for rationale.
159
+ let resolvedModelKey = null;
160
+ const emitter = createProgressEmitter(ctx.server, ctx.progressToken);
161
+ try {
162
+ // Workspace validation inside try → reported as a regular tool error
163
+ // (errorResult, "code failed: …") rather than an unhandled exception
164
+ // surfaced by the server-level handler.
150
165
  try {
151
- // Workspace validation inside try → reported as a regular tool error
152
- // (errorResult, "code failed: …") rather than an unhandled exception
153
- // surfaced by the server-level handler.
154
- try {
155
- validateWorkspacePath(workspaceRoot);
166
+ validateWorkspacePath(workspaceRoot);
167
+ }
168
+ catch (err) {
169
+ if (err instanceof WorkspaceValidationError) {
170
+ return errorResult(`code: ${err.message}`);
156
171
  }
157
- catch (err) {
158
- if (err instanceof WorkspaceValidationError) {
159
- return errorResult(`code: ${err.message}`);
160
- }
161
- throw err;
172
+ throw err;
173
+ }
174
+ emitter.emit(`resolving model '${modelRequest}'…`);
175
+ // `code` is strictly text-reasoning — coding tasks genuinely benefit
176
+ // from reasoning tokens, and dispatching to fast/lite tiers would
177
+ // degrade output quality without meaningful cost savings. Crucially:
178
+ // this category gate prevents image-gen / audio-gen / agent models
179
+ // (which may share `pro` tokens with text models in Google's registry)
180
+ // from reaching `generateContent` with a code-review prompt — the
181
+ // primary motivation for the v1.4.0 taxonomy work.
182
+ const resolved = await resolveModel(modelRequest, ctx.client, {
183
+ requiredCategory: ['text-reasoning'],
184
+ });
185
+ resolvedModelKey = resolved.resolved;
186
+ emitter.emit(`scanning workspace ${workspaceRoot}…`);
187
+ const scan = await scanWorkspace(workspaceRoot, {
188
+ ...(input.includeGlobs !== undefined ? { includeGlobs: input.includeGlobs } : {}),
189
+ ...(input.excludeGlobs !== undefined ? { excludeGlobs: input.excludeGlobs } : {}),
190
+ maxFiles: ctx.config.maxFilesPerWorkspace,
191
+ maxFileSizeBytes: ctx.config.maxFileSizeBytes,
192
+ });
193
+ // Output-cap strategy (v1.4.0) — see ask.tool.ts for full rationale
194
+ // of the three-layer precedence. Summary: input.maxOutputTokens
195
+ // (per-call) > ctx.config.forceMaxOutputTokens (MCP-host env) >
196
+ // auto (omit from wire; Gemini uses model-default). Code review
197
+ // commonly produces long OLD/NEW diff blocks, so operators doing
198
+ // heavy review work set `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true`
199
+ // to pin every call at the model's full 65,536-token capacity.
200
+ const CODE_MAX_OUTPUT_TOKENS_FALLBACK = 65_536;
201
+ const modelOutputLimit = typeof resolved.outputTokenLimit === 'number' && resolved.outputTokenLimit > 0
202
+ ? resolved.outputTokenLimit
203
+ : CODE_MAX_OUTPUT_TOKENS_FALLBACK;
204
+ const wireMaxOutputTokens = input.maxOutputTokens !== undefined
205
+ ? Math.min(input.maxOutputTokens, modelOutputLimit)
206
+ : ctx.config.forceMaxOutputTokens
207
+ ? modelOutputLimit
208
+ : undefined;
209
+ // Effective cap for thinking-budget clamp and budget reservation.
210
+ // When auto (neither override set), Gemini's model-default equals
211
+ // modelOutputLimit per Google docs, so using the limit as worst-case
212
+ // keeps the daily $ cap a true upper bound.
213
+ const effectiveOutputCap = wireMaxOutputTokens ?? modelOutputLimit;
214
+ // Gemini requires `thinkingBudget < maxOutputTokens` (the thinking pool
215
+ // is carved out of the candidate-output allowance). The hard cap above
216
+ // may clamp maxOutputTokens as low as the model's `outputTokenLimit`
217
+ // (e.g. 8_192 on Flash-lite). Clamp the effective thinkingBudget so
218
+ // the generateContent call never 400s on this invariant; reserve at
219
+ // least 1_024 tokens for the actual completion.
220
+ //
221
+ // Only meaningful on the thinkingBudget path — when the caller uses
222
+ // `thinkingLevel` instead, `thinkingBudget` is `undefined` and this
223
+ // value is ignored by the thinkingConfig builder below.
224
+ //
225
+ // Early-reject when the caller's per-call `maxOutputTokens` can't fit
226
+ // an explicit positive `thinkingBudget` + 1024-token answer reserve.
227
+ // Silently clamping to 0 would make Gemini 3 Pro 400 on a
228
+ // "thinking disabled" error and obscure the real mismatch (PR #22
229
+ // round-3 review finding #C).
230
+ if (input.thinkingBudget !== undefined &&
231
+ input.thinkingBudget > 0 &&
232
+ input.maxOutputTokens !== undefined &&
233
+ effectiveOutputCap < input.thinkingBudget + 1024) {
234
+ return errorResult(`code: thinkingBudget (${input.thinkingBudget}) + 1024-token answer reserve exceeds maxOutputTokens (${effectiveOutputCap}). Raise \`maxOutputTokens\` to at least ${input.thinkingBudget + 1024}, or lower \`thinkingBudget\`.`);
235
+ }
236
+ const effectiveThinkingBudget = thinkingBudget !== undefined && thinkingBudget > 0
237
+ ? Math.max(0, Math.min(thinkingBudget, effectiveOutputCap - 1024))
238
+ : 0;
239
+ // Cost-estimate thinking-token reserve — tier-aware when the caller
240
+ // uses `thinkingLevel`, exact-on-the-budget when they use
241
+ // `thinkingBudget`. Mirror of `ask.tool.ts` logic; see
242
+ // `THINKING_LEVEL_RESERVE` in `shared/thinking.ts` for the rationale
243
+ // behind the per-tier numbers and why HIGH falls through to the
244
+ // dynamic cap.
245
+ //
246
+ // Defensive clamp: tier reserves (MINIMAL=512, LOW=2048, MEDIUM=4096)
247
+ // are fixed constants, but `maxOutputTokens` can be clamped down to a
248
+ // resolved model's `outputTokenLimit`. A future small-cap model (say
249
+ // `outputTokenLimit: 4000`) would let MEDIUM's 4096 exceed the
250
+ // available headroom and over-estimate the budget reservation. Clamp
251
+ // every tier's reserve against the dynamic headroom so the upper
252
+ // bound stays coherent across model rollouts (PR #17 self-review F2).
253
+ const thinkingHeadroom = Math.max(0, effectiveOutputCap - 1024);
254
+ const thinkingTokensForEstimate = input.thinkingLevel !== undefined
255
+ ? Math.min(THINKING_LEVEL_RESERVE[input.thinkingLevel] ?? thinkingHeadroom, thinkingHeadroom)
256
+ : effectiveThinkingBudget;
257
+ // Shared input-token fingerprint for budget + TPM throttle (see
258
+ // ask.tool.ts for the rationale — same `Math.ceil(bytes/4)` tokenisation
259
+ // used by `estimatePreCallCostUsd`).
260
+ const workspaceBytes = scan.files.reduce((sum, f) => sum + f.size, 0);
261
+ const estimatedInputTokens = Math.ceil(workspaceBytes / 4) + Math.ceil(input.task.length / 4);
262
+ // v1.5.0 preflight — mirror of ask.tool.ts guard. See there for rationale.
263
+ const contextWindow = resolved.inputTokenLimit;
264
+ if (typeof contextWindow === 'number' && contextWindow > 0) {
265
+ const threshold = Math.floor(contextWindow * ctx.config.workspaceGuardRatio);
266
+ if (estimatedInputTokens > threshold) {
267
+ const pctDisplay = Math.round(ctx.config.workspaceGuardRatio * 100);
268
+ return errorResult(`Workspace too large for eager \`code\`: ~${estimatedInputTokens.toLocaleString()} input tokens exceeds ${threshold.toLocaleString()} (${pctDisplay}% of ${resolved.resolved}'s ${contextWindow.toLocaleString()} context window). Options: (a) pass \`excludeGlobs\` to filter large/generated files — supports \`*.ext\` patterns, filenames, and directory paths, (b) narrow with \`includeGlobs\`, (c) switch to a larger-context model, (d) split the workspace into subdirectories, or (e) use \`ask_agentic\` for Q&A-style analysis without uploading the repo (\`code\` itself still requires the eager path for its OLD/NEW edit format).`, {
269
+ errorCode: 'WORKSPACE_TOO_LARGE',
270
+ retryable: false,
271
+ estimatedInputTokens,
272
+ contextWindowTokens: contextWindow,
273
+ thresholdTokens: threshold,
274
+ guardRatio: ctx.config.workspaceGuardRatio,
275
+ resolvedModel: resolved.resolved,
276
+ filesIndexed: scan.files.length,
277
+ });
162
278
  }
163
- emitter.emit(`resolving model '${modelRequest}'…`);
164
- // `code` is strictly text-reasoning — coding tasks genuinely benefit
165
- // from reasoning tokens, and dispatching to fast/lite tiers would
166
- // degrade output quality without meaningful cost savings. Crucially:
167
- // this category gate prevents image-gen / audio-gen / agent models
168
- // (which may share `pro` tokens with text models in Google's registry)
169
- // from reaching `generateContent` with a code-review prompt — the
170
- // primary motivation for the v1.4.0 taxonomy work.
171
- const resolved = await resolveModel(modelRequest, ctx.client, {
172
- requiredCategory: ['text-reasoning'],
279
+ }
280
+ else {
281
+ logger.warn(`code: resolved model ${resolved.resolved} has no advertised inputTokenLimit — workspace size guard skipped. Request may fail downstream if the workspace exceeds the model's context window.`);
282
+ }
283
+ // Atomic budget reservation — see ask.tool.ts for the full rationale.
284
+ // Estimate includes the thinking budget (billed as output tokens on Pro)
285
+ // PLUS the candidate output cap.
286
+ if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
287
+ const estimateUsd = estimatePreCallCostUsd({
288
+ model: resolved.resolved,
289
+ workspaceBytes,
290
+ promptChars: input.task.length,
291
+ expectedOutputTokens: effectiveOutputCap,
292
+ thinkingTokens: thinkingTokensForEstimate,
173
293
  });
174
- resolvedModelKey = resolved.resolved;
175
- emitter.emit(`scanning workspace ${workspaceRoot}…`);
176
- const scan = await scanWorkspace(workspaceRoot, {
177
- ...(input.includeGlobs !== undefined ? { includeGlobs: input.includeGlobs } : {}),
178
- ...(input.excludeGlobs !== undefined ? { excludeGlobs: input.excludeGlobs } : {}),
179
- maxFiles: ctx.config.maxFilesPerWorkspace,
180
- maxFileSizeBytes: ctx.config.maxFileSizeBytes,
294
+ const reserve = ctx.manifest.reserveBudget({
295
+ workspaceRoot,
296
+ toolName: 'code',
297
+ model: resolved.resolved,
298
+ estimatedCostMicros: toMicrosUsd(estimateUsd),
299
+ dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
300
+ nowMs: Date.now(),
181
301
  });
182
- // Output-cap strategy (v1.4.0) — see ask.tool.ts for full rationale
183
- // of the three-layer precedence. Summary: input.maxOutputTokens
184
- // (per-call) > ctx.config.forceMaxOutputTokens (MCP-host env) >
185
- // auto (omit from wire; Gemini uses model-default). Code review
186
- // commonly produces long OLD/NEW diff blocks, so operators doing
187
- // heavy review work set `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true`
188
- // to pin every call at the model's full 65,536-token capacity.
189
- const CODE_MAX_OUTPUT_TOKENS_FALLBACK = 65_536;
190
- const modelOutputLimit = typeof resolved.outputTokenLimit === 'number' && resolved.outputTokenLimit > 0
191
- ? resolved.outputTokenLimit
192
- : CODE_MAX_OUTPUT_TOKENS_FALLBACK;
193
- const wireMaxOutputTokens = input.maxOutputTokens !== undefined
194
- ? Math.min(input.maxOutputTokens, modelOutputLimit)
195
- : ctx.config.forceMaxOutputTokens
196
- ? modelOutputLimit
197
- : undefined;
198
- // Effective cap for thinking-budget clamp and budget reservation.
199
- // When auto (neither override set), Gemini's model-default equals
200
- // modelOutputLimit per Google docs, so using the limit as worst-case
201
- // keeps the daily $ cap a true upper bound.
202
- const effectiveOutputCap = wireMaxOutputTokens ?? modelOutputLimit;
203
- // Gemini requires `thinkingBudget < maxOutputTokens` (the thinking pool
204
- // is carved out of the candidate-output allowance). The hard cap above
205
- // may clamp maxOutputTokens as low as the model's `outputTokenLimit`
206
- // (e.g. 8_192 on Flash-lite). Clamp the effective thinkingBudget so
207
- // the generateContent call never 400s on this invariant; reserve at
208
- // least 1_024 tokens for the actual completion.
209
- //
210
- // Only meaningful on the thinkingBudget path — when the caller uses
211
- // `thinkingLevel` instead, `thinkingBudget` is `undefined` and this
212
- // value is ignored by the thinkingConfig builder below.
213
- //
214
- // Early-reject when the caller's per-call `maxOutputTokens` can't fit
215
- // an explicit positive `thinkingBudget` + 1024-token answer reserve.
216
- // Silently clamping to 0 would make Gemini 3 Pro 400 on a
217
- // "thinking disabled" error and obscure the real mismatch (PR #22
218
- // round-3 review finding #C).
219
- if (input.thinkingBudget !== undefined &&
220
- input.thinkingBudget > 0 &&
221
- input.maxOutputTokens !== undefined &&
222
- effectiveOutputCap < input.thinkingBudget + 1024) {
223
- return errorResult(`code: thinkingBudget (${input.thinkingBudget}) + 1024-token answer reserve exceeds maxOutputTokens (${effectiveOutputCap}). Raise \`maxOutputTokens\` to at least ${input.thinkingBudget + 1024}, or lower \`thinkingBudget\`.`);
302
+ if ('rejected' in reserve) {
303
+ const spentUsd = reserve.spentMicros / 1_000_000;
304
+ 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\`.`, { errorCode: 'BUDGET_REJECT', retryable: false });
224
305
  }
225
- const effectiveThinkingBudget = thinkingBudget !== undefined && thinkingBudget > 0
226
- ? Math.max(0, Math.min(thinkingBudget, effectiveOutputCap - 1024))
227
- : 0;
228
- // Cost-estimate thinking-token reserve — tier-aware when the caller
229
- // uses `thinkingLevel`, exact-on-the-budget when they use
230
- // `thinkingBudget`. Mirror of `ask.tool.ts` logic; see
231
- // `THINKING_LEVEL_RESERVE` in `shared/thinking.ts` for the rationale
232
- // behind the per-tier numbers and why HIGH falls through to the
233
- // dynamic cap.
234
- //
235
- // Defensive clamp: tier reserves (MINIMAL=512, LOW=2048, MEDIUM=4096)
236
- // are fixed constants, but `maxOutputTokens` can be clamped down to a
237
- // resolved model's `outputTokenLimit`. A future small-cap model (say
238
- // `outputTokenLimit: 4000`) would let MEDIUM's 4096 exceed the
239
- // available headroom and over-estimate the budget reservation. Clamp
240
- // every tier's reserve against the dynamic headroom so the upper
241
- // bound stays coherent across model rollouts (PR #17 self-review F2).
242
- const thinkingHeadroom = Math.max(0, effectiveOutputCap - 1024);
243
- const thinkingTokensForEstimate = input.thinkingLevel !== undefined
244
- ? Math.min(THINKING_LEVEL_RESERVE[input.thinkingLevel] ?? thinkingHeadroom, thinkingHeadroom)
245
- : effectiveThinkingBudget;
246
- // Shared input-token fingerprint for budget + TPM throttle (see
247
- // ask.tool.ts for the rationale — same `Math.ceil(bytes/4)` tokenisation
248
- // used by `estimatePreCallCostUsd`).
249
- const workspaceBytes = scan.files.reduce((sum, f) => sum + f.size, 0);
250
- const estimatedInputTokens = Math.ceil(workspaceBytes / 4) + Math.ceil(input.task.length / 4);
251
- // Atomic budget reservation — see ask.tool.ts for the full rationale.
252
- // Estimate includes the thinking budget (billed as output tokens on Pro)
253
- // PLUS the candidate output cap.
254
- if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
255
- const estimateUsd = estimatePreCallCostUsd({
256
- model: resolved.resolved,
257
- workspaceBytes,
258
- promptChars: input.task.length,
259
- expectedOutputTokens: effectiveOutputCap,
260
- thinkingTokens: thinkingTokensForEstimate,
261
- });
262
- const reserve = ctx.manifest.reserveBudget({
263
- workspaceRoot,
264
- toolName: 'code',
265
- model: resolved.resolved,
266
- estimatedCostMicros: toMicrosUsd(estimateUsd),
267
- dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
268
- nowMs: Date.now(),
269
- });
270
- if ('rejected' in reserve) {
271
- const spentUsd = reserve.spentMicros / 1_000_000;
272
- 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\`.`);
273
- }
274
- reservationId = reserve.id;
306
+ reservationId = reserve.id;
307
+ }
308
+ const systemPromptHash = createHash('sha256')
309
+ .update(SYSTEM_INSTRUCTION_CODE)
310
+ .digest('hex')
311
+ .slice(0, 16);
312
+ const ctxPrep = await prepareContext({
313
+ client: ctx.client,
314
+ manifest: ctx.manifest,
315
+ scan,
316
+ model: resolved,
317
+ systemPromptHash,
318
+ systemInstruction: SYSTEM_INSTRUCTION_CODE,
319
+ ttlSeconds: ctx.config.cacheTtlSeconds,
320
+ cacheMinTokens: ctx.config.cacheMinTokens,
321
+ emitter,
322
+ // codeExecution requires `tools:[{codeExecution:{}}]` on generateContent,
323
+ // which Gemini rejects together with cachedContent. Force inline path
324
+ // when codeExecution is requested so we have actual inline file parts
325
+ // to embed alongside the prompt.
326
+ allowCaching: scan.files.length > 0 && !codeExecution,
327
+ });
328
+ // TPM throttle — placed AFTER `prepareContext`, immediately before
329
+ // `generateContent`, so the reservation's `tsMs` accurately reflects
330
+ // when tokens hit Gemini's quota counter. See ask.tool.ts for the
331
+ // full rationale and the cold-cache-timing concern it fixes.
332
+ //
333
+ // Extracted into a helper so the stale-cache retry branch can
334
+ // cancel-and-re-reserve with an accurate tsMs rather than reusing a
335
+ // stale reservation.
336
+ const reserveForDispatch = async () => {
337
+ if (ctx.config.tpmThrottleLimit <= 0)
338
+ return;
339
+ const reservation = ctx.throttle.reserve(resolved.resolved, estimatedInputTokens);
340
+ throttleReservationId = reservation.releaseId;
341
+ if (reservation.delayMs > 0) {
342
+ emitter.emit(`throttle: waiting ${Math.ceil(reservation.delayMs / 1000)}s for TPM window…`);
343
+ await new Promise((resolveSleep) => setTimeout(resolveSleep, reservation.delayMs));
275
344
  }
276
- const systemPromptHash = createHash('sha256')
277
- .update(SYSTEM_INSTRUCTION_CODE)
278
- .digest('hex')
279
- .slice(0, 16);
280
- const ctxPrep = await prepareContext({
281
- client: ctx.client,
282
- manifest: ctx.manifest,
283
- scan,
284
- model: resolved,
285
- systemPromptHash,
286
- systemInstruction: SYSTEM_INSTRUCTION_CODE,
287
- ttlSeconds: ctx.config.cacheTtlSeconds,
288
- cacheMinTokens: ctx.config.cacheMinTokens,
289
- emitter,
290
- // codeExecution requires `tools:[{codeExecution:{}}]` on generateContent,
291
- // which Gemini rejects together with cachedContent. Force inline path
292
- // when codeExecution is requested so we have actual inline file parts
293
- // to embed alongside the prompt.
294
- allowCaching: scan.files.length > 0 && !codeExecution,
295
- });
296
- // TPM throttle — placed AFTER `prepareContext`, immediately before
297
- // `generateContent`, so the reservation's `tsMs` accurately reflects
298
- // when tokens hit Gemini's quota counter. See ask.tool.ts for the
299
- // full rationale and the cold-cache-timing concern it fixes.
300
- //
301
- // Extracted into a helper so the stale-cache retry branch can
302
- // cancel-and-re-reserve with an accurate tsMs rather than reusing a
303
- // stale reservation.
304
- const reserveForDispatch = async () => {
305
- if (ctx.config.tpmThrottleLimit <= 0)
306
- return;
307
- const reservation = ctx.throttle.reserve(resolved.resolved, estimatedInputTokens);
308
- throttleReservationId = reservation.releaseId;
309
- if (reservation.delayMs > 0) {
310
- emitter.emit(`throttle: waiting ${Math.ceil(reservation.delayMs / 1000)}s for TPM window…`);
311
- await new Promise((resolveSleep) => setTimeout(resolveSleep, reservation.delayMs));
312
- }
313
- };
314
- await reserveForDispatch();
315
- const userPrompt = expectEdits
316
- ? `${input.task}\n\nRespond with your rationale and OLD/NEW diff blocks per the system instruction.`
317
- : input.task;
318
- const thinkingDescription = usingThinkingLevel
319
- ? `thinking-level=${input.thinkingLevel}`
320
- : `thinking=${effectiveThinkingBudget}`;
321
- emitter.emit(codeExecution
322
- ? `generating with ${thinkingDescription} + codeExecution…`
323
- : `generating with ${thinkingDescription}…`);
324
- // Two mutually-exclusive reasoning-control paths (enforced by schema
325
- // `.refine()`):
326
- // a) `thinkingLevel` set → cast to the SDK enum and pass through.
327
- // Google's recommended path on Gemini 3. Rejected by Gemini 2.5.
328
- // Cast rather than runtime enum-object lookup so a future SDK
329
- // rename surfaces as a Gemini 400, not a silent `undefined`.
330
- // b) `thinkingBudget` path (default 16_384, clamped above) → pass
331
- // `thinkingBudget` as before.
332
- // `includeThoughts: true` is unconditional so `thinkingSummary`
333
- // extraction below always has material to find.
334
- const thinkingConfig = usingThinkingLevel
335
- ? {
336
- thinkingLevel: input.thinkingLevel,
337
- includeThoughts: true,
338
- }
339
- : { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
340
- // Gemini rejects generateContent({cachedContent, system_instruction|tools|tool_config})
341
- // with 400. System instruction is baked into the cache at build time; tools
342
- // (codeExecution) cannot be combined with a cache built without them. When
343
- // codeExecution is requested AND a cache is active, we can't use both — in that
344
- // case we bypass the cache so the user's explicit codeExecution request wins.
345
- const canUseCache = (cacheId) => cacheId !== null && !codeExecution;
346
- if (ctxPrep.cacheId && codeExecution) {
347
- logger.warn('code({ codeExecution: true }) is incompatible with an active cache; bypassing cache for this call.');
345
+ };
346
+ await reserveForDispatch();
347
+ const userPrompt = expectEdits
348
+ ? `${input.task}\n\nRespond with your rationale and OLD/NEW diff blocks per the system instruction.`
349
+ : input.task;
350
+ const thinkingDescription = usingThinkingLevel
351
+ ? `thinking-level=${input.thinkingLevel}`
352
+ : `thinking=${effectiveThinkingBudget}`;
353
+ emitter.emit(codeExecution
354
+ ? `generating with ${thinkingDescription} + codeExecution…`
355
+ : `generating with ${thinkingDescription}…`);
356
+ // Two mutually-exclusive reasoning-control paths (enforced by schema
357
+ // `.refine()`):
358
+ // a) `thinkingLevel` set → cast to the SDK enum and pass through.
359
+ // Google's recommended path on Gemini 3. Rejected by Gemini 2.5.
360
+ // Cast rather than runtime enum-object lookup so a future SDK
361
+ // rename surfaces as a Gemini 400, not a silent `undefined`.
362
+ // b) `thinkingBudget` path (default 16_384, clamped above) → pass
363
+ // `thinkingBudget` as before.
364
+ // `includeThoughts: true` is unconditional so `thinkingSummary`
365
+ // extraction below always has material to find.
366
+ const thinkingConfig = usingThinkingLevel
367
+ ? {
368
+ thinkingLevel: input.thinkingLevel,
369
+ includeThoughts: true,
348
370
  }
349
- const buildConfig = (cacheId) => {
350
- const maxOutputField = wireMaxOutputTokens !== undefined ? { maxOutputTokens: wireMaxOutputTokens } : {};
351
- if (canUseCache(cacheId) && cacheId) {
352
- // With cache: system_instruction is baked in; thinkingConfig remains OK.
353
- // `maxOutputTokens` only emitted when the caller set it explicitly
354
- // or `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true` — otherwise omit
355
- // and Gemini uses its model-default.
356
- return {
357
- cachedContent: cacheId,
358
- thinkingConfig,
359
- ...maxOutputField,
360
- };
361
- }
362
- // Without cache (or cache bypassed for codeExecution): pass full config.
371
+ : { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
372
+ // Gemini rejects generateContent({cachedContent, system_instruction|tools|tool_config})
373
+ // with 400. System instruction is baked into the cache at build time; tools
374
+ // (codeExecution) cannot be combined with a cache built without them. When
375
+ // codeExecution is requested AND a cache is active, we can't use both — in that
376
+ // case we bypass the cache so the user's explicit codeExecution request wins.
377
+ const canUseCache = (cacheId) => cacheId !== null && !codeExecution;
378
+ if (ctxPrep.cacheId && codeExecution) {
379
+ logger.warn('code({ codeExecution: true }) is incompatible with an active cache; bypassing cache for this call.');
380
+ }
381
+ const buildConfig = (cacheId) => {
382
+ const maxOutputField = wireMaxOutputTokens !== undefined ? { maxOutputTokens: wireMaxOutputTokens } : {};
383
+ if (canUseCache(cacheId) && cacheId) {
384
+ // With cache: system_instruction is baked in; thinkingConfig remains OK.
385
+ // `maxOutputTokens` only emitted when the caller set it explicitly
386
+ // or `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true` — otherwise omit
387
+ // and Gemini uses its model-default.
363
388
  return {
364
- systemInstruction: SYSTEM_INSTRUCTION_CODE,
389
+ cachedContent: cacheId,
365
390
  thinkingConfig,
366
391
  ...maxOutputField,
367
- ...(codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
368
392
  };
369
- };
370
- const buildContents = (cacheId, inline) => canUseCache(cacheId)
371
- ? userPrompt
372
- : [...inline, { role: 'user', parts: [{ text: userPrompt }] }];
373
- let activePrep = ctxPrep;
374
- let retriedOnStaleCache = false;
375
- let response;
376
- try {
377
- response = await ctx.client.models.generateContent({
378
- model: resolved.resolved,
379
- contents: buildContents(activePrep.cacheId, activePrep.inlineContents),
380
- config: buildConfig(activePrep.cacheId),
381
- });
382
- }
383
- catch (err) {
384
- if (activePrep.cacheId && isStaleCacheError(err)) {
385
- logger.warn(`Gemini rejected cached content ${activePrep.cacheId}; invalidating and retrying once.`);
386
- try {
387
- // Reset cache pointer only — preserve `files` rows so the rebuild
388
- // reuses uploaded files via content-hash dedup instead of double-
389
- // uploading. The Gemini-side cache is already dead.
390
- markCacheStale({ manifest: ctx.manifest, workspaceRoot });
391
- const rebuilt = await prepareContext({
392
- client: ctx.client,
393
- manifest: ctx.manifest,
394
- scan,
395
- model: resolved,
396
- systemPromptHash,
397
- systemInstruction: SYSTEM_INSTRUCTION_CODE,
398
- ttlSeconds: ctx.config.cacheTtlSeconds,
399
- cacheMinTokens: ctx.config.cacheMinTokens,
400
- emitter,
401
- allowCaching: scan.files.length > 0 && !codeExecution,
402
- });
403
- // Cancel stale reservation (tsMs was stamped before first
404
- // dispatch, now seconds old after rebuild) and re-reserve so
405
- // the retry's tsMs matches actual dispatch time. Mirror of
406
- // ask.tool.ts — see rationale there.
407
- if (throttleReservationId !== -1) {
408
- ctx.throttle.cancel(throttleReservationId);
409
- throttleReservationId = -1;
410
- }
411
- await reserveForDispatch();
412
- response = await ctx.client.models.generateContent({
413
- model: resolved.resolved,
414
- contents: buildContents(rebuilt.cacheId, rebuilt.inlineContents),
415
- config: buildConfig(rebuilt.cacheId),
416
- });
417
- activePrep = rebuilt;
418
- retriedOnStaleCache = true;
419
- }
420
- catch (retryErr) {
421
- throw new Error(`code retry after stale cache failed: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { cause: err });
422
- }
423
- }
424
- else {
425
- throw err;
426
- }
427
393
  }
428
- if (activePrep.cacheId) {
429
- ctx.ttlWatcher.markHot(workspaceRoot, activePrep.cacheId, ctx.config.cacheTtlSeconds);
430
- }
431
- const text = response.text ?? '';
432
- const edits = expectEdits ? parseEdits(text) : [];
433
- const codeBlocks = parseCodeBlocks(text);
434
- // Extract code_execution tool artifacts + Gemini's thinking summary if present.
435
- const executedCode = [];
436
- const executionOutput = [];
437
- const thoughtTexts = [];
438
- const candidates = response.candidates ?? [];
439
- for (const cand of candidates) {
440
- const parts = cand.content?.parts ?? [];
441
- for (const part of parts) {
442
- if (part.executableCode?.code)
443
- executedCode.push(part.executableCode.code);
444
- if (part.codeExecutionResult?.output)
445
- executionOutput.push(part.codeExecutionResult.output);
446
- // `thinkingConfig: { includeThoughts: true }` returns thinking as parts
447
- // flagged with `thought: true`. Cap the summary to avoid overwhelming the MCP response.
448
- if (part.thought === true && typeof part.text === 'string') {
449
- thoughtTexts.push(part.text);
450
- }
451
- }
452
- }
453
- const thinkingSummary = thoughtTexts.length > 0 ? thoughtTexts.join('\n').slice(0, 1200) : null;
454
- const usage = response.usageMetadata;
455
- const cached = typeof usage?.cachedContentTokenCount === 'number' ? usage.cachedContentTokenCount : 0;
456
- const inputTotal = typeof usage?.promptTokenCount === 'number' ? usage.promptTokenCount : 0;
457
- const uncached = Math.max(0, inputTotal - cached);
458
- const output = typeof usage?.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : 0;
459
- const thinking = typeof usage?.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : 0;
460
- // Finalise TPM throttle reservation with actual input tokens
461
- // (cached + uncached — both count toward Gemini's per-minute quota).
462
- if (throttleReservationId !== -1) {
463
- ctx.throttle.release(throttleReservationId, inputTotal);
464
- throttleReservationId = -1;
465
- }
466
- const cost = estimateCostUsd({
394
+ // Without cache (or cache bypassed for codeExecution): pass full config.
395
+ return {
396
+ systemInstruction: SYSTEM_INSTRUCTION_CODE,
397
+ thinkingConfig,
398
+ ...maxOutputField,
399
+ ...(codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
400
+ };
401
+ };
402
+ const buildContents = (cacheId, inline) => canUseCache(cacheId)
403
+ ? userPrompt
404
+ : [...inline, { role: 'user', parts: [{ text: userPrompt }] }];
405
+ let activePrep = ctxPrep;
406
+ let retriedOnStaleCache = false;
407
+ let response;
408
+ try {
409
+ // `withNetworkRetry` covers pre-response transient failures
410
+ // (`TypeError: fetch failed`). See `src/gemini/retry.ts` for the full
411
+ // rationale; 429 rate-limits continue to be handled at the tool layer
412
+ // via `isGemini429` + `parseRetryDelayMs`.
413
+ response = await withNetworkRetry(() => ctx.client.models.generateContent({
467
414
  model: resolved.resolved,
468
- uncachedInputTokens: uncached,
469
- cachedInputTokens: cached,
470
- outputTokens: output,
471
- thinkingTokens: thinking,
415
+ contents: buildContents(activePrep.cacheId, activePrep.inlineContents),
416
+ config: buildConfig(activePrep.cacheId),
417
+ }), {
418
+ onRetry: (attempt, retryErr) => {
419
+ logger.warn(`code: retrying generateContent after transient network failure (attempt ${attempt}): ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`);
420
+ },
472
421
  });
473
- const costMicros = toMicrosUsd(cost);
474
- const durationMs = Date.now() - started;
475
- if (reservationId !== null) {
476
- // Defensive: if `finalize` throws (disk full / lock contention), keep
477
- // the reservation row so we don't lose all record of this billable
478
- // call. Drop `reservationId` either way so the outer catch doesn't
479
- // touch it.
422
+ }
423
+ catch (err) {
424
+ if (activePrep.cacheId && isStaleCacheError(err)) {
425
+ logger.warn(`Gemini rejected cached content ${activePrep.cacheId}; invalidating and retrying once.`);
480
426
  try {
481
- ctx.manifest.finalizeBudgetReservation(reservationId, {
482
- cachedTokens: cached,
483
- uncachedTokens: uncached,
484
- costUsdMicro: costMicros,
485
- durationMs,
427
+ // Reset cache pointer only — preserve `files` rows so the rebuild
428
+ // reuses uploaded files via content-hash dedup instead of double-
429
+ // uploading. The Gemini-side cache is already dead.
430
+ markCacheStale({ manifest: ctx.manifest, workspaceRoot });
431
+ const rebuilt = await prepareContext({
432
+ client: ctx.client,
433
+ manifest: ctx.manifest,
434
+ scan,
435
+ model: resolved,
436
+ systemPromptHash,
437
+ systemInstruction: SYSTEM_INSTRUCTION_CODE,
438
+ ttlSeconds: ctx.config.cacheTtlSeconds,
439
+ cacheMinTokens: ctx.config.cacheMinTokens,
440
+ emitter,
441
+ allowCaching: scan.files.length > 0 && !codeExecution,
442
+ });
443
+ // Cancel stale reservation (tsMs was stamped before first
444
+ // dispatch, now seconds old after rebuild) and re-reserve so
445
+ // the retry's tsMs matches actual dispatch time. Mirror of
446
+ // ask.tool.ts — see rationale there.
447
+ if (throttleReservationId !== -1) {
448
+ ctx.throttle.cancel(throttleReservationId);
449
+ throttleReservationId = -1;
450
+ }
451
+ await reserveForDispatch();
452
+ // The stale-cache retry itself can hit a transient network failure;
453
+ // wrap it too so the rebuild isn't wasted on a one-off blip.
454
+ response = await withNetworkRetry(() => ctx.client.models.generateContent({
455
+ model: resolved.resolved,
456
+ contents: buildContents(rebuilt.cacheId, rebuilt.inlineContents),
457
+ config: buildConfig(rebuilt.cacheId),
458
+ }), {
459
+ onRetry: (attempt, retryErr) => {
460
+ logger.warn(`code (stale-cache retry): retrying generateContent after transient network failure (attempt ${attempt}): ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`);
461
+ },
486
462
  });
463
+ activePrep = rebuilt;
464
+ retriedOnStaleCache = true;
487
465
  }
488
- catch (finalizeErr) {
489
- logger.error(`code: finalizeBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate (${costMicros} micros). Error: ${String(finalizeErr)}`);
466
+ catch (retryErr) {
467
+ throw new Error(`code retry after stale cache failed: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { cause: err });
490
468
  }
491
- reservationId = null;
492
469
  }
493
470
  else {
494
- ctx.manifest.insertUsageMetric({
495
- workspaceRoot,
496
- toolName: 'code',
497
- model: resolved.resolved,
471
+ throw err;
472
+ }
473
+ }
474
+ if (activePrep.cacheId) {
475
+ ctx.ttlWatcher.markHot(workspaceRoot, activePrep.cacheId, ctx.config.cacheTtlSeconds);
476
+ }
477
+ const text = response.text ?? '';
478
+ const edits = expectEdits ? parseEdits(text) : [];
479
+ const codeBlocks = parseCodeBlocks(text);
480
+ // Extract code_execution tool artifacts + Gemini's thinking summary if present.
481
+ const executedCode = [];
482
+ const executionOutput = [];
483
+ const thoughtTexts = [];
484
+ const candidates = response.candidates ?? [];
485
+ for (const cand of candidates) {
486
+ const parts = cand.content?.parts ?? [];
487
+ for (const part of parts) {
488
+ if (part.executableCode?.code)
489
+ executedCode.push(part.executableCode.code);
490
+ if (part.codeExecutionResult?.output)
491
+ executionOutput.push(part.codeExecutionResult.output);
492
+ // `thinkingConfig: { includeThoughts: true }` returns thinking as parts
493
+ // flagged with `thought: true`. Cap the summary to avoid overwhelming the MCP response.
494
+ if (part.thought === true && typeof part.text === 'string') {
495
+ thoughtTexts.push(part.text);
496
+ }
497
+ }
498
+ }
499
+ const thinkingSummary = thoughtTexts.length > 0 ? thoughtTexts.join('\n').slice(0, 1200) : null;
500
+ const usage = response.usageMetadata;
501
+ const cached = typeof usage?.cachedContentTokenCount === 'number' ? usage.cachedContentTokenCount : 0;
502
+ const inputTotal = typeof usage?.promptTokenCount === 'number' ? usage.promptTokenCount : 0;
503
+ const uncached = Math.max(0, inputTotal - cached);
504
+ const output = typeof usage?.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : 0;
505
+ const thinking = typeof usage?.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : 0;
506
+ // Finalise TPM throttle reservation with actual input tokens
507
+ // (cached + uncached — both count toward Gemini's per-minute quota).
508
+ if (throttleReservationId !== -1) {
509
+ ctx.throttle.release(throttleReservationId, inputTotal);
510
+ throttleReservationId = -1;
511
+ }
512
+ const cost = estimateCostUsd({
513
+ model: resolved.resolved,
514
+ uncachedInputTokens: uncached,
515
+ cachedInputTokens: cached,
516
+ outputTokens: output,
517
+ thinkingTokens: thinking,
518
+ });
519
+ const costMicros = toMicrosUsd(cost);
520
+ const durationMs = Date.now() - started;
521
+ if (reservationId !== null) {
522
+ // Defensive: if `finalize` throws (disk full / lock contention), keep
523
+ // the reservation row so we don't lose all record of this billable
524
+ // call. Drop `reservationId` either way so the outer catch doesn't
525
+ // touch it.
526
+ try {
527
+ ctx.manifest.finalizeBudgetReservation(reservationId, {
498
528
  cachedTokens: cached,
499
529
  uncachedTokens: uncached,
500
530
  costUsdMicro: costMicros,
501
531
  durationMs,
502
- occurredAt: Date.now(),
503
532
  });
504
533
  }
505
- if (scan.truncated) {
506
- logger.warn(`workspace ${workspaceRoot} contains more files than GEMINI_CODE_CONTEXT_MAX_FILES (${ctx.config.maxFilesPerWorkspace}); the tail was dropped before indexing.`);
534
+ catch (finalizeErr) {
535
+ logger.error(`code: finalizeBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate (${costMicros} micros). Error: ${String(finalizeErr)}`);
507
536
  }
508
- const structured = {
509
- resolvedModel: resolved.resolved,
510
- requestedModel: resolved.requested,
511
- modelCategory: resolved.category,
512
- modelCostTier: resolved.capabilities.costTier,
513
- contextWindow: resolved.inputTokenLimit,
514
- // `thinkingBudget` echoes the clamped value actually sent on the
515
- // wire; it's only meaningful on the budget path. On the
516
- // `thinkingLevel` path nothing is sent for `thinkingBudget`, so we
517
- // emit `null` (not `0`) — `0` is the wire sentinel for "thinking
518
- // disabled" and reporting it here for a level-path call would lie
519
- // to downstream audit / dashboard consumers (PR #17 self-review F1,
520
- // 3-reviewer consensus: GPT + Copilot + Self). Matches `ask.tool.ts`.
521
- thinkingBudget: usingThinkingLevel ? null : effectiveThinkingBudget,
522
- thinkingLevel: input.thinkingLevel ?? null,
523
- codeExecutionUsed: codeExecution,
524
- cacheHit: activePrep.reused,
525
- cacheRebuilt: activePrep.rebuilt || retriedOnStaleCache,
526
- retriedOnStaleCache,
537
+ reservationId = null;
538
+ }
539
+ else {
540
+ ctx.manifest.insertUsageMetric({
541
+ workspaceRoot,
542
+ toolName: 'code',
543
+ model: resolved.resolved,
527
544
  cachedTokens: cached,
528
545
  uncachedTokens: uncached,
529
- thinkingTokens: thinking,
530
- outputTokens: output,
531
- costEstimateUsd: Math.round(cost * 10000) / 10000,
546
+ costUsdMicro: costMicros,
532
547
  durationMs,
533
- edits: edits.map((e) => ({
534
- file: e.file,
535
- oldPreview: e.old.slice(0, 120),
536
- newPreview: e.new.slice(0, 120),
537
- })),
538
- editCount: edits.length,
539
- codeBlocks: codeBlocks.map((b) => ({ lang: b.lang, length: b.content.length })),
540
- workspaceTruncated: scan.truncated,
541
- maxFilesCap: ctx.config.maxFilesPerWorkspace,
542
- filesIndexed: scan.files.length,
543
- filesUploadFailed: activePrep.uploaded.failedCount,
544
- ...(activePrep.uploaded.failedCount > 0
545
- ? { uploadFailures: activePrep.uploaded.failures.slice(0, 5) }
546
- : {}),
547
- inlineOnly: activePrep.inlineOnly,
548
- ...(thinkingSummary ? { thinkingSummary } : {}),
549
- ...(executedCode.length > 0 ? { executedCode } : {}),
550
- ...(executionOutput.length > 0 ? { executionOutput } : {}),
551
- };
552
- return textResult(text, structured);
548
+ occurredAt: Date.now(),
549
+ });
553
550
  }
554
- catch (err) {
555
- logger.error(`code failed: ${String(err)}`);
556
- // T22a + v1.3.2 — seed the throttle's retry-hint from Gemini 429
557
- // bodies, gated on `isGemini429` (ApiError instance + status===429)
558
- // to prevent hint-poisoning. Mirror of ask.tool.ts — see there for
559
- // full rationale.
560
- const retryDelayMs = isGemini429(err) ? parseRetryDelayMs(err.message) : null;
561
- if (retryDelayMs !== null && resolvedModelKey !== null) {
562
- ctx.throttle.recordRetryHint(resolvedModelKey, retryDelayMs);
563
- }
564
- if (reservationId !== null) {
565
- try {
566
- ctx.manifest.cancelBudgetReservation(reservationId);
567
- }
568
- catch (cancelErr) {
569
- logger.error(`code: cancelBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate. Error: ${String(cancelErr)}`);
570
- }
571
- reservationId = null;
551
+ if (scan.truncated) {
552
+ logger.warn(`workspace ${workspaceRoot} contains more files than GEMINI_CODE_CONTEXT_MAX_FILES (${ctx.config.maxFilesPerWorkspace}); the tail was dropped before indexing.`);
553
+ }
554
+ const structured = {
555
+ resolvedModel: resolved.resolved,
556
+ requestedModel: resolved.requested,
557
+ modelCategory: resolved.category,
558
+ modelCostTier: resolved.capabilities.costTier,
559
+ contextWindow: resolved.inputTokenLimit,
560
+ // `thinkingBudget` echoes the clamped value actually sent on the
561
+ // wire; it's only meaningful on the budget path. On the
562
+ // `thinkingLevel` path nothing is sent for `thinkingBudget`, so we
563
+ // emit `null` (not `0`) — `0` is the wire sentinel for "thinking
564
+ // disabled" and reporting it here for a level-path call would lie
565
+ // to downstream audit / dashboard consumers (PR #17 self-review F1,
566
+ // 3-reviewer consensus: GPT + Copilot + Self). Matches `ask.tool.ts`.
567
+ thinkingBudget: usingThinkingLevel ? null : effectiveThinkingBudget,
568
+ thinkingLevel: input.thinkingLevel ?? null,
569
+ codeExecutionUsed: codeExecution,
570
+ cacheHit: activePrep.reused,
571
+ cacheRebuilt: activePrep.rebuilt || retriedOnStaleCache,
572
+ retriedOnStaleCache,
573
+ cachedTokens: cached,
574
+ uncachedTokens: uncached,
575
+ thinkingTokens: thinking,
576
+ outputTokens: output,
577
+ costEstimateUsd: Math.round(cost * 10000) / 10000,
578
+ durationMs,
579
+ edits: edits.map((e) => ({
580
+ file: e.file,
581
+ oldPreview: e.old.slice(0, 120),
582
+ newPreview: e.new.slice(0, 120),
583
+ })),
584
+ editCount: edits.length,
585
+ codeBlocks: codeBlocks.map((b) => ({ lang: b.lang, length: b.content.length })),
586
+ workspaceTruncated: scan.truncated,
587
+ maxFilesCap: ctx.config.maxFilesPerWorkspace,
588
+ filesIndexed: scan.files.length,
589
+ filesUploadFailed: activePrep.uploaded.failedCount,
590
+ ...(activePrep.uploaded.failedCount > 0
591
+ ? { uploadFailures: activePrep.uploaded.failures.slice(0, 5) }
592
+ : {}),
593
+ inlineOnly: activePrep.inlineOnly,
594
+ ...(thinkingSummary ? { thinkingSummary } : {}),
595
+ ...(executedCode.length > 0 ? { executedCode } : {}),
596
+ ...(executionOutput.length > 0 ? { executionOutput } : {}),
597
+ };
598
+ return textResult(text, structured);
599
+ }
600
+ catch (err) {
601
+ logger.error(`code failed: ${String(err)}`);
602
+ // T22a + v1.3.2 — seed the throttle's retry-hint from Gemini 429
603
+ // bodies, gated on `isGemini429` (ApiError instance + status===429)
604
+ // to prevent hint-poisoning. Mirror of ask.tool.ts — see there for
605
+ // full rationale.
606
+ const retryDelayMs = isGemini429(err) ? parseRetryDelayMs(err.message) : null;
607
+ if (retryDelayMs !== null && resolvedModelKey !== null) {
608
+ ctx.throttle.recordRetryHint(resolvedModelKey, retryDelayMs);
609
+ }
610
+ if (reservationId !== null) {
611
+ try {
612
+ ctx.manifest.cancelBudgetReservation(reservationId);
572
613
  }
573
- // Drop TPM reservation on failure — mirror of ask.tool.ts rationale.
574
- if (throttleReservationId !== -1) {
575
- ctx.throttle.cancel(throttleReservationId);
576
- throttleReservationId = -1;
614
+ catch (cancelErr) {
615
+ logger.error(`code: cancelBudgetReservation failed for id=${reservationId}; reservation row keeps the estimate. Error: ${String(cancelErr)}`);
577
616
  }
578
- return errorResult(`code failed: ${err instanceof Error ? err.message : String(err)}`);
617
+ reservationId = null;
579
618
  }
580
- finally {
581
- emitter.stop();
619
+ // Drop TPM reservation on failure — mirror of ask.tool.ts rationale.
620
+ if (throttleReservationId !== -1) {
621
+ ctx.throttle.cancel(throttleReservationId);
622
+ throttleReservationId = -1;
582
623
  }
583
- },
584
- };
624
+ const httpStatus = err.status;
625
+ return errorResult(`code failed: ${err instanceof Error ? err.message : String(err)}`, {
626
+ errorCode: 'UNKNOWN',
627
+ ...(httpStatus !== undefined ? { httpStatus } : {}),
628
+ });
629
+ }
630
+ finally {
631
+ emitter.stop();
632
+ }
633
+ }
585
634
  //# sourceMappingURL=code.tool.js.map