@eduardo191labs/opencode-free-pi 0.6.9 → 0.7.1

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.
package/README.md CHANGED
@@ -98,6 +98,15 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
98
98
  porque los modelos gratuitos ignoran las reglas del sistema. Esos turnos
99
99
  viajan una sola vez en la primera petición posterior, por si el resumen los
100
100
  comprimió de más; caducan a la hora y no se guardan en disco.
101
+ - **Poda de resultados antiguos**: las sesiones largas llegan a prompts de
102
+ 100k–170k tokens y a ese tamaño los modelos gratuitos pierden el centro de la
103
+ conversación y dejan de seguir las reglas, aunque el gateway acepte la
104
+ petición. Antes de enviar, el plugin colapsa los resultados de herramientas
105
+ antiguos (conserva 600 caracteres de cabecera y 240 del final, con un aviso de
106
+ que se podaron), sin tocar el texto de usuario, las decisiones del asistente
107
+ ni los mensajes más recientes. El presupuesto es el 40 % de la ventana
108
+ anunciada (mínimo 24k), así que el prompt vuelve a la zona donde el modelo
109
+ atiende.
101
110
  - **Sin bucles de compactación**: si el servidor rechaza como «demasiado
102
111
  largo» una petición que cabe de sobra en la ventana (menos de 60k tokens),
103
112
  el plugin la reintenta con un `x-session-id` nuevo en vez de compactar. Si
@@ -543,6 +552,7 @@ test/smoke.mjs prueba de humo del build
543
552
  test/registry.mjs models.dev en vivo y tolerancia a fallos
544
553
  test/models.mjs capacidades, variantes y límites
545
554
  test/live.mjs ventana medida y observaciones del gateway
555
+ test/diet.mjs poda de resultados de herramientas antiguos
546
556
  test/hooks.mjs hooks de sesión, anuncios, cuota y compactación
547
557
  ```
548
558
 
@@ -16,6 +16,15 @@ export declare const CONTEXT_WINDOW = 200000;
16
16
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
17
  export declare const MAX_CONTEXT_WINDOW = 1000000;
18
18
  export declare const MAX_OUTPUT_TOKENS = 32768;
19
+ /**
20
+ * Share of the advertised window a primary request may occupy before stale
21
+ * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
+ * and the free models then lose the middle of the conversation and stop
23
+ * following the working rules, even though the gateway still accepts them.
24
+ */
25
+ export declare const CONTEXT_DIET_SHARE = 0.4;
26
+ /** Below this window the diet is pointless: the request is small anyway. */
27
+ export declare const CONTEXT_DIET_MIN_TOKENS = 24000;
19
28
  /**
20
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
21
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -57,7 +66,7 @@ export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
57
66
  * for terse checkpoints, which is fine for strong models but loses the exact
58
67
  * facts the free models need; spell out what must survive the rewrite.
59
68
  */
60
- export declare const FREE_PI_COMPACTION_GUIDANCE = "# free-pi compaction rules\n- Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.\n- Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.\n- Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.\n- Do not invent progress or results that are not in the conversation.";
69
+ export declare const FREE_PI_COMPACTION_GUIDANCE = "# free-pi compaction rules\n- Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.\n- For each step in the work state, write the conclusion it proved, not only the file or command: \"read X and confirmed Y\", \"build failed with Z\". A list of actions without their findings makes the next agent repeat the work.\n- Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.\n- Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.\n- Do not invent progress or results that are not in the conversation.";
61
70
  export declare const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
62
71
  /**
63
72
  * OpenCode keeps only the latest exchange beside a summary, so after a
package/dist/constants.js CHANGED
@@ -16,6 +16,15 @@ export const CONTEXT_WINDOW = 200_000;
16
16
  /** Largest window the plugin will ever advertise after measuring the gateway. */
17
17
  export const MAX_CONTEXT_WINDOW = 1_000_000;
18
18
  export const MAX_OUTPUT_TOKENS = 32_768;
19
+ /**
20
+ * Share of the advertised window a primary request may occupy before stale
21
+ * tool results are collapsed. Long free-pi sessions reach 100k-170k prompts
22
+ * and the free models then lose the middle of the conversation and stop
23
+ * following the working rules, even though the gateway still accepts them.
24
+ */
25
+ export const CONTEXT_DIET_SHARE = 0.4;
26
+ /** Below this window the diet is pointless: the request is small anyway. */
27
+ export const CONTEXT_DIET_MIN_TOKENS = 24_000;
19
28
  /**
20
29
  * Upper bound for a model that publishes a larger output budget. Reasoning
21
30
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -83,6 +92,7 @@ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
83
92
  */
84
93
  export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
85
94
  - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
95
+ - For each step in the work state, write the conclusion it proved, not only the file or command: "read X and confirmed Y", "build failed with Z". A list of actions without their findings makes the next agent repeat the work.
86
96
  - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
87
97
  - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
88
98
  - Do not invent progress or results that are not in the conversation.`;
package/dist/plugin.js CHANGED
@@ -179,12 +179,14 @@ async function setup(ctx) {
179
179
  const defenseNow = buildDefense();
180
180
  for (const [id, model] of Object.entries(mainNow)) {
181
181
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
182
+ state.contextLimits.set(`${PROVIDER_ID}/${id}`, model.limit.context);
182
183
  if (model.modalities.input.includes("image")) {
183
184
  state.imageModels.add(`${PROVIDER_ID}/${id}`);
184
185
  }
185
186
  }
186
187
  for (const [id, model] of Object.entries(defenseNow)) {
187
188
  state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
189
+ state.contextLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.context);
188
190
  if (model.modalities.input.includes("image")) {
189
191
  state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
190
192
  }
@@ -0,0 +1,23 @@
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;
@@ -0,0 +1,176 @@
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
+ }
@@ -2,13 +2,14 @@
2
2
  import { ensureAdImpression } from "../ads/impression.js";
3
3
  import { resolveAdTurn } from "../ads/resolve.js";
4
4
  import { resolveToken } from "../auth/token.js";
5
- import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RECENT_WINDOW_CARRY_MARKER, RECENT_WINDOW_CARRY_MS, RECENT_WINDOW_MARKER, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, TRANSPORT_RETRY_BASE_MS, TRANSPORT_RETRY_MAX, TRANSPORT_RETRY_MAX_DELAY_MS, } from "../constants.js";
5
+ import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, CONTEXT_DIET_MIN_TOKENS, CONTEXT_DIET_SHARE, DEFENSE_PROVIDER_ID, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RECENT_WINDOW_CARRY_MARKER, RECENT_WINDOW_CARRY_MS, RECENT_WINDOW_MARKER, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, TRANSPORT_RETRY_BASE_MS, TRANSPORT_RETRY_MAX, TRANSPORT_RETRY_MAX_DELAY_MS, } from "../constants.js";
6
6
  import { currentLiveLimits, learnedContextWindow, noteRejectedPrompt, } from "../catalog/live.js";
7
7
  import { closeFreePiSession } from "../api/session.js";
8
8
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
9
9
  import { parseFreePiError } from "../errors/parse.js";
10
10
  import { trimMap } from "../utils/async.js";
11
- import { trimMessagesForBudget } from "./overflow.js";
11
+ import { pruneStaleToolResults } from "./diet.js";
12
+ import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
12
13
  import { buildRecentWindow, carriedWindowGuidance, recentWindowGuidance } from "./recent.js";
13
14
  import { watchFreePiNotice } from "./notices.js";
14
15
  import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
@@ -132,6 +133,42 @@ function appendCarriedWindow(deps, event) {
132
133
  return;
133
134
  appendSystemGuidance(event, carriedWindowGuidance(carried.text), RECENT_WINDOW_CARRY_MARKER);
134
135
  }
136
+ /**
137
+ * Collapses stale tool payloads before a request goes out. Long free-pi
138
+ * sessions reach 100k-170k token prompts, and at that size the free models
139
+ * lose the middle of the conversation and stop following the working rules
140
+ * even though the gateway accepts the request. User wording, assistant text
141
+ * and the newest messages are never touched; only old `read`/`grep`/`shell`
142
+ * results are shortened, with a note that says they were pruned.
143
+ */
144
+ function applyContextDiet(deps, event) {
145
+ const providerID = event.model?.providerID;
146
+ const modelID = event.model?.id;
147
+ if (typeof providerID !== "string" || typeof modelID !== "string")
148
+ return;
149
+ const context = deps.state.contextLimits.get(`${providerID}/${modelID}`);
150
+ if (!context || context <= CONTEXT_DIET_MIN_TOKENS)
151
+ return;
152
+ const budget = Math.max(CONTEXT_DIET_MIN_TOKENS, Math.floor(context * CONTEXT_DIET_SHARE));
153
+ if (budget >= context)
154
+ return;
155
+ const messages = event.messages;
156
+ if (!Array.isArray(messages) || messages.length === 0)
157
+ return;
158
+ const result = pruneStaleToolResults(messages, budget, estimateMessageTokens);
159
+ if (result.pruned === 0)
160
+ return;
161
+ event.messages = [...result.messages];
162
+ deps.log.info("free-pi pruned stale tool results so the prompt stays attended", {
163
+ sessionID: event.sessionID,
164
+ model: modelID,
165
+ context,
166
+ budget,
167
+ pruned: result.pruned,
168
+ tokensBefore: result.tokensBefore,
169
+ tokensAfter: result.tokensAfter,
170
+ });
171
+ }
135
172
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
136
173
  async function applyGeneration(deps, event, kind) {
137
174
  if (!isFreePiProvider(event.model?.providerID))
@@ -175,8 +212,12 @@ async function applyGeneration(deps, event, kind) {
175
212
  // The free models tend to skip planning and claim work they did not do;
176
213
  // the CLI gets a much larger agent prompt. This is the compact equivalent.
177
214
  appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
215
+ applyContextDiet(deps, event);
178
216
  appendCarriedWindow(deps, event);
179
217
  }
218
+ else {
219
+ applyContextDiet(deps, event);
220
+ }
180
221
  const agent = event.agent;
181
222
  const turn = await resolveAdTurn(deps, {
182
223
  sessionID: event.sessionID,
@@ -36,6 +36,7 @@ OpenCode keeps only the latest exchange beside this summary and shortens tool ou
36
36
  The summary you write must end with a section named \`## Recent window\` that reproduces these turns in order. Without it the summary is incomplete and the next agent will not know what was just done.
37
37
 
38
38
  - Keep the user's exact requests, the decisions with their reasons, the commands and file paths, the tool results and errors, and the step that is still in progress.
39
+ - State what each action proved ("read X and confirmed Y"), so the next agent does not repeat it.
39
40
  - Quote the recent turns; do not replace them with a one line recap.
40
41
 
41
42
  ${window.text}`;
package/dist/state.d.ts CHANGED
@@ -14,6 +14,8 @@ export type RuntimeState = {
14
14
  lastQuotaNotice?: string;
15
15
  catalogModels: Catalog;
16
16
  outputLimits: Map<string, number>;
17
+ /** Advertised context window per `provider/model`, for request trimming. */
18
+ contextLimits: Map<string, number>;
17
19
  /** `provider/model` ids whose upstream accepts image input. */
18
20
  imageModels: Set<string>;
19
21
  quotaCache?: QuotaSnapshot;
package/dist/state.js CHANGED
@@ -8,6 +8,7 @@ export function createRuntimeState() {
8
8
  registryAttemptAt: 0,
9
9
  catalogModels: {},
10
10
  outputLimits: new Map(),
11
+ contextLimits: new Map(),
11
12
  imageModels: new Set(),
12
13
  lastQuotaRefreshAt: 0,
13
14
  lastErrorLogAt: 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.6.9",
3
+ "version": "0.7.1",
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/compaction.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/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/catalog.mjs && node test/compaction.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/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
package/src/constants.ts CHANGED
@@ -20,6 +20,15 @@ export const CONTEXT_WINDOW = 200_000;
20
20
  /** Largest window the plugin will ever advertise after measuring the gateway. */
21
21
  export const MAX_CONTEXT_WINDOW = 1_000_000;
22
22
  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 and stop
27
+ * following the working rules, even though the 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;
23
32
  /**
24
33
  * Upper bound for a model that publishes a larger output budget. Reasoning
25
34
  * tokens share this budget, so a model that can emit more must not be pinned to
@@ -91,6 +100,7 @@ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
91
100
  */
92
101
  export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
93
102
  - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
103
+ - For each step in the work state, write the conclusion it proved, not only the file or command: "read X and confirmed Y", "build failed with Z". A list of actions without their findings makes the next agent repeat the work.
94
104
  - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
95
105
  - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
96
106
  - Do not invent progress or results that are not in the conversation.`;
package/src/plugin.ts CHANGED
@@ -218,12 +218,14 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
218
218
  const defenseNow = buildDefense();
219
219
  for (const [id, model] of Object.entries(mainNow)) {
220
220
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
221
+ state.contextLimits.set(`${PROVIDER_ID}/${id}`, model.limit.context);
221
222
  if (model.modalities.input.includes("image")) {
222
223
  state.imageModels.add(`${PROVIDER_ID}/${id}`);
223
224
  }
224
225
  }
225
226
  for (const [id, model] of Object.entries(defenseNow)) {
226
227
  state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
228
+ state.contextLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.context);
227
229
  if (model.modalities.input.includes("image")) {
228
230
  state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
229
231
  }
@@ -0,0 +1,201 @@
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
+ }
@@ -11,6 +11,8 @@ import {
11
11
  CONCURRENT_RETRY_BASE_MS,
12
12
  CONCURRENT_RETRY_MAX,
13
13
  CONCURRENT_RETRY_MAX_DELAY_MS,
14
+ CONTEXT_DIET_MIN_TOKENS,
15
+ CONTEXT_DIET_SHARE,
14
16
  DEFENSE_PROVIDER_ID,
15
17
  FREE_PI_COMPACTION_GUIDANCE,
16
18
  FREE_PI_COMPACTION_MARKER,
@@ -43,7 +45,8 @@ import {
43
45
  } from "../errors/limit.js";
44
46
  import { parseFreePiError } from "../errors/parse.js";
45
47
  import { trimMap } from "../utils/async.js";
46
- import { trimMessagesForBudget } from "./overflow.js";
48
+ import { pruneStaleToolResults } from "./diet.js";
49
+ import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
47
50
  import { buildRecentWindow, carriedWindowGuidance, recentWindowGuidance } from "./recent.js";
48
51
  import type { RecentWindow } from "./recent.js";
49
52
  import { watchFreePiNotice } from "./notices.js";
@@ -249,6 +252,44 @@ function appendCarriedWindow(deps: Deps, event: any): void {
249
252
  );
250
253
  }
251
254
 
255
+ /**
256
+ * Collapses stale tool payloads before a request goes out. Long free-pi
257
+ * sessions reach 100k-170k token prompts, and at that size the free models
258
+ * lose the middle of the conversation and stop following the working rules
259
+ * even though the gateway accepts the request. User wording, assistant text
260
+ * and the newest messages are never touched; only old `read`/`grep`/`shell`
261
+ * results are shortened, with a note that says they were pruned.
262
+ */
263
+ function applyContextDiet(deps: Deps, event: any): void {
264
+ const providerID = event.model?.providerID;
265
+ const modelID = event.model?.id;
266
+ if (typeof providerID !== "string" || typeof modelID !== "string") return;
267
+ const context = deps.state.contextLimits.get(`${providerID}/${modelID}`);
268
+ if (!context || context <= CONTEXT_DIET_MIN_TOKENS) return;
269
+ const budget = Math.max(
270
+ CONTEXT_DIET_MIN_TOKENS,
271
+ Math.floor(context * CONTEXT_DIET_SHARE),
272
+ );
273
+ if (budget >= context) return;
274
+ const messages = event.messages;
275
+ if (!Array.isArray(messages) || messages.length === 0) return;
276
+ const result = pruneStaleToolResults(messages, budget, estimateMessageTokens);
277
+ if (result.pruned === 0) return;
278
+ event.messages = [...result.messages];
279
+ deps.log.info(
280
+ "free-pi pruned stale tool results so the prompt stays attended",
281
+ {
282
+ sessionID: event.sessionID,
283
+ model: modelID,
284
+ context,
285
+ budget,
286
+ pruned: result.pruned,
287
+ tokensBefore: result.tokensBefore,
288
+ tokensAfter: result.tokensAfter,
289
+ },
290
+ );
291
+ }
292
+
252
293
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
253
294
  async function applyGeneration(
254
295
  deps: Deps,
@@ -305,7 +346,10 @@ async function applyGeneration(
305
346
  // The free models tend to skip planning and claim work they did not do;
306
347
  // the CLI gets a much larger agent prompt. This is the compact equivalent.
307
348
  appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
349
+ applyContextDiet(deps, event);
308
350
  appendCarriedWindow(deps, event);
351
+ } else {
352
+ applyContextDiet(deps, event);
309
353
  }
310
354
 
311
355
  const agent = event.agent;
@@ -55,6 +55,7 @@ OpenCode keeps only the latest exchange beside this summary and shortens tool ou
55
55
  The summary you write must end with a section named \`## Recent window\` that reproduces these turns in order. Without it the summary is incomplete and the next agent will not know what was just done.
56
56
 
57
57
  - Keep the user's exact requests, the decisions with their reasons, the commands and file paths, the tool results and errors, and the step that is still in progress.
58
+ - State what each action proved ("read X and confirmed Y"), so the next agent does not repeat it.
58
59
  - Quote the recent turns; do not replace them with a one line recap.
59
60
 
60
61
  ${window.text}`;
package/src/state.ts CHANGED
@@ -29,6 +29,8 @@ export type RuntimeState = {
29
29
  lastQuotaNotice?: string;
30
30
  catalogModels: Catalog;
31
31
  outputLimits: Map<string, number>;
32
+ /** Advertised context window per `provider/model`, for request trimming. */
33
+ contextLimits: Map<string, number>;
32
34
  /** `provider/model` ids whose upstream accepts image input. */
33
35
  imageModels: Set<string>;
34
36
 
@@ -78,6 +80,7 @@ export function createRuntimeState(): RuntimeState {
78
80
  registryAttemptAt: 0,
79
81
  catalogModels: {},
80
82
  outputLimits: new Map(),
83
+ contextLimits: new Map(),
81
84
  imageModels: new Set(),
82
85
  lastQuotaRefreshAt: 0,
83
86
  lastErrorLogAt: 0,