@eduardo191labs/opencode-free-pi 0.7.26 → 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,37 +1,17 @@
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
 
17
- import { closeFreePiSession } from "../api/session.js";
18
10
  import type { Deps } from "../deps.js";
19
- import { overflowCodeOf } from "../errors/limit.js";
20
- import { sleep, trimMap } from "../utils/async.js";
21
- import {
22
- profileRequest,
23
- SPURIOUS_OVERFLOW_TOKENS,
24
- } from "./overflow.js";
11
+ import { trimMap } from "../utils/async.js";
25
12
  import { traceRequestBody } from "./trace.js";
26
- import { rotateWireSessionID, wireSessionID } from "./wire.js";
27
13
 
28
14
  const REPLAY_BODY_LIMIT = 24;
29
- const REPLAY_MAX_ATTEMPTS = 4;
30
- const REPLAY_BASE_DELAY_MS = 400;
31
- const REPLAY_MAX_DELAY_MS = 3_000;
32
-
33
- /** A rejected request that fits is retried only this many times on fresh ids. */
34
- const OVERFLOW_REPLAY_ATTEMPTS = 2;
35
15
 
36
16
  function requestKey(sessionID: string, request: Request): string {
37
17
  const turn = request.headers.get("x-turn-id") ?? "";
@@ -42,7 +22,7 @@ function isJson(request: Request): boolean {
42
22
  return (request.headers.get("content-type") ?? "").includes("json");
43
23
  }
44
24
 
45
- /** Keeps the body around so a 429 can be replayed after fetch consumed it. */
25
+ /** Keeps the body around so an overflow can be sized after fetch consumed it. */
46
26
  export async function rememberReplayBody(
47
27
  deps: Deps,
48
28
  event: any,
@@ -59,21 +39,15 @@ export async function rememberReplayBody(
59
39
  trimMap(deps.state.replayBodies, REPLAY_BODY_LIMIT);
60
40
  traceRequestBody(deps, event.sessionID, body, request.headers);
61
41
  } catch {
62
- // A non-replayable body simply falls back to the normal retry hook.
42
+ // A body that cannot be read simply has no overflow size to measure.
63
43
  }
64
44
  }
65
45
 
66
- async function isConcurrent(response: Response): Promise<boolean> {
67
- if (response.status !== 429) return false;
68
- const body = await response
69
- .clone()
70
- .text()
71
- .catch(() => "");
72
- return /"concurrent"/i.test(body) || /one request at a time/i.test(body);
73
- }
74
-
75
46
  /** The request body, either remembered before the send or re-read from it. */
76
- async function storedBody(deps: Deps, event: any): Promise<string | undefined> {
47
+ export async function storedBody(
48
+ deps: Deps,
49
+ event: any,
50
+ ): Promise<string | undefined> {
77
51
  const request = event?.request;
78
52
  if (!(request instanceof Request) || !event.sessionID) return;
79
53
  const remembered = deps.state.replayBodies.get(
@@ -86,153 +60,3 @@ async function storedBody(deps: Deps, event: any): Promise<string | undefined> {
86
60
  .text()
87
61
  .catch(() => undefined);
88
62
  }
89
-
90
- function concurrentDelay(attempt: number): number {
91
- return Math.min(
92
- REPLAY_BASE_DELAY_MS * 2 ** Math.max(0, attempt - 1),
93
- REPLAY_MAX_DELAY_MS,
94
- );
95
- }
96
-
97
- /**
98
- * Returns a replacement response when a concurrent 429 was recovered, or
99
- * `undefined` to leave the original response untouched.
100
- */
101
- export async function replayConcurrentResponse(
102
- deps: Deps,
103
- event: any,
104
- ): Promise<Response | undefined> {
105
- const original = event?.response;
106
- const request = event?.request;
107
- if (!(original instanceof Response) || !(request instanceof Request)) return;
108
- if (request.signal.aborted) return;
109
- if (!(await isConcurrent(original))) return;
110
-
111
- const body = await storedBody(deps, event);
112
- if (!body) {
113
- deps.log.warn(
114
- "free-pi session busy but the request body was not available to replay",
115
- { sessionID: event.sessionID },
116
- );
117
- return;
118
- }
119
-
120
- let previous =
121
- request.headers.get("x-session-id") ??
122
- wireSessionID(deps, event.sessionID);
123
-
124
- for (let attempt = 1; attempt <= REPLAY_MAX_ATTEMPTS; attempt++) {
125
- if (request.signal.aborted) return;
126
- if (attempt > 1) await sleep(concurrentDelay(attempt));
127
- const next = rotateWireSessionID(deps, event.sessionID);
128
- if (previous && previous !== next) {
129
- void closeFreePiSession(deps, previous).catch(() => undefined);
130
- }
131
- previous = next;
132
-
133
- const headers = new Headers(request.headers);
134
- headers.set("x-session-id", next);
135
- headers.delete("content-length");
136
- headers.delete("host");
137
-
138
- const response = await fetch(request.url, {
139
- method: request.method,
140
- headers,
141
- body,
142
- signal: request.signal,
143
- }).catch(() => undefined);
144
- if (!response) continue;
145
- if (!(await isConcurrent(response))) {
146
- deps.log.info(
147
- "free-pi session busy; replayed the request with a fresh session id",
148
- {
149
- sessionID: event.sessionID,
150
- from: request.headers.get("x-session-id") ?? undefined,
151
- to: next,
152
- attempt,
153
- },
154
- );
155
- return response;
156
- }
157
- }
158
- return undefined;
159
- }
160
-
161
- export type OverflowReplay = {
162
- /** Tokens of the rejected request, when its body was available. */
163
- readonly tokens?: number;
164
- /** Upstream model the rejected request asked for. */
165
- readonly model?: string;
166
- /** Whether the rejected request carried an inline image or file. */
167
- readonly hasMedia?: boolean;
168
- /** Whether the rejected request plainly fits the model window. */
169
- readonly spurious?: boolean;
170
- /** A good response from a fresh wire session, when the retry succeeded. */
171
- readonly response?: Response;
172
- };
173
-
174
- /**
175
- * Retries an overflow rejection whose request plainly fits the model window.
176
- *
177
- * free-pi reports `context_ceiling`/`context_too_long` from the upstream
178
- * model, and a failing gateway can report them for a small prompt. Compacting
179
- * cannot fix that: the summary is accepted, the next turn is rejected the same
180
- * way, and the runner compacts again. A fresh wire session is the cheapest
181
- * recovery, so a small request is replayed on one before the overflow is
182
- * handed to the runner.
183
- */
184
- export async function replaySpuriousOverflow(
185
- deps: Deps,
186
- event: any,
187
- ): Promise<OverflowReplay> {
188
- const original = event?.response;
189
- const request = event?.request;
190
- if (!(original instanceof Response) || !(request instanceof Request)) return {};
191
- if (request.signal.aborted) return {};
192
- if (!(await overflowCodeOf(original))) return {};
193
-
194
- const body = await storedBody(deps, event);
195
- if (!body) return {};
196
- const profile = profileRequest(body);
197
- const tokens = profile.tokens;
198
- const facts = { model: profile.model, hasMedia: profile.hasMedia };
199
- if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
200
- return { tokens, ...facts, spurious: false };
201
- }
202
-
203
- let previous =
204
- request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
205
- for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
206
- if (request.signal.aborted) return { tokens, ...facts, spurious: true };
207
- const next = rotateWireSessionID(deps, event.sessionID);
208
- if (previous && previous !== next) {
209
- void closeFreePiSession(deps, previous).catch(() => undefined);
210
- }
211
- previous = next;
212
-
213
- const headers = new Headers(request.headers);
214
- headers.set("x-session-id", next);
215
- headers.delete("content-length");
216
- headers.delete("host");
217
-
218
- const response = await fetch(request.url, {
219
- method: request.method,
220
- headers,
221
- body,
222
- signal: request.signal,
223
- }).catch(() => undefined);
224
- if (!response) continue;
225
- if (!(await overflowCodeOf(response))) {
226
- deps.log.info(
227
- "free-pi rejected a request that fits as too long; replayed it on a fresh session id",
228
- { sessionID: event.sessionID, tokens, to: next, attempt },
229
- );
230
- return { tokens, ...facts, spurious: true, response };
231
- }
232
- }
233
- deps.log.info(
234
- "free-pi keeps rejecting a request that fits as too long; the provider is failing",
235
- { sessionID: event.sessionID, tokens },
236
- );
237
- return { tokens, ...facts, spurious: true };
238
- }
@@ -4,11 +4,9 @@
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
 
10
9
  import {
11
- COMPACTED_HEADER,
12
10
  DEFENSE_PROVIDER_ID,
13
11
  PROVIDER_ID,
14
12
  TOOL_ERRORS_HEADER,
@@ -75,7 +73,6 @@ function statsFor(deps: Deps, sessionID: string): ToolStats {
75
73
  failed: [],
76
74
  evicted: false,
77
75
  started: new Map(),
78
- compacted: 0,
79
76
  };
80
77
  trimMap(deps.state.toolStats, 200);
81
78
  deps.state.toolStats.set(sessionID, stats);
@@ -135,34 +132,16 @@ export function recordToolEnd(deps: Deps, sessionID: string, end: ToolEnd): void
135
132
  stats.evicted = true;
136
133
  }
137
134
 
138
- export function recordCompaction(
139
- deps: Deps,
140
- sessionID: string,
141
- droppedMessages: number,
142
- ): void {
143
- if (!isFreePiSession(deps, sessionID) || droppedMessages <= 0) return;
144
- const stats = statsFor(deps, sessionID);
145
- stats.compacted += droppedMessages;
146
- }
147
-
148
- /**
149
- * Headers for the outgoing request. `consumeCompacted` is false for the
150
- * compaction request itself so the marker lands on the request that follows.
151
- */
135
+ /** Headers for the outgoing request, describing the tools this turn ran. */
152
136
  export function toolHeaders(
153
137
  deps: Deps,
154
138
  sessionID: string,
155
- consumeCompacted: boolean,
156
139
  ): Record<string, string> {
157
140
  const stats = deps.state.toolStats.get(sessionID);
158
141
  const headers: Record<string, string> = {};
159
142
  if (stats?.meta.length) {
160
143
  headers[TOOL_META_HEADER] = `v1:${stats.meta.join(",")}`;
161
144
  }
162
- if (stats && consumeCompacted && stats.compacted > 0) {
163
- headers[COMPACTED_HEADER] = `v1:${stats.compacted}`;
164
- stats.compacted = 0;
165
- }
166
145
  headers[TOOL_ERRORS_HEADER] = `${stats?.evicted ? "v1x" : "v1"}:${(stats?.failed ?? []).join(",")}`;
167
146
  return headers;
168
147
  }
@@ -137,6 +137,5 @@ function headerTrace(headers: Headers | undefined): Record<string, unknown> {
137
137
  xAdUserStart: adUserStart,
138
138
  xSubagent: headers.get("x-freepi-subagent") ?? "",
139
139
  xToolMeta: headers.get("x-freepi-tool-meta") ?? "",
140
- xCompacted: headers.get("x-freepi-compacted") ?? "",
141
140
  };
142
141
  }
package/src/state.ts CHANGED
@@ -28,9 +28,6 @@ export type RuntimeState = {
28
28
  lastCatalogNotice?: string;
29
29
  lastQuotaNotice?: string;
30
30
  catalogModels: Catalog;
31
- outputLimits: Map<string, number>;
32
- /** Advertised context window per `provider/model`, for request trimming. */
33
- contextLimits: Map<string, number>;
34
31
  /** `provider/model` ids whose upstream accepts image input. */
35
32
  imageModels: Set<string>;
36
33
 
@@ -81,8 +78,6 @@ export function createRuntimeState(): RuntimeState {
81
78
  cachedRegistryAt: 0,
82
79
  registryAttemptAt: 0,
83
80
  catalogModels: {},
84
- outputLimits: new Map(),
85
- contextLimits: new Map(),
86
81
  imageModels: new Set(),
87
82
  lastQuotaRefreshAt: 0,
88
83
  lastErrorLogAt: 0,
@@ -61,6 +61,8 @@ const ERROR_TEXT: Record<string, string> = {
61
61
  not_configured:
62
62
  "Image understanding is not available on this server. Do not call look_at_image again in this session.",
63
63
  upstream_error: "The vision provider failed. You may retry once.",
64
+ image_screen_unavailable:
65
+ "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.",
64
66
  account_review:
65
67
  "This account is under review, so image understanding is disabled. Do not retry; tell the user and continue without it.",
66
68
  invalid_request:
package/src/types.ts CHANGED
@@ -259,7 +259,6 @@ export type ToolStats = {
259
259
  failed: string[];
260
260
  evicted: boolean;
261
261
  started: Map<string, number>;
262
- compacted: number;
263
262
  };
264
263
 
265
264
  export type TokenUsageLike = {
@@ -1,23 +0,0 @@
1
- /**
2
- * Keeps a primary request inside the range where free models still attend to
3
- * the system prompt and the recent turns.
4
- *
5
- * Long free-pi sessions reach 100k-170k token prompts because every `read`,
6
- * `grep` and `shell` result stays verbatim forever. At that size the free
7
- * models lose the middle of the conversation and stop following the working
8
- * rules even though the gateway accepts the request. Whole turns cannot be
9
- * dropped: the user's wording and the assistant's decisions must survive. Only
10
- * stale tool payloads are collapsed, and the newest messages are never touched.
11
- */
12
- export type DietResult = {
13
- readonly messages: readonly unknown[];
14
- readonly pruned: number;
15
- readonly tokensBefore: number;
16
- readonly tokensAfter: number;
17
- };
18
- /**
19
- * Collapses stale tool results until the request fits `budget` tokens. The
20
- * newest messages (up to half the budget) are protected so the model always
21
- * sees what it was doing. Returns the same list untouched when it already fits.
22
- */
23
- export declare function pruneStaleToolResults(messages: readonly unknown[], budget: number, estimate: (message: unknown) => number): DietResult;
@@ -1,176 +0,0 @@
1
- /**
2
- * Keeps a primary request inside the range where free models still attend to
3
- * the system prompt and the recent turns.
4
- *
5
- * Long free-pi sessions reach 100k-170k token prompts because every `read`,
6
- * `grep` and `shell` result stays verbatim forever. At that size the free
7
- * models lose the middle of the conversation and stop following the working
8
- * rules even though the gateway accepts the request. Whole turns cannot be
9
- * dropped: the user's wording and the assistant's decisions must survive. Only
10
- * stale tool payloads are collapsed, and the newest messages are never touched.
11
- */
12
- /** Characters of a pruned tool result that stay readable at the head. */
13
- const STUB_HEAD_CHARS = 600;
14
- /** Characters kept from the end of a pruned result (summaries, errors, totals). */
15
- const STUB_TAIL_CHARS = 240;
16
- /** A result smaller than this is left alone: stubbing it saves nothing. */
17
- const MIN_PRUNE_CHARS = STUB_HEAD_CHARS + STUB_TAIL_CHARS + 400;
18
- function messageRole(message) {
19
- const role = message?.role;
20
- return typeof role === "string" ? role : undefined;
21
- }
22
- /** Text of a tool result in either the request shape or the native one. */
23
- function textOfContent(content) {
24
- if (typeof content === "string")
25
- return content;
26
- if (!Array.isArray(content))
27
- return "";
28
- let text = "";
29
- for (const part of content) {
30
- if (typeof part?.text === "string")
31
- text += part.text;
32
- }
33
- return text;
34
- }
35
- /**
36
- * Renders an OpenCode v2 `tool-result` value as text. Media parts (files,
37
- * images) are never rendered: pruning them would destroy the payload instead of
38
- * shortening prose.
39
- */
40
- function textOfResult(result) {
41
- if (!result || typeof result !== "object")
42
- return undefined;
43
- if (result.type === "content") {
44
- if (!Array.isArray(result.value))
45
- return undefined;
46
- let text = "";
47
- for (const part of result.value) {
48
- if (part?.type === "file")
49
- return undefined;
50
- if (typeof part?.text === "string")
51
- text += part.text;
52
- }
53
- return text;
54
- }
55
- if (typeof result.value === "string")
56
- return result.value;
57
- if (result.value === undefined || result.value === null)
58
- return undefined;
59
- try {
60
- return JSON.stringify(result.value);
61
- }
62
- catch {
63
- return undefined;
64
- }
65
- }
66
- function onlyTextParts(content) {
67
- if (!Array.isArray(content))
68
- return false;
69
- return content.every((part) => part?.type === "text" || typeof part?.text === "string");
70
- }
71
- function stub(text) {
72
- const head = text.slice(0, STUB_HEAD_CHARS);
73
- const tail = text.length > STUB_HEAD_CHARS + STUB_TAIL_CHARS
74
- ? text.slice(-STUB_TAIL_CHARS)
75
- : "";
76
- const cut = text.length - head.length - tail.length;
77
- const note = `[... ${cut} characters of this tool result were pruned so the prompt stays readable; call the tool again if you need them]`;
78
- return tail ? `${head}\n${note}\n${tail}` : `${head}\n${note}`;
79
- }
80
- /**
81
- * The same message with its tool result collapsed, or `undefined` when the
82
- * message has nothing worth pruning. The native v2 shape (`tool-result` parts
83
- * with `result.value`) is the one OpenCode sends; the OpenAI-style shapes are
84
- * accepted too so a provider-lowered list is handled the same way.
85
- */
86
- function shrunk(message) {
87
- const role = messageRole(message);
88
- const record = message;
89
- if (role === "tool") {
90
- if (typeof record.content === "string") {
91
- return record.content.length < MIN_PRUNE_CHARS
92
- ? undefined
93
- : { ...record, content: stub(record.content) };
94
- }
95
- if (!Array.isArray(record.content))
96
- return undefined;
97
- const parts = record.content;
98
- if (parts.length === 0)
99
- return undefined;
100
- // Legacy/OpenAI-style text parts.
101
- if (onlyTextParts(parts)) {
102
- const text = textOfContent(parts);
103
- if (text.length < MIN_PRUNE_CHARS)
104
- return undefined;
105
- return { ...record, content: stub(text) };
106
- }
107
- let changed = false;
108
- const next = parts.map((part) => {
109
- if (part?.type !== "tool-result")
110
- return part;
111
- const text = textOfResult(part.result);
112
- if (!text || text.length < MIN_PRUNE_CHARS)
113
- return part;
114
- changed = true;
115
- return { ...part, result: { type: "text", value: stub(text) } };
116
- });
117
- return changed ? { ...record, content: next } : undefined;
118
- }
119
- if (role !== "assistant" || !Array.isArray(record.content))
120
- return undefined;
121
- const parts = record.content;
122
- let changed = false;
123
- const next = parts.map((part) => {
124
- if (part?.type !== "tool" || !part.state)
125
- return part;
126
- const text = textOfContent(part.state.content);
127
- if (text.length < MIN_PRUNE_CHARS)
128
- return part;
129
- changed = true;
130
- return {
131
- ...part,
132
- state: { ...part.state, content: [{ type: "text", text: stub(text) }] },
133
- };
134
- });
135
- return changed ? { ...record, content: next } : undefined;
136
- }
137
- /**
138
- * Collapses stale tool results until the request fits `budget` tokens. The
139
- * newest messages (up to half the budget) are protected so the model always
140
- * sees what it was doing. Returns the same list untouched when it already fits.
141
- */
142
- export function pruneStaleToolResults(messages, budget, estimate) {
143
- const tokensBefore = messages.reduce((sum, message) => sum + estimate(message), 0);
144
- if (messages.length === 0 || !(budget > 0) || tokensBefore <= budget) {
145
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
146
- }
147
- const sizes = messages.map(estimate);
148
- let protectedStart = messages.length;
149
- let tail = 0;
150
- for (let index = messages.length - 1; index >= 0; index -= 1) {
151
- const size = sizes[index];
152
- if (tail > 0 && tail + size > budget * 0.5)
153
- break;
154
- tail += size;
155
- protectedStart = index;
156
- }
157
- const out = [...messages];
158
- let total = tokensBefore;
159
- let pruned = 0;
160
- for (let index = 0; index < protectedStart && total > budget; index += 1) {
161
- const smaller = shrunk(out[index]);
162
- if (!smaller)
163
- continue;
164
- const size = estimate(smaller);
165
- if (size >= sizes[index])
166
- continue;
167
- total -= sizes[index] - size;
168
- sizes[index] = size;
169
- out[index] = smaller;
170
- pruned += 1;
171
- }
172
- if (pruned === 0) {
173
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
174
- }
175
- return { messages: out, pruned, tokensBefore, tokensAfter: total };
176
- }