@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
@@ -1,9 +1,7 @@
1
1
  /** Fetches the models.dev capability registry. */
2
- import { REGISTRY_ATTEMPTS, REGISTRY_DISK_TTL_MS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
2
+ import { REGISTRY_ATTEMPTS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
3
3
  import { sleep } from "../utils/async.js";
4
- import { readCache, writeCache } from "../utils/cache.js";
5
4
  import { modelsRegistryUrl } from "../utils/urls.js";
6
- const CACHE_FILE = "models-dev.json";
7
5
  function isRegistry(value) {
8
6
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
7
  }
@@ -54,7 +52,6 @@ export function refreshModelsRegistry(deps) {
54
52
  }
55
53
  state.cachedRegistry = registry;
56
54
  state.cachedRegistryAt = Date.now();
57
- void writeCache(CACHE_FILE, registry);
58
55
  return registry;
59
56
  }
60
57
  catch (error) {
@@ -79,18 +76,11 @@ export async function fetchModelsRegistry(deps) {
79
76
  return state.cachedRegistry;
80
77
  }
81
78
  if (!state.cachedRegistry) {
82
- const disk = await readCache(CACHE_FILE, REGISTRY_DISK_TTL_MS);
83
- if (isRegistry(disk)) {
84
- state.cachedRegistry = disk;
85
- state.cachedRegistryAt = Date.now();
86
- // Serve the cached copy immediately and refresh it in the background.
87
- void refreshModelsRegistry(deps);
88
- return disk;
79
+ if (state.registryAttemptAt &&
80
+ Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
81
+ return state.cachedRegistry;
89
82
  }
90
- }
91
- if (state.registryAttemptAt &&
92
- Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
93
- return state.cachedRegistry;
83
+ return refreshModelsRegistry(deps);
94
84
  }
95
85
  return refreshModelsRegistry(deps);
96
86
  }
@@ -7,8 +7,15 @@ export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
7
  export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
8
  export declare const DEFAULT_CLIENT_VERSION = "0.6.25";
9
9
  export declare const CONSENT_VERSION = "4";
10
+ /**
11
+ * The provider CLI's window. The gateway enforces its own ceiling but does not
12
+ * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
13
+ * with what the server actually accepts.
14
+ */
10
15
  export declare const CONTEXT_WINDOW = 200000;
11
16
  export declare const MAX_OUTPUT_TOKENS = 32768;
17
+ /** How long a measured gateway window is trusted before checking again. */
18
+ export declare const VERIFY_LIMITS_TTL_MS: number;
12
19
  export declare 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 declare const AD_CONTEXT_HEADER = "x-ad-context";
16
23
  */
17
24
  export declare const AD_CONTEXT_OPT_OUT = "none";
18
25
  export declare const SUBAGENT_HEADER = "x-freepi-subagent";
19
- export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
- export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
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
@@ -28,6 +33,21 @@ export declare const EFFICIENCY_RULE = "- When several independent reads or sear
28
33
  export declare const DEFAULT_REASONING_EFFORT = "medium";
29
34
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
30
35
  export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high"];
36
+ /**
37
+ * Injected into every primary free-pi request. OpenCode already supplies the
38
+ * coding instructions; this block covers the failure modes the weaker free
39
+ * models show: skipping analysis, inventing verification, and ignoring the
40
+ * context the conversation already established.
41
+ */
42
+ export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
43
+ export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
44
+ /**
45
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
46
+ * for terse checkpoints, which is fine for strong models but loses the exact
47
+ * facts the free models need; spell out what must survive the rewrite.
48
+ */
49
+ export declare const FREE_PI_COMPACTION_GUIDANCE = "# free-pi compaction rules\n- Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.\n- Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.\n- Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.\n- Do not invent progress or results that are not in the conversation.";
50
+ export declare const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
31
51
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
32
52
  export declare const HEADER_TIMEOUT_MS = 300000;
33
53
  export declare const CHUNK_TIMEOUT_MS = 300000;
@@ -43,23 +63,12 @@ export declare const RETRY_MAX_DELAY_MS = 60000;
43
63
  export declare const CONCURRENT_RETRY_MAX = 6;
44
64
  export declare const CONCURRENT_RETRY_BASE_MS = 1000;
45
65
  export declare const CONCURRENT_RETRY_MAX_DELAY_MS = 15000;
46
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
47
- export declare const CACHE_TTL_MS: number;
48
- export declare const CACHE_MISS_NOISE_FLOOR_TOKENS = 1024;
49
- export declare const CACHE_MISS_NOTICE_TOKENS = 20000;
50
66
  /** Tool outcome headers emitted by the free-pi provider CLI. */
51
67
  export declare const TOOL_META_HEADER = "x-freepi-tool-meta";
52
68
  export declare const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
53
69
  export declare const COMPACTED_HEADER = "x-freepi-compacted";
54
70
  export declare const TOOL_META_BUDGET = 1500;
55
71
  export declare const TOOL_ID_LIMIT = 50;
56
- /**
57
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
58
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
59
- * 117_647 is the smallest window that keeps that trigger at 100k.
60
- */
61
- export declare const COMPACT100_TRIGGER_TOKENS = 100000;
62
- export declare const COMPACT100_CONTEXT_WINDOW = 117647;
63
72
  export declare const SESSION_TRACK_LIMIT = 200;
64
73
  export declare const AUTH_SKEW_MS = 60000;
65
74
  export declare const AUTH_TIMEOUT_MS: number;
@@ -73,10 +82,8 @@ export declare const AD_TURN_LIMIT = 200;
73
82
  export declare const AD_IMPRESSION_LIMIT = 200;
74
83
  export declare const CREDITS_PER_USD: number;
75
84
  export declare const CATALOG_TTL_MS: number;
76
- export declare const CATALOG_DISK_TTL_MS: number;
77
85
  export declare const CATALOG_TIMEOUT_MS = 8000;
78
86
  export declare const REGISTRY_TTL_MS: number;
79
- export declare const REGISTRY_DISK_TTL_MS: number;
80
87
  export declare const REGISTRY_RETRY_MS = 60000;
81
88
  export declare const REGISTRY_TIMEOUT_MS = 3500;
82
89
  export declare const REGISTRY_ATTEMPTS = 2;
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
@@ -41,6 +46,31 @@ export const DEFAULT_THINKING_LEVELS = [
41
46
  "medium",
42
47
  "high",
43
48
  ];
49
+ /**
50
+ * Injected into every primary free-pi request. OpenCode already supplies the
51
+ * coding instructions; this block covers the failure modes the weaker free
52
+ * models show: skipping analysis, inventing verification, and ignoring the
53
+ * context the conversation already established.
54
+ */
55
+ export const FREE_PI_GUIDANCE = `# free-pi working rules
56
+ - Answer the user's latest request and keep their constraints; do not switch to a different task.
57
+ - 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.
58
+ - 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.
59
+ - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
60
+ - Never claim to have compacted, summarized or cleared context unless that actually happened.
61
+ - Continue until the request is finished, then report concisely what changed and what you verified.`;
62
+ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
63
+ /**
64
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
65
+ * for terse checkpoints, which is fine for strong models but loses the exact
66
+ * facts the free models need; spell out what must survive the rewrite.
67
+ */
68
+ export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
69
+ - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
70
+ - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
71
+ - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
72
+ - Do not invent progress or results that are not in the conversation.`;
73
+ export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
44
74
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
45
75
  export const HEADER_TIMEOUT_MS = 300_000;
46
76
  export const CHUNK_TIMEOUT_MS = 300_000;
@@ -56,23 +86,12 @@ export const RETRY_MAX_DELAY_MS = 60_000;
56
86
  export const CONCURRENT_RETRY_MAX = 6;
57
87
  export const CONCURRENT_RETRY_BASE_MS = 1_000;
58
88
  export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
59
- /** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
60
- export const CACHE_TTL_MS = 5 * 60_000;
61
- export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
62
- export const CACHE_MISS_NOTICE_TOKENS = 20_000;
63
89
  /** Tool outcome headers emitted by the free-pi provider CLI. */
64
90
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
65
91
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
66
92
  export const COMPACTED_HEADER = "x-freepi-compacted";
67
93
  export const TOOL_META_BUDGET = 1_500;
68
94
  export const TOOL_ID_LIMIT = 50;
69
- /**
70
- * The `compact100` cost experiment reserves 100k tokens, so pi compacts when
71
- * the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
72
- * 117_647 is the smallest window that keeps that trigger at 100k.
73
- */
74
- export const COMPACT100_TRIGGER_TOKENS = 100_000;
75
- export const COMPACT100_CONTEXT_WINDOW = 117_647;
76
95
  export const SESSION_TRACK_LIMIT = 200;
77
96
  export const AUTH_SKEW_MS = 60_000;
78
97
  export const AUTH_TIMEOUT_MS = 15 * 60_000;
@@ -86,10 +105,8 @@ export const AD_TURN_LIMIT = 200;
86
105
  export const AD_IMPRESSION_LIMIT = 200;
87
106
  export const CREDITS_PER_USD = 40_000 / 3;
88
107
  export const CATALOG_TTL_MS = 10 * 60_000;
89
- export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
90
108
  export const CATALOG_TIMEOUT_MS = 8_000;
91
109
  export const REGISTRY_TTL_MS = 5 * 60_000;
92
- export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
93
110
  export const REGISTRY_RETRY_MS = 60_000;
94
111
  export const REGISTRY_TIMEOUT_MS = 3_500;
95
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, 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";
@@ -27,6 +27,17 @@ function rememberPending(deps, key, turn) {
27
27
  trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
28
28
  deps.state.pendingAdTurns.set(key, turn);
29
29
  }
30
+ /** Adds a system block once, even when OpenCode reuses the same event. */
31
+ function appendSystemGuidance(event, text, marker) {
32
+ const system = Array.isArray(event.system) ? event.system : [];
33
+ if (system.some((part) => part?.type === "text" &&
34
+ typeof part.text === "string" &&
35
+ part.text.startsWith(marker))) {
36
+ return;
37
+ }
38
+ system.push({ type: "text", text });
39
+ event.system = system;
40
+ }
30
41
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
31
42
  async function applyGeneration(deps, event, kind) {
32
43
  if (!isFreePiProvider(event.model?.providerID))
@@ -48,16 +59,15 @@ async function applyGeneration(deps, event, kind) {
48
59
  event.options.maxTokens = cap;
49
60
  }
50
61
  if (kind === "compaction") {
62
+ appendSystemGuidance(event, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER);
51
63
  // OpenCode sends the messages it is folding into the summary, which is the
52
64
  // same set pi reports through `session_before_compact`.
53
65
  recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
54
66
  }
55
- if (deps.state.costExperimentArm === "efficiency") {
56
- const system = Array.isArray(event.system) ? event.system : [];
57
- if (!system.some((part) => part?.type === "text" && part.text === EFFICIENCY_RULE)) {
58
- system.push({ type: "text", text: EFFICIENCY_RULE });
59
- event.system = system;
60
- }
67
+ else if (kind === "primary") {
68
+ // The free models tend to skip planning and claim work they did not do;
69
+ // the CLI gets a much larger agent prompt. This is the compact equivalent.
70
+ appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
61
71
  }
62
72
  const agent = event.agent;
63
73
  const turn = await resolveAdTurn(deps, {
@@ -104,9 +114,6 @@ async function applyModelRequest(deps, event) {
104
114
  if (deps.state.subagentSessions.has(event.sessionID)) {
105
115
  event.headers[SUBAGENT_HEADER] = "1";
106
116
  }
107
- if (deps.state.costExperimentArm) {
108
- event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
109
- }
110
117
  // Title requests are suppressed by the title hook, so an ad for them would be
111
118
  // an impression the user never sees.
112
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) => {