-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathunified.go
More file actions
1105 lines (991 loc) · 35.7 KB
/
Copy pathunified.go
File metadata and controls
1105 lines (991 loc) · 35.7 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hookshot
import (
"encoding/json"
"errors"
"strings"
"github.com/CorridorSecurity/hookshot/cascade"
"github.com/CorridorSecurity/hookshot/claude"
"github.com/CorridorSecurity/hookshot/codex"
"github.com/CorridorSecurity/hookshot/cursor"
"github.com/CorridorSecurity/hookshot/droid"
"github.com/CorridorSecurity/hookshot/internal"
)
// Platform identifies which AI coding tool triggered the hook.
type Platform string
const (
PlatformClaude Platform = "claude"
PlatformCursor Platform = "cursor"
PlatformDroid Platform = "droid"
PlatformCascade Platform = "cascade"
PlatformCodex Platform = "codex"
)
// =============================================================================
// Unified Stop Handler
// =============================================================================
// StopContext provides a unified view of stop events from both platforms.
type StopContext struct {
Platform Platform
SessionID string // Claude Code: session_id, Cursor: conversation_id
Cwd string // Working directory (all platforms)
// Claude Code-specific fields
StopHookActive bool // True if already continuing from a previous stop hook
// Cursor-specific fields
Status string // "completed", "aborted", or "error"
LoopCount int // Number of previous auto follow-ups (max 5)
}
// ShouldSkip returns true if the stop hook should be skipped to prevent loops.
// For Claude Code, Droid, and Codex, this checks StopHookActive. For Cursor,
// this checks LoopCount >= 3. For Cascade, there is no loop prevention
// mechanism (returns false).
func (c StopContext) ShouldSkip() bool {
if c.Platform == PlatformClaude || c.Platform == PlatformDroid || c.Platform == PlatformCodex {
return c.StopHookActive
}
if c.Platform == PlatformCursor {
return c.LoopCount >= 3
}
// Cascade has no loop prevention mechanism
return false
}
// StopDecision represents the unified decision for stop hooks.
type StopDecision struct {
// Continue determines whether the agent should stop.
// true = allow stopping, false = prevent stopping (continue working)
Continue bool
// Message is shown to the agent when Continue is false.
// For Claude Code, this becomes the "reason" field.
// For Cursor, this becomes the "followup_message" field.
Message string
}
// AllowStop returns a decision that allows the agent to stop.
func AllowStop() StopDecision {
return StopDecision{Continue: true}
}
// PreventStop returns a decision that prevents stopping with a message.
func PreventStop(message string) StopDecision {
return StopDecision{Continue: false, Message: message}
}
// StopHandler is the function signature for unified stop handlers.
type StopHandler func(StopContext) StopDecision
// OnStop registers a unified handler for stop events on all platforms.
// It automatically registers handlers for "claude-stop", "cursor-stop",
// "droid-stop", "cascade-post-cascade-response", and "codex-stop".
func OnStop(handler StopHandler) {
Register("claude-stop", func() {
Run(func(input claude.StopInput) claude.StopOutput {
ctx := StopContext{
Platform: PlatformClaude,
SessionID: input.SessionID,
Cwd: input.Cwd,
StopHookActive: input.StopHookActive,
}
decision := handler(ctx)
if decision.Continue {
return claude.Continue()
}
return claude.Block(decision.Message)
})
})
Register("cursor-stop", func() {
Run(func(input cursor.StopInput) cursor.StopOutput {
ctx := StopContext{
Platform: PlatformCursor,
SessionID: input.ConversationID,
Cwd: cursorWorkspaceRoot(input.WorkspaceRoots),
Status: input.Status,
LoopCount: input.LoopCount,
}
decision := handler(ctx)
if decision.Continue {
return cursor.Continue()
}
return cursor.Followup(decision.Message)
})
})
Register("droid-stop", func() {
Run(func(input droid.StopInput) droid.StopOutput {
ctx := StopContext{
Platform: PlatformDroid,
SessionID: input.SessionID,
Cwd: input.Cwd,
StopHookActive: input.StopHookActive,
}
decision := handler(ctx)
if decision.Continue {
return droid.Continue()
}
return droid.Block(decision.Message)
})
})
// Cascade uses post_cascade_response as the closest equivalent to stop hooks
Register("cascade-post-cascade-response", func() {
Run(func(input cascade.PostCascadeResponseInput) cascade.PostCascadeResponseOutput {
ctx := StopContext{
Platform: PlatformCascade,
SessionID: input.TrajectoryID,
}
// Cascade post hooks are fire-and-forget, but we still call the handler
// for side effects (logging, telemetry, etc.)
handler(ctx)
return cascade.PostCascadeResponseOK()
})
})
// Codex uses the same JSON wire protocol as Claude Code but with stricter
// validation. Use codex.* helpers (not claude.*) so any Codex-specific
// quirks (e.g. rejected suppressOutput / updatedInput) are handled in
// one place — the codex package.
Register("codex-stop", func() {
Run(func(input codex.StopInput) codex.StopOutput {
ctx := StopContext{
Platform: PlatformCodex,
SessionID: input.SessionID,
Cwd: input.Cwd,
StopHookActive: input.StopHookActive,
}
decision := handler(ctx)
if decision.Continue {
return codex.Continue()
}
return codex.Block(decision.Message)
})
})
}
// =============================================================================
// Unified Before Execution Handler
// =============================================================================
// ExecutionType identifies what kind of execution is being attempted.
type ExecutionType string
const (
ExecutionShell ExecutionType = "shell"
ExecutionMCP ExecutionType = "mcp"
ExecutionTool ExecutionType = "tool" // Claude Code non-MCP tools (Read, Write, etc.)
)
// ExecutionContext provides a unified view of pre-execution events.
type ExecutionContext struct {
Platform Platform
Type ExecutionType
// For shell execution (Cursor beforeShellExecution, Claude Code Bash tool)
// Also used for local MCP servers on Cursor (command-based MCP servers)
// NOTE: Only populated for Cursor and Cascade, not Claude Code or Droid
Command string
Cwd string // Working directory
// For MCP execution
ToolName string // MCP tool name (e.g., "mcp__server__tool")
ToolInput json.RawMessage // Tool input parameters as JSON
ServerURL string // MCP server URL (Cursor/Cascade only, for URL-based servers)
// Raw input for advanced use cases
RawClaudeCode *claude.PreToolUseInput
RawCursor any // *cursor.BeforeShellExecutionInput or *cursor.BeforeMCPExecutionInput
RawDroid *droid.PreToolUseInput
RawCascade any // *cascade.PreRunCommandInput or *cascade.PreMCPToolUseInput
}
// IsMCP returns true if this is an MCP tool execution.
func (c ExecutionContext) IsMCP() bool {
return c.Type == ExecutionMCP
}
// ExecutionDecision represents the unified decision for execution hooks.
type ExecutionDecision struct {
// Allow determines whether execution should proceed.
Allow bool
// Reason explains the decision.
// For Allow=true, shown to user (if not empty).
// For Allow=false, shown to agent.
Reason string
// Ask prompts the user to confirm (only if Allow is false and Ask is true).
Ask bool
}
// AllowExecution returns a decision that permits execution.
func AllowExecution() ExecutionDecision {
return ExecutionDecision{Allow: true}
}
// AllowExecutionWithReason permits execution with a reason shown to the user.
func AllowExecutionWithReason(reason string) ExecutionDecision {
return ExecutionDecision{Allow: true, Reason: reason}
}
// DenyExecution blocks execution with a reason shown to the agent.
func DenyExecution(reason string) ExecutionDecision {
return ExecutionDecision{Allow: false, Reason: reason}
}
// AskExecution prompts the user to confirm execution.
func AskExecution(reason string) ExecutionDecision {
return ExecutionDecision{Allow: false, Ask: true, Reason: reason}
}
// ExecutionHandler is the function signature for unified execution handlers.
type ExecutionHandler func(ExecutionContext) ExecutionDecision
// OnBeforeExecution registers a unified handler for pre-execution events.
// It automatically registers handlers for:
// - "claude-pre-tool-use" (filters to Bash and mcp__* tools)
// - "cursor-before-shell"
// - "cursor-before-mcp"
// - "droid-pre-tool-use" (filters to Bash and mcp__* tools)
// - "cascade-pre-run-command"
// - "cascade-pre-mcp-tool-use"
// - "codex-pre-tool-use" (filters to Bash, apply_patch, and mcp__* tools)
func OnBeforeExecution(handler ExecutionHandler) {
// Claude Code PreToolUse (for Bash and MCP tools)
Register("claude-pre-tool-use", func() {
Run(func(input claude.PreToolUseInput) claude.PreToolUseOutput {
// Determine execution type
var execType ExecutionType
if input.ToolName == "Bash" {
execType = ExecutionShell
} else if len(input.ToolName) > 5 && input.ToolName[:5] == "mcp__" {
execType = ExecutionMCP
} else {
execType = ExecutionTool
}
// Extract command for Bash tool
var command string
if execType == ExecutionShell {
var bashInput struct {
Command string `json:"command"`
}
json.Unmarshal(input.ToolInput, &bashInput)
command = bashInput.Command
}
ctx := ExecutionContext{
Platform: PlatformClaude,
Type: execType,
Command: command,
Cwd: input.Cwd,
ToolName: input.ToolName,
ToolInput: input.ToolInput,
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Allow {
if decision.Reason != "" {
return claude.Allow(decision.Reason)
}
return claude.AllowSilent()
}
if decision.Ask {
return claude.Ask(decision.Reason)
}
return claude.Deny(decision.Reason)
})
})
// Cursor beforeShellExecution
Register("cursor-before-shell", func() {
Run(func(input cursor.BeforeShellExecutionInput) cursor.BeforeExecutionOutput {
cwd := input.Cwd
if cwd == "" {
cwd = cursorWorkspaceRoot(input.WorkspaceRoots)
}
ctx := ExecutionContext{
Platform: PlatformCursor,
Type: ExecutionShell,
Command: input.Command,
Cwd: cwd,
RawCursor: &input,
}
decision := handler(ctx)
if decision.Allow {
if decision.Reason != "" {
return cursor.AllowWithMessage(decision.Reason)
}
return cursor.Allow()
}
if decision.Ask {
return cursor.Ask(decision.Reason)
}
return cursor.Deny(decision.Reason, decision.Reason)
})
})
// Cursor beforeMCPExecution
Register("cursor-before-mcp", func() {
Run(func(input cursor.BeforeMCPExecutionInput) cursor.BeforeExecutionOutput {
ctx := ExecutionContext{
Platform: PlatformCursor,
Type: ExecutionMCP,
ToolName: input.ToolName,
ToolInput: json.RawMessage(input.ToolInput),
ServerURL: input.URL,
Command: input.Command, // For local MCP servers (command-based)
Cwd: cursorWorkspaceRoot(input.WorkspaceRoots),
RawCursor: &input,
}
decision := handler(ctx)
if decision.Allow {
if decision.Reason != "" {
return cursor.AllowWithMessage(decision.Reason)
}
return cursor.Allow()
}
if decision.Ask {
return cursor.Ask(decision.Reason)
}
return cursor.Deny(decision.Reason, decision.Reason)
})
})
// Droid PreToolUse (for Bash and MCP tools)
// Uses RunE so that blocking decisions exit with code 2, which is how
// Factory Droid detects that a hook has denied an action.
Register("droid-pre-tool-use", func() {
RunE(func(input droid.PreToolUseInput) (droid.PreToolUseOutput, error) {
// Determine execution type
// Droid MCP tools use serverName___toolName format (e.g. corridor___listProjects)
// unlike Claude's mcp__server__tool format
var execType ExecutionType
if input.ToolName == "Bash" {
execType = ExecutionShell
} else if len(input.ToolName) > 5 && input.ToolName[:5] == "mcp__" {
execType = ExecutionMCP
} else if strings.Contains(input.ToolName, "___") {
execType = ExecutionMCP
} else {
execType = ExecutionTool
}
// Extract command for Bash tool
var command string
if execType == ExecutionShell {
var bashInput struct {
Command string `json:"command"`
}
json.Unmarshal(input.ToolInput, &bashInput)
command = bashInput.Command
}
ctx := ExecutionContext{
Platform: PlatformDroid,
Type: execType,
Command: command,
Cwd: input.Cwd,
ToolName: input.ToolName,
ToolInput: input.ToolInput,
RawDroid: &input,
}
decision := handler(ctx)
if decision.Allow {
if decision.Reason != "" {
return droid.Allow(decision.Reason), nil
}
return droid.AllowSilent(), nil
}
// Exit code 2 + stderr message for blocking (per Factory docs)
return droid.PreToolUseOutput{}, errors.New(decision.Reason)
})
})
// Cascade preRunCommand
// Uses RunE so that blocking decisions exit with code 2, which is how
// Windsurf Cascade detects that a hook has denied an action.
Register("cascade-pre-run-command", func() {
RunE(func(input cascade.PreRunCommandInput) (cascade.PreRunCommandOutput, error) {
ctx := ExecutionContext{
Platform: PlatformCascade,
Type: ExecutionShell,
Command: input.ToolInfo.CommandLine,
Cwd: input.ToolInfo.Cwd,
RawCascade: &input,
}
decision := handler(ctx)
if decision.Allow {
return cascade.AllowCommand(), nil
}
return cascade.PreRunCommandOutput{}, errors.New(decision.Reason)
})
})
// Cascade preMCPToolUse
// Uses RunE so that blocking decisions exit with code 2, which is how
// Windsurf Cascade detects that a hook has denied an action.
Register("cascade-pre-mcp-tool-use", func() {
RunE(func(input cascade.PreMCPToolUseInput) (cascade.PreMCPToolUseOutput, error) {
ctx := ExecutionContext{
Platform: PlatformCascade,
Type: ExecutionMCP,
ToolName: input.ToolInfo.MCPToolName,
ToolInput: input.ToolInfo.MCPToolArguments,
ServerURL: input.ToolInfo.MCPServerName,
RawCascade: &input,
}
decision := handler(ctx)
if decision.Allow {
return cascade.AllowMCP(), nil
}
return cascade.PreMCPToolUseOutput{}, errors.New(decision.Reason)
})
})
// Codex PreToolUse (same JSON wire protocol as Claude Code, stricter
// validation). Codex tool names include "Bash", "apply_patch", and MCP
// names like "mcp__server__tool". apply_patch is classified as
// ExecutionTool because it represents a file edit rather than a shell
// command or MCP call. For apply_patch the underlying tool_input.command
// is parsed and exposed via ExecutionContext.Command so policies can
// inspect the patch text. Uses codex.* helpers so Codex quirks (no
// suppressOutput, no updatedInput) live in the codex package.
Register("codex-pre-tool-use", func() {
Run(func(input codex.PreToolUseInput) codex.PreToolUseOutput {
var execType ExecutionType
if input.ToolName == "Bash" {
execType = ExecutionShell
} else if len(input.ToolName) > 5 && input.ToolName[:5] == "mcp__" {
execType = ExecutionMCP
} else {
execType = ExecutionTool
}
var command string
if execType == ExecutionShell || input.ToolName == "apply_patch" {
var cmdInput struct {
Command string `json:"command"`
}
json.Unmarshal(input.ToolInput, &cmdInput)
command = cmdInput.Command
}
ctx := ExecutionContext{
Platform: PlatformCodex,
Type: execType,
Command: command,
Cwd: input.Cwd,
ToolName: input.ToolName,
ToolInput: input.ToolInput,
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Allow {
if decision.Reason != "" {
return codex.Allow(decision.Reason)
}
// codex.AllowSilent is a Codex-safe no-op (emits {}) — it
// does NOT set suppressOutput like claude.AllowSilent,
// because Codex rejects that field with "PreToolUse hook
// returned unsupported suppressOutput".
return codex.AllowSilent()
}
// Codex currently parses but does not enforce permissionDecision
// "ask" for PreToolUse, so an Ask decision would silently fail
// open. Until Codex enforces it, fail closed by denying — this
// matches the security posture of the other platforms where
// Ask actually surfaces an approval prompt.
if decision.Ask {
return codex.Deny(decision.Reason)
}
return codex.Deny(decision.Reason)
})
})
}
// =============================================================================
// Unified After File Edit Handler
// =============================================================================
// FileEdit represents a single edit operation.
type FileEdit struct {
OldString string
NewString string
}
// FileEditContext provides a unified view of file edit events.
type FileEditContext struct {
Platform Platform
SessionID string // Claude Code: session_id, Cursor: conversation_id, Cascade: trajectory_id
FilePath string
// NewFilePath is the destination path when the edit also renames the
// file (Codex apply_patch "*** Move to:" today; future platforms may
// surface their own rename semantics). It is empty for in-place edits.
//
// For Codex moves, the unified bridge invokes OnAfterFileEdit twice —
// once with FilePath set to the source and once with FilePath set to
// the destination — and populates NewFilePath on both invocations so
// path-based policies can never be bypassed by inspecting only
// FilePath. Handlers that want to detect a rename should check
// `ctx.NewFilePath != "" && ctx.NewFilePath != ctx.FilePath`.
NewFilePath string
Edits []FileEdit
Cwd string
// Raw input for advanced use cases
RawClaudeCode *claude.PostToolUseInput
RawCursor *cursor.AfterFileEditInput
RawDroid *droid.PostToolUseInput
RawCascade *cascade.PostWriteCodeInput
}
// FileEditDecision represents the unified decision for file edit hooks.
type FileEditDecision struct {
// Block sends feedback to the agent (Claude Code only).
Block bool
// Reason is shown to the agent when Block is true.
Reason string
// Context is additional context added for the agent (Claude Code only).
Context string
}
// FileEditOK returns a decision that allows normal flow.
func FileEditOK() FileEditDecision {
return FileEditDecision{}
}
// FileEditBlock sends feedback to the agent about the edit.
func FileEditBlock(reason string) FileEditDecision {
return FileEditDecision{Block: true, Reason: reason}
}
// FileEditAddContext adds context for the agent to consider.
func FileEditAddContext(context string) FileEditDecision {
return FileEditDecision{Context: context}
}
// FileEditHandler is the function signature for unified file edit handlers.
type FileEditHandler func(FileEditContext) FileEditDecision
// OnAfterFileEdit registers a unified handler for post-file-edit events.
// It automatically registers handlers for:
// - "claude-after-file-edit" (PostToolUse for Write/Edit)
// - "cursor-after-file-edit"
// - "droid-after-file-edit" (PostToolUse for Write/Edit)
// - "cascade-post-write-code"
// - "codex-post-tool-use" (PostToolUse for Write/Edit/apply_patch)
func OnAfterFileEdit(handler FileEditHandler) {
// Claude Code PostToolUse (for Write/Edit)
Register("claude-after-file-edit", func() {
Run(func(input claude.PostToolUseInput) claude.PostToolUseOutput {
// Only handle Write and Edit tools
if input.ToolName != "Write" && input.ToolName != "Edit" {
return claude.PostToolOK()
}
// Extract file path and edits from tool input
var toolInput struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
}
json.Unmarshal(input.ToolInput, &toolInput)
var edits []FileEdit
if input.ToolName == "Edit" {
edits = []FileEdit{{OldString: toolInput.OldString, NewString: toolInput.NewString}}
} else {
edits = []FileEdit{{OldString: "", NewString: toolInput.Content}}
}
ctx := FileEditContext{
Platform: PlatformClaude,
SessionID: input.SessionID,
FilePath: toolInput.FilePath,
Edits: edits,
Cwd: input.Cwd,
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Block {
return claude.PostToolBlock(decision.Reason)
}
if decision.Context != "" {
return claude.PostToolContext(decision.Context)
}
return claude.PostToolOK()
})
})
// Cursor afterFileEdit
Register("cursor-after-file-edit", func() {
Run(func(input cursor.AfterFileEditInput) cursor.AfterFileEditOutput {
var edits []FileEdit
for _, e := range input.Edits {
edits = append(edits, FileEdit{OldString: e.OldString, NewString: e.NewString})
}
ctx := FileEditContext{
Platform: PlatformCursor,
SessionID: input.ConversationID,
FilePath: input.FilePath,
Edits: edits,
Cwd: cursorWorkspaceRoot(input.WorkspaceRoots),
RawCursor: &input,
}
// Cursor afterFileEdit has no decision control, but we still call the handler
// for side effects (logging, telemetry, etc.)
handler(ctx)
return cursor.AfterFileEditOK()
})
})
// Droid PostToolUse (for Write/Edit)
Register("droid-after-file-edit", func() {
Run(func(input droid.PostToolUseInput) droid.PostToolUseOutput {
// Only handle Write and Edit tools
if input.ToolName != "Write" && input.ToolName != "Edit" {
return droid.PostToolOK()
}
// Extract file path and edits from tool input
// Factory Droid uses "old_str"/"new_str" (not "old_string"/"new_string" like Claude Code)
var toolInput struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
OldStr string `json:"old_str"`
NewStr string `json:"new_str"`
}
json.Unmarshal(input.ToolInput, &toolInput)
var edits []FileEdit
if input.ToolName == "Edit" {
edits = []FileEdit{{OldString: toolInput.OldStr, NewString: toolInput.NewStr}}
} else {
edits = []FileEdit{{OldString: "", NewString: toolInput.Content}}
}
ctx := FileEditContext{
Platform: PlatformDroid,
SessionID: input.SessionID,
FilePath: toolInput.FilePath,
Edits: edits,
Cwd: input.Cwd,
RawDroid: &input,
}
decision := handler(ctx)
if decision.Block {
return droid.PostToolBlock(decision.Reason)
}
if decision.Context != "" {
return droid.PostToolContext(decision.Context)
}
return droid.PostToolOK()
})
})
// Cascade postWriteCode
Register("cascade-post-write-code", func() {
Run(func(input cascade.PostWriteCodeInput) cascade.PostWriteCodeOutput {
var edits []FileEdit
for _, e := range input.ToolInfo.Edits {
edits = append(edits, FileEdit{OldString: e.OldString, NewString: e.NewString})
}
ctx := FileEditContext{
Platform: PlatformCascade,
SessionID: input.TrajectoryID,
FilePath: input.ToolInfo.FilePath,
Edits: edits,
RawCascade: &input,
}
// Cascade post hooks are fire-and-forget, but we still call the handler
// for side effects (logging, telemetry, etc.)
handler(ctx)
return cascade.PostWriteCodeOK()
})
})
// Codex PostToolUse (same JSON protocol as Claude Code).
//
// Codex emits file edits in three shapes:
// 1. Write / Edit — Claude-style tool_input with file_path + content
// or old_string/new_string. Native first-class tools.
// 2. apply_patch — tool_input.command holds a unified-diff envelope
// that may touch multiple files in a single call.
// 3. Bash — tool_input.command holds one of two shapes:
// a. Edits: `apply_patch <<'PATCH' … PATCH`
// (sometimes with an absolute path
// to a per-session apply_patch shim)
// b. Writes: `cat <<'EOF' > FILE … EOF` or
// `tee FILE <<'EOF' … EOF`
// Codex routes virtually all file operations this
// way: edits via (a), greenfield writes via (b).
// Without handling BOTH cases the
// SecurityScanResults dashboard stayed empty for
// every Codex session — no afterFileEdit
// telemetry was ever emitted for "Create a file"
// prompts or for in-place edits.
//
// For (2) and (3a) we run the patch through codex.ParseApplyPatch and
// invoke the user's handler exactly once per file in the envelope. For
// (3b) codex.ParseBashRedirectWrite synthesizes a single PatchFile so
// the same dispatchPatch reducer drives every shape. Per-file
// decisions reduce as: a Block from any file wins, otherwise context
// strings are concatenated. The parsers are also exported as
// codex.ParseApplyPatch / codex.ParseApplyPatchFromBash /
// codex.ParseBashRedirectWrite for callers that want raw access.
//
// Configure the hook with matcher "Bash|apply_patch|mcp__.*" in
// hooks.json — "Edit" and "Write" matcher aliases exist but are
// redundant with "apply_patch", and "Bash" is required to catch the
// heredoc shape.
Register("codex-post-tool-use", func() {
Run(func(input codex.PostToolUseInput) codex.PostToolUseOutput {
// dispatchPatch invokes handler once per file in the patch
// envelope, then reduces per-file decisions to one
// PostToolUseOutput. fallbackCommand is used as the
// NewString of a single synthetic FileEdit when the patch
// could not be parsed (len(files)==0), so policies still
// see a Codex PostToolUse event rather than nothing.
dispatchPatch := func(files []codex.PatchFile, fallbackCommand string) codex.PostToolUseOutput {
if len(files) == 0 {
ctx := FileEditContext{
Platform: PlatformCodex,
SessionID: input.SessionID,
Cwd: input.Cwd,
Edits: []FileEdit{{OldString: "", NewString: fallbackCommand}},
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Block {
return codex.PostToolBlock(decision.Reason)
}
if decision.Context != "" {
return codex.PostToolContext(decision.Context)
}
return codex.PostToolOK()
}
var (
blockReasons []string
contexts []string
)
invoke := func(filePath string, f codex.PatchFile) {
edits := make([]FileEdit, 0, len(f.Edits))
for _, e := range f.Edits {
edits = append(edits, FileEdit{OldString: e.OldString, NewString: e.NewString})
}
ctx := FileEditContext{
Platform: PlatformCodex,
SessionID: input.SessionID,
FilePath: filePath,
NewFilePath: f.NewFilePath,
Edits: edits,
Cwd: input.Cwd,
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Block {
blockReasons = append(blockReasons, decision.Reason)
} else if decision.Context != "" {
contexts = append(contexts, decision.Context)
}
}
for _, f := range files {
// Always invoke for the declared source path.
invoke(f.FilePath, f)
// For renames, invoke again with the destination so
// policies that only inspect ctx.FilePath cannot be
// bypassed by a "*** Move to:" pointing at a
// sensitive path (e.g. "../../.ssh/authorized_keys").
// NewFilePath is populated on both invocations so
// policies that want to detect the rename
// relationship can.
if f.NewFilePath != "" && f.NewFilePath != f.FilePath {
invoke(f.NewFilePath, f)
}
}
if len(blockReasons) > 0 {
return codex.PostToolBlock(strings.Join(blockReasons, "\n"))
}
if len(contexts) > 0 {
return codex.PostToolContext(strings.Join(contexts, "\n"))
}
return codex.PostToolOK()
}
switch input.ToolName {
case "Write", "Edit":
var toolInput struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
}
json.Unmarshal(input.ToolInput, &toolInput)
var edits []FileEdit
if input.ToolName == "Edit" {
edits = []FileEdit{{OldString: toolInput.OldString, NewString: toolInput.NewString}}
} else {
edits = []FileEdit{{OldString: "", NewString: toolInput.Content}}
}
ctx := FileEditContext{
Platform: PlatformCodex,
SessionID: input.SessionID,
FilePath: toolInput.FilePath,
Edits: edits,
Cwd: input.Cwd,
RawClaudeCode: &input,
}
decision := handler(ctx)
if decision.Block {
return codex.PostToolBlock(decision.Reason)
}
if decision.Context != "" {
return codex.PostToolContext(decision.Context)
}
return codex.PostToolOK()
case "apply_patch":
var applyInput struct {
Command string `json:"command"`
}
json.Unmarshal(input.ToolInput, &applyInput)
return dispatchPatch(codex.ParseApplyPatch(applyInput.Command), applyInput.Command)
case "Bash":
// Codex routes file operations through Bash in two
// distinct shapes that look superficially similar but
// require different parsers:
//
// 1. Edits to existing files:
// apply_patch <<'PATCH' … *** End Patch … PATCH
// parsed by codex.ParseApplyPatchFromBash.
//
// 2. Greenfield writes (and overwrite-style writes):
// cat <<'EOF' > newfile.txt … EOF
// tee newfile.txt <<'EOF' … EOF
// parsed by codex.ParseBashRedirectWrite.
//
// Both produce []PatchFile suitable for the shared
// dispatchPatch reducer. We try apply_patch first
// because it's the higher-fidelity shape (per-hunk
// old/new) when both detectors would match, then fall
// back to the heredoc-write detector. Non-edit Bash
// commands short-circuit at the second `if !ok` check
// without paying for either full parse pass.
var bashInput struct {
Command string `json:"command"`
}
json.Unmarshal(input.ToolInput, &bashInput)
if files, ok := codex.ParseApplyPatchFromBash(bashInput.Command); ok {
return dispatchPatch(files, bashInput.Command)
}
if files, ok := codex.ParseBashRedirectWrite(bashInput.Command); ok {
return dispatchPatch(files, bashInput.Command)
}
return codex.PostToolOK()
default:
return codex.PostToolOK()
}
})
})
}
// =============================================================================
// Unified Prompt Submit Handler
// =============================================================================
// PromptContext provides a unified view of prompt submission events.
type PromptContext struct {
Platform Platform
SessionID string // Claude Code: session_id, Cursor: conversation_id, Cascade: trajectory_id
Prompt string
Cwd string // Working directory (Cursor: from workspace_roots[0])
// Raw input for advanced use cases
RawClaudeCode *claude.UserPromptSubmitInput
RawCursor *cursor.BeforeSubmitPromptInput
RawDroid *droid.UserPromptSubmitInput
RawCascade *cascade.PreUserPromptInput
}
// PromptDecision represents the unified decision for prompt hooks.
type PromptDecision struct {
// Allow determines whether the prompt should be processed.
Allow bool
// Reason is shown to the user when Allow is false.
Reason string
// Context is additional context added for the agent (Claude Code only).
Context string
}
// AllowPromptDecision returns a decision that allows the prompt.
func AllowPromptDecision() PromptDecision {
return PromptDecision{Allow: true}
}
// BlockPromptDecision blocks the prompt with a reason.
func BlockPromptDecision(reason string) PromptDecision {
return PromptDecision{Allow: false, Reason: reason}
}
// AddPromptContext allows the prompt and adds context.
func AddPromptContext(context string) PromptDecision {
return PromptDecision{Allow: true, Context: context}
}
// PromptHandler is the function signature for unified prompt handlers.
type PromptHandler func(PromptContext) PromptDecision
// OnPromptSubmit registers a unified handler for prompt submission events.
// It automatically registers handlers for:
// - "claude-user-prompt-submit"
// - "cursor-before-submit-prompt"
// - "droid-user-prompt-submit"
// - "cascade-pre-user-prompt"
// - "codex-user-prompt-submit"
func OnPromptSubmit(handler PromptHandler) {
// Claude Code UserPromptSubmit
Register("claude-user-prompt-submit", func() {
Run(func(input claude.UserPromptSubmitInput) claude.UserPromptSubmitOutput {
ctx := PromptContext{
Platform: PlatformClaude,
SessionID: input.SessionID,
Prompt: input.Prompt,
Cwd: input.Cwd,
RawClaudeCode: &input,
}
decision := handler(ctx)
if !decision.Allow {
return claude.BlockPrompt(decision.Reason)
}
if decision.Context != "" {
return claude.AddContext(decision.Context)
}
return claude.AllowPrompt()
})
})
// Cursor beforeSubmitPrompt