pi-refuseless-tether 0.1.1 → 0.1.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2 - 2026-11-28
4
+
5
+ - Keep the last good model catalog selectable when startup or a background refresh fails or returns an incomplete list.
6
+ - Run `/refuseless refresh` online to accept a validated catalog that drops retired models or reflects changed account access.
7
+
3
8
  ## 0.1.1 - 2026-11-20
4
9
 
5
10
  - Resolve models at startup in restricted Pi children even when the catalog store cannot be written.
package/DETAILS.md CHANGED
@@ -35,9 +35,9 @@ pi --model refuseless/deepseek-v4.1-flash-fast --thinking off
35
35
  pi --list-models refuseless
36
36
  ```
37
37
 
38
- The catalog is fetched with your key from `/v1/models`. It reflects account-specific access and current rates. Pi persists the snapshot in its own model store, so `--offline --list-models refuseless` and `--offline -p` can select cached models. Offline mode disables catalog network activity, **not inference**. A first-ever offline start without a snapshot has no Refuseless models. A failed refresh retains the previous snapshot; a successful empty list clears it. Opening Pi's model picker refreshes through Pi's native catalog path.
38
+ The catalog is fetched with your key from `/v1/models`. It reflects account-specific access and current rates. Pi persists the snapshot in its own model store, so `--offline --list-models refuseless` and `--offline -p` can select cached models. Offline mode disables catalog network activity, **not inference**. A first-ever offline start without a snapshot has no Refuseless models. Startup and background refreshes, including opening Pi's model picker, do not remove known model IDs: a partial response can look just like a retirement. To accept removals, run `/refuseless refresh` in an online Pi session. This explicitly replaces the cache with the account's validated list, even when it is smaller. Request failures, empty lists and malformed or duplicate entries are rejected even on that path; the previous snapshot remains selectable.
39
39
 
40
- On Pi 1.5.2, newly registered providers are restored cache-only before initial model selection. The awaited extension factory therefore primes the catalog once when online, using the selected agent directory's stored API-key credential or environment fallback, and publishes the result through Pi's generation-checked model store. There is no separate catalog cache or periodic timer. Prices can change after a snapshot; refresh the catalog for current rates.
40
+ The extension seeds model selection from Pi's existing snapshot before registration, so startup does not depend on Pi invoking the cache-only refresh callback before lookup. When online it stages a live catalog using the selected agent directory's stored credential or environment fallback. Automatic replacement requires a validated snapshot that includes all known models. Warm startup skips writes for unchanged catalogs. If a concurrent write makes the initial read unreadable, Pi still attempts its normal locked restore. Pi's generation-checked model store owns persistence; there is no second cache or periodic timer. Prices can change after a snapshot; refresh the catalog for current rates.
41
41
 
42
42
  ### Names, images and output limits
43
43
 
@@ -92,4 +92,4 @@ npm run typecheck
92
92
  npm run scan:public
93
93
  ```
94
94
 
95
- Development dependencies are pinned to the versions used for qualification; Pi host packages remain wildcard peer dependencies. Tests cover catalog conversion/persistence, native cost tiers, reasoning clamping/wire payloads, validated login/logout, key-change races, credits, UI hooks, streamed errors, server-directed cancellation and retry-after under both host retry paths.
95
+ Development dependencies are pinned for the unit suite; Pi host packages remain wildcard peer dependencies. To test a real Pi executable against a local catalog with 19 concurrent starts sharing an isolated agent directory, run `node tests/concurrent-startup.mjs "$(command -v pi)" src/index.ts`. Tests cover catalog conversion/persistence, native cost tiers, reasoning clamping/wire payloads, validated login/logout, key-change races, credits, UI hooks, streamed errors, server-directed cancellation and retry-after under both host retry paths.
package/README.md CHANGED
@@ -16,7 +16,7 @@ Choose **Refuseless** in `/model`, or use `pi --list-models refuseless` to see t
16
16
 
17
17
  ## Models, effort, and credits
18
18
 
19
- - **Models come from your account.** Context, image support, pricing, and available reasoning efforts come from the vendor catalog. An existing cached catalog can be used at an offline start; inference still needs network access.
19
+ - **Models come from your account.** Context, image support, pricing, and available reasoning efforts come from the vendor catalog. An existing cached catalog can be used at an offline start; inference still needs network access. To remove retired models or update the list after changing accounts, run `/refuseless refresh` in an online Pi session. A failed refresh leaves the cached list intact.
20
20
  - **Effort follows the selected model.** Shift+Tab cycles the levels the model accepts. Where the model supports `off`, the provider sends it explicitly.
21
21
  - **Costs use the catalog's rates.** Pi accounts for cached input and any reported long-context tier. Missing pricing means the cost is unknown, not that inference is free.
22
22
  - **Credits are visible in Pi.** The footer shows available credit while you're on a Refuseless model. Run `/refuseless` for the balance and current model's prices. A low-credit estimate warns without blocking the request.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-refuseless-tether",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Native Refuseless provider, live model catalog and credits for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/api.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const BASE_URL = "https://api.refuseless.com/v1";
2
- export const USER_AGENT = "pi-refuseless/0.1.1";
2
+ export const USER_AGENT = "pi-refuseless/0.1.2";
3
3
 
4
4
  export function errorText(
5
5
  status: number,
package/src/index.ts CHANGED
@@ -58,8 +58,8 @@ export default async function refuseless(pi: ExtensionAPI) {
58
58
  });
59
59
  let warned = false;
60
60
  pi.registerCommand("refuseless", {
61
- description: "Show Refuseless credits and current model pricing",
62
- async handler(_args, ctx) {
61
+ description: "Show Refuseless credits and prices; /refuseless refresh replaces the model catalog",
62
+ async handler(args, ctx) {
63
63
  const key = await ctx.modelRegistry.getApiKeyForProvider("refuseless");
64
64
  if (!key) {
65
65
  credits.clear();
@@ -71,6 +71,20 @@ export default async function refuseless(pi: ExtensionAPI) {
71
71
  );
72
72
  return;
73
73
  }
74
+ if (args.trim() === "refresh") {
75
+ if (process.env.PI_OFFLINE !== undefined) {
76
+ ctx.ui.notify("Refuseless: catalog refresh requires an online session.", "warning");
77
+ return;
78
+ }
79
+ const result = await ctx.modelRegistry.refresh({
80
+ providers: ["refuseless"], force: true, signal: ctx.signal,
81
+ });
82
+ if (result.aborted) return;
83
+ const error = result.errors.get("refuseless");
84
+ if (error) ctx.ui.notify(`Refuseless catalog unchanged: ${error.message}`, "error");
85
+ else ctx.ui.notify("Refuseless model catalog refreshed.", "info");
86
+ return;
87
+ }
74
88
  if (key !== currentKey) {
75
89
  credits.clear();
76
90
  currentKey = key;
package/src/provider.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { createProvider, type ApiKeyAuth } from "@earendil-works/pi-ai";
1
+ import { createProvider, hasApi, type ApiKeyAuth, type Model, type RefreshModelsContext } from "@earendil-works/pi-ai";
2
2
  import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
3
3
  import { BASE_URL, USER_AGENT, getJson } from "./api.ts";
4
4
  import { readFile } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
+ import { isDeepStrictEqual } from "node:util";
6
7
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
8
  import { catalogModels, type Entry } from "./catalog.ts";
8
9
  import { validateCredits } from "./credits.ts";
@@ -34,21 +35,54 @@ export const apiKeyAuth: ApiKeyAuth = {
34
35
  : undefined;
35
36
  },
36
37
  };
38
+ async function fetchCatalog(key: string, signal?: AbortSignal, baseUrl = BASE_URL) {
39
+ const body = (await getJson("/models", key, signal, baseUrl)) as { data?: Entry[] } | undefined;
40
+ if (!Array.isArray(body?.data))
41
+ throw new Error("Refuseless catalog response has no data array.");
42
+ const models = catalogModels(body.data);
43
+ const ids = new Set(models.map(({ id }) => id));
44
+ if (!models.length || ids.size !== body.data.length)
45
+ throw new Error("Refuseless catalog response is empty, malformed or has duplicate model IDs.");
46
+ return { models, ids, checkedAt: Date.now() };
47
+ }
48
+
49
+ const providerId = "refuseless";
50
+
51
+ function ownModels(models: NonNullable<RefreshModelsContext["stored"]>["models"]) {
52
+ return models.filter((model): model is Model<"openai-completions"> =>
53
+ model?.provider === providerId && typeof model.id === "string" && hasApi(model, "openai-completions"),
54
+ );
55
+ }
56
+
57
+ async function readStartupModels(agentDir: string) {
58
+ try {
59
+ // Pi can reach model selection without invoking refreshModels. Seed selection
60
+ // from its existing snapshot; a concurrent in-place write can make this read
61
+ // fail, so Pi's locked restore still runs normally. Never write this file here.
62
+ const file = await readFile(join(agentDir, "models-store.json"), "utf8");
63
+ const entry = JSON.parse(file.replace(/^\uFEFF/, ""))?.[providerId];
64
+ return Array.isArray(entry?.models) ? ownModels(entry.models) : [];
65
+ } catch {
66
+ return [];
67
+ }
68
+ }
69
+
37
70
  export async function refuselessProvider() {
38
- // Pi 1.5.2 restores registered providers cache-only before initial model selection.
39
- // Prime the native provider during its awaited factory, then publish through Pi's store.
40
- // Read credentials only from the selected agent dir; never write/copy them ourselves.
71
+ const agentDir = getAgentDir();
72
+ const startupModels = await readStartupModels(agentDir);
73
+ // Stage discovery in the awaited factory, with only the selected directory's
74
+ // credential or environment fallback. Pi still owns publication and storage.
41
75
  let key = process.env.REFUSELESS_API_KEY?.trim();
42
76
  try {
43
77
  const stored = JSON.parse(
44
- await readFile(join(getAgentDir(), "auth.json"), "utf8"),
78
+ await readFile(join(agentDir, "auth.json"), "utf8"),
45
79
  ).refuseless;
46
80
  if (stored?.type === "api_key" && typeof stored.key === "string")
47
81
  key = stored.key.trim() || key;
48
82
  } catch {
49
83
  /* Pi reports credential-store errors; an explicit env fallback still works. */
50
84
  }
51
- let primed: ReturnType<typeof catalogModels> | undefined;
85
+ let primed: Awaited<ReturnType<typeof fetchCatalog>> | undefined;
52
86
  if (
53
87
  key &&
54
88
  !["1", "true", "yes"].includes(
@@ -57,71 +91,68 @@ export async function refuselessProvider() {
57
91
  !process.argv.includes("--offline")
58
92
  ) {
59
93
  try {
60
- const body = (await getJson("/models", key)) as { data: Entry[] };
61
- primed = catalogModels(body.data);
94
+ primed = await fetchCatalog(key);
62
95
  } catch {
63
96
  /* Native stored catalog remains usable when the service is unreachable. */
64
97
  }
65
98
  }
66
- const provider = createProvider({
67
- id: "refuseless",
99
+ const provider = createProvider<"openai-completions">({
100
+ id: providerId,
68
101
  name: "Refuseless",
69
102
  baseUrl: BASE_URL,
70
103
  headers: { "User-Agent": USER_AGENT },
71
104
  auth: { apiKey: apiKeyAuth },
72
105
  models: [],
73
106
  api: withRetryAfter(openAICompletionsApi()),
74
- async fetchModels(context) {
75
- const key =
76
- context.credential?.type === "api_key"
77
- ? context.credential.key
78
- : undefined;
79
- if (!key) return context.stored?.models ?? [];
80
- const body = (await getJson(
81
- "/models",
82
- key,
83
- context.signal,
84
- context.baseUrl ?? BASE_URL,
85
- )) as { data?: Entry[] };
86
- if (!Array.isArray(body?.data))
87
- throw new Error("Refuseless catalog response has no data array.");
88
- return catalogModels(body.data);
89
- },
90
107
  });
91
- const primedAt = Date.now();
92
- const refresh = provider.refreshModels!;
108
+ let selected: ReturnType<typeof provider.getModels> = startupModels.length ? startupModels : primed?.models ?? [];
109
+ provider.getModels = provider.getAllModels = () => selected;
93
110
  provider.refreshModels = async (context) => {
94
- // Reuse createProvider's transactional restore/persist behavior with the already fetched data.
95
- if (
96
- primed !== undefined &&
97
- !context.allowNetwork &&
98
- (context.stored?.checkedAt ?? 0) <= primedAt
99
- ) {
100
- const snapshot = primed;
101
- await refresh({
102
- ...context,
103
- stored: { models: snapshot, checkedAt: primedAt },
104
- allowNetwork: false,
105
- publish: async (publication) => {
106
- let accepted: boolean;
107
- try {
108
- accepted = await context.publish({
109
- ...publication,
110
- persist: { models: snapshot, checkedAt: primedAt },
111
- });
112
- } catch (error) {
113
- // Pi persists before applying the update. A read-only store must
114
- // not prevent a child from using the catalog it just fetched.
115
- const code = (error as NodeJS.ErrnoException | undefined)?.code;
116
- if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
117
- throw error;
118
- accepted = await context.publish(publication);
119
- }
120
- if (accepted) primed = undefined;
121
- return accepted;
122
- },
123
- });
124
- } else await refresh(context);
111
+ const { stored, publish, signal, allowNetwork, credential } = context;
112
+ if (signal.aborted) return;
113
+ if (stored) {
114
+ // A later restore must not shrink a catalog already in use in this process.
115
+ const known = new Map(selected.map((model) => [model.id, model]));
116
+ for (const model of ownModels(stored.models)) known.set(model.id, model);
117
+ if (!(await publish({ update: () => { selected = [...known.values()]; } })))
118
+ return;
119
+ }
120
+
121
+ const fromPrime = !allowNetwork;
122
+ const key = credential?.type === "api_key" ? credential.key : undefined;
123
+ const candidate = fromPrime
124
+ ? primed
125
+ : key ? await fetchCatalog(key, signal, context.baseUrl) : undefined;
126
+ if (!candidate || signal.aborted) return;
127
+ if (fromPrime && (stored?.checkedAt ?? 0) > candidate.checkedAt) return;
128
+ // Only an explicit network refresh can treat a validated smaller list as authoritative.
129
+ const forced = allowNetwork && context.force === true;
130
+ if (!forced && selected.some(({ id }) => !candidate.ids.has(id))) {
131
+ if (fromPrime) {
132
+ primed = undefined;
133
+ return;
134
+ }
135
+ throw new Error("Refuseless catalog response is missing previously known models.");
136
+ }
137
+
138
+ const { models, checkedAt } = candidate;
139
+ if (fromPrime && stored && isDeepStrictEqual(stored.models, models)) {
140
+ // Warm starts do not contend for a write just to advance the timestamp.
141
+ primed = undefined;
142
+ return;
143
+ }
144
+ const update = () => { selected = models; };
145
+ let accepted: boolean;
146
+ try {
147
+ accepted = await publish({ persist: { models, checkedAt }, update });
148
+ } catch (error) {
149
+ // A forced replacement must stay replaced on the next restore. If Pi
150
+ // cannot write it, leave both catalogs alone and surface the error.
151
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
152
+ if (forced || (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")) throw error;
153
+ accepted = await publish({ update });
154
+ }
155
+ if (accepted) primed = undefined;
125
156
  };
126
157
  return provider;
127
158
  }