Skip to content

Commit 2491039

Browse files
terisukeclaude
andcommitted
feat(hook): add shell script hook system for tool lifecycle events
Implements Epic #38 (Issues #46 + #47): - Hook schema with 4 event types: PreToolUse, PostToolUse, SessionStart, Notification - Shell script execution engine with exit code semantics: - exit 0: pass (stderr -> context injection) - exit 2: block tool execution (stderr -> LLM feedback) - exit other: warning, continue - Configurable timeout (default 10s) via AbortSignal - Matcher-based tool name filtering (glob support) - Integration in prompt.ts before existing plugin hooks - Config schema addition in opencode.json - 31 tests covering executor, matcher, and schema validation Closes #46, closes #47 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 085967b commit 2491039

7 files changed

Lines changed: 463 additions & 0 deletions

File tree

‎packages/opencode/src/config/config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -999,6 +999,17 @@ export namespace Config {
999999
layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
10001000
permission: Permission.optional(),
10011001
tools: z.record(z.string(), z.boolean()).optional(),
1002+
hooks: z
1003+
.object({
1004+
PreToolUse: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1005+
PostToolUse: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1006+
SessionStart: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1007+
Notification: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1008+
})
1009+
.strict()
1010+
.partial()
1011+
.optional()
1012+
.describe("Shell script hooks for lifecycle events"),
10021013
enterprise: z
10031014
.object({
10041015
url: z.string().optional().describe("Enterprise URL"),
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { Log } from "../util/log"
2+
import { Process } from "../util/process"
3+
import type { HookEntry } from "./schema"
4+
5+
const log = Log.create({ service: "hook" })
6+
const DEFAULT_TIMEOUT = 10_000
7+
8+
export interface HookEnv {
9+
OPENCODE_HOOK_EVENT: string
10+
OPENCODE_TOOL_NAME?: string
11+
OPENCODE_TOOL_INPUT?: string
12+
OPENCODE_PROJECT_DIR: string
13+
OPENCODE_SESSION_ID: string
14+
}
15+
16+
export interface HookResult {
17+
action: "pass" | "block"
18+
message?: string
19+
}
20+
21+
export async function runHook(entry: HookEntry, env: HookEnv): Promise<HookResult> {
22+
const timeout = entry.timeout ?? DEFAULT_TIMEOUT
23+
const command = entry.command.replace(/^~/, process.env.HOME ?? "~")
24+
25+
try {
26+
const result = await Process.run(["sh", "-c", command], {
27+
env: toEnvRecord(env),
28+
abort: AbortSignal.timeout(timeout),
29+
nothrow: true,
30+
})
31+
32+
const stderr = result.stderr.toString().trim()
33+
34+
if (result.code === 0) {
35+
return { action: "pass", message: stderr || undefined }
36+
}
37+
if (result.code === 2) {
38+
return { action: "block", message: stderr || "Blocked by hook" }
39+
}
40+
41+
log.warn("hook exited with unexpected code", {
42+
command: entry.command,
43+
code: result.code,
44+
stderr,
45+
})
46+
return { action: "pass" }
47+
} catch (error) {
48+
log.warn("hook execution failed", {
49+
command: entry.command,
50+
error: error instanceof Error ? error.message : String(error),
51+
})
52+
return { action: "pass" }
53+
}
54+
}
55+
56+
function toEnvRecord(env: HookEnv): Record<string, string> {
57+
const record: Record<string, string> = {
58+
OPENCODE_HOOK_EVENT: env.OPENCODE_HOOK_EVENT,
59+
OPENCODE_PROJECT_DIR: env.OPENCODE_PROJECT_DIR,
60+
OPENCODE_SESSION_ID: env.OPENCODE_SESSION_ID,
61+
}
62+
if (env.OPENCODE_TOOL_NAME !== undefined) record.OPENCODE_TOOL_NAME = env.OPENCODE_TOOL_NAME
63+
if (env.OPENCODE_TOOL_INPUT !== undefined) record.OPENCODE_TOOL_INPUT = env.OPENCODE_TOOL_INPUT
64+
return record
65+
}
66+
67+
export function matchesTool(matcher: string | undefined, toolName: string): boolean {
68+
if (!matcher) return true
69+
if (matcher === toolName) return true
70+
if (matcher.endsWith("*")) {
71+
return toolName.startsWith(matcher.slice(0, -1))
72+
}
73+
return false
74+
}
75+
76+
export async function runHooks(
77+
entries: HookEntry[] | undefined,
78+
toolName: string,
79+
env: HookEnv,
80+
): Promise<HookResult> {
81+
if (!entries || entries.length === 0) return { action: "pass" }
82+
83+
const messages: string[] = []
84+
85+
for (const entry of entries) {
86+
if (!matchesTool(entry.matcher, toolName)) continue
87+
88+
const result = await runHook(entry, env)
89+
if (result.message) messages.push(result.message)
90+
if (result.action === "block") {
91+
return { action: "block", message: messages.join("\n") }
92+
}
93+
}
94+
95+
return {
96+
action: "pass",
97+
message: messages.length > 0 ? messages.join("\n") : undefined,
98+
}
99+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export {
2+
type HookEvent,
3+
type HookEntry,
4+
type HookConfig,
5+
HOOK_EVENTS,
6+
HookEntry as HookEntrySchema,
7+
HookConfig as HookConfigSchema,
8+
} from "./schema"
9+
export { runHooks, runHook, matchesTool, type HookResult, type HookEnv } from "./execute"
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import z from "zod"
2+
3+
export const HOOK_EVENTS = ["PreToolUse", "PostToolUse", "SessionStart", "Notification"] as const
4+
export type HookEvent = (typeof HOOK_EVENTS)[number]
5+
6+
export const HookEntry = z.object({
7+
command: z.string().describe("Shell command or path to script"),
8+
matcher: z.string().optional().describe("Tool name glob pattern (PreToolUse/PostToolUse only)"),
9+
timeout: z.number().int().positive().optional().describe("Timeout in ms (default: 10000)"),
10+
})
11+
export type HookEntry = z.infer<typeof HookEntry>
12+
13+
const hookEntryArray = z.array(HookEntry)
14+
15+
export const HookConfig = z
16+
.object({
17+
PreToolUse: hookEntryArray,
18+
PostToolUse: hookEntryArray,
19+
SessionStart: hookEntryArray,
20+
Notification: hookEntryArray,
21+
})
22+
.strict()
23+
.partial()
24+
.optional()
25+
.describe("Shell script hooks for lifecycle events")
26+
export type HookConfig = z.infer<typeof HookConfig>

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ import { Shell } from "@/shell/shell"
4848
import { AppFileSystem } from "@/filesystem"
4949
import { Truncate } from "@/tool/truncate"
5050
import { decodeDataUrl } from "@/util/data-url"
51+
import { runHooks, type HookEnv } from "../hook"
52+
import { Config } from "../config/config"
5153
import { Process } from "@/util/process"
5254
import { Cause, Effect, Exit, Layer, Option, Scope, ServiceMap } from "effect"
5355
import { InstanceState } from "@/effect/instance-state"
@@ -100,6 +102,7 @@ export namespace SessionPrompt {
100102
const filetime = yield* FileTime.Service
101103
const registry = yield* ToolRegistry.Service
102104
const truncate = yield* Truncate.Service
105+
const config = yield* Config.Service
103106
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
104107
const scope = yield* Scope.Scope
105108
const instruction = yield* Instruction.Service
@@ -458,6 +461,27 @@ NOTE: At any point in time through this workflow you should feel free to ask the
458461
return Effect.runPromise(
459462
Effect.gen(function* () {
460463
const ctx = context(args, options)
464+
465+
// Config hooks (shell scripts) — before plugin hooks
466+
const hookCfg = yield* config.get()
467+
const hookEnv: HookEnv = {
468+
OPENCODE_HOOK_EVENT: "PreToolUse",
469+
OPENCODE_TOOL_NAME: item.id,
470+
OPENCODE_TOOL_INPUT: JSON.stringify(args),
471+
OPENCODE_PROJECT_DIR: Instance.directory,
472+
OPENCODE_SESSION_ID: ctx.sessionID,
473+
}
474+
const hookResult = yield* Effect.promise(() =>
475+
runHooks(hookCfg.hooks?.PreToolUse, item.id, hookEnv),
476+
)
477+
if (hookResult.action === "block") {
478+
return {
479+
title: "Blocked by hook",
480+
output: hookResult.message ?? "Tool execution blocked by hook",
481+
metadata: {} as any,
482+
}
483+
}
484+
461485
yield* plugin.trigger(
462486
"tool.execute.before",
463487
{ tool: item.id, sessionID: ctx.sessionID, callID: ctx.callID },
@@ -478,6 +502,15 @@ NOTE: At any point in time through this workflow you should feel free to ask the
478502
{ tool: item.id, sessionID: ctx.sessionID, callID: ctx.callID, args },
479503
output,
480504
)
505+
506+
// PostToolUse hooks
507+
yield* Effect.promise(() =>
508+
runHooks(hookCfg.hooks?.PostToolUse, item.id, {
509+
...hookEnv,
510+
OPENCODE_HOOK_EVENT: "PostToolUse",
511+
}),
512+
)
513+
481514
return output
482515
}),
483516
)
@@ -496,6 +529,30 @@ NOTE: At any point in time through this workflow you should feel free to ask the
496529
Effect.runPromise(
497530
Effect.gen(function* () {
498531
const ctx = context(args, opts)
532+
533+
// Config hooks (shell scripts) — before plugin hooks
534+
const mcpHookCfg = yield* config.get()
535+
const mcpHookEnv: HookEnv = {
536+
OPENCODE_HOOK_EVENT: "PreToolUse",
537+
OPENCODE_TOOL_NAME: key,
538+
OPENCODE_TOOL_INPUT: JSON.stringify(args),
539+
OPENCODE_PROJECT_DIR: Instance.directory,
540+
OPENCODE_SESSION_ID: ctx.sessionID,
541+
}
542+
const mcpHookResult = yield* Effect.promise(() =>
543+
runHooks(mcpHookCfg.hooks?.PreToolUse, key, mcpHookEnv),
544+
)
545+
if (mcpHookResult.action === "block") {
546+
return {
547+
content: [
548+
{
549+
type: "text" as const,
550+
text: mcpHookResult.message ?? "Tool execution blocked by hook",
551+
},
552+
],
553+
}
554+
}
555+
499556
yield* plugin.trigger(
500557
"tool.execute.before",
501558
{ tool: key, sessionID: ctx.sessionID, callID: opts.toolCallId },
@@ -511,6 +568,14 @@ NOTE: At any point in time through this workflow you should feel free to ask the
511568
result,
512569
)
513570

571+
// PostToolUse hooks
572+
yield* Effect.promise(() =>
573+
runHooks(mcpHookCfg.hooks?.PostToolUse, key, {
574+
...mcpHookEnv,
575+
OPENCODE_HOOK_EVENT: "PostToolUse",
576+
}),
577+
)
578+
514579
const textParts: string[] = []
515580
const attachments: Omit<MessageV2.FilePart, "id" | "sessionID" | "messageID">[] = []
516581
for (const contentItem of result.content) {
@@ -1330,6 +1395,16 @@ NOTE: At any point in time through this workflow you should feel free to ask the
13301395
yield* sessions.setPermission({ sessionID: session.id, permission: permissions })
13311396
}
13321397

1398+
// SessionStart hooks
1399+
const startHookCfg = yield* config.get()
1400+
yield* Effect.promise(() =>
1401+
runHooks(startHookCfg.hooks?.SessionStart, "", {
1402+
OPENCODE_HOOK_EVENT: "SessionStart",
1403+
OPENCODE_PROJECT_DIR: Instance.directory,
1404+
OPENCODE_SESSION_ID: input.sessionID,
1405+
}),
1406+
)
1407+
13331408
if (input.noReply === true) return message
13341409
return yield* loop({ sessionID: input.sessionID })
13351410
},
@@ -1744,6 +1819,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
17441819
Layer.provide(Agent.defaultLayer),
17451820
Layer.provide(Bus.layer),
17461821
Layer.provide(CrossSpawnSpawner.defaultLayer),
1822+
Layer.provide(Config.defaultLayer),
17471823
),
17481824
),
17491825
)

0 commit comments

Comments
 (0)