|
| 1 | +import type { PluginInput } from "@opencode-ai/plugin" |
| 2 | +import { |
| 3 | + HOOK_NAME, |
| 4 | + INTERACTIVE_FLAG_PATTERNS, |
| 5 | + STDIN_REQUIRING_COMMANDS, |
| 6 | + TMUX_SUGGESTION, |
| 7 | +} from "./constants" |
| 8 | +import type { BlockResult } from "./types" |
| 9 | +import { log } from "../../shared" |
| 10 | + |
| 11 | +export * from "./constants" |
| 12 | +export * from "./types" |
| 13 | + |
| 14 | +function checkInteractiveCommand(command: string): BlockResult { |
| 15 | + const normalizedCmd = command.trim() |
| 16 | + |
| 17 | + for (const pattern of INTERACTIVE_FLAG_PATTERNS) { |
| 18 | + if (pattern.test(normalizedCmd)) { |
| 19 | + return { |
| 20 | + blocked: true, |
| 21 | + reason: `Command contains interactive pattern`, |
| 22 | + command: normalizedCmd, |
| 23 | + matchedPattern: pattern.source, |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + for (const cmd of STDIN_REQUIRING_COMMANDS) { |
| 29 | + if (normalizedCmd.includes(cmd)) { |
| 30 | + return { |
| 31 | + blocked: true, |
| 32 | + reason: `Command requires stdin interaction: ${cmd}`, |
| 33 | + command: normalizedCmd, |
| 34 | + matchedPattern: cmd, |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return { blocked: false } |
| 40 | +} |
| 41 | + |
| 42 | +export function createInteractiveBashBlockerHook(ctx: PluginInput) { |
| 43 | + return { |
| 44 | + "tool.execute.before": async ( |
| 45 | + input: { tool: string; sessionID: string; callID: string }, |
| 46 | + output: { args: Record<string, unknown> } |
| 47 | + ): Promise<void> => { |
| 48 | + const toolLower = input.tool.toLowerCase() |
| 49 | + |
| 50 | + if (toolLower !== "bash") { |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + const command = output.args.command as string | undefined |
| 55 | + if (!command) { |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + const result = checkInteractiveCommand(command) |
| 60 | + |
| 61 | + if (result.blocked) { |
| 62 | + log(`[${HOOK_NAME}] Blocking interactive command`, { |
| 63 | + sessionID: input.sessionID, |
| 64 | + command: result.command, |
| 65 | + pattern: result.matchedPattern, |
| 66 | + }) |
| 67 | + |
| 68 | + ctx.client.tui |
| 69 | + .showToast({ |
| 70 | + body: { |
| 71 | + title: "Interactive Command Blocked", |
| 72 | + message: `${result.reason}\nUse tmux or interactive-terminal skill instead.`, |
| 73 | + variant: "error", |
| 74 | + duration: 5000, |
| 75 | + }, |
| 76 | + }) |
| 77 | + .catch(() => {}) |
| 78 | + |
| 79 | + throw new Error( |
| 80 | + `[${HOOK_NAME}] ${result.reason}\n` + |
| 81 | + `Command: ${result.command}\n` + |
| 82 | + `Pattern: ${result.matchedPattern}\n` + |
| 83 | + TMUX_SUGGESTION |
| 84 | + ) |
| 85 | + } |
| 86 | + }, |
| 87 | + } |
| 88 | +} |
0 commit comments