@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,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
- }
@@ -1,49 +0,0 @@
1
- /** Best-effort JSON cache on disk for data fetched over the network. */
2
-
3
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
- import { dirname, join } from "node:path";
6
-
7
- type CacheEntry<T> = { at: number; value: T };
8
-
9
- export function cacheDir(): string {
10
- const configured = process.env.FREE_PI_CACHE_DIR?.trim();
11
- if (configured) return configured;
12
- return join(homedir(), ".cache", "opencode", "free-pi");
13
- }
14
-
15
- export function cachePath(name: string): string {
16
- return join(cacheDir(), name);
17
- }
18
-
19
- /** Reads a cached value when it is younger than `ttlMs`. Never throws. */
20
- export async function readCache<T>(
21
- name: string,
22
- ttlMs: number,
23
- ): Promise<T | undefined> {
24
- try {
25
- const raw = await readFile(cachePath(name), "utf8");
26
- const entry = JSON.parse(raw) as CacheEntry<T>;
27
- if (!entry || typeof entry.at !== "number") return undefined;
28
- if (!Number.isFinite(entry.at)) return undefined;
29
- if (Date.now() - entry.at > ttlMs) return undefined;
30
- return entry.value;
31
- } catch {
32
- return undefined;
33
- }
34
- }
35
-
36
- /** Writes a value atomically. Never throws. */
37
- export async function writeCache<T>(name: string, value: T): Promise<void> {
38
- try {
39
- const file = cachePath(name);
40
- await mkdir(dirname(file), { recursive: true });
41
- const temp = `${file}.${process.pid}.${Math.random()
42
- .toString(36)
43
- .slice(2)}.tmp`;
44
- await writeFile(temp, JSON.stringify({ at: Date.now(), value }), "utf8");
45
- await rename(temp, file);
46
- } catch {
47
- // The cache is an optimization; failures must not affect the plugin.
48
- }
49
- }