import { createRequire as __vfCreateRequire } from 'node:module';
const require = __vfCreateRequire(import.meta.url);

// src/tools/zod-to-json-schema.ts
function getDef(z) {
  return z._def;
}
function getDescription(z) {
  let current = z;
  while (current) {
    const def = getDef(current);
    if (def.description) return def.description;
    current = def.innerType;
  }
  return void 0;
}
function unwrapOptional(z) {
  const def = getDef(z);
  if (def.typeName === "ZodOptional" && def.innerType) {
    return { inner: def.innerType, optional: true };
  }
  return { inner: z, optional: false };
}
function unwrapDefault(z) {
  const def = getDef(z);
  if (def.typeName === "ZodDefault" && def.innerType && def.defaultValue) {
    return { inner: def.innerType, defaultValue: def.defaultValue() };
  }
  return { inner: z };
}
function convertLeaf(z, description) {
  const { inner: afterDefault, defaultValue } = unwrapDefault(z);
  const def = getDef(afterDefault);
  const desc = description ?? getDescription(z);
  const base = {};
  if (desc) base.description = desc;
  if (defaultValue !== void 0) base.default = defaultValue;
  switch (def.typeName) {
    case "ZodString":
      return { type: "string", ...base };
    case "ZodNumber":
      return { type: "number", ...base };
    case "ZodBoolean":
      return { type: "boolean", ...base };
    case "ZodEnum":
      if (!def.values) throw new Error(`zod-to-json-schema: ZodEnum without values`);
      return { type: "string", enum: def.values, ...base };
    case "ZodLiteral": {
      const value = def.value;
      if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
        throw new Error(`zod-to-json-schema: ZodLiteral with unsupported value type`);
      }
      const type = typeof value === "boolean" ? "boolean" : typeof value;
      const out = { type, ...base };
      if (typeof value === "string" || typeof value === "number") out.enum = [value];
      return out;
    }
    case "ZodArray": {
      if (!def.type) throw new Error(`zod-to-json-schema: ZodArray without item type`);
      return { type: "array", items: convertLeaf(def.type), ...base };
    }
    case "ZodRecord": {
      const valueType = def.valueType;
      if (!valueType) {
        return { type: "object", additionalProperties: true, ...base };
      }
      const valueDef = getDef(valueType);
      if (valueDef.typeName === "ZodUnknown" || valueDef.typeName === "ZodAny") {
        return { type: "object", additionalProperties: true, ...base };
      }
      return { type: "object", additionalProperties: convertLeaf(valueType), ...base };
    }
    case "ZodObject":
      return convertObject(afterDefault, desc);
    default:
      throw new Error(
        `zod-to-json-schema: unsupported Zod type "${def.typeName}". Add support in packages/cli/src/tools/zod-to-json-schema.ts or use a supported variant (string, number, boolean, enum, literal, optional, default, array, object).`
      );
  }
}
function convertObject(z, description) {
  const def = getDef(z);
  if (def.typeName !== "ZodObject" || !def.shape) {
    throw new Error(`zod-to-json-schema: convertObject called on non-ZodObject (${def.typeName})`);
  }
  const shape = def.shape();
  const properties = {};
  const required = [];
  for (const [key, value] of Object.entries(shape)) {
    const { inner, optional } = unwrapOptional(value);
    const fieldDesc = getDescription(value);
    properties[key] = convertLeaf(inner, fieldDesc);
    if (!optional) required.push(key);
  }
  const out = {
    type: "object",
    properties,
    required
  };
  if (description) out.description = description;
  return out;
}
function zodToJsonSchema(schema) {
  const def = getDef(schema);
  if (def.typeName !== "ZodObject") {
    throw new Error(`zodToJsonSchema: top-level schema must be ZodObject; got ${def.typeName}`);
  }
  return convertObject(schema);
}

// src/tools/adapters/mcp.ts
function formatConsolePart(value) {
  if (typeof value === "string") return value;
  if (value instanceof Error) return value.stack ?? value.message;
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
}
function invokeWriteCallback(encodingOrCallback, callback) {
  const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : typeof callback === "function" ? callback : void 0;
  if (cb) queueMicrotask(() => cb());
}
function formatStdoutChunk(chunk, encodingOrCallback) {
  if (Buffer.isBuffer(chunk)) {
    const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : "utf8";
    return chunk.toString(encoding);
  }
  return String(chunk);
}
async function withCapturedStdout(fn) {
  const originalWrite = process.stdout.write;
  const originalConsoleLog = console.log;
  const originalConsoleInfo = console.info;
  const originalConsoleDebug = console.debug;
  let captured = "";
  const captureConsole = (...values) => {
    captured += `${values.map(formatConsolePart).join(" ")}
`;
  };
  process.stdout.write = (chunk, encodingOrCallback, callback) => {
    const text = formatStdoutChunk(chunk, encodingOrCallback);
    if (text.startsWith("{") && text.includes('"jsonrpc":"2.0"')) {
      return originalWrite.call(
        process.stdout,
        chunk,
        encodingOrCallback,
        callback
      );
    }
    captured += text;
    invokeWriteCallback(encodingOrCallback, callback);
    return true;
  };
  console.log = captureConsole;
  console.info = captureConsole;
  console.debug = captureConsole;
  try {
    return await fn();
  } finally {
    process.stdout.write = originalWrite;
    console.log = originalConsoleLog;
    console.info = originalConsoleInfo;
    console.debug = originalConsoleDebug;
    if (captured.trim() && process.env.VIBE_MCP_DEBUG_STDIO === "1") {
      process.stderr.write(captured);
    }
  }
}
function makeProgressSink(raw, minIntervalMs = 1e3) {
  if (!raw) {
    return { send: () => void 0, close: () => void 0 };
  }
  let closed = false;
  let lastSentAt = 0;
  let lastProgress = 0;
  return {
    send: (update) => {
      if (closed) return;
      const now = Date.now();
      if (lastSentAt !== 0 && now - lastSentAt < minIntervalMs) return;
      lastSentAt = now;
      const progress = update.progress !== void 0 && update.progress > lastProgress ? update.progress : lastProgress + 1;
      lastProgress = progress;
      raw({
        progress,
        ...update.total !== void 0 ? { total: update.total } : {},
        ...update.message ? { message: update.message } : {}
      });
    },
    close: () => {
      closed = true;
    }
  };
}
function formatZodError(err) {
  const missing = err.issues.filter((i) => {
    if (i.code !== "invalid_type") return false;
    const received = i.received;
    return received === "undefined" || received === "null";
  }).map((i) => i.path.join(".")).filter(Boolean);
  if (missing.length > 0) {
    const plural = missing.length > 1 ? "s" : "";
    return `missing required argument${plural}: ${missing.join(", ")}`;
  }
  return err.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
}
function manifestToMcpTools(manifest) {
  return manifest.filter((t) => !t.surfaces || t.surfaces.includes("mcp")).map((t) => {
    const inputSchema = zodToJsonSchema(t.schema);
    return {
      name: t.name,
      title: t.title,
      description: t.description,
      inputSchema: {
        type: "object",
        properties: inputSchema.properties ?? {},
        required: inputSchema.required ?? [],
        ...inputSchema.description ? { description: inputSchema.description } : {}
      },
      annotations: toMcpAnnotations(t.annotations)
    };
  });
}
function toMcpAnnotations(a) {
  if (a.readOnly) {
    return { readOnlyHint: true, openWorldHint: a.openWorld };
  }
  return {
    readOnlyHint: false,
    destructiveHint: a.destructive ?? true,
    ...a.idempotent !== void 0 ? { idempotentHint: a.idempotent } : {},
    openWorldHint: a.openWorld
  };
}
function buildMcpDispatcher(manifest) {
  const byName = /* @__PURE__ */ new Map();
  for (const t of manifest) {
    if (!t.surfaces || t.surfaces.includes("mcp")) {
      byName.set(t.name, t);
    }
  }
  return async (name, args, extra) => {
    const tool = byName.get(name);
    if (!tool) {
      return { content: [{ type: "text", text: `Unknown tool: ${name}` }] };
    }
    const parsed = tool.schema.safeParse(args);
    if (!parsed.success) {
      return {
        content: [{ type: "text", text: `${name} failed: ${formatZodError(parsed.error)}` }]
      };
    }
    const sink = makeProgressSink(extra?.onProgress);
    try {
      const result = await withCapturedStdout(
        () => tool.execute(parsed.data, {
          workingDirectory: process.cwd(),
          surface: "mcp",
          ...extra?.onProgress ? { onProgress: sink.send } : {},
          ...extra?.elicit ? { elicit: extra.elicit } : {}
        })
      );
      const text = result.success ? JSON.stringify({ success: true, ...result.data }) : result.data ? JSON.stringify({
        success: false,
        error: result.error ?? "unknown error",
        ...result.data
      }) : `${name} failed: ${result.error ?? "unknown error"}`;
      return { content: [{ type: "text", text }] };
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      return { content: [{ type: "text", text: `${name} threw: ${msg}` }] };
    } finally {
      sink.close();
    }
  };
}
export {
  buildMcpDispatcher,
  makeProgressSink,
  manifestToMcpTools
};
