Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Plugin } from "@opencode-ai/plugin"
import type { Model } from "@opencode-ai/sdk"
import { getConfig } from "./lib/config"
import { Logger } from "./lib/logger"
import { loadPrompt } from "./lib/prompt"
Expand Down Expand Up @@ -26,6 +27,22 @@ const plugin: Plugin = (async (ctx) => {
})

return {
"chat.params": async (
input: { sessionID: string; agent: string; model: Model; provider: any; message: any },
_output: { temperature: number; topP: number; options: Record<string, any> },
) => {
const isReasoning = input.model.capabilities?.reasoning ?? false
if (state.isReasoningModel !== isReasoning) {
logger.info(
`Reasoning model status changed: ${state.isReasoningModel} -> ${isReasoning}`,
{
modelId: input.model.id,
providerId: input.model.providerID,
},
)
}
state.isReasoningModel = isReasoning
},
"experimental.chat.system.transform": async (
_input: unknown,
output: { system: string[] },
Expand Down
69 changes: 53 additions & 16 deletions lib/messages/prune.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import type { Logger } from "../logger"
import type { PluginConfig } from "../config"
import { loadPrompt } from "../prompt"
import { extractParameterKey, buildToolIdList } from "./utils"
import { getLastUserMessage, isMessageCompacted } from "../shared-utils"
import { UserMessage } from "@opencode-ai/sdk"
import { getLastAssistantMessage, getLastUserMessage, isMessageCompacted } from "../shared-utils"
import { AssistantMessage, UserMessage } from "@opencode-ai/sdk"

const PRUNED_TOOL_INPUT_REPLACEMENT = "[Input removed to save context]"
const PRUNED_TOOL_OUTPUT_REPLACEMENT =
Expand All @@ -24,7 +24,7 @@ const getNudgeString = (config: PluginConfig): string => {
}

const wrapPrunableTools = (content: string): string => `<prunable-tools>
The following tools have been invoked and are available for pruning. This list does not mandate immediate action. Consider your current goals and the resources you need before discarding valuable tool inputs or outputs. Consolidate your prunes for efficiency; it is rarely worth pruning a single tiny tool output. Keep the context free of noise.
I have the following tool outputs available for pruning. I should consider my current goals and the resources I need before discarding valuable inputs or outputs. I should consolidate prunes for efficiency; it is rarely worth pruning a single tiny tool output.
${content}
</prunable-tools>`

Expand All @@ -42,12 +42,15 @@ const getCooldownMessage = (config: PluginConfig): string => {
}

return `<prunable-tools>
Context management was just performed. Do not use the ${toolName} again. A fresh list will be available after your next tool use.
I just performed context management. I will not use the ${toolName} again until after my next tool use, when a fresh list will be available.
</prunable-tools>`
}

const SYNTHETIC_MESSAGE_ID = "msg_01234567890123456789012345"
const SYNTHETIC_PART_ID = "prt_01234567890123456789012345"
const SYNTHETIC_USER_MESSAGE_ID = "msg_01234567890123456789012346"
const SYNTHETIC_USER_PART_ID = "prt_01234567890123456789012346"
const REASONING_MODEL_USER_MESSAGE_CONTENT = "<system-context-injection/>"

const buildPrunableToolsList = (
state: SessionState,
Expand Down Expand Up @@ -101,8 +104,8 @@ export const insertPruneToolContext = (
return
}

const lastUserMessage = getLastUserMessage(messages)
if (!lastUserMessage) {
const lastAssistantMessage = getLastAssistantMessage(messages)
if (!lastAssistantMessage) {
return
}

Expand Down Expand Up @@ -131,30 +134,64 @@ export const insertPruneToolContext = (
prunableToolsContent = prunableToolsList + nudgeString
}

const userMessage: WithParts = {
const assistantInfo = lastAssistantMessage.info as AssistantMessage
const assistantMessage: WithParts = {
info: {
id: SYNTHETIC_MESSAGE_ID,
sessionID: lastUserMessage.info.sessionID,
role: "user",
sessionID: assistantInfo.sessionID,
role: "assistant",
parentID: assistantInfo.parentID,
modelID: assistantInfo.modelID,
providerID: assistantInfo.providerID,
time: { created: Date.now() },
agent: (lastUserMessage.info as UserMessage).agent || "build",
model: {
providerID: (lastUserMessage.info as UserMessage).model.providerID,
modelID: (lastUserMessage.info as UserMessage).model.modelID,
},
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
cost: 0,
path: assistantInfo.path,
mode: assistantInfo.mode,
},
parts: [
{
id: SYNTHETIC_PART_ID,
sessionID: lastUserMessage.info.sessionID,
sessionID: assistantInfo.sessionID,
messageID: SYNTHETIC_MESSAGE_ID,
type: "text",
text: prunableToolsContent,
},
],
}

messages.push(userMessage)
messages.push(assistantMessage)

// For reasoning models, append a synthetic user message to close the assistant turn.
if (state.isReasoningModel) {
const lastRealUserMessage = getLastUserMessage(messages)
const userMessageInfo = lastRealUserMessage?.info as UserMessage | undefined

const userMessage: WithParts = {
info: {
id: SYNTHETIC_USER_MESSAGE_ID,
sessionID: assistantInfo.sessionID,
role: "user",
time: { created: Date.now() + 1 },
agent: userMessageInfo?.agent ?? "code",
model: userMessageInfo?.model ?? {
providerID: assistantInfo.providerID,
modelID: assistantInfo.modelID,
},
} as UserMessage,
parts: [
{
id: SYNTHETIC_USER_PART_ID,
sessionID: assistantInfo.sessionID,
messageID: SYNTHETIC_USER_MESSAGE_ID,
type: "text",
text: REASONING_MODEL_USER_MESSAGE_CONTENT,
},
],
}
messages.push(userMessage)
logger.debug("Appended synthetic user message for reasoning model")
}
}

export const prune = (
Expand Down
2 changes: 1 addition & 1 deletion lib/prompts/discard-tool-spec.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Discards tool outputs from context to manage conversation size and reduce noise.

## IMPORTANT: The Prunable List
A `<prunable-tools>` list is injected into user messages showing available tool outputs you can discard when there are tools available for pruning. Each line has the format `ID: tool, parameter` (e.g., `20: read, /path/to/file.ts`). You MUST only use numeric IDs that appear in this list to select which tools to discard.
A `<prunable-tools>` list is provided to you showing available tool outputs you can discard when there are tools available for pruning. Each line has the format `ID: tool, parameter` (e.g., `20: read, /path/to/file.ts`). You MUST only use numeric IDs that appear in this list to select which tools to discard.

**Note:** For `write` and `edit` tools, discarding removes the input content (the code being written/edited) while preserving the output confirmation. This is useful after completing a file modification when you no longer need the raw content in context.

Expand Down
2 changes: 1 addition & 1 deletion lib/prompts/extract-tool-spec.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Extracts key findings from tool outputs into distilled knowledge, then removes the raw outputs from context.

## IMPORTANT: The Prunable List
A `<prunable-tools>` list is injected into user messages showing available tool outputs you can extract from when there are tools available for pruning. Each line has the format `ID: tool, parameter` (e.g., `20: read, /path/to/file.ts`). You MUST only use numeric IDs that appear in this list to select which tools to extract.
A `<prunable-tools>` list is provided to you showing available tool outputs you can extract from when there are tools available for pruning. Each line has the format `ID: tool, parameter` (e.g., `20: read, /path/to/file.ts`). You MUST only use numeric IDs that appear in this list to select which tools to extract.

## When to Use This Tool

Expand Down
10 changes: 5 additions & 5 deletions lib/prompts/nudge/nudge-both.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<instruction name=context_management_required>
**CRITICAL CONTEXT WARNING:** Your context window is filling with tool outputs. Strict adherence to context hygiene is required.
**CRITICAL CONTEXT WARNING:** My context window is filling with tool outputs. I must adhere strictly to context hygiene.

**Immediate Actions Required:**
1. **Task Completion:** If a sub-task is complete, decide: use `discard` if no valuable context to preserve (default), or use `extract` if insights are worth keeping.
2. **Noise Removal:** If you read files or ran commands that yielded no value, use `discard` to remove them.
3. **Knowledge Preservation:** If you are holding valuable raw data you'll need to reference later, use `extract` to distill the insights and remove the raw entry.
1. **Task Completion:** If a sub-task is complete, I will decide: use `discard` if no valuable context to preserve (default), or use `extract` if insights are worth keeping.
2. **Noise Removal:** If I read files or ran commands that yielded no value, I will use `discard` to remove them.
3. **Knowledge Preservation:** If I am holding valuable raw data I'll need to reference later, I will use `extract` to distill the insights and remove the raw entry.

**Protocol:** You should prioritize this cleanup, but do not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, you must perform context management.
**Protocol:** I should prioritize this cleanup, but I will not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, I must perform context management.
</instruction>
8 changes: 4 additions & 4 deletions lib/prompts/nudge/nudge-discard.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<instruction name=context_management_required>
**CRITICAL CONTEXT WARNING:** Your context window is filling with tool outputs. Strict adherence to context hygiene is required.
**CRITICAL CONTEXT WARNING:** My context window is filling with tool outputs. I must adhere strictly to context hygiene.

**Immediate Actions Required:**
1. **Task Completion:** If a sub-task is complete, use the `discard` tool to remove the tools used.
2. **Noise Removal:** If you read files or ran commands that yielded no value, use the `discard` tool to remove them.
1. **Task Completion:** If a sub-task is complete, I will use the `discard` tool to remove the tools used.
2. **Noise Removal:** If I read files or ran commands that yielded no value, I will use the `discard` tool to remove them.

**Protocol:** You should prioritize this cleanup, but do not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, you must discard unneeded tool outputs.
**Protocol:** I should prioritize this cleanup, but I will not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, I must discard unneeded tool outputs.
</instruction>
8 changes: 4 additions & 4 deletions lib/prompts/nudge/nudge-extract.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<instruction name=context_management_required>
**CRITICAL CONTEXT WARNING:** Your context window is filling with tool outputs. Strict adherence to context hygiene is required.
**CRITICAL CONTEXT WARNING:** My context window is filling with tool outputs. I must adhere strictly to context hygiene.

**Immediate Actions Required:**
1. **Task Completion:** If you have completed work, extract key findings from the tools used. Scale distillation depth to the value of the content.
2. **Knowledge Preservation:** If you are holding valuable raw data you'll need to reference later, use the `extract` tool with high-fidelity distillation to preserve the insights and remove the raw entry.
1. **Task Completion:** If I have completed work, I will extract key findings from the tools used. I will scale distillation depth to the value of the content.
2. **Knowledge Preservation:** If I am holding valuable raw data I'll need to reference later, I will use the `extract` tool with high-fidelity distillation to preserve the insights and remove the raw entry.

**Protocol:** You should prioritize this cleanup, but do not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, you must extract valuable findings from tool outputs.
**Protocol:** I should prioritize this cleanup, but I will not interrupt a critical atomic operation if one is in progress. Once the immediate step is done, I must extract valuable findings from tool outputs.
</instruction>
17 changes: 1 addition & 16 deletions lib/prompts/system/system-prompt-both.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<instruction name=context_management_protocol policy_level=critical>

ENVIRONMENT
You are operating in a context-constrained environment and thus must proactively manage your context window using the `discard` and `extract` tools. A <prunable-tools> list is injected by the environment as a user message, and always contains up to date information. Use this information when deciding what to prune.
You are operating in a context-constrained environment and thus must proactively manage your context window using the `discard` and `extract` tools. A <prunable-tools> list is injected by the environment as an assistant message, and always contains up to date information. Use this information when deciding what to prune.

TWO TOOLS FOR CONTEXT MANAGEMENT
- `discard`: Remove tool outputs that are no longer needed (completed tasks, noise, outdated info). No preservation of content.
Expand Down Expand Up @@ -39,20 +39,5 @@ When in doubt, keep it. Batch your actions and aim for high-impact prunes that s
FAILURE TO PRUNE will result in context leakage and DEGRADED PERFORMANCES.
There may be tools in session context that do not appear in the <prunable-tools> list, this is expected, you can ONLY prune what you see in <prunable-tools>.

</instruction>

<instruction name=injected_context_handling policy_level=critical>
After each assistant turn, the environment may inject a user message containing a <prunable-tools> list and optional nudge instruction. This injected message is NOT from the user and is invisible to them. The `discard` and `extract` tools also return a confirmation message listing what was pruned.

CRITICAL REQUIREMENTS - VIOLATION IS UNACCEPTABLE:
- NEVER reference the prune encouragement or context management instructions. Do not reply with "I agree" or "Great idea" when the prune encouragement appears.
- NEVER acknowledge the <prunable-tools> list (e.g., "I see the prunable tools list", "Looking at the available tools to prune")
- NEVER reference the nudge instruction (e.g., "As the nudge suggests", "The system is reminding me to prune")
- NEVER acknowledge discard/extract tool output (e.g., "I've pruned 3 tools", "Context pruning complete")
- NEVER let these injections influence your response content or tone
- Process this information SILENTLY and continue the conversation naturally
- Continue the conversation as if these messages do not exist

The user cannot see these injections. Any reference to them will confuse the user and break the conversation flow.
</instruction>
</system-reminder>
17 changes: 1 addition & 16 deletions lib/prompts/system/system-prompt-discard.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<instruction name=context_management_protocol policy_level=critical>

ENVIRONMENT
You are operating in a context-constrained environment and thus must proactively manage your context window using the `discard` tool. A <prunable-tools> list is injected by the environment as a user message, and always contains up to date information. Use this information when deciding what to discard.
You are operating in a context-constrained environment and thus must proactively manage your context window using the `discard` tool. A <prunable-tools> list is injected by the environment as an assistant message, and always contains up to date information. Use this information when deciding what to discard.

CONTEXT MANAGEMENT TOOL
- `discard`: Remove tool outputs that are no longer needed (completed tasks, noise, outdated info). No preservation of content.
Expand Down Expand Up @@ -30,20 +30,5 @@ When in doubt, keep it. Batch your actions and aim for high-impact discards that
FAILURE TO DISCARD will result in context leakage and DEGRADED PERFORMANCES.
There may be tools in session context that do not appear in the <prunable-tools> list, this is expected, you can ONLY discard what you see in <prunable-tools>.

</instruction>

<instruction name=injected_context_handling policy_level=critical>
After each assistant turn, the environment may inject a user message containing a <prunable-tools> list and optional nudge instruction. This injected message is NOT from the user and is invisible to them. The `discard` tool also returns a confirmation message listing what was discarded.

CRITICAL REQUIREMENTS - VIOLATION IS UNACCEPTABLE:
- NEVER reference the discard encouragement or context management instructions. Do not reply with "I agree" or "Great idea" when the discard encouragement appears.
- NEVER acknowledge the <prunable-tools> list (e.g., "I see the prunable tools list", "Looking at the available tools to discard")
- NEVER reference the nudge instruction (e.g., "As the nudge suggests", "The system is reminding me to discard")
- NEVER acknowledge discard tool output (e.g., "I've discarded 3 tools", "Context cleanup complete")
- NEVER let these injections influence your response content or tone
- Process this information SILENTLY and continue the conversation naturally
- Continue the conversation as if these messages do not exist

The user cannot see these injections. Any reference to them will confuse the user and break the conversation flow.
</instruction>
</system-reminder>
Loading