jeopi-ai 16.7.10 → 16.7.12
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 +18 -0
- package/dist/types/error/flags.d.ts +2 -0
- package/dist/types/error/rate-limit.d.ts +20 -31
- package/dist/types/utils/dsml-leak.d.ts +35 -0
- package/dist/types/utils/empty-completion-retry.d.ts +30 -8
- package/dist/types/utils/retry-after.d.ts +30 -0
- package/dist/types/utils/retry-wait.d.ts +9 -0
- package/dist/types/utils/thinking-loop.d.ts +35 -46
- package/dist/types/utils/tool-call-loop-guard.d.ts +5 -1
- package/package.json +4 -4
- package/src/error/flags.ts +51 -14
- package/src/error/rate-limit.ts +323 -82
- package/src/error/retryable.ts +9 -0
- package/src/providers/google-gemini-cli.ts +1 -1
- package/src/providers/google-shared.ts +1 -1
- package/src/utils/dsml-leak.ts +299 -0
- package/src/utils/empty-completion-retry.ts +127 -50
- package/src/utils/retry-after.ts +110 -47
- package/src/utils/retry-wait.ts +19 -0
- package/src/utils/thinking-loop.ts +241 -215
- package/src/utils/tool-call-loop-guard.ts +19 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [16.7.12] - 2026-11-24
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Added `dsml-leak.ts` (`DSML_MARKUP_RE`, `hasDsmlMarkup`) to detect leaked DeepSeek DSML tool-call markup in assistant text and `retry-wait.ts` (`computeRetryWait`, `getResetDelayMs`, `RETRY_WAIT_DEFAULTS`) for unified retry delay calculation.
|
|
10
|
+
- Expanded rate-limit and error classifiers in `error/rate-limit.ts`, `error/flags.ts`, and `error/retryable.ts` to cover structured Google RPC rate-limit reasons (`INSUFFICIENT_G1_CREDITS_BALANCE`, `CONCURRENT_LIMIT`), OpenRouter/Anthropic/Cursor/LiteLLM/CN credit and billing caps, Aliyun MM transient 400 flaps, and `stream ended without a finish reason`.
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Hardened `withEmptyCompletionRetry`, `ThinkingLoopDetector` / `withGeminiThinkingLoopGuard`, and `retry-after.ts` hint extraction while preserving `ProviderRetryableHooks` and existing quota/usage-limit detection.
|
|
15
|
+
|
|
16
|
+
## [16.7.11] - 2026-11-23
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- Clamped `usage.input` to `>= 0` in `google-gemini-cli` and `google-shared` when providers report `cachedContentTokenCount > promptTokenCount`.
|
|
21
|
+
- 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.
|
|
22
|
+
|
|
5
23
|
## [16.7.8] - 2026-11-23
|
|
6
24
|
|
|
7
25
|
### Added
|
|
@@ -31,6 +31,8 @@ export declare const TRANSIENT_TRANSPORT_PATTERN: RegExp;
|
|
|
31
31
|
* output, so callers strip {@link Flag.Transient} when this matches.
|
|
32
32
|
*/
|
|
33
33
|
export declare const LLAMA_CPP_TOOL_CALL_PARSE_PATTERN: RegExp;
|
|
34
|
+
export declare const ALIYUN_MM_GATEWAY_PATTERN: RegExp;
|
|
35
|
+
export declare const CODEX_HTTP_BODY_READ_ERROR_PATTERN: RegExp;
|
|
34
36
|
/** Whether an OAuth refresh error message means the grant is definitively dead. */
|
|
35
37
|
export declare function isOAuthExpiry(errorMessage: string): boolean;
|
|
36
38
|
export declare function create(...flags: number[]): number;
|
|
@@ -2,14 +2,19 @@
|
|
|
2
2
|
* Rate limit reason classification and backoff calculation utilities.
|
|
3
3
|
* Ported from opencode-antigravity-auth plugin for consistency.
|
|
4
4
|
*/
|
|
5
|
-
export type RateLimitReason = "QUOTA_EXHAUSTED" | "RATE_LIMIT_EXCEEDED" | "MODEL_CAPACITY_EXHAUSTED" | "SERVER_ERROR" | "UNKNOWN";
|
|
5
|
+
export type RateLimitReason = "QUOTA_EXHAUSTED" | "INSUFFICIENT_G1_CREDITS_BALANCE" | "RATE_LIMIT_EXCEEDED" | "CONCURRENT_LIMIT" | "MODEL_CAPACITY_EXHAUSTED" | "SERVER_ERROR" | "UNKNOWN";
|
|
6
|
+
/** True for DashScope/Bailian's documented OpenAI-compatible TPM/TPS throttle. */
|
|
7
|
+
export declare function isDashScopeTokenLimitText(errorMessage: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Actionable suffix for a 429 whose `header` (an `x-ratelimit-limit-*` name)
|
|
10
|
+
* reported a zero allowance. Recognized by {@link matchesUsageLimitText},
|
|
11
|
+
* {@link parseRateLimitReason}, and {@link isBillingCapUsageLimit}.
|
|
12
|
+
*/
|
|
13
|
+
export declare function formatZeroAllowanceNotice(header: string): string;
|
|
14
|
+
/** Parse an embedded JSON object from an error message. */
|
|
15
|
+
export declare function parseJsonBody(errorMessage: string): Record<string, unknown> | undefined;
|
|
6
16
|
/**
|
|
7
17
|
* Classify a rate-limit error message into a reason category.
|
|
8
|
-
* Priority order: QUOTA (Antigravity "quota will reset") > MODEL_CAPACITY > QUOTA (account) >
|
|
9
|
-
* RATE_LIMIT > QUOTA (generic) > SERVER_ERROR > UNKNOWN.
|
|
10
|
-
*
|
|
11
|
-
* "resource exhausted" maps to MODEL_CAPACITY (transient, short wait)
|
|
12
|
-
* "quota exceeded" / "quota will reset" maps to QUOTA_EXHAUSTED (long wait, switch account)
|
|
13
18
|
*/
|
|
14
19
|
export declare function parseRateLimitReason(errorMessage: string): RateLimitReason;
|
|
15
20
|
/**
|
|
@@ -17,43 +22,27 @@ export declare function parseRateLimitReason(errorMessage: string): RateLimitRea
|
|
|
17
22
|
* MODEL_CAPACITY gets jitter to prevent thundering herd.
|
|
18
23
|
*/
|
|
19
24
|
export declare function calculateRateLimitBackoffMs(reason: RateLimitReason): number;
|
|
20
|
-
/**
|
|
21
|
-
* HTTP status codes that, absent richer body classification, represent an
|
|
22
|
-
* account-local usage cap rather than a bad credential or a transient blip.
|
|
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.
|
|
26
|
-
*/
|
|
27
25
|
export declare function isUsageLimitStatus(status: number | undefined): boolean;
|
|
28
26
|
export declare function is402BillingCapBody(message: string | undefined): boolean;
|
|
29
27
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
28
|
+
* Whether a usage-limit failure is a *billing* cap rather than a window that
|
|
29
|
+
* reopens on a clock.
|
|
32
30
|
*/
|
|
33
31
|
export declare function isBillingCapUsageLimit(status: number | undefined, message: string | undefined): boolean;
|
|
34
32
|
/**
|
|
35
33
|
* Returns true for failures that should burn one credential and rotate to a
|
|
36
|
-
* sibling account.
|
|
37
|
-
*
|
|
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.
|
|
34
|
+
* sibling account.
|
|
44
35
|
*/
|
|
45
36
|
export declare function isUsageLimitOutcome(status: number | undefined, message: string | undefined): boolean;
|
|
46
37
|
/**
|
|
47
|
-
* A
|
|
48
|
-
* empty, whitespace-only, the status digits with HTTP/JSON
|
|
49
|
-
* generic punctuation.
|
|
50
|
-
* descriptions) is informative enough to defer to the classifier.
|
|
38
|
+
* A usage-limit status body is opaque when it carries no signal beyond the
|
|
39
|
+
* status itself — empty, whitespace-only, the status digits with HTTP/JSON
|
|
40
|
+
* framing, or generic punctuation.
|
|
51
41
|
*/
|
|
52
42
|
export declare function isOpaqueStatusBody(message: string): boolean;
|
|
53
43
|
/**
|
|
54
|
-
* Internal text matcher for usage/quota-limit phrasing.
|
|
55
|
-
* API — callers classify through {@link import("./flags").isUsageLimit} (the
|
|
56
|
-
* flag accessor). `flags.ts` consumes this to populate `Flag.UsageLimit`, and
|
|
57
|
-
* {@link isUsageLimitOutcome} uses it for the account-rotation decision.
|
|
44
|
+
* Internal text matcher for usage/quota-limit phrasing.
|
|
58
45
|
*/
|
|
59
46
|
export declare function matchesUsageLimitText(errorMessage: string): boolean;
|
|
47
|
+
export declare function isAccountScopedCapText(message: string): boolean;
|
|
48
|
+
export declare function isConcurrencyCapExclusion(status: number | undefined, message: string | undefined): boolean;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Removal of DeepSeek tool-call markup left in visible assistant text.
|
|
3
|
+
*
|
|
4
|
+
* DeepSeek models on OpenAI-compatible hosts sometimes emit their tool calls as
|
|
5
|
+
* text in `content`: the V4 `<|DSML|…>` envelope or the V3 chat-template
|
|
6
|
+
* tokens (`<|tool▁calls▁begin|>` …). A well-formed call is healed into a
|
|
7
|
+
* structured call by `StreamMarkupHealing`, but a degraded model can drop
|
|
8
|
+
* required tags (or the host runs no healer at all). That markup must not stay
|
|
9
|
+
* in history: replaying it teaches the model to keep writing tool calls as text
|
|
10
|
+
* (issue #10556). Callers strip it before the message is committed and tell the
|
|
11
|
+
* model its call failed.
|
|
12
|
+
*
|
|
13
|
+
* The same markup also leaks into the string arguments of calls the host did
|
|
14
|
+
* parse (`"command": "ls</|DSML| parameter>"`); it is cut off before the call
|
|
15
|
+
* runs. A native Responses replay payload (OpenRouter) holds its own copy of
|
|
16
|
+
* the turn's text, reasoning and arguments and is cleaned the same way.
|
|
17
|
+
*/
|
|
18
|
+
import type { AssistantMessage, Model } from "../types";
|
|
19
|
+
/**
|
|
20
|
+
* Whether DSML leak recovery applies to `model`: a DeepSeek-class model, or one
|
|
21
|
+
* explicitly configured with the `dsml` stream healer.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isDsmlLeakRecoveryTarget(model: Model): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Strip leaked DeepSeek tool-call markup (DSML or chat-template tokens) from
|
|
26
|
+
* `text`, leaving quoted code intact. Returns `undefined` when `text` carries
|
|
27
|
+
* no such markup.
|
|
28
|
+
*/
|
|
29
|
+
export declare function stripDsmlToolMarkup(text: string): string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Remove leaked DSML tool-call markup from an assistant message before commit,
|
|
32
|
+
* including reasoning blocks, turns with valid structured calls, the string
|
|
33
|
+
* arguments of those calls, and the native Responses replay payload.
|
|
34
|
+
*/
|
|
35
|
+
export declare function removeDsmlToolMarkupLeak(message: AssistantMessage): boolean;
|
|
@@ -3,19 +3,41 @@ import { AssistantMessageEventStream } from "./event-stream";
|
|
|
3
3
|
export declare const MAX_EMPTY_COMPLETION_RETRIES = 2;
|
|
4
4
|
export declare const EMPTY_COMPLETION_BASE_DELAY_MS = 500;
|
|
5
5
|
/**
|
|
6
|
-
* Whether a completed assistant message carries content worth delivering: a
|
|
7
|
-
* call or any non-whitespace text. An empty/whitespace-only message — or
|
|
8
|
-
* that only ever produced thinking — is the "empty response" failure.
|
|
6
|
+
* Whether a completed assistant message carries content worth delivering: a
|
|
7
|
+
* tool call or any non-whitespace text. An empty/whitespace-only message — or
|
|
8
|
+
* one that only ever produced thinking — is the "empty response" failure.
|
|
9
9
|
*/
|
|
10
10
|
export declare function hasVisibleAssistantContent(message: AssistantMessage): boolean;
|
|
11
|
-
interface EmptyCompletionRetryOptions {
|
|
11
|
+
export interface EmptyCompletionRetryOptions {
|
|
12
12
|
signal?: AbortSignal;
|
|
13
13
|
providerRetryWait?: (delayMs: number, signal?: AbortSignal) => Promise<void>;
|
|
14
|
+
acceptEmptyResponse?: boolean;
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
17
|
+
* Error messages whose transient HTTP status (408, 429, 5xx) the transport
|
|
18
|
+
* owned: it either spent its retry budget on it or declined to retry it
|
|
19
|
+
* (`x-should-retry: false`, a zero-limit 429). A replay would multiply or
|
|
20
|
+
* override that decision, so the provider marks them. In-band errors inside a
|
|
21
|
+
* 200 stream are not marked and keep their one replay.
|
|
22
|
+
*/
|
|
23
|
+
export declare const transportExhaustedMessages: WeakSet<AssistantMessage>;
|
|
24
|
+
/** Controls which replay-safe provider results may issue a fresh request. */
|
|
25
|
+
export interface ReplaySafeStreamRetryPolicy {
|
|
26
|
+
/** Retry benign terminal stops that contain no visible output. */
|
|
27
|
+
retryEmptyCompletion?: boolean | (() => boolean);
|
|
28
|
+
/** Retry transient provider errors before output is committed. */
|
|
29
|
+
retryProviderErrors?: boolean;
|
|
30
|
+
/** Maximum transient provider-error retries; empty completions keep their shared fixed budget. */
|
|
31
|
+
maxProviderErrorRetries?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Re-issues a fresh provider request only while the current attempt remains
|
|
35
|
+
* replay-safe. Buffered pre-output events from discarded attempts never reach
|
|
36
|
+
* consumers.
|
|
37
|
+
*/
|
|
38
|
+
export declare function withReplaySafeStreamRetry<M, O extends EmptyCompletionRetryOptions>(model: M, context: Context, options: O | undefined, attempt: (model: M, context: Context, options?: O) => AssistantMessageEventStream, policy: ReplaySafeStreamRetryPolicy): AssistantMessageEventStream;
|
|
39
|
+
/**
|
|
40
|
+
* Convenience wrapper for empty-completion retries (backwards-compatible with
|
|
41
|
+
* provider call sites that only opt into empty-completion retry).
|
|
19
42
|
*/
|
|
20
43
|
export declare function withEmptyCompletionRetry<M, O extends EmptyCompletionRetryOptions>(model: M, context: Context, options: O | undefined, attempt: (model: M, context: Context, options?: O) => AssistantMessageEventStream): AssistantMessageEventStream;
|
|
21
|
-
export {};
|
|
@@ -1,4 +1,34 @@
|
|
|
1
1
|
export type HeadersLike = Headers | Record<string, string | undefined> | undefined | null;
|
|
2
|
+
/**
|
|
3
|
+
* Append `retry-after-ms=<n>` to `message` when `retryAfterMs` is positive and
|
|
4
|
+
* the hint is not already present. Shared across providers so every transport
|
|
5
|
+
* formats retry delays identically for {@link extractRetryHint}.
|
|
6
|
+
*/
|
|
7
|
+
export declare function appendRetryAfterHint(message: string, retryAfterMs: number | undefined): string;
|
|
8
|
+
/**
|
|
9
|
+
* Extract the text of an arbitrary thrown value: `Error.message` when it is an
|
|
10
|
+
* `Error`, the string itself when it is a string, otherwise `JSON.stringify`
|
|
11
|
+
* with a `String(error)` fallback so non-JSON-serializable values never throw.
|
|
12
|
+
*/
|
|
13
|
+
export declare function errorMessageText(error: unknown): string;
|
|
2
14
|
export declare function formatErrorMessageWithRetryAfter(error: unknown, headers?: HeadersLike): string;
|
|
15
|
+
/**
|
|
16
|
+
* Parse a `retry-after-ms` header value (positive finite milliseconds).
|
|
17
|
+
* Returns `undefined` when missing, empty, non-numeric, or non-positive.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseRetryAfterMsHeader(raw: string | undefined | null): number | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Honor the explicit `x-should-retry` response header used by Anthropic and
|
|
22
|
+
* OpenAI SDKs (`"true"` / `"false"`). Returns `undefined` when absent or
|
|
23
|
+
* unrecognized so callers fall back to status/body heuristics.
|
|
24
|
+
*/
|
|
25
|
+
export declare function getShouldRetryFromHeaders(headers: HeadersLike): boolean | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Detect any `x-ratelimit-limit-*` response header whose numeric value is `0`
|
|
28
|
+
* (e.g. Mistral `x-ratelimit-limit-req-minute: 0` when the plan grants no
|
|
29
|
+
* allowance for the requested model). Returns the header name so callers can
|
|
30
|
+
* surface an actionable zero-allowance notice.
|
|
31
|
+
*/
|
|
32
|
+
export declare function getZeroRateLimitHeader(headers: HeadersLike): string | undefined;
|
|
3
33
|
export declare function getRetryAfterMsFromHeaders(headers: HeadersLike): number | undefined;
|
|
4
34
|
export declare function getHeadersFromError(error: unknown): HeadersLike;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Injected retry sleep: `StreamOptions.providerRetryWait` / `UsageFetchContext.retryWait`. */
|
|
2
|
+
export type RetryWaitHook = (delayMs: number, signal?: AbortSignal) => Promise<void>;
|
|
3
|
+
/**
|
|
4
|
+
* Waits `delayMs` between retry attempts. Honors the caller's retry-wait hook
|
|
5
|
+
* when one is set (tests and custom transports inject it to avoid real sleeps)
|
|
6
|
+
* and otherwise sleeps on `signal`, so an abort rejects instead of the retry
|
|
7
|
+
* proceeding.
|
|
8
|
+
*/
|
|
9
|
+
export declare function waitForRetry(retryWait: RetryWaitHook | undefined, delayMs: number, signal?: AbortSignal): Promise<void>;
|
|
@@ -4,25 +4,30 @@ import { AssistantMessageEventStream } from "./event-stream";
|
|
|
4
4
|
* message also carries "stream stall" so the session + transport retry
|
|
5
5
|
* classifiers treat it as a transient (retryable) stop without bespoke rules. */
|
|
6
6
|
export declare const THINKING_LOOP_ERROR_MARKER = "Thinking loop detected";
|
|
7
|
+
/**
|
|
8
|
+
* How much of the loop guard runs on a stream: `off` none, `exact` only
|
|
9
|
+
* exact suffix cycles, `semantic` exact cycles plus the near-duplicate and
|
|
10
|
+
* progress-lexicon paragraph heuristics.
|
|
11
|
+
*/
|
|
12
|
+
export type LoopGuardLevel = "off" | "exact" | "semantic";
|
|
7
13
|
/**
|
|
8
14
|
* True when `model` is a Gemini model whose native thinking stream surfaces the
|
|
9
15
|
* "thought summary" titles this module's header guard counts.
|
|
10
|
-
*
|
|
11
|
-
* OpenAI-compat transports can serve Gemini under an arbitrary provider/id, so they
|
|
12
|
-
* carry the explicit `compat.enableGeminiThinkingLoopGuard` flag; direct Gemini
|
|
13
|
-
* transports carry a clearly shaped id/provider, so a string match is sufficient.
|
|
14
16
|
*/
|
|
15
17
|
export declare function isGeminiThinkingModel(model: Model<Api>): boolean;
|
|
16
18
|
/**
|
|
17
|
-
* True when `model` should be guarded
|
|
18
|
-
*
|
|
19
|
-
* OpenAI-compat transports can serve Gemini or DeepSeek under an arbitrary provider/id.
|
|
20
|
-
* Direct Gemini/DeepSeek transports carry a clearly shaped id/provider, so a string match
|
|
21
|
-
* is sufficient.
|
|
19
|
+
* True when `model` should be guarded with full semantic thinking/response
|
|
20
|
+
* loop heuristics (Gemini & DeepSeek).
|
|
22
21
|
*/
|
|
23
22
|
export declare function isLoopGuardedModel(model: Model<Api>, options?: StreamOptions): boolean;
|
|
24
23
|
/** @deprecated Use isLoopGuardedModel instead. */
|
|
25
24
|
export declare function isGeminiThinkingLoopModel(model: Model<Api>): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Loop-guard level for a model stream. `PI_NO_THINKING_LOOP_GUARD=1` and
|
|
27
|
+
* `loopGuard.enabled: false` turn it off; Gemini/DeepSeek/Grok get `semantic`,
|
|
28
|
+
* Claude is `off`, and other models get `exact`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function loopGuardLevel(model: Model<Api>, options?: StreamOptions): LoopGuardLevel;
|
|
26
31
|
/**
|
|
27
32
|
* Stateful detector fed the streamed thinking deltas. `push` returns a
|
|
28
33
|
* human-readable reason the first time a loop shape is recognized; the caller
|
|
@@ -30,68 +35,52 @@ export declare function isGeminiThinkingLoopModel(model: Model<Api>): boolean;
|
|
|
30
35
|
*/
|
|
31
36
|
export declare class ThinkingLoopDetector {
|
|
32
37
|
#private;
|
|
38
|
+
private readonly semanticHeuristics;
|
|
39
|
+
constructor(semanticHeuristics?: boolean);
|
|
33
40
|
push(delta: string): string | null;
|
|
34
|
-
/** Process the buffered trailing paragraph
|
|
35
|
-
* terminator). Called when the thinking block ends so the final segment —
|
|
36
|
-
* which may be the one that completes a duplicate cluster — is not dropped. */
|
|
41
|
+
/** Process the buffered trailing paragraph and run one final exact-cycle check. */
|
|
37
42
|
flush(): string | null;
|
|
38
43
|
}
|
|
39
44
|
/**
|
|
40
45
|
* Consecutive Gemini thought-summary headers in one uninterrupted reasoning
|
|
41
|
-
* stream that trips the tool-call reminder.
|
|
42
|
-
*
|
|
43
|
-
* Rendering", …) without ever calling a tool, burning the whole budget on
|
|
44
|
-
* planning. This is the over-planning shape {@link ThinkingLoopDetector} misses —
|
|
45
|
-
* those titles are stripped before its similarity analysis precisely because their
|
|
46
|
-
* wording keeps changing, so a genuinely-distinct planning runaway never trips it.
|
|
47
|
-
*
|
|
48
|
-
* Set well above legitimate hard-problem depth: a capable model can emit ~10
|
|
49
|
-
* distinct, progressing hypotheses in a single reasoning block before acting (and
|
|
50
|
-
* a false trip is costly — the interrupt discards the whole reasoning turn). A
|
|
51
|
-
* real narration runaway burns dozens-to-hundreds of titles, so this still trips
|
|
52
|
-
* fast on the actual pathology.
|
|
46
|
+
* stream that trips the tool-call reminder. Set well above legitimate hard
|
|
47
|
+
* reasoning depth while still tripping fast on narration runaways.
|
|
53
48
|
*/
|
|
54
|
-
export declare const GEMINI_HEADER_RUNAWAY_THRESHOLD =
|
|
49
|
+
export declare const GEMINI_HEADER_RUNAWAY_THRESHOLD = 64;
|
|
55
50
|
/**
|
|
56
51
|
* True when a single trimmed line is a Gemini reasoning-summary title: a markdown
|
|
57
52
|
* ATX heading (`## …`) or a whole-line bold / bold-italic run (`**Title**`,
|
|
58
|
-
* `***Title***`).
|
|
59
|
-
* span the entire line. Mirrors the title shapes {@link ThinkingLoopDetector}
|
|
60
|
-
* strips before similarity analysis.
|
|
53
|
+
* `***Title***`).
|
|
61
54
|
*/
|
|
62
55
|
export declare function isReasoningSummaryHeader(line: string): boolean;
|
|
63
56
|
/**
|
|
64
57
|
* Counts consecutive Gemini reasoning-summary headers across a streamed thinking
|
|
65
|
-
* block.
|
|
66
|
-
* first reaches {@link GEMINI_HEADER_RUNAWAY_THRESHOLD} — and the caller then
|
|
67
|
-
* interrupts the stream and reminds the model to issue a tool call. Paragraph
|
|
68
|
-
* lines between titles do NOT reset the run (Gemini emits header + paragraph per
|
|
69
|
-
* thought, so the run IS the number of summaries); leaving the reasoning channel
|
|
70
|
-
* does, via {@link reset} on a new thinking block / prose / tool call.
|
|
58
|
+
* block.
|
|
71
59
|
*/
|
|
72
60
|
export declare class GeminiHeaderRunDetector {
|
|
73
61
|
#private;
|
|
74
|
-
/** Feed a thinking delta. Returns true the first time the run hits the threshold. */
|
|
75
62
|
push(delta: string): boolean;
|
|
76
|
-
/** Number of summary titles counted in the current run (for the reminder/log). */
|
|
77
63
|
get count(): number;
|
|
78
|
-
/** Re-arm for a fresh reasoning block: clears the buffer, count, and latch. */
|
|
79
64
|
reset(): void;
|
|
80
65
|
}
|
|
81
66
|
/**
|
|
82
67
|
* Wrap a provider stream with the loop guard. `controller` is the guard's own
|
|
83
|
-
* abort handle: aborting it
|
|
84
|
-
* {@link withGeminiThinkingLoopGuard}) tears down the upstream once a loop
|
|
85
|
-
* trips.
|
|
68
|
+
* abort handle: aborting it tears down the upstream once a loop trips.
|
|
86
69
|
*/
|
|
87
70
|
export declare function guardThinkingLoopStream(inner: AssistantMessageEventStream, model: Model<Api>, controller: AbortController, options?: StreamOptions): AssistantMessageEventStream;
|
|
88
71
|
/**
|
|
89
|
-
* Apply the loop guard around a provider dispatch
|
|
90
|
-
*
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
72
|
+
* Apply the loop guard around a provider dispatch at the model's
|
|
73
|
+
* {@link loopGuardLevel}; `off` dispatches unwrapped.
|
|
74
|
+
*/
|
|
75
|
+
export declare function withThinkingLoopGuard<O extends {
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
loopGuard?: {
|
|
78
|
+
enabled?: boolean;
|
|
79
|
+
checkAssistantContent?: boolean;
|
|
80
|
+
};
|
|
81
|
+
}>(model: Model<Api>, options: O | undefined, dispatch: (options: O | undefined) => AssistantMessageEventStream): AssistantMessageEventStream;
|
|
82
|
+
/**
|
|
83
|
+
* Backwards-compatible entry point used by `stream.ts` and tests.
|
|
95
84
|
*/
|
|
96
85
|
export declare function withGeminiThinkingLoopGuard<O extends {
|
|
97
86
|
signal?: AbortSignal;
|
|
@@ -1,8 +1,10 @@
|
|
|
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;
|
|
8
10
|
/** Redirects allowed before escalating to stalled_tool_call (`0` disables redirect-count escalation; default `2`). */
|
|
@@ -12,6 +14,8 @@ export interface ToolCallLoopGuardOptions {
|
|
|
12
14
|
export interface ToolCallLoopTurn {
|
|
13
15
|
readonly message: AssistantMessage;
|
|
14
16
|
readonly toolResults: readonly ToolResultMessage[];
|
|
17
|
+
/** The turn also delivered context outside its tool results (extension `additionalContext`). */
|
|
18
|
+
readonly injectedContext?: boolean;
|
|
15
19
|
}
|
|
16
20
|
/** Details needed to steer the model away from a repeated tool call. */
|
|
17
21
|
export interface RepeatedToolCallDetection {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "jeopi-ai",
|
|
4
|
-
"version": "16.7.
|
|
4
|
+
"version": "16.7.12",
|
|
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.
|
|
42
|
-
"jeopi-utils": "16.7.
|
|
43
|
-
"jeopi-wire": "16.7.
|
|
41
|
+
"jeopi-catalog": "16.7.12",
|
|
42
|
+
"jeopi-utils": "16.7.12",
|
|
43
|
+
"jeopi-wire": "16.7.12",
|
|
44
44
|
"arktype": "2.2.3",
|
|
45
45
|
"zod": "^4"
|
|
46
46
|
},
|
package/src/error/flags.ts
CHANGED
|
@@ -6,7 +6,16 @@ import {
|
|
|
6
6
|
ProviderHttpError,
|
|
7
7
|
STREAM_ENVELOPE_ERROR_PREFIX,
|
|
8
8
|
} from "./classes";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
is402BillingCapBody,
|
|
11
|
+
isAccountScopedCapText,
|
|
12
|
+
isConcurrencyCapExclusion,
|
|
13
|
+
isDashScopeTokenLimitText,
|
|
14
|
+
isOpaqueStatusBody,
|
|
15
|
+
isUsageLimitStatus,
|
|
16
|
+
matchesUsageLimitText,
|
|
17
|
+
parseRateLimitReason,
|
|
18
|
+
} from "./rate-limit";
|
|
10
19
|
|
|
11
20
|
export const Flag = {
|
|
12
21
|
Class: 0x1000,
|
|
@@ -110,6 +119,11 @@ export const LLAMA_CPP_TOOL_CALL_PARSE_PATTERN =
|
|
|
110
119
|
// error, also surfaced in text). Treated as transient — a retry usually lands
|
|
111
120
|
// on a backend that has the model.
|
|
112
121
|
const COPILOT_MODEL_NOT_SUPPORTED_PATTERN = /model_not_supported/i;
|
|
122
|
+
// Aliyun Bailian / DashScope multimodal gateway occasionally rejects a valid
|
|
123
|
+
// request with HTTP 400 and "Failed to download multimodal content" — transient.
|
|
124
|
+
export const ALIYUN_MM_GATEWAY_PATTERN = /failed to download multimodal content/i;
|
|
125
|
+
// Codex HTTP streaming body read transient failure.
|
|
126
|
+
export const CODEX_HTTP_BODY_READ_ERROR_PATTERN = /error occurred while reading (?:the )?(?:response |http )?body/i;
|
|
113
127
|
// Anthropic strict-tool grammar too large / schema too complex (400 invalid_request_error).
|
|
114
128
|
const GRAMMAR_TOO_LARGE_PATTERN = /compiled grammar/i;
|
|
115
129
|
const GRAMMAR_TOO_LARGE_DETAIL_PATTERN = /too large/i;
|
|
@@ -261,6 +275,7 @@ function isTransientErrorText(text: string): boolean {
|
|
|
261
275
|
return (
|
|
262
276
|
isUnexpectedSocketCloseMessage(text) ||
|
|
263
277
|
isStreamReadErrorText(text) ||
|
|
278
|
+
CODEX_HTTP_BODY_READ_ERROR_PATTERN.test(text) ||
|
|
264
279
|
(TRANSIENT_ENVELOPE_PATTERN.test(text) && TRANSIENT_ENVELOPE_BEFORE_START_PATTERN.test(text)) ||
|
|
265
280
|
TRANSIENT_TRANSPORT_PATTERN.test(text)
|
|
266
281
|
);
|
|
@@ -304,26 +319,44 @@ function isTerminalClientErrorStatus(code: number | undefined): boolean {
|
|
|
304
319
|
function classifyText(errorMessage: string | undefined, errorStatus: number | undefined, api?: Api): number {
|
|
305
320
|
let kinds = 0;
|
|
306
321
|
if (errorMessage) {
|
|
307
|
-
if (matchesOverflowText(errorMessage)) kinds |= Flag.ContextOverflow;
|
|
308
|
-
if (isMalformedFunctionCallText(errorMessage)) kinds |= Flag.MalformedFunctionCall;
|
|
309
|
-
if (isProviderFinishErrorText(errorMessage)) kinds |= Flag.ProviderFinishError;
|
|
310
|
-
if (isContentBlockedText(errorMessage)) kinds |= Flag.ContentBlocked;
|
|
311
|
-
if (isAuthFailureText(errorMessage)) kinds |= Flag.AuthFailed;
|
|
312
|
-
|
|
313
322
|
const statusClean = errorStatus ? errorStatus : (status({ message: errorMessage }) ?? undefined);
|
|
314
323
|
const cleanMessage = errorMessage;
|
|
315
324
|
const isOpaque = isOpaqueStatusBody(cleanMessage);
|
|
325
|
+
const rateLimitReason = parseRateLimitReason(cleanMessage);
|
|
326
|
+
const isQuotaExhausted =
|
|
327
|
+
rateLimitReason === "QUOTA_EXHAUSTED" || rateLimitReason === "INSUFFICIENT_G1_CREDITS_BALANCE";
|
|
328
|
+
const isConcurrencyExcluded = isConcurrencyCapExclusion(statusClean, cleanMessage);
|
|
329
|
+
|
|
330
|
+
// A 429/402 whose body contains "too many tokens" or "token limit exceeded"
|
|
331
|
+
// is a TPM/usage-limit response, not a context-window overflow.
|
|
332
|
+
if (!isUsageLimitStatus(statusClean) && matchesOverflowText(errorMessage)) kinds |= Flag.ContextOverflow;
|
|
333
|
+
if (isMalformedFunctionCallText(errorMessage)) kinds |= Flag.MalformedFunctionCall;
|
|
334
|
+
if (isProviderFinishErrorText(errorMessage)) kinds |= Flag.ProviderFinishError;
|
|
335
|
+
if (isContentBlockedText(errorMessage)) kinds |= Flag.ContentBlocked;
|
|
336
|
+
// Account-scoped 403 caps and 403 concurrency limits are NOT dead credentials.
|
|
337
|
+
if (
|
|
338
|
+
isAuthFailureText(errorMessage) &&
|
|
339
|
+
!(statusClean === 403 && (isAccountScopedCapText(cleanMessage) || isConcurrencyExcluded))
|
|
340
|
+
) {
|
|
341
|
+
kinds |= Flag.AuthFailed;
|
|
342
|
+
}
|
|
316
343
|
|
|
317
344
|
const isLimitStatus = statusClean === 429;
|
|
318
345
|
const is402BillingCap = statusClean === 402 && is402BillingCapBody(cleanMessage);
|
|
319
346
|
if (
|
|
320
|
-
|
|
321
|
-
(
|
|
322
|
-
|
|
347
|
+
!isConcurrencyExcluded &&
|
|
348
|
+
(is402BillingCap ||
|
|
349
|
+
(statusClean !== 402 && matchesUsageLimitText(cleanMessage)) ||
|
|
350
|
+
((statusClean === 403 || statusClean === undefined) && isAccountScopedCapText(cleanMessage)) ||
|
|
351
|
+
(isLimitStatus && (isOpaque || isQuotaExhausted)))
|
|
323
352
|
) {
|
|
324
353
|
kinds |= Flag.UsageLimit;
|
|
325
354
|
}
|
|
326
355
|
|
|
356
|
+
if (isConcurrencyExcluded || isDashScopeTokenLimitText(cleanMessage)) {
|
|
357
|
+
kinds |= Flag.Transient;
|
|
358
|
+
}
|
|
359
|
+
|
|
327
360
|
// Transport/timeout/truncation/stream-drop wording that rides on a terminal
|
|
328
361
|
// 4xx describes a deterministic client error that replays identically, so
|
|
329
362
|
// keep it terminal — matching isProviderRetryableError.
|
|
@@ -338,8 +371,13 @@ function classifyText(errorMessage: string | undefined, errorStatus: number | un
|
|
|
338
371
|
kinds |= Flag.StaleResponsesItem;
|
|
339
372
|
}
|
|
340
373
|
|
|
341
|
-
// Copilot
|
|
342
|
-
if (
|
|
374
|
+
// Provider-specific transient 400 flaps: Copilot model_not_supported & Aliyun MM download.
|
|
375
|
+
if (
|
|
376
|
+
statusClean === 400 &&
|
|
377
|
+
(COPILOT_MODEL_NOT_SUPPORTED_PATTERN.test(cleanMessage) || ALIYUN_MM_GATEWAY_PATTERN.test(cleanMessage))
|
|
378
|
+
) {
|
|
379
|
+
kinds |= Flag.Transient;
|
|
380
|
+
}
|
|
343
381
|
if (matchesGrammarTooLarge(cleanMessage, statusClean)) kinds |= Flag.Grammar;
|
|
344
382
|
if (matchesFastModeUnsupported(cleanMessage, statusClean)) kinds |= Flag.FastModeUnsupported;
|
|
345
383
|
}
|
|
@@ -538,8 +576,7 @@ export function isTransientStreamParseError(error: unknown): boolean {
|
|
|
538
576
|
* terminal event, with no JSON-parse signal and no retryable status attached.
|
|
539
577
|
*/
|
|
540
578
|
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
|
-
|
|
579
|
+
/stream disconnected before completion|(?:stream|websocket) closed before response\.completed|stream (?:was )?interrupted|stream ended (?:before (?:terminal (?:chunk|completion event)|message_(?:start|delta|stop))|without a finish reason)|socket disconnected before secure tls connection/i;
|
|
543
580
|
/** Transport stream-drop diagnostic (see {@link STREAM_DROP_PATTERN}). */
|
|
544
581
|
export function isTransientStreamDropError(error: unknown): boolean {
|
|
545
582
|
if (typeof error === "string") return STREAM_DROP_PATTERN.test(error);
|