@qmediat.io/gemini-code-context-mcp 1.24.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.
- package/CHANGELOG.md +110 -1
- package/README.md +1 -1
- package/dist/cache/cache-manager.d.ts +23 -34
- package/dist/cache/cache-manager.d.ts.map +1 -1
- package/dist/cache/cache-manager.js +324 -272
- package/dist/cache/cache-manager.js.map +1 -1
- package/dist/cache/caching-mode.d.ts +5 -3
- package/dist/cache/caching-mode.d.ts.map +1 -1
- package/dist/cache/caching-mode.js +6 -4
- package/dist/cache/caching-mode.js.map +1 -1
- package/dist/cache/ttl-watcher.d.ts.map +1 -1
- package/dist/cache/ttl-watcher.js +7 -1
- package/dist/cache/ttl-watcher.js.map +1 -1
- package/dist/cache/ttl.d.ts +8 -0
- package/dist/cache/ttl.d.ts.map +1 -0
- package/dist/cache/ttl.js +10 -0
- package/dist/cache/ttl.js.map +1 -0
- package/dist/manifest/db.d.ts.map +1 -1
- package/dist/manifest/db.js +2 -1
- package/dist/manifest/db.js.map +1 -1
- package/dist/tools/agentic/dispatch.d.ts +68 -0
- package/dist/tools/agentic/dispatch.d.ts.map +1 -0
- package/dist/tools/agentic/dispatch.js +167 -0
- package/dist/tools/agentic/dispatch.js.map +1 -0
- package/dist/tools/agentic/input.d.ts +28 -0
- package/dist/tools/agentic/input.d.ts.map +1 -0
- package/dist/tools/agentic/input.js +66 -0
- package/dist/tools/agentic/input.js.map +1 -0
- package/dist/tools/agentic/instructions.d.ts +46 -0
- package/dist/tools/agentic/instructions.d.ts.map +1 -0
- package/dist/tools/agentic/instructions.js +170 -0
- package/dist/tools/agentic/instructions.js.map +1 -0
- package/dist/tools/agentic/iteration.d.ts +81 -0
- package/dist/tools/agentic/iteration.d.ts.map +1 -0
- package/dist/tools/agentic/iteration.js +317 -0
- package/dist/tools/agentic/iteration.js.map +1 -0
- package/dist/tools/agentic/ledger.d.ts +64 -0
- package/dist/tools/agentic/ledger.d.ts.map +1 -0
- package/dist/tools/agentic/ledger.js +110 -0
- package/dist/tools/agentic/ledger.js.map +1 -0
- package/dist/tools/agentic/loop.d.ts +10 -0
- package/dist/tools/agentic/loop.d.ts.map +1 -0
- package/dist/tools/agentic/loop.js +179 -0
- package/dist/tools/agentic/loop.js.map +1 -0
- package/dist/tools/agentic/no-progress.d.ts +90 -0
- package/dist/tools/agentic/no-progress.d.ts.map +1 -0
- package/dist/tools/agentic/no-progress.js +107 -0
- package/dist/tools/agentic/no-progress.js.map +1 -0
- package/dist/tools/agentic/pass-clock.d.ts +85 -0
- package/dist/tools/agentic/pass-clock.d.ts.map +1 -0
- package/dist/tools/agentic/pass-clock.js +162 -0
- package/dist/tools/agentic/pass-clock.js.map +1 -0
- package/dist/tools/agentic/phase-defaults.d.ts +29 -0
- package/dist/tools/agentic/phase-defaults.d.ts.map +1 -0
- package/dist/tools/agentic/phase-defaults.js +23 -0
- package/dist/tools/agentic/phase-defaults.js.map +1 -0
- package/dist/tools/agentic/rescue.d.ts +69 -0
- package/dist/tools/agentic/rescue.d.ts.map +1 -0
- package/dist/tools/agentic/rescue.js +203 -0
- package/dist/tools/agentic/rescue.js.map +1 -0
- package/dist/tools/agentic/response.d.ts +16 -0
- package/dist/tools/agentic/response.d.ts.map +1 -0
- package/dist/tools/agentic/response.js +25 -0
- package/dist/tools/agentic/response.js.map +1 -0
- package/dist/tools/agentic/results.d.ts +76 -0
- package/dist/tools/agentic/results.d.ts.map +1 -0
- package/dist/tools/agentic/results.js +228 -0
- package/dist/tools/agentic/results.js.map +1 -0
- package/dist/tools/agentic/run.d.ts +130 -0
- package/dist/tools/agentic/run.d.ts.map +1 -0
- package/dist/tools/agentic/run.js +128 -0
- package/dist/tools/agentic/run.js.map +1 -0
- package/dist/tools/agentic/sandbox.d.ts +13 -2
- package/dist/tools/agentic/sandbox.d.ts.map +1 -1
- package/dist/tools/agentic/sandbox.js +127 -111
- package/dist/tools/agentic/sandbox.js.map +1 -1
- package/dist/tools/agentic/workspace-tools.d.ts +30 -27
- package/dist/tools/agentic/workspace-tools.d.ts.map +1 -1
- package/dist/tools/agentic/workspace-tools.js +324 -385
- package/dist/tools/agentic/workspace-tools.js.map +1 -1
- package/dist/tools/ask/answer.d.ts +9 -0
- package/dist/tools/ask/answer.d.ts.map +1 -0
- package/dist/tools/ask/answer.js +28 -0
- package/dist/tools/ask/answer.js.map +1 -0
- package/dist/tools/ask/attachments.d.ts +25 -0
- package/dist/tools/ask/attachments.d.ts.map +1 -0
- package/dist/tools/ask/attachments.js +85 -0
- package/dist/tools/ask/attachments.js.map +1 -0
- package/dist/tools/ask/call.d.ts +61 -0
- package/dist/tools/ask/call.d.ts.map +1 -0
- package/dist/tools/ask/call.js +6 -0
- package/dist/tools/ask/call.js.map +1 -0
- package/dist/tools/ask/guard.d.ts +24 -0
- package/dist/tools/ask/guard.d.ts.map +1 -0
- package/dist/tools/ask/guard.js +79 -0
- package/dist/tools/ask/guard.js.map +1 -0
- package/dist/tools/ask/input.d.ts +45 -0
- package/dist/tools/ask/input.d.ts.map +1 -0
- package/dist/tools/ask/input.js +93 -0
- package/dist/tools/ask/input.js.map +1 -0
- package/dist/tools/ask/instruction.d.ts +8 -0
- package/dist/tools/ask/instruction.d.ts.map +1 -0
- package/dist/tools/ask/instruction.js +13 -0
- package/dist/tools/ask/instruction.js.map +1 -0
- package/dist/tools/ask/request.d.ts +14 -0
- package/dist/tools/ask/request.d.ts.map +1 -0
- package/dist/tools/ask/request.js +38 -0
- package/dist/tools/ask/request.js.map +1 -0
- package/dist/tools/ask/results.d.ts +23 -0
- package/dist/tools/ask/results.d.ts.map +1 -0
- package/dist/tools/ask/results.js +107 -0
- package/dist/tools/ask/results.js.map +1 -0
- package/dist/tools/ask/setup.d.ts +22 -0
- package/dist/tools/ask/setup.d.ts.map +1 -0
- package/dist/tools/ask/setup.js +57 -0
- package/dist/tools/ask/setup.js.map +1 -0
- package/dist/tools/ask/sizing.d.ts +10 -0
- package/dist/tools/ask/sizing.d.ts.map +1 -0
- package/dist/tools/ask/sizing.js +33 -0
- package/dist/tools/ask/sizing.js.map +1 -0
- package/dist/tools/ask/thinking.d.ts +54 -0
- package/dist/tools/ask/thinking.d.ts.map +1 -0
- package/dist/tools/ask/thinking.js +69 -0
- package/dist/tools/ask/thinking.js.map +1 -0
- package/dist/tools/ask-agentic-fallback.d.ts +33 -0
- package/dist/tools/ask-agentic-fallback.d.ts.map +1 -0
- package/dist/tools/ask-agentic-fallback.js +113 -0
- package/dist/tools/ask-agentic-fallback.js.map +1 -0
- package/dist/tools/ask-agentic.tool.d.ts +11 -44
- package/dist/tools/ask-agentic.tool.d.ts.map +1 -1
- package/dist/tools/ask-agentic.tool.js +139 -1618
- package/dist/tools/ask-agentic.tool.js.map +1 -1
- package/dist/tools/ask.tool.d.ts +3 -41
- package/dist/tools/ask.tool.d.ts.map +1 -1
- package/dist/tools/ask.tool.js +46 -944
- package/dist/tools/ask.tool.js.map +1 -1
- package/dist/tools/code.tool.d.ts.map +1 -1
- package/dist/tools/code.tool.js +376 -514
- package/dist/tools/code.tool.js.map +1 -1
- package/dist/tools/reindex.tool.d.ts.map +1 -1
- package/dist/tools/reindex.tool.js +19 -22
- package/dist/tools/reindex.tool.js.map +1 -1
- package/dist/tools/shared/abort-timeout.d.ts +43 -5
- package/dist/tools/shared/abort-timeout.d.ts.map +1 -1
- package/dist/tools/shared/abort-timeout.js +111 -102
- package/dist/tools/shared/abort-timeout.js.map +1 -1
- package/dist/tools/shared/call-ledger.d.ts +27 -12
- package/dist/tools/shared/call-ledger.d.ts.map +1 -1
- package/dist/tools/shared/call-ledger.js +57 -39
- package/dist/tools/shared/call-ledger.js.map +1 -1
- package/dist/tools/shared/continuation.d.ts +1 -1
- package/dist/tools/shared/continuation.d.ts.map +1 -1
- package/dist/tools/shared/eager-answer.d.ts +78 -0
- package/dist/tools/shared/eager-answer.d.ts.map +1 -0
- package/dist/tools/shared/eager-answer.js +130 -0
- package/dist/tools/shared/eager-answer.js.map +1 -0
- package/dist/tools/shared/eager-call.d.ts +114 -0
- package/dist/tools/shared/eager-call.d.ts.map +1 -0
- package/dist/tools/shared/eager-call.js +95 -0
- package/dist/tools/shared/eager-call.js.map +1 -0
- package/dist/tools/shared/eager-steps.d.ts +114 -0
- package/dist/tools/shared/eager-steps.d.ts.map +1 -0
- package/dist/tools/shared/eager-steps.js +152 -0
- package/dist/tools/shared/eager-steps.js.map +1 -0
- package/dist/tools/shared/question-fields.d.ts +10 -0
- package/dist/tools/shared/question-fields.d.ts.map +1 -0
- package/dist/tools/shared/question-fields.js +13 -0
- package/dist/tools/shared/question-fields.js.map +1 -0
- package/dist/tools/shared/service-tier.d.ts +9 -0
- package/dist/tools/shared/service-tier.d.ts.map +1 -1
- package/dist/tools/shared/service-tier.js +15 -0
- package/dist/tools/shared/service-tier.js.map +1 -1
- package/dist/tools/shared/settle-call.d.ts +11 -6
- package/dist/tools/shared/settle-call.d.ts.map +1 -1
- package/dist/tools/shared/settle-call.js +14 -10
- package/dist/tools/shared/settle-call.js.map +1 -1
- package/dist/tools/shared/thinking.d.ts +9 -0
- package/dist/tools/shared/thinking.d.ts.map +1 -1
- package/dist/tools/shared/thinking.js +10 -0
- package/dist/tools/shared/thinking.js.map +1 -1
- package/dist/tools/shared/throttle.d.ts +7 -0
- package/dist/tools/shared/throttle.d.ts.map +1 -1
- package/dist/tools/shared/throttle.js +18 -0
- package/dist/tools/shared/throttle.js.map +1 -1
- package/dist/tools/shared/workspace-refusal.d.ts +13 -0
- package/dist/tools/shared/workspace-refusal.d.ts.map +1 -0
- package/dist/tools/shared/workspace-refusal.js +23 -0
- package/dist/tools/shared/workspace-refusal.js.map +1 -0
- package/package.json +1 -1
package/dist/tools/code.tool.js
CHANGED
|
@@ -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 {
|
|
14
|
-
import {
|
|
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 {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
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
|
|
@@ -112,7 +105,7 @@ export const codeInputSchema = z
|
|
|
112
105
|
.min(1_000)
|
|
113
106
|
.max(1_800_000)
|
|
114
107
|
.optional()
|
|
115
|
-
.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.
|
|
108
|
+
.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_CODE_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.'),
|
|
116
109
|
stallMs: z
|
|
117
110
|
.number()
|
|
118
111
|
.int()
|
|
@@ -227,516 +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
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
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 = createTimeoutController({
|
|
262
|
-
...(input.timeoutMs !== undefined ? { totalMs: input.timeoutMs } : {}),
|
|
263
|
-
totalEnvVar: 'GEMINI_CODE_CONTEXT_CODE_TIMEOUT_MS',
|
|
264
|
-
...(input.stallMs !== undefined ? { stallMs: input.stallMs } : {}),
|
|
265
|
-
stallEnvVar: 'GEMINI_CODE_CONTEXT_CODE_STALL_MS',
|
|
266
|
-
});
|
|
267
|
-
const abortSignal = timeoutController.signal;
|
|
268
|
-
// Each request of the decode holds its own TPM reservation; a failure drops the one held.
|
|
269
|
-
const dispatch = new DispatchThrottle({
|
|
270
|
-
throttle: ctx.throttle,
|
|
271
|
-
enabled: ctx.config.tpmThrottleLimit > 0,
|
|
272
|
-
signal: abortSignal,
|
|
273
|
-
emit: (message) => emitter.emit(message),
|
|
274
|
-
});
|
|
275
239
|
try {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
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,
|
|
309
282
|
retryable: false,
|
|
310
283
|
serviceTier: 'flex',
|
|
311
284
|
resolvedModel: resolved.resolved,
|
|
312
|
-
configuredModelReplaced
|
|
313
|
-
})
|
|
314
|
-
}
|
|
315
|
-
modelAudit = {
|
|
316
|
-
resolvedModel: resolved.resolved,
|
|
317
|
-
configuredModelReplaced: choice.replacedDefault ?? null,
|
|
318
|
-
serviceTier,
|
|
285
|
+
configuredModelReplaced,
|
|
286
|
+
}),
|
|
319
287
|
};
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
else {
|
|
404
|
-
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.`);
|
|
405
|
-
}
|
|
406
|
-
const { cap: runCap, cut: inputWindowCut } = capThatRuns({
|
|
407
|
-
tool: 'code',
|
|
408
|
-
cap: outputCap,
|
|
409
|
-
promptTokens: preflight?.effectiveTokens,
|
|
410
|
-
inputTokenLimit: contextWindow,
|
|
411
|
-
emit: (message) => emitter.emit(message),
|
|
412
|
-
});
|
|
413
|
-
// The budget on the wire: clamped below the cap that runs, after the input window's cut — a cap cut to one
|
|
414
|
-
// request goes on the wire as its cut value, and `thinkingBudget < maxOutputTokens` holds there too.
|
|
415
|
-
const effectiveThinkingBudget = thinkingBudget !== undefined && thinkingBudget > 0
|
|
416
|
-
? thinkingBudgetUnder(runCap, thinkingBudget)
|
|
417
|
-
: 0;
|
|
418
|
-
// The thinking the budget reservation counts, from the cap that runs.
|
|
419
|
-
const thinkingTokensForEstimate = thinkingReserve(input.thinkingLevel, effectiveThinkingBudget, runCap);
|
|
420
|
-
// Atomic budget reservation — see ask.tool.ts for the full rationale.
|
|
421
|
-
// Estimate includes the thinking budget (billed as output tokens on Pro)
|
|
422
|
-
// PLUS the candidate output cap.
|
|
423
|
-
if (Number.isFinite(ctx.config.dailyBudgetUsd)) {
|
|
424
|
-
const estimateUsd = estimatePreCallCostUsd({
|
|
425
|
-
model: resolved.resolved,
|
|
426
|
-
serviceTier,
|
|
427
|
-
workspaceBytes,
|
|
428
|
-
promptChars: input.task.length,
|
|
429
|
-
expectedOutputTokens: runCap.effective,
|
|
430
|
-
// A cap above the per-request limit (long decode) adds the input every continuation request bills again.
|
|
431
|
-
perRequestOutputTokens: runCap.perRequest,
|
|
432
|
-
// The preflight's count, when it ran: the reservation takes the larger of it and the bytes/4 heuristic.
|
|
433
|
-
countedInputTokens: preflight?.effectiveTokens,
|
|
434
|
-
thinkingTokens: thinkingTokensForEstimate,
|
|
435
|
-
coverMs: timeoutController.timeoutMs,
|
|
436
|
-
});
|
|
437
|
-
const reserve = ctx.manifest.reserveBudget({
|
|
438
|
-
workspaceRoot,
|
|
439
|
-
toolName: 'code',
|
|
440
|
-
model: resolved.resolved,
|
|
441
|
-
estimatedCostMicros: toMicrosUsd(estimateUsd),
|
|
442
|
-
dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
|
|
443
|
-
nowMs: Date.now(),
|
|
444
|
-
});
|
|
445
|
-
if ('rejected' in reserve) {
|
|
446
|
-
const spentUsd = reserve.spentMicros / 1_000_000;
|
|
447
|
-
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 });
|
|
448
|
-
}
|
|
449
|
-
reservationId = reserve.id;
|
|
450
|
-
}
|
|
451
|
-
const systemPromptHash = createHash('sha256')
|
|
452
|
-
.update(SYSTEM_INSTRUCTION_CODE)
|
|
453
|
-
.digest('hex')
|
|
454
|
-
.slice(0, 16);
|
|
455
|
-
// v1.14.0 — `cachingMode` default flipped to `'implicit'` (resolved via
|
|
456
|
-
// `ctx.config.cachingMode`, env-driven). codeExecution still forces inline
|
|
457
|
-
// regardless because Gemini rejects `cachedContent` + `tools` together;
|
|
458
|
-
// telemetry records the ACTUAL mode (FN2 fix) so the mode flip + the
|
|
459
|
-
// codeExecution-forced-inline path stay distinguishable.
|
|
460
|
-
const caching = cachingModeFor(input.cachingMode ?? ctx.config.cachingMode, resolved, emitter);
|
|
461
|
-
const requestedCachingMode = caching.mode;
|
|
462
|
-
// The context of the call: built here, and again by the stale-cache retry on a fresh cache.
|
|
463
|
-
const prepare = () => prepareContext({
|
|
464
|
-
client: ctx.client,
|
|
465
|
-
manifest: ctx.manifest,
|
|
466
|
-
scan,
|
|
467
|
-
model: resolved,
|
|
468
|
-
systemPromptHash,
|
|
469
|
-
systemInstruction: SYSTEM_INSTRUCTION_CODE,
|
|
470
|
-
ttlSeconds: ctx.config.cacheTtlSeconds,
|
|
471
|
-
cacheMinTokens: ctx.config.cacheMinTokens,
|
|
472
|
-
emitter,
|
|
473
|
-
// codeExecution requires `tools:[{codeExecution:{}}]` on generateContent,
|
|
474
|
-
// which Gemini rejects together with cachedContent. Force inline path
|
|
475
|
-
// when codeExecution is requested so we have actual inline file parts
|
|
476
|
-
// to embed alongside the prompt.
|
|
477
|
-
allowCaching: scan.files.length > 0 && !codeExecution,
|
|
478
|
-
// v1.12.1 — let `timeoutMs` interrupt the upload phase too.
|
|
479
|
-
signal: abortSignal,
|
|
480
|
-
// v1.13.0 — opt-in implicit caching path (skip caches.create).
|
|
481
|
-
cachingMode: requestedCachingMode,
|
|
482
|
-
});
|
|
483
|
-
const ctxPrep = await prepare();
|
|
484
|
-
const userPrompt = expectEdits
|
|
485
|
-
? `${input.task}\n\nRespond with your rationale and OLD/NEW diff blocks per the system instruction.`
|
|
486
|
-
: input.task;
|
|
487
|
-
const thinkingDescription = usingThinkingLevel
|
|
488
|
-
? `thinking-level=${input.thinkingLevel}`
|
|
489
|
-
: `thinking=${effectiveThinkingBudget}`;
|
|
490
|
-
emitter.emit(codeExecution
|
|
491
|
-
? `generating with ${thinkingDescription} + codeExecution…`
|
|
492
|
-
: `generating with ${thinkingDescription}…`);
|
|
493
|
-
// Two mutually-exclusive reasoning-control paths (enforced by schema
|
|
494
|
-
// `.refine()`):
|
|
495
|
-
// a) `thinkingLevel` set → cast to the SDK enum and pass through.
|
|
496
|
-
// Google's recommended path on Gemini 3. Rejected by Gemini 2.5.
|
|
497
|
-
// Cast rather than runtime enum-object lookup so a future SDK
|
|
498
|
-
// rename surfaces as a Gemini 400, not a silent `undefined`.
|
|
499
|
-
// b) `thinkingBudget` path (default 16_384, clamped above) → pass
|
|
500
|
-
// `thinkingBudget` as before.
|
|
501
|
-
// `includeThoughts: true` is unconditional so `thinkingSummary`
|
|
502
|
-
// extraction below always has material to find.
|
|
503
|
-
const thinkingConfig = usingThinkingLevel
|
|
504
|
-
? {
|
|
505
|
-
thinkingLevel: input.thinkingLevel,
|
|
506
|
-
includeThoughts: true,
|
|
507
|
-
}
|
|
508
|
-
: { thinkingBudget: effectiveThinkingBudget, includeThoughts: true };
|
|
509
|
-
// Gemini rejects generateContent({cachedContent, system_instruction|tools|tool_config})
|
|
510
|
-
// with 400. System instruction is baked into the cache at build time; tools
|
|
511
|
-
// (codeExecution) cannot be combined with a cache built without them. When
|
|
512
|
-
// codeExecution is requested AND a cache is active, we can't use both — in that
|
|
513
|
-
// case we bypass the cache so the user's explicit codeExecution request wins.
|
|
514
|
-
const canUseCache = (cacheId) => cacheId !== null && !codeExecution;
|
|
515
|
-
if (ctxPrep.cacheId && codeExecution) {
|
|
516
|
-
logger.warn('code({ codeExecution: true }) is incompatible with an active cache; bypassing cache for this call.');
|
|
517
|
-
}
|
|
518
|
-
const tierField = serviceTierConfig(serviceTier);
|
|
519
|
-
const buildConfig = (cacheId) => {
|
|
520
|
-
const maxOutputField = runCap.wire !== undefined ? { maxOutputTokens: runCap.wire } : {};
|
|
521
|
-
if (canUseCache(cacheId) && cacheId) {
|
|
522
|
-
// With cache: system_instruction is baked in; thinkingConfig remains OK.
|
|
523
|
-
// `maxOutputTokens` only emitted when the caller set it explicitly
|
|
524
|
-
// or `GEMINI_CODE_CONTEXT_FORCE_MAX_OUTPUT=true` — otherwise omit
|
|
525
|
-
// and Gemini uses its model-default.
|
|
526
|
-
return {
|
|
527
|
-
cachedContent: cacheId,
|
|
528
|
-
thinkingConfig,
|
|
529
|
-
...maxOutputField,
|
|
530
|
-
...tierField,
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
// Without cache (or cache bypassed for codeExecution): pass full config.
|
|
534
|
-
return {
|
|
535
|
-
systemInstruction: SYSTEM_INSTRUCTION_CODE,
|
|
536
|
-
thinkingConfig,
|
|
537
|
-
...tierField,
|
|
538
|
-
...maxOutputField,
|
|
539
|
-
...(codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
|
|
540
|
-
};
|
|
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
|
+
}),
|
|
541
371
|
};
|
|
542
|
-
|
|
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)
|
|
543
438
|
? userPrompt
|
|
544
|
-
: [...
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
limits: { maxRequests: runCap.maxRequests, cap: runCap.effective },
|
|
563
|
-
timeout: timeoutController,
|
|
564
|
-
emit: (message) => emitter.emit(message),
|
|
565
|
-
completed,
|
|
566
|
-
tracking,
|
|
567
|
-
throttle: dispatch,
|
|
568
|
-
inputTokens: { estimated: estimatedInputTokens, counted: preflight?.effectiveTokens },
|
|
569
|
-
}, ctxPrep);
|
|
570
|
-
const { response, prep: activePrep, retriedOnStaleCache } = decoded;
|
|
571
|
-
const text = response.text;
|
|
572
|
-
const edits = expectEdits ? parseEdits(text) : [];
|
|
573
|
-
const codeBlocks = parseCodeBlocks(text);
|
|
574
|
-
// Extract code_execution tool artifacts. Thought summary now comes from
|
|
575
|
-
// `collectStream` (T20) — `response.thoughtsSummary` is already capped
|
|
576
|
-
// and matches the live progress emit. We still iterate candidates here
|
|
577
|
-
// for executableCode / codeExecutionResult parts (those aren't
|
|
578
|
-
// accumulated by collectStream — they're full per-chunk artefacts).
|
|
579
|
-
const executedCode = [];
|
|
580
|
-
const executionOutput = [];
|
|
581
|
-
const candidates = response.candidates ?? [];
|
|
582
|
-
for (const cand of candidates) {
|
|
583
|
-
const parts = cand.content?.parts ?? [];
|
|
584
|
-
for (const part of parts) {
|
|
585
|
-
if (part.executableCode?.code)
|
|
586
|
-
executedCode.push(part.executableCode.code);
|
|
587
|
-
if (part.codeExecutionResult?.output)
|
|
588
|
-
executionOutput.push(part.codeExecutionResult.output);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
const thinkingSummary = response.thoughtsSummary;
|
|
592
|
-
// Telemetry and the response record the mode that ran, not the one asked for
|
|
593
|
-
// (`cachingRan`: a codeExecution call is forced inline and never builds a cache).
|
|
594
|
-
const ran = cachingRan(activePrep, caching);
|
|
595
|
-
const effectiveCachingMode = ran.mode;
|
|
596
|
-
const durationMs = Date.now() - started;
|
|
597
|
-
// Settled here, once: the outer catch then neither releases the reservation nor books the call again. What the
|
|
598
|
-
// API billed is every request that completed, over a long decode and a stale-cache retry alike.
|
|
599
|
-
const settledReservation = reservationId;
|
|
600
|
-
reservationId = null;
|
|
601
|
-
tracking.ledgerEntry = null;
|
|
602
|
-
const settled = settleAnswer({
|
|
603
|
-
manifest: ctx.manifest,
|
|
604
|
-
reservationId: settledReservation,
|
|
605
|
-
entry: {
|
|
606
|
-
workspaceRoot,
|
|
607
|
-
toolName: 'code',
|
|
608
|
-
model: resolved.resolved,
|
|
609
|
-
serviceTier,
|
|
610
|
-
cachingMode: effectiveCachingMode,
|
|
611
|
-
},
|
|
612
|
-
completed,
|
|
613
|
-
response,
|
|
614
|
-
cap: runCap,
|
|
615
|
-
cut: inputWindowCut,
|
|
616
|
-
durationMs,
|
|
617
|
-
});
|
|
618
|
-
const finish = settled.finish;
|
|
619
|
-
// Settled and billed above; an empty answer at the cap is a failure the caller can act on, never a success.
|
|
620
|
-
if (settled.outputCapStop !== null) {
|
|
621
|
-
return errorResult(`code: ${settled.outputCapStop.message}`, {
|
|
622
|
-
...modelAudit,
|
|
623
|
-
...settled.outputCapStop.fields,
|
|
624
|
-
});
|
|
625
|
-
}
|
|
626
|
-
if (scan.truncated) {
|
|
627
|
-
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 };
|
|
628
457
|
}
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
// `thinkingBudget` echoes the clamped value actually sent on the
|
|
636
|
-
// wire; it's only meaningful on the budget path. On the
|
|
637
|
-
// `thinkingLevel` path nothing is sent for `thinkingBudget`, so we
|
|
638
|
-
// emit `null` (not `0`) — `0` is the wire sentinel for "thinking
|
|
639
|
-
// disabled" and reporting it here for a level-path call would lie
|
|
640
|
-
// to downstream audit / dashboard consumers (PR #17 self-review F1,
|
|
641
|
-
// 3-reviewer consensus: GPT + Copilot + Self). Matches `ask.tool.ts`.
|
|
642
|
-
thinkingBudget: usingThinkingLevel ? null : effectiveThinkingBudget,
|
|
643
|
-
thinkingLevel: input.thinkingLevel ?? null,
|
|
644
|
-
codeExecutionUsed: codeExecution,
|
|
645
|
-
cacheHit: activePrep.reused,
|
|
646
|
-
cacheRebuilt: activePrep.rebuilt || retriedOnStaleCache,
|
|
647
|
-
retriedOnStaleCache,
|
|
648
|
-
...settled.usage,
|
|
649
|
-
...settled.cutFields,
|
|
650
|
-
// `truncated`: the answer stopped at the output cap (MAX_TOKENS, or a long decode at its limits) — it is cut
|
|
651
|
-
finishReason: finish.finishReason,
|
|
652
|
-
truncated: finish.truncated,
|
|
653
|
-
durationMs,
|
|
654
|
-
edits: edits.map((e) => ({
|
|
655
|
-
file: e.file,
|
|
656
|
-
oldPreview: e.old.slice(0, 120),
|
|
657
|
-
newPreview: e.new.slice(0, 120),
|
|
658
|
-
})),
|
|
659
|
-
editCount: edits.length,
|
|
660
|
-
codeBlocks: codeBlocks.map((b) => ({ lang: b.lang, length: b.content.length })),
|
|
661
|
-
workspaceTruncated: scan.truncated,
|
|
662
|
-
maxFilesCap: ctx.config.maxFilesPerWorkspace,
|
|
663
|
-
filesIndexed: scan.files.length,
|
|
664
|
-
excludedDirs: scan.excludedDirs,
|
|
665
|
-
excludedDirsTotal: scan.excludedDirsTotal,
|
|
666
|
-
filesSkippedNonSource: scan.skippedNonSource,
|
|
667
|
-
filesUploadFailed: activePrep.uploaded.failedCount,
|
|
668
|
-
...(activePrep.uploaded.failedCount > 0
|
|
669
|
-
? { uploadFailures: activePrep.uploaded.failures.slice(0, 5) }
|
|
670
|
-
: {}),
|
|
671
|
-
inlineOnly: activePrep.inlineOnly,
|
|
672
|
-
cachingMode: effectiveCachingMode,
|
|
673
|
-
...(ran.note !== null ? { cachingModeNote: ran.note } : {}),
|
|
674
|
-
// Preflight token-count provenance — surfaces on every successful
|
|
675
|
-
// call. See ask.tool.ts for the contract; same fields apply here.
|
|
676
|
-
...(preflight !== undefined
|
|
677
|
-
? {
|
|
678
|
-
tokenCountMethod: preflight.method,
|
|
679
|
-
rawTokenCount: preflight.rawTokens,
|
|
680
|
-
tokenCountCacheHit: preflight.cacheHit,
|
|
681
|
-
}
|
|
682
|
-
: {}),
|
|
683
|
-
...(thinkingSummary ? { thinkingSummary } : {}),
|
|
684
|
-
...(executedCode.length > 0 ? { executedCode } : {}),
|
|
685
|
-
...(executionOutput.length > 0 ? { executionOutput } : {}),
|
|
458
|
+
return {
|
|
459
|
+
systemInstruction: SYSTEM_INSTRUCTION_CODE,
|
|
460
|
+
thinkingConfig,
|
|
461
|
+
...tierField,
|
|
462
|
+
...maxOutputField,
|
|
463
|
+
...(call.codeExecution ? { tools: [{ codeExecution: {} }] } : {}),
|
|
686
464
|
};
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
timeoutKind: kind ?? 'total',
|
|
721
|
-
timeoutMs: ms,
|
|
722
|
-
stallMs,
|
|
723
|
-
retryable: true,
|
|
724
|
-
...modelAudit,
|
|
725
|
-
...failedUsage,
|
|
726
|
-
});
|
|
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);
|
|
727
498
|
}
|
|
728
|
-
const httpStatus = statusOf(err);
|
|
729
|
-
return errorResult(`code failed: ${err instanceof Error ? err.message : String(err)}`, {
|
|
730
|
-
...tierErrorMeta(err, tracking.streamOpened),
|
|
731
|
-
...(httpStatus !== undefined ? { httpStatus } : {}),
|
|
732
|
-
serviceTier: input.serviceTier ?? ctx.config.serviceTier, // before the model is resolved: the requested tier
|
|
733
|
-
...modelAudit,
|
|
734
|
-
...failedUsage,
|
|
735
|
-
});
|
|
736
499
|
}
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
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
|
+
});
|
|
740
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
|
+
});
|
|
741
603
|
}
|
|
742
604
|
//# sourceMappingURL=code.tool.js.map
|