import { arrayFormatter } from "./array.js";
import { enumFormatter } from "./enum.js";
import { jsonFormatter } from "./json.js";
import { jsonlFormatter } from "./jsonl.js";
import { textFormatter } from "./text.js";
function defineFormat(registry, options, handler) {
  const { name, ...config } = options;
  const formatter = { config, handler };
  registry.registerValue("format", name, formatter);
  return formatter;
}
async function resolveFormat(registry, outputOpts) {
  if (!outputOpts) return void 0;
  if ((outputOpts.jsonSchema || outputOpts.schema) && !outputOpts.format) {
    return registry.lookupValue("format", "json");
  }
  if (outputOpts.format) {
    return registry.lookupValue("format", outputOpts.format);
  }
  return void 0;
}
function resolveInstructions(format, schema, instructionsOption) {
  if (typeof instructionsOption === "string") return instructionsOption;
  if (instructionsOption === false) return void 0;
  if (!format) return void 0;
  return format.handler(schema).instructions;
}
function injectInstructions(messages, instructions) {
  if (!instructions) return messages;
  if (messages.find(
    (m2) => m2.content.find(
      (p) => p.metadata?.purpose === "output" && !p.metadata?.pending
    )
  )) {
    return messages;
  }
  const newPart = {
    text: instructions,
    metadata: { purpose: "output" }
  };
  let targetIndex = messages.findIndex((m2) => m2.role === "system");
  if (targetIndex < 0)
    targetIndex = messages.map((m2) => m2.role).lastIndexOf("user");
  if (targetIndex < 0) return messages;
  const m = {
    ...messages[targetIndex],
    content: [...messages[targetIndex].content]
  };
  const partIndex = m.content.findIndex(
    (p) => p.metadata?.purpose === "output" && p.metadata?.pending
  );
  if (partIndex > 0) {
    m.content.splice(partIndex, 1, newPart);
  } else {
    m.content.push(newPart);
  }
  const outMessages = [...messages];
  outMessages.splice(targetIndex, 1, m);
  return outMessages;
}
const DEFAULT_FORMATS = [
  jsonFormatter,
  arrayFormatter,
  textFormatter,
  enumFormatter,
  jsonlFormatter
];
function configureFormats(registry) {
  for (const format of DEFAULT_FORMATS) {
    defineFormat(
      registry,
      { name: format.name, ...format.config },
      format.handler
    );
  }
}
export {
  DEFAULT_FORMATS,
  configureFormats,
  defineFormat,
  injectInstructions,
  resolveFormat,
  resolveInstructions
};
//# sourceMappingURL=index.mjs.map