| 56 | } |
| 57 | |
| 58 | export const AtomicHooksPlugin: Plugin = async ({ $, directory }) => { |
| 59 | const ATOMIC = "atomic"; |
| 60 | const atomicDir = join(directory, ".atomic"); |
| 61 | const logFile = join(atomicDir, "plugin.log"); |
| 62 | const debugFile = join(atomicDir, "plugin-debug.log"); |
| 63 | try { |
| 64 | mkdirSync(atomicDir, { recursive: true }); |
| 65 | } catch {} |
| 66 | |
| 67 | // Set of messageIDs that belong to user messages (from chat.message hook). |
| 68 | // Used to distinguish user text parts from assistant text parts in the event stream. |
| 69 | const userMessageIDs = new Set<string>(); |
| 70 | |
| 71 | const log = (msg: string) => { |
| 72 | const line = `${new Date().toISOString()} ${msg}\n`; |
| 73 | try { |
| 74 | appendFileSync(logFile, line); |
| 75 | } catch {} |
| 76 | }; |
| 77 | |
| 78 | // DEBUG: Separate debug log with full object inspection |
| 79 | const debug = (label: string, data?: unknown) => { |
| 80 | const ts = new Date().toISOString(); |
| 81 | const body = data !== undefined ? `\n${inspect(data)}` : ""; |
| 82 | try { |
| 83 | appendFileSync(debugFile, `${ts} [${label}]${body}\n---\n`); |
| 84 | } catch {} |
| 85 | }; |
| 86 | |
| 87 | const hook = async ( |
| 88 | sessionID: string, |
| 89 | verb: string, |
| 90 | extra: Record<string, unknown> = {}, |
| 91 | ) => { |
| 92 | const payload = JSON.stringify({ |
| 93 | session_id: sessionID, |
| 94 | cwd: directory, |
| 95 | timestamp: new Date().toISOString(), |
| 96 | ...extra, |
| 97 | }); |
| 98 | try { |
| 99 | const result = |
| 100 | await $`echo ${payload} | ${ATOMIC} agent hooks opencode ${verb}` |
| 101 | .cwd(directory) |
| 102 | .quiet() |
| 103 | .nothrow(); |
| 104 | const ok = result.exitCode === 0; |
| 105 | const stderr = result.stderr.toString().trim(); |
| 106 | log( |
| 107 | `${verb} session=${sessionID} exit=${result.exitCode}${stderr ? " stderr=" + stderr : ""}`, |
| 108 | ); |
| 109 | return ok; |
| 110 | } catch (err) { |
| 111 | log(`${verb} session=${sessionID} error=${err}`); |
| 112 | return false; |
| 113 | } |
| 114 | }; |
| 115 | |