// ctx-wire Pi extension - rewrites bash commands through ctx-wire so their
// output reaches the model filtered and secret-scrubbed.
//
// Thin delegating extension: all rewrite logic lives in `ctx-wire rewrite` (the
// single source of truth). Do not edit this file to change rules. Requires
// ctx-wire on PATH.

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
import { isToolCallEventType } from "@earendil-works/pi-coding-agent"

const REWRITE_TIMEOUT_MS = 2_000

export default async function (pi: ExtensionAPI) {
  const ver = await pi.exec("ctx-wire", ["version"], { timeout: REWRITE_TIMEOUT_MS })
  if (ver.code !== 0) {
    console.warn("[ctx-wire] binary not found in PATH - extension disabled")
    return
  }

  pi.on("tool_call", async (event, ctx) => {
    try {
      if (!isToolCallEventType("bash", event)) return

      const cmd = event.input.command
      if (typeof cmd !== "string" || cmd.trim() === "") return
      if (cmd.startsWith("ctx-wire ")) return

      const result = await pi.exec("ctx-wire", ["rewrite", "--agent", "pi", cmd], {
        timeout: REWRITE_TIMEOUT_MS,
        signal: ctx.signal,
      })
      if (result.killed || result.code !== 0) return

      const rewritten = result.stdout.trim()
      if (rewritten && rewritten !== cmd) {
        event.input.command = rewritten
      }
    } catch (err) {
      // Fail open: never block execution on an unexpected error.
      console.warn("[ctx-wire] tool_call handler error; passing through", err)
    }
  })
}
