@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.
@@ -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,18 @@
1
+ /**
2
+ * Builds session titles locally.
3
+ *
4
+ * free-pi charges credits and shows ads per model request, and the CLI never
5
+ * spends a turn on a title. OpenCode asks the selected model for a title, so
6
+ * the title hook answers from the first user message instead: the session gets
7
+ * a real name immediately, no ad is fetched, and a failed title request can
8
+ * never leave the session stuck on "New session".
9
+ */
10
+ type TitleMessage = {
11
+ role?: unknown;
12
+ type?: unknown;
13
+ text?: unknown;
14
+ content?: unknown;
15
+ };
16
+ /** Derives a title from the first meaningful line of the title request. */
17
+ export declare function localTitle(messages: readonly TitleMessage[] | undefined): string;
18
+ export {};
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Builds session titles locally.
3
+ *
4
+ * free-pi charges credits and shows ads per model request, and the CLI never
5
+ * spends a turn on a title. OpenCode asks the selected model for a title, so
6
+ * the title hook answers from the first user message instead: the session gets
7
+ * a real name immediately, no ad is fetched, and a failed title request can
8
+ * never leave the session stuck on "New session".
9
+ */
10
+ const MAX_TITLE_LENGTH = 60;
11
+ const MAX_SOURCE_LENGTH = 4_000;
12
+ const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
13
+ const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
14
+ const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
15
+ const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
16
+ const XML_LINE = /^<\/?[a-z][^>]*>$/i;
17
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
18
+ function textOf(content) {
19
+ if (typeof content === "string")
20
+ return content;
21
+ if (!Array.isArray(content))
22
+ return "";
23
+ return content
24
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
25
+ .map((part) => part.text)
26
+ .join("\n");
27
+ }
28
+ function latestUserText(messages) {
29
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
30
+ const message = messages[index];
31
+ const role = message?.role ?? message?.type;
32
+ if (role !== "user")
33
+ continue;
34
+ const text = typeof message?.text === "string"
35
+ ? message.text
36
+ : textOf(message?.content);
37
+ if (text.trim())
38
+ return text;
39
+ }
40
+ return "";
41
+ }
42
+ /** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
43
+ function sourceText(messages) {
44
+ const raw = latestUserText(messages);
45
+ const block = MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
46
+ return block.slice(0, MAX_SOURCE_LENGTH);
47
+ }
48
+ function cleanLine(line) {
49
+ let value = line.replace(CONTROL, " ").trim();
50
+ if (!value)
51
+ return undefined;
52
+ value = value
53
+ .replace(/^#{1,6}\s+/, "")
54
+ .replace(/^[-*+>]\s+/, "")
55
+ .trim();
56
+ value = value.replace(PREFIX, "").trim();
57
+ if (!value || NOISE.test(value) || XML_LINE.test(value))
58
+ return undefined;
59
+ value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
60
+ return value || undefined;
61
+ }
62
+ function truncate(value) {
63
+ if (value.length <= MAX_TITLE_LENGTH)
64
+ return value;
65
+ const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
66
+ const space = cut.lastIndexOf(" ");
67
+ return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
68
+ }
69
+ /** Derives a title from the first meaningful line of the title request. */
70
+ export function localTitle(messages) {
71
+ if (!Array.isArray(messages) || messages.length === 0)
72
+ return "Session";
73
+ const lines = sourceText(messages)
74
+ .split(/\r?\n/)
75
+ .map(cleanLine)
76
+ .filter((line) => Boolean(line));
77
+ const first = lines[0];
78
+ if (!first)
79
+ return "Session";
80
+ return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
81
+ }
@@ -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;
@@ -11,6 +11,8 @@ export type RuntimeState = {
11
11
  registryAttemptAt: number;
12
12
  registryPromise?: Promise<ModelRegistry | undefined>;
13
13
  costExperimentArm?: string;
14
+ lastCatalogNotice?: string;
15
+ lastQuotaNotice?: string;
14
16
  catalogModels: Catalog;
15
17
  outputLimits: Map<string, number>;
16
18
  quotaCache?: QuotaSnapshot;
@@ -39,5 +41,8 @@ export type RuntimeState = {
39
41
  pendingAdTurns: Map<string, AdTurn>;
40
42
  adImpressions: Map<string, Promise<void>>;
41
43
  trackedModels: Map<string, TrackedModel>;
44
+ cacheMisses: Map<string, CacheMissState>;
45
+ toolStats: Map<string, ToolStats>;
46
+ subagentSessions: Set<string>;
42
47
  };
43
48
  export declare function createRuntimeState(): RuntimeState;
package/dist/state.js CHANGED
@@ -22,5 +22,8 @@ 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(),
27
+ subagentSessions: new Set(),
25
28
  };
26
29
  }
package/dist/types.d.ts CHANGED
@@ -87,8 +87,10 @@ export type RegistryCandidate = {
87
87
  model: ModelsDevModel;
88
88
  };
89
89
  export type Catalog = {
90
+ min?: string;
90
91
  latest?: string;
91
92
  default_model?: string;
93
+ notice?: string;
92
94
  models?: CatalogModel[];
93
95
  cost_experiment?: {
94
96
  arm?: string;
@@ -103,6 +105,9 @@ export type ModelDefinition = {
103
105
  reasoning: boolean;
104
106
  reasoning_options?: ReasoningOption[];
105
107
  variants: Record<string, Record<string, unknown>>;
108
+ /** Model-level provider options, such as the default reasoning effort. */
109
+ settings?: Record<string, unknown>;
110
+ enabled: boolean;
106
111
  temperature: boolean;
107
112
  tool_call: boolean;
108
113
  attachment: boolean;
@@ -237,6 +242,20 @@ export type TrackedModel = {
237
242
  providerID: string;
238
243
  modelID: string;
239
244
  };
245
+ export type CacheMissState = {
246
+ promptTokens: number;
247
+ at: number;
248
+ modelKey: string;
249
+ reportedCache: boolean;
250
+ };
251
+ export type ToolStats = {
252
+ meta: string[];
253
+ metaBytes: number;
254
+ failed: string[];
255
+ evicted: boolean;
256
+ started: Map<string, number>;
257
+ compacted: number;
258
+ };
240
259
  export type TokenUsageLike = {
241
260
  input?: number;
242
261
  output?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs",
27
+ "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
package/src/api/quota.ts CHANGED
@@ -86,6 +86,14 @@ export async function fetchQuota(
86
86
  : undefined;
87
87
  if (meResponse?.ok || statsResponse?.ok)
88
88
  rememberTokenCheck(deps, token, "ok");
89
+ if (
90
+ typeof me?.notice === "string" &&
91
+ me.notice &&
92
+ me.notice !== deps.state.lastQuotaNotice
93
+ ) {
94
+ deps.state.lastQuotaNotice = me.notice;
95
+ deps.log.info("free-pi account notice", { notice: me.notice });
96
+ }
89
97
  const snapshot: QuotaSnapshot = {
90
98
  fetchedAt: Date.now(),
91
99
  token,
@@ -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";
@@ -33,6 +35,14 @@ function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
33
35
  typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
34
36
  ? arm
35
37
  : undefined;
38
+ if (
39
+ typeof catalog.notice === "string" &&
40
+ catalog.notice &&
41
+ catalog.notice !== state.lastCatalogNotice
42
+ ) {
43
+ state.lastCatalogNotice = catalog.notice;
44
+ deps.log.info("free-pi catalog notice", { notice: catalog.notice });
45
+ }
36
46
  state.cachedCatalog = catalog;
37
47
  state.cachedCatalogAt = Date.now();
38
48
  return catalog;
@@ -44,8 +54,16 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
44
54
  if (state.catalogPromise) return state.catalogPromise;
45
55
  const pending = (async () => {
46
56
  try {
57
+ // The CLI asks for the catalog with its JWT and the cost-experiment
58
+ // header; without both the server may omit `cost_experiment`.
59
+ const token = await resolveToken(deps).catch(() => undefined);
60
+ const headers: Record<string, string> = {
61
+ accept: "application/json",
62
+ [COST_EXPERIMENT_HEADER]: "1",
63
+ };
64
+ if (token) headers.authorization = `Bearer ${token}`;
47
65
  const response = await fetch(`${resolveBaseUrl()}/client-version`, {
48
- headers: { accept: "application/json" },
66
+ headers,
49
67
  signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
50
68
  });
51
69
  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 {
@@ -155,42 +158,30 @@ export function modelCapability(
155
158
  return best;
156
159
  }
157
160
 
158
- function budgetVariants(
159
- option: Extract<ReasoningOption, { type: "budget_tokens" }>,
160
- outputLimit: number,
161
- variants: VariantMap,
162
- ): void {
163
- const ceiling = Math.max(
164
- 1,
165
- Math.min(
166
- positiveNumber(option.max) ?? outputLimit - 1024,
167
- outputLimit - 1024,
168
- MAX_OUTPUT_TOKENS - 1024,
169
- ),
170
- );
171
- const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
172
- const high = Math.min(
173
- Math.max(floor, Math.floor((ceiling + 1) / 2)),
174
- ceiling,
175
- );
176
- for (const [level, budget] of [
177
- ["high", high],
178
- ["max", ceiling],
179
- ] as const) {
180
- variants[level] = {
181
- reasoningEffort: level,
182
- thinking_budget: budget,
183
- thinking: { type: "enabled", budget_tokens: budget },
184
- };
185
- }
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" };
186
170
  }
187
171
 
188
172
  export function modelVariants(
189
173
  options: ReasoningOption[] | undefined,
190
- outputLimit: number,
174
+ _outputLimit: number,
191
175
  ): VariantMap {
192
176
  const variants: VariantMap = {};
193
- 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
+ }
194
185
  const effort = options.find(
195
186
  (option): option is Extract<ReasoningOption, { type: "effort" }> =>
196
187
  option.type === "effort",
@@ -205,17 +196,21 @@ export function modelVariants(
205
196
  variants.none = { reasoningEffort: "none" };
206
197
  variants.high = { reasoningEffort: "high" };
207
198
  }
208
- const budget = options.find(
209
- (option): option is Extract<ReasoningOption, { type: "budget_tokens" }> =>
210
- option.type === "budget_tokens",
211
- );
212
- if (budget) budgetVariants(budget, outputLimit, variants);
199
+ if (options.some((option) => option.type === "budget_tokens")) {
200
+ budgetVariants(variants);
201
+ }
213
202
  return variants;
214
203
  }
215
204
 
205
+ export type BuildModelsOptions = {
206
+ /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
207
+ compact100?: boolean;
208
+ };
209
+
216
210
  export function buildModels(
217
211
  models: CatalogModel[],
218
212
  candidates: RegistryCandidate[] = [],
213
+ options: BuildModelsOptions = {},
219
214
  ): ModelMap {
220
215
  const result: ModelMap = {};
221
216
  for (const model of models) {
@@ -230,14 +225,17 @@ export function buildModels(
230
225
  // an advertised 1M window would let OpenCode grow a session past the
231
226
  // server's real ceiling and fail with `context_too_long` instead of
232
227
  // compacting.
228
+ const contextCeiling = options.compact100
229
+ ? COMPACT100_CONTEXT_WINDOW
230
+ : CONTEXT_WINDOW;
233
231
  const limitContext = Math.min(
234
232
  positiveNumber(
235
233
  model.context_window,
236
234
  model.contextWindow,
237
235
  model.limit?.context,
238
236
  capability?.limit?.context,
239
- ) ?? CONTEXT_WINDOW,
240
- CONTEXT_WINDOW,
237
+ ) ?? contextCeiling,
238
+ contextCeiling,
241
239
  );
242
240
  const limitOutput = Math.min(
243
241
  positiveNumber(
@@ -260,6 +258,10 @@ export function buildModels(
260
258
  reasoning,
261
259
  reasoning_options: reasoningOptions,
262
260
  variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
261
+ ...(reasoning
262
+ ? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
263
+ : {}),
264
+ enabled: model.unavailable !== true,
263
265
  temperature: model.temperature ?? capability?.temperature ?? true,
264
266
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
265
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
@@ -15,10 +15,54 @@ export const CONTEXT_WINDOW = 200_000;
15
15
  export const MAX_OUTPUT_TOKENS = 32_768;
16
16
 
17
17
  export const AD_CONTEXT_HEADER = "x-ad-context";
18
+ export const SUBAGENT_HEADER = "x-freepi-subagent";
18
19
  export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
19
20
  export const EFFICIENCY_RULE =
20
21
  "- When several independent reads or searches are needed, issue them in the same turn.";
21
22
 
23
+ /**
24
+ * The provider CLI registers every free-pi model with reasoning enabled and
25
+ * defaults to thinking off. OpenCode only sends `reasoning_effort` when a
26
+ * variant or model setting provides one, so the model carries the off default
27
+ * and the picker offers the levels the CLI would.
28
+ */
29
+ export const DEFAULT_REASONING_EFFORT = "none";
30
+ export const DEFAULT_THINKING_LEVELS = [
31
+ "minimal",
32
+ "low",
33
+ "medium",
34
+ "high",
35
+ ] as const;
36
+
37
+ /** pi-ai's HTTP idle timeout for headers and body chunks. */
38
+ export const HEADER_TIMEOUT_MS = 300_000;
39
+ export const CHUNK_TIMEOUT_MS = 300_000;
40
+
41
+ /** pi's retry policy: 3 retries, 2s base, 60s cap. */
42
+ export const RETRY_MAX_RETRIES = 3;
43
+ export const RETRY_BASE_DELAY_MS = 2_000;
44
+ export const RETRY_MAX_DELAY_MS = 60_000;
45
+
46
+ /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
47
+ export const CACHE_TTL_MS = 5 * 60_000;
48
+ export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
49
+ export const CACHE_MISS_NOTICE_TOKENS = 20_000;
50
+
51
+ /** Tool outcome headers emitted by the free-pi provider CLI. */
52
+ export const TOOL_META_HEADER = "x-freepi-tool-meta";
53
+ export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
54
+ export const COMPACTED_HEADER = "x-freepi-compacted";
55
+ export const TOOL_META_BUDGET = 1_500;
56
+ export const TOOL_ID_LIMIT = 50;
57
+
58
+ /**
59
+ * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
60
+ * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
61
+ * 117_647 is the smallest window that keeps that trigger at 100k.
62
+ */
63
+ export const COMPACT100_TRIGGER_TOKENS = 100_000;
64
+ export const COMPACT100_CONTEXT_WINDOW = 117_647;
65
+
22
66
  export const SESSION_TRACK_LIMIT = 200;
23
67
  export const AUTH_SKEW_MS = 60_000;
24
68
  export const AUTH_TIMEOUT_MS = 15 * 60_000;