@eduardo191labs/opencode-free-pi 0.5.5 → 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 +50 -41
  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 +26 -36
  7. package/dist/catalog/registry.js +5 -15
  8. package/dist/constants.d.ts +22 -15
  9. package/dist/constants.js +32 -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 +17 -10
  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 +34 -38
  27. package/src/catalog/registry.ts +6 -21
  28. package/src/constants.ts +34 -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 +34 -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/src/constants.ts CHANGED
@@ -11,8 +11,15 @@ export const DEFAULT_BASE_URL = "https://api.freepi.ai";
11
11
  export const DEFAULT_CLIENT_VERSION = "0.6.25";
12
12
  export const CONSENT_VERSION = "4";
13
13
 
14
+ /**
15
+ * The provider CLI's window. The gateway enforces its own ceiling but does not
16
+ * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
17
+ * with what the server actually accepts.
18
+ */
14
19
  export const CONTEXT_WINDOW = 200_000;
15
20
  export const MAX_OUTPUT_TOKENS = 32_768;
21
+ /** How long a measured gateway window is trusted before checking again. */
22
+ export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
16
23
 
17
24
  export const AD_CONTEXT_HEADER = "x-ad-context";
18
25
  /**
@@ -21,9 +28,6 @@ export const AD_CONTEXT_HEADER = "x-ad-context";
21
28
  */
22
29
  export const AD_CONTEXT_OPT_OUT = "none";
23
30
  export const SUBAGENT_HEADER = "x-freepi-subagent";
24
- export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
25
- export const EFFICIENCY_RULE =
26
- "- When several independent reads or searches are needed, issue them in the same turn.";
27
31
 
28
32
  /**
29
33
  * The provider CLI starts with thinking off, but leaving `reasoning_effort`
@@ -49,6 +53,33 @@ export const DEFAULT_THINKING_LEVELS = [
49
53
  "high",
50
54
  ] as const;
51
55
 
56
+ /**
57
+ * Injected into every primary free-pi request. OpenCode already supplies the
58
+ * coding instructions; this block covers the failure modes the weaker free
59
+ * models show: skipping analysis, inventing verification, and ignoring the
60
+ * context the conversation already established.
61
+ */
62
+ export const FREE_PI_GUIDANCE = `# free-pi working rules
63
+ - Answer the user's latest request and keep their constraints; do not switch to a different task.
64
+ - 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.
65
+ - 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.
66
+ - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
67
+ - Never claim to have compacted, summarized or cleared context unless that actually happened.
68
+ - Continue until the request is finished, then report concisely what changed and what you verified.`;
69
+ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
70
+
71
+ /**
72
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
73
+ * for terse checkpoints, which is fine for strong models but loses the exact
74
+ * facts the free models need; spell out what must survive the rewrite.
75
+ */
76
+ export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
77
+ - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
78
+ - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
79
+ - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
80
+ - Do not invent progress or results that are not in the conversation.`;
81
+ export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
82
+
52
83
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
53
84
  export const HEADER_TIMEOUT_MS = 300_000;
54
85
  export const CHUNK_TIMEOUT_MS = 300_000;
@@ -67,11 +98,6 @@ export const CONCURRENT_RETRY_MAX = 6;
67
98
  export const CONCURRENT_RETRY_BASE_MS = 1_000;
68
99
  export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
69
100
 
70
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
71
- export const CACHE_TTL_MS = 5 * 60_000;
72
- export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
73
- export const CACHE_MISS_NOTICE_TOKENS = 20_000;
74
-
75
101
  /** Tool outcome headers emitted by the free-pi provider CLI. */
76
102
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
77
103
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
@@ -79,14 +105,6 @@ export const COMPACTED_HEADER = "x-freepi-compacted";
79
105
  export const TOOL_META_BUDGET = 1_500;
80
106
  export const TOOL_ID_LIMIT = 50;
81
107
 
82
- /**
83
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
84
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
85
- * 117_647 is the smallest window that keeps that trigger at 100k.
86
- */
87
- export const COMPACT100_TRIGGER_TOKENS = 100_000;
88
- export const COMPACT100_CONTEXT_WINDOW = 117_647;
89
-
90
108
  export const SESSION_TRACK_LIMIT = 200;
91
109
  export const AUTH_SKEW_MS = 60_000;
92
110
  export const AUTH_TIMEOUT_MS = 15 * 60_000;
@@ -103,10 +121,8 @@ export const AD_IMPRESSION_LIMIT = 200;
103
121
  export const CREDITS_PER_USD = 40_000 / 3;
104
122
 
105
123
  export const CATALOG_TTL_MS = 10 * 60_000;
106
- export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
107
124
  export const CATALOG_TIMEOUT_MS = 8_000;
108
125
  export const REGISTRY_TTL_MS = 5 * 60_000;
109
- export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
110
126
  export const REGISTRY_RETRY_MS = 60_000;
111
127
  export const REGISTRY_TIMEOUT_MS = 3_500;
112
128
  export const REGISTRY_ATTEMPTS = 2;
package/src/logging.ts CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
5
- import { cacheDir } from "./utils/cache.js";
5
+ import { dataDir } from "./utils/data-dir.js";
6
6
 
7
7
  export type LogLevel = "info" | "warn" | "error" | "debug";
8
8
 
@@ -19,7 +19,7 @@ let fileFailureReported = false;
19
19
 
20
20
  function logFile(): string {
21
21
  const configured = process.env.FREE_PI_LOG_FILE?.trim();
22
- return configured || join(cacheDir(), "plugin.log");
22
+ return configured || join(dataDir(), "plugin.log");
23
23
  }
24
24
 
25
25
  function rotate(file: string): void {
package/src/plugin.ts CHANGED
@@ -15,6 +15,11 @@ import { closeFreePiSession } from "./api/session.js";
15
15
  import { readCredentialsToken } from "./auth/credentials.js";
16
16
  import { tokenFromCredential } from "./auth/credential.js";
17
17
  import { fetchCatalog } from "./catalog/catalog.js";
18
+ import {
19
+ loadLiveLimits,
20
+ shouldVerifyWindow,
21
+ verifyGatewayWindow,
22
+ } from "./catalog/live.js";
18
23
  import {
19
24
  accountAccess,
20
25
  buildModels,
@@ -130,9 +135,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
130
135
  const main = filterAccessibleModels(catalogMain, access);
131
136
  const defense = filterAccessibleModels(catalogDefense, access);
132
137
  const candidates = modelRegistryCandidates(registry);
138
+ const live = await loadLiveLimits();
133
139
  const configuredEffort = ctx.options?.reasoningEffort;
134
140
  const buildOptions = {
135
- compact100: state.costExperimentArm === "compact100",
141
+ live,
136
142
  ...(configuredEffort === false
137
143
  ? { reasoningEffort: false as const }
138
144
  : isReasoningEffort(configuredEffort)
@@ -174,6 +180,19 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
174
180
  }
175
181
  });
176
182
 
183
+ // The gateway does not publish its context ceiling. Verify the compiled
184
+ // window against it once a week with a free model, in the background, and
185
+ // persist the result for the next catalog build.
186
+ if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
187
+ const probe =
188
+ main.find((model) => model.free === true)?.id ??
189
+ catalog?.default_model ??
190
+ Object.keys(mainModels)[0];
191
+ if (probe) {
192
+ void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
193
+ }
194
+ }
195
+
177
196
  // V1 selected the catalog default when the user had no model configured.
178
197
  await ctx.model.transform((editor) => {
179
198
  if (editor.default.get()) return;
@@ -211,7 +230,6 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
211
230
  defaultModel: catalog?.default_model,
212
231
  clientVersion: state.latestClientVersion,
213
232
  capabilities: candidates.length,
214
- costArm: state.costExperimentArm,
215
233
  models: main.map((model) => model.id),
216
234
  },
217
235
  );
@@ -6,7 +6,7 @@ import { readCredentialsToken } from "../auth/credentials.js";
6
6
  import { tokenFromCredential } from "../auth/credential.js";
7
7
  import type { Deps } from "../deps.js";
8
8
  import { handleFreePiError } from "../errors/handle.js";
9
- import { forgetCacheMiss, observeStepUsage } from "./cache.js";
9
+ import { noteStepTokens } from "../catalog/live.js";
10
10
  import { forgetToolStats } from "./tools.js";
11
11
  import {
12
12
  beginExecution,
@@ -113,7 +113,11 @@ async function handleEvent(
113
113
  event.data?.tokens,
114
114
  );
115
115
  // Step tokens are per request; usage.updated is cumulative.
116
- observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
116
+ noteStepTokens(
117
+ deps,
118
+ deps.state.trackedModels.get(event.data?.sessionID)?.modelID ?? "",
119
+ event.data?.tokens,
120
+ );
117
121
  return;
118
122
  }
119
123
  case "session.deleted": {
@@ -121,7 +125,6 @@ async function handleEvent(
121
125
  if (typeof sessionID !== "string") return;
122
126
  await finalizeFreePiSession(deps, sessionID);
123
127
  forgetFreePiSession(deps, sessionID);
124
- forgetCacheMiss(deps, sessionID);
125
128
  forgetToolStats(deps, sessionID);
126
129
  deps.state.subagentSessions.delete(sessionID);
127
130
  return;
@@ -8,12 +8,14 @@ import { resolveToken } from "../auth/token.js";
8
8
  import {
9
9
  AD_CONTEXT_HEADER,
10
10
  AD_CONTEXT_OPT_OUT,
11
- COST_EXPERIMENT_HEADER,
12
11
  CONCURRENT_RETRY_BASE_MS,
13
12
  CONCURRENT_RETRY_MAX,
14
13
  CONCURRENT_RETRY_MAX_DELAY_MS,
15
14
  DEFENSE_PROVIDER_ID,
16
- EFFICIENCY_RULE,
15
+ FREE_PI_COMPACTION_GUIDANCE,
16
+ FREE_PI_COMPACTION_MARKER,
17
+ FREE_PI_GUIDANCE,
18
+ FREE_PI_GUIDANCE_MARKER,
17
19
  MAX_OUTPUT_TOKENS,
18
20
  PROVIDER_ID,
19
21
  RETRY_BASE_DELAY_MS,
@@ -92,6 +94,27 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
92
94
  deps.state.pendingAdTurns.set(key, turn);
93
95
  }
94
96
 
97
+ /** Adds a system block once, even when OpenCode reuses the same event. */
98
+ function appendSystemGuidance(
99
+ event: any,
100
+ text: string,
101
+ marker: string,
102
+ ): void {
103
+ const system = Array.isArray(event.system) ? event.system : [];
104
+ if (
105
+ system.some(
106
+ (part: any) =>
107
+ part?.type === "text" &&
108
+ typeof part.text === "string" &&
109
+ part.text.startsWith(marker),
110
+ )
111
+ ) {
112
+ return;
113
+ }
114
+ system.push({ type: "text", text });
115
+ event.system = system;
116
+ }
117
+
95
118
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
96
119
  async function applyGeneration(
97
120
  deps: Deps,
@@ -120,6 +143,11 @@ async function applyGeneration(
120
143
  }
121
144
 
122
145
  if (kind === "compaction") {
146
+ appendSystemGuidance(
147
+ event,
148
+ FREE_PI_COMPACTION_GUIDANCE,
149
+ FREE_PI_COMPACTION_MARKER,
150
+ );
123
151
  // OpenCode sends the messages it is folding into the summary, which is the
124
152
  // same set pi reports through `session_before_compact`.
125
153
  recordCompaction(
@@ -127,18 +155,10 @@ async function applyGeneration(
127
155
  event.sessionID,
128
156
  Array.isArray(event.messages) ? event.messages.length : 0,
129
157
  );
130
- }
131
-
132
- if (deps.state.costExperimentArm === "efficiency") {
133
- const system = Array.isArray(event.system) ? event.system : [];
134
- if (
135
- !system.some(
136
- (part: any) => part?.type === "text" && part.text === EFFICIENCY_RULE,
137
- )
138
- ) {
139
- system.push({ type: "text", text: EFFICIENCY_RULE });
140
- event.system = system;
141
- }
158
+ } else if (kind === "primary") {
159
+ // The free models tend to skip planning and claim work they did not do;
160
+ // the CLI gets a much larger agent prompt. This is the compact equivalent.
161
+ appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
142
162
  }
143
163
 
144
164
  const agent = event.agent;
@@ -188,9 +208,6 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
188
208
  if (deps.state.subagentSessions.has(event.sessionID)) {
189
209
  event.headers[SUBAGENT_HEADER] = "1";
190
210
  }
191
- if (deps.state.costExperimentArm) {
192
- event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
193
- }
194
211
 
195
212
  // Title requests are suppressed by the title hook, so an ad for them would be
196
213
  // an impression the user never sees.
package/src/state.ts CHANGED
@@ -3,7 +3,6 @@
3
3
  import { DEFAULT_CLIENT_VERSION } from "./constants.js";
4
4
  import type {
5
5
  AdTurn,
6
- CacheMissState,
7
6
  Catalog,
8
7
  FreePiError,
9
8
  ModelRegistry,
@@ -26,7 +25,6 @@ export type RuntimeState = {
26
25
  cachedRegistryAt: number;
27
26
  registryAttemptAt: number;
28
27
  registryPromise?: Promise<ModelRegistry | undefined>;
29
- costExperimentArm?: string;
30
28
  lastCatalogNotice?: string;
31
29
  lastQuotaNotice?: string;
32
30
  catalogModels: Catalog;
@@ -64,20 +62,7 @@ export type RuntimeState = {
64
62
  pendingAdTurns: Map<string, AdTurn>;
65
63
  adImpressions: Map<string, Promise<void>>;
66
64
  trackedModels: Map<string, TrackedModel>;
67
- cacheMisses: Map<string, CacheMissState>;
68
65
  toolStats: Map<string, ToolStats>;
69
- /** Successful paid-tool answers, keyed by canonical input, to avoid rebilling. */
70
- toolSpend: Map<
71
- string,
72
- {
73
- at: number;
74
- output: {
75
- content: ReadonlyArray<{ type: "text"; text: string }>;
76
- metadata: Record<string, unknown>;
77
- };
78
- }
79
- >;
80
- toolSpendPending: Map<string, Promise<any>>;
81
66
  subagentSessions: Set<string>;
82
67
  };
83
68
 
@@ -108,10 +93,7 @@ export function createRuntimeState(): RuntimeState {
108
93
  pendingAdTurns: new Map(),
109
94
  adImpressions: new Map(),
110
95
  trackedModels: new Map(),
111
- cacheMisses: new Map(),
112
96
  toolStats: new Map(),
113
- toolSpend: new Map(),
114
- toolSpendPending: new Map(),
115
97
  subagentSessions: new Set(),
116
98
  };
117
99
  }
@@ -4,14 +4,14 @@
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
 
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
12
12
  import { join } from "node:path";
13
13
  import type { Logger } from "../logging.js";
14
- import { cacheDir } from "../utils/cache.js";
14
+ import { dataDir } from "../utils/data-dir.js";
15
15
 
16
16
  type Owner = { pid: number; startedAt: number; id: string };
17
17
 
@@ -24,7 +24,7 @@ const MAX_WAIT_MS = 120_000;
24
24
  let chain: Promise<void> = Promise.resolve();
25
25
 
26
26
  function lockDir(): string {
27
- return join(cacheDir(), "vision.lock");
27
+ return join(dataDir(), "vision.lock");
28
28
  }
29
29
 
30
30
  function pidAlive(pid: number): boolean {
@@ -87,9 +87,9 @@ async function acquire(log: Logger): Promise<Slot | undefined> {
87
87
  const startedAt = Date.now();
88
88
 
89
89
  try {
90
- await mkdir(cacheDir(), { recursive: true });
90
+ await mkdir(dataDir(), { recursive: true });
91
91
  } catch {
92
- // Without a cache directory the file lock is unavailable; the in-process
92
+ // Without a data directory the file lock is unavailable; the in-process
93
93
  // queue still serializes calls, so keep going.
94
94
  }
95
95
 
@@ -8,13 +8,11 @@
8
8
  */
9
9
 
10
10
  import type { Plugin } from "@opencode/plugin";
11
- import { createHash } from "node:crypto";
12
11
  import { resolveToken } from "../auth/token.js";
13
12
  import type { Deps } from "../deps.js";
14
13
  import { isFreePiSession } from "../session/tools.js";
15
14
  import { resolveBaseUrl } from "../utils/urls.js";
16
15
  import { loadImage, prepareImage, type VisionMime } from "./image.js";
17
- import { spendOnce } from "./spend-cache.js";
18
16
  import { withVisionSlot } from "./vision-queue.js";
19
17
 
20
18
  type Registration = { dispose: () => Promise<void> };
@@ -273,44 +271,34 @@ async function executeVision(
273
271
  );
274
272
  }
275
273
 
276
- const imageKey = createHash("sha256")
277
- .update(prepared.mime)
278
- .update("\u0000")
279
- .update(prepared.data)
280
- .update("\u0000")
281
- .update(question)
282
- .digest("hex");
283
-
284
- return spendOnce(deps, `vision:${imageKey}`, async () => {
285
- const queued = await withVisionSlot(deps.log, () =>
286
- askVision(deps, token, prepared.data, prepared.mime, question, context.signal),
274
+ const queued = await withVisionSlot(deps.log, () =>
275
+ askVision(deps, token, prepared.data, prepared.mime, question, context.signal),
276
+ );
277
+ if (!queued.ok) {
278
+ return fail(
279
+ "Another image question is still running. Wait a moment and call look_at_image again.",
287
280
  );
288
- if (!queued.ok) {
289
- return fail(
290
- "Another image question is still running. Wait a moment and call look_at_image again.",
291
- );
292
- }
293
- if (!queued.value.ok) return fail(queued.value.text);
281
+ }
282
+ if (!queued.value.ok) return fail(queued.value.text);
294
283
 
295
- const { answer, attempts } = queued.value;
296
- const elapsed = Date.now() - startedAt;
297
- deps.log.info("look_at_image answered", {
298
- path,
299
- ms: elapsed,
300
- attempts,
301
- resized: prepared.resized,
302
- bytes: prepared.bytes,
303
- size: `${prepared.width}x${prepared.height}`,
304
- mime: prepared.mime,
305
- model: answer.model,
306
- });
307
- return done(questionText(path, answer.text), {
308
- ok: true,
309
- ...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
310
- ...(answer.model !== undefined ? { model: answer.model } : {}),
311
- elapsed_ms: elapsed,
312
- attempts,
313
- });
284
+ const { answer, attempts } = queued.value;
285
+ const elapsed = Date.now() - startedAt;
286
+ deps.log.info("look_at_image answered", {
287
+ path,
288
+ ms: elapsed,
289
+ attempts,
290
+ resized: prepared.resized,
291
+ bytes: prepared.bytes,
292
+ size: `${prepared.width}x${prepared.height}`,
293
+ mime: prepared.mime,
294
+ model: answer.model,
295
+ });
296
+ return done(questionText(path, answer.text), {
297
+ ok: true,
298
+ ...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
299
+ ...(answer.model !== undefined ? { model: answer.model } : {}),
300
+ elapsed_ms: elapsed,
301
+ attempts,
314
302
  });
315
303
  }
316
304
 
package/src/tools/web.ts CHANGED
@@ -15,7 +15,6 @@ import {
15
15
  isGatedSession,
16
16
  mappedText,
17
17
  } from "./api.js";
18
- import { spendOnce } from "./spend-cache.js";
19
18
 
20
19
  const ERRORS: Record<string, string> = {
21
20
  daily_cap:
@@ -115,30 +114,28 @@ async function executeWebSearch(
115
114
  const num =
116
115
  typeof input?.num_results === "number" ? input.num_results : undefined;
117
116
 
118
- return spendOnce(deps, `web:${query}\u0000${num ?? ""}`, async () => {
119
- const result = await freePiRequest(deps, {
120
- path: "/tools/web-search",
121
- method: "POST",
122
- body: { query, ...(num !== undefined ? { num_results: num } : {}) },
123
- timeoutMs: 30_000,
124
- signal: context.signal,
125
- label: "The web search",
126
- });
127
- if (!result.ok) return fail(mappedText(ERRORS, result));
117
+ const result = await freePiRequest(deps, {
118
+ path: "/tools/web-search",
119
+ method: "POST",
120
+ body: { query, ...(num !== undefined ? { num_results: num } : {}) },
121
+ timeoutMs: 30_000,
122
+ signal: context.signal,
123
+ label: "The web search",
124
+ });
125
+ if (!result.ok) return fail(mappedText(ERRORS, result));
128
126
 
129
- deps.log.info("web_search answered", {
130
- query,
131
- results: Array.isArray(result.data?.results)
132
- ? result.data.results.length
133
- : 0,
134
- costUsd: result.data?.cost_usd,
135
- });
136
- return done(formatWebResults(query, result.data?.results ?? []), {
137
- ok: true,
138
- ...(typeof result.data?.cost_usd === "number"
139
- ? { cost_usd: result.data.cost_usd }
140
- : {}),
141
- });
127
+ deps.log.info("web_search answered", {
128
+ query,
129
+ results: Array.isArray(result.data?.results)
130
+ ? result.data.results.length
131
+ : 0,
132
+ costUsd: result.data?.cost_usd,
133
+ });
134
+ return done(formatWebResults(query, result.data?.results ?? []), {
135
+ ok: true,
136
+ ...(typeof result.data?.cost_usd === "number"
137
+ ? { cost_usd: result.data.cost_usd }
138
+ : {}),
142
139
  });
143
140
  }
144
141
 
@@ -155,42 +152,35 @@ async function executeDocsLookup(
155
152
  if (!library) return fail("docs_lookup needs a library name.");
156
153
  if (!query) return fail("docs_lookup needs a specific question.");
157
154
 
158
- const result = await spendOnce(
159
- deps,
160
- `docs:${library}\u0000${query}\u0000${libraryId}`,
161
- () =>
162
- freePiRequest(deps, {
163
- path: "/tools/docs",
164
- method: "POST",
165
- body: {
166
- library,
167
- query,
168
- ...(libraryId ? { library_id: libraryId } : {}),
169
- },
170
- timeoutMs: 30_000,
171
- signal: context.signal,
172
- label: "The documentation lookup",
173
- }).then((lookup) => {
174
- if (!lookup.ok) return fail(mappedText(ERRORS, lookup, library));
175
- const data = lookup.data ?? {};
176
- deps.log.info("docs_lookup answered", {
177
- library,
178
- libraryID: data.library_id,
179
- costUsd: data.cost_usd,
180
- });
181
- return done(
182
- `${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`,
183
- {
184
- ok: true,
185
- library_id: data.library_id,
186
- ...(typeof data.cost_usd === "number"
187
- ? { cost_usd: data.cost_usd }
188
- : {}),
189
- },
190
- );
191
- }),
155
+ const lookup = await freePiRequest(deps, {
156
+ path: "/tools/docs",
157
+ method: "POST",
158
+ body: {
159
+ library,
160
+ query,
161
+ ...(libraryId ? { library_id: libraryId } : {}),
162
+ },
163
+ timeoutMs: 30_000,
164
+ signal: context.signal,
165
+ label: "The documentation lookup",
166
+ });
167
+ if (!lookup.ok) return fail(mappedText(ERRORS, lookup, library));
168
+ const data = lookup.data ?? {};
169
+ deps.log.info("docs_lookup answered", {
170
+ library,
171
+ libraryID: data.library_id,
172
+ costUsd: data.cost_usd,
173
+ });
174
+ return done(
175
+ `${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`,
176
+ {
177
+ ok: true,
178
+ library_id: data.library_id,
179
+ ...(typeof data.cost_usd === "number"
180
+ ? { cost_usd: data.cost_usd }
181
+ : {}),
182
+ },
192
183
  );
193
- return result;
194
184
  }
195
185
 
196
186
  export async function registerWebTools(
package/src/types.ts CHANGED
@@ -76,7 +76,6 @@ export type Catalog = {
76
76
  default_model?: string;
77
77
  notice?: string;
78
78
  models?: CatalogModel[];
79
- cost_experiment?: { arm?: string };
80
79
  };
81
80
 
82
81
  /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
@@ -115,6 +114,11 @@ export type FreePiOptions = {
115
114
  * models plan before answering. Set `false` to keep the gateway default.
116
115
  */
117
116
  reasoningEffort?: string | false;
117
+ /**
118
+ * Verify the gateway's real context window once a week and reuse the measured
119
+ * value. Defaults to true; set `false` to stay on the compiled window.
120
+ */
121
+ liveLimits?: boolean;
118
122
  };
119
123
 
120
124
  export type MeResponse = {
@@ -243,13 +247,6 @@ export type TrackedModel = {
243
247
  modelID: string;
244
248
  };
245
249
 
246
- export type CacheMissState = {
247
- promptTokens: number;
248
- at: number;
249
- modelKey: string;
250
- reportedCache: boolean;
251
- };
252
-
253
250
  export type ToolStats = {
254
251
  meta: string[];
255
252
  metaBytes: number;
@@ -0,0 +1,14 @@
1
+ /** Per-user directory for the files the plugin keeps between runs. */
2
+
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ export function dataDir(): string {
7
+ const configured = process.env.FREE_PI_DATA_DIR?.trim();
8
+ if (configured) return configured;
9
+ return join(homedir(), ".cache", "opencode", "free-pi");
10
+ }
11
+
12
+ export function dataPath(name: string): string {
13
+ return join(dataDir(), name);
14
+ }
@@ -1,15 +0,0 @@
1
- /**
2
- * Prompt-cache miss notices, mirroring pi's `cache-stats` detector.
3
- *
4
- * free-pi reports no per-token cost, so only the token threshold applies. The
5
- * notices are opt-in because OpenCode has no toast surface for them.
6
- */
7
- import type { Deps } from "../deps.js";
8
- import type { TokenUsageLike } from "../types.js";
9
- /**
10
- * Records one step's usage and logs a miss when the prompt was re-billed.
11
- * `session.step.ended` carries per-step tokens; `session.usage.updated` is a
12
- * cumulative total and must not be fed here.
13
- */
14
- export declare function observeStepUsage(deps: Deps, sessionID: string | undefined, tokens: TokenUsageLike | undefined): void;
15
- export declare function forgetCacheMiss(deps: Deps, sessionID: string): void;