Skip to content

Commit 26dbfc2

Browse files
feat: add uid + token counts to tool outputs and muid to user message
1 parent 1eea9ea commit 26dbfc2

1 file changed

Lines changed: 37 additions & 1 deletion

File tree

lib/hooks.ts

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,49 @@ import { handleHelpCommand } from "./commands/help"
1313
import { handleSweepCommand } from "./commands/sweep"
1414
import { handleManualToggleCommand, handleManualTriggerCommand } from "./commands/manual"
1515
import { ensureSessionInitialized } from "./state/state"
16-
import { getCurrentParams } from "./strategies/utils"
16+
import { getCurrentParams, countToolTokens } from "./strategies/utils"
1717

1818
const INTERNAL_AGENT_SIGNATURES = [
1919
"You are a title generator",
2020
"You are a helpful AI assistant tasked with summarizing conversations",
2121
"Summarize what was done in this conversation",
2222
]
2323

24+
function formatTokenCount(n: number): string {
25+
if (n >= 1000) return `${(n / 1000).toFixed(1)}k tokens`
26+
return `${n} tokens`
27+
}
28+
29+
function annotateContext(messages: WithParts[]): void {
30+
let uid = 0
31+
let muid = 0
32+
for (const msg of messages) {
33+
const parts = Array.isArray(msg.parts) ? msg.parts : []
34+
35+
if (msg.info.role === "user" && !isIgnoredUserMessage(msg)) {
36+
muid++
37+
const text = parts.find(
38+
(p) => p.type === "text" && !(p as any).ignored && !(p as any).synthetic,
39+
)
40+
if (text && text.type === "text") {
41+
text.text = `[muid_${muid}]\n${text.text}`
42+
}
43+
}
44+
45+
for (const part of parts) {
46+
if (part.type !== "tool") continue
47+
uid++
48+
const tokens = countToolTokens(part)
49+
const tag = tokens > 0 ? `[uid_${uid}, ${formatTokenCount(tokens)}]` : `[uid_${uid}]`
50+
if (part.state?.status === "completed" && typeof part.state.output === "string") {
51+
part.state.output = `${tag}\n${part.state.output}`
52+
} else if (part.state?.status === "error" && typeof part.state.error === "string") {
53+
part.state.error = `${tag}\n${part.state.error}`
54+
}
55+
}
56+
}
57+
}
58+
2459
function applyPendingManualTriggerPrompt(
2560
state: SessionState,
2661
messages: WithParts[],
@@ -118,6 +153,7 @@ export function createChatMessageTransformHandler(
118153
insertCompressToolContext(state, config, logger, output.messages)
119154

120155
applyPendingManualTriggerPrompt(state, output.messages, logger)
156+
annotateContext(output.messages)
121157

122158
if (state.sessionId) {
123159
await logger.saveContext(state.sessionId, output.messages)

0 commit comments

Comments
 (0)