@tarquinen/opencode-dcp 3.1.11 → 3.1.13

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.
Files changed (111) hide show
  1. package/README.md +14 -9
  2. package/dist/index.js +106 -49
  3. package/dist/index.js.map +1 -1
  4. package/dist/lib/commands/context.d.ts +15 -0
  5. package/dist/lib/commands/context.d.ts.map +1 -1
  6. package/dist/lib/commands/help.d.ts +1 -0
  7. package/dist/lib/commands/help.d.ts.map +1 -1
  8. package/dist/lib/commands/manual.d.ts +1 -1
  9. package/dist/lib/commands/manual.d.ts.map +1 -1
  10. package/dist/lib/commands/stats.d.ts +10 -0
  11. package/dist/lib/commands/stats.d.ts.map +1 -1
  12. package/dist/lib/compress/pipeline.d.ts.map +1 -1
  13. package/dist/lib/hooks.d.ts +0 -2
  14. package/dist/lib/hooks.d.ts.map +1 -1
  15. package/dist/lib/messages/index.d.ts +0 -1
  16. package/dist/lib/messages/index.d.ts.map +1 -1
  17. package/dist/lib/messages/inject/utils.d.ts +0 -7
  18. package/dist/lib/messages/inject/utils.d.ts.map +1 -1
  19. package/dist/lib/state/persistence.d.ts +3 -0
  20. package/dist/lib/state/persistence.d.ts.map +1 -1
  21. package/dist/lib/state/state.d.ts +1 -0
  22. package/dist/lib/state/state.d.ts.map +1 -1
  23. package/dist/lib/tui/commands.d.ts +3 -0
  24. package/dist/lib/tui/commands.d.ts.map +1 -0
  25. package/dist/lib/tui/data.d.ts +14 -0
  26. package/dist/lib/tui/data.d.ts.map +1 -0
  27. package/dist/lib/tui/dialogs.d.ts +30 -0
  28. package/dist/lib/tui/dialogs.d.ts.map +1 -0
  29. package/dist/lib/tui/format.d.ts +4 -0
  30. package/dist/lib/tui/format.d.ts.map +1 -0
  31. package/dist/lib/tui/modals.d.ts +10 -0
  32. package/dist/lib/tui/modals.d.ts.map +1 -0
  33. package/dist/lib/tui/types.d.ts +15 -0
  34. package/dist/lib/tui/types.d.ts.map +1 -0
  35. package/dist/lib/tui/ui.d.ts +48 -0
  36. package/dist/lib/tui/ui.d.ts.map +1 -0
  37. package/dist/tui.d.ts +7 -0
  38. package/dist/tui.d.ts.map +1 -0
  39. package/lib/auth.ts +37 -0
  40. package/lib/commands/compression-targets.ts +137 -0
  41. package/lib/commands/context.ts +305 -0
  42. package/lib/commands/decompress.ts +275 -0
  43. package/lib/commands/help.ts +76 -0
  44. package/lib/commands/index.ts +11 -0
  45. package/lib/commands/manual.ts +127 -0
  46. package/lib/commands/recompress.ts +224 -0
  47. package/lib/commands/stats.ts +159 -0
  48. package/lib/commands/sweep.ts +268 -0
  49. package/lib/compress/index.ts +3 -0
  50. package/lib/compress/message-utils.ts +250 -0
  51. package/lib/compress/message.ts +145 -0
  52. package/lib/compress/pipeline.ts +108 -0
  53. package/lib/compress/protected-content.ts +208 -0
  54. package/lib/compress/range-utils.ts +308 -0
  55. package/lib/compress/range.ts +192 -0
  56. package/lib/compress/search.ts +267 -0
  57. package/lib/compress/state.ts +268 -0
  58. package/lib/compress/timing.ts +77 -0
  59. package/lib/compress/types.ts +108 -0
  60. package/lib/compress-permission.ts +25 -0
  61. package/lib/config.ts +1007 -0
  62. package/lib/hooks.ts +375 -0
  63. package/lib/host-permissions.ts +101 -0
  64. package/lib/logger.ts +226 -0
  65. package/lib/message-ids.ts +172 -0
  66. package/lib/messages/index.ts +8 -0
  67. package/lib/messages/inject/inject.ts +215 -0
  68. package/lib/messages/inject/subagent-results.ts +82 -0
  69. package/lib/messages/inject/utils.ts +374 -0
  70. package/lib/messages/priority.ts +102 -0
  71. package/lib/messages/prune.ts +233 -0
  72. package/lib/messages/query.ts +72 -0
  73. package/lib/messages/reasoning-strip.ts +40 -0
  74. package/lib/messages/shape.ts +50 -0
  75. package/lib/messages/sync.ts +124 -0
  76. package/lib/messages/utils.ts +185 -0
  77. package/lib/prompts/compress-message.ts +43 -0
  78. package/lib/prompts/compress-range.ts +60 -0
  79. package/lib/prompts/context-limit-nudge.ts +18 -0
  80. package/lib/prompts/extensions/nudge.ts +43 -0
  81. package/lib/prompts/extensions/system.ts +32 -0
  82. package/lib/prompts/extensions/tool.ts +35 -0
  83. package/lib/prompts/index.ts +29 -0
  84. package/lib/prompts/iteration-nudge.ts +6 -0
  85. package/lib/prompts/store.ts +467 -0
  86. package/lib/prompts/system.ts +33 -0
  87. package/lib/prompts/turn-nudge.ts +10 -0
  88. package/lib/protected-patterns.ts +128 -0
  89. package/lib/state/index.ts +4 -0
  90. package/lib/state/persistence.ts +305 -0
  91. package/lib/state/state.ts +208 -0
  92. package/lib/state/tool-cache.ts +98 -0
  93. package/lib/state/types.ts +111 -0
  94. package/lib/state/utils.ts +345 -0
  95. package/lib/strategies/deduplication.ts +127 -0
  96. package/lib/strategies/index.ts +2 -0
  97. package/lib/strategies/purge-errors.ts +88 -0
  98. package/lib/subagents/subagent-results.ts +74 -0
  99. package/lib/token-utils.ts +164 -0
  100. package/lib/tui/commands.ts +31 -0
  101. package/lib/tui/data.ts +73 -0
  102. package/lib/tui/dialogs.tsx +235 -0
  103. package/lib/tui/format.ts +25 -0
  104. package/lib/tui/modals.tsx +92 -0
  105. package/lib/tui/types.ts +16 -0
  106. package/lib/tui/ui.tsx +219 -0
  107. package/lib/ui/notification.ts +347 -0
  108. package/lib/ui/utils.ts +304 -0
  109. package/lib/update.ts +185 -0
  110. package/package.json +17 -5
  111. package/tui.tsx +26 -0
@@ -0,0 +1,268 @@
1
+ /**
2
+ * DCP Sweep command handler.
3
+ * Prunes tool outputs since the last user message, or the last N tools.
4
+ *
5
+ * Usage:
6
+ * /dcp sweep - Prune all tools since the previous user message
7
+ * /dcp sweep 10 - Prune the last 10 tools
8
+ */
9
+
10
+ import type { Logger } from "../logger"
11
+ import type { SessionState, WithParts, ToolParameterEntry } from "../state"
12
+ import type { PluginConfig } from "../config"
13
+ import { sendIgnoredMessage } from "../ui/notification"
14
+ import { formatPrunedItemsList } from "../ui/utils"
15
+ import { getCurrentParams, getTotalToolTokens } from "../token-utils"
16
+ import { isIgnoredUserMessage } from "../messages/query"
17
+ import { buildToolIdList } from "../messages/utils"
18
+ import { saveSessionState } from "../state/persistence"
19
+ import { isMessageCompacted } from "../state/utils"
20
+ import {
21
+ getFilePathsFromParameters,
22
+ isFilePathProtected,
23
+ isToolNameProtected,
24
+ } from "../protected-patterns"
25
+ import { syncToolCache } from "../state/tool-cache"
26
+
27
+ export interface SweepCommandContext {
28
+ client: any
29
+ state: SessionState
30
+ config: PluginConfig
31
+ logger: Logger
32
+ sessionId: string
33
+ messages: WithParts[]
34
+ args: string[]
35
+ workingDirectory: string
36
+ }
37
+
38
+ function findLastUserMessageIndex(messages: WithParts[]): number {
39
+ for (let i = messages.length - 1; i >= 0; i--) {
40
+ const msg = messages[i]
41
+ if (msg.info.role === "user" && !isIgnoredUserMessage(msg)) {
42
+ return i
43
+ }
44
+ }
45
+
46
+ return -1
47
+ }
48
+
49
+ function collectToolIdsAfterIndex(
50
+ state: SessionState,
51
+ messages: WithParts[],
52
+ afterIndex: number,
53
+ ): string[] {
54
+ const toolIds: string[] = []
55
+
56
+ for (let i = afterIndex + 1; i < messages.length; i++) {
57
+ const msg = messages[i]
58
+ if (isMessageCompacted(state, msg)) {
59
+ continue
60
+ }
61
+ const parts = Array.isArray(msg.parts) ? msg.parts : []
62
+ if (parts.length > 0) {
63
+ for (const part of parts) {
64
+ if (part.type === "tool" && part.callID && part.tool) {
65
+ toolIds.push(part.callID)
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ return toolIds
72
+ }
73
+
74
+ function formatNoUserMessage(): string {
75
+ const lines: string[] = []
76
+
77
+ lines.push("╭───────────────────────────────────────────────────────────╮")
78
+ lines.push("│ DCP Sweep │")
79
+ lines.push("╰───────────────────────────────────────────────────────────╯")
80
+ lines.push("")
81
+ lines.push("Nothing swept: no user message found.")
82
+
83
+ return lines.join("\n")
84
+ }
85
+
86
+ function formatSweepMessage(
87
+ toolCount: number,
88
+ tokensSaved: number,
89
+ mode: "since-user" | "last-n",
90
+ toolIds: string[],
91
+ toolMetadata: Map<string, ToolParameterEntry>,
92
+ workingDirectory?: string,
93
+ skippedProtected?: number,
94
+ ): string {
95
+ const lines: string[] = []
96
+
97
+ lines.push("╭───────────────────────────────────────────────────────────╮")
98
+ lines.push("│ DCP Sweep │")
99
+ lines.push("╰───────────────────────────────────────────────────────────╯")
100
+ lines.push("")
101
+
102
+ if (toolCount === 0) {
103
+ if (mode === "since-user") {
104
+ lines.push("No tools found since the previous user message.")
105
+ } else {
106
+ lines.push(`No tools found to sweep.`)
107
+ }
108
+ if (skippedProtected && skippedProtected > 0) {
109
+ lines.push(`(${skippedProtected} protected tool(s) skipped)`)
110
+ }
111
+ } else {
112
+ if (mode === "since-user") {
113
+ lines.push(`Swept ${toolCount} tool(s) since the previous user message.`)
114
+ } else {
115
+ lines.push(`Swept the last ${toolCount} tool(s).`)
116
+ }
117
+ lines.push(`Tokens saved: ~${tokensSaved.toLocaleString()}`)
118
+ if (skippedProtected && skippedProtected > 0) {
119
+ lines.push(`(${skippedProtected} protected tool(s) skipped)`)
120
+ }
121
+ lines.push("")
122
+ const itemLines = formatPrunedItemsList(toolIds, toolMetadata, workingDirectory)
123
+ lines.push(...itemLines)
124
+ }
125
+
126
+ return lines.join("\n")
127
+ }
128
+
129
+ export async function handleSweepCommand(ctx: SweepCommandContext): Promise<void> {
130
+ const { client, state, config, logger, sessionId, messages, args, workingDirectory } = ctx
131
+
132
+ const params = getCurrentParams(state, messages, logger)
133
+ const protectedTools = config.commands.protectedTools
134
+
135
+ syncToolCache(state, config, logger, messages)
136
+ buildToolIdList(state, messages)
137
+
138
+ // Parse optional numeric argument
139
+ const numArg = args[0] ? parseInt(args[0], 10) : null
140
+ const isLastNMode = numArg !== null && !isNaN(numArg) && numArg > 0
141
+
142
+ let toolIdsToSweep: string[]
143
+ let mode: "since-user" | "last-n"
144
+
145
+ if (isLastNMode) {
146
+ // Mode: Sweep last N tools
147
+ mode = "last-n"
148
+ const startIndex = Math.max(0, state.toolIdList.length - numArg!)
149
+ toolIdsToSweep = state.toolIdList.slice(startIndex)
150
+ logger.info(`Sweep command: last ${numArg} mode, found ${toolIdsToSweep.length} tools`)
151
+ } else {
152
+ // Mode: Sweep since last user message
153
+ mode = "since-user"
154
+ const lastUserMsgIndex = findLastUserMessageIndex(messages)
155
+
156
+ if (lastUserMsgIndex === -1) {
157
+ // No user message found - show message and return
158
+ const message = formatNoUserMessage()
159
+ await sendIgnoredMessage(client, sessionId, message, params, logger)
160
+ logger.info("Sweep command: no user message found")
161
+ return
162
+ } else {
163
+ toolIdsToSweep = collectToolIdsAfterIndex(state, messages, lastUserMsgIndex)
164
+ logger.info(
165
+ `Sweep command: found last user at index ${lastUserMsgIndex}, sweeping ${toolIdsToSweep.length} tools`,
166
+ )
167
+ }
168
+ }
169
+
170
+ // Filter out already-pruned tools, protected tools, and protected file paths
171
+ const newToolIds = toolIdsToSweep.filter((id) => {
172
+ if (state.prune.tools.has(id)) {
173
+ return false
174
+ }
175
+ const entry = state.toolParameters.get(id)
176
+ if (!entry) {
177
+ return true
178
+ }
179
+ if (isToolNameProtected(entry.tool, protectedTools)) {
180
+ logger.debug(`Sweep: skipping protected tool ${entry.tool} (${id})`)
181
+ return false
182
+ }
183
+ const filePaths = getFilePathsFromParameters(entry.tool, entry.parameters)
184
+ if (isFilePathProtected(filePaths, config.protectedFilePatterns)) {
185
+ logger.debug(`Sweep: skipping protected file path(s) ${filePaths.join(", ")} (${id})`)
186
+ return false
187
+ }
188
+ return true
189
+ })
190
+
191
+ // Count how many were skipped due to protection
192
+ const skippedProtected = toolIdsToSweep.filter((id) => {
193
+ const entry = state.toolParameters.get(id)
194
+ if (!entry) {
195
+ return false
196
+ }
197
+ if (isToolNameProtected(entry.tool, protectedTools)) {
198
+ return true
199
+ }
200
+ const filePaths = getFilePathsFromParameters(entry.tool, entry.parameters)
201
+ if (isFilePathProtected(filePaths, config.protectedFilePatterns)) {
202
+ return true
203
+ }
204
+ return false
205
+ }).length
206
+
207
+ if (newToolIds.length === 0) {
208
+ const message = formatSweepMessage(
209
+ 0,
210
+ 0,
211
+ mode,
212
+ [],
213
+ new Map(),
214
+ workingDirectory,
215
+ skippedProtected,
216
+ )
217
+ await sendIgnoredMessage(client, sessionId, message, params, logger)
218
+ logger.info("Sweep command: no new tools to sweep", { skippedProtected })
219
+ return
220
+ }
221
+
222
+ const tokensSaved = getTotalToolTokens(state, newToolIds)
223
+
224
+ // Add to prune list
225
+ for (const id of newToolIds) {
226
+ const entry = state.toolParameters.get(id)
227
+ state.prune.tools.set(id, entry?.tokenCount ?? 0)
228
+ }
229
+ state.stats.pruneTokenCounter += tokensSaved
230
+ state.stats.totalPruneTokens += state.stats.pruneTokenCounter
231
+ state.stats.pruneTokenCounter = 0
232
+
233
+ // Collect metadata for logging
234
+ const toolMetadata: Map<string, ToolParameterEntry> = new Map()
235
+ for (const id of newToolIds) {
236
+ const entry = state.toolParameters.get(id)
237
+ if (entry) {
238
+ toolMetadata.set(id, entry)
239
+ }
240
+ }
241
+
242
+ // Persist state
243
+ saveSessionState(state, logger).catch((err) =>
244
+ logger.error("Failed to persist state after sweep", { error: err.message }),
245
+ )
246
+
247
+ const message = formatSweepMessage(
248
+ newToolIds.length,
249
+ tokensSaved,
250
+ mode,
251
+ newToolIds,
252
+ toolMetadata,
253
+ workingDirectory,
254
+ skippedProtected,
255
+ )
256
+ await sendIgnoredMessage(client, sessionId, message, params, logger)
257
+
258
+ logger.info("Sweep command completed", {
259
+ toolsSwept: newToolIds.length,
260
+ tokensSaved,
261
+ skippedProtected,
262
+ mode,
263
+ tools: Array.from(toolMetadata.entries()).map(([id, entry]) => ({
264
+ id,
265
+ tool: entry.tool,
266
+ })),
267
+ })
268
+ }
@@ -0,0 +1,3 @@
1
+ export { ToolContext } from "./types"
2
+ export { createCompressMessageTool } from "./message"
3
+ export { createCompressRangeTool } from "./range"
@@ -0,0 +1,250 @@
1
+ import type { PluginConfig } from "../config"
2
+ import type { SessionState } from "../state"
3
+ import { parseBoundaryId } from "../message-ids"
4
+ import { isIgnoredUserMessage, isProtectedUserMessage } from "../messages/query"
5
+ import { resolveAnchorMessageId, resolveBoundaryIds, resolveSelection } from "./search"
6
+ import { COMPRESSED_BLOCK_HEADER } from "./state"
7
+ import type {
8
+ CompressMessageEntry,
9
+ CompressMessageToolArgs,
10
+ ResolvedMessageCompression,
11
+ ResolvedMessageCompressionsResult,
12
+ SearchContext,
13
+ } from "./types"
14
+
15
+ interface SkippedIssue {
16
+ kind: string
17
+ messageId: string
18
+ }
19
+
20
+ class SoftIssue extends Error {
21
+ constructor(
22
+ public readonly kind: string,
23
+ public readonly messageId: string,
24
+ message: string,
25
+ ) {
26
+ super(message)
27
+ }
28
+ }
29
+
30
+ export function validateArgs(args: CompressMessageToolArgs): void {
31
+ if (typeof args.topic !== "string" || args.topic.trim().length === 0) {
32
+ throw new Error("topic is required and must be a non-empty string")
33
+ }
34
+
35
+ if (!Array.isArray(args.content) || args.content.length === 0) {
36
+ throw new Error("content is required and must be a non-empty array")
37
+ }
38
+
39
+ for (let index = 0; index < args.content.length; index++) {
40
+ const entry = args.content[index]
41
+ const prefix = `content[${index}]`
42
+
43
+ if (typeof entry?.messageId !== "string" || entry.messageId.trim().length === 0) {
44
+ throw new Error(`${prefix}.messageId is required and must be a non-empty string`)
45
+ }
46
+
47
+ if (typeof entry?.topic !== "string" || entry.topic.trim().length === 0) {
48
+ throw new Error(`${prefix}.topic is required and must be a non-empty string`)
49
+ }
50
+
51
+ if (typeof entry?.summary !== "string" || entry.summary.trim().length === 0) {
52
+ throw new Error(`${prefix}.summary is required and must be a non-empty string`)
53
+ }
54
+ }
55
+ }
56
+
57
+ export function formatResult(
58
+ processedCount: number,
59
+ skippedIssues: string[],
60
+ skippedCount: number,
61
+ ): string {
62
+ const messageNoun = processedCount === 1 ? "message" : "messages"
63
+ const processedText =
64
+ processedCount > 0
65
+ ? `Compressed ${processedCount} ${messageNoun} into ${COMPRESSED_BLOCK_HEADER}.`
66
+ : "Compressed 0 messages."
67
+
68
+ if (skippedCount === 0) {
69
+ return processedText
70
+ }
71
+
72
+ const issueNoun = skippedCount === 1 ? "issue" : "issues"
73
+ const issueLines = skippedIssues.map((issue) => `- ${issue}`).join("\n")
74
+ return `${processedText}\nSkipped ${skippedCount} ${issueNoun}:\n${issueLines}`
75
+ }
76
+
77
+ export function formatIssues(skippedIssues: string[], skippedCount: number): string {
78
+ const issueNoun = skippedCount === 1 ? "issue" : "issues"
79
+ const issueLines = skippedIssues.map((issue) => `- ${issue}`).join("\n")
80
+ return `Unable to compress any messages. Found ${skippedCount} ${issueNoun}:\n${issueLines}`
81
+ }
82
+
83
+ const ISSUE_TEMPLATES: Record<string, [singular: string, plural: string]> = {
84
+ blocked: [
85
+ "refers to a protected message and cannot be compressed.",
86
+ "refer to protected messages and cannot be compressed.",
87
+ ],
88
+ "invalid-format": [
89
+ "is invalid. Use an injected raw message ID of the form mNNNN.",
90
+ "are invalid. Use injected raw message IDs of the form mNNNN.",
91
+ ],
92
+ "block-id": [
93
+ "is invalid here. Block IDs like bN are not allowed; use an mNNNN message ID instead.",
94
+ "are invalid here. Block IDs like bN are not allowed; use mNNNN message IDs instead.",
95
+ ],
96
+ "not-in-context": [
97
+ "is not available in the current conversation context. Choose an injected mNNNN ID visible in context.",
98
+ "are not available in the current conversation context. Choose injected mNNNN IDs visible in context.",
99
+ ],
100
+ protected: [
101
+ "refers to a protected message and cannot be compressed.",
102
+ "refer to protected messages and cannot be compressed.",
103
+ ],
104
+ "already-compressed": [
105
+ "is already part of an active compression.",
106
+ "are already part of active compressions.",
107
+ ],
108
+ duplicate: [
109
+ "was selected more than once in this batch.",
110
+ "were each selected more than once in this batch.",
111
+ ],
112
+ }
113
+
114
+ function formatSkippedGroup(kind: string, messageIds: string[]): string {
115
+ const templates = ISSUE_TEMPLATES[kind]
116
+ const ids = messageIds.join(", ")
117
+ const single = messageIds.length === 1
118
+ const prefix = single ? "messageId" : "messageIds"
119
+
120
+ if (!templates) {
121
+ return `${prefix} ${ids}: unknown issue.`
122
+ }
123
+
124
+ return `${prefix} ${ids} ${single ? templates[0] : templates[1]}`
125
+ }
126
+
127
+ function groupSkippedIssues(issues: SkippedIssue[]): string[] {
128
+ const groups = new Map<string, string[]>()
129
+ const order: string[] = []
130
+
131
+ for (const issue of issues) {
132
+ let ids = groups.get(issue.kind)
133
+ if (!ids) {
134
+ ids = []
135
+ groups.set(issue.kind, ids)
136
+ order.push(issue.kind)
137
+ }
138
+ ids.push(issue.messageId)
139
+ }
140
+
141
+ return order.map((kind) => {
142
+ const ids = groups.get(kind)!
143
+ return formatSkippedGroup(kind, ids)
144
+ })
145
+ }
146
+
147
+ export function resolveMessages(
148
+ args: CompressMessageToolArgs,
149
+ searchContext: SearchContext,
150
+ state: SessionState,
151
+ config: PluginConfig,
152
+ ): ResolvedMessageCompressionsResult {
153
+ const issues: SkippedIssue[] = []
154
+ const plans: ResolvedMessageCompression[] = []
155
+ const seenMessageIds = new Set<string>()
156
+
157
+ for (const entry of args.content) {
158
+ const normalizedMessageId = entry.messageId.trim()
159
+ if (seenMessageIds.has(normalizedMessageId)) {
160
+ issues.push({ kind: "duplicate", messageId: normalizedMessageId })
161
+ continue
162
+ }
163
+
164
+ try {
165
+ const plan = resolveMessage(
166
+ {
167
+ ...entry,
168
+ messageId: normalizedMessageId,
169
+ },
170
+ searchContext,
171
+ state,
172
+ config,
173
+ )
174
+ seenMessageIds.add(plan.entry.messageId)
175
+ plans.push(plan)
176
+ } catch (error: any) {
177
+ if (error instanceof SoftIssue) {
178
+ issues.push({ kind: error.kind, messageId: error.messageId })
179
+ continue
180
+ }
181
+
182
+ throw error
183
+ }
184
+ }
185
+
186
+ return {
187
+ plans,
188
+ skippedIssues: groupSkippedIssues(issues),
189
+ skippedCount: issues.length,
190
+ }
191
+ }
192
+
193
+ function resolveMessage(
194
+ entry: CompressMessageEntry,
195
+ searchContext: SearchContext,
196
+ state: SessionState,
197
+ config: PluginConfig,
198
+ ): ResolvedMessageCompression {
199
+ if (entry.messageId.toUpperCase() === "BLOCKED") {
200
+ throw new SoftIssue("blocked", "BLOCKED", "protected message")
201
+ }
202
+
203
+ const parsed = parseBoundaryId(entry.messageId)
204
+
205
+ if (!parsed) {
206
+ throw new SoftIssue("invalid-format", entry.messageId, "invalid format")
207
+ }
208
+
209
+ if (parsed.kind === "compressed-block") {
210
+ throw new SoftIssue("block-id", entry.messageId, "block ID used")
211
+ }
212
+
213
+ const messageId = state.messageIds.byRef.get(parsed.ref)
214
+ const rawMessage = messageId ? searchContext.rawMessagesById.get(messageId) : undefined
215
+ if (
216
+ !messageId ||
217
+ !rawMessage ||
218
+ !searchContext.rawIndexById.has(messageId) ||
219
+ isIgnoredUserMessage(rawMessage)
220
+ ) {
221
+ throw new SoftIssue("not-in-context", parsed.ref, "not in context")
222
+ }
223
+
224
+ const { startReference, endReference } = resolveBoundaryIds(
225
+ searchContext,
226
+ state,
227
+ parsed.ref,
228
+ parsed.ref,
229
+ )
230
+ const selection = resolveSelection(searchContext, startReference, endReference)
231
+
232
+ if (isProtectedUserMessage(config, rawMessage)) {
233
+ throw new SoftIssue("protected", parsed.ref, "protected message")
234
+ }
235
+
236
+ const pruneEntry = state.prune.messages.byMessageId.get(messageId)
237
+ if (pruneEntry && pruneEntry.activeBlockIds.length > 0) {
238
+ throw new SoftIssue("already-compressed", parsed.ref, "already compressed")
239
+ }
240
+
241
+ return {
242
+ entry: {
243
+ messageId: parsed.ref,
244
+ topic: entry.topic,
245
+ summary: entry.summary,
246
+ },
247
+ selection,
248
+ anchorMessageId: resolveAnchorMessageId(startReference),
249
+ }
250
+ }
@@ -0,0 +1,145 @@
1
+ import { tool } from "@opencode-ai/plugin"
2
+ import type { ToolContext } from "./types"
3
+ import { countTokens } from "../token-utils"
4
+ import { MESSAGE_FORMAT_EXTENSION } from "../prompts/extensions/tool"
5
+ import { formatIssues, formatResult, resolveMessages, validateArgs } from "./message-utils"
6
+ import { finalizeSession, prepareSession, type NotificationEntry } from "./pipeline"
7
+ import { appendProtectedPromptInfo, appendProtectedTools } from "./protected-content"
8
+ import {
9
+ allocateBlockId,
10
+ allocateRunId,
11
+ applyCompressionState,
12
+ wrapCompressedSummary,
13
+ } from "./state"
14
+ import type { CompressMessageToolArgs } from "./types"
15
+
16
+ function buildSchema() {
17
+ return {
18
+ topic: tool.schema
19
+ .string()
20
+ .describe(
21
+ "Short label (3-5 words) for the overall batch - e.g., 'Closed Research Notes'",
22
+ ),
23
+ content: tool.schema
24
+ .array(
25
+ tool.schema.object({
26
+ messageId: tool.schema
27
+ .string()
28
+ .describe("Raw message ID to compress (e.g. m0001)"),
29
+ topic: tool.schema
30
+ .string()
31
+ .describe("Short label (3-5 words) for this one message summary"),
32
+ summary: tool.schema
33
+ .string()
34
+ .describe("Complete technical summary replacing that one message"),
35
+ }),
36
+ )
37
+ .describe("Batch of individual message summaries to create in one tool call"),
38
+ }
39
+ }
40
+
41
+ export function createCompressMessageTool(ctx: ToolContext): ReturnType<typeof tool> {
42
+ ctx.prompts.reload()
43
+ const runtimePrompts = ctx.prompts.getRuntimePrompts()
44
+
45
+ return tool({
46
+ description: runtimePrompts.compressMessage + MESSAGE_FORMAT_EXTENSION,
47
+ args: buildSchema(),
48
+ async execute(args, toolCtx) {
49
+ const input = args as CompressMessageToolArgs
50
+ validateArgs(input)
51
+ const callId =
52
+ typeof (toolCtx as unknown as { callID?: unknown }).callID === "string"
53
+ ? (toolCtx as unknown as { callID: string }).callID
54
+ : undefined
55
+
56
+ const { rawMessages, searchContext } = await prepareSession(
57
+ ctx,
58
+ toolCtx,
59
+ `Compress Message: ${input.topic}`,
60
+ )
61
+ const { plans, skippedIssues, skippedCount } = resolveMessages(
62
+ input,
63
+ searchContext,
64
+ ctx.state,
65
+ ctx.config,
66
+ )
67
+
68
+ if (plans.length === 0 && skippedCount > 0) {
69
+ throw new Error(formatIssues(skippedIssues, skippedCount))
70
+ }
71
+
72
+ const notifications: NotificationEntry[] = []
73
+
74
+ const preparedPlans: Array<{
75
+ plan: (typeof plans)[number]
76
+ summaryWithTools: string
77
+ }> = []
78
+
79
+ for (const plan of plans) {
80
+ const summaryWithPromptInfo = appendProtectedPromptInfo(
81
+ plan.entry.summary,
82
+ plan.selection,
83
+ searchContext,
84
+ ctx.state,
85
+ ctx.config.compress.protectTags,
86
+ )
87
+
88
+ const summaryWithTools = await appendProtectedTools(
89
+ ctx.client,
90
+ ctx.state,
91
+ ctx.config.experimental.allowSubAgents,
92
+ summaryWithPromptInfo,
93
+ plan.selection,
94
+ searchContext,
95
+ ctx.config.compress.protectedTools,
96
+ ctx.config.protectedFilePatterns,
97
+ )
98
+
99
+ preparedPlans.push({
100
+ plan,
101
+ summaryWithTools,
102
+ })
103
+ }
104
+
105
+ const runId = allocateRunId(ctx.state)
106
+
107
+ for (const { plan, summaryWithTools } of preparedPlans) {
108
+ const blockId = allocateBlockId(ctx.state)
109
+ const storedSummary = wrapCompressedSummary(blockId, summaryWithTools)
110
+ const summaryTokens = countTokens(storedSummary)
111
+
112
+ applyCompressionState(
113
+ ctx.state,
114
+ {
115
+ topic: plan.entry.topic,
116
+ batchTopic: input.topic,
117
+ startId: plan.entry.messageId,
118
+ endId: plan.entry.messageId,
119
+ mode: "message",
120
+ runId,
121
+ compressMessageId: toolCtx.messageID,
122
+ compressCallId: callId,
123
+ summaryTokens,
124
+ },
125
+ plan.selection,
126
+ plan.anchorMessageId,
127
+ blockId,
128
+ storedSummary,
129
+ [],
130
+ )
131
+
132
+ notifications.push({
133
+ blockId,
134
+ runId,
135
+ summary: summaryWithTools,
136
+ summaryTokens,
137
+ })
138
+ }
139
+
140
+ await finalizeSession(ctx, toolCtx, rawMessages, notifications, input.topic)
141
+
142
+ return formatResult(plans.length, skippedIssues, skippedCount)
143
+ },
144
+ })
145
+ }