@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
@@ -16,8 +16,13 @@
16
16
 
17
17
  import type { Deps } from "../deps.js";
18
18
 
19
- /** A request below this many tokens cannot exhaust a 200k window on its own. */
20
- export const SPURIOUS_OVERFLOW_TOKENS = 60_000;
19
+ /**
20
+ * A request smaller than this share of the model's window cannot be a real
21
+ * overflow: the gateway has accepted prompts up to the window for that model,
22
+ * so a rejection well below it is a provider failure and compacting again
23
+ * cannot help.
24
+ */
25
+ export const SPURIOUS_OVERFLOW_SHARE = 0.75;
21
26
 
22
27
  /** Spurious rejections closer together than this belong to the same incident. */
23
28
  const STORM_WINDOW_MS = 10 * 60_000;
@@ -101,81 +106,6 @@ export function profileRequest(body: string): RequestProfile {
101
106
  }
102
107
  }
103
108
 
104
- /** Token count of a request body, without the extra facts. */
105
- export function measureRequestTokens(body: string): number {
106
- return profileRequest(body).tokens;
107
- }
108
-
109
- /** Part types OpenCode keeps in the session but does not send to free-pi. */
110
- const UNSENT_PART_TYPES = new Set(["reasoning", "thinking"]);
111
-
112
- /**
113
- * Cheap per-message estimate; the body is serialized once per message.
114
- *
115
- * Assistant reasoning is stored in the session but the provider lowering drops
116
- * it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
117
- * made the diet and the compaction trim believe a prompt was 30-50k tokens
118
- * larger than the wire, so they pruned or dropped turns the model never saw.
119
- */
120
- export function estimateMessageTokens(message: unknown): number {
121
- try {
122
- const full = JSON.stringify(message).length;
123
- const content = (message as { content?: unknown } | null)?.content;
124
- if (!Array.isArray(content)) return Math.ceil(full / 4);
125
- let unsent = 0;
126
- for (const part of content) {
127
- if (UNSENT_PART_TYPES.has((part as { type?: string } | null)?.type ?? "")) {
128
- unsent += JSON.stringify(part).length + 1;
129
- }
130
- }
131
- return Math.ceil(Math.max(0, full - unsent) / 4);
132
- } catch {
133
- return 0;
134
- }
135
- }
136
-
137
- /**
138
- * Keeps the newest part of a message list inside `budget` tokens, cutting only
139
- * at user turns so an assistant tool call never loses its results.
140
- *
141
- * OpenCode refuses to compact when the summarization request itself is still
142
- * too large, and then the turn dies with nothing but the checkpoint shown. The
143
- * gateway's real ceiling is lower than the advertised window, so the plugin
144
- * trims the oldest turns it can spare before the summarizer is asked to read
145
- * them.
146
- */
147
- export function trimMessagesForBudget(
148
- messages: readonly unknown[],
149
- budget: number,
150
- ): {
151
- readonly messages: readonly unknown[];
152
- readonly dropped: number;
153
- readonly tokens: number;
154
- } {
155
- if (messages.length === 0) return { messages, dropped: 0, tokens: 0 };
156
- const sizes = messages.map(estimateMessageTokens);
157
- let total = 0;
158
- for (const size of sizes) total += size;
159
- if (total <= budget) return { messages, dropped: 0, tokens: total };
160
-
161
- const cuts: number[] = [];
162
- for (let index = 1; index < messages.length; index += 1) {
163
- const role = (messages[index] as { role?: unknown } | undefined)?.role;
164
- if (role === "user") cuts.push(index);
165
- }
166
- for (const cut of cuts) {
167
- let tail = 0;
168
- for (let index = cut; index < sizes.length; index += 1) tail += sizes[index]!;
169
- if (tail <= budget) {
170
- return { messages: messages.slice(cut), dropped: cut, tokens: tail };
171
- }
172
- }
173
- const last = cuts.length > 0 ? cuts[cuts.length - 1]! : messages.length - 1;
174
- let tail = 0;
175
- for (let index = last; index < sizes.length; index += 1) tail += sizes[index]!;
176
- return { messages: messages.slice(last), dropped: last, tokens: tail };
177
- }
178
-
179
109
  /**
180
110
  * Records a rejection of a request that fits, and returns the number of them
181
111
  * seen for the session inside the current window. A run of them means the
@@ -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
  }
@@ -17,6 +17,17 @@ import type { Deps } from "../deps.js";
17
17
  import { trimMap, trimSet } from "../utils/async.js";
18
18
  import { forgetWireSessionID, wireSessionID } from "./wire.js";
19
19
 
20
+ /** The model a session asked for, used by the tool gate and image handling. */
21
+ export function rememberTrackedModel(
22
+ deps: Deps,
23
+ sessionID: string,
24
+ providerID: string,
25
+ modelID: string,
26
+ ): void {
27
+ trimMap(deps.state.trackedModels, 200);
28
+ deps.state.trackedModels.set(sessionID, { providerID, modelID });
29
+ }
30
+
20
31
  export function rememberFreePiSession(deps: Deps, sessionID: string): void {
21
32
  if (!sessionID) return;
22
33
  const sessions = deps.state.freePiSessions;
package/src/state.ts CHANGED
@@ -7,7 +7,6 @@ import type {
7
7
  FreePiError,
8
8
  ModelRegistry,
9
9
  QuotaSnapshot,
10
- RequestUsage,
11
10
  SessionResetOutcome,
12
11
  TokenCheckState,
13
12
  ToolStats,
@@ -28,9 +27,6 @@ export type RuntimeState = {
28
27
  lastCatalogNotice?: string;
29
28
  lastQuotaNotice?: string;
30
29
  catalogModels: Catalog;
31
- outputLimits: Map<string, number>;
32
- /** Advertised context window per `provider/model`, for request trimming. */
33
- contextLimits: Map<string, number>;
34
30
  /** `provider/model` ids whose upstream accepts image input. */
35
31
  imageModels: Set<string>;
36
32
 
@@ -38,8 +34,6 @@ export type RuntimeState = {
38
34
  quotaPromise?: Promise<QuotaSnapshot>;
39
35
  lastQuotaRefreshAt: number;
40
36
 
41
- lastUsage?: RequestUsage;
42
- lastUsageMessageID?: string;
43
37
  lastFreePiError?: FreePiError;
44
38
  lastErrorLogKey?: string;
45
39
  lastErrorLogAt: number;
@@ -81,8 +75,6 @@ export function createRuntimeState(): RuntimeState {
81
75
  cachedRegistryAt: 0,
82
76
  registryAttemptAt: 0,
83
77
  catalogModels: {},
84
- outputLimits: new Map(),
85
- contextLimits: new Map(),
86
78
  imageModels: new Set(),
87
79
  lastQuotaRefreshAt: 0,
88
80
  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
- }
@@ -1,18 +0,0 @@
1
- /**
2
- * Builds session titles locally.
3
- *
4
- * free-pi charges credits and shows ads per model request, and the CLI never
5
- * spends a turn on a title. OpenCode asks the selected model for a title, so
6
- * the title hook answers from the first user message instead: the session gets
7
- * a real name immediately, no ad is fetched, and a failed title request can
8
- * never leave the session stuck on "New session".
9
- */
10
- type TitleMessage = {
11
- role?: unknown;
12
- type?: unknown;
13
- text?: unknown;
14
- content?: unknown;
15
- };
16
- /** Derives a title from the first meaningful line of the title request. */
17
- export declare function localTitle(messages: readonly TitleMessage[] | undefined): string;
18
- export {};