@eduardo191labs/opencode-free-pi 0.3.3 → 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 CHANGED
@@ -74,6 +74,17 @@ 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
+ - **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.
77
88
  - Anuncios e impresiones asociados al turno correcto.
78
89
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
79
90
  de anuncios; nunca reutiliza los del agente principal.
@@ -95,6 +106,12 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
95
106
 
96
107
  - **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
97
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.
98
115
  - **Anuncios** (`/ads/next`): `authorization`, `x-session-id`,
99
116
  `x-client-version`, `x-turn-id`, `x-ad-trigger`, `x-client-os`,
100
117
  `x-client-arch`, `x-client-timezone`, `x-client-locale` y `x-ad-context`.
@@ -114,6 +131,11 @@ eso los modelos se registran con costo `0`, igual que el CLI del proveedor; el
114
131
  consumo real se consulta en `/me` y `/me/stats` y se refleja en los mensajes de
115
132
  cuota y límite.
116
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.
138
+
117
139
  ## Rutas por plataforma
118
140
 
119
141
  | Elemento | Windows | Linux / macOS / Termux |
@@ -137,6 +159,7 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
137
159
  | `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
138
160
  | `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
139
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. |
140
163
 
141
164
  No hay variables obligatorias.
142
165
 
@@ -1,5 +1,6 @@
1
1
  /** Fetches the live free-pi model catalog. */
2
- import { CATALOG_DISK_TTL_MS, CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, } from "../constants.js";
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: { accept: "application/json" },
47
+ headers,
38
48
  signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
39
49
  });
40
50
  if (!response.ok)
@@ -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, outputLimit: number): VariantMap;
15
- export declare function buildModels(models: CatalogModel[], candidates?: RegistryCandidate[]): ModelMap;
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;
@@ -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
- function budgetVariants(option, outputLimit, variants) {
119
- const ceiling = Math.max(1, Math.min(positiveNumber(option.max) ?? outputLimit - 1024, outputLimit - 1024, MAX_OUTPUT_TOKENS - 1024));
120
- const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
121
- const high = Math.min(Math.max(floor, Math.floor((ceiling + 1) / 2)), ceiling);
122
- for (const [level, budget] of [
123
- ["high", high],
124
- ["max", ceiling],
125
- ]) {
126
- variants[level] = {
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, outputLimit) {
128
+ export function modelVariants(options, _outputLimit) {
134
129
  const variants = {};
135
- if (!options || options.length === 0)
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
- const budget = options.find((option) => option.type === "budget_tokens");
149
- if (budget)
150
- budgetVariants(budget, outputLimit, variants);
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 limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? CONTEXT_WINDOW, CONTEXT_WINDOW);
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,
@@ -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
- input: model.modalities?.input ?? ["text"],
17
- output: model.modalities?.output ?? ["text"],
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: true,
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
  }
@@ -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/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 mainModels = buildModels(main, candidates);
58
- const defenseModels = buildModels(defense, candidates);
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
+ }
@@ -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": {
@@ -2,10 +2,12 @@
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, } 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";
8
9
  import { rememberFreePiSession } from "./track.js";
10
+ import { recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
9
11
  import { rememberTrackedModel } from "./usage.js";
10
12
  const PENDING_LIMIT = 400;
11
13
  /** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
@@ -38,6 +40,11 @@ async function applyGeneration(deps, event, kind) {
38
40
  if (current === undefined || current > cap)
39
41
  event.options.maxTokens = cap;
40
42
  }
43
+ if (kind === "compaction") {
44
+ // OpenCode sends the messages it is folding into the summary, which is the
45
+ // same set pi reports through `session_before_compact`.
46
+ recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
47
+ }
41
48
  if (deps.state.costExperimentArm === "efficiency") {
42
49
  const system = Array.isArray(event.system) ? event.system : [];
43
50
  if (!system.some((part) => part?.type === "text" && part.text === EFFICIENCY_RULE)) {
@@ -77,6 +84,7 @@ async function applyModelRequest(deps, event) {
77
84
  // an impression the user never sees.
78
85
  if (event.kind === "title")
79
86
  return;
87
+ Object.assign(event.headers, toolHeaders(deps, event.sessionID, event.kind !== "compaction"));
80
88
  const pending = deps.state.pendingAdTurns.get(pendingKeyOf(event.sessionID, agent, event.kind));
81
89
  const turn = pending ??
82
90
  (await resolveAdTurn(deps, {
@@ -94,6 +102,36 @@ async function applyModelRequest(deps, event) {
94
102
  await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
95
103
  }
96
104
  }
105
+ /**
106
+ * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
107
+ * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
108
+ * Non-retryable decisions are left alone.
109
+ */
110
+ function applyRetryPolicy(event) {
111
+ if (event.attempt > RETRY_MAX_RETRIES + 1) {
112
+ event.decision = { retry: false };
113
+ return;
114
+ }
115
+ if (!event.decision?.retry)
116
+ return;
117
+ const attempt = Math.max(1, event.attempt - 1);
118
+ event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
119
+ }
120
+ async function registerToolHooks(ctx, deps, registrations) {
121
+ if (!ctx.tool?.hook)
122
+ return;
123
+ registrations.push(await ctx.tool.hook("execute.before", (event) => {
124
+ recordToolStart(deps, event.sessionID, event.id);
125
+ }));
126
+ registrations.push(await ctx.tool.hook("execute.after", (event) => {
127
+ recordToolEnd(deps, event.sessionID, {
128
+ id: event.id,
129
+ tool: event.tool,
130
+ status: event.status,
131
+ ...(event.status === "completed" ? { result: event.result } : {}),
132
+ });
133
+ }));
134
+ }
97
135
  async function hookForProviders(ctx, name, callback, registrations) {
98
136
  for (const providerID of [PROVIDER_ID, DEFENSE_PROVIDER_ID]) {
99
137
  registrations.push(await ctx.session.hook(name, callback, {
@@ -114,12 +152,13 @@ export async function registerSessionHooks(ctx, deps) {
114
152
  // become a 400 overflow, not a friendly long-lived limit.
115
153
  const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
116
154
  if (overflow) {
117
- event.response = overflow;
155
+ event.response = watchFreePiNotice(deps, overflow);
118
156
  return;
119
157
  }
120
158
  const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
121
- if (rewritten)
122
- event.response = rewritten;
159
+ event.response = watchFreePiNotice(deps, rewritten ?? event.response);
123
160
  }, registrations);
161
+ await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(event), registrations);
162
+ await registerToolHooks(ctx, deps, registrations);
124
163
  return registrations;
125
164
  }
@@ -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;
@@ -0,0 +1,34 @@
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
+ const NOTICE_HEADER = "x-freepi-notice";
7
+ const SSE_NOTICE = "freepi_notice";
8
+ export function watchFreePiNotice(deps, response) {
9
+ const notice = response.headers.get(NOTICE_HEADER);
10
+ if (notice)
11
+ deps.log.info("free-pi server notice", { notice });
12
+ const type = response.headers.get("content-type") ?? "";
13
+ if (!response.body || !type.includes("text/event-stream"))
14
+ return response;
15
+ const decoder = new TextDecoder();
16
+ let reported = false;
17
+ const body = response.body.pipeThrough(new TransformStream({
18
+ transform(chunk, controller) {
19
+ if (!reported) {
20
+ const text = decoder.decode(chunk, { stream: true });
21
+ if (text.includes(SSE_NOTICE)) {
22
+ reported = true;
23
+ deps.log.warn("free-pi server sent a restart notice");
24
+ }
25
+ }
26
+ controller.enqueue(chunk);
27
+ },
28
+ }));
29
+ return new Response(body, {
30
+ status: response.status,
31
+ statusText: response.statusText,
32
+ headers: response.headers,
33
+ });
34
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Tool outcome headers, mirroring the free-pi provider CLI's
3
+ * `free-pi-tool-outcomes` extension:
4
+ *
5
+ * - `x-freepi-tool-meta: v1:<id>~<ms>~<exit>~<truncated>,...`
6
+ * - `x-freepi-tool-errors: v1:<ids>` (`v1x:` once old IDs were evicted)
7
+ * - `x-freepi-compacted: v1:<dropped messages>` on the request after compaction
8
+ */
9
+ import type { Deps } from "../deps.js";
10
+ type ToolResultLike = {
11
+ metadata?: Record<string, unknown>;
12
+ };
13
+ type ToolEnd = {
14
+ id: string;
15
+ tool: string;
16
+ status: "completed" | "error";
17
+ result?: ToolResultLike;
18
+ };
19
+ export declare function recordToolStart(deps: Deps, sessionID: string, id: string): void;
20
+ export declare function recordToolEnd(deps: Deps, sessionID: string, end: ToolEnd): void;
21
+ export declare function recordCompaction(deps: Deps, sessionID: string, droppedMessages: number): void;
22
+ /**
23
+ * Headers for the outgoing request. `consumeCompacted` is false for the
24
+ * compaction request itself so the marker lands on the request that follows.
25
+ */
26
+ export declare function toolHeaders(deps: Deps, sessionID: string, consumeCompacted: boolean): Record<string, string>;
27
+ export declare function forgetToolStats(deps: Deps, sessionID: string): void;
28
+ export {};