@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.
@@ -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";
6
- import { rewriteLimitResponse } from "../errors/limit.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
+ 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, {
@@ -110,9 +148,17 @@ export async function registerSessionHooks(ctx, deps) {
110
148
  await hookForProviders(ctx, "title", generation("title"), registrations);
111
149
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
112
150
  await hookForProviders(ctx, "http.response", async (event) => {
151
+ // Context overflow has to be handled first: a 429 context ceiling must
152
+ // become a 400 overflow, not a friendly long-lived limit.
153
+ const overflow = await rewriteContextOverflowResponse(event.response).catch(() => undefined);
154
+ if (overflow) {
155
+ event.response = watchFreePiNotice(deps, overflow);
156
+ return;
157
+ }
113
158
  const rewritten = await rewriteLimitResponse(event.response).catch(() => undefined);
114
- if (rewritten)
115
- event.response = rewritten;
159
+ event.response = watchFreePiNotice(deps, rewritten ?? event.response);
116
160
  }, registrations);
161
+ await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(event), registrations);
162
+ await registerToolHooks(ctx, deps, registrations);
117
163
  return registrations;
118
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 {};
@@ -0,0 +1,112 @@
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 { COMPACTED_HEADER, DEFENSE_PROVIDER_ID, PROVIDER_ID, TOOL_ERRORS_HEADER, TOOL_ID_LIMIT, TOOL_META_BUDGET, TOOL_META_HEADER, } from "../constants.js";
10
+ import { trimMap } from "../utils/async.js";
11
+ const ID_PATTERN = /^[\w.:-]{1,100}$/;
12
+ const MAX_ENTRY_LENGTH = 150;
13
+ const MAX_STARTED = 200;
14
+ function isFreePiSession(deps, sessionID) {
15
+ if (deps.state.freePiSessions.has(sessionID))
16
+ return true;
17
+ const tracked = deps.state.trackedModels.get(sessionID);
18
+ return (tracked?.providerID === PROVIDER_ID ||
19
+ tracked?.providerID === DEFENSE_PROVIDER_ID);
20
+ }
21
+ function statsFor(deps, sessionID) {
22
+ let stats = deps.state.toolStats.get(sessionID);
23
+ if (!stats) {
24
+ stats = {
25
+ meta: [],
26
+ metaBytes: 3,
27
+ failed: [],
28
+ evicted: false,
29
+ started: new Map(),
30
+ compacted: 0,
31
+ };
32
+ trimMap(deps.state.toolStats, 200);
33
+ deps.state.toolStats.set(sessionID, stats);
34
+ }
35
+ return stats;
36
+ }
37
+ function shellExit(stats) {
38
+ if (stats.status === "error")
39
+ return "-";
40
+ const exit = stats.result?.metadata?.exit;
41
+ return typeof exit === "number" ? String(exit) : "0";
42
+ }
43
+ function truncated(stats) {
44
+ const metadata = stats.result?.metadata;
45
+ if (metadata?.truncated === true)
46
+ return true;
47
+ const truncation = metadata?.truncation;
48
+ return Boolean(truncation &&
49
+ typeof truncation === "object" &&
50
+ truncation.truncated === true);
51
+ }
52
+ export function recordToolStart(deps, sessionID, id) {
53
+ if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(id))
54
+ return;
55
+ const stats = statsFor(deps, sessionID);
56
+ stats.started.set(id, Date.now());
57
+ if (stats.started.size <= MAX_STARTED)
58
+ return;
59
+ const oldest = stats.started.keys().next().value;
60
+ if (oldest !== undefined)
61
+ stats.started.delete(oldest);
62
+ }
63
+ export function recordToolEnd(deps, sessionID, end) {
64
+ if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(end.id))
65
+ return;
66
+ const stats = statsFor(deps, sessionID);
67
+ const startedAt = stats.started.get(end.id);
68
+ stats.started.delete(end.id);
69
+ const duration = startedAt === undefined ? 0 : Date.now() - startedAt;
70
+ const entry = `${end.id}~${Math.max(0, Math.round(duration))}~${shellExit(end)}~${truncated(end) ? 1 : 0}`;
71
+ if (entry.length <= MAX_ENTRY_LENGTH) {
72
+ stats.meta.push(entry);
73
+ stats.metaBytes += entry.length + 1;
74
+ while (stats.metaBytes > TOOL_META_BUDGET && stats.meta.length > 1) {
75
+ const removed = stats.meta.shift();
76
+ stats.metaBytes -= (removed?.length ?? 0) + 1;
77
+ }
78
+ }
79
+ if (end.status !== "error")
80
+ return;
81
+ stats.failed.push(end.id);
82
+ if (stats.failed.length <= TOOL_ID_LIMIT)
83
+ return;
84
+ stats.failed.shift();
85
+ stats.evicted = true;
86
+ }
87
+ export function recordCompaction(deps, sessionID, droppedMessages) {
88
+ if (!isFreePiSession(deps, sessionID) || droppedMessages <= 0)
89
+ return;
90
+ const stats = statsFor(deps, sessionID);
91
+ stats.compacted += droppedMessages;
92
+ }
93
+ /**
94
+ * Headers for the outgoing request. `consumeCompacted` is false for the
95
+ * compaction request itself so the marker lands on the request that follows.
96
+ */
97
+ export function toolHeaders(deps, sessionID, consumeCompacted) {
98
+ const stats = deps.state.toolStats.get(sessionID);
99
+ const headers = {};
100
+ if (stats?.meta.length) {
101
+ headers[TOOL_META_HEADER] = `v1:${stats.meta.join(",")}`;
102
+ }
103
+ if (stats && consumeCompacted && stats.compacted > 0) {
104
+ headers[COMPACTED_HEADER] = `v1:${stats.compacted}`;
105
+ stats.compacted = 0;
106
+ }
107
+ headers[TOOL_ERRORS_HEADER] = `${stats?.evicted ? "v1x" : "v1"}:${(stats?.failed ?? []).join(",")}`;
108
+ return headers;
109
+ }
110
+ export function forgetToolStats(deps, sessionID) {
111
+ deps.state.toolStats.delete(sessionID);
112
+ }
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Per-plugin-instance mutable state. */
2
- import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, RequestUsage, SessionResetOutcome, TokenCheckState, TrackedModel } from "./types.js";
2
+ import type { AdTurn, CacheMissState, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, RequestUsage, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
3
3
  export type RuntimeState = {
4
4
  latestClientVersion: string;
5
5
  providerToken?: string;
@@ -39,5 +39,7 @@ export type RuntimeState = {
39
39
  pendingAdTurns: Map<string, AdTurn>;
40
40
  adImpressions: Map<string, Promise<void>>;
41
41
  trackedModels: Map<string, TrackedModel>;
42
+ cacheMisses: Map<string, CacheMissState>;
43
+ toolStats: Map<string, ToolStats>;
42
44
  };
43
45
  export declare function createRuntimeState(): RuntimeState;
package/dist/state.js CHANGED
@@ -22,5 +22,7 @@ export function createRuntimeState() {
22
22
  pendingAdTurns: new Map(),
23
23
  adImpressions: new Map(),
24
24
  trackedModels: new Map(),
25
+ cacheMisses: new Map(),
26
+ toolStats: new Map(),
25
27
  };
26
28
  }
package/dist/types.d.ts CHANGED
@@ -103,6 +103,9 @@ export type ModelDefinition = {
103
103
  reasoning: boolean;
104
104
  reasoning_options?: ReasoningOption[];
105
105
  variants: Record<string, Record<string, unknown>>;
106
+ /** Model-level provider options, such as the default reasoning effort. */
107
+ settings?: Record<string, unknown>;
108
+ enabled: boolean;
106
109
  temperature: boolean;
107
110
  tool_call: boolean;
108
111
  attachment: boolean;
@@ -237,6 +240,20 @@ export type TrackedModel = {
237
240
  providerID: string;
238
241
  modelID: string;
239
242
  };
243
+ export type CacheMissState = {
244
+ promptTokens: number;
245
+ at: number;
246
+ modelKey: string;
247
+ reportedCache: boolean;
248
+ };
249
+ export type ToolStats = {
250
+ meta: string[];
251
+ metaBytes: number;
252
+ failed: string[];
253
+ evicted: boolean;
254
+ started: Map<string, number>;
255
+ compacted: number;
256
+ };
240
257
  export type TokenUsageLike = {
241
258
  input?: number;
242
259
  output?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,9 +1,11 @@
1
1
  /** Fetches the live free-pi model catalog. */
2
2
 
3
+ import { resolveToken } from "../auth/token.js";
3
4
  import {
4
5
  CATALOG_DISK_TTL_MS,
5
6
  CATALOG_TIMEOUT_MS,
6
7
  CATALOG_TTL_MS,
8
+ COST_EXPERIMENT_HEADER,
7
9
  } from "../constants.js";
8
10
  import type { Deps } from "../deps.js";
9
11
  import type { Catalog } from "../types.js";
@@ -44,8 +46,16 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
44
46
  if (state.catalogPromise) return state.catalogPromise;
45
47
  const pending = (async () => {
46
48
  try {
49
+ // The CLI asks for the catalog with its JWT and the cost-experiment
50
+ // header; without both the server may omit `cost_experiment`.
51
+ const token = await resolveToken(deps).catch(() => undefined);
52
+ const headers: Record<string, string> = {
53
+ accept: "application/json",
54
+ [COST_EXPERIMENT_HEADER]: "1",
55
+ };
56
+ if (token) headers.authorization = `Bearer ${token}`;
47
57
  const response = await fetch(`${resolveBaseUrl()}/client-version`, {
48
- headers: { accept: "application/json" },
58
+ headers,
49
59
  signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
50
60
  });
51
61
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -1,7 +1,10 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
2
 
3
3
  import {
4
+ COMPACT100_CONTEXT_WINDOW,
4
5
  CONTEXT_WINDOW,
6
+ DEFAULT_REASONING_EFFORT,
7
+ DEFAULT_THINKING_LEVELS,
5
8
  MAX_OUTPUT_TOKENS,
6
9
  } from "../constants.js";
7
10
  import type {
@@ -13,7 +16,7 @@ import type {
13
16
  ReasoningOption,
14
17
  RegistryCandidate,
15
18
  } from "../types.js";
16
- import { creditsToUsd, positiveNumber } from "../utils/numbers.js";
19
+ import { positiveNumber } from "../utils/numbers.js";
17
20
  import { cleanText } from "../utils/text.js";
18
21
 
19
22
  export type VariantMap = Record<string, Record<string, unknown>>;
@@ -63,34 +66,14 @@ export function displayName(model: CatalogModel): string {
63
66
  }
64
67
 
65
68
  export function modelCost(
66
- model: CatalogModel,
67
- capability?: ModelsDevModel,
69
+ _model: CatalogModel,
70
+ _capability?: ModelsDevModel,
68
71
  ): ModelDefinition["cost"] {
69
- const zero = { input: 0, output: 0, cache_read: 0, cache_write: 0 };
70
- if (model.free === true) return zero;
71
- const input =
72
- creditsToUsd(model.input_credits_per_mtok) ||
73
- positiveNumber(capability?.cost?.input) ||
74
- 0;
75
- const output =
76
- creditsToUsd(model.output_credits_per_mtok) ||
77
- positiveNumber(capability?.cost?.output) ||
78
- 0;
79
- if (input > 0 || output > 0) {
80
- return {
81
- input,
82
- output,
83
- cache_read:
84
- creditsToUsd(model.cache_read_credits_per_mtok) ||
85
- positiveNumber(capability?.cost?.cache_read) ||
86
- input,
87
- cache_write:
88
- creditsToUsd(model.cache_write_credits_per_mtok) ||
89
- positiveNumber(capability?.cost?.cache_write) ||
90
- input,
91
- };
92
- }
93
- return zero;
72
+ // free-pi bills in credits against a daily allowance; it does not charge
73
+ // per-token USD. The provider CLI registers every model with zero cost and
74
+ // shows the real usage through /usage, so publishing reseller prices here
75
+ // would only invent a cost the account never pays.
76
+ return { input: 0, output: 0, cache_read: 0, cache_write: 0 };
94
77
  }
95
78
 
96
79
  export function modelRegistryCandidates(
@@ -175,42 +158,30 @@ export function modelCapability(
175
158
  return best;
176
159
  }
177
160
 
178
- function budgetVariants(
179
- option: Extract<ReasoningOption, { type: "budget_tokens" }>,
180
- outputLimit: number,
181
- variants: VariantMap,
182
- ): void {
183
- const ceiling = Math.max(
184
- 1,
185
- Math.min(
186
- positiveNumber(option.max) ?? outputLimit - 1024,
187
- outputLimit - 1024,
188
- MAX_OUTPUT_TOKENS - 1024,
189
- ),
190
- );
191
- const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
192
- const high = Math.min(
193
- Math.max(floor, Math.floor((ceiling + 1) / 2)),
194
- ceiling,
195
- );
196
- for (const [level, budget] of [
197
- ["high", high],
198
- ["max", ceiling],
199
- ] as const) {
200
- variants[level] = {
201
- reasoningEffort: level,
202
- thinking_budget: budget,
203
- thinking: { type: "enabled", budget_tokens: budget },
204
- };
205
- }
161
+ /**
162
+ * free-pi's openai-compatible route only understands `reasoning_effort`.
163
+ * pi's `thinking_budget` and `thinking` fields are dropped by OpenCode's
164
+ * lowering, so advertising them would be inert. Budget-style catalogs still
165
+ * expose their top levels as effort variants.
166
+ */
167
+ function budgetVariants(variants: VariantMap): void {
168
+ variants.high = { reasoningEffort: "high" };
169
+ variants.max = { reasoningEffort: "max" };
206
170
  }
207
171
 
208
172
  export function modelVariants(
209
173
  options: ReasoningOption[] | undefined,
210
- outputLimit: number,
174
+ _outputLimit: number,
211
175
  ): VariantMap {
212
176
  const variants: VariantMap = {};
213
- if (!options || options.length === 0) return variants;
177
+ // The provider CLI offers these levels to every reasoning model because its
178
+ // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
179
+ if (!options || options.length === 0) {
180
+ for (const level of DEFAULT_THINKING_LEVELS) {
181
+ variants[level] = { reasoningEffort: level };
182
+ }
183
+ return variants;
184
+ }
214
185
  const effort = options.find(
215
186
  (option): option is Extract<ReasoningOption, { type: "effort" }> =>
216
187
  option.type === "effort",
@@ -225,17 +196,21 @@ export function modelVariants(
225
196
  variants.none = { reasoningEffort: "none" };
226
197
  variants.high = { reasoningEffort: "high" };
227
198
  }
228
- const budget = options.find(
229
- (option): option is Extract<ReasoningOption, { type: "budget_tokens" }> =>
230
- option.type === "budget_tokens",
231
- );
232
- if (budget) budgetVariants(budget, outputLimit, variants);
199
+ if (options.some((option) => option.type === "budget_tokens")) {
200
+ budgetVariants(variants);
201
+ }
233
202
  return variants;
234
203
  }
235
204
 
205
+ export type BuildModelsOptions = {
206
+ /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
207
+ compact100?: boolean;
208
+ };
209
+
236
210
  export function buildModels(
237
211
  models: CatalogModel[],
238
212
  candidates: RegistryCandidate[] = [],
213
+ options: BuildModelsOptions = {},
239
214
  ): ModelMap {
240
215
  const result: ModelMap = {};
241
216
  for (const model of models) {
@@ -244,21 +219,34 @@ export function buildModels(
244
219
  const reasoning = model.reasoning ?? capability?.reasoning ?? true;
245
220
  const reasoningOptions =
246
221
  model.reasoning_options ?? capability?.reasoning_options;
247
- const limitContext =
222
+ // free-pi enforces a 200k input window and 32k output cap on every model,
223
+ // regardless of what models.dev reports for the upstream provider. The
224
+ // provider CLI registers exactly these limits, so clamp to them here too:
225
+ // an advertised 1M window would let OpenCode grow a session past the
226
+ // server's real ceiling and fail with `context_too_long` instead of
227
+ // compacting.
228
+ const contextCeiling = options.compact100
229
+ ? COMPACT100_CONTEXT_WINDOW
230
+ : CONTEXT_WINDOW;
231
+ const limitContext = Math.min(
248
232
  positiveNumber(
249
233
  model.context_window,
250
234
  model.contextWindow,
251
235
  model.limit?.context,
252
236
  capability?.limit?.context,
253
- ) ?? CONTEXT_WINDOW;
254
- const limitOutput =
237
+ ) ?? contextCeiling,
238
+ contextCeiling,
239
+ );
240
+ const limitOutput = Math.min(
255
241
  positiveNumber(
256
242
  model.max_tokens,
257
243
  model.maxTokens,
258
244
  model.max_output_tokens,
259
245
  model.limit?.output,
260
246
  capability?.limit?.output,
261
- ) ?? MAX_OUTPUT_TOKENS;
247
+ ) ?? MAX_OUTPUT_TOKENS,
248
+ MAX_OUTPUT_TOKENS,
249
+ );
262
250
  result[model.id] = {
263
251
  id: model.id,
264
252
  name: displayName(model),
@@ -270,6 +258,10 @@ export function buildModels(
270
258
  reasoning,
271
259
  reasoning_options: reasoningOptions,
272
260
  variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
261
+ ...(reasoning
262
+ ? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
263
+ : {}),
264
+ enabled: model.unavailable !== true,
273
265
  temperature: model.temperature ?? capability?.temperature ?? true,
274
266
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
275
267
  attachment: model.attachment ?? capability?.attachment ?? false,
package/src/catalog/v2.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  /** Converts internal model definitions into OpenCode V2 provider records. */
2
2
 
3
3
  import {
4
+ CHUNK_TIMEOUT_MS,
4
5
  CONTEXT_WINDOW,
6
+ HEADER_TIMEOUT_MS,
5
7
  MAX_OUTPUT_TOKENS,
6
8
  OPENAI_COMPATIBLE_PACKAGE,
7
9
  PROVIDER_ID,
@@ -30,12 +32,16 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
30
32
  ...(model.family ? { family: model.family } : {}),
31
33
  capabilities: {
32
34
  tools: model.tool_call !== false,
33
- input: model.modalities?.input ?? ["text"],
34
- output: model.modalities?.output ?? ["text"],
35
+ // The provider CLI registers every free-pi model as text-only. An
36
+ // advertised image input would let OpenCode send media the server
37
+ // does not accept.
38
+ input: ["text"],
39
+ output: ["text"],
35
40
  ...(model.temperature === undefined
36
41
  ? {}
37
42
  : { temperature: model.temperature }),
38
43
  },
44
+ ...(model.settings ? { settings: model.settings } : {}),
39
45
  variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
40
46
  id,
41
47
  settings,
@@ -52,7 +58,7 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
52
58
  },
53
59
  ],
54
60
  status: model.status === "deprecated" ? "deprecated" : "active",
55
- enabled: true,
61
+ enabled: model.enabled !== false,
56
62
  limit: {
57
63
  context: model.limit?.context ?? CONTEXT_WINDOW,
58
64
  output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
@@ -75,6 +81,13 @@ export function baseProviderInfo(
75
81
  settings: {
76
82
  baseURL: completionsBaseUrl(),
77
83
  apiKey: token ?? "free-pi",
84
+ // free-pi is ad-supported and bills credits, so OpenCode's keep-alive
85
+ // warmer would spend requests the provider CLI never makes. pi keeps
86
+ // warming off for free-pi and the economics are always zero.
87
+ cache: { warming: false },
88
+ // Match pi's HTTP idle timeout for both response headers and chunks.
89
+ headerTimeout: HEADER_TIMEOUT_MS,
90
+ chunkTimeout: CHUNK_TIMEOUT_MS,
78
91
  },
79
92
  };
80
93
  }
package/src/constants.ts CHANGED
@@ -19,6 +19,49 @@ export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
19
19
  export const EFFICIENCY_RULE =
20
20
  "- When several independent reads or searches are needed, issue them in the same turn.";
21
21
 
22
+ /**
23
+ * The provider CLI registers every free-pi model with reasoning enabled and
24
+ * defaults to thinking off. OpenCode only sends `reasoning_effort` when a
25
+ * variant or model setting provides one, so the model carries the off default
26
+ * and the picker offers the levels the CLI would.
27
+ */
28
+ export const DEFAULT_REASONING_EFFORT = "none";
29
+ export const DEFAULT_THINKING_LEVELS = [
30
+ "minimal",
31
+ "low",
32
+ "medium",
33
+ "high",
34
+ ] as const;
35
+
36
+ /** pi-ai's HTTP idle timeout for headers and body chunks. */
37
+ export const HEADER_TIMEOUT_MS = 300_000;
38
+ export const CHUNK_TIMEOUT_MS = 300_000;
39
+
40
+ /** pi's retry policy: 3 retries, 2s base, 60s cap. */
41
+ export const RETRY_MAX_RETRIES = 3;
42
+ export const RETRY_BASE_DELAY_MS = 2_000;
43
+ export const RETRY_MAX_DELAY_MS = 60_000;
44
+
45
+ /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
46
+ export const CACHE_TTL_MS = 5 * 60_000;
47
+ export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
48
+ export const CACHE_MISS_NOTICE_TOKENS = 20_000;
49
+
50
+ /** Tool outcome headers emitted by the free-pi provider CLI. */
51
+ export const TOOL_META_HEADER = "x-freepi-tool-meta";
52
+ export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
53
+ export const COMPACTED_HEADER = "x-freepi-compacted";
54
+ export const TOOL_META_BUDGET = 1_500;
55
+ export const TOOL_ID_LIMIT = 50;
56
+
57
+ /**
58
+ * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
59
+ * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
60
+ * 117_647 is the smallest window that keeps that trigger at 100k.
61
+ */
62
+ export const COMPACT100_TRIGGER_TOKENS = 100_000;
63
+ export const COMPACT100_CONTEXT_WINDOW = 117_647;
64
+
22
65
  export const SESSION_TRACK_LIMIT = 200;
23
66
  export const AUTH_SKEW_MS = 60_000;
24
67
  export const AUTH_TIMEOUT_MS = 15 * 60_000;