import { createRequire as _cjsReq } from 'module'; if(typeof require === 'undefined') var require = _cjsReq(import.meta.url);
import {
  ChatApp,
  createSession,
  ensureAuthenticated,
  fetchSession,
  fetchSessionEvents,
  render_default,
  require_react,
  suppressScrollbackClear
} from "./chunk-7JJT3RNI.js";
import {
  BuildFailedError,
  BuildTimeoutError,
  buildEphemeralVersion,
  getAgentId,
  readAgentFiles
} from "./chunk-EQUW4M5A.js";
import {
  Command,
  Option,
  getOutputMode,
  isQuietMode
} from "./chunk-YQWI6SUV.js";
import {
  open_default
} from "./chunk-56YCMGL3.js";
import "./chunk-6EX6E7WP.js";
import {
  pollForResponse
} from "./chunk-F3F5CUO3.js";
import {
  GuildAPIClient,
  getWorkspaceId,
  getWorkspaceSourceLabel
} from "./chunk-RJHD6XTV.js";
import {
  ErrorCodes,
  ensureInteractiveStdin,
  format,
  getCliVersion,
  handleAxiosError,
  hyperlink,
  readStdinAsJSON
} from "./chunk-JQRJ4A4S.js";
import "./chunk-M347HP6M.js";
import "./chunk-ENKEEJ45.js";
import "./chunk-VVSOU6ON.js";
import "./chunk-PNCUR4OB.js";
import "./chunk-X3ADGWOF.js";
import {
  __toESM
} from "./chunk-OYQ476FQ.js";

// src/commands/agent/chat.ts
var import_react = __toESM(require_react(), 1);
import path from "path";
import * as readline from "readline";
var cliVersion = getCliVersion();
function createAgentChatCommand() {
  const cmd = new Command("chat");
  cmd.description("Chat with the agent in current directory").argument("[prompt...]", "Optional initial prompt for the agent").option("--path <dir>", "Path to agent directory (defaults to current directory)").option(
    "--workspace <identifier>",
    "Workspace ID or full name (e.g., owner~workspace-name)"
  ).option(
    "--agent-version <id>",
    "Chat with a specific version (UUID or version number)"
  ).option("--no-splash", "Skip the splash screen animation").option("--resume <session-id>", "Resume an existing session").option("--open", "Open session in web dashboard").option("--no-cache", "Skip ephemeral build cache (force a fresh build)").addOption(new Option("--mode <format>").hideHelp()).addHelpText(
    "after",
    "\nTo chat with a published agent by name: guild chat --agent owner~agent-name"
  ).action(
    async (promptArgs, options) => {
      try {
        const agentPath = options.path || ".";
        const { agentId, config } = await getAgentId(void 0, agentPath);
        const initialPrompt = promptArgs.length > 0 ? promptArgs.join(" ") : "Hello";
        const outputMode = getOutputMode();
        let inputData;
        if (outputMode === "json") {
          try {
            inputData = await readStdinAsJSON();
          } catch (error) {
            const err = error;
            console.error(`Error: ${err.message}`);
            console.error("");
            console.error("Example usage:");
            console.error(
              `  echo '{"prompt": "test"}' | guild agent chat --mode json`
            );
            console.error("  guild agent chat --mode json < input.json");
            process.exit(1);
          }
        }
        await ensureAuthenticated();
        const client = new GuildAPIClient();
        const quiet = isQuietMode();
        const resolvedPath = path.resolve(agentPath);
        let version;
        let ephemeralCached = false;
        if (options.agentVersion) {
          const existingVersions = await client.get(
            `/agents/${agentId}/versions`
          );
          const match = existingVersions.items.find(
            (v) => v.id === options.agentVersion || v.version_number === options.agentVersion
          );
          if (!match) {
            console.error(`Error: Version not found: ${options.agentVersion}`);
            console.error("");
            console.error("List available versions:");
            console.error(`  guild agent versions ${agentId}`);
            process.exit(1);
          }
          version = match;
        } else {
          if (!quiet) {
            console.error("Building agent...");
          }
          const agentFiles = await readAgentFiles(resolvedPath);
          const noCache = options.cache === false;
          const result = await buildEphemeralVersion(
            client,
            agentId,
            agentFiles,
            resolvedPath,
            "[Chat] Ephemeral development version",
            { noCache }
          );
          version = result.version;
          ephemeralCached = result.cached;
          if (ephemeralCached && !quiet) {
            console.error("No changes detected, reusing cached build.");
          }
        }
        if (outputMode === "json" || outputMode === "jsonl") {
          const sessionPrompt = outputMode === "json" && inputData ? JSON.stringify(inputData) : initialPrompt;
          let resolvedWorkspaceId = options.workspace;
          let workspaceSourceLabel;
          if (!resolvedWorkspaceId) {
            const wsResolved = await getWorkspaceId(resolvedPath);
            resolvedWorkspaceId = wsResolved?.workspaceId;
            workspaceSourceLabel = wsResolved ? getWorkspaceSourceLabel(wsResolved.source) : void 0;
          }
          const session = await createSession(
            client,
            resolvedWorkspaceId,
            sessionPrompt,
            version.id
          );
          if (!quiet) {
            console.log(`\u2713 Agent: ${config?.name || agentId}`);
            if (session.workspace_id) {
              const workspaceDisplay = workspaceSourceLabel ? `${session.workspace_id} (from ${workspaceSourceLabel})` : session.workspace_id;
              console.log(`\u2713 Workspace: ${workspaceDisplay}`);
            }
            const sessionLink = session.session_url ? hyperlink(session.id, session.session_url) : session.id;
            console.log(`\u2713 Session: ${sessionLink}`);
            console.log("");
          }
          if (options.open && session.session_url) {
            await open_default(session.session_url);
          }
          if (outputMode === "json" && inputData) {
            try {
              const { response } = await pollForResponse(
                client,
                session.id,
                void 0
              );
              if (!response) {
                console.error("Timeout: No response received from agent");
                process.exit(1);
              }
              if (quiet) {
                console.log(response);
              } else {
                console.log(`< ${response}`);
                console.log("");
                console.log("\u2713 Chat complete");
              }
              process.exit(0);
            } catch (error) {
              const formattedError = handleAxiosError(error);
              console.error(`Error: ${formattedError.details}`);
              process.exit(1);
            }
          } else if (outputMode === "jsonl") {
            const rl = readline.createInterface({
              input: process.stdin,
              output: process.stdout,
              terminal: false
            });
            let lineNumber = 0;
            let processedCount = 0;
            let lastEventId;
            for await (const line of rl) {
              lineNumber++;
              if (!line.trim()) continue;
              try {
                const jsonInput = JSON.parse(line);
                if (!quiet) {
                  console.error(`Processing line ${lineNumber}...`);
                }
                await client.post(`/sessions/${session.id}/events`, {
                  mode: "json",
                  content: jsonInput
                });
                const result = await pollForResponse(client, session.id, lastEventId);
                lastEventId = result.lastEventId;
                if (!result.response) {
                  console.error(`Timeout: No response for line ${lineNumber}`);
                  continue;
                }
                const response = result.response;
                if (quiet) {
                  console.log(response);
                } else {
                  console.log(`< ${response}`);
                  console.log("");
                }
                processedCount++;
              } catch (error) {
                const err = error;
                console.error(`Error: Invalid JSON on line ${lineNumber}`);
                console.error(`Failed to parse JSON: ${err.message}`);
                console.error("Skipping line and continuing...");
              }
            }
            if (!quiet) {
              console.log(`
\u2713 Processed ${processedCount} messages`);
            }
            process.exit(0);
          }
        } else {
          ensureInteractiveStdin("guild agent chat");
          const resumeCommand = "guild agent chat";
          let resumeSession;
          let resumeSessionEvents;
          if (options.resume) {
            resumeSession = await fetchSession(client, options.resume);
            resumeSessionEvents = await fetchSessionEvents(client, options.resume);
          }
          const isInteractive = getOutputMode() === "interactive" && !isQuietMode();
          const shouldShowSplash = isInteractive && !options.noSplash && !options.resume;
          if (shouldShowSplash) {
            suppressScrollbackClear();
          }
          const { waitUntilExit } = render_default(
            import_react.default.createElement(ChatApp, {
              initialPrompt,
              version: cliVersion,
              workspaceId: options.workspace,
              versionId: version.id,
              agentName: config?.name,
              showSplash: shouldShowSplash,
              resumeSession,
              resumeEvents: resumeSessionEvents,
              resumeCommand,
              openDashboard: options.open
            }),
            {
              exitOnCtrlC: false
              // We handle Ctrl-C in useInput (raw mode)
            }
          );
          await waitUntilExit();
        }
      } catch (error) {
        if (error instanceof BuildTimeoutError) {
          console.error("Error: Build did not complete");
          console.error("");
          console.error(error.message);
          console.error("");
          console.error("Check build status:");
          console.error("  guild agent versions");
          process.exit(1);
        }
        if (error instanceof BuildFailedError) {
          console.error(`Error: ${error.message}`);
          process.exit(1);
        }
        const formattedError = handleAxiosError(error);
        if (formattedError.code === ErrorCodes.AUTH_REQUIRED || formattedError.code === ErrorCodes.AUTH_TOKEN_INVALID) {
          format.error("Not authenticated. Run: guild auth login");
          process.exit(1);
        }
        console.error(`Error: ${formattedError.details}`);
        process.exit(1);
      }
    }
  );
  return cmd;
}
async function handleAgentChatAction(_promptArgs, _options) {
  const cmd = createAgentChatCommand();
  await cmd.parseAsync(process.argv.slice(3), { from: "user" });
}
export {
  createAgentChatCommand,
  handleAgentChatAction
};
//# sourceMappingURL=chat-ALOJ22JR.js.map
