@eduardo191labs/opencode-free-pi 0.3.9 → 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
@@ -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";
@@ -234,16 +235,22 @@ export async function registerSessionHooks(ctx, deps) {
234
235
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
235
236
  await hookForProviders(ctx, "title", generation("title"), registrations);
236
237
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
238
+ await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
237
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;
238
245
  // Context overflow has to be handled first: a 429 context ceiling must
239
246
  // become a 400 overflow, not a friendly long-lived limit.
240
- const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
247
+ const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
241
248
  if (overflow) {
242
249
  event.response = watchFreePiNotice(deps, overflow);
243
250
  return;
244
251
  }
245
- const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
246
- event.response = watchFreePiNotice(deps, rewritten ?? event.response);
252
+ const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
253
+ event.response = watchFreePiNotice(deps, rewritten ?? response);
247
254
  }, registrations);
248
255
  await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
249
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.9",
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",
@@ -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";
@@ -351,25 +356,38 @@ export async function registerSessionHooks(
351
356
  (event: any) => applyModelRequest(deps, event),
352
357
  registrations,
353
358
  );
359
+ await hookForProviders(
360
+ ctx,
361
+ "http.request",
362
+ (event: any) => rememberReplayBody(deps, event),
363
+ registrations,
364
+ );
354
365
  await hookForProviders(
355
366
  ctx,
356
367
  "http.response",
357
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;
358
376
  // Context overflow has to be handled first: a 429 context ceiling must
359
377
  // become a 400 overflow, not a friendly long-lived limit.
360
- const overflow = await rewriteContextOverflowResponse(
361
- event.response,
362
- ).catch(() => undefined);
378
+ const overflow = await rewriteContextOverflowResponse(response).catch(
379
+ () => undefined,
380
+ );
363
381
  if (overflow) {
364
382
  event.response = watchFreePiNotice(deps, overflow);
365
383
  return;
366
384
  }
367
- const rewritten = await rewriteLimitResponse(event.response).catch(
385
+ const rewritten = await rewriteLimitResponse(response).catch(
368
386
  () => undefined,
369
387
  );
370
388
  event.response = watchFreePiNotice(
371
389
  deps,
372
- rewritten ?? event.response,
390
+ rewritten ?? response,
373
391
  );
374
392
  },
375
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(),