forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsessionHooks.ts
More file actions
447 lines (398 loc) · 11.8 KB
/
Copy pathsessionHooks.ts
File metadata and controls
447 lines (398 loc) · 11.8 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import { HOOK_EVENTS, type HookEvent } from 'src/entrypoints/agentSdkTypes.js'
import type { AppState } from 'src/state/AppState.js'
import type { Message } from 'src/types/message.js'
import { logForDebugging } from '../debug.js'
import type { AggregatedHookResult } from '../hooks.js'
import type { HookCommand } from '../settings/types.js'
import { isHookEqual } from './hooksSettings.js'
type OnHookSuccess = (
hook: HookCommand | FunctionHook,
result: AggregatedHookResult,
) => void
/** Function hook callback - returns true if check passes, false to block */
export type FunctionHookCallback = (
messages: Message[],
signal?: AbortSignal,
) => boolean | Promise<boolean>
/**
* Function hook type with callback embedded.
* Session-scoped only, cannot be persisted to settings.json.
*/
export type FunctionHook = {
type: 'function'
id?: string // Optional unique ID for removal
timeout?: number
callback: FunctionHookCallback
errorMessage: string
statusMessage?: string
}
type SessionHookMatcher = {
matcher: string
skillRoot?: string
hooks: Array<{
hook: HookCommand | FunctionHook
onHookSuccess?: OnHookSuccess
}>
}
export type SessionStore = {
hooks: {
[event in HookEvent]?: SessionHookMatcher[]
}
}
/**
* Map (not Record) so .set/.delete don't change the container's identity.
* Mutator functions mutate the Map and return prev unchanged, letting
* store.ts's Object.is(next, prev) check short-circuit and skip listener
* notification. Session hooks are ephemeral per-agent runtime callbacks,
* never reactively read (only getAppState() snapshots in the query loop).
* Same pattern as agentControllers on LocalWorkflowTaskState.
*
* This matters under high-concurrency workflows: parallel() with N
* schema-mode agents fires N addFunctionHook calls in one synchronous
* tick. With a Record + spread, each call cost O(N) to copy the growing
* map (O(N²) total) plus fired all ~30 store listeners. With Map: .set()
* is O(1), return prev means zero listener fires.
*/
export type SessionHooksState = Map<string, SessionStore>
/**
* Add a command or prompt hook to the session.
* Session hooks are temporary, in-memory only, and cleared when session ends.
*/
export function addSessionHook(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
event: HookEvent,
matcher: string,
hook: HookCommand,
onHookSuccess?: OnHookSuccess,
skillRoot?: string,
): void {
addHookToSession(
setAppState,
sessionId,
event,
matcher,
hook,
onHookSuccess,
skillRoot,
)
}
/**
* Add a function hook to the session.
* Function hooks execute TypeScript callbacks in-memory for validation.
* @returns The hook ID (for removal)
*/
export function addFunctionHook(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
event: HookEvent,
matcher: string,
callback: FunctionHookCallback,
errorMessage: string,
options?: {
timeout?: number
id?: string
},
): string {
const id = options?.id || `function-hook-${Date.now()}-${Math.random()}`
const hook: FunctionHook = {
type: 'function',
id,
timeout: options?.timeout || 5000,
callback,
errorMessage,
}
addHookToSession(setAppState, sessionId, event, matcher, hook)
return id
}
/**
* Remove a function hook by ID from the session.
*/
export function removeFunctionHook(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
event: HookEvent,
hookId: string,
): void {
setAppState(prev => {
const store = prev.sessionHooks.get(sessionId)
if (!store) {
return prev
}
const eventMatchers = store.hooks[event] || []
// Remove the hook with matching ID from all matchers
const updatedMatchers = eventMatchers
.map(matcher => {
const updatedHooks = matcher.hooks.filter(h => {
if (h.hook.type !== 'function') return true
return h.hook.id !== hookId
})
return updatedHooks.length > 0
? { ...matcher, hooks: updatedHooks }
: null
})
.filter((m): m is SessionHookMatcher => m !== null)
const newHooks =
updatedMatchers.length > 0
? { ...store.hooks, [event]: updatedMatchers }
: Object.fromEntries(
Object.entries(store.hooks).filter(([e]) => e !== event),
)
prev.sessionHooks.set(sessionId, { hooks: newHooks })
return prev
})
logForDebugging(
`Removed function hook ${hookId} for event ${event} in session ${sessionId}`,
)
}
/**
* Internal helper to add a hook to session state
*/
function addHookToSession(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
event: HookEvent,
matcher: string,
hook: HookCommand | FunctionHook,
onHookSuccess?: OnHookSuccess,
skillRoot?: string,
): void {
setAppState(prev => {
const store = prev.sessionHooks.get(sessionId) ?? { hooks: {} }
const eventMatchers = store.hooks[event] || []
// Find existing matcher or create new one
const existingMatcherIndex = eventMatchers.findIndex(
m => m.matcher === matcher && m.skillRoot === skillRoot,
)
let updatedMatchers: SessionHookMatcher[]
if (existingMatcherIndex >= 0) {
// Add to existing matcher
updatedMatchers = [...eventMatchers]
const existingMatcher = updatedMatchers[existingMatcherIndex]!
updatedMatchers[existingMatcherIndex] = {
matcher: existingMatcher.matcher,
skillRoot: existingMatcher.skillRoot,
hooks: [...existingMatcher.hooks, { hook, onHookSuccess }],
}
} else {
// Create new matcher
updatedMatchers = [
...eventMatchers,
{
matcher,
skillRoot,
hooks: [{ hook, onHookSuccess }],
},
]
}
const newHooks = { ...store.hooks, [event]: updatedMatchers }
prev.sessionHooks.set(sessionId, { hooks: newHooks })
return prev
})
logForDebugging(
`Added session hook for event ${event} in session ${sessionId}`,
)
}
/**
* Remove a specific hook from the session
* @param setAppState The function to update the app state
* @param sessionId The session ID
* @param event The hook event
* @param hook The hook command to remove
*/
export function removeSessionHook(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
event: HookEvent,
hook: HookCommand,
): void {
setAppState(prev => {
const store = prev.sessionHooks.get(sessionId)
if (!store) {
return prev
}
const eventMatchers = store.hooks[event] || []
// Remove the hook from all matchers
const updatedMatchers = eventMatchers
.map(matcher => {
const updatedHooks = matcher.hooks.filter(
h => !isHookEqual(h.hook, hook),
)
return updatedHooks.length > 0
? { ...matcher, hooks: updatedHooks }
: null
})
.filter((m): m is SessionHookMatcher => m !== null)
const newHooks =
updatedMatchers.length > 0
? { ...store.hooks, [event]: updatedMatchers }
: { ...store.hooks }
if (updatedMatchers.length === 0) {
delete newHooks[event]
}
prev.sessionHooks.set(sessionId, { ...store, hooks: newHooks })
return prev
})
logForDebugging(
`Removed session hook for event ${event} in session ${sessionId}`,
)
}
// Extended hook matcher that includes optional skillRoot for skill-scoped hooks
export type SessionDerivedHookMatcher = {
matcher: string
hooks: HookCommand[]
skillRoot?: string
}
/**
* Convert session hook matchers to regular hook matchers
* @param sessionMatchers The session hook matchers to convert
* @returns Regular hook matchers (with optional skillRoot preserved)
*/
function convertToHookMatchers(
sessionMatchers: SessionHookMatcher[],
): SessionDerivedHookMatcher[] {
return sessionMatchers.map(sm => ({
matcher: sm.matcher,
skillRoot: sm.skillRoot,
// Filter out function hooks - they can't be persisted to HookMatcher format
hooks: sm.hooks
.map(h => h.hook)
.filter((h): h is HookCommand => h.type !== 'function'),
}))
}
/**
* Get all session hooks for a specific event (excluding function hooks)
* @param appState The app state
* @param sessionId The session ID
* @param event Optional event to filter by
* @returns Hook matchers for the event, or all hooks if no event specified
*/
export function getSessionHooks(
appState: AppState,
sessionId: string,
event?: HookEvent,
): Map<HookEvent, SessionDerivedHookMatcher[]> {
const store = appState.sessionHooks.get(sessionId)
if (!store) {
return new Map()
}
const result = new Map<HookEvent, SessionDerivedHookMatcher[]>()
if (event) {
const sessionMatchers = store.hooks[event]
if (sessionMatchers) {
result.set(event, convertToHookMatchers(sessionMatchers))
}
return result
}
for (const evt of HOOK_EVENTS) {
const sessionMatchers = store.hooks[evt]
if (sessionMatchers) {
result.set(evt, convertToHookMatchers(sessionMatchers))
}
}
return result
}
type FunctionHookMatcher = {
matcher: string
hooks: FunctionHook[]
}
/**
* Get all session function hooks for a specific event
* Function hooks are kept separate because they can't be persisted to HookMatcher format.
* @param appState The app state
* @param sessionId The session ID
* @param event Optional event to filter by
* @returns Function hook matchers for the event
*/
export function getSessionFunctionHooks(
appState: AppState,
sessionId: string,
event?: HookEvent,
): Map<HookEvent, FunctionHookMatcher[]> {
const store = appState.sessionHooks.get(sessionId)
if (!store) {
return new Map()
}
const result = new Map<HookEvent, FunctionHookMatcher[]>()
const extractFunctionHooks = (
sessionMatchers: SessionHookMatcher[],
): FunctionHookMatcher[] => {
return sessionMatchers
.map(sm => ({
matcher: sm.matcher,
hooks: sm.hooks
.map(h => h.hook)
.filter((h): h is FunctionHook => h.type === 'function'),
}))
.filter(m => m.hooks.length > 0)
}
if (event) {
const sessionMatchers = store.hooks[event]
if (sessionMatchers) {
const functionMatchers = extractFunctionHooks(sessionMatchers)
if (functionMatchers.length > 0) {
result.set(event, functionMatchers)
}
}
return result
}
for (const evt of HOOK_EVENTS) {
const sessionMatchers = store.hooks[evt]
if (sessionMatchers) {
const functionMatchers = extractFunctionHooks(sessionMatchers)
if (functionMatchers.length > 0) {
result.set(evt, functionMatchers)
}
}
}
return result
}
/**
* Get the full hook entry (including callbacks) for a specific session hook
*/
export function getSessionHookCallback(
appState: AppState,
sessionId: string,
event: HookEvent,
matcher: string,
hook: HookCommand | FunctionHook,
):
| {
hook: HookCommand | FunctionHook
onHookSuccess?: OnHookSuccess
}
| undefined {
const store = appState.sessionHooks.get(sessionId)
if (!store) {
return undefined
}
const eventMatchers = store.hooks[event]
if (!eventMatchers) {
return undefined
}
// Find the hook in the matchers
for (const matcherEntry of eventMatchers) {
if (matcherEntry.matcher === matcher || matcher === '') {
const hookEntry = matcherEntry.hooks.find(h => isHookEqual(h.hook, hook))
if (hookEntry) {
return hookEntry
}
}
}
return undefined
}
/**
* Clear all session hooks for a specific session
* @param setAppState The function to update the app state
* @param sessionId The session ID
*/
export function clearSessionHooks(
setAppState: (updater: (prev: AppState) => AppState) => void,
sessionId: string,
): void {
setAppState(prev => {
prev.sessionHooks.delete(sessionId)
return prev
})
logForDebugging(`Cleared all session hooks for session ${sessionId}`)
}