jeopi-ai 16.7.7 → 16.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [16.7.11] - 2026-11-23
6
+
7
+ ### Fixed
8
+
9
+ - Clamped `usage.input` to `>= 0` in `google-gemini-cli` and `google-shared` when providers report `cachedContentTokenCount > promptTokenCount`.
10
+ - Narrowed `EVAL_CMD_TOKEN_RE` in `ToolCallLoopGuard` from `jev(?:\s+status)?` to `jev\s+status` so distinct read-only `eval` calls mentioning `jev` in paths or strings do not collapse into false-positive loop detections.
11
+
12
+ ## [16.7.8] - 2026-11-23
13
+
14
+ ### Added
15
+
16
+ - Extended `ToolCallLoopGuard` with `maxRedirectsBeforeStop` escalation, `reason` classification on `stalled_tool_call` (`unchanged_output`, `error_streak`, `redirect_escalation`, `cycle_escalation`), parallel batch stall detection, 3-step cycle detection/escalation, and `reset()`.
17
+ - Exported `isTransientStreamDropError`, `is402BillingCapBody`, and `isBillingCapUsageLimit` from the error classifier.
18
+
19
+ ### Fixed
20
+
21
+ - Classified mid-stream transport drops and inflected `stream stalled` watchdogs as retryable transient errors while keeping terminal 4xx responses non-retryable, and classified HTTP 402 billing-cap bodies as usage limits.
22
+ - Raised default `streamFirstEventTimeoutMs` and `streamIdleTimeoutMs` stream watchdogs to 15 minutes (`900_000` ms) to avoid aborting long reasoning streams prematurely.
23
+ - Exempted structured JSON records and pipe-led markdown tables whose rows vary only in numbers from `ThinkingLoopDetector` trigram false positives while still catching byte-identical row cycles.
24
+
5
25
  ## [16.7.6] - 2026-11-21
6
26
 
7
27
  ### Fixed
@@ -74,6 +74,8 @@ export declare function isContextOverflow(message: AssistantMessage, contextWind
74
74
  export declare function stringify(id: number | undefined): string;
75
75
  /** Transient stream corruption where the response was truncated mid-JSON. */
76
76
  export declare function isTransientStreamParseError(error: unknown): boolean;
77
+ /** Transport stream-drop diagnostic (see {@link STREAM_DROP_PATTERN}). */
78
+ export declare function isTransientStreamDropError(error: unknown): boolean;
77
79
  /** Any malformed stream-envelope error (prefix-tagged or out-of-order events). */
78
80
  export declare function isStreamEnvelopeError(error: unknown): boolean;
79
81
  /** Stream-envelope errors safe to retry against the provider (event ordering only). */
@@ -20,31 +20,31 @@ export declare function calculateRateLimitBackoffMs(reason: RateLimitReason): nu
20
20
  /**
21
21
  * HTTP status codes that, absent richer body classification, represent an
22
22
  * account-local usage cap rather than a bad credential or a transient blip.
23
- * Always combine with {@link isUsageLimitOutcome} when a message is available
24
- * — a 429 carrying transient rate-limit wording is NOT a usage cap.
23
+ * HTTP 402 Payment Required represents an account-billing cap when opaque,
24
+ * payment/deactivation/balance/funds/billing-error-worded, or QUOTA_EXHAUSTED.
25
+ * Always combine with {@link isUsageLimitOutcome} when a message is available.
25
26
  */
26
27
  export declare function isUsageLimitStatus(status: number | undefined): boolean;
28
+ export declare function is402BillingCapBody(message: string | undefined): boolean;
29
+ /**
30
+ * True when a usage-limit failure reflects a billing/credit cap (cannot recover
31
+ * by waiting out a short quota reset window).
32
+ */
33
+ export declare function isBillingCapUsageLimit(status: number | undefined, message: string | undefined): boolean;
27
34
  /**
28
35
  * Returns true for failures that should burn one credential and rotate to a
29
36
  * sibling account. Decision tree:
30
37
  *
31
- * 1. Body matches {@link isUsageLimitError} (Codex `usage_limit_reached`,
32
- * Anthropic account rate-limit, Google `resource_exhausted`, OpenAI
33
- * `insufficient_quota`, …) → rotate.
34
- * 2. Status is not 429 → backoff (caller's domain).
35
- * 3. Body is absent or {@link isOpaqueStatusBody opaque} (just the status,
36
- * empty JSON, HTTP framing only) → rotate conservatively: the server
37
- * gave us nothing else to go on.
38
- * 4. Body has content → defer to {@link parseRateLimitReason}. Only
39
- * `QUOTA_EXHAUSTED` rotates; `RATE_LIMIT_EXCEEDED` (`Too many requests`,
40
- * per-minute caps), `MODEL_CAPACITY_EXHAUSTED` (`Service overloaded`),
41
- * `SERVER_ERROR`, and `UNKNOWN` (`Please retry in 5s`) stay in the
42
- * provider's own backoff layer so transient 429s don't burn sibling
43
- * credentials.
38
+ * 1. Status 402 → delegate to {@link is402BillingCapBody}.
39
+ * 2. Body matches {@link matchesUsageLimitText} → rotate.
40
+ * 3. Status is not 429/402 → backoff (caller's domain).
41
+ * 4. Body is absent or {@link isOpaqueStatusBody opaque} → rotate conservatively.
42
+ * 5. Body has content → defer to {@link parseRateLimitReason}. Only
43
+ * `QUOTA_EXHAUSTED` rotates.
44
44
  */
45
45
  export declare function isUsageLimitOutcome(status: number | undefined, message: string | undefined): boolean;
46
46
  /**
47
- * A 429 body is opaque when it carries no signal beyond the status itself —
47
+ * A 429/402 body is opaque when it carries no signal beyond the status itself —
48
48
  * empty, whitespace-only, the status digits with HTTP/JSON framing, or
49
49
  * generic punctuation. Anything else (retry hints, capacity wording, error
50
50
  * descriptions) is informative enough to defer to the classifier.
@@ -288,7 +288,7 @@ export interface StreamOptions {
288
288
  * in the iterator while waiting for the first semantic stream event. Set to
289
289
  * `0` to disable both layers for this request. After the first semantic
290
290
  * event arrives, `streamIdleTimeoutMs` governs inter-event stalls. Falls
291
- * back to `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` and then to a 100s default.
291
+ * back to `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` and then to a 900s default.
292
292
  * OpenAI-family transports additionally honor
293
293
  * `PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS` as the most-specific override and
294
294
  * floor the first-event budget at the resolved idle (per-call
@@ -307,7 +307,7 @@ export interface StreamOptions {
307
307
  * mid-stream stalls (broker dies, half-open socket, model produces no real
308
308
  * progress for too long). Set to `0` to disable. Falls back to
309
309
  * `PI_STREAM_IDLE_TIMEOUT_MS` (alias: `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS`)
310
- * and then to a 120s default.
310
+ * and then to a 900s default.
311
311
  */
312
312
  streamIdleTimeoutMs?: number;
313
313
  /**
@@ -1,15 +1,21 @@
1
- import type { AssistantMessage, ToolResultMessage } from "../types";
1
+ import type { AssistantMessage, ToolCall, ToolResultMessage } from "../types";
2
2
  /** Runtime settings for cross-turn tool-call repetition detection. */
3
3
  export interface ToolCallLoopGuardOptions {
4
4
  readonly threshold: number;
5
5
  readonly exemptTools: readonly string[];
6
+ /** Lets transport calls inherit an exemption from their dispatched tool without exempting the transport itself. */
7
+ readonly exemptionAlias?: (call: ToolCall) => string | undefined;
6
8
  /** Window size for alternating-pattern (A,B,A,B,…) cycle detection; defaults to 6. */
7
9
  readonly cycleWindowSize?: number;
10
+ /** Redirects allowed before escalating to stalled_tool_call (`0` disables redirect-count escalation; default `2`). */
11
+ readonly maxRedirectsBeforeStop?: number;
8
12
  }
9
13
  /** A completed assistant turn plus the tool results it produced. */
10
14
  export interface ToolCallLoopTurn {
11
15
  readonly message: AssistantMessage;
12
16
  readonly toolResults: readonly ToolResultMessage[];
17
+ /** The turn also delivered context outside its tool results (extension `additionalContext`). */
18
+ readonly injectedContext?: boolean;
13
19
  }
14
20
  /** Details needed to steer the model away from a repeated tool call. */
15
21
  export interface RepeatedToolCallDetection {
@@ -29,11 +35,13 @@ export interface CyclicalToolCallDetection {
29
35
  export type ToolCallLoopDetection = RepeatedToolCallDetection | CyclicalToolCallDetection | {
30
36
  readonly kind: "stalled_tool_call";
31
37
  readonly toolName: string;
38
+ readonly reason?: "unchanged_output" | "error_streak" | "redirect_escalation" | "cycle_escalation";
32
39
  };
33
40
  /** Detects consecutive identical or semantically repeated assistant tool calls across model turns. */
34
41
  export declare class ToolCallLoopGuard {
35
42
  #private;
36
43
  constructor(options: ToolCallLoopGuardOptions);
44
+ reset(): void;
37
45
  /** Records one completed turn and returns the threshold/cycle hit, if any. */
38
46
  recordTurn(turn: ToolCallLoopTurn): ToolCallLoopDetection | null;
39
47
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "jeopi-ai",
4
- "version": "16.7.7",
4
+ "version": "16.7.11",
5
5
  "description": "Unified LLM API with automatic model discovery and provider configuration",
6
6
  "homepage": "https://github.com/akillness/jeopi",
7
7
  "author": "Can Boluk",
@@ -38,9 +38,9 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@bufbuild/protobuf": "^2.12.0",
41
- "jeopi-catalog": "16.7.7",
42
- "jeopi-utils": "16.7.7",
43
- "jeopi-wire": "16.7.7",
41
+ "jeopi-catalog": "16.7.11",
42
+ "jeopi-utils": "16.7.11",
43
+ "jeopi-wire": "16.7.11",
44
44
  "arktype": "2.2.3",
45
45
  "zod": "^4"
46
46
  },
@@ -6,7 +6,7 @@ import {
6
6
  ProviderHttpError,
7
7
  STREAM_ENVELOPE_ERROR_PREFIX,
8
8
  } from "./classes";
9
- import { isOpaqueStatusBody, matchesUsageLimitText, parseRateLimitReason } from "./rate-limit";
9
+ import { is402BillingCapBody, isOpaqueStatusBody, matchesUsageLimitText, parseRateLimitReason } from "./rate-limit";
10
10
 
11
11
  export const Flag = {
12
12
  Class: 0x1000,
@@ -84,7 +84,7 @@ const OVERFLOW_PATTERNS = [
84
84
  ];
85
85
 
86
86
  const OVERFLOW_NO_BODY_PATTERN = /\b4(00|13)\s*(status code)?\s*\(no body\)/i;
87
- const TIMEOUT_PATTERN = /\b(?:operation\s+)?timed?\s*out\b|\btimeout\b|\bstream stall\b/i;
87
+ const TIMEOUT_PATTERN = /\b(?:operation\s+)?timed?\s*out\b|\btimeout\b|\bstream stall(?:ed|s|ing)?\b/i;
88
88
  const TRANSIENT_ENVELOPE_PATTERN = /anthropic stream envelope error:/i;
89
89
  const TRANSIENT_ENVELOPE_BEFORE_START_PATTERN = /before message_start/i;
90
90
  export const STREAM_READ_ERROR_PATTERN = /stream[_ -]?read[_ -]?error/i;
@@ -297,6 +297,10 @@ function matchesOverflowText(text: string): boolean {
297
297
  return OVERFLOW_PATTERNS.some(p => p.test(text)) || OVERFLOW_NO_BODY_PATTERN.test(text);
298
298
  }
299
299
 
300
+ function isTerminalClientErrorStatus(code: number | undefined): boolean {
301
+ return code !== undefined && code >= 400 && code < 500 && code !== 408 && code !== 429;
302
+ }
303
+
300
304
  function classifyText(errorMessage: string | undefined, errorStatus: number | undefined, api?: Api): number {
301
305
  let kinds = 0;
302
306
  if (errorMessage) {
@@ -311,15 +315,25 @@ function classifyText(errorMessage: string | undefined, errorStatus: number | un
311
315
  const isOpaque = isOpaqueStatusBody(cleanMessage);
312
316
 
313
317
  const isLimitStatus = statusClean === 429;
318
+ const is402BillingCap = statusClean === 402 && is402BillingCapBody(cleanMessage);
314
319
  if (
315
- matchesUsageLimitText(cleanMessage) ||
320
+ is402BillingCap ||
321
+ (statusClean !== 402 && matchesUsageLimitText(cleanMessage)) ||
316
322
  (isLimitStatus && (isOpaque || parseRateLimitReason(cleanMessage) === "QUOTA_EXHAUSTED"))
317
323
  ) {
318
324
  kinds |= Flag.UsageLimit;
319
325
  }
320
326
 
321
- if (isTimeoutText(errorMessage)) kinds |= Flag.Transient | Flag.Timeout;
322
- else if (isTransientErrorText(errorMessage)) kinds |= Flag.Transient;
327
+ // Transport/timeout/truncation/stream-drop wording that rides on a terminal
328
+ // 4xx describes a deterministic client error that replays identically, so
329
+ // keep it terminal — matching isProviderRetryableError.
330
+ if (!isTerminalClientErrorStatus(statusClean)) {
331
+ if (isTimeoutText(errorMessage)) kinds |= Flag.Transient | Flag.Timeout;
332
+ else if (isTransientErrorText(errorMessage)) kinds |= Flag.Transient;
333
+ if (isTransientStreamParseError(errorMessage) || isTransientStreamDropError(errorMessage)) {
334
+ kinds |= Flag.Transient;
335
+ }
336
+ }
323
337
  if ((api === "openai-responses" || api === "openai-codex-responses") && isStaleResponsesText(errorMessage)) {
324
338
  kinds |= Flag.StaleResponsesItem;
325
339
  }
@@ -329,6 +343,10 @@ function classifyText(errorMessage: string | undefined, errorStatus: number | un
329
343
  if (matchesGrammarTooLarge(cleanMessage, statusClean)) kinds |= Flag.Grammar;
330
344
  if (matchesFastModeUnsupported(cleanMessage, statusClean)) kinds |= Flag.FastModeUnsupported;
331
345
  }
346
+ const statusEvidence = errorStatus ?? (errorMessage ? status({ message: errorMessage }) : undefined);
347
+ if (statusEvidence === 402 && (errorMessage === undefined || isOpaqueStatusBody(errorMessage))) {
348
+ kinds |= Flag.UsageLimit;
349
+ }
332
350
  if (kinds !== 0) return create(kinds);
333
351
  const fallbackStatus = errorStatus ?? (errorMessage ? status({ message: errorMessage }) : undefined);
334
352
  if (fallbackStatus === 401 || fallbackStatus === 403) return create(Flag.AuthFailed);
@@ -339,6 +357,7 @@ export function classify(error: unknown, api?: Api): number {
339
357
  let kinds = 0;
340
358
  const seen = new Set<object>();
341
359
  let link: unknown = error;
360
+ let outerTerminalStatus: number | undefined;
342
361
  while (link !== undefined && link !== null) {
343
362
  if (typeof link === "object") {
344
363
  if (seen.has(link)) break;
@@ -369,7 +388,13 @@ export function classify(error: unknown, api?: Api): number {
369
388
  } else if (link instanceof ProviderHttpError) {
370
389
  let linkKinds = 0;
371
390
  const { status: codeStatus, code } = link;
372
- if (code === "usage_limit_reached" || code === "insufficient_quota") {
391
+ if (
392
+ code === "usage_limit_reached" ||
393
+ code === "insufficient_quota" ||
394
+ (codeStatus === 402 &&
395
+ (is402BillingCapBody(link.message) ||
396
+ (code !== undefined && !isOpaqueStatusBody(code) && is402BillingCapBody(code))))
397
+ ) {
373
398
  linkKinds |= Flag.UsageLimit;
374
399
  }
375
400
  if (code === "overloaded_error" || code === "rate_limit_error") {
@@ -400,7 +425,11 @@ export function classify(error: unknown, api?: Api): number {
400
425
  linkMessage = (link as { message: string }).message;
401
426
  }
402
427
 
403
- const textId = classifyText(linkMessage, status(link), api);
428
+ const linkStatus = status(link);
429
+ if (outerTerminalStatus === undefined && isTerminalClientErrorStatus(linkStatus)) {
430
+ outerTerminalStatus = linkStatus;
431
+ }
432
+ const textId = classifyText(linkMessage, linkStatus ?? outerTerminalStatus, api);
404
433
  kinds |= textId & KIND_MASK;
405
434
 
406
435
  link = typeof link === "object" && "cause" in link ? (link as { cause: unknown }).cause : undefined;
@@ -494,13 +523,29 @@ export function stringify(id: number | undefined): string {
494
523
 
495
524
  const STREAM_PARSE_TRUNCATION_PATTERN =
496
525
  /unterminated string|unexpected end of json input|unexpected end of data|unexpected eof|end of file|eof while parsing|truncated/i;
526
+ const STREAM_PARSE_DIAGNOSTIC_PATTERN =
527
+ /unterminated string|unexpected end of json input|unexpected end of data|unexpected eof|eof while parsing/i;
497
528
  const STREAM_EVENT_ORDER_PATTERN = /stream event order|before message_start/i;
498
529
 
499
530
  /** Transient stream corruption where the response was truncated mid-JSON. */
500
531
  export function isTransientStreamParseError(error: unknown): boolean {
532
+ if (typeof error === "string") return STREAM_PARSE_DIAGNOSTIC_PATTERN.test(error);
501
533
  return error instanceof Error && STREAM_PARSE_TRUNCATION_PATTERN.test(error.message);
502
534
  }
503
535
 
536
+ /**
537
+ * Transport-level stream drops: the connection or upstream stream ended before a
538
+ * terminal event, with no JSON-parse signal and no retryable status attached.
539
+ */
540
+ const STREAM_DROP_PATTERN =
541
+ /stream disconnected before completion|(?:stream|websocket) closed before response\.completed|stream (?:was )?interrupted|stream ended before (?:terminal (?:chunk|completion event)|message_(?:start|delta|stop))|socket disconnected before secure tls connection/i;
542
+
543
+ /** Transport stream-drop diagnostic (see {@link STREAM_DROP_PATTERN}). */
544
+ export function isTransientStreamDropError(error: unknown): boolean {
545
+ if (typeof error === "string") return STREAM_DROP_PATTERN.test(error);
546
+ return error instanceof Error && STREAM_DROP_PATTERN.test(error.message);
547
+ }
548
+
504
549
  /** Any malformed stream-envelope error (prefix-tagged or out-of-order events). */
505
550
  export function isStreamEnvelopeError(error: unknown): boolean {
506
551
  return (
@@ -100,37 +100,92 @@ export function calculateRateLimitBackoffMs(reason: RateLimitReason): number {
100
100
 
101
101
  /** Detect usage/quota limit errors in error messages (persistent, requires credential switch). */
102
102
  const USAGE_LIMIT_PATTERN =
103
- /usage.?limit|usage_limit_reached|usage_not_included|limit_reached|quota.?exceeded|quota.?reached|quota.?exhaust(ed|ion)?|resource.?exhausted|exhausted your capacity|quota will reset|insufficient.?(?:balance|quota)/i;
103
+ /usage.?limit|usage_limit_reached|usage_not_included|limit_reached|quota.?(?:exceeded|reached|exhaust(?:ed|ion)?|insufficient)|resource.?exhausted|exhausted your capacity|quota will reset|insufficient.?(?:balance|quota)|insufficient_g1_credits_balance/i;
104
+
105
+ const OUT_OF_CREDIT_PATTERN = /\bout of credit|\badd (?:more )?credit|\btop ?up\b|\bcredit balance\b/i;
106
+ const CREDITS_EXHAUSTED_PATTERN = /\bcredits?\s+(?:are\s+)?(?:exhausted|depleted|unavailable)\b/i;
107
+ const SPEND_LIMIT_PATTERN = /\bspending[- _]?limit\b/i;
108
+
109
+ const STATUS_402_QUOTA_PATTERN =
110
+ /\b(?:payment(?:\s+is)?[-_.\s]*required|deactivated_workspace|insufficient.?(?:balance|credits?|account.?funds)|requires?\s+more\s+credits|billing[-_.\s]*(?:verification|error|issue)|can only afford)\b/i;
111
+
112
+ // Machine fields survive provider parsing even when the human detail is generic.
113
+ const BILLING_ERROR_CODE_PATTERN = /^billing_(?:error|not_configured)$/i;
114
+ const BILLING_ERROR_FIELD_PATTERN = /\b(?:type|code|param)=billing_(?:error|not_configured)(?=[\s)]|$)/i;
115
+
116
+ function parseJsonBody(message: string): Record<string, unknown> | undefined {
117
+ const start = message.indexOf("{");
118
+ if (start === -1) return undefined;
119
+ try {
120
+ const parsed: unknown = JSON.parse(message.slice(start));
121
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
122
+ ? (parsed as Record<string, unknown>)
123
+ : undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }
104
128
 
105
129
  /**
106
130
  * HTTP status codes that, absent richer body classification, represent an
107
131
  * account-local usage cap rather than a bad credential or a transient blip.
108
- * Always combine with {@link isUsageLimitOutcome} when a message is available
109
- * — a 429 carrying transient rate-limit wording is NOT a usage cap.
132
+ * HTTP 402 Payment Required represents an account-billing cap when opaque,
133
+ * payment/deactivation/balance/funds/billing-error-worded, or QUOTA_EXHAUSTED.
134
+ * Always combine with {@link isUsageLimitOutcome} when a message is available.
110
135
  */
111
136
  export function isUsageLimitStatus(status: number | undefined): boolean {
112
- return status === 429;
137
+ return status === 429 || status === 402;
138
+ }
139
+
140
+ export function is402BillingCapBody(message: string | undefined): boolean {
141
+ if (message === undefined || isOpaqueStatusBody(message)) return true;
142
+ if (BILLING_ERROR_CODE_PATTERN.test(message) || BILLING_ERROR_FIELD_PATTERN.test(message)) return true;
143
+ const body = parseJsonBody(message);
144
+ const errorObj =
145
+ body?.error && typeof body.error === "object" && !Array.isArray(body.error)
146
+ ? (body.error as Record<string, unknown>)
147
+ : body;
148
+ if (
149
+ [errorObj?.type, errorObj?.code, errorObj?.param].some(
150
+ value => typeof value === "string" && BILLING_ERROR_CODE_PATTERN.test(value),
151
+ )
152
+ ) {
153
+ return true;
154
+ }
155
+ if (STATUS_402_QUOTA_PATTERN.test(message)) return true;
156
+ return parseRateLimitReason(message) === "QUOTA_EXHAUSTED";
157
+ }
158
+
159
+ /**
160
+ * True when a usage-limit failure reflects a billing/credit cap (cannot recover
161
+ * by waiting out a short quota reset window).
162
+ */
163
+ export function isBillingCapUsageLimit(status: number | undefined, message: string | undefined): boolean {
164
+ if (message === undefined) return false;
165
+ if (status === 402) return is402BillingCapBody(message);
166
+ return (
167
+ /\binsufficient_g1_credits_balance\b/i.test(message) ||
168
+ OUT_OF_CREDIT_PATTERN.test(message) ||
169
+ INSUFFICIENT_BALANCE_PATTERN.test(message) ||
170
+ CREDITS_EXHAUSTED_PATTERN.test(message) ||
171
+ SPEND_LIMIT_PATTERN.test(message) ||
172
+ /\binsufficient_quota\b/i.test(message)
173
+ );
113
174
  }
114
175
 
115
176
  /**
116
177
  * Returns true for failures that should burn one credential and rotate to a
117
178
  * sibling account. Decision tree:
118
179
  *
119
- * 1. Body matches {@link isUsageLimitError} (Codex `usage_limit_reached`,
120
- * Anthropic account rate-limit, Google `resource_exhausted`, OpenAI
121
- * `insufficient_quota`, …) → rotate.
122
- * 2. Status is not 429 → backoff (caller's domain).
123
- * 3. Body is absent or {@link isOpaqueStatusBody opaque} (just the status,
124
- * empty JSON, HTTP framing only) → rotate conservatively: the server
125
- * gave us nothing else to go on.
126
- * 4. Body has content → defer to {@link parseRateLimitReason}. Only
127
- * `QUOTA_EXHAUSTED` rotates; `RATE_LIMIT_EXCEEDED` (`Too many requests`,
128
- * per-minute caps), `MODEL_CAPACITY_EXHAUSTED` (`Service overloaded`),
129
- * `SERVER_ERROR`, and `UNKNOWN` (`Please retry in 5s`) stay in the
130
- * provider's own backoff layer so transient 429s don't burn sibling
131
- * credentials.
180
+ * 1. Status 402 → delegate to {@link is402BillingCapBody}.
181
+ * 2. Body matches {@link matchesUsageLimitText} → rotate.
182
+ * 3. Status is not 429/402 → backoff (caller's domain).
183
+ * 4. Body is absent or {@link isOpaqueStatusBody opaque} → rotate conservatively.
184
+ * 5. Body has content → defer to {@link parseRateLimitReason}. Only
185
+ * `QUOTA_EXHAUSTED` rotates.
132
186
  */
133
187
  export function isUsageLimitOutcome(status: number | undefined, message: string | undefined): boolean {
188
+ if (status === 402) return is402BillingCapBody(message);
134
189
  if (message && matchesUsageLimitText(message)) return true;
135
190
  if (!isUsageLimitStatus(status)) return false;
136
191
  if (!message || isOpaqueStatusBody(message)) return true;
@@ -138,14 +193,14 @@ export function isUsageLimitOutcome(status: number | undefined, message: string
138
193
  }
139
194
 
140
195
  /**
141
- * A 429 body is opaque when it carries no signal beyond the status itself —
196
+ * A 429/402 body is opaque when it carries no signal beyond the status itself —
142
197
  * empty, whitespace-only, the status digits with HTTP/JSON framing, or
143
198
  * generic punctuation. Anything else (retry hints, capacity wording, error
144
199
  * descriptions) is informative enough to defer to the classifier.
145
200
  */
146
201
  export function isOpaqueStatusBody(message: string): boolean {
147
202
  const cleaned = message
148
- .replace(/\b429\b/g, "")
203
+ .replace(/\b(?:402|429)\b/g, "")
149
204
  .replace(/\b(?:http|https|status|error|code|response|message)\b/gi, "");
150
205
  return !/[a-z\d]{3,}/i.test(cleaned);
151
206
  }
@@ -1,6 +1,7 @@
1
1
  import { isRetryableError, isUnexpectedSocketCloseMessage } from "jeopi-utils";
2
2
  import {
3
3
  isRetryableStreamEnvelopeError,
4
+ isTransientStreamDropError,
4
5
  isTransientStreamParseError,
5
6
  isUsageLimit,
6
7
  status,
@@ -62,6 +63,7 @@ export function isProviderRetryableError(error: unknown, hooks: ProviderRetryabl
62
63
  TRANSIENT_TRANSPORT_PATTERN.test(msg) ||
63
64
  PROVIDER_TRANSIENT_EXTRA_PATTERN.test(msg) ||
64
65
  isTransientStreamParseError(error) ||
66
+ isTransientStreamDropError(error) ||
65
67
  isRetryableStreamEnvelopeError(error)
66
68
  ) {
67
69
  return true;
@@ -1021,7 +1021,7 @@ export const streamGoogleGeminiCli: StreamFunction<"google-gemini-cli"> = (
1021
1021
  const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;
1022
1022
  const thinkingTokens = responseData.usageMetadata.thoughtsTokenCount || 0;
1023
1023
  output.usage = {
1024
- input: promptTokens - cacheReadTokens,
1024
+ input: Math.max(0, promptTokens - cacheReadTokens),
1025
1025
  output: (responseData.usageMetadata.candidatesTokenCount || 0) + thinkingTokens,
1026
1026
  cacheRead: cacheReadTokens,
1027
1027
  cacheWrite: 0,
@@ -748,7 +748,7 @@ export async function consumeGoogleStream<T extends GoogleApiType>(args: {
748
748
  const cachedTokens = chunk.usageMetadata.cachedContentTokenCount || 0;
749
749
  const thinkingTokens = chunk.usageMetadata.thoughtsTokenCount || 0;
750
750
  output.usage = {
751
- input: (chunk.usageMetadata.promptTokenCount || 0) - cachedTokens,
751
+ input: Math.max(0, (chunk.usageMetadata.promptTokenCount || 0) - cachedTokens),
752
752
  output: (chunk.usageMetadata.candidatesTokenCount || 0) + thinkingTokens,
753
753
  cacheRead: cachedTokens,
754
754
  cacheWrite: 0,
package/src/types.ts CHANGED
@@ -424,7 +424,7 @@ export interface StreamOptions {
424
424
  * in the iterator while waiting for the first semantic stream event. Set to
425
425
  * `0` to disable both layers for this request. After the first semantic
426
426
  * event arrives, `streamIdleTimeoutMs` governs inter-event stalls. Falls
427
- * back to `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` and then to a 100s default.
427
+ * back to `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` and then to a 900s default.
428
428
  * OpenAI-family transports additionally honor
429
429
  * `PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS` as the most-specific override and
430
430
  * floor the first-event budget at the resolved idle (per-call
@@ -443,7 +443,7 @@ export interface StreamOptions {
443
443
  * mid-stream stalls (broker dies, half-open socket, model produces no real
444
444
  * progress for too long). Set to `0` to disable. Falls back to
445
445
  * `PI_STREAM_IDLE_TIMEOUT_MS` (alias: `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS`)
446
- * and then to a 120s default.
446
+ * and then to a 900s default.
447
447
  */
448
448
  streamIdleTimeoutMs?: number;
449
449
  /**
@@ -1,8 +1,8 @@
1
1
  import { $env } from "jeopi-utils";
2
2
  import * as AIError from "../error";
3
3
 
4
- const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 120_000;
5
- const DEFAULT_STREAM_FIRST_EVENT_TIMEOUT_MS = 100_000;
4
+ const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 900_000;
5
+ const DEFAULT_STREAM_FIRST_EVENT_TIMEOUT_MS = 900_000;
6
6
  /** Re-mint persistent race promises every N iterations (see hoisted-racer comment). */
7
7
  const RACER_REMINT_INTERVAL = 1024;
8
8
 
@@ -84,6 +84,23 @@ const LEX_STALL_NOVELTY_FLOOR = 0.2;
84
84
  * the real reasoning-summarizer loop sustains far longer runs (10+). */
85
85
  const LEX_STALL_MIN_RUN = 8;
86
86
 
87
+ const JSON_STRING_TAIL = /^[^"\n]*"(?=\s*[,}\]:])/;
88
+ const JSON_STRING_LEAD = /^\s*"(?:\\.|[^"\\\n])*"?(?=\s*[,}\]:]|$)/;
89
+ const JSON_STRING = /(?<=[{[,:]\s*)"(?:\\.|[^"\\\n])*"?/g;
90
+ const JSON_SCALAR = /""|-?\d[\d.eE+-]*|true|false|null/;
91
+ const JSON_SCALAR_ARRAY = new RegExp(
92
+ `\\[\\s*(?:(?:${JSON_SCALAR.source})(?:\\s*,\\s*(?:${JSON_SCALAR.source}))*)?\\s*\\]`,
93
+ );
94
+ const JSON_FIELD = new RegExp(
95
+ `(?:^|[{,])\\s*""\\s*:\\s*(?:${JSON_SCALAR.source}|${JSON_SCALAR_ARRAY.source})|^\\s*""(?=\\s*[,}\\]])`,
96
+ "gm",
97
+ );
98
+ const JSON_MIN_FIELDS = 2;
99
+ const JSON_MIN_FIELD_SHARE = 0.5;
100
+ const TABLE_ROW_MIN_PIPES = 2;
101
+ const TABLE_MIN_LINES = 2;
102
+ const TABLE_ROW_MIN_SHARE = 0.6;
103
+
87
104
  /** A concrete reference the model is actually reasoning about: a code span, a
88
105
  * file extension / dotted member, a multi-segment path, or a snake/camel/Pascal
89
106
  * identifier. A segment that introduces a NEW one resets the lexical-stall run —
@@ -235,6 +252,9 @@ export class ThinkingLoopDetector {
235
252
  if (this.#consecutiveExact >= CONSECUTIVE_EXACT_MIN) {
236
253
  return `repeated identical segment ${this.#consecutiveExact}× consecutively`;
237
254
  }
255
+ // Structured answer content (JSON records / pipe-led markdown tables) is not
256
+ // reasoning; its rows differ only in numeric data normalization drops.
257
+ if (isStructuredSegment(segment)) return null;
238
258
  // (a) Near-duplicate trigram cluster: the same paragraph reused with
239
259
  // cosmetic wording drift (high word-trigram overlap).
240
260
  const fingerprint = trigramShingles(normalized);
@@ -548,6 +568,28 @@ function detectVerbatimRepetition(text: string): [unit: string, count: number] |
548
568
  return null;
549
569
  }
550
570
 
571
+ /** Structured answer content: a segment whose text is mostly JSON key/value fields
572
+ * (a record, or a fragment of one cut mid-line), or whose non-blank lines are mostly
573
+ * markdown table rows. A table row leads with a pipe: prose that merely contains two
574
+ * pipes (a union type such as `A | B`, a shell pipeline such as `cat f | grep x`) is
575
+ * reasoning and must still trip. Bullet and numbered lists are not structured here. */
576
+ function isStructuredSegment(segment: string): boolean {
577
+ const masked = segment.replace(JSON_STRING_TAIL, '""').replace(JSON_STRING_LEAD, '""').replace(JSON_STRING, '""');
578
+ let fields = 0;
579
+ let fieldChars = 0;
580
+ for (const match of masked.matchAll(JSON_FIELD)) {
581
+ fields++;
582
+ fieldChars += match[0].length;
583
+ }
584
+ if (fields >= JSON_MIN_FIELDS && fieldChars >= masked.trim().length * JSON_MIN_FIELD_SHARE) return true;
585
+ const lines = segment.split("\n").filter(line => line.trim() !== "");
586
+ if (lines.length < TABLE_MIN_LINES) return false;
587
+ const tableRows = lines.filter(
588
+ line => /^\s*\|/.test(line) && (line.match(/\|/g)?.length ?? 0) >= TABLE_ROW_MIN_PIPES,
589
+ ).length;
590
+ return tableRows >= lines.length * TABLE_ROW_MIN_SHARE;
591
+ }
592
+
551
593
  /** Lowercase and tokenize prose plus code/path payloads, dropping pure numbers. */
552
594
  function normalizeSegment(segment: string): string {
553
595
  return segment
@@ -9,14 +9,20 @@ const ARGUMENT_SUMMARY_LIMIT = 400;
9
9
  export interface ToolCallLoopGuardOptions {
10
10
  readonly threshold: number;
11
11
  readonly exemptTools: readonly string[];
12
+ /** Lets transport calls inherit an exemption from their dispatched tool without exempting the transport itself. */
13
+ readonly exemptionAlias?: (call: ToolCall) => string | undefined;
12
14
  /** Window size for alternating-pattern (A,B,A,B,…) cycle detection; defaults to 6. */
13
15
  readonly cycleWindowSize?: number;
16
+ /** Redirects allowed before escalating to stalled_tool_call (`0` disables redirect-count escalation; default `2`). */
17
+ readonly maxRedirectsBeforeStop?: number;
14
18
  }
15
19
 
16
20
  /** A completed assistant turn plus the tool results it produced. */
17
21
  export interface ToolCallLoopTurn {
18
22
  readonly message: AssistantMessage;
19
23
  readonly toolResults: readonly ToolResultMessage[];
24
+ /** The turn also delivered context outside its tool results (extension `additionalContext`). */
25
+ readonly injectedContext?: boolean;
20
26
  }
21
27
 
22
28
  /** Details needed to steer the model away from a repeated tool call. */
@@ -39,7 +45,11 @@ export interface CyclicalToolCallDetection {
39
45
  export type ToolCallLoopDetection =
40
46
  | RepeatedToolCallDetection
41
47
  | CyclicalToolCallDetection
42
- | { readonly kind: "stalled_tool_call"; readonly toolName: string };
48
+ | {
49
+ readonly kind: "stalled_tool_call";
50
+ readonly toolName: string;
51
+ readonly reason?: "unchanged_output" | "error_streak" | "redirect_escalation" | "cycle_escalation";
52
+ };
43
53
 
44
54
  function canonicalizeToolCallValue(value: unknown): unknown {
45
55
  if (Array.isArray(value)) {
@@ -82,7 +92,7 @@ function summarizeToolResult(toolResults: readonly ToolResultMessage[], toolCall
82
92
  const EVAL_MUTATION_RE =
83
93
  /\b(?:write_text|write_bytes|os\.remove|os\.unlink|os\.rename|os\.replace|shutil\.\w+|os\.mkdir|os\.makedirs|Bun\.write|fs\.write\w*|fs\.rm\w*|fs\.unlink\w*|git\s+(?:commit|checkout|reset|apply|merge|rebase)|sed\s+-i|perl\s+-pi)\b|\.write\s*\(|open\s*\([^)]*,\s*["'][wa+]/;
84
94
  const EVAL_CMD_TOKEN_RE =
85
- /\b(?:git\s+(?:status|diff|log|show|branch|rev-parse)|bun\s+(?:run\s+)?(?:typecheck|test|check|lint)|pytest|tsc|cargo\s+(?:test|check|clippy)|jev(?:\s+status)?|node\s+.*?jev-harness\.mjs\s+.*status)\b/g;
95
+ /\b(?:git\s+(?:status|diff|log|show|branch|rev-parse)|bun\s+(?:run\s+)?(?:typecheck|test|check|lint)|pytest|tsc|cargo\s+(?:test|check|clippy)|jev\s+status|node\s+.*?jev-harness\.mjs\s+.*status)\b/g;
86
96
  const EVAL_PATH_LITERAL_RE =
87
97
  /["']((?:\.\/|\.\.\/|\/|~\/|src\/|packages\/|test\/|tests\/|crates\/|python\/)[^"'\n]{1,120})["']/g;
88
98
  const EVAL_API_TOKEN_RE = /\b(?:os\.walk|glob\.glob|os\.listdir|subprocess\.(?:run|check_output|Popen)|read_text)\b/g;
@@ -168,22 +178,52 @@ function buildEvalLookupKey(args: Record<string, unknown>, canonicalArgs: string
168
178
  export class ToolCallLoopGuard {
169
179
  #threshold: number;
170
180
  #exemptTools: ReadonlySet<string>;
181
+ #exemptionAlias: ((call: ToolCall) => string | undefined) | undefined;
171
182
  #callStreaks = new Map<string, number>();
172
183
  #unchanged: { fingerprint: bigint; count: number } | undefined;
173
184
  #cycleWindowSize: number;
174
185
  #recentCalls: Array<{ hash: string; toolNames: string[] }> = [];
175
186
  #lastCycleSignature: string | undefined;
187
+ #maxRedirectsBeforeStop: number;
188
+ #redirectsIssued = 0;
189
+ #cycleRepeatTurns = 0;
176
190
 
177
191
  constructor(options: ToolCallLoopGuardOptions) {
178
192
  this.#threshold = Math.max(1, Math.trunc(options.threshold));
179
193
  this.#exemptTools = new Set(options.exemptTools);
194
+ this.#exemptionAlias = options.exemptionAlias;
180
195
  this.#cycleWindowSize = Math.max(3, Math.trunc(options.cycleWindowSize ?? 6));
196
+ this.#maxRedirectsBeforeStop = Math.max(0, Math.trunc(options.maxRedirectsBeforeStop ?? 2));
197
+ }
198
+ reset(): void {
199
+ this.#reset();
200
+ }
201
+
202
+ #reset(): void {
203
+ this.#unchanged = undefined;
204
+ this.#callStreaks.clear();
205
+ this.#recentCalls = [];
206
+ this.#lastCycleSignature = undefined;
207
+ this.#redirectsIssued = 0;
208
+ this.#cycleRepeatTurns = 0;
209
+ }
210
+
211
+ #collectRecentToolNames(): string[] {
212
+ const toolNames: string[] = [];
213
+ for (const call of this.#recentCalls) {
214
+ for (const name of call.toolNames) {
215
+ if (!toolNames.includes(name)) toolNames.push(name);
216
+ }
217
+ }
218
+ return toolNames;
181
219
  }
182
220
 
183
221
  #isExemptToolCall(toolCall: ToolCall): boolean {
184
- if (!this.#exemptTools.has(toolCall.name)) return false;
222
+ const alias = this.#exemptionAlias?.(toolCall);
223
+ const effectiveName = alias !== undefined && this.#exemptTools.has(alias) ? alias : toolCall.name;
224
+ if (!this.#exemptTools.has(effectiveName)) return false;
185
225
  if (
186
- (toolCall.name === "subagent" || toolCall.name === "job") &&
226
+ (effectiveName === "subagent" || effectiveName === "job") &&
187
227
  toolCall.arguments &&
188
228
  typeof toolCall.arguments === "object" &&
189
229
  (toolCall.arguments as Record<string, unknown>).action === "list"
@@ -193,13 +233,6 @@ export class ToolCallLoopGuard {
193
233
  return true;
194
234
  }
195
235
 
196
- #reset(): void {
197
- this.#unchanged = undefined;
198
- this.#callStreaks.clear();
199
- this.#recentCalls = [];
200
- this.#lastCycleSignature = undefined;
201
- }
202
-
203
236
  #computeLookupKey(toolCall: ToolCall, canonicalArgs: string, toolResults: readonly ToolResultMessage[]): string {
204
237
  const args =
205
238
  toolCall.arguments && typeof toolCall.arguments === "object" && !Array.isArray(toolCall.arguments)
@@ -245,7 +278,14 @@ export class ToolCallLoopGuard {
245
278
 
246
279
  const trackedCalls = allToolCalls.filter(call => !this.#isExemptToolCall(call));
247
280
  if (trackedCalls.length === 0) {
248
- this.#unchanged = undefined;
281
+ const idle =
282
+ !turn.injectedContext &&
283
+ allToolCalls.every(tc => turn.toolResults.find(r => r.toolCallId === tc.id)?.useless === true);
284
+ if (!idle) {
285
+ this.#reset();
286
+ } else {
287
+ this.#unchanged = undefined;
288
+ }
249
289
  return null;
250
290
  }
251
291
 
@@ -278,39 +318,72 @@ export class ToolCallLoopGuard {
278
318
  this.#callStreaks = nextStreaks;
279
319
 
280
320
  // The redirect uses a broad semantic match. Pausing needs stronger evidence:
281
- // one exact call and the same full text result, after a redirect was sent.
282
- const entry = turnEntries[0];
283
- const result = turn.toolResults[0];
284
- if (
285
- allToolCalls.length === 1 &&
286
- entry &&
287
- (nextStreaks.get(entry.lookupKey) ?? 0) > this.#threshold &&
288
- turn.toolResults.length === 1 &&
289
- result?.toolCallId === entry.toolCall.id &&
290
- result.content.length &&
291
- result.content.every(part => part.type === "text")
292
- ) {
293
- const normalizedContent = result.isError
294
- ? result.content.map(part =>
295
- part.type === "text" ? { type: part.type, text: normalizeVolatileErrorText(part.text) } : part,
296
- )
297
- : result.content;
298
- const fingerprint = Bun.hash(
299
- JSON.stringify([entry.toolCall.name, entry.canonicalArgs, result.isError, normalizedContent]),
300
- );
321
+ // all calls in the batch produce the same text results, after a redirect was sent.
322
+ const hasStreakPastThreshold = turnEntries.some(
323
+ entry => (nextStreaks.get(entry.lookupKey) ?? 0) > this.#threshold,
324
+ );
325
+
326
+ const callResultPairs: Array<{ call: ToolCall; result: ToolResultMessage }> = [];
327
+ let allCallsHaveMatchingTextResult = turnEntries.length > 0 && hasStreakPastThreshold;
328
+
329
+ if (allCallsHaveMatchingTextResult) {
330
+ for (const call of allToolCalls) {
331
+ const result = turn.toolResults.find(candidate => candidate.toolCallId === call.id);
332
+ if (!result || result.content.length === 0 || !result.content.every(part => part.type === "text")) {
333
+ allCallsHaveMatchingTextResult = false;
334
+ break;
335
+ }
336
+ callResultPairs.push({ call, result });
337
+ }
338
+ }
339
+
340
+ if (allCallsHaveMatchingTextResult) {
341
+ const serializedTuples: string[] = [];
342
+ for (const { call, result } of callResultPairs) {
343
+ const canonicalArgs = JSON.stringify(canonicalizeToolCallValue(call.arguments));
344
+ const normalizedContent = result.isError
345
+ ? result.content.map(part =>
346
+ part.type === "text" ? { type: part.type, text: normalizeVolatileErrorText(part.text) } : part,
347
+ )
348
+ : result.content;
349
+ serializedTuples.push(JSON.stringify([call.name, canonicalArgs, result.isError, normalizedContent]));
350
+ }
351
+ serializedTuples.sort();
352
+ const fingerprint = Bun.hash(JSON.stringify(serializedTuples));
301
353
  const count = this.#unchanged?.fingerprint === fingerprint ? this.#unchanged.count + 1 : 1;
302
354
  this.#unchanged = { fingerprint, count };
303
- const streak = nextStreaks.get(entry.lookupKey) ?? 0;
355
+
356
+ let maxStreak = 0;
357
+ for (const entry of turnEntries) {
358
+ const streak = nextStreaks.get(entry.lookupKey) ?? 0;
359
+ if (streak > maxStreak) maxStreak = streak;
360
+ }
361
+ const anyError = callResultPairs.some(pair => pair.result.isError);
304
362
  const pauseAfter = Math.max(2, this.#threshold);
305
- if (count >= pauseAfter || (result.isError && streak >= this.#threshold + pauseAfter)) {
363
+
364
+ if (count >= pauseAfter || (anyError && maxStreak >= this.#threshold + pauseAfter)) {
306
365
  this.#reset();
307
- return { kind: "stalled_tool_call", toolName: entry.toolCall.name };
366
+ const distinctNames: string[] = [];
367
+ for (const entry of turnEntries) {
368
+ if (!distinctNames.includes(entry.toolCall.name)) {
369
+ distinctNames.push(entry.toolCall.name);
370
+ }
371
+ }
372
+ const batchToolLabel = allToolCalls.length === 1 ? turnEntries[0]!.toolCall.name : distinctNames.join(", ");
373
+ const reason = anyError && count < pauseAfter ? "error_streak" : "unchanged_output";
374
+ return { kind: "stalled_tool_call", toolName: batchToolLabel, reason };
308
375
  }
309
376
  } else {
310
377
  this.#unchanged = undefined;
311
378
  }
312
379
 
313
380
  if (hitEntry) {
381
+ this.#redirectsIssued++;
382
+ if (this.#maxRedirectsBeforeStop > 0 && this.#redirectsIssued > this.#maxRedirectsBeforeStop) {
383
+ const toolName = hitEntry.toolCall.name;
384
+ this.#reset();
385
+ return { kind: "stalled_tool_call", toolName, reason: "redirect_escalation" };
386
+ }
314
387
  return {
315
388
  kind: "repeated_tool_call",
316
389
  toolName: hitEntry.toolCall.name,
@@ -320,10 +393,11 @@ export class ToolCallLoopGuard {
320
393
  };
321
394
  }
322
395
 
323
- // Alternating A,B,A,B,… pattern: exact-repeat detection above never fires
324
- // (the hash changes every turn), but the model is still spinning between
325
- // two distinct calls/turn-signatures without making progress.
326
- const turnHash = turnEntries.map(entry => entry.lookupKey).join("\u001f");
396
+ // Alternating 2-step (A,B,A,B,…) or 3-step (A,B,C,A,B,C,…) pattern.
397
+ const turnHash = turnEntries
398
+ .map(entry => entry.lookupKey)
399
+ .sort()
400
+ .join("\u001f");
327
401
  const turnToolNames: string[] = [];
328
402
  for (const entry of turnEntries) {
329
403
  if (!turnToolNames.includes(entry.toolCall.name)) {
@@ -336,20 +410,58 @@ export class ToolCallLoopGuard {
336
410
  if (this.#recentCalls.length < this.#cycleWindowSize) return null;
337
411
 
338
412
  const distinctHashes = new Set(this.#recentCalls.map(call => call.hash));
339
- if (distinctHashes.size !== 2) {
413
+ let cyclePeriod: 2 | 3 | undefined;
414
+ if (distinctHashes.size === 2) {
415
+ cyclePeriod = 2;
416
+ } else if (
417
+ distinctHashes.size === 3 &&
418
+ this.#recentCalls.length >= 6 &&
419
+ this.#recentCalls.every((call, i) => call.hash === this.#recentCalls[i % 3]!.hash)
420
+ ) {
421
+ cyclePeriod = 3;
422
+ }
423
+
424
+ if (!cyclePeriod) {
340
425
  this.#lastCycleSignature = undefined;
426
+ this.#cycleRepeatTurns = 0;
341
427
  return null;
342
428
  }
429
+
343
430
  const signature = [...distinctHashes].sort().join("|");
344
- if (signature === this.#lastCycleSignature) return null;
431
+ if (signature === this.#lastCycleSignature) {
432
+ this.#cycleRepeatTurns++;
433
+ if (this.#cycleRepeatTurns === 1) {
434
+ return null;
435
+ }
436
+ if (this.#cycleRepeatTurns % cyclePeriod === 0) {
437
+ const repeatedCycles = Math.floor(this.#cycleRepeatTurns / cyclePeriod);
438
+ if (this.#maxRedirectsBeforeStop > 0 && repeatedCycles > this.#maxRedirectsBeforeStop) {
439
+ const toolNames = this.#collectRecentToolNames();
440
+ this.#reset();
441
+ return {
442
+ kind: "stalled_tool_call",
443
+ toolName: toolNames.join(", "),
444
+ reason: "cycle_escalation",
445
+ };
446
+ }
447
+ }
448
+ return null;
449
+ }
450
+
345
451
  this.#lastCycleSignature = signature;
452
+ this.#cycleRepeatTurns = 0;
453
+ this.#redirectsIssued++;
346
454
 
347
- const toolNames: string[] = [];
348
- for (const call of this.#recentCalls) {
349
- for (const name of call.toolNames) {
350
- if (!toolNames.includes(name)) toolNames.push(name);
351
- }
455
+ const toolNames = this.#collectRecentToolNames();
456
+ if (this.#maxRedirectsBeforeStop > 0 && this.#redirectsIssued > this.#maxRedirectsBeforeStop) {
457
+ this.#reset();
458
+ return {
459
+ kind: "stalled_tool_call",
460
+ toolName: toolNames.join(", "),
461
+ reason: "redirect_escalation",
462
+ };
352
463
  }
464
+
353
465
  return { kind: "cyclical_tool_calls", toolNames, windowSize: this.#cycleWindowSize };
354
466
  }
355
467
  }