forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecPromptHook.ts
More file actions
211 lines (194 loc) · 6.66 KB
/
Copy pathexecPromptHook.ts
File metadata and controls
211 lines (194 loc) · 6.66 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
import { randomUUID } from 'crypto'
import type { HookEvent } from 'src/entrypoints/agentSdkTypes.js'
import { queryModelWithoutStreaming } from '../../services/api/claude.js'
import type { ToolUseContext } from '../../Tool.js'
import type { Message } from '../../types/message.js'
import { createAttachmentMessage } from '../attachments.js'
import { createCombinedAbortSignal } from '../combinedAbortSignal.js'
import { logForDebugging } from '../debug.js'
import { errorMessage } from '../errors.js'
import type { HookResult } from '../hooks.js'
import { safeParseJSON } from '../json.js'
import { createUserMessage, extractTextContent } from '../messages.js'
import { getSmallFastModel } from '../model/model.js'
import type { PromptHook } from '../settings/types.js'
import { asSystemPrompt } from '../systemPromptType.js'
import { addArgumentsToPrompt, hookResponseSchema } from './hookHelpers.js'
/**
* Execute a prompt-based hook using an LLM
*/
export async function execPromptHook(
hook: PromptHook,
hookName: string,
hookEvent: HookEvent,
jsonInput: string,
signal: AbortSignal,
toolUseContext: ToolUseContext,
messages?: Message[],
toolUseID?: string,
): Promise<HookResult> {
// Use provided toolUseID or generate a new one
const effectiveToolUseID = toolUseID || `hook-${randomUUID()}`
try {
// Replace $ARGUMENTS with the JSON input
const processedPrompt = addArgumentsToPrompt(hook.prompt, jsonInput)
logForDebugging(
`Hooks: Processing prompt hook with prompt: ${processedPrompt}`,
)
// Create user message directly - no need for processUserInput which would
// trigger UserPromptSubmit hooks and cause infinite recursion
const userMessage = createUserMessage({ content: processedPrompt })
// Prepend conversation history if provided
const messagesToQuery =
messages && messages.length > 0
? [...messages, userMessage]
: [userMessage]
logForDebugging(
`Hooks: Querying model with ${messagesToQuery.length} messages`,
)
// Query the model with Haiku
const hookTimeoutMs = hook.timeout ? hook.timeout * 1000 : 30000
// Combined signal: aborts if either the hook signal or timeout triggers
const { signal: combinedSignal, cleanup: cleanupSignal } =
createCombinedAbortSignal(signal, { timeoutMs: hookTimeoutMs })
try {
const response = await queryModelWithoutStreaming({
messages: messagesToQuery,
systemPrompt: asSystemPrompt([
`You are evaluating a hook in Claude Code.
Your response must be a JSON object matching one of the following schemas:
1. If the condition is met, return: {"ok": true}
2. If the condition is not met, return: {"ok": false, "reason": "Reason for why it is not met"}`,
]),
thinkingConfig: { type: 'disabled' as const },
tools: toolUseContext.options.tools,
signal: combinedSignal,
options: {
async getToolPermissionContext() {
const appState = toolUseContext.getAppState()
return appState.toolPermissionContext
},
model: hook.model ?? getSmallFastModel(),
toolChoice: undefined,
isNonInteractiveSession: true,
hasAppendSystemPrompt: false,
agents: [],
querySource: 'hook_prompt',
mcpTools: [],
agentId: toolUseContext.agentId,
outputFormat: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
ok: { type: 'boolean' },
reason: { type: 'string' },
},
required: ['ok'],
additionalProperties: false,
},
},
},
})
cleanupSignal()
// Extract text content from response
const content = extractTextContent(response.message.content)
// Update response length for spinner display
toolUseContext.setResponseLength(length => length + content.length)
const fullResponse = content.trim()
logForDebugging(`Hooks: Model response: ${fullResponse}`)
const json = safeParseJSON(fullResponse)
if (!json) {
logForDebugging(
`Hooks: error parsing response as JSON: ${fullResponse}`,
)
return {
hook,
outcome: 'non_blocking_error',
message: createAttachmentMessage({
type: 'hook_non_blocking_error',
hookName,
toolUseID: effectiveToolUseID,
hookEvent,
stderr: 'JSON validation failed',
stdout: fullResponse,
exitCode: 1,
}),
}
}
const parsed = hookResponseSchema().safeParse(json)
if (!parsed.success) {
logForDebugging(
`Hooks: model response does not conform to expected schema: ${parsed.error.message}`,
)
return {
hook,
outcome: 'non_blocking_error',
message: createAttachmentMessage({
type: 'hook_non_blocking_error',
hookName,
toolUseID: effectiveToolUseID,
hookEvent,
stderr: `Schema validation failed: ${parsed.error.message}`,
stdout: fullResponse,
exitCode: 1,
}),
}
}
// Failed to meet condition
if (!parsed.data.ok) {
logForDebugging(
`Hooks: Prompt hook condition was not met: ${parsed.data.reason}`,
)
return {
hook,
outcome: 'blocking',
blockingError: {
blockingError: `Prompt hook condition was not met: ${parsed.data.reason}`,
command: hook.prompt,
},
preventContinuation: true,
stopReason: parsed.data.reason,
}
}
// Condition was met
logForDebugging(`Hooks: Prompt hook condition was met`)
return {
hook,
outcome: 'success',
message: createAttachmentMessage({
type: 'hook_success',
hookName,
toolUseID: effectiveToolUseID,
hookEvent,
content: '',
}),
}
} catch (error) {
cleanupSignal()
if (combinedSignal.aborted) {
return {
hook,
outcome: 'cancelled',
}
}
throw error
}
} catch (error) {
const errorMsg = errorMessage(error)
logForDebugging(`Hooks: Prompt hook error: ${errorMsg}`)
return {
hook,
outcome: 'non_blocking_error',
message: createAttachmentMessage({
type: 'hook_non_blocking_error',
hookName,
toolUseID: effectiveToolUseID,
hookEvent,
stderr: `Error executing prompt hook: ${errorMsg}`,
stdout: '',
exitCode: 1,
}),
}
}
}