@eduardo191labs/opencode-free-pi 0.3.7 → 0.3.9

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
@@ -103,6 +103,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
103
103
  plugin finaliza la sesión del proveedor cuando la ejecución del modelo
104
104
  termina (éxito, fallo o interrupción) y al apagar OpenCode.
105
105
  - Recuperación automática del límite de sesiones concurrentes.
106
+ - **Recuperación de `concurrent`**: free-pi admite una sola petición en vuelo por
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.
106
111
  - **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
107
112
  models.dev se guardan en disco; si la red falla al arrancar se usan las copias
108
113
  locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
@@ -146,9 +151,16 @@ consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
146
151
  cuota y límite.
147
152
 
148
153
  Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
149
- `min(2s · 2^(n-1), 60s)`. Si el catálogo asigna el experimento `compact100`, el
150
- plugin baja la ventana a 117 647 tokens para que OpenCode compacte al llegar a
151
- 100k, que es el mismo umbral que consigue `reserveTokens: 100000` en el CLI.
154
+ `min(2s · 2^(n-1), 60s)`. Los límites terminales (`free_usage_limit`, cupos
155
+ diarios u horarios, créditos, cuenta bloqueada) se convierten en un 400 con el
156
+ mensaje amigable y no se reintentan, igual que hace el CLI de pi; así OpenCode no
157
+ 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.
152
164
 
153
165
  ## Rutas por plataforma
154
166
 
@@ -28,6 +28,14 @@ export declare const CHUNK_TIMEOUT_MS = 300000;
28
28
  export declare const RETRY_MAX_RETRIES = 3;
29
29
  export declare const RETRY_BASE_DELAY_MS = 2000;
30
30
  export declare const RETRY_MAX_DELAY_MS = 60000;
31
+ /**
32
+ * free-pi allows one in-flight request per `x-session-id` and answers a second
33
+ * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
34
+ * can leak server-side, so the plugin rotates the wire session id and retries.
35
+ */
36
+ export declare const CONCURRENT_RETRY_MAX = 6;
37
+ export declare const CONCURRENT_RETRY_BASE_MS = 1000;
38
+ export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
31
39
  /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
32
40
  export declare const CACHE_TTL_MS: number;
33
41
  export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
package/dist/constants.js CHANGED
@@ -33,6 +33,14 @@ export const CHUNK_TIMEOUT_MS = 300_000;
33
33
  export const RETRY_MAX_RETRIES = 3;
34
34
  export const RETRY_BASE_DELAY_MS = 2_000;
35
35
  export const RETRY_MAX_DELAY_MS = 60_000;
36
+ /**
37
+ * free-pi allows one in-flight request per `x-session-id` and answers a second
38
+ * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
39
+ * can leak server-side, so the plugin rotates the wire session id and retries.
40
+ */
41
+ export const CONCURRENT_RETRY_MAX = 6;
42
+ export const CONCURRENT_RETRY_BASE_MS = 1_000;
43
+ export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
36
44
  /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
37
45
  export const CACHE_TTL_MS = 5 * 60_000;
38
46
  export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
@@ -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.",
@@ -2,12 +2,15 @@
2
2
  import { ensureAdImpression } from "../ads/impression.js";
3
3
  import { resolveAdTurn } from "../ads/resolve.js";
4
4
  import { resolveToken } from "../auth/token.js";
5
- import { COST_EXPERIMENT_HEADER, 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";
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
+ import { closeFreePiSession } from "../api/session.js";
6
7
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
8
+ import { parseFreePiError } from "../errors/parse.js";
7
9
  import { trimMap } from "../utils/async.js";
8
10
  import { watchFreePiNotice } from "./notices.js";
9
11
  import { localTitle } from "./title.js";
10
12
  import { rememberFreePiSession } from "./track.js";
13
+ import { rotateWireSessionID, wireSessionID } from "./wire.js";
11
14
  import { recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
12
15
  import { rememberTrackedModel } from "./usage.js";
13
16
  const PENDING_LIMIT = 400;
@@ -77,7 +80,7 @@ async function applyModelRequest(deps, event) {
77
80
  const token = await resolveToken(deps);
78
81
  if (token)
79
82
  event.headers.authorization = `Bearer ${token}`;
80
- event.headers["x-session-id"] = event.sessionID;
83
+ event.headers["x-session-id"] = wireSessionID(deps, event.sessionID);
81
84
  event.headers["x-client-version"] = deps.state.latestClientVersion;
82
85
  if (deps.state.subagentSessions.has(event.sessionID)) {
83
86
  event.headers[SUBAGENT_HEADER] = "1";
@@ -107,12 +110,91 @@ async function applyModelRequest(deps, event) {
107
110
  await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
108
111
  }
109
112
  }
113
+ /** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
114
+ function isConcurrentFailure(error) {
115
+ if (!error)
116
+ return false;
117
+ const body = typeof error.response?.body === "string" ? error.response.body : "";
118
+ const message = typeof error.message === "string" ? error.message : "";
119
+ return (/one request at a time/i.test(message) ||
120
+ /one request at a time/i.test(body) ||
121
+ /"concurrent"/.test(body));
122
+ }
123
+ /**
124
+ * Limits and account blocks do not recover by retrying. pi's own retry helper
125
+ * treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
126
+ * OpenCode retries every 429 by default, which surfaces as an endless
127
+ * "Retrying…". The response rewrite turns most of these into a 400; this guard
128
+ * covers the rest and keeps the CLI's behavior.
129
+ */
130
+ const TERMINAL_RETRY_CODES = new Set([
131
+ "daily_cap",
132
+ "hourly_ceiling",
133
+ "rolling_cap",
134
+ "global_cap",
135
+ "account_ceiling",
136
+ "free_usage_limit",
137
+ "premium_allowance",
138
+ "guest_allowance",
139
+ "model_requires_credits",
140
+ "insufficient_credits",
141
+ "ads_required",
142
+ "account_review",
143
+ "region_unavailable",
144
+ "unauthorized",
145
+ "expired_token",
146
+ "guest_login_required",
147
+ "consent_required",
148
+ "upgrade_required",
149
+ "reward_required",
150
+ "content_filter",
151
+ "subagents_unavailable",
152
+ ]);
153
+ 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
+ function isTerminalFailure(error) {
155
+ const parsed = parseFreePiError(error, true);
156
+ if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
157
+ return true;
158
+ const body = typeof error?.response?.body === "string" ? error.response.body : "";
159
+ const message = typeof error?.message === "string" ? error.message : "";
160
+ return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
161
+ }
110
162
  /**
111
163
  * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
112
164
  * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
113
165
  * Non-retryable decisions are left alone.
166
+ *
167
+ * The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
168
+ * and the server can leave a per-session lock behind that resets do not clear.
169
+ * Rotating the wire session id and retrying turns that into a normal retry.
114
170
  */
115
- function applyRetryPolicy(event) {
171
+ function applyRetryPolicy(deps, event) {
172
+ if (isConcurrentFailure(event.error)) {
173
+ if (event.attempt > CONCURRENT_RETRY_MAX) {
174
+ event.decision = { retry: false };
175
+ return;
176
+ }
177
+ const previous = wireSessionID(deps, event.sessionID);
178
+ const next = rotateWireSessionID(deps, event.sessionID);
179
+ // Releasing the old id cleans up an orphaned slot; a leaked live lock
180
+ // ignores reset, which is exactly why the next request uses a fresh id.
181
+ void closeFreePiSession(deps, previous).catch(() => undefined);
182
+ deps.log.info("free-pi session busy; retrying with a fresh session id", {
183
+ sessionID: event.sessionID,
184
+ from: previous,
185
+ to: next,
186
+ attempt: event.attempt,
187
+ });
188
+ event.decision = {
189
+ retry: true,
190
+ delay: Math.min(CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1), CONCURRENT_RETRY_MAX_DELAY_MS),
191
+ };
192
+ return;
193
+ }
194
+ if (isTerminalFailure(event.error)) {
195
+ event.decision = { retry: false };
196
+ return;
197
+ }
116
198
  if (event.attempt > RETRY_MAX_RETRIES + 1) {
117
199
  event.decision = { retry: false };
118
200
  return;
@@ -163,7 +245,7 @@ export async function registerSessionHooks(ctx, deps) {
163
245
  const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
164
246
  event.response = watchFreePiNotice(deps, rewritten ?? event.response);
165
247
  }, registrations);
166
- await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(event), registrations);
248
+ await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
167
249
  await registerToolHooks(ctx, deps, registrations);
168
250
  return registrations;
169
251
  }
@@ -10,6 +10,7 @@
10
10
  import { closeFreePiSession } from "../api/session.js";
11
11
  import { SESSION_FINALIZE_DELAY_MS, SESSION_TRACK_LIMIT, } from "../constants.js";
12
12
  import { trimMap, trimSet } from "../utils/async.js";
13
+ import { forgetWireSessionID, wireSessionID } from "./wire.js";
13
14
  export function rememberFreePiSession(deps, sessionID) {
14
15
  if (!sessionID)
15
16
  return;
@@ -93,7 +94,8 @@ export async function finalizeFreePiSession(deps, sessionID) {
93
94
  deps.state.finalizedSessions.delete(sessionID);
94
95
  deps.state.finalizedSessions.add(sessionID);
95
96
  trimSet(deps.state.finalizedSessions, SESSION_TRACK_LIMIT);
96
- await closeFreePiSession(deps, sessionID).catch(() => undefined);
97
+ // Release the id the session actually sent; a rotated id may be the live one.
98
+ await closeFreePiSession(deps, wireSessionID(deps, sessionID)).catch(() => undefined);
97
99
  }
98
100
  export function forgetFreePiSession(deps, sessionID) {
99
101
  if (!sessionID)
@@ -104,4 +106,5 @@ export function forgetFreePiSession(deps, sessionID) {
104
106
  deps.state.activeExecutions.delete(sessionID);
105
107
  deps.state.sessionActivity.delete(sessionID);
106
108
  deps.state.trackedModels.delete(sessionID);
109
+ forgetWireSessionID(deps, sessionID);
107
110
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Tracks the `x-session-id` each OpenCode session sends to free-pi.
3
+ *
4
+ * free-pi admits one in-flight request per wire session id. The server can
5
+ * leave a per-session lock behind after a crashed or aborted stream, and a new
6
+ * request on the same id then fails with `429 concurrent` forever: resets do
7
+ * not clear it. Rotating the wire id is the recovery, so the plugin keeps the
8
+ * mapping until the OpenCode session is gone.
9
+ */
10
+ import type { Deps } from "../deps.js";
11
+ export declare function wireSessionID(deps: Deps, sessionID: string): string;
12
+ /** Points the OpenCode session at a fresh wire id and returns it. */
13
+ export declare function rotateWireSessionID(deps: Deps, sessionID: string): string;
14
+ export declare function forgetWireSessionID(deps: Deps, sessionID: string): void;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Tracks the `x-session-id` each OpenCode session sends to free-pi.
3
+ *
4
+ * free-pi admits one in-flight request per wire session id. The server can
5
+ * leave a per-session lock behind after a crashed or aborted stream, and a new
6
+ * request on the same id then fails with `429 concurrent` forever: resets do
7
+ * not clear it. Rotating the wire id is the recovery, so the plugin keeps the
8
+ * mapping until the OpenCode session is gone.
9
+ */
10
+ export function wireSessionID(deps, sessionID) {
11
+ return deps.state.wireSessions.get(sessionID) ?? sessionID;
12
+ }
13
+ /** Points the OpenCode session at a fresh wire id and returns it. */
14
+ export function rotateWireSessionID(deps, sessionID) {
15
+ const suffix = Math.random().toString(36).slice(2, 10);
16
+ const next = `${sessionID}-r${suffix}`;
17
+ deps.state.wireSessions.set(sessionID, next);
18
+ return next;
19
+ }
20
+ export function forgetWireSessionID(deps, sessionID) {
21
+ deps.state.wireSessions.delete(sessionID);
22
+ }
package/dist/state.d.ts CHANGED
@@ -33,6 +33,7 @@ export type RuntimeState = {
33
33
  sessionResetPromise?: Promise<SessionResetOutcome>;
34
34
  lastSessionResetAt: number;
35
35
  freePiSessions: Set<string>;
36
+ wireSessions: Map<string, string>;
36
37
  finalizedSessions: Set<string>;
37
38
  activeExecutions: Set<string>;
38
39
  sessionActivity: Map<string, number>;
package/dist/state.js CHANGED
@@ -14,6 +14,7 @@ export function createRuntimeState() {
14
14
  sessionClosePromises: new Map(),
15
15
  lastSessionResetAt: 0,
16
16
  freePiSessions: new Set(),
17
+ wireSessions: new Map(),
17
18
  finalizedSessions: new Set(),
18
19
  activeExecutions: new Set(),
19
20
  sessionActivity: new Map(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
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",
package/src/constants.ts CHANGED
@@ -43,6 +43,15 @@ export const RETRY_MAX_RETRIES = 3;
43
43
  export const RETRY_BASE_DELAY_MS = 2_000;
44
44
  export const RETRY_MAX_DELAY_MS = 60_000;
45
45
 
46
+ /**
47
+ * free-pi allows one in-flight request per `x-session-id` and answers a second
48
+ * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
49
+ * can leak server-side, so the plugin rotates the wire session id and retries.
50
+ */
51
+ export const CONCURRENT_RETRY_MAX = 6;
52
+ export const CONCURRENT_RETRY_BASE_MS = 1_000;
53
+ export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
54
+
46
55
  /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
47
56
  export const CACHE_TTL_MS = 5 * 60_000;
48
57
  export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
@@ -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.",
@@ -7,6 +7,9 @@ import type { AdTurn } from "../types.js";
7
7
  import { resolveToken } from "../auth/token.js";
8
8
  import {
9
9
  COST_EXPERIMENT_HEADER,
10
+ CONCURRENT_RETRY_BASE_MS,
11
+ CONCURRENT_RETRY_MAX,
12
+ CONCURRENT_RETRY_MAX_DELAY_MS,
10
13
  DEFENSE_PROVIDER_ID,
11
14
  EFFICIENCY_RULE,
12
15
  MAX_OUTPUT_TOKENS,
@@ -17,14 +20,17 @@ import {
17
20
  SUBAGENT_HEADER,
18
21
  } from "../constants.js";
19
22
  import type { Deps } from "../deps.js";
23
+ import { closeFreePiSession } from "../api/session.js";
20
24
  import {
21
25
  rewriteContextOverflowResponse,
22
26
  rewriteLimitResponse,
23
27
  } from "../errors/limit.js";
28
+ import { parseFreePiError } from "../errors/parse.js";
24
29
  import { trimMap } from "../utils/async.js";
25
30
  import { watchFreePiNotice } from "./notices.js";
26
31
  import { localTitle } from "./title.js";
27
32
  import { rememberFreePiSession } from "./track.js";
33
+ import { rotateWireSessionID, wireSessionID } from "./wire.js";
28
34
  import {
29
35
  recordCompaction,
30
36
  recordToolEnd,
@@ -136,7 +142,7 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
136
142
  event.headers ??= {};
137
143
  const token = await resolveToken(deps);
138
144
  if (token) event.headers.authorization = `Bearer ${token}`;
139
- event.headers["x-session-id"] = event.sessionID;
145
+ event.headers["x-session-id"] = wireSessionID(deps, event.sessionID);
140
146
  event.headers["x-client-version"] = deps.state.latestClientVersion;
141
147
  if (deps.state.subagentSessions.has(event.sessionID)) {
142
148
  event.headers[SUBAGENT_HEADER] = "1";
@@ -177,12 +183,101 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
177
183
  }
178
184
  }
179
185
 
186
+ /** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
187
+ function isConcurrentFailure(error: any): boolean {
188
+ if (!error) return false;
189
+ const body =
190
+ typeof error.response?.body === "string" ? error.response.body : "";
191
+ const message = typeof error.message === "string" ? error.message : "";
192
+ return (
193
+ /one request at a time/i.test(message) ||
194
+ /one request at a time/i.test(body) ||
195
+ /"concurrent"/.test(body)
196
+ );
197
+ }
198
+
199
+ /**
200
+ * Limits and account blocks do not recover by retrying. pi's own retry helper
201
+ * treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
202
+ * OpenCode retries every 429 by default, which surfaces as an endless
203
+ * "Retrying…". The response rewrite turns most of these into a 400; this guard
204
+ * covers the rest and keeps the CLI's behavior.
205
+ */
206
+ const TERMINAL_RETRY_CODES = new Set([
207
+ "daily_cap",
208
+ "hourly_ceiling",
209
+ "rolling_cap",
210
+ "global_cap",
211
+ "account_ceiling",
212
+ "free_usage_limit",
213
+ "premium_allowance",
214
+ "guest_allowance",
215
+ "model_requires_credits",
216
+ "insufficient_credits",
217
+ "ads_required",
218
+ "account_review",
219
+ "region_unavailable",
220
+ "unauthorized",
221
+ "expired_token",
222
+ "guest_login_required",
223
+ "consent_required",
224
+ "upgrade_required",
225
+ "reward_required",
226
+ "content_filter",
227
+ "subagents_unavailable",
228
+ ]);
229
+
230
+ const TERMINAL_RETRY_PATTERN =
231
+ /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
232
+
233
+ function isTerminalFailure(error: any): boolean {
234
+ const parsed = parseFreePiError(error, true);
235
+ if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code)) return true;
236
+ const body =
237
+ typeof error?.response?.body === "string" ? error.response.body : "";
238
+ const message = typeof error?.message === "string" ? error.message : "";
239
+ return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
240
+ }
241
+
180
242
  /**
181
243
  * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
182
244
  * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
183
245
  * Non-retryable decisions are left alone.
246
+ *
247
+ * The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
248
+ * and the server can leave a per-session lock behind that resets do not clear.
249
+ * Rotating the wire session id and retrying turns that into a normal retry.
184
250
  */
185
- function applyRetryPolicy(event: any): void {
251
+ function applyRetryPolicy(deps: Deps, event: any): void {
252
+ if (isConcurrentFailure(event.error)) {
253
+ if (event.attempt > CONCURRENT_RETRY_MAX) {
254
+ event.decision = { retry: false };
255
+ return;
256
+ }
257
+ const previous = wireSessionID(deps, event.sessionID);
258
+ const next = rotateWireSessionID(deps, event.sessionID);
259
+ // Releasing the old id cleans up an orphaned slot; a leaked live lock
260
+ // ignores reset, which is exactly why the next request uses a fresh id.
261
+ void closeFreePiSession(deps, previous).catch(() => undefined);
262
+ deps.log.info("free-pi session busy; retrying with a fresh session id", {
263
+ sessionID: event.sessionID,
264
+ from: previous,
265
+ to: next,
266
+ attempt: event.attempt,
267
+ });
268
+ event.decision = {
269
+ retry: true,
270
+ delay: Math.min(
271
+ CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1),
272
+ CONCURRENT_RETRY_MAX_DELAY_MS,
273
+ ),
274
+ };
275
+ return;
276
+ }
277
+ if (isTerminalFailure(event.error)) {
278
+ event.decision = { retry: false };
279
+ return;
280
+ }
186
281
  if (event.attempt > RETRY_MAX_RETRIES + 1) {
187
282
  event.decision = { retry: false };
188
283
  return;
@@ -282,7 +377,7 @@ export async function registerSessionHooks(
282
377
  await hookForProviders(
283
378
  ctx,
284
379
  "retry",
285
- (event: any) => applyRetryPolicy(event),
380
+ (event: any) => applyRetryPolicy(deps, event),
286
381
  registrations,
287
382
  );
288
383
  await registerToolHooks(ctx, deps, registrations);
@@ -15,6 +15,7 @@ import {
15
15
  } from "../constants.js";
16
16
  import type { Deps } from "../deps.js";
17
17
  import { trimMap, trimSet } from "../utils/async.js";
18
+ import { forgetWireSessionID, wireSessionID } from "./wire.js";
18
19
 
19
20
  export function rememberFreePiSession(deps: Deps, sessionID: string): void {
20
21
  if (!sessionID) return;
@@ -110,7 +111,10 @@ export async function finalizeFreePiSession(
110
111
  deps.state.finalizedSessions.delete(sessionID);
111
112
  deps.state.finalizedSessions.add(sessionID);
112
113
  trimSet(deps.state.finalizedSessions, SESSION_TRACK_LIMIT);
113
- await closeFreePiSession(deps, sessionID).catch(() => undefined);
114
+ // Release the id the session actually sent; a rotated id may be the live one.
115
+ await closeFreePiSession(deps, wireSessionID(deps, sessionID)).catch(
116
+ () => undefined,
117
+ );
114
118
  }
115
119
 
116
120
  export function forgetFreePiSession(deps: Deps, sessionID: string): void {
@@ -121,4 +125,5 @@ export function forgetFreePiSession(deps: Deps, sessionID: string): void {
121
125
  deps.state.activeExecutions.delete(sessionID);
122
126
  deps.state.sessionActivity.delete(sessionID);
123
127
  deps.state.trackedModels.delete(sessionID);
128
+ forgetWireSessionID(deps, sessionID);
124
129
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Tracks the `x-session-id` each OpenCode session sends to free-pi.
3
+ *
4
+ * free-pi admits one in-flight request per wire session id. The server can
5
+ * leave a per-session lock behind after a crashed or aborted stream, and a new
6
+ * request on the same id then fails with `429 concurrent` forever: resets do
7
+ * not clear it. Rotating the wire id is the recovery, so the plugin keeps the
8
+ * mapping until the OpenCode session is gone.
9
+ */
10
+
11
+ import type { Deps } from "../deps.js";
12
+
13
+ export function wireSessionID(deps: Deps, sessionID: string): string {
14
+ return deps.state.wireSessions.get(sessionID) ?? sessionID;
15
+ }
16
+
17
+ /** Points the OpenCode session at a fresh wire id and returns it. */
18
+ export function rotateWireSessionID(deps: Deps, sessionID: string): string {
19
+ const suffix = Math.random().toString(36).slice(2, 10);
20
+ const next = `${sessionID}-r${suffix}`;
21
+ deps.state.wireSessions.set(sessionID, next);
22
+ return next;
23
+ }
24
+
25
+ export function forgetWireSessionID(deps: Deps, sessionID: string): void {
26
+ deps.state.wireSessions.delete(sessionID);
27
+ }
package/src/state.ts CHANGED
@@ -50,6 +50,7 @@ export type RuntimeState = {
50
50
  lastSessionResetAt: number;
51
51
 
52
52
  freePiSessions: Set<string>;
53
+ wireSessions: Map<string, string>;
53
54
  finalizedSessions: Set<string>;
54
55
  activeExecutions: Set<string>;
55
56
  sessionActivity: Map<string, number>;
@@ -77,6 +78,7 @@ export function createRuntimeState(): RuntimeState {
77
78
  sessionClosePromises: new Map(),
78
79
  lastSessionResetAt: 0,
79
80
  freePiSessions: new Set(),
81
+ wireSessions: new Map(),
80
82
  finalizedSessions: new Set(),
81
83
  activeExecutions: new Set(),
82
84
  sessionActivity: new Map(),