From d7d386afda5e1b0e9e2262ed933535256e03992c Mon Sep 17 00:00:00 2001 From: Jay Flowers Date: Fri, 2 Oct 2026 11:58:26 -0400 Subject: [PATCH] feat: add investigate and read_original tools for delegated retrieval of compressed content Add two always-on tools that let the agent resolve questions about compressed/compacted sections without re-expanding them into the main context: - read_original(bN, maxTokens?) returns the raw slice of the original messages for a compression block. - investigate(bN, question) spawns a child session (parentID = current session), prompts it with the raw slice + question, and returns only the synthesized answer, then deletes the child session. Also adds /dcp read and /dcp investigate slash commands, a system-prompt awareness section, and a hint line in the xml compressed-block footer. --- index.ts | 13 ++ lib/commands/index.ts | 2 + lib/commands/investigate.ts | 80 ++++++++++++ lib/commands/read.ts | 65 ++++++++++ lib/compress/state.ts | 10 +- lib/hooks.ts | 18 +++ lib/investigate/index.ts | 5 + lib/investigate/investigate.ts | 64 ++++++++++ lib/investigate/read-original.ts | 54 ++++++++ lib/investigate/resolve.ts | 96 ++++++++++++++ lib/investigate/subagent.ts | 106 ++++++++++++++++ lib/investigate/types.ts | 8 ++ lib/prompts/system.ts | 11 ++ tests/investigate.test.ts | 203 ++++++++++++++++++++++++++++++ tests/read-original.test.ts | 210 +++++++++++++++++++++++++++++++ 15 files changed, 944 insertions(+), 1 deletion(-) create mode 100644 lib/commands/investigate.ts create mode 100644 lib/commands/read.ts create mode 100644 lib/investigate/index.ts create mode 100644 lib/investigate/investigate.ts create mode 100644 lib/investigate/read-original.ts create mode 100644 lib/investigate/resolve.ts create mode 100644 lib/investigate/subagent.ts create mode 100644 lib/investigate/types.ts create mode 100644 tests/investigate.test.ts create mode 100644 tests/read-original.test.ts diff --git a/index.ts b/index.ts index 02216b33b..b448d8a98 100644 --- a/index.ts +++ b/index.ts @@ -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, @@ -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 ( @@ -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 ?? [] @@ -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]) => [ diff --git a/lib/commands/index.ts b/lib/commands/index.ts index 993420bfc..cefde9255 100644 --- a/lib/commands/index.ts +++ b/lib/commands/index.ts @@ -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" diff --git a/lib/commands/investigate.ts b/lib/commands/investigate.ts new file mode 100644 index 000000000..7249c6ef6 --- /dev/null +++ b/lib/commands/investigate.ts @@ -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 { + 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 ""`, + 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) +} diff --git a/lib/commands/read.ts b/lib/commands/read.ts new file mode 100644 index 000000000..545508771 --- /dev/null +++ b/lib/commands/read.ts @@ -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 { + 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 ", 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, + ) +} diff --git a/lib/compress/state.ts b/lib/compress/state.ts index b902e0147..6abe43669 100644 --- a/lib/compress/state.ts +++ b/lib/compress/state.ts @@ -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}` } diff --git a/lib/hooks.ts b/lib/hooks.ts index 6d6f3862d..eb7604a5e 100644 --- a/lib/hooks.ts +++ b/lib/hooks.ts @@ -28,8 +28,10 @@ import { handleContextCommand, handleDecompressCommand, handleHelpCommand, + handleInvestigateCommand, handleManualToggleCommand, handleManualTriggerCommand, + handleReadOriginalCommand, handleRecompressCommand, handleStatsCommand, handleSweepCommand, @@ -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 } diff --git a/lib/investigate/index.ts b/lib/investigate/index.ts new file mode 100644 index 000000000..4b6a0599f --- /dev/null +++ b/lib/investigate/index.ts @@ -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" diff --git a/lib/investigate/investigate.ts b/lib/investigate/investigate.ts new file mode 100644 index 000000000..b24b9cde7 --- /dev/null +++ b/lib/investigate/investigate.ts @@ -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 { + 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, + ) + }, + }) +} diff --git a/lib/investigate/read-original.ts b/lib/investigate/read-original.ts new file mode 100644 index 000000000..32a15dee9 --- /dev/null +++ b/lib/investigate/read-original.ts @@ -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 { + 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}` + }, + }) +} diff --git a/lib/investigate/resolve.ts b/lib/investigate/resolve.ts new file mode 100644 index 000000000..91a8815ca --- /dev/null +++ b/lib/investigate/resolve.ts @@ -0,0 +1,96 @@ +import type { CompressionBlock, SessionState, WithParts } from "../state" +import { formatBlockRef, parseBlockRef } from "../message-ids" +import { countTokens, extractCompletedToolOutput } from "../token-utils" + +export interface ResolvedSlice { + block: CompressionBlock + blockRef: string + messages: WithParts[] +} + +export function parseBlockIdArg(arg: string): number | null { + const normalized = arg.trim().toLowerCase() + const blockRef = parseBlockRef(normalized) ?? parseBlockRef(normalized, "compact") + if (blockRef !== null) { + return blockRef + } + if (!/^[1-9]\d*$/.test(normalized)) { + return null + } + const parsed = Number.parseInt(normalized, 10) + return Number.isInteger(parsed) && parsed > 0 ? parsed : null +} + +export function resolveBlockSlice( + state: SessionState, + rawMessages: WithParts[], + blockId: number, +): ResolvedSlice { + const block = state.prune.messages.blocksById.get(blockId) + if (!block) { + throw new Error(`Compression block ${blockId} does not exist in this session.`) + } + + const ids = + block.effectiveMessageIds.length > 0 ? block.effectiveMessageIds : block.directMessageIds + const idSet = new Set(ids) + const messages = rawMessages.filter((message) => idSet.has(message.info.id)) + + return { + block, + blockRef: formatBlockRef(blockId, state.idFormat), + messages, + } +} + +export function serializeMessages(messages: WithParts[]): string { + const blocks: string[] = [] + for (const message of messages) { + const role = message.info.role ?? "message" + const parts = Array.isArray(message.parts) ? message.parts : [] + const chunks: string[] = [] + for (const part of parts) { + if (part.type === "text") { + const text = (part as { text?: string }).text + if (typeof text === "string" && text.trim().length > 0) { + chunks.push(text) + } + } else if (part.type === "tool") { + const toolPart = part as any + const name = toolPart.tool ?? "tool" + const input = toolPart.state?.input + const output = extractCompletedToolOutput(toolPart) + let chunk = `[tool call: ${name}]` + if (input !== undefined) { + chunk += `\n(input: ${typeof input === "string" ? input : JSON.stringify(input)})` + } + if (output !== undefined) { + chunk += `\n(output: ${output})` + } + chunks.push(chunk) + } + } + if (chunks.length === 0) { + continue + } + blocks.push(`### ${role}\n${chunks.join("\n")}`) + } + return blocks.join("\n\n") +} + +export function truncateMessages( + messages: WithParts[], + maxTokens?: number, +): { text: string; truncated: boolean } { + const full = serializeMessages(messages) + if (!Number.isFinite(maxTokens) || (maxTokens ?? 0) <= 0 || countTokens(full) <= maxTokens!) { + return { text: full, truncated: false } + } + for (let i = 1; i < messages.length; i++) { + const text = serializeMessages(messages.slice(i)) + if (countTokens(text) <= maxTokens!) { + return { text, truncated: true } + } + } + return { text: serializeMessages(messages.slice(-1)), truncated: true } +} diff --git a/lib/investigate/subagent.ts b/lib/investigate/subagent.ts new file mode 100644 index 000000000..8c8d5bcca --- /dev/null +++ b/lib/investigate/subagent.ts @@ -0,0 +1,106 @@ +import type { CompressionBlock } from "../state" +import type { Logger } from "../logger" + +function unwrapSession(value: any): any { + return value?.data ?? value +} + +function extractAssistantText(result: any): string { + const data = unwrapSession(result) + const parts = Array.isArray(data?.parts) ? data.parts : [] + const texts: string[] = [] + for (const part of parts) { + if (part?.type === "text" && typeof part.text === "string" && part.text.trim().length > 0) { + texts.push(part.text.trim()) + } + } + return texts.join("\n").trim() +} + +function lastAssistantText(messagesResponse: any): string { + const data = unwrapSession(messagesResponse) + const list = Array.isArray(data) ? data : [] + for (let i = list.length - 1; i >= 0; i--) { + const message = list[i] + const info = message?.info ?? message + if (info?.role !== "assistant") { + continue + } + const parts = Array.isArray(message?.parts) ? message.parts : [] + for (let j = parts.length - 1; j >= 0; j--) { + const part = parts[j] + if ( + part?.type === "text" && + typeof part.text === "string" && + part.text.trim().length > 0 + ) { + return part.text.trim() + } + } + } + return "" +} + +export async function runInvestigation( + client: any, + logger: Logger, + parentSessionId: string, + block: CompressionBlock, + blockRef: string, + question: string, + content: string, +): Promise { + const prompt = [ + "You are a subagent answering a question about a section of a conversation that was compressed.", + `The section was compressed into block ${blockRef}${block.topic ? ` (topic: ${block.topic})` : ""}.`, + "Below is the ORIGINAL, un-compressed content of that section.", + "", + "--- BEGIN ORIGINAL CONTENT ---", + content, + "--- END ORIGINAL CONTENT ---", + "", + `Question: ${question}`, + "", + "Answer the question using ONLY the provided content. Do not use any tools. Return only the answer, with no preamble, no caveats about the content being a summary, and no explanation of your process.", + ].join("\n") + + let child: any + try { + const created = await client.session.create({ + body: { + parentID: parentSessionId, + title: `dcp investigate ${blockRef}`, + }, + }) + child = unwrapSession(created) + const childId = child?.id + if (!childId) { + throw new Error("Failed to create investigation sub-session") + } + + const result = await client.session.prompt({ + path: { id: childId }, + body: { + parts: [{ type: "text", text: prompt }], + }, + }) + + let answer = extractAssistantText(result) + if (!answer) { + const messagesResponse = await client.session.messages({ path: { id: childId } }) + answer = lastAssistantText(messagesResponse) + } + return answer || "(no answer produced)" + } catch (error: any) { + logger.error("Investigation subagent failed", { error: error?.message ?? String(error) }) + throw new Error(`Investigation failed: ${error?.message ?? String(error)}`) + } finally { + if (child?.id) { + try { + await client.session.delete({ path: { id: child.id } }) + } catch { + // best-effort cleanup + } + } + } +} diff --git a/lib/investigate/types.ts b/lib/investigate/types.ts new file mode 100644 index 000000000..3c7efe965 --- /dev/null +++ b/lib/investigate/types.ts @@ -0,0 +1,8 @@ +import type { SessionState } from "../state" +import type { Logger } from "../logger" + +export interface InvestigateToolContext { + client: any + state: SessionState + logger: Logger +} diff --git a/lib/prompts/system.ts b/lib/prompts/system.ts index 08a89450e..f4f2b0f02 100644 --- a/lib/prompts/system.ts +++ b/lib/prompts/system.ts @@ -35,6 +35,17 @@ Before compressing, ask: _"Is this section closed enough to become summary-only Evaluate conversation signal-to-noise REGULARLY. Use \`compress\` deliberately with quality-first summaries. Prioritize stale content intelligently to maintain a high-signal context window that supports your agency. It is of your responsibility to keep a sharp, high-quality context window for optimal performance. + +DELEGATED INVESTIGATION OF COMPRESSED CONTENT + +Content under a \`[Compressed conversation section]\` header that ends with a \`bN\` tag is a summary, not the source. The block ID (bN) identifies the compression. + +When you need detail that a summary does not contain, do NOT decompress it back into your context. Instead: + +- Call \`investigate(bN, "")\` to delegate a question to a subagent that reads the original content and returns only the answer. This is the default choice. +- Call \`read_original(bN)\` only when you must have the exact source content in your own context. + +The original content is never destroyed; these tools simply keep it out of your main context window. ` } diff --git a/tests/investigate.test.ts b/tests/investigate.test.ts new file mode 100644 index 000000000..14dc122d5 --- /dev/null +++ b/tests/investigate.test.ts @@ -0,0 +1,203 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { join } from "node:path" +import { tmpdir } from "node:os" +import { mkdirSync } from "node:fs" +import { createInvestigateTool } from "../lib/investigate/investigate" +import { runInvestigation } from "../lib/investigate/subagent" +import { createSessionState, type CompressionBlock, type WithParts } from "../lib/state" +import { Logger } from "../lib/logger" + +const testDataHome = join(tmpdir(), `opencode-dcp-investigate-${process.pid}`) +process.env.XDG_DATA_HOME = testDataHome +mkdirSync(testDataHome, { recursive: true }) + +function buildBlock(blockId: number, messageIds: string[], topic?: string): CompressionBlock { + return { + blockId, + runId: blockId, + active: true, + deactivatedByUser: false, + compressedTokens: 10, + summaryTokens: 5, + durationMs: 100, + mode: "range", + topic: topic ?? `topic-${blockId}`, + batchTopic: `topic-${blockId}`, + startId: `m${blockId}`, + endId: `m${blockId}`, + anchorMessageId: messageIds[0] ?? `msg-${blockId}`, + compressMessageId: `origin-${blockId}`, + includedBlockIds: [], + consumedBlockIds: [], + parentBlockIds: [], + directMessageIds: messageIds, + directToolIds: [], + effectiveMessageIds: messageIds, + effectiveToolIds: [], + createdAt: blockId, + summary: `summary-${blockId}`, + } +} + +function textMessage( + sessionID: string, + id: string, + role: "user" | "assistant", + text: string, +): WithParts { + return { + info: { + id, + role, + sessionID, + time: { created: 1 }, + } as WithParts["info"], + parts: [ + { + id: `${id}-part`, + messageID: id, + sessionID, + type: "text" as const, + text, + }, + ], + } +} + +test("runInvestigation spawns a child session, returns the answer, and cleans up", async () => { + const parentSessionId = "ses-parent" + const calls: { create?: any; prompt?: any; deletedId?: string } = {} + + const client = { + session: { + create: async (input: any) => { + calls.create = input + return { data: { id: "child-1" } } + }, + prompt: async (input: any) => { + calls.prompt = input + return { data: { parts: [{ type: "text", text: "the answer" }] } } + }, + messages: async () => ({ data: [] }), + delete: async (input: any) => { + calls.deletedId = input.path.id + return { data: true } + }, + }, + } + + const block = buildBlock(1, ["msg-a"], "some topic") + const logger = new Logger(false) + + const answer = await runInvestigation( + client, + logger, + parentSessionId, + block, + "b1", + "what happened?", + "original content", + ) + + assert.equal(answer, "the answer") + assert.equal(calls.create.body.parentID, parentSessionId) + assert.match(calls.create.body.title, /b1/) + assert.equal(calls.prompt.path.id, "child-1") + assert.match(calls.prompt.body.parts[0].text, /original content/) + assert.match(calls.prompt.body.parts[0].text, /what happened\?/) + assert.equal(calls.deletedId, "child-1") +}) + +test("runInvestigation falls back to polling messages when prompt returns no text", async () => { + const client = { + session: { + create: async () => ({ data: { id: "child-2" } }), + prompt: async () => ({ data: { parts: [] } }), + messages: async () => ({ + data: [ + { info: { role: "user" }, parts: [{ type: "text", text: "prompt" }] }, + { + info: { role: "assistant" }, + parts: [{ type: "text", text: "fallback answer" }], + }, + ], + }), + delete: async () => ({ data: true }), + }, + } + + const answer = await runInvestigation( + client, + new Logger(false), + "ses-parent", + buildBlock(1, ["msg-a"]), + "b1", + "q?", + "content", + ) + assert.equal(answer, "fallback answer") +}) + +test("investigate tool returns an answer without raw content in main context", async () => { + const sessionID = `ses_investigate_${Date.now()}` + const rawMessages = [textMessage(sessionID, "msg-a", "user", "the secret original message")] + + const state = createSessionState() + state.sessionId = sessionID + state.prune.messages.blocksById.set(1, buildBlock(1, ["msg-a"])) + + let deletedId: string | undefined + + const logger = new Logger(false) + const tool = createInvestigateTool({ + client: { + session: { + messages: async () => ({ data: rawMessages }), + get: async () => ({ data: { parentID: null } }), + create: async () => ({ data: { id: "child-3" } }), + prompt: async () => ({ + data: { parts: [{ type: "text", text: "subagent answer" }] }, + }), + delete: async (input: any) => { + deletedId = input.path.id + return { data: true } + }, + }, + }, + state, + logger, + } as any) + + const result = await tool.execute( + { blockId: "b1", question: "what was the secret?" }, + { ask: async () => {}, metadata: () => {}, sessionID, messageID: "msg-call" }, + ) + + assert.equal(result, "subagent answer") + assert.equal(deletedId, "child-3") +}) + +test("investigate tool rejects an invalid block reference", async () => { + const sessionID = `ses_investigate_bad_${Date.now()}` + const state = createSessionState() + state.sessionId = sessionID + const tool = createInvestigateTool({ + client: { + session: { + messages: async () => ({ data: [] }), + get: async () => ({ data: { parentID: null } }), + }, + }, + state, + logger: new Logger(false), + } as any) + + await assert.rejects( + tool.execute( + { blockId: "bad", question: "q" }, + { ask: async () => {}, metadata: () => {}, sessionID, messageID: "msg-call" }, + ), + /Invalid block reference/, + ) +}) diff --git a/tests/read-original.test.ts b/tests/read-original.test.ts new file mode 100644 index 000000000..b616813c0 --- /dev/null +++ b/tests/read-original.test.ts @@ -0,0 +1,210 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { join } from "node:path" +import { tmpdir } from "node:os" +import { mkdirSync } from "node:fs" +import { createReadOriginalTool } from "../lib/investigate/read-original" +import { + parseBlockIdArg, + resolveBlockSlice, + serializeMessages, + truncateMessages, +} from "../lib/investigate/resolve" +import { createSessionState, type CompressionBlock, type WithParts } from "../lib/state" +import { Logger } from "../lib/logger" + +const testDataHome = join(tmpdir(), `opencode-dcp-read-original-${process.pid}`) +process.env.XDG_DATA_HOME = testDataHome +mkdirSync(testDataHome, { recursive: true }) + +function buildBlock(blockId: number, messageIds: string[], topic?: string): CompressionBlock { + return { + blockId, + runId: blockId, + active: true, + deactivatedByUser: false, + compressedTokens: 10, + summaryTokens: 5, + durationMs: 100, + mode: "range", + topic: topic ?? `topic-${blockId}`, + batchTopic: `topic-${blockId}`, + startId: `m${blockId}`, + endId: `m${blockId}`, + anchorMessageId: messageIds[0] ?? `msg-${blockId}`, + compressMessageId: `origin-${blockId}`, + includedBlockIds: [], + consumedBlockIds: [], + parentBlockIds: [], + directMessageIds: messageIds, + directToolIds: [], + effectiveMessageIds: messageIds, + effectiveToolIds: [], + createdAt: blockId, + summary: `summary-${blockId}`, + } +} + +function textMessage( + sessionID: string, + id: string, + role: "user" | "assistant", + text: string, +): WithParts { + return { + info: { + id, + role, + sessionID, + time: { created: 1 }, + } as WithParts["info"], + parts: [ + { + id: `${id}-part`, + messageID: id, + sessionID, + type: "text" as const, + text, + }, + ], + } +} + +test("parseBlockIdArg accepts bN, N, and rejects garbage", () => { + assert.equal(parseBlockIdArg("b3"), 3) + assert.equal(parseBlockIdArg("B5"), 5) + assert.equal(parseBlockIdArg(" b7 "), 7) + assert.equal(parseBlockIdArg("12"), 12) + assert.equal(parseBlockIdArg("abc"), null) + assert.equal(parseBlockIdArg("0"), null) + assert.equal(parseBlockIdArg(""), null) +}) + +test("resolveBlockSlice maps a block back to its original messages", () => { + const sessionID = "ses-resolve" + const state = createSessionState() + state.prune.messages.blocksById.set(1, buildBlock(1, ["msg-a", "msg-b"])) + + const rawMessages = [ + textMessage(sessionID, "msg-a", "user", "first"), + textMessage(sessionID, "msg-keep", "assistant", "unrelated"), + textMessage(sessionID, "msg-b", "assistant", "second"), + ] + + const slice = resolveBlockSlice(state, rawMessages, 1) + assert.equal(slice.blockRef, "b1") + assert.deepEqual( + slice.messages.map((m) => m.info.id), + ["msg-a", "msg-b"], + ) +}) + +test("resolveBlockSlice throws for a missing block", () => { + const state = createSessionState() + assert.throws(() => resolveBlockSlice(state, [], 99), /does not exist/) +}) + +test("resolveBlockSlice falls back to directMessageIds when effective is empty", () => { + const state = createSessionState() + const block = buildBlock(1, ["msg-a"]) + block.effectiveMessageIds = [] + state.prune.messages.blocksById.set(1, block) + + const rawMessages = [textMessage("ses-fallback", "msg-a", "user", "hello")] + const slice = resolveBlockSlice(state, rawMessages, 1) + assert.deepEqual( + slice.messages.map((m) => m.info.id), + ["msg-a"], + ) +}) + +test("serializeMessages formats roles and text parts", () => { + const messages = [ + textMessage("ses-s", "msg-a", "user", "question here"), + textMessage("ses-s", "msg-b", "assistant", "answer here"), + ] + const output = serializeMessages(messages) + assert.match(output, /### user/) + assert.match(output, /question here/) + assert.match(output, /### assistant/) + assert.match(output, /answer here/) +}) + +test("truncateMessages returns untruncated output when no budget is set", () => { + const messages = [textMessage("ses-t", "msg-a", "user", "hello")] + const result = truncateMessages(messages) + assert.equal(result.truncated, false) + assert.match(result.text, /hello/) +}) + +test("truncateMessages marks truncated when budget is too small", () => { + const messages = [ + textMessage("ses-t2", "msg-a", "user", "a very long sentence that should exceed one token"), + textMessage( + "ses-t2", + "msg-b", + "assistant", + "another very long sentence to push over budget", + ), + ] + const result = truncateMessages(messages, 1) + assert.equal(result.truncated, true) +}) + +test("read_original tool returns the original content for a block", async () => { + const sessionID = `ses_read_original_${Date.now()}` + const rawMessages = [ + textMessage(sessionID, "msg-a", "user", "what does foo do?"), + textMessage(sessionID, "msg-b", "assistant", "foo does the thing."), + ] + + const state = createSessionState() + state.sessionId = sessionID + state.prune.messages.blocksById.set(1, buildBlock(1, ["msg-a", "msg-b"])) + + const logger = new Logger(false) + const tool = createReadOriginalTool({ + client: { + session: { + messages: async () => ({ data: rawMessages }), + get: async () => ({ data: { parentID: null } }), + }, + }, + state, + logger, + } as any) + + const result = await tool.execute( + { blockId: "b1" }, + { ask: async () => {}, metadata: () => {}, sessionID, messageID: "msg-call" }, + ) + + assert.match(result, /Original content of compression b1/) + assert.match(result, /what does foo do\?/) + assert.match(result, /foo does the thing\./) +}) + +test("read_original tool rejects an invalid block reference", async () => { + const sessionID = `ses_read_original_bad_${Date.now()}` + const state = createSessionState() + state.sessionId = sessionID + const logger = new Logger(false) + const tool = createReadOriginalTool({ + client: { + session: { + messages: async () => ({ data: [] }), + get: async () => ({ data: { parentID: null } }), + }, + }, + state, + logger, + } as any) + + await assert.rejects( + tool.execute( + { blockId: "nope" }, + { ask: async () => {}, metadata: () => {}, sessionID, messageID: "msg-call" }, + ), + /Invalid block reference/, + ) +})