@qmediat.io/gemini-code-context-mcp 1.25.0 → 1.25.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 (107) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +1 -1
  3. package/dist/cache/cache-manager.d.ts +23 -34
  4. package/dist/cache/cache-manager.d.ts.map +1 -1
  5. package/dist/cache/cache-manager.js +324 -272
  6. package/dist/cache/cache-manager.js.map +1 -1
  7. package/dist/cache/caching-mode.d.ts +5 -3
  8. package/dist/cache/caching-mode.d.ts.map +1 -1
  9. package/dist/cache/caching-mode.js +6 -4
  10. package/dist/cache/caching-mode.js.map +1 -1
  11. package/dist/cache/ttl-watcher.d.ts.map +1 -1
  12. package/dist/cache/ttl-watcher.js +7 -1
  13. package/dist/cache/ttl-watcher.js.map +1 -1
  14. package/dist/cache/ttl.d.ts +8 -0
  15. package/dist/cache/ttl.d.ts.map +1 -0
  16. package/dist/cache/ttl.js +10 -0
  17. package/dist/cache/ttl.js.map +1 -0
  18. package/dist/manifest/db.d.ts.map +1 -1
  19. package/dist/manifest/db.js +2 -1
  20. package/dist/manifest/db.js.map +1 -1
  21. package/dist/tools/agentic/run.d.ts.map +1 -1
  22. package/dist/tools/agentic/run.js +3 -6
  23. package/dist/tools/agentic/run.js.map +1 -1
  24. package/dist/tools/ask/answer.d.ts +9 -0
  25. package/dist/tools/ask/answer.d.ts.map +1 -0
  26. package/dist/tools/ask/answer.js +28 -0
  27. package/dist/tools/ask/answer.js.map +1 -0
  28. package/dist/tools/ask/attachments.d.ts +25 -0
  29. package/dist/tools/ask/attachments.d.ts.map +1 -0
  30. package/dist/tools/ask/attachments.js +85 -0
  31. package/dist/tools/ask/attachments.js.map +1 -0
  32. package/dist/tools/ask/call.d.ts +61 -0
  33. package/dist/tools/ask/call.d.ts.map +1 -0
  34. package/dist/tools/ask/call.js +6 -0
  35. package/dist/tools/ask/call.js.map +1 -0
  36. package/dist/tools/ask/guard.d.ts +24 -0
  37. package/dist/tools/ask/guard.d.ts.map +1 -0
  38. package/dist/tools/ask/guard.js +79 -0
  39. package/dist/tools/ask/guard.js.map +1 -0
  40. package/dist/tools/ask/input.d.ts +45 -0
  41. package/dist/tools/ask/input.d.ts.map +1 -0
  42. package/dist/tools/ask/input.js +93 -0
  43. package/dist/tools/ask/input.js.map +1 -0
  44. package/dist/tools/ask/instruction.d.ts +8 -0
  45. package/dist/tools/ask/instruction.d.ts.map +1 -0
  46. package/dist/tools/ask/instruction.js +13 -0
  47. package/dist/tools/ask/instruction.js.map +1 -0
  48. package/dist/tools/ask/request.d.ts +14 -0
  49. package/dist/tools/ask/request.d.ts.map +1 -0
  50. package/dist/tools/ask/request.js +38 -0
  51. package/dist/tools/ask/request.js.map +1 -0
  52. package/dist/tools/ask/results.d.ts +23 -0
  53. package/dist/tools/ask/results.d.ts.map +1 -0
  54. package/dist/tools/ask/results.js +107 -0
  55. package/dist/tools/ask/results.js.map +1 -0
  56. package/dist/tools/ask/setup.d.ts +22 -0
  57. package/dist/tools/ask/setup.d.ts.map +1 -0
  58. package/dist/tools/ask/setup.js +57 -0
  59. package/dist/tools/ask/setup.js.map +1 -0
  60. package/dist/tools/ask/sizing.d.ts +10 -0
  61. package/dist/tools/ask/sizing.d.ts.map +1 -0
  62. package/dist/tools/ask/sizing.js +33 -0
  63. package/dist/tools/ask/sizing.js.map +1 -0
  64. package/dist/tools/ask/thinking.d.ts +54 -0
  65. package/dist/tools/ask/thinking.d.ts.map +1 -0
  66. package/dist/tools/ask/thinking.js +69 -0
  67. package/dist/tools/ask/thinking.js.map +1 -0
  68. package/dist/tools/ask-agentic-fallback.d.ts +1 -1
  69. package/dist/tools/ask-agentic-fallback.d.ts.map +1 -1
  70. package/dist/tools/ask-agentic.tool.d.ts.map +1 -1
  71. package/dist/tools/ask-agentic.tool.js +4 -10
  72. package/dist/tools/ask-agentic.tool.js.map +1 -1
  73. package/dist/tools/ask.tool.d.ts +3 -41
  74. package/dist/tools/ask.tool.d.ts.map +1 -1
  75. package/dist/tools/ask.tool.js +46 -795
  76. package/dist/tools/ask.tool.js.map +1 -1
  77. package/dist/tools/code.tool.d.ts.map +1 -1
  78. package/dist/tools/code.tool.js +375 -502
  79. package/dist/tools/code.tool.js.map +1 -1
  80. package/dist/tools/reindex.tool.d.ts.map +1 -1
  81. package/dist/tools/reindex.tool.js +19 -22
  82. package/dist/tools/reindex.tool.js.map +1 -1
  83. package/dist/tools/shared/eager-answer.d.ts +78 -0
  84. package/dist/tools/shared/eager-answer.d.ts.map +1 -0
  85. package/dist/tools/shared/eager-answer.js +130 -0
  86. package/dist/tools/shared/eager-answer.js.map +1 -0
  87. package/dist/tools/shared/eager-call.d.ts +114 -0
  88. package/dist/tools/shared/eager-call.d.ts.map +1 -0
  89. package/dist/tools/shared/eager-call.js +95 -0
  90. package/dist/tools/shared/eager-call.js.map +1 -0
  91. package/dist/tools/shared/eager-steps.d.ts +114 -0
  92. package/dist/tools/shared/eager-steps.d.ts.map +1 -0
  93. package/dist/tools/shared/eager-steps.js +152 -0
  94. package/dist/tools/shared/eager-steps.js.map +1 -0
  95. package/dist/tools/shared/service-tier.d.ts +9 -0
  96. package/dist/tools/shared/service-tier.d.ts.map +1 -1
  97. package/dist/tools/shared/service-tier.js +15 -0
  98. package/dist/tools/shared/service-tier.js.map +1 -1
  99. package/dist/tools/shared/thinking.d.ts +9 -0
  100. package/dist/tools/shared/thinking.d.ts.map +1 -1
  101. package/dist/tools/shared/thinking.js +10 -0
  102. package/dist/tools/shared/thinking.js.map +1 -1
  103. package/dist/tools/shared/workspace-refusal.d.ts +13 -0
  104. package/dist/tools/shared/workspace-refusal.d.ts.map +1 -0
  105. package/dist/tools/shared/workspace-refusal.js +23 -0
  106. package/dist/tools/shared/workspace-refusal.js.map +1 -0
  107. package/package.json +1 -1
@@ -7,29 +7,22 @@
7
7
  * - Coding-optimized system prompt
8
8
  * - Structured output parser extracts code blocks and OLD/NEW diffs
9
9
  */
10
- import { createHash } from 'node:crypto';
11
10
  import { resolve } from 'node:path';
12
11
  import { z } from 'zod';
13
- import { prepareContext } from '../cache/cache-manager.js';
14
- import { CACHING_MODE_FALLBACK_DESCRIPTION, cachingModeFor, cachingRan, } from '../cache/caching-mode.js';
15
- import { capThatRuns, preflightModeFor, resolveOutputCap, thinkingBudgetRefusal, } from '../gemini/long-decode.js';
12
+ import { CACHING_MODE_FALLBACK_DESCRIPTION } from '../cache/caching-mode.js';
13
+ import { capThatRuns, thinkingBudgetRefusal, } from '../gemini/long-decode.js';
16
14
  import { ModelCategoryMismatchError } from '../gemini/model-taxonomy.js';
17
15
  import { resolveModel } from '../gemini/models.js';
18
- import { countForPreflight } from '../gemini/token-counter.js';
19
- import { buildScanMemo, scanWorkspace } from '../indexer/workspace-scanner.js';
20
- import { WorkspaceValidationError, validateWorkspacePath, } from '../indexer/workspace-validation.js';
21
- import { estimatePreCallCostUsd, toMicrosUsd } from '../utils/cost-estimator.js';
22
16
  import { logger, safeForLog } from '../utils/logger.js';
23
- import { createProgressEmitter } from '../utils/progress.js';
24
- import { errorResult, textResult } from './registry.js';
25
- import { isTimeoutAbort, timedOutCall, toolTimeoutController } from './shared/abort-timeout.js';
26
- import { decodeOnContext } from './shared/context-decode.js';
27
- import { CompletedRequests, LONG_DECODE_CAP_DESCRIPTION } from './shared/continuation.js';
28
- import { DispatchThrottle } from './shared/dispatch-throttle.js';
29
- import { SERVICE_TIER_DESCRIPTION, ServiceTierError, networkAttempts, resolveServiceTier, serviceTierConfig, statusOf, tierErrorMeta, } from './shared/service-tier.js';
30
- import { settleAnswer, settleFailure } from './shared/settle-call.js';
17
+ import { errorResult, textResult, } from './registry.js';
18
+ import { LONG_DECODE_CAP_DESCRIPTION } from './shared/continuation.js';
19
+ import { decodeEagerCall, prepareCallContext, scanFields, settleDecoded, warnTruncatedScan, } from './shared/eager-answer.js';
20
+ import { closeEagerCall, openEagerCall, settleFailedEager, } from './shared/eager-call.js';
21
+ import { countPreflight, eagerOutputCap, estimateInput, overWindow, preflightFields, reserveCallBudget, scanForCall, } from './shared/eager-steps.js';
22
+ import { SERVICE_TIER_DESCRIPTION, ServiceTierError, serviceTierConfig, serviceTierOrRefusal, } from './shared/service-tier.js';
31
23
  import { SYSTEM_INSTRUCTION_SAFETY_EAGER } from './shared/system-instruction-safety.js';
32
- import { THINKING_LEVEL_FIELD, thinkingBudgetUnder, thinkingReserve } from './shared/thinking.js';
24
+ import { THINKING_LEVEL_FIELD, levelThinkingConfig, thinkingBudgetUnder, thinkingReserve, } from './shared/thinking.js';
25
+ import { workspaceRefusal } from './shared/workspace-refusal.js';
33
26
  /**
34
27
  * `code` system instruction. Prepends the shared `SYSTEM_INSTRUCTION_SAFETY_EAGER`
35
28
  * data-vs-instruction firewall (added in v1.15.2 — pre-v1.15.2 `code` had no
@@ -227,505 +220,385 @@ async function resolveCodeModel(requested, fromConfig, client) {
227
220
  });
228
221
  return { resolved, replacedDefault: requested };
229
222
  }
223
+ /** `code`'s default thinking budget: strong reasoning for coding out of the box, which coding tasks benefit from. */
224
+ const CODE_DEFAULT_THINKING_BUDGET = 16_384;
225
+ /**
226
+ * One `code` call: opened before its first await, its steps run in order — each goes on with the next stage or ends
227
+ * the call — and closed on every path. Every throw of a step reaches the one failure path.
228
+ */
230
229
  async function executeCodeBody(input, ctx, workspaceRoot, started) {
231
- // The configured default (GEMINI_CODE_CONTEXT_DEFAULT_MODEL, then the profile, then the alias — loadConfig always
232
- // sets it), as ask and ask_agentic read it. `resolveCodeModel` keeps `code` on a thinking reasoning model when the
233
- // configured default is not one, and the response names the replaced default.
234
- const modelRequest = input.model ?? ctx.config.defaultModel ?? CODE_FALLBACK_MODEL; // the last ?? as ask_agentic has it
230
+ const eager = openEagerCall({
231
+ tool: 'code',
232
+ knobs: input,
233
+ requestedTier: input.serviceTier ?? ctx.config.serviceTier,
234
+ workspaceRoot,
235
+ started,
236
+ }, ctx);
235
237
  const expectEdits = input.expectEdits ?? true;
236
238
  const codeExecution = input.codeExecution ?? false;
237
- // Schema `.refine()` guarantees `thinkingBudget` and `thinkingLevel` are
238
- // never both set. `usingThinkingLevel` is a single source of truth for
239
- // the "is the caller driving reasoning via the discrete-tier knob?"
240
- // predicate — used by the cost estimate, the emitter message, and the
241
- // thinkingConfig shape below.
242
- const usingThinkingLevel = input.thinkingLevel !== undefined;
243
- // `code` keeps its pre-existing default of 16_384 for the `thinkingBudget`
244
- // path (strong reasoning for coding out of the box — coding tasks
245
- // genuinely benefit from it and callers rarely want to disable thinking).
246
- // When the caller uses `thinkingLevel` instead, `thinkingBudget` stays
247
- // undefined and we take the level branch below.
248
- const thinkingBudget = usingThinkingLevel ? undefined : (input.thinkingBudget ?? 16_384);
249
- let reservationId = null;
250
- // Canonical resolved-model string for retry-hint seeding (T22a).
251
- // See ask.tool.ts for rationale.
252
- let resolvedModelKey = null;
253
- // every request that completed is billed: the ledger settles from these, on an answer and on a failure alike
254
- const completed = new CompletedRequests();
255
- // the running decode's booking and whether a stream opened (a later failure is then billed work, not re-sent)
256
- const tracking = { ledgerEntry: null, streamOpened: false };
257
- let modelAudit = {};
258
- const emitter = createProgressEmitter(ctx.server, ctx.progressToken);
259
- // T19 + Phase 4 — composite controller (wall-clock + stall watchdog).
260
- // See ask.tool.ts for rationale; same shape here.
261
- const timeoutController = toolTimeoutController('code', input);
262
- const abortSignal = timeoutController.signal;
263
- // Each request of the decode holds its own TPM reservation; a failure drops the one held.
264
- const dispatch = new DispatchThrottle({
265
- throttle: ctx.throttle,
266
- enabled: ctx.config.tpmThrottleLimit > 0,
267
- signal: abortSignal,
268
- emit: (message) => emitter.emit(message),
269
- });
270
239
  try {
271
- // Workspace validation inside try → reported as a regular tool error
272
- // (errorResult, "code failed: …") rather than an unhandled exception
273
- // surfaced by the server-level handler.
274
- try {
275
- validateWorkspacePath(workspaceRoot);
276
- }
277
- catch (err) {
278
- if (err instanceof WorkspaceValidationError) {
279
- return errorResult(`code: ${err.message}`);
280
- }
281
- throw err;
282
- }
283
- emitter.emit(`resolving model '${modelRequest}'…`);
284
- // `code` is strictly text-reasoning — coding tasks genuinely benefit
285
- // from reasoning tokens, and dispatching to fast/lite tiers would
286
- // degrade output quality without meaningful cost savings. Crucially:
287
- // this category gate prevents image-gen / audio-gen / agent models
288
- // (which may share `pro` tokens with text models in Google's registry)
289
- // from reaching `generateContent` with a code-review prompt — the
290
- // primary motivation for the v1.4.0 taxonomy work.
291
- const choice = await resolveCodeModel(modelRequest, input.model == null, ctx.client);
292
- const resolved = choice.resolved;
293
- // The same two fields on every result after this point, error results included: an audit of a failed call
294
- // can still tell a fallback from a caller's choice.
295
- let serviceTier;
296
- try {
297
- serviceTier = resolveServiceTier(input.serviceTier, ctx.config.serviceTier, ctx.config.vertex);
298
- }
299
- catch (err) {
300
- if (!(err instanceof ServiceTierError))
301
- throw err;
302
- return errorResult(`code: ${err.message}`, {
303
- errorCode: err.code,
240
+ const refusal = workspaceRefusal('code', workspaceRoot);
241
+ if (refusal !== null)
242
+ return refusal;
243
+ const resolved = await resolveCode({ input, ctx, eager, expectEdits, codeExecution });
244
+ if ('end' in resolved)
245
+ return resolved.end;
246
+ const counted = await guardCode(resolved.next);
247
+ if ('end' in counted)
248
+ return counted.end;
249
+ const sized = sizeCode(counted.next);
250
+ if ('end' in sized)
251
+ return sized.end;
252
+ return await answerCode(sized.next);
253
+ }
254
+ catch (err) {
255
+ return codeFailedResult(settleFailedEager(eager, ctx, err));
256
+ }
257
+ finally {
258
+ closeEagerCall(eager);
259
+ }
260
+ }
261
+ /**
262
+ * Resolve the model and the tier. The model asked for is the caller's, else the configured default
263
+ * (GEMINI_CODE_CONTEXT_DEFAULT_MODEL, then the profile, then the alias — loadConfig always sets it), as `ask` and
264
+ * `ask_agentic` read it; `resolveCodeModel` keeps `code` on a thinking reasoning model when the configured default is
265
+ * not one, and the results name the replaced default. `code` is strictly text-reasoning: the category gate keeps an
266
+ * image, audio or agent model (which may share `pro` tokens with text models in Google's registry) from reaching
267
+ * `generateContent` with a coding prompt. From here every result, error results included, carries the audit, so an
268
+ * audit of a failed call can still tell a fallback from a caller's choice.
269
+ */
270
+ async function resolveCode(call) {
271
+ const { input, ctx, eager } = call;
272
+ const modelRequest = input.model ?? ctx.config.defaultModel ?? CODE_FALLBACK_MODEL; // the last ?? as ask_agentic has it
273
+ eager.emitter.emit(`resolving model '${modelRequest}'…`);
274
+ const choice = await resolveCodeModel(modelRequest, input.model == null, ctx.client);
275
+ const { resolved } = choice;
276
+ const configuredModelReplaced = choice.replacedDefault ?? null;
277
+ const serviceTier = serviceTierOrRefusal(input.serviceTier, ctx.config);
278
+ if (serviceTier instanceof ServiceTierError) {
279
+ return {
280
+ end: errorResult(`code: ${serviceTier.message}`, {
281
+ errorCode: serviceTier.code,
304
282
  retryable: false,
305
283
  serviceTier: 'flex',
306
284
  resolvedModel: resolved.resolved,
307
- configuredModelReplaced: choice.replacedDefault ?? null,
308
- });
309
- }
310
- modelAudit = {
311
- resolvedModel: resolved.resolved,
312
- configuredModelReplaced: choice.replacedDefault ?? null,
313
- serviceTier,
285
+ configuredModelReplaced,
286
+ }),
314
287
  };
315
- if (choice.replacedDefault !== undefined) {
316
- emitter.emit(`configured default model ${safeForLog(choice.replacedDefault)} replaced by ${CODE_FALLBACK_MODEL} for this call (code needs a thinking reasoning model)`);
317
- }
318
- resolvedModelKey = resolved.resolved;
319
- emitter.emit(`scanning workspace ${workspaceRoot}…`);
320
- // v1.13.0 — see ask.tool.ts for the scan-memo rationale. Same pattern.
321
- const scanMemo = buildScanMemo(ctx.manifest.getFiles(workspaceRoot));
322
- const scan = await scanWorkspace(workspaceRoot, {
323
- ...(input.includeGlobs !== undefined ? { includeGlobs: input.includeGlobs } : {}),
324
- ...(input.excludeGlobs !== undefined ? { excludeGlobs: input.excludeGlobs } : {}),
325
- maxFiles: ctx.config.maxFilesPerWorkspace,
326
- maxFileSizeBytes: ctx.config.maxFileSizeBytes,
327
- manifestMemo: scanMemo,
328
- forceRescan: input.forceRescan === true || ctx.config.forceRescan === true,
329
- });
330
- // Output-cap strategy (v1.4.0) — see ask.tool.ts for full rationale
331
- // of the three-layer precedence. Summary: input.maxOutputTokens
332
- // (per-call) > ctx.config.forceMaxOutputTokens (MCP-host env) >
333
- // auto (omit from wire; Gemini uses model-default). Code review
334
- // commonly produces long OLD/NEW diff blocks, so operators doing
335
- // heavy review work set `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true`
336
- // to pin every call at the model's full 65,536-token capacity.
337
- const CODE_MAX_OUTPUT_TOKENS_FALLBACK = 65_536;
338
- // The caller's `thinkingBudget` is checked against `outputCap` (the wire cap, else the model's per-request limit);
339
- // the clamp and the reservation use the cap that runs (`runCap`, after the input window's cut).
340
- const outputCap = resolveOutputCap({
341
- requested: input.maxOutputTokens,
342
- forceMax: ctx.config.forceMaxOutputTokens,
343
- outputTokenLimit: resolved.outputTokenLimit,
344
- longDecodeTokenLimit: resolved.longDecodeTokenLimit,
345
- fallbackLimit: CODE_MAX_OUTPUT_TOKENS_FALLBACK,
346
- });
347
- // A positive `thinkingBudget` that leaves no answer reserve under the caller's own cap is refused
348
- // (`thinkingBudgetRefusal`); below, the budget on the wire is clamped under the cap that runs.
349
- const budgetRefusal = thinkingBudgetRefusal(input.thinkingBudget, input.maxOutputTokens, outputCap.effective);
350
- if (budgetRefusal !== null)
351
- return errorResult(`code: ${budgetRefusal}`);
352
- // Shared input-token fingerprint for budget + TPM throttle (see
353
- // ask.tool.ts for the rationale — same `Math.ceil(bytes/4)` tokenisation
354
- // used by `estimatePreCallCostUsd`). The PREFLIGHT against
355
- // `inputTokenLimit` goes through the v1.10.0 two-tier `countForPreflight`
356
- // (heuristic for small repos; real `countTokens` near the cliff). Closes
357
- // T17 (`bytes/4` undercount on dense Unicode).
358
- const workspaceBytes = scan.files.reduce((sum, f) => sum + f.size, 0);
359
- const estimatedInputTokens = Math.ceil(workspaceBytes / 4) + Math.ceil(input.task.length / 4);
360
- // v1.5.0 preflight (rebuilt v1.10.0 atop countTokens) — mirror of
361
- // ask.tool.ts guard. See there for rationale. Hoisted so the
362
- // success-path metadata can surface preflight provenance.
363
- let preflight;
364
- const contextWindow = resolved.inputTokenLimit;
365
- // A decode that may take more than one request takes the exact count: its prompt is billed per request.
366
- const preflightMode = preflightModeFor(input.preflightMode, outputCap);
367
- if (typeof contextWindow === 'number' && contextWindow > 0) {
368
- preflight = await countForPreflight(ctx.client, {
369
- files: scan.files,
370
- prompt: input.task,
371
- model: resolved.resolved,
372
- // `filesHash` is post-glob-filter — no separate globsHash needed.
373
- filesHash: scan.filesHash,
374
- ...(preflightMode !== undefined ? { preflightMode } : {}),
375
- inputTokenLimit: contextWindow,
376
- // See ask.tool.ts for AbortSignal contract — abort propagates as
377
- // `AbortError` to outer catch (mapped to `errorCode: 'TIMEOUT'`).
378
- signal: abortSignal,
379
- });
380
- const threshold = Math.floor(contextWindow * ctx.config.workspaceGuardRatio);
381
- if (preflight.effectiveTokens > threshold) {
382
- const pctDisplay = Math.round(ctx.config.workspaceGuardRatio * 100);
383
- return errorResult(`Workspace too large for eager \`code\`: ~${preflight.effectiveTokens.toLocaleString()} input tokens (${preflight.method} count) 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).`, {
384
- errorCode: 'WORKSPACE_TOO_LARGE',
385
- retryable: false,
386
- estimatedInputTokens: preflight.effectiveTokens,
387
- tokenCountMethod: preflight.method,
388
- rawTokenCount: preflight.rawTokens,
389
- tokenCountCacheHit: preflight.cacheHit,
390
- contextWindowTokens: contextWindow,
391
- thresholdTokens: threshold,
392
- guardRatio: ctx.config.workspaceGuardRatio,
393
- ...modelAudit,
394
- filesIndexed: scan.files.length,
395
- });
396
- }
397
- }
398
- else {
399
- logger.warn(`code: resolved model ${safeForLog(resolved.resolved)} has no advertised inputTokenLimit — workspace size guard skipped. Request may fail downstream if the workspace exceeds the model's context window.`);
400
- }
401
- const { cap: runCap, cut: inputWindowCut } = capThatRuns({
402
- tool: 'code',
403
- cap: outputCap,
404
- promptTokens: preflight?.effectiveTokens,
405
- inputTokenLimit: contextWindow,
406
- emit: (message) => emitter.emit(message),
407
- });
408
- // The budget on the wire: clamped below the cap that runs, after the input window's cut — a cap cut to one
409
- // request goes on the wire as its cut value, and `thinkingBudget < maxOutputTokens` holds there too.
410
- const effectiveThinkingBudget = thinkingBudget !== undefined && thinkingBudget > 0
411
- ? thinkingBudgetUnder(runCap, thinkingBudget)
412
- : 0;
413
- // The thinking the budget reservation counts, from the cap that runs.
414
- const thinkingTokensForEstimate = thinkingReserve(input.thinkingLevel, effectiveThinkingBudget, runCap);
415
- // Atomic budget reservation — see ask.tool.ts for the full rationale.
416
- // Estimate includes the thinking budget (billed as output tokens on Pro)
417
- // PLUS the candidate output cap.
418
- if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
419
- const estimateUsd = estimatePreCallCostUsd({
420
- model: resolved.resolved,
421
- serviceTier,
422
- workspaceBytes,
423
- promptChars: input.task.length,
424
- expectedOutputTokens: runCap.effective,
425
- // A cap above the per-request limit (long decode) adds the input every continuation request bills again.
426
- perRequestOutputTokens: runCap.perRequest,
427
- // The preflight's count, when it ran: the reservation takes the larger of it and the bytes/4 heuristic.
428
- countedInputTokens: preflight?.effectiveTokens,
429
- thinkingTokens: thinkingTokensForEstimate,
430
- coverMs: timeoutController.timeoutMs,
431
- });
432
- const reserve = ctx.manifest.reserveBudget({
433
- workspaceRoot,
434
- toolName: 'code',
435
- model: resolved.resolved,
436
- estimatedCostMicros: toMicrosUsd(estimateUsd),
437
- dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
438
- nowMs: Date.now(),
439
- });
440
- if ('rejected' in reserve) {
441
- const spentUsd = reserve.spentMicros / 1_000_000;
442
- 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, ...modelAudit });
443
- }
444
- reservationId = reserve.id;
445
- }
446
- const systemPromptHash = createHash('sha256')
447
- .update(SYSTEM_INSTRUCTION_CODE)
448
- .digest('hex')
449
- .slice(0, 16);
450
- // v1.14.0 — `cachingMode` default flipped to `'implicit'` (resolved via
451
- // `ctx.config.cachingMode`, env-driven). codeExecution still forces inline
452
- // regardless because Gemini rejects `cachedContent` + `tools` together;
453
- // telemetry records the ACTUAL mode (FN2 fix) so the mode flip + the
454
- // codeExecution-forced-inline path stay distinguishable.
455
- const caching = cachingModeFor(input.cachingMode ?? ctx.config.cachingMode, resolved, emitter);
456
- const requestedCachingMode = caching.mode;
457
- // The context of the call: built here, and again by the stale-cache retry on a fresh cache.
458
- const prepare = () => prepareContext({
459
- client: ctx.client,
460
- manifest: ctx.manifest,
461
- scan,
462
- model: resolved,
463
- systemPromptHash,
464
- systemInstruction: SYSTEM_INSTRUCTION_CODE,
465
- ttlSeconds: ctx.config.cacheTtlSeconds,
466
- cacheMinTokens: ctx.config.cacheMinTokens,
467
- emitter,
468
- // codeExecution requires `tools:[{codeExecution:{}}]` on generateContent,
469
- // which Gemini rejects together with cachedContent. Force inline path
470
- // when codeExecution is requested so we have actual inline file parts
471
- // to embed alongside the prompt.
472
- allowCaching: scan.files.length > 0 && !codeExecution,
473
- // v1.12.1 — let `timeoutMs` interrupt the upload phase too.
474
- signal: abortSignal,
475
- // v1.13.0 — opt-in implicit caching path (skip caches.create).
476
- cachingMode: requestedCachingMode,
477
- });
478
- const ctxPrep = await prepare();
479
- const userPrompt = expectEdits
480
- ? `${input.task}\n\nRespond with your rationale and OLD/NEW diff blocks per the system instruction.`
481
- : input.task;
482
- const thinkingDescription = usingThinkingLevel
483
- ? `thinking-level=${input.thinkingLevel}`
484
- : `thinking=${effectiveThinkingBudget}`;
485
- emitter.emit(codeExecution
486
- ? `generating with ${thinkingDescription} + codeExecution…`
487
- : `generating with ${thinkingDescription}…`);
488
- // Two mutually-exclusive reasoning-control paths (enforced by schema
489
- // `.refine()`):
490
- // a) `thinkingLevel` set → cast to the SDK enum and pass through.
491
- // Google's recommended path on Gemini 3. Rejected by Gemini 2.5.
492
- // Cast rather than runtime enum-object lookup so a future SDK
493
- // rename surfaces as a Gemini 400, not a silent `undefined`.
494
- // b) `thinkingBudget` path (default 16_384, clamped above) → pass
495
- // `thinkingBudget` as before.
496
- // `includeThoughts: true` is unconditional so `thinkingSummary`
497
- // extraction below always has material to find.
498
- const thinkingConfig = usingThinkingLevel
499
- ? {
500
- thinkingLevel: input.thinkingLevel,
501
- includeThoughts: true,
502
- }
503
- : { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
504
- // Gemini rejects generateContent({cachedContent, system_instruction|tools|tool_config})
505
- // with 400. System instruction is baked into the cache at build time; tools
506
- // (codeExecution) cannot be combined with a cache built without them. When
507
- // codeExecution is requested AND a cache is active, we can't use both — in that
508
- // case we bypass the cache so the user's explicit codeExecution request wins.
509
- const canUseCache = (cacheId) => cacheId !== null && !codeExecution;
510
- if (ctxPrep.cacheId && codeExecution) {
511
- logger.warn('code({ codeExecution: true }) is incompatible with an active cache; bypassing cache for this call.');
512
- }
513
- const tierField = serviceTierConfig(serviceTier);
514
- const buildConfig = (cacheId) => {
515
- const maxOutputField = runCap.wire !== undefined ? { maxOutputTokens: runCap.wire } : {};
516
- if (canUseCache(cacheId) && cacheId) {
517
- // With cache: system_instruction is baked in; thinkingConfig remains OK.
518
- // `maxOutputTokens` only emitted when the caller set it explicitly
519
- // or `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true` — otherwise omit
520
- // and Gemini uses its model-default.
521
- return {
522
- cachedContent: cacheId,
523
- thinkingConfig,
524
- ...maxOutputField,
525
- ...tierField,
526
- };
527
- }
528
- // Without cache (or cache bypassed for codeExecution): pass full config.
529
- return {
530
- systemInstruction: SYSTEM_INSTRUCTION_CODE,
531
- thinkingConfig,
532
- ...tierField,
533
- ...maxOutputField,
534
- ...(codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
535
- };
288
+ }
289
+ const audit = {
290
+ resolvedModel: resolved.resolved,
291
+ configuredModelReplaced,
292
+ serviceTier,
293
+ };
294
+ eager.trail.model = audit;
295
+ if (choice.replacedDefault !== undefined) {
296
+ eager.emitter.emit(`configured default model ${safeForLog(choice.replacedDefault)} replaced by ${CODE_FALLBACK_MODEL} for this call (code needs a thinking reasoning model)`);
297
+ }
298
+ return { next: { ...call, resolved, serviceTier, audit } };
299
+ }
300
+ /**
301
+ * Scan the workspace and hold the call against the model's window — the same guard as `ask`'s, with no fallback. A
302
+ * positive `thinkingBudget` that leaves no answer reserve under the caller's own cap is refused first
303
+ * (`thinkingBudgetRefusal`; the budget on the wire is clamped under the cap that runs later).
304
+ */
305
+ async function guardCode(call) {
306
+ const { input, ctx, eager, resolved } = call;
307
+ const scan = await scanForCall(eager, ctx, input);
308
+ const outputCap = eagerOutputCap(input.maxOutputTokens, ctx, resolved);
309
+ const budgetRefusal = thinkingBudgetRefusal(input.thinkingBudget, input.maxOutputTokens, outputCap.effective);
310
+ if (budgetRefusal !== null)
311
+ return { end: errorResult(`code: ${budgetRefusal}`) };
312
+ const estimate = estimateInput(scan, input.task, 0);
313
+ const count = await countPreflight(eager, ctx, {
314
+ scan,
315
+ prompt: input.task,
316
+ resolved,
317
+ mode: input.preflightMode,
318
+ cap: outputCap,
319
+ extraTokens: 0,
320
+ });
321
+ const counted = { ...call, scan, outputCap, estimate, count };
322
+ const over = overWindow(count, ctx);
323
+ if (over !== null)
324
+ return { end: codeTooLargeResult(counted, over) };
325
+ return { next: counted };
326
+ }
327
+ /** The refusal of a workspace over the window, with the ways out. */
328
+ function codeTooLargeResult(call, over) {
329
+ const { counted, threshold, contextWindow } = over;
330
+ return errorResult(`Workspace too large for eager \`code\`: ~${counted.effectiveTokens.toLocaleString()} input tokens (${counted.method} count) exceeds ${threshold.toLocaleString()} (${over.pctDisplay}% of ${call.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).`, {
331
+ errorCode: 'WORKSPACE_TOO_LARGE',
332
+ retryable: false,
333
+ estimatedInputTokens: counted.effectiveTokens,
334
+ tokenCountMethod: counted.method,
335
+ rawTokenCount: counted.rawTokens,
336
+ tokenCountCacheHit: counted.cacheHit,
337
+ contextWindowTokens: contextWindow,
338
+ thresholdTokens: threshold,
339
+ guardRatio: call.ctx.config.workspaceGuardRatio,
340
+ ...call.audit,
341
+ filesIndexed: call.scan.files.length,
342
+ });
343
+ }
344
+ /**
345
+ * Size the call: the output cap bounded by the model's input window (a cut is said on the progress channel and the
346
+ * log), the budget clamped under it, then the reservation — the thinking it counts from the cap that runs.
347
+ */
348
+ function sizeCode(call) {
349
+ const { input, eager } = call;
350
+ const bounded = capThatRuns({
351
+ tool: 'code',
352
+ cap: call.outputCap,
353
+ promptTokens: call.count?.preflight.effectiveTokens,
354
+ inputTokenLimit: call.resolved.inputTokenLimit,
355
+ emit: (message) => eager.emitter.emit(message),
356
+ });
357
+ const thinkingBudget = codeThinkingBudget(input, bounded.cap);
358
+ const sized = { ...call, bounded, thinkingBudget };
359
+ const refusal = reserveCallBudget(eager, call.ctx, sized, {
360
+ promptChars: input.task.length,
361
+ extraInputTokens: 0,
362
+ thinkingTokens: thinkingReserve(input.thinkingLevel, thinkingBudget, bounded.cap),
363
+ });
364
+ if (refusal !== null) {
365
+ return {
366
+ end: errorResult(refusal, {
367
+ errorCode: 'BUDGET_REJECT',
368
+ retryable: false,
369
+ ...call.audit,
370
+ }),
536
371
  };
537
- const buildContents = (cacheId, inline) => canUseCache(cacheId)
372
+ }
373
+ return { next: sized };
374
+ }
375
+ /**
376
+ * The budget on the wire: the caller's `thinkingBudget`, else `code`'s default, clamped below the cap that runs —
377
+ * after the input window's cut, so under a cap cut to one request `thinkingBudget < maxOutputTokens` holds too. `0` on
378
+ * the `thinkingLevel` path (schema `.refine()` guarantees the two are never both set) and for a budget of `0`.
379
+ */
380
+ function codeThinkingBudget(input, cap) {
381
+ if (input.thinkingLevel !== undefined)
382
+ return 0;
383
+ const budget = input.thinkingBudget ?? CODE_DEFAULT_THINKING_BUDGET;
384
+ return budget > 0 ? thinkingBudgetUnder(cap, budget) : 0;
385
+ }
386
+ /**
387
+ * Prepare the context — a cache only with files and without `codeExecution` (a cache cannot be combined with `tools`:
388
+ * the files go inline) —, decode, parse the artefacts, then book the answer once. The artefacts are parsed BEFORE the
389
+ * settlement: a failure there is booked at the completed requests and reports their usage. The stop at the output cap
390
+ * is returned before the truncated-scan warning.
391
+ */
392
+ async function answerCode(call) {
393
+ const { input, ctx, eager, scan } = call;
394
+ const context = await prepareCallContext(eager, ctx, {
395
+ scan,
396
+ resolved: call.resolved,
397
+ systemInstruction: SYSTEM_INSTRUCTION_CODE,
398
+ allowCaching: scan.files.length > 0 && !call.codeExecution,
399
+ requestedMode: input.cachingMode ?? ctx.config.cachingMode,
400
+ });
401
+ eager.emitter.emit(codeGeneratingLine(call));
402
+ const decoded = await decodeEagerCall(eager, ctx, call, codeRequest(call, context.prepared), context);
403
+ const artifacts = codeArtifacts(decoded.response, call.expectEdits);
404
+ const settledDecode = settleDecoded(eager, ctx, decoded, call, context.caching);
405
+ const stop = settledDecode.settled.outputCapStop;
406
+ // Settled and billed above; an empty answer at the cap is a failure the caller can act on, never a success.
407
+ if (stop !== null)
408
+ return errorResult(`code: ${stop.message}`, { ...call.audit, ...stop.fields });
409
+ warnTruncatedScan(eager, ctx, scan);
410
+ return codeAnswerResult(call, decoded, settledDecode, artifacts);
411
+ }
412
+ /** The progress line that opens the decode. */
413
+ function codeGeneratingLine(call) {
414
+ const level = call.input.thinkingLevel;
415
+ const thinking = level !== undefined ? `thinking-level=${level}` : `thinking=${call.thinkingBudget}`;
416
+ return call.codeExecution
417
+ ? `generating with ${thinking} + codeExecution…`
418
+ : `generating with ${thinking}…`;
419
+ }
420
+ /**
421
+ * The request builder of one call; what a cached context forbids is `RequestBuilder`'s rule
422
+ * (`./shared/eager-answer.ts`). `tools` (`codeExecution`) are among it, so with `codeExecution` an active cache is
423
+ * bypassed (said in the log) and the caller's explicit request wins. The user prompt asks for OLD/NEW blocks when
424
+ * edits are expected.
425
+ */
426
+ function codeRequest(call, prepared) {
427
+ const { codeExecution } = call;
428
+ const userPrompt = call.expectEdits
429
+ ? `${call.input.task}\n\nRespond with your rationale and OLD/NEW diff blocks per the system instruction.`
430
+ : call.input.task;
431
+ const canUseCache = (cacheId) => cacheId !== null && !codeExecution;
432
+ if (prepared.cacheId && codeExecution) {
433
+ logger.warn('code({ codeExecution: true }) is incompatible with an active cache; bypassing cache for this call.');
434
+ }
435
+ const config = codeConfig(call, canUseCache);
436
+ return (prep) => ({
437
+ contents: canUseCache(prep.cacheId)
538
438
  ? userPrompt
539
- : [...inline, { role: 'user', parts: [{ text: userPrompt }] }];
540
- // The decode and its one stale-cache retry — the shared path of `ask` and `code` (see ask.tool.ts).
541
- const decoded = await decodeOnContext({
542
- client: ctx.client,
543
- booking: { workspaceRoot, toolName: 'code', model: resolved.resolved, serviceTier },
544
- // `cachingRan`: a codeExecution call is forced inline and never builds a cache.
545
- cachingMode: (prep) => cachingRan(prep, caching).mode,
546
- request: (prep) => ({
547
- contents: buildContents(prep.cacheId, prep.inlineContents),
548
- config: buildConfig(prep.cacheId),
549
- }),
550
- cache: {
551
- ttlWatcher: ctx.ttlWatcher,
552
- manifest: ctx.manifest,
553
- ttlSeconds: ctx.config.cacheTtlSeconds,
554
- prepare,
555
- },
556
- openAttempts: networkAttempts(serviceTier), // a flex request is never re-sent
557
- limits: { maxRequests: runCap.maxRequests, cap: runCap.effective },
558
- timeout: timeoutController,
559
- emit: (message) => emitter.emit(message),
560
- completed,
561
- tracking,
562
- throttle: dispatch,
563
- inputTokens: { estimated: estimatedInputTokens, counted: preflight?.effectiveTokens },
564
- }, ctxPrep);
565
- const { response, prep: activePrep, retriedOnStaleCache } = decoded;
566
- const text = response.text;
567
- const edits = expectEdits ? parseEdits(text) : [];
568
- const codeBlocks = parseCodeBlocks(text);
569
- // Extract code_execution tool artifacts. Thought summary now comes from
570
- // `collectStream` (T20) — `response.thoughtsSummary` is already capped
571
- // and matches the live progress emit. We still iterate candidates here
572
- // for executableCode / codeExecutionResult parts (those aren't
573
- // accumulated by collectStream — they're full per-chunk artefacts).
574
- const executedCode = [];
575
- const executionOutput = [];
576
- const candidates = response.candidates ?? [];
577
- for (const cand of candidates) {
578
- const parts = cand.content?.parts ?? [];
579
- for (const part of parts) {
580
- if (part.executableCode?.code)
581
- executedCode.push(part.executableCode.code);
582
- if (part.codeExecutionResult?.output)
583
- executionOutput.push(part.codeExecutionResult.output);
584
- }
585
- }
586
- const thinkingSummary = response.thoughtsSummary;
587
- // Telemetry and the response record the mode that ran, not the one asked for
588
- // (`cachingRan`: a codeExecution call is forced inline and never builds a cache).
589
- const ran = cachingRan(activePrep, caching);
590
- const effectiveCachingMode = ran.mode;
591
- const durationMs = Date.now() - started;
592
- // Settled here, once: the outer catch then neither releases the reservation nor books the call again. What the
593
- // API billed is every request that completed, over a long decode and a stale-cache retry alike.
594
- const settledReservation = reservationId;
595
- reservationId = null;
596
- tracking.ledgerEntry = null;
597
- const settled = settleAnswer({
598
- manifest: ctx.manifest,
599
- reservationId: settledReservation,
600
- entry: {
601
- workspaceRoot,
602
- toolName: 'code',
603
- model: resolved.resolved,
604
- serviceTier,
605
- cachingMode: effectiveCachingMode,
606
- },
607
- completed,
608
- response,
609
- cap: runCap,
610
- cut: inputWindowCut,
611
- durationMs,
612
- });
613
- const finish = settled.finish;
614
- // Settled and billed above; an empty answer at the cap is a failure the caller can act on, never a success.
615
- if (settled.outputCapStop !== null) {
616
- return errorResult(`code: ${settled.outputCapStop.message}`, {
617
- ...modelAudit,
618
- ...settled.outputCapStop.fields,
619
- });
620
- }
621
- if (scan.truncated) {
622
- logger.warn(`workspace ${workspaceRoot} contains more files than GEMINI_CODE_CONTEXT_MAX_FILES (${ctx.config.maxFilesPerWorkspace}); the tail was dropped before indexing.`);
439
+ : [...prep.inlineContents, { role: 'user', parts: [{ text: userPrompt }] }],
440
+ config: config(prep.cacheId),
441
+ });
442
+ }
443
+ /**
444
+ * The `config` of every request. With a cache, `cachedContent` and `thinkingConfig`; without one — or with the cache
445
+ * bypassed for `codeExecution` — the full config, `tools` with `codeExecution`. `maxOutputTokens` goes on the wire only when the cap has a wire value (the caller's
446
+ * `maxOutputTokens`, `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true`, or a cap the input window cut); otherwise Gemini
447
+ * applies the model's default.
448
+ */
449
+ function codeConfig(call, canUseCache) {
450
+ const thinkingConfig = codeThinkingConfig(call);
451
+ const tierField = serviceTierConfig(call.serviceTier);
452
+ const cap = call.bounded.cap;
453
+ return (cacheId) => {
454
+ const maxOutputField = cap.wire !== undefined ? { maxOutputTokens: cap.wire } : {};
455
+ if (canUseCache(cacheId) && cacheId) {
456
+ return { cachedContent: cacheId, thinkingConfig, ...maxOutputField, ...tierField };
623
457
  }
624
- const structured = {
625
- ...modelAudit,
626
- requestedModel: resolved.requested,
627
- modelCategory: resolved.category,
628
- modelCostTier: resolved.capabilities.costTier,
629
- contextWindow: resolved.inputTokenLimit,
630
- // `thinkingBudget` echoes the clamped value actually sent on the
631
- // wire; it's only meaningful on the budget path. On the
632
- // `thinkingLevel` path nothing is sent for `thinkingBudget`, so we
633
- // emit `null` (not `0`) — `0` is the wire sentinel for "thinking
634
- // disabled" and reporting it here for a level-path call would lie
635
- // to downstream audit / dashboard consumers (PR #17 self-review F1,
636
- // 3-reviewer consensus: GPT + Copilot + Self). Matches `ask.tool.ts`.
637
- thinkingBudget: usingThinkingLevel ? null : effectiveThinkingBudget,
638
- thinkingLevel: input.thinkingLevel ?? null,
639
- codeExecutionUsed: codeExecution,
640
- cacheHit: activePrep.reused,
641
- cacheRebuilt: activePrep.rebuilt || retriedOnStaleCache,
642
- retriedOnStaleCache,
643
- ...settled.usage,
644
- ...settled.cutFields,
645
- // `truncated`: the answer stopped at the output cap (MAX_TOKENS, or a long decode at its limits) — it is cut
646
- finishReason: finish.finishReason,
647
- truncated: finish.truncated,
648
- durationMs,
649
- edits: edits.map((e) => ({
650
- file: e.file,
651
- oldPreview: e.old.slice(0, 120),
652
- newPreview: e.new.slice(0, 120),
653
- })),
654
- editCount: edits.length,
655
- codeBlocks: codeBlocks.map((b) => ({ lang: b.lang, length: b.content.length })),
656
- workspaceTruncated: scan.truncated,
657
- maxFilesCap: ctx.config.maxFilesPerWorkspace,
658
- filesIndexed: scan.files.length,
659
- excludedDirs: scan.excludedDirs,
660
- excludedDirsTotal: scan.excludedDirsTotal,
661
- filesSkippedNonSource: scan.skippedNonSource,
662
- filesUploadFailed: activePrep.uploaded.failedCount,
663
- ...(activePrep.uploaded.failedCount > 0
664
- ? { uploadFailures: activePrep.uploaded.failures.slice(0, 5) }
665
- : {}),
666
- inlineOnly: activePrep.inlineOnly,
667
- cachingMode: effectiveCachingMode,
668
- ...(ran.note !== null ? { cachingModeNote: ran.note } : {}),
669
- // Preflight token-count provenance — surfaces on every successful
670
- // call. See ask.tool.ts for the contract; same fields apply here.
671
- ...(preflight !== undefined
672
- ? {
673
- tokenCountMethod: preflight.method,
674
- rawTokenCount: preflight.rawTokens,
675
- tokenCountCacheHit: preflight.cacheHit,
676
- }
677
- : {}),
678
- ...(thinkingSummary ? { thinkingSummary } : {}),
679
- ...(executedCode.length > 0 ? { executedCode } : {}),
680
- ...(executionOutput.length > 0 ? { executionOutput } : {}),
458
+ return {
459
+ systemInstruction: SYSTEM_INSTRUCTION_CODE,
460
+ thinkingConfig,
461
+ ...tierField,
462
+ ...maxOutputField,
463
+ ...(call.codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
681
464
  };
682
- return textResult(finish.truncated ? `${truncatedNote(expectEdits)}\n\n${text}` : text, structured);
683
- }
684
- catch (err) {
685
- logger.error(`code failed: ${safeForLog(err)}`);
686
- // A 429's retry hint seeds the throttle; the ledger keeps what the completed requests billed and releases the rest
687
- // (all of it when none completed).
688
- const failedUsage = settleFailure({
689
- manifest: ctx.manifest,
690
- failed: {
691
- toolName: 'code',
692
- reservationId,
693
- entry: tracking.ledgerEntry,
694
- completed,
695
- durationMs: Date.now() - started,
696
- },
697
- err,
698
- model: resolvedModelKey,
699
- throttle: ctx.throttle,
700
- dispatch,
701
- });
702
- reservationId = null;
703
- // v1.12.0 — `timeoutKind` distinguishes wall-clock cap from stall watchdog.
704
- if (isTimeoutAbort(err)) {
705
- const timedOut = timedOutCall('code', err, timeoutController);
706
- emitter.emit(`code: aborted after ${timedOut.limitMs ?? '?'}ms ${timedOut.kind}`);
707
- return errorResult(timedOut.message, {
708
- errorCode: 'TIMEOUT',
709
- timeoutKind: timedOut.kind,
710
- timeoutMs: timeoutController.timeoutMs,
711
- stallMs: timeoutController.stallMs,
712
- retryable: true,
713
- ...modelAudit,
714
- ...failedUsage,
715
- });
465
+ };
466
+ }
467
+ /**
468
+ * The `thinkingConfig` of every request: the caller's `thinkingLevel` (`levelThinkingConfig`), else the budget.
469
+ * `includeThoughts: true` always, so the answer has a thought summary to report.
470
+ */
471
+ function codeThinkingConfig(call) {
472
+ const level = call.input.thinkingLevel;
473
+ return level !== undefined
474
+ ? levelThinkingConfig(level)
475
+ : { thinkingBudget: call.thinkingBudget, includeThoughts: true };
476
+ }
477
+ /**
478
+ * The answer's artefacts: the OLD/NEW edits (when asked for), the code blocks, and the Code Execution tool's
479
+ * `executableCode` / `codeExecutionResult` parts, which the stream collector does not accumulate — they are whole
480
+ * per-chunk artefacts, read from the candidates.
481
+ */
482
+ function codeArtifacts(response, expectEdits) {
483
+ const { text } = response;
484
+ const edits = expectEdits ? parseEdits(text) : [];
485
+ const codeBlocks = parseCodeBlocks(text);
486
+ return { edits, codeBlocks, ...executionParts(response) };
487
+ }
488
+ /** The Code Execution tool's parts of every candidate, in their order. */
489
+ function executionParts(response) {
490
+ const executedCode = [];
491
+ const executionOutput = [];
492
+ for (const cand of response.candidates ?? []) {
493
+ for (const part of cand.content?.parts ?? []) {
494
+ if (part.executableCode?.code)
495
+ executedCode.push(part.executableCode.code);
496
+ if (part.codeExecutionResult?.output)
497
+ executionOutput.push(part.codeExecutionResult.output);
716
498
  }
717
- const httpStatus = statusOf(err);
718
- return errorResult(`code failed: ${err instanceof Error ? err.message : String(err)}`, {
719
- ...tierErrorMeta(err, tracking.streamOpened),
720
- ...(httpStatus !== undefined ? { httpStatus } : {}),
721
- serviceTier: input.serviceTier ?? ctx.config.serviceTier, // before the model is resolved: the requested tier
722
- ...modelAudit,
723
- ...failedUsage,
724
- });
725
499
  }
726
- finally {
727
- timeoutController.dispose();
728
- emitter.stop();
500
+ return { executedCode, executionOutput };
501
+ }
502
+ /** The answer: its text, led by the truncation note when it was cut, and what the call ran on and produced. */
503
+ function codeAnswerResult(call, decoded, settledDecode, artifacts) {
504
+ const { response } = decoded;
505
+ const { finish } = settledDecode.settled;
506
+ const { executedCode, executionOutput } = artifacts;
507
+ // the thought summary as the stream collector capped it, the same the progress channel showed
508
+ const thinkingSummary = response.thoughtsSummary;
509
+ return textResult(finish.truncated ? `${truncatedNote(call.expectEdits)}\n\n${response.text}` : response.text, {
510
+ ...codeModelFields(call),
511
+ ...codeDecodeFields(decoded, settledDecode),
512
+ ...artifactFields(artifacts),
513
+ ...codeWorkspaceFields(call, decoded.prep, settledDecode.ran),
514
+ ...preflightFields(call.count),
515
+ ...(thinkingSummary ? { thinkingSummary } : {}),
516
+ ...(executedCode.length > 0 ? { executedCode } : {}),
517
+ ...(executionOutput.length > 0 ? { executionOutput } : {}),
518
+ });
519
+ }
520
+ /**
521
+ * The audit, the model and the thinking the call ran with. `thinkingBudget` is the clamped value sent on the wire;
522
+ * on the `thinkingLevel` path nothing is sent, so it is `null`, never `0` — the wire's "thinking disabled" — as
523
+ * `ask` reports it.
524
+ */
525
+ function codeModelFields(call) {
526
+ const { resolved, input } = call;
527
+ return {
528
+ ...call.audit,
529
+ requestedModel: resolved.requested,
530
+ modelCategory: resolved.category,
531
+ modelCostTier: resolved.capabilities.costTier,
532
+ contextWindow: resolved.inputTokenLimit,
533
+ thinkingBudget: input.thinkingLevel !== undefined ? null : call.thinkingBudget,
534
+ thinkingLevel: input.thinkingLevel ?? null,
535
+ codeExecutionUsed: call.codeExecution,
536
+ };
537
+ }
538
+ /** The context the decode ran on, what it billed and how it ended. */
539
+ function codeDecodeFields(decoded, settledDecode) {
540
+ const { prep, retriedOnStaleCache } = decoded;
541
+ const { settled, durationMs } = settledDecode;
542
+ return {
543
+ cacheHit: prep.reused,
544
+ cacheRebuilt: prep.rebuilt || retriedOnStaleCache,
545
+ retriedOnStaleCache,
546
+ ...settled.usage,
547
+ ...settled.cutFields,
548
+ // `truncated`: the answer stopped at the output cap (MAX_TOKENS, or a long decode at its limits) — it is cut
549
+ finishReason: settled.finish.finishReason,
550
+ truncated: settled.finish.truncated,
551
+ durationMs,
552
+ };
553
+ }
554
+ /** The edits as previews, the code blocks as their lengths. */
555
+ function artifactFields(artifacts) {
556
+ const { edits, codeBlocks } = artifacts;
557
+ return {
558
+ edits: edits.map((e) => ({
559
+ file: e.file,
560
+ oldPreview: e.old.slice(0, 120),
561
+ newPreview: e.new.slice(0, 120),
562
+ })),
563
+ editCount: edits.length,
564
+ codeBlocks: codeBlocks.map((b) => ({ lang: b.lang, length: b.content.length })),
565
+ };
566
+ }
567
+ /** What the scan indexed and dropped, what the upload could not send, and the caching mode that ran. */
568
+ function codeWorkspaceFields(call, prep, ran) {
569
+ const { scan } = call;
570
+ return {
571
+ workspaceTruncated: scan.truncated,
572
+ maxFilesCap: call.ctx.config.maxFilesPerWorkspace,
573
+ filesIndexed: scan.files.length,
574
+ ...scanFields(scan, prep),
575
+ inlineOnly: prep.inlineOnly,
576
+ cachingMode: ran.mode,
577
+ ...(ran.note !== null ? { cachingModeNote: ran.note } : {}),
578
+ };
579
+ }
580
+ /**
581
+ * `code`'s result of a failed call: its model audit once the model resolved, none before — a timeout then carries no
582
+ * tier, any other failure the requested one.
583
+ */
584
+ function codeFailedResult(failure) {
585
+ if (failure.kind === 'timeout') {
586
+ return errorResult(failure.timedOut.message, {
587
+ errorCode: 'TIMEOUT',
588
+ timeoutKind: failure.timedOut.kind,
589
+ timeoutMs: failure.timeoutMs,
590
+ stallMs: failure.stallMs,
591
+ retryable: true,
592
+ ...failure.model,
593
+ ...failure.usage,
594
+ });
729
595
  }
596
+ return errorResult(failure.message, {
597
+ ...failure.tierMeta,
598
+ ...(failure.httpStatus !== undefined ? { httpStatus: failure.httpStatus } : {}),
599
+ serviceTier: failure.requestedTier, // the audit's tier replaces it once the model resolved
600
+ ...failure.model,
601
+ ...failure.usage,
602
+ });
730
603
  }
731
604
  //# sourceMappingURL=code.tool.js.map