refactor(core): split index.ts and config-handler.ts into focused modules

Main entry point:
- create-hooks.ts, create-tools.ts, create-managers.ts
- plugin-interface.ts: plugin interface types
- plugin/ directory: plugin lifecycle modules

Config handler:
- agent-config-handler.ts, command-config-handler.ts
- tool-config-handler.ts, mcp-config-handler.ts
- provider-config-handler.ts, category-config-resolver.ts
- agent-priority-order.ts, prometheus-agent-config-builder.ts
- plugin-components-loader.ts
This commit is contained in:
YeonGyu-Kim
2026-02-08 16:25:25 +09:00
parent 35ef0a19a6
commit 9a027ddff8
33 changed files with 2305 additions and 1443 deletions
+29
View File
@@ -0,0 +1,29 @@
import type { AvailableCategory } from "../agents/dynamic-agent-prompt-builder"
import type { OhMyOpenCodeConfig } from "../config"
import {
CATEGORY_DESCRIPTIONS,
DEFAULT_CATEGORIES,
} from "../tools/delegate-task/constants"
export function createAvailableCategories(
pluginConfig: OhMyOpenCodeConfig,
): AvailableCategory[] {
const mergedCategories = pluginConfig.categories
? { ...DEFAULT_CATEGORIES, ...pluginConfig.categories }
: DEFAULT_CATEGORIES
return Object.entries(mergedCategories).map(([name, categoryConfig]) => {
const model =
typeof categoryConfig.model === "string" ? categoryConfig.model : undefined
return {
name,
description:
pluginConfig.categories?.[name]?.description ??
CATEGORY_DESCRIPTIONS[name] ??
"General tasks",
model,
}
})
}
+139
View File
@@ -0,0 +1,139 @@
import type { OhMyOpenCodeConfig } from "../config"
import type { PluginContext } from "./types"
import {
applyAgentVariant,
resolveAgentVariant,
resolveVariantForModel,
} from "../shared/agent-variant"
import { hasConnectedProvidersCache } from "../shared"
import {
setSessionAgent,
} from "../features/claude-code-session-state"
import type { CreatedHooks } from "../create-hooks"
type FirstMessageVariantGate = {
shouldOverride: (sessionID: string) => boolean
markApplied: (sessionID: string) => void
}
type ChatMessagePart = { type: string; text?: string; [key: string]: unknown }
type ChatMessageHandlerOutput = { message: Record<string, unknown>; parts: ChatMessagePart[] }
type StartWorkHookOutput = { parts: Array<{ type: string; text?: string }> }
function isStartWorkHookOutput(value: unknown): value is StartWorkHookOutput {
if (typeof value !== "object" || value === null) return false
const record = value as Record<string, unknown>
const partsValue = record["parts"]
if (!Array.isArray(partsValue)) return false
return partsValue.every((part) => {
if (typeof part !== "object" || part === null) return false
const partRecord = part as Record<string, unknown>
return typeof partRecord["type"] === "string"
})
}
export function createChatMessageHandler(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
firstMessageVariantGate: FirstMessageVariantGate
hooks: CreatedHooks
}): (
input: { sessionID: string; agent?: string; model?: { providerID: string; modelID: string } },
output: ChatMessageHandlerOutput
) => Promise<void> {
const { ctx, pluginConfig, firstMessageVariantGate, hooks } = args
return async (
input: { sessionID: string; agent?: string; model?: { providerID: string; modelID: string } },
output: ChatMessageHandlerOutput
): Promise<void> => {
if (input.agent) {
setSessionAgent(input.sessionID, input.agent)
}
const message = output.message
if (firstMessageVariantGate.shouldOverride(input.sessionID)) {
const variant =
input.model && input.agent
? resolveVariantForModel(pluginConfig, input.agent, input.model)
: resolveAgentVariant(pluginConfig, input.agent)
if (variant !== undefined) {
message["variant"] = variant
}
firstMessageVariantGate.markApplied(input.sessionID)
} else {
if (input.model && input.agent && message["variant"] === undefined) {
const variant = resolveVariantForModel(pluginConfig, input.agent, input.model)
if (variant !== undefined) {
message["variant"] = variant
}
} else {
applyAgentVariant(pluginConfig, input.agent, message)
}
}
await hooks.stopContinuationGuard?.["chat.message"]?.(input)
await hooks.keywordDetector?.["chat.message"]?.(input, output)
await hooks.claudeCodeHooks?.["chat.message"]?.(input, output)
await hooks.autoSlashCommand?.["chat.message"]?.(input, output)
if (hooks.startWork && isStartWorkHookOutput(output)) {
await hooks.startWork["chat.message"]?.(input, output)
}
if (!hasConnectedProvidersCache()) {
ctx.client.tui
.showToast({
body: {
title: "⚠️ Provider Cache Missing",
message:
"Model filtering disabled. RESTART OpenCode to enable full functionality.",
variant: "warning" as const,
duration: 6000,
},
})
.catch(() => {})
}
if (hooks.ralphLoop) {
const parts = output.parts
const promptText =
parts
?.filter((p) => p.type === "text" && p.text)
.map((p) => p.text)
.join("\n")
.trim() || ""
const isRalphLoopTemplate =
promptText.includes("You are starting a Ralph Loop") &&
promptText.includes("<user-task>")
const isCancelRalphTemplate = promptText.includes(
"Cancel the currently active Ralph Loop",
)
if (isRalphLoopTemplate) {
const taskMatch = promptText.match(/<user-task>\s*([\s\S]*?)\s*<\/user-task>/i)
const rawTask = taskMatch?.[1]?.trim() || ""
const quotedMatch = rawTask.match(/^["'](.+?)["']/)
const prompt =
quotedMatch?.[1] ||
rawTask.split(/\s+--/)[0]?.trim() ||
"Complete the task as instructed"
const maxIterMatch = rawTask.match(/--max-iterations=(\d+)/i)
const promiseMatch = rawTask.match(
/--completion-promise=["']?([^"'\s]+)["']?/i,
)
hooks.ralphLoop.startLoop(input.sessionID, prompt, {
maxIterations: maxIterMatch ? parseInt(maxIterMatch[1], 10) : undefined,
completionPromise: promiseMatch?.[1],
})
} else if (isCancelRalphTemplate) {
hooks.ralphLoop.cancelLoop(input.sessionID)
}
}
}
}
+71
View File
@@ -0,0 +1,71 @@
type ChatParamsInput = {
sessionID: string
agent: { name?: string }
model: { providerID: string; modelID: string }
provider: { id: string }
message: { variant?: string }
}
type ChatParamsOutput = {
temperature?: number
topP?: number
topK?: number
options: Record<string, unknown>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function buildChatParamsInput(raw: unknown): ChatParamsInput | null {
if (!isRecord(raw)) return null
const sessionID = raw.sessionID
const agent = raw.agent
const model = raw.model
const provider = raw.provider
const message = raw.message
if (typeof sessionID !== "string") return null
if (typeof agent !== "string") return null
if (!isRecord(model)) return null
if (!isRecord(provider)) return null
if (!isRecord(message)) return null
const providerID = model.providerID
const modelID = model.modelID
const providerId = provider.id
const variant = message.variant
if (typeof providerID !== "string") return null
if (typeof modelID !== "string") return null
if (typeof providerId !== "string") return null
return {
sessionID,
agent: { name: agent },
model: { providerID, modelID },
provider: { id: providerId },
message: typeof variant === "string" ? { variant } : {},
}
}
function isChatParamsOutput(raw: unknown): raw is ChatParamsOutput {
if (!isRecord(raw)) return false
if (!isRecord(raw.options)) {
raw.options = {}
}
return isRecord(raw.options)
}
export function createChatParamsHandler(args: {
anthropicEffort: { "chat.params"?: (input: ChatParamsInput, output: ChatParamsOutput) => Promise<void> } | null
}): (input: unknown, output: unknown) => Promise<void> {
return async (input, output): Promise<void> => {
const normalizedInput = buildChatParamsInput(input)
if (!normalizedInput) return
if (!isChatParamsOutput(output)) return
await args.anthropicEffort?.["chat.params"]?.(normalizedInput, output)
}
}
+133
View File
@@ -0,0 +1,133 @@
import type { OhMyOpenCodeConfig } from "../config"
import type { PluginContext } from "./types"
import {
clearSessionAgent,
getMainSessionID,
setMainSession,
updateSessionAgent,
} from "../features/claude-code-session-state"
import { resetMessageCursor } from "../shared"
import { lspManager } from "../tools"
import type { CreatedHooks } from "../create-hooks"
import type { Managers } from "../create-managers"
type FirstMessageVariantGate = {
markSessionCreated: (sessionInfo: { id?: string; title?: string; parentID?: string } | undefined) => void
clear: (sessionID: string) => void
}
export function createEventHandler(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
firstMessageVariantGate: FirstMessageVariantGate
managers: Managers
hooks: CreatedHooks
}): (input: { event: { type: string; properties?: Record<string, unknown> } }) => Promise<void> {
const { ctx, firstMessageVariantGate, managers, hooks } = args
return async (input): Promise<void> => {
await hooks.autoUpdateChecker?.event?.(input)
await hooks.claudeCodeHooks?.event?.(input)
await hooks.backgroundNotificationHook?.event?.(input)
await hooks.sessionNotification?.(input)
await hooks.todoContinuationEnforcer?.handler?.(input)
await hooks.unstableAgentBabysitter?.event?.(input)
await hooks.contextWindowMonitor?.event?.(input)
await hooks.directoryAgentsInjector?.event?.(input)
await hooks.directoryReadmeInjector?.event?.(input)
await hooks.rulesInjector?.event?.(input)
await hooks.thinkMode?.event?.(input)
await hooks.anthropicContextWindowLimitRecovery?.event?.(input)
await hooks.agentUsageReminder?.event?.(input)
await hooks.categorySkillReminder?.event?.(input)
await hooks.interactiveBashSession?.event?.(input)
await hooks.ralphLoop?.event?.(input)
await hooks.stopContinuationGuard?.event?.(input)
await hooks.compactionTodoPreserver?.event?.(input)
await hooks.atlasHook?.handler?.(input)
const { event } = input
const props = event.properties as Record<string, unknown> | undefined
if (event.type === "session.created") {
const sessionInfo = props?.info as
| { id?: string; title?: string; parentID?: string }
| undefined
if (!sessionInfo?.parentID) {
setMainSession(sessionInfo?.id)
}
firstMessageVariantGate.markSessionCreated(sessionInfo)
await managers.tmuxSessionManager.onSessionCreated(
event as {
type: string
properties?: {
info?: { id?: string; parentID?: string; title?: string }
}
},
)
}
if (event.type === "session.deleted") {
const sessionInfo = props?.info as { id?: string } | undefined
if (sessionInfo?.id === getMainSessionID()) {
setMainSession(undefined)
}
if (sessionInfo?.id) {
clearSessionAgent(sessionInfo.id)
resetMessageCursor(sessionInfo.id)
firstMessageVariantGate.clear(sessionInfo.id)
await managers.skillMcpManager.disconnectSession(sessionInfo.id)
await lspManager.cleanupTempDirectoryClients()
await managers.tmuxSessionManager.onSessionDeleted({
sessionID: sessionInfo.id,
})
}
}
if (event.type === "message.updated") {
const info = props?.info as Record<string, unknown> | undefined
const sessionID = info?.sessionID as string | undefined
const agent = info?.agent as string | undefined
const role = info?.role as string | undefined
if (sessionID && agent && role === "user") {
updateSessionAgent(sessionID, agent)
}
}
if (event.type === "session.error") {
const sessionID = props?.sessionID as string | undefined
const error = props?.error
if (hooks.sessionRecovery?.isRecoverableError(error)) {
const messageInfo = {
id: props?.messageID as string | undefined,
role: "assistant" as const,
sessionID,
error,
}
const recovered = await hooks.sessionRecovery.handleSessionRecovery(messageInfo)
if (
recovered &&
sessionID &&
sessionID === getMainSessionID() &&
!hooks.stopContinuationGuard?.isStopped(sessionID)
) {
await ctx.client.session
.prompt({
path: { id: sessionID },
body: { parts: [{ type: "text", text: "continue" }] },
query: { directory: ctx.directory },
})
.catch(() => {})
}
}
}
}
}
@@ -0,0 +1,104 @@
import type { HookName, OhMyOpenCodeConfig } from "../../config"
import type { BackgroundManager } from "../../features/background-agent"
import type { PluginContext } from "../types"
import {
createTodoContinuationEnforcer,
createBackgroundNotificationHook,
createStopContinuationGuardHook,
createCompactionContextInjector,
createCompactionTodoPreserverHook,
createAtlasHook,
} from "../../hooks"
import { safeCreateHook } from "../../shared/safe-create-hook"
import { createUnstableAgentBabysitter } from "../unstable-agent-babysitter"
export type ContinuationHooks = {
stopContinuationGuard: ReturnType<typeof createStopContinuationGuardHook> | null
compactionContextInjector: ReturnType<typeof createCompactionContextInjector> | null
compactionTodoPreserver: ReturnType<typeof createCompactionTodoPreserverHook> | null
todoContinuationEnforcer: ReturnType<typeof createTodoContinuationEnforcer> | null
unstableAgentBabysitter: ReturnType<typeof createUnstableAgentBabysitter> | null
backgroundNotificationHook: ReturnType<typeof createBackgroundNotificationHook> | null
atlasHook: ReturnType<typeof createAtlasHook> | null
}
type SessionRecovery = {
setOnAbortCallback: (callback: (sessionID: string) => void) => void
setOnRecoveryCompleteCallback: (callback: (sessionID: string) => void) => void
} | null
export function createContinuationHooks(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
isHookEnabled: (hookName: HookName) => boolean
safeHookEnabled: boolean
backgroundManager: BackgroundManager
sessionRecovery: SessionRecovery
}): ContinuationHooks {
const {
ctx,
pluginConfig,
isHookEnabled,
safeHookEnabled,
backgroundManager,
sessionRecovery,
} = args
const safeHook = <T>(hookName: HookName, factory: () => T): T | null =>
safeCreateHook(hookName, factory, { enabled: safeHookEnabled })
const stopContinuationGuard = isHookEnabled("stop-continuation-guard")
? safeHook("stop-continuation-guard", () => createStopContinuationGuardHook(ctx))
: null
const compactionContextInjector = isHookEnabled("compaction-context-injector")
? safeHook("compaction-context-injector", () => createCompactionContextInjector())
: null
const compactionTodoPreserver = isHookEnabled("compaction-todo-preserver")
? safeHook("compaction-todo-preserver", () => createCompactionTodoPreserverHook(ctx))
: null
const todoContinuationEnforcer = isHookEnabled("todo-continuation-enforcer")
? safeHook("todo-continuation-enforcer", () =>
createTodoContinuationEnforcer(ctx, {
backgroundManager,
isContinuationStopped: stopContinuationGuard?.isStopped,
}))
: null
const unstableAgentBabysitter = isHookEnabled("unstable-agent-babysitter")
? safeHook("unstable-agent-babysitter", () =>
createUnstableAgentBabysitter({ ctx, backgroundManager, pluginConfig }))
: null
if (sessionRecovery && todoContinuationEnforcer) {
sessionRecovery.setOnAbortCallback(todoContinuationEnforcer.markRecovering)
sessionRecovery.setOnRecoveryCompleteCallback(todoContinuationEnforcer.markRecoveryComplete)
}
const backgroundNotificationHook = isHookEnabled("background-notification")
? safeHook("background-notification", () => createBackgroundNotificationHook(backgroundManager))
: null
const atlasHook = isHookEnabled("atlas")
? safeHook("atlas", () =>
createAtlasHook(ctx, {
directory: ctx.directory,
backgroundManager,
isContinuationStopped: (sessionID: string) =>
stopContinuationGuard?.isStopped(sessionID) ?? false,
}))
: null
return {
stopContinuationGuard,
compactionContextInjector,
compactionTodoPreserver,
todoContinuationEnforcer,
unstableAgentBabysitter,
backgroundNotificationHook,
atlasHook,
}
}
+42
View File
@@ -0,0 +1,42 @@
import type { HookName, OhMyOpenCodeConfig } from "../../config"
import type { PluginContext } from "../types"
import { createSessionHooks } from "./create-session-hooks"
import { createToolGuardHooks } from "./create-tool-guard-hooks"
import { createTransformHooks } from "./create-transform-hooks"
export function createCoreHooks(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
isHookEnabled: (hookName: HookName) => boolean
safeHookEnabled: boolean
}) {
const { ctx, pluginConfig, isHookEnabled, safeHookEnabled } = args
const session = createSessionHooks({
ctx,
pluginConfig,
isHookEnabled,
safeHookEnabled,
})
const tool = createToolGuardHooks({
ctx,
pluginConfig,
isHookEnabled,
safeHookEnabled,
})
const transform = createTransformHooks({
ctx,
pluginConfig,
isHookEnabled: (name) => isHookEnabled(name as HookName),
safeHookEnabled,
})
return {
...session,
...tool,
...transform,
}
}
+181
View File
@@ -0,0 +1,181 @@
import type { OhMyOpenCodeConfig, HookName } from "../../config"
import type { PluginContext } from "../types"
import {
createContextWindowMonitorHook,
createSessionRecoveryHook,
createSessionNotification,
createThinkModeHook,
createAnthropicContextWindowLimitRecoveryHook,
createAutoUpdateCheckerHook,
createAgentUsageReminderHook,
createNonInteractiveEnvHook,
createInteractiveBashSessionHook,
createRalphLoopHook,
createEditErrorRecoveryHook,
createDelegateTaskRetryHook,
createTaskResumeInfoHook,
createStartWorkHook,
createPrometheusMdOnlyHook,
createSisyphusJuniorNotepadHook,
createQuestionLabelTruncatorHook,
createSubagentQuestionBlockerHook,
createPreemptiveCompactionHook,
} from "../../hooks"
import { createAnthropicEffortHook } from "../../hooks/anthropic-effort"
import {
detectExternalNotificationPlugin,
getNotificationConflictWarning,
log,
} from "../../shared"
import { safeCreateHook } from "../../shared/safe-create-hook"
import { sessionExists } from "../../tools"
export type SessionHooks = {
contextWindowMonitor: ReturnType<typeof createContextWindowMonitorHook> | null
preemptiveCompaction: ReturnType<typeof createPreemptiveCompactionHook> | null
sessionRecovery: ReturnType<typeof createSessionRecoveryHook> | null
sessionNotification: ReturnType<typeof createSessionNotification> | null
thinkMode: ReturnType<typeof createThinkModeHook> | null
anthropicContextWindowLimitRecovery: ReturnType<typeof createAnthropicContextWindowLimitRecoveryHook> | null
autoUpdateChecker: ReturnType<typeof createAutoUpdateCheckerHook> | null
agentUsageReminder: ReturnType<typeof createAgentUsageReminderHook> | null
nonInteractiveEnv: ReturnType<typeof createNonInteractiveEnvHook> | null
interactiveBashSession: ReturnType<typeof createInteractiveBashSessionHook> | null
ralphLoop: ReturnType<typeof createRalphLoopHook> | null
editErrorRecovery: ReturnType<typeof createEditErrorRecoveryHook> | null
delegateTaskRetry: ReturnType<typeof createDelegateTaskRetryHook> | null
startWork: ReturnType<typeof createStartWorkHook> | null
prometheusMdOnly: ReturnType<typeof createPrometheusMdOnlyHook> | null
sisyphusJuniorNotepad: ReturnType<typeof createSisyphusJuniorNotepadHook> | null
questionLabelTruncator: ReturnType<typeof createQuestionLabelTruncatorHook>
subagentQuestionBlocker: ReturnType<typeof createSubagentQuestionBlockerHook>
taskResumeInfo: ReturnType<typeof createTaskResumeInfoHook>
anthropicEffort: ReturnType<typeof createAnthropicEffortHook> | null
}
export function createSessionHooks(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
isHookEnabled: (hookName: HookName) => boolean
safeHookEnabled: boolean
}): SessionHooks {
const { ctx, pluginConfig, isHookEnabled, safeHookEnabled } = args
const safeHook = <T>(hookName: HookName, factory: () => T): T | null =>
safeCreateHook(hookName, factory, { enabled: safeHookEnabled })
const contextWindowMonitor = isHookEnabled("context-window-monitor")
? safeHook("context-window-monitor", () => createContextWindowMonitorHook(ctx))
: null
const preemptiveCompaction =
isHookEnabled("preemptive-compaction") &&
pluginConfig.experimental?.preemptive_compaction
? safeHook("preemptive-compaction", () => createPreemptiveCompactionHook(ctx))
: null
const sessionRecovery = isHookEnabled("session-recovery")
? safeHook("session-recovery", () =>
createSessionRecoveryHook(ctx, { experimental: pluginConfig.experimental }))
: null
let sessionNotification: ReturnType<typeof createSessionNotification> | null = null
if (isHookEnabled("session-notification")) {
const forceEnable = pluginConfig.notification?.force_enable ?? false
const externalNotifier = detectExternalNotificationPlugin(ctx.directory)
if (externalNotifier.detected && !forceEnable) {
log(getNotificationConflictWarning(externalNotifier.pluginName!))
} else {
sessionNotification = safeHook("session-notification", () => createSessionNotification(ctx))
}
}
const thinkMode = isHookEnabled("think-mode")
? safeHook("think-mode", () => createThinkModeHook())
: null
const anthropicContextWindowLimitRecovery = isHookEnabled("anthropic-context-window-limit-recovery")
? safeHook("anthropic-context-window-limit-recovery", () =>
createAnthropicContextWindowLimitRecoveryHook(ctx, { experimental: pluginConfig.experimental }))
: null
const autoUpdateChecker = isHookEnabled("auto-update-checker")
? safeHook("auto-update-checker", () =>
createAutoUpdateCheckerHook(ctx, {
showStartupToast: isHookEnabled("startup-toast"),
isSisyphusEnabled: pluginConfig.sisyphus_agent?.disabled !== true,
autoUpdate: pluginConfig.auto_update ?? true,
}))
: null
const agentUsageReminder = isHookEnabled("agent-usage-reminder")
? safeHook("agent-usage-reminder", () => createAgentUsageReminderHook(ctx))
: null
const nonInteractiveEnv = isHookEnabled("non-interactive-env")
? safeHook("non-interactive-env", () => createNonInteractiveEnvHook(ctx))
: null
const interactiveBashSession = isHookEnabled("interactive-bash-session")
? safeHook("interactive-bash-session", () => createInteractiveBashSessionHook(ctx))
: null
const ralphLoop = isHookEnabled("ralph-loop")
? safeHook("ralph-loop", () =>
createRalphLoopHook(ctx, {
config: pluginConfig.ralph_loop,
checkSessionExists: async (sessionId) => sessionExists(sessionId),
}))
: null
const editErrorRecovery = isHookEnabled("edit-error-recovery")
? safeHook("edit-error-recovery", () => createEditErrorRecoveryHook(ctx))
: null
const delegateTaskRetry = isHookEnabled("delegate-task-retry")
? safeHook("delegate-task-retry", () => createDelegateTaskRetryHook(ctx))
: null
const startWork = isHookEnabled("start-work")
? safeHook("start-work", () => createStartWorkHook(ctx))
: null
const prometheusMdOnly = isHookEnabled("prometheus-md-only")
? safeHook("prometheus-md-only", () => createPrometheusMdOnlyHook(ctx))
: null
const sisyphusJuniorNotepad = isHookEnabled("sisyphus-junior-notepad")
? safeHook("sisyphus-junior-notepad", () => createSisyphusJuniorNotepadHook(ctx))
: null
const questionLabelTruncator = createQuestionLabelTruncatorHook()
const subagentQuestionBlocker = createSubagentQuestionBlockerHook()
const taskResumeInfo = createTaskResumeInfoHook()
const anthropicEffort = isHookEnabled("anthropic-effort")
? safeHook("anthropic-effort", () => createAnthropicEffortHook())
: null
return {
contextWindowMonitor,
preemptiveCompaction,
sessionRecovery,
sessionNotification,
thinkMode,
anthropicContextWindowLimitRecovery,
autoUpdateChecker,
agentUsageReminder,
nonInteractiveEnv,
interactiveBashSession,
ralphLoop,
editErrorRecovery,
delegateTaskRetry,
startWork,
prometheusMdOnly,
sisyphusJuniorNotepad,
questionLabelTruncator,
subagentQuestionBlocker,
taskResumeInfo,
anthropicEffort,
}
}
+37
View File
@@ -0,0 +1,37 @@
import type { AvailableSkill } from "../../agents/dynamic-agent-prompt-builder"
import type { HookName } from "../../config"
import type { LoadedSkill } from "../../features/opencode-skill-loader/types"
import type { PluginContext } from "../types"
import { createAutoSlashCommandHook, createCategorySkillReminderHook } from "../../hooks"
import { safeCreateHook } from "../../shared/safe-create-hook"
export type SkillHooks = {
categorySkillReminder: ReturnType<typeof createCategorySkillReminderHook> | null
autoSlashCommand: ReturnType<typeof createAutoSlashCommandHook> | null
}
export function createSkillHooks(args: {
ctx: PluginContext
isHookEnabled: (hookName: HookName) => boolean
safeHookEnabled: boolean
mergedSkills: LoadedSkill[]
availableSkills: AvailableSkill[]
}): SkillHooks {
const { ctx, isHookEnabled, safeHookEnabled, mergedSkills, availableSkills } = args
const safeHook = <T>(hookName: HookName, factory: () => T): T | null =>
safeCreateHook(hookName, factory, { enabled: safeHookEnabled })
const categorySkillReminder = isHookEnabled("category-skill-reminder")
? safeHook("category-skill-reminder", () =>
createCategorySkillReminderHook(ctx, availableSkills))
: null
const autoSlashCommand = isHookEnabled("auto-slash-command")
? safeHook("auto-slash-command", () =>
createAutoSlashCommandHook({ skills: mergedSkills }))
: null
return { categorySkillReminder, autoSlashCommand }
}
@@ -0,0 +1,98 @@
import type { HookName, OhMyOpenCodeConfig } from "../../config"
import type { PluginContext } from "../types"
import {
createCommentCheckerHooks,
createToolOutputTruncatorHook,
createDirectoryAgentsInjectorHook,
createDirectoryReadmeInjectorHook,
createEmptyTaskResponseDetectorHook,
createRulesInjectorHook,
createTasksTodowriteDisablerHook,
createWriteExistingFileGuardHook,
} from "../../hooks"
import {
getOpenCodeVersion,
isOpenCodeVersionAtLeast,
log,
OPENCODE_NATIVE_AGENTS_INJECTION_VERSION,
} from "../../shared"
import { safeCreateHook } from "../../shared/safe-create-hook"
export type ToolGuardHooks = {
commentChecker: ReturnType<typeof createCommentCheckerHooks> | null
toolOutputTruncator: ReturnType<typeof createToolOutputTruncatorHook> | null
directoryAgentsInjector: ReturnType<typeof createDirectoryAgentsInjectorHook> | null
directoryReadmeInjector: ReturnType<typeof createDirectoryReadmeInjectorHook> | null
emptyTaskResponseDetector: ReturnType<typeof createEmptyTaskResponseDetectorHook> | null
rulesInjector: ReturnType<typeof createRulesInjectorHook> | null
tasksTodowriteDisabler: ReturnType<typeof createTasksTodowriteDisablerHook> | null
writeExistingFileGuard: ReturnType<typeof createWriteExistingFileGuardHook> | null
}
export function createToolGuardHooks(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
isHookEnabled: (hookName: HookName) => boolean
safeHookEnabled: boolean
}): ToolGuardHooks {
const { ctx, pluginConfig, isHookEnabled, safeHookEnabled } = args
const safeHook = <T>(hookName: HookName, factory: () => T): T | null =>
safeCreateHook(hookName, factory, { enabled: safeHookEnabled })
const commentChecker = isHookEnabled("comment-checker")
? safeHook("comment-checker", () => createCommentCheckerHooks(pluginConfig.comment_checker))
: null
const toolOutputTruncator = isHookEnabled("tool-output-truncator")
? safeHook("tool-output-truncator", () =>
createToolOutputTruncatorHook(ctx, { experimental: pluginConfig.experimental }))
: null
let directoryAgentsInjector: ReturnType<typeof createDirectoryAgentsInjectorHook> | null = null
if (isHookEnabled("directory-agents-injector")) {
const currentVersion = getOpenCodeVersion()
const hasNativeSupport =
currentVersion !== null && isOpenCodeVersionAtLeast(OPENCODE_NATIVE_AGENTS_INJECTION_VERSION)
if (hasNativeSupport) {
log("directory-agents-injector auto-disabled due to native OpenCode support", {
currentVersion,
nativeVersion: OPENCODE_NATIVE_AGENTS_INJECTION_VERSION,
})
} else {
directoryAgentsInjector = safeHook("directory-agents-injector", () => createDirectoryAgentsInjectorHook(ctx))
}
}
const directoryReadmeInjector = isHookEnabled("directory-readme-injector")
? safeHook("directory-readme-injector", () => createDirectoryReadmeInjectorHook(ctx))
: null
const emptyTaskResponseDetector = isHookEnabled("empty-task-response-detector")
? safeHook("empty-task-response-detector", () => createEmptyTaskResponseDetectorHook(ctx))
: null
const rulesInjector = isHookEnabled("rules-injector")
? safeHook("rules-injector", () => createRulesInjectorHook(ctx))
: null
const tasksTodowriteDisabler = isHookEnabled("tasks-todowrite-disabler")
? safeHook("tasks-todowrite-disabler", () =>
createTasksTodowriteDisablerHook({ experimental: pluginConfig.experimental }))
: null
const writeExistingFileGuard = isHookEnabled("write-existing-file-guard")
? safeHook("write-existing-file-guard", () => createWriteExistingFileGuardHook(ctx))
: null
return {
commentChecker,
toolOutputTruncator,
directoryAgentsInjector,
directoryReadmeInjector,
emptyTaskResponseDetector,
rulesInjector,
tasksTodowriteDisabler,
writeExistingFileGuard,
}
}
@@ -0,0 +1,65 @@
import type { OhMyOpenCodeConfig } from "../../config"
import type { PluginContext } from "../types"
import {
createClaudeCodeHooksHook,
createKeywordDetectorHook,
createThinkingBlockValidatorHook,
} from "../../hooks"
import {
contextCollector,
createContextInjectorMessagesTransformHook,
} from "../../features/context-injector"
import { safeCreateHook } from "../../shared/safe-create-hook"
export type TransformHooks = {
claudeCodeHooks: ReturnType<typeof createClaudeCodeHooksHook>
keywordDetector: ReturnType<typeof createKeywordDetectorHook> | null
contextInjectorMessagesTransform: ReturnType<typeof createContextInjectorMessagesTransformHook>
thinkingBlockValidator: ReturnType<typeof createThinkingBlockValidatorHook> | null
}
export function createTransformHooks(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
isHookEnabled: (hookName: string) => boolean
safeHookEnabled?: boolean
}): TransformHooks {
const { ctx, pluginConfig, isHookEnabled } = args
const safeHookEnabled = args.safeHookEnabled ?? true
const claudeCodeHooks = createClaudeCodeHooksHook(
ctx,
{
disabledHooks: (pluginConfig.claude_code?.hooks ?? true) ? undefined : true,
keywordDetectorDisabled: !isHookEnabled("keyword-detector"),
},
contextCollector,
)
const keywordDetector = isHookEnabled("keyword-detector")
? safeCreateHook(
"keyword-detector",
() => createKeywordDetectorHook(ctx, contextCollector),
{ enabled: safeHookEnabled },
)
: null
const contextInjectorMessagesTransform =
createContextInjectorMessagesTransformHook(contextCollector)
const thinkingBlockValidator = isHookEnabled("thinking-block-validator")
? safeCreateHook(
"thinking-block-validator",
() => createThinkingBlockValidatorHook(),
{ enabled: safeHookEnabled },
)
: null
return {
claudeCodeHooks,
keywordDetector,
contextInjectorMessagesTransform,
thinkingBlockValidator,
}
}
+24
View File
@@ -0,0 +1,24 @@
import type { Message, Part } from "@opencode-ai/sdk"
import type { CreatedHooks } from "../create-hooks"
type MessageWithParts = {
info: Message
parts: Part[]
}
type MessagesTransformOutput = { messages: MessageWithParts[] }
export function createMessagesTransformHandler(args: {
hooks: CreatedHooks
}): (input: Record<string, never>, output: MessagesTransformOutput) => Promise<void> {
return async (input, output): Promise<void> => {
await args.hooks.contextInjectorMessagesTransform?.[
"experimental.chat.messages.transform"
]?.(input, output)
await args.hooks.thinkingBlockValidator?.[
"experimental.chat.messages.transform"
]?.(input, output)
}
}
+87
View File
@@ -0,0 +1,87 @@
import type { AvailableSkill } from "../agents/dynamic-agent-prompt-builder"
import type { OhMyOpenCodeConfig } from "../config"
import type { BrowserAutomationProvider } from "../config/schema/browser-automation"
import type {
LoadedSkill,
SkillScope,
} from "../features/opencode-skill-loader/types"
import {
discoverUserClaudeSkills,
discoverProjectClaudeSkills,
discoverOpencodeGlobalSkills,
discoverOpencodeProjectSkills,
mergeSkills,
} from "../features/opencode-skill-loader"
import { createBuiltinSkills } from "../features/builtin-skills"
import { getSystemMcpServerNames } from "../features/claude-code-mcp-loader"
export type SkillContext = {
mergedSkills: LoadedSkill[]
availableSkills: AvailableSkill[]
browserProvider: BrowserAutomationProvider
disabledSkills: Set<string>
}
function mapScopeToLocation(scope: SkillScope): AvailableSkill["location"] {
if (scope === "user" || scope === "opencode") return "user"
if (scope === "project" || scope === "opencode-project") return "project"
return "plugin"
}
export async function createSkillContext(args: {
directory: string
pluginConfig: OhMyOpenCodeConfig
}): Promise<SkillContext> {
const { directory, pluginConfig } = args
const browserProvider: BrowserAutomationProvider =
pluginConfig.browser_automation_engine?.provider ?? "playwright"
const disabledSkills = new Set<string>(pluginConfig.disabled_skills ?? [])
const systemMcpNames = getSystemMcpServerNames()
const builtinSkills = createBuiltinSkills({
browserProvider,
disabledSkills,
}).filter((skill) => {
if (skill.mcpConfig) {
for (const mcpName of Object.keys(skill.mcpConfig)) {
if (systemMcpNames.has(mcpName)) return false
}
}
return true
})
const includeClaudeSkills = pluginConfig.claude_code?.skills !== false
const [userSkills, globalSkills, projectSkills, opencodeProjectSkills] =
await Promise.all([
includeClaudeSkills ? discoverUserClaudeSkills() : Promise.resolve([]),
discoverOpencodeGlobalSkills(),
includeClaudeSkills ? discoverProjectClaudeSkills() : Promise.resolve([]),
discoverOpencodeProjectSkills(),
])
const mergedSkills = mergeSkills(
builtinSkills,
pluginConfig.skills,
userSkills,
globalSkills,
projectSkills,
opencodeProjectSkills,
{ configDir: directory },
)
const availableSkills: AvailableSkill[] = mergedSkills.map((skill) => ({
name: skill.name,
description: skill.definition.description ?? "",
location: mapScopeToLocation(skill.scope),
}))
return {
mergedSkills,
availableSkills,
browserProvider,
disabledSkills,
}
}
+47
View File
@@ -0,0 +1,47 @@
import { consumeToolMetadata } from "../features/tool-metadata-store"
import type { CreatedHooks } from "../create-hooks"
export function createToolExecuteAfterHandler(args: {
hooks: CreatedHooks
}): (
input: { tool: string; sessionID: string; callID: string },
output:
| { title: string; output: string; metadata: Record<string, unknown> }
| undefined,
) => Promise<void> {
const { hooks } = args
return async (
input: { tool: string; sessionID: string; callID: string },
output: { title: string; output: string; metadata: Record<string, unknown> } | undefined,
): Promise<void> => {
if (!output) return
const stored = consumeToolMetadata(input.sessionID, input.callID)
if (stored) {
if (stored.title) {
output.title = stored.title
}
if (stored.metadata) {
output.metadata = { ...output.metadata, ...stored.metadata }
}
}
await hooks.claudeCodeHooks?.["tool.execute.after"]?.(input, output)
await hooks.toolOutputTruncator?.["tool.execute.after"]?.(input, output)
await hooks.preemptiveCompaction?.["tool.execute.after"]?.(input, output)
await hooks.contextWindowMonitor?.["tool.execute.after"]?.(input, output)
await hooks.commentChecker?.["tool.execute.after"]?.(input, output)
await hooks.directoryAgentsInjector?.["tool.execute.after"]?.(input, output)
await hooks.directoryReadmeInjector?.["tool.execute.after"]?.(input, output)
await hooks.rulesInjector?.["tool.execute.after"]?.(input, output)
await hooks.emptyTaskResponseDetector?.["tool.execute.after"]?.(input, output)
await hooks.agentUsageReminder?.["tool.execute.after"]?.(input, output)
await hooks.categorySkillReminder?.["tool.execute.after"]?.(input, output)
await hooks.interactiveBashSession?.["tool.execute.after"]?.(input, output)
await hooks.editErrorRecovery?.["tool.execute.after"]?.(input, output)
await hooks.delegateTaskRetry?.["tool.execute.after"]?.(input, output)
await hooks.atlasHook?.["tool.execute.after"]?.(input, output)
await hooks.taskResumeInfo?.["tool.execute.after"]?.(input, output)
}
}
+99
View File
@@ -0,0 +1,99 @@
import type { PluginContext } from "./types"
import { getMainSessionID } from "../features/claude-code-session-state"
import { clearBoulderState } from "../features/boulder-state"
import { log } from "../shared"
import type { CreatedHooks } from "../create-hooks"
export function createToolExecuteBeforeHandler(args: {
ctx: PluginContext
hooks: CreatedHooks
}): (
input: { tool: string; sessionID: string; callID: string },
output: { args: Record<string, unknown> },
) => Promise<void> {
const { ctx, hooks } = args
return async (input, output): Promise<void> => {
await hooks.subagentQuestionBlocker?.["tool.execute.before"]?.(input, output)
await hooks.writeExistingFileGuard?.["tool.execute.before"]?.(input, output)
await hooks.questionLabelTruncator?.["tool.execute.before"]?.(input, output)
await hooks.claudeCodeHooks?.["tool.execute.before"]?.(input, output)
await hooks.nonInteractiveEnv?.["tool.execute.before"]?.(input, output)
await hooks.commentChecker?.["tool.execute.before"]?.(input, output)
await hooks.directoryAgentsInjector?.["tool.execute.before"]?.(input, output)
await hooks.directoryReadmeInjector?.["tool.execute.before"]?.(input, output)
await hooks.rulesInjector?.["tool.execute.before"]?.(input, output)
await hooks.tasksTodowriteDisabler?.["tool.execute.before"]?.(input, output)
await hooks.prometheusMdOnly?.["tool.execute.before"]?.(input, output)
await hooks.sisyphusJuniorNotepad?.["tool.execute.before"]?.(input, output)
await hooks.atlasHook?.["tool.execute.before"]?.(input, output)
if (input.tool === "task") {
const argsObject = output.args
const category = typeof argsObject.category === "string" ? argsObject.category : undefined
const subagentType = typeof argsObject.subagent_type === "string" ? argsObject.subagent_type : undefined
if (category && !subagentType) {
argsObject.subagent_type = "sisyphus-junior"
}
}
if (hooks.ralphLoop && input.tool === "slashcommand") {
const rawCommand = typeof output.args.command === "string" ? output.args.command : undefined
const command = rawCommand?.replace(/^\//, "").toLowerCase()
const sessionID = input.sessionID || getMainSessionID()
if (command === "ralph-loop" && sessionID) {
const rawArgs = rawCommand?.replace(/^\/?(ralph-loop)\s*/i, "") || ""
const taskMatch = rawArgs.match(/^["'](.+?)["']/)
const prompt =
taskMatch?.[1] ||
rawArgs.split(/\s+--/)[0]?.trim() ||
"Complete the task as instructed"
const maxIterMatch = rawArgs.match(/--max-iterations=(\d+)/i)
const promiseMatch = rawArgs.match(/--completion-promise=["']?([^"'\s]+)["']?/i)
hooks.ralphLoop.startLoop(sessionID, prompt, {
maxIterations: maxIterMatch ? parseInt(maxIterMatch[1], 10) : undefined,
completionPromise: promiseMatch?.[1],
})
} else if (command === "cancel-ralph" && sessionID) {
hooks.ralphLoop.cancelLoop(sessionID)
} else if (command === "ulw-loop" && sessionID) {
const rawArgs = rawCommand?.replace(/^\/?(ulw-loop)\s*/i, "") || ""
const taskMatch = rawArgs.match(/^["'](.+?)["']/)
const prompt =
taskMatch?.[1] ||
rawArgs.split(/\s+--/)[0]?.trim() ||
"Complete the task as instructed"
const maxIterMatch = rawArgs.match(/--max-iterations=(\d+)/i)
const promiseMatch = rawArgs.match(/--completion-promise=["']?([^"'\s]+)["']?/i)
hooks.ralphLoop.startLoop(sessionID, prompt, {
ultrawork: true,
maxIterations: maxIterMatch ? parseInt(maxIterMatch[1], 10) : undefined,
completionPromise: promiseMatch?.[1],
})
}
}
if (input.tool === "slashcommand") {
const rawCommand = typeof output.args.command === "string" ? output.args.command : undefined
const command = rawCommand?.replace(/^\//, "").toLowerCase()
const sessionID = input.sessionID || getMainSessionID()
if (command === "stop-continuation" && sessionID) {
hooks.stopContinuationGuard?.stop(sessionID)
hooks.todoContinuationEnforcer?.cancelAllCountdowns()
hooks.ralphLoop?.cancelLoop(sessionID)
clearBoulderState(ctx.directory)
log("[stop-continuation] All continuation mechanisms stopped", {
sessionID,
})
}
}
}
}
+143
View File
@@ -0,0 +1,143 @@
import type { ToolDefinition } from "@opencode-ai/plugin"
import type {
AvailableCategory,
} from "../agents/dynamic-agent-prompt-builder"
import type { OhMyOpenCodeConfig } from "../config"
import type { PluginContext, ToolsRecord } from "./types"
import {
builtinTools,
createBackgroundTools,
createCallOmoAgent,
createLookAt,
createSkillTool,
createSkillMcpTool,
createSlashcommandTool,
createGrepTools,
createGlobTools,
createAstGrepTools,
createSessionManagerTools,
createDelegateTask,
discoverCommandsSync,
interactive_bash,
createTaskCreateTool,
createTaskGetTool,
createTaskList,
createTaskUpdateTool,
} from "../tools"
import { getMainSessionID } from "../features/claude-code-session-state"
import { filterDisabledTools } from "../shared/disabled-tools"
import { log } from "../shared"
import type { Managers } from "../create-managers"
import type { SkillContext } from "./skill-context"
export type ToolRegistryResult = {
filteredTools: ToolsRecord
taskSystemEnabled: boolean
}
export function createToolRegistry(args: {
ctx: PluginContext
pluginConfig: OhMyOpenCodeConfig
managers: Pick<Managers, "backgroundManager" | "tmuxSessionManager" | "skillMcpManager">
skillContext: SkillContext
availableCategories: AvailableCategory[]
}): ToolRegistryResult {
const { ctx, pluginConfig, managers, skillContext, availableCategories } = args
const backgroundTools = createBackgroundTools(managers.backgroundManager, ctx.client)
const callOmoAgent = createCallOmoAgent(ctx, managers.backgroundManager)
const isMultimodalLookerEnabled = !(pluginConfig.disabled_agents ?? []).some(
(agent) => agent.toLowerCase() === "multimodal-looker",
)
const lookAt = isMultimodalLookerEnabled ? createLookAt(ctx) : null
const delegateTask = createDelegateTask({
manager: managers.backgroundManager,
client: ctx.client,
directory: ctx.directory,
userCategories: pluginConfig.categories,
gitMasterConfig: pluginConfig.git_master,
sisyphusJuniorModel: pluginConfig.agents?.["sisyphus-junior"]?.model,
browserProvider: skillContext.browserProvider,
disabledSkills: skillContext.disabledSkills,
availableCategories,
availableSkills: skillContext.availableSkills,
onSyncSessionCreated: async (event) => {
log("[index] onSyncSessionCreated callback", {
sessionID: event.sessionID,
parentID: event.parentID,
title: event.title,
})
await managers.tmuxSessionManager.onSessionCreated({
type: "session.created",
properties: {
info: {
id: event.sessionID,
parentID: event.parentID,
title: event.title,
},
},
})
},
})
const getSessionIDForMcp = (): string => getMainSessionID() || ""
const skillTool = createSkillTool({
skills: skillContext.mergedSkills,
mcpManager: managers.skillMcpManager,
getSessionID: getSessionIDForMcp,
gitMasterConfig: pluginConfig.git_master,
disabledSkills: skillContext.disabledSkills,
})
const skillMcpTool = createSkillMcpTool({
manager: managers.skillMcpManager,
getLoadedSkills: () => skillContext.mergedSkills,
getSessionID: getSessionIDForMcp,
})
const commands = discoverCommandsSync()
const slashcommandTool = createSlashcommandTool({
commands,
skills: skillContext.mergedSkills,
})
const taskSystemEnabled = pluginConfig.experimental?.task_system ?? false
const taskToolsRecord: Record<string, ToolDefinition> = taskSystemEnabled
? {
task_create: createTaskCreateTool(pluginConfig, ctx),
task_get: createTaskGetTool(pluginConfig),
task_list: createTaskList(pluginConfig),
task_update: createTaskUpdateTool(pluginConfig, ctx),
}
: {}
const allTools: Record<string, ToolDefinition> = {
...builtinTools,
...createGrepTools(ctx),
...createGlobTools(ctx),
...createAstGrepTools(ctx),
...createSessionManagerTools(ctx),
...backgroundTools,
call_omo_agent: callOmoAgent,
...(lookAt ? { look_at: lookAt } : {}),
task: delegateTask,
skill: skillTool,
skill_mcp: skillMcpTool,
slashcommand: slashcommandTool,
interactive_bash,
...taskToolsRecord,
}
const filteredTools = filterDisabledTools(allTools, pluginConfig.disabled_tools)
return {
filteredTools,
taskSystemEnabled,
}
}
+15
View File
@@ -0,0 +1,15 @@
import type { Plugin, ToolDefinition } from "@opencode-ai/plugin"
export type PluginContext = Parameters<Plugin>[0]
export type PluginInstance = Awaited<ReturnType<Plugin>>
export type PluginInterface = Omit<PluginInstance, "experimental.session.compacting">
export type ToolsRecord = Record<string, ToolDefinition>
export type TmuxConfig = {
enabled: boolean
layout: "main-horizontal" | "main-vertical" | "tiled" | "even-horizontal" | "even-vertical"
main_pane_size: number
main_pane_min_width: number
agent_pane_min_width: number
}
+41
View File
@@ -0,0 +1,41 @@
import type { OhMyOpenCodeConfig } from "../config"
import type { PluginContext } from "./types"
import { createUnstableAgentBabysitterHook } from "../hooks"
import type { BackgroundManager } from "../features/background-agent"
export function createUnstableAgentBabysitter(args: {
ctx: PluginContext
backgroundManager: BackgroundManager
pluginConfig: OhMyOpenCodeConfig
}) {
const { ctx, backgroundManager, pluginConfig } = args
return createUnstableAgentBabysitterHook(
{
directory: ctx.directory,
client: {
session: {
messages: async ({ path }) => {
const result = await ctx.client.session.messages({ path })
if (Array.isArray(result)) return result
if (typeof result === "object" && result !== null) {
return result
}
return []
},
prompt: async (promptArgs) => {
await ctx.client.session.promptAsync(promptArgs)
},
promptAsync: async (promptArgs) => {
await ctx.client.session.promptAsync(promptArgs)
},
},
},
},
{
backgroundManager,
config: pluginConfig.babysitting,
},
)
}