@eduardo191labs/opencode-free-pi 0.6.9 → 0.7.0
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 +10 -0
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -0
- package/dist/plugin.js +2 -0
- package/dist/session/diet.d.ts +23 -0
- package/dist/session/diet.js +124 -0
- package/dist/session/hooks.js +43 -2
- package/dist/session/recent.js +1 -0
- package/dist/state.d.ts +2 -0
- package/dist/state.js +1 -0
- package/package.json +2 -2
- package/src/constants.ts +10 -0
- package/src/plugin.ts +2 -0
- package/src/session/diet.ts +152 -0
- package/src/session/hooks.ts +45 -1
- package/src/session/recent.ts +1 -0
- package/src/state.ts +3 -0
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
|
|
package/dist/constants.d.ts
CHANGED
|
@@ -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,124 @@
|
|
|
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
|
+
function onlyTextParts(content) {
|
|
36
|
+
if (!Array.isArray(content))
|
|
37
|
+
return false;
|
|
38
|
+
return content.every((part) => part?.type === "text" || typeof part?.text === "string");
|
|
39
|
+
}
|
|
40
|
+
function stub(text) {
|
|
41
|
+
const head = text.slice(0, STUB_HEAD_CHARS);
|
|
42
|
+
const tail = text.length > STUB_HEAD_CHARS + STUB_TAIL_CHARS
|
|
43
|
+
? text.slice(-STUB_TAIL_CHARS)
|
|
44
|
+
: "";
|
|
45
|
+
const cut = text.length - head.length - tail.length;
|
|
46
|
+
const note = `[... ${cut} characters of this tool result were pruned so the prompt stays readable; call the tool again if you need them]`;
|
|
47
|
+
return tail ? `${head}\n${note}\n${tail}` : `${head}\n${note}`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The same message with its tool result collapsed, or `undefined` when the
|
|
51
|
+
* message has nothing worth pruning. Both shapes are supported: OpenAI-style
|
|
52
|
+
* `role: "tool"` messages and the native assistant parts with `state.content`.
|
|
53
|
+
*/
|
|
54
|
+
function shrunk(message) {
|
|
55
|
+
const role = messageRole(message);
|
|
56
|
+
const record = message;
|
|
57
|
+
if (role === "tool") {
|
|
58
|
+
const text = typeof record.content === "string"
|
|
59
|
+
? record.content
|
|
60
|
+
: onlyTextParts(record.content)
|
|
61
|
+
? textOfContent(record.content)
|
|
62
|
+
: "";
|
|
63
|
+
if (text.length < MIN_PRUNE_CHARS)
|
|
64
|
+
return undefined;
|
|
65
|
+
return { ...record, content: stub(text) };
|
|
66
|
+
}
|
|
67
|
+
if (role !== "assistant" || !Array.isArray(record.content))
|
|
68
|
+
return undefined;
|
|
69
|
+
const parts = record.content;
|
|
70
|
+
let changed = false;
|
|
71
|
+
const next = parts.map((part) => {
|
|
72
|
+
if (part?.type !== "tool" || !part.state)
|
|
73
|
+
return part;
|
|
74
|
+
const text = textOfContent(part.state.content);
|
|
75
|
+
if (text.length < MIN_PRUNE_CHARS)
|
|
76
|
+
return part;
|
|
77
|
+
changed = true;
|
|
78
|
+
return {
|
|
79
|
+
...part,
|
|
80
|
+
state: { ...part.state, content: [{ type: "text", text: stub(text) }] },
|
|
81
|
+
};
|
|
82
|
+
});
|
|
83
|
+
return changed ? { ...record, content: next } : undefined;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Collapses stale tool results until the request fits `budget` tokens. The
|
|
87
|
+
* newest messages (up to half the budget) are protected so the model always
|
|
88
|
+
* sees what it was doing. Returns the same list untouched when it already fits.
|
|
89
|
+
*/
|
|
90
|
+
export function pruneStaleToolResults(messages, budget, estimate) {
|
|
91
|
+
const tokensBefore = messages.reduce((sum, message) => sum + estimate(message), 0);
|
|
92
|
+
if (messages.length === 0 || !(budget > 0) || tokensBefore <= budget) {
|
|
93
|
+
return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
|
|
94
|
+
}
|
|
95
|
+
const sizes = messages.map(estimate);
|
|
96
|
+
let protectedStart = messages.length;
|
|
97
|
+
let tail = 0;
|
|
98
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
99
|
+
const size = sizes[index];
|
|
100
|
+
if (tail > 0 && tail + size > budget * 0.5)
|
|
101
|
+
break;
|
|
102
|
+
tail += size;
|
|
103
|
+
protectedStart = index;
|
|
104
|
+
}
|
|
105
|
+
const out = [...messages];
|
|
106
|
+
let total = tokensBefore;
|
|
107
|
+
let pruned = 0;
|
|
108
|
+
for (let index = 0; index < protectedStart && total > budget; index += 1) {
|
|
109
|
+
const smaller = shrunk(out[index]);
|
|
110
|
+
if (!smaller)
|
|
111
|
+
continue;
|
|
112
|
+
const size = estimate(smaller);
|
|
113
|
+
if (size >= sizes[index])
|
|
114
|
+
continue;
|
|
115
|
+
total -= sizes[index] - size;
|
|
116
|
+
sizes[index] = size;
|
|
117
|
+
out[index] = smaller;
|
|
118
|
+
pruned += 1;
|
|
119
|
+
}
|
|
120
|
+
if (pruned === 0) {
|
|
121
|
+
return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
|
|
122
|
+
}
|
|
123
|
+
return { messages: out, pruned, tokensBefore, tokensAfter: total };
|
|
124
|
+
}
|
package/dist/session/hooks.js
CHANGED
|
@@ -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 {
|
|
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,
|
package/dist/session/recent.js
CHANGED
|
@@ -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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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,152 @@
|
|
|
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
|
+
};
|
|
33
|
+
|
|
34
|
+
function messageRole(message: unknown): string | undefined {
|
|
35
|
+
const role = (message as { role?: unknown } | undefined)?.role;
|
|
36
|
+
return typeof role === "string" ? role : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Text of a tool result in either the request shape or the native one. */
|
|
40
|
+
function textOfContent(content: unknown): string {
|
|
41
|
+
if (typeof content === "string") return content;
|
|
42
|
+
if (!Array.isArray(content)) return "";
|
|
43
|
+
let text = "";
|
|
44
|
+
for (const part of content as Part[]) {
|
|
45
|
+
if (typeof part?.text === "string") text += part.text;
|
|
46
|
+
}
|
|
47
|
+
return text;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function onlyTextParts(content: unknown): boolean {
|
|
51
|
+
if (!Array.isArray(content)) return false;
|
|
52
|
+
return (content as Part[]).every(
|
|
53
|
+
(part) => part?.type === "text" || typeof part?.text === "string",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function stub(text: string): string {
|
|
58
|
+
const head = text.slice(0, STUB_HEAD_CHARS);
|
|
59
|
+
const tail =
|
|
60
|
+
text.length > STUB_HEAD_CHARS + STUB_TAIL_CHARS
|
|
61
|
+
? text.slice(-STUB_TAIL_CHARS)
|
|
62
|
+
: "";
|
|
63
|
+
const cut = text.length - head.length - tail.length;
|
|
64
|
+
const note = `[... ${cut} characters of this tool result were pruned so the prompt stays readable; call the tool again if you need them]`;
|
|
65
|
+
return tail ? `${head}\n${note}\n${tail}` : `${head}\n${note}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The same message with its tool result collapsed, or `undefined` when the
|
|
70
|
+
* message has nothing worth pruning. Both shapes are supported: OpenAI-style
|
|
71
|
+
* `role: "tool"` messages and the native assistant parts with `state.content`.
|
|
72
|
+
*/
|
|
73
|
+
function shrunk(message: unknown): unknown | undefined {
|
|
74
|
+
const role = messageRole(message);
|
|
75
|
+
const record = message as Record<string, unknown> & {
|
|
76
|
+
content?: unknown;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
if (role === "tool") {
|
|
80
|
+
const text =
|
|
81
|
+
typeof record.content === "string"
|
|
82
|
+
? record.content
|
|
83
|
+
: onlyTextParts(record.content)
|
|
84
|
+
? textOfContent(record.content)
|
|
85
|
+
: "";
|
|
86
|
+
if (text.length < MIN_PRUNE_CHARS) return undefined;
|
|
87
|
+
return { ...record, content: stub(text) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (role !== "assistant" || !Array.isArray(record.content)) return undefined;
|
|
91
|
+
const parts = record.content as Part[];
|
|
92
|
+
let changed = false;
|
|
93
|
+
const next = parts.map((part) => {
|
|
94
|
+
if (part?.type !== "tool" || !part.state) return part;
|
|
95
|
+
const text = textOfContent(part.state.content);
|
|
96
|
+
if (text.length < MIN_PRUNE_CHARS) return part;
|
|
97
|
+
changed = true;
|
|
98
|
+
return {
|
|
99
|
+
...part,
|
|
100
|
+
state: { ...part.state, content: [{ type: "text", text: stub(text) }] },
|
|
101
|
+
};
|
|
102
|
+
});
|
|
103
|
+
return changed ? { ...record, content: next } : undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Collapses stale tool results until the request fits `budget` tokens. The
|
|
108
|
+
* newest messages (up to half the budget) are protected so the model always
|
|
109
|
+
* sees what it was doing. Returns the same list untouched when it already fits.
|
|
110
|
+
*/
|
|
111
|
+
export function pruneStaleToolResults(
|
|
112
|
+
messages: readonly unknown[],
|
|
113
|
+
budget: number,
|
|
114
|
+
estimate: (message: unknown) => number,
|
|
115
|
+
): DietResult {
|
|
116
|
+
const tokensBefore = messages.reduce<number>(
|
|
117
|
+
(sum, message) => sum + estimate(message),
|
|
118
|
+
0,
|
|
119
|
+
);
|
|
120
|
+
if (messages.length === 0 || !(budget > 0) || tokensBefore <= budget) {
|
|
121
|
+
return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const sizes = messages.map(estimate);
|
|
125
|
+
let protectedStart = messages.length;
|
|
126
|
+
let tail = 0;
|
|
127
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
128
|
+
const size = sizes[index]!;
|
|
129
|
+
if (tail > 0 && tail + size > budget * 0.5) break;
|
|
130
|
+
tail += size;
|
|
131
|
+
protectedStart = index;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const out = [...messages];
|
|
135
|
+
let total = tokensBefore;
|
|
136
|
+
let pruned = 0;
|
|
137
|
+
for (let index = 0; index < protectedStart && total > budget; index += 1) {
|
|
138
|
+
const smaller = shrunk(out[index]);
|
|
139
|
+
if (!smaller) continue;
|
|
140
|
+
const size = estimate(smaller);
|
|
141
|
+
if (size >= sizes[index]!) continue;
|
|
142
|
+
total -= sizes[index]! - size;
|
|
143
|
+
sizes[index] = size;
|
|
144
|
+
out[index] = smaller;
|
|
145
|
+
pruned += 1;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (pruned === 0) {
|
|
149
|
+
return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
|
|
150
|
+
}
|
|
151
|
+
return { messages: out, pruned, tokensBefore, tokensAfter: total };
|
|
152
|
+
}
|
package/src/session/hooks.ts
CHANGED
|
@@ -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 {
|
|
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;
|
package/src/session/recent.ts
CHANGED
|
@@ -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,
|