Skip to content

Commit b810411

Browse files
authored
Merge pull request #151 from Opencode-DCP/refactor-utils-structure
utils structure refactor
2 parents 7849674 + 350c9cb commit b810411

File tree

11 files changed

+67
-69
lines changed

11 files changed

+67
-69
lines changed

lib/messages/prune.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import type { SessionState, WithParts } from "../state"
22
import type { Logger } from "../logger"
33
import type { PluginConfig } from "../config"
4-
import { getLastUserMessage, extractParameterKey, buildToolIdList } from "./utils"
54
import { loadPrompt } from "../prompt"
5+
import { extractParameterKey, buildToolIdList } from "./utils"
6+
import { getLastUserMessage } from "../shared-utils"
7+
import { UserMessage } from "@opencode-ai/sdk"
68

79
const PRUNED_TOOL_OUTPUT_REPLACEMENT = '[Output removed to save context - information superseded or no longer needed]'
810
const NUDGE_STRING = loadPrompt("nudge")
@@ -51,7 +53,7 @@ export const insertPruneToolContext = (
5153
}
5254

5355
const lastUserMessage = getLastUserMessage(messages)
54-
if (!lastUserMessage || lastUserMessage.info.role !== 'user') {
56+
if (!lastUserMessage) {
5557
return
5658
}
5759

@@ -72,10 +74,10 @@ export const insertPruneToolContext = (
7274
sessionID: lastUserMessage.info.sessionID,
7375
role: "user",
7476
time: { created: Date.now() },
75-
agent: lastUserMessage.info.agent || "build",
77+
agent: (lastUserMessage.info as UserMessage).agent || "build",
7678
model: {
77-
providerID: lastUserMessage.info.model.providerID,
78-
modelID: lastUserMessage.info.model.modelID
79+
providerID: (lastUserMessage.info as UserMessage).model.providerID,
80+
modelID: (lastUserMessage.info as UserMessage).model.modelID
7981
}
8082
},
8183
parts: [
@@ -118,9 +120,6 @@ const pruneToolOutputs = (
118120
if (part.state.status === 'completed') {
119121
part.state.output = PRUNED_TOOL_OUTPUT_REPLACEMENT
120122
}
121-
// if (part.state.status === 'error') {
122-
// part.state.error = PRUNED_TOOL_OUTPUT_REPLACEMENT
123-
// }
124123
}
125124
}
126125
}

lib/messages/utils.ts

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { UserMessage } from "@opencode-ai/sdk"
2-
import { Logger } from "../logger"
31
import type { WithParts } from "../state"
42

53
/**
@@ -73,38 +71,6 @@ export const extractParameterKey = (tool: string, parameters: any): string => {
7371
return paramStr.substring(0, 50)
7472
}
7573

76-
export const getLastUserMessage = (
77-
messages: WithParts[]
78-
): WithParts | null => {
79-
for (let i = messages.length - 1; i >= 0; i--) {
80-
const msg = messages[i]
81-
if (msg.info.role === 'user') {
82-
return msg
83-
}
84-
}
85-
return null
86-
}
87-
88-
export function getCurrentParams(
89-
messages: WithParts[],
90-
logger: Logger
91-
): {
92-
providerId: string | undefined,
93-
modelId: string | undefined,
94-
agent: string | undefined
95-
} {
96-
const userMsg = getLastUserMessage(messages)
97-
if (!userMsg) {
98-
logger.debug("No user message found when determining current params")
99-
return { providerId: undefined, modelId: undefined, agent: undefined }
100-
}
101-
const agent: string = (userMsg.info as UserMessage).agent
102-
const providerId: string | undefined = (userMsg.info as UserMessage).model.providerID
103-
const modelId: string | undefined = (userMsg.info as UserMessage).model.modelID
104-
105-
return { providerId, modelId, agent }
106-
}
107-
10874
export function buildToolIdList(messages: WithParts[]): string[] {
10975
const toolIds: string[] = []
11076
for (const msg of messages) {

lib/shared-utils.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { WithParts } from "./state"
2+
3+
export const getLastUserMessage = (
4+
messages: WithParts[]
5+
): WithParts | null => {
6+
for (let i = messages.length - 1; i >= 0; i--) {
7+
const msg = messages[i]
8+
if (msg.info.role === 'user') {
9+
return msg
10+
}
11+
}
12+
return null
13+
}

lib/state/state.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import type { SessionState, ToolParameterEntry, WithParts } from "./types"
22
import type { Logger } from "../logger"
33
import { loadSessionState } from "./persistence"
4-
import { getLastUserMessage } from "../messages/utils"
5-
import { isSubAgentSession } from "../utils"
4+
import { isSubAgentSession } from "./utils"
5+
import { getLastUserMessage } from "../shared-utils"
66

77
export const checkSession = async (
88
client: any,

lib/state/utils.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export async function isSubAgentSession(client: any, sessionID: string): Promise<boolean> {
2+
try {
3+
const result = await client.session.get({ path: { id: sessionID } })
4+
return !!result.data?.parentID
5+
} catch (error: any) {
6+
return false
7+
}
8+
}

lib/strategies/deduplication.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { PluginConfig } from "../config"
22
import { Logger } from "../logger"
33
import type { SessionState, WithParts } from "../state"
4-
import { calculateTokensSaved } from "../utils"
54
import { buildToolIdList } from "../messages/utils"
5+
import { calculateTokensSaved } from "./utils"
66

77
/**
88
* Deduplication strategy - prunes older tool calls that have identical

lib/strategies/on-idle.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ import type { Logger } from "../logger"
44
import type { PluginConfig } from "../config"
55
import { buildAnalysisPrompt } from "../prompt"
66
import { selectModel, ModelInfo } from "../model-selector"
7-
import { calculateTokensSaved } from "../utils"
8-
import { getCurrentParams } from "../messages/utils"
97
import { saveSessionState } from "../state/persistence"
108
import { sendUnifiedNotification } from "../ui/notification"
9+
import { calculateTokensSaved, getCurrentParams } from "./utils"
1110

1211
export interface OnIdleResult {
1312
prunedCount: number

lib/strategies/prune-tool.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { tool } from "@opencode-ai/plugin"
22
import type { SessionState, ToolParameterEntry, WithParts } from "../state"
33
import type { PluginConfig } from "../config"
4-
import { getCurrentParams, buildToolIdList } from "../messages/utils"
5-
import { calculateTokensSaved } from "../utils"
4+
import { buildToolIdList } from "../messages/utils"
65
import { PruneReason, sendUnifiedNotification } from "../ui/notification"
7-
import { formatPruningResultForTool } from "../ui/display-utils"
6+
import { formatPruningResultForTool } from "../ui/utils"
87
import { ensureSessionInitialized } from "../state"
98
import { saveSessionState } from "../state/persistence"
109
import type { Logger } from "../logger"
1110
import { loadPrompt } from "../prompt"
11+
import { calculateTokensSaved, getCurrentParams } from "./utils"
1212

1313
/** Tool description loaded from prompts/tool.txt */
1414
const TOOL_DESCRIPTION = loadPrompt("tool")

lib/utils.ts renamed to lib/strategies/utils.ts

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
1-
import { WithParts } from "./state"
1+
import { WithParts } from "../state"
2+
import { UserMessage } from "@opencode-ai/sdk"
3+
import { Logger } from "../logger"
24
import { encode } from 'gpt-tokenizer'
5+
import { getLastUserMessage } from "../shared-utils"
6+
7+
export function getCurrentParams(
8+
messages: WithParts[],
9+
logger: Logger
10+
): {
11+
providerId: string | undefined,
12+
modelId: string | undefined,
13+
agent: string | undefined
14+
} {
15+
const userMsg = getLastUserMessage(messages)
16+
if (!userMsg) {
17+
logger.debug("No user message found when determining current params")
18+
return { providerId: undefined, modelId: undefined, agent: undefined }
19+
}
20+
const agent: string = (userMsg.info as UserMessage).agent
21+
const providerId: string | undefined = (userMsg.info as UserMessage).model.providerID
22+
const modelId: string | undefined = (userMsg.info as UserMessage).model.modelID
23+
24+
return { providerId, modelId, agent }
25+
}
326

427
/**
528
* Estimates token counts for a batch of texts using gpt-tokenizer.
@@ -47,19 +70,3 @@ export const calculateTokensSaved = (
4770
return 0
4871
}
4972
}
50-
51-
export function formatTokenCount(tokens: number): string {
52-
if (tokens >= 1000) {
53-
return `${(tokens / 1000).toFixed(1)}K`.replace('.0K', 'K') + ' tokens'
54-
}
55-
return tokens.toString() + ' tokens'
56-
}
57-
58-
export async function isSubAgentSession(client: any, sessionID: string): Promise<boolean> {
59-
try {
60-
const result = await client.session.get({ path: { id: sessionID } })
61-
return !!result.data?.parentID
62-
} catch (error: any) {
63-
return false
64-
}
65-
}

lib/ui/notification.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import type { Logger } from "../logger"
22
import type { SessionState } from "../state"
3-
import { formatTokenCount } from "../utils"
4-
import { formatPrunedItemsList } from "./display-utils"
3+
import { formatPrunedItemsList, formatTokenCount } from "./utils"
54
import { ToolParameterEntry } from "../state"
65
import { PluginConfig } from "../config"
76

0 commit comments

Comments
 (0)