@eduardo191labs/opencode-free-pi 0.3.6 → 0.3.8
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 +16 -3
- package/dist/catalog/v2.js +5 -4
- package/dist/constants.d.ts +8 -0
- package/dist/constants.js +8 -0
- package/dist/session/hooks.js +42 -4
- package/dist/session/track.js +4 -1
- package/dist/session/wire.d.ts +14 -0
- package/dist/session/wire.js +22 -0
- package/dist/state.d.ts +1 -0
- package/dist/state.js +1 -0
- package/package.json +1 -1
- package/src/catalog/v2.ts +5 -4
- package/src/constants.ts +9 -0
- package/src/session/hooks.ts +50 -3
- package/src/session/track.ts +6 -1
- package/src/session/wire.ts +27 -0
- package/src/state.ts +2 -0
package/README.md
CHANGED
|
@@ -78,6 +78,10 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
78
78
|
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
79
79
|
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
80
80
|
«New session».
|
|
81
|
+
- **Imágenes nativas**: los modelos aceptan imágenes pegadas o adjuntas.
|
|
82
|
+
El CLI las bloquea porque pi-ai no transporta imágenes, pero el endpoint de
|
|
83
|
+
chat de free-pi sí las acepta (verificado en vivo), así que OpenCode las
|
|
84
|
+
envía de forma nativa como partes `image_url`.
|
|
81
85
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
82
86
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
83
87
|
subagentes.
|
|
@@ -99,6 +103,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
99
103
|
plugin finaliza la sesión del proveedor cuando la ejecución del modelo
|
|
100
104
|
termina (éxito, fallo o interrupción) y al apagar OpenCode.
|
|
101
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.
|
|
102
111
|
- **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
|
|
103
112
|
models.dev se guardan en disco; si la red falla al arrancar se usan las copias
|
|
104
113
|
locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
|
|
@@ -142,9 +151,13 @@ consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
|
142
151
|
cuota y límite.
|
|
143
152
|
|
|
144
153
|
Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
|
|
145
|
-
`min(2s · 2^(n-1), 60s)`.
|
|
146
|
-
|
|
147
|
-
|
|
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.
|
|
148
161
|
|
|
149
162
|
## Rutas por plataforma
|
|
150
163
|
|
package/dist/catalog/v2.js
CHANGED
|
@@ -13,10 +13,11 @@ export function toV2Models(providerID, models) {
|
|
|
13
13
|
...(model.family ? { family: model.family } : {}),
|
|
14
14
|
capabilities: {
|
|
15
15
|
tools: model.tool_call !== false,
|
|
16
|
-
// The provider CLI registers every free-pi model as text-only
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
|
|
16
|
+
// The provider CLI registers every free-pi model as text-only because
|
|
17
|
+
// pi-ai cannot carry image parts, but the server's chat endpoint does
|
|
18
|
+
// accept OpenAI-style image_url parts (verified live), so OpenCode can
|
|
19
|
+
// attach images natively.
|
|
20
|
+
input: ["text", "image"],
|
|
20
21
|
output: ["text"],
|
|
21
22
|
...(model.temperature === undefined
|
|
22
23
|
? {}
|
package/dist/constants.d.ts
CHANGED
|
@@ -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;
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
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";
|
|
7
8
|
import { trimMap } from "../utils/async.js";
|
|
8
9
|
import { watchFreePiNotice } from "./notices.js";
|
|
9
10
|
import { localTitle } from "./title.js";
|
|
10
11
|
import { rememberFreePiSession } from "./track.js";
|
|
12
|
+
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
11
13
|
import { recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
12
14
|
import { rememberTrackedModel } from "./usage.js";
|
|
13
15
|
const PENDING_LIMIT = 400;
|
|
@@ -77,7 +79,7 @@ async function applyModelRequest(deps, event) {
|
|
|
77
79
|
const token = await resolveToken(deps);
|
|
78
80
|
if (token)
|
|
79
81
|
event.headers.authorization = `Bearer ${token}`;
|
|
80
|
-
event.headers["x-session-id"] = event.sessionID;
|
|
82
|
+
event.headers["x-session-id"] = wireSessionID(deps, event.sessionID);
|
|
81
83
|
event.headers["x-client-version"] = deps.state.latestClientVersion;
|
|
82
84
|
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
83
85
|
event.headers[SUBAGENT_HEADER] = "1";
|
|
@@ -107,12 +109,48 @@ async function applyModelRequest(deps, event) {
|
|
|
107
109
|
await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
|
|
108
110
|
}
|
|
109
111
|
}
|
|
112
|
+
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
113
|
+
function isConcurrentFailure(error) {
|
|
114
|
+
if (!error)
|
|
115
|
+
return false;
|
|
116
|
+
const body = typeof error.response?.body === "string" ? error.response.body : "";
|
|
117
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
118
|
+
return (/one request at a time/i.test(message) ||
|
|
119
|
+
/one request at a time/i.test(body) ||
|
|
120
|
+
/"concurrent"/.test(body));
|
|
121
|
+
}
|
|
110
122
|
/**
|
|
111
123
|
* pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
|
|
112
124
|
* `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
|
|
113
125
|
* Non-retryable decisions are left alone.
|
|
126
|
+
*
|
|
127
|
+
* The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
|
|
128
|
+
* and the server can leave a per-session lock behind that resets do not clear.
|
|
129
|
+
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
114
130
|
*/
|
|
115
|
-
function applyRetryPolicy(event) {
|
|
131
|
+
function applyRetryPolicy(deps, event) {
|
|
132
|
+
if (isConcurrentFailure(event.error)) {
|
|
133
|
+
if (event.attempt > CONCURRENT_RETRY_MAX) {
|
|
134
|
+
event.decision = { retry: false };
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const previous = wireSessionID(deps, event.sessionID);
|
|
138
|
+
const next = rotateWireSessionID(deps, event.sessionID);
|
|
139
|
+
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
140
|
+
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
141
|
+
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
142
|
+
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
143
|
+
sessionID: event.sessionID,
|
|
144
|
+
from: previous,
|
|
145
|
+
to: next,
|
|
146
|
+
attempt: event.attempt,
|
|
147
|
+
});
|
|
148
|
+
event.decision = {
|
|
149
|
+
retry: true,
|
|
150
|
+
delay: Math.min(CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1), CONCURRENT_RETRY_MAX_DELAY_MS),
|
|
151
|
+
};
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
116
154
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
117
155
|
event.decision = { retry: false };
|
|
118
156
|
return;
|
|
@@ -163,7 +201,7 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
163
201
|
const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
|
|
164
202
|
event.response = watchFreePiNotice(deps, rewritten ?? event.response);
|
|
165
203
|
}, registrations);
|
|
166
|
-
await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(event), registrations);
|
|
204
|
+
await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
|
|
167
205
|
await registerToolHooks(ctx, deps, registrations);
|
|
168
206
|
return registrations;
|
|
169
207
|
}
|
package/dist/session/track.js
CHANGED
|
@@ -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
|
-
|
|
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
package/package.json
CHANGED
package/src/catalog/v2.ts
CHANGED
|
@@ -32,10 +32,11 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
|
|
|
32
32
|
...(model.family ? { family: model.family } : {}),
|
|
33
33
|
capabilities: {
|
|
34
34
|
tools: model.tool_call !== false,
|
|
35
|
-
// The provider CLI registers every free-pi model as text-only
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
35
|
+
// The provider CLI registers every free-pi model as text-only because
|
|
36
|
+
// pi-ai cannot carry image parts, but the server's chat endpoint does
|
|
37
|
+
// accept OpenAI-style image_url parts (verified live), so OpenCode can
|
|
38
|
+
// attach images natively.
|
|
39
|
+
input: ["text", "image"],
|
|
39
40
|
output: ["text"],
|
|
40
41
|
...(model.temperature === undefined
|
|
41
42
|
? {}
|
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;
|
package/src/session/hooks.ts
CHANGED
|
@@ -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,6 +20,7 @@ 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,
|
|
@@ -25,6 +29,7 @@ import { trimMap } from "../utils/async.js";
|
|
|
25
29
|
import { watchFreePiNotice } from "./notices.js";
|
|
26
30
|
import { localTitle } from "./title.js";
|
|
27
31
|
import { rememberFreePiSession } from "./track.js";
|
|
32
|
+
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
28
33
|
import {
|
|
29
34
|
recordCompaction,
|
|
30
35
|
recordToolEnd,
|
|
@@ -136,7 +141,7 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
136
141
|
event.headers ??= {};
|
|
137
142
|
const token = await resolveToken(deps);
|
|
138
143
|
if (token) event.headers.authorization = `Bearer ${token}`;
|
|
139
|
-
event.headers["x-session-id"] = event.sessionID;
|
|
144
|
+
event.headers["x-session-id"] = wireSessionID(deps, event.sessionID);
|
|
140
145
|
event.headers["x-client-version"] = deps.state.latestClientVersion;
|
|
141
146
|
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
142
147
|
event.headers[SUBAGENT_HEADER] = "1";
|
|
@@ -177,12 +182,54 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
177
182
|
}
|
|
178
183
|
}
|
|
179
184
|
|
|
185
|
+
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
186
|
+
function isConcurrentFailure(error: any): boolean {
|
|
187
|
+
if (!error) return false;
|
|
188
|
+
const body =
|
|
189
|
+
typeof error.response?.body === "string" ? error.response.body : "";
|
|
190
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
191
|
+
return (
|
|
192
|
+
/one request at a time/i.test(message) ||
|
|
193
|
+
/one request at a time/i.test(body) ||
|
|
194
|
+
/"concurrent"/.test(body)
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
180
198
|
/**
|
|
181
199
|
* pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
|
|
182
200
|
* `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
|
|
183
201
|
* Non-retryable decisions are left alone.
|
|
202
|
+
*
|
|
203
|
+
* The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
|
|
204
|
+
* and the server can leave a per-session lock behind that resets do not clear.
|
|
205
|
+
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
184
206
|
*/
|
|
185
|
-
function applyRetryPolicy(event: any): void {
|
|
207
|
+
function applyRetryPolicy(deps: Deps, event: any): void {
|
|
208
|
+
if (isConcurrentFailure(event.error)) {
|
|
209
|
+
if (event.attempt > CONCURRENT_RETRY_MAX) {
|
|
210
|
+
event.decision = { retry: false };
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const previous = wireSessionID(deps, event.sessionID);
|
|
214
|
+
const next = rotateWireSessionID(deps, event.sessionID);
|
|
215
|
+
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
216
|
+
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
217
|
+
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
218
|
+
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
219
|
+
sessionID: event.sessionID,
|
|
220
|
+
from: previous,
|
|
221
|
+
to: next,
|
|
222
|
+
attempt: event.attempt,
|
|
223
|
+
});
|
|
224
|
+
event.decision = {
|
|
225
|
+
retry: true,
|
|
226
|
+
delay: Math.min(
|
|
227
|
+
CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1),
|
|
228
|
+
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
229
|
+
),
|
|
230
|
+
};
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
186
233
|
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
187
234
|
event.decision = { retry: false };
|
|
188
235
|
return;
|
|
@@ -282,7 +329,7 @@ export async function registerSessionHooks(
|
|
|
282
329
|
await hookForProviders(
|
|
283
330
|
ctx,
|
|
284
331
|
"retry",
|
|
285
|
-
(event: any) => applyRetryPolicy(event),
|
|
332
|
+
(event: any) => applyRetryPolicy(deps, event),
|
|
286
333
|
registrations,
|
|
287
334
|
);
|
|
288
335
|
await registerToolHooks(ctx, deps, registrations);
|
package/src/session/track.ts
CHANGED
|
@@ -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
|
-
|
|
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(),
|