@eduardo191labs/opencode-free-pi 0.7.30 → 0.7.32

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
@@ -123,9 +123,10 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
123
123
  funciona es pedir el trabajo explícito: con la regla de «escribe cada paso,
124
124
  recalcula por un segundo método y no respondas hasta que coincidan», el mismo
125
125
  modelo subió de ~450 a ~1250 tokens de razonamiento y acertó 5/5 problemas de
126
- lógica frente a 3/5 sin la regla. Por eso la guía de trabajo prioriza la
127
- respuesta lenta y verificada, y el límite de salida se deja amplio para que
128
- esa cadena no se trunque.
126
+ lógica frente a 3/5 sin la regla. Esa instrucción es una recomendación de uso
127
+ para tu mensaje, no un prompt que el plugin inyecte: el plugin no añade
128
+ instrucciones a la sesión. El límite de salida se deja amplio para que la
129
+ cadena de razonamiento no se trunque.
129
130
  - **Capacidades iguales al CLI**: todos los modelos se registran con
130
131
  razonamiento activo, coste cero, la ventana medida y el límite de salida que
131
132
  publica el upstream (32k por defecto, hasta 131k). No se fuerza temperatura ni
@@ -161,11 +162,11 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
161
162
  - **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
162
163
  respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
163
164
  - Anuncios e impresiones asociados al turno correcto. El contexto del anuncio se
164
- construye solo con el último mensaje real del usuario: se ignoran el
165
- recordatorio del plugin y los mensajes sintéticos que OpenCode inserta en el
166
- mismo turno (resultado de un subagente, salida de un shell en segundo plano,
167
- AGENTS.md, reinicio del servidor o respuesta interrumpida), que antes
168
- rotaban el anuncio a mitad de turno y enviaban ids internos como contexto.
165
+ construye solo con el último mensaje real del usuario: se ignoran los
166
+ mensajes sintéticos que OpenCode inserta en el mismo turno (resultado de un
167
+ subagente, salida de un shell en segundo plano, AGENTS.md, reinicio del
168
+ servidor o respuesta interrumpida), que antes rotaban el anuncio a mitad de
169
+ turno y enviaban ids internos como contexto.
169
170
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
170
171
  de anuncios; nunca reutiliza los del agente principal.
171
172
  - **Cierre de sesión**: free-pi limita la cuenta a 4 sesiones simultáneas. El
@@ -2,4 +2,3 @@
2
2
  import type { Credential } from "@opencode/schema/credential";
3
3
  export declare function tokenFromCredential(credential: Credential.Value | undefined): string | undefined;
4
4
  export declare function expiryFromCredential(credential: Credential.Value | undefined): number | undefined;
5
- export declare function issuerFromCredential(credential: Credential.Value | undefined): string | undefined;
@@ -1,6 +1,5 @@
1
1
  /** Translates OpenCode V2 credentials into free-pi tokens. */
2
- import { decodeRefreshToken, tokenExpiry } from "./jwt.js";
3
- import { normalizeIssuer } from "../utils/urls.js";
2
+ import { tokenExpiry } from "./jwt.js";
4
3
  export function tokenFromCredential(credential) {
5
4
  if (!credential)
6
5
  return undefined;
@@ -23,12 +22,3 @@ export function expiryFromCredential(credential) {
23
22
  const token = tokenFromCredential(credential);
24
23
  return token ? tokenExpiry(token) : undefined;
25
24
  }
26
- export function issuerFromCredential(credential) {
27
- if (!credential)
28
- return undefined;
29
- if (credential.type === "oauth")
30
- return decodeRefreshToken(credential.refresh)?.issuer;
31
- if (credential.type === "key")
32
- return normalizeIssuer(credential.metadata?.issuer);
33
- return undefined;
34
- }
@@ -1,7 +1,6 @@
1
1
  /** The free-pi credential file written by the free-pi CLI. */
2
2
  import type { Credentials } from "../types.js";
3
3
  export declare function credentialsPath(): string;
4
- export declare function credentialsDisplayPath(): string;
5
4
  export declare function readCredentials(): Promise<Credentials | undefined>;
6
5
  export declare function readCredentialsToken(): Promise<string | undefined>;
7
6
  export declare function writeCredentials(token: string, issuer?: string): Promise<void>;
@@ -9,14 +9,6 @@ export function credentialsPath() {
9
9
  return resolve(override);
10
10
  return join(homedir(), ".free-pi", "agent", "credentials.json");
11
11
  }
12
- export function credentialsDisplayPath() {
13
- const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
14
- if (override)
15
- return override;
16
- return process.platform === "win32"
17
- ? join("%USERPROFILE%", ".free-pi", "agent", "credentials.json")
18
- : "~/.free-pi/agent/credentials.json";
19
- }
20
12
  export async function readCredentials() {
21
13
  const envToken = process.env.FREEPI_JWT?.trim();
22
14
  if (envToken)
@@ -1,7 +1,6 @@
1
1
  /** JWT and refresh-token encoding helpers. */
2
- import type { Credentials, JwtClaims } from "../types.js";
2
+ import type { JwtClaims } from "../types.js";
3
3
  export declare function parseJwtClaims(token: string): JwtClaims | undefined;
4
4
  export declare function tokenExpiry(token: string): number | undefined;
5
5
  export declare function tokenNeedsRefresh(token: string, expires?: number): boolean;
6
6
  export declare function encodeRefreshToken(token: string, issuer?: string): string;
7
- export declare function decodeRefreshToken(value: string | undefined): Credentials | undefined;
package/dist/auth/jwt.js CHANGED
@@ -1,6 +1,5 @@
1
1
  /** JWT and refresh-token encoding helpers. */
2
2
  import { AUTH_SKEW_MS, REFRESH_PREFIX, } from "../constants.js";
3
- import { normalizeIssuer } from "../utils/urls.js";
4
3
  export function parseJwtClaims(token) {
5
4
  const payload = token.split(".")[1];
6
5
  if (!payload)
@@ -33,28 +32,3 @@ export function encodeRefreshToken(token, issuer) {
33
32
  const payload = JSON.stringify(issuer ? { token, issuer } : { token });
34
33
  return `${REFRESH_PREFIX}${Buffer.from(payload).toString("base64url")}`;
35
34
  }
36
- export function decodeRefreshToken(value) {
37
- if (!value)
38
- return undefined;
39
- if (value.startsWith(REFRESH_PREFIX)) {
40
- try {
41
- const parsed = JSON.parse(Buffer.from(value.slice(REFRESH_PREFIX.length), "base64url").toString("utf8"));
42
- if (typeof parsed.token === "string" && parsed.token.length > 0) {
43
- const issuer = normalizeIssuer(parsed.issuer);
44
- return issuer
45
- ? { token: parsed.token, issuer }
46
- : { token: parsed.token };
47
- }
48
- }
49
- catch { }
50
- }
51
- try {
52
- const parsed = JSON.parse(value);
53
- if (typeof parsed.token === "string" && parsed.token.length > 0) {
54
- const issuer = normalizeIssuer(parsed.issuer);
55
- return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
56
- }
57
- }
58
- catch { }
59
- return { token: value };
60
- }
@@ -260,7 +260,7 @@ export function settleWindow(samples) {
260
260
  * accepted probe, so a process that exits mid-verification keeps the smallest
261
261
  * proven value instead of losing the whole run.
262
262
  */
263
- async function commitWindow(deps, tokens, modelID) {
263
+ async function commitWindow(tokens, modelID) {
264
264
  const limits = (cached ??= emptyLimits());
265
265
  // The measured ceiling belongs to the model probed, not to every model: the
266
266
  // gateway's limit is per model, and a global window taken from one model
@@ -344,7 +344,7 @@ export async function verifyGatewayWindow(deps, options = {}) {
344
344
  const settled = settleWindow(samples);
345
345
  if (settled) {
346
346
  // Never go below the window that already worked for this account.
347
- verified = await commitWindow(deps, Math.max(settled, floor), modelID);
347
+ verified = await commitWindow(Math.max(settled, floor), modelID);
348
348
  }
349
349
  if (accepted >= MAX_WINDOW)
350
350
  break;
@@ -1,9 +1,6 @@
1
1
  /** Identifiers and defaults shared by every part of the plugin. */
2
2
  export declare const PROVIDER_ID = "free-pi";
3
3
  export declare const DEFENSE_PROVIDER_ID = "free-pi-defense";
4
- export declare const INTEGRATION_ID = "free-pi";
5
- export declare const PROVIDER_NAME = "Free Pi";
6
- export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
4
  export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
5
  export declare const DEFAULT_CLIENT_VERSION = "0.6.28";
9
6
  export declare const CONSENT_VERSION = "4";
package/dist/constants.js CHANGED
@@ -1,9 +1,6 @@
1
1
  /** Identifiers and defaults shared by every part of the plugin. */
2
2
  export const PROVIDER_ID = "free-pi";
3
3
  export const DEFENSE_PROVIDER_ID = "free-pi-defense";
4
- export const INTEGRATION_ID = PROVIDER_ID;
5
- export const PROVIDER_NAME = "Free Pi";
6
- export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
7
4
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
8
5
  export const DEFAULT_CLIENT_VERSION = "0.6.28";
9
6
  export const CONSENT_VERSION = "4";
@@ -8,7 +8,6 @@ export async function handleFreePiError(deps, error, opts = {}) {
8
8
  const parsed = parseFreePiError(error, opts.allowRaw === true);
9
9
  if (!parsed)
10
10
  return;
11
- deps.state.lastFreePiError = parsed;
12
11
  if (parsed.status === 401 ||
13
12
  parsed.code === "unauthorized" ||
14
13
  parsed.code === "expired_token") {
@@ -2,8 +2,6 @@
2
2
  * Rewrites long-lived free-pi limit responses so the client shows the friendly
3
3
  * message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
4
4
  */
5
- /** The free-pi overflow code carried by a response, when it is one. */
6
- export declare function overflowCodeOf(response: Response): Promise<string | undefined>;
7
5
  /**
8
6
  * Returns a replacement response when `response` is a free-pi context overflow.
9
7
  * The replacement is a 400 with a message OpenCode recognizes as context
@@ -105,20 +105,6 @@ function contextOverflowCode(body) {
105
105
  catch { }
106
106
  return undefined;
107
107
  }
108
- /** The free-pi overflow code carried by a response, when it is one. */
109
- export async function overflowCodeOf(response) {
110
- if (response.status !== 413 &&
111
- response.status !== 429 &&
112
- response.status !== 400)
113
- return undefined;
114
- const body = await response
115
- .clone()
116
- .text()
117
- .catch(() => "");
118
- if (!body)
119
- return undefined;
120
- return contextOverflowCode(body);
121
- }
122
108
  /**
123
109
  * Returns a replacement response when `response` is a free-pi context overflow.
124
110
  * The replacement is a 400 with a message OpenCode recognizes as context
package/dist/plugin.js CHANGED
@@ -63,6 +63,9 @@ async function setup(ctx) {
63
63
  const removed = await removeLegacyFreePiFiles();
64
64
  if (removed.length > 0) {
65
65
  log.info(`Removed ${removed.length} legacy free-pi agent/skill file(s); OpenCode now owns them`, removed);
66
+ // Let OpenCode's own registry drop the files it loaded from disk.
67
+ await ctx.agent.reload().catch(() => undefined);
68
+ await ctx.skill.reload().catch(() => undefined);
66
69
  }
67
70
  }
68
71
  catch (error) {
@@ -112,18 +115,21 @@ async function setup(ctx) {
112
115
  const buildMain = () => withoutDenied(PROVIDER_ID, buildModels(currentMain, candidates, buildOptions));
113
116
  const buildDefense = () => withoutDenied(DEFENSE_PROVIDER_ID, buildModels(currentDefense, candidates, buildOptions));
114
117
  function indexModelState() {
115
- const mainNow = buildMain();
116
- const defenseNow = buildDefense();
117
- for (const [id, model] of Object.entries(mainNow)) {
118
+ // Rebuilt, not appended: a model that disappears or stops accepting images
119
+ // must stop being treated as image-capable, or a later `read` keeps sending
120
+ // an attachment the current catalog no longer supports.
121
+ const images = new Set();
122
+ for (const [id, model] of Object.entries(buildMain())) {
118
123
  if (model.modalities.input.includes("image")) {
119
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
124
+ images.add(`${PROVIDER_ID}/${id}`);
120
125
  }
121
126
  }
122
- for (const [id, model] of Object.entries(defenseNow)) {
127
+ for (const [id, model] of Object.entries(buildDefense())) {
123
128
  if (model.modalities.input.includes("image")) {
124
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
129
+ images.add(`${DEFENSE_PROVIDER_ID}/${id}`);
125
130
  }
126
131
  }
132
+ state.imageModels = images;
127
133
  }
128
134
  indexModelState();
129
135
  const credential = await deps.activeCredential().catch(() => undefined);
@@ -161,55 +161,9 @@ async function registerToolHooks(ctx, deps, registrations) {
161
161
  status: event.status,
162
162
  ...(event.status === "completed" ? { result: event.result } : {}),
163
163
  });
164
- nudgeFailedTool(deps, event);
165
164
  replaceUnsupportedImages(deps, event);
166
165
  }));
167
166
  }
168
- /**
169
- * Adds the concrete next step to a tool failure the free models repeat.
170
- *
171
- * The scan of a week of sessions shows the same failures over and over: the
172
- * portable shell scanner rejects a heredoc or a nested-quote one-liner (72
173
- * times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
174
- * The model reads the bare error and often repeats the call. The hint is short
175
- * and only goes to free-pi sessions; other providers keep their own messages.
176
- */
177
- function nudgeFailedTool(deps, event) {
178
- if (event.status !== "error")
179
- return;
180
- if (!isFreePiSession(deps, event.sessionID))
181
- return;
182
- const error = event.error;
183
- if (!error || typeof error !== "object")
184
- return;
185
- const message = typeof error.message === "string" ? error.message : "";
186
- if (!message)
187
- return;
188
- let hint = "";
189
- if (message.includes("Portable shell scanner cannot analyze command")) {
190
- hint =
191
- " Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
192
- }
193
- else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
194
- hint =
195
- " Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
196
- }
197
- else if (/Found \d+ matches? for oldString/i.test(message)) {
198
- hint =
199
- " Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
200
- }
201
- else if (/has not been read yet|read it before/i.test(message)) {
202
- hint = " Read the file with the read tool in this turn before editing it.";
203
- }
204
- if (!hint)
205
- return;
206
- try {
207
- error.message = `${message}${hint}`;
208
- }
209
- catch {
210
- // A frozen error still reaches the model unchanged; the hint is best effort.
211
- }
212
- }
213
167
  /**
214
168
  * Models whose upstream accepts images get them natively, so a `read` that
215
169
  * returns a picture must keep the file part. Text-only models would turn it
@@ -46,7 +46,6 @@ export declare function profileRequest(body: string): RequestProfile;
46
46
  * provider is failing, so compacting again cannot help.
47
47
  */
48
48
  export declare function noteSpuriousOverflow(deps: Deps, sessionID: string): number;
49
- export declare function clearSpuriousOverflows(deps: Deps, sessionID: string): void;
50
49
  /** Whether the session has had enough spurious rejections to stop compacting. */
51
50
  export declare function overflowingSpuriously(deps: Deps, sessionID: string): boolean;
52
51
  /**
@@ -109,9 +109,6 @@ export function noteSpuriousOverflow(deps, sessionID) {
109
109
  }
110
110
  return count;
111
111
  }
112
- export function clearSpuriousOverflows(deps, sessionID) {
113
- deps.state.spuriousOverflows.delete(sessionID);
114
- }
115
112
  /** Whether the session has had enough spurious rejections to stop compacting. */
116
113
  export function overflowingSpuriously(deps, sessionID) {
117
114
  const entry = deps.state.spuriousOverflows.get(sessionID);
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Per-plugin-instance mutable state. */
2
- import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
2
+ import type { AdTurn, Catalog, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
3
3
  export type RuntimeState = {
4
4
  latestClientVersion: string;
5
5
  providerToken?: string;
@@ -12,13 +12,10 @@ export type RuntimeState = {
12
12
  registryPromise?: Promise<ModelRegistry | undefined>;
13
13
  lastCatalogNotice?: string;
14
14
  lastQuotaNotice?: string;
15
- catalogModels: Catalog;
16
15
  /** `provider/model` ids whose upstream accepts image input. */
17
16
  imageModels: Set<string>;
18
17
  quotaCache?: QuotaSnapshot;
19
18
  quotaPromise?: Promise<QuotaSnapshot>;
20
- lastQuotaRefreshAt: number;
21
- lastFreePiError?: FreePiError;
22
19
  lastErrorLogKey?: string;
23
20
  lastErrorLogAt: number;
24
21
  lastInvalidToken?: string;
package/dist/state.js CHANGED
@@ -6,9 +6,7 @@ export function createRuntimeState() {
6
6
  cachedCatalogAt: 0,
7
7
  cachedRegistryAt: 0,
8
8
  registryAttemptAt: 0,
9
- catalogModels: {},
10
9
  imageModels: new Set(),
11
- lastQuotaRefreshAt: 0,
12
10
  lastErrorLogAt: 0,
13
11
  tokenChecks: new Map(),
14
12
  sessionClosePromises: new Map(),
@@ -50,5 +50,5 @@ export declare function freePiRequest(deps: Deps, options: RequestOptions): Prom
50
50
  /** Maps a business error code to the CLI's wording, or keeps the HTTP text. */
51
51
  export declare function mappedText(table: Record<string, string>, result: Extract<ApiResult, {
52
52
  ok: false;
53
- }>, library?: string): string;
53
+ }>): string;
54
54
  export {};
package/dist/tools/api.js CHANGED
@@ -110,7 +110,7 @@ export async function freePiRequest(deps, options) {
110
110
  };
111
111
  }
112
112
  /** Maps a business error code to the CLI's wording, or keeps the HTTP text. */
113
- export function mappedText(table, result, library) {
113
+ export function mappedText(table, result) {
114
114
  if (result.code === "no_token")
115
115
  return NO_TOKEN_TEXT;
116
116
  const mapped = table[result.code];
package/dist/tools/web.js CHANGED
@@ -130,7 +130,7 @@ async function executeDocsLookup(deps, raw, context) {
130
130
  label: "The documentation lookup",
131
131
  });
132
132
  if (!lookup.ok)
133
- return fail(mappedText(ERRORS, lookup, library));
133
+ return fail(mappedText(ERRORS, lookup));
134
134
  const data = lookup.data ?? {};
135
135
  deps.log.info("docs_lookup answered", {
136
136
  library,
package/dist/types.d.ts CHANGED
@@ -210,18 +210,6 @@ export type FreePiError = {
210
210
  allowance_credits?: number;
211
211
  };
212
212
  export type TokenCheckState = "ok" | "invalid" | "unknown";
213
- export type RequestUsage = {
214
- at: number;
215
- messageID: string;
216
- providerID: string;
217
- modelID: string;
218
- cost: number;
219
- input: number;
220
- output: number;
221
- reasoning: number;
222
- cacheRead: number;
223
- cacheWrite: number;
224
- };
225
213
  export type Credentials = {
226
214
  token: string;
227
215
  issuer?: string;
@@ -1,6 +1,5 @@
1
1
  /** Numeric and human-readable formatting helpers. */
2
2
  export declare function duplicateNumber(value: unknown): number | undefined;
3
3
  export declare function positiveNumber(...values: Array<number | undefined>): number | undefined;
4
- export declare function creditsToUsd(credits: number | undefined): number;
5
4
  export declare function formatRefillTime(value: string | undefined): string;
6
5
  export declare function formatWait(seconds: number | undefined): string | undefined;
@@ -1,5 +1,4 @@
1
1
  /** Numeric and human-readable formatting helpers. */
2
- import { CREDITS_PER_USD } from "../constants.js";
3
2
  export function duplicateNumber(value) {
4
3
  return typeof value === "number" && Number.isFinite(value) && value > 0
5
4
  ? value
@@ -13,11 +12,6 @@ export function positiveNumber(...values) {
13
12
  }
14
13
  return undefined;
15
14
  }
16
- export function creditsToUsd(credits) {
17
- return typeof credits === "number" && Number.isFinite(credits) && credits > 0
18
- ? credits / CREDITS_PER_USD
19
- : 0;
20
- }
21
15
  export function formatRefillTime(value) {
22
16
  if (!value)
23
17
  return "unknown";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.30",
3
+ "version": "0.7.32",
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",
@@ -1,8 +1,7 @@
1
1
  /** Translates OpenCode V2 credentials into free-pi tokens. */
2
2
 
3
3
  import type { Credential } from "@opencode/schema/credential";
4
- import { decodeRefreshToken, tokenExpiry } from "./jwt.js";
5
- import { normalizeIssuer } from "../utils/urls.js";
4
+ import { tokenExpiry } from "./jwt.js";
6
5
 
7
6
  export function tokenFromCredential(
8
7
  credential: Credential.Value | undefined,
@@ -26,14 +25,3 @@ export function expiryFromCredential(
26
25
  const token = tokenFromCredential(credential);
27
26
  return token ? tokenExpiry(token) : undefined;
28
27
  }
29
-
30
- export function issuerFromCredential(
31
- credential: Credential.Value | undefined,
32
- ): string | undefined {
33
- if (!credential) return undefined;
34
- if (credential.type === "oauth")
35
- return decodeRefreshToken(credential.refresh)?.issuer;
36
- if (credential.type === "key")
37
- return normalizeIssuer(credential.metadata?.issuer);
38
- return undefined;
39
- }
@@ -12,14 +12,6 @@ export function credentialsPath(): string {
12
12
  return join(homedir(), ".free-pi", "agent", "credentials.json");
13
13
  }
14
14
 
15
- export function credentialsDisplayPath(): string {
16
- const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
17
- if (override) return override;
18
- return process.platform === "win32"
19
- ? join("%USERPROFILE%", ".free-pi", "agent", "credentials.json")
20
- : "~/.free-pi/agent/credentials.json";
21
- }
22
-
23
15
  export async function readCredentials(): Promise<Credentials | undefined> {
24
16
  const envToken = process.env.FREEPI_JWT?.trim();
25
17
  if (envToken) return { token: envToken, issuer: resolveBaseUrl() };
package/src/auth/jwt.ts CHANGED
@@ -4,8 +4,7 @@ import {
4
4
  AUTH_SKEW_MS,
5
5
  REFRESH_PREFIX,
6
6
  } from "../constants.js";
7
- import type { Credentials, JwtClaims } from "../types.js";
8
- import { normalizeIssuer } from "../utils/urls.js";
7
+ import type { JwtClaims } from "../types.js";
9
8
 
10
9
  export function parseJwtClaims(token: string): JwtClaims | undefined {
11
10
  const payload = token.split(".")[1];
@@ -44,32 +43,3 @@ export function encodeRefreshToken(token: string, issuer?: string): string {
44
43
  const payload = JSON.stringify(issuer ? { token, issuer } : { token });
45
44
  return `${REFRESH_PREFIX}${Buffer.from(payload).toString("base64url")}`;
46
45
  }
47
-
48
- export function decodeRefreshToken(
49
- value: string | undefined,
50
- ): Credentials | undefined {
51
- if (!value) return undefined;
52
- if (value.startsWith(REFRESH_PREFIX)) {
53
- try {
54
- const parsed = JSON.parse(
55
- Buffer.from(value.slice(REFRESH_PREFIX.length), "base64url").toString(
56
- "utf8",
57
- ),
58
- ) as { token?: unknown; issuer?: unknown };
59
- if (typeof parsed.token === "string" && parsed.token.length > 0) {
60
- const issuer = normalizeIssuer(parsed.issuer);
61
- return issuer
62
- ? { token: parsed.token, issuer }
63
- : { token: parsed.token };
64
- }
65
- } catch {}
66
- }
67
- try {
68
- const parsed = JSON.parse(value) as { token?: unknown; issuer?: unknown };
69
- if (typeof parsed.token === "string" && parsed.token.length > 0) {
70
- const issuer = normalizeIssuer(parsed.issuer);
71
- return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
72
- }
73
- } catch {}
74
- return { token: value };
75
- }
@@ -341,7 +341,6 @@ export function settleWindow(
341
341
  * proven value instead of losing the whole run.
342
342
  */
343
343
  async function commitWindow(
344
- deps: Deps,
345
344
  tokens: number,
346
345
  modelID: string,
347
346
  ): Promise<number> {
@@ -432,7 +431,7 @@ export async function verifyGatewayWindow(
432
431
  const settled = settleWindow(samples);
433
432
  if (settled) {
434
433
  // Never go below the window that already worked for this account.
435
- verified = await commitWindow(deps, Math.max(settled, floor), modelID);
434
+ verified = await commitWindow(Math.max(settled, floor), modelID);
436
435
  }
437
436
  if (accepted >= MAX_WINDOW) break;
438
437
  const next = Math.min(MAX_WINDOW, Math.floor(accepted * 1.2));
package/src/constants.ts CHANGED
@@ -2,10 +2,6 @@
2
2
 
3
3
  export const PROVIDER_ID = "free-pi";
4
4
  export const DEFENSE_PROVIDER_ID = "free-pi-defense";
5
- export const INTEGRATION_ID = PROVIDER_ID;
6
-
7
- export const PROVIDER_NAME = "Free Pi";
8
- export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
9
5
 
10
6
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
11
7
  export const DEFAULT_CLIENT_VERSION = "0.6.28";
@@ -19,7 +19,6 @@ export async function handleFreePiError(
19
19
  ): Promise<void> {
20
20
  const parsed = parseFreePiError(error, opts.allowRaw === true);
21
21
  if (!parsed) return;
22
- deps.state.lastFreePiError = parsed;
23
22
 
24
23
  if (
25
24
  parsed.status === 401 ||
@@ -111,24 +111,6 @@ function contextOverflowCode(body: string): string | undefined {
111
111
  return undefined;
112
112
  }
113
113
 
114
- /** The free-pi overflow code carried by a response, when it is one. */
115
- export async function overflowCodeOf(
116
- response: Response,
117
- ): Promise<string | undefined> {
118
- if (
119
- response.status !== 413 &&
120
- response.status !== 429 &&
121
- response.status !== 400
122
- )
123
- return undefined;
124
- const body = await response
125
- .clone()
126
- .text()
127
- .catch(() => "");
128
- if (!body) return undefined;
129
- return contextOverflowCode(body);
130
- }
131
-
132
114
  /**
133
115
  * Returns a replacement response when `response` is a free-pi context overflow.
134
116
  * The replacement is a 400 with a message OpenCode recognizes as context
package/src/legacy.ts CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { readFile, rm, rmdir } from "node:fs/promises";
13
13
  import { homedir } from "node:os";
14
- import { dirname, join } from "node:path";
14
+ import { join } from "node:path";
15
15
 
16
16
  const MARKER =
17
17
  "<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->";
package/src/plugin.ts CHANGED
@@ -84,6 +84,9 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
84
84
  `Removed ${removed.length} legacy free-pi agent/skill file(s); OpenCode now owns them`,
85
85
  removed,
86
86
  );
87
+ // Let OpenCode's own registry drop the files it loaded from disk.
88
+ await ctx.agent.reload().catch(() => undefined);
89
+ await ctx.skill.reload().catch(() => undefined);
87
90
  }
88
91
  } catch (error) {
89
92
  log.warn("Could not remove the legacy free-pi agent/skill files", error);
@@ -143,18 +146,21 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
143
146
  );
144
147
 
145
148
  function indexModelState(): void {
146
- const mainNow = buildMain();
147
- const defenseNow = buildDefense();
148
- for (const [id, model] of Object.entries(mainNow)) {
149
+ // Rebuilt, not appended: a model that disappears or stops accepting images
150
+ // must stop being treated as image-capable, or a later `read` keeps sending
151
+ // an attachment the current catalog no longer supports.
152
+ const images = new Set<string>();
153
+ for (const [id, model] of Object.entries(buildMain())) {
149
154
  if (model.modalities.input.includes("image")) {
150
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
155
+ images.add(`${PROVIDER_ID}/${id}`);
151
156
  }
152
157
  }
153
- for (const [id, model] of Object.entries(defenseNow)) {
158
+ for (const [id, model] of Object.entries(buildDefense())) {
154
159
  if (model.modalities.input.includes("image")) {
155
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
160
+ images.add(`${DEFENSE_PROVIDER_ID}/${id}`);
156
161
  }
157
162
  }
163
+ state.imageModels = images;
158
164
  }
159
165
  indexModelState();
160
166
 
@@ -20,7 +20,6 @@ import {
20
20
  rewriteContextOverflowResponse,
21
21
  rewriteLimitResponse,
22
22
  } from "../errors/limit.js";
23
- import { parseFreePiError } from "../errors/parse.js";
24
23
  import { trimMap } from "../utils/async.js";
25
24
  import { watchFreePiNotice } from "./notices.js";
26
25
  import {
@@ -240,49 +239,11 @@ async function registerToolHooks(
240
239
  status: event.status,
241
240
  ...(event.status === "completed" ? { result: event.result } : {}),
242
241
  });
243
- nudgeFailedTool(deps, event);
244
242
  replaceUnsupportedImages(deps, event);
245
243
  }),
246
244
  );
247
245
  }
248
246
 
249
- /**
250
- * Adds the concrete next step to a tool failure the free models repeat.
251
- *
252
- * The scan of a week of sessions shows the same failures over and over: the
253
- * portable shell scanner rejects a heredoc or a nested-quote one-liner (72
254
- * times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
255
- * The model reads the bare error and often repeats the call. The hint is short
256
- * and only goes to free-pi sessions; other providers keep their own messages.
257
- */
258
- function nudgeFailedTool(deps: Deps, event: any): void {
259
- if (event.status !== "error") return;
260
- if (!isFreePiSession(deps, event.sessionID)) return;
261
- const error = event.error;
262
- if (!error || typeof error !== "object") return;
263
- const message = typeof error.message === "string" ? error.message : "";
264
- if (!message) return;
265
- let hint = "";
266
- if (message.includes("Portable shell scanner cannot analyze command")) {
267
- hint =
268
- " Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
269
- } else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
270
- hint =
271
- " Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
272
- } else if (/Found \d+ matches? for oldString/i.test(message)) {
273
- hint =
274
- " Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
275
- } else if (/has not been read yet|read it before/i.test(message)) {
276
- hint = " Read the file with the read tool in this turn before editing it.";
277
- }
278
- if (!hint) return;
279
- try {
280
- error.message = `${message}${hint}`;
281
- } catch {
282
- // A frozen error still reaches the model unchanged; the hint is best effort.
283
- }
284
- }
285
-
286
247
  /**
287
248
  * Models whose upstream accepts images get them natively, so a `read` that
288
249
  * returns a picture must keep the file part. Text-only models would turn it
@@ -129,10 +129,6 @@ export function noteSpuriousOverflow(deps: Deps, sessionID: string): number {
129
129
  return count;
130
130
  }
131
131
 
132
- export function clearSpuriousOverflows(deps: Deps, sessionID: string): void {
133
- deps.state.spuriousOverflows.delete(sessionID);
134
- }
135
-
136
132
  /** Whether the session has had enough spurious rejections to stop compacting. */
137
133
  export function overflowingSpuriously(deps: Deps, sessionID: string): boolean {
138
134
  const entry = deps.state.spuriousOverflows.get(sessionID);
package/src/state.ts CHANGED
@@ -4,7 +4,6 @@ import { DEFAULT_CLIENT_VERSION } from "./constants.js";
4
4
  import type {
5
5
  AdTurn,
6
6
  Catalog,
7
- FreePiError,
8
7
  ModelRegistry,
9
8
  QuotaSnapshot,
10
9
  SessionResetOutcome,
@@ -26,15 +25,12 @@ export type RuntimeState = {
26
25
  registryPromise?: Promise<ModelRegistry | undefined>;
27
26
  lastCatalogNotice?: string;
28
27
  lastQuotaNotice?: string;
29
- catalogModels: Catalog;
30
28
  /** `provider/model` ids whose upstream accepts image input. */
31
29
  imageModels: Set<string>;
32
30
 
33
31
  quotaCache?: QuotaSnapshot;
34
32
  quotaPromise?: Promise<QuotaSnapshot>;
35
- lastQuotaRefreshAt: number;
36
33
 
37
- lastFreePiError?: FreePiError;
38
34
  lastErrorLogKey?: string;
39
35
  lastErrorLogAt: number;
40
36
  lastInvalidToken?: string;
@@ -74,9 +70,7 @@ export function createRuntimeState(): RuntimeState {
74
70
  cachedCatalogAt: 0,
75
71
  cachedRegistryAt: 0,
76
72
  registryAttemptAt: 0,
77
- catalogModels: {},
78
73
  imageModels: new Set(),
79
- lastQuotaRefreshAt: 0,
80
74
  lastErrorLogAt: 0,
81
75
  tokenChecks: new Map(),
82
76
  sessionClosePromises: new Map(),
package/src/tools/api.ts CHANGED
@@ -169,7 +169,6 @@ export async function freePiRequest(
169
169
  export function mappedText(
170
170
  table: Record<string, string>,
171
171
  result: Extract<ApiResult, { ok: false }>,
172
- library?: string,
173
172
  ): string {
174
173
  if (result.code === "no_token") return NO_TOKEN_TEXT;
175
174
  const mapped = table[result.code];
@@ -11,7 +11,6 @@ import {
11
11
  done,
12
12
  fail,
13
13
  freePiRequest,
14
- friendlyStatus,
15
14
  GATED_TEXT,
16
15
  isGatedSession,
17
16
  } from "./api.js";
package/src/tools/web.ts CHANGED
@@ -164,7 +164,7 @@ async function executeDocsLookup(
164
164
  signal: context.signal,
165
165
  label: "The documentation lookup",
166
166
  });
167
- if (!lookup.ok) return fail(mappedText(ERRORS, lookup, library));
167
+ if (!lookup.ok) return fail(mappedText(ERRORS, lookup));
168
168
  const data = lookup.data ?? {};
169
169
  deps.log.info("docs_lookup answered", {
170
170
  library,
package/src/types.ts CHANGED
@@ -192,19 +192,6 @@ export type FreePiError = {
192
192
 
193
193
  export type TokenCheckState = "ok" | "invalid" | "unknown";
194
194
 
195
- export type RequestUsage = {
196
- at: number;
197
- messageID: string;
198
- providerID: string;
199
- modelID: string;
200
- cost: number;
201
- input: number;
202
- output: number;
203
- reasoning: number;
204
- cacheRead: number;
205
- cacheWrite: number;
206
- };
207
-
208
195
  export type Credentials = {
209
196
  token: string;
210
197
  issuer?: string;
@@ -1,7 +1,5 @@
1
1
  /** Numeric and human-readable formatting helpers. */
2
2
 
3
- import { CREDITS_PER_USD } from "../constants.js";
4
-
5
3
  export function duplicateNumber(value: unknown): number | undefined {
6
4
  return typeof value === "number" && Number.isFinite(value) && value > 0
7
5
  ? value
@@ -19,12 +17,6 @@ export function positiveNumber(
19
17
  return undefined;
20
18
  }
21
19
 
22
- export function creditsToUsd(credits: number | undefined): number {
23
- return typeof credits === "number" && Number.isFinite(credits) && credits > 0
24
- ? credits / CREDITS_PER_USD
25
- : 0;
26
- }
27
-
28
20
  export function formatRefillTime(value: string | undefined): string {
29
21
  if (!value) return "unknown";
30
22
  const date = new Date(value);