@eduardo191labs/opencode-free-pi 0.7.13 → 0.7.15

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.
@@ -205,7 +205,15 @@ export function accountAccess(me) {
205
205
  function isPremiumModel(model) {
206
206
  if (model.tier === "premium")
207
207
  return true;
208
- return /premium\s+credits/i.test(model.note ?? "");
208
+ if (/premium\s+credits/i.test(model.note ?? ""))
209
+ return true;
210
+ // The catalog labels every model the free lane cannot take with "at capacity
211
+ // for free users" (the name) even when `note` is empty. A curl_cffi probe of
212
+ // all 27 models showed that exactly those, plus the defense section, answer
213
+ // 403 `model_requires_credits`; the numbered `usage_x` alone does not predict
214
+ // it (Hy4 Flash, GPT-OSS 20B). Treat the label as premium-only so the picker
215
+ // does not offer a model that fails on the first turn.
216
+ return /at capacity for free users/i.test(model.name ?? "");
209
217
  }
210
218
  export function filterAccessibleModels(models, access) {
211
219
  // Without a quota snapshot, show everything instead of guessing and hiding
package/dist/plugin.js CHANGED
@@ -169,16 +169,29 @@ async function setup(ctx) {
169
169
  ? { reasoningEffort: configuredEffort }
170
170
  : {}),
171
171
  };
172
+ // A model the gateway refused with `model_requires_credits` stays hidden until
173
+ // the credential or the catalog changes, so the picker only offers choices
174
+ // that work for this account.
175
+ const withoutDenied = (providerID, models) => {
176
+ if (state.deniedModels.size === 0)
177
+ return models;
178
+ const kept = {};
179
+ for (const [id, model] of Object.entries(models)) {
180
+ if (!state.deniedModels.has(`${providerID}/${id}`))
181
+ kept[id] = model;
182
+ }
183
+ return kept;
184
+ };
172
185
  // Rebuilt on every call so a learned context ceiling or a recovered catalog
173
186
  // applies without restarting OpenCode.
174
- const buildMain = () => buildModels(currentMain, candidates, {
187
+ const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, {
175
188
  ...buildOptions,
176
189
  live: currentLiveLimits() ?? live,
177
- });
178
- const buildDefense = () => buildModels(currentDefense, candidates, {
190
+ }));
191
+ const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, {
179
192
  ...buildOptions,
180
193
  live: currentLiveLimits() ?? live,
181
- });
194
+ }));
182
195
  function indexModelState() {
183
196
  const mainNow = buildMain();
184
197
  const defenseNow = buildDefense();
@@ -203,6 +216,10 @@ async function setup(ctx) {
203
216
  tokenFromCredential(credential) ?? (await readCredentialsToken());
204
217
  await registerIntegration(ctx, deps);
205
218
  await ctx.provider.transform((editor) => {
219
+ // Re-index on every transform: a learned context/output ceiling changes the
220
+ // built model, and the diet and maxTokens cap read these maps. Refreshing
221
+ // only at setup would keep budgeting against the old window after a reload.
222
+ indexModelState();
206
223
  applyProvider(editor, PROVIDER_ID, "Free Pi", buildMain(), state.providerToken);
207
224
  if (includeDefense && currentDefense.length > 0) {
208
225
  applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", buildDefense(), state.providerToken);
@@ -3,8 +3,11 @@ 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 { parseFreePiError } from "../errors/parse.js";
6
7
  import { noteStepTokens } from "../catalog/live.js";
8
+ import { SESSION_TRACK_LIMIT } from "../constants.js";
7
9
  import { forgetToolStats, isFreePiSession } from "./tools.js";
10
+ import { trimSet } from "../utils/async.js";
8
11
  import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
9
12
  import { markWireSessionDirty, } from "./wire.js";
10
13
  import { recordUsage } from "./usage.js";
@@ -28,6 +31,24 @@ const EVENT_TYPES = [
28
31
  "session.deleted",
29
32
  "location.shutdown",
30
33
  ];
34
+ /**
35
+ * Hides a model the gateway rejected with `model_requires_credits`. The error
36
+ * body does not name the model, but the session's last request does; removing
37
+ * it and reloading the provider keeps the picker from offering a choice that
38
+ * always fails on this account.
39
+ */
40
+ async function hideRejectedModel(ctx, deps, sessionID, error) {
41
+ const parsed = parseFreePiError(error, true);
42
+ if (parsed?.code !== "model_requires_credits")
43
+ return;
44
+ const key = deps.state.lastModelBySession.get(sessionID);
45
+ if (!key || deps.state.deniedModels.has(key))
46
+ return;
47
+ deps.state.deniedModels.add(key);
48
+ deps.log.warn("free-pi hid a model this account cannot use", { model: key });
49
+ await ctx.provider.reload().catch(() => undefined);
50
+ await ctx.model.reload().catch(() => undefined);
51
+ }
31
52
  async function handleEvent(ctx, deps, event) {
32
53
  switch (event.type) {
33
54
  case "credential.updated":
@@ -37,6 +58,8 @@ async function handleEvent(ctx, deps, event) {
37
58
  if (next === deps.state.providerToken)
38
59
  return;
39
60
  deps.state.providerToken = next;
61
+ // A different sign-in can have premium credits, so re-test every model.
62
+ deps.state.deniedModels.clear();
40
63
  await ctx.provider.reload().catch(() => undefined);
41
64
  return;
42
65
  }
@@ -48,6 +71,9 @@ async function handleEvent(ctx, deps, event) {
48
71
  return;
49
72
  if (typeof event.data?.parentID === "string") {
50
73
  deps.state.subagentSessions.add(sessionID);
74
+ // Bound the set: a child whose deletion event is missed (crash, restart)
75
+ // would otherwise grow it forever and keep marking requests as children.
76
+ trimSet(deps.state.subagentSessions, SESSION_TRACK_LIMIT);
51
77
  }
52
78
  return;
53
79
  }
@@ -67,6 +93,7 @@ async function handleEvent(ctx, deps, event) {
67
93
  if (isAbortLike(event.data?.error)) {
68
94
  markWireSessionDirty(deps, sessionID);
69
95
  }
96
+ await hideRejectedModel(ctx, deps, sessionID, event.data?.error);
70
97
  await handleFreePiError(deps, event.data?.error, {
71
98
  allowRaw: true,
72
99
  }).catch(() => undefined);
@@ -112,6 +139,7 @@ async function handleEvent(ctx, deps, event) {
112
139
  forgetFreePiSession(deps, sessionID);
113
140
  forgetToolStats(deps, sessionID);
114
141
  deps.state.subagentSessions.delete(sessionID);
142
+ deps.state.lastModelBySession.delete(sessionID);
115
143
  return;
116
144
  }
117
145
  case "location.shutdown": {
@@ -115,8 +115,13 @@ function applyRecentWindow(deps, event, window) {
115
115
  part.text.startsWith(RECENT_WINDOW_MARKER))
116
116
  : false);
117
117
  if (!already) {
118
- messages.push({ role: "user", content: [{ type: "text", text: guidance }] });
119
- event.messages = messages;
118
+ // A fresh array: OpenCode reuses the event across hooks, and appending to
119
+ // the shared array would carry this block into the stored conversation and
120
+ // the next, unrelated request.
121
+ event.messages = [
122
+ ...messages,
123
+ { role: "user", content: [{ type: "text", text: guidance }] },
124
+ ];
120
125
  }
121
126
  // Keep the same text for the next request: if the summary compressed the
122
127
  // newest turns anyway, the agent still sees what it was doing.
@@ -275,6 +280,11 @@ async function applyGeneration(deps, event, kind) {
275
280
  }
276
281
  stripAssistantReasoning(deps, event);
277
282
  const modelID = event.model?.id;
283
+ // Remember the choice so a `model_requires_credits` failure can hide exactly
284
+ // the model that was rejected instead of the whole provider.
285
+ if (typeof event.sessionID === "string" && typeof modelID === "string") {
286
+ deps.state.lastModelBySession.set(event.sessionID, `${event.model.providerID}/${modelID}`);
287
+ }
278
288
  const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
279
289
  // The compaction summary is the one response that must never be cut: a
280
290
  // summary that reaches the output limit fails the whole compaction and the
@@ -388,9 +398,11 @@ async function applyModelRequest(deps, event) {
388
398
  event.kind === "compaction"
389
399
  ? AD_CONTEXT_OPT_OUT
390
400
  : (turn.context ?? AD_CONTEXT_OPT_OUT);
391
- if (token) {
401
+ if (token && event.kind !== "compaction") {
392
402
  // V1 awaited the first ad fetch for the turn so the impression lands
393
403
  // before the model request. Later steps reuse the settled promise.
404
+ // Compaction opts out of the ad context, so it must not fetch or record a
405
+ // new impression for a request the user never sees.
394
406
  await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
395
407
  }
396
408
  }
@@ -101,10 +101,18 @@ export function forgetFreePiSession(deps, sessionID) {
101
101
  if (!sessionID)
102
102
  return;
103
103
  cancelFinalizeTimer(deps, sessionID);
104
+ // A session evicted from the bounded tracking set never reached
105
+ // `finalizeFreePiSession`, so its server slot would stay open until the
106
+ // gateway times it out. Release it here unless the finalize already did.
107
+ const released = deps.state.finalizedSessions.has(sessionID);
108
+ const wireID = wireSessionID(deps, sessionID);
104
109
  deps.state.freePiSessions.delete(sessionID);
105
110
  deps.state.finalizedSessions.delete(sessionID);
106
111
  deps.state.activeExecutions.delete(sessionID);
107
112
  deps.state.sessionActivity.delete(sessionID);
108
113
  deps.state.trackedModels.delete(sessionID);
109
114
  forgetWireSessionID(deps, sessionID);
115
+ if (!released) {
116
+ void closeFreePiSession(deps, wireID).catch(() => undefined);
117
+ }
110
118
  }
package/dist/state.d.ts CHANGED
@@ -53,6 +53,10 @@ export type RuntimeState = {
53
53
  pendingAdTurns: Map<string, AdTurn>;
54
54
  adImpressions: Map<string, Promise<void>>;
55
55
  trackedModels: Map<string, TrackedModel>;
56
+ /** Last `provider/model` each session asked for, used to hide rejected models. */
57
+ lastModelBySession: Map<string, string>;
58
+ /** `provider/model` ids the gateway rejected as premium-only for this account. */
59
+ deniedModels: Set<string>;
56
60
  toolStats: Map<string, ToolStats>;
57
61
  subagentSessions: Set<string>;
58
62
  /** Newest turns quoted at the last compaction, carried once into the next request. */
package/dist/state.js CHANGED
@@ -29,6 +29,8 @@ export function createRuntimeState() {
29
29
  pendingAdTurns: new Map(),
30
30
  adImpressions: new Map(),
31
31
  trackedModels: new Map(),
32
+ lastModelBySession: new Map(),
33
+ deniedModels: new Set(),
32
34
  toolStats: new Map(),
33
35
  subagentSessions: new Set(),
34
36
  recentWindows: new Map(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.13",
3
+ "version": "0.7.15",
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",
@@ -301,7 +301,14 @@ export function accountAccess(me: MeResponse | undefined): AccountAccess | undef
301
301
 
302
302
  function isPremiumModel(model: CatalogModel): boolean {
303
303
  if (model.tier === "premium") return true;
304
- return /premium\s+credits/i.test(model.note ?? "");
304
+ if (/premium\s+credits/i.test(model.note ?? "")) return true;
305
+ // The catalog labels every model the free lane cannot take with "at capacity
306
+ // for free users" (the name) even when `note` is empty. A curl_cffi probe of
307
+ // all 27 models showed that exactly those, plus the defense section, answer
308
+ // 403 `model_requires_credits`; the numbered `usage_x` alone does not predict
309
+ // it (Hy4 Flash, GPT-OSS 20B). Treat the label as premium-only so the picker
310
+ // does not offer a model that fails on the first turn.
311
+ return /at capacity for free users/i.test(model.name ?? "");
305
312
  }
306
313
 
307
314
  export function filterAccessibleModels(
package/src/plugin.ts CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  PROVIDER_ID,
41
41
  } from "./constants.js";
42
42
  import type { Deps } from "./deps.js";
43
+ import type { ModelMap } from "./types.js";
43
44
  import { registerIntegration } from "./integration/setup.js";
44
45
  import { createLogger } from "./logging.js";
45
46
  import { applyEnvironmentProxy } from "./network/proxy.js";
@@ -207,18 +208,36 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
207
208
  : {}),
208
209
  };
209
210
 
211
+ // A model the gateway refused with `model_requires_credits` stays hidden until
212
+ // the credential or the catalog changes, so the picker only offers choices
213
+ // that work for this account.
214
+ const withoutDenied = (providerID: string, models: ModelMap): ModelMap => {
215
+ if (state.deniedModels.size === 0) return models;
216
+ const kept: ModelMap = {};
217
+ for (const [id, model] of Object.entries(models)) {
218
+ if (!state.deniedModels.has(`${providerID}/${id}`)) kept[id] = model;
219
+ }
220
+ return kept;
221
+ };
222
+
210
223
  // Rebuilt on every call so a learned context ceiling or a recovered catalog
211
224
  // applies without restarting OpenCode.
212
225
  const buildMain = () =>
213
- buildModels(currentMain, candidates, {
214
- ...buildOptions,
215
- live: currentLiveLimits() ?? live,
216
- });
226
+ withoutDenied(
227
+ PROVIDER_ID,
228
+ buildModels(currentMain, candidates, {
229
+ ...buildOptions,
230
+ live: currentLiveLimits() ?? live,
231
+ }),
232
+ );
217
233
  const buildDefense = () =>
218
- buildModels(currentDefense, candidates, {
219
- ...buildOptions,
220
- live: currentLiveLimits() ?? live,
221
- });
234
+ withoutDenied(
235
+ DEFENSE_PROVIDER_ID,
236
+ buildModels(currentDefense, candidates, {
237
+ ...buildOptions,
238
+ live: currentLiveLimits() ?? live,
239
+ }),
240
+ );
222
241
 
223
242
  function indexModelState(): void {
224
243
  const mainNow = buildMain();
@@ -247,6 +266,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
247
266
  await registerIntegration(ctx, deps);
248
267
 
249
268
  await ctx.provider.transform((editor) => {
269
+ // Re-index on every transform: a learned context/output ceiling changes the
270
+ // built model, and the diet and maxTokens cap read these maps. Refreshing
271
+ // only at setup would keep budgeting against the old window after a reload.
272
+ indexModelState();
250
273
  applyProvider(
251
274
  editor,
252
275
  PROVIDER_ID,
@@ -6,8 +6,11 @@ import { readCredentialsToken } from "../auth/credentials.js";
6
6
  import { tokenFromCredential } from "../auth/credential.js";
7
7
  import type { Deps } from "../deps.js";
8
8
  import { handleFreePiError } from "../errors/handle.js";
9
+ import { parseFreePiError } from "../errors/parse.js";
9
10
  import { noteStepTokens } from "../catalog/live.js";
11
+ import { SESSION_TRACK_LIMIT } from "../constants.js";
10
12
  import { forgetToolStats, isFreePiSession } from "./tools.js";
13
+ import { trimSet } from "../utils/async.js";
11
14
  import {
12
15
  beginExecution,
13
16
  cancelAllFinalizeTimers,
@@ -42,6 +45,28 @@ const EVENT_TYPES = [
42
45
  "location.shutdown",
43
46
  ] as const;
44
47
 
48
+ /**
49
+ * Hides a model the gateway rejected with `model_requires_credits`. The error
50
+ * body does not name the model, but the session's last request does; removing
51
+ * it and reloading the provider keeps the picker from offering a choice that
52
+ * always fails on this account.
53
+ */
54
+ async function hideRejectedModel(
55
+ ctx: Plugin.Context,
56
+ deps: Deps,
57
+ sessionID: string,
58
+ error: any,
59
+ ): Promise<void> {
60
+ const parsed = parseFreePiError(error, true);
61
+ if (parsed?.code !== "model_requires_credits") return;
62
+ const key = deps.state.lastModelBySession.get(sessionID);
63
+ if (!key || deps.state.deniedModels.has(key)) return;
64
+ deps.state.deniedModels.add(key);
65
+ deps.log.warn("free-pi hid a model this account cannot use", { model: key });
66
+ await ctx.provider.reload().catch(() => undefined);
67
+ await ctx.model.reload().catch(() => undefined);
68
+ }
69
+
45
70
  async function handleEvent(
46
71
  ctx: Plugin.Context,
47
72
  deps: Deps,
@@ -55,6 +80,8 @@ async function handleEvent(
55
80
  tokenFromCredential(credential) ?? (await readCredentialsToken());
56
81
  if (next === deps.state.providerToken) return;
57
82
  deps.state.providerToken = next;
83
+ // A different sign-in can have premium credits, so re-test every model.
84
+ deps.state.deniedModels.clear();
58
85
  await ctx.provider.reload().catch(() => undefined);
59
86
  return;
60
87
  }
@@ -65,6 +92,9 @@ async function handleEvent(
65
92
  if (typeof sessionID !== "string") return;
66
93
  if (typeof event.data?.parentID === "string") {
67
94
  deps.state.subagentSessions.add(sessionID);
95
+ // Bound the set: a child whose deletion event is missed (crash, restart)
96
+ // would otherwise grow it forever and keep marking requests as children.
97
+ trimSet(deps.state.subagentSessions, SESSION_TRACK_LIMIT);
68
98
  }
69
99
  return;
70
100
  }
@@ -84,6 +114,7 @@ async function handleEvent(
84
114
  if (isAbortLike(event.data?.error)) {
85
115
  markWireSessionDirty(deps, sessionID);
86
116
  }
117
+ await hideRejectedModel(ctx, deps, sessionID, event.data?.error);
87
118
  await handleFreePiError(deps, event.data?.error, {
88
119
  allowRaw: true,
89
120
  }).catch(() => undefined);
@@ -132,6 +163,7 @@ async function handleEvent(
132
163
  forgetFreePiSession(deps, sessionID);
133
164
  forgetToolStats(deps, sessionID);
134
165
  deps.state.subagentSessions.delete(sessionID);
166
+ deps.state.lastModelBySession.delete(sessionID);
135
167
  return;
136
168
  }
137
169
  case "location.shutdown": {
@@ -233,8 +233,13 @@ function applyRecentWindow(
233
233
  : false,
234
234
  );
235
235
  if (!already) {
236
- messages.push({ role: "user", content: [{ type: "text", text: guidance }] });
237
- event.messages = messages;
236
+ // A fresh array: OpenCode reuses the event across hooks, and appending to
237
+ // the shared array would carry this block into the stored conversation and
238
+ // the next, unrelated request.
239
+ event.messages = [
240
+ ...messages,
241
+ { role: "user", content: [{ type: "text", text: guidance }] },
242
+ ];
238
243
  }
239
244
  // Keep the same text for the next request: if the summary compressed the
240
245
  // newest turns anyway, the agent still sees what it was doing.
@@ -410,6 +415,14 @@ async function applyGeneration(
410
415
  stripAssistantReasoning(deps, event);
411
416
 
412
417
  const modelID = event.model?.id;
418
+ // Remember the choice so a `model_requires_credits` failure can hide exactly
419
+ // the model that was rejected instead of the whole provider.
420
+ if (typeof event.sessionID === "string" && typeof modelID === "string") {
421
+ deps.state.lastModelBySession.set(
422
+ event.sessionID,
423
+ `${event.model.providerID}/${modelID}`,
424
+ );
425
+ }
413
426
  const limit = deps.state.outputLimits.get(
414
427
  `${event.model.providerID}/${modelID}`,
415
428
  );
@@ -541,9 +554,11 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
541
554
  event.kind === "compaction"
542
555
  ? AD_CONTEXT_OPT_OUT
543
556
  : (turn.context ?? AD_CONTEXT_OPT_OUT);
544
- if (token) {
557
+ if (token && event.kind !== "compaction") {
545
558
  // V1 awaited the first ad fetch for the turn so the impression lands
546
559
  // before the model request. Later steps reuse the settled promise.
560
+ // Compaction opts out of the ad context, so it must not fetch or record a
561
+ // new impression for a request the user never sees.
547
562
  await ensureAdImpression(deps, token, event.sessionID, turn).catch(
548
563
  () => undefined,
549
564
  );
@@ -120,10 +120,18 @@ export async function finalizeFreePiSession(
120
120
  export function forgetFreePiSession(deps: Deps, sessionID: string): void {
121
121
  if (!sessionID) return;
122
122
  cancelFinalizeTimer(deps, sessionID);
123
+ // A session evicted from the bounded tracking set never reached
124
+ // `finalizeFreePiSession`, so its server slot would stay open until the
125
+ // gateway times it out. Release it here unless the finalize already did.
126
+ const released = deps.state.finalizedSessions.has(sessionID);
127
+ const wireID = wireSessionID(deps, sessionID);
123
128
  deps.state.freePiSessions.delete(sessionID);
124
129
  deps.state.finalizedSessions.delete(sessionID);
125
130
  deps.state.activeExecutions.delete(sessionID);
126
131
  deps.state.sessionActivity.delete(sessionID);
127
132
  deps.state.trackedModels.delete(sessionID);
128
133
  forgetWireSessionID(deps, sessionID);
134
+ if (!released) {
135
+ void closeFreePiSession(deps, wireID).catch(() => undefined);
136
+ }
129
137
  }
package/src/state.ts CHANGED
@@ -66,6 +66,10 @@ export type RuntimeState = {
66
66
  pendingAdTurns: Map<string, AdTurn>;
67
67
  adImpressions: Map<string, Promise<void>>;
68
68
  trackedModels: Map<string, TrackedModel>;
69
+ /** Last `provider/model` each session asked for, used to hide rejected models. */
70
+ lastModelBySession: Map<string, string>;
71
+ /** `provider/model` ids the gateway rejected as premium-only for this account. */
72
+ deniedModels: Set<string>;
69
73
  toolStats: Map<string, ToolStats>;
70
74
  subagentSessions: Set<string>;
71
75
  /** Newest turns quoted at the last compaction, carried once into the next request. */
@@ -101,6 +105,8 @@ export function createRuntimeState(): RuntimeState {
101
105
  pendingAdTurns: new Map(),
102
106
  adImpressions: new Map(),
103
107
  trackedModels: new Map(),
108
+ lastModelBySession: new Map(),
109
+ deniedModels: new Set(),
104
110
  toolStats: new Map(),
105
111
  subagentSessions: new Set(),
106
112
  recentWindows: new Map(),