import { URI as A } from "vscode-uri";
import { W as he } from "./workspace-connection-impl-Dee9nf40.js";
import * as S from "path";
import { a as u } from "./logger-CTb8_yz9.js";
import { h as Z, G as me } from "./get-user-input-Bp29a2Ky.js";
import "./prompt-DuC9mWRH.js";
import { z as C } from "zod";
import "os";
import { randomUUID as x } from "crypto";
import "dedent";
import { d as U, O as p } from "./shared-types-CIxCt9tj.js";
import "zod-stream";
import "./number-coercion-CeAOJ7Po.js";
import { I as fe, n as ge, R as we, q as ye, D as Ie, h as Pe, g as Se, S as Ce, e as Ae, b as Te, o as be, k as Ee, s as ke, u as xe, d as ee, W as ve, f as Ne, m as Re } from "./disclose-context-D8nDFuh2.js";
import { R as Me } from "./remote-tools-discovery-zcV7PSKX.js";
import { P as te, C as se } from "./pruning-service-DJ-mli7u.js";
import { b as _, T as $e } from "./telemetry-Bf0GI6nJ.js";
import { g as F, v as O } from "./validate-file-modification-DmMrabti.js";
import { a as oe } from "./tool-tags-NGeoUHCI.js";
import { NodeTaskService as Ue } from "./spec/tasks/index.js";
import { g as _e, U as Fe } from "./index-qeF2v9PW.js";
import { a as Oe, c as je, P as De } from "./pending-changes-BF3vCKkj.js";
import * as z from "fs";
import { a as Le } from "./cancellation-C60foDZK.js";
import { m as qe, f as We, e as ze, a as Be } from "./session-update-utils-S4kmZ2as.js";
import { CodeWhispererStreaming as ne, InvokeMCPCommand as B, MCPMethod as H } from "@aws/codewhisperer-streaming-client";
import { g as He, Q as Ge } from "./q-developer-converse-BT9F76b_.js";
import { L as Ke } from "./types-CkvOiUfs.js";
const Qe = (i) => typeof i == "object" && i !== null, Ye = (i) => typeof i == "object" && i !== null && "entries" in i, Je = (i) => typeof i == "object" && i !== null && "type" in i && "size" in i;
class Ve {
  constructor(e, t, s) {
    this.connection = e, this.sessionId = t, this.cwd = s;
  }
  /** Reads a text file via ACP, with optional line and limit parameters. */
  async readTextFile(e) {
    return this.connection.readTextFile({
      sessionId: this.sessionId,
      path: this.resolvePath(e.path),
      line: e.line,
      limit: e.limit
    });
  }
  /** Writes text content to a file via ACP. */
  async writeTextFile(e) {
    return this.connection.writeTextFile({
      sessionId: this.sessionId,
      path: this.resolvePath(e.path),
      content: e.content
    });
  }
  /** Returns file stat information via ACP extMethod. */
  async stat(e) {
    const s = await this.connection.extMethod("_kiro/fs/stat", {
      sessionId: this.sessionId,
      path: this.resolvePath(e)
    });
    if (!Je(s))
      throw new Error(`Invalid stat response: ${e}`);
    if (s.message)
      throw new Error(s.message);
    return { type: s.type };
  }
  /** Reads directory entries via ACP extMethod. */
  async readDirectory(e) {
    const s = await this.connection.extMethod("_kiro/fs/read_directory", {
      sessionId: this.sessionId,
      path: this.resolvePath(e)
    });
    if (!Ye(s))
      throw new Error(`Invalid readDirectory response: ${e}`);
    if (s.message)
      throw new Error(s.message);
    return s.entries.map((n) => ({
      name: n.name,
      type: n.type
    }));
  }
  /** Checks whether a file exists by attempting to stat it. */
  async exists(e) {
    try {
      return await this.stat(e), !0;
    } catch {
      return !1;
    }
  }
  /** Deletes a file via ACP extMethod. */
  async delete(e) {
    const s = await this.connection.extMethod("_kiro/fs/delete", {
      sessionId: this.sessionId,
      path: this.resolvePath(e)
    });
    if (!Qe(s))
      throw new Error(`Invalid delete response: ${e}`);
    if (s.message)
      throw new Error(s.message);
  }
  resolvePath(e) {
    return e.startsWith("/") || e.startsWith("~") ? e : `${this.cwd}/${e}`;
  }
}
class Xe {
  constructor(e, t) {
    this.connection = e, this.sessionId = t;
  }
  processes = /* @__PURE__ */ new Map();
  terminalHandles = /* @__PURE__ */ new Map();
  /** Starts a background process, reusing an existing one if it matches. */
  async startProcess(e, t, s) {
    for (const [a, c] of this.processes)
      if (c.command === t && c.cwd === s && c.status === "running")
        return { terminalId: a, isReused: !0, status: "running" };
    const n = t.split(/\s+/), o = await this.connection.createTerminal({
      sessionId: this.sessionId,
      command: n[0],
      args: n.slice(1),
      cwd: s
    }), r = `term_${Date.now()}_${Math.random().toString(36).slice(2)}`;
    return this.processes.set(r, { command: t, cwd: s, status: "running" }), this.terminalHandles.set(r, o), { terminalId: r, isReused: !1, status: "running" };
  }
  /** Stops a background process and releases its terminal handle. */
  async stopProcess(e, t) {
    const s = this.processes.get(t), n = this.terminalHandles.get(t);
    s && n && (await n.kill(), await n.release(), s.status = "stopped");
  }
  /** Returns the output of a background process, optionally limited to recent lines. */
  async getProcessOutput(e, t, s) {
    const n = this.terminalHandles.get(t);
    if (!n)
      return "";
    const o = await n.currentOutput();
    return s && s > 0 ? o.output.split(`
`).slice(-s).join(`
`) : o.output;
  }
  /** Returns the metadata for a single background process by terminal ID. */
  getProcess(e) {
    const t = this.processes.get(e);
    if (t)
      return { terminalId: e, ...t };
  }
  /** Lists all tracked background processes and their statuses. */
  listProcesses() {
    return Array.from(this.processes.entries()).map(([e, t]) => ({
      terminalId: e,
      ...t
    }));
  }
  /** No-op in ACP mode; terminals cannot be focused. */
  openTerminal(e) {
  }
}
function Ze(i, e, t) {
  const s = i.split(`
`), n = e.start?.line ?? 0, o = e.start?.character ?? 0, r = e.end?.line ?? s.length - 1, a = e.end?.character ?? (s[r] ? s[r].length : 0), c = s.slice(0, n).join(`
`) + (n > 0 ? `
` : "") + s[n].slice(0, o), l = (s[r]?.slice(a) ?? "") + (r < s.length - 1 ? `
` + s.slice(r + 1).join(`
`) : "");
  return c + t + l;
}
const et = {
  ts: "typescript",
  tsx: "typescriptreact",
  js: "javascript",
  jsx: "javascriptreact",
  py: "python",
  rs: "rust",
  go: "go",
  java: "java",
  rb: "ruby",
  md: "markdown",
  json: "json",
  yaml: "yaml",
  yml: "yaml"
};
function tt(i) {
  const e = i.split(".").pop()?.toLowerCase() ?? "";
  return et[e] ?? "plaintext";
}
class st {
  constructor(e, t, s, n) {
    this.persistence = e, this.fs = t, this.sessionId = s, this.workspacePaths = n;
  }
  /** Snapshots the file content via SessionPersistence and returns a kiro-snapshot:// URI. */
  async checkpointFile(e) {
    if (!this.persistence)
      return u.debug("[ACPCheckpointProvider] No persistence available, returning no-op checkpoint"), { commitId: "acp-no-checkpoint", uri: e.fileUri };
    const t = this.toRelativePath(e.fileUri.fsPath);
    let s;
    try {
      s = (await this.fs.readTextFile({ path: e.fileUri.fsPath })).content;
    } catch {
      s = "";
    }
    const n = await this.persistence.snapshotFile(this.sessionId, this.workspacePaths, t, s);
    u.debug(
      `[ACPCheckpointProvider] Created snapshot ${n.snapshotId} for ${t} (${s.length} bytes)`
    );
    const o = A.parse(
      `kiro-snapshot:///${t}?snapshotId=${n.snapshotId}&sessionId=${this.sessionId}`
    );
    return { commitId: n.snapshotId, uri: o };
  }
  toRelativePath(e) {
    const t = [...this.workspacePaths].sort((s, n) => n.length - s.length);
    for (const s of t)
      if (e.startsWith(s))
        return e.slice(s.length + 1);
    return e;
  }
}
class ot {
  constructor(e, t, s) {
    this.connection = e, this.sessionId = t, this.checkpointProvider = s;
  }
  /** Reads a file and returns its content along with language metadata. */
  async readFileWithMetadata(e) {
    const t = e.uri.fsPath, s = await this.connection.readTextFile({
      sessionId: this.sessionId,
      path: t,
      line: e.range?.start.line,
      limit: e.range ? e.range.end.line - e.range.start.line + 1 : void 0
    });
    return {
      content: {
        text: s.content,
        range: e.range ?? {
          start: { line: 0, character: 0 },
          end: { line: s.content.split(`
`).length - 1, character: 0 }
        }
      },
      metadata: {
        language: tt(t),
        problems: []
      }
    };
  }
  /** Writes file content, supporting both string and async iterable inputs. */
  async writeFileWithStreaming(e) {
    const t = e.uri.fsPath, s = this.checkpointProvider;
    let n;
    if (s && !e.skipCheckpointing)
      try {
        n = await s.checkpointFile({ fileUri: e.uri, filePath: t });
      } catch {
      }
    const o = (async () => {
      let r;
      if (typeof e.text == "string")
        r = e.text;
      else {
        const l = [];
        for await (const d of e.text)
          l.push(d);
        r = l.join("");
      }
      let a;
      if (e.range) {
        const l = await this.connection.readTextFile({ sessionId: this.sessionId, path: t });
        a = Ze(l.content, e.range, r);
      } else
        a = r;
      await this.connection.writeTextFile({
        sessionId: this.sessionId,
        path: t,
        content: a
      });
      let c;
      if (s && !e.skipCheckpointing)
        try {
          c = await s.checkpointFile({ fileUri: e.uri, filePath: t });
        } catch {
        }
      return {
        endCursorPosition: { line: a.split(`
`).length - 1, character: 0 },
        checkpointUri: c?.uri ?? e.uri
      };
    })();
    return {
      original: n?.uri,
      modified: e.uri,
      write: o
    };
  }
  /** No-op notification for created files in ACP mode. */
  notifyFilesCreated() {
  }
  /** No-op notification for deleted files in ACP mode. */
  notifyFilesDeleted() {
  }
}
class G {
  workspacePaths;
  constructor(e) {
    this.workspacePaths = e;
  }
  /**
   * resolveRelativePath given the workspace paths available.
   */
  resolveRelativePath(e) {
    if (S.isAbsolute(e) || e.startsWith("~"))
      return Promise.resolve(A.file(e));
    if (this.workspacePaths.length === 1)
      return Promise.resolve(A.file(S.join(this.workspacePaths[0], e)));
    for (const t of this.workspacePaths) {
      const s = S.basename(t), o = S.normalize(e).split(S.sep);
      if (o[0] === s) {
        const r = o.slice(1).join(S.sep);
        return Promise.resolve(A.file(S.join(t, r)));
      }
    }
    return Promise.resolve(A.file(S.join(this.workspacePaths[0], e)));
  }
  /**
   * Return a relative path that can later be resolved.
   */
  asRelativePath(e) {
    const t = e.path, s = [...this.workspacePaths].sort((n, o) => o.length - n.length);
    for (const n of s) {
      const o = A.file(n).path;
      if (t.startsWith(o + "/"))
        return t.slice(o.length + 1);
      if (t === o)
        return "";
    }
    return e.fsPath;
  }
}
class nt {
  constructor(e, t) {
    this.connection = e, this.sessionId = t;
  }
  nextId = 1;
  /** Creates or retrieves a terminal instance for command execution. */
  getOrCreateTerminal(e) {
    const t = this.nextId++;
    return Promise.resolve(new rt(this.connection, this.sessionId, t, e.cwd));
  }
}
class rt {
  constructor(e, t, s, n) {
    this.connection = e, this.sessionId = t, this.id = s, this.cwd = n;
  }
  isBusy = !1;
  isClosed = !1;
  async runCommand(e, t) {
    const s = e.split(/\s+/), n = await this.connection.createTerminal({
      sessionId: this.sessionId,
      command: s[0],
      args: s.slice(1),
      cwd: this.cwd
    }), o = await n.waitForExit(), r = await n.currentOutput();
    return await n.release(), {
      output: r.output,
      exitCode: o.exitCode ?? void 0,
      terminalId: this.id
    };
  }
  readOutputLines() {
    return "";
  }
  ensureCommandRunsInCwd(e, t) {
    return e;
  }
  close() {
  }
  focus() {
  }
}
function it() {
  return new Pe({
    validateContent: O,
    getStreamingTextPadForValidation: F
  });
}
function at() {
  return new Se({
    validateContent: O,
    getStreamingTextPadForValidation: F
  });
}
function ct() {
  return new Ce({
    validateContent: O,
    getStreamingTextPadForValidation: F
  });
}
function lt() {
  return new Ie({
    promptUser: () => (u.warn("[ACP] DeleteFile promptUser called - auto-accepting in ACP mode"), Promise.resolve("accept"))
  });
}
function re() {
  return new ge({
    // ACP mode: use default implementation (no recursive listing override)
  });
}
function ie() {
  return new we({
    pruneFileContent: async (i, e, t, s, n) => {
      try {
        const o = await te.pruneContent({
          content: i,
          contentType: se.Code,
          contextIdentifier: e,
          pruningReasoning: t,
          skipPruning: s,
          signal: n
        });
        return o.wasPruned ? o.prunedContent : i;
      } catch {
        return i;
      }
    }
  });
}
function ae() {
  return new ye({
    pruneFileContent: async (i, e, t, s, n) => {
      try {
        const o = await te.pruneContent({
          content: i,
          contentType: se.Code,
          contextIdentifier: e,
          pruningReasoning: t,
          skipPruning: s,
          signal: n
        });
        return o.wasPruned ? `${o.prunedContent}

<!-- File was automatically pruned from ${o.originalLength} to ${o.prunedLength} characters (${o.reductionPercentage.toFixed(1)}% reduction) based on context: "${t}" -->` : i;
      } catch {
        return i;
      }
    }
  });
}
function dt() {
  return [
    re(),
    ie(),
    ae(),
    lt(),
    it(),
    at(),
    ct()
  ];
}
const pt = _(U.Tool, "execute-bash"), ut = _(U.Tool, "control-process");
function ht(i) {
  return new Ae(
    { configuredTimeout: void 0, isSingleRootWorkspace: !0 },
    {
      acpToolApproval: i,
      recordBashToolEvent: () => {
      },
      recordMetricTrace: (e) => pt.callWithTrace(e, () => {
      })
    }
  );
}
function mt(i, e, t) {
  return new Te(
    i,
    e,
    { isSingleRootWorkspace: !0 },
    {
      acpToolApproval: t,
      validateFileAccess: () => {
      },
      checkDirectoryExists: () => Promise.resolve(!0),
      recordBashToolEvent: () => {
      },
      recordMetricTrace: (s) => ut.callWithTrace(s, () => {
      })
    }
  );
}
function ft(i, e) {
  return new be(i, e);
}
function gt(i, e) {
  return new Ee(i, e);
}
function wt(i, e, t) {
  return [
    ht(t),
    mt(i, e, t),
    ft(i, e),
    gt(i, e)
  ];
}
function yt(i) {
  return new ve({
    acpToolApproval: i,
    userAgent: "KiroACP"
  });
}
function It(i, e) {
  const t = [];
  return e && t.push(...e.getCachedTools()), t.push(yt(i)), t;
}
function K(i, e, t, s) {
  return [
    ...dt(),
    ...wt(i, e, t),
    ...It(t, s)
  ];
}
function R(i, e = !1, t) {
  return new fe(
    {
      registry: i,
      generateOperationId: (s) => `${s}_${x()}`,
      contextProviderRegistry: t
    },
    e
  );
}
const Pt = {
  isToolTrusted: () => !0,
  trustTool: () => Promise.resolve(),
  trustWebTools: () => Promise.resolve()
};
function St(i) {
  return {
    mcpClient: i,
    toolTrustManager: Pt,
    awaitCommandApproval: () => Promise.resolve("accept")
  };
}
function fs(i) {
  return new Me({
    mcpClient: i,
    createToolOptions: () => St(i)
  });
}
function Ct() {
  return new ke();
}
function At() {
  return new xe();
}
function Tt() {
  return [Ct(), At()];
}
function Q(i) {
  return new ee(i);
}
function bt(i, e) {
  return {
    async findFiles(t, s, n) {
      try {
        return (await i.extMethod("_kiro/search/find_files", {
          sessionId: e,
          pattern: t,
          exclude: s ?? void 0,
          maxResults: n
        })).files;
      } catch (o) {
        return u.warn("[ACP FileSearch] extMethod call failed:", o), [];
      }
    }
  };
}
function Et(i, e) {
  return {
    async search(t) {
      try {
        return (await i.extMethod("_kiro/search/text_search", {
          sessionId: e,
          pattern: t.pattern,
          caseSensitive: t.caseSensitive,
          includePattern: t.includePattern,
          excludePattern: t.excludePattern
        })).matches;
      } catch (s) {
        return u.warn("[ACP GrepSearch] extMethod call failed:", s), [];
      }
    }
  };
}
class j extends Z {
  constructor(e, t) {
    super({
      id: e.sanitizedUniqueName,
      description: e.description || `Use the ${e.toolName} tool`,
      schema: e.inputSchema,
      validationSchema: C.object({}),
      tags: [`@${e.serverName}/${e.toolName}`, `@${e.serverName}`, oe.MCP]
    }), this.toolConfig = e, this.getConnection = t;
  }
  /** Invokes the MCP tool via the session-scoped connection. */
  async handle({
    input: e,
    state: t,
    toolUse: s
  }) {
    const n = this.getConnection(this.toolConfig.serverName);
    if (!n)
      return this.withSyncToolMessage(
        t,
        s,
        `MCP server "${this.toolConfig.serverName}" is not connected`,
        !1
      );
    try {
      const o = { ...e };
      delete o._meta;
      const r = await n.mcpClient.callTool({
        name: this.toolConfig.toolName,
        arguments: o
      }), a = "content" in r && Array.isArray(r.content) ? r.content : [], { textResults: c, imageBase64UrlResults: l } = j.parseResponseContent(a), d = c.join(`
`);
      return r.isError ? this.withSyncToolMessage(t, s, `MCP tool error: ${d}`, !1) : this.withSyncToolMessage(
        t,
        s,
        d,
        !0,
        l.length > 0 ? l : void 0
      );
    } catch (o) {
      const r = o instanceof Error ? o.message : String(o);
      return u.error(`[MCP] [${this.toolConfig.serverName}] Tool call failed: ${r}`), this.withSyncToolMessage(t, s, `MCP tool call failed: ${r}`, !1);
    }
  }
  /** Parses MCP response content into text and image results. */
  static parseResponseContent(e) {
    const t = [], s = [];
    for (const n of e) {
      if (typeof n != "object" || n === null || !("type" in n))
        continue;
      const o = n;
      switch (o.type) {
        case "text":
          typeof o.text == "string" && t.push(o.text);
          break;
        case "image":
          typeof o.mimeType == "string" && typeof o.data == "string" && s.push(`data:${o.mimeType};base64,${o.data}`);
          break;
        case "resource": {
          const r = o.resource;
          if (!r) break;
          if (typeof r.text == "string")
            t.push(r.text);
          else if (typeof r.blob == "string") {
            const a = r.mimeType;
            a?.startsWith("image/") ? s.push(`data:${a};base64,${r.blob}`) : a?.startsWith("text/") || a === "application/json" ? t.push(Buffer.from(r.blob, "base64").toString("utf-8")) : u.error(`[MCP] Unsupported resource mime type: ${a}`);
          }
          break;
        }
        default:
          u.error(`[MCP] Unsupported response content type: ${String(o.type)}`);
          break;
      }
    }
    return { textResults: t, imageBase64UrlResults: s };
  }
}
class kt {
  constructor(e, t, s, n) {
    this.provider = e, this.persistence = t, this.sessionId = s, this.workspacePaths = n;
  }
  /** Snapshots the file and returns a checkpoint result. */
  async commitFile(e, t) {
    const s = await this.provider.checkpointFile({ fileUri: t, filePath: t.fsPath });
    return { commitId: s.commitId, uri: s.uri };
  }
  /** Reads file content from a previously stored snapshot. */
  async getFileContentAtCommit(e, t) {
    return this.persistence ? await this.persistence.getSnapshotContent(
      this.sessionId,
      this.workspacePaths,
      t,
      e
    ) ?? void 0 : void 0;
  }
  /** Builds a kiro-snapshot URI for diff display. */
  buildDiffUri(e, t, s) {
    const n = e.startsWith("/") ? e : "/" + e;
    return A.from({
      scheme: "kiro-snapshot",
      path: n,
      query: `snapshotId=${t}&executionId=${s}`
    });
  }
}
class xt {
  constructor(e, t, s, n, o) {
    this.fs = e, this.resolver = t, this.persistence = s, this.sessionId = n, this.workspacePaths = o;
  }
  /** Reads file content as bytes. Handles kiro-snapshot URIs by reading from snapshot store. */
  async readFile(e) {
    if (e.scheme === "kiro-snapshot" && this.persistence) {
      const s = new URLSearchParams(e.query).get("snapshotId"), n = e.path.startsWith("/") ? e.path.substring(1) : e.path;
      if (s) {
        const o = await this.persistence.getSnapshotContent(
          this.sessionId,
          this.workspacePaths,
          s,
          n
        );
        return new TextEncoder().encode(o ?? "");
      }
    }
    const t = await this.fs.readTextFile({ path: e.fsPath });
    return new TextEncoder().encode(t.content);
  }
  /** Writes byte content to a file. */
  async writeFile(e, t) {
    const s = new TextDecoder().decode(t);
    await this.fs.writeTextFile({ path: e.fsPath, content: s });
  }
  /** Deletes a file. */
  async deleteFile(e) {
    await this.fs.delete(e.fsPath);
  }
  /** Renames a file via read+write+delete (ACP has no native rename). */
  async rename(e, t) {
    const s = await this.readFile(e);
    await this.writeFile(t, s), await this.deleteFile(e);
  }
  /** Checks whether a file exists. Snapshot URIs check the snapshot store. */
  async exists(e) {
    if (e.scheme === "kiro-snapshot" && this.persistence) {
      const t = new URLSearchParams(e.query).get("snapshotId"), s = e.path.startsWith("/") ? e.path.substring(1) : e.path;
      if (t)
        return await this.persistence.getSnapshotContent(
          this.sessionId,
          this.workspacePaths,
          t,
          s
        ) !== null;
    }
    return this.fs.exists(e.fsPath);
  }
  /** Resolves a relative path to a workspace URI. */
  async resolveWorkspacePath(e) {
    return this.resolver.resolveRelativePath(e);
  }
}
class vt {
  actions = /* @__PURE__ */ new Map();
  /** Records or updates a file action for later retrieval by PendingChangesService. */
  trackAction(e, t) {
    const s = this.actions.get(e) ?? [], n = s.findIndex((o) => o.actionId === t.actionId);
    n >= 0 ? s[n] = t : s.push(t), this.actions.set(e, s);
  }
  /** Returns tracked actions for an execution. */
  getExecution(e) {
    const t = this.actions.get(e);
    return Promise.resolve(t ? { actions: t } : void 0);
  }
  /** Clears tracked actions for an execution. */
  clear(e) {
    this.actions.delete(e);
  }
}
var Nt = Object.defineProperty, Rt = Object.getOwnPropertyDescriptor, Mt = (i, e, t, s) => {
  for (var n = Rt(e, t), o = i.length - 1, r; o >= 0; o--)
    (r = i[o]) && (n = r(e, t, n) || n);
  return n && Nt(e, t, n), n;
};
const $t = C.object({
  action: C.enum(["list", "activate", "use", "readSteering", "configure"]).describe(
    'The action to perform: "list" to discover installed powers, "activate" to get documentation, "use" to execute power tools, "readSteering" for guides, "configure" to open config file'
  ),
  powerName: C.string().optional().nullable().describe("Name of the power (required for activate, use, readSteering actions; not used for list or configure)"),
  serverName: C.string().optional().nullable().describe(
    "Name of the MCP server within the power (REQUIRED for use action - get from toolsByServer in activate response)"
  ),
  toolName: C.string().optional().nullable().describe("Name of the tool to execute within the power (required for use action)"),
  arguments: C.record(C.any()).optional().nullable().describe("Arguments object for the tool being called (use action only, get schema from activate action)"),
  steeringFile: C.string().optional().nullable().describe(
    "Name of the steering file to read (REQUIRED for readSteering action - get from steeringFiles array in activate response, including .md extension)"
  )
}), Y = _(U.Tool, "Tool.KiroPowers");
function J(i, e) {
  return `power-${i}-${e}`;
}
const ce = class $ extends Z {
  static toolId = "kiroPowers";
  powersManager;
  mcpManager;
  homeDir;
  constructor(e, t, s) {
    super({
      id: $.toolId,
      description: $.generateDescription(e),
      schema: $t,
      tags: [oe.POWERS]
    }), this.powersManager = e, this.mcpManager = t, this.homeDir = s;
  }
  /**
   * Generates a dynamic description listing all installed powers.
   */
  static generateDescription(e) {
    const t = e.getInstalledPowers();
    let s = `Tool to manage and use Kiro Powers.

**About Powers:** Powers package documentation, workflow guides (steering files), and optionally MCP servers. When a power includes MCP servers, their tools are accessed through this interface rather than exposed directly.

`;
    if (t.length === 0)
      s += `**Currently Installed Powers:** None

No powers are installed. Use action="configure" to open the powers management panel.

`;
    else {
      s += `**Currently Installed Powers:**

`;
      for (const n of t)
        s += `• **${n.name}**
  ${n.description}
`, n.keywords.length > 0 && (s += `  Keywords: ${n.keywords.join(", ")}
`), n.mcpServerNames.length > 0 && (s += `  MCP Servers: ${n.mcpServerNames.join(", ")}
`), s += `
`;
      s += `**IMPORTANT: Call action="activate" with a powerName before using any power to understand its tools and parameters.**

`;
    }
    return s += `# ACTIONS:

1. **LIST** ("list") - See all installed powers
   Returns: Formatted list with names, descriptions, keywords, and MCP servers

2. **ACTIVATE** ("activate") - Get comprehensive power documentation
   Parameters: powerName (required)
   Returns: POWER.md content, available tools grouped by server with schemas, and steering file list

3. **USE** ("use") - Execute a tool from a power's MCP server
   Parameters: powerName, serverName, toolName, arguments (all required)
   **CRITICAL:** You MUST call action="activate" first to get serverName from toolsByServer

4. **READ_STEERING** ("readSteering") - Get detailed workflow guides
   Parameters: powerName, steeringFile (both required)

5. **CONFIGURE** ("configure") - Open powers management panel
   Returns: Success message indicating the panel should be opened

**CRITICAL RULES:**
- NEVER call action="use" without calling action="activate" first
- Tool names and input schemas come from the activate response
- Power names are case-sensitive`, s;
  }
  async handle({
    input: e,
    state: t,
    toolUse: s,
    actionId: n
  }) {
    const o = Date.now();
    try {
      let r, a;
      switch (e.action) {
        case "list":
          r = this.handleListPowers(e, t, n, o), a = typeof r == "object" && "formattedList" in r && typeof r.formattedList == "string" ? r.formattedList : `Found ${typeof r == "object" && "total" in r ? String(r.total) : "0"} powers`;
          break;
        case "activate":
          if (r = await this.handleActivatePower(e, t, n, o), typeof r == "object" && "toolsByServer" in r) {
            const l = r;
            let d = "";
            if (Object.keys(l.toolsByServer).length > 0) {
              d += `**Available Tools by Server:**

`;
              for (const [m, h] of Object.entries(l.toolsByServer)) {
                if (d += `**Server: \`${m}\`**

`, Array.isArray(h) && h.length > 0)
                  for (const w of h) {
                    if (d += `• **${w.name}**`, w.description && (d += ` - ${w.description}`), d += `
`, w.inputSchema && typeof w.inputSchema == "object" && "properties" in w.inputSchema) {
                      const T = w.inputSchema;
                      if (T.properties) {
                        d += `  Parameters:
`;
                        for (const [y, I] of Object.entries(T.properties)) {
                          const v = T.required?.includes(y);
                          d += `    - \`${y}\`${v ? " (required)" : " (optional)"}`, typeof I == "object" && I !== null && "type" in I && typeof I.type == "string" && (d += `: ${I.type}`), typeof I == "object" && I !== null && "description" in I && typeof I.description == "string" && (d += ` - ${I.description}`), d += `
`;
                        }
                      }
                    }
                    d += `
`;
                  }
                else
                  d += `  (No tools available)

`;
                d += `
`;
              }
            }
            l.steeringFiles.length > 0 && (d += `**Steering Files:** ${l.steeringFiles.join(", ")}

`), l.overview && (d += `---

`, d += l.overview), a = d;
          } else
            a = `No documentation available for power: ${e.powerName ?? "unknown"}`;
          break;
        case "use":
          if (r = await this.handleUsePower(e, t, n, o), typeof r == "object" && "content" in r && Array.isArray(r.content)) {
            const l = r.content, d = [];
            for (const f of l)
              f && typeof f == "object" && "type" in f && f.type === "text" && "text" in f && typeof f.text == "string" && d.push(f.text);
            a = d.length > 0 ? d.join(`
`) : `Executed tool ${e.toolName ?? "unknown"} from power ${e.powerName ?? "unknown"}`;
          } else
            a = `Executed tool ${e.toolName ?? "unknown"} from power ${e.powerName ?? "unknown"}`;
          break;
        case "readSteering":
          r = await this.handleReadSteering(e, t, n, o), a = `**Steering Guide: ${String(r.fileName)}**

${String(r.content)}`;
          break;
        case "configure":
          r = this.handleConfigurePower(e, t, n, o), a = "Use the Powers panel in the sidebar to manage powers.";
          break;
        default:
          throw new Error(`Unknown action: ${"action" in e ? String(e.action) : "undefined"}`);
      }
      Y.reportCountMetrics({ [`kiroPowers_${e.action}_success`]: 1 });
      const { state: c } = this.withSyncToolMessage(t, s, a, !0);
      return {
        state: c,
        output: r
      };
    } catch (r) {
      const a = r instanceof Error ? r.message : String(r);
      u.error("[KiroPowers] Error:", { action: e.action, error: a }), Y.reportCountMetrics({ [`kiroPowers_${e.action}_error`]: 1 });
      const { state: c } = this.withSyncToolMessage(t, s, a, !1);
      return {
        state: c,
        output: {
          success: !1,
          message: a
        }
      };
    }
  }
  /**
   * Create event emitter function for a power action
   */
  createEventEmitter(e, t, s, n) {
    return (o, r) => {
      t.execution.emit({
        type: "AgentExecutionAction",
        executionId: t.execution.executionId,
        actionId: s,
        actionState: o,
        actionType: "kiroPower",
        input: {
          action: e.action,
          powerName: e.powerName,
          toolName: e.toolName,
          arguments: e.arguments
        },
        output: r,
        startTime: n,
        endTime: o === p.Success || o === p.Error || o === p.Rejected ? Date.now() : void 0
      });
    };
  }
  /**
   * Handle LIST action - list installed powers with formatted descriptions
   */
  handleListPowers(e, t, s, n) {
    const o = this.createEventEmitter(e, t, s, n);
    o(p.Running);
    const r = this.powersManager.getInstalledPowers();
    let a = "";
    if (r.length === 0)
      a = `**No powers installed**

`, a += `You have no powers installed yet.

`, a += `**To get started:**

`, a += `• Use action="configure" to open the powers UI

`, a += `• Browse and install available powers

`, a += `• Or ask me to help you find and install a power
`;
    else {
      a += `**Installed Powers (${r.length}):**

`;
      for (const l of r)
        a += `• **${l.name}**
`, a += `  ${l.description}
`, l.keywords.length > 0 && (a += `  Keywords: ${l.keywords.join(", ")} — **If you see any of these words in the user's message, strongly consider activating this power immediately!**
`), l.mcpServerNames.length > 0 && (a += `  MCP Servers: ${l.mcpServerNames.join(", ")}
`), a += `
`;
      a += `**How to use powers:**
`, a += `1. **Activate first**: Use action="activate" with powerName to understand the power
`, a += `2. **Then use**: Use action="use" with powerName, serverName, toolName, and arguments
`, a += `3. **Read guides**: Use action="readSteering" for step-by-step workflows
`;
    }
    const c = {
      powers: r,
      total: r.length,
      formattedList: a
    };
    return o(p.Success, { response: a }), c;
  }
  /**
   * Handle ACTIVATE action - get comprehensive power documentation
   */
  async handleActivatePower(e, t, s, n) {
    if (!e.powerName)
      throw new Error("powerName is required for activate action");
    const o = this.createEventEmitter(e, t, s, n);
    o(p.Running);
    const a = this.powersManager.getInstalledPowers().find((m) => m.name === e.powerName);
    if (!a)
      throw new Error(`Power '${e.powerName}' is not installed`);
    const c = await this.powersManager.getPowerDocumentation(e.powerName) ?? "", l = {};
    for (const m of a.mcpServerNames) {
      const h = J(e.powerName, m), T = this.mcpManager.getTools().filter((y) => y.serverName === h && !y.disabled);
      l[m] = T.map((y) => ({
        name: y.toolName,
        description: y.description,
        inputSchema: y.inputSchema
      }));
    }
    const d = await this.powersManager.getSteeringFiles(e.powerName), f = {
      powerName: e.powerName,
      displayName: a.displayName ?? e.powerName,
      description: a.description,
      keywords: a.keywords,
      overview: c,
      steeringFiles: d,
      toolsByServer: l
    };
    return o(p.Success, { response: JSON.stringify(f) }), f;
  }
  /**
   * Handle USE action - execute a tool from a power's MCP server
   */
  async handleUsePower(e, t, s, n) {
    if (!e.powerName)
      throw new Error("powerName is required for use action");
    if (!e.serverName)
      throw new Error(
        'serverName is required for use action. Call action="activate" first to discover available servers from toolsByServer.'
      );
    if (!e.toolName)
      throw new Error("toolName is required for use action");
    const o = this.createEventEmitter(e, t, s, n), a = this.powersManager.getInstalledPowers().find((m) => m.name === e.powerName);
    if (!a)
      throw new Error(`Power '${e.powerName}' is not installed`);
    if (!a.mcpServerNames.includes(e.serverName))
      throw new Error(
        `Server '${e.serverName}' not found in power '${e.powerName}'. Available servers: ${a.mcpServerNames.join(", ")}. Call action="activate" to see toolsByServer.`
      );
    const c = J(e.powerName, e.serverName), l = this.mcpManager.getConnection(c);
    if (!l?.mcpClient)
      throw new Error(`MCP server '${c}' is not connected`);
    if (!await this.isPowerToolApproved(c, e.toolName)) {
      try {
        await t.execution.acquireYield("kiro-powers");
      } catch (h) {
        const w = `Power tool cannot proceed: ${h instanceof Error ? h.message : String(h)}`;
        throw o(p.Error, { error: w }), new Error(w);
      }
      o(p.PendingAction);
      let m;
      try {
        const h = Oe();
        m = await Le(h.awaitApproval(s), t.execution.abortController.signal);
      } catch {
        m = !1;
      } finally {
        try {
          await t.execution.releaseYield("kiro-powers");
        } catch {
        }
      }
      if (!m) {
        const h = `Tool execution denied. Tool '${e.toolName}' from power '${e.powerName}' requires your approval.`;
        throw o(p.Rejected, { response: h }), new Error(h);
      }
    }
    o(p.Running);
    const f = await l.mcpClient.callTool(
      {
        name: e.toolName,
        arguments: e.arguments || {}
      },
      void 0,
      {
        timeout: 864e5
        // 24 hours
      }
    );
    if (f.isError && f.content) {
      const m = JSON.stringify(f.content).toLowerCase();
      if (m.includes("not enabled") || m.includes("not found") || m.includes("unknown")) {
        const h = `Tool '${e.toolName}' does not exist on server '${c}'.

You must call action="activate" with powerName="${e.powerName}" first to learn about available tools and their parameters.`;
        return o(p.Error, { error: h }), {
          content: [
            {
              type: "text",
              text: h
            }
          ],
          isError: !0
        };
      }
    }
    return o(p.Success, { result: f }), f;
  }
  /**
   * Handle READ_STEERING action - read workflow guides
   */
  async handleReadSteering(e, t, s, n) {
    if (!e.powerName)
      throw new Error("powerName is required for readSteering action");
    if (!e.steeringFile)
      throw new Error(
        'steeringFile is required for readSteering action. Call action="activate" first to get the steeringFiles array.'
      );
    if (!this.powersManager.getInstalledPowers().find((d) => d.name === e.powerName))
      throw new Error(`Power '${e.powerName}' is not installed`);
    const a = this.createEventEmitter(e, t, s, n);
    a(p.Running);
    const c = await this.powersManager.getSteeringContent(e.powerName, e.steeringFile);
    if (!c)
      throw new Error(`Steering file '${e.steeringFile}' not found for power '${e.powerName}'`);
    const l = {
      content: c,
      fileName: e.steeringFile,
      powerName: e.powerName
    };
    return a(p.Success, { response: c, fileName: e.steeringFile }), l;
  }
  /**
   * Handle CONFIGURE action - open powers management panel
   */
  handleConfigurePower(e, t, s, n) {
    const o = this.createEventEmitter(e, t, s, n);
    o(p.Running);
    const r = {
      success: !0,
      message: "Use the Powers panel in the sidebar to manage powers."
    };
    return o(p.Success, { response: JSON.stringify(r) }), r;
  }
  /**
   * Check if a power tool is auto-approved in ~/.kiro/settings/mcp.json.
   * Returns true if the tool is in the autoApprove list (or wildcard '*'), false otherwise.
   */
  async isPowerToolApproved(e, t) {
    try {
      const s = S.join(this.homeDir, ".kiro", "settings", "mcp.json");
      if (!z.existsSync(s))
        return !1;
      const n = await z.promises.readFile(s, "utf-8"), o = JSON.parse(n);
      if (o && typeof o == "object" && "powers" in o && o.powers && typeof o.powers == "object" && "mcpServers" in o.powers) {
        const a = (o.powers.mcpServers && typeof o.powers.mcpServers == "object" ? o.powers.mcpServers : {})[e];
        if (!a || typeof a != "object")
          return !1;
        const c = "autoApprove" in a && Array.isArray(a.autoApprove) ? a.autoApprove : [];
        return c.includes(t) || c.includes("*");
      }
      return !1;
    } catch {
      return !1;
    }
  }
};
Mt([
  $e.Trace("Tool.KiroPowers")
], ce.prototype, "handle");
let M = ce;
function gs(i) {
  const {
    connection: e,
    sessionId: t,
    workspacePaths: s,
    machineId: n = "acp-client",
    customAgentRegistry: o,
    clientTools: r = [],
    mcpManager: a,
    steeringProvider: c,
    remoteToolsDiscovery: l,
    persistence: d,
    contextProviderRegistry: f,
    progressiveContextManager: m,
    powersManager: h,
    homeDir: w
  } = i, T = s[0] ?? ".", y = new Ve(e, t, T), I = new Xe(e, t), v = s.map((g) => A.file(g)), de = new Ue(y);
  let E = m ? r.filter((g) => g.id !== ee.toolId) : r;
  h && (E = E.filter((g) => g.id !== M.toolId));
  const D = () => {
    if (!a) return [];
    const g = (P) => a.getConnection(P);
    return a.getTools().map((P) => new j(P, g));
  }, N = new st(d, y, t, s), L = new vt(), pe = new De(
    new kt(N, d, t, s),
    new xt(
      y,
      new G(s),
      d,
      t,
      s
    ),
    L
  );
  je(pe);
  const q = async (g) => {
    u.info(
      `[ACP ToolApproval] Requesting permission for toolId=${g.toolId}, operationId=${g.operationId}, sessionId=${t}`
    );
    try {
      const P = await e.requestPermission({
        sessionId: t,
        toolCall: {
          toolCallId: g.operationId,
          status: "pending",
          title: g.command ?? g.toolId
        },
        options: [
          { optionId: "accept", name: "Allow", kind: "allow_once" },
          { optionId: "always-accept", name: "Always allow", kind: "allow_always" },
          { optionId: "reject", name: "Deny", kind: "reject_once" }
        ],
        _meta: {
          kiro: {
            toolId: g.toolId,
            ...g.command && { command: g.command }
          }
        }
      });
      if (u.info(`[ACP ToolApproval] Got response: ${JSON.stringify(P.outcome)}`), P.outcome.outcome === "selected") {
        const b = P.outcome.optionId;
        return b === "accept" || b === "always-accept" ? "accept" : "reject";
      }
      return "reject";
    } catch (P) {
      return u.error("[ACP ToolApproval] requestPermission failed:", P), "reject";
    }
  }, ue = {
    workspaceFolders: v,
    machineId: n,
    fs: y,
    terminalManager: new nt(e, t),
    backgroundProcessManager: I,
    steeringProvider: c,
    taskProvider: de,
    checkpointProvider: N,
    fileOperationsProvider: new ot(e, t, N),
    workspaceResolver: new G(s),
    getTools: (g) => {
      const P = [
        new Ne(bt(e, t)),
        new Re(Et(e, t))
      ], b = [
        ...K(I, t, q, l),
        ...P,
        ...E,
        ...D()
      ];
      o && b.push(R(o, !1, f)), m && b.push(Q(m)), h && a && w && b.push(new M(h, a, w));
      const k = [
        ..._e(g),
        ...K(I, t, q, l),
        ...P,
        ...E,
        ...D()
      ];
      o && k.push(R(o, !0)), m && k.push(Q(m)), h && a && w && k.push(new M(h, a, w));
      const W = [
        new me(),
        new Fe(),
        re(),
        ie(),
        ae(),
        ...P
      ];
      return o && W.push(R(o, !0)), {
        chat: b,
        specAgent: k,
        specOrchestrator: W,
        // Subagent tools should only include subagent-specific coordination tools.
        // General-purpose tools come from getSpecAgentTools() (filtered by allowedTools)
        // in SubAgentGraph, matching VSCode behavior.
        subAgent: Tt()
      };
    }
  };
  return { workspace: new he(ue), executionLog: L };
}
function Ut(i) {
  return i >= 95 ? "critical" : i >= 80 ? "warning" : "normal";
}
function V(i) {
  return typeof i == "object" && i !== null && "message" in i;
}
function _t(i) {
  return i === "cancelled" ? "aborted" : i === "refusal" ? "failed" : "success";
}
const Ft = /* @__PURE__ */ new Set([
  "model",
  "label",
  "intentClassification",
  "retry",
  "compact",
  "submit",
  "userApproval",
  "displayError",
  "specAgent",
  "do",
  "ContextualHookInvoked",
  "reportProgress"
]);
function X(i) {
  switch (i) {
    case p.Running:
      return "in_progress";
    case p.Success:
    case p.Accepted:
      return "completed";
    case p.Error:
    case p.HandledError:
    case p.Canceled:
    case p.Rejected:
      return "failed";
    default:
      return "pending";
  }
}
class ws {
  connection;
  sessionId;
  workspacePaths;
  persistence;
  subscriptionId;
  sayContentByActionId = /* @__PURE__ */ new Map();
  reasoningContentByActionId = /* @__PURE__ */ new Map();
  fullResponse = "";
  executionId = x();
  persistenceSuppressed = !1;
  emittedToolCallIds = /* @__PURE__ */ new Set();
  controller;
  pendingPersistence = [];
  /** Tracks the executionId that belongs to this adapter's session. */
  ownedExecutionId;
  /** Stores summary from Action(Success) until SummarizationComplete arrives with sessionTitle */
  pendingSummarization;
  constructor(e) {
    this.connection = e.connection, this.sessionId = e.sessionId, this.workspacePaths = e.workspacePaths, this.persistence = e.persistence;
  }
  /** Subscribes to AgentController events and forwards them to ACP. */
  subscribe(e) {
    this.controller = e, this.subscriptionId = e.subscribeToEvents((t) => {
      this.handleEvent(t);
    });
  }
  /** Unsubscribes from AgentController events. */
  unsubscribe(e) {
    this.subscriptionId && (e.unsubscribeFromEvents(this.subscriptionId), this.subscriptionId = void 0);
  }
  /** Sets the executionId that this adapter should process events for. */
  setOwnedExecutionId(e) {
    this.ownedExecutionId = e;
  }
  /** Resets the response tracking for a new execution. */
  resetForNewExecution() {
    this.sayContentByActionId.clear(), this.reasoningContentByActionId.clear(), this.fullResponse = "", this.executionId = x(), this.emittedToolCallIds.clear(), this.pendingPersistence = [];
  }
  /** Gets the full response text accumulated during execution. */
  getFullResponse() {
    return this.fullResponse;
  }
  /** Suppresses persistence writes. Used during session replay. */
  suppressPersistence() {
    this.persistenceSuppressed = !0;
  }
  /** Resumes persistence writes after replay completes. */
  resumePersistence() {
    this.persistenceSuppressed = !1;
  }
  /** Persists the accumulated assistant message and session event on prompt completion. */
  async onPromptComplete(e) {
    if (this.persistenceSuppressed)
      return;
    this.pendingPersistence.length > 0 && (await Promise.allSettled(this.pendingPersistence), this.pendingPersistence = []);
    const t = [];
    if (this.fullResponse && t.push({
      id: x(),
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      payload: {
        type: "assistant",
        content: this.fullResponse,
        operationType: "Say",
        executionId: this.executionId
      }
    }), t.push({
      id: `${this.executionId}-complete`,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      payload: {
        type: "session_event",
        category: "session_pause",
        context: { executionId: this.executionId, status: _t(e) }
      }
    }), t.length > 0)
      try {
        await this.persistence.appendMessages(this.sessionId, this.workspacePaths, t);
      } catch (s) {
        u.warn("[ACPEventAdapter] Failed to persist messages", {
          sessionId: this.sessionId,
          error: s instanceof Error ? s.message : String(s)
        });
      }
  }
  isOwnedEvent(e) {
    return !this.ownedExecutionId || e.executionId === this.ownedExecutionId;
  }
  handleEvent(e) {
    switch (e.type) {
      case "AgentExecutionBegan":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution began: ${e.executionId}`), this.resetForNewExecution(), this.pendingSummarization = void 0;
        break;
      case "AgentExecutionSuccess":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution succeeded: ${e.executionId}`);
        break;
      case "AgentExecutionFailed":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution failed: ${e.executionId}`);
        break;
      case "AgentExecutionAborted":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution aborted: ${e.executionId}`);
        break;
      case "AgentExecutionYielded":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution yielded: ${e.executionId}`);
        break;
      case "AgentExecutionResumed":
        if (!this.isOwnedEvent(e)) return;
        u.info(`[ACPEventAdapter] Execution resumed: ${e.executionId}`);
        break;
      case "AgentExecutionAction":
        if (!this.isOwnedEvent(e)) return;
        this.handleActionEvent(e);
        break;
      case "AgentExecutionContextUsageUpdate":
        if (!this.isOwnedEvent(e)) return;
        this.handleContextUsageUpdate(e);
        break;
      case "AgentExecutionSummarizationComplete":
        if (!this.isOwnedEvent(e)) return;
        this.handleSummarizationComplete(e);
        break;
      case "AgentExecutionErrorOccurred":
        if (!this.isOwnedEvent(e)) return;
        this.handleErrorOccurred(e);
        break;
    }
  }
  handleActionEvent(e) {
    if (!Ft.has(e.actionType))
      switch (e.actionType) {
        case "say":
          this.handleSayAction(e);
          break;
        case "reasoning":
          this.handleReasoningAction(e);
          break;
        case "steering":
          this.handleSteeringAction(e);
          break;
        case "invokeSubAgent":
          this.handleSubAgentAction(e);
          break;
        case "summarization":
          this.handleSummarizationAction(e);
          break;
        case "userMessage":
          break;
        case "userInput":
          this.handleUserInputAction(e);
          break;
        default:
          this.handleToolAction(e);
          break;
      }
  }
  handleSayAction(e) {
    if (V(e.output)) {
      const t = this.sayContentByActionId.get(e.actionId) ?? "", s = e.output.message.slice(t.length);
      s && (this.sayContentByActionId.set(e.actionId, e.output.message), e.subExecutionId || (this.fullResponse = e.output.message), this.sendSessionUpdate({
        sessionUpdate: "agent_message_chunk",
        content: { type: "text", text: s },
        ...e.subExecutionId && { _meta: { kiro: { agentSubtaskId: e.subExecutionId } } }
      }));
    }
  }
  handleReasoningAction(e) {
    if (V(e.output)) {
      const t = this.reasoningContentByActionId.get(e.actionId) ?? "", s = e.output.message.slice(t.length);
      s && (this.reasoningContentByActionId.set(e.actionId, e.output.message), this.sendSessionUpdate({
        sessionUpdate: "agent_thought_chunk",
        content: { type: "text", text: s },
        ...e.subExecutionId && { _meta: { kiro: { agentSubtaskId: e.subExecutionId } } }
      }));
    }
    this.persistAction(e);
  }
  handleSteeringAction(e) {
    this.persistAction(e);
    const s = e.input?.documents;
    Array.isArray(s) && s.length > 0 && this.sendSessionUpdate({
      sessionUpdate: "session_info_update",
      _meta: {
        kiro: {
          steeringDocuments: s,
          ...e.subExecutionId && { agentSubtaskId: e.subExecutionId }
        }
      }
    });
  }
  handleSubAgentAction(e) {
    const t = e.input, s = e.output, n = t?.subAgentName ? `Sub-agent: ${t.subAgentName}` : "Sub-agent execution", o = X(e.actionState), r = s?.subExecutionId ?? e.actionId;
    e.actionState === p.Running && (this.emittedToolCallIds.has(e.actionId) ? this.sendSessionUpdate({
      sessionUpdate: "tool_call_update",
      toolCallId: e.actionId,
      status: o,
      rawInput: e.input
    }) : (this.emittedToolCallIds.add(e.actionId), this.sendSessionUpdate({
      sessionUpdate: "tool_call",
      toolCallId: e.actionId,
      title: n,
      kind: "other",
      rawInput: e.input,
      status: o,
      _meta: { kiro: { kind: "agent-subtask", agentSubtaskId: r } }
    }))), (e.actionState === p.Success || e.actionState === p.Error || e.actionState === p.HandledError) && (this.emittedToolCallIds.delete(e.actionId), this.sendSessionUpdate({
      sessionUpdate: "tool_call_update",
      toolCallId: e.actionId,
      status: e.actionState === p.Success ? "completed" : "failed",
      rawOutput: e.output ?? e.errorMessage
    })), this.persistAction(e);
  }
  handleErrorOccurred(e) {
    this.sendSessionUpdate({
      sessionUpdate: "agent_message_chunk",
      content: { type: "text", text: e.errorMessage }
    });
  }
  /**
   * Bridges userInput actions to ACP requestPermission so the session-view
   * can render question options as permission buttons.
   */
  handleUserInputAction(e) {
    if (e.actionState !== p.PendingAction)
      return;
    const s = e.output?.questions;
    if (!s?.length)
      return;
    const n = s[0], o = n.options?.map((a) => ({
      optionId: a.id,
      name: a.label,
      kind: "allow_once"
    })) ?? [];
    if (o.length === 0)
      return;
    const r = () => this.controller?.getExecutionsForId(e.executionId) ?? this.controller?.getCurrentExecution();
    this.sendSessionUpdate({
      sessionUpdate: "tool_call",
      toolCallId: e.actionId,
      title: n.question,
      kind: "other",
      status: "pending"
    }), (async () => {
      try {
        const a = await this.connection.requestPermission({
          sessionId: this.sessionId,
          toolCall: { toolCallId: e.actionId, title: n.question, status: "pending" },
          options: o
        }), { outcome: c } = a;
        if (c.outcome === "selected") {
          const l = c.optionId, d = n.options?.find((f) => f.id === l)?.label ?? l;
          r()?.respondToQuestion(n.id, { type: "answered", answer: d }), this.sendSessionUpdate({
            sessionUpdate: "tool_call_update",
            toolCallId: e.actionId,
            status: "completed"
          });
        } else
          r()?.respondToQuestion(n.id, { type: "next-phase" }), this.sendSessionUpdate({
            sessionUpdate: "tool_call_update",
            toolCallId: e.actionId,
            status: "completed"
          });
      } catch (a) {
        u.error("[ACPEventAdapter] requestPermission for userInput failed:", a), r()?.respondToQuestion(n.id, { type: "next-phase" }), this.sendSessionUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: e.actionId,
          status: "failed"
        });
      }
    })();
  }
  handleToolAction(e) {
    const t = X(e.actionState), s = e.subExecutionId ? { _meta: { kiro: { agentSubtaskId: e.subExecutionId } } } : {}, n = qe(e.actionType);
    if (e.actionState === p.Running || e.actionState === p.PendingAction)
      if (this.emittedToolCallIds.has(e.actionId))
        this.sendSessionUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: e.actionId,
          status: t,
          rawInput: e.input
        });
      else {
        this.emittedToolCallIds.add(e.actionId);
        const o = We(e.input);
        this.sendSessionUpdate({
          sessionUpdate: "tool_call",
          toolCallId: e.actionId,
          title: e.actionType,
          kind: n,
          rawInput: e.input,
          status: t,
          ...o.length > 0 && { locations: o },
          ...s
        });
      }
    else {
      this.emittedToolCallIds.delete(e.actionId);
      const o = ze(n, e.input);
      this.sendSessionUpdate({
        sessionUpdate: "tool_call_update",
        toolCallId: e.actionId,
        status: t,
        rawOutput: e.output ?? e.errorMessage,
        ...o && {
          _meta: { kiro: { checkpoint: o } }
        }
      });
    }
    this.persistAction(e);
  }
  /**
   * Converts the action event to persisted messages via the shared adapter
   * and appends them to the session store.
   */
  persistAction(e) {
    if (this.persistenceSuppressed)
      return;
    const t = {
      executionId: e.executionId,
      actionId: e.actionId,
      actionType: e.actionType,
      actionState: e.actionState,
      startTime: e.startTime,
      endTime: e.endTime,
      errorMessage: e.errorMessage,
      input: e.input,
      output: e.output,
      subExecutionId: e.subExecutionId
    }, s = Be(t, this.executionId);
    if (s.length === 0)
      return;
    const n = this.appendMessagesQuietly(e.actionType, s);
    this.pendingPersistence.push(n);
  }
  async appendMessagesQuietly(e, t) {
    try {
      await this.persistence.appendMessages(this.sessionId, this.workspacePaths, t);
    } catch (s) {
      u.warn("[ACPEventAdapter] Failed to persist action", {
        sessionId: this.sessionId,
        actionType: e,
        error: s instanceof Error ? s.message : String(s)
      });
    }
  }
  async sendSessionUpdate(e) {
    await this.connection.sessionUpdate({
      sessionId: this.sessionId,
      update: e
    });
  }
  /**
   * Bridges AgentExecutionContextUsageUpdate to session_info_update with _meta.kiro.contextUsage.
   *
   * Tier thresholds match summarization-detection-node.ts:
   *   normal: <80%  |  warning: 80-95%  |  critical: >=95%
   */
  handleContextUsageUpdate(e) {
    const t = Ut(e.contextUsagePercentage);
    this.sendSessionUpdate({
      sessionUpdate: "session_info_update",
      _meta: {
        kiro: {
          contextUsage: { usagePercentage: e.contextUsagePercentage, tier: t }
        }
      }
    });
  }
  /**
   * Bridges AgentExecutionAction(summarization) to session_info_update with _meta.kiro.summarization.
   *
   * Two-phase coalescing: Action(Success) stores summary + truncated from output,
   * then SummarizationComplete sends the final notification with sessionTitle.
   * Emission order is guaranteed: Action(Running) -> Action(Success) -> SummarizationComplete.
   */
  handleSummarizationAction(e) {
    const t = e.actionState;
    if (t) {
      if (t === p.Running) {
        this.sendSessionUpdate({
          sessionUpdate: "session_info_update",
          _meta: {
            kiro: {
              summarization: { status: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString() }
            }
          }
        });
        return;
      }
      if (t === p.Error || t === p.Canceled) {
        const s = t === p.Error ? "error" : "canceled";
        this.sendSessionUpdate({
          sessionUpdate: "session_info_update",
          _meta: {
            kiro: {
              summarization: { status: s, completedAt: (/* @__PURE__ */ new Date()).toISOString() }
            }
          }
        }), this.pendingSummarization = void 0;
        return;
      }
      if (t === p.Success) {
        const s = e.output;
        this.pendingSummarization = {
          conversationSummary: s?.conversationSummary ?? "",
          truncated: s?.truncated ?? !1
        };
      }
    }
  }
  /**
   * Bridges AgentExecutionSummarizationComplete to session_info_update.
   *
   * Phase 2: Combines stored summary (from Action(Success)) with sessionTitle,
   * sends final success notification. Title is included in the SAME update
   * so it won't be dropped by the UI interceptor.
   */
  handleSummarizationComplete(e) {
    const t = this.pendingSummarization ?? {
      conversationSummary: e.summary.conversationSummary,
      truncated: !1
    };
    this.sendSessionUpdate({
      sessionUpdate: "session_info_update",
      _meta: {
        kiro: {
          summarization: {
            status: "success",
            completedAt: (/* @__PURE__ */ new Date()).toISOString(),
            summary: t
          }
        }
      },
      // Title in SAME update — won't be dropped by UI interceptor
      ...e.sessionTitle ? { title: e.sessionTitle } : {}
    }), this.pendingSummarization = void 0;
  }
}
function Ot(i, e, t) {
  if (t)
    return;
  u.debug(`${e}: content collection is disabled, setting x-amzn-codewhisperer-optout to true`);
  const s = (n) => async (o) => {
    const r = o;
    return r.request.headers = {
      ...r.request.headers,
      "x-amzn-codewhisperer-optout": "true"
    }, n(o);
  };
  i.middlewareStack.add(s, { step: "build" });
}
function jt(i, e) {
  const t = (s) => async (n) => {
    const o = n;
    return o.request.headers = {
      ...o.request.headers,
      "x-amzn-kiro-agent-mode": e
    }, s(n);
  };
  i.middlewareStack.add(t, { step: "build" });
}
function le(i, e, t = "CodeWhisperer") {
  if (e !== "external_idp")
    return;
  u.debug(`${t}: adding TokenType header for External IdP`);
  const s = (n) => async (o) => {
    const r = o;
    return r.request.headers = {
      ...r.request.headers,
      TokenType: "EXTERNAL_IDP"
    }, n(o);
  };
  i.middlewareStack.add(s, { step: "build" });
}
const Dt = "https://q.us-east-1.amazonaws.com", Lt = "us-east-1";
function ys(i, e = {}) {
  const t = e.contentCollectionEnabled ?? !1;
  return {
    createQDeveloperConverse: (s, n) => {
      const o = e.region || i.region || Lt, r = e.endpoint || Dt;
      return new He(s, n, {
        authProvider: i,
        getCodeWhispererStreamingClient: async (c) => {
          const l = await i.getToken(), d = new ne({
            region: o,
            endpoint: r,
            token: { token: l },
            retryStrategy: c,
            customUserAgent: e.customUserAgent
          });
          return le(d, i.readToken()?.authMethod, "acp-q-client"), d;
        },
        addPrivacyHeadersMiddleware: (c, l) => {
          Ot(c, l, t);
        },
        addAgentModeHeadersMiddleware: (c, l) => {
          jt(c, l);
        },
        metrics: {
          reportCountMetrics: () => {
          },
          reportHistogramMetrics: () => {
          },
          createTrace: (c) => ({
            start: () => {
            },
            success: () => {
            },
            fail: (l) => {
            },
            setAttributes: (l) => {
            }
          })
        },
        qLogger: {
          debug: (c, ...l) => u.debug(c, ...l),
          error: (c, ...l) => u.error(c, ...l)
        },
        qChatLogger: {
          appendLine: (c) => u.debug("[QChat]", c),
          capture: () => "",
          storeConversationId: () => {
          },
          getConversationIds: () => []
        },
        isUsageEnabled: () => !0,
        isReferenceTrackerEnabled: () => !1,
        recordReferences: () => {
        }
      });
    }
  };
}
const qt = "https://q.us-east-1.amazonaws.com", Wt = "us-east-1";
function Is(i, e = {}) {
  const t = new Ge();
  async function s() {
    const n = e.region || i.region || Wt, o = e.endpoint || qt, r = await i.getToken(), a = new ne({
      region: n,
      endpoint: o,
      token: { token: r },
      retryStrategy: t,
      customUserAgent: e.customUserAgent
    });
    return le(a, i.readToken()?.authMethod, "acp-remote-mcp"), a;
  }
  return {
    async listTools() {
      const o = await (await s()).send(
        new B({
          jsonrpc: "2.0",
          id: "tools_list",
          method: H.TOOLS_LIST,
          profileArn: await i.getProfileArn()
        })
      );
      if (o.error)
        throw new Error(`Failed to fetch remote tools: ${o.error.message}`);
      if (!o.result)
        throw new Error("No result returned from tools/list");
      const r = Ke.safeParse(o.result);
      return r.success ? { tools: r.data.tools } : (u.error("[ACPRemoteMCPClient] Failed to parse tools list", JSON.stringify(r.error)), null);
    },
    async callTool(n, o, r) {
      const c = await (await s()).send(
        new B({
          jsonrpc: "2.0",
          id: r,
          method: H.TOOLS_CALL,
          profileArn: await i.getProfileArn(),
          params: { name: n, arguments: o }
        })
      );
      return {
        result: c.result,
        error: c.error ? { message: c.error.message ?? "", code: c.error.code ?? 0 } : void 0
      };
    }
  };
}
export {
  Xe as A,
  st as a,
  ws as b,
  vt as c,
  ot as d,
  Ve as e,
  nt as f,
  G as g,
  ys as h,
  Is as i,
  gs as j,
  dt as k,
  R as l,
  fs as m,
  St as n,
  wt as o,
  Tt as p,
  K as q
};
//# sourceMappingURL=acp-remote-mcp-client-Bc6Bn8WU.js.map
