dsh-subscriptions 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +129 -0
- package/cordis.patch.yml +12 -0
- package/lib/auth/claude-code-creds.d.ts +23 -0
- package/lib/auth/claude-code-creds.js +172 -0
- package/lib/auth/device-flow.d.ts +55 -0
- package/lib/auth/device-flow.js +177 -0
- package/lib/auth/jwt.d.ts +10 -0
- package/lib/auth/jwt.js +25 -0
- package/lib/auth/oauth-flow.d.ts +91 -0
- package/lib/auth/oauth-flow.js +227 -0
- package/lib/auth/pkce.d.ts +31 -0
- package/lib/auth/pkce.js +35 -0
- package/lib/auth/rpc.d.ts +209 -0
- package/lib/auth/rpc.js +386 -0
- package/lib/auth/store.d.ts +196 -0
- package/lib/auth/store.js +468 -0
- package/lib/client/CursorCard.d.ts +9 -0
- package/lib/client/CursorCard.js +113 -0
- package/lib/client/ExternalUsageCards.d.ts +9 -0
- package/lib/client/ExternalUsageCards.js +72 -0
- package/lib/client/ImageGallery.d.ts +54 -0
- package/lib/client/ImageGallery.js +112 -0
- package/lib/client/ImageGenerateToolview.d.ts +48 -0
- package/lib/client/ImageGenerateToolview.js +133 -0
- package/lib/client/ProviderAccountManager.d.ts +13 -0
- package/lib/client/ProviderAccountManager.js +147 -0
- package/lib/client/ProviderModelEditor.d.ts +39 -0
- package/lib/client/ProviderModelEditor.js +107 -0
- package/lib/client/SpeedSelect.d.ts +71 -0
- package/lib/client/SpeedSelect.js +177 -0
- package/lib/client/SubscriptionUsageBadge.d.ts +116 -0
- package/lib/client/SubscriptionUsageBadge.js +543 -0
- package/lib/client/SubscriptionsSection.d.ts +140 -0
- package/lib/client/SubscriptionsSection.js +544 -0
- package/lib/client/UsageBadgeDisplaySetting.d.ts +7 -0
- package/lib/client/UsageBadgeDisplaySetting.js +36 -0
- package/lib/client/VideoGenerateToolview.d.ts +42 -0
- package/lib/client/VideoGenerateToolview.js +175 -0
- package/lib/client/account-preferences.d.ts +24 -0
- package/lib/client/account-preferences.js +21 -0
- package/lib/client/fast-command.d.ts +2 -0
- package/lib/client/fast-command.js +4 -0
- package/lib/client/host-contract.d.ts +90 -0
- package/lib/client/host-contract.js +101 -0
- package/lib/client/host-icons.d.ts +24 -0
- package/lib/client/host-icons.js +21 -0
- package/lib/client/index.d.ts +27 -0
- package/lib/client/index.js +136 -0
- package/lib/client/locales.d.ts +297 -0
- package/lib/client/locales.js +295 -0
- package/lib/client/subscription-card-styles.d.ts +3 -0
- package/lib/client/subscription-card-styles.js +53 -0
- package/lib/client/subscriptions-rpc.d.ts +14 -0
- package/lib/client/subscriptions-rpc.js +34 -0
- package/lib/client/usage-badge-preferences.d.ts +11 -0
- package/lib/client/usage-badge-preferences.js +41 -0
- package/lib/client.js +4472 -0
- package/lib/client.js.map +1 -0
- package/lib/compat.d.ts +36 -0
- package/lib/compat.js +20 -0
- package/lib/http.d.ts +6 -0
- package/lib/http.js +15 -0
- package/lib/index.d.ts +80 -0
- package/lib/index.js +14018 -0
- package/lib/model-defaults.d.ts +23 -0
- package/lib/model-defaults.js +237 -0
- package/lib/provider-settings.d.ts +39 -0
- package/lib/provider-settings.js +151 -0
- package/lib/providers/account-preferences.d.ts +41 -0
- package/lib/providers/account-preferences.js +153 -0
- package/lib/providers/accounts.d.ts +112 -0
- package/lib/providers/accounts.js +142 -0
- package/lib/providers/antigravity-oauth-client.d.ts +7 -0
- package/lib/providers/antigravity-oauth-client.js +7 -0
- package/lib/providers/antigravity.d.ts +110 -0
- package/lib/providers/antigravity.js +516 -0
- package/lib/providers/catalog-store.d.ts +48 -0
- package/lib/providers/catalog-store.js +243 -0
- package/lib/providers/claude-cli-version.d.ts +15 -0
- package/lib/providers/claude-cli-version.js +24 -0
- package/lib/providers/claude.d.ts +181 -0
- package/lib/providers/claude.js +680 -0
- package/lib/providers/codex-client-version.d.ts +8 -0
- package/lib/providers/codex-client-version.js +17 -0
- package/lib/providers/codex-search.d.ts +29 -0
- package/lib/providers/codex-search.js +198 -0
- package/lib/providers/codex.d.ts +229 -0
- package/lib/providers/codex.js +821 -0
- package/lib/providers/common.d.ts +389 -0
- package/lib/providers/common.js +656 -0
- package/lib/providers/copilot.d.ts +344 -0
- package/lib/providers/copilot.js +888 -0
- package/lib/providers/cursor-adapter.d.ts +15 -0
- package/lib/providers/cursor-adapter.js +39 -0
- package/lib/providers/cursor-auth.d.ts +43 -0
- package/lib/providers/cursor-auth.js +169 -0
- package/lib/providers/cursor-model-settings.d.ts +15 -0
- package/lib/providers/cursor-model-settings.js +51 -0
- package/lib/providers/cursor-usage.d.ts +9 -0
- package/lib/providers/cursor-usage.js +112 -0
- package/lib/providers/external-usage-controller.d.ts +19 -0
- package/lib/providers/external-usage-controller.js +32 -0
- package/lib/providers/external-usage.d.ts +8 -0
- package/lib/providers/external-usage.js +82 -0
- package/lib/providers/grok.d.ts +205 -0
- package/lib/providers/grok.js +713 -0
- package/lib/providers/image-pool.d.ts +30 -0
- package/lib/providers/image-pool.js +89 -0
- package/lib/providers/npm-cli-version.d.ts +56 -0
- package/lib/providers/npm-cli-version.js +98 -0
- package/lib/providers/pool-family.d.ts +56 -0
- package/lib/providers/pool-family.js +45 -0
- package/lib/providers/pool-health.d.ts +74 -0
- package/lib/providers/pool-health.js +150 -0
- package/lib/providers/pool-usage.d.ts +86 -0
- package/lib/providers/pool-usage.js +223 -0
- package/lib/providers/pool.d.ts +108 -0
- package/lib/providers/pool.js +368 -0
- package/lib/providers/rate-limit.d.ts +192 -0
- package/lib/providers/rate-limit.js +338 -0
- package/lib/tools/image-generate.d.ts +128 -0
- package/lib/tools/image-generate.js +438 -0
- package/lib/tools/registration.d.ts +15 -0
- package/lib/tools/registration.js +24 -0
- package/lib/tools/video-generate.d.ts +89 -0
- package/lib/tools/video-generate.js +257 -0
- package/lib/tools/x-search.d.ts +58 -0
- package/lib/tools/x-search.js +197 -0
- package/lib/translate/anthropic.d.ts +161 -0
- package/lib/translate/anthropic.js +515 -0
- package/lib/translate/antigravity-schema.d.ts +4 -0
- package/lib/translate/antigravity-schema.js +145 -0
- package/lib/translate/antigravity-thinking.d.ts +5 -0
- package/lib/translate/antigravity-thinking.js +44 -0
- package/lib/translate/antigravity.d.ts +114 -0
- package/lib/translate/antigravity.js +366 -0
- package/lib/translate/chat-completions.d.ts +120 -0
- package/lib/translate/chat-completions.js +382 -0
- package/lib/translate/resolved.d.ts +80 -0
- package/lib/translate/resolved.js +118 -0
- package/lib/translate/responses.d.ts +179 -0
- package/lib/translate/responses.js +408 -0
- package/lib/translate/sse.d.ts +21 -0
- package/lib/translate/sse.js +56 -0
- package/package.json +114 -0
- package/vendor/cursor/LICENSE +21 -0
- package/vendor/cursor/index.d.ts +18 -0
- package/vendor/cursor/index.js +3574 -0
- package/vendor/cursor/proto.js +254 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate-limit window handling shared by the subscription adapters.
|
|
3
|
+
*
|
|
4
|
+
* A subscription plan is rate-limit shaped by design — a five-hour session
|
|
5
|
+
* window, a weekly window, and on some plans a per-model weekly one — so a 429
|
|
6
|
+
* is not a dead end: the window reopens at a time the provider discloses. This
|
|
7
|
+
* module turns that disclosure into the `providerRetryAfterMs` the optional
|
|
8
|
+
* `@deepseek-ai/dsh-llm-retry` plugin waits out, and resolves the retry policy
|
|
9
|
+
* whose `maxDelayMs` decides how long a route is allowed to hold the turn.
|
|
10
|
+
*
|
|
11
|
+
* The wait itself is provider-independent: adapters own the policy, the retry
|
|
12
|
+
* plugin executes it. Only the extraction of the reset instant differs, so each
|
|
13
|
+
* adapter contributes one {@link RateLimitResetReader} built from the parsing
|
|
14
|
+
* primitives here.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-subscriptions/providers/rate-limit
|
|
17
|
+
*/
|
|
18
|
+
import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
19
|
+
/**
|
|
20
|
+
* Extra time added to every provider-disclosed wait. Absorbs clock skew
|
|
21
|
+
* between the harness and the provider, so a retry does not land a moment
|
|
22
|
+
* before the window actually reopens and burn an attempt on a second 429.
|
|
23
|
+
*/
|
|
24
|
+
const RESET_GRACE_MS = 2_000;
|
|
25
|
+
/** Shortest wait ever scheduled, including for a reset instant already in the past. */
|
|
26
|
+
const MIN_WAIT_MS = 1_000;
|
|
27
|
+
/** Below this a bare number is a delay in seconds rather than an epoch stamp. */
|
|
28
|
+
const EPOCH_SECONDS_FLOOR = 1_000_000_000;
|
|
29
|
+
/** At or above this a bare epoch stamp is already in milliseconds. */
|
|
30
|
+
const EPOCH_MILLIS_FLOOR = 1_000_000_000_000;
|
|
31
|
+
/** Node's maximum timer delay; a longer wait cannot be scheduled at all. */
|
|
32
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
33
|
+
/** Default ceiling on a rate-limit wait: six hours covers a five-hour session window with slack. */
|
|
34
|
+
export const DEFAULT_RATE_LIMIT_MAX_WAIT_MS = 6 * 60 * 60 * 1_000;
|
|
35
|
+
/**
|
|
36
|
+
* Interpret a bare numeric rate-limit value, which providers write in three
|
|
37
|
+
* shapes: epoch milliseconds, epoch seconds, or a delay in seconds. The
|
|
38
|
+
* magnitude separates them unambiguously for any plausible value — an epoch in
|
|
39
|
+
* seconds is ~1.8e9 today, while a delay of even a full week is ~6e5.
|
|
40
|
+
* @param value - the raw numeric value.
|
|
41
|
+
* @param now - the current epoch milliseconds.
|
|
42
|
+
* @returns epoch milliseconds of the reset, or undefined when the value is unusable.
|
|
43
|
+
*/
|
|
44
|
+
export function resetInstantFromNumber(value, now) {
|
|
45
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (value >= EPOCH_MILLIS_FLOOR)
|
|
48
|
+
return value;
|
|
49
|
+
if (value >= EPOCH_SECONDS_FLOOR)
|
|
50
|
+
return value * 1_000;
|
|
51
|
+
// Provider body fields in this helper's allowlists are contracted as
|
|
52
|
+
// seconds. A provider that sends milliseconds here (for example,
|
|
53
|
+
// `retry_after: 30000`) would be interpreted as 30,000 seconds (~8.3 h),
|
|
54
|
+
// so such a field must be normalized by its provider reader first.
|
|
55
|
+
return now + value * 1_000;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Parse a Go-style duration (`6m0s`, `1h2m3.5s`, `150ms`) into milliseconds —
|
|
59
|
+
* the form OpenAI-compatible `x-ratelimit-reset-*` headers use.
|
|
60
|
+
* @param text - the raw header value.
|
|
61
|
+
* @returns the duration in milliseconds, or undefined when the text is not one.
|
|
62
|
+
*/
|
|
63
|
+
export function durationMs(text) {
|
|
64
|
+
const trimmed = text.trim();
|
|
65
|
+
if (trimmed.length === 0)
|
|
66
|
+
return undefined;
|
|
67
|
+
// Sticky: every component must abut the previous one, so trailing or
|
|
68
|
+
// interleaved junk ("6m0s later") fails the length check below.
|
|
69
|
+
const pattern = /(\d+(?:\.\d+)?)(ms|h|m|s)/y;
|
|
70
|
+
const units = { h: 3_600_000, m: 60_000, s: 1_000, ms: 1 };
|
|
71
|
+
let total = 0;
|
|
72
|
+
let matched = false;
|
|
73
|
+
// A failed sticky exec resets `lastIndex` to zero, so the reached offset is
|
|
74
|
+
// tracked separately rather than read back off the regex after the loop.
|
|
75
|
+
let index = 0;
|
|
76
|
+
// Components run strictly coarse to fine, the only order Go writes them in;
|
|
77
|
+
// a repeated or out-of-order unit ("1s2h", "1s1s") is not a duration and
|
|
78
|
+
// must not be silently summed into one.
|
|
79
|
+
let previousUnit = Number.POSITIVE_INFINITY;
|
|
80
|
+
for (;;) {
|
|
81
|
+
pattern.lastIndex = index;
|
|
82
|
+
const match = pattern.exec(trimmed);
|
|
83
|
+
if (match === null)
|
|
84
|
+
break;
|
|
85
|
+
const unit = units[match[2]];
|
|
86
|
+
if (unit >= previousUnit)
|
|
87
|
+
return undefined;
|
|
88
|
+
previousUnit = unit;
|
|
89
|
+
total += Number(match[1]) * unit;
|
|
90
|
+
index = pattern.lastIndex;
|
|
91
|
+
matched = true;
|
|
92
|
+
}
|
|
93
|
+
if (!matched || index !== trimmed.length)
|
|
94
|
+
return undefined;
|
|
95
|
+
// A zero duration ("0s") is not a disclosed reset — it is a bucket that has
|
|
96
|
+
// already rolled over — and reporting it as one would short-circuit the real
|
|
97
|
+
// signal behind it with a wait of `now`. The numeric path agrees:
|
|
98
|
+
// {@link resetInstantFromNumber} rejects zero too.
|
|
99
|
+
return total > 0 ? total : undefined;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Interpret any single rate-limit value — a number, a numeric string, a
|
|
103
|
+
* duration (`6m0s`), or a date — as the instant a window reopens. One reader
|
|
104
|
+
* for every shape, so a provider that changes the encoding of a field it
|
|
105
|
+
* already sends does not need a code change here.
|
|
106
|
+
* @param value - the raw header value or JSON field.
|
|
107
|
+
* @param now - the current epoch milliseconds.
|
|
108
|
+
* @returns epoch milliseconds of the reset, or undefined when the value is unusable.
|
|
109
|
+
*/
|
|
110
|
+
export function resetInstantFromValue(value, now) {
|
|
111
|
+
if (typeof value === 'number')
|
|
112
|
+
return resetInstantFromNumber(value, now);
|
|
113
|
+
if (typeof value !== 'string')
|
|
114
|
+
return undefined;
|
|
115
|
+
const trimmed = value.trim();
|
|
116
|
+
if (trimmed.length === 0)
|
|
117
|
+
return undefined;
|
|
118
|
+
const numeric = Number(trimmed);
|
|
119
|
+
if (Number.isFinite(numeric))
|
|
120
|
+
return resetInstantFromNumber(numeric, now);
|
|
121
|
+
const duration = durationMs(trimmed);
|
|
122
|
+
if (duration !== undefined)
|
|
123
|
+
return now + duration;
|
|
124
|
+
const parsed = Date.parse(trimmed);
|
|
125
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Read a header carrying any of the {@link resetInstantFromValue} shapes.
|
|
129
|
+
* @param response - the failed response.
|
|
130
|
+
* @param name - the header to read.
|
|
131
|
+
* @param now - the current epoch milliseconds.
|
|
132
|
+
* @returns epoch milliseconds of the reset, or undefined when absent or unusable.
|
|
133
|
+
*/
|
|
134
|
+
export function resetInstantFromHeader(response, name, now) {
|
|
135
|
+
return resetInstantFromValue(response.headers.get(name), now);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Read the RFC 7231 `retry-after` header in both its forms: a delay in seconds
|
|
139
|
+
* (never an epoch stamp, whatever its magnitude) or an HTTP-date.
|
|
140
|
+
* @param response - the failed response.
|
|
141
|
+
* @param now - the current epoch milliseconds.
|
|
142
|
+
* @returns epoch milliseconds of the reset, or undefined when absent or unusable.
|
|
143
|
+
*/
|
|
144
|
+
export function retryAfterInstant(response, now) {
|
|
145
|
+
const raw = response.headers.get('retry-after');
|
|
146
|
+
if (raw === null)
|
|
147
|
+
return undefined;
|
|
148
|
+
const trimmed = raw.trim();
|
|
149
|
+
if (trimmed.length === 0)
|
|
150
|
+
return undefined;
|
|
151
|
+
const seconds = Number(trimmed);
|
|
152
|
+
if (Number.isFinite(seconds))
|
|
153
|
+
return seconds > 0 ? now + seconds * 1_000 : undefined;
|
|
154
|
+
const parsed = Date.parse(trimmed);
|
|
155
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Parse a response body as JSON without throwing on the non-JSON bodies
|
|
159
|
+
* providers occasionally return under load (an HTML gateway page, say).
|
|
160
|
+
* @param body - the complete response body.
|
|
161
|
+
* @returns the parsed value, or undefined when the body is not JSON.
|
|
162
|
+
*/
|
|
163
|
+
export function jsonBody(body) {
|
|
164
|
+
if (body.length === 0)
|
|
165
|
+
return undefined;
|
|
166
|
+
try {
|
|
167
|
+
return JSON.parse(body);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
// Only swallow body parsing: header-derived signals still apply.
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** How deep {@link resetFromFields} walks; every observed payload nests one or two levels. */
|
|
175
|
+
const MAX_BODY_DEPTH = 4;
|
|
176
|
+
/**
|
|
177
|
+
* Find a reset instant under any of the named keys, anywhere in a parsed body.
|
|
178
|
+
*
|
|
179
|
+
* The search is by key rather than by path on purpose: providers move the same
|
|
180
|
+
* field between containers (`detail`, `error`, top level) across endpoints and
|
|
181
|
+
* versions, and a path-shaped reader silently stops working when they do. Only
|
|
182
|
+
* the key list is provider-specific.
|
|
183
|
+
* @param value - the parsed body, or any nested value.
|
|
184
|
+
* @param keys - field names this provider uses for a reset or delay.
|
|
185
|
+
* @param now - the current epoch milliseconds.
|
|
186
|
+
* @param depth - remaining recursion depth.
|
|
187
|
+
* @returns the earliest instant found, or undefined when no key matched.
|
|
188
|
+
*/
|
|
189
|
+
export function resetFromFields(value, keys, now, depth = MAX_BODY_DEPTH) {
|
|
190
|
+
if (depth <= 0 || value === null || typeof value !== 'object')
|
|
191
|
+
return undefined;
|
|
192
|
+
let earliest;
|
|
193
|
+
const consider = (candidate) => {
|
|
194
|
+
if (candidate !== undefined && (earliest === undefined || candidate < earliest))
|
|
195
|
+
earliest = candidate;
|
|
196
|
+
};
|
|
197
|
+
if (Array.isArray(value)) {
|
|
198
|
+
for (const item of value)
|
|
199
|
+
consider(resetFromFields(item, keys, now, depth - 1));
|
|
200
|
+
return earliest;
|
|
201
|
+
}
|
|
202
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
203
|
+
if (keys.includes(key))
|
|
204
|
+
consider(resetInstantFromValue(nested, now));
|
|
205
|
+
else
|
|
206
|
+
consider(resetFromFields(nested, keys, now, depth - 1));
|
|
207
|
+
}
|
|
208
|
+
return earliest;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The earliest of several candidate reset instants, ignoring absent ones. The
|
|
212
|
+
* earliest is the one that matters: it is the first moment any of the reported
|
|
213
|
+
* limits allows a request again.
|
|
214
|
+
* @param candidates - reset instants in no particular order.
|
|
215
|
+
* @returns the earliest instant, or undefined when every candidate is absent.
|
|
216
|
+
*/
|
|
217
|
+
export function earliestReset(...candidates) {
|
|
218
|
+
let earliest;
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
if (candidate === undefined)
|
|
221
|
+
continue;
|
|
222
|
+
if (earliest === undefined || candidate < earliest)
|
|
223
|
+
earliest = candidate;
|
|
224
|
+
}
|
|
225
|
+
return earliest;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Turn a reset instant into the wait to report as `providerRetryAfterMs`.
|
|
229
|
+
*
|
|
230
|
+
* Deliberately not capped: a reset beyond the policy's `maxDelayMs` makes the
|
|
231
|
+
* retry plugin delegate immediately, failing the turn at once with the real
|
|
232
|
+
* reset in the message, rather than clamping the wait down and burning the
|
|
233
|
+
* retry budget against a window that is still closed.
|
|
234
|
+
* @param instant - epoch milliseconds the window reopens.
|
|
235
|
+
* @param now - the current epoch milliseconds.
|
|
236
|
+
* @returns the wait in milliseconds, never below {@link MIN_WAIT_MS}.
|
|
237
|
+
*/
|
|
238
|
+
export function waitFromReset(instant, now) {
|
|
239
|
+
return Math.max(MIN_WAIT_MS, instant - now + RESET_GRACE_MS);
|
|
240
|
+
}
|
|
241
|
+
/** Header names worth showing when a 429 disclosed no reset this code recognizes. */
|
|
242
|
+
const DIAGNOSTIC_HEADER = /rate-?limit|retry|reset|^x-codex-/i;
|
|
243
|
+
/**
|
|
244
|
+
* Render the rate-limit-shaped headers and the head of the body of a 429 whose
|
|
245
|
+
* reset instant nothing parsed. Emitted through the adapter's `onWarn`, this is
|
|
246
|
+
* how an unrecognized provider field gets named from live traffic instead of
|
|
247
|
+
* being guessed at.
|
|
248
|
+
*
|
|
249
|
+
* It is also where the per-bucket rollover snapshots land by design — no reader
|
|
250
|
+
* parks a turn on one, because on a 429 they cannot say which bucket refused —
|
|
251
|
+
* so the operator still sees what the provider disclosed.
|
|
252
|
+
* @param response - the failed response.
|
|
253
|
+
* @param body - the complete response body.
|
|
254
|
+
* @returns a one-line diagnostic.
|
|
255
|
+
*/
|
|
256
|
+
export function rateLimitDiagnostics(response, body) {
|
|
257
|
+
const headers = [];
|
|
258
|
+
response.headers.forEach((value, key) => {
|
|
259
|
+
if (DIAGNOSTIC_HEADER.test(key))
|
|
260
|
+
headers.push(`${key}: ${value}`);
|
|
261
|
+
});
|
|
262
|
+
headers.sort();
|
|
263
|
+
const rendered = headers.length > 0 ? headers.join('; ') : '(none)';
|
|
264
|
+
const head = body.slice(0, 200);
|
|
265
|
+
return `429 disclosed no reset time; headers [${rendered}]; body ${head.length > 0 ? head : '(empty)'}`;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* The retry shape every subscription route starts from: Claude Code's own SDK
|
|
269
|
+
* numbers — ten retries after the first attempt, exponential backoff from 1s
|
|
270
|
+
* doubling per attempt, capped at 60s, plus 20% jitter.
|
|
271
|
+
*
|
|
272
|
+
* Shared across all four routes rather than kept to claude, because what these
|
|
273
|
+
* numbers are tuned for is the shape of a subscription endpoint — a consumer
|
|
274
|
+
* plan behind a session window, which sheds load in bursts and rewards an
|
|
275
|
+
* attempt that outlasts them — and that is the same on all four. The dsh-llm
|
|
276
|
+
* defaults (5 retries from 500ms to 10s) give up after about fifteen seconds,
|
|
277
|
+
* which is short for that.
|
|
278
|
+
*
|
|
279
|
+
* The 60s cap governs local backoff only: a disclosed rate-limit reset is
|
|
280
|
+
* accepted up to the configured wait ceiling instead.
|
|
281
|
+
*/
|
|
282
|
+
export const DEFAULT_RETRY = Object.freeze({
|
|
283
|
+
maxRetries: 10,
|
|
284
|
+
initialDelayMs: 1_000,
|
|
285
|
+
maxDelayMs: 60_000,
|
|
286
|
+
jitterRatio: 0.2,
|
|
287
|
+
});
|
|
288
|
+
/** Waiting behavior a route falls back to when the plugin passed none (waiting on, six-hour ceiling). */
|
|
289
|
+
export const DEFAULT_RATE_LIMIT_WAIT = Object.freeze({
|
|
290
|
+
wait: true,
|
|
291
|
+
maxWaitMs: DEFAULT_RATE_LIMIT_MAX_WAIT_MS,
|
|
292
|
+
});
|
|
293
|
+
/**
|
|
294
|
+
* Validate and default the rate-limit waiting config.
|
|
295
|
+
* @param config - the raw plugin config section, when present.
|
|
296
|
+
* @param path - diagnostic path naming the config that owns the value.
|
|
297
|
+
* @returns the resolved, immutable behavior.
|
|
298
|
+
*/
|
|
299
|
+
export function resolveRateLimitWait(config, path) {
|
|
300
|
+
const wait = config?.wait ?? true;
|
|
301
|
+
const maxWaitMs = config?.maxWaitMs ?? DEFAULT_RATE_LIMIT_MAX_WAIT_MS;
|
|
302
|
+
if (!Number.isFinite(maxWaitMs) || maxWaitMs <= 0) {
|
|
303
|
+
throw new Error(`${path}.maxWaitMs must be a positive finite number of milliseconds`);
|
|
304
|
+
}
|
|
305
|
+
if (maxWaitMs > MAX_TIMER_DELAY_MS) {
|
|
306
|
+
throw new Error(`${path}.maxWaitMs must be no greater than ${String(MAX_TIMER_DELAY_MS)} (the maximum schedulable delay)`);
|
|
307
|
+
}
|
|
308
|
+
return Object.freeze({ wait, maxWaitMs });
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Resolve one route's retry policy, widening the delay ceiling to the
|
|
312
|
+
* configured wait so a disclosed reset hours out is accepted rather than
|
|
313
|
+
* refused.
|
|
314
|
+
*
|
|
315
|
+
* The ceiling is shared with local exponential backoff, so widening it also
|
|
316
|
+
* raises how long an unrelated transient failure may back off for. That stays
|
|
317
|
+
* bounded by the finite retry budget — the claude route's ten retries reach
|
|
318
|
+
* 512 s per attempt at most — and it only governs when the provider disclosed
|
|
319
|
+
* nothing, which is exactly the case where a longer wait is the safer guess.
|
|
320
|
+
* @param defaults - the route's retry shape.
|
|
321
|
+
* @param rateLimit - resolved waiting behavior.
|
|
322
|
+
* @param path - diagnostic path naming the provider route.
|
|
323
|
+
* @returns the policy to report from `providerRetryPolicy`.
|
|
324
|
+
*/
|
|
325
|
+
export function subscriptionRetryPolicy(defaults, rateLimit, path) {
|
|
326
|
+
const maxDelayMs = rateLimit.wait
|
|
327
|
+
? Math.max(defaults.maxDelayMs, rateLimit.maxWaitMs)
|
|
328
|
+
: defaults.maxDelayMs;
|
|
329
|
+
return resolveRetryPolicy({
|
|
330
|
+
mode: 'normal',
|
|
331
|
+
maxRetries: defaults.maxRetries,
|
|
332
|
+
backoff: {
|
|
333
|
+
initialDelayMs: defaults.initialDelayMs,
|
|
334
|
+
maxDelayMs,
|
|
335
|
+
jitterRatio: defaults.jitterRatio,
|
|
336
|
+
},
|
|
337
|
+
}, path);
|
|
338
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `image_generate` tool: generate images through a subscription image
|
|
3
|
+
* endpoint, save them under the harness home, and — when the deployment
|
|
4
|
+
* mounts an attachment store and the calling route declares image input —
|
|
5
|
+
* also commit the bytes as durable attachments so the images render inline
|
|
6
|
+
* and enter model context (the same path `read_image` uses).
|
|
7
|
+
*
|
|
8
|
+
* Provider selection: the `provider` argument names the preferred provider
|
|
9
|
+
* (default `gpt`, i.e. the ChatGPT/Codex subscription serving gpt-image-2 —
|
|
10
|
+
* mirrors codex-rs `codex-api/src/images.rs`); when the preferred one is
|
|
11
|
+
* logged out the other serves as fallback (`grok` is grok-imagine-image-2.0
|
|
12
|
+
* via `api.x.ai/v1/images/generations` with `response_format: 'b64_json'`).
|
|
13
|
+
* Both answer the OpenAI images shape (`data[].b64_json`).
|
|
14
|
+
*/
|
|
15
|
+
import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
|
|
16
|
+
import type { LlmRuntime } from '@deepseek-ai/dsh-llm';
|
|
17
|
+
import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
|
|
18
|
+
import type { CodexSession, GrokSession } from '../auth/store.js';
|
|
19
|
+
import { AccountTokenManager } from '../providers/accounts.js';
|
|
20
|
+
import { ImageAccountPool } from '../providers/image-pool.js';
|
|
21
|
+
import type { FetchFn } from '../providers/common.js';
|
|
22
|
+
/** Endpoint the codex generation request is posted to. */
|
|
23
|
+
export declare const IMAGE_GENERATE_URL = "https://chatgpt.com/backend-api/codex/images/generations";
|
|
24
|
+
export declare const IMAGE_EDIT_URL = "https://chatgpt.com/backend-api/codex/images/edits";
|
|
25
|
+
/** The image model the codex subscription endpoint serves. */
|
|
26
|
+
export declare const IMAGE_GENERATE_MODEL = "gpt-image-2";
|
|
27
|
+
/** Endpoint the grok generation request is posted to. */
|
|
28
|
+
export declare const GROK_IMAGE_GENERATE_URL = "https://api.x.ai/v1/images/generations";
|
|
29
|
+
export declare const GROK_IMAGE_EDIT_URL = "https://api.x.ai/v1/images/edits";
|
|
30
|
+
/** The image model the grok subscription endpoint serves. */
|
|
31
|
+
export declare const GROK_IMAGE_GENERATE_MODEL = "grok-imagine-image-2.0";
|
|
32
|
+
/** Dependencies of the `image_generate` tool. */
|
|
33
|
+
export interface ImageGenerateToolOptions {
|
|
34
|
+
/** Shared generation/edit account scheduling; standalone tools get a private pool. */
|
|
35
|
+
imagePool?: ImageAccountPool;
|
|
36
|
+
/** Creation-time provider policy; existing sessions retain their original tools. */
|
|
37
|
+
providerEnabled?: (provider: 'codex' | 'grok', createdAt: number | undefined) => boolean;
|
|
38
|
+
/** Codex session source; the default preferred provider (`provider: 'gpt'`). */
|
|
39
|
+
codexTokens?: AccountTokenManager<CodexSession>;
|
|
40
|
+
/** Grok session source; preferred when the call passes `provider: 'grok'`. */
|
|
41
|
+
grokTokens?: AccountTokenManager<GrokSession>;
|
|
42
|
+
/** Fetch implementation (injectable for tests). */
|
|
43
|
+
fetchFn?: FetchFn;
|
|
44
|
+
/** Directory override for saved images (defaults under the harness home). */
|
|
45
|
+
imagesDir?: string;
|
|
46
|
+
/** Lazy attachment-store lookup; absent or unmounted store keeps the text-only result. */
|
|
47
|
+
resolveAttachments?: () => AttachmentStore | undefined;
|
|
48
|
+
/** Lazy llm-service lookup for the image-capability route check. */
|
|
49
|
+
resolveLlm?: () => LlmRuntime | undefined;
|
|
50
|
+
}
|
|
51
|
+
/** The wire request body for one generation call. */
|
|
52
|
+
export interface ImageGenerateRequestBody {
|
|
53
|
+
prompt: string;
|
|
54
|
+
model: string;
|
|
55
|
+
size?: string;
|
|
56
|
+
quality?: string;
|
|
57
|
+
}
|
|
58
|
+
/** The tool's own argument shape, shared by both provider body builders. */
|
|
59
|
+
export interface ImageGenerateArgs {
|
|
60
|
+
prompt: string;
|
|
61
|
+
size?: '1024x1024' | '1024x1536' | '1536x1024' | 'auto';
|
|
62
|
+
quality?: 'low' | 'medium' | 'high' | 'auto';
|
|
63
|
+
/** Preferred provider; the other one serves when the preferred is logged out. */
|
|
64
|
+
provider?: 'gpt' | 'grok';
|
|
65
|
+
/** Ordered durable references; omission generates, presence edits. */
|
|
66
|
+
referenceImages?: ImageGenerateImageValue[];
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Assemble the codex request body from tool arguments (hand-checks the
|
|
70
|
+
* non-empty prompt the schema DSL cannot express).
|
|
71
|
+
*/
|
|
72
|
+
export declare function buildImageGenerateBody(args: ImageGenerateArgs): ImageGenerateRequestBody;
|
|
73
|
+
/** The wire request body for one grok generation call. */
|
|
74
|
+
export interface GrokImageGenerateRequestBody {
|
|
75
|
+
prompt: string;
|
|
76
|
+
model: string;
|
|
77
|
+
response_format: 'b64_json';
|
|
78
|
+
aspect_ratio?: string;
|
|
79
|
+
quality?: 'low' | 'medium';
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Assemble the grok request body from the same tool arguments: `size` maps
|
|
83
|
+
* onto the nearest `aspect_ratio`, and `quality` folds into grok's low/medium
|
|
84
|
+
* pair (`high` → `medium`, `auto` → provider default).
|
|
85
|
+
*/
|
|
86
|
+
export declare function buildGrokImageGenerateBody(args: ImageGenerateArgs): GrokImageGenerateRequestBody;
|
|
87
|
+
/** One generated image decoded from the response. */
|
|
88
|
+
export interface GeneratedImage {
|
|
89
|
+
/** PNG bytes. */
|
|
90
|
+
data: Buffer;
|
|
91
|
+
/** Provider-revised prompt, when the response carries one. */
|
|
92
|
+
revisedPrompt?: string;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Parse the generations response into decodable images. Throws when the
|
|
96
|
+
* payload carries no usable `b64_json` entries.
|
|
97
|
+
*/
|
|
98
|
+
export declare function parseImageGenerateResponse(payload: unknown): GeneratedImage[];
|
|
99
|
+
/** Directory the generated image files are written to. */
|
|
100
|
+
export declare function imagesDirectory(): string;
|
|
101
|
+
/** Media types the attachment store accepts and this tool can produce. */
|
|
102
|
+
export type GeneratedImageMediaType = 'image/png' | 'image/jpeg' | 'image/webp';
|
|
103
|
+
/**
|
|
104
|
+
* Sniff a generated image's media type from its magic bytes (codex serves
|
|
105
|
+
* PNG; grok's format is undocumented, so trust the bytes). Unrecognized data
|
|
106
|
+
* defaults to PNG, matching the historical behavior.
|
|
107
|
+
*/
|
|
108
|
+
export declare function sniffImageMediaType(data: Buffer): GeneratedImageMediaType;
|
|
109
|
+
/** Canonical image metadata as the output schema declares it. */
|
|
110
|
+
interface ImageGenerateImageValue {
|
|
111
|
+
attachmentId: string;
|
|
112
|
+
mediaType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif';
|
|
113
|
+
bytes: number;
|
|
114
|
+
width: number;
|
|
115
|
+
height: number;
|
|
116
|
+
name?: string;
|
|
117
|
+
originalDimensions?: {
|
|
118
|
+
width: number;
|
|
119
|
+
height: number;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Build the `image_generate` tool definition.
|
|
124
|
+
* @param options - codex session source, fetch implementation, and image directory.
|
|
125
|
+
* @returns the tool to register on `ctx.tools`.
|
|
126
|
+
*/
|
|
127
|
+
export declare function createImageGenerateTool(options: ImageGenerateToolOptions): ToolDefinition;
|
|
128
|
+
export {};
|