{"version":3,"file":"prompts-manager.mjs","names":[],"sources":["../../../../../../../ai/src/prompts/prompts-manager.ts"],"sourcesContent":["import type { Placeholders } from \"../contracts/placeholders.type\";\nimport type {\n  SystemPromptBlockContract,\n  SystemPromptContract,\n  SystemPromptMeta,\n} from \"../contracts/system-prompt.contract\";\nimport { InvalidRequestError } from \"../errors\";\nimport { Instruction } from \"../system-prompt/instruction\";\nimport { Persona } from \"../system-prompt/persona\";\nimport { SystemPrompt } from \"../system-prompt/system-prompt\";\nimport type {\n  PromptsManagerContract,\n  PromptsManagerEntry,\n  PromptsManagerRegisterOptions,\n} from \"./prompts-manager.contract\";\nimport type {\n  ExportedPromptVersion,\n  ExportedRegistry,\n  PromptDiff,\n  PromptDiffBlock,\n  PromptJudgeCacheLike,\n  PromptsManagerOptions,\n  PromptTemplateVersion,\n  PromptValidateTarget,\n  PromptValidationResult,\n  PromptsValidateOptions,\n} from \"./prompts-manager.type\";\nimport {\n  describeContractTarget,\n  findMissingPlaceholders,\n  findUnreferencedRequired,\n  judgePromptBodyCached,\n} from \"./prompts-validate\";\n\n/**\n * Build the `name@version` registry key. Centralized so the duplicate check,\n * `get`, and `composedFrom` provenance all agree on one label shape.\n */\nexport function promptKey(name: string, version: string): string {\n  return `${name}@${version}`;\n}\n\n/**\n * Serialize a prompt's observable content — its ordered blocks (discriminator\n * + raw template text) — into a stable signature. Two prompts with the same\n * blocks in the same order share a signature, which is how `register()` tells\n * an idempotent re-registration from a genuine clash. Meta is intentionally\n * excluded: provenance / description should not defeat idempotency.\n */\nfunction contentSignature(contract: SystemPromptContract): string {\n  return JSON.stringify(\n    contract.blocks.map(block => [block.type, block.text]),\n  );\n}\n\n/**\n * Reconstruct a block from its `{ type, text }` snapshot — `persona` blocks\n * become a `Persona`, everything else an `Instruction`. The inverse of the\n * flattening `export()` performs, so an imported registry resolves identically.\n */\nfunction blockFromSnapshot(block: PromptDiffBlock): SystemPromptBlockContract {\n  return block.type === \"persona\"\n    ? new Persona(block.text)\n    : new Instruction(block.text);\n}\n\n/**\n * Narrow a {@link PromptTemplateVersion} body to its ordered block list: a raw\n * string becomes one instruction block; an explicit block list is used verbatim.\n */\nfunction blocksFromTemplate(\n  template: string | readonly SystemPromptBlockContract[],\n): SystemPromptBlockContract[] {\n  if (typeof template === \"string\") {\n    return [new Instruction(template)];\n  }\n\n  return [...template];\n}\n\n/**\n * Concrete `PromptsManagerContract` — a single registry of named, versioned\n * `SystemPromptContract` builders keyed by `name@version`.\n *\n * **Role.** The store behind `ai.prompts`. It holds one flat\n * `Map<string, PromptsManagerEntry>` keyed by `name@version`, plus a monotonic\n * counter that stamps each entry's `addedAt` so \"latest\" is deterministic\n * (highest `addedAt` for a name) without ever reading the wall clock.\n *\n * **Responsibility.**\n * - Owns: the registry map, the `addedAt` counter, the duplicate /\n *   idempotency rule, default version derivation, latest selection, the\n *   per-version tag pins, and the validate / diff / export / import surface.\n * - Does NOT own: prompt rendering (delegated to the contract's `resolve()`),\n *   block composition, or the LLM-judge mechanics (delegated to the eval\n *   `judge` scorer via `prompts-validate`).\n *\n * Users construct via the `prompts()` factory — `new PromptsManager()` is not\n * the public API.\n */\nclass PromptsManager implements PromptsManagerContract {\n  /** Flat registry keyed by `name@version`. */\n  private readonly entries = new Map<string, PromptsManagerEntry>();\n\n  /** First-seen order of names, for a stable `list()`. */\n  private readonly names: string[] = [];\n\n  /** Per-name tag pins: `name` → (`tag` → `version`). */\n  private readonly pins = new Map<string, Map<string, string>>();\n\n  /** Optional process-level judge-verdict memo (absent ⇒ judge always runs live). */\n  private readonly judgeCache?: PromptJudgeCacheLike;\n\n  /** Monotonic insertion counter — the deterministic stand-in for a timestamp. */\n  private counter = 0;\n\n  public constructor(options: PromptsManagerOptions = {}) {\n    this.judgeCache = options.judgeCache;\n  }\n\n  public register(\n    contract: SystemPromptContract,\n    options: PromptsManagerRegisterOptions = {},\n  ): PromptsManagerContract {\n    const meta = contract.meta();\n    // An explicit override (from define() / import()) wins over the contract's\n    // own meta — it lets those bulk paths register an anonymous contract under\n    // a name without the SystemPrompt constructor's default-manager auto-reg.\n    const name = options.name ?? meta?.name;\n\n    if (!name) {\n      throw new InvalidRequestError(\n        \"Cannot register a prompt without a name — set meta.name via \" +\n          \"systemPrompt(input, { name }) or .meta({ name }).\",\n        { context: { meta } },\n      );\n    }\n\n    const version =\n      options.version ?? meta?.version ?? this.nextVersion(name);\n    const key = promptKey(name, version);\n    const existing = this.entries.get(key);\n\n    if (existing) {\n      // Idempotent re-registration: identical content under the same\n      // name@version is a no-op, not an error. Anything else is a clash.\n      if (contentSignature(existing.contract) === contentSignature(contract)) {\n        return this;\n      }\n\n      throw new InvalidRequestError(\n        `A different prompt is already registered as \"${key}\".`,\n        { context: { name, version } },\n      );\n    }\n\n    if (!this.names.includes(name)) {\n      this.names.push(name);\n    }\n\n    this.entries.set(key, {\n      name,\n      version,\n      addedAt: this.counter++,\n      contract,\n      ...(options.tags ? { tags: options.tags } : {}),\n    });\n\n    return this;\n  }\n\n  public create(\n    input?: string | ReadonlyArray<SystemPromptBlockContract>,\n    meta?: SystemPromptMeta,\n  ): SystemPromptContract {\n    // Mirror `systemPromptFactory` exactly (no import — `system-prompt.ts`\n    // already depends on this module, so importing its factory back here would\n    // close an import cycle). A name in `meta` auto-registers into the\n    // process-wide default manager via the SystemPrompt constructor.\n    if (input === undefined) {\n      return new SystemPrompt([], meta);\n    }\n\n    if (typeof input === \"string\") {\n      return new SystemPrompt([new Instruction(input)], meta);\n    }\n\n    return new SystemPrompt([...input], meta);\n  }\n\n  public get(name: string, versionOrTag?: string): SystemPromptContract {\n    return this.requireEntry(name, versionOrTag).contract;\n  }\n\n  public has(name: string, versionOrTag?: string): boolean {\n    const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n    if (selector !== undefined) {\n      return this.resolveSelector(baseName, selector) !== undefined;\n    }\n\n    return this.latestEntry(baseName) !== undefined;\n  }\n\n  public list(): string[] {\n    return [...this.names];\n  }\n\n  public versions(name: string): string[] {\n    return [...this.entries.values()]\n      .filter(entry => entry.name === name)\n      .sort((a, b) => a.addedAt - b.addedAt)\n      .map(entry => entry.version);\n  }\n\n  public resolve(\n    name: string,\n    versionOrTag?: string,\n    placeholders?: Placeholders,\n  ): string {\n    return this.requireEntry(name, versionOrTag).contract.resolve(placeholders);\n  }\n\n  public define(\n    name: string,\n    versions: readonly PromptTemplateVersion[],\n  ): PromptsManagerContract {\n    for (const entry of versions) {\n      const blocks = blocksFromTemplate(entry.template);\n      // Anonymous contract (no name in meta ⇒ no SystemPrompt constructor\n      // auto-registration into the default manager); the name/version are\n      // supplied explicitly so define() targets only THIS manager.\n      const contract = new SystemPrompt(blocks);\n\n      this.register(contract, { name, version: entry.version });\n    }\n\n    return this;\n  }\n\n  public tag(\n    name: string,\n    tag: string,\n    version: string,\n  ): PromptsManagerContract {\n    // Validate the target exists before pinning — a tag to a missing version is\n    // an authoring mistake, not a silent dangling pin.\n    if (!this.entries.has(promptKey(name, version))) {\n      throw new InvalidRequestError(\n        `Cannot tag \"${tag}\" — no prompt registered as \"${promptKey(\n          name,\n          version,\n        )}\".`,\n        { context: { name, tag, version } },\n      );\n    }\n\n    const nameTags = this.pins.get(name) ?? new Map<string, string>();\n    nameTags.set(tag, version);\n    this.pins.set(name, nameTags);\n\n    return this;\n  }\n\n  public async validate(\n    target: PromptValidateTarget,\n    options: PromptsValidateOptions = {},\n  ): Promise<PromptValidationResult> {\n    const { text, required } = this.describeTarget(target);\n\n    const provided = new Set(Object.keys(options.placeholders ?? {}));\n    const declared = new Set<string>([\n      ...required,\n      ...(options.declare ?? []),\n    ]);\n\n    const missing = findMissingPlaceholders(text, provided, declared);\n\n    // A declared-required key that the body never references is itself a\n    // defect — surface it as an issue (it does not affect `missing` / `ok`,\n    // which track unresolved placeholders).\n    const unreferenced = findUnreferencedRequired(text, required);\n\n    const ok = missing.length === 0;\n\n    if (!options.judge) {\n      if (unreferenced.length === 0) {\n        return { ok, missing };\n      }\n\n      return {\n        ok,\n        missing,\n        issues: unreferenced.map(\n          key => `Required key \"${key}\" is never referenced in the prompt.`,\n        ),\n      };\n    }\n\n    // Per-call cache override wins over the manager-level memo. `criteria`\n    // (when set) replaces the built-in rubric the judge grades against.\n    const cache = options.judgeCache ?? this.judgeCache;\n    const judgeOutcome = await judgePromptBodyCached(\n      text,\n      options.judge,\n      cache,\n      options.criteria,\n    );\n\n    const issues = [\n      ...unreferenced.map(\n        key => `Required key \"${key}\" is never referenced in the prompt.`,\n      ),\n      ...judgeOutcome.issues,\n    ];\n\n    return {\n      ok,\n      missing,\n      ...(judgeOutcome.score !== undefined ? { score: judgeOutcome.score } : {}),\n      issues,\n    };\n  }\n\n  public diff(name: string, from: string, to: string): PromptDiff {\n    const fromBlocks = this.snapshotBlocks(this.requireExact(name, from));\n    const toBlocks = this.snapshotBlocks(this.requireExact(name, to));\n\n    const added: PromptDiffBlock[] = [];\n    const removed: PromptDiffBlock[] = [];\n    const changed: { from: PromptDiffBlock; to: PromptDiffBlock }[] = [];\n\n    const max = Math.max(fromBlocks.length, toBlocks.length);\n\n    for (let index = 0; index < max; index++) {\n      const left = fromBlocks[index];\n      const right = toBlocks[index];\n\n      if (left && !right) {\n        removed.push(left);\n        continue;\n      }\n\n      if (!left && right) {\n        added.push(right);\n        continue;\n      }\n\n      if (left && right && (left.type !== right.type || left.text !== right.text)) {\n        changed.push({ from: left, to: right });\n      }\n    }\n\n    return {\n      name,\n      from,\n      to,\n      added,\n      removed,\n      changed,\n      identical:\n        added.length === 0 && removed.length === 0 && changed.length === 0,\n    };\n  }\n\n  public export(): ExportedRegistry {\n    return {\n      prompts: this.names.map(name => ({\n        name,\n        versions: this.versions(name).map(version =>\n          this.exportVersion(name, version),\n        ),\n      })),\n    };\n  }\n\n  public import(snapshot: ExportedRegistry): PromptsManagerContract {\n    for (const exported of snapshot.prompts) {\n      for (const version of exported.versions) {\n        const blocks = version.blocks.map(blockFromSnapshot);\n        // Anonymous (no `name` in meta) so the SystemPrompt constructor does\n        // not auto-register into the default manager; description / required\n        // ride along for round-trip fidelity. Name/version are explicit so the\n        // import lands only on THIS manager.\n        const contract = new SystemPrompt(blocks, {\n          ...(version.description ? { description: version.description } : {}),\n          ...(version.required ? { required: version.required } : {}),\n        });\n\n        this.register(contract, {\n          name: exported.name,\n          version: version.version,\n        });\n\n        for (const tag of version.tags ?? []) {\n          this.tag(exported.name, tag, version.version);\n        }\n      }\n    }\n\n    return this;\n  }\n\n  /**\n   * Flatten a registered version into its portable `{ version, blocks, tags?,\n   * description?, required? }` snapshot for `export()`.\n   */\n  private exportVersion(name: string, version: string): ExportedPromptVersion {\n    const entry = this.requireExact(name, version);\n    const meta = entry.contract.meta();\n    const tags = this.tagsForVersion(name, version);\n\n    return {\n      version,\n      blocks: this.snapshotBlocks(entry),\n      ...(tags.length > 0 ? { tags } : {}),\n      ...(meta?.description ? { description: meta.description } : {}),\n      ...(meta?.required ? { required: [...meta.required] } : {}),\n    };\n  }\n\n  /** Every tag currently pinned to a specific `name@version`, in pin order. */\n  private tagsForVersion(name: string, version: string): string[] {\n    const nameTags = this.pins.get(name);\n\n    if (!nameTags) {\n      return [];\n    }\n\n    const tags: string[] = [];\n\n    for (const [tag, pinnedVersion] of nameTags) {\n      if (pinnedVersion === version) {\n        tags.push(tag);\n      }\n    }\n\n    return tags;\n  }\n\n  /** Flatten an entry's blocks to `{ type, text }` snapshots. */\n  private snapshotBlocks(entry: PromptsManagerEntry): PromptDiffBlock[] {\n    return entry.contract.blocks.map(block => ({\n      type: block.type,\n      text: block.text,\n    }));\n  }\n\n  /**\n   * Resolve the body + declared-required keys for any `validate` target: a\n   * registered name (or `name@selector`), a `SystemPromptContract` instance, or\n   * a raw string.\n   */\n  private describeTarget(target: PromptValidateTarget): {\n    text: string;\n    required: readonly string[];\n  } {\n    if (typeof target === \"string\") {\n      // An inline `name@selector` (or a bare registered name) resolves through\n      // the registry; anything else is a raw prompt body validated verbatim.\n      const { baseName, selector } = this.parseSelector(target, undefined);\n      const entry = selector\n        ? this.resolveSelector(baseName, selector)\n        : this.latestEntry(baseName);\n\n      if (entry) {\n        return describeContractTarget(entry.contract);\n      }\n\n      return { text: target, required: [] };\n    }\n\n    if (isSystemPromptContract(target)) {\n      return describeContractTarget(target);\n    }\n\n    if (isBlock(target)) {\n      return { text: target.text, required: [] };\n    }\n\n    throw new InvalidRequestError(\n      \"validate() target must be a registered name, a SystemPromptContract, \" +\n        \"a prompt block, or a raw string.\",\n      { context: { target } },\n    );\n  }\n\n  /**\n   * The next integer version label for a name — `\"1\"` for the first, then the\n   * count of existing versions plus one. String-typed to match the free-form\n   * `version` label shape.\n   */\n  private nextVersion(name: string): string {\n    const count = [...this.entries.values()].filter(\n      entry => entry.name === name,\n    ).length;\n\n    return String(count + 1);\n  }\n\n  /** Pick the highest-`addedAt` entry for a name, or `undefined` when absent. */\n  private latestEntry(name: string): PromptsManagerEntry | undefined {\n    let latest: PromptsManagerEntry | undefined;\n\n    for (const entry of this.entries.values()) {\n      if (entry.name !== name) {\n        continue;\n      }\n\n      if (!latest || entry.addedAt > latest.addedAt) {\n        latest = entry;\n      }\n    }\n\n    return latest;\n  }\n\n  /**\n   * Split a name argument into its base name + optional selector. The selector\n   * comes from the explicit second argument when present, else from an inline\n   * `name@selector` in the first argument. A bare name yields no selector.\n   */\n  private parseSelector(\n    name: string,\n    versionOrTag: string | undefined,\n  ): { baseName: string; selector: string | undefined } {\n    if (versionOrTag !== undefined) {\n      return { baseName: name, selector: versionOrTag };\n    }\n\n    const at = name.indexOf(\"@\");\n\n    if (at > 0) {\n      return { baseName: name.slice(0, at), selector: name.slice(at + 1) };\n    }\n\n    return { baseName: name, selector: undefined };\n  }\n\n  /**\n   * Resolve a selector (a version label OR a pinned tag) to a concrete entry.\n   * Version labels win over tags when both could match — the explicit label is\n   * the more specific intent. Returns `undefined` when neither resolves.\n   */\n  private resolveSelector(\n    name: string,\n    selector: string,\n  ): PromptsManagerEntry | undefined {\n    const byVersion = this.entries.get(promptKey(name, selector));\n\n    if (byVersion) {\n      return byVersion;\n    }\n\n    const pinnedVersion = this.pins.get(name)?.get(selector);\n\n    if (pinnedVersion !== undefined) {\n      return this.entries.get(promptKey(name, pinnedVersion));\n    }\n\n    return undefined;\n  }\n\n  /**\n   * Resolve an entry by name (+ optional version / tag / inline selector),\n   * throwing {@link InvalidRequestError} when the name or the requested\n   * selector is unknown. The single lookup path `get` / `resolve` share.\n   */\n  private requireEntry(\n    name: string,\n    versionOrTag?: string,\n  ): PromptsManagerEntry {\n    const { baseName, selector } = this.parseSelector(name, versionOrTag);\n\n    if (selector !== undefined) {\n      const entry = this.resolveSelector(baseName, selector);\n\n      if (!entry) {\n        throw new InvalidRequestError(\n          `No prompt registered as \"${baseName}\" with version/tag \"${selector}\".`,\n          { context: { name: baseName, selector } },\n        );\n      }\n\n      return entry;\n    }\n\n    const latest = this.latestEntry(baseName);\n\n    if (!latest) {\n      throw new InvalidRequestError(\n        `No prompt registered under name \"${baseName}\".`,\n        { context: { name: baseName } },\n      );\n    }\n\n    return latest;\n  }\n\n  /**\n   * Resolve a name + EXACT version label to its entry (no tag fallback), for\n   * `diff` / `export` where a concrete version is always required. Throws\n   * {@link InvalidRequestError} on a miss.\n   */\n  private requireExact(name: string, version: string): PromptsManagerEntry {\n    const entry = this.entries.get(promptKey(name, version));\n\n    if (!entry) {\n      throw new InvalidRequestError(\n        `No prompt registered as \"${promptKey(name, version)}\".`,\n        { context: { name, version } },\n      );\n    }\n\n    return entry;\n  }\n}\n\n/**\n * Narrow an arbitrary value to a `SystemPromptContract` — true when it exposes\n * the builder surface (`blocks` array + a callable `resolve`) AND a callable\n * `meta`. Robust across duplicate package copies (no `instanceof`).\n */\nfunction isSystemPromptContract(\n  value: unknown,\n): value is SystemPromptContract {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    Array.isArray((value as { blocks?: unknown }).blocks) &&\n    typeof (value as { resolve?: unknown }).resolve === \"function\" &&\n    typeof (value as { meta?: unknown }).meta === \"function\"\n  );\n}\n\n/**\n * Narrow an arbitrary value to a single `SystemPromptBlockContract` — true when\n * it carries a string `type` + `text` and a callable `resolve` but is NOT a\n * full prompt (no `blocks` array). Lets `validate` accept a lone block.\n */\nfunction isBlock(value: unknown): value is SystemPromptBlockContract {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as { type?: unknown }).type === \"string\" &&\n    typeof (value as { text?: unknown }).text === \"string\" &&\n    typeof (value as { resolve?: unknown }).resolve === \"function\"\n  );\n}\n\n/**\n * Create a new, isolated prompts manager.\n *\n * **Role.** Public factory for {@link PromptsManagerContract} — keeps\n * user-facing code free of `new` and consistent with the other `ai.*`\n * factories. Each call returns a fresh registry, so parallel test suites and\n * multi-tenant apps never share mutable global prompt state.\n *\n * The process-wide instance that named `systemPrompt(...)` builders\n * auto-register into is `ai.prompts` (see {@link defaultPromptsManager}).\n *\n * @param options - Optional wiring, notably a `judgeCache` that memoizes\n *   LLM-judge verdicts (absent ⇒ every judge pass runs live).\n *\n * @example\n * const registry = prompts();\n * registry.register(systemPrompt(\"You are support.\", { name: \"support\" }));\n * registry.resolve(\"support\"); // \"You are support.\"\n *\n * @example\n * // Memoize judge verdicts across validations.\n * const registry = prompts({ judgeCache: new MemoryCacheDriver() });\n */\nexport function prompts(options?: PromptsManagerOptions): PromptsManagerContract {\n  return new PromptsManager(options);\n}\n\n/**\n * The process-wide default manager that named prompts auto-register into.\n *\n * Held as a module-level singleton (lazily created on first access) so\n * `system-prompt.ts` can register a named builder without importing the\n * `PromptsManager` class — keeping the auto-registration seam free of a\n * runtime import cycle.\n */\nlet defaultManager: PromptsManagerContract | undefined;\n\n/** Accessor for the process-wide default {@link PromptsManagerContract}. */\nexport function defaultPromptsManager(): PromptsManagerContract {\n  if (!defaultManager) {\n    defaultManager = new PromptsManager();\n  }\n\n  return defaultManager;\n}\n"],"mappings":";;;;;;;;;;;;AAsCA,SAAgB,UAAU,MAAc,SAAyB;CAC/D,OAAO,GAAG,KAAK,GAAG;AACpB;;;;;;;;AASA,SAAS,iBAA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