@eduardo191labs/opencode-free-pi 0.7.19 → 0.7.21

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.
@@ -124,8 +124,6 @@ export function latestUserText(messages) {
124
124
  if (roleOf(message) !== "user")
125
125
  continue;
126
126
  const text = messageText(message);
127
- // The plugin appends this after the ad turn is resolved; ignore it if the
128
- // event is reused so the next ad never describes the reminder itself.
129
127
  if (isRealUserTurn(text))
130
128
  return text;
131
129
  }
@@ -138,9 +136,8 @@ function messageText(message) {
138
136
  * A user-role message that is not the user's own turn.
139
137
  *
140
138
  * OpenCode lowers a finished subagent into a `user` message that starts with
141
- * `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
142
- * also a `user` message. Treating either as a new turn rotated the ad in the
143
- * middle of one user request and sent its internal ids as the ad context.
139
+ * `<subagent sessionID=… state=…>`. Treating it as a new turn rotated the ad in
140
+ * the middle of one user request and sent its internal ids as the ad context.
144
141
  */
145
142
  function isRealUserTurn(text) {
146
143
  return (text.length > 0 &&
@@ -1,5 +1,5 @@
1
1
  /** Fetches the models.dev capability registry. */
2
- import { REGISTRY_ATTEMPTS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
2
+ import { REGISTRY_ATTEMPTS, REGISTRY_BODY_TIMEOUT_MS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
3
3
  import { sleep } from "../utils/async.js";
4
4
  import { modelsRegistryUrl } from "../utils/urls.js";
5
5
  function isRegistry(value) {
@@ -16,20 +16,36 @@ async function requestRegistry() {
16
16
  const url = base.endsWith(".json") ? base : `${base}/api.json`;
17
17
  let lastError;
18
18
  for (let attempt = 1; attempt <= REGISTRY_ATTEMPTS; attempt += 1) {
19
+ // The registry payload is ~7 MB. A single deadline covering the body made
20
+ // every request on a mobile connection time out at 3.5s even though the
21
+ // headers arrive quickly, so the deadline only guards the response head
22
+ // and the body gets its own, larger budget.
23
+ const controller = new AbortController();
24
+ const headerTimer = setTimeout(() => controller.abort(new Error("request timed out")), REGISTRY_TIMEOUT_MS);
19
25
  try {
20
26
  const response = await fetch(url, {
21
27
  headers: { accept: "application/json" },
22
- signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
28
+ signal: controller.signal,
23
29
  });
30
+ clearTimeout(headerTimer);
24
31
  if (!response.ok)
25
32
  throw new Error(`HTTP ${response.status}`);
26
- return (await response.json());
33
+ const bodyTimer = setTimeout(() => controller.abort(new Error("request timed out")), REGISTRY_BODY_TIMEOUT_MS);
34
+ try {
35
+ return (await response.json());
36
+ }
37
+ finally {
38
+ clearTimeout(bodyTimer);
39
+ }
27
40
  }
28
41
  catch (error) {
29
42
  lastError = error;
30
43
  if (attempt < REGISTRY_ATTEMPTS)
31
44
  await sleep(500 * attempt);
32
45
  }
46
+ finally {
47
+ clearTimeout(headerTimer);
48
+ }
33
49
  }
34
50
  throw lastError instanceof Error
35
51
  ? lastError
@@ -19,8 +19,8 @@ export declare const MAX_OUTPUT_TOKENS = 32768;
19
19
  /**
20
20
  * Share of the advertised window a primary request may occupy before stale
21
21
  * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation and stop
23
- * following the working rules, even though the gateway still accepts them.
22
+ * and the free models then lose the middle of the conversation even though the
23
+ * gateway still accepts them.
24
24
  */
25
25
  export declare const CONTEXT_DIET_SHARE = 0.4;
26
26
  /** Below this window the diet is pointless: the request is small anyway. */
@@ -119,6 +119,8 @@ export declare const CATALOG_RECOVERY_LOG_EVERY = 10;
119
119
  export declare const REGISTRY_TTL_MS: number;
120
120
  export declare const REGISTRY_RETRY_MS = 60000;
121
121
  export declare const REGISTRY_TIMEOUT_MS = 3500;
122
+ /** The registry body is ~7 MB; reading it needs far more than the header budget. */
123
+ export declare const REGISTRY_BODY_TIMEOUT_MS = 60000;
122
124
  export declare const REGISTRY_ATTEMPTS = 2;
123
125
  export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
124
126
  export declare const QUOTA_TTL_MS = 30000;
package/dist/constants.js CHANGED
@@ -19,8 +19,8 @@ export const MAX_OUTPUT_TOKENS = 32_768;
19
19
  /**
20
20
  * Share of the advertised window a primary request may occupy before stale
21
21
  * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
- * and the free models then lose the middle of the conversation and stop
23
- * following the working rules, even though the gateway still accepts them.
22
+ * and the free models then lose the middle of the conversation even though the
23
+ * gateway still accepts them.
24
24
  */
25
25
  export const CONTEXT_DIET_SHARE = 0.4;
26
26
  /** Below this window the diet is pointless: the request is small anyway. */
@@ -135,6 +135,8 @@ export const CATALOG_RECOVERY_LOG_EVERY = 10;
135
135
  export const REGISTRY_TTL_MS = 5 * 60_000;
136
136
  export const REGISTRY_RETRY_MS = 60_000;
137
137
  export const REGISTRY_TIMEOUT_MS = 3_500;
138
+ /** The registry body is ~7 MB; reading it needs far more than the header budget. */
139
+ export const REGISTRY_BODY_TIMEOUT_MS = 60_000;
138
140
  export const REGISTRY_ATTEMPTS = 2;
139
141
  export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
140
142
  export const QUOTA_TTL_MS = 30_000;
@@ -60,10 +60,10 @@ function fitCompactionMessages(deps, event, reserveTokens = 0) {
60
60
  /**
61
61
  * Collapses stale tool payloads before a request goes out. Long free-pi
62
62
  * sessions reach 100k-170k token prompts, and at that size the free models
63
- * lose the middle of the conversation and stop following the working rules
64
- * even though the gateway accepts the request. User wording, assistant text
65
- * and the newest messages are never touched; only old `read`/`grep`/`shell`
66
- * results are shortened, with a note that says they were pruned.
63
+ * lose the middle of the conversation even though the gateway accepts the
64
+ * request. User wording, assistant text and the newest messages are never
65
+ * touched; only old `read`/`grep`/`shell` results are shortened, with a note
66
+ * that says they were pruned.
67
67
  */
68
68
  function applyContextDiet(deps, event) {
69
69
  const providerID = event.model?.providerID;
@@ -190,9 +190,6 @@ async function applyGeneration(deps, event, kind) {
190
190
  // model receives (the whole compacted history goes out every time).
191
191
  markWireSessionDirty(deps, event.sessionID);
192
192
  }
193
- else if (kind === "primary") {
194
- applyContextDiet(deps, event);
195
- }
196
193
  else {
197
194
  applyContextDiet(deps, event);
198
195
  }
@@ -2,9 +2,9 @@
2
2
  * Diagnostic dump of what the plugin actually sends to free-pi.
3
3
  *
4
4
  * Enabled with `FREE_PI_TRACE=1`. It answers the questions the TUI and the
5
- * session database cannot: whether the tools travel complete, whether the
6
- * provider request keeps older reasoning, and whether the per-turn reminder is
7
- * the last message OpenCode sends. It never runs unless the env var is set.
5
+ * session database cannot: whether the tools travel complete and whether the
6
+ * provider request keeps older reasoning. It never runs unless the env var is
7
+ * set.
8
8
  */
9
9
  import type { Deps } from "../deps.js";
10
10
  export declare function traceRequestBody(deps: Deps, sessionID: string, body: string, headers?: Headers): void;
@@ -2,9 +2,9 @@
2
2
  * Diagnostic dump of what the plugin actually sends to free-pi.
3
3
  *
4
4
  * Enabled with `FREE_PI_TRACE=1`. It answers the questions the TUI and the
5
- * session database cannot: whether the tools travel complete, whether the
6
- * provider request keeps older reasoning, and whether the per-turn reminder is
7
- * the last message OpenCode sends. It never runs unless the env var is set.
5
+ * session database cannot: whether the tools travel complete and whether the
6
+ * provider request keeps older reasoning. It never runs unless the env var is
7
+ * set.
8
8
  */
9
9
  function textOf(content) {
10
10
  if (typeof content === "string")
@@ -88,8 +88,8 @@ export function traceRequestBody(deps, sessionID, body, headers) {
88
88
  }
89
89
  /**
90
90
  * Summarises the plugin's headers without leaking the token. The ad context is
91
- * base64url JSON, so it is decoded here: if the reminder ever replaced the real
92
- * user text, this trace is what proves it.
91
+ * base64url JSON, so it is decoded here to show the exact user text the ad was
92
+ * derived from.
93
93
  */
94
94
  function headerTrace(headers) {
95
95
  if (!headers)
@@ -17,7 +17,27 @@ export function rememberFreePiSession(deps, sessionID) {
17
17
  const sessions = deps.state.freePiSessions;
18
18
  sessions.delete(sessionID);
19
19
  sessions.add(sessionID);
20
- trimSet(sessions, SESSION_TRACK_LIMIT);
20
+ // Evicting from the bounded set must still release the server slot: free-pi
21
+ // allows four concurrent sessions per account, and a dropped session that
22
+ // never reaches `forgetFreePiSession` would hold its slot until the gateway
23
+ // times it out.
24
+ while (sessions.size > SESSION_TRACK_LIMIT) {
25
+ const oldest = sessions.values().next().value;
26
+ if (oldest === undefined || oldest === sessionID)
27
+ break;
28
+ sessions.delete(oldest);
29
+ cancelFinalizeTimer(deps, oldest);
30
+ const wireID = wireSessionID(deps, oldest);
31
+ const released = deps.state.finalizedSessions.has(oldest);
32
+ deps.state.finalizedSessions.delete(oldest);
33
+ deps.state.activeExecutions.delete(oldest);
34
+ deps.state.sessionActivity.delete(oldest);
35
+ deps.state.trackedModels.delete(oldest);
36
+ forgetWireSessionID(deps, oldest);
37
+ if (!released) {
38
+ void closeFreePiSession(deps, wireID).catch(() => undefined);
39
+ }
40
+ }
21
41
  touchSessionActivity(deps, sessionID);
22
42
  }
23
43
  /** Records free-pi activity so a pending close waits for the request to settle. */
@@ -14,6 +14,10 @@ const NO_ARGUMENTS = "free_pi_usage takes no arguments.";
14
14
  const SLOW_LANE_NOTICE = "You're out of free credits for today. You can keep working on our spare capacity while it lasts, or buy credits to keep going at full speed.";
15
15
  const number = (value) => value.toLocaleString("en-US");
16
16
  function formatRefillEt(date) {
17
+ // A malformed `refill_at` from the gateway would make Intl throw
18
+ // `RangeError: Invalid time value` and fail the whole usage tool.
19
+ if (Number.isNaN(date.getTime()))
20
+ return "the next reset";
17
21
  const formatted = new Intl.DateTimeFormat("en-US", {
18
22
  timeZone: "America/New_York",
19
23
  hour: "numeric",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.19",
3
+ "version": "0.7.21",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/catalog.mjs && node test/diet.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/catalog.mjs && node test/diet.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs && node test/slots.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -154,8 +154,6 @@ export function latestUserText(messages: readonly AdMessage[]): string {
154
154
  const message = messages[index];
155
155
  if (roleOf(message) !== "user") continue;
156
156
  const text = messageText(message);
157
- // The plugin appends this after the ad turn is resolved; ignore it if the
158
- // event is reused so the next ad never describes the reminder itself.
159
157
  if (isRealUserTurn(text)) return text;
160
158
  }
161
159
  return "";
@@ -171,9 +169,8 @@ function messageText(message: AdMessage): string {
171
169
  * A user-role message that is not the user's own turn.
172
170
  *
173
171
  * OpenCode lowers a finished subagent into a `user` message that starts with
174
- * `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
175
- * also a `user` message. Treating either as a new turn rotated the ad in the
176
- * middle of one user request and sent its internal ids as the ad context.
172
+ * `<subagent sessionID=… state=…>`. Treating it as a new turn rotated the ad in
173
+ * the middle of one user request and sent its internal ids as the ad context.
177
174
  */
178
175
  function isRealUserTurn(text: string): boolean {
179
176
  return (
@@ -2,6 +2,7 @@
2
2
 
3
3
  import {
4
4
  REGISTRY_ATTEMPTS,
5
+ REGISTRY_BODY_TIMEOUT_MS,
5
6
  REGISTRY_RETRY_MS,
6
7
  REGISTRY_TIMEOUT_MS,
7
8
  REGISTRY_TTL_MS,
@@ -27,16 +28,36 @@ async function requestRegistry(): Promise<ModelRegistry> {
27
28
  const url = base.endsWith(".json") ? base : `${base}/api.json`;
28
29
  let lastError: unknown;
29
30
  for (let attempt = 1; attempt <= REGISTRY_ATTEMPTS; attempt += 1) {
31
+ // The registry payload is ~7 MB. A single deadline covering the body made
32
+ // every request on a mobile connection time out at 3.5s even though the
33
+ // headers arrive quickly, so the deadline only guards the response head
34
+ // and the body gets its own, larger budget.
35
+ const controller = new AbortController();
36
+ const headerTimer = setTimeout(
37
+ () => controller.abort(new Error("request timed out")),
38
+ REGISTRY_TIMEOUT_MS,
39
+ );
30
40
  try {
31
41
  const response = await fetch(url, {
32
42
  headers: { accept: "application/json" },
33
- signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
43
+ signal: controller.signal,
34
44
  });
45
+ clearTimeout(headerTimer);
35
46
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
36
- return (await response.json()) as ModelRegistry;
47
+ const bodyTimer = setTimeout(
48
+ () => controller.abort(new Error("request timed out")),
49
+ REGISTRY_BODY_TIMEOUT_MS,
50
+ );
51
+ try {
52
+ return (await response.json()) as ModelRegistry;
53
+ } finally {
54
+ clearTimeout(bodyTimer);
55
+ }
37
56
  } catch (error) {
38
57
  lastError = error;
39
58
  if (attempt < REGISTRY_ATTEMPTS) await sleep(500 * attempt);
59
+ } finally {
60
+ clearTimeout(headerTimer);
40
61
  }
41
62
  }
42
63
  throw lastError instanceof Error
package/src/constants.ts CHANGED
@@ -23,8 +23,8 @@ export const MAX_OUTPUT_TOKENS = 32_768;
23
23
  /**
24
24
  * Share of the advertised window a primary request may occupy before stale
25
25
  * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
26
- * and the free models then lose the middle of the conversation and stop
27
- * following the working rules, even though the gateway still accepts them.
26
+ * and the free models then lose the middle of the conversation even though the
27
+ * gateway still accepts them.
28
28
  */
29
29
  export const CONTEXT_DIET_SHARE = 0.4;
30
30
  /** Below this window the diet is pointless: the request is small anyway. */
@@ -151,6 +151,8 @@ export const CATALOG_RECOVERY_LOG_EVERY = 10;
151
151
  export const REGISTRY_TTL_MS = 5 * 60_000;
152
152
  export const REGISTRY_RETRY_MS = 60_000;
153
153
  export const REGISTRY_TIMEOUT_MS = 3_500;
154
+ /** The registry body is ~7 MB; reading it needs far more than the header budget. */
155
+ export const REGISTRY_BODY_TIMEOUT_MS = 60_000;
154
156
  export const REGISTRY_ATTEMPTS = 2;
155
157
  export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
156
158
 
@@ -142,10 +142,10 @@ function fitCompactionMessages(
142
142
  /**
143
143
  * Collapses stale tool payloads before a request goes out. Long free-pi
144
144
  * sessions reach 100k-170k token prompts, and at that size the free models
145
- * lose the middle of the conversation and stop following the working rules
146
- * even though the gateway accepts the request. User wording, assistant text
147
- * and the newest messages are never touched; only old `read`/`grep`/`shell`
148
- * results are shortened, with a note that says they were pruned.
145
+ * lose the middle of the conversation even though the gateway accepts the
146
+ * request. User wording, assistant text and the newest messages are never
147
+ * touched; only old `read`/`grep`/`shell` results are shortened, with a note
148
+ * that says they were pruned.
149
149
  */
150
150
  function applyContextDiet(deps: Deps, event: any): void {
151
151
  const providerID = event.model?.providerID;
@@ -285,8 +285,6 @@ async function applyGeneration(
285
285
  // id for the next request avoids that round trip without changing what the
286
286
  // model receives (the whole compacted history goes out every time).
287
287
  markWireSessionDirty(deps, event.sessionID);
288
- } else if (kind === "primary") {
289
- applyContextDiet(deps, event);
290
288
  } else {
291
289
  applyContextDiet(deps, event);
292
290
  }
@@ -2,9 +2,9 @@
2
2
  * Diagnostic dump of what the plugin actually sends to free-pi.
3
3
  *
4
4
  * Enabled with `FREE_PI_TRACE=1`. It answers the questions the TUI and the
5
- * session database cannot: whether the tools travel complete, whether the
6
- * provider request keeps older reasoning, and whether the per-turn reminder is
7
- * the last message OpenCode sends. It never runs unless the env var is set.
5
+ * session database cannot: whether the tools travel complete and whether the
6
+ * provider request keeps older reasoning. It never runs unless the env var is
7
+ * set.
8
8
  */
9
9
 
10
10
  import type { Deps } from "../deps.js";
@@ -107,8 +107,8 @@ export function traceRequestBody(
107
107
 
108
108
  /**
109
109
  * Summarises the plugin's headers without leaking the token. The ad context is
110
- * base64url JSON, so it is decoded here: if the reminder ever replaced the real
111
- * user text, this trace is what proves it.
110
+ * base64url JSON, so it is decoded here to show the exact user text the ad was
111
+ * derived from.
112
112
  */
113
113
  function headerTrace(headers: Headers | undefined): Record<string, unknown> {
114
114
  if (!headers) return {};
@@ -22,7 +22,26 @@ export function rememberFreePiSession(deps: Deps, sessionID: string): void {
22
22
  const sessions = deps.state.freePiSessions;
23
23
  sessions.delete(sessionID);
24
24
  sessions.add(sessionID);
25
- trimSet(sessions, SESSION_TRACK_LIMIT);
25
+ // Evicting from the bounded set must still release the server slot: free-pi
26
+ // allows four concurrent sessions per account, and a dropped session that
27
+ // never reaches `forgetFreePiSession` would hold its slot until the gateway
28
+ // times it out.
29
+ while (sessions.size > SESSION_TRACK_LIMIT) {
30
+ const oldest = sessions.values().next().value;
31
+ if (oldest === undefined || oldest === sessionID) break;
32
+ sessions.delete(oldest);
33
+ cancelFinalizeTimer(deps, oldest);
34
+ const wireID = wireSessionID(deps, oldest);
35
+ const released = deps.state.finalizedSessions.has(oldest);
36
+ deps.state.finalizedSessions.delete(oldest);
37
+ deps.state.activeExecutions.delete(oldest);
38
+ deps.state.sessionActivity.delete(oldest);
39
+ deps.state.trackedModels.delete(oldest);
40
+ forgetWireSessionID(deps, oldest);
41
+ if (!released) {
42
+ void closeFreePiSession(deps, wireID).catch(() => undefined);
43
+ }
44
+ }
26
45
  touchSessionActivity(deps, sessionID);
27
46
  }
28
47
 
@@ -30,6 +30,9 @@ const SLOW_LANE_NOTICE =
30
30
  const number = (value: number) => value.toLocaleString("en-US");
31
31
 
32
32
  function formatRefillEt(date: Date): string {
33
+ // A malformed `refill_at` from the gateway would make Intl throw
34
+ // `RangeError: Invalid time value` and fail the whole usage tool.
35
+ if (Number.isNaN(date.getTime())) return "the next reset";
33
36
  const formatted = new Intl.DateTimeFormat("en-US", {
34
37
  timeZone: "America/New_York",
35
38
  hour: "numeric",