@eduardo191labs/opencode-free-pi 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -155,12 +156,14 @@ Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
155
156
  diarios u horarios, créditos, cuenta bloqueada) se convierten en un 400 con el
156
157
  mensaje amigable y no se reintentan, igual que hace el CLI de pi; así OpenCode no
157
158
  muestra un «Retrying…» que nunca termina. El 429 `concurrent` («one request at a
158
- time») es la excepción: como el servidor puede dejar el slot de una sesión
159
- bloqueado, el plugin cambia el `x-session-id` de esa sesión, libera el anterior y
160
- reintenta hasta 6 veces con esperas de 1s a 15s. Si el catálogo asigna el
161
- experimento `compact100`, el plugin baja la ventana a 117 647 tokens para que
162
- OpenCode compacte al llegar a 100k, que es el mismo umbral que consigue
163
- `reserveTokens: 100000` en el CLI.
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.
164
167
 
165
168
  ## Rutas por plataforma
166
169
 
@@ -8,6 +8,7 @@ import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors
8
8
  import { parseFreePiError } from "../errors/parse.js";
9
9
  import { trimMap } from "../utils/async.js";
10
10
  import { watchFreePiNotice } from "./notices.js";
11
+ import { rememberReplayBody, replayConcurrentResponse, } from "./replay.js";
11
12
  import { localTitle } from "./title.js";
12
13
  import { rememberFreePiSession } from "./track.js";
13
14
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
@@ -152,6 +153,10 @@ const TERMINAL_RETRY_CODES = new Set([
152
153
  ]);
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;
154
155
  function isTerminalFailure(error) {
156
+ if (error?.type === "aborted" ||
157
+ /aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
158
+ return true;
159
+ }
155
160
  const parsed = parseFreePiError(error, true);
156
161
  if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
157
162
  return true;
@@ -234,16 +239,22 @@ export async function registerSessionHooks(ctx, deps) {
234
239
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
235
240
  await hookForProviders(ctx, "title", generation("title"), registrations);
236
241
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
242
+ await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
237
243
  await hookForProviders(ctx, "http.response", async (event) => {
244
+ // Recover a per-session `429 concurrent` before OpenCode sees it: the
245
+ // step's prepared request is reused on retry, so rotating the id in the
246
+ // retry hook is too late for the failed attempt.
247
+ const replayed = await replayConcurrentResponse(deps, event).catch(() => undefined);
248
+ const response = replayed ?? event.response;
238
249
  // Context overflow has to be handled first: a 429 context ceiling must
239
250
  // become a 400 overflow, not a friendly long-lived limit.
240
- const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
251
+ const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
241
252
  if (overflow) {
242
253
  event.response = watchFreePiNotice(deps, overflow);
243
254
  return;
244
255
  }
245
- const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
246
- event.response = watchFreePiNotice(deps, rewritten ?? event.response);
256
+ const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
257
+ event.response = watchFreePiNotice(deps, rewritten ?? response);
247
258
  }, registrations);
248
259
  await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
249
260
  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,117 @@
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 (request.signal.aborted)
70
+ return;
71
+ if (!(await isConcurrent(original)))
72
+ return;
73
+ const body = deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
74
+ (isJson(request)
75
+ ? await request
76
+ .clone()
77
+ .text()
78
+ .catch(() => undefined)
79
+ : undefined);
80
+ if (!body)
81
+ return;
82
+ let previous = request.headers.get("x-session-id") ??
83
+ wireSessionID(deps, event.sessionID);
84
+ for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
85
+ if (request.signal.aborted)
86
+ return;
87
+ if (attempt > 1)
88
+ await sleep(concurrentDelay(attempt));
89
+ const next = rotateWireSessionID(deps, event.sessionID);
90
+ if (previous && previous !== next) {
91
+ void closeFreePiSession(deps, previous).catch(() => undefined);
92
+ }
93
+ previous = next;
94
+ const headers = new Headers(request.headers);
95
+ headers.set("x-session-id", next);
96
+ headers.delete("content-length");
97
+ headers.delete("host");
98
+ const response = await fetch(request.url, {
99
+ method: request.method,
100
+ headers,
101
+ body,
102
+ signal: request.signal,
103
+ }).catch(() => undefined);
104
+ if (!response)
105
+ continue;
106
+ if (!(await isConcurrent(response))) {
107
+ deps.log.info("free-pi session busy; replayed the request with a fresh session id", {
108
+ sessionID: event.sessionID,
109
+ from: request.headers.get("x-session-id") ?? undefined,
110
+ to: next,
111
+ attempt,
112
+ });
113
+ return response;
114
+ }
115
+ }
116
+ return undefined;
117
+ }
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.9",
3
+ "version": "0.3.11",
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",
@@ -28,6 +28,10 @@ import {
28
28
  import { parseFreePiError } from "../errors/parse.js";
29
29
  import { trimMap } from "../utils/async.js";
30
30
  import { watchFreePiNotice } from "./notices.js";
31
+ import {
32
+ rememberReplayBody,
33
+ replayConcurrentResponse,
34
+ } from "./replay.js";
31
35
  import { localTitle } from "./title.js";
32
36
  import { rememberFreePiSession } from "./track.js";
33
37
  import { rotateWireSessionID, wireSessionID } from "./wire.js";
@@ -46,6 +50,7 @@ type SessionHookName =
46
50
  | "generate"
47
51
  | "title"
48
52
  | "model.request"
53
+ | "http.request"
49
54
  | "http.response"
50
55
  | "retry";
51
56
  type RequestKind = "primary" | "compaction" | "generate" | "title";
@@ -231,6 +236,14 @@ const TERMINAL_RETRY_PATTERN =
231
236
  /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
232
237
 
233
238
  function isTerminalFailure(error: any): boolean {
239
+ if (
240
+ error?.type === "aborted" ||
241
+ /aborted|cancelled|canceled|interrupted|AbortError/i.test(
242
+ `${error?.message ?? ""}`,
243
+ )
244
+ ) {
245
+ return true;
246
+ }
234
247
  const parsed = parseFreePiError(error, true);
235
248
  if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code)) return true;
236
249
  const body =
@@ -351,25 +364,38 @@ export async function registerSessionHooks(
351
364
  (event: any) => applyModelRequest(deps, event),
352
365
  registrations,
353
366
  );
367
+ await hookForProviders(
368
+ ctx,
369
+ "http.request",
370
+ (event: any) => rememberReplayBody(deps, event),
371
+ registrations,
372
+ );
354
373
  await hookForProviders(
355
374
  ctx,
356
375
  "http.response",
357
376
  async (event: any) => {
377
+ // Recover a per-session `429 concurrent` before OpenCode sees it: the
378
+ // step's prepared request is reused on retry, so rotating the id in the
379
+ // retry hook is too late for the failed attempt.
380
+ const replayed = await replayConcurrentResponse(deps, event).catch(
381
+ () => undefined,
382
+ );
383
+ const response = replayed ?? event.response;
358
384
  // Context overflow has to be handled first: a 429 context ceiling must
359
385
  // become a 400 overflow, not a friendly long-lived limit.
360
- const overflow = await rewriteContextOverflowResponse(
361
- event.response,
362
- ).catch(() => undefined);
386
+ const overflow = await rewriteContextOverflowResponse(response).catch(
387
+ () => undefined,
388
+ );
363
389
  if (overflow) {
364
390
  event.response = watchFreePiNotice(deps, overflow);
365
391
  return;
366
392
  }
367
- const rewritten = await rewriteLimitResponse(event.response).catch(
393
+ const rewritten = await rewriteLimitResponse(response).catch(
368
394
  () => undefined,
369
395
  );
370
396
  event.response = watchFreePiNotice(
371
397
  deps,
372
- rewritten ?? event.response,
398
+ rewritten ?? response,
373
399
  );
374
400
  },
375
401
  registrations,
@@ -0,0 +1,135 @@
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 (request.signal.aborted) return;
84
+ if (!(await isConcurrent(original))) return;
85
+
86
+ const body =
87
+ deps.state.replayBodies.get(requestKey(event.sessionID, request)) ??
88
+ (isJson(request)
89
+ ? await request
90
+ .clone()
91
+ .text()
92
+ .catch(() => undefined)
93
+ : undefined);
94
+ if (!body) return;
95
+
96
+ let previous =
97
+ request.headers.get("x-session-id") ??
98
+ wireSessionID(deps, event.sessionID);
99
+
100
+ for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
101
+ if (request.signal.aborted) return;
102
+ if (attempt > 1) await sleep(concurrentDelay(attempt));
103
+ const next = rotateWireSessionID(deps, event.sessionID);
104
+ if (previous && previous !== next) {
105
+ void closeFreePiSession(deps, previous).catch(() => undefined);
106
+ }
107
+ previous = next;
108
+
109
+ const headers = new Headers(request.headers);
110
+ headers.set("x-session-id", next);
111
+ headers.delete("content-length");
112
+ headers.delete("host");
113
+
114
+ const response = await fetch(request.url, {
115
+ method: request.method,
116
+ headers,
117
+ body,
118
+ signal: request.signal,
119
+ }).catch(() => undefined);
120
+ if (!response) continue;
121
+ if (!(await isConcurrent(response))) {
122
+ deps.log.info(
123
+ "free-pi session busy; replayed the request with a fresh session id",
124
+ {
125
+ sessionID: event.sessionID,
126
+ from: request.headers.get("x-session-id") ?? undefined,
127
+ to: next,
128
+ attempt,
129
+ },
130
+ );
131
+ return response;
132
+ }
133
+ }
134
+ return undefined;
135
+ }
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(),