Skip to content
Open
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
13 changes: 13 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Plugin } from "@opencode-ai/plugin"
import { getConfig } from "./lib/config"
import { createCompressMessageTool, createCompressRangeTool } from "./lib/compress"
import { createInvestigateTool, createReadOriginalTool } from "./lib/investigate"
import {
compressDisabledByOpencode,
hasExplicitToolPermission,
Expand Down Expand Up @@ -86,6 +87,8 @@ const server: Plugin = (async (ctx) => {
? createCompressMessageTool(compressToolContext)
: createCompressRangeTool(compressToolContext),
}),
read_original: createReadOriginalTool({ client: ctx.client, state, logger }),
investigate: createInvestigateTool({ client: ctx.client, state, logger }),
},
config: async (opencodeConfig) => {
if (
Expand All @@ -107,6 +110,7 @@ const server: Plugin = (async (ctx) => {
if (config.compress.permission !== "deny" && !config.experimental.allowSubAgents) {
toolsToAdd.push("compress")
}
toolsToAdd.push("read_original", "investigate")

if (toolsToAdd.length > 0) {
const existingPrimaryTools = opencodeConfig.experimental?.primary_tools ?? []
Expand All @@ -124,6 +128,15 @@ const server: Plugin = (async (ctx) => {
} as typeof permission
}

if (!hasExplicitToolPermission(opencodeConfig.permission, "read_original")) {
const permission = opencodeConfig.permission ?? {}
opencodeConfig.permission = {
...permission,
read_original: "allow",
investigate: "allow",
} as typeof permission
}

hostPermissions.global = opencodeConfig.permission
hostPermissions.agents = Object.fromEntries(
Object.entries(opencodeConfig.agent ?? {}).map(([name, agent]) => [
Expand Down
2 changes: 2 additions & 0 deletions lib/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
export { handleContextCommand } from "./context"
export { handleDecompressCommand } from "./decompress"
export { handleHelpCommand } from "./help"
export { handleInvestigateCommand } from "./investigate"
export {
applyPendingManualTrigger,
handleManualToggleCommand,
handleManualTriggerCommand,
} from "./manual"
export { handleReadOriginalCommand } from "./read"
export { handleRecompressCommand } from "./recompress"
export { handleStatsCommand } from "./stats"
export { handleSweepCommand } from "./sweep"
80 changes: 80 additions & 0 deletions lib/commands/investigate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { Logger } from "../logger"
import type { SessionState, WithParts } from "../state"
import { getCurrentParams } from "../token-utils"
import { sendIgnoredMessage } from "../ui/notification"
import {
parseBlockIdArg,
resolveBlockSlice,
runInvestigation,
truncateMessages,
} from "../investigate"

export interface InvestigateCommandContext {
client: any
state: SessionState
logger: Logger
sessionId: string
messages: WithParts[]
args: string[]
}

export async function handleInvestigateCommand(ctx: InvestigateCommandContext): Promise<void> {
const { client, state, logger, sessionId, messages, args } = ctx
const params = getCurrentParams(state, messages, logger)

const blockArg = args[0]
const question = args.slice(1).join(" ").trim()
if (!blockArg || !question) {
await sendIgnoredMessage(
client,
sessionId,
`Usage: /dcp investigate <bN> "<question>"`,
params,
logger,
)
return
}

const blockId = parseBlockIdArg(blockArg)
if (blockId === null) {
await sendIgnoredMessage(
client,
sessionId,
`Please enter a compression block ID. Example: /dcp investigate b3 "what was the error?"`,
params,
logger,
)
return
}

let slice
try {
slice = resolveBlockSlice(state, messages, blockId)
} catch (error: any) {
await sendIgnoredMessage(client, sessionId, error?.message ?? String(error), params, logger)
return
}

if (slice.messages.length === 0) {
await sendIgnoredMessage(
client,
sessionId,
`Compression ${slice.blockRef} covers no messages in the current session.`,
params,
logger,
)
return
}

const { text } = truncateMessages(slice.messages)
const answer = await runInvestigation(
client,
logger,
sessionId,
slice.block,
slice.blockRef,
question,
text,
)
await sendIgnoredMessage(client, sessionId, answer, params, logger)
}
65 changes: 65 additions & 0 deletions lib/commands/read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { Logger } from "../logger"
import type { SessionState, WithParts } from "../state"
import { getCurrentParams } from "../token-utils"
import { sendIgnoredMessage } from "../ui/notification"
import { parseBlockIdArg, resolveBlockSlice, truncateMessages } from "../investigate"

export interface ReadOriginalCommandContext {
client: any
state: SessionState
logger: Logger
sessionId: string
messages: WithParts[]
args: string[]
}

export async function handleReadOriginalCommand(ctx: ReadOriginalCommandContext): Promise<void> {
const { client, state, logger, sessionId, messages, args } = ctx
const params = getCurrentParams(state, messages, logger)

const blockArg = args[0]
if (!blockArg) {
await sendIgnoredMessage(client, sessionId, "Usage: /dcp read <bN>", params, logger)
return
}

const blockId = parseBlockIdArg(blockArg)
if (blockId === null) {
await sendIgnoredMessage(
client,
sessionId,
`Please enter a compression block ID. Example: /dcp read b3`,
params,
logger,
)
return
}

let slice
try {
slice = resolveBlockSlice(state, messages, blockId)
} catch (error: any) {
await sendIgnoredMessage(client, sessionId, error?.message ?? String(error), params, logger)
return
}

if (slice.messages.length === 0) {
await sendIgnoredMessage(
client,
sessionId,
`Compression ${slice.blockRef} covers no messages in the current session.`,
params,
logger,
)
return
}

const { text } = truncateMessages(slice.messages)
await sendIgnoredMessage(
client,
sessionId,
`Original content of ${slice.blockRef}:\n\n${text}`,
params,
logger,
)
}
10 changes: 9 additions & 1 deletion lib/compress/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,16 @@ export function wrapCompressedSummary(
format: IdFormat = "xml",
): string {
const header = COMPRESSED_BLOCK_HEADER
const footer = formatMessageIdTag(formatBlockRef(blockId, format), undefined, format)
const blockRef = formatBlockRef(blockId, format)
const footer = formatMessageIdTag(blockRef, undefined, format)
const body = summary.trim()
if (format === "xml") {
const hint = `[Compressed section ${blockRef} — retrieve the original content with read_original("${blockRef}") or investigate("${blockRef}", "your question") without expanding your context.]`
if (body.length === 0) {
return `${header}\n\n${hint}\n${footer}`
}
return `${header}\n${body}\n\n${hint}\n\n${footer}`
}
if (body.length === 0) {
return `${header}\n${footer}`
}
Expand Down
18 changes: 18 additions & 0 deletions lib/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ import {
handleContextCommand,
handleDecompressCommand,
handleHelpCommand,
handleInvestigateCommand,
handleManualToggleCommand,
handleManualTriggerCommand,
handleReadOriginalCommand,
handleRecompressCommand,
handleStatsCommand,
handleSweepCommand,
Expand Down Expand Up @@ -283,6 +285,22 @@ export function createCommandExecuteHandler(
return
}

if (subcommand === "read") {
await handleReadOriginalCommand({
...commandCtx,
args: subArgs,
})
return
}

if (subcommand === "investigate") {
await handleInvestigateCommand({
...commandCtx,
args: subArgs,
})
return
}

await handleHelpCommand(commandCtx)
return
}
Expand Down
5 changes: 5 additions & 0 deletions lib/investigate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { createReadOriginalTool } from "./read-original"
export { createInvestigateTool } from "./investigate"
export { runInvestigation } from "./subagent"
export { parseBlockIdArg, resolveBlockSlice, serializeMessages, truncateMessages } from "./resolve"
export type { InvestigateToolContext } from "./types"
64 changes: 64 additions & 0 deletions lib/investigate/investigate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { tool } from "@opencode-ai/plugin"
import { ensureSessionInitialized } from "../state"
import { fetchSessionMessages } from "../compress/search"
import type { InvestigateToolContext } from "./types"
import { parseBlockIdArg, resolveBlockSlice, truncateMessages } from "./resolve"
import { runInvestigation } from "./subagent"

function buildSchema() {
return {
blockId: tool.schema
.string()
.describe("Compression block reference to investigate, e.g. 'b3' or '3'."),
question: tool.schema
.string()
.describe("The specific question to answer about the compressed content."),
maxTokens: tool.schema
.number()
.optional()
.describe("Optional token budget for the original content passed to the subagent."),
}
}

export function createInvestigateTool(ctx: InvestigateToolContext): ReturnType<typeof tool> {
return tool({
description:
"Answer a question about a DCP compression block (identified by its bN block reference) by delegating to a subagent that reads the ORIGINAL, un-pruned content. Returns ONLY the answer, so the raw content never re-enters your main context. Use this instead of decompressing or reading the original content yourself when you only need a specific answer or clarification about a summary.",
args: buildSchema(),
async execute(args, toolCtx) {
const input = args as { blockId: string; question: string; maxTokens?: number }
const blockId = parseBlockIdArg(input.blockId)
if (blockId === null) {
throw new Error(
`Invalid block reference "${input.blockId}". Use a block ID like "b3" or "3".`,
)
}

const rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID)
await ensureSessionInitialized(
ctx.client,
ctx.state,
toolCtx.sessionID,
ctx.logger,
rawMessages,
false,
)

const slice = resolveBlockSlice(ctx.state, rawMessages, blockId)
if (slice.messages.length === 0) {
return `Compression ${slice.blockRef} covers no messages in the current session. Nothing to investigate.`
}

const { text } = truncateMessages(slice.messages, input.maxTokens)
return await runInvestigation(
ctx.client,
ctx.logger,
toolCtx.sessionID,
slice.block,
slice.blockRef,
input.question,
text,
)
},
})
}
54 changes: 54 additions & 0 deletions lib/investigate/read-original.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { tool } from "@opencode-ai/plugin"
import { ensureSessionInitialized } from "../state"
import { fetchSessionMessages } from "../compress/search"
import type { InvestigateToolContext } from "./types"
import { parseBlockIdArg, resolveBlockSlice, truncateMessages } from "./resolve"

function buildSchema() {
return {
blockId: tool.schema
.string()
.describe("Compression block reference to read, e.g. 'b3' or '3'."),
maxTokens: tool.schema
.number()
.optional()
.describe("Optional token budget for the returned content. Omit to return everything."),
}
}

export function createReadOriginalTool(ctx: InvestigateToolContext): ReturnType<typeof tool> {
return tool({
description:
"Read the ORIGINAL, un-pruned content of a DCP compression block (identified by its bN block reference) back into the current context. Use this when you need the exact source content that a summary replaced. Prefer the `investigate` tool when you only need an answer to a specific question, since this tool re-expands tokens that were deliberately compressed away.",
args: buildSchema(),
async execute(args, toolCtx) {
const input = args as { blockId: string; maxTokens?: number }
const blockId = parseBlockIdArg(input.blockId)
if (blockId === null) {
throw new Error(
`Invalid block reference "${input.blockId}". Use a block ID like "b3" or "3".`,
)
}

const rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID)
await ensureSessionInitialized(
ctx.client,
ctx.state,
toolCtx.sessionID,
ctx.logger,
rawMessages,
false,
)

const slice = resolveBlockSlice(ctx.state, rawMessages, blockId)
if (slice.messages.length === 0) {
return `Compression ${slice.blockRef} covers no messages in the current session. Its summary may reference nested compressions that were already consumed.`
}

const { text, truncated } = truncateMessages(slice.messages, input.maxTokens)
const header = `Original content of compression ${slice.blockRef} (${slice.messages.length} message(s)${slice.block.topic ? `, topic: ${slice.block.topic}` : ""}):`
const note = truncated ? `\n\n[truncated to ~${input.maxTokens} tokens]` : ""
return `${header}\n\n${text}${note}`
},
})
}
Loading