@eduardo191labs/opencode-free-pi 0.3.3 → 0.3.5
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 +34 -1
- package/dist/api/quota.js +6 -0
- package/dist/catalog/catalog.js +18 -2
- package/dist/catalog/models.d.ts +6 -2
- package/dist/catalog/models.js +30 -22
- package/dist/catalog/v2.js +15 -4
- package/dist/constants.d.ts +33 -0
- package/dist/constants.js +38 -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 +23 -1
- package/dist/session/hooks.js +51 -7
- package/dist/session/notices.d.ts +7 -0
- package/dist/session/notices.js +34 -0
- package/dist/session/title.d.ts +18 -0
- package/dist/session/title.js +81 -0
- package/dist/session/tools.d.ts +28 -0
- package/dist/session/tools.js +112 -0
- package/dist/state.d.ts +6 -1
- package/dist/state.js +3 -0
- package/dist/types.d.ts +19 -0
- package/package.json +2 -2
- package/src/api/quota.ts +8 -0
- package/src/catalog/catalog.ts +19 -1
- package/src/catalog/models.ts +39 -37
- package/src/catalog/v2.ts +16 -3
- package/src/constants.ts +44 -0
- package/src/plugin.ts +3 -2
- package/src/session/cache.ts +82 -0
- package/src/session/events.ts +27 -1
- package/src/session/hooks.ts +89 -6
- package/src/session/notices.ts +40 -0
- package/src/session/title.ts +90 -0
- package/src/session/tools.ts +150 -0
- package/src/state.ts +10 -0
- package/src/types.ts +21 -0
package/README.md
CHANGED
|
@@ -74,6 +74,24 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
74
74
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
75
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
76
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
77
|
+
- **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
|
|
78
|
+
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
79
|
+
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
80
|
+
«New session».
|
|
81
|
+
- **Subagentes identificados**: las sesiones hijas envían
|
|
82
|
+
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
83
|
+
subagentes.
|
|
84
|
+
- **Pensamiento como el CLI**: todos los modelos razonan y empiezan en `off`;
|
|
85
|
+
el selector ofrece `minimal`, `low`, `medium` y `high` mediante
|
|
86
|
+
`reasoning_effort`, igual que `pi-ai`. No se anuncian `thinking_budget` ni
|
|
87
|
+
`thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
|
|
88
|
+
- **Sin cache warming**: el plugin desactiva los keep-alives de OpenCode para
|
|
89
|
+
free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
|
|
90
|
+
- **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
|
|
91
|
+
respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
|
|
92
|
+
- **Avisos de cache miss opcionales**: con `FREE_PI_CACHE_MISS_NOTICES=1` el
|
|
93
|
+
plugin registra en el log los turnos que vuelven a facturar más de 20k
|
|
94
|
+
tokens de prompt, usando la misma fórmula que `cache-stats` de pi.
|
|
77
95
|
- Anuncios e impresiones asociados al turno correcto.
|
|
78
96
|
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
79
97
|
de anuncios; nunca reutiliza los del agente principal.
|
|
@@ -83,7 +101,9 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
83
101
|
- Recuperación automática del límite de sesiones concurrentes.
|
|
84
102
|
- **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
|
|
85
103
|
models.dev se guardan en disco; si la red falla al arrancar se usan las copias
|
|
86
|
-
locales en vez de quedarse sin modelos o sin límites de contexto.
|
|
104
|
+
locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
|
|
105
|
+
que el servidor manda en el catálogo y en `/me` (`notice`) se registran una
|
|
106
|
+
vez en el log del plugin.
|
|
87
107
|
- Compatible con rutas, credenciales y navegador de cada sistema operativo.
|
|
88
108
|
|
|
89
109
|
No incluye herramientas personalizadas. Usa las herramientas integradas de
|
|
@@ -95,6 +115,13 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
95
115
|
|
|
96
116
|
- **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
|
|
97
117
|
`x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
|
|
118
|
+
Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
119
|
+
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
120
|
+
salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
|
|
121
|
+
herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
|
|
122
|
+
última compactación, en la petición siguiente).
|
|
123
|
+
- **Catálogo** (`/client-version`): `authorization` y `x-freepi-cost-exp: 1`,
|
|
124
|
+
igual que el CLI, para que el servidor pueda asignar el experimento de coste.
|
|
98
125
|
- **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
|
|
99
126
|
`x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
|
|
100
127
|
`x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
|
|
@@ -114,6 +141,11 @@ eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
|
|
|
114
141
|
consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
|
|
115
142
|
cuota y límite.
|
|
116
143
|
|
|
144
|
+
Los reintentos siguen la política de pi: como máximo 3 reintentos, con espera
|
|
145
|
+
`min(2s · 2^(n-1), 60s)`. Si el catálogo asigna el experimento `compact100`, el
|
|
146
|
+
plugin baja la ventana a 117 647 tokens para que OpenCode compacte al llegar a
|
|
147
|
+
100k, que es el mismo umbral que consigue `reserveTokens: 100000` en el CLI.
|
|
148
|
+
|
|
117
149
|
## Rutas por plataforma
|
|
118
150
|
|
|
119
151
|
| Elemento | Windows | Linux / macOS / Termux |
|
|
@@ -137,6 +169,7 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
|
137
169
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
138
170
|
| `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
|
|
139
171
|
| `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
|
|
172
|
+
| `FREE_PI_CACHE_MISS_NOTICES=1` | Registrar en el log los cache miss de más de 20k tokens. |
|
|
140
173
|
|
|
141
174
|
No hay variables obligatorias.
|
|
142
175
|
|
package/dist/api/quota.js
CHANGED
|
@@ -65,6 +65,12 @@ export async function fetchQuota(deps, opts = {}) {
|
|
|
65
65
|
: undefined;
|
|
66
66
|
if (meResponse?.ok || statsResponse?.ok)
|
|
67
67
|
rememberTokenCheck(deps, token, "ok");
|
|
68
|
+
if (typeof me?.notice === "string" &&
|
|
69
|
+
me.notice &&
|
|
70
|
+
me.notice !== deps.state.lastQuotaNotice) {
|
|
71
|
+
deps.state.lastQuotaNotice = me.notice;
|
|
72
|
+
deps.log.info("free-pi account notice", { notice: me.notice });
|
|
73
|
+
}
|
|
68
74
|
const snapshot = {
|
|
69
75
|
fetchedAt: Date.now(),
|
|
70
76
|
token,
|
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";
|
|
@@ -22,6 +23,12 @@ function applyCatalog(deps, catalog) {
|
|
|
22
23
|
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
23
24
|
? arm
|
|
24
25
|
: undefined;
|
|
26
|
+
if (typeof catalog.notice === "string" &&
|
|
27
|
+
catalog.notice &&
|
|
28
|
+
catalog.notice !== state.lastCatalogNotice) {
|
|
29
|
+
state.lastCatalogNotice = catalog.notice;
|
|
30
|
+
deps.log.info("free-pi catalog notice", { notice: catalog.notice });
|
|
31
|
+
}
|
|
25
32
|
state.cachedCatalog = catalog;
|
|
26
33
|
state.cachedCatalogAt = Date.now();
|
|
27
34
|
return catalog;
|
|
@@ -33,8 +40,17 @@ export function refreshCatalog(deps) {
|
|
|
33
40
|
return state.catalogPromise;
|
|
34
41
|
const pending = (async () => {
|
|
35
42
|
try {
|
|
43
|
+
// The CLI asks for the catalog with its JWT and the cost-experiment
|
|
44
|
+
// header; without both the server may omit `cost_experiment`.
|
|
45
|
+
const token = await resolveToken(deps).catch(() => undefined);
|
|
46
|
+
const headers = {
|
|
47
|
+
accept: "application/json",
|
|
48
|
+
[COST_EXPERIMENT_HEADER]: "1",
|
|
49
|
+
};
|
|
50
|
+
if (token)
|
|
51
|
+
headers.authorization = `Bearer ${token}`;
|
|
36
52
|
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
37
|
-
headers
|
|
53
|
+
headers,
|
|
38
54
|
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
39
55
|
});
|
|
40
56
|
if (!response.ok)
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -11,5 +11,9 @@ export declare function displayName(model: CatalogModel): string;
|
|
|
11
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,5 +1,5 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
2
|
+
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
3
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
@@ -115,25 +115,26 @@ export function modelCapability(model, candidates) {
|
|
|
115
115
|
}
|
|
116
116
|
return best;
|
|
117
117
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
reasoningEffort: level,
|
|
128
|
-
thinking_budget: budget,
|
|
129
|
-
thinking: { type: "enabled", budget_tokens: budget },
|
|
130
|
-
};
|
|
131
|
-
}
|
|
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" };
|
|
132
127
|
}
|
|
133
|
-
export function modelVariants(options,
|
|
128
|
+
export function modelVariants(options, _outputLimit) {
|
|
134
129
|
const variants = {};
|
|
135
|
-
|
|
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
|
+
}
|
|
136
136
|
return variants;
|
|
137
|
+
}
|
|
137
138
|
const effort = options.find((option) => option.type === "effort");
|
|
138
139
|
if (effort) {
|
|
139
140
|
for (const value of effort.values) {
|
|
@@ -145,12 +146,12 @@ export function modelVariants(options, outputLimit) {
|
|
|
145
146
|
variants.none = { reasoningEffort: "none" };
|
|
146
147
|
variants.high = { reasoningEffort: "high" };
|
|
147
148
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
if (options.some((option) => option.type === "budget_tokens")) {
|
|
150
|
+
budgetVariants(variants);
|
|
151
|
+
}
|
|
151
152
|
return variants;
|
|
152
153
|
}
|
|
153
|
-
export function buildModels(models, candidates = []) {
|
|
154
|
+
export function buildModels(models, candidates = [], options = {}) {
|
|
154
155
|
const result = {};
|
|
155
156
|
for (const model of models) {
|
|
156
157
|
if (!model.id)
|
|
@@ -164,7 +165,10 @@ export function buildModels(models, candidates = []) {
|
|
|
164
165
|
// an advertised 1M window would let OpenCode grow a session past the
|
|
165
166
|
// server's real ceiling and fail with `context_too_long` instead of
|
|
166
167
|
// compacting.
|
|
167
|
-
const
|
|
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);
|
|
168
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);
|
|
169
173
|
result[model.id] = {
|
|
170
174
|
id: model.id,
|
|
@@ -176,6 +180,10 @@ export function buildModels(models, candidates = []) {
|
|
|
176
180
|
reasoning,
|
|
177
181
|
reasoning_options: reasoningOptions,
|
|
178
182
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
183
|
+
...(reasoning
|
|
184
|
+
? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
|
|
185
|
+
: {}),
|
|
186
|
+
enabled: model.unavailable !== true,
|
|
179
187
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
180
188
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
181
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
|
@@ -10,8 +10,41 @@ export declare const CONSENT_VERSION = "4";
|
|
|
10
10
|
export declare const CONTEXT_WINDOW = 200000;
|
|
11
11
|
export declare const MAX_OUTPUT_TOKENS = 32768;
|
|
12
12
|
export declare const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export declare const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
13
14
|
export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
15
|
export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
16
|
+
/**
|
|
17
|
+
* The provider CLI registers every free-pi model with reasoning enabled and
|
|
18
|
+
* defaults to thinking off. OpenCode only sends `reasoning_effort` when a
|
|
19
|
+
* variant or model setting provides one, so the model carries the off default
|
|
20
|
+
* and the picker offers the levels the CLI would.
|
|
21
|
+
*/
|
|
22
|
+
export declare const DEFAULT_REASONING_EFFORT = "none";
|
|
23
|
+
export declare const DEFAULT_THINKING_LEVELS: readonly ["minimal", "low", "medium", "high"];
|
|
24
|
+
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
25
|
+
export declare const HEADER_TIMEOUT_MS = 300000;
|
|
26
|
+
export declare const CHUNK_TIMEOUT_MS = 300000;
|
|
27
|
+
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
28
|
+
export declare const RETRY_MAX_RETRIES = 3;
|
|
29
|
+
export declare const RETRY_BASE_DELAY_MS = 2000;
|
|
30
|
+
export declare const RETRY_MAX_DELAY_MS = 60000;
|
|
31
|
+
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
32
|
+
export declare const CACHE_TTL_MS: number;
|
|
33
|
+
export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
|
|
34
|
+
export declare const CACHE_MISS_NOTICE_TOKENS = 20000;
|
|
35
|
+
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
36
|
+
export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
37
|
+
export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
38
|
+
export declare const COMPACTED_HEADER = "x-freepi-compacted";
|
|
39
|
+
export declare const TOOL_META_BUDGET = 1500;
|
|
40
|
+
export declare const TOOL_ID_LIMIT = 50;
|
|
41
|
+
/**
|
|
42
|
+
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
43
|
+
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
44
|
+
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
45
|
+
*/
|
|
46
|
+
export declare const COMPACT100_TRIGGER_TOKENS = 100000;
|
|
47
|
+
export declare const COMPACT100_CONTEXT_WINDOW = 117647;
|
|
15
48
|
export declare const SESSION_TRACK_LIMIT = 200;
|
|
16
49
|
export declare const AUTH_SKEW_MS = 60000;
|
|
17
50
|
export declare const AUTH_TIMEOUT_MS: number;
|
package/dist/constants.js
CHANGED
|
@@ -10,8 +10,46 @@ export const CONSENT_VERSION = "4";
|
|
|
10
10
|
export const CONTEXT_WINDOW = 200_000;
|
|
11
11
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
12
12
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
13
14
|
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
15
|
export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
16
|
+
/**
|
|
17
|
+
* The provider CLI registers every free-pi model with reasoning enabled and
|
|
18
|
+
* defaults to thinking off. OpenCode only sends `reasoning_effort` when a
|
|
19
|
+
* variant or model setting provides one, so the model carries the off default
|
|
20
|
+
* and the picker offers the levels the CLI would.
|
|
21
|
+
*/
|
|
22
|
+
export const DEFAULT_REASONING_EFFORT = "none";
|
|
23
|
+
export const DEFAULT_THINKING_LEVELS = [
|
|
24
|
+
"minimal",
|
|
25
|
+
"low",
|
|
26
|
+
"medium",
|
|
27
|
+
"high",
|
|
28
|
+
];
|
|
29
|
+
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
30
|
+
export const HEADER_TIMEOUT_MS = 300_000;
|
|
31
|
+
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
32
|
+
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
33
|
+
export const RETRY_MAX_RETRIES = 3;
|
|
34
|
+
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
35
|
+
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
36
|
+
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
37
|
+
export const CACHE_TTL_MS = 5 * 60_000;
|
|
38
|
+
export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
39
|
+
export const CACHE_MISS_NOTICE_TOKENS = 20_000;
|
|
40
|
+
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
41
|
+
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
42
|
+
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
43
|
+
export const COMPACTED_HEADER = "x-freepi-compacted";
|
|
44
|
+
export const TOOL_META_BUDGET = 1_500;
|
|
45
|
+
export const TOOL_ID_LIMIT = 50;
|
|
46
|
+
/**
|
|
47
|
+
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
48
|
+
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
49
|
+
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
50
|
+
*/
|
|
51
|
+
export const COMPACT100_TRIGGER_TOKENS = 100_000;
|
|
52
|
+
export const COMPACT100_CONTEXT_WINDOW = 117_647;
|
|
15
53
|
export const SESSION_TRACK_LIMIT = 200;
|
|
16
54
|
export const AUTH_SKEW_MS = 60_000;
|
|
17
55
|
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
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,11 +3,14 @@ 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 = [
|
|
9
11
|
"credential.updated",
|
|
10
12
|
"credential.switched",
|
|
13
|
+
"session.created",
|
|
11
14
|
"session.execution.started",
|
|
12
15
|
"session.execution.succeeded",
|
|
13
16
|
"session.execution.failed",
|
|
@@ -29,6 +32,17 @@ async function handleEvent(ctx, deps, event) {
|
|
|
29
32
|
await ctx.provider.reload().catch(() => undefined);
|
|
30
33
|
return;
|
|
31
34
|
}
|
|
35
|
+
case "session.created": {
|
|
36
|
+
// The CLI marks requests from its own subagents so the server can bill
|
|
37
|
+
// and rate-limit them separately; OpenCode's children map the same way.
|
|
38
|
+
const sessionID = event.data?.sessionID;
|
|
39
|
+
if (typeof sessionID !== "string")
|
|
40
|
+
return;
|
|
41
|
+
if (typeof event.data?.parentID === "string") {
|
|
42
|
+
deps.state.subagentSessions.add(sessionID);
|
|
43
|
+
}
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
32
46
|
case "session.execution.started": {
|
|
33
47
|
beginExecution(deps, event.data?.sessionID);
|
|
34
48
|
return;
|
|
@@ -47,9 +61,14 @@ async function handleEvent(ctx, deps, event) {
|
|
|
47
61
|
endExecution(deps, event.data?.sessionID);
|
|
48
62
|
return;
|
|
49
63
|
}
|
|
50
|
-
case "session.usage.updated":
|
|
64
|
+
case "session.usage.updated": {
|
|
65
|
+
recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
51
68
|
case "session.step.ended": {
|
|
52
69
|
recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
|
|
70
|
+
// Step tokens are per request; usage.updated is cumulative.
|
|
71
|
+
observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
|
|
53
72
|
return;
|
|
54
73
|
}
|
|
55
74
|
case "session.deleted": {
|
|
@@ -58,6 +77,9 @@ async function handleEvent(ctx, deps, event) {
|
|
|
58
77
|
return;
|
|
59
78
|
await finalizeFreePiSession(deps, sessionID);
|
|
60
79
|
forgetFreePiSession(deps, sessionID);
|
|
80
|
+
forgetCacheMiss(deps, sessionID);
|
|
81
|
+
forgetToolStats(deps, sessionID);
|
|
82
|
+
deps.state.subagentSessions.delete(sessionID);
|
|
61
83
|
return;
|
|
62
84
|
}
|
|
63
85
|
case "location.shutdown": {
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
|
-
import { COST_EXPERIMENT_HEADER, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, } from "../constants.js";
|
|
5
|
+
import { COST_EXPERIMENT_HEADER, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
6
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
7
7
|
import { trimMap } from "../utils/async.js";
|
|
8
|
+
import { watchFreePiNotice } from "./notices.js";
|
|
9
|
+
import { localTitle } from "./title.js";
|
|
8
10
|
import { rememberFreePiSession } from "./track.js";
|
|
11
|
+
import { recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
9
12
|
import { rememberTrackedModel } from "./usage.js";
|
|
10
13
|
const PENDING_LIMIT = 400;
|
|
11
14
|
/** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
|
|
@@ -24,10 +27,11 @@ async function applyGeneration(deps, event, kind) {
|
|
|
24
27
|
if (!isFreePiProvider(event.model?.providerID))
|
|
25
28
|
return;
|
|
26
29
|
rememberFreePiSession(deps, event.sessionID);
|
|
27
|
-
// V1 disabled the title agent.
|
|
28
|
-
//
|
|
30
|
+
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
31
|
+
// from the first user message: no free-pi request, no ad impression, and the
|
|
32
|
+
// session leaves the "New session" state immediately.
|
|
29
33
|
if (kind === "title") {
|
|
30
|
-
event.result =
|
|
34
|
+
event.result = localTitle(event.messages);
|
|
31
35
|
return;
|
|
32
36
|
}
|
|
33
37
|
const modelID = event.model?.id;
|
|
@@ -38,6 +42,11 @@ async function applyGeneration(deps, event, kind) {
|
|
|
38
42
|
if (current === undefined || current > cap)
|
|
39
43
|
event.options.maxTokens = cap;
|
|
40
44
|
}
|
|
45
|
+
if (kind === "compaction") {
|
|
46
|
+
// OpenCode sends the messages it is folding into the summary, which is the
|
|
47
|
+
// same set pi reports through `session_before_compact`.
|
|
48
|
+
recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
|
|
49
|
+
}
|
|
41
50
|
if (deps.state.costExperimentArm === "efficiency") {
|
|
42
51
|
const system = Array.isArray(event.system) ? event.system : [];
|
|
43
52
|
if (!system.some((part) => part?.type === "text" && part.text === EFFICIENCY_RULE)) {
|
|
@@ -70,6 +79,9 @@ async function applyModelRequest(deps, event) {
|
|
|
70
79
|
event.headers.authorization = `Bearer ${token}`;
|
|
71
80
|
event.headers["x-session-id"] = event.sessionID;
|
|
72
81
|
event.headers["x-client-version"] = deps.state.latestClientVersion;
|
|
82
|
+
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
83
|
+
event.headers[SUBAGENT_HEADER] = "1";
|
|
84
|
+
}
|
|
73
85
|
if (deps.state.costExperimentArm) {
|
|
74
86
|
event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
|
|
75
87
|
}
|
|
@@ -77,6 +89,7 @@ async function applyModelRequest(deps, event) {
|
|
|
77
89
|
// an impression the user never sees.
|
|
78
90
|
if (event.kind === "title")
|
|
79
91
|
return;
|
|
92
|
+
Object.assign(event.headers, toolHeaders(deps, event.sessionID, event.kind !== "compaction"));
|
|
80
93
|
const pending = deps.state.pendingAdTurns.get(pendingKeyOf(event.sessionID, agent, event.kind));
|
|
81
94
|
const turn = pending ??
|
|
82
95
|
(await resolveAdTurn(deps, {
|
|
@@ -94,6 +107,36 @@ async function applyModelRequest(deps, event) {
|
|
|
94
107
|
await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
|
|
95
108
|
}
|
|
96
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
|
|
112
|
+
* `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
|
|
113
|
+
* Non-retryable decisions are left alone.
|
|
114
|
+
*/
|
|
115
|
+
function applyRetryPolicy(event) {
|
|
116
|
+
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
117
|
+
event.decision = { retry: false };
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (!event.decision?.retry)
|
|
121
|
+
return;
|
|
122
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
123
|
+
event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
|
|
124
|
+
}
|
|
125
|
+
async function registerToolHooks(ctx, deps, registrations) {
|
|
126
|
+
if (!ctx.tool?.hook)
|
|
127
|
+
return;
|
|
128
|
+
registrations.push(await ctx.tool.hook("execute.before", (event) => {
|
|
129
|
+
recordToolStart(deps, event.sessionID, event.id);
|
|
130
|
+
}));
|
|
131
|
+
registrations.push(await ctx.tool.hook("execute.after", (event) => {
|
|
132
|
+
recordToolEnd(deps, event.sessionID, {
|
|
133
|
+
id: event.id,
|
|
134
|
+
tool: event.tool,
|
|
135
|
+
status: event.status,
|
|
136
|
+
...(event.status === "completed" ? { result: event.result } : {}),
|
|
137
|
+
});
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
97
140
|
async function hookForProviders(ctx, name, callback, registrations) {
|
|
98
141
|
for (const providerID of [PROVIDER_ID, DEFENSE_PROVIDER_ID]) {
|
|
99
142
|
registrations.push(await ctx.session.hook(name, callback, {
|
|
@@ -114,12 +157,13 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
114
157
|
// become a 400 overflow, not a friendly long-lived limit.
|
|
115
158
|
const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
|
|
116
159
|
if (overflow) {
|
|
117
|
-
event.response = overflow;
|
|
160
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
118
161
|
return;
|
|
119
162
|
}
|
|
120
163
|
const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
|
|
121
|
-
|
|
122
|
-
event.response = rewritten;
|
|
164
|
+
event.response = watchFreePiNotice(deps, rewritten ?? event.response);
|
|
123
165
|
}, registrations);
|
|
166
|
+
await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(event), registrations);
|
|
167
|
+
await registerToolHooks(ctx, deps, registrations);
|
|
124
168
|
return registrations;
|
|
125
169
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logs the two server notices the free-pi CLI watches for: the
|
|
3
|
+
* `x-freepi-notice` header and the `: freepi_notice` SSE marker sent when the
|
|
4
|
+
* server restarts.
|
|
5
|
+
*/
|
|
6
|
+
import type { Deps } from "../deps.js";
|
|
7
|
+
export declare function watchFreePiNotice(deps: Deps, response: Response): Response;
|