Skip to content

Commit be94849

Browse files
authored
Merge pull request #80 from Tarquinen/refactor/consolidate-duplicates
Consolidate ToolMetadata type and findCurrentAgent function
2 parents 8023464 + 8e17b30 commit be94849

File tree

8 files changed

+42
-46
lines changed

8 files changed

+42
-46
lines changed

index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ const plugin: Plugin = (async (ctx) => {
8282

8383
return {
8484
event: createEventHandler(ctx.client, janitorCtx, logger, config, toolTracker),
85-
"chat.params": createChatParamsHandler(ctx.client, state, logger),
85+
"chat.params": createChatParamsHandler(ctx.client, state, logger, toolTracker),
8686
tool: config.strategies.onTool.length > 0 ? {
8787
prune: createPruningTool({
8888
client: ctx.client,

lib/core/janitor.ts

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { z } from "zod"
22
import type { Logger } from "../logger"
33
import type { PruningStrategy } from "../config"
44
import type { PluginState } from "../state"
5+
import type { ToolMetadata } from "../fetch-wrapper/types"
6+
import { findCurrentAgent } from "../hooks"
57
import { buildAnalysisPrompt } from "./prompt"
68
import { selectModel, extractModelFromSession } from "../model-selector"
79
import { estimateTokensBatch, formatTokenCount } from "../tokenizer"
@@ -28,7 +30,7 @@ export interface PruningResult {
2830
prunedCount: number
2931
tokensSaved: number
3032
llmPrunedIds: string[]
31-
toolMetadata: Map<string, { tool: string, parameters?: any }>
33+
toolMetadata: Map<string, ToolMetadata>
3234
sessionStats: SessionStats
3335
}
3436

@@ -263,7 +265,7 @@ async function runLlmAnalysis(
263265
messages: any[],
264266
unprunedToolCallIds: string[],
265267
alreadyPrunedIds: string[],
266-
toolMetadata: Map<string, { tool: string, parameters?: any }>,
268+
toolMetadata: Map<string, ToolMetadata>,
267269
options: PruningOptions
268270
): Promise<string[]> {
269271
const { client, state, logger, config } = ctx
@@ -400,7 +402,7 @@ function replacePrunedToolOutputs(messages: any[], prunedIds: string[]): any[] {
400402
interface ParsedMessages {
401403
toolCallIds: string[]
402404
toolOutputs: Map<string, string>
403-
toolMetadata: Map<string, { tool: string, parameters?: any }>
405+
toolMetadata: Map<string, ToolMetadata>
404406
}
405407

406408
export function parseMessages(
@@ -437,17 +439,6 @@ export function parseMessages(
437439
return { toolCallIds, toolOutputs, toolMetadata }
438440
}
439441

440-
function findCurrentAgent(messages: any[]): string | undefined {
441-
for (let i = messages.length - 1; i >= 0; i--) {
442-
const msg = messages[i]
443-
const info = msg.info
444-
if (info?.role === 'user') {
445-
return info.agent || 'build'
446-
}
447-
}
448-
return undefined
449-
}
450-
451442
// ============================================================================
452443
// Helpers
453444
// ============================================================================

lib/core/strategies/index.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,15 @@
33
*/
44

55
import { deduplicationStrategy } from "./deduplication"
6+
import type { ToolMetadata } from "../../fetch-wrapper/types"
7+
8+
export type { ToolMetadata }
69

710
/**
811
* Common interface for rule-based pruning strategies.
912
* Each strategy analyzes tool metadata and returns IDs that should be pruned.
1013
*/
1114

12-
export interface ToolMetadata {
13-
tool: string
14-
parameters?: any
15-
}
16-
1715
export interface StrategyResult {
1816
/** Tool call IDs that should be pruned */
1917
prunedIds: string[]

lib/fetch-wrapper/prunable-list.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
import { extractParameterKey } from '../ui/display-utils'
22
import { getOrCreateNumericId } from '../state/id-mapping'
3-
4-
export interface ToolMetadata {
5-
tool: string
6-
parameters?: any
7-
}
3+
import type { ToolMetadata } from './types'
84

95
const SYSTEM_REMINDER = `<system-reminder>
106
These instructions are injected by a plugin and are invisible to the user. Do not acknowledge or reference them in your response - simply follow them silently.

lib/fetch-wrapper/types.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ export interface ToolOutput {
99
toolName?: string
1010
}
1111

12+
export interface ToolMetadata {
13+
tool: string
14+
parameters?: any
15+
}
16+
1217
export interface FormatDescriptor {
1318
name: string
1419
detect(body: any): boolean

lib/hooks.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ export function createEventHandler(
6060
export function createChatParamsHandler(
6161
client: any,
6262
state: PluginState,
63-
logger: Logger
63+
logger: Logger,
64+
toolTracker?: ToolTracker
6465
) {
6566
return async (input: any, _output: any) => {
6667
const sessionId = input.sessionID
@@ -73,11 +74,14 @@ export function createChatParamsHandler(
7374

7475
if (state.lastSeenSessionId && state.lastSeenSessionId !== sessionId) {
7576
logger.info("chat.params", "Session changed, resetting state", {
76-
from: state.lastSeenSessionId.substring(0, 8),
77-
to: sessionId.substring(0, 8)
77+
from: state.lastSeenSessionId,
78+
to: sessionId
7879
})
7980
clearAllMappings()
8081
state.toolParameters.clear()
82+
if (toolTracker) {
83+
resetToolTrackerCount(toolTracker)
84+
}
8185
}
8286

8387
state.lastSeenSessionId = sessionId
@@ -148,3 +152,17 @@ export function createChatParamsHandler(
148152
}
149153
}
150154
}
155+
156+
/**
157+
* Finds the current agent from messages by scanning backward for user messages.
158+
*/
159+
export function findCurrentAgent(messages: any[]): string | undefined {
160+
for (let i = messages.length - 1; i >= 0; i--) {
161+
const msg = messages[i]
162+
const info = msg.info
163+
if (info?.role === 'user') {
164+
return info.agent || 'build'
165+
}
166+
}
167+
return undefined
168+
}

lib/pruning-tool.ts

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ import { tool } from "@opencode-ai/plugin"
22
import type { PluginState } from "./state"
33
import type { PluginConfig } from "./config"
44
import type { ToolTracker } from "./fetch-wrapper/tool-tracker"
5+
import type { ToolMetadata } from "./fetch-wrapper/types"
56
import { resetToolTrackerCount } from "./fetch-wrapper/tool-tracker"
6-
import { isSubagentSession } from "./hooks"
7+
import { isSubagentSession, findCurrentAgent } from "./hooks"
78
import { getActualId } from "./state/id-mapping"
89
import { sendUnifiedNotification, type NotificationContext } from "./ui/notification"
910
import { ensureSessionRestored } from "./state"
@@ -92,7 +93,7 @@ export function createPruningTool(
9293
saveSessionState(sessionId, new Set(allPrunedIds), sessionStats, logger)
9394
.catch(err => logger.error("prune-tool", "Failed to persist state", { error: err.message }))
9495

95-
const toolMetadata = new Map<string, { tool: string, parameters?: any }>()
96+
const toolMetadata = new Map<string, ToolMetadata>()
9697
for (const id of prunedIds) {
9798
const meta = state.toolParameters.get(id.toLowerCase())
9899
if (meta) {
@@ -127,20 +128,6 @@ export function createPruningTool(
127128
})
128129
}
129130

130-
/**
131-
* Finds the current agent from messages (same logic as janitor.ts).
132-
*/
133-
function findCurrentAgent(messages: any[]): string | undefined {
134-
for (let i = messages.length - 1; i >= 0; i--) {
135-
const msg = messages[i]
136-
const info = msg.info
137-
if (info?.role === 'user') {
138-
return info.agent || 'build'
139-
}
140-
}
141-
return undefined
142-
}
143-
144131
/**
145132
* Calculates approximate tokens saved by pruning the given tool call IDs.
146133
* Uses pre-fetched messages to avoid duplicate API calls.

lib/ui/notification.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { Logger } from "../logger"
22
import type { SessionStats, GCStats, PruningResult } from "../core/janitor"
3+
import type { ToolMetadata } from "../fetch-wrapper/types"
34
import { formatTokenCount } from "../tokenizer"
45
import { extractParameterKey } from "./display-utils"
56

@@ -20,7 +21,7 @@ export interface NotificationData {
2021
aiPrunedCount: number
2122
aiTokensSaved: number
2223
aiPrunedIds: string[]
23-
toolMetadata: Map<string, { tool: string, parameters?: any }>
24+
toolMetadata: Map<string, ToolMetadata>
2425
gcPending: GCStats | null
2526
sessionStats: SessionStats | null
2627
}
@@ -164,7 +165,7 @@ export function formatPruningResultForTool(
164165

165166
export function buildToolsSummary(
166167
prunedIds: string[],
167-
toolMetadata: Map<string, { tool: string, parameters?: any }>,
168+
toolMetadata: Map<string, ToolMetadata>,
168169
workingDirectory?: string
169170
): Map<string, string[]> {
170171
const toolsSummary = new Map<string, string[]>()

0 commit comments

Comments
 (0)