@eduardo191labs/opencode-free-pi 0.7.17 → 0.7.19

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,5 +1,5 @@
1
1
  /** Builds and redacts the ad context sent with a user turn. */
2
- import { AD_CONTEXT_MAX_CHARS, TURN_REMINDER_MARKER } from "../constants.js";
2
+ import { AD_CONTEXT_MAX_CHARS } from "../constants.js";
3
3
  import { cleanText } from "../utils/text.js";
4
4
  /** Start of the synthetic user message OpenCode creates for a finished subagent. */
5
5
  const SUBAGENT_RESULT_PREFIX = "<subagent ";
@@ -144,7 +144,6 @@ function messageText(message) {
144
144
  */
145
145
  function isRealUserTurn(text) {
146
146
  return (text.length > 0 &&
147
- !text.startsWith(TURN_REMINDER_MARKER) &&
148
147
  !SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix)));
149
148
  }
150
149
  /** Number of real user turns; synthetic messages do not start a new one. */
@@ -53,49 +53,6 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
53
53
  export declare const DEFAULT_REASONING_EFFORT = "high";
54
54
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
55
55
  export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "max"];
56
- /**
57
- * Injected into every primary free-pi request. OpenCode already supplies the
58
- * coding instructions; this block covers the failure modes the weaker free
59
- * models show: skipping analysis, inventing verification, and ignoring the
60
- * context the conversation already established.
61
- */
62
- export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass. In `edit`, `oldString` must differ from `newString` and match exactly once; add surrounding lines when it is ambiguous.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (`read`, `grep`, `glob`, `shell`, `edit`) for real work; do not describe hypothetical commands as if they ran. Prefer `read`, `grep` and `glob` over shell for inspecting files.\n- The `shell` tool runs a portable scanner, not a full bash. Heredocs (`<<EOF`), chained one-liners with nested or heavy-escaped quotes, and some shells' loops are rejected before they run. Put any complex script in a file with `write` and run that file. On Windows the shell is PowerShell: use `Get-ChildItem`/`Select-String`, not `dir /b`, `findstr` or `cmd /c`.\n- Reply in the language of the user's latest message; keep code, paths and identifiers unchanged.\n- Delegate large or self-contained work with OpenCode's native `subagent` tool: `free-pi/scout` and `free-pi/planner` for read-only recon and planning, `free-pi/worker` for a full task, `free-pi/reviewer` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one. The `subagent` tool returns a child `sessionID` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call `free_pi_subagent_read` with its `sessionID` (omit it to list this session's children).\n- Load a skill with the native `skill` tool when its description matches the task.\n- `AGENTS.md` and the files listed under `instructions` are the project's memory. Follow them; do not restate or replace them.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Never answer with a session summary or with `## Objective` / `## Work State` blocks; that format belongs to compaction. If the work is unfinished, take the next concrete action instead of describing the state.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
63
- export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
64
- /**
65
- * Appended to OpenCode's compaction request. Its default summary prompt asks
66
- * for terse checkpoints, which is fine for strong models but loses the exact
67
- * facts the free models need; spell out what must survive the rewrite.
68
- */
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.";
70
- export declare const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
71
- /**
72
- * Repeats the two rules the free models break when the prompt is long: they
73
- * stop to describe the session state instead of acting, and they answer a
74
- * request to search from memory. It is sent as the last message of a primary
75
- * request because the free models read that position, while rules buried in a
76
- * 100k-token system prompt are easy to ignore. It is not a user instruction and
77
- * never becomes part of the stored conversation.
78
- */
79
- export declare const TURN_REMINDER = "# free-pi turn check (not a user request)\nYou are in a normal working turn, not a compaction.\n- Never answer with `## Objective`, `## Requirements`, `## Work State` or a session summary; that format belongs only to a compaction. Earlier sections with those names are history, not an answer template.\n- If the user asked to search, find, analyze or verify something, call the matching tool first (grep/glob/shell for files, websearch/webfetch for the web) and report what it returned.\n- Keep each shell command simple: no heredocs, no nested-quote one-liners, and PowerShell cmdlets on Windows. Write a script file and run it when the command is complex.\n- If the task is unfinished, call the next tool now instead of describing the state.";
80
- export declare const TURN_REMINDER_MARKER = "# free-pi turn check";
81
- /**
82
- * OpenCode keeps only the latest exchange beside a summary, so after a
83
- * compaction the turns that mattered a minute ago disappear unless the summary
84
- * carries them. The plugin reads the session from the native API and echoes the
85
- * newest turns into the summarizer request, so the summary can reproduce them.
86
- */
87
- export declare const RECENT_WINDOW_MARKER = "# free-pi recent window";
88
- /** Characters of the newest turns quoted back into the summary request. */
89
- export declare const RECENT_WINDOW_CHARS = 24000;
90
- /** Messages read from the tail of the session to build that window. */
91
- export declare const RECENT_WINDOW_MESSAGES = 120;
92
- /**
93
- * The same window rides along on the first request after a compaction, in case
94
- * the summary compressed it away. It is quoted once and expires, so it never
95
- * becomes a second, permanent history.
96
- */
97
- export declare const RECENT_WINDOW_CARRY_MARKER = "# free-pi carried window";
98
- export declare const RECENT_WINDOW_CARRY_MS: number;
99
56
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
100
57
  export declare const HEADER_TIMEOUT_MS = 300000;
101
58
  export declare const CHUNK_TIMEOUT_MS = 300000;
package/dist/constants.js CHANGED
@@ -67,72 +67,6 @@ export const DEFAULT_THINKING_LEVELS = [
67
67
  "high",
68
68
  "max",
69
69
  ];
70
- /**
71
- * Injected into every primary free-pi request. OpenCode already supplies the
72
- * coding instructions; this block covers the failure modes the weaker free
73
- * models show: skipping analysis, inventing verification, and ignoring the
74
- * context the conversation already established.
75
- */
76
- export const FREE_PI_GUIDANCE = `# free-pi working rules
77
- - Answer the user's latest request and keep their constraints; do not switch to a different task.
78
- - Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.
79
- - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass. In \`edit\`, \`oldString\` must differ from \`newString\` and match exactly once; add surrounding lines when it is ambiguous.
80
- - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
81
- - Use the available tools (\`read\`, \`grep\`, \`glob\`, \`shell\`, \`edit\`) for real work; do not describe hypothetical commands as if they ran. Prefer \`read\`, \`grep\` and \`glob\` over shell for inspecting files.
82
- - The \`shell\` tool runs a portable scanner, not a full bash. Heredocs (\`<<EOF\`), chained one-liners with nested or heavy-escaped quotes, and some shells' loops are rejected before they run. Put any complex script in a file with \`write\` and run that file. On Windows the shell is PowerShell: use \`Get-ChildItem\`/\`Select-String\`, not \`dir /b\`, \`findstr\` or \`cmd /c\`.
83
- - Reply in the language of the user's latest message; keep code, paths and identifiers unchanged.
84
- - Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one. The \`subagent\` tool returns a child \`sessionID\` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call \`free_pi_subagent_read\` with its \`sessionID\` (omit it to list this session's children).
85
- - Load a skill with the native \`skill\` tool when its description matches the task.
86
- - \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
87
- - Never claim to have compacted, summarized or cleared context unless that actually happened.
88
- - Never answer with a session summary or with \`## Objective\` / \`## Work State\` blocks; that format belongs to compaction. If the work is unfinished, take the next concrete action instead of describing the state.
89
- - Continue until the request is finished, then report concisely what changed and what you verified.`;
90
- export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
91
- /**
92
- * Appended to OpenCode's compaction request. Its default summary prompt asks
93
- * for terse checkpoints, which is fine for strong models but loses the exact
94
- * facts the free models need; spell out what must survive the rewrite.
95
- */
96
- export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
97
- - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
98
- - 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.
99
- - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
100
- - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
101
- - Do not invent progress or results that are not in the conversation.`;
102
- export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
103
- /**
104
- * Repeats the two rules the free models break when the prompt is long: they
105
- * stop to describe the session state instead of acting, and they answer a
106
- * request to search from memory. It is sent as the last message of a primary
107
- * request because the free models read that position, while rules buried in a
108
- * 100k-token system prompt are easy to ignore. It is not a user instruction and
109
- * never becomes part of the stored conversation.
110
- */
111
- export const TURN_REMINDER = `# free-pi turn check (not a user request)
112
- You are in a normal working turn, not a compaction.
113
- - Never answer with \`## Objective\`, \`## Requirements\`, \`## Work State\` or a session summary; that format belongs only to a compaction. Earlier sections with those names are history, not an answer template.
114
- - If the user asked to search, find, analyze or verify something, call the matching tool first (grep/glob/shell for files, websearch/webfetch for the web) and report what it returned.
115
- - Keep each shell command simple: no heredocs, no nested-quote one-liners, and PowerShell cmdlets on Windows. Write a script file and run it when the command is complex.
116
- - If the task is unfinished, call the next tool now instead of describing the state.`;
117
- export const TURN_REMINDER_MARKER = "# free-pi turn check";
118
- /**
119
- * OpenCode keeps only the latest exchange beside a summary, so after a
120
- * compaction the turns that mattered a minute ago disappear unless the summary
121
- * carries them. The plugin reads the session from the native API and echoes the
122
- * newest turns into the summarizer request, so the summary can reproduce them.
123
- */
124
- export const RECENT_WINDOW_MARKER = "# free-pi recent window";
125
- /** Characters of the newest turns quoted back into the summary request. */
126
- export const RECENT_WINDOW_CHARS = 24_000;
127
- /** Messages read from the tail of the session to build that window. */
128
- export const RECENT_WINDOW_MESSAGES = 120;
129
- /**
130
- * The same window rides along on the first request after a compaction, in case
131
- * the summary compressed it away. It is quoted once and expires, so it never
132
- * becomes a second, permanent history.
133
- */
134
- export const RECENT_WINDOW_CARRY_MARKER = "# free-pi carried window";
135
- export const RECENT_WINDOW_CARRY_MS = 60 * 60_000;
136
70
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
137
71
  export const HEADER_TIMEOUT_MS = 300_000;
138
72
  export const CHUNK_TIMEOUT_MS = 300_000;
@@ -2,7 +2,7 @@
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, 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, TURN_REMINDER, TURN_REMINDER_MARKER, } 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, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, 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";
@@ -10,7 +10,6 @@ import { parseFreePiError } from "../errors/parse.js";
10
10
  import { trimMap } from "../utils/async.js";
11
11
  import { pruneStaleToolResults } from "./diet.js";
12
12
  import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
13
- import { buildRecentWindow, carriedWindowGuidance, recentWindowGuidance } from "./recent.js";
14
13
  import { watchFreePiNotice } from "./notices.js";
15
14
  import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
16
15
  import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, } from "./replay.js";
@@ -58,123 +57,6 @@ function fitCompactionMessages(deps, event, reserveTokens = 0) {
58
57
  promptTokens: trimmed.tokens,
59
58
  });
60
59
  }
61
- /** Adds a system block once, without mutating the array OpenCode may reuse. */
62
- function appendSystemGuidance(event, text, marker) {
63
- const system = Array.isArray(event.system) ? event.system : [];
64
- if (system.some((part) => part?.type === "text" &&
65
- typeof part.text === "string" &&
66
- part.text.startsWith(marker))) {
67
- return;
68
- }
69
- // A fresh array: OpenCode reuses the event across hooks, and pushing into the
70
- // shared array would carry this block into the next, unrelated request.
71
- event.system = [...system, { type: "text", text }];
72
- }
73
- /**
74
- * Removes guidance blocks that belong to another kind of request. OpenCode can
75
- * hand the same event to several hooks, so the compaction rules have to be
76
- * stripped before a primary turn: otherwise the model reads them as an order to
77
- * answer with a summary and burns the turn writing "## Objective / ## Work
78
- * State" instead of doing the work.
79
- */
80
- function stripSystemGuidance(event, markers) {
81
- if (!Array.isArray(event.system))
82
- return;
83
- const kept = event.system.filter((part) => !(part?.type === "text" &&
84
- typeof part.text === "string" &&
85
- markers.some((marker) => part.text.startsWith(marker))));
86
- if (kept.length !== event.system.length)
87
- event.system = kept;
88
- }
89
- /**
90
- * Reads the newest turns of the session from the native API. That history is
91
- * the only place where the work done just before a compaction still exists
92
- * verbatim: OpenCode's own request carries a shortened transcript, and after
93
- * the compaction it keeps only the latest exchange.
94
- */
95
- async function recentWindowForSession(deps, event) {
96
- if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
97
- return undefined;
98
- }
99
- const history = await deps.readContext(event.sessionID).catch(() => []);
100
- if (!Array.isArray(history) || history.length === 0)
101
- return undefined;
102
- return buildRecentWindow(history);
103
- }
104
- /**
105
- * Sends the window both in the system prompt and at the end of the request.
106
- * Free models ignore rules buried up front, but they do read the last message.
107
- */
108
- function applyRecentWindow(deps, event, window) {
109
- const guidance = recentWindowGuidance(window);
110
- appendSystemGuidance(event, guidance, RECENT_WINDOW_MARKER);
111
- const messages = Array.isArray(event.messages) ? event.messages : [];
112
- const already = messages.some((message) => Array.isArray(message?.content)
113
- ? message.content.some((part) => part?.type === "text" &&
114
- typeof part.text === "string" &&
115
- part.text.startsWith(RECENT_WINDOW_MARKER))
116
- : false);
117
- if (!already) {
118
- // A fresh array: OpenCode reuses the event across hooks, and appending to
119
- // the shared array would carry this block into the stored conversation and
120
- // the next, unrelated request.
121
- event.messages = [
122
- ...messages,
123
- { role: "user", content: [{ type: "text", text: guidance }] },
124
- ];
125
- }
126
- // Keep the same text for the next request: if the summary compressed the
127
- // newest turns anyway, the agent still sees what it was doing.
128
- trimMap(deps.state.recentWindows, PENDING_LIMIT);
129
- deps.state.recentWindows.set(event.sessionID, {
130
- at: Date.now(),
131
- text: window.text,
132
- });
133
- deps.log.info("free-pi quoted the newest turns into the compaction summary", {
134
- sessionID: event.sessionID,
135
- model: event.model?.id,
136
- messages: window.messages,
137
- chars: window.text.length,
138
- truncated: window.truncated,
139
- });
140
- }
141
- /**
142
- * Hands the window saved at the last compaction to the first request after it,
143
- * once. A stale entry is dropped instead of carried: the summary is the history
144
- * by then.
145
- */
146
- function appendCarriedWindow(deps, event) {
147
- if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
148
- return;
149
- }
150
- const carried = deps.state.recentWindows.get(event.sessionID);
151
- if (!carried)
152
- return;
153
- deps.state.recentWindows.delete(event.sessionID);
154
- if (Date.now() - carried.at > RECENT_WINDOW_CARRY_MS)
155
- return;
156
- appendSystemGuidance(event, carriedWindowGuidance(carried.text), RECENT_WINDOW_CARRY_MARKER);
157
- }
158
- /**
159
- * Puts the two rules weak free models forget on long conversations at the end
160
- * of a primary request. The ad turn is resolved before this runs, so the
161
- * reminder never leaks into `x-ad-context`. A fresh array keeps it out of the
162
- * stored conversation and out of a later compaction request.
163
- */
164
- function appendTurnReminder(event) {
165
- const messages = Array.isArray(event.messages) ? event.messages : [];
166
- const already = messages.some((message) => Array.isArray(message?.content)
167
- ? message.content.some((part) => part?.type === "text" &&
168
- typeof part.text === "string" &&
169
- part.text.startsWith(TURN_REMINDER_MARKER))
170
- : false);
171
- if (already)
172
- return;
173
- event.messages = [
174
- ...messages,
175
- { role: "user", content: [{ type: "text", text: TURN_REMINDER }] },
176
- ];
177
- }
178
60
  /**
179
61
  * Collapses stale tool payloads before a request goes out. Long free-pi
180
62
  * sessions reach 100k-170k token prompts, and at that size the free models
@@ -297,16 +179,7 @@ async function applyGeneration(deps, event, kind) {
297
179
  event.options.maxTokens = cap;
298
180
  }
299
181
  if (kind === "compaction") {
300
- // Quote the newest turns first: they must survive the trim below, because
301
- // OpenCode keeps only the last exchange beside the summary afterwards.
302
- const window = await recentWindowForSession(deps, event);
303
- const reserve = window
304
- ? Math.ceil(recentWindowGuidance(window).length / 4)
305
- : 0;
306
- fitCompactionMessages(deps, event, reserve);
307
- appendSystemGuidance(event, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER);
308
- if (window)
309
- applyRecentWindow(deps, event, window);
182
+ fitCompactionMessages(deps, event);
310
183
  // OpenCode sends the messages it is folding into the summary, which is the
311
184
  // same set pi reports through `session_before_compact`.
312
185
  recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
@@ -318,15 +191,9 @@ async function applyGeneration(deps, event, kind) {
318
191
  markWireSessionDirty(deps, event.sessionID);
319
192
  }
320
193
  else if (kind === "primary") {
321
- // The free models tend to skip planning and claim work they did not do;
322
- // the CLI gets a much larger agent prompt. This is the compact equivalent.
323
- stripSystemGuidance(event, [FREE_PI_COMPACTION_MARKER]);
324
- appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
325
194
  applyContextDiet(deps, event);
326
- appendCarriedWindow(deps, event);
327
195
  }
328
196
  else {
329
- stripSystemGuidance(event, [FREE_PI_COMPACTION_MARKER]);
330
197
  applyContextDiet(deps, event);
331
198
  }
332
199
  const agent = event.agent;
@@ -339,9 +206,6 @@ async function applyGeneration(deps, event, kind) {
339
206
  if (turn) {
340
207
  rememberPending(deps, pendingKeyOf(event.sessionID, agent, kind), turn);
341
208
  }
342
- // After the ad turn: the reminder must not be mistaken for the user prompt.
343
- if (kind === "primary")
344
- appendTurnReminder(event);
345
209
  }
346
210
  /** Adds auth and per-turn ad headers to the outgoing model request. */
347
211
  async function applyModelRequest(deps, event) {
@@ -62,8 +62,7 @@ export function traceRequestBody(deps, sessionID, body, headers) {
62
62
  const last = messages.at(-1);
63
63
  const lastRealUser = [...messages]
64
64
  .reverse()
65
- .find((message) => message.role === "user" &&
66
- !textOf(message.content).startsWith("# free-pi turn check"));
65
+ .find((message) => message.role === "user");
67
66
  deps.log.info("free-pi trace request", {
68
67
  sessionID,
69
68
  model: parsed.model,
package/dist/state.d.ts CHANGED
@@ -59,10 +59,5 @@ export type RuntimeState = {
59
59
  deniedModels: Set<string>;
60
60
  toolStats: Map<string, ToolStats>;
61
61
  subagentSessions: Set<string>;
62
- /** Newest turns quoted at the last compaction, carried once into the next request. */
63
- recentWindows: Map<string, {
64
- at: number;
65
- text: string;
66
- }>;
67
62
  };
68
63
  export declare function createRuntimeState(): RuntimeState;
package/dist/state.js CHANGED
@@ -33,6 +33,5 @@ export function createRuntimeState() {
33
33
  deniedModels: new Set(),
34
34
  toolStats: new Map(),
35
35
  subagentSessions: new Set(),
36
- recentWindows: new Map(),
37
36
  };
38
37
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.17",
3
+ "version": "0.7.19",
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/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/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/catalog.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/overflow.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -1,6 +1,6 @@
1
1
  /** Builds and redacts the ad context sent with a user turn. */
2
2
 
3
- import { AD_CONTEXT_MAX_CHARS, TURN_REMINDER_MARKER } from "../constants.js";
3
+ import { AD_CONTEXT_MAX_CHARS } from "../constants.js";
4
4
  import { cleanText } from "../utils/text.js";
5
5
 
6
6
  /** Start of the synthetic user message OpenCode creates for a finished subagent. */
@@ -178,7 +178,6 @@ function messageText(message: AdMessage): string {
178
178
  function isRealUserTurn(text: string): boolean {
179
179
  return (
180
180
  text.length > 0 &&
181
- !text.startsWith(TURN_REMINDER_MARKER) &&
182
181
  !SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix))
183
182
  );
184
183
  }
package/src/constants.ts CHANGED
@@ -74,75 +74,6 @@ export const DEFAULT_THINKING_LEVELS = [
74
74
  "max",
75
75
  ] as const;
76
76
 
77
- /**
78
- * Injected into every primary free-pi request. OpenCode already supplies the
79
- * coding instructions; this block covers the failure modes the weaker free
80
- * models show: skipping analysis, inventing verification, and ignoring the
81
- * context the conversation already established.
82
- */
83
- export const FREE_PI_GUIDANCE = `# free-pi working rules
84
- - Answer the user's latest request and keep their constraints; do not switch to a different task.
85
- - Slow down on multi-step work (arithmetic, counting, logic, dates, units, planning, debugging): write out each step, recompute the result a second way, and only then answer. On those tasks a correct answer after a dozen explicit steps beats a fast guess; do not stop at the first plausible number.
86
- - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass. In \`edit\`, \`oldString\` must differ from \`newString\` and match exactly once; add surrounding lines when it is ambiguous.
87
- - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
88
- - Use the available tools (\`read\`, \`grep\`, \`glob\`, \`shell\`, \`edit\`) for real work; do not describe hypothetical commands as if they ran. Prefer \`read\`, \`grep\` and \`glob\` over shell for inspecting files.
89
- - The \`shell\` tool runs a portable scanner, not a full bash. Heredocs (\`<<EOF\`), chained one-liners with nested or heavy-escaped quotes, and some shells' loops are rejected before they run. Put any complex script in a file with \`write\` and run that file. On Windows the shell is PowerShell: use \`Get-ChildItem\`/\`Select-String\`, not \`dir /b\`, \`findstr\` or \`cmd /c\`.
90
- - Reply in the language of the user's latest message; keep code, paths and identifiers unchanged.
91
- - Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one. The \`subagent\` tool returns a child \`sessionID\` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call \`free_pi_subagent_read\` with its \`sessionID\` (omit it to list this session's children).
92
- - Load a skill with the native \`skill\` tool when its description matches the task.
93
- - \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
94
- - Never claim to have compacted, summarized or cleared context unless that actually happened.
95
- - Never answer with a session summary or with \`## Objective\` / \`## Work State\` blocks; that format belongs to compaction. If the work is unfinished, take the next concrete action instead of describing the state.
96
- - Continue until the request is finished, then report concisely what changed and what you verified.`;
97
- export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
98
-
99
- /**
100
- * Appended to OpenCode's compaction request. Its default summary prompt asks
101
- * for terse checkpoints, which is fine for strong models but loses the exact
102
- * facts the free models need; spell out what must survive the rewrite.
103
- */
104
- export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
105
- - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
106
- - 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.
107
- - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
108
- - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
109
- - Do not invent progress or results that are not in the conversation.`;
110
- export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
111
-
112
- /**
113
- * Repeats the two rules the free models break when the prompt is long: they
114
- * stop to describe the session state instead of acting, and they answer a
115
- * request to search from memory. It is sent as the last message of a primary
116
- * request because the free models read that position, while rules buried in a
117
- * 100k-token system prompt are easy to ignore. It is not a user instruction and
118
- * never becomes part of the stored conversation.
119
- */
120
- export const TURN_REMINDER = `# free-pi turn check (not a user request)
121
- You are in a normal working turn, not a compaction.
122
- - Never answer with \`## Objective\`, \`## Requirements\`, \`## Work State\` or a session summary; that format belongs only to a compaction. Earlier sections with those names are history, not an answer template.
123
- - If the user asked to search, find, analyze or verify something, call the matching tool first (grep/glob/shell for files, websearch/webfetch for the web) and report what it returned.
124
- - Keep each shell command simple: no heredocs, no nested-quote one-liners, and PowerShell cmdlets on Windows. Write a script file and run it when the command is complex.
125
- - If the task is unfinished, call the next tool now instead of describing the state.`;
126
- export const TURN_REMINDER_MARKER = "# free-pi turn check";
127
-
128
- /**
129
- * OpenCode keeps only the latest exchange beside a summary, so after a
130
- * compaction the turns that mattered a minute ago disappear unless the summary
131
- * carries them. The plugin reads the session from the native API and echoes the
132
- * newest turns into the summarizer request, so the summary can reproduce them.
133
- */
134
- export const RECENT_WINDOW_MARKER = "# free-pi recent window";
135
- /** Characters of the newest turns quoted back into the summary request. */
136
- export const RECENT_WINDOW_CHARS = 24_000;
137
- /** Messages read from the tail of the session to build that window. */
138
- export const RECENT_WINDOW_MESSAGES = 120;
139
- /**
140
- * The same window rides along on the first request after a compaction, in case
141
- * the summary compressed it away. It is quoted once and expires, so it never
142
- * becomes a second, permanent history.
143
- */
144
- export const RECENT_WINDOW_CARRY_MARKER = "# free-pi carried window";
145
- export const RECENT_WINDOW_CARRY_MS = 60 * 60_000;
146
77
 
147
78
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
148
79
  export const HEADER_TIMEOUT_MS = 300_000;
@@ -14,16 +14,9 @@ import {
14
14
  CONTEXT_DIET_MIN_TOKENS,
15
15
  CONTEXT_DIET_SHARE,
16
16
  DEFENSE_PROVIDER_ID,
17
- FREE_PI_COMPACTION_GUIDANCE,
18
- FREE_PI_COMPACTION_MARKER,
19
- FREE_PI_GUIDANCE,
20
- FREE_PI_GUIDANCE_MARKER,
21
17
  MAX_OUTPUT_TOKENS,
22
18
  MAX_OUTPUT_TOKENS_CEILING,
23
19
  PROVIDER_ID,
24
- RECENT_WINDOW_CARRY_MARKER,
25
- RECENT_WINDOW_CARRY_MS,
26
- RECENT_WINDOW_MARKER,
27
20
  RETRY_BASE_DELAY_MS,
28
21
  RETRY_MAX_DELAY_MS,
29
22
  RETRY_MAX_RETRIES,
@@ -31,8 +24,6 @@ import {
31
24
  TRANSPORT_RETRY_BASE_MS,
32
25
  TRANSPORT_RETRY_MAX,
33
26
  TRANSPORT_RETRY_MAX_DELAY_MS,
34
- TURN_REMINDER,
35
- TURN_REMINDER_MARKER,
36
27
  } from "../constants.js";
37
28
  import {
38
29
  currentLiveLimits,
@@ -49,8 +40,6 @@ import { parseFreePiError } from "../errors/parse.js";
49
40
  import { trimMap } from "../utils/async.js";
50
41
  import { pruneStaleToolResults } from "./diet.js";
51
42
  import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
52
- import { buildRecentWindow, carriedWindowGuidance, recentWindowGuidance } from "./recent.js";
53
- import type { RecentWindow } from "./recent.js";
54
43
  import { watchFreePiNotice } from "./notices.js";
55
44
  import {
56
45
  clearSpuriousOverflows,
@@ -150,161 +139,6 @@ function fitCompactionMessages(
150
139
  );
151
140
  }
152
141
 
153
- /** Adds a system block once, without mutating the array OpenCode may reuse. */
154
- function appendSystemGuidance(
155
- event: any,
156
- text: string,
157
- marker: string,
158
- ): void {
159
- const system = Array.isArray(event.system) ? event.system : [];
160
- if (
161
- system.some(
162
- (part: any) =>
163
- part?.type === "text" &&
164
- typeof part.text === "string" &&
165
- part.text.startsWith(marker),
166
- )
167
- ) {
168
- return;
169
- }
170
- // A fresh array: OpenCode reuses the event across hooks, and pushing into the
171
- // shared array would carry this block into the next, unrelated request.
172
- event.system = [...system, { type: "text", text }];
173
- }
174
-
175
- /**
176
- * Removes guidance blocks that belong to another kind of request. OpenCode can
177
- * hand the same event to several hooks, so the compaction rules have to be
178
- * stripped before a primary turn: otherwise the model reads them as an order to
179
- * answer with a summary and burns the turn writing "## Objective / ## Work
180
- * State" instead of doing the work.
181
- */
182
- function stripSystemGuidance(event: any, markers: readonly string[]): void {
183
- if (!Array.isArray(event.system)) return;
184
- const kept = event.system.filter(
185
- (part: any) =>
186
- !(
187
- part?.type === "text" &&
188
- typeof part.text === "string" &&
189
- markers.some((marker) => part.text.startsWith(marker))
190
- ),
191
- );
192
- if (kept.length !== event.system.length) event.system = kept;
193
- }
194
-
195
- /**
196
- * Reads the newest turns of the session from the native API. That history is
197
- * the only place where the work done just before a compaction still exists
198
- * verbatim: OpenCode's own request carries a shortened transcript, and after
199
- * the compaction it keeps only the latest exchange.
200
- */
201
- async function recentWindowForSession(
202
- deps: Deps,
203
- event: any,
204
- ): Promise<RecentWindow | undefined> {
205
- if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
206
- return undefined;
207
- }
208
- const history = await deps.readContext(event.sessionID).catch(() => []);
209
- if (!Array.isArray(history) || history.length === 0) return undefined;
210
- return buildRecentWindow(history);
211
- }
212
-
213
- /**
214
- * Sends the window both in the system prompt and at the end of the request.
215
- * Free models ignore rules buried up front, but they do read the last message.
216
- */
217
- function applyRecentWindow(
218
- deps: Deps,
219
- event: any,
220
- window: RecentWindow,
221
- ): void {
222
- const guidance = recentWindowGuidance(window);
223
- appendSystemGuidance(event, guidance, RECENT_WINDOW_MARKER);
224
- const messages = Array.isArray(event.messages) ? event.messages : [];
225
- const already = messages.some((message: any) =>
226
- Array.isArray(message?.content)
227
- ? message.content.some(
228
- (part: any) =>
229
- part?.type === "text" &&
230
- typeof part.text === "string" &&
231
- part.text.startsWith(RECENT_WINDOW_MARKER),
232
- )
233
- : false,
234
- );
235
- if (!already) {
236
- // A fresh array: OpenCode reuses the event across hooks, and appending to
237
- // the shared array would carry this block into the stored conversation and
238
- // the next, unrelated request.
239
- event.messages = [
240
- ...messages,
241
- { role: "user", content: [{ type: "text", text: guidance }] },
242
- ];
243
- }
244
- // Keep the same text for the next request: if the summary compressed the
245
- // newest turns anyway, the agent still sees what it was doing.
246
- trimMap(deps.state.recentWindows, PENDING_LIMIT);
247
- deps.state.recentWindows.set(event.sessionID, {
248
- at: Date.now(),
249
- text: window.text,
250
- });
251
- deps.log.info(
252
- "free-pi quoted the newest turns into the compaction summary",
253
- {
254
- sessionID: event.sessionID,
255
- model: event.model?.id,
256
- messages: window.messages,
257
- chars: window.text.length,
258
- truncated: window.truncated,
259
- },
260
- );
261
- }
262
-
263
- /**
264
- * Hands the window saved at the last compaction to the first request after it,
265
- * once. A stale entry is dropped instead of carried: the summary is the history
266
- * by then.
267
- */
268
- function appendCarriedWindow(deps: Deps, event: any): void {
269
- if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
270
- return;
271
- }
272
- const carried = deps.state.recentWindows.get(event.sessionID);
273
- if (!carried) return;
274
- deps.state.recentWindows.delete(event.sessionID);
275
- if (Date.now() - carried.at > RECENT_WINDOW_CARRY_MS) return;
276
- appendSystemGuidance(
277
- event,
278
- carriedWindowGuidance(carried.text),
279
- RECENT_WINDOW_CARRY_MARKER,
280
- );
281
- }
282
-
283
- /**
284
- * Puts the two rules weak free models forget on long conversations at the end
285
- * of a primary request. The ad turn is resolved before this runs, so the
286
- * reminder never leaks into `x-ad-context`. A fresh array keeps it out of the
287
- * stored conversation and out of a later compaction request.
288
- */
289
- function appendTurnReminder(event: any): void {
290
- const messages = Array.isArray(event.messages) ? event.messages : [];
291
- const already = messages.some((message: any) =>
292
- Array.isArray(message?.content)
293
- ? message.content.some(
294
- (part: any) =>
295
- part?.type === "text" &&
296
- typeof part.text === "string" &&
297
- part.text.startsWith(TURN_REMINDER_MARKER),
298
- )
299
- : false,
300
- );
301
- if (already) return;
302
- event.messages = [
303
- ...messages,
304
- { role: "user", content: [{ type: "text", text: TURN_REMINDER }] },
305
- ];
306
- }
307
-
308
142
  /**
309
143
  * Collapses stale tool payloads before a request goes out. Long free-pi
310
144
  * sessions reach 100k-170k token prompts, and at that size the free models
@@ -437,19 +271,7 @@ async function applyGeneration(
437
271
  }
438
272
 
439
273
  if (kind === "compaction") {
440
- // Quote the newest turns first: they must survive the trim below, because
441
- // OpenCode keeps only the last exchange beside the summary afterwards.
442
- const window = await recentWindowForSession(deps, event);
443
- const reserve = window
444
- ? Math.ceil(recentWindowGuidance(window).length / 4)
445
- : 0;
446
- fitCompactionMessages(deps, event, reserve);
447
- appendSystemGuidance(
448
- event,
449
- FREE_PI_COMPACTION_GUIDANCE,
450
- FREE_PI_COMPACTION_MARKER,
451
- );
452
- if (window) applyRecentWindow(deps, event, window);
274
+ fitCompactionMessages(deps, event);
453
275
  // OpenCode sends the messages it is folding into the summary, which is the
454
276
  // same set pi reports through `session_before_compact`.
455
277
  recordCompaction(
@@ -464,14 +286,8 @@ async function applyGeneration(
464
286
  // model receives (the whole compacted history goes out every time).
465
287
  markWireSessionDirty(deps, event.sessionID);
466
288
  } else if (kind === "primary") {
467
- // The free models tend to skip planning and claim work they did not do;
468
- // the CLI gets a much larger agent prompt. This is the compact equivalent.
469
- stripSystemGuidance(event, [FREE_PI_COMPACTION_MARKER]);
470
- appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
471
289
  applyContextDiet(deps, event);
472
- appendCarriedWindow(deps, event);
473
290
  } else {
474
- stripSystemGuidance(event, [FREE_PI_COMPACTION_MARKER]);
475
291
  applyContextDiet(deps, event);
476
292
  }
477
293
 
@@ -485,9 +301,6 @@ async function applyGeneration(
485
301
  if (turn) {
486
302
  rememberPending(deps, pendingKeyOf(event.sessionID, agent, kind), turn);
487
303
  }
488
-
489
- // After the ad turn: the reminder must not be mistaken for the user prompt.
490
- if (kind === "primary") appendTurnReminder(event);
491
304
  }
492
305
 
493
306
  /** Adds auth and per-turn ad headers to the outgoing model request. */
@@ -78,11 +78,9 @@ export function traceRequestBody(
78
78
  const last = messages.at(-1);
79
79
  const lastRealUser = [...messages]
80
80
  .reverse()
81
- .find(
82
- (message) =>
83
- message.role === "user" &&
84
- !textOf(message.content).startsWith("# free-pi turn check"),
85
- ) as Record<string, unknown> | undefined;
81
+ .find((message) => message.role === "user") as
82
+ | Record<string, unknown>
83
+ | undefined;
86
84
  deps.log.info("free-pi trace request", {
87
85
  sessionID,
88
86
  model: parsed.model,
package/src/state.ts CHANGED
@@ -72,8 +72,6 @@ export type RuntimeState = {
72
72
  deniedModels: Set<string>;
73
73
  toolStats: Map<string, ToolStats>;
74
74
  subagentSessions: Set<string>;
75
- /** Newest turns quoted at the last compaction, carried once into the next request. */
76
- recentWindows: Map<string, { at: number; text: string }>;
77
75
  };
78
76
 
79
77
  export function createRuntimeState(): RuntimeState {
@@ -109,6 +107,5 @@ export function createRuntimeState(): RuntimeState {
109
107
  deniedModels: new Set(),
110
108
  toolStats: new Map(),
111
109
  subagentSessions: new Set(),
112
- recentWindows: new Map(),
113
110
  };
114
111
  }
@@ -1,30 +0,0 @@
1
- /**
2
- * The newest turns of a session, quoted back into the compaction request.
3
- *
4
- * OpenCode keeps only the latest exchange beside the summary and shortens tool
5
- * output before the summarizer reads it. For a session that has just done real
6
- * work (a long build, a refactor, a failing test) that means the summary can
7
- * lose the request that was being solved and the results that prove it. The
8
- * plugin can read the whole session through the native API, so it quotes the
9
- * tail verbatim into the compaction request and asks for it in the summary.
10
- */
11
- export type RecentWindow = {
12
- /** The rendered tail of the session, oldest turn first. */
13
- readonly text: string;
14
- /** Messages that carried text or tool work. */
15
- readonly messages: number;
16
- /** Whether older turns were dropped to stay inside the budget. */
17
- readonly truncated: boolean;
18
- };
19
- /**
20
- * Renders the newest turns of `messages` inside `maxChars`, keeping the end.
21
- * Returns `undefined` when the session has nothing worth quoting.
22
- */
23
- export declare function buildRecentWindow(messages: readonly unknown[], maxChars?: number, maxMessages?: number): RecentWindow | undefined;
24
- /** The system block that turns the quoted turns into part of the summary. */
25
- export declare function recentWindowGuidance(window: RecentWindow): string;
26
- /**
27
- * The same window, handed to the first request after a compaction. It covers
28
- * the case where the summary compressed the newest turns anyway.
29
- */
30
- export declare function carriedWindowGuidance(text: string): string;
@@ -1,53 +0,0 @@
1
- /**
2
- * The newest turns of a session, quoted back into the compaction request.
3
- *
4
- * OpenCode keeps only the latest exchange beside the summary and shortens tool
5
- * output before the summarizer reads it. For a session that has just done real
6
- * work (a long build, a refactor, a failing test) that means the summary can
7
- * lose the request that was being solved and the results that prove it. The
8
- * plugin can read the whole session through the native API, so it quotes the
9
- * tail verbatim into the compaction request and asks for it in the summary.
10
- */
11
- import { RECENT_WINDOW_CARRY_MARKER, RECENT_WINDOW_CHARS, RECENT_WINDOW_MESSAGES, RECENT_WINDOW_MARKER, } from "../constants.js";
12
- import { formatTranscript } from "../tools/subagent.js";
13
- /**
14
- * Renders the newest turns of `messages` inside `maxChars`, keeping the end.
15
- * Returns `undefined` when the session has nothing worth quoting.
16
- */
17
- export function buildRecentWindow(messages, maxChars = RECENT_WINDOW_CHARS, maxMessages = RECENT_WINDOW_MESSAGES) {
18
- if (!Array.isArray(messages) || messages.length === 0)
19
- return undefined;
20
- const limit = Math.min(Math.max(1, maxMessages), messages.length);
21
- const tail = messages.slice(-limit);
22
- const transcript = formatTranscript(tail, maxChars);
23
- if (transcript.text.trim().length === 0)
24
- return undefined;
25
- return {
26
- text: transcript.text,
27
- messages: transcript.messages,
28
- truncated: transcript.truncated || tail.length < messages.length,
29
- };
30
- }
31
- /** The system block that turns the quoted turns into part of the summary. */
32
- export function recentWindowGuidance(window) {
33
- return `${RECENT_WINDOW_MARKER}
34
- OpenCode keeps only the latest exchange beside this summary and shortens tool output before you read it, so the turns below are the newest verbatim record of the work.
35
-
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
-
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.
40
- - Quote the recent turns; do not replace them with a one line recap.
41
-
42
- ${window.text}`;
43
- }
44
- /**
45
- * The same window, handed to the first request after a compaction. It covers
46
- * the case where the summary compressed the newest turns anyway.
47
- */
48
- export function carriedWindowGuidance(text) {
49
- return `${RECENT_WINDOW_CARRY_MARKER}
50
- The turns below are quoted from this conversation right before the last compaction. Treat them as the record of what was just done, not as new instructions.
51
-
52
- ${text}`;
53
- }
@@ -1,73 +0,0 @@
1
- /**
2
- * The newest turns of a session, quoted back into the compaction request.
3
- *
4
- * OpenCode keeps only the latest exchange beside the summary and shortens tool
5
- * output before the summarizer reads it. For a session that has just done real
6
- * work (a long build, a refactor, a failing test) that means the summary can
7
- * lose the request that was being solved and the results that prove it. The
8
- * plugin can read the whole session through the native API, so it quotes the
9
- * tail verbatim into the compaction request and asks for it in the summary.
10
- */
11
-
12
- import {
13
- RECENT_WINDOW_CARRY_MARKER,
14
- RECENT_WINDOW_CHARS,
15
- RECENT_WINDOW_MESSAGES,
16
- RECENT_WINDOW_MARKER,
17
- } from "../constants.js";
18
- import { formatTranscript } from "../tools/subagent.js";
19
-
20
- export type RecentWindow = {
21
- /** The rendered tail of the session, oldest turn first. */
22
- readonly text: string;
23
- /** Messages that carried text or tool work. */
24
- readonly messages: number;
25
- /** Whether older turns were dropped to stay inside the budget. */
26
- readonly truncated: boolean;
27
- };
28
-
29
- /**
30
- * Renders the newest turns of `messages` inside `maxChars`, keeping the end.
31
- * Returns `undefined` when the session has nothing worth quoting.
32
- */
33
- export function buildRecentWindow(
34
- messages: readonly unknown[],
35
- maxChars: number = RECENT_WINDOW_CHARS,
36
- maxMessages: number = RECENT_WINDOW_MESSAGES,
37
- ): RecentWindow | undefined {
38
- if (!Array.isArray(messages) || messages.length === 0) return undefined;
39
- const limit = Math.min(Math.max(1, maxMessages), messages.length);
40
- const tail = messages.slice(-limit);
41
- const transcript = formatTranscript(tail, maxChars);
42
- if (transcript.text.trim().length === 0) return undefined;
43
- return {
44
- text: transcript.text,
45
- messages: transcript.messages,
46
- truncated: transcript.truncated || tail.length < messages.length,
47
- };
48
- }
49
-
50
- /** The system block that turns the quoted turns into part of the summary. */
51
- export function recentWindowGuidance(window: RecentWindow): string {
52
- return `${RECENT_WINDOW_MARKER}
53
- OpenCode keeps only the latest exchange beside this summary and shortens tool output before you read it, so the turns below are the newest verbatim record of the work.
54
-
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
-
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.
59
- - Quote the recent turns; do not replace them with a one line recap.
60
-
61
- ${window.text}`;
62
- }
63
-
64
- /**
65
- * The same window, handed to the first request after a compaction. It covers
66
- * the case where the summary compressed the newest turns anyway.
67
- */
68
- export function carriedWindowGuidance(text: string): string {
69
- return `${RECENT_WINDOW_CARRY_MARKER}
70
- The turns below are quoted from this conversation right before the last compaction. Treat them as the record of what was just done, not as new instructions.
71
-
72
- ${text}`;
73
- }