@eduardo191labs/opencode-free-pi 0.7.27 → 0.7.29
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 +27 -39
- package/dist/constants.d.ts +0 -22
- package/dist/constants.js +0 -22
- package/dist/index.d.ts +1 -1
- package/dist/session/events.js +5 -12
- package/dist/session/hooks.js +9 -185
- package/dist/session/track.d.ts +2 -0
- package/dist/session/track.js +5 -0
- package/dist/state.d.ts +1 -3
- package/package.json +2 -2
- package/src/constants.ts +0 -25
- package/src/index.ts +0 -1
- package/src/session/events.ts +5 -12
- package/src/session/hooks.ts +8 -224
- package/src/session/track.ts +11 -0
- package/src/state.ts +0 -3
- package/dist/session/title.d.ts +0 -18
- package/dist/session/title.js +0 -81
- package/dist/session/usage.d.ts +0 -5
- package/dist/session/usage.js +0 -32
- package/src/session/title.ts +0 -90
- package/src/session/usage.ts +0 -46
package/README.md
CHANGED
|
@@ -87,10 +87,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
87
87
|
que OpenCode compacte una vez y, si el rechazo se repite, devuelve un error de
|
|
88
88
|
proveedor que OpenCode no clasifica como desbordamiento, para no gastar
|
|
89
89
|
créditos en resúmenes que no arreglan nada.
|
|
90
|
-
- **Títulos
|
|
91
|
-
El plugin
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
- **Títulos de OpenCode**: el agente de títulos, su prompt y su modelo son de
|
|
91
|
+
OpenCode. El plugin no intercepta la petición ni reemplaza el resultado
|
|
92
|
+
(`ctx.session.hook("title")` no se registra), y solo evita pedir un anuncio
|
|
93
|
+
para una petición que el usuario nunca ve. El gateway se validó en vivo con
|
|
94
|
+
la petición de título: responde 200 con un título limpio.
|
|
94
95
|
- **Capacidades según el modelo**: los modelos gratuitos aceptan imágenes de
|
|
95
96
|
entrada de forma nativa; se comprobó con `curl_cffi` contra el gateway y los
|
|
96
97
|
cuatro transcriben una captura adjunta. Los alias de pago anuncian lo que
|
|
@@ -389,9 +390,9 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
389
390
|
- **Modelo**: `authorization`, `x-session-id`, `x-client-version` y
|
|
390
391
|
`x-turn-id`. Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
391
392
|
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
392
|
-
salida y truncado de las últimas llamadas)
|
|
393
|
-
herramientas fallidas) y
|
|
394
|
-
|
|
393
|
+
salida y truncado de las últimas llamadas) y `x-freepi-tool-errors` (IDs de
|
|
394
|
+
herramientas fallidas). El historial y su compactación son de OpenCode: el
|
|
395
|
+
plugin no pliega mensajes ni envía marcadores de compactación.
|
|
395
396
|
- **Catálogo** (`/client-version`): `authorization`.
|
|
396
397
|
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
397
398
|
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
@@ -408,49 +409,36 @@ se reescriben a un `400` con el texto que OpenCode clasifica como
|
|
|
408
409
|
desbordamiento de contexto, para que dispare la compactación automática.
|
|
409
410
|
|
|
410
411
|
El plugin mide el cuerpo de cada petición rechazada. Cuando el rechazo llega
|
|
411
|
-
con un cuerpo que no puede agotar la ventana, lo
|
|
412
|
-
proveedor
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
412
|
+
con un cuerpo que no puede agotar la ventana, lo clasifica como fallo del
|
|
413
|
+
proveedor y devuelve un `400` con un mensaje de error: ese texto no coincide con
|
|
414
|
+
el patrón de desbordamiento de OpenCode, así que el runner deja de compactar en
|
|
415
|
+
lugar de entrar en un ciclo de resúmenes que no reducen nada. El plugin nunca
|
|
416
|
+
reenvía la petición ni recorta el historial.
|
|
416
417
|
|
|
417
418
|
Cuando el rechazo sí corresponde a una conversación larga, el tamaño medido se
|
|
418
419
|
guarda como `rejectedPromptTokens` del modelo en `live-limits.json`. El
|
|
419
420
|
`provider.transform` reconstruye el catálogo con ese techo (85 % del tamaño
|
|
420
421
|
rechazado, sin bajar de la ventana ya aceptada) y `provider.reload` lo aplica en
|
|
421
|
-
caliente, de modo que la siguiente compactación
|
|
422
|
-
|
|
423
|
-
compactación descarta los turnos de usuario más antiguos en lugar de dejar que
|
|
424
|
-
OpenCode aborte el turno.
|
|
422
|
+
caliente, de modo que la siguiente compactación la decide OpenCode con un
|
|
423
|
+
presupuesto más realista.
|
|
425
424
|
|
|
426
425
|
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
427
426
|
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
428
427
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
429
428
|
cuota y límite.
|
|
430
429
|
|
|
431
|
-
Los reintentos
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
de modo que la sesión continúa sin interrupciones y sin pasar por un reintento.
|
|
444
|
-
Una compactación también deja el id marcado: el resumen y el turno siguiente se
|
|
445
|
-
solapan en el gateway y ese solape producía un 429 `concurrent` y un replay en
|
|
446
|
-
cada compactación, así que el turno posterior ya sale con un id nuevo.
|
|
447
|
-
|
|
448
|
-
Los fallos de transporte (`ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, DNS
|
|
449
|
-
temporal, `socket hang up`) no son límites de cuenta: el plugin los reintenta con
|
|
450
|
-
espera exponencial hasta cinco veces más (2 s, 4 s, 8 s, 16 s y 30 s) y marca el
|
|
451
|
-
`x-session-id` como sucio para que el siguiente intento use una conexión y un
|
|
452
|
-
slot nuevos. Así un corte breve de red, del router o del servicio local de
|
|
453
|
-
OpenCode no termina el turno en el segundo intento.
|
|
430
|
+
Los reintentos son de OpenCode: el runner decide si un error se reintenta, con
|
|
431
|
+
qué presupuesto y con qué espera. El plugin no fija delays ni límites de
|
|
432
|
+
intentos y tampoco reenvía la petición. Lo único que hace en el hook de
|
|
433
|
+
reintento es preparar el `x-session-id` de free-pi: si OpenCode va a reintentar,
|
|
434
|
+
marca el id como sucio y el siguiente intento sale con uno nuevo, porque el
|
|
435
|
+
gateway mantiene un slot por sesión y un intento fallido puede dejarlo ocupado.
|
|
436
|
+
Al rotar, el plugin libera el id anterior con `/session/reset`. Un turno
|
|
437
|
+
abortado o interrumpido hace lo mismo para el turno siguiente.
|
|
438
|
+
|
|
439
|
+
Los límites de larga duración (`free_usage_limit`, cupos diarios u horarios,
|
|
440
|
+
créditos, cuenta bloqueada) se reescriben a un `400` con el mensaje amigable;
|
|
441
|
+
OpenCode los trata como un fallo normal y no muestra un «Retrying…» infinito.
|
|
454
442
|
|
|
455
443
|
## Rutas por plataforma
|
|
456
444
|
|
package/dist/constants.d.ts
CHANGED
|
@@ -59,27 +59,6 @@ export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low"
|
|
|
59
59
|
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
60
60
|
export declare const HEADER_TIMEOUT_MS = 300000;
|
|
61
61
|
export declare const CHUNK_TIMEOUT_MS = 300000;
|
|
62
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
63
|
-
export declare const RETRY_MAX_RETRIES = 3;
|
|
64
|
-
export declare const RETRY_BASE_DELAY_MS = 2000;
|
|
65
|
-
export declare const RETRY_MAX_DELAY_MS = 60000;
|
|
66
|
-
/**
|
|
67
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
68
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
69
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
70
|
-
* them a longer budget before giving up.
|
|
71
|
-
*/
|
|
72
|
-
export declare const TRANSPORT_RETRY_MAX = 5;
|
|
73
|
-
export declare const TRANSPORT_RETRY_BASE_MS = 2000;
|
|
74
|
-
export declare const TRANSPORT_RETRY_MAX_DELAY_MS = 30000;
|
|
75
|
-
/**
|
|
76
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
77
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
78
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
79
|
-
*/
|
|
80
|
-
export declare const CONCURRENT_RETRY_MAX = 6;
|
|
81
|
-
export declare const CONCURRENT_RETRY_BASE_MS = 1000;
|
|
82
|
-
export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
|
|
83
62
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
84
63
|
export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
85
64
|
export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -129,7 +108,6 @@ export declare const REGISTRY_ATTEMPTS = 2;
|
|
|
129
108
|
export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
130
109
|
export declare const QUOTA_TTL_MS = 30000;
|
|
131
110
|
export declare const QUOTA_HTTP_TIMEOUT_MS = 5000;
|
|
132
|
-
export declare const QUOTA_REFRESH_DEBOUNCE_MS = 1000;
|
|
133
111
|
export declare const SESSION_RESET_COOLDOWN_MS = 15000;
|
|
134
112
|
/**
|
|
135
113
|
* Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
|
package/dist/constants.js
CHANGED
|
@@ -73,27 +73,6 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
73
73
|
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
74
74
|
export const HEADER_TIMEOUT_MS = 300_000;
|
|
75
75
|
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
76
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
77
|
-
export const RETRY_MAX_RETRIES = 3;
|
|
78
|
-
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
79
|
-
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
80
|
-
/**
|
|
81
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
82
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
83
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
84
|
-
* them a longer budget before giving up.
|
|
85
|
-
*/
|
|
86
|
-
export const TRANSPORT_RETRY_MAX = 5;
|
|
87
|
-
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
88
|
-
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
89
|
-
/**
|
|
90
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
91
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
92
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
93
|
-
*/
|
|
94
|
-
export const CONCURRENT_RETRY_MAX = 6;
|
|
95
|
-
export const CONCURRENT_RETRY_BASE_MS = 1_000;
|
|
96
|
-
export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
97
76
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
98
77
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
99
78
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -145,7 +124,6 @@ export const REGISTRY_ATTEMPTS = 2;
|
|
|
145
124
|
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
146
125
|
export const QUOTA_TTL_MS = 30_000;
|
|
147
126
|
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
148
|
-
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
149
127
|
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
150
128
|
/**
|
|
151
129
|
* Releasing a server slot is a tiny POST, but a VPN or a proxy adds a round
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
* Ad-supported free-pi provider plugin for OpenCode V2.
|
|
5
5
|
*/
|
|
6
6
|
export { FreePiPlugin, default } from "./plugin.js";
|
|
7
|
-
export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot,
|
|
7
|
+
export type { Catalog, CatalogModel, FreePiError, FreePiOptions, MeResponse, MeStatsResponse, ModelDefinition, ModelsDevModel, ModelsDevProvider, ModelRegistry, QuotaSnapshot, } from "./types.js";
|
|
8
8
|
export { createLogger } from "./logging.js";
|
|
9
9
|
export type { Logger, LogLevel } from "./logging.js";
|
package/dist/session/events.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Subscribes to core events that affect free-pi state. */
|
|
2
|
+
import { fetchQuota } from "../api/quota.js";
|
|
2
3
|
import { closeFreePiSession } from "../api/session.js";
|
|
3
4
|
import { readCredentialsToken } from "../auth/credentials.js";
|
|
4
5
|
import { tokenFromCredential } from "../auth/credential.js";
|
|
@@ -10,7 +11,6 @@ import { forgetToolStats, isFreePiSession } from "./tools.js";
|
|
|
10
11
|
import { trimSet } from "../utils/async.js";
|
|
11
12
|
import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
|
|
12
13
|
import { markWireSessionDirty, } from "./wire.js";
|
|
13
|
-
import { recordUsage } from "./usage.js";
|
|
14
14
|
function isAbortLike(error) {
|
|
15
15
|
if (!error)
|
|
16
16
|
return false;
|
|
@@ -26,7 +26,6 @@ const EVENT_TYPES = [
|
|
|
26
26
|
"session.execution.succeeded",
|
|
27
27
|
"session.execution.failed",
|
|
28
28
|
"session.execution.interrupted",
|
|
29
|
-
"session.usage.updated",
|
|
30
29
|
"session.step.ended",
|
|
31
30
|
"session.deleted",
|
|
32
31
|
"location.shutdown",
|
|
@@ -103,6 +102,9 @@ async function handleEvent(ctx, deps, event) {
|
|
|
103
102
|
}
|
|
104
103
|
case "session.execution.succeeded": {
|
|
105
104
|
endExecution(deps, event.data?.sessionID);
|
|
105
|
+
// Usage and cost are OpenCode's; the free-pi account quota is not, so a
|
|
106
|
+
// finished turn is the moment to refresh the picker's access filter.
|
|
107
|
+
void fetchQuota(deps).catch(() => undefined);
|
|
106
108
|
return;
|
|
107
109
|
}
|
|
108
110
|
case "session.execution.interrupted": {
|
|
@@ -113,21 +115,12 @@ async function handleEvent(ctx, deps, event) {
|
|
|
113
115
|
endExecution(deps, sessionID);
|
|
114
116
|
return;
|
|
115
117
|
}
|
|
116
|
-
case "session.usage.updated": {
|
|
117
|
-
const sessionID = event.data?.sessionID;
|
|
118
|
-
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
118
|
case "session.step.ended": {
|
|
125
119
|
const sessionID = event.data?.sessionID;
|
|
126
120
|
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
127
121
|
return;
|
|
128
122
|
}
|
|
129
|
-
|
|
130
|
-
// Step tokens are per request; usage.updated is cumulative.
|
|
123
|
+
// Step tokens are per request; OpenCode owns cumulative usage.
|
|
131
124
|
noteStepTokens(deps, deps.state.trackedModels.get(sessionID)?.modelID ?? "", event.data?.tokens);
|
|
132
125
|
return;
|
|
133
126
|
}
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,20 +2,17 @@
|
|
|
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 { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT,
|
|
5
|
+
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONTEXT_WINDOW, DEFENSE_PROVIDER_ID, PROVIDER_ID, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
6
|
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
7
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
8
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
9
|
-
import { parseFreePiError } from "../errors/parse.js";
|
|
10
9
|
import { trimMap } from "../utils/async.js";
|
|
11
10
|
import { watchFreePiNotice } from "./notices.js";
|
|
12
11
|
import { noteSpuriousOverflow, overflowingSpuriously, profileRequest, SPURIOUS_OVERFLOW_SHARE, spuriousOverflowResponse, } from "./overflow.js";
|
|
13
12
|
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
14
|
-
import {
|
|
15
|
-
import { rememberFreePiSession } from "./track.js";
|
|
13
|
+
import { rememberFreePiSession, rememberTrackedModel } from "./track.js";
|
|
16
14
|
import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
|
|
17
15
|
import { FREE_PI_TOOL_NAMES, isFreePiSession, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
18
|
-
import { rememberTrackedModel } from "./usage.js";
|
|
19
16
|
const PENDING_LIMIT = 400;
|
|
20
17
|
/** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
|
|
21
18
|
function pendingKeyOf(sessionID, agent, kind) {
|
|
@@ -33,14 +30,6 @@ async function applyGeneration(deps, event, kind) {
|
|
|
33
30
|
if (!isFreePiProvider(event.model?.providerID))
|
|
34
31
|
return;
|
|
35
32
|
rememberFreePiSession(deps, event.sessionID);
|
|
36
|
-
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
37
|
-
// from the first user message: no free-pi request, no ad impression, and the
|
|
38
|
-
// session leaves the "New session" state immediately.
|
|
39
|
-
if (kind === "title") {
|
|
40
|
-
event.result = localTitle(event.messages);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
// The title agent gets a local answer, so no free-pi request is made.
|
|
44
33
|
const modelID = event.model?.id;
|
|
45
34
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
46
35
|
// the model that was rejected instead of the whole provider.
|
|
@@ -129,181 +118,17 @@ async function applyModelRequest(deps, event) {
|
|
|
129
118
|
await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
|
|
130
119
|
}
|
|
131
120
|
}
|
|
132
|
-
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
133
|
-
function isConcurrentFailure(error) {
|
|
134
|
-
if (!error)
|
|
135
|
-
return false;
|
|
136
|
-
const body = typeof error.response?.body === "string" ? error.response.body : "";
|
|
137
|
-
const message = typeof error.message === "string" ? error.message : "";
|
|
138
|
-
return (/one request at a time/i.test(message) ||
|
|
139
|
-
/one request at a time/i.test(body) ||
|
|
140
|
-
/"concurrent"/.test(body));
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Limits and account blocks do not recover by retrying. pi's own retry helper
|
|
144
|
-
* treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
|
|
145
|
-
* OpenCode retries every 429 by default, which surfaces as an endless
|
|
146
|
-
* "Retrying…". The response rewrite turns most of these into a 400; this guard
|
|
147
|
-
* covers the rest and keeps the CLI's behavior.
|
|
148
|
-
*/
|
|
149
|
-
const TERMINAL_RETRY_CODES = new Set([
|
|
150
|
-
"daily_cap",
|
|
151
|
-
"hourly_ceiling",
|
|
152
|
-
"rolling_cap",
|
|
153
|
-
"global_cap",
|
|
154
|
-
"account_ceiling",
|
|
155
|
-
"free_usage_limit",
|
|
156
|
-
"premium_allowance",
|
|
157
|
-
"guest_allowance",
|
|
158
|
-
"model_requires_credits",
|
|
159
|
-
"insufficient_credits",
|
|
160
|
-
"ads_required",
|
|
161
|
-
"account_review",
|
|
162
|
-
"region_unavailable",
|
|
163
|
-
"unauthorized",
|
|
164
|
-
"expired_token",
|
|
165
|
-
"guest_login_required",
|
|
166
|
-
"consent_required",
|
|
167
|
-
"upgrade_required",
|
|
168
|
-
"reward_required",
|
|
169
|
-
"content_filter",
|
|
170
|
-
"subagents_unavailable",
|
|
171
|
-
]);
|
|
172
|
-
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;
|
|
173
|
-
/**
|
|
174
|
-
* A request that never reached the gateway. `provider.transport` covers the
|
|
175
|
-
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
176
|
-
* retrying beyond the usual budget: a brief offline moment or a background
|
|
177
|
-
* service restart is not a provider limit.
|
|
178
|
-
*/
|
|
179
|
-
const TRANSPORT_RETRY_PATTERN = /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
180
|
-
function isTransportFailure(error) {
|
|
181
|
-
const type = typeof error?.type === "string" ? error.type : "";
|
|
182
|
-
if (/transport|network|connection/i.test(type))
|
|
183
|
-
return true;
|
|
184
|
-
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
185
|
-
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* A 5xx the gateway itself returned: the request was valid but the server had
|
|
189
|
-
* a bad moment. Measured live: image input on every free model answered 503
|
|
190
|
-
* `image_screen_unavailable` for minutes at a stretch. Retrying is the only
|
|
191
|
-
* useful response, and the wire id rotates because the failed attempt may
|
|
192
|
-
* have left the session slot marked busy.
|
|
193
|
-
*/
|
|
194
|
-
function isServerFailure(error) {
|
|
195
|
-
const status = error?.response?.status ??
|
|
196
|
-
(typeof error?.status === "number" ? error.status : undefined);
|
|
197
|
-
if (typeof status === "number" && status >= 500 && status <= 599) {
|
|
198
|
-
return true;
|
|
199
|
-
}
|
|
200
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
201
|
-
return /server error|temporarily unavailable|try again later|image_screen_unavailable/i.test(message);
|
|
202
|
-
}
|
|
203
|
-
function isTerminalFailure(error) {
|
|
204
|
-
if (error?.type === "aborted" ||
|
|
205
|
-
/aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
|
|
206
|
-
return true;
|
|
207
|
-
}
|
|
208
|
-
const parsed = parseFreePiError(error, true);
|
|
209
|
-
if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
|
|
210
|
-
return true;
|
|
211
|
-
const body = typeof error?.response?.body === "string" ? error.response.body : "";
|
|
212
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
213
|
-
return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
|
|
214
|
-
}
|
|
215
121
|
/**
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* and the server can leave a per-session lock behind that resets do not clear.
|
|
222
|
-
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
122
|
+
* Retries belong to OpenCode's session runner: it decides whether an error is
|
|
123
|
+
* retryable, how many times, and the delay. The one thing the runner cannot
|
|
124
|
+
* know is that free-pi holds a per-session request slot and that a failed
|
|
125
|
+
* attempt can leave it marked busy, so the next attempt must use a fresh wire
|
|
126
|
+
* id. This hook only arms that rotation and never touches `decision`.
|
|
223
127
|
*/
|
|
224
128
|
function applyRetryPolicy(deps, event) {
|
|
225
|
-
if (
|
|
226
|
-
if (event.attempt > CONCURRENT_RETRY_MAX) {
|
|
227
|
-
event.decision = { retry: false };
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
const previous = wireSessionID(deps, event.sessionID);
|
|
231
|
-
const next = rotateWireSessionID(deps, event.sessionID);
|
|
232
|
-
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
233
|
-
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
234
|
-
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
235
|
-
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
236
|
-
sessionID: event.sessionID,
|
|
237
|
-
from: previous,
|
|
238
|
-
to: next,
|
|
239
|
-
attempt: event.attempt,
|
|
240
|
-
});
|
|
241
|
-
event.decision = {
|
|
242
|
-
retry: true,
|
|
243
|
-
delay: Math.min(CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1), CONCURRENT_RETRY_MAX_DELAY_MS),
|
|
244
|
-
};
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
if (isTerminalFailure(event.error)) {
|
|
248
|
-
// Remember the broken stream too, so the next turn rotates its wire id
|
|
249
|
-
// instead of running into the stale per-session lock.
|
|
250
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
251
|
-
event.decision = { retry: false };
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (isTransportFailure(event.error)) {
|
|
255
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
256
|
-
event.decision = { retry: false };
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
260
|
-
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
261
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
262
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
263
|
-
event.decision = {
|
|
264
|
-
retry: true,
|
|
265
|
-
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
266
|
-
};
|
|
267
|
-
deps.log.warn("free-pi could not be reached; retrying", {
|
|
268
|
-
sessionID: event.sessionID,
|
|
269
|
-
attempt: event.attempt,
|
|
270
|
-
delay: event.decision.delay,
|
|
271
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
272
|
-
});
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
// A 5xx from the gateway (`image_screen_unavailable` was measured live as a
|
|
276
|
-
// 503) is the server having a bad moment, not the request being wrong. The
|
|
277
|
-
// default retry would stop after three attempts even though the outage
|
|
278
|
-
// usually clears in seconds, so treat it like a transport failure: rotate
|
|
279
|
-
// the wire id and keep trying within the transport budget.
|
|
280
|
-
if (isServerFailure(event.error)) {
|
|
281
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
282
|
-
event.decision = { retry: false };
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
286
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
287
|
-
event.decision = {
|
|
288
|
-
retry: true,
|
|
289
|
-
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
290
|
-
};
|
|
291
|
-
deps.log.warn("free-pi returned a server error; retrying", {
|
|
292
|
-
sessionID: event.sessionID,
|
|
293
|
-
attempt: event.attempt,
|
|
294
|
-
delay: event.decision.delay,
|
|
295
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
296
|
-
});
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
300
|
-
event.decision = { retry: false };
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
if (!event.decision?.retry)
|
|
129
|
+
if (event.decision?.retry !== true)
|
|
304
130
|
return;
|
|
305
|
-
|
|
306
|
-
event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
|
|
131
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
307
132
|
}
|
|
308
133
|
/**
|
|
309
134
|
* Removes this plugin's tools from a request served by another provider. The
|
|
@@ -497,7 +322,6 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
497
322
|
await hookForProviders(ctx, "context", generation("primary"), registrations);
|
|
498
323
|
await hookForProviders(ctx, "compaction", generation("compaction"), registrations);
|
|
499
324
|
await hookForProviders(ctx, "generate", generation("generate"), registrations);
|
|
500
|
-
await hookForProviders(ctx, "title", generation("title"), registrations);
|
|
501
325
|
// The generation hooks above only run for free-pi providers. These unscoped
|
|
502
326
|
// ones strip the plugin's tools from every other provider's requests.
|
|
503
327
|
for (const name of ["context", "compaction", "generate"]) {
|
package/dist/session/track.d.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* later activity instead of running inline with the execution event.
|
|
9
9
|
*/
|
|
10
10
|
import type { Deps } from "../deps.js";
|
|
11
|
+
/** The model a session asked for, used by the tool gate and image handling. */
|
|
12
|
+
export declare function rememberTrackedModel(deps: Deps, sessionID: string, providerID: string, modelID: string): void;
|
|
11
13
|
export declare function rememberFreePiSession(deps: Deps, sessionID: string): void;
|
|
12
14
|
/** Records free-pi activity so a pending close waits for the request to settle. */
|
|
13
15
|
export declare function touchSessionActivity(deps: Deps, sessionID: string): void;
|
package/dist/session/track.js
CHANGED
|
@@ -11,6 +11,11 @@ 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
13
|
import { forgetWireSessionID, wireSessionID } from "./wire.js";
|
|
14
|
+
/** The model a session asked for, used by the tool gate and image handling. */
|
|
15
|
+
export function rememberTrackedModel(deps, sessionID, providerID, modelID) {
|
|
16
|
+
trimMap(deps.state.trackedModels, 200);
|
|
17
|
+
deps.state.trackedModels.set(sessionID, { providerID, modelID });
|
|
18
|
+
}
|
|
14
19
|
export function rememberFreePiSession(deps, sessionID) {
|
|
15
20
|
if (!sessionID)
|
|
16
21
|
return;
|
package/dist/state.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Per-plugin-instance mutable state. */
|
|
2
|
-
import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot,
|
|
2
|
+
import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
|
|
3
3
|
export type RuntimeState = {
|
|
4
4
|
latestClientVersion: string;
|
|
5
5
|
providerToken?: string;
|
|
@@ -18,8 +18,6 @@ export type RuntimeState = {
|
|
|
18
18
|
quotaCache?: QuotaSnapshot;
|
|
19
19
|
quotaPromise?: Promise<QuotaSnapshot>;
|
|
20
20
|
lastQuotaRefreshAt: number;
|
|
21
|
-
lastUsage?: RequestUsage;
|
|
22
|
-
lastUsageMessageID?: string;
|
|
23
21
|
lastFreePiError?: FreePiError;
|
|
24
22
|
lastErrorLogKey?: string;
|
|
25
23
|
lastErrorLogAt: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.29",
|
|
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",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
|
|
26
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
-
"test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/
|
|
27
|
+
"test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/errors.mjs && node test/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs && node test/slots.mjs",
|
|
28
28
|
"prepublishOnly": "npm run build",
|
|
29
29
|
"postinstall": "node scripts/postinstall.mjs"
|
|
30
30
|
},
|
package/src/constants.ts
CHANGED
|
@@ -83,30 +83,6 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
83
83
|
export const HEADER_TIMEOUT_MS = 300_000;
|
|
84
84
|
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
85
85
|
|
|
86
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
87
|
-
export const RETRY_MAX_RETRIES = 3;
|
|
88
|
-
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
89
|
-
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
93
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
94
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
95
|
-
* them a longer budget before giving up.
|
|
96
|
-
*/
|
|
97
|
-
export const TRANSPORT_RETRY_MAX = 5;
|
|
98
|
-
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
99
|
-
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
103
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
104
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
105
|
-
*/
|
|
106
|
-
export const CONCURRENT_RETRY_MAX = 6;
|
|
107
|
-
export const CONCURRENT_RETRY_BASE_MS = 1_000;
|
|
108
|
-
export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
109
|
-
|
|
110
86
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
111
87
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
112
88
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -163,7 +139,6 @@ export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
|
163
139
|
|
|
164
140
|
export const QUOTA_TTL_MS = 30_000;
|
|
165
141
|
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
166
|
-
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
167
142
|
|
|
168
143
|
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
169
144
|
/**
|
package/src/index.ts
CHANGED
package/src/session/events.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Subscribes to core events that affect free-pi state. */
|
|
2
2
|
|
|
3
3
|
import type { Plugin } from "@opencode/plugin";
|
|
4
|
+
import { fetchQuota } from "../api/quota.js";
|
|
4
5
|
import { closeFreePiSession } from "../api/session.js";
|
|
5
6
|
import { readCredentialsToken } from "../auth/credentials.js";
|
|
6
7
|
import { tokenFromCredential } from "../auth/credential.js";
|
|
@@ -21,7 +22,6 @@ import {
|
|
|
21
22
|
import {
|
|
22
23
|
markWireSessionDirty,
|
|
23
24
|
} from "./wire.js";
|
|
24
|
-
import { recordUsage } from "./usage.js";
|
|
25
25
|
|
|
26
26
|
function isAbortLike(error: any): boolean {
|
|
27
27
|
if (!error) return false;
|
|
@@ -39,7 +39,6 @@ const EVENT_TYPES = [
|
|
|
39
39
|
"session.execution.succeeded",
|
|
40
40
|
"session.execution.failed",
|
|
41
41
|
"session.execution.interrupted",
|
|
42
|
-
"session.usage.updated",
|
|
43
42
|
"session.step.ended",
|
|
44
43
|
"session.deleted",
|
|
45
44
|
"location.shutdown",
|
|
@@ -124,6 +123,9 @@ async function handleEvent(
|
|
|
124
123
|
}
|
|
125
124
|
case "session.execution.succeeded": {
|
|
126
125
|
endExecution(deps, event.data?.sessionID);
|
|
126
|
+
// Usage and cost are OpenCode's; the free-pi account quota is not, so a
|
|
127
|
+
// finished turn is the moment to refresh the picker's access filter.
|
|
128
|
+
void fetchQuota(deps).catch(() => undefined);
|
|
127
129
|
return;
|
|
128
130
|
}
|
|
129
131
|
case "session.execution.interrupted": {
|
|
@@ -134,21 +136,12 @@ async function handleEvent(
|
|
|
134
136
|
endExecution(deps, sessionID);
|
|
135
137
|
return;
|
|
136
138
|
}
|
|
137
|
-
case "session.usage.updated": {
|
|
138
|
-
const sessionID = event.data?.sessionID;
|
|
139
|
-
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
139
|
case "session.step.ended": {
|
|
146
140
|
const sessionID = event.data?.sessionID;
|
|
147
141
|
if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
|
|
148
142
|
return;
|
|
149
143
|
}
|
|
150
|
-
|
|
151
|
-
// Step tokens are per request; usage.updated is cumulative.
|
|
144
|
+
// Step tokens are per request; OpenCode owns cumulative usage.
|
|
152
145
|
noteStepTokens(
|
|
153
146
|
deps,
|
|
154
147
|
deps.state.trackedModels.get(sessionID)?.modelID ?? "",
|
package/src/session/hooks.ts
CHANGED
|
@@ -8,19 +8,10 @@ import { resolveToken } from "../auth/token.js";
|
|
|
8
8
|
import {
|
|
9
9
|
AD_CONTEXT_HEADER,
|
|
10
10
|
AD_CONTEXT_OPT_OUT,
|
|
11
|
-
CONCURRENT_RETRY_BASE_MS,
|
|
12
|
-
CONCURRENT_RETRY_MAX,
|
|
13
|
-
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
14
11
|
CONTEXT_WINDOW,
|
|
15
12
|
DEFENSE_PROVIDER_ID,
|
|
16
13
|
PROVIDER_ID,
|
|
17
|
-
RETRY_BASE_DELAY_MS,
|
|
18
|
-
RETRY_MAX_DELAY_MS,
|
|
19
|
-
RETRY_MAX_RETRIES,
|
|
20
14
|
SUBAGENT_HEADER,
|
|
21
|
-
TRANSPORT_RETRY_BASE_MS,
|
|
22
|
-
TRANSPORT_RETRY_MAX,
|
|
23
|
-
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
24
15
|
} from "../constants.js";
|
|
25
16
|
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
26
17
|
import type { Deps } from "../deps.js";
|
|
@@ -40,8 +31,7 @@ import {
|
|
|
40
31
|
spuriousOverflowResponse,
|
|
41
32
|
} from "./overflow.js";
|
|
42
33
|
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
43
|
-
import {
|
|
44
|
-
import { rememberFreePiSession } from "./track.js";
|
|
34
|
+
import { rememberFreePiSession, rememberTrackedModel } from "./track.js";
|
|
45
35
|
import {
|
|
46
36
|
hydrateWireSessionID,
|
|
47
37
|
markWireSessionDirty,
|
|
@@ -56,14 +46,12 @@ import {
|
|
|
56
46
|
recordToolStart,
|
|
57
47
|
toolHeaders,
|
|
58
48
|
} from "./tools.js";
|
|
59
|
-
import { rememberTrackedModel } from "./usage.js";
|
|
60
49
|
|
|
61
50
|
type Registration = { dispose: () => Promise<void> };
|
|
62
51
|
type SessionHookName =
|
|
63
52
|
| "context"
|
|
64
53
|
| "compaction"
|
|
65
54
|
| "generate"
|
|
66
|
-
| "title"
|
|
67
55
|
| "model.request"
|
|
68
56
|
| "http.request"
|
|
69
57
|
| "http.response"
|
|
@@ -99,16 +87,6 @@ async function applyGeneration(
|
|
|
99
87
|
if (!isFreePiProvider(event.model?.providerID)) return;
|
|
100
88
|
rememberFreePiSession(deps, event.sessionID);
|
|
101
89
|
|
|
102
|
-
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
103
|
-
// from the first user message: no free-pi request, no ad impression, and the
|
|
104
|
-
// session leaves the "New session" state immediately.
|
|
105
|
-
if (kind === "title") {
|
|
106
|
-
event.result = localTitle(event.messages);
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// The title agent gets a local answer, so no free-pi request is made.
|
|
111
|
-
|
|
112
90
|
const modelID = event.model?.id;
|
|
113
91
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
114
92
|
// the model that was rejected instead of the whole provider.
|
|
@@ -215,209 +193,16 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
215
193
|
}
|
|
216
194
|
}
|
|
217
195
|
|
|
218
|
-
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
219
|
-
function isConcurrentFailure(error: any): boolean {
|
|
220
|
-
if (!error) return false;
|
|
221
|
-
const body =
|
|
222
|
-
typeof error.response?.body === "string" ? error.response.body : "";
|
|
223
|
-
const message = typeof error.message === "string" ? error.message : "";
|
|
224
|
-
return (
|
|
225
|
-
/one request at a time/i.test(message) ||
|
|
226
|
-
/one request at a time/i.test(body) ||
|
|
227
|
-
/"concurrent"/.test(body)
|
|
228
|
-
);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Limits and account blocks do not recover by retrying. pi's own retry helper
|
|
233
|
-
* treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
|
|
234
|
-
* OpenCode retries every 429 by default, which surfaces as an endless
|
|
235
|
-
* "Retrying…". The response rewrite turns most of these into a 400; this guard
|
|
236
|
-
* covers the rest and keeps the CLI's behavior.
|
|
237
|
-
*/
|
|
238
|
-
const TERMINAL_RETRY_CODES = new Set([
|
|
239
|
-
"daily_cap",
|
|
240
|
-
"hourly_ceiling",
|
|
241
|
-
"rolling_cap",
|
|
242
|
-
"global_cap",
|
|
243
|
-
"account_ceiling",
|
|
244
|
-
"free_usage_limit",
|
|
245
|
-
"premium_allowance",
|
|
246
|
-
"guest_allowance",
|
|
247
|
-
"model_requires_credits",
|
|
248
|
-
"insufficient_credits",
|
|
249
|
-
"ads_required",
|
|
250
|
-
"account_review",
|
|
251
|
-
"region_unavailable",
|
|
252
|
-
"unauthorized",
|
|
253
|
-
"expired_token",
|
|
254
|
-
"guest_login_required",
|
|
255
|
-
"consent_required",
|
|
256
|
-
"upgrade_required",
|
|
257
|
-
"reward_required",
|
|
258
|
-
"content_filter",
|
|
259
|
-
"subagents_unavailable",
|
|
260
|
-
]);
|
|
261
|
-
|
|
262
|
-
const TERMINAL_RETRY_PATTERN =
|
|
263
|
-
/free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* A request that never reached the gateway. `provider.transport` covers the
|
|
267
|
-
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
268
|
-
* retrying beyond the usual budget: a brief offline moment or a background
|
|
269
|
-
* service restart is not a provider limit.
|
|
270
|
-
*/
|
|
271
|
-
const TRANSPORT_RETRY_PATTERN =
|
|
272
|
-
/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
273
|
-
|
|
274
|
-
function isTransportFailure(error: any): boolean {
|
|
275
|
-
const type = typeof error?.type === "string" ? error.type : "";
|
|
276
|
-
if (/transport|network|connection/i.test(type)) return true;
|
|
277
|
-
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
278
|
-
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
196
|
/**
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*/
|
|
288
|
-
function isServerFailure(error: any): boolean {
|
|
289
|
-
const status =
|
|
290
|
-
error?.response?.status ??
|
|
291
|
-
(typeof error?.status === "number" ? error.status : undefined);
|
|
292
|
-
if (typeof status === "number" && status >= 500 && status <= 599) {
|
|
293
|
-
return true;
|
|
294
|
-
}
|
|
295
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
296
|
-
return /server error|temporarily unavailable|try again later|image_screen_unavailable/i.test(
|
|
297
|
-
message,
|
|
298
|
-
);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
function isTerminalFailure(error: any): boolean {
|
|
302
|
-
if (
|
|
303
|
-
error?.type === "aborted" ||
|
|
304
|
-
/aborted|cancelled|canceled|interrupted|AbortError/i.test(
|
|
305
|
-
`${error?.message ?? ""}`,
|
|
306
|
-
)
|
|
307
|
-
) {
|
|
308
|
-
return true;
|
|
309
|
-
}
|
|
310
|
-
const parsed = parseFreePiError(error, true);
|
|
311
|
-
if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code)) return true;
|
|
312
|
-
const body =
|
|
313
|
-
typeof error?.response?.body === "string" ? error.response.body : "";
|
|
314
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
315
|
-
return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/**
|
|
319
|
-
* pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
|
|
320
|
-
* `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
|
|
321
|
-
* Non-retryable decisions are left alone.
|
|
322
|
-
*
|
|
323
|
-
* The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
|
|
324
|
-
* and the server can leave a per-session lock behind that resets do not clear.
|
|
325
|
-
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
197
|
+
* Retries belong to OpenCode's session runner: it decides whether an error is
|
|
198
|
+
* retryable, how many times, and the delay. The one thing the runner cannot
|
|
199
|
+
* know is that free-pi holds a per-session request slot and that a failed
|
|
200
|
+
* attempt can leave it marked busy, so the next attempt must use a fresh wire
|
|
201
|
+
* id. This hook only arms that rotation and never touches `decision`.
|
|
326
202
|
*/
|
|
327
203
|
function applyRetryPolicy(deps: Deps, event: any): void {
|
|
328
|
-
if (
|
|
329
|
-
|
|
330
|
-
event.decision = { retry: false };
|
|
331
|
-
return;
|
|
332
|
-
}
|
|
333
|
-
const previous = wireSessionID(deps, event.sessionID);
|
|
334
|
-
const next = rotateWireSessionID(deps, event.sessionID);
|
|
335
|
-
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
336
|
-
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
337
|
-
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
338
|
-
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
339
|
-
sessionID: event.sessionID,
|
|
340
|
-
from: previous,
|
|
341
|
-
to: next,
|
|
342
|
-
attempt: event.attempt,
|
|
343
|
-
});
|
|
344
|
-
event.decision = {
|
|
345
|
-
retry: true,
|
|
346
|
-
delay: Math.min(
|
|
347
|
-
CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1),
|
|
348
|
-
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
349
|
-
),
|
|
350
|
-
};
|
|
351
|
-
return;
|
|
352
|
-
}
|
|
353
|
-
if (isTerminalFailure(event.error)) {
|
|
354
|
-
// Remember the broken stream too, so the next turn rotates its wire id
|
|
355
|
-
// instead of running into the stale per-session lock.
|
|
356
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
357
|
-
event.decision = { retry: false };
|
|
358
|
-
return;
|
|
359
|
-
}
|
|
360
|
-
if (isTransportFailure(event.error)) {
|
|
361
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
362
|
-
event.decision = { retry: false };
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
366
|
-
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
367
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
368
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
369
|
-
event.decision = {
|
|
370
|
-
retry: true,
|
|
371
|
-
delay: Math.min(
|
|
372
|
-
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
373
|
-
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
374
|
-
),
|
|
375
|
-
};
|
|
376
|
-
deps.log.warn("free-pi could not be reached; retrying", {
|
|
377
|
-
sessionID: event.sessionID,
|
|
378
|
-
attempt: event.attempt,
|
|
379
|
-
delay: event.decision.delay,
|
|
380
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
381
|
-
});
|
|
382
|
-
return;
|
|
383
|
-
}
|
|
384
|
-
// A 5xx from the gateway (`image_screen_unavailable` was measured live as a
|
|
385
|
-
// 503) is the server having a bad moment, not the request being wrong. The
|
|
386
|
-
// default retry would stop after three attempts even though the outage
|
|
387
|
-
// usually clears in seconds, so treat it like a transport failure: rotate
|
|
388
|
-
// the wire id and keep trying within the transport budget.
|
|
389
|
-
if (isServerFailure(event.error)) {
|
|
390
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
391
|
-
event.decision = { retry: false };
|
|
392
|
-
return;
|
|
393
|
-
}
|
|
394
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
395
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
396
|
-
event.decision = {
|
|
397
|
-
retry: true,
|
|
398
|
-
delay: Math.min(
|
|
399
|
-
TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
|
|
400
|
-
TRANSPORT_RETRY_MAX_DELAY_MS,
|
|
401
|
-
),
|
|
402
|
-
};
|
|
403
|
-
deps.log.warn("free-pi returned a server error; retrying", {
|
|
404
|
-
sessionID: event.sessionID,
|
|
405
|
-
attempt: event.attempt,
|
|
406
|
-
delay: event.decision.delay,
|
|
407
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
408
|
-
});
|
|
409
|
-
return;
|
|
410
|
-
}
|
|
411
|
-
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
412
|
-
event.decision = { retry: false };
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
if (!event.decision?.retry) return;
|
|
416
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
417
|
-
event.decision.delay = Math.min(
|
|
418
|
-
RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),
|
|
419
|
-
RETRY_MAX_DELAY_MS,
|
|
420
|
-
);
|
|
204
|
+
if (event.decision?.retry !== true) return;
|
|
205
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
421
206
|
}
|
|
422
207
|
|
|
423
208
|
/**
|
|
@@ -652,7 +437,6 @@ export async function registerSessionHooks(
|
|
|
652
437
|
registrations,
|
|
653
438
|
);
|
|
654
439
|
await hookForProviders(ctx, "generate", generation("generate"), registrations);
|
|
655
|
-
await hookForProviders(ctx, "title", generation("title"), registrations);
|
|
656
440
|
// The generation hooks above only run for free-pi providers. These unscoped
|
|
657
441
|
// ones strip the plugin's tools from every other provider's requests.
|
|
658
442
|
for (const name of ["context", "compaction", "generate"] as const) {
|
package/src/session/track.ts
CHANGED
|
@@ -17,6 +17,17 @@ import type { Deps } from "../deps.js";
|
|
|
17
17
|
import { trimMap, trimSet } from "../utils/async.js";
|
|
18
18
|
import { forgetWireSessionID, wireSessionID } from "./wire.js";
|
|
19
19
|
|
|
20
|
+
/** The model a session asked for, used by the tool gate and image handling. */
|
|
21
|
+
export function rememberTrackedModel(
|
|
22
|
+
deps: Deps,
|
|
23
|
+
sessionID: string,
|
|
24
|
+
providerID: string,
|
|
25
|
+
modelID: string,
|
|
26
|
+
): void {
|
|
27
|
+
trimMap(deps.state.trackedModels, 200);
|
|
28
|
+
deps.state.trackedModels.set(sessionID, { providerID, modelID });
|
|
29
|
+
}
|
|
30
|
+
|
|
20
31
|
export function rememberFreePiSession(deps: Deps, sessionID: string): void {
|
|
21
32
|
if (!sessionID) return;
|
|
22
33
|
const sessions = deps.state.freePiSessions;
|
package/src/state.ts
CHANGED
|
@@ -7,7 +7,6 @@ import type {
|
|
|
7
7
|
FreePiError,
|
|
8
8
|
ModelRegistry,
|
|
9
9
|
QuotaSnapshot,
|
|
10
|
-
RequestUsage,
|
|
11
10
|
SessionResetOutcome,
|
|
12
11
|
TokenCheckState,
|
|
13
12
|
ToolStats,
|
|
@@ -35,8 +34,6 @@ export type RuntimeState = {
|
|
|
35
34
|
quotaPromise?: Promise<QuotaSnapshot>;
|
|
36
35
|
lastQuotaRefreshAt: number;
|
|
37
36
|
|
|
38
|
-
lastUsage?: RequestUsage;
|
|
39
|
-
lastUsageMessageID?: string;
|
|
40
37
|
lastFreePiError?: FreePiError;
|
|
41
38
|
lastErrorLogKey?: string;
|
|
42
39
|
lastErrorLogAt: number;
|
package/dist/session/title.d.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds session titles locally.
|
|
3
|
-
*
|
|
4
|
-
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
-
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
-
* the title hook answers from the first user message instead: the session gets
|
|
7
|
-
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
-
* never leave the session stuck on "New session".
|
|
9
|
-
*/
|
|
10
|
-
type TitleMessage = {
|
|
11
|
-
role?: unknown;
|
|
12
|
-
type?: unknown;
|
|
13
|
-
text?: unknown;
|
|
14
|
-
content?: unknown;
|
|
15
|
-
};
|
|
16
|
-
/** Derives a title from the first meaningful line of the title request. */
|
|
17
|
-
export declare function localTitle(messages: readonly TitleMessage[] | undefined): string;
|
|
18
|
-
export {};
|
package/dist/session/title.js
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds session titles locally.
|
|
3
|
-
*
|
|
4
|
-
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
-
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
-
* the title hook answers from the first user message instead: the session gets
|
|
7
|
-
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
-
* never leave the session stuck on "New session".
|
|
9
|
-
*/
|
|
10
|
-
const MAX_TITLE_LENGTH = 60;
|
|
11
|
-
const MAX_SOURCE_LENGTH = 4_000;
|
|
12
|
-
const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
|
|
13
|
-
const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
|
|
14
|
-
const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
|
|
15
|
-
const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
|
|
16
|
-
const XML_LINE = /^<\/?[a-z][^>]*>$/i;
|
|
17
|
-
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
|
|
18
|
-
function textOf(content) {
|
|
19
|
-
if (typeof content === "string")
|
|
20
|
-
return content;
|
|
21
|
-
if (!Array.isArray(content))
|
|
22
|
-
return "";
|
|
23
|
-
return content
|
|
24
|
-
.filter((part) => part?.type === "text" && typeof part.text === "string")
|
|
25
|
-
.map((part) => part.text)
|
|
26
|
-
.join("\n");
|
|
27
|
-
}
|
|
28
|
-
function latestUserText(messages) {
|
|
29
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
30
|
-
const message = messages[index];
|
|
31
|
-
const role = message?.role ?? message?.type;
|
|
32
|
-
if (role !== "user")
|
|
33
|
-
continue;
|
|
34
|
-
const text = typeof message?.text === "string"
|
|
35
|
-
? message.text
|
|
36
|
-
: textOf(message?.content);
|
|
37
|
-
if (text.trim())
|
|
38
|
-
return text;
|
|
39
|
-
}
|
|
40
|
-
return "";
|
|
41
|
-
}
|
|
42
|
-
/** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
|
|
43
|
-
function sourceText(messages) {
|
|
44
|
-
const raw = latestUserText(messages);
|
|
45
|
-
const block = MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
|
|
46
|
-
return block.slice(0, MAX_SOURCE_LENGTH);
|
|
47
|
-
}
|
|
48
|
-
function cleanLine(line) {
|
|
49
|
-
let value = line.replace(CONTROL, " ").trim();
|
|
50
|
-
if (!value)
|
|
51
|
-
return undefined;
|
|
52
|
-
value = value
|
|
53
|
-
.replace(/^#{1,6}\s+/, "")
|
|
54
|
-
.replace(/^[-*+>]\s+/, "")
|
|
55
|
-
.trim();
|
|
56
|
-
value = value.replace(PREFIX, "").trim();
|
|
57
|
-
if (!value || NOISE.test(value) || XML_LINE.test(value))
|
|
58
|
-
return undefined;
|
|
59
|
-
value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
|
|
60
|
-
return value || undefined;
|
|
61
|
-
}
|
|
62
|
-
function truncate(value) {
|
|
63
|
-
if (value.length <= MAX_TITLE_LENGTH)
|
|
64
|
-
return value;
|
|
65
|
-
const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
|
|
66
|
-
const space = cut.lastIndexOf(" ");
|
|
67
|
-
return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
|
|
68
|
-
}
|
|
69
|
-
/** Derives a title from the first meaningful line of the title request. */
|
|
70
|
-
export function localTitle(messages) {
|
|
71
|
-
if (!Array.isArray(messages) || messages.length === 0)
|
|
72
|
-
return "Session";
|
|
73
|
-
const lines = sourceText(messages)
|
|
74
|
-
.split(/\r?\n/)
|
|
75
|
-
.map(cleanLine)
|
|
76
|
-
.filter((line) => Boolean(line));
|
|
77
|
-
const first = lines[0];
|
|
78
|
-
if (!first)
|
|
79
|
-
return "Session";
|
|
80
|
-
return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
|
|
81
|
-
}
|
package/dist/session/usage.d.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/** Tracks the last request's model and token usage and refreshes quota. */
|
|
2
|
-
import type { Deps } from "../deps.js";
|
|
3
|
-
import type { TokenUsageLike } from "../types.js";
|
|
4
|
-
export declare function rememberTrackedModel(deps: Deps, sessionID: string, providerID: string, modelID: string): void;
|
|
5
|
-
export declare function recordUsage(deps: Deps, sessionID: string, cost: number, tokens: TokenUsageLike | undefined): void;
|
package/dist/session/usage.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
/** Tracks the last request's model and token usage and refreshes quota. */
|
|
2
|
-
import { fetchQuota } from "../api/quota.js";
|
|
3
|
-
import { QUOTA_REFRESH_DEBOUNCE_MS } from "../constants.js";
|
|
4
|
-
import { trimMap } from "../utils/async.js";
|
|
5
|
-
import { touchSessionActivity } from "./track.js";
|
|
6
|
-
export function rememberTrackedModel(deps, sessionID, providerID, modelID) {
|
|
7
|
-
trimMap(deps.state.trackedModels, 200);
|
|
8
|
-
deps.state.trackedModels.set(sessionID, { providerID, modelID });
|
|
9
|
-
}
|
|
10
|
-
export function recordUsage(deps, sessionID, cost, tokens) {
|
|
11
|
-
if (typeof sessionID !== "string" || !sessionID)
|
|
12
|
-
return;
|
|
13
|
-
touchSessionActivity(deps, sessionID);
|
|
14
|
-
const tracked = deps.state.trackedModels.get(sessionID);
|
|
15
|
-
deps.state.lastUsage = {
|
|
16
|
-
at: Date.now(),
|
|
17
|
-
messageID: "",
|
|
18
|
-
providerID: tracked?.providerID ?? "",
|
|
19
|
-
modelID: tracked?.modelID ?? "",
|
|
20
|
-
cost: typeof cost === "number" ? cost : 0,
|
|
21
|
-
input: tokens?.input ?? 0,
|
|
22
|
-
output: tokens?.output ?? 0,
|
|
23
|
-
reasoning: tokens?.reasoning ?? 0,
|
|
24
|
-
cacheRead: tokens?.cache?.read ?? 0,
|
|
25
|
-
cacheWrite: tokens?.cache?.write ?? 0,
|
|
26
|
-
};
|
|
27
|
-
const now = Date.now();
|
|
28
|
-
if (now - deps.state.lastQuotaRefreshAt < QUOTA_REFRESH_DEBOUNCE_MS)
|
|
29
|
-
return;
|
|
30
|
-
deps.state.lastQuotaRefreshAt = now;
|
|
31
|
-
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
32
|
-
}
|
package/src/session/title.ts
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds session titles locally.
|
|
3
|
-
*
|
|
4
|
-
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
-
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
-
* the title hook answers from the first user message instead: the session gets
|
|
7
|
-
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
-
* never leave the session stuck on "New session".
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const MAX_TITLE_LENGTH = 60;
|
|
12
|
-
const MAX_SOURCE_LENGTH = 4_000;
|
|
13
|
-
const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
|
|
14
|
-
const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
|
|
15
|
-
const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
|
|
16
|
-
const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
|
|
17
|
-
const XML_LINE = /^<\/?[a-z][^>]*>$/i;
|
|
18
|
-
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
|
|
19
|
-
|
|
20
|
-
type TitleMessage = {
|
|
21
|
-
role?: unknown;
|
|
22
|
-
type?: unknown;
|
|
23
|
-
text?: unknown;
|
|
24
|
-
content?: unknown;
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
function textOf(content: unknown): string {
|
|
28
|
-
if (typeof content === "string") return content;
|
|
29
|
-
if (!Array.isArray(content)) return "";
|
|
30
|
-
return content
|
|
31
|
-
.filter(
|
|
32
|
-
(part: any) => part?.type === "text" && typeof part.text === "string",
|
|
33
|
-
)
|
|
34
|
-
.map((part: any) => part.text)
|
|
35
|
-
.join("\n");
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function latestUserText(messages: readonly TitleMessage[]): string {
|
|
39
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
40
|
-
const message = messages[index];
|
|
41
|
-
const role = message?.role ?? message?.type;
|
|
42
|
-
if (role !== "user") continue;
|
|
43
|
-
const text =
|
|
44
|
-
typeof message?.text === "string"
|
|
45
|
-
? message.text
|
|
46
|
-
: textOf(message?.content);
|
|
47
|
-
if (text.trim()) return text;
|
|
48
|
-
}
|
|
49
|
-
return "";
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
|
|
53
|
-
function sourceText(messages: readonly TitleMessage[]): string {
|
|
54
|
-
const raw = latestUserText(messages);
|
|
55
|
-
const block =
|
|
56
|
-
MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
|
|
57
|
-
return block.slice(0, MAX_SOURCE_LENGTH);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function cleanLine(line: string): string | undefined {
|
|
61
|
-
let value = line.replace(CONTROL, " ").trim();
|
|
62
|
-
if (!value) return undefined;
|
|
63
|
-
value = value
|
|
64
|
-
.replace(/^#{1,6}\s+/, "")
|
|
65
|
-
.replace(/^[-*+>]\s+/, "")
|
|
66
|
-
.trim();
|
|
67
|
-
value = value.replace(PREFIX, "").trim();
|
|
68
|
-
if (!value || NOISE.test(value) || XML_LINE.test(value)) return undefined;
|
|
69
|
-
value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
|
|
70
|
-
return value || undefined;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function truncate(value: string): string {
|
|
74
|
-
if (value.length <= MAX_TITLE_LENGTH) return value;
|
|
75
|
-
const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
|
|
76
|
-
const space = cut.lastIndexOf(" ");
|
|
77
|
-
return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** Derives a title from the first meaningful line of the title request. */
|
|
81
|
-
export function localTitle(messages: readonly TitleMessage[] | undefined): string {
|
|
82
|
-
if (!Array.isArray(messages) || messages.length === 0) return "Session";
|
|
83
|
-
const lines = sourceText(messages)
|
|
84
|
-
.split(/\r?\n/)
|
|
85
|
-
.map(cleanLine)
|
|
86
|
-
.filter((line): line is string => Boolean(line));
|
|
87
|
-
const first = lines[0];
|
|
88
|
-
if (!first) return "Session";
|
|
89
|
-
return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
|
|
90
|
-
}
|
package/src/session/usage.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
/** Tracks the last request's model and token usage and refreshes quota. */
|
|
2
|
-
|
|
3
|
-
import { fetchQuota } from "../api/quota.js";
|
|
4
|
-
import { QUOTA_REFRESH_DEBOUNCE_MS } from "../constants.js";
|
|
5
|
-
import type { Deps } from "../deps.js";
|
|
6
|
-
import type { TokenUsageLike } from "../types.js";
|
|
7
|
-
import { trimMap } from "../utils/async.js";
|
|
8
|
-
import { touchSessionActivity } from "./track.js";
|
|
9
|
-
|
|
10
|
-
export function rememberTrackedModel(
|
|
11
|
-
deps: Deps,
|
|
12
|
-
sessionID: string,
|
|
13
|
-
providerID: string,
|
|
14
|
-
modelID: string,
|
|
15
|
-
): void {
|
|
16
|
-
trimMap(deps.state.trackedModels, 200);
|
|
17
|
-
deps.state.trackedModels.set(sessionID, { providerID, modelID });
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function recordUsage(
|
|
21
|
-
deps: Deps,
|
|
22
|
-
sessionID: string,
|
|
23
|
-
cost: number,
|
|
24
|
-
tokens: TokenUsageLike | undefined,
|
|
25
|
-
): void {
|
|
26
|
-
if (typeof sessionID !== "string" || !sessionID) return;
|
|
27
|
-
touchSessionActivity(deps, sessionID);
|
|
28
|
-
const tracked = deps.state.trackedModels.get(sessionID);
|
|
29
|
-
deps.state.lastUsage = {
|
|
30
|
-
at: Date.now(),
|
|
31
|
-
messageID: "",
|
|
32
|
-
providerID: tracked?.providerID ?? "",
|
|
33
|
-
modelID: tracked?.modelID ?? "",
|
|
34
|
-
cost: typeof cost === "number" ? cost : 0,
|
|
35
|
-
input: tokens?.input ?? 0,
|
|
36
|
-
output: tokens?.output ?? 0,
|
|
37
|
-
reasoning: tokens?.reasoning ?? 0,
|
|
38
|
-
cacheRead: tokens?.cache?.read ?? 0,
|
|
39
|
-
cacheWrite: tokens?.cache?.write ?? 0,
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
const now = Date.now();
|
|
43
|
-
if (now - deps.state.lastQuotaRefreshAt < QUOTA_REFRESH_DEBOUNCE_MS) return;
|
|
44
|
-
deps.state.lastQuotaRefreshAt = now;
|
|
45
|
-
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
46
|
-
}
|