@eduardo191labs/opencode-free-pi 0.7.12 → 0.7.14

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.
package/README.md CHANGED
@@ -155,6 +155,12 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
155
155
  publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
156
156
  `top_p`: la petición real no los incluye, así que el gateway aplica su propio
157
157
  valor. El prompt se envía con rol `system`, no `developer`.
158
+ - **Sin razonamiento reenviado**: OpenCode guarda el pensamiento del modelo en
159
+ los mensajes del asistente y lo devuelve dentro de `reasoning_content`. La
160
+ captura con `curl_cffi` mostró que el gateway lo cobra como entrada (mismo
161
+ prompt y misma respuesta pasaron de 27 a 188 tokens en `glm-5.3-flash`), así
162
+ que el plugin lo quita antes de enviar. No cambia la respuesta: el modelo ya
163
+ razonó en su turno y el historial conserva el texto visible.
158
164
  - **Límites medidos, no inventados**: `/client-version` solo devuelve id,
159
165
  nombre, `free`, `section`, `note`, `stats_id` y `usage_x`; no hay endpoint de
160
166
  capacidades ni de ventana. El plugin no se queda en constantes: confirma la
@@ -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();
@@ -3,6 +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 { parseFreePiError } from "../errors/parse.js";
6
7
  import { noteStepTokens } from "../catalog/live.js";
7
8
  import { forgetToolStats, isFreePiSession } from "./tools.js";
8
9
  import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
@@ -28,6 +29,24 @@ const EVENT_TYPES = [
28
29
  "session.deleted",
29
30
  "location.shutdown",
30
31
  ];
32
+ /**
33
+ * Hides a model the gateway rejected with `model_requires_credits`. The error
34
+ * body does not name the model, but the session's last request does; removing
35
+ * it and reloading the provider keeps the picker from offering a choice that
36
+ * always fails on this account.
37
+ */
38
+ async function hideRejectedModel(ctx, deps, sessionID, error) {
39
+ const parsed = parseFreePiError(error, true);
40
+ if (parsed?.code !== "model_requires_credits")
41
+ return;
42
+ const key = deps.state.lastModelBySession.get(sessionID);
43
+ if (!key || deps.state.deniedModels.has(key))
44
+ return;
45
+ deps.state.deniedModels.add(key);
46
+ deps.log.warn("free-pi hid a model this account cannot use", { model: key });
47
+ await ctx.provider.reload().catch(() => undefined);
48
+ await ctx.model.reload().catch(() => undefined);
49
+ }
31
50
  async function handleEvent(ctx, deps, event) {
32
51
  switch (event.type) {
33
52
  case "credential.updated":
@@ -37,6 +56,8 @@ async function handleEvent(ctx, deps, event) {
37
56
  if (next === deps.state.providerToken)
38
57
  return;
39
58
  deps.state.providerToken = next;
59
+ // A different sign-in can have premium credits, so re-test every model.
60
+ deps.state.deniedModels.clear();
40
61
  await ctx.provider.reload().catch(() => undefined);
41
62
  return;
42
63
  }
@@ -67,6 +88,7 @@ async function handleEvent(ctx, deps, event) {
67
88
  if (isAbortLike(event.data?.error)) {
68
89
  markWireSessionDirty(deps, sessionID);
69
90
  }
91
+ await hideRejectedModel(ctx, deps, sessionID, event.data?.error);
70
92
  await handleFreePiError(deps, event.data?.error, {
71
93
  allowRaw: true,
72
94
  }).catch(() => undefined);
@@ -206,6 +206,61 @@ function applyContextDiet(deps, event) {
206
206
  tokensAfter: result.tokensAfter,
207
207
  });
208
208
  }
209
+ /**
210
+ * Drops the reasoning OpenCode stores and echoes back inside assistant
211
+ * messages.
212
+ *
213
+ * The provider request carries it as `reasoning_content`, but it is not input:
214
+ * the gateway billed it on some models (a measured glm-5.3-flash request went
215
+ * from 27 to 188 prompt tokens with the same answer) and the token estimate used
216
+ * for diet/compaction assumes it is not sent. Removing it keeps the request
217
+ * identical in behavior and smaller in credits.
218
+ */
219
+ function stripAssistantReasoning(deps, event) {
220
+ const messages = event.messages;
221
+ if (!Array.isArray(messages) || messages.length === 0)
222
+ return;
223
+ let chars = 0;
224
+ let changed = false;
225
+ const next = messages.map((message) => {
226
+ if (!message || message.role !== "assistant")
227
+ return message;
228
+ let copy;
229
+ const ensureCopy = () => {
230
+ if (!copy)
231
+ copy = { ...message };
232
+ return copy;
233
+ };
234
+ for (const key of ["reasoning_content", "reasoning"]) {
235
+ if (!(key in message))
236
+ continue;
237
+ const value = message[key];
238
+ if (typeof value === "string")
239
+ chars += value.length;
240
+ ensureCopy();
241
+ delete copy[key];
242
+ changed = true;
243
+ }
244
+ if (Array.isArray(message.content)) {
245
+ const kept = message.content.filter((part) => part?.type !== "reasoning" && part?.type !== "thinking");
246
+ if (kept.length !== message.content.length) {
247
+ ensureCopy();
248
+ copy.content = kept;
249
+ changed = true;
250
+ }
251
+ }
252
+ return copy ?? message;
253
+ });
254
+ if (!changed)
255
+ return;
256
+ event.messages = next;
257
+ if (chars > 0) {
258
+ deps.log.info("free-pi dropped stored reasoning from the request", {
259
+ sessionID: event.sessionID,
260
+ chars,
261
+ });
262
+ }
263
+ }
209
264
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
210
265
  async function applyGeneration(deps, event, kind) {
211
266
  if (!isFreePiProvider(event.model?.providerID))
@@ -218,7 +273,13 @@ async function applyGeneration(deps, event, kind) {
218
273
  event.result = localTitle(event.messages);
219
274
  return;
220
275
  }
276
+ stripAssistantReasoning(deps, event);
221
277
  const modelID = event.model?.id;
278
+ // Remember the choice so a `model_requires_credits` failure can hide exactly
279
+ // the model that was rejected instead of the whole provider.
280
+ if (typeof event.sessionID === "string" && typeof modelID === "string") {
281
+ deps.state.lastModelBySession.set(event.sessionID, `${event.model.providerID}/${modelID}`);
282
+ }
222
283
  const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
223
284
  // The compaction summary is the one response that must never be cut: a
224
285
  // summary that reaches the output limit fails the whole compaction and the
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.12",
3
+ "version": "0.7.14",
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();
@@ -6,6 +6,7 @@ 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";
10
11
  import { forgetToolStats, isFreePiSession } from "./tools.js";
11
12
  import {
@@ -42,6 +43,28 @@ const EVENT_TYPES = [
42
43
  "location.shutdown",
43
44
  ] as const;
44
45
 
46
+ /**
47
+ * Hides a model the gateway rejected with `model_requires_credits`. The error
48
+ * body does not name the model, but the session's last request does; removing
49
+ * it and reloading the provider keeps the picker from offering a choice that
50
+ * always fails on this account.
51
+ */
52
+ async function hideRejectedModel(
53
+ ctx: Plugin.Context,
54
+ deps: Deps,
55
+ sessionID: string,
56
+ error: any,
57
+ ): Promise<void> {
58
+ const parsed = parseFreePiError(error, true);
59
+ if (parsed?.code !== "model_requires_credits") return;
60
+ const key = deps.state.lastModelBySession.get(sessionID);
61
+ if (!key || deps.state.deniedModels.has(key)) return;
62
+ deps.state.deniedModels.add(key);
63
+ deps.log.warn("free-pi hid a model this account cannot use", { model: key });
64
+ await ctx.provider.reload().catch(() => undefined);
65
+ await ctx.model.reload().catch(() => undefined);
66
+ }
67
+
45
68
  async function handleEvent(
46
69
  ctx: Plugin.Context,
47
70
  deps: Deps,
@@ -55,6 +78,8 @@ async function handleEvent(
55
78
  tokenFromCredential(credential) ?? (await readCredentialsToken());
56
79
  if (next === deps.state.providerToken) return;
57
80
  deps.state.providerToken = next;
81
+ // A different sign-in can have premium credits, so re-test every model.
82
+ deps.state.deniedModels.clear();
58
83
  await ctx.provider.reload().catch(() => undefined);
59
84
  return;
60
85
  }
@@ -84,6 +109,7 @@ async function handleEvent(
84
109
  if (isAbortLike(event.data?.error)) {
85
110
  markWireSessionDirty(deps, sessionID);
86
111
  }
112
+ await hideRejectedModel(ctx, deps, sessionID, event.data?.error);
87
113
  await handleFreePiError(deps, event.data?.error, {
88
114
  allowRaw: true,
89
115
  }).catch(() => undefined);
@@ -338,6 +338,58 @@ function applyContextDiet(deps: Deps, event: any): void {
338
338
  );
339
339
  }
340
340
 
341
+ /**
342
+ * Drops the reasoning OpenCode stores and echoes back inside assistant
343
+ * messages.
344
+ *
345
+ * The provider request carries it as `reasoning_content`, but it is not input:
346
+ * the gateway billed it on some models (a measured glm-5.3-flash request went
347
+ * from 27 to 188 prompt tokens with the same answer) and the token estimate used
348
+ * for diet/compaction assumes it is not sent. Removing it keeps the request
349
+ * identical in behavior and smaller in credits.
350
+ */
351
+ function stripAssistantReasoning(deps: Deps, event: any): void {
352
+ const messages = event.messages;
353
+ if (!Array.isArray(messages) || messages.length === 0) return;
354
+ let chars = 0;
355
+ let changed = false;
356
+ const next = messages.map((message: any) => {
357
+ if (!message || message.role !== "assistant") return message;
358
+ let copy: any | undefined;
359
+ const ensureCopy = () => {
360
+ if (!copy) copy = { ...message };
361
+ return copy;
362
+ };
363
+ for (const key of ["reasoning_content", "reasoning"] as const) {
364
+ if (!(key in message)) continue;
365
+ const value = message[key];
366
+ if (typeof value === "string") chars += value.length;
367
+ ensureCopy();
368
+ delete copy[key];
369
+ changed = true;
370
+ }
371
+ if (Array.isArray(message.content)) {
372
+ const kept = message.content.filter(
373
+ (part: any) => part?.type !== "reasoning" && part?.type !== "thinking",
374
+ );
375
+ if (kept.length !== message.content.length) {
376
+ ensureCopy();
377
+ copy.content = kept;
378
+ changed = true;
379
+ }
380
+ }
381
+ return copy ?? message;
382
+ });
383
+ if (!changed) return;
384
+ event.messages = next;
385
+ if (chars > 0) {
386
+ deps.log.info("free-pi dropped stored reasoning from the request", {
387
+ sessionID: event.sessionID,
388
+ chars,
389
+ });
390
+ }
391
+ }
392
+
341
393
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
342
394
  async function applyGeneration(
343
395
  deps: Deps,
@@ -355,7 +407,17 @@ async function applyGeneration(
355
407
  return;
356
408
  }
357
409
 
410
+ stripAssistantReasoning(deps, event);
411
+
358
412
  const modelID = event.model?.id;
413
+ // Remember the choice so a `model_requires_credits` failure can hide exactly
414
+ // the model that was rejected instead of the whole provider.
415
+ if (typeof event.sessionID === "string" && typeof modelID === "string") {
416
+ deps.state.lastModelBySession.set(
417
+ event.sessionID,
418
+ `${event.model.providerID}/${modelID}`,
419
+ );
420
+ }
359
421
  const limit = deps.state.outputLimits.get(
360
422
  `${event.model.providerID}/${modelID}`,
361
423
  );
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(),