@eduardo191labs/opencode-free-pi 0.6.7 → 0.6.8

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
@@ -185,6 +185,13 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
185
185
  ya esté en memoria en vez de inventar límites. Los avisos que el servidor
186
186
  manda en el catálogo y en `/me` (`notice`) se registran una vez en el log del
187
187
  plugin.
188
+ - **Catálogo que se recupera solo**: si `/client-version` no responde, el
189
+ proveedor quedaría registrado sin modelos y el selector de esa ubicación
190
+ mostraría «Model unavailable» para todos los modelos free-pi. Por eso la
191
+ petición se reintenta una vez de inmediato y, si aun así falla, el plugin
192
+ vuelve a pedir el catálogo en segundo plano (2 s, 5 s, 10 s, 20 s, 30 s y 60 s)
193
+ y, en cuanto lo obtiene, registra los modelos y recarga proveedor y modelo en
194
+ caliente. No hace falta reiniciar OpenCode ni elegir otra carpeta.
188
195
  - **Aislamiento por proveedor**: todo lo que añade el plugin —herramientas,
189
196
  cabeceras, anuncios, reglas de prompt, compactación, reintentos, topes de
190
197
  tokens y ajustes— se aplica solo a `free-pi` y `free-pi-defense`. Los demás
@@ -1,6 +1,7 @@
1
1
  /** Fetches the live free-pi model catalog. */
2
2
  import { resolveToken } from "../auth/token.js";
3
- import { CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, } from "../constants.js";
3
+ import { CATALOG_ATTEMPTS, CATALOG_RETRY_MS, CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, } from "../constants.js";
4
+ import { sleep } from "../utils/async.js";
4
5
  import { resolveBaseUrl } from "../utils/urls.js";
5
6
  function isCatalog(value) {
6
7
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -32,33 +33,48 @@ export function refreshCatalog(deps) {
32
33
  if (state.catalogPromise)
33
34
  return state.catalogPromise;
34
35
  const pending = (async () => {
35
- try {
36
- const token = await resolveToken(deps).catch(() => undefined);
37
- const headers = {
38
- accept: "application/json",
39
- };
40
- if (token)
41
- headers.authorization = `Bearer ${token}`;
42
- const response = await fetch(`${resolveBaseUrl()}/client-version`, {
43
- headers,
44
- signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
45
- });
46
- if (!response.ok)
47
- throw new Error(`HTTP ${response.status}`);
48
- const catalog = (await response.json());
49
- if (!isCatalog(catalog)) {
50
- throw new Error("free-pi returned an unexpected catalog payload");
36
+ let lastError;
37
+ for (let attempt = 1; attempt <= CATALOG_ATTEMPTS; attempt += 1) {
38
+ try {
39
+ const token = await resolveToken(deps).catch(() => undefined);
40
+ const headers = {
41
+ accept: "application/json",
42
+ };
43
+ if (token)
44
+ headers.authorization = `Bearer ${token}`;
45
+ const response = await fetch(`${resolveBaseUrl()}/client-version`, {
46
+ headers,
47
+ signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
48
+ });
49
+ if (!response.ok)
50
+ throw new Error(`HTTP ${response.status}`);
51
+ const catalog = (await response.json());
52
+ if (!isCatalog(catalog)) {
53
+ throw new Error("free-pi returned an unexpected catalog payload");
54
+ }
55
+ applyCatalog(deps, catalog);
56
+ return catalog;
57
+ }
58
+ catch (error) {
59
+ lastError = error;
60
+ // A timeout or a dropped connection is often transient. Retrying here
61
+ // avoids registering a provider with zero models for this location,
62
+ // which would hide every free-pi model from the picker until OpenCode
63
+ // restarts.
64
+ if (attempt < CATALOG_ATTEMPTS) {
65
+ deps.log.info("free-pi catalog request failed; retrying", {
66
+ attempt,
67
+ reason: reasonText(error),
68
+ });
69
+ await sleep(CATALOG_RETRY_MS * attempt);
70
+ }
51
71
  }
52
- applyCatalog(deps, catalog);
53
- return catalog;
54
- }
55
- catch (error) {
56
- const cached = state.cachedCatalog;
57
- deps.log.warn(cached
58
- ? "free-pi catalog is unreachable; using the cached model list"
59
- : "free-pi catalog is unreachable; no free-pi models were registered", { reason: reasonText(error) });
60
- return cached;
61
72
  }
73
+ const cached = state.cachedCatalog;
74
+ deps.log.warn(cached
75
+ ? "free-pi catalog is unreachable; using the cached model list"
76
+ : "free-pi catalog is unreachable; no free-pi models were registered", { reason: reasonText(lastError) });
77
+ return cached;
62
78
  })();
63
79
  state.catalogPromise = pending;
64
80
  void pending.finally(() => {
@@ -103,6 +103,15 @@ export declare const AD_IMPRESSION_LIMIT = 200;
103
103
  export declare const CREDITS_PER_USD: number;
104
104
  export declare const CATALOG_TTL_MS: number;
105
105
  export declare const CATALOG_TIMEOUT_MS = 8000;
106
+ export declare const CATALOG_ATTEMPTS = 2;
107
+ export declare const CATALOG_RETRY_MS = 1000;
108
+ /**
109
+ * When the catalog cannot be fetched, the provider is registered with no models
110
+ * and the model picker loses every free-pi entry for that location. These are
111
+ * the delays before each background attempt to fetch it again and re-register
112
+ * the models, so a transient timeout heals without restarting OpenCode.
113
+ */
114
+ export declare const CATALOG_RECOVERY_DELAYS_MS: readonly [2000, 5000, 10000, 20000, 30000, 60000];
106
115
  export declare const REGISTRY_TTL_MS: number;
107
116
  export declare const REGISTRY_RETRY_MS = 60000;
108
117
  export declare const REGISTRY_TIMEOUT_MS = 3500;
package/dist/constants.js CHANGED
@@ -131,6 +131,17 @@ export const AD_IMPRESSION_LIMIT = 200;
131
131
  export const CREDITS_PER_USD = 40_000 / 3;
132
132
  export const CATALOG_TTL_MS = 10 * 60_000;
133
133
  export const CATALOG_TIMEOUT_MS = 8_000;
134
+ export const CATALOG_ATTEMPTS = 2;
135
+ export const CATALOG_RETRY_MS = 1_000;
136
+ /**
137
+ * When the catalog cannot be fetched, the provider is registered with no models
138
+ * and the model picker loses every free-pi entry for that location. These are
139
+ * the delays before each background attempt to fetch it again and re-register
140
+ * the models, so a transient timeout heals without restarting OpenCode.
141
+ */
142
+ export const CATALOG_RECOVERY_DELAYS_MS = [
143
+ 2_000, 5_000, 10_000, 20_000, 30_000, 60_000,
144
+ ];
134
145
  export const REGISTRY_TTL_MS = 5 * 60_000;
135
146
  export const REGISTRY_RETRY_MS = 60_000;
136
147
  export const REGISTRY_TIMEOUT_MS = 3_500;
package/dist/plugin.js CHANGED
@@ -10,7 +10,7 @@ import { currentLiveLimits, loadLiveLimits, shouldVerifyWindow, verifyGatewayWin
10
10
  import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
11
11
  import { fetchModelsRegistry } from "./catalog/registry.js";
12
12
  import { applyProvider } from "./catalog/v2.js";
13
- import { DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
13
+ import { CATALOG_RECOVERY_DELAYS_MS, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
14
14
  import { registerIntegration } from "./integration/setup.js";
15
15
  import { createLogger } from "./logging.js";
16
16
  import { subscribeEvents } from "./session/events.js";
@@ -150,8 +150,9 @@ async function setup(ctx) {
150
150
  // Without a quota snapshot every model stays visible.
151
151
  const access = accountAccess(quota?.me);
152
152
  const { main: catalogMain, defense: catalogDefense } = partitionModels(catalog);
153
- const main = filterAccessibleModels(catalogMain, access);
154
- const defense = filterAccessibleModels(catalogDefense, access);
153
+ let currentCatalog = catalog;
154
+ let currentMain = filterAccessibleModels(catalogMain, access);
155
+ let currentDefense = filterAccessibleModels(catalogDefense, access);
155
156
  const candidates = modelRegistryCandidates(registry);
156
157
  const live = await loadLiveLimits();
157
158
  const configuredEffort = ctx.options?.reasoningEffort;
@@ -163,34 +164,41 @@ async function setup(ctx) {
163
164
  ? { reasoningEffort: configuredEffort }
164
165
  : {}),
165
166
  };
166
- const mainModels = buildModels(main, candidates, buildOptions);
167
- const defenseModels = buildModels(defense, candidates, buildOptions);
168
- for (const [id, model] of Object.entries(mainModels)) {
169
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
170
- if (model.modalities.input.includes("image")) {
171
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
167
+ // Rebuilt on every call so a learned context ceiling or a recovered catalog
168
+ // applies without restarting OpenCode.
169
+ const buildMain = () => buildModels(currentMain, candidates, {
170
+ ...buildOptions,
171
+ live: currentLiveLimits() ?? live,
172
+ });
173
+ const buildDefense = () => buildModels(currentDefense, candidates, {
174
+ ...buildOptions,
175
+ live: currentLiveLimits() ?? live,
176
+ });
177
+ function indexModelState() {
178
+ const mainNow = buildMain();
179
+ const defenseNow = buildDefense();
180
+ for (const [id, model] of Object.entries(mainNow)) {
181
+ state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
182
+ if (model.modalities.input.includes("image")) {
183
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
184
+ }
172
185
  }
173
- }
174
- for (const [id, model] of Object.entries(defenseModels)) {
175
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
176
- if (model.modalities.input.includes("image")) {
177
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
186
+ for (const [id, model] of Object.entries(defenseNow)) {
187
+ state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
188
+ if (model.modalities.input.includes("image")) {
189
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
190
+ }
178
191
  }
179
192
  }
193
+ indexModelState();
180
194
  const credential = await deps.activeCredential().catch(() => undefined);
181
195
  state.providerToken =
182
196
  tokenFromCredential(credential) ?? (await readCredentialsToken());
183
197
  await registerIntegration(ctx, deps);
184
198
  await ctx.provider.transform((editor) => {
185
- // Rebuilt on every transform so a learned context ceiling applies as soon
186
- // as the response hook records it, without restarting OpenCode.
187
- const active = currentLiveLimits() ?? live;
188
- const buildOptionsNow = { ...buildOptions, live: active };
189
- const mainNow = buildModels(main, candidates, buildOptionsNow);
190
- const defenseNow = buildModels(defense, candidates, buildOptionsNow);
191
- applyProvider(editor, PROVIDER_ID, "Free Pi", mainNow, state.providerToken);
192
- if (includeDefense && defense.length > 0) {
193
- applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", defenseNow, state.providerToken);
199
+ applyProvider(editor, PROVIDER_ID, "Free Pi", buildMain(), state.providerToken);
200
+ if (includeDefense && currentDefense.length > 0) {
201
+ applyProvider(editor, DEFENSE_PROVIDER_ID, "Free Pi Defense", buildDefense(), state.providerToken);
194
202
  }
195
203
  });
196
204
  // The gateway does not publish its context ceiling. Verify the compiled
@@ -199,19 +207,19 @@ async function setup(ctx) {
199
207
  // the largest prompt already accepted in real traffic: it has the most
200
208
  // evidence behind it, so the growth probes describe the window sessions use.
201
209
  if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
202
- const free = main.filter((model) => model.free === true && typeof model.id === "string");
210
+ const free = currentMain.filter((model) => model.free === true && typeof model.id === "string");
203
211
  const probe = free
204
212
  .map((model) => ({
205
213
  id: model.id,
206
214
  seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
207
215
  }))
208
216
  .sort((a, b) => b.seen - a.seen)[0]?.id ??
209
- (catalog?.default_model &&
210
- free.some((model) => model.id === catalog.default_model)
211
- ? catalog.default_model
217
+ (currentCatalog?.default_model &&
218
+ free.some((model) => model.id === currentCatalog?.default_model)
219
+ ? currentCatalog.default_model
212
220
  : undefined) ??
213
221
  free[0]?.id ??
214
- Object.keys(mainModels)[0];
222
+ Object.keys(buildMain())[0];
215
223
  if (probe) {
216
224
  void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
217
225
  }
@@ -220,9 +228,10 @@ async function setup(ctx) {
220
228
  await ctx.model.transform((editor) => {
221
229
  if (editor.default.get())
222
230
  return;
223
- const preferred = (catalog?.default_model && mainModels[catalog.default_model]
224
- ? catalog.default_model
225
- : undefined) ?? Object.keys(mainModels)[0];
231
+ const models = buildMain();
232
+ const preferred = (currentCatalog?.default_model && models[currentCatalog.default_model]
233
+ ? currentCatalog.default_model
234
+ : undefined) ?? Object.keys(models)[0];
226
235
  if (preferred)
227
236
  editor.default.set(PROVIDER_ID, preferred);
228
237
  });
@@ -248,11 +257,61 @@ async function setup(ctx) {
248
257
  }
249
258
  const abort = new AbortController();
250
259
  const eventTask = subscribeEvents(ctx, deps, abort.signal);
251
- log.info(`Loaded ${main.length} free-pi model(s) and ${includeDefense ? defense.length : 0} defense model(s)`, {
252
- defaultModel: catalog?.default_model,
260
+ // A failed catalog fetch registers the provider with zero models, which
261
+ // hides every free-pi entry from the model picker for this location until
262
+ // OpenCode restarts. Retry in the background and re-register the models as
263
+ // soon as the gateway answers, so a transient timeout heals on its own.
264
+ const waitForAbort = (ms) => new Promise((resolve) => {
265
+ if (abort.signal.aborted)
266
+ return resolve();
267
+ const finish = () => {
268
+ clearTimeout(timer);
269
+ abort.signal.removeEventListener("abort", finish);
270
+ resolve();
271
+ };
272
+ const timer = setTimeout(finish, ms);
273
+ abort.signal.addEventListener("abort", finish, { once: true });
274
+ });
275
+ const catalogRecovery = (async () => {
276
+ // Only a missing catalog needs recovery; an empty model list after access
277
+ // filtering means the account cannot use these models, not a timeout.
278
+ if (currentCatalog)
279
+ return;
280
+ for (const delay of CATALOG_RECOVERY_DELAYS_MS) {
281
+ if (abort.signal.aborted || currentMain.length > 0)
282
+ return;
283
+ await waitForAbort(delay);
284
+ if (abort.signal.aborted || currentMain.length > 0)
285
+ return;
286
+ const next = await fetchCatalog(deps).catch(() => undefined);
287
+ if (!next)
288
+ continue;
289
+ const parts = partitionModels(next);
290
+ const accessNow = accountAccess(state.quotaCache?.me);
291
+ const nextMain = filterAccessibleModels(parts.main, accessNow);
292
+ if (nextMain.length === 0)
293
+ continue;
294
+ currentCatalog = next;
295
+ currentMain = nextMain;
296
+ currentDefense = filterAccessibleModels(parts.defense, accessNow);
297
+ indexModelState();
298
+ await ctx.provider.reload().catch(() => undefined);
299
+ await ctx.model.reload().catch(() => undefined);
300
+ log.info(`free-pi catalog recovered; registered ${currentMain.length} model(s)`, {
301
+ defaultModel: currentCatalog?.default_model,
302
+ clientVersion: state.latestClientVersion,
303
+ models: currentMain.map((model) => model.id),
304
+ });
305
+ return;
306
+ }
307
+ log.warn("free-pi catalog stayed unreachable; free-pi models remain unavailable", { attempts: CATALOG_RECOVERY_DELAYS_MS.length });
308
+ })();
309
+ void catalogRecovery.catch(() => undefined);
310
+ log.info(`Loaded ${currentMain.length} free-pi model(s) and ${includeDefense ? currentDefense.length : 0} defense model(s)`, {
311
+ defaultModel: currentCatalog?.default_model,
253
312
  clientVersion: state.latestClientVersion,
254
313
  capabilities: candidates.length,
255
- models: main.map((model) => model.id),
314
+ models: currentMain.map((model) => model.id),
256
315
  });
257
316
  return async () => {
258
317
  abort.abort();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.6.7",
3
+ "version": "0.6.8",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -2,11 +2,14 @@
2
2
 
3
3
  import { resolveToken } from "../auth/token.js";
4
4
  import {
5
+ CATALOG_ATTEMPTS,
6
+ CATALOG_RETRY_MS,
5
7
  CATALOG_TIMEOUT_MS,
6
8
  CATALOG_TTL_MS,
7
9
  } from "../constants.js";
8
10
  import type { Deps } from "../deps.js";
9
11
  import type { Catalog } from "../types.js";
12
+ import { sleep } from "../utils/async.js";
10
13
  import { resolveBaseUrl } from "../utils/urls.js";
11
14
 
12
15
  function isCatalog(value: unknown): value is Catalog {
@@ -43,33 +46,48 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
43
46
  const state = deps.state;
44
47
  if (state.catalogPromise) return state.catalogPromise;
45
48
  const pending = (async () => {
46
- try {
47
- const token = await resolveToken(deps).catch(() => undefined);
48
- const headers: Record<string, string> = {
49
- accept: "application/json",
50
- };
51
- if (token) headers.authorization = `Bearer ${token}`;
52
- const response = await fetch(`${resolveBaseUrl()}/client-version`, {
53
- headers,
54
- signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
55
- });
56
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
57
- const catalog = (await response.json()) as Catalog;
58
- if (!isCatalog(catalog)) {
59
- throw new Error("free-pi returned an unexpected catalog payload");
49
+ let lastError: unknown;
50
+ for (let attempt = 1; attempt <= CATALOG_ATTEMPTS; attempt += 1) {
51
+ try {
52
+ const token = await resolveToken(deps).catch(() => undefined);
53
+ const headers: Record<string, string> = {
54
+ accept: "application/json",
55
+ };
56
+ if (token) headers.authorization = `Bearer ${token}`;
57
+ const response = await fetch(`${resolveBaseUrl()}/client-version`, {
58
+ headers,
59
+ signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
60
+ });
61
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
62
+ const catalog = (await response.json()) as Catalog;
63
+ if (!isCatalog(catalog)) {
64
+ throw new Error("free-pi returned an unexpected catalog payload");
65
+ }
66
+ applyCatalog(deps, catalog);
67
+ return catalog;
68
+ } catch (error) {
69
+ lastError = error;
70
+ // A timeout or a dropped connection is often transient. Retrying here
71
+ // avoids registering a provider with zero models for this location,
72
+ // which would hide every free-pi model from the picker until OpenCode
73
+ // restarts.
74
+ if (attempt < CATALOG_ATTEMPTS) {
75
+ deps.log.info("free-pi catalog request failed; retrying", {
76
+ attempt,
77
+ reason: reasonText(error),
78
+ });
79
+ await sleep(CATALOG_RETRY_MS * attempt);
80
+ }
60
81
  }
61
- applyCatalog(deps, catalog);
62
- return catalog;
63
- } catch (error) {
64
- const cached = state.cachedCatalog;
65
- deps.log.warn(
66
- cached
67
- ? "free-pi catalog is unreachable; using the cached model list"
68
- : "free-pi catalog is unreachable; no free-pi models were registered",
69
- { reason: reasonText(error) },
70
- );
71
- return cached;
72
82
  }
83
+ const cached = state.cachedCatalog;
84
+ deps.log.warn(
85
+ cached
86
+ ? "free-pi catalog is unreachable; using the cached model list"
87
+ : "free-pi catalog is unreachable; no free-pi models were registered",
88
+ { reason: reasonText(lastError) },
89
+ );
90
+ return cached;
73
91
  })();
74
92
  state.catalogPromise = pending;
75
93
  void pending.finally(() => {
package/src/constants.ts CHANGED
@@ -148,6 +148,17 @@ export const CREDITS_PER_USD = 40_000 / 3;
148
148
 
149
149
  export const CATALOG_TTL_MS = 10 * 60_000;
150
150
  export const CATALOG_TIMEOUT_MS = 8_000;
151
+ export const CATALOG_ATTEMPTS = 2;
152
+ export const CATALOG_RETRY_MS = 1_000;
153
+ /**
154
+ * When the catalog cannot be fetched, the provider is registered with no models
155
+ * and the model picker loses every free-pi entry for that location. These are
156
+ * the delays before each background attempt to fetch it again and re-register
157
+ * the models, so a transient timeout heals without restarting OpenCode.
158
+ */
159
+ export const CATALOG_RECOVERY_DELAYS_MS = [
160
+ 2_000, 5_000, 10_000, 20_000, 30_000, 60_000,
161
+ ] as const;
151
162
  export const REGISTRY_TTL_MS = 5 * 60_000;
152
163
  export const REGISTRY_RETRY_MS = 60_000;
153
164
  export const REGISTRY_TIMEOUT_MS = 3_500;
package/src/plugin.ts CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  import { fetchModelsRegistry } from "./catalog/registry.js";
34
34
  import { applyProvider } from "./catalog/v2.js";
35
35
  import {
36
+ CATALOG_RECOVERY_DELAYS_MS,
36
37
  DEFENSE_PROVIDER_ID,
37
38
  PROVIDER_ID,
38
39
  } from "./constants.js";
@@ -184,8 +185,9 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
184
185
  const access = accountAccess(quota?.me);
185
186
  const { main: catalogMain, defense: catalogDefense } =
186
187
  partitionModels(catalog);
187
- const main = filterAccessibleModels(catalogMain, access);
188
- const defense = filterAccessibleModels(catalogDefense, access);
188
+ let currentCatalog = catalog;
189
+ let currentMain = filterAccessibleModels(catalogMain, access);
190
+ let currentDefense = filterAccessibleModels(catalogDefense, access);
189
191
  const candidates = modelRegistryCandidates(registry);
190
192
  const live = await loadLiveLimits();
191
193
  const configuredEffort = ctx.options?.reasoningEffort;
@@ -197,21 +199,37 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
197
199
  ? { reasoningEffort: configuredEffort }
198
200
  : {}),
199
201
  };
200
- const mainModels = buildModels(main, candidates, buildOptions);
201
- const defenseModels = buildModels(defense, candidates, buildOptions);
202
202
 
203
- for (const [id, model] of Object.entries(mainModels)) {
204
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
205
- if (model.modalities.input.includes("image")) {
206
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
203
+ // Rebuilt on every call so a learned context ceiling or a recovered catalog
204
+ // applies without restarting OpenCode.
205
+ const buildMain = () =>
206
+ buildModels(currentMain, candidates, {
207
+ ...buildOptions,
208
+ live: currentLiveLimits() ?? live,
209
+ });
210
+ const buildDefense = () =>
211
+ buildModels(currentDefense, candidates, {
212
+ ...buildOptions,
213
+ live: currentLiveLimits() ?? live,
214
+ });
215
+
216
+ function indexModelState(): void {
217
+ const mainNow = buildMain();
218
+ const defenseNow = buildDefense();
219
+ for (const [id, model] of Object.entries(mainNow)) {
220
+ state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
221
+ if (model.modalities.input.includes("image")) {
222
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
223
+ }
207
224
  }
208
- }
209
- for (const [id, model] of Object.entries(defenseModels)) {
210
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
211
- if (model.modalities.input.includes("image")) {
212
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
225
+ for (const [id, model] of Object.entries(defenseNow)) {
226
+ state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
227
+ if (model.modalities.input.includes("image")) {
228
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
229
+ }
213
230
  }
214
231
  }
232
+ indexModelState();
215
233
 
216
234
  const credential = await deps.activeCredential().catch(() => undefined);
217
235
  state.providerToken =
@@ -220,25 +238,19 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
220
238
  await registerIntegration(ctx, deps);
221
239
 
222
240
  await ctx.provider.transform((editor) => {
223
- // Rebuilt on every transform so a learned context ceiling applies as soon
224
- // as the response hook records it, without restarting OpenCode.
225
- const active = currentLiveLimits() ?? live;
226
- const buildOptionsNow = { ...buildOptions, live: active };
227
- const mainNow = buildModels(main, candidates, buildOptionsNow);
228
- const defenseNow = buildModels(defense, candidates, buildOptionsNow);
229
241
  applyProvider(
230
242
  editor,
231
243
  PROVIDER_ID,
232
244
  "Free Pi",
233
- mainNow,
245
+ buildMain(),
234
246
  state.providerToken,
235
247
  );
236
- if (includeDefense && defense.length > 0) {
248
+ if (includeDefense && currentDefense.length > 0) {
237
249
  applyProvider(
238
250
  editor,
239
251
  DEFENSE_PROVIDER_ID,
240
252
  "Free Pi Defense",
241
- defenseNow,
253
+ buildDefense(),
242
254
  state.providerToken,
243
255
  );
244
256
  }
@@ -250,7 +262,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
250
262
  // the largest prompt already accepted in real traffic: it has the most
251
263
  // evidence behind it, so the growth probes describe the window sessions use.
252
264
  if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
253
- const free = main.filter(
265
+ const free = currentMain.filter(
254
266
  (model) => model.free === true && typeof model.id === "string",
255
267
  );
256
268
  const probe =
@@ -260,12 +272,12 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
260
272
  seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
261
273
  }))
262
274
  .sort((a, b) => b.seen - a.seen)[0]?.id ??
263
- (catalog?.default_model &&
264
- free.some((model) => model.id === catalog.default_model)
265
- ? catalog.default_model
275
+ (currentCatalog?.default_model &&
276
+ free.some((model) => model.id === currentCatalog?.default_model)
277
+ ? currentCatalog.default_model
266
278
  : undefined) ??
267
279
  free[0]?.id ??
268
- Object.keys(mainModels)[0];
280
+ Object.keys(buildMain())[0];
269
281
  if (probe) {
270
282
  void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
271
283
  }
@@ -274,10 +286,11 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
274
286
  // V1 selected the catalog default when the user had no model configured.
275
287
  await ctx.model.transform((editor) => {
276
288
  if (editor.default.get()) return;
289
+ const models = buildMain();
277
290
  const preferred =
278
- (catalog?.default_model && mainModels[catalog.default_model]
279
- ? catalog.default_model
280
- : undefined) ?? Object.keys(mainModels)[0];
291
+ (currentCatalog?.default_model && models[currentCatalog.default_model]
292
+ ? currentCatalog.default_model
293
+ : undefined) ?? Object.keys(models)[0];
281
294
  if (preferred) editor.default.set(PROVIDER_ID, preferred);
282
295
  });
283
296
 
@@ -306,13 +319,65 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
306
319
  const abort = new AbortController();
307
320
  const eventTask = subscribeEvents(ctx, deps, abort.signal);
308
321
 
322
+ // A failed catalog fetch registers the provider with zero models, which
323
+ // hides every free-pi entry from the model picker for this location until
324
+ // OpenCode restarts. Retry in the background and re-register the models as
325
+ // soon as the gateway answers, so a transient timeout heals on its own.
326
+ const waitForAbort = (ms: number) =>
327
+ new Promise<void>((resolve) => {
328
+ if (abort.signal.aborted) return resolve();
329
+ const finish = () => {
330
+ clearTimeout(timer);
331
+ abort.signal.removeEventListener("abort", finish);
332
+ resolve();
333
+ };
334
+ const timer = setTimeout(finish, ms);
335
+ abort.signal.addEventListener("abort", finish, { once: true });
336
+ });
337
+ const catalogRecovery = (async () => {
338
+ // Only a missing catalog needs recovery; an empty model list after access
339
+ // filtering means the account cannot use these models, not a timeout.
340
+ if (currentCatalog) return;
341
+ for (const delay of CATALOG_RECOVERY_DELAYS_MS) {
342
+ if (abort.signal.aborted || currentMain.length > 0) return;
343
+ await waitForAbort(delay);
344
+ if (abort.signal.aborted || currentMain.length > 0) return;
345
+ const next = await fetchCatalog(deps).catch(() => undefined);
346
+ if (!next) continue;
347
+ const parts = partitionModels(next);
348
+ const accessNow = accountAccess(state.quotaCache?.me);
349
+ const nextMain = filterAccessibleModels(parts.main, accessNow);
350
+ if (nextMain.length === 0) continue;
351
+ currentCatalog = next;
352
+ currentMain = nextMain;
353
+ currentDefense = filterAccessibleModels(parts.defense, accessNow);
354
+ indexModelState();
355
+ await ctx.provider.reload().catch(() => undefined);
356
+ await ctx.model.reload().catch(() => undefined);
357
+ log.info(
358
+ `free-pi catalog recovered; registered ${currentMain.length} model(s)`,
359
+ {
360
+ defaultModel: currentCatalog?.default_model,
361
+ clientVersion: state.latestClientVersion,
362
+ models: currentMain.map((model) => model.id),
363
+ },
364
+ );
365
+ return;
366
+ }
367
+ log.warn(
368
+ "free-pi catalog stayed unreachable; free-pi models remain unavailable",
369
+ { attempts: CATALOG_RECOVERY_DELAYS_MS.length },
370
+ );
371
+ })();
372
+ void catalogRecovery.catch(() => undefined);
373
+
309
374
  log.info(
310
- `Loaded ${main.length} free-pi model(s) and ${includeDefense ? defense.length : 0} defense model(s)`,
375
+ `Loaded ${currentMain.length} free-pi model(s) and ${includeDefense ? currentDefense.length : 0} defense model(s)`,
311
376
  {
312
- defaultModel: catalog?.default_model,
377
+ defaultModel: currentCatalog?.default_model,
313
378
  clientVersion: state.latestClientVersion,
314
379
  capabilities: candidates.length,
315
- models: main.map((model) => model.id),
380
+ models: currentMain.map((model) => model.id),
316
381
  },
317
382
  );
318
383