import { stripFrontmatter, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
import * as NodeCrypto from "node:crypto";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import { Type } from "typebox";

const URL_ENV = "T3_MCP_URL";
const TOKEN_ENV = "T3_MCP_BEARER_TOKEN";
const RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE";
const EXTENSION_PATH_ENV = "T3_PI_MCP_EXTENSION_PATH";
const ORCHESTRATION_INSTRUCTIONS = "## T3 Code orchestration\n\nOrdinary coding tasks need no T3 tools.\n\n- Subagents: use your native tool when the child uses your provider, a model it offers and no settings beyond yours (Claude `Agent`, `run_in_background:false`; Codex `spawn_agent`, then wait). Use `delegate_task` for another provider's model, user-asked settings, a separate checkout (`isolation:\"worktree\"`), or `delegate_task` by name. A native type on another provider's model counts too. Background agent: `delegate_task`, never a background `Agent`. Workflow only when asked.\n- Call `orchestrator_capabilities` once per thread, before the first `delegate_task`. Again only after an error or a user-named provider change. Settings go in `target.options`. Provider or model unavailable: say so. Never switch unasked or fall back to native tools, Workflow or CLIs. Never make a child's checkout in the shell or in `task`.\n- Every new delegate review or re-check is a new `delegate_task` (brief, findings, objections), never a `t3_thread_send`. Fix small review findings yourself; start no delegate for them. When told to proceed without a delegate, or to run fewer, `task_cancel` the extras. Start no replacement.\n- Follow a running delegate's `next`. Don't poll it (`task_status`, `sleep`, watchers, Monitor, ScheduleWakeup). Stop a delegate run you replace or no longer need with `task_cancel`, never `t3_thread_interrupt` on a `childThreadId`.\n- As a subagent or child, do the work yourself. Start no subagents unless your task says to.\n\n- `t3_thread_launch` and `create_threads` make new top-level threads, only when the user asks for a new thread. \"Subagent\", \"delegate\", and \"parallel\" never mean one. Worktree thread: set `workspaceStrategy`. Honor a requested base. Otherwise independent work uses the default branch as `remote/branch` with `startFromOrigin:true`; with no remote, use the local default. Required unpublished commits and dependent work use their local base. Shell worktrees don't bind it, and no checkout setup in its prompt. No `workspaceStrategy`: project root, not your worktree.\n- Given a thread id, `t3_thread_read` it before you answer about it. Asked to settle a thread, this one too: `t3_thread_organize`.\n- Another machine: `t3_environment_links` lists linked ones. Pass its `environmentId` and that machine's `threadId` to T3 tools.\n- Unlinked (\"delegate this to my vps\"): `t3_environment_link` with a `hint` from the user's words, never a pairing code in chat. No link tools: say to enable Settings → Labs → Linked environments.\n- In your reply, mention a thread by its `link`, verbatim, never a plain title or bare id.\n- A login, token, PIN, pairing code or sudo password only the user can give: call `request_secret`, not a chat ask or a handoff. Not for access you have. Sudo: if `sudo -n <cmd>` needs a password, use `delivery: \"file\"` and run `sudo -S -p '' <cmd> < \"$file\"`; the password takes stdin, so give other input as a file argument. Asked only to schedule: `schedule_task` without running its prompt.\n- T3 tools may load late. Try the name once before you call it absent.\n\n### Visuals and preview\n\n- Answer data with a trend or comparison with a chart and show any visual the user asks for here: pass an HTML file path or inline HTML to `html_preview`, then `html_render`. A screenshot on disk or a text description doesn't show it. Never start a server for it. Page tools write only on user request. Never use them to show results. Asked for an image to post, send or use elsewhere: a `.png` file and its path, never `html_render`.\n- Never use `preview_*` unasked to verify or show your own edit. Use them when the current request asks for browser work, including recording edits, or names a page or tab. Don't repeat preview calls from an earlier turn. Public pages: web fetch or search unless browser work was asked; then preview tools only, no web fetch. Close a tab you opened before you reply, unless the user asked for it or uses it.";
const PULL_REQUEST_LINKING_INSTRUCTIONS = "<pull_request_linking>\nLink each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR <full URL>, head <SHA>, checks and reviews <state>. Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you.\nIf available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read.\n</pull_request_linking>";
const SERVICE_TIER_COMMAND = "t3-service-tier";
const PROTOCOL = "2025-06-18";
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
const FILE_CHANGE_TOOLS = new Set(["edit","write"]);

type RuntimeMode = "approval-required" | "auto-accept-edits" | "auto" | "full-access";

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

type JsonRpcResponse = {
  readonly id?: number | string;
  readonly result?: JsonValue;
  readonly error?: { readonly message?: string };
};

type McpTool = {
  readonly name: string;
  readonly description?: string;
  readonly inputSchema?: Record<string, unknown>;
  readonly annotations?: { readonly readOnlyHint?: boolean };
  readonly outputSchema?: Record<string, unknown>;
};

function env(name: string): string | undefined {
  const value = process.env[name];
  return value && value.length > 0 ? value : undefined;
}

function runtimeMode(): RuntimeMode {
  const value = env(RUNTIME_MODE_ENV);
  return value === "approval-required" ||
    value === "auto-accept-edits" ||
    value === "auto" ||
    value === "full-access"
    ? value
    : "full-access";
}

// T3 keys "Always allow this session" on this text, so a cut summary ends with the
// full input's hash: calls that differ only past the cut get separate grants.
function toolInputSummary(input: unknown): string {
  let text: string;
  try {
    text = JSON.stringify(input, null, 2) ?? String(input);
  } catch {
    text = String(input);
  }
  if (text.length <= 4_000) return text;
  const hash = NodeCrypto.createHash("sha256").update(text, "utf16le").digest("hex");
  return text.slice(0, 4_000) + "\n... " + (text.length - 4_000) +
    " more characters not shown (sha256 " + hash + ")";
}

function parseSseOrJson(body: string, contentType: string): JsonRpcResponse {
  if (contentType.includes("text/event-stream")) {
    for (const line of body.split("\n")) {
      const trimmed = line.startsWith("data:") ? line.slice(5).trim() : "";
      if (trimmed.length === 0) continue;
      const parsed = JSON.parse(trimmed) as JsonRpcResponse;
      if (parsed.id !== undefined || parsed.result !== undefined || parsed.error !== undefined) {
        return parsed;
      }
    }
    throw new Error("MCP SSE response had no JSON-RPC payload.");
  }
  return JSON.parse(body) as JsonRpcResponse;
}

function jsonSchemaToTypebox(schema: Record<string, unknown> | undefined) {
  const unsafe = (Type as { Unsafe?: (value: unknown) => unknown }).Unsafe;
  if (typeof unsafe === "function" && schema !== undefined) {
    // Zero-argument MCP tools may omit "properties", which some OpenAI-compatible
    // servers reject. Declare it, as Pi does for its own MCP tools.
    return unsafe({
      ...schema,
      type: schema.type ?? "object",
      ...(schema.properties === undefined ? { properties: {} } : {}),
    });
  }
  return Type.Object({}, { additionalProperties: true });
}

type ModelContent =
  | { type: "text"; text: string }
  | { type: "image"; data: string; mimeType: string };

function mcpModelContent(result: unknown): ModelContent[] {
  if (result === null || result === undefined) return [];
  if (typeof result !== "object") return [{ type: "text", text: String(result) }];
  const record = result as {
    readonly content?: ReadonlyArray<{
      readonly type?: string;
      readonly text?: string;
      readonly data?: string;
      readonly mimeType?: string;
    }>;
    readonly structuredContent?: unknown;
  };
  const content: ModelContent[] = [];
  if (Array.isArray(record.content)) {
    for (const part of record.content) {
      if (part?.type === "text" && typeof part.text === "string") {
        content.push({ type: "text", text: part.text });
      } else if (part?.type === "image" && typeof part.data === "string" && typeof part.mimeType === "string") {
        content.push({ type: "image", data: part.data, mimeType: part.mimeType });
      }
    }
  }
  // Structured output belongs to scripts. Only use it as model text when
  // the server supplied no model-facing blocks, matching Pi's native MCP tools.
  if (content.length === 0) {
    content.push({ type: "text", text: JSON.stringify(record.structuredContent ?? result) });
  }
  return content;
}

function mcpScriptResult(result: JsonValue | undefined) {
  if (typeof result !== "object" || result === null || Array.isArray(result)) return result;
  const { _meta: _ignored, ...scriptResult } = result;
  return scriptResult;
}

function mcpOutputSchema(tool: McpTool) {
  return jsonSchemaToTypebox({
    type: "object",
    properties: {
      content: { type: "array", items: { type: "object" } },
      ...(tool.outputSchema === undefined ? {} : { structuredContent: tool.outputSchema }),
      isError: { type: "boolean" },
      _meta: { type: "object" },
    },
    required: ["content"],
  });
}

function isMcpToolError(result: unknown): boolean {
  return (
    typeof result === "object" &&
    result !== null &&
    "isError" in result &&
    result.isError === true
  );
}

function createMcpClient(endpoint: string, token: string) {
  let nextId = 1;
  let sessionId: string | undefined;

  const headers = (): Record<string, string> => {
    const next: Record<string, string> = {
      accept: "application/json, text/event-stream",
      authorization: token.startsWith("Bearer ") ? token : `Bearer ${token}`,
      "content-type": "application/json",
      // Effect's HTTP MCP rejects post-initialize requests without this
      // (400). The worktree client in McpHttpServer tests sends the same
      // header; initialize itself does not require it.
      "mcp-protocol-version": PROTOCOL,
    };
    if (sessionId !== undefined) next["mcp-session-id"] = sessionId;
    return next;
  };

  const request = async (method: string, params?: unknown, signal?: AbortSignal) => {
    const id = nextId++;
    const response = await fetch(endpoint, {
      method: "POST",
      headers: headers(),
      body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
      signal,
    });
    const nextSession = response.headers.get("mcp-session-id");
    if (nextSession) sessionId = nextSession;
    const body = await response.text();
    if (!response.ok) {
      throw new Error(`MCP ${method} failed (${response.status}): ${body.slice(0, 400)}`);
    }
    if (body.length === 0) return undefined;
    const parsed = parseSseOrJson(body, response.headers.get("content-type") ?? "");
    if (parsed.error) {
      throw new Error(parsed.error.message ?? `MCP ${method} returned an error`);
    }
    return parsed.result;
  };

  const notify = async (method: string, params?: unknown, signal?: AbortSignal) => {
    await fetch(endpoint, {
      method: "POST",
      headers: headers(),
      body: JSON.stringify({ jsonrpc: "2.0", method, params }),
      signal,
    });
  };

  return {
    async connect(signal?: AbortSignal) {
      await request(
        "initialize",
        {
          protocolVersion: PROTOCOL,
          capabilities: {},
          clientInfo: { name: "t3-pi-mcp", version: "1.0.0" },
        },
        signal,
      );
      await notify("notifications/initialized", {}, signal).catch(() => undefined);
    },
    async listTools(signal?: AbortSignal) {
      const tools: McpTool[] = [];
      let cursor: string | undefined;
      do {
        const result = (await request(
          "tools/list",
          cursor === undefined ? {} : { cursor },
          signal,
        )) as { tools?: McpTool[]; nextCursor?: string } | undefined;
        tools.push(...(result?.tools ?? []));
        cursor = result?.nextCursor;
      } while (cursor);
      return tools;
    },
    async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal) {
      return request("tools/call", { name, arguments: args }, signal);
    },
  };
}

export default async function t3McpExtension(pi: ExtensionAPI) {
  // RPC has no trust prompt, so Pi skips an untrusted folder's protected resources. Session
  // replacement reruns this factory without project_trust, and T3 drops notices outside a turn,
  // so check each session's first turn. An explicit --no-approve is deliberate and stays quiet.
  let projectTrustChecked = false;
  pi.on("before_agent_start", (_event, ctx) => {
    if (projectTrustChecked) return;
    projectTrustChecked = true;
    if (ctx.isProjectTrusted() || process.argv.some((arg) => arg === "--no-approve" || arg === "-na")) return;
    ctx.ui.notify(
      `Pi did not load project settings, extensions, skills, prompts, MCP servers or system prompt files for ${ctx.cwd} because the folder is not trusted. To load them, run the configured Pi binary there with the same PI_CODING_AGENT_DIR (if set), trust the folder or its parent with /trust, then start a new thread in that same worktree. To trust every project, add --approve to Pi's launch arguments in T3 Code settings; to keep them off without this notice, add --no-approve.`,
      "warning",
    );
  });

  // Keep skill chips in the request. Pi expands only one leading /skill:
  // command, so use its own frontmatter loader for every selected chip here.
  pi.on("input", async (event, ctx) => {
    if (!event.text.includes("$")) return;
    const commands = pi.getCommands().filter((command) => command.source === "skill");
    const nativeSkill = /^\/skill:([^ ]+)(?: |$)/.exec(event.text)?.[1];
    const seen = new Set<string>(nativeSkill === undefined ? [] : [nativeSkill]);
    const blocks: string[] = [];
    for (const match of event.text.matchAll(/(^|\s)\$([^\s]+)(?=\s|$)/g)) {
      const name = match[2];
      if (name === undefined || seen.has(name)) continue;
      const command = commands.find((candidate) => candidate.name === "skill:" + name);
      if (command === undefined) continue;
      seen.add(name);
      const path = command.sourceInfo.path;
      try {
        const body = stripFrontmatter(await NodeFSP.readFile(path, "utf8")).trim();
        blocks.push(
          `<skill name="${name}" location="${path}">\nReferences are relative to ${NodePath.dirname(path)}.\n\n${body}\n</skill>`,
        );
      } catch {
        ctx.ui.notify(`Could not load skill ${name} from ${path}.`, "error");
      }
    }
    if (blocks.length === 0) return;
    return {
      action: "transform",
      text: event.text + "\n\n" + blocks.join("\n\n"),
      images: event.images,
    };
  });

  // Pi has no service tier setting, so T3 sets one through this command before each turn.
  // Only a tier the active model advertises is sent; Standard sends none.
  let serviceTier: string | undefined;
  pi.registerCommand(SERVICE_TIER_COMMAND, {
    description: "Set the service tier T3 Code sends with provider requests",
    handler: async (args) => {
      serviceTier = args.trim() || undefined;
    },
  });

  pi.on("before_provider_request", (event, ctx) => {
    const payload = event.payload;
    if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
    const replacement = { ...payload } as Record<string, unknown>;
    let changed = false;
    // Workaround for an upstream Pi context-budgeting bug: pi-ai reuses the
    // previous response's usage even when a fork's instructions/tools differ,
    // then reserves almost all remaining context for output. OpenRouter can
    // reject even a short conversation. Remove this cap when Pi accounts for
    // the current request prefix reliably (api/simple-options + utils/estimate).
    if (ctx.model?.provider === "openrouter") {
      for (const key of ["max_tokens", "max_completion_tokens"]) {
        const limit = replacement[key];
        if (typeof limit === "number" && Number.isFinite(limit) && limit > 32_768) {
          replacement[key] = 32_768;
          changed = true;
        }
      }
    }
    const tiers = (ctx.model as { serviceTiers?: unknown } | undefined)?.serviceTiers;
    if (
      serviceTier !== undefined &&
      Array.isArray(tiers) &&
      tiers.some((tier) => tier?.id === serviceTier)
    ) {
      replacement.service_tier = serviceTier;
      changed = true;
    }
    if (changed) return replacement;
  });

  // Pi deliberately leaves permission policy to extensions. T3's injected
  // bridge uses Pi's public blocking tool hook so the shared runtime modes
  // keep their normal meaning without replacing or shadowing Pi's runtime.
  // Only Pi's own search is known to be read-only. An extension that replaces
  // it keeps the name, and cannot discover deferred tools either.
  // OmO reports Pi's builtin search with angle brackets around the same path.
  const BUILTIN_TOOL_SEARCH_PATHS = new Set(["builtin:tool-search", "<builtin:tool-search>"]);
  const hasBuiltinToolSearch = () =>
    typeof pi.getAllTools === "function" &&
    pi.getAllTools().some((tool) => tool.name === "tool_search" && BUILTIN_TOOL_SEARCH_PATHS.has(tool.sourceInfo?.path ?? ""));

  const readOnlyMcpTools = new Set<string>();
  const isReadOnlyMcpTool = (name: string) => {
    const extensionPath = env(EXTENSION_PATH_ENV);
    if (extensionPath === undefined || !readOnlyMcpTools.has(name) || typeof pi.getAllTools !== "function") return false;
    // A user extension may own the same name. Only our registered HTTP bridge
    // may inherit the canonical T3 server's read-only annotation.
    return pi.getAllTools().some((tool) => tool.name === name &&
      typeof tool.sourceInfo?.path === "string" &&
      NodePath.resolve(tool.sourceInfo.path) === NodePath.resolve(extensionPath));
  };

  pi.on("tool_call", async (event, ctx) => {
    const mode = runtimeMode();
    if (mode === "full-access") return;
    if ((event.toolName === "tool_search" ? hasBuiltinToolSearch() : READ_ONLY_TOOLS.has(event.toolName)) || isReadOnlyMcpTool(event.toolName)) {
      return;
    }
    if (mode === "auto-accept-edits" && FILE_CHANGE_TOOLS.has(event.toolName)) {
      return;
    }
    const approved = await ctx.ui.confirm(
      `Allow ${event.toolName}?`,
      toolInputSummary(event.input),
      { signal: ctx.signal },
    );
    if (!approved) {
      return { block: true, reason: `${event.toolName} was declined in T3 Code.` };
    }
  });

  const endpoint = env(URL_ENV);
  const token = env(TOKEN_ENV);
  if (endpoint === undefined || token === undefined) {
    pi.on("session_start", async (_event, ctx) => {
      ctx.ui.notify(
        "t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.",
        "warning",
      );
    });
    return;
  }

  // Tool exposure arrived with registerMcpServer in Pi 0.99. Keep the HTTP
  // bridge as the credential owner: mcp.json overrides native registrations.
  const supportsExposure = "registerMcpServer" in pi && typeof pi.registerMcpServer === "function";
  const directTools = new Set(["orchestrator_capabilities", "delegate_task", "task_status"]);
  const ALIAS_PREFIX = "mcp__t3_code__";
  let deferOptionalTools = supportsExposure;
  const isDeferred = (name: string) => deferOptionalTools && !directTools.has(name);
  // An alias follows its public tool: gone when --exclude-tools removed it,
  // off while a direct one is off.
  const followsPublicTool = (
    name: string,
    registered: ReadonlySet<string>,
    active: ReadonlyArray<string>,
  ) =>
    registered.has("mcp__t3-code__" + name) &&
    (isDeferred(name) || active.includes("mcp__t3-code__" + name));
  let catalog: ReadonlyArray<McpTool> = [];

  const client = createMcpClient(endpoint, token);
  let started: Promise<void> | undefined;

  const registerTools = () => {
    // Preserve public names for saved loadouts and tool selectors. The alias,
    // Pi's own MCP name for T3, reserves it against Pi's configured MCP servers.
    // model-only keeps it out of codemode; it hides its own declaration.
    const prefixes = supportsExposure ? ["mcp__t3-code__", ALIAS_PREFIX] : ["mcp__t3-code__"];
    readOnlyMcpTools.clear();
    for (const tool of catalog) {
      const name = tool.name;
      for (const prefix of prefixes) {
        const toolName = `${prefix}${name}`;
        if (tool.annotations?.readOnlyHint === true) readOnlyMcpTools.add(toolName);
        const isAlias = prefix === ALIAS_PREFIX;
        const exposure = isAlias ? "model-only" : isDeferred(name) ? "deferred" : "direct";
        pi.registerTool({
          name: toolName,
          label: name,
          // Pi records active declarations in the transcript even when hidden, and
          // estimates context from them. The model sees only the public schema;
          // T3's server still validates the arguments.
          description: isAlias ? "Same as mcp__t3-code__" + name + "." : (tool.description ?? name),
          parameters: jsonSchemaToTypebox(isAlias ? { type: "object" } : tool.inputSchema),
          ...(supportsExposure ? { outputSchema: mcpOutputSchema(tool) } : {}),
          ...(supportsExposure ? { exposure } : {}),
          ...(isAlias ? { prepareLoadout: () => ({ hiddenDeclarations: [toolName] }) } : {}),
          async execute(_toolCallId, params, signal) {
            // Another extension may switch the public tool off after reconciliation.
            if (
              isAlias &&
              !followsPublicTool(name, new Set(pi.getAllTools().map((tool) => tool.name)), pi.getActiveTools())
            ) {
              return { content: [{ type: "text", text: `Tool ${toolName} not found` }], details: {}, isError: true };
            }
            const result = await client.callTool(
              name,
              (params ?? {}) as Record<string, unknown>,
              signal,
            );
            const content = mcpModelContent(result);
            if (isMcpToolError(result) && !content.some((part) => part.type === "text" && part.text.length > 0)) {
              content.push({ type: "text", text: "MCP tool t3-code/" + name + " returned an error" });
            }
            return {
              content,
              structuredContent: mcpScriptResult(result),
              details: { server: "t3-code", tool: name },
              ...(isMcpToolError(result) ? { isError: true } : {}),
            };
          },
        });
      }
    }
  };

  const ensureStarted = () => {
    if (started !== undefined) return started;
    const attempt = (async () => {
      const signal = AbortSignal.timeout(10_000);
      await client.connect(signal);
      catalog = await client.listTools(signal);
      registerTools();
    })();
    started = attempt;
    void attempt.catch(() => {
      if (started === attempt) started = undefined;
    });
    return attempt;
  };

  // CLI extensions load before builtins, and Pi keeps the first registration
  // of a tool name. Register now so the bridge owns the T3 namespace even when
  // mcp.json configures it; retry a failed connection at session_start.
  await ensureStarted().catch(() => undefined);

  const reconcileDiscovery = (ctx: Pick<ExtensionContext, "model">) => {
    if (!supportsExposure) return;
    // A disabled or replaced search builtin cannot discover deferred tools.
    const hasToolSearch = hasBuiltinToolSearch();
    const exposureChanged = deferOptionalTools !== hasToolSearch;
    deferOptionalTools = hasToolSearch;
    if (exposureChanged) registerTools();
    // Completion gateways can silently drop calls to undeclared tools named
    // in history or guidance. Eagerly load T3 schemas, including after tree
    // restores, while retaining deferred exposure for Pi's allowlist rules.
    // Pi still applies --tools/--exclude-tools to this active loadout.
    const eagerSchemas = ctx.model?.api === "openai-completions";
    const required = [
      ...(hasToolSearch ? ["tool_search"] : []),
      ...(eagerSchemas ? catalog.map((tool) => "mcp__t3-code__" + tool.name) : []),
    ];
    const current = pi.getActiveTools();
    const missing = required.filter((name) => !current.includes(name));
    if (missing.length > 0) pi.setActiveTools([...current, ...missing]);
    // An alias is callable only while active, and Pi records every active
    // declaration in the transcript, hidden or not. Calls to the alias of an
    // active public tool are renamed at message_end instead. Once tool_search
    // loads a deferred tool, its alias is already in the transcript: dropping it
    // re-declares it in the prompt head, so the next request misses the cache.
    const registered = new Set(pi.getAllTools().map((tool) => tool.name));
    const loaded = pi.getActiveTools();
    const aliases = catalog
      .filter((tool) => registered.has(ALIAS_PREFIX + tool.name) &&
        followsPublicTool(tool.name, registered, loaded) &&
        (!loaded.includes("mcp__t3-code__" + tool.name) ||
          (!eagerSchemas && isDeferred(tool.name) && loaded.includes(ALIAS_PREFIX + tool.name))))
      .map((tool) => ALIAS_PREFIX + tool.name);
    const kept = loaded.filter((name) => !name.startsWith(ALIAS_PREFIX) || aliases.includes(name));
    const added = aliases.filter((name) => !loaded.includes(name));
    if (added.length > 0 || kept.length !== loaded.length) pi.setActiveTools([...kept, ...added]);
  };

  // Pi runs a message's tool calls after message_end handlers replace it.
  pi.on("message_end", (event) => {
    const message = event.message;
    if (!supportsExposure || message.role !== "assistant" || !Array.isArray(message.content)) return undefined;
    const active = pi.getActiveTools();
    let renamed = false;
    const content = message.content.map((part) => {
      if (part.type !== "toolCall" || !part.name.startsWith(ALIAS_PREFIX)) return part;
      const publicName = "mcp__t3-code__" + part.name.slice(ALIAS_PREFIX.length);
      if (!active.includes(publicName)) return part;
      renamed = true;
      return { ...part, name: publicName };
    });
    return renamed ? { message: { ...message, content } } : undefined;
  });

  // Tree navigation restores its saved loadout after session_start.
  pi.on("session_tree", (_event, ctx) => reconcileDiscovery(ctx));
  pi.on("model_select", (_event, ctx) => reconcileDiscovery(ctx));
  pi.on("session_start", async (_event, ctx) => {
    reconcileDiscovery(ctx);
    try {
      await ensureStarted();
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      ctx.ui.notify(`t3-code MCP unavailable: ${message}`, "warning");
    }
  });

  // Keep guidance in the system prompt so leading slash commands still expand.
  pi.on("before_agent_start", (event, ctx) => {
    reconcileDiscovery(ctx);
    const instructions = ORCHESTRATION_INSTRUCTIONS + "\n\n" + PULL_REQUEST_LINKING_INSTRUCTIONS;
    const sections = event.systemPromptOptions?.sections;
    if (sections && typeof sections === "object" && event.systemPromptOptions?.forceSystemPrompt === undefined) {
      // A full prompt override bypasses Pi's later section rendering.
      sections.t3_code_orchestration = instructions;
      return undefined;
    }
    return { systemPrompt: event.systemPrompt + "\n\n" + instructions };
  });
}
