@eduardo191labs/opencode-free-pi 0.3.8 → 0.3.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/README.md CHANGED
@@ -105,9 +105,10 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
105
105
  - Recuperación automática del límite de sesiones concurrentes.
106
106
  - **Recuperación de `concurrent`**: free-pi admite una sola petición en vuelo por
107
107
  `x-session-id` y puede dejar el slot bloqueado en el servidor tras un stream
108
- abortado. El plugin rota el `x-session-id` (y libera el anterior), reintenta
109
- con espera exponencial hasta 6 intentos y evita el error «one request at a
110
- time» en el turno.
108
+ abortado. El plugin repite la petición con un `x-session-id` nuevo desde el
109
+ hook de respuesta y entrega el resultado a OpenCode, así que el turno sigue sin
110
+ mostrar «one request at a time»; el reintento normal también rota el id como
111
+ respaldo.
111
112
  - **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
112
113
  models.dev se guardan en disco; si la red falla al arrancar se usan las copias
113
114
  locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
@@ -151,13 +152,18 @@ consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
151
152
  cuota y límite.
152
153
 
153
154
  Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
154
- `min(2s · 2^(n-1), 60s)`. El 429 `concurrent` («one request at a time») es la
155
- excepción: como el servidor puede dejar el slot de una sesión bloqueado, el
156
- plugin cambia el `x-session-id` de esa sesión, libera el anterior y reintenta
157
- hasta 6 veces con esperas de 1s a 15s. Si el catálogo asigna el experimento
158
- `compact100`, el plugin baja la ventana a 117 647 tokens para que OpenCode
159
- compacte al llegar a 100k, que es el mismo umbral que consigue
160
- `reserveTokens: 100000` en el CLI.
155
+ `min(2s · 2^(n-1), 60s)`. Los límites terminales (`free_usage_limit`, cupos
156
+ diarios u horarios, créditos, cuenta bloqueada) se convierten en un 400 con el
157
+ mensaje amigable y no se reintentan, igual que hace el CLI de pi; así OpenCode no
158
+ muestra un «Retrying…» que nunca termina. El 429 `concurrent` («one request at a
159
+ time») es la excepción: como OpenCode reutiliza la petición ya preparada al
160
+ reintentar, el plugin **repite la petición** desde el hook de respuesta con un
161
+ `x-session-id` nuevo y devuelve el resultado bueno a OpenCode; el turno continúa
162
+ sin fallar ni mostrar reintentos. Además libera el id anterior, y si el replay no
163
+ puede completarse el hook de reintento rota el id para los siguientes pasos. Si
164
+ el catálogo asigna el experimento `compact100`, el plugin baja la ventana a 117
165
+ 647 tokens para que OpenCode compacte al llegar a 100k, que es el mismo umbral
166
+ que consigue `reserveTokens: 100000` en el CLI.
161
167
 
162
168
  ## Rutas por plataforma
163
169
 
@@ -10,6 +10,7 @@ const LONG_LIMIT_CODES = new Set([
10
10
  "global_cap",
11
11
  "premium_allowance",
12
12
  "guest_allowance",
13
+ "free_usage_limit",
13
14
  "concurrent_session",
14
15
  "model_requires_credits",
15
16
  "insufficient_credits",
@@ -15,6 +15,7 @@ const FREE_PI_ERROR_TEXT = {
15
15
  account_review: "This account is under review; contact support.",
16
16
  ads_required: "Ads are not displaying for this account, so free completions are paused. Run `npx free-pi-cli@latest` so ads can show, then retry.",
17
17
  guest_allowance: "Guest trial used up; sign in with GitHub for a larger allowance.",
18
+ free_usage_limit: "Free usage limit reached. Wait for the allowance to reset, switch models or add credits.",
18
19
  guest_unavailable: "Guest access is unavailable right now.",
19
20
  guest_login_required: "This needs a GitHub sign-in.",
20
21
  region_unavailable: "free-pi is not available in your region.",
@@ -5,8 +5,10 @@ import { resolveToken } from "../auth/token.js";
5
5
  import { COST_EXPERIMENT_HEADER, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
6
6
  import { closeFreePiSession } from "../api/session.js";
7
7
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
8
+ import { parseFreePiError } from "../errors/parse.js";
8
9
  import { trimMap } from "../utils/async.js";
9
10
  import { watchFreePiNotice } from "./notices.js";
11
+ import { rememberReplayBody, replayConcurrentResponse, } from "./replay.js";
10
12
  import { localTitle } from "./title.js";
11
13
  import { rememberFreePiSession } from "./track.js";
12
14
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
@@ -119,6 +121,45 @@ function isConcurrentFailure(error) {
119
121
  /one request at a time/i.test(body) ||
120
122
  /"concurrent"/.test(body));
121
123
  }
124
+ /**
125
+ * Limits and account blocks do not recover by retrying. pi's own retry helper
126
+ * treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
127
+ * OpenCode retries every 429 by default, which surfaces as an endless
128
+ * "Retrying…". The response rewrite turns most of these into a 400; this guard
129
+ * covers the rest and keeps the CLI's behavior.
130
+ */
131
+ const TERMINAL_RETRY_CODES = new Set([
132
+ "daily_cap",
133
+ "hourly_ceiling",
134
+ "rolling_cap",
135
+ "global_cap",
136
+ "account_ceiling",
137
+ "free_usage_limit",
138
+ "premium_allowance",
139
+ "guest_allowance",
140
+ "model_requires_credits",
141
+ "insufficient_credits",
142
+ "ads_required",
143
+ "account_review",
144
+ "region_unavailable",
145
+ "unauthorized",
146
+ "expired_token",
147
+ "guest_login_required",
148
+ "consent_required",
149
+ "upgrade_required",
150
+ "reward_required",
151
+ "content_filter",
152
+ "subagents_unavailable",
153
+ ]);
154
+ const TERMINAL_RETRY_PATTERN = /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
155
+ function isTerminalFailure(error) {
156
+ const parsed = parseFreePiError(error, true);
157
+ if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
158
+ return true;
159
+ const body = typeof error?.response?.body === "string" ? error.response.body : "";
160
+ const message = typeof error?.message === "string" ? error.message : "";
161
+ return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
162
+ }
122
163
  /**
123
164
  * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
124
165
  * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
@@ -151,6 +192,10 @@ function applyRetryPolicy(deps, event) {
151
192
  };
152
193
  return;
153
194
  }
195
+ if (isTerminalFailure(event.error)) {
196
+ event.decision = { retry: false };
197
+ return;
198
+ }
154
199
  if (event.attempt > RETRY_MAX_RETRIES + 1) {
155
200
  event.decision = { retry: false };
156
201
  return;
@@ -190,16 +235,22 @@ export async function registerSessionHooks(ctx, deps) {
190
235
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
191
236
  await hookForProviders(ctx, "title", generation("title"), registrations);
192
237
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
238
+ await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
193
239
  await hookForProviders(ctx, "http.response", async (event) => {
240
+ // Recover a per-session `429 concurrent` before OpenCode sees it: the
241
+ // step's prepared request is reused on retry, so rotating the id in the
242
+ // retry hook is too late for the failed attempt.
243
+ const replayed = await replayConcurrentResponse(deps, event).catch(() => undefined);
244
+ const response = replayed ?? event.response;
194
245
  // Context overflow has to be handled first: a 429 context ceiling must
195
246
  // become a 400 overflow, not a friendly long-lived limit.
196
- const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
247
+ const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
197
248
  if (overflow) {
198
249
  event.response = watchFreePiNotice(deps, overflow);
199
250
  return;
200
251
  }
201
- const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
202
- event.response = watchFreePiNotice(deps, rewritten ?? event.response);
252
+ const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
253
+ event.response = watchFreePiNotice(deps, rewritten ?? response);
203
254
  }, registrations);
204
255
  await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
205
256
  await registerToolHooks(ctx, deps, registrations);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Transparently replays a free-pi request that hit the per-session
3
+ * `429 concurrent` limit.
4
+ *
5
+ * OpenCode builds the provider request once and reuses it for every retry of a
6
+ * step (`SessionRunner.runStep` calls `request.primary` outside the attempt
7
+ * loop). Rotating `x-session-id` in the retry hook therefore cannot help the
8
+ * failed attempt: the retried request still carries the old id. The server can
9
+ * also leave a session slot locked after an aborted stream, which resets do not
10
+ * clear.
11
+ *
12
+ * Replaying from `http.response` instead sends the same body with a fresh wire
13
+ * session id and returns the good response to OpenCode, so the turn continues
14
+ * without a visible "Retrying…" or a failed step.
15
+ */
16
+ import type { Deps } from "../deps.js";
17
+ /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
18
+ export declare function rememberReplayBody(deps: Deps, event: any): Promise<void>;
19
+ /**
20
+ * Returns a replacement response when a concurrent 429 was recovered, or
21
+ * `undefined` to leave the original response untouched.
22
+ */
23
+ export declare function replayConcurrentResponse(deps: Deps, event: any): Promise<Response | undefined>;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Transparently replays a free-pi request that hit the per-session
3
+ * `429 concurrent` limit.
4
+ *
5
+ * OpenCode builds the provider request once and reuses it for every retry of a
6
+ * step (`SessionRunner.runStep` calls `request.primary` outside the attempt
7
+ * loop). Rotating `x-session-id` in the retry hook therefore cannot help the
8
+ * failed attempt: the retried request still carries the old id. The server can
9
+ * also leave a session slot locked after an aborted stream, which resets do not
10
+ * clear.
11
+ *
12
+ * Replaying from `http.response` instead sends the same body with a fresh wire
13
+ * session id and returns the good response to OpenCode, so the turn continues
14
+ * without a visible "Retrying…" or a failed step.
15
+ */
16
+ import { closeFreePiSession } from "../api/session.js";
17
+ import { sleep, trimMap } from "../utils/async.js";
18
+ import { rotateWireSessionID, wireSessionID } from "./wire.js";
19
+ const REPLAY_BODY_LIMIT = 24;
20
+ const REPLAY_MAX_ATTEMPTS = 4;
21
+ const REPLAY_BASE_DELAY_MS = 400;
22
+ const REPLAY_MAX_DELAY_MS = 3_000;
23
+ function requestKey(sessionID, request) {
24
+ const turn = request.headers.get("x-turn-id") ?? "";
25
+ return `${sessionID}\u0000${turn}\u0000${request.url}`;
26
+ }
27
+ function isJson(request) {
28
+ return (request.headers.get("content-type") ?? "").includes("json");
29
+ }
30
+ /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
31
+ export async function rememberReplayBody(deps, event) {
32
+ const request = event?.request;
33
+ if (!(request instanceof Request) || !isJson(request) || !event.sessionID)
34
+ return;
35
+ const key = requestKey(event.sessionID, request);
36
+ try {
37
+ const body = await request.clone().text();
38
+ if (!body)
39
+ return;
40
+ deps.state.replayBodies.delete(key);
41
+ deps.state.replayBodies.set(key, body);
42
+ trimMap(deps.state.replayBodies, REPLAY_BODY_LIMIT);
43
+ }
44
+ catch {
45
+ // A non-replayable body simply falls back to the normal retry hook.
46
+ }
47
+ }
48
+ async function isConcurrent(response) {
49
+ if (response.status !== 429)
50
+ return false;
51
+ const body = await response
52
+ .clone()
53
+ .text()
54
+ .catch(() => "");
55
+ return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
56
+ }
57
+ function concurrentDelay(attempt) {
58
+ return Math.min(REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1), REPLAY_MAX_DELAY_MS);
59
+ }
60
+ /**
61
+ * Returns a replacement response when a concurrent 429 was recovered, or
62
+ * `undefined` to leave the original response untouched.
63
+ */
64
+ export async function replayConcurrentResponse(deps, event) {
65
+ const original = event?.response;
66
+ const request = event?.request;
67
+ if (!(original instanceof Response) || !(request instanceof Request))
68
+ return;
69
+ if (!(await isConcurrent(original)))
70
+ return;
71
+ const body = deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
72
+ (isJson(request)
73
+ ? await request
74
+ .clone()
75
+ .text()
76
+ .catch(() => undefined)
77
+ : undefined);
78
+ if (!body)
79
+ return;
80
+ let previous = request.headers.get("x-session-id") ??
81
+ wireSessionID(deps, event.sessionID);
82
+ for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
83
+ if (attempt > 1)
84
+ await sleep(concurrentDelay(attempt));
85
+ const next = rotateWireSessionID(deps, event.sessionID);
86
+ if (previous && previous !== next) {
87
+ void closeFreePiSession(deps, previous).catch(() => undefined);
88
+ }
89
+ previous = next;
90
+ const headers = new Headers(request.headers);
91
+ headers.set("x-session-id", next);
92
+ headers.delete("content-length");
93
+ headers.delete("host");
94
+ const response = await fetch(request.url, {
95
+ method: request.method,
96
+ headers,
97
+ body,
98
+ signal: request.signal,
99
+ }).catch(() => undefined);
100
+ if (!response)
101
+ continue;
102
+ if (!(await isConcurrent(response))) {
103
+ deps.log.info("free-pi session busy; replayed the request with a fresh session id", {
104
+ sessionID: event.sessionID,
105
+ from: request.headers.get("x-session-id") ?? undefined,
106
+ to: next,
107
+ attempt,
108
+ });
109
+ return response;
110
+ }
111
+ }
112
+ return undefined;
113
+ }
package/dist/state.d.ts CHANGED
@@ -34,6 +34,7 @@ export type RuntimeState = {
34
34
  lastSessionResetAt: number;
35
35
  freePiSessions: Set<string>;
36
36
  wireSessions: Map<string, string>;
37
+ replayBodies: Map<string, string>;
37
38
  finalizedSessions: Set<string>;
38
39
  activeExecutions: Set<string>;
39
40
  sessionActivity: Map<string, number>;
package/dist/state.js CHANGED
@@ -15,6 +15,7 @@ export function createRuntimeState() {
15
15
  lastSessionResetAt: 0,
16
16
  freePiSessions: new Set(),
17
17
  wireSessions: new Map(),
18
+ replayBodies: new Map(),
18
19
  finalizedSessions: new Set(),
19
20
  activeExecutions: new Set(),
20
21
  sessionActivity: new Map(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -13,6 +13,7 @@ const LONG_LIMIT_CODES = new Set([
13
13
  "global_cap",
14
14
  "premium_allowance",
15
15
  "guest_allowance",
16
+ "free_usage_limit",
16
17
  "concurrent_session",
17
18
  "model_requires_credits",
18
19
  "insufficient_credits",
@@ -26,6 +26,8 @@ const FREE_PI_ERROR_TEXT: Record<string, string> = {
26
26
  "Ads are not displaying for this account, so free completions are paused. Run `npx free-pi-cli@latest` so ads can show, then retry.",
27
27
  guest_allowance:
28
28
  "Guest trial used up; sign in with GitHub for a larger allowance.",
29
+ free_usage_limit:
30
+ "Free usage limit reached. Wait for the allowance to reset, switch models or add credits.",
29
31
  guest_unavailable: "Guest access is unavailable right now.",
30
32
  guest_login_required: "This needs a GitHub sign-in.",
31
33
  region_unavailable: "free-pi is not available in your region.",
@@ -25,8 +25,13 @@ import {
25
25
  rewriteContextOverflowResponse,
26
26
  rewriteLimitResponse,
27
27
  } from "../errors/limit.js";
28
+ import { parseFreePiError } from "../errors/parse.js";
28
29
  import { trimMap } from "../utils/async.js";
29
30
  import { watchFreePiNotice } from "./notices.js";
31
+ import {
32
+ rememberReplayBody,
33
+ replayConcurrentResponse,
34
+ } from "./replay.js";
30
35
  import { localTitle } from "./title.js";
31
36
  import { rememberFreePiSession } from "./track.js";
32
37
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
@@ -45,6 +50,7 @@ type SessionHookName =
45
50
  | "generate"
46
51
  | "title"
47
52
  | "model.request"
53
+ | "http.request"
48
54
  | "http.response"
49
55
  | "retry";
50
56
  type RequestKind = "primary" | "compaction" | "generate" | "title";
@@ -195,6 +201,49 @@ function isConcurrentFailure(error: any): boolean {
195
201
  );
196
202
  }
197
203
 
204
+ /**
205
+ * Limits and account blocks do not recover by retrying. pi's own retry helper
206
+ * treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
207
+ * OpenCode retries every 429 by default, which surfaces as an endless
208
+ * "Retrying…". The response rewrite turns most of these into a 400; this guard
209
+ * covers the rest and keeps the CLI's behavior.
210
+ */
211
+ const TERMINAL_RETRY_CODES = new Set([
212
+ "daily_cap",
213
+ "hourly_ceiling",
214
+ "rolling_cap",
215
+ "global_cap",
216
+ "account_ceiling",
217
+ "free_usage_limit",
218
+ "premium_allowance",
219
+ "guest_allowance",
220
+ "model_requires_credits",
221
+ "insufficient_credits",
222
+ "ads_required",
223
+ "account_review",
224
+ "region_unavailable",
225
+ "unauthorized",
226
+ "expired_token",
227
+ "guest_login_required",
228
+ "consent_required",
229
+ "upgrade_required",
230
+ "reward_required",
231
+ "content_filter",
232
+ "subagents_unavailable",
233
+ ]);
234
+
235
+ const TERMINAL_RETRY_PATTERN =
236
+ /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
237
+
238
+ function isTerminalFailure(error: any): boolean {
239
+ const parsed = parseFreePiError(error, true);
240
+ if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code)) return true;
241
+ const body =
242
+ typeof error?.response?.body === "string" ? error.response.body : "";
243
+ const message = typeof error?.message === "string" ? error.message : "";
244
+ return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
245
+ }
246
+
198
247
  /**
199
248
  * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
200
249
  * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
@@ -230,6 +279,10 @@ function applyRetryPolicy(deps: Deps, event: any): void {
230
279
  };
231
280
  return;
232
281
  }
282
+ if (isTerminalFailure(event.error)) {
283
+ event.decision = { retry: false };
284
+ return;
285
+ }
233
286
  if (event.attempt > RETRY_MAX_RETRIES + 1) {
234
287
  event.decision = { retry: false };
235
288
  return;
@@ -303,25 +356,38 @@ export async function registerSessionHooks(
303
356
  (event: any) => applyModelRequest(deps, event),
304
357
  registrations,
305
358
  );
359
+ await hookForProviders(
360
+ ctx,
361
+ "http.request",
362
+ (event: any) => rememberReplayBody(deps, event),
363
+ registrations,
364
+ );
306
365
  await hookForProviders(
307
366
  ctx,
308
367
  "http.response",
309
368
  async (event: any) => {
369
+ // Recover a per-session `429 concurrent` before OpenCode sees it: the
370
+ // step's prepared request is reused on retry, so rotating the id in the
371
+ // retry hook is too late for the failed attempt.
372
+ const replayed = await replayConcurrentResponse(deps, event).catch(
373
+ () => undefined,
374
+ );
375
+ const response = replayed ?? event.response;
310
376
  // Context overflow has to be handled first: a 429 context ceiling must
311
377
  // become a 400 overflow, not a friendly long-lived limit.
312
- const overflow = await rewriteContextOverflowResponse(
313
- event.response,
314
- ).catch(() => undefined);
378
+ const overflow = await rewriteContextOverflowResponse(response).catch(
379
+ () => undefined,
380
+ );
315
381
  if (overflow) {
316
382
  event.response = watchFreePiNotice(deps, overflow);
317
383
  return;
318
384
  }
319
- const rewritten = await rewriteLimitResponse(event.response).catch(
385
+ const rewritten = await rewriteLimitResponse(response).catch(
320
386
  () => undefined,
321
387
  );
322
388
  event.response = watchFreePiNotice(
323
389
  deps,
324
- rewritten ?? event.response,
390
+ rewritten ?? response,
325
391
  );
326
392
  },
327
393
  registrations,
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Transparently replays a free-pi request that hit the per-session
3
+ * `429 concurrent` limit.
4
+ *
5
+ * OpenCode builds the provider request once and reuses it for every retry of a
6
+ * step (`SessionRunner.runStep` calls `request.primary` outside the attempt
7
+ * loop). Rotating `x-session-id` in the retry hook therefore cannot help the
8
+ * failed attempt: the retried request still carries the old id. The server can
9
+ * also leave a session slot locked after an aborted stream, which resets do not
10
+ * clear.
11
+ *
12
+ * Replaying from `http.response` instead sends the same body with a fresh wire
13
+ * session id and returns the good response to OpenCode, so the turn continues
14
+ * without a visible "Retrying…" or a failed step.
15
+ */
16
+
17
+ import { closeFreePiSession } from "../api/session.js";
18
+ import type { Deps } from "../deps.js";
19
+ import { sleep, trimMap } from "../utils/async.js";
20
+ import { rotateWireSessionID, wireSessionID } from "./wire.js";
21
+
22
+ const REPLAY_BODY_LIMIT = 24;
23
+ const REPLAY_MAX_ATTEMPTS = 4;
24
+ const REPLAY_BASE_DELAY_MS = 400;
25
+ const REPLAY_MAX_DELAY_MS = 3_000;
26
+
27
+ function requestKey(sessionID: string, request: Request): string {
28
+ const turn = request.headers.get("x-turn-id") ?? "";
29
+ return `${sessionID}\u0000${turn}\u0000${request.url}`;
30
+ }
31
+
32
+ function isJson(request: Request): boolean {
33
+ return (request.headers.get("content-type") ?? "").includes("json");
34
+ }
35
+
36
+ /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
37
+ export async function rememberReplayBody(
38
+ deps: Deps,
39
+ event: any,
40
+ ): Promise<void> {
41
+ const request = event?.request;
42
+ if (!(request instanceof Request) || !isJson(request) || !event.sessionID)
43
+ return;
44
+ const key = requestKey(event.sessionID, request);
45
+ try {
46
+ const body = await request.clone().text();
47
+ if (!body) return;
48
+ deps.state.replayBodies.delete(key);
49
+ deps.state.replayBodies.set(key, body);
50
+ trimMap(deps.state.replayBodies, REPLAY_BODY_LIMIT);
51
+ } catch {
52
+ // A non-replayable body simply falls back to the normal retry hook.
53
+ }
54
+ }
55
+
56
+ async function isConcurrent(response: Response): Promise<boolean> {
57
+ if (response.status !== 429) return false;
58
+ const body = await response
59
+ .clone()
60
+ .text()
61
+ .catch(() => "");
62
+ return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
63
+ }
64
+
65
+ function concurrentDelay(attempt: number): number {
66
+ return Math.min(
67
+ REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1),
68
+ REPLAY_MAX_DELAY_MS,
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Returns a replacement response when a concurrent 429 was recovered, or
74
+ * `undefined` to leave the original response untouched.
75
+ */
76
+ export async function replayConcurrentResponse(
77
+ deps: Deps,
78
+ event: any,
79
+ ): Promise<Response | undefined> {
80
+ const original = event?.response;
81
+ const request = event?.request;
82
+ if (!(original instanceof Response) || !(request instanceof Request)) return;
83
+ if (!(await isConcurrent(original))) return;
84
+
85
+ const body =
86
+ deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
87
+ (isJson(request)
88
+ ? await request
89
+ .clone()
90
+ .text()
91
+ .catch(() => undefined)
92
+ : undefined);
93
+ if (!body) return;
94
+
95
+ let previous =
96
+ request.headers.get("x-session-id") ??
97
+ wireSessionID(deps, event.sessionID);
98
+
99
+ for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
100
+ if (attempt > 1) await sleep(concurrentDelay(attempt));
101
+ const next = rotateWireSessionID(deps, event.sessionID);
102
+ if (previous && previous !== next) {
103
+ void closeFreePiSession(deps, previous).catch(() => undefined);
104
+ }
105
+ previous = next;
106
+
107
+ const headers = new Headers(request.headers);
108
+ headers.set("x-session-id", next);
109
+ headers.delete("content-length");
110
+ headers.delete("host");
111
+
112
+ const response = await fetch(request.url, {
113
+ method: request.method,
114
+ headers,
115
+ body,
116
+ signal: request.signal,
117
+ }).catch(() => undefined);
118
+ if (!response) continue;
119
+ if (!(await isConcurrent(response))) {
120
+ deps.log.info(
121
+ "free-pi session busy; replayed the request with a fresh session id",
122
+ {
123
+ sessionID: event.sessionID,
124
+ from: request.headers.get("x-session-id") ?? undefined,
125
+ to: next,
126
+ attempt,
127
+ },
128
+ );
129
+ return response;
130
+ }
131
+ }
132
+ return undefined;
133
+ }
package/src/state.ts CHANGED
@@ -51,6 +51,7 @@ export type RuntimeState = {
51
51
 
52
52
  freePiSessions: Set<string>;
53
53
  wireSessions: Map<string, string>;
54
+ replayBodies: Map<string, string>;
54
55
  finalizedSessions: Set<string>;
55
56
  activeExecutions: Set<string>;
56
57
  sessionActivity: Map<string, number>;
@@ -79,6 +80,7 @@ export function createRuntimeState(): RuntimeState {
79
80
  lastSessionResetAt: 0,
80
81
  freePiSessions: new Set(),
81
82
  wireSessions: new Map(),
83
+ replayBodies: new Map(),
82
84
  finalizedSessions: new Set(),
83
85
  activeExecutions: new Set(),
84
86
  sessionActivity: new Map(),