@qmediat.io/gemini-code-context-mcp 1.23.1 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/CHANGELOG.md +161 -1
  2. package/README.md +1 -1
  3. package/dist/cache/ttl-watcher.d.ts +29 -0
  4. package/dist/cache/ttl-watcher.d.ts.map +1 -1
  5. package/dist/cache/ttl-watcher.js +104 -43
  6. package/dist/cache/ttl-watcher.js.map +1 -1
  7. package/dist/gemini/client.d.ts +7 -0
  8. package/dist/gemini/client.d.ts.map +1 -1
  9. package/dist/gemini/client.js +8 -1
  10. package/dist/gemini/client.js.map +1 -1
  11. package/dist/gemini/long-decode.d.ts +153 -0
  12. package/dist/gemini/long-decode.d.ts.map +1 -0
  13. package/dist/gemini/long-decode.js +178 -0
  14. package/dist/gemini/long-decode.js.map +1 -0
  15. package/dist/gemini/model-registry.d.ts +2 -0
  16. package/dist/gemini/model-registry.d.ts.map +1 -1
  17. package/dist/gemini/model-registry.js +5 -2
  18. package/dist/gemini/model-registry.js.map +1 -1
  19. package/dist/gemini/models.d.ts.map +1 -1
  20. package/dist/gemini/models.js +1 -0
  21. package/dist/gemini/models.js.map +1 -1
  22. package/dist/gemini/retry.d.ts +8 -0
  23. package/dist/gemini/retry.d.ts.map +1 -1
  24. package/dist/gemini/retry.js +33 -1
  25. package/dist/gemini/retry.js.map +1 -1
  26. package/dist/tools/agentic/dispatch.d.ts +68 -0
  27. package/dist/tools/agentic/dispatch.d.ts.map +1 -0
  28. package/dist/tools/agentic/dispatch.js +167 -0
  29. package/dist/tools/agentic/dispatch.js.map +1 -0
  30. package/dist/tools/agentic/input.d.ts +28 -0
  31. package/dist/tools/agentic/input.d.ts.map +1 -0
  32. package/dist/tools/agentic/input.js +66 -0
  33. package/dist/tools/agentic/input.js.map +1 -0
  34. package/dist/tools/agentic/instructions.d.ts +46 -0
  35. package/dist/tools/agentic/instructions.d.ts.map +1 -0
  36. package/dist/tools/agentic/instructions.js +170 -0
  37. package/dist/tools/agentic/instructions.js.map +1 -0
  38. package/dist/tools/agentic/iteration.d.ts +81 -0
  39. package/dist/tools/agentic/iteration.d.ts.map +1 -0
  40. package/dist/tools/agentic/iteration.js +317 -0
  41. package/dist/tools/agentic/iteration.js.map +1 -0
  42. package/dist/tools/agentic/ledger.d.ts +64 -0
  43. package/dist/tools/agentic/ledger.d.ts.map +1 -0
  44. package/dist/tools/agentic/ledger.js +110 -0
  45. package/dist/tools/agentic/ledger.js.map +1 -0
  46. package/dist/tools/agentic/loop.d.ts +10 -0
  47. package/dist/tools/agentic/loop.d.ts.map +1 -0
  48. package/dist/tools/agentic/loop.js +179 -0
  49. package/dist/tools/agentic/loop.js.map +1 -0
  50. package/dist/tools/agentic/no-progress.d.ts +90 -0
  51. package/dist/tools/agentic/no-progress.d.ts.map +1 -0
  52. package/dist/tools/agentic/no-progress.js +107 -0
  53. package/dist/tools/agentic/no-progress.js.map +1 -0
  54. package/dist/tools/agentic/pass-clock.d.ts +85 -0
  55. package/dist/tools/agentic/pass-clock.d.ts.map +1 -0
  56. package/dist/tools/agentic/pass-clock.js +162 -0
  57. package/dist/tools/agentic/pass-clock.js.map +1 -0
  58. package/dist/tools/agentic/phase-defaults.d.ts +29 -0
  59. package/dist/tools/agentic/phase-defaults.d.ts.map +1 -0
  60. package/dist/tools/agentic/phase-defaults.js +23 -0
  61. package/dist/tools/agentic/phase-defaults.js.map +1 -0
  62. package/dist/tools/agentic/rescue.d.ts +69 -0
  63. package/dist/tools/agentic/rescue.d.ts.map +1 -0
  64. package/dist/tools/agentic/rescue.js +203 -0
  65. package/dist/tools/agentic/rescue.js.map +1 -0
  66. package/dist/tools/agentic/response.d.ts +16 -0
  67. package/dist/tools/agentic/response.d.ts.map +1 -0
  68. package/dist/tools/agentic/response.js +25 -0
  69. package/dist/tools/agentic/response.js.map +1 -0
  70. package/dist/tools/agentic/results.d.ts +76 -0
  71. package/dist/tools/agentic/results.d.ts.map +1 -0
  72. package/dist/tools/agentic/results.js +228 -0
  73. package/dist/tools/agentic/results.js.map +1 -0
  74. package/dist/tools/agentic/run.d.ts +130 -0
  75. package/dist/tools/agentic/run.d.ts.map +1 -0
  76. package/dist/tools/agentic/run.js +131 -0
  77. package/dist/tools/agentic/run.js.map +1 -0
  78. package/dist/tools/agentic/sandbox.d.ts +13 -2
  79. package/dist/tools/agentic/sandbox.d.ts.map +1 -1
  80. package/dist/tools/agentic/sandbox.js +127 -111
  81. package/dist/tools/agentic/sandbox.js.map +1 -1
  82. package/dist/tools/agentic/workspace-tools.d.ts +30 -27
  83. package/dist/tools/agentic/workspace-tools.d.ts.map +1 -1
  84. package/dist/tools/agentic/workspace-tools.js +324 -385
  85. package/dist/tools/agentic/workspace-tools.js.map +1 -1
  86. package/dist/tools/ask-agentic-fallback.d.ts +33 -0
  87. package/dist/tools/ask-agentic-fallback.d.ts.map +1 -0
  88. package/dist/tools/ask-agentic-fallback.js +113 -0
  89. package/dist/tools/ask-agentic-fallback.js.map +1 -0
  90. package/dist/tools/ask-agentic.tool.d.ts +11 -44
  91. package/dist/tools/ask-agentic.tool.d.ts.map +1 -1
  92. package/dist/tools/ask-agentic.tool.js +143 -1618
  93. package/dist/tools/ask-agentic.tool.js.map +1 -1
  94. package/dist/tools/ask.tool.d.ts.map +1 -1
  95. package/dist/tools/ask.tool.js +195 -555
  96. package/dist/tools/ask.tool.js.map +1 -1
  97. package/dist/tools/code.tool.d.ts +6 -0
  98. package/dist/tools/code.tool.d.ts.map +1 -1
  99. package/dist/tools/code.tool.js +155 -306
  100. package/dist/tools/code.tool.js.map +1 -1
  101. package/dist/tools/shared/abort-timeout.d.ts +48 -4
  102. package/dist/tools/shared/abort-timeout.d.ts.map +1 -1
  103. package/dist/tools/shared/abort-timeout.js +116 -95
  104. package/dist/tools/shared/abort-timeout.js.map +1 -1
  105. package/dist/tools/shared/call-ledger.d.ts +88 -0
  106. package/dist/tools/shared/call-ledger.d.ts.map +1 -0
  107. package/dist/tools/shared/call-ledger.js +133 -0
  108. package/dist/tools/shared/call-ledger.js.map +1 -0
  109. package/dist/tools/shared/context-decode.d.ts +77 -0
  110. package/dist/tools/shared/context-decode.d.ts.map +1 -0
  111. package/dist/tools/shared/context-decode.js +125 -0
  112. package/dist/tools/shared/context-decode.js.map +1 -0
  113. package/dist/tools/shared/continuation.d.ts +124 -0
  114. package/dist/tools/shared/continuation.d.ts.map +1 -0
  115. package/dist/tools/shared/continuation.js +302 -0
  116. package/dist/tools/shared/continuation.js.map +1 -0
  117. package/dist/tools/shared/dispatch-throttle.d.ts +43 -0
  118. package/dist/tools/shared/dispatch-throttle.d.ts.map +1 -0
  119. package/dist/tools/shared/dispatch-throttle.js +65 -0
  120. package/dist/tools/shared/dispatch-throttle.js.map +1 -0
  121. package/dist/tools/shared/question-fields.d.ts +10 -0
  122. package/dist/tools/shared/question-fields.d.ts.map +1 -0
  123. package/dist/tools/shared/question-fields.js +13 -0
  124. package/dist/tools/shared/question-fields.js.map +1 -0
  125. package/dist/tools/shared/settle-call.d.ts +68 -0
  126. package/dist/tools/shared/settle-call.d.ts.map +1 -0
  127. package/dist/tools/shared/settle-call.js +59 -0
  128. package/dist/tools/shared/settle-call.js.map +1 -0
  129. package/dist/tools/shared/stream-collector.d.ts +7 -0
  130. package/dist/tools/shared/stream-collector.d.ts.map +1 -1
  131. package/dist/tools/shared/stream-collector.js +5 -1
  132. package/dist/tools/shared/stream-collector.js.map +1 -1
  133. package/dist/tools/shared/thinking.d.ts +41 -11
  134. package/dist/tools/shared/thinking.d.ts.map +1 -1
  135. package/dist/tools/shared/thinking.js +62 -9
  136. package/dist/tools/shared/thinking.js.map +1 -1
  137. package/dist/tools/shared/throttle.d.ts +7 -0
  138. package/dist/tools/shared/throttle.d.ts.map +1 -1
  139. package/dist/tools/shared/throttle.js +18 -0
  140. package/dist/tools/shared/throttle.js.map +1 -1
  141. package/dist/types.d.ts +2 -0
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/utils/cost-estimator.d.ts +17 -0
  144. package/dist/utils/cost-estimator.d.ts.map +1 -1
  145. package/dist/utils/cost-estimator.js +15 -2
  146. package/dist/utils/cost-estimator.js.map +1 -1
  147. package/package.json +4 -3
@@ -0,0 +1,317 @@
1
+ /**
2
+ * One iteration of the `ask_agentic` loop: one streamed `generateContent` and, when the model asked for function
3
+ * calls, one parallel batch of tool executions whose responses are appended to the conversation. Every phase reads its
4
+ * bound from the pass's clock: each request's opening and its stream through the SDK's abort signal, the tools phase
5
+ * (path resolution and the batch, raced as one) through `abortable`, the workers' check before each call and the
6
+ * executors' checkpoints, which also report their progress to the clock.
7
+ */
8
+ import { abortable, abortableSleep, withNetworkRetry } from '../../gemini/retry.js';
9
+ import { logger } from '../../utils/logger.js';
10
+ import { collectStream } from '../shared/stream-collector.js';
11
+ import { resolveToolExecutionConcurrency, startToolBatch, } from './dispatch.js';
12
+ import { completeCall } from './ledger.js';
13
+ import { thinkingSummaryOf } from './response.js';
14
+ import { resolveInsideWorkspace } from './sandbox.js';
15
+ import { checkpoint } from './workspace-tools.js';
16
+ /**
17
+ * Each agentic iteration is its own `generateContent` call; a transient
18
+ * pre-response network failure in the middle of a long loop (default 20
19
+ * iterations) would otherwise discard partial progress. `withNetworkRetry`
20
+ * covers `TypeError: fetch failed` (see `src/gemini/retry.ts` for the
21
+ * rationale — SDK-side retry is intentionally disabled because enabling it
22
+ * strips Gemini's informative error bodies; 429 rate-limits continue to be
23
+ * handled at the tool layer via `isGemini429` + `parseRetryDelayMs`).
24
+ *
25
+ * v1.16.2 (T33 TRIM): switched to `generateContentStream` + `collectStream`
26
+ * for two operator wins: (1) live `thinking: …` progress events during the
27
+ * 30-120s thinking phase (previously only iter-counter notifications),
28
+ * (2) heartbeat-aware `stallMs` watchdog that resets on every chunk —
29
+ * catches dead sockets ~30× faster than wall-clock alone without
30
+ * penalising legitimate deep reasoning. Mid-stream failures cannot be
31
+ * retried (Gemini's generateContentStream has no resume), so the retry
32
+ * wraps ONLY the stream OPENING — same contract as `ask`/`code`. The
33
+ * assembled `CollectedResponse` is shape-identical to the previous
34
+ * `GenerateContentResponse`, so all downstream extraction
35
+ * (`response.candidates[0].content.parts`, `response.usageMetadata`) is
36
+ * unchanged. The post-loop forced-finalization rescue does not stream
37
+ * (`generateContent`); both mark their call completed the same way
38
+ * (`completeCall`).
39
+ */
40
+ async function streamIteration(args) {
41
+ const { ctx, resolvedModel, conversation, baseConfig, clock } = args;
42
+ const abortSignal = clock.signal;
43
+ const stream = await withNetworkRetry(() => {
44
+ clock.enter('opening');
45
+ return ctx.client.models.generateContentStream({
46
+ model: resolvedModel,
47
+ contents: conversation,
48
+ config: { ...baseConfig, abortSignal },
49
+ });
50
+ }, {
51
+ signal: abortSignal,
52
+ onRetry: (attempt, err) => {
53
+ clock.enter('opening');
54
+ logger.warn(`ask_agentic: retrying generateContent after transient network failure (attempt ${attempt}): ${err instanceof Error ? err.message : String(err)}`);
55
+ },
56
+ });
57
+ return collectStream(stream, {
58
+ signal: abortSignal,
59
+ onThoughtChunk: args.onThoughtChunk,
60
+ onChunkReceived: () => clock.recordChunk(),
61
+ });
62
+ }
63
+ /** FINAL TEXT path — no function calls requested. A final-text iteration appends nothing new to
64
+ * the conversation (it's the iteration that exits the loop), so there is no tool-response delta. */
65
+ function finalTextIteration(response, parts, usage, thinkingSummary) {
66
+ const finalText = response.text ??
67
+ parts
68
+ .map((p) => p.text ?? '')
69
+ .join('')
70
+ .trim();
71
+ return {
72
+ finalText: finalText.length > 0 ? finalText : '(model returned empty response)',
73
+ functionCallCount: 0,
74
+ signatures: [],
75
+ usage,
76
+ thinkingSummary,
77
+ toolResponseTokens: 0,
78
+ };
79
+ }
80
+ /** The canonical relpath of `reqPath`, or `null` when it does not resolve — dispatch then produces
81
+ * the real SandboxError (PATH_TRAVERSAL / NOT_FOUND etc.), so the model gets a useful error shape,
82
+ * not a stale-cap-fire. */
83
+ async function canonicalRelpath(workspaceRoot, reqPath) {
84
+ try {
85
+ const r = await resolveInsideWorkspace(workspaceRoot, reqPath);
86
+ return r.relpath;
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ /**
93
+ * Short-circuit cap on distinct files read — canonical check: the refusal of a `read_file` past
94
+ * `maxFilesRead`, or `null` when the call may run. `filesReadSet` is keyed on the sandbox-resolved
95
+ * `relpath`, not the raw input, so path aliases (`./a.ts`, `a.ts`, `sub/../a.ts`) must be resolved
96
+ * here too before comparing — otherwise the pre-dispatch gate rejects legitimate re-reads at cap
97
+ * boundary. PR #24 round-3 review by GPT, Gemini, and self-review.
98
+ */
99
+ async function capRefusal(fc, call, args) {
100
+ const { workspaceRoot, filesReadSet, maxFilesRead } = args;
101
+ const atCap = call.name === 'read_file' && filesReadSet.size >= maxFilesRead;
102
+ if (!atCap)
103
+ return null;
104
+ const reqPath = typeof call.args.path === 'string' ? call.args.path : '';
105
+ const canonicalRel = await canonicalRelpath(workspaceRoot, reqPath);
106
+ const alreadyRead = canonicalRel !== null && filesReadSet.has(canonicalRel);
107
+ if (alreadyRead)
108
+ return null;
109
+ return {
110
+ functionResponse: {
111
+ ...(fc.id ? { id: fc.id } : {}),
112
+ name: call.name,
113
+ response: {
114
+ error: `maxFilesRead (${maxFilesRead}) reached. Summarise with what you have already read, or ask a narrower question.`,
115
+ },
116
+ },
117
+ };
118
+ }
119
+ /** The tools phase's work as it runs: path resolution in flight, then the batch. Each call is counted once: refused at
120
+ * the `maxFilesRead` cap, running, or never started. */
121
+ class ToolsWork {
122
+ calls;
123
+ resolving = false;
124
+ /** The calls refused at the `maxFilesRead` cap so far: answered, never an executor's. */
125
+ refused = 0;
126
+ batch = null;
127
+ constructor(calls) {
128
+ this.calls = calls;
129
+ }
130
+ /** What still runs: a path resolution in flight counts as one call. */
131
+ running() {
132
+ return (this.resolving ? 1 : 0) + (this.batch?.running() ?? 0);
133
+ }
134
+ /** The calls no executor took, as the batch counts them: before it exists, every call neither refused nor in path
135
+ * resolution. */
136
+ neverStarted() {
137
+ if (this.batch !== null)
138
+ return this.batch.neverStarted();
139
+ return this.calls - this.refused - (this.resolving ? 1 : 0);
140
+ }
141
+ }
142
+ /** The calls of a model turn, each refused at the `maxFilesRead` cap (counted on `work`) or planned for dispatch; a
143
+ * checkpoint follows each path resolution. */
144
+ async function planDispatch(functionCallParts, args, work, watch) {
145
+ const plan = {
146
+ signatures: [],
147
+ responseParts: new Array(functionCallParts.length).fill(null),
148
+ toDispatch: [],
149
+ dispatchIndexMap: [],
150
+ };
151
+ for (let i = 0; i < functionCallParts.length; i++) {
152
+ const part = functionCallParts[i];
153
+ if (!part)
154
+ continue;
155
+ const fc = part.functionCall;
156
+ const call = {
157
+ name: fc.name ?? 'unknown',
158
+ args: (fc.args ?? {}),
159
+ };
160
+ plan.signatures.push(call);
161
+ const refusal = await capRefusal(fc, call, args);
162
+ checkpoint(watch);
163
+ if (refusal !== null) {
164
+ plan.responseParts[i] = refusal;
165
+ work.refused += 1;
166
+ continue;
167
+ }
168
+ plan.dispatchIndexMap.push(i);
169
+ plan.toDispatch.push({ name: call.name, args: call.args });
170
+ }
171
+ return plan;
172
+ }
173
+ /** A successful `read_file` adds its sandbox-resolved `relpath` — this closes the alias-bypass on
174
+ * `maxFilesRead` because `./a.ts` and `a.ts` both yield `relpath: 'a.ts'` from `resolveInsideWorkspace`. */
175
+ function recordRead(res, filesReadSet) {
176
+ if (res.name !== 'read_file' || res.isError)
177
+ return;
178
+ const canonical = res.response.relpath;
179
+ if (typeof canonical === 'string' && canonical.length > 0) {
180
+ filesReadSet.add(canonical);
181
+ }
182
+ }
183
+ /** Merge dispatched results back into `responseParts` at their original positions. */
184
+ function mergeDispatched(dispatched, plan, functionCallParts, filesReadSet) {
185
+ for (let k = 0; k < dispatched.length; k++) {
186
+ const res = dispatched[k];
187
+ const originalIdx = plan.dispatchIndexMap[k];
188
+ if (res === undefined || originalIdx === undefined)
189
+ continue;
190
+ const part = functionCallParts[originalIdx];
191
+ if (!part)
192
+ continue;
193
+ const fc = part.functionCall;
194
+ plan.responseParts[originalIdx] = {
195
+ functionResponse: {
196
+ ...(fc.id ? { id: fc.id } : {}),
197
+ name: res.name,
198
+ response: res.response,
199
+ },
200
+ };
201
+ recordRead(res, filesReadSet);
202
+ }
203
+ }
204
+ /**
205
+ * P5 (v1.15.0): bytes/4 heuristic for the tool-response payload size — the
206
+ * rescue's `finalizationEstimate` adds this to `lastIterationPromptTokens`
207
+ * so its TPM/budget reservation accounts for the data that was appended to
208
+ * `conversation` AFTER the iteration's `generateContent` returned (which
209
+ * is what the rescue's prompt will replay). Stringify is wrapped in try so a
210
+ * pathological circular-ref Part (shouldn't happen — Parts are POJOs from
211
+ * the SDK + our `read_file` output — but defensive) falls back to 0
212
+ * rather than blowing the loop. The static `PER_ITERATION_INPUT_TOKENS`
213
+ * fallback at the rescue site still covers the 0-token edge.
214
+ *
215
+ * CC1 fix (v1.15.0 PR-Round-1, Copilot): UTF-8 BYTE length, not
216
+ * String#length. The latter returns UTF-16 code units — for non-ASCII
217
+ * content (CJK, emoji) it under-counts the UTF-8 byte size by 2-3x,
218
+ * re-introducing rescue under-reservation on multilingual workloads.
219
+ * Tokenizers approximate from UTF-8 bytes, so bytes/4 stays the
220
+ * intended heuristic.
221
+ */
222
+ function toolResponseTokensOf(finalResponseParts) {
223
+ try {
224
+ const serialized = JSON.stringify(finalResponseParts);
225
+ return Math.ceil(Buffer.byteLength(serialized, 'utf8') / 4);
226
+ }
227
+ catch {
228
+ return 0;
229
+ }
230
+ }
231
+ /** Resolve the plan, then run its batch: once the clock fired its workers take no call (`startToolBatch`). */
232
+ async function planAndRun(functionCallParts, args, work) {
233
+ const watch = { signal: args.clock.signal, onProgress: () => args.clock.recordProgress() };
234
+ work.resolving = true;
235
+ let plan;
236
+ try {
237
+ plan = await planDispatch(functionCallParts, args, work, watch);
238
+ }
239
+ finally {
240
+ work.resolving = false;
241
+ }
242
+ work.batch = startToolBatch(args.workspaceRoot, plan.toDispatch, resolveToolExecutionConcurrency(), args.matchConfig, watch);
243
+ return { plan, dispatched: await work.batch.settled };
244
+ }
245
+ /** `true` when `settled` settles within `graceMs`; the grace's timer is cleared when it does. */
246
+ async function settlesWithin(settled, graceMs) {
247
+ const grace = new AbortController();
248
+ const inTime = settled.then(() => true, () => true);
249
+ const late = abortableSleep(graceMs, grace.signal).then(() => false, () => false);
250
+ const result = await Promise.race([inTime, late]);
251
+ grace.abort();
252
+ return result;
253
+ }
254
+ /**
255
+ * The tools phase after its bound fired: the executors still running are given `graceMs` (the clock's `settleGraceMs`)
256
+ * to settle; what still runs then is counted and said, and whatever it returns later is dropped — it never reaches the
257
+ * conversation, the files-read set or the ledger.
258
+ */
259
+ async function toolsTimedOut(work, settled, graceMs) {
260
+ const inTime = await settlesWithin(settled, graceMs);
261
+ const running = inTime ? 0 : work.running();
262
+ if (running > 0) {
263
+ logger.warn(`ask_agentic: ${running} tool call(s) still running ${graceMs} ms after the iteration's bound (${work.neverStarted()} never started); their results will be dropped`);
264
+ settled.then(() => logger.debug('ask_agentic: a tool batch settled after its bound; its results were dropped'), (err) => logger.debug(`ask_agentic: a tool batch failed after its bound: ${String(err)}`));
265
+ }
266
+ return { kind: 'timed-out', running };
267
+ }
268
+ /** Path resolution and the batch, raced as one against the pass's clock. */
269
+ async function runToolsPhase(functionCallParts, args) {
270
+ const work = new ToolsWork(functionCallParts.length);
271
+ const settled = planAndRun(functionCallParts, args, work);
272
+ try {
273
+ const { plan, dispatched } = await abortable(settled, args.clock.signal);
274
+ return { kind: 'done', plan, dispatched };
275
+ }
276
+ catch (err) {
277
+ if (!args.clock.signal.aborted)
278
+ throw err;
279
+ return toolsTimedOut(work, settled, args.clock.settleGraceMs);
280
+ }
281
+ }
282
+ /**
283
+ * Run one iteration. The model's response (including the function calls) is recorded so the next turn has full
284
+ * context — Gemini requires the full call-response pair to stay in the conversation; both turns are appended only when
285
+ * the tools phase answered. The non-capped calls are dispatched in parallel; the concurrency resolves per call from the
286
+ * env override (`GEMINI_CODE_CONTEXT_AGENTIC_TOOL_CONCURRENCY`), default 10. Remaining `null` slots shouldn't happen in
287
+ * practice (every call gets either a short-circuit or a dispatched response), but are skipped rather than sending a
288
+ * malformed turn to Gemini.
289
+ */
290
+ export async function runAgenticIteration(args) {
291
+ const response = await streamIteration(args);
292
+ const usage = completeCall(args.call, response);
293
+ args.clock.enter('tools');
294
+ const parts = response.candidates?.[0]?.content?.parts ?? [];
295
+ const functionCallParts = parts.filter((p) => Boolean(p.functionCall && typeof p.functionCall.name === 'string'));
296
+ const thinkingSummary = thinkingSummaryOf(parts);
297
+ if (functionCallParts.length === 0) {
298
+ return { kind: 'done', iteration: finalTextIteration(response, parts, usage, thinkingSummary) };
299
+ }
300
+ const tools = await runToolsPhase(functionCallParts, args);
301
+ if (tools.kind === 'timed-out')
302
+ return { kind: 'tools-timed-out', running: tools.running };
303
+ args.conversation.push({ role: 'model', parts });
304
+ mergeDispatched(tools.dispatched, tools.plan, functionCallParts, args.filesReadSet);
305
+ const finalResponseParts = tools.plan.responseParts.filter((p) => p !== null);
306
+ args.conversation.push({ role: 'user', parts: finalResponseParts });
307
+ const iteration = {
308
+ finalText: null,
309
+ functionCallCount: functionCallParts.length,
310
+ signatures: tools.plan.signatures,
311
+ usage,
312
+ thinkingSummary,
313
+ toolResponseTokens: toolResponseTokensOf(finalResponseParts),
314
+ };
315
+ return { kind: 'done', iteration };
316
+ }
317
+ //# sourceMappingURL=iteration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iteration.js","sourceRoot":"","sources":["../../../src/tools/agentic/iteration.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEpF,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,OAAO,EAA0B,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAIL,+BAA+B,EAC/B,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,OA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AE,kBAAkB,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,CAAC,EAAE,CAAC;IAClG,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;IAC3D,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAC3F,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;IACjD,eAAe,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,IAAI,EAAE,iBAAiB,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IACpF,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAa,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;IACzF,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,kBAAkB,EAAE,CAAC,CAAC;IACpE,MAAM,SAAS,GAAoB;QACjC,SAAS,EAAE,IAAI;QACf,iBAAiB,EAAE,iBAAiB,CAAC,MAAM;QAC3C,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,UAAU;QACjC,KAAK;QACL,eAAe;QACf,kBAAkB,EAAE,oBAAoB,CAAC,kBAAkB,CAAC;KAC7D,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AACrC,CAAC"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The budget ledger and TPM throttle calls of `ask_agentic`. Each pass (a loop iteration or the forced-finalization
3
+ * pass) is an independent `generateContent` billable, so each is reserved and closed on its own, once, by `closePass`:
4
+ * a pass whose model call completed — the stream reached its end, or `generateContent` returned — is booked at what it
5
+ * billed (`recordBilledCall`, the rule of `ask` / `code` — its reservation finalised under a daily cap, a usage row
6
+ * without one) and its TPM reservation released at the input it billed, whatever failed after the call (reading the
7
+ * response, the tool batch, the iteration's timeout); a pass whose call did not complete (refused, failed at its
8
+ * opening or mid-stream, aborted before its end) has both reservations cancelled. A ledger failure while settling is
9
+ * logged, never thrown. A pass booked when it failed reports its billed fields in the error result, as a failed `ask`
10
+ * / `code` call reports its completed requests'.
11
+ */
12
+ import type { GenerateContentResponse } from '@google/genai';
13
+ import type { ToolContext } from '../registry.js';
14
+ import { type BilledFields } from '../shared/call-ledger.js';
15
+ import { type UsageCounts } from './response.js';
16
+ import { type AgenticRun } from './run.js';
17
+ export type BudgetReservation = ReturnType<ToolContext['manifest']['reserveBudget']>;
18
+ /** A TPM reservation id that was never taken. */
19
+ export declare const NO_THROTTLE_RESERVATION = -1;
20
+ /**
21
+ * A pass's model call as far as it went: `completed` is set the moment the call completed (its work is billed), before
22
+ * its response is read; `usage` holds the counts read from the response, `null` until they are read.
23
+ */
24
+ export interface PassCall {
25
+ completed: boolean;
26
+ usage: UsageCounts | null;
27
+ }
28
+ /** A pass's model call before it is made. */
29
+ export declare function callNotMade(): PassCall;
30
+ /**
31
+ * Mark a pass's model call completed, then read the response's usage into it: the mark comes first — before
32
+ * `usageMetadata` is touched — so a read that throws leaves a completed call with no usage, booked at its reservation.
33
+ * Returns the usage.
34
+ */
35
+ export declare function completeCall(call: PassCall, response: {
36
+ readonly usageMetadata?: GenerateContentResponse['usageMetadata'] | undefined;
37
+ }): UsageCounts;
38
+ /** A pass's reservations and when it started. */
39
+ export interface PassReservations {
40
+ /** The daily-budget reservation; `null` without a daily cap. */
41
+ reservationId: number | null;
42
+ throttleReservationId: number;
43
+ /** The input-token estimate both reservations were taken for. */
44
+ estimate: number;
45
+ startedAt: number;
46
+ }
47
+ /** Reserve one pass's estimated cost against the daily budget cap. */
48
+ export declare function reservePass(run: AgenticRun, costUsd: number): BudgetReservation;
49
+ /**
50
+ * Take a pass's TPM reservation for `inputTokens` and wait out its delay. The id is recorded in `holder`
51
+ * before the wait, so a timeout firing during the wait (`abortableSleep` rejects with the pass's
52
+ * TimeoutError) still finds it to cancel; `waitingLine` words the progress line from the seconds to wait.
53
+ */
54
+ export declare function waitForTpm(run: AgenticRun, holder: {
55
+ throttleReservationId: number;
56
+ }, inputTokens: number, signal: AbortSignal, waitingLine: (seconds: number) => string): Promise<void>;
57
+ /**
58
+ * Close a pass, on every exit it has: settled as billed when its model call completed — its billed fields returned —,
59
+ * both reservations cancelled when it did not (`null`). A completed call whose usage could not be read (the read threw)
60
+ * is settled at the tokens its reservation was taken for (`passReservedUsage`): nothing says it billed less. Called
61
+ * once per pass; `label` names the pass in the log.
62
+ */
63
+ export declare function closePass(run: AgenticRun, pass: PassReservations, call: PassCall, label?: string): BilledFields | null;
64
+ //# sourceMappingURL=ledger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.d.ts","sourceRoot":"","sources":["../../../src/tools/agentic/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EACL,KAAK,YAAY,EAOlB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,KAAK,WAAW,EAAe,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,KAAK,UAAU,EAAqB,MAAM,UAAU,CAAC;AAE9D,MAAM,MAAM,iBAAiB,GAAG,UAAU,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC;AAErF,iDAAiD;AACjD,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACvB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;CAC3B;AAED,6CAA6C;AAC7C,wBAAgB,WAAW,IAAI,QAAQ,CAEtC;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,QAAQ,EAAE;IAAE,QAAQ,CAAC,aAAa,CAAC,EAAE,uBAAuB,CAAC,eAAe,CAAC,GAAG,SAAS,CAAA;CAAE,GAC1F,WAAW,CAKb;AAED,iDAAiD;AACjD,MAAM,WAAW,gBAAgB;IAC/B,gEAAgE;IAChE,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,iEAAiE;IACjE,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,sEAAsE;AACtE,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,GAAG,iBAAiB,CAU/E;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC9B,GAAG,EAAE,UAAU,EACf,MAAM,EAAE;IAAE,qBAAqB,EAAE,MAAM,CAAA;CAAE,EACzC,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,WAAW,EACnB,WAAW,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,GACvC,OAAO,CAAC,IAAI,CAAC,CAOf;AAqBD;;;;;GAKG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,QAAQ,EACd,KAAK,SAAgB,GACpB,YAAY,GAAG,IAAI,CAMrB"}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The budget ledger and TPM throttle calls of `ask_agentic`. Each pass (a loop iteration or the forced-finalization
3
+ * pass) is an independent `generateContent` billable, so each is reserved and closed on its own, once, by `closePass`:
4
+ * a pass whose model call completed — the stream reached its end, or `generateContent` returned — is booked at what it
5
+ * billed (`recordBilledCall`, the rule of `ask` / `code` — its reservation finalised under a daily cap, a usage row
6
+ * without one) and its TPM reservation released at the input it billed, whatever failed after the call (reading the
7
+ * response, the tool batch, the iteration's timeout); a pass whose call did not complete (refused, failed at its
8
+ * opening or mid-stream, aborted before its end) has both reservations cancelled. A ledger failure while settling is
9
+ * logged, never thrown. A pass booked when it failed reports its billed fields in the error result, as a failed `ask`
10
+ * / `code` call reports its completed requests'.
11
+ */
12
+ import { abortableSleep } from '../../gemini/retry.js';
13
+ import { toMicrosUsd } from '../../utils/cost-estimator.js';
14
+ import { billedFields, billedInputTokens, billedUsage, recordBilledCall, releaseReservation, } from '../shared/call-ledger.js';
15
+ import { usageCounts } from './response.js';
16
+ import { passReservedUsage } from './run.js';
17
+ /** A TPM reservation id that was never taken. */
18
+ export const NO_THROTTLE_RESERVATION = -1;
19
+ /** A pass's model call before it is made. */
20
+ export function callNotMade() {
21
+ return { completed: false, usage: null };
22
+ }
23
+ /**
24
+ * Mark a pass's model call completed, then read the response's usage into it: the mark comes first — before
25
+ * `usageMetadata` is touched — so a read that throws leaves a completed call with no usage, booked at its reservation.
26
+ * Returns the usage.
27
+ */
28
+ export function completeCall(call, response) {
29
+ call.completed = true;
30
+ const usage = usageCounts(response.usageMetadata);
31
+ call.usage = usage;
32
+ return usage;
33
+ }
34
+ /** Reserve one pass's estimated cost against the daily budget cap. */
35
+ export function reservePass(run, costUsd) {
36
+ const { ctx } = run;
37
+ return ctx.manifest.reserveBudget({
38
+ workspaceRoot: run.workspaceRoot,
39
+ toolName: 'ask_agentic',
40
+ model: run.resolved.resolved,
41
+ estimatedCostMicros: toMicrosUsd(costUsd),
42
+ dailyBudgetMicros: toMicrosUsd(ctx.config.dailyBudgetUsd),
43
+ nowMs: Date.now(),
44
+ });
45
+ }
46
+ /**
47
+ * Take a pass's TPM reservation for `inputTokens` and wait out its delay. The id is recorded in `holder`
48
+ * before the wait, so a timeout firing during the wait (`abortableSleep` rejects with the pass's
49
+ * TimeoutError) still finds it to cancel; `waitingLine` words the progress line from the seconds to wait.
50
+ */
51
+ export async function waitForTpm(run, holder, inputTokens, signal, waitingLine) {
52
+ const reservation = run.ctx.throttle.reserve(run.resolved.resolved, inputTokens);
53
+ holder.throttleReservationId = reservation.releaseId;
54
+ if (reservation.delayMs > 0) {
55
+ run.emitter.emit(waitingLine(Math.ceil(reservation.delayMs / 1000)));
56
+ await abortableSleep(reservation.delayMs, signal);
57
+ }
58
+ }
59
+ /** Release both reservations of a pass whose call never completed; `label` names the pass in the log. */
60
+ function cancelPass(ctx, pass, label) {
61
+ releaseReservation(ctx.manifest, label, pass.reservationId);
62
+ if (pass.throttleReservationId !== NO_THROTTLE_RESERVATION) {
63
+ ctx.throttle.cancel(pass.throttleReservationId);
64
+ }
65
+ }
66
+ /** Where an `ask_agentic` pass is booked: it sends no cached content, so no caching mode is recorded. */
67
+ function ledgerEntryOf(run) {
68
+ return {
69
+ workspaceRoot: run.workspaceRoot,
70
+ toolName: 'ask_agentic',
71
+ model: run.resolved.resolved,
72
+ serviceTier: undefined,
73
+ cachingMode: null,
74
+ };
75
+ }
76
+ /**
77
+ * Close a pass, on every exit it has: settled as billed when its model call completed — its billed fields returned —,
78
+ * both reservations cancelled when it did not (`null`). A completed call whose usage could not be read (the read threw)
79
+ * is settled at the tokens its reservation was taken for (`passReservedUsage`): nothing says it billed less. Called
80
+ * once per pass; `label` names the pass in the log.
81
+ */
82
+ export function closePass(run, pass, call, label = 'ask_agentic') {
83
+ if (!call.completed) {
84
+ cancelPass(run.ctx, pass, label);
85
+ return null;
86
+ }
87
+ return settleBilledPass(run, pass, call.usage ?? passReservedUsage(run, pass.estimate), label);
88
+ }
89
+ /**
90
+ * Settle a pass whose API call completed (its tokens were billed, even when reading the response threw afterwards).
91
+ * The input it billed is the prompt tokens it reported, else — a response without usage — the pass's estimate
92
+ * (`billedInputTokens`, the rule of `ask` / `code`): under-billing a completed call is the worse error. A loop
93
+ * iteration's estimate is a fixed 50,000 tokens, so such a booking can be below what the pass sent. The booking and the
94
+ * TPM release use that one figure; the booking's `durationMs` is the pass's wall time; a booking that cannot be written
95
+ * is logged by `recordBilledCall`. Returns the billed fields the result reports.
96
+ */
97
+ function settleBilledPass(run, pass, usage, label) {
98
+ const billedInput = billedInputTokens(usage.promptTokenCount, pass.estimate);
99
+ const billed = billedUsage({
100
+ promptTokenCount: billedInput,
101
+ candidatesTokenCount: usage.candidatesTokenCount,
102
+ thoughtsTokenCount: usage.thoughtsTokenCount,
103
+ }, run.resolved.resolved, undefined);
104
+ recordBilledCall(run.ctx.manifest, pass.reservationId, ledgerEntryOf(run), billed, Date.now() - pass.startedAt, label);
105
+ if (pass.throttleReservationId !== NO_THROTTLE_RESERVATION) {
106
+ run.ctx.throttle.release(pass.throttleReservationId, billedInput);
107
+ }
108
+ return billedFields(billed);
109
+ }
110
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../../src/tools/agentic/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE5D,OAAO,EAGL,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAoB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAmB,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAI9D,iDAAiD;AACjD,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC,CAAC;AAW1C,6CAA6C;AAC7C,MAAM,UAAU,WAAW;IACzB,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC3C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,IAAc,EACd,QAA2F;IAE3F,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IACtB,MAAM,KAAK,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C7C,EACD,GAAG,CAAC,QAAQ,CAAC,QAAQ,EACrB,SAAS,CACV,CAAC;IACF,gBAAgB,CACd,GAAG,CAAC,GAAG,CAAC,QAAQ,EAChB,IAAI,CAAC,aAAa,EAClB,aAAa,CAAC,GAAG,CAAC,EAClB,MAAM,EACN,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,EAC3B,KAAK,CACN,CAAC;IACF,IAAI,IAAI,CAAC,qBAAqB,KAAK,uBAAuB,EAAE,CAAC;QAC3D,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,WAAW,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The `ask_agentic` iteration loop and its budgets: per iteration a daily-budget reservation, a clock (`PassClock`:
3
+ * every phase's bound), a TPM reservation, one model call with its tool batch, the settlement, and the three guards
4
+ * that end the loop early — the answer, the cumulative input-token budget and the no-progress detector.
5
+ */
6
+ import type { TextToolResult } from '../registry.js';
7
+ import { type AgenticRun, type LoopState } from './run.js';
8
+ /** Run the loop until a result ends the call, or `null` once `maxIterations` is exhausted. */
9
+ export declare function runLoop(run: AgenticRun, state: LoopState): Promise<TextToolResult | null>;
10
+ //# sourceMappingURL=loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../../../src/tools/agentic/loop.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAqBrD,OAAO,EACL,KAAK,UAAU,EACf,KAAK,SAAS,EAGf,MAAM,UAAU,CAAC;AAsNlB,8FAA8F;AAC9F,wBAAsB,OAAO,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAO/F"}