jeopi-ai 16.7.7 → 16.7.10

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,19 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [16.7.8] - 2026-11-23
6
+
7
+ ### Added
8
+
9
+ - 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()`.
10
+ - Exported `isTransientStreamDropError`, `is402BillingCapBody`, and `isBillingCapUsageLimit` from the error classifier.
11
+
12
+ ### Fixed
13
+
14
+ - 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.
15
+ - Raised default `streamFirstEventTimeoutMs` and `streamIdleTimeoutMs` stream watchdogs to 15 minutes (`900_000` ms) to avoid aborting long reasoning streams prematurely.
16
+ - 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.
17
+
5
18
  ## [16.7.6] - 2026-11-21
6
19
 
7
20
  ### 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
  /**
@@ -5,6 +5,8 @@ export interface ToolCallLoopGuardOptions {
5
5
  readonly exemptTools: readonly string[];
6
6
  /** Window size for alternating-pattern (A,B,A,B,…) cycle detection; defaults to 6. */
7
7
  readonly cycleWindowSize?: number;
8
+ /** Redirects allowed before escalating to stalled_tool_call (`0` disables redirect-count escalation; default `2`). */
9
+ readonly maxRedirectsBeforeStop?: number;
8
10
  }
9
11
  /** A completed assistant turn plus the tool results it produced. */
10
12
  export interface ToolCallLoopTurn {
@@ -29,11 +31,13 @@ export interface CyclicalToolCallDetection {
29
31
  export type ToolCallLoopDetection = RepeatedToolCallDetection | CyclicalToolCallDetection | {
30
32
  readonly kind: "stalled_tool_call";
31
33
  readonly toolName: string;
34
+ readonly reason?: "unchanged_output" | "error_streak" | "redirect_escalation" | "cycle_escalation";
32
35
  };
33
36
  /** Detects consecutive identical or semantically repeated assistant tool calls across model turns. */
34
37
  export declare class ToolCallLoopGuard {
35
38
  #private;
36
39
  constructor(options: ToolCallLoopGuardOptions);
40
+ reset(): void;
37
41
  /** Records one completed turn and returns the threshold/cycle hit, if any. */
38
42
  recordTurn(turn: ToolCallLoopTurn): ToolCallLoopDetection | null;
39
43
  }
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.10",
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.10",
42
+ "jeopi-utils": "16.7.10",
43
+ "jeopi-wire": "16.7.10",
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;
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
@@ -11,6 +11,8 @@ export interface ToolCallLoopGuardOptions {
11
11
  readonly exemptTools: readonly string[];
12
12
  /** Window size for alternating-pattern (A,B,A,B,…) cycle detection; defaults to 6. */
13
13
  readonly cycleWindowSize?: number;
14
+ /** Redirects allowed before escalating to stalled_tool_call (`0` disables redirect-count escalation; default `2`). */
15
+ readonly maxRedirectsBeforeStop?: number;
14
16
  }
15
17
 
16
18
  /** A completed assistant turn plus the tool results it produced. */
@@ -39,7 +41,11 @@ export interface CyclicalToolCallDetection {
39
41
  export type ToolCallLoopDetection =
40
42
  | RepeatedToolCallDetection
41
43
  | CyclicalToolCallDetection
42
- | { readonly kind: "stalled_tool_call"; readonly toolName: string };
44
+ | {
45
+ readonly kind: "stalled_tool_call";
46
+ readonly toolName: string;
47
+ readonly reason?: "unchanged_output" | "error_streak" | "redirect_escalation" | "cycle_escalation";
48
+ };
43
49
 
44
50
  function canonicalizeToolCallValue(value: unknown): unknown {
45
51
  if (Array.isArray(value)) {
@@ -173,11 +179,37 @@ export class ToolCallLoopGuard {
173
179
  #cycleWindowSize: number;
174
180
  #recentCalls: Array<{ hash: string; toolNames: string[] }> = [];
175
181
  #lastCycleSignature: string | undefined;
182
+ #maxRedirectsBeforeStop: number;
183
+ #redirectsIssued = 0;
184
+ #cycleRepeatTurns = 0;
176
185
 
177
186
  constructor(options: ToolCallLoopGuardOptions) {
178
187
  this.#threshold = Math.max(1, Math.trunc(options.threshold));
179
188
  this.#exemptTools = new Set(options.exemptTools);
180
189
  this.#cycleWindowSize = Math.max(3, Math.trunc(options.cycleWindowSize ?? 6));
190
+ this.#maxRedirectsBeforeStop = Math.max(0, Math.trunc(options.maxRedirectsBeforeStop ?? 2));
191
+ }
192
+ reset(): void {
193
+ this.#reset();
194
+ }
195
+
196
+ #reset(): void {
197
+ this.#unchanged = undefined;
198
+ this.#callStreaks.clear();
199
+ this.#recentCalls = [];
200
+ this.#lastCycleSignature = undefined;
201
+ this.#redirectsIssued = 0;
202
+ this.#cycleRepeatTurns = 0;
203
+ }
204
+
205
+ #collectRecentToolNames(): string[] {
206
+ const toolNames: string[] = [];
207
+ for (const call of this.#recentCalls) {
208
+ for (const name of call.toolNames) {
209
+ if (!toolNames.includes(name)) toolNames.push(name);
210
+ }
211
+ }
212
+ return toolNames;
181
213
  }
182
214
 
183
215
  #isExemptToolCall(toolCall: ToolCall): boolean {
@@ -193,13 +225,6 @@ export class ToolCallLoopGuard {
193
225
  return true;
194
226
  }
195
227
 
196
- #reset(): void {
197
- this.#unchanged = undefined;
198
- this.#callStreaks.clear();
199
- this.#recentCalls = [];
200
- this.#lastCycleSignature = undefined;
201
- }
202
-
203
228
  #computeLookupKey(toolCall: ToolCall, canonicalArgs: string, toolResults: readonly ToolResultMessage[]): string {
204
229
  const args =
205
230
  toolCall.arguments && typeof toolCall.arguments === "object" && !Array.isArray(toolCall.arguments)
@@ -278,39 +303,72 @@ export class ToolCallLoopGuard {
278
303
  this.#callStreaks = nextStreaks;
279
304
 
280
305
  // 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
- );
306
+ // all calls in the batch produce the same text results, after a redirect was sent.
307
+ const hasStreakPastThreshold = turnEntries.some(
308
+ entry => (nextStreaks.get(entry.lookupKey) ?? 0) > this.#threshold,
309
+ );
310
+
311
+ const callResultPairs: Array<{ call: ToolCall; result: ToolResultMessage }> = [];
312
+ let allCallsHaveMatchingTextResult = turnEntries.length > 0 && hasStreakPastThreshold;
313
+
314
+ if (allCallsHaveMatchingTextResult) {
315
+ for (const call of allToolCalls) {
316
+ const result = turn.toolResults.find(candidate => candidate.toolCallId === call.id);
317
+ if (!result || result.content.length === 0 || !result.content.every(part => part.type === "text")) {
318
+ allCallsHaveMatchingTextResult = false;
319
+ break;
320
+ }
321
+ callResultPairs.push({ call, result });
322
+ }
323
+ }
324
+
325
+ if (allCallsHaveMatchingTextResult) {
326
+ const serializedTuples: string[] = [];
327
+ for (const { call, result } of callResultPairs) {
328
+ const canonicalArgs = JSON.stringify(canonicalizeToolCallValue(call.arguments));
329
+ const normalizedContent = result.isError
330
+ ? result.content.map(part =>
331
+ part.type === "text" ? { type: part.type, text: normalizeVolatileErrorText(part.text) } : part,
332
+ )
333
+ : result.content;
334
+ serializedTuples.push(JSON.stringify([call.name, canonicalArgs, result.isError, normalizedContent]));
335
+ }
336
+ serializedTuples.sort();
337
+ const fingerprint = Bun.hash(JSON.stringify(serializedTuples));
301
338
  const count = this.#unchanged?.fingerprint === fingerprint ? this.#unchanged.count + 1 : 1;
302
339
  this.#unchanged = { fingerprint, count };
303
- const streak = nextStreaks.get(entry.lookupKey) ?? 0;
340
+
341
+ let maxStreak = 0;
342
+ for (const entry of turnEntries) {
343
+ const streak = nextStreaks.get(entry.lookupKey) ?? 0;
344
+ if (streak > maxStreak) maxStreak = streak;
345
+ }
346
+ const anyError = callResultPairs.some(pair => pair.result.isError);
304
347
  const pauseAfter = Math.max(2, this.#threshold);
305
- if (count >= pauseAfter || (result.isError && streak >= this.#threshold + pauseAfter)) {
348
+
349
+ if (count >= pauseAfter || (anyError && maxStreak >= this.#threshold + pauseAfter)) {
306
350
  this.#reset();
307
- return { kind: "stalled_tool_call", toolName: entry.toolCall.name };
351
+ const distinctNames: string[] = [];
352
+ for (const entry of turnEntries) {
353
+ if (!distinctNames.includes(entry.toolCall.name)) {
354
+ distinctNames.push(entry.toolCall.name);
355
+ }
356
+ }
357
+ const batchToolLabel = allToolCalls.length === 1 ? turnEntries[0]!.toolCall.name : distinctNames.join(", ");
358
+ const reason = anyError && count < pauseAfter ? "error_streak" : "unchanged_output";
359
+ return { kind: "stalled_tool_call", toolName: batchToolLabel, reason };
308
360
  }
309
361
  } else {
310
362
  this.#unchanged = undefined;
311
363
  }
312
364
 
313
365
  if (hitEntry) {
366
+ this.#redirectsIssued++;
367
+ if (this.#maxRedirectsBeforeStop > 0 && this.#redirectsIssued > this.#maxRedirectsBeforeStop) {
368
+ const toolName = hitEntry.toolCall.name;
369
+ this.#reset();
370
+ return { kind: "stalled_tool_call", toolName, reason: "redirect_escalation" };
371
+ }
314
372
  return {
315
373
  kind: "repeated_tool_call",
316
374
  toolName: hitEntry.toolCall.name,
@@ -320,10 +378,11 @@ export class ToolCallLoopGuard {
320
378
  };
321
379
  }
322
380
 
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");
381
+ // Alternating 2-step (A,B,A,B,…) or 3-step (A,B,C,A,B,C,…) pattern.
382
+ const turnHash = turnEntries
383
+ .map(entry => entry.lookupKey)
384
+ .sort()
385
+ .join("\u001f");
327
386
  const turnToolNames: string[] = [];
328
387
  for (const entry of turnEntries) {
329
388
  if (!turnToolNames.includes(entry.toolCall.name)) {
@@ -336,20 +395,58 @@ export class ToolCallLoopGuard {
336
395
  if (this.#recentCalls.length < this.#cycleWindowSize) return null;
337
396
 
338
397
  const distinctHashes = new Set(this.#recentCalls.map(call => call.hash));
339
- if (distinctHashes.size !== 2) {
398
+ let cyclePeriod: 2 | 3 | undefined;
399
+ if (distinctHashes.size === 2) {
400
+ cyclePeriod = 2;
401
+ } else if (
402
+ distinctHashes.size === 3 &&
403
+ this.#recentCalls.length >= 6 &&
404
+ this.#recentCalls.every((call, i) => call.hash === this.#recentCalls[i % 3]!.hash)
405
+ ) {
406
+ cyclePeriod = 3;
407
+ }
408
+
409
+ if (!cyclePeriod) {
340
410
  this.#lastCycleSignature = undefined;
411
+ this.#cycleRepeatTurns = 0;
341
412
  return null;
342
413
  }
414
+
343
415
  const signature = [...distinctHashes].sort().join("|");
344
- if (signature === this.#lastCycleSignature) return null;
416
+ if (signature === this.#lastCycleSignature) {
417
+ this.#cycleRepeatTurns++;
418
+ if (this.#cycleRepeatTurns === 1) {
419
+ return null;
420
+ }
421
+ if (this.#cycleRepeatTurns % cyclePeriod === 0) {
422
+ const repeatedCycles = Math.floor(this.#cycleRepeatTurns / cyclePeriod);
423
+ if (this.#maxRedirectsBeforeStop > 0 && repeatedCycles > this.#maxRedirectsBeforeStop) {
424
+ const toolNames = this.#collectRecentToolNames();
425
+ this.#reset();
426
+ return {
427
+ kind: "stalled_tool_call",
428
+ toolName: toolNames.join(", "),
429
+ reason: "cycle_escalation",
430
+ };
431
+ }
432
+ }
433
+ return null;
434
+ }
435
+
345
436
  this.#lastCycleSignature = signature;
437
+ this.#cycleRepeatTurns = 0;
438
+ this.#redirectsIssued++;
346
439
 
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
- }
440
+ const toolNames = this.#collectRecentToolNames();
441
+ if (this.#maxRedirectsBeforeStop > 0 && this.#redirectsIssued > this.#maxRedirectsBeforeStop) {
442
+ this.#reset();
443
+ return {
444
+ kind: "stalled_tool_call",
445
+ toolName: toolNames.join(", "),
446
+ reason: "redirect_escalation",
447
+ };
352
448
  }
449
+
353
450
  return { kind: "cyclical_tool_calls", toolNames, windowSize: this.#cycleWindowSize };
354
451
  }
355
452
  }