@eduardo191labs/opencode-free-pi 0.3.2 → 0.3.4
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 +42 -3
- package/dist/catalog/catalog.js +12 -2
- package/dist/catalog/models.d.ts +7 -3
- package/dist/catalog/models.js +44 -47
- package/dist/catalog/v2.js +15 -4
- package/dist/constants.d.ts +32 -0
- package/dist/constants.js +37 -0
- package/dist/errors/limit.d.ts +7 -0
- package/dist/errors/limit.js +67 -0
- package/dist/plugin.js +3 -2
- package/dist/session/cache.d.ts +15 -0
- package/dist/session/cache.js +57 -0
- package/dist/session/events.js +10 -1
- package/dist/session/hooks.js +50 -4
- package/dist/session/notices.d.ts +7 -0
- package/dist/session/notices.js +34 -0
- package/dist/session/tools.d.ts +28 -0
- package/dist/session/tools.js +112 -0
- package/dist/state.d.ts +3 -1
- package/dist/state.js +2 -0
- package/dist/types.d.ts +17 -0
- package/package.json +1 -1
- package/src/catalog/catalog.ts +11 -1
- package/src/catalog/models.ts +59 -67
- package/src/catalog/v2.ts +16 -3
- package/src/constants.ts +43 -0
- package/src/errors/limit.ts +73 -0
- package/src/plugin.ts +3 -2
- package/src/session/cache.ts +82 -0
- package/src/session/events.ts +15 -1
- package/src/session/hooks.ts +92 -3
- package/src/session/notices.ts +40 -0
- package/src/session/tools.ts +150 -0
- package/src/state.ts +6 -0
- package/src/types.ts +19 -0
package/README.md
CHANGED
|
@@ -66,6 +66,25 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
66
66
|
- Catálogo en vivo de modelos **free-pi** y **free-pi-defense**.
|
|
67
67
|
- Integración nativa de OpenCode V2 para credenciales OAuth, clave y entorno.
|
|
68
68
|
- Cuota diaria, créditos premium y límites con mensajes claros.
|
|
69
|
+
- **Límites reales de free-pi**: todos los modelos anuncian la ventana de
|
|
70
|
+
contexto de 200k y el límite de salida de 32k que aplica el CLI del
|
|
71
|
+
proveedor, aunque models.dev informe ventanas mayores para el modelo
|
|
72
|
+
upstream. Así OpenCode compacta antes de que el servidor rechace la
|
|
73
|
+
conversación.
|
|
74
|
+
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
|
+
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
|
+
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
77
|
+
- **Pensamiento como el CLI**: todos los modelos razonan y empiezan en `off`;
|
|
78
|
+
el selector ofrece `minimal`, `low`, `medium` y `high` mediante
|
|
79
|
+
`reasoning_effort`, igual que `pi-ai`. No se anuncian `thinking_budget` ni
|
|
80
|
+
`thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
|
|
81
|
+
- **Sin cache warming**: el plugin desactiva los keep-alives de OpenCode para
|
|
82
|
+
free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
|
|
83
|
+
- **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
|
|
84
|
+
respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
|
|
85
|
+
- **Avisos de cache miss opcionales**: con `FREE_PI_CACHE_MISS_NOTICES=1` el
|
|
86
|
+
plugin registra en el log los turnos que vuelven a facturar más de 20k
|
|
87
|
+
tokens de prompt, usando la misma fórmula que `cache-stats` de pi.
|
|
69
88
|
- Anuncios e impresiones asociados al turno correcto.
|
|
70
89
|
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
71
90
|
de anuncios; nunca reutiliza los del agente principal.
|
|
@@ -87,6 +106,12 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
87
106
|
|
|
88
107
|
- **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
|
|
89
108
|
`x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
|
|
109
|
+
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
110
|
+
salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
|
|
111
|
+
herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
|
|
112
|
+
última compactación, en la petición siguiente).
|
|
113
|
+
- **Catálogo** (`/client-version`): `authorization` y `x-freepi-cost-exp: 1`,
|
|
114
|
+
igual que el CLI, para que el servidor pueda asignar el experimento de coste.
|
|
90
115
|
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
91
116
|
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
92
117
|
`x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
|
|
@@ -96,7 +121,20 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
96
121
|
`x-client-version` y, cuando aplica, `x-session-id`.
|
|
97
122
|
|
|
98
123
|
Las respuestas `429` de límites largos se reescriben a un `400` con el mensaje
|
|
99
|
-
amigable, igual que en el plugin V1.
|
|
124
|
+
amigable, igual que en el plugin V1. Las respuestas `413` (o `429`/`400`) con
|
|
125
|
+
código `context_too_long`, `context_too_long_for_fallback` o `context_ceiling`
|
|
126
|
+
se reescriben a un `400` con el texto que OpenCode clasifica como
|
|
127
|
+
desbordamiento de contexto, para que dispare la compactación automática.
|
|
128
|
+
|
|
129
|
+
free-pi cobra en créditos contra una cuota diaria, no en USD por token. Por
|
|
130
|
+
eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
131
|
+
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
132
|
+
cuota y límite.
|
|
133
|
+
|
|
134
|
+
Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
|
|
135
|
+
`min(2s · 2^(n-1), 60s)`. Si el catálogo asigna el experimento `compact100`, el
|
|
136
|
+
plugin baja la ventana a 117 647 tokens para que OpenCode compacte al llegar a
|
|
137
|
+
100k, que es el mismo umbral que consigue `reserveTokens: 100000` en el CLI.
|
|
100
138
|
|
|
101
139
|
## Rutas por plataforma
|
|
102
140
|
|
|
@@ -121,6 +159,7 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
|
121
159
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
122
160
|
| `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
|
|
123
161
|
| `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
|
|
162
|
+
| `FREE_PI_CACHE_MISS_NOTICES=1` | Registrar en el log los cache miss de más de 20k tokens. |
|
|
124
163
|
|
|
125
164
|
No hay variables obligatorias.
|
|
126
165
|
|
|
@@ -214,8 +253,8 @@ dist/ build ESM y tipos
|
|
|
214
253
|
scripts/postinstall.mjs registro en opencode.json
|
|
215
254
|
test/smoke.mjs prueba de humo del build
|
|
216
255
|
test/registry.mjs caché y tolerancia a fallos de models.dev
|
|
217
|
-
test/models.mjs capacidades, variantes, límites y costos
|
|
218
|
-
test/hooks.mjs hooks de sesión, anuncios y
|
|
256
|
+
test/models.mjs capacidades, variantes, límites reales y costos
|
|
257
|
+
test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
|
|
219
258
|
```
|
|
220
259
|
|
|
221
260
|
## Desinstalar
|
package/dist/catalog/catalog.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
|
-
import {
|
|
2
|
+
import { resolveToken } from "../auth/token.js";
|
|
3
|
+
import { CATALOG_DISK_TTL_MS, CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, COST_EXPERIMENT_HEADER, } from "../constants.js";
|
|
3
4
|
import { readCache, writeCache } from "../utils/cache.js";
|
|
4
5
|
import { resolveBaseUrl } from "../utils/urls.js";
|
|
5
6
|
const CACHE_FILE = "catalog.json";
|
|
@@ -33,8 +34,17 @@ export function refreshCatalog(deps) {
|
|
|
33
34
|
return state.catalogPromise;
|
|
34
35
|
const pending = (async () => {
|
|
35
36
|
try {
|
|
37
|
+
// The CLI asks for the catalog with its JWT and the cost-experiment
|
|
38
|
+
// header; without both the server may omit `cost_experiment`.
|
|
39
|
+
const token = await resolveToken(deps).catch(() => undefined);
|
|
40
|
+
const headers = {
|
|
41
|
+
accept: "application/json",
|
|
42
|
+
[COST_EXPERIMENT_HEADER]: "1",
|
|
43
|
+
};
|
|
44
|
+
if (token)
|
|
45
|
+
headers.authorization = `Bearer ${token}`;
|
|
36
46
|
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
37
|
-
headers
|
|
47
|
+
headers,
|
|
38
48
|
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
39
49
|
});
|
|
40
50
|
if (!response.ok)
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -8,8 +8,12 @@ export declare function partitionModels(catalog: Catalog | undefined): {
|
|
|
8
8
|
defense: CatalogModel[];
|
|
9
9
|
};
|
|
10
10
|
export declare function displayName(model: CatalogModel): string;
|
|
11
|
-
export declare function modelCost(
|
|
11
|
+
export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevModel): ModelDefinition["cost"];
|
|
12
12
|
export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
|
|
13
13
|
export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
|
|
14
|
-
export declare function modelVariants(options: ReasoningOption[] | undefined,
|
|
15
|
-
export
|
|
14
|
+
export declare function modelVariants(options: ReasoningOption[] | undefined, _outputLimit: number): VariantMap;
|
|
15
|
+
export type BuildModelsOptions = {
|
|
16
|
+
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
17
|
+
compact100?: boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare function buildModels(models: CatalogModel[], candidates?: RegistryCandidate[], options?: BuildModelsOptions): ModelMap;
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
|
-
import {
|
|
2
|
+
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
|
+
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
6
6
|
return (catalog?.models ?? []).filter((model) => typeof model.id === "string" && model.id.length > 0);
|
|
@@ -35,29 +35,12 @@ export function displayName(model) {
|
|
|
35
35
|
}
|
|
36
36
|
return tags.length > 0 ? `${base} (${tags.join(" · ")})` : base;
|
|
37
37
|
}
|
|
38
|
-
export function modelCost(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
0;
|
|
45
|
-
const output = creditsToUsd(model.output_credits_per_mtok) ||
|
|
46
|
-
positiveNumber(capability?.cost?.output) ||
|
|
47
|
-
0;
|
|
48
|
-
if (input > 0 || output > 0) {
|
|
49
|
-
return {
|
|
50
|
-
input,
|
|
51
|
-
output,
|
|
52
|
-
cache_read: creditsToUsd(model.cache_read_credits_per_mtok) ||
|
|
53
|
-
positiveNumber(capability?.cost?.cache_read) ||
|
|
54
|
-
input,
|
|
55
|
-
cache_write: creditsToUsd(model.cache_write_credits_per_mtok) ||
|
|
56
|
-
positiveNumber(capability?.cost?.cache_write) ||
|
|
57
|
-
input,
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
return zero;
|
|
38
|
+
export function modelCost(_model, _capability) {
|
|
39
|
+
// free-pi bills in credits against a daily allowance; it does not charge
|
|
40
|
+
// per-token USD. The provider CLI registers every model with zero cost and
|
|
41
|
+
// shows the real usage through /usage, so publishing reseller prices here
|
|
42
|
+
// would only invent a cost the account never pays.
|
|
43
|
+
return { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
61
44
|
}
|
|
62
45
|
export function modelRegistryCandidates(registry) {
|
|
63
46
|
const candidates = [];
|
|
@@ -132,25 +115,26 @@ export function modelCapability(model, candidates) {
|
|
|
132
115
|
}
|
|
133
116
|
return best;
|
|
134
117
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
reasoningEffort: level,
|
|
145
|
-
thinking_budget: budget,
|
|
146
|
-
thinking: { type: "enabled", budget_tokens: budget },
|
|
147
|
-
};
|
|
148
|
-
}
|
|
118
|
+
/**
|
|
119
|
+
* free-pi's openai-compatible route only understands `reasoning_effort`.
|
|
120
|
+
* pi's `thinking_budget` and `thinking` fields are dropped by OpenCode's
|
|
121
|
+
* lowering, so advertising them would be inert. Budget-style catalogs still
|
|
122
|
+
* expose their top levels as effort variants.
|
|
123
|
+
*/
|
|
124
|
+
function budgetVariants(variants) {
|
|
125
|
+
variants.high = { reasoningEffort: "high" };
|
|
126
|
+
variants.max = { reasoningEffort: "max" };
|
|
149
127
|
}
|
|
150
|
-
export function modelVariants(options,
|
|
128
|
+
export function modelVariants(options, _outputLimit) {
|
|
151
129
|
const variants = {};
|
|
152
|
-
|
|
130
|
+
// The provider CLI offers these levels to every reasoning model because its
|
|
131
|
+
// `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
|
|
132
|
+
if (!options || options.length === 0) {
|
|
133
|
+
for (const level of DEFAULT_THINKING_LEVELS) {
|
|
134
|
+
variants[level] = { reasoningEffort: level };
|
|
135
|
+
}
|
|
153
136
|
return variants;
|
|
137
|
+
}
|
|
154
138
|
const effort = options.find((option) => option.type === "effort");
|
|
155
139
|
if (effort) {
|
|
156
140
|
for (const value of effort.values) {
|
|
@@ -162,12 +146,12 @@ export function modelVariants(options, outputLimit) {
|
|
|
162
146
|
variants.none = { reasoningEffort: "none" };
|
|
163
147
|
variants.high = { reasoningEffort: "high" };
|
|
164
148
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
149
|
+
if (options.some((option) => option.type === "budget_tokens")) {
|
|
150
|
+
budgetVariants(variants);
|
|
151
|
+
}
|
|
168
152
|
return variants;
|
|
169
153
|
}
|
|
170
|
-
export function buildModels(models, candidates = []) {
|
|
154
|
+
export function buildModels(models, candidates = [], options = {}) {
|
|
171
155
|
const result = {};
|
|
172
156
|
for (const model of models) {
|
|
173
157
|
if (!model.id)
|
|
@@ -175,8 +159,17 @@ export function buildModels(models, candidates = []) {
|
|
|
175
159
|
const capability = modelCapability(model, candidates);
|
|
176
160
|
const reasoning = model.reasoning ?? capability?.reasoning ?? true;
|
|
177
161
|
const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
|
|
178
|
-
|
|
179
|
-
|
|
162
|
+
// free-pi enforces a 200k input window and 32k output cap on every model,
|
|
163
|
+
// regardless of what models.dev reports for the upstream provider. The
|
|
164
|
+
// provider CLI registers exactly these limits, so clamp to them here too:
|
|
165
|
+
// an advertised 1M window would let OpenCode grow a session past the
|
|
166
|
+
// server's real ceiling and fail with `context_too_long` instead of
|
|
167
|
+
// compacting.
|
|
168
|
+
const contextCeiling = options.compact100
|
|
169
|
+
? COMPACT100_CONTEXT_WINDOW
|
|
170
|
+
: CONTEXT_WINDOW;
|
|
171
|
+
const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
|
|
172
|
+
const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
|
|
180
173
|
result[model.id] = {
|
|
181
174
|
id: model.id,
|
|
182
175
|
name: displayName(model),
|
|
@@ -187,6 +180,10 @@ export function buildModels(models, candidates = []) {
|
|
|
187
180
|
reasoning,
|
|
188
181
|
reasoning_options: reasoningOptions,
|
|
189
182
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
183
|
+
...(reasoning
|
|
184
|
+
? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
|
|
185
|
+
: {}),
|
|
186
|
+
enabled: model.unavailable !== true,
|
|
190
187
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
191
188
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
192
189
|
attachment: model.attachment ?? capability?.attachment ?? false,
|
package/dist/catalog/v2.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Converts internal model definitions into OpenCode V2 provider records. */
|
|
2
|
-
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, OPENAI_COMPATIBLE_PACKAGE, PROVIDER_ID, } from "../constants.js";
|
|
2
|
+
import { CHUNK_TIMEOUT_MS, CONTEXT_WINDOW, HEADER_TIMEOUT_MS, MAX_OUTPUT_TOKENS, OPENAI_COMPATIBLE_PACKAGE, PROVIDER_ID, } from "../constants.js";
|
|
3
3
|
import { completionsBaseUrl } from "../utils/urls.js";
|
|
4
4
|
export function toV2Models(providerID, models) {
|
|
5
5
|
return Object.values(models).map((model) => {
|
|
@@ -13,12 +13,16 @@ export function toV2Models(providerID, models) {
|
|
|
13
13
|
...(model.family ? { family: model.family } : {}),
|
|
14
14
|
capabilities: {
|
|
15
15
|
tools: model.tool_call !== false,
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
// The provider CLI registers every free-pi model as text-only. An
|
|
17
|
+
// advertised image input would let OpenCode send media the server
|
|
18
|
+
// does not accept.
|
|
19
|
+
input: ["text"],
|
|
20
|
+
output: ["text"],
|
|
18
21
|
...(model.temperature === undefined
|
|
19
22
|
? {}
|
|
20
23
|
: { temperature: model.temperature }),
|
|
21
24
|
},
|
|
25
|
+
...(model.settings ? { settings: model.settings } : {}),
|
|
22
26
|
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
23
27
|
id,
|
|
24
28
|
settings,
|
|
@@ -35,7 +39,7 @@ export function toV2Models(providerID, models) {
|
|
|
35
39
|
},
|
|
36
40
|
],
|
|
37
41
|
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
38
|
-
enabled:
|
|
42
|
+
enabled: model.enabled !== false,
|
|
39
43
|
limit: {
|
|
40
44
|
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
41
45
|
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
@@ -53,6 +57,13 @@ export function baseProviderInfo(providerID, name, token) {
|
|
|
53
57
|
settings: {
|
|
54
58
|
baseURL: completionsBaseUrl(),
|
|
55
59
|
apiKey: token ?? "free-pi",
|
|
60
|
+
// free-pi is ad-supported and bills credits, so OpenCode's keep-alive
|
|
61
|
+
// warmer would spend requests the provider CLI never makes. pi keeps
|
|
62
|
+
// warming off for free-pi and the economics are always zero.
|
|
63
|
+
cache: { warming: false },
|
|
64
|
+
// Match pi's HTTP idle timeout for both response headers and chunks.
|
|
65
|
+
headerTimeout: HEADER_TIMEOUT_MS,
|
|
66
|
+
chunkTimeout: CHUNK_TIMEOUT_MS,
|
|
56
67
|
},
|
|
57
68
|
};
|
|
58
69
|
}
|
package/dist/constants.d.ts
CHANGED
|
@@ -12,6 +12,38 @@ export declare const MAX_OUTPUT_TOKENS = 32768;
|
|
|
12
12
|
export declare const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
13
|
export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
14
|
export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
|
+
/**
|
|
16
|
+
* The provider CLI registers every free-pi model with reasoning enabled and
|
|
17
|
+
* defaults to thinking off. OpenCode only sends `reasoning_effort` when a
|
|
18
|
+
* variant or model setting provides one, so the model carries the off default
|
|
19
|
+
* and the picker offers the levels the CLI would.
|
|
20
|
+
*/
|
|
21
|
+
export declare const DEFAULT_REASONING_EFFORT = "none";
|
|
22
|
+
export declare const DEFAULT_THINKING_LEVELS: readonly ["minimal", "low", "medium", "high"];
|
|
23
|
+
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
24
|
+
export declare const HEADER_TIMEOUT_MS = 300000;
|
|
25
|
+
export declare const CHUNK_TIMEOUT_MS = 300000;
|
|
26
|
+
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
27
|
+
export declare const RETRY_MAX_RETRIES = 3;
|
|
28
|
+
export declare const RETRY_BASE_DELAY_MS = 2000;
|
|
29
|
+
export declare const RETRY_MAX_DELAY_MS = 60000;
|
|
30
|
+
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
31
|
+
export declare const CACHE_TTL_MS: number;
|
|
32
|
+
export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
|
|
33
|
+
export declare const CACHE_MISS_NOTICE_TOKENS = 20000;
|
|
34
|
+
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
35
|
+
export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
36
|
+
export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
37
|
+
export declare const COMPACTED_HEADER = "x-freepi-compacted";
|
|
38
|
+
export declare const TOOL_META_BUDGET = 1500;
|
|
39
|
+
export declare const TOOL_ID_LIMIT = 50;
|
|
40
|
+
/**
|
|
41
|
+
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
42
|
+
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
43
|
+
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
44
|
+
*/
|
|
45
|
+
export declare const COMPACT100_TRIGGER_TOKENS = 100000;
|
|
46
|
+
export declare const COMPACT100_CONTEXT_WINDOW = 117647;
|
|
15
47
|
export declare const SESSION_TRACK_LIMIT = 200;
|
|
16
48
|
export declare const AUTH_SKEW_MS = 60000;
|
|
17
49
|
export declare const AUTH_TIMEOUT_MS: number;
|
package/dist/constants.js
CHANGED
|
@@ -12,6 +12,43 @@ export const MAX_OUTPUT_TOKENS = 32_768;
|
|
|
12
12
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
13
|
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
14
|
export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
|
+
/**
|
|
16
|
+
* The provider CLI registers every free-pi model with reasoning enabled and
|
|
17
|
+
* defaults to thinking off. OpenCode only sends `reasoning_effort` when a
|
|
18
|
+
* variant or model setting provides one, so the model carries the off default
|
|
19
|
+
* and the picker offers the levels the CLI would.
|
|
20
|
+
*/
|
|
21
|
+
export const DEFAULT_REASONING_EFFORT = "none";
|
|
22
|
+
export const DEFAULT_THINKING_LEVELS = [
|
|
23
|
+
"minimal",
|
|
24
|
+
"low",
|
|
25
|
+
"medium",
|
|
26
|
+
"high",
|
|
27
|
+
];
|
|
28
|
+
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
29
|
+
export const HEADER_TIMEOUT_MS = 300_000;
|
|
30
|
+
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
31
|
+
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
32
|
+
export const RETRY_MAX_RETRIES = 3;
|
|
33
|
+
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
34
|
+
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
35
|
+
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
36
|
+
export const CACHE_TTL_MS = 5 * 60_000;
|
|
37
|
+
export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
38
|
+
export const CACHE_MISS_NOTICE_TOKENS = 20_000;
|
|
39
|
+
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
40
|
+
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
41
|
+
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
42
|
+
export const COMPACTED_HEADER = "x-freepi-compacted";
|
|
43
|
+
export const TOOL_META_BUDGET = 1_500;
|
|
44
|
+
export const TOOL_ID_LIMIT = 50;
|
|
45
|
+
/**
|
|
46
|
+
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
47
|
+
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
48
|
+
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
49
|
+
*/
|
|
50
|
+
export const COMPACT100_TRIGGER_TOKENS = 100_000;
|
|
51
|
+
export const COMPACT100_CONTEXT_WINDOW = 117_647;
|
|
15
52
|
export const SESSION_TRACK_LIMIT = 200;
|
|
16
53
|
export const AUTH_SKEW_MS = 60_000;
|
|
17
54
|
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
package/dist/errors/limit.d.ts
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
* Rewrites long-lived free-pi limit responses so the client shows the friendly
|
|
3
3
|
* message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
|
|
4
4
|
*/
|
|
5
|
+
/**
|
|
6
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
7
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
8
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
9
|
+
* the fatal "conversation is too long" error.
|
|
10
|
+
*/
|
|
11
|
+
export declare function rewriteContextOverflowResponse(response: Response): Promise<Response | undefined>;
|
|
5
12
|
/**
|
|
6
13
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
7
14
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
package/dist/errors/limit.js
CHANGED
|
@@ -18,6 +18,19 @@ const LONG_LIMIT_CODES = new Set([
|
|
|
18
18
|
"account_ceiling",
|
|
19
19
|
"region_unavailable",
|
|
20
20
|
]);
|
|
21
|
+
const CONTEXT_OVERFLOW_CODES = new Set([
|
|
22
|
+
"context_too_long",
|
|
23
|
+
"context_too_long_for_fallback",
|
|
24
|
+
"context_ceiling",
|
|
25
|
+
]);
|
|
26
|
+
/**
|
|
27
|
+
* OpenCode classifies HTTP 413 as `payload-too-large` before it looks at the
|
|
28
|
+
* message, so free-pi's `context_too_long` 413 never reaches the compaction
|
|
29
|
+
* recovery path. Rewriting it to a 400 whose message matches OpenCode's
|
|
30
|
+
* `prompt is too long` overflow pattern lets the runner compact and retry the
|
|
31
|
+
* turn instead of failing it with the raw server message.
|
|
32
|
+
*/
|
|
33
|
+
const CONTEXT_OVERFLOW_MESSAGE = "prompt is too long for this model's context window; run /compact or start a new session";
|
|
21
34
|
function retryAfterSeconds(response) {
|
|
22
35
|
const retryAfter = response.headers.get("retry-after");
|
|
23
36
|
if (retryAfter) {
|
|
@@ -81,6 +94,60 @@ function friendlyBody(body, info) {
|
|
|
81
94
|
return body;
|
|
82
95
|
}
|
|
83
96
|
}
|
|
97
|
+
function contextOverflowCode(body) {
|
|
98
|
+
try {
|
|
99
|
+
const data = JSON.parse(body);
|
|
100
|
+
const raw = data?.code ?? data?.error?.code ?? data?.limit;
|
|
101
|
+
if (typeof raw === "string" && CONTEXT_OVERFLOW_CODES.has(raw))
|
|
102
|
+
return raw;
|
|
103
|
+
}
|
|
104
|
+
catch { }
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
109
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
110
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
111
|
+
* the fatal "conversation is too long" error.
|
|
112
|
+
*/
|
|
113
|
+
export async function rewriteContextOverflowResponse(response) {
|
|
114
|
+
if (response.status !== 413 &&
|
|
115
|
+
response.status !== 429 &&
|
|
116
|
+
response.status !== 400)
|
|
117
|
+
return undefined;
|
|
118
|
+
const body = await response
|
|
119
|
+
.clone()
|
|
120
|
+
.text()
|
|
121
|
+
.catch(() => "");
|
|
122
|
+
if (!body)
|
|
123
|
+
return undefined;
|
|
124
|
+
const code = contextOverflowCode(body);
|
|
125
|
+
if (!code)
|
|
126
|
+
return undefined;
|
|
127
|
+
const headers = new Headers(response.headers);
|
|
128
|
+
headers.delete("retry-after");
|
|
129
|
+
headers.delete("retry-after-ms");
|
|
130
|
+
headers.set("x-free-pi-original-status", String(response.status));
|
|
131
|
+
headers.set("x-free-pi-original-code", code);
|
|
132
|
+
let data;
|
|
133
|
+
try {
|
|
134
|
+
data = JSON.parse(body);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
data = {};
|
|
138
|
+
}
|
|
139
|
+
if (data && typeof data === "object") {
|
|
140
|
+
data.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
141
|
+
if (data.error && typeof data.error === "object") {
|
|
142
|
+
data.error.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return new Response(JSON.stringify(data), {
|
|
146
|
+
status: 400,
|
|
147
|
+
statusText: "Bad Request",
|
|
148
|
+
headers,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
84
151
|
/**
|
|
85
152
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
86
153
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
package/dist/plugin.js
CHANGED
|
@@ -54,8 +54,9 @@ async function setup(ctx) {
|
|
|
54
54
|
const registry = registryResult ?? state.cachedRegistry;
|
|
55
55
|
const { main, defense } = partitionModels(catalog);
|
|
56
56
|
const candidates = modelRegistryCandidates(registry);
|
|
57
|
-
const
|
|
58
|
-
const
|
|
57
|
+
const buildOptions = { compact100: state.costExperimentArm === "compact100" };
|
|
58
|
+
const mainModels = buildModels(main, candidates, buildOptions);
|
|
59
|
+
const defenseModels = buildModels(defense, candidates, buildOptions);
|
|
59
60
|
for (const [id, model] of Object.entries(mainModels)) {
|
|
60
61
|
state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
|
|
61
62
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt-cache miss notices, mirroring pi's `cache-stats` detector.
|
|
3
|
+
*
|
|
4
|
+
* free-pi reports no per-token cost, so only the token threshold applies. The
|
|
5
|
+
* notices are opt-in because OpenCode has no toast surface for them.
|
|
6
|
+
*/
|
|
7
|
+
import type { Deps } from "../deps.js";
|
|
8
|
+
import type { TokenUsageLike } from "../types.js";
|
|
9
|
+
/**
|
|
10
|
+
* Records one step's usage and logs a miss when the prompt was re-billed.
|
|
11
|
+
* `session.step.ended` carries per-step tokens; `session.usage.updated` is a
|
|
12
|
+
* cumulative total and must not be fed here.
|
|
13
|
+
*/
|
|
14
|
+
export declare function observeStepUsage(deps: Deps, sessionID: string | undefined, tokens: TokenUsageLike | undefined): void;
|
|
15
|
+
export declare function forgetCacheMiss(deps: Deps, sessionID: string): void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt-cache miss notices, mirroring pi's `cache-stats` detector.
|
|
3
|
+
*
|
|
4
|
+
* free-pi reports no per-token cost, so only the token threshold applies. The
|
|
5
|
+
* notices are opt-in because OpenCode has no toast surface for them.
|
|
6
|
+
*/
|
|
7
|
+
import { CACHE_MISS_NOISE_FLOOR_TOKENS, CACHE_MISS_NOTICE_TOKENS, CACHE_TTL_MS, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "../constants.js";
|
|
8
|
+
function noticesEnabled() {
|
|
9
|
+
const value = process.env.FREE_PI_CACHE_MISS_NOTICES?.trim().toLowerCase();
|
|
10
|
+
return value === "1" || value === "true" || value === "yes";
|
|
11
|
+
}
|
|
12
|
+
function idleText(idleMs) {
|
|
13
|
+
const minutes = Math.round(idleMs / 60_000);
|
|
14
|
+
return idleMs > CACHE_TTL_MS ? ` after ${minutes}m idle` : "";
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Records one step's usage and logs a miss when the prompt was re-billed.
|
|
18
|
+
* `session.step.ended` carries per-step tokens; `session.usage.updated` is a
|
|
19
|
+
* cumulative total and must not be fed here.
|
|
20
|
+
*/
|
|
21
|
+
export function observeStepUsage(deps, sessionID, tokens) {
|
|
22
|
+
if (!noticesEnabled() || typeof sessionID !== "string" || !sessionID)
|
|
23
|
+
return;
|
|
24
|
+
const tracked = deps.state.trackedModels.get(sessionID);
|
|
25
|
+
if (tracked?.providerID !== PROVIDER_ID &&
|
|
26
|
+
tracked?.providerID !== DEFENSE_PROVIDER_ID)
|
|
27
|
+
return;
|
|
28
|
+
const cacheRead = tokens?.cache?.read ?? 0;
|
|
29
|
+
const cacheWrite = tokens?.cache?.write ?? 0;
|
|
30
|
+
const promptTokens = (tokens?.input ?? 0) + cacheRead + cacheWrite;
|
|
31
|
+
if (promptTokens <= 0)
|
|
32
|
+
return;
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const modelKey = `${tracked.providerID}/${tracked.modelID}`;
|
|
35
|
+
const previous = deps.state.cacheMisses.get(sessionID);
|
|
36
|
+
if (previous) {
|
|
37
|
+
const reportedCache = previous.reportedCache || cacheRead + cacheWrite > 0;
|
|
38
|
+
if (reportedCache) {
|
|
39
|
+
const missedTokens = Math.min(previous.promptTokens, promptTokens) - cacheRead;
|
|
40
|
+
if (missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS) {
|
|
41
|
+
const modelChanged = previous.modelKey !== modelKey;
|
|
42
|
+
if (missedTokens >= CACHE_MISS_NOTICE_TOKENS) {
|
|
43
|
+
deps.log.info(`cache miss: ${missedTokens} tokens re-billed${idleText(now - previous.at)}${modelChanged ? " (model changed)" : ""}`, { sessionID, model: modelKey });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
deps.state.cacheMisses.set(sessionID, {
|
|
49
|
+
promptTokens,
|
|
50
|
+
at: now,
|
|
51
|
+
modelKey,
|
|
52
|
+
reportedCache: cacheRead + cacheWrite > 0 || (previous?.reportedCache ?? false),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
export function forgetCacheMiss(deps, sessionID) {
|
|
56
|
+
deps.state.cacheMisses.delete(sessionID);
|
|
57
|
+
}
|
package/dist/session/events.js
CHANGED
|
@@ -3,6 +3,8 @@ import { closeFreePiSession } from "../api/session.js";
|
|
|
3
3
|
import { readCredentialsToken } from "../auth/credentials.js";
|
|
4
4
|
import { tokenFromCredential } from "../auth/credential.js";
|
|
5
5
|
import { handleFreePiError } from "../errors/handle.js";
|
|
6
|
+
import { forgetCacheMiss, observeStepUsage } from "./cache.js";
|
|
7
|
+
import { forgetToolStats } from "./tools.js";
|
|
6
8
|
import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
|
|
7
9
|
import { recordUsage } from "./usage.js";
|
|
8
10
|
const EVENT_TYPES = [
|
|
@@ -47,9 +49,14 @@ async function handleEvent(ctx, deps, event) {
|
|
|
47
49
|
endExecution(deps, event.data?.sessionID);
|
|
48
50
|
return;
|
|
49
51
|
}
|
|
50
|
-
case "session.usage.updated":
|
|
52
|
+
case "session.usage.updated": {
|
|
53
|
+
recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
51
56
|
case "session.step.ended": {
|
|
52
57
|
recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
|
|
58
|
+
// Step tokens are per request; usage.updated is cumulative.
|
|
59
|
+
observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
|
|
53
60
|
return;
|
|
54
61
|
}
|
|
55
62
|
case "session.deleted": {
|
|
@@ -58,6 +65,8 @@ async function handleEvent(ctx, deps, event) {
|
|
|
58
65
|
return;
|
|
59
66
|
await finalizeFreePiSession(deps, sessionID);
|
|
60
67
|
forgetFreePiSession(deps, sessionID);
|
|
68
|
+
forgetCacheMiss(deps, sessionID);
|
|
69
|
+
forgetToolStats(deps, sessionID);
|
|
61
70
|
return;
|
|
62
71
|
}
|
|
63
72
|
case "location.shutdown": {
|