@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,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,GAAG,WAAW,CAAC,QAAQ,CAA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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"}
@@ -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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,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;;;;;;;;;4EAS4E;AAC5E,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAqC5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,gBAAgB,CAC9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