@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
@@ -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;
@@ -1,57 +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 { CACHE_MISS_NOISE_FLOOR_TOKENS, CACHE_MISS_NOTICE_TOKENS, CACHE_TTL_MS, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "../constants.js";
8
- function noticesEnabled() {
9
- const value = process.env.FREE_PI_CACHE_MISS_NOTICES?.trim().toLowerCase();
10
- return value === "1" || value === "true" || value === "yes";
11
- }
12
- function idleText(idleMs) {
13
- const minutes = Math.round(idleMs / 60_000);
14
- return idleMs > CACHE_TTL_MS ? ` after ${minutes}m idle` : "";
15
- }
16
- /**
17
- * Records one step's usage and logs a miss when the prompt was re-billed.
18
- * `session.step.ended` carries per-step tokens; `session.usage.updated` is a
19
- * cumulative total and must not be fed here.
20
- */
21
- export function observeStepUsage(deps, sessionID, tokens) {
22
- if (!noticesEnabled() || typeof sessionID !== "string" || !sessionID)
23
- return;
24
- const tracked = deps.state.trackedModels.get(sessionID);
25
- if (tracked?.providerID !== PROVIDER_ID &&
26
- tracked?.providerID !== DEFENSE_PROVIDER_ID)
27
- return;
28
- const cacheRead = tokens?.cache?.read ?? 0;
29
- const cacheWrite = tokens?.cache?.write ?? 0;
30
- const promptTokens = (tokens?.input ?? 0) + cacheRead + cacheWrite;
31
- if (promptTokens <= 0)
32
- return;
33
- const now = Date.now();
34
- const modelKey = `${tracked.providerID}/${tracked.modelID}`;
35
- const previous = deps.state.cacheMisses.get(sessionID);
36
- if (previous) {
37
- const reportedCache = previous.reportedCache || cacheRead + cacheWrite > 0;
38
- if (reportedCache) {
39
- const missedTokens = Math.min(previous.promptTokens, promptTokens) - cacheRead;
40
- if (missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS) {
41
- const modelChanged = previous.modelKey !== modelKey;
42
- if (missedTokens >= CACHE_MISS_NOTICE_TOKENS) {
43
- deps.log.info(`cache miss: ${missedTokens} tokens re-billed${idleText(now - previous.at)}${modelChanged ? " (model changed)" : ""}`, { sessionID, model: modelKey });
44
- }
45
- }
46
- }
47
- }
48
- deps.state.cacheMisses.set(sessionID, {
49
- promptTokens,
50
- at: now,
51
- modelKey,
52
- reportedCache: cacheRead + cacheWrite > 0 || (previous?.reportedCache ?? false),
53
- });
54
- }
55
- export function forgetCacheMiss(deps, sessionID) {
56
- deps.state.cacheMisses.delete(sessionID);
57
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Spend-once cache for the free-pi tools that consume allowance.
3
- *
4
- * `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
5
- * run. Models often ask the same question twice in a turn (or a subagent and
6
- * its lead both ask it), so identical inputs reuse the first answer instead of
7
- * spending credits again. Failures are never cached: the next attempt must
8
- * reach the server and see the real error. Concurrent identical calls share one
9
- * in-flight request, so a parallel tool call cannot double-charge either.
10
- */
11
- import type { Deps } from "../deps.js";
12
- import type { ToolOutput } from "./api.js";
13
- /** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
14
- export declare const SPEND_CACHE_TTL_MS: number;
15
- export declare function spendOnce(deps: Deps, key: string, run: () => Promise<ToolOutput>): Promise<ToolOutput>;
@@ -1,64 +0,0 @@
1
- /**
2
- * Spend-once cache for the free-pi tools that consume allowance.
3
- *
4
- * `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
5
- * run. Models often ask the same question twice in a turn (or a subagent and
6
- * its lead both ask it), so identical inputs reuse the first answer instead of
7
- * spending credits again. Failures are never cached: the next attempt must
8
- * reach the server and see the real error. Concurrent identical calls share one
9
- * in-flight request, so a parallel tool call cannot double-charge either.
10
- */
11
- /** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
12
- export const SPEND_CACHE_TTL_MS = 30 * 60 * 1_000;
13
- const SPEND_CACHE_LIMIT = 128;
14
- function trim(deps) {
15
- const now = Date.now();
16
- for (const [key, entry] of deps.state.toolSpend) {
17
- if (now - entry.at >= SPEND_CACHE_TTL_MS)
18
- deps.state.toolSpend.delete(key);
19
- }
20
- while (deps.state.toolSpend.size > SPEND_CACHE_LIMIT) {
21
- const oldest = deps.state.toolSpend.keys().next().value;
22
- if (oldest === undefined)
23
- break;
24
- deps.state.toolSpend.delete(oldest);
25
- }
26
- }
27
- function cachedResult(entry) {
28
- const { cost_usd: _spent, ...metadata } = entry.output.metadata;
29
- return {
30
- content: entry.output.content.map((part) => ({
31
- type: "text",
32
- text: `${part.text}\n\n(cached answer from earlier - no allowance used)`,
33
- })),
34
- metadata: { ...metadata, cached: true },
35
- };
36
- }
37
- export async function spendOnce(deps, key, run) {
38
- const entry = deps.state.toolSpend.get(key);
39
- if (entry && Date.now() - entry.at < SPEND_CACHE_TTL_MS) {
40
- deps.log.info("reused a cached free-pi tool answer", { key });
41
- return cachedResult(entry);
42
- }
43
- const pending = deps.state.toolSpendPending.get(key);
44
- if (pending) {
45
- const output = await pending;
46
- return output.metadata.ok
47
- ? cachedResult({ at: Date.now(), output })
48
- : run();
49
- }
50
- const request = run();
51
- deps.state.toolSpendPending.set(key, request);
52
- try {
53
- const output = await request;
54
- if (output.metadata.ok) {
55
- deps.state.toolSpend.set(key, { at: Date.now(), output });
56
- trim(deps);
57
- }
58
- return output;
59
- }
60
- finally {
61
- if (deps.state.toolSpendPending.get(key) === request)
62
- deps.state.toolSpendPending.delete(key);
63
- }
64
- }
@@ -1,7 +0,0 @@
1
- /** Best-effort JSON cache on disk for data fetched over the network. */
2
- export declare function cacheDir(): string;
3
- export declare function cachePath(name: string): string;
4
- /** Reads a cached value when it is younger than `ttlMs`. Never throws. */
5
- export declare function readCache<T>(name: string, ttlMs: number): Promise<T | undefined>;
6
- /** Writes a value atomically. Never throws. */
7
- export declare function writeCache<T>(name: string, value: T): Promise<void>;
@@ -1,45 +0,0 @@
1
- /** Best-effort JSON cache on disk for data fetched over the network. */
2
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
5
- export function cacheDir() {
6
- const configured = process.env.FREE_PI_CACHE_DIR?.trim();
7
- if (configured)
8
- return configured;
9
- return join(homedir(), ".cache", "opencode", "free-pi");
10
- }
11
- export function cachePath(name) {
12
- return join(cacheDir(), name);
13
- }
14
- /** Reads a cached value when it is younger than `ttlMs`. Never throws. */
15
- export async function readCache(name, ttlMs) {
16
- try {
17
- const raw = await readFile(cachePath(name), "utf8");
18
- const entry = JSON.parse(raw);
19
- if (!entry || typeof entry.at !== "number")
20
- return undefined;
21
- if (!Number.isFinite(entry.at))
22
- return undefined;
23
- if (Date.now() - entry.at > ttlMs)
24
- return undefined;
25
- return entry.value;
26
- }
27
- catch {
28
- return undefined;
29
- }
30
- }
31
- /** Writes a value atomically. Never throws. */
32
- export async function writeCache(name, value) {
33
- try {
34
- const file = cachePath(name);
35
- await mkdir(dirname(file), { recursive: true });
36
- const temp = `${file}.${process.pid}.${Math.random()
37
- .toString(36)
38
- .slice(2)}.tmp`;
39
- await writeFile(temp, JSON.stringify({ at: Date.now(), value }), "utf8");
40
- await rename(temp, file);
41
- }
42
- catch {
43
- // The cache is an optimization; failures must not affect the plugin.
44
- }
45
- }
@@ -1,82 +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
-
8
- import {
9
- CACHE_MISS_NOISE_FLOOR_TOKENS,
10
- CACHE_MISS_NOTICE_TOKENS,
11
- CACHE_TTL_MS,
12
- DEFENSE_PROVIDER_ID,
13
- PROVIDER_ID,
14
- } from "../constants.js";
15
- import type { Deps } from "../deps.js";
16
- import type { TokenUsageLike } from "../types.js";
17
-
18
- function noticesEnabled(): boolean {
19
- const value = process.env.FREE_PI_CACHE_MISS_NOTICES?.trim().toLowerCase();
20
- return value === "1" || value === "true" || value === "yes";
21
- }
22
-
23
- function idleText(idleMs: number): string {
24
- const minutes = Math.round(idleMs / 60_000);
25
- return idleMs > CACHE_TTL_MS ? ` after ${minutes}m idle` : "";
26
- }
27
-
28
- /**
29
- * Records one step's usage and logs a miss when the prompt was re-billed.
30
- * `session.step.ended` carries per-step tokens; `session.usage.updated` is a
31
- * cumulative total and must not be fed here.
32
- */
33
- export function observeStepUsage(
34
- deps: Deps,
35
- sessionID: string | undefined,
36
- tokens: TokenUsageLike | undefined,
37
- ): void {
38
- if (!noticesEnabled() || typeof sessionID !== "string" || !sessionID) return;
39
- const tracked = deps.state.trackedModels.get(sessionID);
40
- if (
41
- tracked?.providerID !== PROVIDER_ID &&
42
- tracked?.providerID !== DEFENSE_PROVIDER_ID
43
- )
44
- return;
45
-
46
- const cacheRead = tokens?.cache?.read ?? 0;
47
- const cacheWrite = tokens?.cache?.write ?? 0;
48
- const promptTokens = (tokens?.input ?? 0) + cacheRead + cacheWrite;
49
- if (promptTokens <= 0) return;
50
-
51
- const now = Date.now();
52
- const modelKey = `${tracked.providerID}/${tracked.modelID}`;
53
- const previous = deps.state.cacheMisses.get(sessionID);
54
- if (previous) {
55
- const reportedCache =
56
- previous.reportedCache || cacheRead + cacheWrite > 0;
57
- if (reportedCache) {
58
- const missedTokens =
59
- Math.min(previous.promptTokens, promptTokens) - cacheRead;
60
- if (missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS) {
61
- const modelChanged = previous.modelKey !== modelKey;
62
- if (missedTokens >= CACHE_MISS_NOTICE_TOKENS) {
63
- deps.log.info(
64
- `cache miss: ${missedTokens} tokens re-billed${idleText(now - previous.at)}${modelChanged ? " (model changed)" : ""}`,
65
- { sessionID, model: modelKey },
66
- );
67
- }
68
- }
69
- }
70
- }
71
-
72
- deps.state.cacheMisses.set(sessionID, {
73
- promptTokens,
74
- at: now,
75
- modelKey,
76
- reportedCache: cacheRead + cacheWrite > 0 || (previous?.reportedCache ?? false),
77
- });
78
- }
79
-
80
- export function forgetCacheMiss(deps: Deps, sessionID: string): void {
81
- deps.state.cacheMisses.delete(sessionID);
82
- }
@@ -1,79 +0,0 @@
1
- /**
2
- * Spend-once cache for the free-pi tools that consume allowance.
3
- *
4
- * `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
5
- * run. Models often ask the same question twice in a turn (or a subagent and
6
- * its lead both ask it), so identical inputs reuse the first answer instead of
7
- * spending credits again. Failures are never cached: the next attempt must
8
- * reach the server and see the real error. Concurrent identical calls share one
9
- * in-flight request, so a parallel tool call cannot double-charge either.
10
- */
11
-
12
- import type { Deps } from "../deps.js";
13
- import type { ToolOutput } from "./api.js";
14
-
15
- /** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
16
- export const SPEND_CACHE_TTL_MS = 30 * 60 * 1_000;
17
- const SPEND_CACHE_LIMIT = 128;
18
-
19
- type Entry = {
20
- readonly at: number;
21
- readonly output: ToolOutput;
22
- };
23
-
24
- function trim(deps: Deps): void {
25
- const now = Date.now();
26
- for (const [key, entry] of deps.state.toolSpend) {
27
- if (now - entry.at >= SPEND_CACHE_TTL_MS) deps.state.toolSpend.delete(key);
28
- }
29
- while (deps.state.toolSpend.size > SPEND_CACHE_LIMIT) {
30
- const oldest = deps.state.toolSpend.keys().next().value;
31
- if (oldest === undefined) break;
32
- deps.state.toolSpend.delete(oldest);
33
- }
34
- }
35
-
36
- function cachedResult(entry: Entry): ToolOutput {
37
- const { cost_usd: _spent, ...metadata } = entry.output.metadata;
38
- return {
39
- content: entry.output.content.map((part) => ({
40
- type: "text" as const,
41
- text: `${part.text}\n\n(cached answer from earlier - no allowance used)`,
42
- })),
43
- metadata: { ...metadata, cached: true },
44
- };
45
- }
46
-
47
- export async function spendOnce(
48
- deps: Deps,
49
- key: string,
50
- run: () => Promise<ToolOutput>,
51
- ): Promise<ToolOutput> {
52
- const entry = deps.state.toolSpend.get(key);
53
- if (entry && Date.now() - entry.at < SPEND_CACHE_TTL_MS) {
54
- deps.log.info("reused a cached free-pi tool answer", { key });
55
- return cachedResult(entry);
56
- }
57
-
58
- const pending = deps.state.toolSpendPending.get(key);
59
- if (pending) {
60
- const output = await pending;
61
- return output.metadata.ok
62
- ? cachedResult({ at: Date.now(), output })
63
- : run();
64
- }
65
-
66
- const request = run();
67
- deps.state.toolSpendPending.set(key, request);
68
- try {
69
- const output = await request;
70
- if (output.metadata.ok) {
71
- deps.state.toolSpend.set(key, { at: Date.now(), output });
72
- trim(deps);
73
- }
74
- return output;
75
- } finally {
76
- if (deps.state.toolSpendPending.get(key) === request)
77
- deps.state.toolSpendPending.delete(key);
78
- }
79
- }