@eduardo191labs/opencode-free-pi 0.7.34 → 0.7.36

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.
@@ -1,7 +1,6 @@
1
1
  /** Account quota fetching shared by error handling and usage tracking. */
2
2
  import type { Deps } from "../deps.js";
3
- import type { QuotaSnapshot, TokenCheckState } from "../types.js";
4
- export declare function rememberTokenCheck(deps: Deps, token: string, state: TokenCheckState): void;
3
+ import type { QuotaSnapshot } from "../types.js";
5
4
  export declare function fetchQuota(deps: Deps, opts?: {
6
5
  force?: boolean;
7
6
  stats?: boolean;
package/dist/api/quota.js CHANGED
@@ -2,13 +2,8 @@
2
2
  import { resolveToken } from "../auth/token.js";
3
3
  import { QUOTA_HTTP_TIMEOUT_MS, QUOTA_TTL_MS } from "../constants.js";
4
4
  import { logInvalidToken } from "../errors/invalid.js";
5
- import { trimMap } from "../utils/async.js";
6
5
  import { readJson } from "../utils/json.js";
7
6
  import { resolveBaseUrl } from "../utils/urls.js";
8
- export function rememberTokenCheck(deps, token, state) {
9
- trimMap(deps.state.tokenChecks, 100);
10
- deps.state.tokenChecks.set(token, { at: Date.now(), state });
11
- }
12
7
  export async function fetchQuota(deps, opts = {}) {
13
8
  const current = deps.state.quotaCache;
14
9
  if (!opts.force &&
@@ -54,7 +49,6 @@ export async function fetchQuota(deps, opts = {}) {
54
49
  statsRequest,
55
50
  ]);
56
51
  if (meResponse?.status === 401 || statsResponse?.status === 401) {
57
- rememberTokenCheck(deps, token, "invalid");
58
52
  await logInvalidToken(deps, token);
59
53
  const invalid = {
60
54
  fetchedAt: Date.now(),
@@ -71,8 +65,6 @@ export async function fetchQuota(deps, opts = {}) {
71
65
  const stats = statsResponse?.ok
72
66
  ? (await readJson(statsResponse))
73
67
  : undefined;
74
- if (meResponse?.ok || statsResponse?.ok)
75
- rememberTokenCheck(deps, token, "ok");
76
68
  if (typeof me?.notice === "string" &&
77
69
  me.notice &&
78
70
  me.notice !== deps.state.lastQuotaNotice) {
@@ -1,5 +1,5 @@
1
1
  /** Central handling for free-pi failures reported by the provider or session. */
2
- import { fetchQuota, rememberTokenCheck } from "../api/quota.js";
2
+ import { fetchQuota } from "../api/quota.js";
3
3
  import { resetFreePiSessions } from "../api/session.js";
4
4
  import { logInvalidToken } from "./invalid.js";
5
5
  import { freePiErrorSeverity, freePiErrorTitle, friendlyFreePiError, } from "./messages.js";
@@ -12,8 +12,6 @@ export async function handleFreePiError(deps, error, opts = {}) {
12
12
  parsed.code === "unauthorized" ||
13
13
  parsed.code === "expired_token") {
14
14
  const token = deps.state.quotaCache?.token;
15
- if (token)
16
- rememberTokenCheck(deps, token, "invalid");
17
15
  await logInvalidToken(deps, token);
18
16
  void fetchQuota(deps, { force: true }).catch(() => undefined);
19
17
  return;
@@ -1,7 +1,7 @@
1
1
  /** Human-readable copy for free-pi error codes. */
2
2
  import { formatRefillTime, formatWait } from "../utils/numbers.js";
3
3
  const FREE_PI_ERROR_TEXT = {
4
- daily_cap: "Out of free credits today; they refill at UTC midnight, or add credits to keep going now.",
4
+ daily_cap: "Out of free credits today; they refill at the next reset, or add credits to keep going now.",
5
5
  queue_wait: "free-pi is near its daily budget; wait and retry.",
6
6
  rolling_cap: "Over the rolling spend cap on the free tier; wait for the retry window or add credits.",
7
7
  concurrent: "Only one request at a time on the free tier; wait for the current one to finish.",
@@ -11,7 +11,7 @@ const FREE_PI_ERROR_TEXT = {
11
11
  global_cap: "free-pi is over its shared daily budget; back tomorrow.",
12
12
  consent_required: "Consent required. Run `opencode auth login -p free-pi` to review the terms.",
13
13
  upgrade_required: "The free-pi client is out of date; update the plugin or free-pi-cli.",
14
- hourly_ceiling: "Daily allowance still applies; it refills at midnight UTC.",
14
+ hourly_ceiling: "Daily allowance still applies; it refills at the next reset.",
15
15
  account_review: "This account is under review; contact support.",
16
16
  ads_required: "Ads are not displaying for this account, so free completions are paused. Run `npx free-pi-cli@latest` so ads can show, then retry.",
17
17
  guest_allowance: "Guest trial used up; sign in with GitHub for a larger allowance.",
@@ -104,7 +104,7 @@ export function friendlyFreePiError(error) {
104
104
  return `This account hit its hourly limit; ${reset ? `it resets ${reset}` : "wait for it to reset"}. Switch models or retry later.`;
105
105
  }
106
106
  if (error.code === "daily_cap") {
107
- return `Out of free credits today; ${reset ? `it resets ${reset}` : "it refills at UTC midnight"}.`;
107
+ return `Out of free credits today; ${reset ? `it resets ${reset}` : "it refills at the next reset"}.`;
108
108
  }
109
109
  if (error.code === "rolling_cap") {
110
110
  return `Over the rolling spend cap; ${reset ? `retry ${reset}` : "wait for the retry window"}.`;
package/dist/plugin.js CHANGED
@@ -182,7 +182,9 @@ async function setup(ctx) {
182
182
  registrations.push(await tool.register());
183
183
  }
184
184
  catch (error) {
185
- log.warn(`Could not register the ${tool.name} tools`, error);
185
+ log.warn(`Could not register the ${tool.name} tools`, {
186
+ error: error instanceof Error ? error.message : String(error),
187
+ });
186
188
  }
187
189
  }
188
190
  const abort = new AbortController();
@@ -200,6 +202,8 @@ async function setup(ctx) {
200
202
  resolve();
201
203
  };
202
204
  const timer = setTimeout(finish, ms);
205
+ // The recovery wait must never be the reason the process stays alive.
206
+ timer.unref?.();
203
207
  abort.signal.addEventListener("abort", finish, { once: true });
204
208
  });
205
209
  const catalogRecovery = (async () => {
@@ -208,9 +208,9 @@ async function hookForProviders(ctx, name, callback, registrations) {
208
208
  }
209
209
  }
210
210
  /**
211
- * Handles every free-pi HTTP response: replays a busy session, rewrites
212
- * context overflows into something OpenCode compacts on, turns long-lived
213
- * limits into readable messages and watches for server notices.
211
+ * Handles every free-pi HTTP response: rewrites context overflows into
212
+ * something OpenCode compacts on, turns long-lived limits into readable
213
+ * messages and watches for server notices.
214
214
  *
215
215
  * Split from `registerSessionHooks` because the response path is the plugin's
216
216
  * most intricate logic and it was buried mid-function.
@@ -10,7 +10,8 @@
10
10
  * The mapping is also stored in plugin storage, which is how an OpenCode
11
11
  * session reopened after a restart reconnects to the same provider session
12
12
  * instead of starting a new one. If that old id turns out to be locked, the
13
- * existing replay path rotates it on the first `429 concurrent`.
13
+ * request fails with `429 concurrent` and OpenCode's retry finds the session
14
+ * marked dirty, which rotates the id before the next attempt.
14
15
  */
15
16
  import type { Deps } from "../deps.js";
16
17
  export declare function wireSessionID(deps: Deps, sessionID: string): string;
@@ -10,7 +10,8 @@
10
10
  * The mapping is also stored in plugin storage, which is how an OpenCode
11
11
  * session reopened after a restart reconnects to the same provider session
12
12
  * instead of starting a new one. If that old id turns out to be locked, the
13
- * existing replay path rotates it on the first `429 concurrent`.
13
+ * request fails with `429 concurrent` and OpenCode's retry finds the session
14
+ * marked dirty, which rotates the id before the next attempt.
14
15
  */
15
16
  import { trimSet } from "../utils/async.js";
16
17
  const DIRTY_LIMIT = 256;
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Per-plugin-instance mutable state. */
2
- import type { AdTurn, Catalog, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
2
+ import type { AdTurn, Catalog, ModelRegistry, QuotaSnapshot, SessionResetOutcome, ToolStats, TrackedModel } from "./types.js";
3
3
  export type RuntimeState = {
4
4
  latestClientVersion: string;
5
5
  providerToken?: string;
@@ -19,10 +19,6 @@ export type RuntimeState = {
19
19
  lastErrorLogKey?: string;
20
20
  lastErrorLogAt: number;
21
21
  lastInvalidToken?: string;
22
- tokenChecks: Map<string, {
23
- at: number;
24
- state: TokenCheckState;
25
- }>;
26
22
  lastExpiredToken?: string;
27
23
  sessionClosePromises: Map<string, Promise<void>>;
28
24
  sessionResetPromise?: Promise<SessionResetOutcome>;
package/dist/state.js CHANGED
@@ -8,7 +8,6 @@ export function createRuntimeState() {
8
8
  registryAttemptAt: 0,
9
9
  imageModels: new Set(),
10
10
  lastErrorLogAt: 0,
11
- tokenChecks: new Map(),
12
11
  sessionClosePromises: new Map(),
13
12
  lastSessionResetAt: 0,
14
13
  freePiSessions: new Set(),
package/dist/types.d.ts CHANGED
@@ -209,7 +209,6 @@ export type FreePiError = {
209
209
  remaining_credits_today?: number;
210
210
  allowance_credits?: number;
211
211
  };
212
- export type TokenCheckState = "ok" | "invalid" | "unknown";
213
212
  export type Credentials = {
214
213
  token: string;
215
214
  issuer?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.34",
3
+ "version": "0.7.36",
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",
package/src/api/quota.ts CHANGED
@@ -8,21 +8,10 @@ import type {
8
8
  MeResponse,
9
9
  MeStatsResponse,
10
10
  QuotaSnapshot,
11
- TokenCheckState,
12
11
  } from "../types.js";
13
- import { trimMap } from "../utils/async.js";
14
12
  import { readJson } from "../utils/json.js";
15
13
  import { resolveBaseUrl } from "../utils/urls.js";
16
14
 
17
- export function rememberTokenCheck(
18
- deps: Deps,
19
- token: string,
20
- state: TokenCheckState,
21
- ): void {
22
- trimMap(deps.state.tokenChecks, 100);
23
- deps.state.tokenChecks.set(token, { at: Date.now(), state });
24
- }
25
-
26
15
  export async function fetchQuota(
27
16
  deps: Deps,
28
17
  opts: { force?: boolean; stats?: boolean } = {},
@@ -73,7 +62,6 @@ export async function fetchQuota(
73
62
  statsRequest,
74
63
  ]);
75
64
  if (meResponse?.status === 401 || statsResponse?.status === 401) {
76
- rememberTokenCheck(deps, token, "invalid");
77
65
  await logInvalidToken(deps, token);
78
66
  const invalid: QuotaSnapshot = {
79
67
  fetchedAt: Date.now(),
@@ -91,8 +79,6 @@ export async function fetchQuota(
91
79
  const stats = statsResponse?.ok
92
80
  ? ((await readJson(statsResponse)) as MeStatsResponse | undefined)
93
81
  : undefined;
94
- if (meResponse?.ok || statsResponse?.ok)
95
- rememberTokenCheck(deps, token, "ok");
96
82
  if (
97
83
  typeof me?.notice === "string" &&
98
84
  me.notice &&
@@ -1,6 +1,6 @@
1
1
  /** Central handling for free-pi failures reported by the provider or session. */
2
2
 
3
- import { fetchQuota, rememberTokenCheck } from "../api/quota.js";
3
+ import { fetchQuota } from "../api/quota.js";
4
4
  import { resetFreePiSessions } from "../api/session.js";
5
5
  import type { Deps } from "../deps.js";
6
6
  import type { SessionResetOutcome } from "../types.js";
@@ -26,7 +26,6 @@ export async function handleFreePiError(
26
26
  parsed.code === "expired_token"
27
27
  ) {
28
28
  const token = deps.state.quotaCache?.token;
29
- if (token) rememberTokenCheck(deps, token, "invalid");
30
29
  await logInvalidToken(deps, token);
31
30
  void fetchQuota(deps, { force: true }).catch(() => undefined);
32
31
  return;
@@ -5,7 +5,7 @@ import { formatRefillTime, formatWait } from "../utils/numbers.js";
5
5
 
6
6
  const FREE_PI_ERROR_TEXT: Record<string, string> = {
7
7
  daily_cap:
8
- "Out of free credits today; they refill at UTC midnight, or add credits to keep going now.",
8
+ "Out of free credits today; they refill at the next reset, or add credits to keep going now.",
9
9
  queue_wait: "free-pi is near its daily budget; wait and retry.",
10
10
  rolling_cap:
11
11
  "Over the rolling spend cap on the free tier; wait for the retry window or add credits.",
@@ -21,7 +21,7 @@ const FREE_PI_ERROR_TEXT: Record<string, string> = {
21
21
  "Consent required. Run `opencode auth login -p free-pi` to review the terms.",
22
22
  upgrade_required:
23
23
  "The free-pi client is out of date; update the plugin or free-pi-cli.",
24
- hourly_ceiling: "Daily allowance still applies; it refills at midnight UTC.",
24
+ hourly_ceiling: "Daily allowance still applies; it refills at the next reset.",
25
25
  account_review: "This account is under review; contact support.",
26
26
  ads_required:
27
27
  "Ads are not displaying for this account, so free completions are paused. Run `npx free-pi-cli@latest` so ads can show, then retry.",
@@ -135,7 +135,7 @@ export function friendlyFreePiError(error: FreePiError): string {
135
135
  }
136
136
  if (error.code === "daily_cap") {
137
137
  return `Out of free credits today; ${
138
- reset ? `it resets ${reset}` : "it refills at UTC midnight"
138
+ reset ? `it resets ${reset}` : "it refills at the next reset"
139
139
  }.`;
140
140
  }
141
141
  if (error.code === "rolling_cap") {
package/src/plugin.ts CHANGED
@@ -226,7 +226,9 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
226
226
  try {
227
227
  registrations.push(await tool.register());
228
228
  } catch (error) {
229
- log.warn(`Could not register the ${tool.name} tools`, error);
229
+ log.warn(`Could not register the ${tool.name} tools`, {
230
+ error: error instanceof Error ? error.message : String(error),
231
+ });
230
232
  }
231
233
  }
232
234
  const abort = new AbortController();
@@ -245,6 +247,8 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
245
247
  resolve();
246
248
  };
247
249
  const timer = setTimeout(finish, ms);
250
+ // The recovery wait must never be the reason the process stays alive.
251
+ (timer as { unref?: () => void }).unref?.();
248
252
  abort.signal.addEventListener("abort", finish, { once: true });
249
253
  });
250
254
  const catalogRecovery = (async () => {
@@ -295,9 +295,9 @@ async function hookForProviders(
295
295
 
296
296
 
297
297
  /**
298
- * Handles every free-pi HTTP response: replays a busy session, rewrites
299
- * context overflows into something OpenCode compacts on, turns long-lived
300
- * limits into readable messages and watches for server notices.
298
+ * Handles every free-pi HTTP response: rewrites context overflows into
299
+ * something OpenCode compacts on, turns long-lived limits into readable
300
+ * messages and watches for server notices.
301
301
  *
302
302
  * Split from `registerSessionHooks` because the response path is the plugin's
303
303
  * most intricate logic and it was buried mid-function.
@@ -10,7 +10,8 @@
10
10
  * The mapping is also stored in plugin storage, which is how an OpenCode
11
11
  * session reopened after a restart reconnects to the same provider session
12
12
  * instead of starting a new one. If that old id turns out to be locked, the
13
- * existing replay path rotates it on the first `429 concurrent`.
13
+ * request fails with `429 concurrent` and OpenCode's retry finds the session
14
+ * marked dirty, which rotates the id before the next attempt.
14
15
  */
15
16
 
16
17
  import type { Deps } from "../deps.js";
package/src/state.ts CHANGED
@@ -7,7 +7,6 @@ import type {
7
7
  ModelRegistry,
8
8
  QuotaSnapshot,
9
9
  SessionResetOutcome,
10
- TokenCheckState,
11
10
  ToolStats,
12
11
  TrackedModel,
13
12
  } from "./types.js";
@@ -34,7 +33,6 @@ export type RuntimeState = {
34
33
  lastErrorLogKey?: string;
35
34
  lastErrorLogAt: number;
36
35
  lastInvalidToken?: string;
37
- tokenChecks: Map<string, { at: number; state: TokenCheckState }>;
38
36
  lastExpiredToken?: string;
39
37
 
40
38
  sessionClosePromises: Map<string, Promise<void>>;
@@ -72,7 +70,6 @@ export function createRuntimeState(): RuntimeState {
72
70
  registryAttemptAt: 0,
73
71
  imageModels: new Set(),
74
72
  lastErrorLogAt: 0,
75
- tokenChecks: new Map(),
76
73
  sessionClosePromises: new Map(),
77
74
  lastSessionResetAt: 0,
78
75
  freePiSessions: new Set(),
package/src/types.ts CHANGED
@@ -190,8 +190,6 @@ export type FreePiError = {
190
190
  allowance_credits?: number;
191
191
  };
192
192
 
193
- export type TokenCheckState = "ok" | "invalid" | "unknown";
194
-
195
193
  export type Credentials = {
196
194
  token: string;
197
195
  issuer?: string;