@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
@@ -6,154 +6,17 @@
6
6
  * uploads the workspace once and builds a persistent Context Cache (measured
7
7
  * 2026-04-22 on a 670 k-token workspace: first call ~125 s, repeats ~14 s).
8
8
  */
9
- import { createHash } from 'node:crypto';
10
9
  import { resolve } from 'node:path';
11
- import { z } from 'zod';
12
- import { AttachmentError, AttachmentTokensUncountedError, INLINE_REQUEST_LIMIT_BYTES, MAX_ATTACHMENTS, MAX_ATTACHMENTS_TOTAL_BYTES, MAX_ATTACHMENT_BYTES, countAttachmentTokens, inlineRequestBytes, inspectAttachments, readAttachments, } from '../attachments.js';
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';
16
- import { resolveModel } from '../gemini/models.js';
17
- import { countForPreflight } from '../gemini/token-counter.js';
18
- import { buildScanMemo, scanWorkspace } from '../indexer/workspace-scanner.js';
19
- import { WorkspaceValidationError, validateWorkspacePath, } from '../indexer/workspace-validation.js';
20
- import { estimatePreCallCostUsd, toMicrosUsd } from '../utils/cost-estimator.js';
21
- import { logger, safeForLog } from '../utils/logger.js';
22
- import { createProgressEmitter } from '../utils/progress.js';
23
- import { fallBackToAgentic } from './ask-agentic-fallback.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 { PROMPT_FIELD, WORKSPACE_FIELD } from './shared/question-fields.js';
30
- import { SERVICE_TIER_DESCRIPTION, ServiceTierError, networkAttempts, resolveServiceTier, serviceTierConfig, statusOf, tierErrorMeta, } from './shared/service-tier.js';
31
- import { settleAnswer, settleFailure } from './shared/settle-call.js';
32
- import { SYSTEM_INSTRUCTION_SAFETY_EAGER } from './shared/system-instruction-safety.js';
33
- import { THINKING_LEVEL_FIELD, thinkingBudgetUnder, thinkingReserve } from './shared/thinking.js';
34
- /**
35
- * `ask` system instruction. Prepends the shared `SYSTEM_INSTRUCTION_SAFETY_EAGER`
36
- * data-vs-instruction firewall (added in v1.15.2 — pre-v1.15.2 `ask` had no
37
- * safety rules at all, leaving it open to indirect prompt injection via
38
- * adversarial workspace file content; same risk profile as v1.14.4 A1' for
39
- * `ask_agentic`'s rescue path, just for the eager workspace upload channel).
40
- *
41
- * The role-statement after the safety block is the original v1.0 wording —
42
- * task-specific guidance lives there; cross-tool security boundaries live
43
- * in the shared safety block above.
44
- */
45
- const SYSTEM_INSTRUCTION_Q_AND_A = [
46
- SYSTEM_INSTRUCTION_SAFETY_EAGER,
47
- '',
48
- 'You are a senior software engineer analysing a codebase. Be precise, reference specific file paths and line numbers, and cite evidence from the provided files rather than guessing. If the answer is not derivable from the context, say so.',
49
- ].join('\n');
50
- /**
51
- * Fallback output cap used only when the resolved model doesn't advertise
52
- * an `outputTokenLimit` via `models.list()`. Set generously at the current
53
- * Gemini pro-tier ceiling so the default behaviour is "let the model use
54
- * its full trained capacity" — per v1.4.0 user feedback, arbitrary
55
- * internal caps below the model's advertised limit are unhelpful
56
- * self-limiting. Callers who want tighter caps for specific calls pass
57
- * `maxOutputTokens` explicitly in the tool input.
58
- */
59
- const ASK_MAX_OUTPUT_TOKENS_FALLBACK = 65_536;
60
- /**
61
- * Sentinel value in our internal normalisation for "user did not pass
62
- * thinkingBudget". We translate this into an OMITTED `thinkingBudget`
63
- * field on the wire — Gemini then uses each model's native default, which
64
- * per Google's Gemini 3 guide (https://ai.google.dev/gemini-api/docs/gemini-3)
65
- * is HIGH-dynamic on Gemini 3 Pro. Google flags explicit `thinkingBudget`
66
- * as the "legacy" path on Gemini 3 ("may result in unexpected performance"),
67
- * and we empirically observed Gemini 3 Pro hanging on low positive budgets
68
- * with cached content active (see docs/KNOWN-DEFICITS.md). Omitting the
69
- * field sidesteps both issues while still letting power users opt into
70
- * explicit budgets on Gemini 2.5 or for cost-bounded deep-dives.
71
- */
72
- const THINKING_BUDGET_MODEL_DEFAULT = null;
73
- // `THINKING_LEVELS` + `THINKING_LEVEL_RESERVE` live in `./shared/thinking.ts`
74
- // so both `ask` and `code` share a single source of truth — when Google
75
- // publishes per-tier token budgets, one edit propagates to both tools.
76
- export const askInputSchema = z
77
- .object({
78
- prompt: PROMPT_FIELD,
79
- workspace: WORKSPACE_FIELD,
80
- model: z
81
- .string()
82
- .optional()
83
- .describe("Model alias ('latest-pro', 'latest-pro-thinking', 'latest-flash', 'latest-lite', 'latest-vision') or literal model ID. Defaults to the configured default."),
84
- includeGlobs: z
85
- .array(z.string())
86
- .optional()
87
- .describe('Additional file extensions or filenames to include.'),
88
- excludeGlobs: z
89
- .array(z.string())
90
- .optional()
91
- .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.'),
92
- noCache: z
93
- .boolean()
94
- .optional()
95
- .describe('Skip the context cache and embed files inline (slower, more expensive).'),
96
- thinkingBudget: z
97
- .number()
98
- .int()
99
- .min(-1)
100
- .max(65_536)
101
- .optional()
102
- .describe("Explicit reasoning-token cap. OMIT to use each model's native default — recommended on Gemini 3 (Google flags explicit `thinkingBudget` as 'legacy'). Pass a value only when you need a specific cap: `-1` = legacy dynamic, `0` = disable thinking (rejected by Gemini 3 Pro), positive integer = fixed cap. CAVEAT on Gemini 3 Pro: low positive values (empirically ≤256 with cached content) can cause the API to hang — use `-1` or ≥4096 if you must bound it there. For discrete-tier control on Gemini 3 use `thinkingLevel` instead — the two are mutually exclusive."),
103
- thinkingLevel: THINKING_LEVEL_FIELD,
104
- maxOutputTokens: z
105
- .number()
106
- .int()
107
- .min(1)
108
- .optional()
109
- .describe([
110
- "Per-call opt-in cap on response length (tokens). OMIT for the default 'auto' behaviour — 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 when you want a bounded response (e.g. strict summary length, tighter budget per call). On any other model a value larger than the resolved model's limit is clamped down to it. Budget reservation always uses the effective cap (explicit OR model limit) as worst-case, so `GEMINI_DAILY_BUDGET_USD` bounds what a completed call books (a request aborted mid-stream is booked 0: docs/cost-model.md).",
111
- LONG_DECODE_CAP_DESCRIPTION,
112
- ].join(' ')),
113
- timeoutMs: z
114
- .number()
115
- .int()
116
- .min(1_000)
117
- .max(1_800_000)
118
- .optional()
119
- .describe('Per-call wall-clock TOTAL timeout in ms (1s–30min). The cost ceiling — aborts the in-flight `generateContent` request even if it is actively streaming. A request aborted after its stream opened is booked 0; whether Google bills it is not measured (docs/cost-model.md). When omitted, falls back to env var `GEMINI_CODE_CONTEXT_ASK_TIMEOUT_MS`, then to disabled. v1.12.0 RECOMMENDATION: prefer `stallMs` for liveness — `timeoutMs` is the cost cap, `stallMs` is the heartbeat-aware liveness watchdog that does NOT fire while the model is actively thinking. Both can be set simultaneously. Returns `errorCode: "TIMEOUT"` with `timeoutKind: "total"` on abort.'),
120
- stallMs: z
121
- .number()
122
- .int()
123
- .min(1_000)
124
- .max(600_000)
125
- .optional()
126
- .describe('Per-call HEARTBEAT-AWARE stall watchdog in ms (1s–10min, v1.12.0+). Resets on every chunk (text or thought) — fires ONLY when the stream goes silent for this long. Does NOT fire while the model is actively thinking — the streaming heartbeat (every ~1500ms via `onThoughtChunk`) keeps the watchdog reset. This is the right knob for "kill dead sockets quickly without penalising deep reasoning." Recommended setting: `60_000` (60s) — Gemini Pro can pause 15-30s mid-reasoning between thought chunks under heavy thinking; 60s absorbs jitter while still killing truly dead sockets ~30× faster than the wall-clock alternative. When omitted, falls back to env var `GEMINI_CODE_CONTEXT_ASK_STALL_MS`, then to disabled. Returns `errorCode: "TIMEOUT"` with `timeoutKind: "stall"` on abort. Independent of `timeoutMs` — both can be set; whichever fires first wins.'),
127
- preflightMode: z
128
- .enum(['heuristic', 'exact', 'auto'])
129
- .optional()
130
- .describe("Token-count strategy for the WORKSPACE_TOO_LARGE preflight (v1.10.0+). `'heuristic'` = bytes/4 fast estimate (skips API call; coarse — undercounts dense Unicode by 30-50%). `'exact'` = always call Gemini's `countTokens` (free, no quota share with `generateContent`; ~hundreds of ms per call; cached per (filesHash + prompt + model) — `filesHash` is post-glob-filter so changing globs that resolve to different files invalidates automatically). `'auto'` (default, recommended) = heuristic when the workspace is well under 50% of the model's input limit; exact when near the cliff where accuracy matters. Use `'exact'` in CI / tests where you want predictable, accurate behaviour regardless of size."),
131
- serviceTier: z.enum(['standard', 'flex']).optional().describe(SERVICE_TIER_DESCRIPTION),
132
- attachments: z
133
- .array(z.string().min(1)) // the count cap is inspectAttachments' (ATTACHMENT_INVALID), not the schema's
134
- .optional()
135
- .describe(`Local image or PDF files (png, jpg, jpeg, webp, pdf; up to ${MAX_ATTACHMENTS}, ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB each, ${MAX_ATTACHMENTS_TOTAL_BYTES / 1024 / 1024} MB together) sent inline before the question — a screenshot of the bug, a diagram, a spec. Paths are inside the workspace (relative to it or absolute; a symlink is refused, the sandbox's secret rules apply, the first bytes must match the type). They belong to THIS question only, never to the workspace cache. Their tokens are counted by Gemini (one free countTokens call) and enter the size preflight, the budget reservation and the TPM throttle; a count that cannot be obtained refuses the call (ATTACHMENT_TOKENS_UNCOUNTED — retryable after a transient failure: no status, 429, 5xx; not after 401/403/404; a 400 means Gemini refused the parts: ATTACHMENT_INVALID). The model must support vision (ATTACHMENTS_UNSUPPORTED otherwise); a bad file is ATTACHMENT_INVALID, never retryable, and costs nothing. Not available with the ask_agentic fallback.`),
136
- cachingMode: z
137
- .enum(['explicit', 'implicit'])
138
- .optional()
139
- .describe(`Cache strategy for the workspace context. **\`'implicit'\` (default since v1.14.0)** skips \`caches.create\` entirely; file content is sent inline every call and Gemini 2.5+/3 Pro applies its automatic implicit caching on the repeated workspace prefix when prefix matches across calls. Optimised for the review→edit→review workflow — no 60–180 s rebuild wait when files change between queries. **\`'explicit'\`** builds a Gemini Context Cache via \`caches.create\` — guaranteed ~75% discount on cached input tokens, but pays the rebuild cost on every file change. Use explicit when you need predictable per-call costs more than warm-path latency; the trade-off is documented in Gemini's docs as 'no cost saving guarantee' for implicit caching. Hit rate is observable via \`status.structuredContent.caching.implicitHitRate\`. Operator-level override available via env \`GEMINI_CODE_CONTEXT_CACHING_MODE\`.${CACHING_MODE_FALLBACK_DESCRIPTION}`),
140
- forceRescan: z
141
- .boolean()
142
- .optional()
143
- .describe('Bypass the v1.13.0 scan memo and re-hash every file in the workspace (default `false`). The scan memo skips per-file SHA256 when `mtime_ms` and `size` match the previously-stored values — typically ~95% of files on a warm rescan, cutting scan wall-clock by ≥10× on large workspaces. Set this when you suspect the manifest is stale (e.g. files mutated outside the dev workflow, NTP clock-skew, or you ran `git checkout` on a directory tree). Equivalent to setting env `GEMINI_CODE_CONTEXT_FORCE_RESCAN=true` for a single call.'),
144
- onWorkspaceTooLarge: z
145
- .enum(['error', 'fallback-to-agentic'])
146
- .optional()
147
- .describe("Behaviour when the v1.5.0 preflight detects the workspace exceeds the model's `inputTokenLimit × workspaceGuardRatio` (v1.11.0+). `'error'` (default — preserves v1.5.0 behaviour) returns a structured `errorCode: 'WORKSPACE_TOO_LARGE'` and lets the caller decide how to recover. `'fallback-to-agentic'` opt-in: the server transparently re-routes through `ask_agentic` (sandboxed file-access loop — no eager upload, scales to arbitrarily large repos), wraps the agentic result, and surfaces `fallbackApplied: 'ask_agentic'` in `structuredContent` so callers can audit the swap. **Semantic divergence:** `ask_agentic` runs as a multi-iteration loop, so `timeoutMs` (ask's wall-clock cap, per call or `GEMINI_CODE_CONTEXT_ASK_TIMEOUT_MS`) translates to `iterationTimeoutMs` (per-iteration cap; total wall-clock can be N × timeoutMs) and `stallMs` (per call or `GEMINI_CODE_CONTEXT_ASK_STALL_MS`) to the loop's `stallMs` (a stream's silence only — a tool batch longer than `stallMs` answers); a phase neither bounds ends at `ask_agentic`'s default (600 s for a request's opening and a silent stream, 120 s without progress in an iteration's tools). The result reports `iterTimeoutMs`, `iterTimeoutSource: 'timeoutMs'` and `stallMs`, and lifts `errorCode`, `retryable`, `timeoutKind`, `timeoutPhase` and `timeoutSource` of a failed agentic call. Cost shape also changes (multiple smaller calls vs one big eager call). Recommended setting for orchestrators that prioritise getting an answer over a single round-trip; default stays `'error'` so existing callers see no behaviour change. **`code` does NOT support this field** — `code`'s OLD/NEW edit format is load-bearing for Claude's Edit pipeline, and `ask_agentic` returns prose only."),
148
- })
149
- .refine((data) => !(data.thinkingBudget !== undefined && data.thinkingLevel !== undefined), {
150
- 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).',
151
- // `path: []` (root-level error) reflects that the violation is the
152
- // RELATION between two fields, not a problem with either field
153
- // individually. MCP clients that render per-field errors won't
154
- // misattribute the issue to `thinkingLevel` alone.
155
- path: [],
156
- });
10
+ import { answerAsk } from './ask/answer.js';
11
+ import { attachAsk } from './ask/attachments.js';
12
+ import { guardAsk } from './ask/guard.js';
13
+ import { askInputSchema } from './ask/input.js';
14
+ import { failedResult } from './ask/results.js';
15
+ import { resolveAsk, scanAsk } from './ask/setup.js';
16
+ import { sizeAsk } from './ask/sizing.js';
17
+ import { closeEagerCall, openEagerCall, settleFailedEager, } from './shared/eager-call.js';
18
+ import { workspaceRefusal } from './shared/workspace-refusal.js';
19
+ export { askInputSchema };
157
20
  export const askTool = {
158
21
  name: 'ask',
159
22
  title: 'Ask Gemini',
@@ -166,660 +29,48 @@ export const askTool = {
166
29
  return executeAskBody(input, ctx, workspaceRoot, model, started);
167
30
  },
168
31
  };
169
- /** The attachments of one call: inspected, read and counted by Gemini, in that order — a refused file is never read,
170
- * a file that fails to read is never counted, and nothing has been reserved yet. */
171
- async function prepareAttachments(client, paths, workspaceRoot, model, signal) {
172
- const attached = await inspectAttachments(paths, workspaceRoot);
173
- const { parts, bytes } = await readAttachments(attached, signal);
174
- const tokens = await countAttachmentTokens(client, model, parts, signal);
175
- return { attached, parts, bytes, tokens };
176
- }
177
- /** The attachments of one call, or the refusal that ends it: a model without vision, a bad file (never retryable),
178
- * a count Gemini could not give. Nothing has been scanned or reserved yet. */
179
- async function attachmentsOrRefusal(client, paths, resolved, serviceTier, workspaceRoot, signal) {
180
- const meta = { serviceTier, resolvedModel: resolved.resolved };
181
- if (paths.length > 0 && !resolved.capabilities.supportsVision) {
182
- return {
183
- refusal: errorResult(`ask: ${paths.length} attachment(s) given, but ${safeForLog(resolved.resolved)} does not support vision — use \`latest-vision\` or a model that lists it`, { errorCode: 'ATTACHMENTS_UNSUPPORTED', retryable: false, ...meta }),
184
- };
185
- }
186
- try {
187
- return {
188
- prepared: await prepareAttachments(client, paths, workspaceRoot, resolved.resolved, signal),
189
- };
190
- }
191
- catch (err) {
192
- if (!(err instanceof AttachmentError) && !(err instanceof AttachmentTokensUncountedError))
193
- throw err;
194
- return {
195
- refusal: errorResult(`ask: ${err.message}`, {
196
- errorCode: err.code,
197
- retryable: err.retryable,
198
- ...meta,
199
- }),
200
- };
201
- }
202
- }
203
- /** The bytes of one workspace file as the request carries it: its body and its `--- FILE: <relpath> ---` marker. */
204
- const FILE_MARKER_BYTES = '\n\n--- FILE: ---\n\n'.length;
205
- function inlineFileBytes(files) {
206
- return files.reduce((sum, f) => sum + f.size + Buffer.byteLength(f.relpath, 'utf8') + FILE_MARKER_BYTES, 0);
207
- }
208
- /** Google's inline request limit holds whatever the caching mode (an explicit cache may not be built and the call
209
- * then runs inline): the refusal, before any reservation, when a conservative size of the request — the attachments
210
- * encoded, the workspace bodies with their markers, the prompt, the system instruction, the JSON framing — crosses
211
- * it; nothing otherwise. */
212
- function inlineRequestRefusal(prepared, files, prompt, serviceTier) {
213
- if (prepared.attached.length === 0)
214
- return undefined;
215
- const textBytes = inlineFileBytes(files) +
216
- Buffer.byteLength(prompt, 'utf8') +
217
- Buffer.byteLength(SYSTEM_INSTRUCTION_Q_AND_A, 'utf8');
218
- const requestBytes = inlineRequestBytes(prepared.attached.map((a) => a.bytes), textBytes, files.length + 2);
219
- if (requestBytes <= INLINE_REQUEST_LIMIT_BYTES)
220
- return undefined;
221
- return errorResult(`ask: the inline request would carry ${requestBytes} bytes (the attachments base64-encoded, the workspace with its file markers, the prompt, the system instruction and the JSON framing), above Google's ${INLINE_REQUEST_LIMIT_BYTES}-byte limit for inline data; use fewer or smaller attachments, or narrow the workspace with includeGlobs / excludeGlobs`, {
222
- errorCode: 'REQUEST_TOO_LARGE',
223
- retryable: false,
224
- serviceTier,
225
- ...attachmentMetadata(prepared),
226
- });
227
- }
228
- /** `structuredContent` fields of a call with attachments; nothing on a call without. */
229
- function attachmentMetadata(prepared) {
230
- if (prepared.attached.length === 0)
231
- return {};
232
- return {
233
- attachments: prepared.attached.map((a) => ({
234
- path: a.path,
235
- mimeType: a.mimeType,
236
- bytes: a.bytes,
237
- })),
238
- attachmentTokens: prepared.tokens,
239
- };
240
- }
32
+ /**
33
+ * One `ask` call: opened before its first await, its steps run in order — each goes on with the next stage or ends the
34
+ * call — and closed on every path. Every throw of a step reaches the one failure path. The `ask_agentic` fallback's
35
+ * promise is returned unawaited from inside the `try`: the `finally` runs while the fallback runs, and a rejection of
36
+ * the fallback reaches the caller as it came, never the call's failure path.
37
+ */
241
38
  async function executeAskBody(input, ctx, workspaceRoot, model, started) {
242
- let reservationId = null;
243
- // Canonical resolved-model string, captured once after `resolveModel`
244
- // so the outer catch can feed retry hints into the same throttle bucket
245
- // `reserve` used. `model` at the top of execute is the request alias
246
- // ("latest-pro-thinking") — different key, different bucket.
247
- let resolvedModelKey = null;
248
- // every request that completed is billed: the ledger settles from these, on an answer and on a failure alike
249
- const completed = new CompletedRequests();
250
- // the running decode's booking and whether a stream opened (a later failure is then billed work, not re-sent)
251
- const tracking = { ledgerEntry: null, streamOpened: false };
252
- // the tier this call runs on once resolved (Vertex may force standard); before that, the requested one is reported
253
- let serviceTier;
254
- const reportedTier = () => serviceTier ?? input.serviceTier ?? ctx.config.serviceTier;
255
- const emitter = createProgressEmitter(ctx.server, ctx.progressToken);
256
- // Composite timeout controller — wall-clock-bound (`timeoutMs`) AND/OR
257
- // heartbeat-aware stall watchdog (`stallMs`, v1.12.0). Set up before any
258
- // await so a `timeoutMs: 1000` against a slow scan still fires. The
259
- // unified signal threads into both `withNetworkRetry({signal})` and the
260
- // SDK's `config.abortSignal` — whichever timer fires first aborts both
261
- // layers cleanly. `recordChunk()` is wired into `collectStream` to reset
262
- // the stall watchdog on every chunk arrival.
263
- const timeoutController = toolTimeoutController('ask', input);
264
- const abortSignal = timeoutController.signal;
265
- // Each request of the decode holds its own TPM reservation; a failure drops the one held.
266
- const dispatch = new DispatchThrottle({
267
- throttle: ctx.throttle,
268
- enabled: ctx.config.tpmThrottleLimit > 0,
269
- signal: abortSignal,
270
- emit: (message) => emitter.emit(message),
271
- });
39
+ const eager = openEagerCall({
40
+ tool: 'ask',
41
+ knobs: input,
42
+ requestedTier: input.serviceTier ?? ctx.config.serviceTier,
43
+ workspaceRoot,
44
+ started,
45
+ }, ctx);
272
46
  try {
273
- // Workspace path validation lives INSIDE the try so a
274
- // `WorkspaceValidationError` is reported as a regular tool error
275
- // (errorResult, "ask failed: …") rather than an unhandled tool
276
- // exception logged by the server-level handler. Both arrive at the
277
- // user as text, but only the inside-try path keeps logs tidy and the
278
- // user-facing prefix consistent with other validation failures.
279
- try {
280
- validateWorkspacePath(workspaceRoot);
281
- }
282
- catch (err) {
283
- if (err instanceof WorkspaceValidationError) {
284
- return errorResult(`ask: ${err.message}`);
285
- }
286
- throw err;
287
- }
288
- emitter.emit(`resolving model '${model}'…`);
289
- // `ask` accepts all three text-gen tiers — caller picks via alias
290
- // (`latest-pro` / `latest-flash` / `latest-lite` / `latest-vision`)
291
- // or literal model ID. Resolver refuses to dispatch to a category
292
- // outside this set — protects against an image/audio/agent model
293
- // slipping in (e.g. `nano-banana-pro-preview` pre-v1.4.0).
294
- const resolved = await resolveModel(model, ctx.client, {
295
- requiredCategory: ['text-reasoning', 'text-fast', 'text-lite'],
296
- });
297
- resolvedModelKey = resolved.resolved;
298
- try {
299
- serviceTier = resolveServiceTier(input.serviceTier, ctx.config.serviceTier, ctx.config.vertex);
300
- }
301
- catch (err) {
302
- if (!(err instanceof ServiceTierError))
303
- throw err;
304
- return errorResult(`ask: ${err.message}`, {
305
- errorCode: err.code,
306
- retryable: false,
307
- serviceTier: 'flex',
308
- resolvedModel: resolved.resolved,
309
- });
310
- }
311
- // Attachments ride with the prompt as inline parts. Inspected, read and counted here — before the scan, the
312
- // preflight, the budget reservation and the throttle: a bad file costs nothing.
313
- const attachmentsOutcome = await attachmentsOrRefusal(ctx.client, input.attachments ?? [], resolved, serviceTier, workspaceRoot, abortSignal);
314
- if ('refusal' in attachmentsOutcome)
315
- return attachmentsOutcome.refusal;
316
- const attachments = attachmentsOutcome.prepared;
317
- const attachmentTokens = attachments.tokens;
318
- emitter.emit(`scanning workspace ${workspaceRoot}…`);
319
- // v1.13.0 — build the scan memo from previously-stored file rows so the
320
- // scanner can skip re-hashing files whose mtime+size haven't changed.
321
- // First-run on a new workspace produces an empty map (= every file
322
- // hashes), which matches pre-v1.13 behaviour.
323
- const scanMemo = buildScanMemo(ctx.manifest.getFiles(workspaceRoot));
324
- const scan = await scanWorkspace(workspaceRoot, {
325
- ...(input.includeGlobs !== undefined ? { includeGlobs: input.includeGlobs } : {}),
326
- ...(input.excludeGlobs !== undefined ? { excludeGlobs: input.excludeGlobs } : {}),
327
- maxFiles: ctx.config.maxFilesPerWorkspace,
328
- maxFileSizeBytes: ctx.config.maxFileSizeBytes,
329
- manifestMemo: scanMemo,
330
- forceRescan: input.forceRescan === true || ctx.config.forceRescan === true,
331
- });
332
- // Output cap, three layers (`resolveOutputCap`):
333
- //
334
- // 1. `input.maxOutputTokens` (per-call, strongest) — clamped to the
335
- // model's per-request limit, or on a model with long decode
336
- // (Gemini 4) to its long-decode total: a cap above the per-request
337
- // limit continues the decode in further requests.
338
- // 2. `ctx.config.forceMaxOutputTokens` (env override) — every call
339
- // sends the model's per-request limit.
340
- // 3. Default — `maxOutputTokens` is omitted: one request, the model's
341
- // own default (its advertised `outputTokenLimit`), letting the model
342
- // size the response to the query rather than reserving full capacity.
343
- //
344
- // The caller's `thinkingBudget` is checked against `outputCap`; the
345
- // clamp and the reservation use the cap that runs (`runCap`).
346
- const outputCap = resolveOutputCap({
347
- requested: input.maxOutputTokens,
348
- forceMax: ctx.config.forceMaxOutputTokens,
349
- outputTokenLimit: resolved.outputTokenLimit,
350
- longDecodeTokenLimit: resolved.longDecodeTokenLimit,
351
- fallbackLimit: ASK_MAX_OUTPUT_TOKENS_FALLBACK,
352
- });
353
- // Single source of truth for "is the caller driving reasoning via the
354
- // discrete-tier knob?". Three downstream call sites branch on this
355
- // (cost estimate, emitter, thinkingConfig build) — extracting to a
356
- // named const keeps them in lockstep and makes future additions hard
357
- // to forget.
358
- const usingThinkingLevel = input.thinkingLevel !== undefined;
359
- // A positive `thinkingBudget` that leaves no answer reserve under the caller's own cap is refused
360
- // (`thinkingBudgetRefusal`); below, the budget on the wire is clamped under the cap that runs.
361
- const budgetRefusal = thinkingBudgetRefusal(input.thinkingBudget, input.maxOutputTokens, outputCap.effective);
362
- if (budgetRefusal !== null)
363
- return errorResult(`ask: ${budgetRefusal}`);
364
- // Estimated input-token count drives both the daily-budget reservation
365
- // (dollars) and the TPM throttle reservation (rate). Hoisted here so
366
- // both consumers share one fingerprint — no drift between what the $
367
- // ledger thinks we'll spend and what the rate-limiter thinks we'll
368
- // send to Gemini. Budget reservation still uses the bytes/4 heuristic
369
- // (cheap; `estimatePreCallCostUsd` already takes raw bytes), but the
370
- // PREFLIGHT against `inputTokenLimit` now goes through the v1.10.0
371
- // two-tier `countForPreflight` (Tier 1 = heuristic for small repos;
372
- // Tier 2 = real `countTokens` call when near the cliff). Closes T17
373
- // (`bytes/4` undercount on dense Unicode). See `src/gemini/token-counter.ts`.
374
- const workspaceBytes = scan.files.reduce((sum, f) => sum + f.size, 0);
375
- const estimatedInputTokens = Math.ceil(workspaceBytes / 4) + Math.ceil(input.prompt.length / 4) + attachmentTokens;
376
- const inlineRefusal = inlineRequestRefusal(attachments, scan.files, input.prompt, serviceTier);
377
- if (inlineRefusal !== undefined)
378
- return inlineRefusal;
379
- // v1.5.0 preflight (rebuilt in v1.10.0 on top of `countTokens`) — refuse
380
- // immediately if the estimated input doesn't fit under the model's
381
- // advertised `inputTokenLimit * workspaceGuardRatio`. Before this
382
- // guard we would dispatch the request, Gemini would reject with
383
- // `400 INVALID_ARGUMENT "exceeds maximum ..."`, and the calling
384
- // sub-agent would interpret the 400 as retryable (the error body is
385
- // indistinguishable from transient quota errors at the string level)
386
- // → unbounded retry storm. Cheap pre-flight with a structured
387
- // `WORKSPACE_TOO_LARGE` errorCode + `retryable: false` signals to the
388
- // orchestrator that this is not recoverable without user action.
389
- //
390
- // `inputTokenLimit` can be `null` when `models.list()` didn't advertise
391
- // it (typically happens only on internal / preview model IDs we've never
392
- // seen). In that case we fall through without blocking but warn —
393
- // better to let the request hit the API and fail noisily than to
394
- // block a legitimate call on missing metadata.
395
- // Hoisted past the `if (contextWindow > 0)` block so the success-path
396
- // metadata (lines below) can surface `tokenCountMethod` /
397
- // `rawTokenCount` / `tokenCountCacheHit` regardless of whether the
398
- // preflight actually ran. Stays `undefined` only when the resolved
399
- // model has no advertised `inputTokenLimit`.
400
- let preflight;
401
- const contextWindow = resolved.inputTokenLimit;
402
- // A decode that may take more than one request takes the exact count: its prompt is billed per request.
403
- const preflightMode = preflightModeFor(input.preflightMode, outputCap);
404
- if (typeof contextWindow === 'number' && contextWindow > 0) {
405
- preflight = await countForPreflight(ctx.client, {
406
- files: scan.files,
407
- prompt: input.prompt,
408
- model: resolved.resolved,
409
- // `filesHash` is post-glob-filter (see `scanWorkspace`), so it
410
- // already encodes user-supplied includeGlobs/excludeGlobs — no
411
- // separate globsHash axis needed in the cache key.
412
- filesHash: scan.filesHash,
413
- ...(preflightMode !== undefined ? { preflightMode } : {}),
414
- inputTokenLimit: contextWindow,
415
- extraTokens: attachmentTokens, // weighs on the heuristic-vs-exact decision, added to the count below
416
- // Thread the user's `timeoutMs` AbortSignal so a hung countTokens
417
- // call doesn't bleed past the user's stated wall-clock budget. The
418
- // SDK's `CountTokensConfig` accepts `abortSignal`; on cancellation
419
- // the SDK throws `AbortError`, which `countForPreflight` re-throws
420
- // (rather than swallowing as a fallback) so this outer try/catch
421
- // maps it to `errorCode: 'TIMEOUT'` immediately.
422
- signal: abortSignal,
423
- });
424
- // the attachments' tokens, counted by Gemini, join the count whichever way it was made: the window must hold them
425
- preflight = { ...preflight, effectiveTokens: preflight.effectiveTokens + attachmentTokens };
426
- const threshold = Math.floor(contextWindow * ctx.config.workspaceGuardRatio);
427
- if (preflight.effectiveTokens > threshold) {
428
- const pctDisplay = Math.round(ctx.config.workspaceGuardRatio * 100);
429
- // v1.11.0 — opt-in transparent fallback to `ask_agentic` when the
430
- // caller explicitly asked for it via `onWorkspaceTooLarge:
431
- // 'fallback-to-agentic'`. Default stays `'error'` so pre-v1.11.0
432
- // callers see identical behaviour. The fallback re-uses this
433
- // tool's resolved inputs (model / globs / thinking config /
434
- // workspace) and forwards its resolved `timeoutMs` as `iterationTimeoutMs`
435
- // (per-iteration cap; total wall-clock can be N × that) and `stallMs` as
436
- // `stallMs` (`ask-agentic-fallback.ts`). Cost + timing shape genuinely
437
- // changes — opt-in is the right default.
438
- if (input.onWorkspaceTooLarge === 'fallback-to-agentic' &&
439
- attachments.attached.length > 0) {
440
- return errorResult('ask: the workspace is too large for the eager path and `attachments` cannot follow the ask_agentic fallback (it sends no inline parts); drop the attachments or narrow the workspace', {
441
- errorCode: 'WORKSPACE_TOO_LARGE',
442
- retryable: false,
443
- serviceTier,
444
- ...attachmentMetadata(attachments),
445
- });
446
- }
447
- if (input.onWorkspaceTooLarge === 'fallback-to-agentic') {
448
- return fallBackToAgentic({
449
- input,
450
- ctx,
451
- emitter,
452
- serviceTier,
453
- preflight,
454
- threshold,
455
- timeout: timeoutController,
456
- });
457
- }
458
- const attachmentsNote = attachments.attached.length > 0
459
- ? ' — it carries no attachments: drop them, or narrow the workspace and ask again'
460
- : '';
461
- return errorResult(`Workspace too large: ~${preflight.effectiveTokens.toLocaleString()} input tokens (${preflight.method} count) exceeds ${threshold.toLocaleString()} (${pctDisplay}% of ${resolved.resolved}'s ${contextWindow.toLocaleString()} context window). Best option: use \`mcp__gemini-code-context__ask_agentic\` — same model, but it reads only the files it needs via sandboxed tool calls (no eager repo upload)${attachmentsNote}. Or set \`onWorkspaceTooLarge: 'fallback-to-agentic'\` on \`ask\` to have the server route automatically. Other 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, or (d) split the workspace into subdirectories.`, {
462
- errorCode: 'WORKSPACE_TOO_LARGE',
463
- serviceTier,
464
- ...attachmentMetadata(attachments),
465
- retryable: false,
466
- estimatedInputTokens: preflight.effectiveTokens,
467
- tokenCountMethod: preflight.method,
468
- rawTokenCount: preflight.rawTokens,
469
- tokenCountCacheHit: preflight.cacheHit,
470
- contextWindowTokens: contextWindow,
471
- thresholdTokens: threshold,
472
- guardRatio: ctx.config.workspaceGuardRatio,
473
- resolvedModel: resolved.resolved,
474
- filesIndexed: scan.files.length,
475
- });
476
- }
477
- }
478
- else {
479
- logger.warn(`ask: 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.`);
480
- }
481
- const { cap: runCap, cut: inputWindowCut } = capThatRuns({
482
- tool: 'ask',
483
- cap: outputCap,
484
- promptTokens: preflight?.effectiveTokens,
485
- inputTokenLimit: contextWindow,
486
- emit: (message) => emitter.emit(message),
487
- });
488
- // Normalise thinkingBudget:
489
- // undefined → null (model-default path — `thinkingBudget` OMITTED on wire)
490
- // -1 → -1 (explicit legacy dynamic; kept for Gemini 2.5 and
491
- // power-users who want to force the legacy path)
492
- // 0 → 0 (thinking disabled; Gemini 3 Pro will 400 here)
493
- // N > 0 → clamp to [0, cap that runs - 1024] — the thinking
494
- // pool is carved out of the candidate-output allowance,
495
- // so reserving ≥1024 tokens for the answer prevents 400s
496
- // when a caller passes N ≥ maxOutputTokens, and under a
497
- // cap the input window cut to one request (its value on
498
- // the wire) the budget stays below it.
499
- //
500
- // Schema `.refine()` guarantees `thinkingBudget` and `thinkingLevel`
501
- // are never both set, so we handle them in two mutually-exclusive
502
- // branches below.
503
- const rawThinkingBudget = input.thinkingBudget;
504
- const effectiveThinkingBudget = rawThinkingBudget === undefined
505
- ? THINKING_BUDGET_MODEL_DEFAULT
506
- : rawThinkingBudget === -1
507
- ? -1
508
- : rawThinkingBudget > 0
509
- ? thinkingBudgetUnder(runCap, rawThinkingBudget)
510
- : 0;
511
- // The thinking the budget reservation counts, from the cap that runs.
512
- const thinkingTokensForEstimate = thinkingReserve(input.thinkingLevel, effectiveThinkingBudget, runCap);
513
- // Atomic budget reservation. Happens AFTER scan (so the estimate is
514
- // accurate) but BEFORE any billable upload or generateContent call.
515
- // Concurrent tool calls cannot all pass a pre-check and then
516
- // collectively overshoot the cap: `reserveBudget` uses a
517
- // `BEGIN IMMEDIATE` SQLite transaction that serialises check-and-insert.
518
- if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
519
- const estimateUsd = estimatePreCallCostUsd({
520
- model: resolved.resolved,
521
- serviceTier,
522
- extraInputTokens: attachmentTokens,
523
- workspaceBytes,
524
- promptChars: input.prompt.length,
525
- // Budget reservation uses the effective cap (explicit-user-cap
526
- // OR model's full limit) as `expectedOutputTokens` — a TRUE
527
- // upper bound, since Gemini's default stops at the model's
528
- // advertised `outputTokenLimit`.
529
- expectedOutputTokens: runCap.effective,
530
- // A cap above the per-request limit (long decode) adds the input every continuation request bills again.
531
- perRequestOutputTokens: runCap.perRequest,
532
- // The preflight's count, when it ran: the reservation takes the larger of it and the bytes/4 heuristic.
533
- countedInputTokens: preflight?.effectiveTokens,
534
- thinkingTokens: thinkingTokensForEstimate,
535
- coverMs: timeoutController.timeoutMs,
536
- });
537
- const reserve = ctx.manifest.reserveBudget({
538
- workspaceRoot,
539
- toolName: 'ask',
540
- model: resolved.resolved,
541
- estimatedCostMicros: toMicrosUsd(estimateUsd),
542
- dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
543
- nowMs: Date.now(),
544
- });
545
- if ('rejected' in reserve) {
546
- const spentUsd = reserve.spentMicros / 1_000_000;
547
- 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, serviceTier });
548
- }
549
- reservationId = reserve.id;
550
- }
551
- const systemPromptHash = createHash('sha256')
552
- .update(SYSTEM_INSTRUCTION_Q_AND_A)
553
- .digest('hex')
554
- .slice(0, 16);
555
- // v1.14.0 — `cachingMode` default flipped to `'implicit'`: Gemini 2.5+/3
556
- // Pro applies its automatic implicit caching to repeated workspace prefixes,
557
- // eliminating the 60–180 s `caches.create` rebuild wait on the
558
- // review→edit→review path. Per-call `input.cachingMode` always wins;
559
- // env-level override `GEMINI_CODE_CONTEXT_CACHING_MODE` lets operators force
560
- // `'explicit'` when they need predictable per-call billing more than
561
- // warm-path speed. Telemetry on the actual mode (vs requested) is computed
562
- // AFTER `prepareContext` returns from `activePrep.inlineOnly` — see FN2 fix.
563
- const caching = cachingModeFor(input.cachingMode ?? ctx.config.cachingMode, resolved, emitter);
564
- const requestedCachingMode = caching.mode;
565
- // The context of the call: built here, and again by the stale-cache retry on a fresh cache.
566
- const prepare = () => prepareContext({
567
- client: ctx.client,
568
- manifest: ctx.manifest,
569
- scan,
570
- model: resolved,
571
- systemPromptHash,
572
- systemInstruction: SYSTEM_INSTRUCTION_Q_AND_A,
573
- ttlSeconds: ctx.config.cacheTtlSeconds,
574
- cacheMinTokens: ctx.config.cacheMinTokens,
575
- emitter,
576
- allowCaching: !input.noCache && scan.files.length > 0,
577
- // v1.12.1 — let `timeoutMs` interrupt the upload phase too.
578
- signal: abortSignal,
579
- // v1.13.0 — opt-in implicit caching path (skip caches.create).
580
- cachingMode: requestedCachingMode,
581
- });
582
- const ctxPrep = await prepare();
583
- emitter.emit(usingThinkingLevel
584
- ? `generating response (thinking-level=${input.thinkingLevel})…`
585
- : effectiveThinkingBudget === null
586
- ? 'generating response (thinking=model-default)…'
587
- : effectiveThinkingBudget === -1
588
- ? 'generating response (thinking=dynamic)…'
589
- : `generating response (thinking=${effectiveThinkingBudget})…`);
590
- // Gemini rejects `generateContent({cachedContent, systemInstruction})` with 400:
591
- // "CachedContent can not be used with GenerateContent request setting
592
- // system_instruction, tools or tool_config. Move those values to CachedContent."
593
- // The system instruction was already baked into the cache at build time
594
- // (see cache-manager.ts:322 `cacheConfig.systemInstruction`), so we must
595
- // OMIT it on the generate call when a cached context is active.
596
- // `thinkingConfig` is NOT one of the forbidden fields — it is a
597
- // per-request reasoning control and travels with every call regardless
598
- // of cache state. We always set `includeThoughts: true` so callers see
599
- // Gemini's reasoning digest in the response.
600
- //
601
- // Three mutually-exclusive reasoning-control paths (enforced by
602
- // schema `.refine()`):
603
- // a) `thinkingLevel` set → pass it through to the SDK enum. Google's
604
- // recommended path on Gemini 3. Rejected by Gemini 2.5 family.
605
- // b) `thinkingBudget` set (non-null after normalisation) → legacy
606
- // budget path. Required on Gemini 2.5; flagged as "legacy" on
607
- // Gemini 3 but still supported.
608
- // c) neither set → omit both fields, keep only `includeThoughts`.
609
- // Model uses its native default (HIGH-dynamic on Gemini 3 Pro).
610
- //
611
- // `maxOutputTokens` is only passed on the wire when the caller set
612
- // `input.maxOutputTokens` — otherwise we omit it and Gemini uses
613
- // its model-default cap (per docs, = the model's advertised
614
- // `outputTokenLimit`, currently 65,536 for pro-tier 3.x/2.5). Budget
615
- // reservation always uses the cap the decode runs under (explicit cap
616
- // OR model limit, cut by the input window on a long decode) as the
617
- // worst-case upper bound of what a completed request bills.
618
- // Cast to `ThinkingLevel` rather than indexing the runtime enum object
619
- // (`ThinkingLevel[input.thinkingLevel]`). For string enums the value
620
- // IS the member name, so passing `"HIGH"` as `ThinkingLevel` is
621
- // semantically identical at runtime — but it survives SDK renames:
622
- // if a future `@google/genai` release renames a member, the literal
623
- // string reaches Gemini's wire, which 400s with a clear message
624
- // instead of silently becoming `undefined` at the indexing step.
625
- const thinkingConfig = usingThinkingLevel
626
- ? {
627
- thinkingLevel: input.thinkingLevel,
628
- includeThoughts: true,
629
- }
630
- : effectiveThinkingBudget === null
631
- ? { includeThoughts: true }
632
- : { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
633
- const tierField = serviceTierConfig(serviceTier);
634
- const buildConfig = (cacheId) => {
635
- const maxOutputField = runCap.wire !== undefined ? { maxOutputTokens: runCap.wire } : {};
636
- return cacheId
637
- ? { cachedContent: cacheId, thinkingConfig, ...maxOutputField, ...tierField }
638
- : {
639
- systemInstruction: SYSTEM_INSTRUCTION_Q_AND_A,
640
- thinkingConfig,
641
- ...maxOutputField,
642
- ...tierField,
643
- };
644
- };
645
- // The user turn: the attachments first, the question last; with a cache the turn still carries the parts.
646
- const userTurn = {
647
- role: 'user',
648
- parts: [...attachments.parts, { text: input.prompt }],
649
- };
650
- const buildContents = (cacheId, inline) => {
651
- if (cacheId)
652
- return attachments.parts.length === 0 ? input.prompt : [userTurn];
653
- return [...inline, userTurn];
654
- };
655
- // The decode — and, on a stale cache before any request completed, its one retry on a rebuilt cache. The TPM
656
- // reservation is taken here, after `prepareContext` and immediately before the first request, so its timestamp
657
- // is when the tokens reach Gemini's quota counter; only the OPENING of a request is retried (a mid-stream
658
- // failure re-sent would bill the work again).
659
- const decoded = await decodeOnContext({
660
- client: ctx.client,
661
- booking: { workspaceRoot, toolName: 'ask', model: resolved.resolved, serviceTier },
662
- cachingMode: (prep) => cachingRan(prep, caching).mode,
663
- request: (prep) => ({
664
- contents: buildContents(prep.cacheId, prep.inlineContents),
665
- config: buildConfig(prep.cacheId),
666
- }),
667
- cache: {
668
- ttlWatcher: ctx.ttlWatcher,
669
- manifest: ctx.manifest,
670
- ttlSeconds: ctx.config.cacheTtlSeconds,
671
- prepare,
672
- },
673
- openAttempts: networkAttempts(serviceTier), // a flex request is never re-sent
674
- limits: { maxRequests: runCap.maxRequests, cap: runCap.effective },
675
- timeout: timeoutController,
676
- emit: (message) => emitter.emit(message),
677
- completed,
678
- tracking,
679
- throttle: dispatch,
680
- inputTokens: { estimated: estimatedInputTokens, counted: preflight?.effectiveTokens },
681
- }, ctxPrep);
682
- const { response, prep: activePrep, retriedOnStaleCache } = decoded;
683
- const text = response.text;
684
- // `collectStream` already aggregated thought-flagged parts and capped
685
- // the joined summary at 1200 chars (T20). Reuse directly — re-iterating
686
- // `response.candidates` would risk drift between in-flight thought
687
- // emit (live progress) and post-call summary.
688
- const thinkingSummary = response.thoughtsSummary;
689
- // Telemetry and the response record the mode that ran, not the one asked for.
690
- const ran = cachingRan(activePrep, caching);
691
- const effectiveCachingMode = ran.mode;
692
- const durationMs = Date.now() - started;
693
- // Settled here, once: the outer catch then neither releases the reservation nor books the call again. What the
694
- // API billed is every request that completed, over a long decode and a stale-cache retry alike.
695
- const settledReservation = reservationId;
696
- reservationId = null;
697
- tracking.ledgerEntry = null;
698
- const settled = settleAnswer({
699
- manifest: ctx.manifest,
700
- reservationId: settledReservation,
701
- entry: {
702
- workspaceRoot,
703
- toolName: 'ask',
704
- model: resolved.resolved,
705
- serviceTier,
706
- cachingMode: effectiveCachingMode,
707
- },
708
- completed,
709
- response,
710
- cap: runCap,
711
- cut: inputWindowCut,
712
- durationMs,
713
- });
714
- const finish = settled.finish;
715
- // Settled and billed above; an empty answer at the cap is a failure the caller can act on, never a success.
716
- if (settled.outputCapStop !== null) {
717
- return errorResult(`ask: ${settled.outputCapStop.message}`, settled.outputCapStop.fields);
718
- }
719
- if (scan.truncated) {
720
- logger.warn(`workspace ${workspaceRoot} contains more files than GEMINI_CODE_CONTEXT_MAX_FILES (${ctx.config.maxFilesPerWorkspace}); the tail was dropped before indexing.`);
721
- }
722
- const metadata = {
723
- resolvedModel: resolved.resolved,
724
- requestedModel: resolved.requested,
725
- serviceTier,
726
- ...attachmentMetadata(attachments),
727
- fallbackApplied: resolved.fallbackApplied,
728
- modelCategory: resolved.category,
729
- modelCostTier: resolved.capabilities.costTier,
730
- contextWindow: resolved.inputTokenLimit,
731
- thinkingBudget: effectiveThinkingBudget,
732
- thinkingLevel: input.thinkingLevel ?? null,
733
- ...settled.usage,
734
- ...settled.cutFields,
735
- // `truncated`: the answer stopped at the output cap (MAX_TOKENS, or a long decode at its limits) — it is cut
736
- finishReason: finish.finishReason,
737
- truncated: finish.truncated,
738
- cacheHit: activePrep.reused,
739
- cacheRebuilt: activePrep.rebuilt || retriedOnStaleCache,
740
- retriedOnStaleCache,
741
- inlineOnly: activePrep.inlineOnly,
742
- cachingMode: effectiveCachingMode,
743
- ...(ran.note !== null ? { cachingModeNote: ran.note } : {}),
744
- filesIndexed: scan.files.length,
745
- filesSkippedTooLarge: scan.skippedTooLarge,
746
- // v1.21.0+: what the scan left out — the excluded directories it met and the files that are neither source by
747
- // extension nor a `#!` script — so a caller can tell "not in the workspace" from "not indexed".
748
- excludedDirs: scan.excludedDirs,
749
- excludedDirsTotal: scan.excludedDirsTotal,
750
- filesSkippedNonSource: scan.skippedNonSource,
751
- filesUploadFailed: activePrep.uploaded.failedCount,
752
- ...(activePrep.uploaded.failedCount > 0
753
- ? { uploadFailures: activePrep.uploaded.failures.slice(0, 5) }
754
- : {}),
755
- workspaceTruncated: scan.truncated,
756
- maxFilesCap: ctx.config.maxFilesPerWorkspace,
757
- // Preflight token-count provenance — surfaces on every successful
758
- // call so orchestrators / observability layers can see which path
759
- // produced the count (`'heuristic'`, `'exact'`, `'fallback'`),
760
- // whether the LRU saved an API round-trip, and the raw count
761
- // before `SYSTEM_INSTRUCTION_RESERVE` was applied. Omitted when
762
- // the resolved model had no `inputTokenLimit` (preflight skipped).
763
- ...(preflight !== undefined
764
- ? {
765
- tokenCountMethod: preflight.method,
766
- rawTokenCount: preflight.rawTokens,
767
- tokenCountCacheHit: preflight.cacheHit,
768
- }
769
- : {}),
770
- durationMs,
771
- ...(thinkingSummary ? { thinkingSummary } : {}),
772
- };
773
- return textResult(text, metadata);
47
+ const refusal = workspaceRefusal('ask', workspaceRoot);
48
+ if (refusal !== null)
49
+ return refusal;
50
+ const resolved = await resolveAsk({ input, ctx, model, eager });
51
+ if ('end' in resolved)
52
+ return resolved.end;
53
+ const attached = await attachAsk(resolved.next);
54
+ if ('end' in attached)
55
+ return attached.end;
56
+ const scanned = await scanAsk(attached.next);
57
+ if ('end' in scanned)
58
+ return scanned.end;
59
+ const counted = await guardAsk(scanned.next);
60
+ if ('handOff' in counted)
61
+ return counted.handOff;
62
+ if ('end' in counted)
63
+ return counted.end;
64
+ const sized = sizeAsk(counted.next);
65
+ if ('end' in sized)
66
+ return sized.end;
67
+ return await answerAsk(sized.next);
774
68
  }
775
69
  catch (err) {
776
- logger.error(`ask failed: ${safeForLog(err)}`);
777
- // A 429's retry hint seeds the throttle; the ledger keeps what the completed requests billed and releases the rest
778
- // of the reservation (all of it when none completed); their usage goes into the error result.
779
- const failedUsage = settleFailure({
780
- manifest: ctx.manifest,
781
- failed: {
782
- toolName: 'ask',
783
- reservationId,
784
- entry: tracking.ledgerEntry,
785
- completed,
786
- durationMs: Date.now() - started,
787
- },
788
- err,
789
- model: resolvedModelKey,
790
- throttle: ctx.throttle,
791
- dispatch,
792
- });
793
- reservationId = null;
794
- // Timeout-driven abort gets a dedicated errorCode so callers can
795
- // distinguish "Gemini was slow" from "schema invalid" / "auth failed".
796
- // v1.12.0 — `timeoutKind` ('total' | 'stall') distinguishes the
797
- // wall-clock cap from the heartbeat-aware stall watchdog so callers
798
- // can apply different policies (e.g. retry on stall but not on total).
799
- if (isTimeoutAbort(err)) {
800
- const timedOut = timedOutCall('ask', err, timeoutController);
801
- emitter.emit(`ask: aborted after ${timedOut.limitMs ?? '?'}ms ${timedOut.kind}`);
802
- return errorResult(timedOut.message, {
803
- errorCode: 'TIMEOUT',
804
- timeoutKind: timedOut.kind,
805
- timeoutMs: timeoutController.timeoutMs,
806
- stallMs: timeoutController.stallMs,
807
- retryable: true,
808
- serviceTier: reportedTier(),
809
- ...failedUsage,
810
- });
811
- }
812
- const httpStatus = statusOf(err);
813
- return errorResult(`ask failed: ${err instanceof Error ? err.message : String(err)}`, {
814
- ...tierErrorMeta(err, tracking.streamOpened),
815
- serviceTier: reportedTier(),
816
- ...(httpStatus !== undefined ? { httpStatus } : {}),
817
- ...failedUsage,
818
- });
70
+ return failedResult(settleFailedEager(eager, ctx, err));
819
71
  }
820
72
  finally {
821
- timeoutController.dispose();
822
- emitter.stop();
73
+ closeEagerCall(eager);
823
74
  }
824
75
  }
825
76
  //# sourceMappingURL=ask.tool.js.map