@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,179 @@
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 { isTimeoutAbort } from '../shared/abort-timeout.js';
7
+ import { runAgenticIteration } from './iteration.js';
8
+ import { NO_THROTTLE_RESERVATION, callNotMade, closePass, reservePass, waitForTpm, } from './ledger.js';
9
+ import { detectNoProgress } from './no-progress.js';
10
+ import { createPassClock, passTimeoutOf } from './pass-clock.js';
11
+ import { budgetRejected, inputBudgetExceeded, iterationTimedOut, noProgressDetected, organicAnswer, } from './results.js';
12
+ import { PER_ITERATION_INPUT_TOKENS, passReservationUsd, } from './run.js';
13
+ /**
14
+ * Per-iteration budget reservation (mirrors ask.tool.ts): the reservation id (`null` when the daily
15
+ * budget is not enforced), or the BUDGET_REJECT result.
16
+ */
17
+ function reserveIteration(run, state, costUsd) {
18
+ if (!run.budget.dailyBudgetEnforced)
19
+ return { id: null };
20
+ const reserve = reservePass(run, costUsd);
21
+ if ('rejected' in reserve) {
22
+ return { refused: budgetRejected(run, state, reserve.spentMicros, costUsd) };
23
+ }
24
+ return { id: reserve.id };
25
+ }
26
+ /**
27
+ * The TPM throttle reservation and the iteration call. The clock is created BEFORE the throttle wait (phase
28
+ * `tpm-wait`), so `iterationTimeoutMs` bounds the wait too; each request enters its opening (`runAgenticIteration`).
29
+ * `onThoughtChunk` mirrors the ask/code streaming UX so operators see model reasoning progress live instead of waiting
30
+ * for the 30-120s iteration to complete.
31
+ */
32
+ async function throttledIteration(run, state, clock, flight) {
33
+ if (run.budget.tpmEnforced) {
34
+ await waitForTpm(run, flight, flight.estimate, clock.signal, (seconds) => `throttle: waiting ${seconds}s for TPM window…`);
35
+ }
36
+ flight.dispatched = true;
37
+ return runAgenticIteration({
38
+ ctx: run.ctx,
39
+ resolvedModel: run.resolved.resolved,
40
+ conversation: state.conversation,
41
+ baseConfig: run.baseConfig,
42
+ workspaceRoot: run.workspaceRoot,
43
+ filesReadSet: state.filesReadSet,
44
+ maxFilesRead: run.limits.maxFilesRead,
45
+ clock,
46
+ call: flight.call,
47
+ matchConfig: run.matchConfig,
48
+ onThoughtChunk: (text) => {
49
+ const trimmed = text.trim().slice(0, 80);
50
+ if (trimmed.length > 0)
51
+ run.emitter.emit(`thinking: ${trimmed}…`);
52
+ },
53
+ });
54
+ }
55
+ /**
56
+ * A timed-out iteration is closed (`closePass`) — booked at what it billed when its model call had completed (the
57
+ * bound fired in its tools phase), both reservations released when it had not — and becomes the structured TIMEOUT
58
+ * result naming the iteration, the phase and the bound that fired, with the booked pass's billed fields.
59
+ * `toolCallsRunning` is the work of its tools phase still running after the grace.
60
+ */
61
+ function timedOutIteration(run, state, timeout, flight, toolCallsRunning) {
62
+ const billed = closePass(run, flight, flight.call);
63
+ const after = timeout.limitMs === null ? '' : ` after ${timeout.limitMs}ms`;
64
+ run.emitter.emit(`ask_agentic: iteration ${state.iterations} aborted${after} (${timeout.kind})`);
65
+ return iterationTimedOut(state.iterations, {
66
+ timeout,
67
+ timeoutMs: run.knobs.iterationMs,
68
+ stallMs: run.knobs.stallMs,
69
+ knobNames: run.knobNames,
70
+ dispatched: flight.dispatched,
71
+ billed,
72
+ toolCallsRunning,
73
+ });
74
+ }
75
+ /**
76
+ * A failed iteration: a timeout becomes the TIMEOUT result (`timedOutIteration`); any other failure closes the pass and
77
+ * gives `null`, for the caller to re-throw, the billed fields left in `state` for the outer catch (the 429 retry hint
78
+ * is seeded once, by the call's own catch).
79
+ */
80
+ function iterationFailure(run, state, iterErr, clock, flight) {
81
+ if (isTimeoutAbort(iterErr)) {
82
+ return timedOutIteration(run, state, passTimeoutOf(clock, iterErr), flight, 0);
83
+ }
84
+ state.failedPassBilled = closePass(run, flight, flight.call);
85
+ return null;
86
+ }
87
+ /**
88
+ * The TPM wait and the iteration call run INSIDE the same try/catch, so a bound firing during the throttle wait flows
89
+ * through the same close/TIMEOUT path as one firing during the request or the tool batch — neither reservation leaks.
90
+ * The clock is disposed whatever happens. Each path closes the pass once: a failure in the `catch`, a tools timeout
91
+ * after the `try` — never inside it, where a throw of `closePass` would reach the `catch` and close the pass again.
92
+ */
93
+ async function attemptIteration(run, state, clock, flight) {
94
+ let outcome;
95
+ try {
96
+ outcome = await throttledIteration(run, state, clock, flight);
97
+ }
98
+ catch (iterErr) {
99
+ const timedOut = iterationFailure(run, state, iterErr, clock, flight);
100
+ if (timedOut === null)
101
+ throw iterErr;
102
+ return { kind: 'timed-out', result: timedOut };
103
+ }
104
+ finally {
105
+ clock.dispose();
106
+ }
107
+ if (outcome.kind === 'done')
108
+ return { kind: 'completed', iteration: outcome.iteration };
109
+ const timeout = passTimeoutOf(clock, clock.signal.reason);
110
+ return {
111
+ kind: 'timed-out',
112
+ result: timedOutIteration(run, state, timeout, flight, outcome.running),
113
+ };
114
+ }
115
+ function absorbIteration(state, iteration) {
116
+ state.cumulativeInputTokens += iteration.usage.promptTokenCount;
117
+ state.cumulativeOutputTokens += iteration.usage.candidatesTokenCount;
118
+ state.cumulativeThinkingTokens += iteration.usage.thoughtsTokenCount;
119
+ state.lastIterationPromptTokens = iteration.usage.promptTokenCount;
120
+ state.lastToolResponseTokens = iteration.toolResponseTokens;
121
+ }
122
+ /**
123
+ * Final-text first, budget second: if the iteration produced an answer, return it even if the
124
+ * cumulative-token count ticked over `maxTotalInputTokens`. Operators already paid for those tokens;
125
+ * discarding a successful answer just because this iteration nudged the meter over is punitive UX.
126
+ * The budget guard still blocks FUTURE iterations from spending beyond the cap: if we're past the
127
+ * answer check, the model is still asking for tool calls, and another round is refused. Reported in
128
+ * PR #24 review by Gemini. The no-progress detector runs last, on the iteration-end file count.
129
+ */
130
+ function endOfIteration(run, state, iteration) {
131
+ if (iteration.finalText !== null) {
132
+ return organicAnswer(run, state, iteration.finalText, iteration.thinkingSummary);
133
+ }
134
+ if (state.cumulativeInputTokens > run.limits.maxTotalInputTokens) {
135
+ return inputBudgetExceeded(run, state);
136
+ }
137
+ const stuck = detectNoProgress(iteration.signatures, state.signatureCounts, state.filesReadSet.size);
138
+ return stuck === null ? null : noProgressDetected(state, stuck);
139
+ }
140
+ /**
141
+ * One iteration, priced per iteration at the rates in force until its timeout: a loop that crosses a
142
+ * price change reserves at the new rate. The reservation is for a fixed `PER_ITERATION_INPUT_TOKENS`
143
+ * input, so an iteration that sends more is settled above it (`docs/cost-model.md`). Returns the
144
+ * result that ends the call, or `null` to go on.
145
+ */
146
+ async function runIteration(run, state) {
147
+ const estimate = PER_ITERATION_INPUT_TOKENS;
148
+ const reservation = reserveIteration(run, state, passReservationUsd(run, estimate));
149
+ if ('refused' in reservation)
150
+ return reservation.refused;
151
+ const clock = createPassClock(run.knobs);
152
+ const flight = {
153
+ reservationId: reservation.id,
154
+ throttleReservationId: NO_THROTTLE_RESERVATION,
155
+ estimate,
156
+ dispatched: false,
157
+ call: callNotMade(),
158
+ startedAt: Date.now(),
159
+ };
160
+ const attempt = await attemptIteration(run, state, clock, flight);
161
+ if (attempt.kind === 'timed-out')
162
+ return attempt.result;
163
+ const { iteration } = attempt;
164
+ closePass(run, flight, flight.call);
165
+ absorbIteration(state, iteration);
166
+ run.emitter.emit(`iter ${state.iterations}/${run.limits.maxIterations}: ${iteration.functionCallCount} tool calls, ${state.cumulativeInputTokens} in-tokens so far`);
167
+ return endOfIteration(run, state, iteration);
168
+ }
169
+ /** Run the loop until a result ends the call, or `null` once `maxIterations` is exhausted. */
170
+ export async function runLoop(run, state) {
171
+ while (state.iterations < run.limits.maxIterations) {
172
+ state.iterations += 1;
173
+ const ended = await runIteration(run, state);
174
+ if (ended !== null)
175
+ return ended;
176
+ }
177
+ return null;
178
+ }
179
+ //# sourceMappingURL=loop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../src/tools/agentic/loop.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAA+C,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAClG,OAAO,EACL,uBAAuB,EAGvB,WAAW,EACX,SAAS,EACT,WAAW,EACX,UAAU,GACX,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAoC,eAAe,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACnG,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAGL,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAgBlB;;;GAGG;AACH,SAAS,gBAAgB,CACvB,GAAe,EACf,KAAgB,EAChB,OAAe;IAEf,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,mBAAmB;QAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IACzD,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1C,IAAI,UAAU,IAAI,OAAO,EAAE,CAAC;QAC1B,OAAO,EAAE,OAAO,EAAE,cAAc,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,CAAC;IAC/E,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC;AAC5B,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,kBAAkB,CAC/B,GAAe,EACf,KAAgB,EAChB,KAAgB,EAChB,MAAuB;IAEvB,IAAI,GAAG,CAAC,MAAM,CAAC,WAAW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;IACpC,eAAe,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IAClC,GAAG,CAAC,OAAO,CAAC,IAAI,CACd,QAAQ,KAAK,CAAC,UAAU,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa,KAAK,SAAS,CAAC,iBAAiB,gBAAgB,KAAK,CAAC,qBAAqB,mBAAmB,CACnJ,CAAC;IACF,OAAO,cAAc,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;AAC/C,CAAC;AAED,8FAA8F;AAC9F,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,GAAe,EAAE,KAAgB;IAC7D,OAAO,KAAK,CAAC,UAAU,GAAG,GAAG,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC;QACnD,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;QACtB,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7C,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;IACnC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Content-aware no-progress detection for the `ask_agentic` loop: a call signature repeated
3
+ * `NO_PROGRESS_CALL_THRESHOLD` times with no new file read between the repeats ends the loop.
4
+ */
5
+ import type { ToolCall } from './dispatch.js';
6
+ /** If the SAME call signature (name + args) appears this many times, we
7
+ * conclude the model is stuck in a loop and surface a partial answer.
8
+ *
9
+ * Bumped 3 → 5 in v1.14.4 after empirical replay (2026-04-30) showed
10
+ * Gemini 3 Pro under `thinkingLevel: HIGH` legitimately re-emits the same
11
+ * `grep` / `read_file` 3× as "double-checks" within its thought process —
12
+ * not a stuck loop. Threshold-3 was tuned for 2.5 Pro and tripped before
13
+ * `maxIterations`, killing the rescue path. Threshold-5 covers the empirical
14
+ * double-check pattern with margin; `maxIterations` (default 20) and
15
+ * `maxTotalInputTokens` (default 1M) remain the upper-bound safety nets. */
16
+ export declare const NO_PROGRESS_CALL_THRESHOLD = 5;
17
+ /** Call-signature → state, for content-aware no-progress detection.
18
+ *
19
+ * v1.16.0 (P2 Phase B): replaces the v1.14.4 simple counter with a
20
+ * content-aware version. Pre-Phase-B `signatureCounts: Map<string,
21
+ * number>` tracked repeat occurrences of the same signature and
22
+ * tripped after N repeats even if the model had made progress
23
+ * elsewhere since an earlier occurrence. That was empirically wrong
24
+ * on 2026-04-30 — Gemini 3 Pro under HIGH thinking re-runs the same
25
+ * `grep` while ALSO reading new files, which IS progress, but the
26
+ * simple counter still tripped.
27
+ *
28
+ * Phase B tracks `lastFilesReadSize` per signature: same signature
29
+ * counts toward the threshold ONLY if no `read_file` against an
30
+ * unseen path happened between repeats. If `filesReadSet` grew
31
+ * since the previous identical signature, count resets to 1
32
+ * (current call) — the model is exploring, not stuck.
33
+ *
34
+ * Why `read_file` specifically and not all tool calls? `list_directory`
35
+ * / `find_files` / `grep` are exploration without commitment. They
36
+ * tell us where to look but don't capture content into the
37
+ * conversation. `read_file` is the progress signal — it means
38
+ * "I found something worth examining" and grows the conversation
39
+ * the rescue path will replay.
40
+ *
41
+ * Threshold (NO_PROGRESS_CALL_THRESHOLD = 5) unchanged from v1.14.4
42
+ * — Phase B refines the SIGNAL, not the cap. Hard upper bound
43
+ * remains `maxIterations` × `maxTotalInputTokens`. */
44
+ export type SignatureCounts = Map<string, {
45
+ count: number;
46
+ lastFilesReadSize: number;
47
+ }>;
48
+ /** The signature that tripped the detector and how many times it was repeated. */
49
+ export interface NoProgress {
50
+ signature: string;
51
+ count: number;
52
+ }
53
+ /**
54
+ * No-progress detection (v1.16.0 P2 Phase B — content-aware): bails when any
55
+ * single call signature has been issued `NO_PROGRESS_CALL_THRESHOLD` times
56
+ * without any new `filesReadSet` growth between repeats. If `filesReadSet`
57
+ * grew, the model is exploring (productive) — reset that signature's count
58
+ * to 1.
59
+ *
60
+ * `filesReadSizeAtIterEnd` is captured ONCE per iter (after tool execution)
61
+ * so all signatures within the same iter see the same "size at end of this
62
+ * iter" snapshot. Without the snapshot, a single iter that issues
63
+ * `read_file` AND `grep` AND `read_file` would have a different
64
+ * `filesReadSet.size` per signature depending on tool-execution order —
65
+ * non-deterministic + wrong (the snapshot represents iter-level progress,
66
+ * not within-iter).
67
+ *
68
+ * AA1 fix (v1.16.0 PR-Round-1, 3-of-3 cross-corroborated TP HIGH): ALSO
69
+ * dedupe signatures WITHIN an iter before counting. The counter
70
+ * conceptually measures iters-spent-stuck, not raw emission count. If the
71
+ * model glitches and emits the same `grep` 5× in one parallel batch, that's
72
+ * pathological output for ONE iter — should count as +1 toward the
73
+ * threshold, not +5. Pre-AA1 the counter compounded 1→2→3→4→5 in a single
74
+ * iter, instantly tripping AGENTIC_NO_PROGRESS even though zero stuck-iters
75
+ * had elapsed.
76
+ *
77
+ * Tool-surface assumption (AA2 ACCEPTED-DEFERRED): `read_file` is the sole
78
+ * progress oracle because ask_agentic's tool surface is exclusively
79
+ * read-only (`read_file`, `grep`, `list_directory`, `find_files` — no
80
+ * write_file, no terminal exec). When a future PR adds workspace-mutating
81
+ * tools, this oracle MUST be expanded to track any state-changing tool call
82
+ * (e.g., a combined "workspace state version" counter) — otherwise a model
83
+ * iterating on edits + command execution would false-positive
84
+ * AGENTIC_NO_PROGRESS.
85
+ *
86
+ * Returns the first signature that reaches the threshold (the signatures
87
+ * after it in this iteration are not counted), or `null`.
88
+ */
89
+ export declare function detectNoProgress(signatures: ToolCall[], signatureCounts: SignatureCounts, filesReadSizeAtIterEnd: number): NoProgress | null;
90
+ //# sourceMappingURL=no-progress.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-progress.d.ts","sourceRoot":"","sources":["../../../src/tools/agentic/no-progress.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C;;;;;;;;;4EAS4E;AAC5E,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;sDA0BsD;AACtD,MAAM,MAAM,eAAe,GAAG,GAAG,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAExF,kFAAkF;AAClF,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,QAAQ,EAAE,EACtB,eAAe,EAAE,eAAe,EAChC,sBAAsB,EAAE,MAAM,GAC7B,UAAU,GAAG,IAAI,CAenB"}
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Content-aware no-progress detection for the `ask_agentic` loop: a call signature repeated
3
+ * `NO_PROGRESS_CALL_THRESHOLD` times with no new file read between the repeats ends the loop.
4
+ */
5
+ /** If the SAME call signature (name + args) appears this many times, we
6
+ * conclude the model is stuck in a loop and surface a partial answer.
7
+ *
8
+ * Bumped 3 → 5 in v1.14.4 after empirical replay (2026-04-30) showed
9
+ * Gemini 3 Pro under `thinkingLevel: HIGH` legitimately re-emits the same
10
+ * `grep` / `read_file` 3× as "double-checks" within its thought process —
11
+ * not a stuck loop. Threshold-3 was tuned for 2.5 Pro and tripped before
12
+ * `maxIterations`, killing the rescue path. Threshold-5 covers the empirical
13
+ * double-check pattern with margin; `maxIterations` (default 20) and
14
+ * `maxTotalInputTokens` (default 1M) remain the upper-bound safety nets. */
15
+ export const NO_PROGRESS_CALL_THRESHOLD = 5;
16
+ /**
17
+ * No-progress detection (v1.16.0 P2 Phase B — content-aware): bails when any
18
+ * single call signature has been issued `NO_PROGRESS_CALL_THRESHOLD` times
19
+ * without any new `filesReadSet` growth between repeats. If `filesReadSet`
20
+ * grew, the model is exploring (productive) — reset that signature's count
21
+ * to 1.
22
+ *
23
+ * `filesReadSizeAtIterEnd` is captured ONCE per iter (after tool execution)
24
+ * so all signatures within the same iter see the same "size at end of this
25
+ * iter" snapshot. Without the snapshot, a single iter that issues
26
+ * `read_file` AND `grep` AND `read_file` would have a different
27
+ * `filesReadSet.size` per signature depending on tool-execution order —
28
+ * non-deterministic + wrong (the snapshot represents iter-level progress,
29
+ * not within-iter).
30
+ *
31
+ * AA1 fix (v1.16.0 PR-Round-1, 3-of-3 cross-corroborated TP HIGH): ALSO
32
+ * dedupe signatures WITHIN an iter before counting. The counter
33
+ * conceptually measures iters-spent-stuck, not raw emission count. If the
34
+ * model glitches and emits the same `grep` 5× in one parallel batch, that's
35
+ * pathological output for ONE iter — should count as +1 toward the
36
+ * threshold, not +5. Pre-AA1 the counter compounded 1→2→3→4→5 in a single
37
+ * iter, instantly tripping AGENTIC_NO_PROGRESS even though zero stuck-iters
38
+ * had elapsed.
39
+ *
40
+ * Tool-surface assumption (AA2 ACCEPTED-DEFERRED): `read_file` is the sole
41
+ * progress oracle because ask_agentic's tool surface is exclusively
42
+ * read-only (`read_file`, `grep`, `list_directory`, `find_files` — no
43
+ * write_file, no terminal exec). When a future PR adds workspace-mutating
44
+ * tools, this oracle MUST be expanded to track any state-changing tool call
45
+ * (e.g., a combined "workspace state version" counter) — otherwise a model
46
+ * iterating on edits + command execution would false-positive
47
+ * AGENTIC_NO_PROGRESS.
48
+ *
49
+ * Returns the first signature that reaches the threshold (the signatures
50
+ * after it in this iteration are not counted), or `null`.
51
+ */
52
+ export function detectNoProgress(signatures, signatureCounts, filesReadSizeAtIterEnd) {
53
+ const uniqueSigsThisIter = new Set();
54
+ for (const { name, args } of signatures) {
55
+ uniqueSigsThisIter.add(`${name}(${stableJson(args)})`);
56
+ }
57
+ for (const sig of uniqueSigsThisIter) {
58
+ const prev = signatureCounts.get(sig);
59
+ // Reset count when files grew between identical signatures —
60
+ // model is making progress, not stuck. Otherwise increment.
61
+ const count = prev && filesReadSizeAtIterEnd > prev.lastFilesReadSize ? 1 : (prev?.count ?? 0) + 1;
62
+ signatureCounts.set(sig, { count, lastFilesReadSize: filesReadSizeAtIterEnd });
63
+ if (count >= NO_PROGRESS_CALL_THRESHOLD)
64
+ return { signature: sig, count };
65
+ }
66
+ return null;
67
+ }
68
+ /** Maximum recursion depth for `stableJson`. Function-call args in
69
+ * practice are flat `{path, startLine, endLine}` objects, so 10 levels
70
+ * is generous. Guards against stack overflow if a prompt-injected cache
71
+ * managed to smuggle a nested structure into the model's tool-call args. */
72
+ const STABLE_JSON_MAX_DEPTH = 10;
73
+ /** Stable-key JSON for comparing function-call signatures across
74
+ * iterations. Sorted keys so `{a:1,b:2}` and `{b:2,a:1}` hash identical.
75
+ *
76
+ * Hardening (PR #24 review by Grok): depth-limited + protected against
77
+ * circular references. The outer `JSON.stringify` would throw on a cycle,
78
+ * which we catch; but we also walk with our own depth counter because a
79
+ * deeply nested (non-cyclic) args tree can still blow the stack on the
80
+ * default V8 async-aware trampoline. On overflow or stringify error we
81
+ * fall back to a truncated `String(value)` so the no-progress detector
82
+ * still has SOME key rather than crashing the loop. */
83
+ function stableJson(value, depth = 0) {
84
+ if (depth > STABLE_JSON_MAX_DEPTH)
85
+ return '"[depth-truncated]"';
86
+ if (value === null || typeof value !== 'object') {
87
+ try {
88
+ return JSON.stringify(value);
89
+ }
90
+ catch {
91
+ return `"[unstringifiable:${typeof value}]"`;
92
+ }
93
+ }
94
+ if (Array.isArray(value)) {
95
+ return `[${value.map((v) => stableJson(v, depth + 1)).join(',')}]`;
96
+ }
97
+ try {
98
+ const keys = Object.keys(value).sort();
99
+ return `{${keys
100
+ .map((k) => `${JSON.stringify(k)}:${stableJson(value[k], depth + 1)}`)
101
+ .join(',')}}`;
102
+ }
103
+ catch {
104
+ return `"[unstringifiable-object]"`;
105
+ }
106
+ }
107
+ //# sourceMappingURL=no-progress.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-progress.js","sourceRoot":"","sources":["../../../src/tools/agentic/no-progress.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH;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QAAQ,EAAE,CAAC;QAChD,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,qBAAqB,OAAO,KAAK,IAAI,CAAC;QAC/C,CAAC;IACH,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IACrE,CAAC;IACD,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAgC,CAAC,CAAC,IAAI,EAAE,CAAC;QAClE,OAAO,IAAI,IAAI;aACZ,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CACJ,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,UAAU,CAAE,KAAiC,CAAC,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,EAAE,CACzF;aACA,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAClB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,4BAA4B,CAAC;IACtC,CAAC;AACH,CAAC"}
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The one clock of an `ask_agentic` pass (a loop iteration or the forced-finalization pass): every phase of the pass
3
+ * reads its bound from it (`docs/DESIGN-agentic-time-bounds.md`). `iterationTimeoutMs` is the pass's wall clock, armed
4
+ * at creation over every phase; `stallMs` bounds the gaps of the stream only — armed at the first chunk, re-armed per
5
+ * chunk, cleared when the pass leaves the stream; a phase's default (`phase-defaults.ts`) applies only where no knob
6
+ * bounds that phase — the tools phase's is a bound on silence, which executor progress (`recordProgress`) defers. At
7
+ * most two timers are alive at once: the pass deadline and the current phase's.
8
+ */
9
+ import { type TimeoutKind } from '../shared/abort-timeout.js';
10
+ import { type PhaseDefaults } from './phase-defaults.js';
11
+ /** The phases of one pass, in order. The forced pass has `tpm-wait` and `finalization` only. */
12
+ export type PassPhase = 'tpm-wait' | 'opening' | 'stream' | 'tools' | 'finalization';
13
+ /** The phases a default bounds: every phase but the TPM wait, whose throttle delay is finite and known at its start. */
14
+ export type DefaultedPhase = Exclude<PassPhase, 'tpm-wait'>;
15
+ /** The knobs of a call that the clock keeps as bounds. */
16
+ export type KnobSource = 'iterationTimeoutMs' | 'stallMs';
17
+ /** Where a bound the clock keeps comes from. */
18
+ export type ClockSource = KnobSource | 'default';
19
+ /** Where the timeout that ended a pass comes from: a bound of the clock, or `external` — a `TimeoutError` the clock did
20
+ * not raise (an SDK's own), which no bound of this call set. */
21
+ export type BoundSource = ClockSource | 'external';
22
+ /** The call's two knobs, resolved once per call (per call, else the environment); `null` when unset. */
23
+ export interface AgenticKnobs {
24
+ readonly iterationMs: number | null;
25
+ readonly stallMs: number | null;
26
+ }
27
+ /** A knob of the call fired, in the phase the pass was in: read from the clock, never parsed from a message. */
28
+ export interface KnobTimeout {
29
+ readonly phase: PassPhase;
30
+ readonly kind: TimeoutKind;
31
+ readonly source: KnobSource;
32
+ readonly limitMs: number;
33
+ }
34
+ /** A phase's default fired: never in the TPM wait, which has none. */
35
+ export interface DefaultTimeout {
36
+ readonly phase: DefaultedPhase;
37
+ readonly kind: TimeoutKind;
38
+ readonly source: 'default';
39
+ readonly limitMs: number;
40
+ }
41
+ /** A bound of the clock fired. */
42
+ export type ClockTimeout = KnobTimeout | DefaultTimeout;
43
+ /** A `TimeoutError` the clock did not raise ended the pass: no bound of this call fired; `message` is the error's own. */
44
+ export interface ExternalTimeout {
45
+ readonly phase: PassPhase;
46
+ readonly kind: TimeoutKind;
47
+ readonly source: 'external';
48
+ readonly limitMs: null;
49
+ readonly message: string;
50
+ }
51
+ /** What ended a pass on a timeout. */
52
+ export type PassTimeout = ClockTimeout | ExternalTimeout;
53
+ export interface PassClock {
54
+ /** Fires when a bound of the pass fires; its reason is a `TimeoutError` carrying `timeoutPhase` / `timeoutSource`. */
55
+ readonly signal: AbortSignal;
56
+ /** The pass's wall clock (`iterationTimeoutMs`), `null` when unset. */
57
+ readonly timeoutMs: number | null;
58
+ /** The stream's gap watchdog (`stallMs`), `null` when unset. */
59
+ readonly stallMs: number | null;
60
+ readonly phase: PassPhase;
61
+ /** The bound that fired, `null` while none has. */
62
+ readonly timedOut: ClockTimeout | null;
63
+ /** How long, after the tools phase's bound fired, the executors still running are given to settle. */
64
+ readonly settleGraceMs: number;
65
+ /** Leave the current phase: its timer is cleared and the next phase's armed. Entering the phase the pass is in arms
66
+ * its default afresh. A no-op after a fire and after `dispose`: the clock's phase is then the one it stopped in. */
67
+ enter(phase: PassPhase): void;
68
+ /** A chunk arrived: the first one moves `opening` to `stream`; each one re-arms the gap timer. A no-op after a fire
69
+ * and after `dispose`. */
70
+ recordChunk(): void;
71
+ /** An executor made progress: in phase `tools` the silence its default counts starts again; a no-op in every other
72
+ * phase, under `iterationTimeoutMs` (no phase timer: the deadline stays a wall clock), after a fire and after
73
+ * `dispose`. A tick writes one timestamp; the timer is re-armed only when it expires. */
74
+ recordProgress(): void;
75
+ /** Clear both timers. Idempotent; nothing is armed afterwards. */
76
+ dispose(): void;
77
+ }
78
+ /** A new pass's clock, in phase `tpm-wait`, the pass deadline armed when `iterationTimeoutMs` is set. */
79
+ export declare function createPassClock(knobs: AgenticKnobs, defaults?: PhaseDefaults): PassClock;
80
+ /**
81
+ * What ended a pass that failed on a timeout: the bound the clock fired, else an `external` timeout — the error's own
82
+ * kind and message, in the phase the pass was in, no bound of this call named.
83
+ */
84
+ export declare function passTimeoutOf(clock: PassClock, err: unknown): PassTimeout;
85
+ //# sourceMappingURL=pass-clock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pass-clock.d.ts","sourceRoot":"","sources":["../../../src/tools/agentic/pass-clock.ts"],"names":[],"mappings":"AAAA;;;;;;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,eAAe;IAC9B,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED,sCAAsC;AACtC,MAAM,MAAM,WAAW,GAAG,YAAY,GAAG,eAAe,CAAC;AAEzD,MAAM,WAAW,SAAS;IACxB,sHAAsH;IACtH,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,gEAAgE;IAChE,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI,CAAC;IACvC,sGAAsG;IACtG,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B;wHACoH;IACpH,KAAK,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IAC9B;8BAC0B;IAC1B,WAAW,IAAI,IAAI,CAAC;IACpB;;6FAEyF;IACzF,cAAc,IAAI,IAAI,CAAC;IACvB,kEAAkE;IAClE,OAAO,IAAI,IAAI,CAAC;CACjB;AA4JD,yGAAyG;AACzG,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,EACnB,QAAQ,GAAE,aAA8B,GACvC,SAAS,CAEX;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,GAAG,WAAW,CASzE"}
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The one clock of an `ask_agentic` pass (a loop iteration or the forced-finalization pass): every phase of the pass
3
+ * reads its bound from it (`docs/DESIGN-agentic-time-bounds.md`). `iterationTimeoutMs` is the pass's wall clock, armed
4
+ * at creation over every phase; `stallMs` bounds the gaps of the stream only — armed at the first chunk, re-armed per
5
+ * chunk, cleared when the pass leaves the stream; a phase's default (`phase-defaults.ts`) applies only where no knob
6
+ * bounds that phase — the tools phase's is a bound on silence, which executor progress (`recordProgress`) defers. At
7
+ * most two timers are alive at once: the pass deadline and the current phase's.
8
+ */
9
+ import { getTimeoutKind, timeoutReason, unrefTimer, } from '../shared/abort-timeout.js';
10
+ import { PHASE_DEFAULTS } from './phase-defaults.js';
11
+ /** The default of phase `phase` when no knob bounds it; `null` while `iterationTimeoutMs` bounds the pass. */
12
+ const unlessDeadline = (phase, defaultMs, idle = false) => (knobs, d) => knobs.iterationMs === null
13
+ ? { kind: 'total', source: 'default', phase, limitMs: defaultMs(d), idle }
14
+ : null;
15
+ /** A stream gap: `stallMs`, else the default when no knob bounds the stream. Each chunk re-arms it (`recordChunk`). */
16
+ function streamGapBound(knobs, d) {
17
+ if (knobs.stallMs !== null) {
18
+ return { kind: 'stall', source: 'stallMs', limitMs: knobs.stallMs, idle: false };
19
+ }
20
+ if (knobs.iterationMs !== null)
21
+ return null;
22
+ return { kind: 'stall', source: 'default', phase: 'stream', limitMs: d.streamGapMs, idle: false };
23
+ }
24
+ const PHASE_BOUND = {
25
+ 'tpm-wait': () => null,
26
+ opening: unlessDeadline('opening', (d) => d.openingMs),
27
+ stream: streamGapBound,
28
+ tools: unlessDeadline('tools', (d) => d.toolsIdleMs, true),
29
+ finalization: unlessDeadline('finalization', (d) => d.finalizationMs),
30
+ };
31
+ /** What a fired bound reports: a default its own phase — the one it was armed for, which is the pass's phase, since
32
+ * leaving the phase clears it —, a knob the phase the pass is in. */
33
+ function timeoutOf(bound, current) {
34
+ const { kind, limitMs } = bound;
35
+ if (bound.source === 'default')
36
+ return { phase: bound.phase, kind, source: 'default', limitMs };
37
+ return { phase: current, kind, source: bound.source, limitMs };
38
+ }
39
+ /** One pass's clock: one `AbortController`, the pass deadline's timer and the current phase's. */
40
+ class Clock {
41
+ knobs;
42
+ defaults;
43
+ signal;
44
+ timeoutMs;
45
+ stallMs;
46
+ controller = new AbortController();
47
+ current = 'tpm-wait';
48
+ fired = null;
49
+ /** When the current phase's silence started: its timer's arming, or the last executor progress since. */
50
+ quietSince = 0;
51
+ disposed = false;
52
+ passTimer = null;
53
+ phaseTimer = null;
54
+ constructor(knobs, defaults) {
55
+ this.knobs = knobs;
56
+ this.defaults = defaults;
57
+ this.signal = this.controller.signal;
58
+ this.timeoutMs = knobs.iterationMs;
59
+ this.stallMs = knobs.stallMs;
60
+ if (knobs.iterationMs !== null) {
61
+ const deadline = {
62
+ kind: 'total',
63
+ source: 'iterationTimeoutMs',
64
+ limitMs: knobs.iterationMs,
65
+ idle: false,
66
+ };
67
+ this.passTimer = unrefTimer(deadline.limitMs, () => this.fire(deadline));
68
+ }
69
+ }
70
+ get phase() {
71
+ return this.current;
72
+ }
73
+ get timedOut() {
74
+ return this.fired;
75
+ }
76
+ get settleGraceMs() {
77
+ return this.defaults.toolSettleGraceMs;
78
+ }
79
+ enter(phase) {
80
+ if (this.stopped())
81
+ return;
82
+ this.current = phase;
83
+ this.armPhase();
84
+ }
85
+ recordChunk() {
86
+ if (this.stopped())
87
+ return;
88
+ if (this.current === 'opening')
89
+ this.current = 'stream';
90
+ if (this.current === 'stream')
91
+ this.armPhase();
92
+ }
93
+ recordProgress() {
94
+ if (this.current === 'tools' && this.phaseTimer !== null)
95
+ this.quietSince = performance.now();
96
+ }
97
+ dispose() {
98
+ this.disposed = true;
99
+ this.clearTimers();
100
+ }
101
+ /** A fired or disposed clock arms nothing and its phase stays where it stopped. */
102
+ stopped() {
103
+ return this.disposed || this.signal.aborted;
104
+ }
105
+ armPhase() {
106
+ this.clearPhaseTimer();
107
+ const bound = PHASE_BOUND[this.current](this.knobs, this.defaults);
108
+ if (bound === null)
109
+ return;
110
+ this.quietSince = performance.now();
111
+ this.phaseTimer = unrefTimer(bound.limitMs, () => this.phaseExpired(bound));
112
+ }
113
+ /** The phase's timer ran out: an idle bound with progress since its arming waits out the rest of its silence. */
114
+ phaseExpired(bound) {
115
+ const quietMs = performance.now() - this.quietSince;
116
+ if (bound.idle && quietMs < bound.limitMs) {
117
+ this.phaseTimer = unrefTimer(bound.limitMs - quietMs, () => this.phaseExpired(bound));
118
+ return;
119
+ }
120
+ this.fire(bound);
121
+ }
122
+ fire(bound) {
123
+ if (this.signal.aborted)
124
+ return;
125
+ const fired = timeoutOf(bound, this.current);
126
+ this.fired = fired;
127
+ this.clearTimers();
128
+ const extra = { timeoutPhase: fired.phase, timeoutSource: fired.source };
129
+ this.controller.abort(timeoutReason(fired.limitMs, fired.kind, extra));
130
+ }
131
+ clearPhaseTimer() {
132
+ if (this.phaseTimer !== null)
133
+ clearTimeout(this.phaseTimer);
134
+ this.phaseTimer = null;
135
+ }
136
+ clearTimers() {
137
+ if (this.passTimer !== null)
138
+ clearTimeout(this.passTimer);
139
+ this.passTimer = null;
140
+ this.clearPhaseTimer();
141
+ }
142
+ }
143
+ /** A new pass's clock, in phase `tpm-wait`, the pass deadline armed when `iterationTimeoutMs` is set. */
144
+ export function createPassClock(knobs, defaults = PHASE_DEFAULTS) {
145
+ return new Clock(knobs, defaults);
146
+ }
147
+ /**
148
+ * What ended a pass that failed on a timeout: the bound the clock fired, else an `external` timeout — the error's own
149
+ * kind and message, in the phase the pass was in, no bound of this call named.
150
+ */
151
+ export function passTimeoutOf(clock, err) {
152
+ if (clock.timedOut !== null)
153
+ return clock.timedOut;
154
+ return {
155
+ phase: clock.phase,
156
+ kind: getTimeoutKind(err) ?? 'total',
157
+ source: 'external',
158
+ limitMs: null,
159
+ message: err instanceof Error ? err.message : String(err),
160
+ };
161
+ }
162
+ //# sourceMappingURL=pass-clock.js.map