@qmediat.io/gemini-code-context-mcp 1.24.0 → 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 (98) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +1 -1
  3. package/dist/tools/agentic/dispatch.d.ts +68 -0
  4. package/dist/tools/agentic/dispatch.d.ts.map +1 -0
  5. package/dist/tools/agentic/dispatch.js +167 -0
  6. package/dist/tools/agentic/dispatch.js.map +1 -0
  7. package/dist/tools/agentic/input.d.ts +28 -0
  8. package/dist/tools/agentic/input.d.ts.map +1 -0
  9. package/dist/tools/agentic/input.js +66 -0
  10. package/dist/tools/agentic/input.js.map +1 -0
  11. package/dist/tools/agentic/instructions.d.ts +46 -0
  12. package/dist/tools/agentic/instructions.d.ts.map +1 -0
  13. package/dist/tools/agentic/instructions.js +170 -0
  14. package/dist/tools/agentic/instructions.js.map +1 -0
  15. package/dist/tools/agentic/iteration.d.ts +81 -0
  16. package/dist/tools/agentic/iteration.d.ts.map +1 -0
  17. package/dist/tools/agentic/iteration.js +317 -0
  18. package/dist/tools/agentic/iteration.js.map +1 -0
  19. package/dist/tools/agentic/ledger.d.ts +64 -0
  20. package/dist/tools/agentic/ledger.d.ts.map +1 -0
  21. package/dist/tools/agentic/ledger.js +110 -0
  22. package/dist/tools/agentic/ledger.js.map +1 -0
  23. package/dist/tools/agentic/loop.d.ts +10 -0
  24. package/dist/tools/agentic/loop.d.ts.map +1 -0
  25. package/dist/tools/agentic/loop.js +179 -0
  26. package/dist/tools/agentic/loop.js.map +1 -0
  27. package/dist/tools/agentic/no-progress.d.ts +90 -0
  28. package/dist/tools/agentic/no-progress.d.ts.map +1 -0
  29. package/dist/tools/agentic/no-progress.js +107 -0
  30. package/dist/tools/agentic/no-progress.js.map +1 -0
  31. package/dist/tools/agentic/pass-clock.d.ts +85 -0
  32. package/dist/tools/agentic/pass-clock.d.ts.map +1 -0
  33. package/dist/tools/agentic/pass-clock.js +162 -0
  34. package/dist/tools/agentic/pass-clock.js.map +1 -0
  35. package/dist/tools/agentic/phase-defaults.d.ts +29 -0
  36. package/dist/tools/agentic/phase-defaults.d.ts.map +1 -0
  37. package/dist/tools/agentic/phase-defaults.js +23 -0
  38. package/dist/tools/agentic/phase-defaults.js.map +1 -0
  39. package/dist/tools/agentic/rescue.d.ts +69 -0
  40. package/dist/tools/agentic/rescue.d.ts.map +1 -0
  41. package/dist/tools/agentic/rescue.js +203 -0
  42. package/dist/tools/agentic/rescue.js.map +1 -0
  43. package/dist/tools/agentic/response.d.ts +16 -0
  44. package/dist/tools/agentic/response.d.ts.map +1 -0
  45. package/dist/tools/agentic/response.js +25 -0
  46. package/dist/tools/agentic/response.js.map +1 -0
  47. package/dist/tools/agentic/results.d.ts +76 -0
  48. package/dist/tools/agentic/results.d.ts.map +1 -0
  49. package/dist/tools/agentic/results.js +228 -0
  50. package/dist/tools/agentic/results.js.map +1 -0
  51. package/dist/tools/agentic/run.d.ts +130 -0
  52. package/dist/tools/agentic/run.d.ts.map +1 -0
  53. package/dist/tools/agentic/run.js +131 -0
  54. package/dist/tools/agentic/run.js.map +1 -0
  55. package/dist/tools/agentic/sandbox.d.ts +13 -2
  56. package/dist/tools/agentic/sandbox.d.ts.map +1 -1
  57. package/dist/tools/agentic/sandbox.js +127 -111
  58. package/dist/tools/agentic/sandbox.js.map +1 -1
  59. package/dist/tools/agentic/workspace-tools.d.ts +30 -27
  60. package/dist/tools/agentic/workspace-tools.d.ts.map +1 -1
  61. package/dist/tools/agentic/workspace-tools.js +324 -385
  62. package/dist/tools/agentic/workspace-tools.js.map +1 -1
  63. package/dist/tools/ask-agentic-fallback.d.ts +33 -0
  64. package/dist/tools/ask-agentic-fallback.d.ts.map +1 -0
  65. package/dist/tools/ask-agentic-fallback.js +113 -0
  66. package/dist/tools/ask-agentic-fallback.js.map +1 -0
  67. package/dist/tools/ask-agentic.tool.d.ts +11 -44
  68. package/dist/tools/ask-agentic.tool.d.ts.map +1 -1
  69. package/dist/tools/ask-agentic.tool.js +142 -1615
  70. package/dist/tools/ask-agentic.tool.js.map +1 -1
  71. package/dist/tools/ask.tool.d.ts.map +1 -1
  72. package/dist/tools/ask.tool.js +29 -178
  73. package/dist/tools/ask.tool.js.map +1 -1
  74. package/dist/tools/code.tool.js +9 -20
  75. package/dist/tools/code.tool.js.map +1 -1
  76. package/dist/tools/shared/abort-timeout.d.ts +43 -5
  77. package/dist/tools/shared/abort-timeout.d.ts.map +1 -1
  78. package/dist/tools/shared/abort-timeout.js +111 -102
  79. package/dist/tools/shared/abort-timeout.js.map +1 -1
  80. package/dist/tools/shared/call-ledger.d.ts +27 -12
  81. package/dist/tools/shared/call-ledger.d.ts.map +1 -1
  82. package/dist/tools/shared/call-ledger.js +57 -39
  83. package/dist/tools/shared/call-ledger.js.map +1 -1
  84. package/dist/tools/shared/continuation.d.ts +1 -1
  85. package/dist/tools/shared/continuation.d.ts.map +1 -1
  86. package/dist/tools/shared/question-fields.d.ts +10 -0
  87. package/dist/tools/shared/question-fields.d.ts.map +1 -0
  88. package/dist/tools/shared/question-fields.js +13 -0
  89. package/dist/tools/shared/question-fields.js.map +1 -0
  90. package/dist/tools/shared/settle-call.d.ts +11 -6
  91. package/dist/tools/shared/settle-call.d.ts.map +1 -1
  92. package/dist/tools/shared/settle-call.js +14 -10
  93. package/dist/tools/shared/settle-call.js.map +1 -1
  94. package/dist/tools/shared/throttle.d.ts +7 -0
  95. package/dist/tools/shared/throttle.d.ts.map +1 -1
  96. package/dist/tools/shared/throttle.js +18 -0
  97. package/dist/tools/shared/throttle.js.map +1 -1
  98. package/package.json +1 -1
@@ -0,0 +1,170 @@
1
+ /**
2
+ * What `ask_agentic` sends the model besides the conversation: the system instructions of the loop and of the
3
+ * forced-finalization pass, and the declarations of the four sandboxed tools the loop may call.
4
+ */
5
+ import { Type as GeminiType } from '@google/genai';
6
+ import { SYSTEM_INSTRUCTION_SAFETY_AGENTIC } from '../shared/system-instruction-safety.js';
7
+ // ---------------------------------------------------------------------------
8
+ // systemInstruction — prompt-injection defence + tool usage guidance
9
+ // ---------------------------------------------------------------------------
10
+ // Safety preamble — moved to `../shared/system-instruction-safety.ts` in v1.15.2
11
+ // so `ask` and `code` can share the same firewall. See that module for the
12
+ // full rationale + threat model. Two variants exist (AGENTIC vs EAGER) because
13
+ // the data-vs-instruction wording must match the file-delivery channel.
14
+ //
15
+ // `ask_agentic` uses the AGENTIC variant (references the four agentic
16
+ // executors that surface file content into `conversation`). The rescue pass
17
+ // uses the same variant — even though tool dispatch is disabled on the
18
+ // rescue, the conversation history still contains tool-response data that
19
+ // could carry adversarial text, so the firewall stays in effect.
20
+ export const SYSTEM_INSTRUCTION_AGENTIC = [
21
+ 'You are a senior code reviewer analysing a user codebase via sandboxed file-access tools.',
22
+ '',
23
+ SYSTEM_INSTRUCTION_SAFETY_AGENTIC,
24
+ '',
25
+ '# TOOLS AVAILABLE',
26
+ '- `list_directory(path)` — list immediate children (files + subdirs) of a workspace-relative path. Start with `"."` to see the root.',
27
+ '- `find_files(pattern)` — recursive glob (`*` any-except-slash, `**` any). Good for locating files by name without reading them.',
28
+ '- `read_file(path, startLine?, endLine?)` — read a file (or slice). Responses are hard-capped at 200 KB; you will see `truncated: true` with `totalLines` metadata — page through large files via startLine/endLine.',
29
+ '- `grep(pattern, pathPrefix?)` — JS RegExp search. Great for finding symbols before opening files.',
30
+ '',
31
+ '# STRATEGY',
32
+ 'Prefer narrow tool calls over wide ones. A typical flow:',
33
+ '1. Scout with `list_directory(".")` or `find_files("**/*.ts")`',
34
+ '2. Locate relevant symbols with `grep`',
35
+ '3. Open only the handful of files that actually bear on the question via `read_file`',
36
+ 'When you have enough context, respond with a plain-text answer and make NO further tool calls.',
37
+ 'Batch your tool calls within a single iteration. If you need to read 5 files, issue all 5 `read_file` calls in ONE turn rather than one-per-iteration across 5 turns — each iteration costs 30-60s of thinking-token latency that you only pay once when calls are batched. The dispatcher runs the batch in parallel (up to 10 concurrent by default). Only batch calls for paths you have already seen in prior tool results (e.g., from `list_directory`, `find_files`, or `grep` output) or that the user provided. Never synthesize or guess additional paths solely to fill a batch — a hallucinated path costs the same iteration latency as the split you were trying to avoid, and the executors will reject it.',
38
+ '',
39
+ '# DECISIVENESS',
40
+ "Be decisive. Once you have read the relevant files and gathered evidence, produce your final answer. Continuing to call tools when you already have an answer is a failure mode — it wastes the user's budget and delays the response.",
41
+ 'When the user provides a complete diff inline, your primary task is reasoning ABOUT the diff. Read each touched file at most once unless a specific concern requires re-reading; do not recursively explore the project tree to verify what the diff already shows.',
42
+ 'A focused investigation typically converges in 3–8 iterations. If you find yourself on iteration 10+ still calling tools, stop and synthesize what you know — state findings as Known / Unknown / Next checks rather than chasing completeness.',
43
+ '',
44
+ '# OUTPUT',
45
+ "Your final response (the one with no function calls) should directly answer the user's prompt. Cite specific `file:line` when referring to code. Be concrete; do not speculate beyond what you read.",
46
+ ].join('\n');
47
+ /**
48
+ * Forced-finalization system instruction. Sent on the post-loop synthesis
49
+ * pass when the iteration budget is exhausted. Combined with
50
+ * `toolConfig.functionCallingConfig.mode = NONE`, the model is prohibited
51
+ * from emitting further function calls (per Gemini API spec, NONE mode is
52
+ * "equivalent to sending a request without any function declarations") and
53
+ * must answer with text using the conversation it has already accumulated.
54
+ *
55
+ * Tightened in v1.14.4 after empirical replay (2026-04-30) showed Gemini 3 Pro
56
+ * under HIGH thinking treating the previous "Synthesize the evidence ... in
57
+ * the format the user originally requested" wording as an invitation to
58
+ * narrate its thought process — producing stream-of-consciousness output
59
+ * instead of the structured findings the caller requested. The CRITICAL
60
+ * OUTPUT INSTRUCTIONS block below is authoritative ordering: parse the
61
+ * caller's format spec, synthesize evidence into it, no preamble, no narrative,
62
+ * no apologies. The user's original prompt (with any output-format directive)
63
+ * is preserved across the rescue via `contents[0]`, so the model has the
64
+ * format spec available — the system instruction's job is to enforce
65
+ * compliance.
66
+ *
67
+ * SAFETY: this rescue runs with `mode: NONE` (tools disabled) but still
68
+ * evaluates the FULL conversation history including any malicious payloads
69
+ * surfaced by prior `read_file` / `grep` results (LLM calls are stateless
70
+ * per Gemini API semantics — each turn's output is generated under THAT
71
+ * turn's systemInstruction). The shared `SYSTEM_INSTRUCTION_SAFETY_AGENTIC` block
72
+ * (data-vs-instruction firewall) is therefore prepended below. A 3-of-3
73
+ * cross-reviewer audit on 2026-04-30 (gemini-cli + gemini-chat + grok)
74
+ * flagged the prior absence as an indirect-prompt-injection vector.
75
+ *
76
+ * v1.15.0 (C2): citation directive conditionalised symmetrically with the
77
+ * "Unknown" handling — both gemini-chat (Round-2) and Copilot (Round-1)
78
+ * flagged the v1.14.4 unconditional `Cite specific file:line` as a
79
+ * potential format-break for strict JSON / fixed-shape outputs (e.g., a
80
+ * pure JSON array of strings can't carry `(file:42)` annotations without
81
+ * mutating the data). Now reads "ONLY where the requested format provides
82
+ * a compatible place to put citations".
83
+ */
84
+ export const SYSTEM_INSTRUCTION_FINALIZATION = [
85
+ SYSTEM_INSTRUCTION_SAFETY_AGENTIC,
86
+ '',
87
+ 'You are wrapping up an investigation. The conversation history above already contains the tool responses you have gathered.',
88
+ 'Your iteration budget is now exhausted. You CANNOT call any more tools — function calling is disabled for this turn.',
89
+ '',
90
+ 'CRITICAL OUTPUT INSTRUCTIONS:',
91
+ "1. PARSE the user's original prompt for exact output format specifications (e.g., markdown headers, JSON shape, tables).",
92
+ '2. STRICTLY follow that requested structure.',
93
+ '3. Synthesize the gathered evidence into the final answer and output it DIRECTLY in the requested structure. Provide NO preamble, NO apologies, NO "Here is the summary", and NO internal thinking or narrative notes.',
94
+ '',
95
+ 'If some details remain unverified, integrate an "Unknown" element ONLY if it is compatible with the parsed output shape (e.g., adds a row to a table, a field to a JSON object, a sub-bullet under a heading); never add extraneous keys or sections that would invalidate the requested format. Cite specific `file:line` for the claims you can support — but ONLY where the requested format provides a compatible place to put citations (e.g., a sub-bullet, an additional column, embedded inside an existing string field); never break the requested structure to add citations.',
96
+ ].join('\n');
97
+ // ---------------------------------------------------------------------------
98
+ // Function declarations — these get serialised and sent to Gemini so the
99
+ // model knows which tools it may invoke + what arguments each takes.
100
+ //
101
+ // Schemas use the SDK's Upper-Case type enum values (`STRING`, `INTEGER`,
102
+ // `OBJECT`). Each declaration is built fresh per call, so no request shares
103
+ // an object with another.
104
+ // ---------------------------------------------------------------------------
105
+ const stringProp = (description) => ({ type: GeminiType.STRING, description });
106
+ const intProp = (description) => ({ type: GeminiType.INTEGER, description });
107
+ function listDirectoryDeclaration() {
108
+ return {
109
+ name: 'list_directory',
110
+ description: 'List the immediate children (files + subdirectories) of a workspace-relative directory path. Does NOT recurse. Excluded directories (node_modules, .git, .next, etc.) and denylisted filenames (lockfiles, .env, etc.) are silently filtered out.',
111
+ parameters: {
112
+ type: GeminiType.OBJECT,
113
+ properties: {
114
+ path: stringProp('Workspace-relative directory path. Use "." for the workspace root. No leading `/`.'),
115
+ },
116
+ required: ['path'],
117
+ },
118
+ };
119
+ }
120
+ function findFilesDeclaration() {
121
+ return {
122
+ name: 'find_files',
123
+ description: 'Recursive glob search for files under the workspace root. Supports `*` (match any character except `/`) and `**` (match any character including `/`). Examples: `**/*.ts`, `src/**/index.*`, `README.md`. Respects the same default excludes as list_directory.',
124
+ parameters: {
125
+ type: GeminiType.OBJECT,
126
+ properties: {
127
+ pattern: stringProp('Glob pattern relative to workspace root. Uses `*` and `**` only (no `?`, no character classes, no `{a,b}`). Match is anchored — the pattern must match the whole relative path.'),
128
+ },
129
+ required: ['pattern'],
130
+ },
131
+ };
132
+ }
133
+ function readFileDeclaration() {
134
+ return {
135
+ name: 'read_file',
136
+ description: 'Read a file from the workspace, optionally a line-range slice. Responses are hard-capped at 200 KB; if the file is larger you get a head-truncated slice with `truncated: true` and `totalLines` metadata. Call again with `startLine` / `endLine` to page through. Rejects binary / non-source extensions.',
137
+ parameters: {
138
+ type: GeminiType.OBJECT,
139
+ properties: {
140
+ path: stringProp('Workspace-relative file path.'),
141
+ startLine: intProp('1-indexed inclusive start line. Omit for line 1.'),
142
+ endLine: intProp('1-indexed inclusive end line. Omit to read until the default or byte cap kicks in.'),
143
+ },
144
+ required: ['path'],
145
+ },
146
+ };
147
+ }
148
+ function grepDeclaration() {
149
+ return {
150
+ name: 'grep',
151
+ description: 'Regular-expression search through source files in the workspace. Pattern is compiled as a JavaScript RegExp (standard metacharacters). Each match line is capped at 500 characters. At most 100 matches per call.',
152
+ parameters: {
153
+ type: GeminiType.OBJECT,
154
+ properties: {
155
+ pattern: stringProp('JavaScript regular-expression pattern (unanchored, no flags).'),
156
+ pathPrefix: stringProp('Optional: limit search to files under this workspace-relative directory prefix.'),
157
+ },
158
+ required: ['pattern'],
159
+ },
160
+ };
161
+ }
162
+ export function buildFunctionDeclarations() {
163
+ return [
164
+ listDirectoryDeclaration(),
165
+ findFilesDeclaration(),
166
+ readFileDeclaration(),
167
+ grepDeclaration(),
168
+ ];
169
+ }
170
+ //# sourceMappingURL=instructions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../../../src/tools/agentic/instructions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,iCAAiC,EAAE,MAAM,wCAAwC,CAAC;AAE3F,8EAA8E;AAC9E,qEAAqE;AACrE,8EAA8E;AAE9E,iFAAiF;AACjF,2EAA2E;AAC3E,+EAA+E;AAC/E,wEAAwE;AACxE,EAAE;AACF,sEAAsE;AACtE,4EAA4E;AAC5E,uEAAuE;AACvE,0EAA0E;AAC1E,iEAAiE;AAEjE,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,2FAA2F;IAC3F,EAAE;IACF,iCAAiC;IACjC,EAAE;IACF,mBAAmB;IACnB,sIAAsI;IACtI,kIAAkI;IAClI,sNAAsN;IACtN,oGAAoG;IACpG,EAAE;IACF,YAAY;IACZ,0DAA0D;IAC1D,gEAAgE;IAChE,wCAAwC;IACxC,sFAA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AI,EAAE,UAAU,CAAC,MAAM;YACvB,UAAU,EAAE;gBACV,OAAO,EAAE,UAAU,CACjB,iLAAiL,CAClL;aACF;YACD,QAAQ,EAAE,CAAC,SAAS,CAAC;SACZ;KACZ,CAAC;AACJ,CAAC;AAED,SAAS,mBAAmB;IAC1B,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,WAAW,EACT,6SAA6S;QAC/S,UAAU,EAAE;YACV,IAAI,EAAE,UAAU,CAAC,MAAM;YACvB,UAAU,EAAE;gBACV,IAAI,EAAE,UAAU,CAAC,+BAA+B,CAAC;gBACjD,SAAS,EAAE,OAAO,CAAC,kDAAkD,CAAC;gBACtE,OAAO,EAAE,OAAO,CACd,oFAAoF,CACrF;aACF;YACD,QAAQ,EAAE,CAAC,MAAM,CAAC;SACT;KACZ,CAAC;AACJ,CAAC;AAED,SAAS,eAAe;IACtB,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,WAAW,EACT,mNAAmN;QACrN,UAAU,EAAE;YACV,IAAI,EAAE,UAAU,CAAC,MAAM;YACvB,UAAU,EAAE;gBACV,OAAO,EAAE,UAAU,CAAC,+DAA+D,CAAC;gBACpF,UAAU,EAAE,UAAU,CACpB,iFAAiF,CAClF;aACF;YACD,QAAQ,EAAE,CAAC,SAAS,CAAC;SACZ;KACZ,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB;IACvC,OAAO;QACL,wBAAwB,EAAE;QAC1B,oBAAoB,EAAE;QACtB,mBAAmB,EAAE;QACrB,eAAe,EAAE;KAClB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,81 @@
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 type { Content, GenerateContentConfig } from '@google/genai';
9
+ import type { MatchConfig } from '../../indexer/globs.js';
10
+ import type { ToolContext } from '../registry.js';
11
+ import { type ToolCall } from './dispatch.js';
12
+ import { type PassCall } from './ledger.js';
13
+ import type { PassClock } from './pass-clock.js';
14
+ import { type UsageCounts } from './response.js';
15
+ export interface IterationResult {
16
+ /** Text from the final model turn (no function calls) — or null when
17
+ * the model requested more function calls. */
18
+ finalText: string | null;
19
+ functionCallCount: number;
20
+ /** Tool-call signatures observed in THIS iteration (for no-progress
21
+ * detection). Empty on a final-text iteration. */
22
+ signatures: ToolCall[];
23
+ usage: UsageCounts;
24
+ thinkingSummary: string | null;
25
+ /** Approximate token count of the tool-response Parts appended to
26
+ * `conversation` after this iteration's `[model fc]` turn. Bytes/4
27
+ * heuristic — over-estimates dense Unicode but bias is intentional
28
+ * (post-loop rescue's TPM/budget reservation needs to over-reserve
29
+ * rather than under-reserve, which would risk a 429 mid-rescue).
30
+ *
31
+ * Used by the rescue's `finalizationEstimate` (P5/v1.15.0): the rescue
32
+ * replays the entire accumulated conversation, so its actual prompt
33
+ * size ≈ `lastIterationPromptTokens` + size of the tool-response Parts
34
+ * appended AFTER that iteration's `generateContent` returned. Pre-P5
35
+ * the estimate omitted the tool-response delta, undershooting by 100k+
36
+ * tokens when the final iter read several large files concurrently
37
+ * (post-v1.15.1 default `TOOL_EXECUTION_CONCURRENCY = 10`; operator
38
+ * override via `GEMINI_CODE_CONTEXT_AGENTIC_TOOL_CONCURRENCY`). */
39
+ toolResponseTokens: number;
40
+ }
41
+ export interface IterationArgs {
42
+ ctx: ToolContext;
43
+ resolvedModel: string;
44
+ conversation: Content[];
45
+ baseConfig: GenerateContentConfig;
46
+ workspaceRoot: string;
47
+ filesReadSet: Set<string>;
48
+ maxFilesRead: number;
49
+ /** The pass's clock: its signal threads into `withNetworkRetry`, the SDK config and the tools phase; each request
50
+ * enters `opening`, and so does a retry's announcement, so the backoff before a request runs under a fresh default;
51
+ * every chunk reaches `recordChunk`; the tools phase is entered the moment the call completed and its executors'
52
+ * progress reaches `recordProgress`. */
53
+ clock: PassClock;
54
+ /** The pass's model call: marked completed once the stream ended, then given the usage read (`completeCall`). */
55
+ call: PassCall;
56
+ /** User glob filters (v1.9.0+). Honoured by all four agentic executors so
57
+ * a fallback from `ask` (which already applies the same globs to its
58
+ * eager scanner) preserves filter semantics — no privacy regression. */
59
+ matchConfig: MatchConfig;
60
+ /** Surface live thought-chunk previews via the MCP progress channel
61
+ * (T33, v1.16.2). Mirrors the ask/code streaming UX. */
62
+ onThoughtChunk: (text: string) => void;
63
+ }
64
+ /** How an iteration ended: with its result, or at the bound of its tools phase. */
65
+ export type IterationOutcome = {
66
+ readonly kind: 'done';
67
+ readonly iteration: IterationResult;
68
+ } | {
69
+ readonly kind: 'tools-timed-out';
70
+ readonly running: number;
71
+ };
72
+ /**
73
+ * Run one iteration. The model's response (including the function calls) is recorded so the next turn has full
74
+ * context — Gemini requires the full call-response pair to stay in the conversation; both turns are appended only when
75
+ * the tools phase answered. The non-capped calls are dispatched in parallel; the concurrency resolves per call from the
76
+ * env override (`GEMINI_CODE_CONTEXT_AGENTIC_TOOL_CONCURRENCY`), default 10. Remaining `null` slots shouldn't happen in
77
+ * practice (every call gets either a short-circuit or a dispatched response), but are skipped rather than sending a
78
+ * malformed turn to Gemini.
79
+ */
80
+ export declare function runAgenticIteration(args: IterationArgs): Promise<IterationOutcome>;
81
+ //# sourceMappingURL=iteration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iteration.d.ts","sourceRoot":"","sources":["../../../src/tools/agentic/iteration.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAgB,qBAAqB,EAAQ,MAAM,eAAe,CAAC;AAExF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,E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AAA;CAAE,CAAC;AA6FnE;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2BxF"}
@@ -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,OAAO,EAAiB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