@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,201 +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
-
13
- /** Characters of a pruned tool result that stay readable at the head. */
14
- const STUB_HEAD_CHARS = 600;
15
- /** Characters kept from the end of a pruned result (summaries, errors, totals). */
16
- const STUB_TAIL_CHARS = 240;
17
- /** A result smaller than this is left alone: stubbing it saves nothing. */
18
- const MIN_PRUNE_CHARS = STUB_HEAD_CHARS + STUB_TAIL_CHARS + 400;
19
-
20
- export type DietResult = {
21
- readonly messages: readonly unknown[];
22
- readonly pruned: number;
23
- readonly tokensBefore: number;
24
- readonly tokensAfter: number;
25
- };
26
-
27
- type Part = {
28
- type?: string;
29
- text?: string;
30
- name?: string;
31
- state?: { content?: unknown };
32
- result?: { type?: string; value?: unknown };
33
- };
34
-
35
- type ResultPart = Part & { result?: { type?: string; value?: unknown } };
36
-
37
- /** OpenCode v2 `tool-result` value: text, json, error or content parts. */
38
- type ToolResultValue = { type?: string; value?: unknown } | undefined;
39
-
40
- function messageRole(message: unknown): string | undefined {
41
- const role = (message as { role?: unknown } | undefined)?.role;
42
- return typeof role === "string" ? role : undefined;
43
- }
44
-
45
- /** Text of a tool result in either the request shape or the native one. */
46
- function textOfContent(content: unknown): string {
47
- if (typeof content === "string") return content;
48
- if (!Array.isArray(content)) return "";
49
- let text = "";
50
- for (const part of content as Part[]) {
51
- if (typeof part?.text === "string") text += part.text;
52
- }
53
- return text;
54
- }
55
-
56
- /**
57
- * Renders an OpenCode v2 `tool-result` value as text. Media parts (files,
58
- * images) are never rendered: pruning them would destroy the payload instead of
59
- * shortening prose.
60
- */
61
- function textOfResult(result: ToolResultValue): string | undefined {
62
- if (!result || typeof result !== "object") return undefined;
63
- if (result.type === "content") {
64
- if (!Array.isArray(result.value)) return undefined;
65
- let text = "";
66
- for (const part of result.value as Part[]) {
67
- if (part?.type === "file") return undefined;
68
- if (typeof part?.text === "string") text += part.text;
69
- }
70
- return text;
71
- }
72
- if (typeof result.value === "string") return result.value;
73
- if (result.value === undefined || result.value === null) return undefined;
74
- try {
75
- return JSON.stringify(result.value);
76
- } catch {
77
- return undefined;
78
- }
79
- }
80
-
81
- function onlyTextParts(content: unknown): boolean {
82
- if (!Array.isArray(content)) return false;
83
- return (content as Part[]).every(
84
- (part) => part?.type === "text" || typeof part?.text === "string",
85
- );
86
- }
87
-
88
- function stub(text: string): string {
89
- const head = text.slice(0, STUB_HEAD_CHARS);
90
- const tail =
91
- text.length > STUB_HEAD_CHARS + STUB_TAIL_CHARS
92
- ? text.slice(-STUB_TAIL_CHARS)
93
- : "";
94
- const cut = text.length - head.length - tail.length;
95
- const note = `[... ${cut} characters of this tool result were pruned so the prompt stays readable; call the tool again if you need them]`;
96
- return tail ? `${head}\n${note}\n${tail}` : `${head}\n${note}`;
97
- }
98
-
99
- /**
100
- * The same message with its tool result collapsed, or `undefined` when the
101
- * message has nothing worth pruning. The native v2 shape (`tool-result` parts
102
- * with `result.value`) is the one OpenCode sends; the OpenAI-style shapes are
103
- * accepted too so a provider-lowered list is handled the same way.
104
- */
105
- function shrunk(message: unknown): unknown | undefined {
106
- const role = messageRole(message);
107
- const record = message as Record<string, unknown> & {
108
- content?: unknown;
109
- };
110
-
111
- if (role === "tool") {
112
- if (typeof record.content === "string") {
113
- return record.content.length < MIN_PRUNE_CHARS
114
- ? undefined
115
- : { ...record, content: stub(record.content) };
116
- }
117
- if (!Array.isArray(record.content)) return undefined;
118
- const parts = record.content as ResultPart[];
119
- if (parts.length === 0) return undefined;
120
-
121
- // Legacy/OpenAI-style text parts.
122
- if (onlyTextParts(parts)) {
123
- const text = textOfContent(parts);
124
- if (text.length < MIN_PRUNE_CHARS) return undefined;
125
- return { ...record, content: stub(text) };
126
- }
127
-
128
- let changed = false;
129
- const next = parts.map((part) => {
130
- if (part?.type !== "tool-result") return part;
131
- const text = textOfResult(part.result);
132
- if (!text || text.length < MIN_PRUNE_CHARS) return part;
133
- changed = true;
134
- return { ...part, result: { type: "text", value: stub(text) } };
135
- });
136
- return changed ? { ...record, content: next } : undefined;
137
- }
138
-
139
- if (role !== "assistant" || !Array.isArray(record.content)) return undefined;
140
- const parts = record.content as Part[];
141
- let changed = false;
142
- const next = parts.map((part) => {
143
- if (part?.type !== "tool" || !part.state) return part;
144
- const text = textOfContent(part.state.content);
145
- if (text.length < MIN_PRUNE_CHARS) return part;
146
- changed = true;
147
- return {
148
- ...part,
149
- state: { ...part.state, content: [{ type: "text", text: stub(text) }] },
150
- };
151
- });
152
- return changed ? { ...record, content: next } : undefined;
153
- }
154
-
155
- /**
156
- * Collapses stale tool results until the request fits `budget` tokens. The
157
- * newest messages (up to half the budget) are protected so the model always
158
- * sees what it was doing. Returns the same list untouched when it already fits.
159
- */
160
- export function pruneStaleToolResults(
161
- messages: readonly unknown[],
162
- budget: number,
163
- estimate: (message: unknown) => number,
164
- ): DietResult {
165
- const tokensBefore = messages.reduce<number>(
166
- (sum, message) => sum + estimate(message),
167
- 0,
168
- );
169
- if (messages.length === 0 || !(budget > 0) || tokensBefore <= budget) {
170
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
171
- }
172
-
173
- const sizes = messages.map(estimate);
174
- let protectedStart = messages.length;
175
- let tail = 0;
176
- for (let index = messages.length - 1; index >= 0; index -= 1) {
177
- const size = sizes[index]!;
178
- if (tail > 0 && tail + size > budget * 0.5) break;
179
- tail += size;
180
- protectedStart = index;
181
- }
182
-
183
- const out = [...messages];
184
- let total = tokensBefore;
185
- let pruned = 0;
186
- for (let index = 0; index < protectedStart && total > budget; index += 1) {
187
- const smaller = shrunk(out[index]);
188
- if (!smaller) continue;
189
- const size = estimate(smaller);
190
- if (size >= sizes[index]!) continue;
191
- total -= sizes[index]! - size;
192
- sizes[index] = size;
193
- out[index] = smaller;
194
- pruned += 1;
195
- }
196
-
197
- if (pruned === 0) {
198
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
199
- }
200
- return { messages: out, pruned, tokensBefore, tokensAfter: total };
201
- }