@eduardo191labs/opencode-free-pi 0.7.25 → 0.7.27

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.
@@ -1,30 +1,14 @@
1
1
  /**
2
- * Transparently replays a free-pi request that hit the per-session
3
- * `429 concurrent` limit.
2
+ * Keeps the outgoing request body around for diagnostics and overflow sizing.
4
3
  *
5
- * OpenCode builds the provider request once and reuses it for every retry of a
6
- * step (`SessionRunner.runStep` calls `request.primary` outside the attempt
7
- * loop). Rotating `x-session-id` in the retry hook therefore cannot help the
8
- * failed attempt: the retried request still carries the old id. The server can
9
- * also leave a session slot locked after an aborted stream, which resets do not
10
- * clear.
11
- *
12
- * Replaying from `http.response` instead sends the same body with a fresh wire
13
- * session id and returns the good response to OpenCode, so the turn continues
14
- * without a visible "Retrying…" or a failed step.
4
+ * The plugin never re-sends a request on its own: doing that ran the same
5
+ * prompt (and its tool calls) twice for one user turn. Retries belong to
6
+ * OpenCode's runner, which only retries after a failed attempt, and the wire
7
+ * session id is rotated in the retry hook so that retry reaches a free slot.
15
8
  */
16
- import { closeFreePiSession } from "../api/session.js";
17
- import { overflowCodeOf } from "../errors/limit.js";
18
- import { sleep, trimMap } from "../utils/async.js";
19
- import { profileRequest, SPURIOUS_OVERFLOW_TOKENS, } from "./overflow.js";
9
+ import { trimMap } from "../utils/async.js";
20
10
  import { traceRequestBody } from "./trace.js";
21
- import { rotateWireSessionID, wireSessionID } from "./wire.js";
22
11
  const REPLAY_BODY_LIMIT = 24;
23
- const REPLAY_MAX_ATTEMPTS = 4;
24
- const REPLAY_BASE_DELAY_MS = 400;
25
- const REPLAY_MAX_DELAY_MS = 3_000;
26
- /** A rejected request that fits is retried only this many times on fresh ids. */
27
- const OVERFLOW_REPLAY_ATTEMPTS = 2;
28
12
  function requestKey(sessionID, request) {
29
13
  const turn = request.headers.get("x-turn-id") ?? "";
30
14
  return `${sessionID}\u0000${turn}\u0000${request.url}`;
@@ -32,7 +16,7 @@ function requestKey(sessionID, request) {
32
16
  function isJson(request) {
33
17
  return (request.headers.get("content-type") ?? "").includes("json");
34
18
  }
35
- /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
19
+ /** Keeps the body around so an overflow can be sized after fetch consumed it. */
36
20
  export async function rememberReplayBody(deps, event) {
37
21
  const request = event?.request;
38
22
  if (!(request instanceof Request) || !isJson(request) || !event.sessionID)
@@ -48,20 +32,11 @@ export async function rememberReplayBody(deps, event) {
48
32
  traceRequestBody(deps, event.sessionID, body, request.headers);
49
33
  }
50
34
  catch {
51
- // A non-replayable body simply falls back to the normal retry hook.
35
+ // A body that cannot be read simply has no overflow size to measure.
52
36
  }
53
37
  }
54
- async function isConcurrent(response) {
55
- if (response.status !== 429)
56
- return false;
57
- const body = await response
58
- .clone()
59
- .text()
60
- .catch(() => "");
61
- return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
62
- }
63
38
  /** The request body, either remembered before the send or re-read from it. */
64
- async function storedBody(deps, event) {
39
+ export async function storedBody(deps, event) {
65
40
  const request = event?.request;
66
41
  if (!(request instanceof Request) || !event.sessionID)
67
42
  return;
@@ -75,117 +50,3 @@ async function storedBody(deps, event) {
75
50
  .text()
76
51
  .catch(() => undefined);
77
52
  }
78
- function concurrentDelay(attempt) {
79
- return Math.min(REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1), REPLAY_MAX_DELAY_MS);
80
- }
81
- /**
82
- * Returns a replacement response when a concurrent 429 was recovered, or
83
- * `undefined` to leave the original response untouched.
84
- */
85
- export async function replayConcurrentResponse(deps, event) {
86
- const original = event?.response;
87
- const request = event?.request;
88
- if (!(original instanceof Response) || !(request instanceof Request))
89
- return;
90
- if (request.signal.aborted)
91
- return;
92
- if (!(await isConcurrent(original)))
93
- return;
94
- const body = await storedBody(deps, event);
95
- if (!body) {
96
- deps.log.warn("free-pi session busy but the request body was not available to replay", { sessionID: event.sessionID });
97
- return;
98
- }
99
- let previous = request.headers.get("x-session-id") ??
100
- wireSessionID(deps, event.sessionID);
101
- for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
102
- if (request.signal.aborted)
103
- return;
104
- if (attempt > 1)
105
- await sleep(concurrentDelay(attempt));
106
- const next = rotateWireSessionID(deps, event.sessionID);
107
- if (previous && previous !== next) {
108
- void closeFreePiSession(deps, previous).catch(() => undefined);
109
- }
110
- previous = next;
111
- const headers = new Headers(request.headers);
112
- headers.set("x-session-id", next);
113
- headers.delete("content-length");
114
- headers.delete("host");
115
- const response = await fetch(request.url, {
116
- method: request.method,
117
- headers,
118
- body,
119
- signal: request.signal,
120
- }).catch(() => undefined);
121
- if (!response)
122
- continue;
123
- if (!(await isConcurrent(response))) {
124
- deps.log.info("free-pi session busy; replayed the request with a fresh session id", {
125
- sessionID: event.sessionID,
126
- from: request.headers.get("x-session-id") ?? undefined,
127
- to: next,
128
- attempt,
129
- });
130
- return response;
131
- }
132
- }
133
- return undefined;
134
- }
135
- /**
136
- * Retries an overflow rejection whose request plainly fits the model window.
137
- *
138
- * free-pi reports `context_ceiling`/`context_too_long` from the upstream
139
- * model, and a failing gateway can report them for a small prompt. Compacting
140
- * cannot fix that: the summary is accepted, the next turn is rejected the same
141
- * way, and the runner compacts again. A fresh wire session is the cheapest
142
- * recovery, so a small request is replayed on one before the overflow is
143
- * handed to the runner.
144
- */
145
- export async function replaySpuriousOverflow(deps, event) {
146
- const original = event?.response;
147
- const request = event?.request;
148
- if (!(original instanceof Response) || !(request instanceof Request))
149
- return {};
150
- if (request.signal.aborted)
151
- return {};
152
- if (!(await overflowCodeOf(original)))
153
- return {};
154
- const body = await storedBody(deps, event);
155
- if (!body)
156
- return {};
157
- const profile = profileRequest(body);
158
- const tokens = profile.tokens;
159
- const facts = { model: profile.model, hasMedia: profile.hasMedia };
160
- if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
161
- return { tokens, ...facts, spurious: false };
162
- }
163
- let previous = request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
164
- for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
165
- if (request.signal.aborted)
166
- return { tokens, ...facts, spurious: true };
167
- const next = rotateWireSessionID(deps, event.sessionID);
168
- if (previous && previous !== next) {
169
- void closeFreePiSession(deps, previous).catch(() => undefined);
170
- }
171
- previous = next;
172
- const headers = new Headers(request.headers);
173
- headers.set("x-session-id", next);
174
- headers.delete("content-length");
175
- headers.delete("host");
176
- const response = await fetch(request.url, {
177
- method: request.method,
178
- headers,
179
- body,
180
- signal: request.signal,
181
- }).catch(() => undefined);
182
- if (!response)
183
- continue;
184
- if (!(await overflowCodeOf(response))) {
185
- deps.log.info("free-pi rejected a request that fits as too long; replayed it on a fresh session id", { sessionID: event.sessionID, tokens, to: next, attempt });
186
- return { tokens, ...facts, spurious: true, response };
187
- }
188
- }
189
- deps.log.info("free-pi keeps rejecting a request that fits as too long; the provider is failing", { sessionID: event.sessionID, tokens });
190
- return { tokens, ...facts, spurious: true };
191
- }
@@ -4,7 +4,6 @@
4
4
  *
5
5
  * - `x-freepi-tool-meta: v1:<id>~<ms>~<exit>~<truncated>,...`
6
6
  * - `x-freepi-tool-errors: v1:<ids>` (`v1x:` once old IDs were evicted)
7
- * - `x-freepi-compacted: v1:<dropped messages>` on the request after compaction
8
7
  */
9
8
  import type { Deps } from "../deps.js";
10
9
  /**
@@ -31,11 +30,7 @@ type ToolEnd = {
31
30
  export declare function isFreePiSession(deps: Deps, sessionID: string): boolean;
32
31
  export declare function recordToolStart(deps: Deps, sessionID: string, id: string): void;
33
32
  export declare function recordToolEnd(deps: Deps, sessionID: string, end: ToolEnd): void;
34
- export declare function recordCompaction(deps: Deps, sessionID: string, droppedMessages: number): void;
35
- /**
36
- * Headers for the outgoing request. `consumeCompacted` is false for the
37
- * compaction request itself so the marker lands on the request that follows.
38
- */
39
- export declare function toolHeaders(deps: Deps, sessionID: string, consumeCompacted: boolean): Record<string, string>;
33
+ /** Headers for the outgoing request, describing the tools this turn ran. */
34
+ export declare function toolHeaders(deps: Deps, sessionID: string): Record<string, string>;
40
35
  export declare function forgetToolStats(deps: Deps, sessionID: string): void;
41
36
  export {};
@@ -4,9 +4,8 @@
4
4
  *
5
5
  * - `x-freepi-tool-meta: v1:<id>~<ms>~<exit>~<truncated>,...`
6
6
  * - `x-freepi-tool-errors: v1:<ids>` (`v1x:` once old IDs were evicted)
7
- * - `x-freepi-compacted: v1:<dropped messages>` on the request after compaction
8
7
  */
9
- import { COMPACTED_HEADER, DEFENSE_PROVIDER_ID, PROVIDER_ID, TOOL_ERRORS_HEADER, TOOL_ID_LIMIT, TOOL_META_BUDGET, TOOL_META_HEADER, } from "../constants.js";
8
+ import { DEFENSE_PROVIDER_ID, PROVIDER_ID, TOOL_ERRORS_HEADER, TOOL_ID_LIMIT, TOOL_META_BUDGET, TOOL_META_HEADER, } from "../constants.js";
10
9
  import { trimMap } from "../utils/async.js";
11
10
  const ID_PATTERN = /^[\w.:-]{1,100}$/;
12
11
  const MAX_ENTRY_LENGTH = 150;
@@ -47,7 +46,6 @@ function statsFor(deps, sessionID) {
47
46
  failed: [],
48
47
  evicted: false,
49
48
  started: new Map(),
50
- compacted: 0,
51
49
  };
52
50
  trimMap(deps.state.toolStats, 200);
53
51
  deps.state.toolStats.set(sessionID, stats);
@@ -104,26 +102,13 @@ export function recordToolEnd(deps, sessionID, end) {
104
102
  stats.failed.shift();
105
103
  stats.evicted = true;
106
104
  }
107
- export function recordCompaction(deps, sessionID, droppedMessages) {
108
- if (!isFreePiSession(deps, sessionID) || droppedMessages <= 0)
109
- return;
110
- const stats = statsFor(deps, sessionID);
111
- stats.compacted += droppedMessages;
112
- }
113
- /**
114
- * Headers for the outgoing request. `consumeCompacted` is false for the
115
- * compaction request itself so the marker lands on the request that follows.
116
- */
117
- export function toolHeaders(deps, sessionID, consumeCompacted) {
105
+ /** Headers for the outgoing request, describing the tools this turn ran. */
106
+ export function toolHeaders(deps, sessionID) {
118
107
  const stats = deps.state.toolStats.get(sessionID);
119
108
  const headers = {};
120
109
  if (stats?.meta.length) {
121
110
  headers[TOOL_META_HEADER] = `v1:${stats.meta.join(",")}`;
122
111
  }
123
- if (stats && consumeCompacted && stats.compacted > 0) {
124
- headers[COMPACTED_HEADER] = `v1:${stats.compacted}`;
125
- stats.compacted = 0;
126
- }
127
112
  headers[TOOL_ERRORS_HEADER] = `${stats?.evicted ? "v1x" : "v1"}:${(stats?.failed ?? []).join(",")}`;
128
113
  return headers;
129
114
  }
@@ -118,6 +118,5 @@ function headerTrace(headers) {
118
118
  xAdUserStart: adUserStart,
119
119
  xSubagent: headers.get("x-freepi-subagent") ?? "",
120
120
  xToolMeta: headers.get("x-freepi-tool-meta") ?? "",
121
- xCompacted: headers.get("x-freepi-compacted") ?? "",
122
121
  };
123
122
  }
package/dist/state.d.ts CHANGED
@@ -13,9 +13,6 @@ export type RuntimeState = {
13
13
  lastCatalogNotice?: string;
14
14
  lastQuotaNotice?: string;
15
15
  catalogModels: Catalog;
16
- outputLimits: Map<string, number>;
17
- /** Advertised context window per `provider/model`, for request trimming. */
18
- contextLimits: Map<string, number>;
19
16
  /** `provider/model` ids whose upstream accepts image input. */
20
17
  imageModels: Set<string>;
21
18
  quotaCache?: QuotaSnapshot;
package/dist/state.js CHANGED
@@ -7,8 +7,6 @@ export function createRuntimeState() {
7
7
  cachedRegistryAt: 0,
8
8
  registryAttemptAt: 0,
9
9
  catalogModels: {},
10
- outputLimits: new Map(),
11
- contextLimits: new Map(),
12
10
  imageModels: new Set(),
13
11
  lastQuotaRefreshAt: 0,
14
12
  lastErrorLogAt: 0,
@@ -44,6 +44,7 @@ const ERROR_TEXT = {
44
44
  rate_limited: "Another image question is already running or requests are too frequent. Do not call look_at_image again in this turn unless the user asks.",
45
45
  not_configured: "Image understanding is not available on this server. Do not call look_at_image again in this session.",
46
46
  upstream_error: "The vision provider failed. You may retry once.",
47
+ image_screen_unavailable: "Image checking is unavailable right now (the server said so itself). Wait a moment and try once more; if it fails again, continue without this tool.",
47
48
  account_review: "This account is under review, so image understanding is disabled. Do not retry; tell the user and continue without it.",
48
49
  invalid_request: "The server rejected this image or question. Do not retry the same call; check the file is a valid PNG, JPEG or WebP under 5 MB.",
49
50
  };
package/dist/types.d.ts CHANGED
@@ -15,6 +15,8 @@ export type CatalogModel = {
15
15
  display_name?: string;
16
16
  section?: string;
17
17
  tier?: "regular" | "premium";
18
+ /** Billing lane: `free`, `free_unlimited` or `premium_only`. */
19
+ access?: string;
18
20
  input_credits_per_mtok?: number;
19
21
  output_credits_per_mtok?: number;
20
22
  cache_read_credits_per_mtok?: number;
@@ -92,6 +94,11 @@ export type Catalog = {
92
94
  default_model?: string;
93
95
  notice?: string;
94
96
  models?: CatalogModel[];
97
+ /** The gateway's suggested split for fusion-style two-model workflows. */
98
+ fusion?: {
99
+ planner?: string;
100
+ executor?: string;
101
+ } & Record<string, unknown>;
95
102
  };
96
103
  /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
97
104
  export type ModelDefinition = {
@@ -166,6 +173,8 @@ export type MeResponse = {
166
173
  premium_get_line?: string;
167
174
  guest?: boolean;
168
175
  visible_allowance?: boolean;
176
+ return_bonus?: Record<string, unknown> | null;
177
+ streak?: Record<string, unknown> | null;
169
178
  earn_reward?: Record<string, unknown> | null;
170
179
  slow_tier?: Record<string, unknown>;
171
180
  };
@@ -255,7 +264,6 @@ export type ToolStats = {
255
264
  failed: string[];
256
265
  evicted: boolean;
257
266
  started: Map<string, number>;
258
- compacted: number;
259
267
  };
260
268
  export type TokenUsageLike = {
261
269
  input?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.25",
3
+ "version": "0.7.27",
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/catalog.mjs && node test/diet.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/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs && node test/slots.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/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs && node test/slots.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -264,7 +264,10 @@ async function sendProbe(
264
264
  "content-type": "application/json",
265
265
  authorization: `Bearer ${token}`,
266
266
  "x-client-version": deps.state.latestClientVersion,
267
- "x-session-id": `free-pi-window-${Date.now().toString(36)}`,
267
+ "x-session-id": `free-pi-window-${Date.now().toString(36)}-${Math
268
+ .random()
269
+ .toString(36)
270
+ .slice(2, 8)}`,
268
271
  "x-ad-context": "none",
269
272
  },
270
273
  body: JSON.stringify({
@@ -343,6 +346,16 @@ async function commitWindow(
343
346
  modelID: string,
344
347
  ): Promise<number> {
345
348
  const limits = (cached ??= emptyLimits());
349
+ // The measured ceiling belongs to the model probed, not to every model: the
350
+ // gateway's limit is per model, and a global window taken from one model
351
+ // would advertise capacity another one rejects. The per-model value is what
352
+ // `buildModels` reads for that model; the global window stays as the
353
+ // fallback for models never probed.
354
+ const entry = observation(modelID);
355
+ if ((entry.maxPromptTokens ?? 0) < tokens) {
356
+ entry.maxPromptTokens = tokens;
357
+ entry.updatedAt = Date.now();
358
+ }
346
359
  if (limits.window && limits.window.tokens >= tokens) return limits.window.tokens;
347
360
  limits.window = { tokens, verifiedAt: Date.now(), model: modelID };
348
361
  loaded = true;
@@ -233,7 +233,7 @@ export function isReasoningEffort(value: unknown): value is string {
233
233
  /**
234
234
  * The effort sent when no variant is selected. `false` leaves the gateway's
235
235
  * own default untouched; otherwise the catalog's supported levels win over
236
- * `medium`, so a model that only accepts `low`/`high` never gets an effort it
236
+ * `high`, so a model that only accepts `low`/`high` never gets an effort it
237
237
  * would reject.
238
238
  */
239
239
  export function preferredReasoningEffort(
@@ -243,9 +243,26 @@ export function preferredReasoningEffort(
243
243
  if (configured === false) return undefined;
244
244
  if (configured) return configured;
245
245
  // The provider CLI's levels are the source of truth: models.dev often lists
246
- // only a subset, but the gateway accepts the CLI set. `medium` is the sane
247
- // middle ground between the CLI's off default and burning tokens on `high`.
246
+ // only a subset, but the gateway accepts the CLI set. A catalog that lists
247
+ // explicit effort options gets the highest one it lists (a budget-style
248
+ // catalog maps to `high`, the closest explicit level to a token budget);
249
+ // everything else gets the plugin default (`max`), which thinks longest.
248
250
  if (options?.some((option) => option.type === "budget_tokens")) return "high";
251
+ const listed = options
252
+ ?.flatMap((option) =>
253
+ option.type === "effort" && Array.isArray(option.values) ? option.values : [],
254
+ )
255
+ .filter((value) => (REASONING_EFFORTS as readonly string[]).includes(value));
256
+ if (listed && listed.length > 0) {
257
+ return listed.reduce(
258
+ (best, value) =>
259
+ (REASONING_EFFORTS as readonly string[]).indexOf(value) >
260
+ (REASONING_EFFORTS as readonly string[]).indexOf(best)
261
+ ? value
262
+ : best,
263
+ listed[0]!,
264
+ );
265
+ }
249
266
  return DEFAULT_REASONING_EFFORT;
250
267
  }
251
268
 
@@ -300,6 +317,14 @@ export function accountAccess(me: MeResponse | undefined): AccountAccess | undef
300
317
  }
301
318
 
302
319
  function isPremiumModel(model: CatalogModel): boolean {
320
+ // The catalog's `access` field is the authoritative lane. `premium_only`
321
+ // means exactly what the name says; before the field existed the only clues
322
+ // were `tier`, the note and the "at capacity" label, and a curl_cffi probe
323
+ // showed those missed 18 of the 19 premium-only models (no tier, empty note,
324
+ // plain "~Nx usage" names). Keep the old heuristics for catalogs that still
325
+ // omit `access`.
326
+ if (model.access === "premium_only") return true;
327
+ if (model.access === "free" || model.access === "free_unlimited") return false;
303
328
  if (model.tier === "premium") return true;
304
329
  if (/premium\s+credits/i.test(model.note ?? "")) return true;
305
330
  // The catalog labels every model the free lane cannot take with "at capacity
package/src/constants.ts CHANGED
@@ -8,9 +8,19 @@ export const PROVIDER_NAME = "Free Pi";
8
8
  export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
9
9
 
10
10
  export const DEFAULT_BASE_URL = "https://api.freepi.ai";
11
- export const DEFAULT_CLIENT_VERSION = "0.6.25";
11
+ export const DEFAULT_CLIENT_VERSION = "0.6.28";
12
12
  export const CONSENT_VERSION = "4";
13
13
 
14
+ /**
15
+ * The model a fresh session gets when the user has not chosen one. The
16
+ * catalog's own `default_model` points at the fastest cheap model, which is
17
+ * right for the phone app but wrong for coding work: an unset effort makes the
18
+ * free models answer before they think. `glm-5.3-flash` reasons longest of the
19
+ * free models, so it is the better default here; the catalog default stays the
20
+ * fallback when this id ever disappears.
21
+ */
22
+ export const DEFAULT_FREE_MODEL_ID = "glm-5.3-flash";
23
+
14
24
  /**
15
25
  * The provider CLI's window. The gateway enforces its own ceiling but does not
16
26
  * publish it, so this is the starting point; `verifyGatewayWindow` replaces it
@@ -20,15 +30,6 @@ export const CONTEXT_WINDOW = 200_000;
20
30
  /** Largest window the plugin will ever advertise after measuring the gateway. */
21
31
  export const MAX_CONTEXT_WINDOW = 1_000_000;
22
32
  export const MAX_OUTPUT_TOKENS = 32_768;
23
- /**
24
- * Share of the advertised window a primary request may occupy before stale
25
- * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
26
- * and the free models then lose the middle of the conversation even though the
27
- * gateway still accepts them.
28
- */
29
- export const CONTEXT_DIET_SHARE = 0.4;
30
- /** Below this window the diet is pointless: the request is small anyway. */
31
- export const CONTEXT_DIET_MIN_TOKENS = 24_000;
32
33
  /**
33
34
  * Upper bound for a model that publishes a larger output budget. Reasoning
34
35
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -53,10 +54,13 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
53
54
  * dozen reasoning tokens even on tasks that need planning. The gateway accepts
54
55
  * every level (measured with curl_cffi) but currently does not let the level
55
56
  * change how long the upstream thinks, so the plugin also asks for explicit
56
- * step-by-step checking in the prompt and defaults to `high`. `none`/`minimal`
57
- * stay one pick away when speed matters more than care.
57
+ * step-by-step checking in the prompt and defaults to `max`. The gateway
58
+ * accepts every level (measured with curl_cffi) and the reasoning_tokens in
59
+ * the usage response vary with the level, so `max` is the level that thinks
60
+ * longest. `none`/`minimal` stay one pick away when speed matters more than
61
+ * care.
58
62
  */
59
- export const DEFAULT_REASONING_EFFORT = "high";
63
+ export const DEFAULT_REASONING_EFFORT = "max";
60
64
  export const REASONING_EFFORTS = [
61
65
  "none",
62
66
  "minimal",
@@ -106,7 +110,6 @@ export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
106
110
  /** Tool outcome headers emitted by the free-pi provider CLI. */
107
111
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
108
112
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
109
- export const COMPACTED_HEADER = "x-freepi-compacted";
110
113
  export const TOOL_META_BUDGET = 1_500;
111
114
  export const TOOL_ID_LIMIT = 50;
112
115
 
@@ -114,7 +117,9 @@ export const SESSION_TRACK_LIMIT = 200;
114
117
  export const AUTH_SKEW_MS = 60_000;
115
118
  export const AUTH_TIMEOUT_MS = 15 * 60_000;
116
119
  export const AUTH_NETWORK_FAILURES = 6;
117
- export const DEFAULT_TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60_000;
120
+ /** Fallback token lifetime when the JWT carries no `exp`. Measured free-pi
121
+ * tokens live 90 days; this fallback only applies when the header is missing. */
122
+ export const DEFAULT_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60_000;
118
123
  export const REFRESH_PREFIX = "free-pi:v1:";
119
124
 
120
125
  export const AD_CONTEXT_MAX_CHARS = 1_000;
package/src/plugin.ts CHANGED
@@ -16,12 +16,6 @@ import { closeFreePiSession } from "./api/session.js";
16
16
  import { readCredentialsToken } from "./auth/credentials.js";
17
17
  import { tokenFromCredential } from "./auth/credential.js";
18
18
  import { fetchCatalog } from "./catalog/catalog.js";
19
- import {
20
- currentLiveLimits,
21
- loadLiveLimits,
22
- shouldVerifyWindow,
23
- verifyGatewayWindow,
24
- } from "./catalog/live.js";
25
19
  import {
26
20
  accountAccess,
27
21
  buildModels,
@@ -36,6 +30,7 @@ import {
36
30
  CATALOG_RECOVERY_DELAYS_MS,
37
31
  CATALOG_RECOVERY_INTERVAL_MS,
38
32
  CATALOG_RECOVERY_LOG_EVERY,
33
+ DEFAULT_FREE_MODEL_ID,
39
34
  DEFENSE_PROVIDER_ID,
40
35
  PROVIDER_ID,
41
36
  } from "./constants.js";
@@ -197,10 +192,8 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
197
192
  let currentMain = filterAccessibleModels(catalogMain, access);
198
193
  let currentDefense = filterAccessibleModels(catalogDefense, access);
199
194
  const candidates = modelRegistryCandidates(registry);
200
- const live = await loadLiveLimits();
201
195
  const configuredEffort = ctx.options?.reasoningEffort;
202
196
  const buildOptions = {
203
- live,
204
197
  ...(configuredEffort === false
205
198
  ? { reasoningEffort: false as const }
206
199
  : isReasoningEffort(configuredEffort)
@@ -220,38 +213,28 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
220
213
  return kept;
221
214
  };
222
215
 
223
- // Rebuilt on every call so a learned context ceiling or a recovered catalog
224
- // applies without restarting OpenCode.
216
+ // Rebuilt on every call so a recovered catalog or a refreshed quota applies
217
+ // without restarting OpenCode.
225
218
  const buildMain = () =>
226
219
  withoutDenied(
227
220
  PROVIDER_ID,
228
- buildModels(currentMain, candidates, {
229
- ...buildOptions,
230
- live: currentLiveLimits() ?? live,
231
- }),
221
+ buildModels(currentMain, candidates, buildOptions),
232
222
  );
233
223
  const buildDefense = () =>
234
224
  withoutDenied(
235
225
  DEFENSE_PROVIDER_ID,
236
- buildModels(currentDefense, candidates, {
237
- ...buildOptions,
238
- live: currentLiveLimits() ?? live,
239
- }),
226
+ buildModels(currentDefense, candidates, buildOptions),
240
227
  );
241
228
 
242
229
  function indexModelState(): void {
243
230
  const mainNow = buildMain();
244
231
  const defenseNow = buildDefense();
245
232
  for (const [id, model] of Object.entries(mainNow)) {
246
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
247
- state.contextLimits.set(`${PROVIDER_ID}/${id}`, model.limit.context);
248
233
  if (model.modalities.input.includes("image")) {
249
234
  state.imageModels.add(`${PROVIDER_ID}/${id}`);
250
235
  }
251
236
  }
252
237
  for (const [id, model] of Object.entries(defenseNow)) {
253
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
254
- state.contextLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.context);
255
238
  if (model.modalities.input.includes("image")) {
256
239
  state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
257
240
  }
@@ -267,7 +250,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
267
250
 
268
251
  await ctx.provider.transform((editor) => {
269
252
  // Re-index on every transform: a learned context/output ceiling changes the
270
- // built model, and the diet and maxTokens cap read these maps. Refreshing
253
+ // built model, and the maxTokens cap reads these maps. Refreshing
271
254
  // only at setup would keep budgeting against the old window after a reload.
272
255
  indexModelState();
273
256
  applyProvider(
@@ -288,41 +271,18 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
288
271
  }
289
272
  });
290
273
 
291
- // The gateway does not publish its context ceiling. Verify the compiled
292
- // window against it once a week with a free model, in the background, and
293
- // persist the result for the next catalog build. Prefer the free model with
294
- // the largest prompt already accepted in real traffic: it has the most
295
- // evidence behind it, so the growth probes describe the window sessions use.
296
- if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
297
- const free = currentMain.filter(
298
- (model) => model.free === true && typeof model.id === "string",
299
- );
300
- const probe =
301
- free
302
- .map((model) => ({
303
- id: model.id,
304
- seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
305
- }))
306
- .sort((a, b) => b.seen - a.seen)[0]?.id ??
307
- (currentCatalog?.default_model &&
308
- free.some((model) => model.id === currentCatalog?.default_model)
309
- ? currentCatalog.default_model
310
- : undefined) ??
311
- free[0]?.id ??
312
- Object.keys(buildMain())[0];
313
- if (probe) {
314
- void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
315
- }
316
- }
317
-
318
- // V1 selected the catalog default when the user had no model configured.
274
+ // A fresh session gets the model that reasons longest of the free ones, not
275
+ // the catalog's phone-app default (`particle`, the fastest cheap model). The
276
+ // catalog default stays the fallback for the day this id disappears.
319
277
  await ctx.model.transform((editor) => {
320
278
  if (editor.default.get()) return;
321
279
  const models = buildMain();
322
280
  const preferred =
281
+ (models[DEFAULT_FREE_MODEL_ID] ? DEFAULT_FREE_MODEL_ID : undefined) ??
323
282
  (currentCatalog?.default_model && models[currentCatalog.default_model]
324
283
  ? currentCatalog.default_model
325
- : undefined) ?? Object.keys(models)[0];
284
+ : undefined) ??
285
+ Object.keys(models)[0];
326
286
  if (preferred) editor.default.set(PROVIDER_ID, preferred);
327
287
  });
328
288