2026-02-13 12:57:16 +01:00
|
|
|
import type { PluginInput } from "@opencode-ai/plugin"
|
2026-02-13 13:18:07 +01:00
|
|
|
import { consumePendingSwitch } from "../../features/agent-switch"
|
2026-02-13 12:57:16 +01:00
|
|
|
import { log } from "../../shared/logger"
|
|
|
|
|
|
2026-02-13 13:18:07 +01:00
|
|
|
const HOOK_NAME = "agent-switch" as const
|
2026-02-13 12:57:16 +01:00
|
|
|
|
2026-02-13 13:18:07 +01:00
|
|
|
export function createAgentSwitchHook(ctx: PluginInput) {
|
2026-02-13 12:57:16 +01:00
|
|
|
return {
|
|
|
|
|
event: async (input: { event: { type: string; properties?: Record<string, unknown> } }): Promise<void> => {
|
|
|
|
|
if (input.event.type !== "session.idle") return
|
|
|
|
|
|
|
|
|
|
const props = input.event.properties as Record<string, unknown> | undefined
|
|
|
|
|
const sessionID = props?.sessionID as string | undefined
|
|
|
|
|
if (!sessionID) return
|
|
|
|
|
|
2026-02-13 13:18:07 +01:00
|
|
|
const pending = consumePendingSwitch(sessionID)
|
|
|
|
|
if (!pending) return
|
2026-02-13 12:57:16 +01:00
|
|
|
|
2026-02-13 13:18:07 +01:00
|
|
|
log(`[${HOOK_NAME}] Switching to ${pending.agent}`, { sessionID })
|
2026-02-13 12:57:16 +01:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await ctx.client.session.promptAsync({
|
|
|
|
|
path: { id: sessionID },
|
|
|
|
|
body: {
|
2026-02-13 13:18:07 +01:00
|
|
|
agent: pending.agent,
|
|
|
|
|
parts: [{ type: "text", text: pending.context }],
|
2026-02-13 12:57:16 +01:00
|
|
|
},
|
|
|
|
|
query: { directory: ctx.directory },
|
|
|
|
|
})
|
|
|
|
|
|
2026-02-13 13:18:07 +01:00
|
|
|
log(`[${HOOK_NAME}] Switch to ${pending.agent} complete`, { sessionID })
|
2026-02-13 12:57:16 +01:00
|
|
|
} catch (err) {
|
2026-02-13 13:18:07 +01:00
|
|
|
log(`[${HOOK_NAME}] Switch failed`, { sessionID, error: String(err) })
|
2026-02-13 12:57:16 +01:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|