@eduardo191labs/opencode-free-pi 0.5.6 → 0.6.2

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.
Files changed (49) hide show
  1. package/README.md +64 -55
  2. package/dist/catalog/catalog.js +1 -21
  3. package/dist/catalog/live.d.ts +71 -0
  4. package/dist/catalog/live.js +301 -0
  5. package/dist/catalog/models.d.ts +13 -2
  6. package/dist/catalog/models.js +69 -21
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/catalog/v2.js +5 -7
  9. package/dist/constants.d.ts +24 -21
  10. package/dist/constants.js +24 -19
  11. package/dist/logging.js +2 -2
  12. package/dist/plugin.js +26 -2
  13. package/dist/session/events.js +2 -3
  14. package/dist/session/hooks.js +4 -12
  15. package/dist/state.d.ts +1 -15
  16. package/dist/state.js +0 -3
  17. package/dist/tools/vision-queue.d.ts +1 -1
  18. package/dist/tools/vision-queue.js +5 -5
  19. package/dist/tools/vision.js +24 -35
  20. package/dist/tools/web.js +39 -44
  21. package/dist/types.d.ts +5 -9
  22. package/dist/utils/data-dir.d.ts +3 -0
  23. package/dist/utils/data-dir.js +12 -0
  24. package/package.json +2 -2
  25. package/src/catalog/catalog.ts +0 -25
  26. package/src/catalog/live.ts +361 -0
  27. package/src/catalog/models.ts +92 -23
  28. package/src/catalog/registry.ts +6 -21
  29. package/src/catalog/v2.ts +5 -7
  30. package/src/constants.ts +24 -22
  31. package/src/logging.ts +2 -2
  32. package/src/plugin.ts +34 -2
  33. package/src/session/events.ts +6 -3
  34. package/src/session/hooks.ts +4 -18
  35. package/src/state.ts +0 -18
  36. package/src/tools/vision-queue.ts +5 -5
  37. package/src/tools/vision.ts +26 -38
  38. package/src/tools/web.ts +49 -59
  39. package/src/types.ts +5 -8
  40. package/src/utils/data-dir.ts +14 -0
  41. package/dist/session/cache.d.ts +0 -15
  42. package/dist/session/cache.js +0 -57
  43. package/dist/tools/spend-cache.d.ts +0 -15
  44. package/dist/tools/spend-cache.js +0 -64
  45. package/dist/utils/cache.d.ts +0 -7
  46. package/dist/utils/cache.js +0 -45
  47. package/src/session/cache.ts +0 -82
  48. package/src/tools/spend-cache.ts +0 -79
  49. package/src/utils/cache.ts +0 -49
@@ -1,5 +1,6 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
2
  import type { Catalog, CatalogModel, MeResponse, ModelDefinition, ModelRegistry, ModelsDevModel, ReasoningOption, RegistryCandidate } from "../types.js";
3
+ import type { LiveLimits } from "./live.js";
3
4
  export type VariantMap = Record<string, Record<string, unknown>>;
4
5
  export type ModelMap = Record<string, ModelDefinition>;
5
6
  export declare function usableModels(catalog: Catalog | undefined): CatalogModel[];
@@ -12,6 +13,12 @@ export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevM
12
13
  export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
13
14
  export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
14
15
  export declare function modelVariants(options: ReasoningOption[] | undefined, _outputLimit: number): VariantMap;
16
+ /**
17
+ * The levels the model actually exposes, so OpenCode's picker and the
18
+ * `reasoning_effort` values the plugin sends come from the same list. The
19
+ * gateway accepts every level for every model, so the CLI set always applies.
20
+ */
21
+ export declare function effectiveReasoningOptions(options: ReasoningOption[] | undefined, variants: VariantMap): ReasoningOption[];
15
22
  export declare function isReasoningEffort(value: unknown): value is string;
16
23
  /**
17
24
  * The effort sent when no variant is selected. `false` leaves the gateway's
@@ -21,14 +28,18 @@ export declare function isReasoningEffort(value: unknown): value is string;
21
28
  */
22
29
  export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
23
30
  export type BuildModelsOptions = {
24
- /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
25
- compact100?: boolean;
26
31
  /**
27
32
  * Effort sent when the user has not picked a variant. `false` keeps the
28
33
  * gateway default. Defaults to `medium` because an unset effort makes the
29
34
  * free models answer before they reason.
30
35
  */
31
36
  reasoningEffort?: string | false;
37
+ /**
38
+ * Limits and capabilities observed from the live gateway. The verified
39
+ * window replaces the compiled one, and per-model observations prove what the
40
+ * server really accepted for this account.
41
+ */
42
+ live?: LiveLimits;
32
43
  };
33
44
  /**
34
45
  * What the signed-in account can actually use, derived from `GET /me`.
@@ -1,5 +1,5 @@
1
1
  /** Turns the free-pi catalog and models.dev registry into model definitions. */
2
- import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } from "../constants.js";
2
+ import { CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, REASONING_EFFORTS, } 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) {
@@ -129,7 +129,8 @@ export function modelVariants(options, _outputLimit) {
129
129
  // The provider CLI registers every model with `reasoning: true` and an unset
130
130
  // `thinkingLevelMap`, so it offers these levels to every model. models.dev
131
131
  // lists fewer levels for some upstream models, but the gateway accepts the
132
- // CLI's set, and hiding levels only makes the picker disagree with the CLI.
132
+ // CLI's set (including `max`), and hiding levels only makes the picker
133
+ // disagree with the CLI.
133
134
  const variants = {};
134
135
  for (const level of DEFAULT_THINKING_LEVELS) {
135
136
  variants[level] = { reasoningEffort: level };
@@ -147,6 +148,20 @@ export function modelVariants(options, _outputLimit) {
147
148
  }
148
149
  return variants;
149
150
  }
151
+ /**
152
+ * The levels the model actually exposes, so OpenCode's picker and the
153
+ * `reasoning_effort` values the plugin sends come from the same list. The
154
+ * gateway accepts every level for every model, so the CLI set always applies.
155
+ */
156
+ export function effectiveReasoningOptions(options, variants) {
157
+ const values = Object.keys(variants);
158
+ const declared = options?.find((option) => option.type === "effort")?.values;
159
+ for (const value of declared ?? []) {
160
+ if (!values.includes(value))
161
+ values.push(value);
162
+ }
163
+ return values.length > 0 ? [{ type: "effort", values }] : [];
164
+ }
150
165
  export function isReasoningEffort(value) {
151
166
  return (typeof value === "string" &&
152
167
  REASONING_EFFORTS.includes(value));
@@ -206,6 +221,29 @@ export function filterAccessibleModels(models, access) {
206
221
  return access.hasAllowance || access.walletCredits > 0;
207
222
  });
208
223
  }
224
+ const KNOWN_INPUT_MODALITIES = new Set([
225
+ "text",
226
+ "image",
227
+ "audio",
228
+ "video",
229
+ "pdf",
230
+ ]);
231
+ /**
232
+ * Native modalities for the chat route. models.dev describes the upstream
233
+ * model, and the gateway forwards image parts to multimodal upstreams, so an
234
+ * image-capable model is advertised as such. Output is always text: free-pi has
235
+ * no image results on the chat route, and the plugin registers every model as
236
+ * zero-cost text output.
237
+ */
238
+ function modelModalities(model, capability) {
239
+ const declared = model.modalities?.input ?? capability?.modalities?.input;
240
+ const input = (declared ?? ["text"]).filter((value) => KNOWN_INPUT_MODALITIES.has(value));
241
+ if (input.length === 0)
242
+ input.push("text");
243
+ if (!input.includes("text"))
244
+ input.unshift("text");
245
+ return { input, output: ["text"] };
246
+ }
209
247
  export function buildModels(models, candidates = [], options = {}) {
210
248
  const result = {};
211
249
  for (const model of models) {
@@ -217,20 +255,31 @@ export function buildModels(models, candidates = [], options = {}) {
217
255
  // explicit answer, otherwise keep reasoning on like the CLI does.
218
256
  const reasoning = model.reasoning ?? true;
219
257
  const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
220
- // free-pi enforces a 200k input window and 32k output cap on every model,
221
- // regardless of what models.dev reports for the upstream provider. The
222
- // provider CLI registers exactly these limits, so clamp to them here too:
223
- // an advertised 1M window would let OpenCode grow a session past the
224
- // server's real ceiling and fail with `context_too_long` instead of
225
- // compacting.
226
- const contextCeiling = options.compact100
227
- ? COMPACT100_CONTEXT_WINDOW
228
- : CONTEXT_WINDOW;
258
+ // free-pi enforces a context window on every model regardless of what
259
+ // models.dev reports for the upstream provider. The provider CLI starts at
260
+ // 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
261
+ // measures it (growing past 200k when the gateway accepts more) and the
262
+ // result is used here from the next start. Real steps also prove the gateway
263
+ // accepted at least their prompt size. A published catalog field still wins,
264
+ // but only inside that measured ceiling, so an advertised 1M window can
265
+ // never push a session past what the gateway takes.
266
+ const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
267
+ const contextCeiling = Math.min(MAX_CONTEXT_WINDOW, Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed));
229
268
  const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
230
- 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);
269
+ // Reasoning shares the output budget. When models.dev knows the upstream
270
+ // model emits more than the CLI's 32k, advertise that larger budget (up to a
271
+ // sane ceiling) instead of truncating the chain of thought.
272
+ 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_CEILING);
231
273
  const defaultEffort = reasoning
232
274
  ? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
233
275
  : undefined;
276
+ const variants = reasoning
277
+ ? modelVariants(reasoningOptions, limitOutput)
278
+ : {};
279
+ const modalities = modelModalities(model, capability);
280
+ const declaredOptions = reasoning
281
+ ? effectiveReasoningOptions(reasoningOptions, variants)
282
+ : undefined;
234
283
  result[model.id] = {
235
284
  id: model.id,
236
285
  name: displayName(model),
@@ -239,22 +288,21 @@ export function buildModels(models, candidates = [], options = {}) {
239
288
  (model.section === "defense" ? "defense" : ""),
240
289
  release_date: model.release_date ?? capability?.release_date,
241
290
  reasoning,
242
- reasoning_options: reasoningOptions,
243
- variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
291
+ ...(declaredOptions && declaredOptions.length > 0
292
+ ? { reasoning_options: declaredOptions }
293
+ : {}),
294
+ variants,
244
295
  ...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
245
296
  enabled: model.unavailable !== true,
246
297
  temperature: model.temperature ?? capability?.temperature ?? true,
247
298
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
248
- attachment: model.attachment ?? capability?.attachment ?? false,
299
+ attachment: model.attachment ??
300
+ capability?.attachment ??
301
+ modalities.input.includes("image"),
249
302
  interleaved: model.interleaved ?? capability?.interleaved,
250
303
  cost: modelCost(model, capability),
251
304
  limit: { context: limitContext, output: limitOutput },
252
- modalities: {
253
- input: model.modalities?.input ??
254
- capability?.modalities?.input ?? ["text"],
255
- output: model.modalities?.output ??
256
- capability?.modalities?.output ?? ["text"],
257
- },
305
+ modalities,
258
306
  status: model.unavailable ? "deprecated" : "active",
259
307
  };
260
308
  }
@@ -1,9 +1,7 @@
1
1
  /** Fetches the models.dev capability registry. */
2
- import { REGISTRY_ATTEMPTS, REGISTRY_DISK_TTL_MS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
2
+ import { REGISTRY_ATTEMPTS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
3
3
  import { sleep } from "../utils/async.js";
4
- import { readCache, writeCache } from "../utils/cache.js";
5
4
  import { modelsRegistryUrl } from "../utils/urls.js";
6
- const CACHE_FILE = "models-dev.json";
7
5
  function isRegistry(value) {
8
6
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
7
  }
@@ -54,7 +52,6 @@ export function refreshModelsRegistry(deps) {
54
52
  }
55
53
  state.cachedRegistry = registry;
56
54
  state.cachedRegistryAt = Date.now();
57
- void writeCache(CACHE_FILE, registry);
58
55
  return registry;
59
56
  }
60
57
  catch (error) {
@@ -79,18 +76,11 @@ export async function fetchModelsRegistry(deps) {
79
76
  return state.cachedRegistry;
80
77
  }
81
78
  if (!state.cachedRegistry) {
82
- const disk = await readCache(CACHE_FILE, REGISTRY_DISK_TTL_MS);
83
- if (isRegistry(disk)) {
84
- state.cachedRegistry = disk;
85
- state.cachedRegistryAt = Date.now();
86
- // Serve the cached copy immediately and refresh it in the background.
87
- void refreshModelsRegistry(deps);
88
- return disk;
79
+ if (state.registryAttemptAt &&
80
+ Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
81
+ return state.cachedRegistry;
89
82
  }
90
- }
91
- if (state.registryAttemptAt &&
92
- Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
93
- return state.cachedRegistry;
83
+ return refreshModelsRegistry(deps);
94
84
  }
95
85
  return refreshModelsRegistry(deps);
96
86
  }
@@ -13,13 +13,11 @@ export function toV2Models(providerID, models) {
13
13
  ...(model.family ? { family: model.family } : {}),
14
14
  capabilities: {
15
15
  tools: model.tool_call !== false,
16
- // The provider CLI registers every free-pi model as text-only and
17
- // handles images out of band with its vision and image tools. Sending
18
- // native image parts instead makes OpenCode inline every read image
19
- // (hundreds of KB each) into the request, which overflows the 200k
20
- // window and burns the daily allowance on image tokens, so keep the
21
- // advertised capability identical to the CLI.
22
- input: ["text"],
16
+ // models.dev tells us which upstream models accept images. free-pi's
17
+ // gateway forwards image parts, so advertise exactly those modalities.
18
+ // Text-only models keep using the `look_at_image` tool, which keeps
19
+ // screenshots out of the token stream and the daily allowance.
20
+ input: model.modalities?.input ?? ["text"],
23
21
  output: ["text"],
24
22
  ...(model.temperature === undefined
25
23
  ? {}
@@ -7,8 +7,24 @@ export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export declare const DEFAULT_CLIENT_VERSION = "0.6.25";
9
9
  export declare const CONSENT_VERSION = "4";
10
+ /**
11
+ * The provider CLI's window. The gateway enforces its own ceiling but does not
12
+ * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
13
+ * with what the server actually accepts.
14
+ */
10
15
  export declare const CONTEXT_WINDOW = 200000;
16
+ /** Largest window the plugin will ever advertise after measuring the gateway. */
17
+ export declare const MAX_CONTEXT_WINDOW = 1000000;
11
18
  export declare const MAX_OUTPUT_TOKENS = 32768;
19
+ /**
20
+ * Upper bound for a model that publishes a larger output budget. Reasoning
21
+ * tokens share this budget, so a model that can emit more must not be pinned to
22
+ * the CLI's 32k: a long chain of thought would consume it and leave `content`
23
+ * empty.
24
+ */
25
+ export declare const MAX_OUTPUT_TOKENS_CEILING = 131072;
26
+ /** How long a measured gateway window is trusted before checking again. */
27
+ export declare const VERIFY_LIMITS_TTL_MS: number;
12
28
  export declare const AD_CONTEXT_HEADER = "x-ad-context";
13
29
  /**
14
30
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -16,25 +32,25 @@ export declare const AD_CONTEXT_HEADER = "x-ad-context";
16
32
  */
17
33
  export declare const AD_CONTEXT_OPT_OUT = "none";
18
34
  export declare const SUBAGENT_HEADER = "x-freepi-subagent";
19
- export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
- export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
35
  /**
22
36
  * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
37
  * unset makes the gateway answer in a hurry: the free models spend only a few
24
- * dozen reasoning tokens even on tasks that need planning. The plugin therefore
25
- * asks for `medium` by default and keeps the CLI's levels as variants, so
26
- * `none`/`minimal` are still one pick away when speed matters more than care.
38
+ * dozen reasoning tokens even on tasks that need planning. The gateway accepts
39
+ * every level (measured with curl_cffi) but currently does not let the level
40
+ * change how long the upstream thinks, so the plugin also asks for explicit
41
+ * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
42
+ * stay one pick away when speed matters more than care.
27
43
  */
28
- export declare const DEFAULT_REASONING_EFFORT = "medium";
44
+ export declare const DEFAULT_REASONING_EFFORT = "high";
29
45
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
30
- export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high"];
46
+ export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "max"];
31
47
  /**
32
48
  * Injected into every primary free-pi request. OpenCode already supplies the
33
49
  * coding instructions; this block covers the failure modes the weaker free
34
50
  * models show: skipping analysis, inventing verification, and ignoring the
35
51
  * context the conversation already established.
36
52
  */
37
- export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
53
+ export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
38
54
  export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
39
55
  /**
40
56
  * Appended to OpenCode's compaction request. Its default summary prompt asks
@@ -58,23 +74,12 @@ export declare const RETRY_MAX_DELAY_MS = 60000;
58
74
  export declare const CONCURRENT_RETRY_MAX = 6;
59
75
  export declare const CONCURRENT_RETRY_BASE_MS = 1000;
60
76
  export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
61
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
62
- export declare const CACHE_TTL_MS: number;
63
- export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
64
- export declare const CACHE_MISS_NOTICE_TOKENS = 20000;
65
77
  /** Tool outcome headers emitted by the free-pi provider CLI. */
66
78
  export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
67
79
  export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
68
80
  export declare const COMPACTED_HEADER = "x-freepi-compacted";
69
81
  export declare const TOOL_META_BUDGET = 1500;
70
82
  export declare const TOOL_ID_LIMIT = 50;
71
- /**
72
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
73
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
74
- * 117_647 is the smallest window that keeps that trigger at 100k.
75
- */
76
- export declare const COMPACT100_TRIGGER_TOKENS = 100000;
77
- export declare const COMPACT100_CONTEXT_WINDOW = 117647;
78
83
  export declare const SESSION_TRACK_LIMIT = 200;
79
84
  export declare const AUTH_SKEW_MS = 60000;
80
85
  export declare const AUTH_TIMEOUT_MS: number;
@@ -88,10 +93,8 @@ export declare const AD_TURN_LIMIT = 200;
88
93
  export declare const AD_IMPRESSION_LIMIT = 200;
89
94
  export declare const CREDITS_PER_USD: number;
90
95
  export declare const CATALOG_TTL_MS: number;
91
- export declare const CATALOG_DISK_TTL_MS: number;
92
96
  export declare const CATALOG_TIMEOUT_MS = 8000;
93
97
  export declare const REGISTRY_TTL_MS: number;
94
- export declare const REGISTRY_DISK_TTL_MS: number;
95
98
  export declare const REGISTRY_RETRY_MS = 60000;
96
99
  export declare const REGISTRY_TIMEOUT_MS = 3500;
97
100
  export declare const REGISTRY_ATTEMPTS = 2;
package/dist/constants.js CHANGED
@@ -7,8 +7,24 @@ export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export const DEFAULT_CLIENT_VERSION = "0.6.25";
9
9
  export const CONSENT_VERSION = "4";
10
+ /**
11
+ * The provider CLI's window. The gateway enforces its own ceiling but does not
12
+ * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
13
+ * with what the server actually accepts.
14
+ */
10
15
  export const CONTEXT_WINDOW = 200_000;
16
+ /** Largest window the plugin will ever advertise after measuring the gateway. */
17
+ export const MAX_CONTEXT_WINDOW = 1_000_000;
11
18
  export const MAX_OUTPUT_TOKENS = 32_768;
19
+ /**
20
+ * Upper bound for a model that publishes a larger output budget. Reasoning
21
+ * tokens share this budget, so a model that can emit more must not be pinned to
22
+ * the CLI's 32k: a long chain of thought would consume it and leave `content`
23
+ * empty.
24
+ */
25
+ export const MAX_OUTPUT_TOKENS_CEILING = 131_072;
26
+ /** How long a measured gateway window is trusted before checking again. */
27
+ export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
12
28
  export const AD_CONTEXT_HEADER = "x-ad-context";
13
29
  /**
14
30
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -16,16 +32,16 @@ export const AD_CONTEXT_HEADER = "x-ad-context";
16
32
  */
17
33
  export const AD_CONTEXT_OPT_OUT = "none";
18
34
  export const SUBAGENT_HEADER = "x-freepi-subagent";
19
- export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
- export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
35
  /**
22
36
  * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
37
  * unset makes the gateway answer in a hurry: the free models spend only a few
24
- * dozen reasoning tokens even on tasks that need planning. The plugin therefore
25
- * asks for `medium` by default and keeps the CLI's levels as variants, so
26
- * `none`/`minimal` are still one pick away when speed matters more than care.
38
+ * dozen reasoning tokens even on tasks that need planning. The gateway accepts
39
+ * every level (measured with curl_cffi) but currently does not let the level
40
+ * change how long the upstream thinks, so the plugin also asks for explicit
41
+ * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
42
+ * stay one pick away when speed matters more than care.
27
43
  */
28
- export const DEFAULT_REASONING_EFFORT = "medium";
44
+ export const DEFAULT_REASONING_EFFORT = "high";
29
45
  export const REASONING_EFFORTS = [
30
46
  "none",
31
47
  "minimal",
@@ -40,6 +56,7 @@ export const DEFAULT_THINKING_LEVELS = [
40
56
  "low",
41
57
  "medium",
42
58
  "high",
59
+ "max",
43
60
  ];
44
61
  /**
45
62
  * Injected into every primary free-pi request. OpenCode already supplies the
@@ -49,6 +66,7 @@ export const DEFAULT_THINKING_LEVELS = [
49
66
  */
50
67
  export const FREE_PI_GUIDANCE = `# free-pi working rules
51
68
  - Answer the user's latest request and keep their constraints; do not switch to a different task.
69
+ - Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.
52
70
  - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
53
71
  - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
54
72
  - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
@@ -81,23 +99,12 @@ export const RETRY_MAX_DELAY_MS = 60_000;
81
99
  export const CONCURRENT_RETRY_MAX = 6;
82
100
  export const CONCURRENT_RETRY_BASE_MS = 1_000;
83
101
  export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
84
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
85
- export const CACHE_TTL_MS = 5 * 60_000;
86
- export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
87
- export const CACHE_MISS_NOTICE_TOKENS = 20_000;
88
102
  /** Tool outcome headers emitted by the free-pi provider CLI. */
89
103
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
90
104
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
91
105
  export const COMPACTED_HEADER = "x-freepi-compacted";
92
106
  export const TOOL_META_BUDGET = 1_500;
93
107
  export const TOOL_ID_LIMIT = 50;
94
- /**
95
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
96
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
97
- * 117_647 is the smallest window that keeps that trigger at 100k.
98
- */
99
- export const COMPACT100_TRIGGER_TOKENS = 100_000;
100
- export const COMPACT100_CONTEXT_WINDOW = 117_647;
101
108
  export const SESSION_TRACK_LIMIT = 200;
102
109
  export const AUTH_SKEW_MS = 60_000;
103
110
  export const AUTH_TIMEOUT_MS = 15 * 60_000;
@@ -111,10 +118,8 @@ export const AD_TURN_LIMIT = 200;
111
118
  export const AD_IMPRESSION_LIMIT = 200;
112
119
  export const CREDITS_PER_USD = 40_000 / 3;
113
120
  export const CATALOG_TTL_MS = 10 * 60_000;
114
- export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
115
121
  export const CATALOG_TIMEOUT_MS = 8_000;
116
122
  export const REGISTRY_TTL_MS = 5 * 60_000;
117
- export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
118
123
  export const REGISTRY_RETRY_MS = 60_000;
119
124
  export const REGISTRY_TIMEOUT_MS = 3_500;
120
125
  export const REGISTRY_ATTEMPTS = 2;
package/dist/logging.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /** Logging for the plugin. V2 has no `app.log`, so messages go to the console and a file. */
2
2
  import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
- import { cacheDir } from "./utils/cache.js";
4
+ import { dataDir } from "./utils/data-dir.js";
5
5
  const MAX_LOG_BYTES = 1_000_000;
6
6
  let fileFailureReported = false;
7
7
  function logFile() {
8
8
  const configured = process.env.FREE_PI_LOG_FILE?.trim();
9
- return configured || join(cacheDir(), "plugin.log");
9
+ return configured || join(dataDir(), "plugin.log");
10
10
  }
11
11
  function rotate(file) {
12
12
  try {
package/dist/plugin.js CHANGED
@@ -7,6 +7,7 @@ import { closeFreePiSession } from "./api/session.js";
7
7
  import { readCredentialsToken } from "./auth/credentials.js";
8
8
  import { tokenFromCredential } from "./auth/credential.js";
9
9
  import { fetchCatalog } from "./catalog/catalog.js";
10
+ import { loadLiveLimits, shouldVerifyWindow, verifyGatewayWindow, } from "./catalog/live.js";
10
11
  import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
11
12
  import { fetchModelsRegistry } from "./catalog/registry.js";
12
13
  import { applyProvider } from "./catalog/v2.js";
@@ -103,9 +104,10 @@ async function setup(ctx) {
103
104
  const main = filterAccessibleModels(catalogMain, access);
104
105
  const defense = filterAccessibleModels(catalogDefense, access);
105
106
  const candidates = modelRegistryCandidates(registry);
107
+ const live = await loadLiveLimits();
106
108
  const configuredEffort = ctx.options?.reasoningEffort;
107
109
  const buildOptions = {
108
- compact100: state.costExperimentArm === "compact100",
110
+ live,
109
111
  ...(configuredEffort === false
110
112
  ? { reasoningEffort: false }
111
113
  : isReasoningEffort(configuredEffort)
@@ -130,6 +132,29 @@ async function setup(ctx) {
130
132
  applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", defenseModels, state.providerToken);
131
133
  }
132
134
  });
135
+ // The gateway does not publish its context ceiling. Verify the compiled
136
+ // window against it once a week with a free model, in the background, and
137
+ // persist the result for the next catalog build. Prefer the free model with
138
+ // the largest prompt already accepted in real traffic: it has the most
139
+ // evidence behind it, so the growth probes describe the window sessions use.
140
+ if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
141
+ const free = main.filter((model) => model.free === true && typeof model.id === "string");
142
+ const probe = free
143
+ .map((model) => ({
144
+ id: model.id,
145
+ seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
146
+ }))
147
+ .sort((a, b) => b.seen - a.seen)[0]?.id ??
148
+ (catalog?.default_model &&
149
+ free.some((model) => model.id === catalog.default_model)
150
+ ? catalog.default_model
151
+ : undefined) ??
152
+ free[0]?.id ??
153
+ Object.keys(mainModels)[0];
154
+ if (probe) {
155
+ void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
156
+ }
157
+ }
133
158
  // V1 selected the catalog default when the user had no model configured.
134
159
  await ctx.model.transform((editor) => {
135
160
  if (editor.default.get())
@@ -162,7 +187,6 @@ async function setup(ctx) {
162
187
  defaultModel: catalog?.default_model,
163
188
  clientVersion: state.latestClientVersion,
164
189
  capabilities: candidates.length,
165
- costArm: state.costExperimentArm,
166
190
  models: main.map((model) => model.id),
167
191
  });
168
192
  return async () => {
@@ -3,7 +3,7 @@ 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";
6
+ import { noteStepTokens } from "../catalog/live.js";
7
7
  import { forgetToolStats } from "./tools.js";
8
8
  import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
9
9
  import { markWireSessionDirty, } from "./wire.js";
@@ -85,7 +85,7 @@ async function handleEvent(ctx, deps, event) {
85
85
  case "session.step.ended": {
86
86
  recordUsage(deps, event.data?.sessionID, event.data?.cost, event.data?.tokens);
87
87
  // Step tokens are per request; usage.updated is cumulative.
88
- observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
88
+ noteStepTokens(deps, deps.state.trackedModels.get(event.data?.sessionID)?.modelID ?? "", event.data?.tokens);
89
89
  return;
90
90
  }
91
91
  case "session.deleted": {
@@ -94,7 +94,6 @@ async function handleEvent(ctx, deps, event) {
94
94
  return;
95
95
  await finalizeFreePiSession(deps, sessionID);
96
96
  forgetFreePiSession(deps, sessionID);
97
- forgetCacheMiss(deps, sessionID);
98
97
  forgetToolStats(deps, sessionID);
99
98
  deps.state.subagentSessions.delete(sessionID);
100
99
  return;
@@ -2,7 +2,7 @@
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 { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, COST_EXPERIMENT_HEADER, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
5
+ import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
6
6
  import { closeFreePiSession } from "../api/session.js";
7
7
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
8
8
  import { parseFreePiError } from "../errors/parse.js";
@@ -52,7 +52,9 @@ async function applyGeneration(deps, event, kind) {
52
52
  }
53
53
  const modelID = event.model?.id;
54
54
  const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
55
- const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
55
+ // Reasoning shares the output budget; a model that publishes more than the
56
+ // CLI's 32k keeps that larger budget (up to the plugin ceiling).
57
+ const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
56
58
  if (event.options) {
57
59
  const current = event.options.maxTokens;
58
60
  if (current === undefined || current > cap)
@@ -69,13 +71,6 @@ async function applyGeneration(deps, event, kind) {
69
71
  // the CLI gets a much larger agent prompt. This is the compact equivalent.
70
72
  appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
71
73
  }
72
- if (deps.state.costExperimentArm === "efficiency") {
73
- const system = Array.isArray(event.system) ? event.system : [];
74
- if (!system.some((part) => part?.type === "text" && part.text === EFFICIENCY_RULE)) {
75
- system.push({ type: "text", text: EFFICIENCY_RULE });
76
- event.system = system;
77
- }
78
- }
79
74
  const agent = event.agent;
80
75
  const turn = await resolveAdTurn(deps, {
81
76
  sessionID: event.sessionID,
@@ -121,9 +116,6 @@ async function applyModelRequest(deps, event) {
121
116
  if (deps.state.subagentSessions.has(event.sessionID)) {
122
117
  event.headers[SUBAGENT_HEADER] = "1";
123
118
  }
124
- if (deps.state.costExperimentArm) {
125
- event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
126
- }
127
119
  // Title requests are suppressed by the title hook, so an ad for them would be
128
120
  // an impression the user never sees.
129
121
  if (event.kind === "title")
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Per-plugin-instance mutable state. */
2
- import type { AdTurn, CacheMissState, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, RequestUsage, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
2
+ import type { AdTurn, 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;
@@ -10,7 +10,6 @@ export type RuntimeState = {
10
10
  cachedRegistryAt: number;
11
11
  registryAttemptAt: number;
12
12
  registryPromise?: Promise<ModelRegistry | undefined>;
13
- costExperimentArm?: string;
14
13
  lastCatalogNotice?: string;
15
14
  lastQuotaNotice?: string;
16
15
  catalogModels: Catalog;
@@ -50,20 +49,7 @@ export type RuntimeState = {
50
49
  pendingAdTurns: Map<string, AdTurn>;
51
50
  adImpressions: Map<string, Promise<void>>;
52
51
  trackedModels: Map<string, TrackedModel>;
53
- cacheMisses: Map<string, CacheMissState>;
54
52
  toolStats: Map<string, ToolStats>;
55
- /** Successful paid-tool answers, keyed by canonical input, to avoid rebilling. */
56
- toolSpend: Map<string, {
57
- at: number;
58
- output: {
59
- content: ReadonlyArray<{
60
- type: "text";
61
- text: string;
62
- }>;
63
- metadata: Record<string, unknown>;
64
- };
65
- }>;
66
- toolSpendPending: Map<string, Promise<any>>;
67
53
  subagentSessions: Set<string>;
68
54
  };
69
55
  export declare function createRuntimeState(): RuntimeState;
package/dist/state.js CHANGED
@@ -27,10 +27,7 @@ export function createRuntimeState() {
27
27
  pendingAdTurns: new Map(),
28
28
  adImpressions: new Map(),
29
29
  trackedModels: new Map(),
30
- cacheMisses: new Map(),
31
30
  toolStats: new Map(),
32
- toolSpend: new Map(),
33
- toolSpendPending: new Map(),
34
31
  subagentSessions: new Set(),
35
32
  };
36
33
  }
@@ -4,7 +4,7 @@
4
4
  * free-pi answers one `/tools/vision` request at a time: a second concurrent
5
5
  * question gets `rate_limited`. OpenCode can run several sessions, and users can
6
6
  * run several OpenCode processes, so calls are queued in-process and coordinated
7
- * through a lock directory in the free-pi cache.
7
+ * through a lock directory in the free-pi data directory.
8
8
  */
9
9
  import type { Logger } from "../logging.js";
10
10
  /**