@eduardo191labs/opencode-free-pi 0.5.6 → 0.6.0

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 (47) hide show
  1. package/README.md +33 -39
  2. package/dist/catalog/catalog.js +1 -21
  3. package/dist/catalog/live.d.ts +55 -0
  4. package/dist/catalog/live.js +229 -0
  5. package/dist/catalog/models.d.ts +7 -2
  6. package/dist/catalog/models.js +10 -10
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/constants.d.ts +7 -15
  9. package/dist/constants.js +7 -15
  10. package/dist/logging.js +2 -2
  11. package/dist/plugin.js +14 -2
  12. package/dist/session/events.js +2 -3
  13. package/dist/session/hooks.js +1 -11
  14. package/dist/state.d.ts +1 -15
  15. package/dist/state.js +0 -3
  16. package/dist/tools/vision-queue.d.ts +1 -1
  17. package/dist/tools/vision-queue.js +5 -5
  18. package/dist/tools/vision.js +24 -35
  19. package/dist/tools/web.js +39 -44
  20. package/dist/types.d.ts +5 -9
  21. package/dist/utils/data-dir.d.ts +3 -0
  22. package/dist/utils/data-dir.js +12 -0
  23. package/package.json +2 -2
  24. package/src/catalog/catalog.ts +0 -25
  25. package/src/catalog/live.ts +277 -0
  26. package/src/catalog/models.ts +19 -12
  27. package/src/catalog/registry.ts +6 -21
  28. package/src/constants.ts +7 -18
  29. package/src/logging.ts +2 -2
  30. package/src/plugin.ts +20 -2
  31. package/src/session/events.ts +6 -3
  32. package/src/session/hooks.ts +0 -17
  33. package/src/state.ts +0 -18
  34. package/src/tools/vision-queue.ts +5 -5
  35. package/src/tools/vision.ts +26 -38
  36. package/src/tools/web.ts +49 -59
  37. package/src/types.ts +5 -8
  38. package/src/utils/data-dir.ts +14 -0
  39. package/dist/session/cache.d.ts +0 -15
  40. package/dist/session/cache.js +0 -57
  41. package/dist/tools/spend-cache.d.ts +0 -15
  42. package/dist/tools/spend-cache.js +0 -64
  43. package/dist/utils/cache.d.ts +0 -7
  44. package/dist/utils/cache.js +0 -45
  45. package/src/session/cache.ts +0 -82
  46. package/src/tools/spend-cache.ts +0 -79
  47. package/src/utils/cache.ts +0 -49
package/dist/constants.js CHANGED
@@ -7,8 +7,15 @@ 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;
11
16
  export const MAX_OUTPUT_TOKENS = 32_768;
17
+ /** How long a measured gateway window is trusted before checking again. */
18
+ export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
12
19
  export const AD_CONTEXT_HEADER = "x-ad-context";
13
20
  /**
14
21
  * The CLI sends `none` when the ad context is unavailable or private instead of
@@ -16,8 +23,6 @@ export const AD_CONTEXT_HEADER = "x-ad-context";
16
23
  */
17
24
  export const AD_CONTEXT_OPT_OUT = "none";
18
25
  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
26
  /**
22
27
  * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
28
  * unset makes the gateway answer in a hurry: the free models spend only a few
@@ -81,23 +86,12 @@ export const RETRY_MAX_DELAY_MS = 60_000;
81
86
  export const CONCURRENT_RETRY_MAX = 6;
82
87
  export const CONCURRENT_RETRY_BASE_MS = 1_000;
83
88
  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
89
  /** Tool outcome headers emitted by the free-pi provider CLI. */
89
90
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
90
91
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
91
92
  export const COMPACTED_HEADER = "x-freepi-compacted";
92
93
  export const TOOL_META_BUDGET = 1_500;
93
94
  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
95
  export const SESSION_TRACK_LIMIT = 200;
102
96
  export const AUTH_SKEW_MS = 60_000;
103
97
  export const AUTH_TIMEOUT_MS = 15 * 60_000;
@@ -111,10 +105,8 @@ export const AD_TURN_LIMIT = 200;
111
105
  export const AD_IMPRESSION_LIMIT = 200;
112
106
  export const CREDITS_PER_USD = 40_000 / 3;
113
107
  export const CATALOG_TTL_MS = 10 * 60_000;
114
- export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
115
108
  export const CATALOG_TIMEOUT_MS = 8_000;
116
109
  export const REGISTRY_TTL_MS = 5 * 60_000;
117
- export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
118
110
  export const REGISTRY_RETRY_MS = 60_000;
119
111
  export const REGISTRY_TIMEOUT_MS = 3_500;
120
112
  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,17 @@ 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.
138
+ if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
139
+ const probe = main.find((model) => model.free === true)?.id ??
140
+ catalog?.default_model ??
141
+ Object.keys(mainModels)[0];
142
+ if (probe) {
143
+ void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
144
+ }
145
+ }
133
146
  // V1 selected the catalog default when the user had no model configured.
134
147
  await ctx.model.transform((editor) => {
135
148
  if (editor.default.get())
@@ -162,7 +175,6 @@ async function setup(ctx) {
162
175
  defaultModel: catalog?.default_model,
163
176
  clientVersion: state.latestClientVersion,
164
177
  capabilities: candidates.length,
165
- costArm: state.costExperimentArm,
166
178
  models: main.map((model) => model.id),
167
179
  });
168
180
  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, 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";
@@ -69,13 +69,6 @@ async function applyGeneration(deps, event, kind) {
69
69
  // the CLI gets a much larger agent prompt. This is the compact equivalent.
70
70
  appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
71
71
  }
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
72
  const agent = event.agent;
80
73
  const turn = await resolveAdTurn(deps, {
81
74
  sessionID: event.sessionID,
@@ -121,9 +114,6 @@ async function applyModelRequest(deps, event) {
121
114
  if (deps.state.subagentSessions.has(event.sessionID)) {
122
115
  event.headers[SUBAGENT_HEADER] = "1";
123
116
  }
124
- if (deps.state.costExperimentArm) {
125
- event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
126
- }
127
117
  // Title requests are suppressed by the title hook, so an ad for them would be
128
118
  // an impression the user never sees.
129
119
  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
  /**
@@ -4,12 +4,12 @@
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 { randomUUID } from "node:crypto";
10
10
  import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
11
11
  import { join } from "node:path";
12
- import { cacheDir } from "../utils/cache.js";
12
+ import { dataDir } from "../utils/data-dir.js";
13
13
  const OWNER_FILE = "owner.json";
14
14
  const POLL_MS = 350;
15
15
  /** A live owner may legitimately hold the lock for a 90 s request. */
@@ -17,7 +17,7 @@ const STALE_MS = 10 * 60_000;
17
17
  const MAX_WAIT_MS = 120_000;
18
18
  let chain = Promise.resolve();
19
19
  function lockDir() {
20
- return join(cacheDir(), "vision.lock");
20
+ return join(dataDir(), "vision.lock");
21
21
  }
22
22
  function pidAlive(pid) {
23
23
  try {
@@ -76,10 +76,10 @@ async function acquire(log) {
76
76
  };
77
77
  const startedAt = Date.now();
78
78
  try {
79
- await mkdir(cacheDir(), { recursive: true });
79
+ await mkdir(dataDir(), { recursive: true });
80
80
  }
81
81
  catch {
82
- // Without a cache directory the file lock is unavailable; the in-process
82
+ // Without a data directory the file lock is unavailable; the in-process
83
83
  // queue still serializes calls, so keep going.
84
84
  }
85
85
  while (Date.now() - startedAt < MAX_WAIT_MS) {
@@ -6,12 +6,10 @@
6
6
  * `/tools/vision` and returns the vision model's text answer. Each call counts
7
7
  * against the user's daily allowance.
8
8
  */
9
- import { createHash } from "node:crypto";
10
9
  import { resolveToken } from "../auth/token.js";
11
10
  import { isFreePiSession } from "../session/tools.js";
12
11
  import { resolveBaseUrl } from "../utils/urls.js";
13
12
  import { loadImage, prepareImage } from "./image.js";
14
- import { spendOnce } from "./spend-cache.js";
15
13
  import { withVisionSlot } from "./vision-queue.js";
16
14
  const TOOL_NAME = "look_at_image";
17
15
  const TIMEOUT_MS = 90_000;
@@ -214,39 +212,30 @@ async function executeVision(ctx, deps, raw, context) {
214
212
  if (!token) {
215
213
  return fail("look_at_image needs a free-pi sign-in. Do not retry; tell the user to connect the free-pi integration, and continue without this tool.");
216
214
  }
217
- const imageKey = createHash("sha256")
218
- .update(prepared.mime)
219
- .update("\u0000")
220
- .update(prepared.data)
221
- .update("\u0000")
222
- .update(question)
223
- .digest("hex");
224
- return spendOnce(deps, `vision:${imageKey}`, async () => {
225
- const queued = await withVisionSlot(deps.log, () => askVision(deps, token, prepared.data, prepared.mime, question, context.signal));
226
- if (!queued.ok) {
227
- return fail("Another image question is still running. Wait a moment and call look_at_image again.");
228
- }
229
- if (!queued.value.ok)
230
- return fail(queued.value.text);
231
- const { answer, attempts } = queued.value;
232
- const elapsed = Date.now() - startedAt;
233
- deps.log.info("look_at_image answered", {
234
- path,
235
- ms: elapsed,
236
- attempts,
237
- resized: prepared.resized,
238
- bytes: prepared.bytes,
239
- size: `${prepared.width}x${prepared.height}`,
240
- mime: prepared.mime,
241
- model: answer.model,
242
- });
243
- return done(questionText(path, answer.text), {
244
- ok: true,
245
- ...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
246
- ...(answer.model !== undefined ? { model: answer.model } : {}),
247
- elapsed_ms: elapsed,
248
- attempts,
249
- });
215
+ const queued = await withVisionSlot(deps.log, () => askVision(deps, token, prepared.data, prepared.mime, question, context.signal));
216
+ if (!queued.ok) {
217
+ return fail("Another image question is still running. Wait a moment and call look_at_image again.");
218
+ }
219
+ if (!queued.value.ok)
220
+ return fail(queued.value.text);
221
+ const { answer, attempts } = queued.value;
222
+ const elapsed = Date.now() - startedAt;
223
+ deps.log.info("look_at_image answered", {
224
+ path,
225
+ ms: elapsed,
226
+ attempts,
227
+ resized: prepared.resized,
228
+ bytes: prepared.bytes,
229
+ size: `${prepared.width}x${prepared.height}`,
230
+ mime: prepared.mime,
231
+ model: answer.model,
232
+ });
233
+ return done(questionText(path, answer.text), {
234
+ ok: true,
235
+ ...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
236
+ ...(answer.model !== undefined ? { model: answer.model } : {}),
237
+ elapsed_ms: elapsed,
238
+ attempts,
250
239
  });
251
240
  }
252
241
  /**
package/dist/tools/web.js CHANGED
@@ -5,7 +5,6 @@
5
5
  * CLI, and are only exposed inside free-pi sessions.
6
6
  */
7
7
  import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, mappedText, } from "./api.js";
8
- import { spendOnce } from "./spend-cache.js";
9
8
  const ERRORS = {
10
9
  daily_cap: "The user's daily free usage is used up. Do not retry; tell the user and continue without this tool.",
11
10
  rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
@@ -83,30 +82,28 @@ async function executeWebSearch(deps, raw, context) {
83
82
  if (!query)
84
83
  return fail("web_search needs a query.");
85
84
  const num = typeof input?.num_results === "number" ? input.num_results : undefined;
86
- return spendOnce(deps, `web:${query}\u0000${num ?? ""}`, async () => {
87
- const result = await freePiRequest(deps, {
88
- path: "/tools/web-search",
89
- method: "POST",
90
- body: { query, ...(num !== undefined ? { num_results: num } : {}) },
91
- timeoutMs: 30_000,
92
- signal: context.signal,
93
- label: "The web search",
94
- });
95
- if (!result.ok)
96
- return fail(mappedText(ERRORS, result));
97
- deps.log.info("web_search answered", {
98
- query,
99
- results: Array.isArray(result.data?.results)
100
- ? result.data.results.length
101
- : 0,
102
- costUsd: result.data?.cost_usd,
103
- });
104
- return done(formatWebResults(query, result.data?.results ?? []), {
105
- ok: true,
106
- ...(typeof result.data?.cost_usd === "number"
107
- ? { cost_usd: result.data.cost_usd }
108
- : {}),
109
- });
85
+ const result = await freePiRequest(deps, {
86
+ path: "/tools/web-search",
87
+ method: "POST",
88
+ body: { query, ...(num !== undefined ? { num_results: num } : {}) },
89
+ timeoutMs: 30_000,
90
+ signal: context.signal,
91
+ label: "The web search",
92
+ });
93
+ if (!result.ok)
94
+ return fail(mappedText(ERRORS, result));
95
+ deps.log.info("web_search answered", {
96
+ query,
97
+ results: Array.isArray(result.data?.results)
98
+ ? result.data.results.length
99
+ : 0,
100
+ costUsd: result.data?.cost_usd,
101
+ });
102
+ return done(formatWebResults(query, result.data?.results ?? []), {
103
+ ok: true,
104
+ ...(typeof result.data?.cost_usd === "number"
105
+ ? { cost_usd: result.data.cost_usd }
106
+ : {}),
110
107
  });
111
108
  }
112
109
  async function executeDocsLookup(deps, raw, context) {
@@ -120,7 +117,7 @@ async function executeDocsLookup(deps, raw, context) {
120
117
  return fail("docs_lookup needs a library name.");
121
118
  if (!query)
122
119
  return fail("docs_lookup needs a specific question.");
123
- const result = await spendOnce(deps, `docs:${library}\u0000${query}\u0000${libraryId}`, () => freePiRequest(deps, {
120
+ const lookup = await freePiRequest(deps, {
124
121
  path: "/tools/docs",
125
122
  method: "POST",
126
123
  body: {
@@ -131,24 +128,22 @@ async function executeDocsLookup(deps, raw, context) {
131
128
  timeoutMs: 30_000,
132
129
  signal: context.signal,
133
130
  label: "The documentation lookup",
134
- }).then((lookup) => {
135
- if (!lookup.ok)
136
- return fail(mappedText(ERRORS, lookup, library));
137
- const data = lookup.data ?? {};
138
- deps.log.info("docs_lookup answered", {
139
- library,
140
- libraryID: data.library_id,
141
- costUsd: data.cost_usd,
142
- });
143
- return done(`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`, {
144
- ok: true,
145
- library_id: data.library_id,
146
- ...(typeof data.cost_usd === "number"
147
- ? { cost_usd: data.cost_usd }
148
- : {}),
149
- });
150
- }));
151
- return result;
131
+ });
132
+ if (!lookup.ok)
133
+ return fail(mappedText(ERRORS, lookup, library));
134
+ const data = lookup.data ?? {};
135
+ deps.log.info("docs_lookup answered", {
136
+ library,
137
+ libraryID: data.library_id,
138
+ costUsd: data.cost_usd,
139
+ });
140
+ return done(`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`, {
141
+ ok: true,
142
+ library_id: data.library_id,
143
+ ...(typeof data.cost_usd === "number"
144
+ ? { cost_usd: data.cost_usd }
145
+ : {}),
146
+ });
152
147
  }
153
148
  export async function registerWebTools(ctx, deps) {
154
149
  return ctx.tool.transform((editor) => {
package/dist/types.d.ts CHANGED
@@ -92,9 +92,6 @@ export type Catalog = {
92
92
  default_model?: string;
93
93
  notice?: string;
94
94
  models?: CatalogModel[];
95
- cost_experiment?: {
96
- arm?: string;
97
- };
98
95
  };
99
96
  /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
100
97
  export type ModelDefinition = {
@@ -138,6 +135,11 @@ export type FreePiOptions = {
138
135
  * models plan before answering. Set `false` to keep the gateway default.
139
136
  */
140
137
  reasoningEffort?: string | false;
138
+ /**
139
+ * Verify the gateway's real context window once a week and reuse the measured
140
+ * value. Defaults to true; set `false` to stay on the compiled window.
141
+ */
142
+ liveLimits?: boolean;
141
143
  };
142
144
  export type MeResponse = {
143
145
  handle?: string;
@@ -247,12 +249,6 @@ export type TrackedModel = {
247
249
  providerID: string;
248
250
  modelID: string;
249
251
  };
250
- export type CacheMissState = {
251
- promptTokens: number;
252
- at: number;
253
- modelKey: string;
254
- reportedCache: boolean;
255
- };
256
252
  export type ToolStats = {
257
253
  meta: string[];
258
254
  metaBytes: number;
@@ -0,0 +1,3 @@
1
+ /** Per-user directory for the files the plugin keeps between runs. */
2
+ export declare function dataDir(): string;
3
+ export declare function dataPath(name: string): string;
@@ -0,0 +1,12 @@
1
+ /** Per-user directory for the files the plugin keeps between runs. */
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ export function dataDir() {
5
+ const configured = process.env.FREE_PI_DATA_DIR?.trim();
6
+ if (configured)
7
+ return configured;
8
+ return join(homedir(), ".cache", "opencode", "free-pi");
9
+ }
10
+ export function dataPath(name) {
11
+ return join(dataDir(), name);
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.5.6",
3
+ "version": "0.6.0",
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": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && 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 && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/spend.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -2,18 +2,13 @@
2
2
 
3
3
  import { resolveToken } from "../auth/token.js";
4
4
  import {
5
- CATALOG_DISK_TTL_MS,
6
5
  CATALOG_TIMEOUT_MS,
7
6
  CATALOG_TTL_MS,
8
- COST_EXPERIMENT_HEADER,
9
7
  } from "../constants.js";
10
8
  import type { Deps } from "../deps.js";
11
9
  import type { Catalog } from "../types.js";
12
- import { readCache, writeCache } from "../utils/cache.js";
13
10
  import { resolveBaseUrl } from "../utils/urls.js";
14
11
 
15
- const CACHE_FILE = "catalog.json";
16
-
17
12
  function isCatalog(value: unknown): value is Catalog {
18
13
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19
14
  }
@@ -30,11 +25,6 @@ function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
30
25
  if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
31
26
  state.latestClientVersion = catalog.latest;
32
27
  }
33
- const arm = catalog.cost_experiment?.arm;
34
- state.costExperimentArm =
35
- typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
36
- ? arm
37
- : undefined;
38
28
  if (
39
29
  typeof catalog.notice === "string" &&
40
30
  catalog.notice &&
@@ -54,12 +44,9 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
54
44
  if (state.catalogPromise) return state.catalogPromise;
55
45
  const pending = (async () => {
56
46
  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
47
  const token = await resolveToken(deps).catch(() => undefined);
60
48
  const headers: Record<string, string> = {
61
49
  accept: "application/json",
62
- [COST_EXPERIMENT_HEADER]: "1",
63
50
  };
64
51
  if (token) headers.authorization = `Bearer ${token}`;
65
52
  const response = await fetch(`${resolveBaseUrl()}/client-version`, {
@@ -72,7 +59,6 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
72
59
  throw new Error("free-pi returned an unexpected catalog payload");
73
60
  }
74
61
  applyCatalog(deps, catalog);
75
- void writeCache(CACHE_FILE, catalog);
76
62
  return catalog;
77
63
  } catch (error) {
78
64
  const cached = state.cachedCatalog;
@@ -97,16 +83,5 @@ export async function fetchCatalog(deps: Deps): Promise<Catalog | undefined> {
97
83
  if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
98
84
  return state.cachedCatalog;
99
85
  }
100
-
101
- if (!state.cachedCatalog) {
102
- const disk = await readCache<Catalog>(CACHE_FILE, CATALOG_DISK_TTL_MS);
103
- if (isCatalog(disk)) {
104
- applyCatalog(deps, disk);
105
- // Serve the cached copy immediately and refresh it in the background.
106
- void refreshCatalog(deps);
107
- return disk;
108
- }
109
- }
110
-
111
86
  return refreshCatalog(deps);
112
87
  }