@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.29

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.
Files changed (48) hide show
  1. package/README.md +60 -105
  2. package/dist/catalog/live.js +4 -1
  3. package/dist/catalog/models.d.ts +1 -1
  4. package/dist/catalog/models.js +14 -3
  5. package/dist/constants.d.ts +15 -35
  6. package/dist/constants.js +15 -35
  7. package/dist/index.d.ts +1 -1
  8. package/dist/plugin.js +14 -46
  9. package/dist/session/events.js +5 -12
  10. package/dist/session/hooks.js +83 -348
  11. package/dist/session/overflow.d.ts +7 -28
  12. package/dist/session/overflow.js +7 -73
  13. package/dist/session/replay.d.ts +8 -41
  14. package/dist/session/replay.js +9 -148
  15. package/dist/session/tools.d.ts +2 -7
  16. package/dist/session/tools.js +3 -18
  17. package/dist/session/trace.js +0 -1
  18. package/dist/session/track.d.ts +2 -0
  19. package/dist/session/track.js +5 -0
  20. package/dist/state.d.ts +1 -6
  21. package/dist/state.js +0 -2
  22. package/dist/tools/vision.js +1 -0
  23. package/dist/types.d.ts +0 -1
  24. package/package.json +2 -2
  25. package/src/catalog/live.ts +4 -1
  26. package/src/catalog/models.ts +20 -3
  27. package/src/constants.ts +16 -38
  28. package/src/index.ts +0 -1
  29. package/src/plugin.ts +12 -52
  30. package/src/session/events.ts +5 -12
  31. package/src/session/hooks.ts +109 -431
  32. package/src/session/overflow.ts +7 -77
  33. package/src/session/replay.ts +12 -188
  34. package/src/session/tools.ts +1 -22
  35. package/src/session/trace.ts +0 -1
  36. package/src/session/track.ts +11 -0
  37. package/src/state.ts +0 -8
  38. package/src/tools/vision.ts +2 -0
  39. package/src/types.ts +0 -1
  40. package/dist/session/diet.d.ts +0 -23
  41. package/dist/session/diet.js +0 -176
  42. package/dist/session/title.d.ts +0 -18
  43. package/dist/session/title.js +0 -81
  44. package/dist/session/usage.d.ts +0 -5
  45. package/dist/session/usage.js +0 -32
  46. package/src/session/diet.ts +0 -201
  47. package/src/session/title.ts +0 -90
  48. package/src/session/usage.ts +0 -46
@@ -13,8 +13,13 @@
13
13
  * still fails, surfaces a provider error instead of asking for another
14
14
  * compaction.
15
15
  */
16
- /** A request below this many tokens cannot exhaust a 200k window on its own. */
17
- export const SPURIOUS_OVERFLOW_TOKENS = 60_000;
16
+ /**
17
+ * A request smaller than this share of the model's window cannot be a real
18
+ * overflow: the gateway has accepted prompts up to the window for that model,
19
+ * so a rejection well below it is a provider failure and compacting again
20
+ * cannot help.
21
+ */
22
+ export const SPURIOUS_OVERFLOW_SHARE = 0.75;
18
23
  /** Spurious rejections closer together than this belong to the same incident. */
19
24
  const STORM_WINDOW_MS = 10 * 60_000;
20
25
  /** Spurious rejections tolerated in a window before the error stops compacting. */
@@ -81,77 +86,6 @@ export function profileRequest(body) {
81
86
  return { tokens: Math.ceil(body.length / 4), hasMedia: false };
82
87
  }
83
88
  }
84
- /** Token count of a request body, without the extra facts. */
85
- export function measureRequestTokens(body) {
86
- return profileRequest(body).tokens;
87
- }
88
- /** Part types OpenCode keeps in the session but does not send to free-pi. */
89
- const UNSENT_PART_TYPES = new Set(["reasoning", "thinking"]);
90
- /**
91
- * Cheap per-message estimate; the body is serialized once per message.
92
- *
93
- * Assistant reasoning is stored in the session but the provider lowering drops
94
- * it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
95
- * made the diet and the compaction trim believe a prompt was 30-50k tokens
96
- * larger than the wire, so they pruned or dropped turns the model never saw.
97
- */
98
- export function estimateMessageTokens(message) {
99
- try {
100
- const full = JSON.stringify(message).length;
101
- const content = message?.content;
102
- if (!Array.isArray(content))
103
- return Math.ceil(full / 4);
104
- let unsent = 0;
105
- for (const part of content) {
106
- if (UNSENT_PART_TYPES.has(part?.type ?? "")) {
107
- unsent += JSON.stringify(part).length + 1;
108
- }
109
- }
110
- return Math.ceil(Math.max(0, full - unsent) / 4);
111
- }
112
- catch {
113
- return 0;
114
- }
115
- }
116
- /**
117
- * Keeps the newest part of a message list inside `budget` tokens, cutting only
118
- * at user turns so an assistant tool call never loses its results.
119
- *
120
- * OpenCode refuses to compact when the summarization request itself is still
121
- * too large, and then the turn dies with nothing but the checkpoint shown. The
122
- * gateway's real ceiling is lower than the advertised window, so the plugin
123
- * trims the oldest turns it can spare before the summarizer is asked to read
124
- * them.
125
- */
126
- export function trimMessagesForBudget(messages, budget) {
127
- if (messages.length === 0)
128
- return { messages, dropped: 0, tokens: 0 };
129
- const sizes = messages.map(estimateMessageTokens);
130
- let total = 0;
131
- for (const size of sizes)
132
- total += size;
133
- if (total <= budget)
134
- return { messages, dropped: 0, tokens: total };
135
- const cuts = [];
136
- for (let index = 1; index < messages.length; index += 1) {
137
- const role = messages[index]?.role;
138
- if (role === "user")
139
- cuts.push(index);
140
- }
141
- for (const cut of cuts) {
142
- let tail = 0;
143
- for (let index = cut; index < sizes.length; index += 1)
144
- tail += sizes[index];
145
- if (tail <= budget) {
146
- return { messages: messages.slice(cut), dropped: cut, tokens: tail };
147
- }
148
- }
149
- const last = cuts.length > 0 ? cuts[cuts.length - 1] : messages.length - 1;
150
- let tail = 0;
151
- for (let index = last; index < sizes.length; index += 1)
152
- tail += sizes[index];
153
- return { messages: messages.slice(last), dropped: last, tokens: tail };
154
- }
155
89
  /**
156
90
  * Records a rejection of a request that fits, and returns the number of them
157
91
  * seen for the session inside the current window. A run of them means the
@@ -1,46 +1,13 @@
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
9
  import type { Deps } from "../deps.js";
17
- /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
10
+ /** Keeps the body around so an overflow can be sized after fetch consumed it. */
18
11
  export declare function rememberReplayBody(deps: Deps, event: any): Promise<void>;
19
- /**
20
- * Returns a replacement response when a concurrent 429 was recovered, or
21
- * `undefined` to leave the original response untouched.
22
- */
23
- export declare function replayConcurrentResponse(deps: Deps, event: any): Promise<Response | undefined>;
24
- export type OverflowReplay = {
25
- /** Tokens of the rejected request, when its body was available. */
26
- readonly tokens?: number;
27
- /** Upstream model the rejected request asked for. */
28
- readonly model?: string;
29
- /** Whether the rejected request carried an inline image or file. */
30
- readonly hasMedia?: boolean;
31
- /** Whether the rejected request plainly fits the model window. */
32
- readonly spurious?: boolean;
33
- /** A good response from a fresh wire session, when the retry succeeded. */
34
- readonly response?: Response;
35
- };
36
- /**
37
- * Retries an overflow rejection whose request plainly fits the model window.
38
- *
39
- * free-pi reports `context_ceiling`/`context_too_long` from the upstream
40
- * model, and a failing gateway can report them for a small prompt. Compacting
41
- * cannot fix that: the summary is accepted, the next turn is rejected the same
42
- * way, and the runner compacts again. A fresh wire session is the cheapest
43
- * recovery, so a small request is replayed on one before the overflow is
44
- * handed to the runner.
45
- */
46
- export declare function replaySpuriousOverflow(deps: Deps, event: any): Promise<OverflowReplay>;
12
+ /** The request body, either remembered before the send or re-read from it. */
13
+ export declare function storedBody(deps: Deps, event: any): Promise<string | undefined>;
@@ -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
  }
@@ -8,6 +8,8 @@
8
8
  * later activity instead of running inline with the execution event.
9
9
  */
10
10
  import type { Deps } from "../deps.js";
11
+ /** The model a session asked for, used by the tool gate and image handling. */
12
+ export declare function rememberTrackedModel(deps: Deps, sessionID: string, providerID: string, modelID: string): void;
11
13
  export declare function rememberFreePiSession(deps: Deps, sessionID: string): void;
12
14
  /** Records free-pi activity so a pending close waits for the request to settle. */
13
15
  export declare function touchSessionActivity(deps: Deps, sessionID: string): void;
@@ -11,6 +11,11 @@ import { closeFreePiSession } from "../api/session.js";
11
11
  import { SESSION_FINALIZE_DELAY_MS, SESSION_TRACK_LIMIT, } from "../constants.js";
12
12
  import { trimMap, trimSet } from "../utils/async.js";
13
13
  import { forgetWireSessionID, wireSessionID } from "./wire.js";
14
+ /** The model a session asked for, used by the tool gate and image handling. */
15
+ export function rememberTrackedModel(deps, sessionID, providerID, modelID) {
16
+ trimMap(deps.state.trackedModels, 200);
17
+ deps.state.trackedModels.set(sessionID, { providerID, modelID });
18
+ }
14
19
  export function rememberFreePiSession(deps, sessionID) {
15
20
  if (!sessionID)
16
21
  return;
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, RequestUsage, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
2
+ import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
3
3
  export type RuntimeState = {
4
4
  latestClientVersion: string;
5
5
  providerToken?: string;
@@ -13,16 +13,11 @@ 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;
22
19
  quotaPromise?: Promise<QuotaSnapshot>;
23
20
  lastQuotaRefreshAt: number;
24
- lastUsage?: RequestUsage;
25
- lastUsageMessageID?: string;
26
21
  lastFreePiError?: FreePiError;
27
22
  lastErrorLogKey?: string;
28
23
  lastErrorLogAt: number;
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
@@ -264,7 +264,6 @@ export type ToolStats = {
264
264
  failed: string[];
265
265
  evicted: boolean;
266
266
  started: Map<string, number>;
267
- compacted: number;
268
267
  };
269
268
  export type TokenUsageLike = {
270
269
  input?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.26",
3
+ "version": "0.7.29",
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/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({
@@ -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
 
package/src/constants.ts CHANGED
@@ -11,6 +11,16 @@ export const DEFAULT_BASE_URL = "https://api.freepi.ai";
11
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",
@@ -79,34 +83,9 @@ export const DEFAULT_THINKING_LEVELS = [
79
83
  export const HEADER_TIMEOUT_MS = 300_000;
80
84
  export const CHUNK_TIMEOUT_MS = 300_000;
81
85
 
82
- /** pi's retry policy: 3 retries, 2s base, 60s cap. */
83
- export const RETRY_MAX_RETRIES = 3;
84
- export const RETRY_BASE_DELAY_MS = 2_000;
85
- export const RETRY_MAX_DELAY_MS = 60_000;
86
-
87
- /**
88
- * Transport failures (a refused or dropped connection, DNS blips) usually
89
- * clear on their own. OpenCode stops after its own retries, which can end a
90
- * turn during a brief local network or service restart, so the plugin gives
91
- * them a longer budget before giving up.
92
- */
93
- export const TRANSPORT_RETRY_MAX = 5;
94
- export const TRANSPORT_RETRY_BASE_MS = 2_000;
95
- export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
96
-
97
- /**
98
- * free-pi allows one in-flight request per `x-session-id` and answers a second
99
- * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
100
- * can leak server-side, so the plugin rotates the wire session id and retries.
101
- */
102
- export const CONCURRENT_RETRY_MAX = 6;
103
- export const CONCURRENT_RETRY_BASE_MS = 1_000;
104
- export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
105
-
106
86
  /** Tool outcome headers emitted by the free-pi provider CLI. */
107
87
  export const TOOL_META_HEADER = "x-freepi-tool-meta";
108
88
  export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
109
- export const COMPACTED_HEADER = "x-freepi-compacted";
110
89
  export const TOOL_META_BUDGET = 1_500;
111
90
  export const TOOL_ID_LIMIT = 50;
112
91
 
@@ -160,7 +139,6 @@ export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
160
139
 
161
140
  export const QUOTA_TTL_MS = 30_000;
162
141
  export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
163
- export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
164
142
 
165
143
  export const SESSION_RESET_COOLDOWN_MS = 15_000;
166
144
  /**