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);
}
var zodToAgentParameters = zodToJsonSchema;

// src/tools/adapters/agent.ts
function formatZodError(err) {
  return err.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
}
function toAgentDefinition(t) {
  const json = zodToAgentParameters(t.schema);
  const properties = {};
  for (const [k, v] of Object.entries(json.properties ?? {})) {
    properties[k] = v;
  }
  return {
    name: t.name,
    description: t.description,
    surface: t.productSurface,
    replacement: t.replacement,
    note: t.note,
    // Propagate the manifest's cost tier so the agent's executor can
    // mandate a confirm prompt for high-spend tools without needing a
    // parallel SSOT.
    cost: t.cost,
    parameters: {
      type: "object",
      properties,
      required: json.required ?? []
    }
  };
}
function registerManifestIntoAgent(registry, manifest) {
  for (const tool of manifest) {
    if (tool.surfaces && !tool.surfaces.includes("agent")) continue;
    const definition = toAgentDefinition(tool);
    const handler = async (args, context) => {
      const parsed = tool.schema.safeParse(args);
      if (!parsed.success) {
        return {
          toolCallId: "",
          success: false,
          output: "",
          error: formatZodError(parsed.error)
        };
      }
      try {
        const result = await tool.execute(parsed.data, {
          workingDirectory: context.workingDirectory,
          surface: "agent",
          agent: {
            projectPath: context.projectPath,
            setProjectPath(path) {
              context.projectPath = path;
            }
          }
        });
        if (!result.success) {
          return {
            toolCallId: "",
            success: false,
            output: "",
            error: result.error ?? "tool execution failed"
          };
        }
        const output = result.humanLines && result.humanLines.length > 0 ? result.humanLines.join("\n") : result.data ? JSON.stringify(result.data) : "";
        return { toolCallId: "", success: true, output };
      } catch (error) {
        return {
          toolCallId: "",
          success: false,
          output: "",
          error: error instanceof Error ? error.message : String(error)
        };
      }
    };
    registry.register(definition, handler);
  }
}
export {
  registerManifestIntoAgent
};
