@nicerice/openhooks 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright © 2026 nice rice
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @nicerice/openhooks
2
+
3
+ YAML based native hooks for OpenCode. Runs bash commands on tool and session lifecycle events. Reports failures via the native OpenCode plugin API (throws) instead of injected messages, so the model sees tool errors naturally without assuming them as another prompt.
4
+
5
+ ## Install
6
+
7
+ Add to `opencode.json`:
8
+
9
+ ```json
10
+ {
11
+ "plugin": ["@nicerice/openhooks"]
12
+ }
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ Create `~/.config/opencode/hooks.yaml` (global) or `.opencode/hooks.yaml` (project):
18
+
19
+ ```yaml
20
+ hooks:
21
+ - event: tool.execute.after
22
+ tools: [write, edit, patch, apply_patch]
23
+ actions:
24
+ - bash: "mx ci"
25
+ - event: tool.execute.before
26
+ tools: [bash]
27
+ actions:
28
+ - bash: "validate-command.sh"
29
+ - event: session.idle
30
+ actions:
31
+ - bash: "notify.sh"
32
+ - event: session.created
33
+ actions:
34
+ - bash: "echo started"
35
+ ```
36
+
37
+ Global and project configs merge by hook id (project overrides global).
38
+
39
+ ## Events
40
+
41
+ | Event | When | Failure behavior |
42
+ |---|---|---|
43
+ | `tool.execute.before` | Before a tool runs | Throws, blocks the tool |
44
+ | `tool.execute.after` | After a tool completes | Throws, model sees tool error |
45
+ | `session.created` | Session created | Logs, doesn't throw |
46
+ | `session.deleted` | Session deleted | Logs, doesn't throw |
47
+ | `session.idle` | Session idle | Logs, doesn't throw |
48
+ | `session.error` | Session error | Logs, doesn't throw |
49
+
50
+ ## Config
51
+
52
+ | Field | Required | Description |
53
+ |-------|----------|-------------|
54
+ | `id` | no | Unique identifier for override merging |
55
+ | `event` | yes | Event type from the table above |
56
+ | `tools` | no | Array of tool names (e.g. `[write, edit]`). Only for tool events. Omit to match all. |
57
+ | `actions` | yes | Array of `{ bash: "cmd" }` entries. Run sequentially, stops on first failure. |
package/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { loadConfig } from "./src/infrastructure/config.ts"
2
+ import { registerHooks } from "./src/application/hooks.ts"
3
+
4
+ export const OpenhooksPlugin = async (ctx: { worktree?: string; directory?: string; project?: { root?: string } }) => {
5
+ const root = ctx.worktree || ctx.directory || ctx.project?.root || process.cwd()
6
+ const config = loadConfig(root)
7
+ return registerHooks(config)
8
+ }
9
+
10
+ export default OpenhooksPlugin
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@nicerice/openhooks",
3
+ "description": "[opencode plugin] Hook any command into opencode's tool events.",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "main": "./index.ts",
7
+ "exports": {
8
+ ".": {
9
+ "bun": "./index.ts",
10
+ "default": "./index.ts"
11
+ }
12
+ },
13
+ "files": [
14
+ "index.ts",
15
+ "src",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "test": "bun test"
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "latest"
23
+ },
24
+ "dependencies": {}
25
+ }
@@ -0,0 +1,81 @@
1
+ import type { HooksConfig, HookEntry, SessionHookEntry, ExecResult } from "../domain/types.ts"
2
+ import { exec } from "../infrastructure/executor.ts"
3
+
4
+ type ToolInput = {
5
+ tool: string
6
+ sessionID: string
7
+ callID: string
8
+ args?: Record<string, unknown>
9
+ }
10
+
11
+ type ToolOutput = {
12
+ title?: string
13
+ output?: string
14
+ metadata?: Record<string, unknown>
15
+ }
16
+
17
+ type EventInput = {
18
+ event: { type: string; properties?: Record<string, unknown> }
19
+ }
20
+
21
+ const runActions = (actions: { bash: string }[], label: string): void => {
22
+ for (const action of actions) {
23
+ const result: ExecResult = exec(action.bash)
24
+ if (result.exitCode === 0) continue
25
+ throw new Error(`openhooks: ${label} failed (exit ${result.exitCode})\n${result.stderr || result.stdout}`)
26
+ }
27
+ }
28
+
29
+ export const registerHooks = (config: HooksConfig) => {
30
+ const toolHooks: Record<string, (HookEntry & { tools?: string[] })[]> = {}
31
+ const sessionHooks: SessionHookEntry[] = []
32
+
33
+ for (const entry of config.hooks) {
34
+ if ("tools" in entry) {
35
+ if (!toolHooks[entry.event]) toolHooks[entry.event] = []
36
+ toolHooks[entry.event]!.push(entry as HookEntry & { tools?: string[] })
37
+ } else if (entry.event.startsWith("session.")) {
38
+ sessionHooks.push(entry as SessionHookEntry)
39
+ }
40
+ }
41
+
42
+ const hooks: Record<string, (input: ToolInput | EventInput, output?: ToolOutput) => Promise<void>> = {}
43
+
44
+ for (const [event, entries] of Object.entries(toolHooks)) {
45
+ if (event === "tool.execute.before" || event === "tool.execute.after") {
46
+ hooks[event] = async (input: ToolInput, output?: ToolOutput) => {
47
+ const toolInput = input as ToolInput
48
+
49
+ for (const entry of entries) {
50
+ if (entry.tools && !entry.tools.includes(toolInput.tool)) continue
51
+
52
+ if (output) {
53
+ output.title = entry.id || event
54
+ }
55
+
56
+ runActions(entry.actions, entry.id || event)
57
+ }
58
+ }
59
+ }
60
+ }
61
+
62
+ if (sessionHooks.length > 0) {
63
+ hooks.event = async (input: EventInput) => {
64
+ const type = input.event.type
65
+
66
+ for (const entry of sessionHooks) {
67
+ const sessionEvent = entry.event.replace("session.", "")
68
+ if (type !== sessionEvent && type !== entry.event) continue
69
+
70
+ try {
71
+ runActions(entry.actions, entry.id || entry.event)
72
+ } catch (e) {
73
+ // ponytail: don't throw for session events, just log
74
+ console.error(`openhooks: session hook failed: ${e}`)
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ return hooks
81
+ }
@@ -0,0 +1,37 @@
1
+ export type EventType =
2
+ | "tool.execute.before"
3
+ | "tool.execute.after"
4
+
5
+ export type SessionEventType =
6
+ | "session.created"
7
+ | "session.deleted"
8
+ | "session.idle"
9
+ | "session.error"
10
+
11
+ export type BashAction = {
12
+ bash: string
13
+ timeout?: number
14
+ }
15
+
16
+ export type HookEntry = {
17
+ id?: string
18
+ event: EventType
19
+ tools?: string[]
20
+ actions: BashAction[]
21
+ }
22
+
23
+ export type SessionHookEntry = {
24
+ id?: string
25
+ event: SessionEventType
26
+ actions: BashAction[]
27
+ }
28
+
29
+ export type HooksConfig = {
30
+ hooks: (HookEntry | SessionHookEntry)[]
31
+ }
32
+
33
+ export type ExecResult = {
34
+ exitCode: number
35
+ stdout: string
36
+ stderr: string
37
+ }
@@ -0,0 +1,73 @@
1
+ import { readFileSync, existsSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import type { HooksConfig, HookEntry, SessionHookEntry } from "../domain/types.ts"
5
+
6
+ const parseYaml = (text: string): HooksConfig => {
7
+ const hooks: (HookEntry | SessionHookEntry)[] = []
8
+ let current: Record<string, unknown> | null = null
9
+ const lines = text.split("\n")
10
+
11
+ for (const raw of lines) {
12
+ const line = raw.trimEnd()
13
+ if (line.trim() === "" || line.trimStart().startsWith("#")) continue
14
+
15
+ const listStart = line.match(/^ - (\w+):\s*(.*)/)
16
+ if (listStart) {
17
+ if (current) hooks.push(current as HookEntry | SessionHookEntry)
18
+ current = { [listStart[1]!]: listStart[2]!.trim() } as Record<string, unknown>
19
+ continue
20
+ }
21
+
22
+ if (!current) continue
23
+
24
+ const propMatch = line.match(/^\s+(\w+):\s*(.*)/)
25
+ const bashMatch = line.match(/^\s+- bash:\s*(.*)/)
26
+
27
+ if (!propMatch && !bashMatch) continue
28
+
29
+ if (bashMatch) {
30
+ if (!current.actions || !Array.isArray(current.actions)) current.actions = []
31
+ ;(current.actions as { bash: string }[]).push({ bash: bashMatch[1]!.trim().replace(/^["']|["']$/g, "") })
32
+ continue
33
+ }
34
+
35
+ const key = propMatch![1]!
36
+ const val = propMatch![2]!.trim()
37
+
38
+ if (key === "tools" && val.startsWith("[")) {
39
+ current.tools = val.slice(1, -1).split(",").map((s) => s.trim().replace(/['"]/g, ""))
40
+ } else if (key === "actions") {
41
+ if (!current.actions) current.actions = []
42
+ } else {
43
+ current[key] = val
44
+ }
45
+ }
46
+
47
+ if (current) hooks.push(current as HookEntry | SessionHookEntry)
48
+
49
+ return { hooks }
50
+ }
51
+
52
+ const GLOBAL_PATH = join(homedir(), ".config", "opencode", "hooks.yaml")
53
+ const PROJECT_PATH = ".opencode/hooks.yaml"
54
+
55
+ export const loadConfig = (worktree: string): HooksConfig => {
56
+ const allHooks: (HookEntry | SessionHookEntry)[] = []
57
+
58
+ if (existsSync(GLOBAL_PATH)) {
59
+ const global = parseYaml(readFileSync(GLOBAL_PATH, "utf-8"))
60
+ allHooks.push(...global.hooks)
61
+ }
62
+
63
+ const projectPath = join(worktree, PROJECT_PATH)
64
+ if (existsSync(projectPath)) {
65
+ const project = parseYaml(readFileSync(projectPath, "utf-8"))
66
+ const ids = new Set(project.hooks.map((h) => h.id).filter(Boolean))
67
+ const filtered = allHooks.filter((h) => !ids.has(h.id))
68
+ allHooks.length = 0
69
+ allHooks.push(...filtered, ...project.hooks)
70
+ }
71
+
72
+ return { hooks: allHooks }
73
+ }
@@ -0,0 +1,17 @@
1
+ import { spawnSync } from "node:child_process"
2
+ import type { ExecResult } from "../domain/types.ts"
3
+
4
+ export const exec = (command: string, timeoutMs = 60_000): ExecResult => {
5
+ const result = spawnSync(command, {
6
+ stdio: ["ignore", "pipe", "pipe"],
7
+ encoding: "utf-8",
8
+ shell: true,
9
+ timeout: timeoutMs,
10
+ })
11
+
12
+ return {
13
+ exitCode: result.status ?? 1,
14
+ stdout: (result.stdout || "").trim(),
15
+ stderr: (result.stderr || "").trim(),
16
+ }
17
+ }