-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathhooks.ts
More file actions
227 lines (194 loc) · 7.34 KB
/
hooks.ts
File metadata and controls
227 lines (194 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import type { SessionState, WithParts } from "./state"
import type { Logger } from "./logger"
import type { PluginConfig } from "./config"
import { assignMessageRefs } from "./message-ids"
import { syncToolCache } from "./state/tool-cache"
import { deduplicate, supersedeWrites, purgeErrors } from "./strategies"
import { prune, insertPruneToolContext, insertMessageIdContext } from "./messages"
import { buildToolIdList, isIgnoredUserMessage } from "./messages/utils"
import { checkSession } from "./state"
import { renderSystemPrompt } from "./prompts"
import { handleStatsCommand } from "./commands/stats"
import { handleContextCommand } from "./commands/context"
import { handleHelpCommand } from "./commands/help"
import { handleSweepCommand } from "./commands/sweep"
import { handleManualToggleCommand, handleManualTriggerCommand } from "./commands/manual"
import { ensureSessionInitialized } from "./state/state"
const INTERNAL_AGENT_SIGNATURES = [
"You are a title generator",
"You are a helpful AI assistant tasked with summarizing conversations",
"Summarize what was done in this conversation",
]
function applyPendingManualTriggerPrompt(
state: SessionState,
messages: WithParts[],
logger: Logger,
): void {
const pending = state.pendingManualTrigger
if (!pending) {
return
}
if (!state.sessionId || pending.sessionId !== state.sessionId) {
state.pendingManualTrigger = null
return
}
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
if (msg.info.role !== "user" || isIgnoredUserMessage(msg)) {
continue
}
for (const part of msg.parts) {
if (part.type !== "text" || part.ignored || part.synthetic) {
continue
}
part.text = pending.prompt
state.pendingManualTrigger = null
logger.debug("Applied pending manual trigger prompt", { sessionId: pending.sessionId })
return
}
}
state.pendingManualTrigger = null
}
export function createSystemPromptHandler(
state: SessionState,
logger: Logger,
config: PluginConfig,
) {
return async (
input: { sessionID?: string; model: { limit: { context: number } } },
output: { system: string[] },
) => {
if (input.model?.limit?.context) {
state.modelContextLimit = input.model.limit.context
logger.debug("Cached model context limit", { limit: state.modelContextLimit })
}
if (state.isSubAgent) {
return
}
const systemText = output.system.join("\n")
if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
logger.info("Skipping DCP system prompt injection for internal agent")
return
}
const flags = {
prune: config.tools.prune.permission !== "deny",
distill: config.tools.distill.permission !== "deny",
compress: config.tools.compress.permission !== "deny",
manual: state.manualMode,
}
if (!flags.prune && !flags.distill && !flags.compress) {
return
}
output.system.push(renderSystemPrompt(flags))
}
}
export function createChatMessageTransformHandler(
client: any,
state: SessionState,
logger: Logger,
config: PluginConfig,
) {
return async (input: {}, output: { messages: WithParts[] }) => {
await checkSession(client, state, logger, output.messages, config.manualMode.enabled)
if (state.isSubAgent) {
return
}
assignMessageRefs(state, output.messages)
syncToolCache(state, config, logger, output.messages)
buildToolIdList(state, output.messages, logger)
deduplicate(state, logger, config, output.messages)
supersedeWrites(state, logger, config, output.messages)
purgeErrors(state, logger, config, output.messages)
prune(state, logger, config, output.messages)
insertPruneToolContext(state, config, logger, output.messages)
insertMessageIdContext(state, config, output.messages)
applyPendingManualTriggerPrompt(state, output.messages, logger)
if (state.sessionId) {
await logger.saveContext(state.sessionId, output.messages)
}
}
}
export function createCommandExecuteHandler(
client: any,
state: SessionState,
logger: Logger,
config: PluginConfig,
workingDirectory: string,
) {
return async (
input: { command: string; sessionID: string; arguments: string },
output: { parts: any[] },
) => {
if (!config.commands.enabled) {
return
}
if (input.command === "dcp") {
const messagesResponse = await client.session.messages({
path: { id: input.sessionID },
})
const messages = (messagesResponse.data || messagesResponse) as WithParts[]
await ensureSessionInitialized(
client,
state,
input.sessionID,
logger,
messages,
config.manualMode.enabled,
)
const args = (input.arguments || "").trim().split(/\s+/).filter(Boolean)
const subcommand = args[0]?.toLowerCase() || ""
const subArgs = args.slice(1)
const commandCtx = {
client,
state,
config,
logger,
sessionId: input.sessionID,
messages,
}
if (subcommand === "context") {
await handleContextCommand(commandCtx)
throw new Error("__DCP_CONTEXT_HANDLED__")
}
if (subcommand === "stats") {
await handleStatsCommand(commandCtx)
throw new Error("__DCP_STATS_HANDLED__")
}
if (subcommand === "sweep") {
await handleSweepCommand({
...commandCtx,
args: subArgs,
workingDirectory,
})
throw new Error("__DCP_SWEEP_HANDLED__")
}
if (subcommand === "manual") {
await handleManualToggleCommand(commandCtx, subArgs[0]?.toLowerCase())
throw new Error("__DCP_MANUAL_HANDLED__")
}
if (
(subcommand === "prune" || subcommand === "distill" || subcommand === "compress") &&
config.tools[subcommand].permission !== "deny"
) {
const userFocus = subArgs.join(" ").trim()
const prompt = await handleManualTriggerCommand(commandCtx, subcommand, userFocus)
if (!prompt) {
throw new Error("__DCP_MANUAL_TRIGGER_BLOCKED__")
}
state.pendingManualTrigger = {
sessionId: input.sessionID,
prompt,
}
const rawArgs = (input.arguments || "").trim()
output.parts.length = 0
output.parts.push({
type: "text",
text: rawArgs ? `/dcp ${rawArgs}` : `/dcp ${subcommand}`,
})
return
}
await handleHelpCommand(commandCtx)
throw new Error("__DCP_HELP_HANDLED__")
}
}
}