{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../ai/src/image/image.ts"],"sourcesContent":["import type {\n  GeneratedImage,\n  ImageModelContract,\n} from \"../contracts/image-model.contract\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\nimport type { ExecuteResult } from \"../contracts/result/execute-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AIError } from \"../errors/ai-error\";\nimport { ProviderError } from \"../errors/provider-error\";\nimport type { FlowObserveOption } from \"../observe/resolve-observers\";\nimport { notifyObservers } from \"../observe/resolve-observers\";\nimport { generateRunId } from \"../utils/generate-run-id\";\nimport { stampReportLineage } from \"../utils/stamp-report-lineage\";\nimport { computeImageCost } from \"./image-cost\";\n\n/**\n * Parameters for {@link image}. `model` comes from an adapter's\n * `image()` factory (`openai.image({ name })` / `google.image({ name })`);\n * the rest are provider-neutral generation knobs plus the standard\n * observability seam every verb shares.\n */\nexport type ImageParams = {\n  /** The image model to generate from (`sdk.image({ name })`). */\n  model: ImageModelContract;\n  /** Text description of the image(s) to generate. */\n  prompt: string;\n  /** How many images to generate. Adapters clamp to the provider max. */\n  count?: number;\n  /** Requested pixel size as `\"WxH\"` (e.g. `\"1024x1024\"`). */\n  size?: string;\n  /** Quality tier (e.g. `\"standard\"` / `\"hd\"`). */\n  quality?: string;\n  /** Aspect ratio (e.g. `\"1:1\"`, `\"16:9\"`) — ratio-based providers (Imagen). */\n  aspectRatio?: string;\n  /** Concepts to steer away from (Imagen `negativePrompt`). */\n  negativePrompt?: string;\n  /** Output container hint (`\"png\"` / `\"jpeg\"` / `\"webp\"`). */\n  format?: string;\n  /** Cancellation handle, wired into the provider request where supported. */\n  signal?: AbortSignal;\n  /**\n   * Observability routing for this call — same `observe` seam as\n   * agents / workflows. `true` routes to the globally registered\n   * observers; an `Observer` object routes flow-locally; `false` opts\n   * out; omitted follows the global observe-all flag.\n   */\n  observe?: FlowObserveOption;\n  /** Groups this call into a session for flat cost/trace queries. */\n  sessionId?: string;\n  /** Report node name (defaults to `\"image\"`). */\n  name?: string;\n  /** Provider-specific options forwarded verbatim to the adapter. */\n  options?: Record<string, unknown>;\n};\n\n/** Success payload of an {@link image} run. */\nexport type ImageData = {\n  /** The generated images, normalized to the discriminated shape. */\n  images: GeneratedImage[];\n};\n\n/**\n * The report node an {@link image} run produces — a {@link BaseReport}\n * (`type: \"image\"`) plus which model ran and how many images came back,\n * so panoptic and any flat-row consumer attribute the cost/latency\n * without special-casing.\n */\nexport type ImageReport = BaseReport & {\n  type: \"image\";\n  /** Identity of the image model this run used. */\n  model: { name: string; provider: string };\n  /** Number of images returned (0 on failure). */\n  imageCount: number;\n};\n\n/**\n * Result envelope of {@link image} — the same uniform\n * `{ data, error, usage, report }` every executable returns, narrowed\n * with the `\"image\"` discriminant.\n */\nexport type ImageResult = ExecuteResult<ImageData> & {\n  type: \"image\";\n  report: ImageReport;\n};\n\n/**\n * Generate one or more images from a text prompt — the image-output\n * counterpart to `ai.agent`, and the first verb of the output-modality\n * track (Theme I). Wraps an {@link ImageModelContract} (from\n * `openai.image(...)` / `google.image(...)`) in the framework's uniform\n * result contract:\n *\n * - **Never throws.** Provider failures (auth, rate-limit,\n *   content-filter, invalid request) surface as a typed `AIError` on\n *   `result.error`; `result.data` is then `undefined`.\n * - **Cost-truth.** When the model carries pricing, `result.usage.cost`\n *   is filled in — per-token for gpt-image-1, per-image for\n *   DALL·E / Imagen — folding into the same `Usage.cost` rollup as text.\n * - **Observable.** The completed {@link ImageReport} routes to any\n *   registered `Observer` (panoptic, OTel, …) via the shared `observe`\n *   seam, exactly like an agent run.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey });\n * const { data, error, usage } = await ai.image({\n *   model: openai.image({ name: \"gpt-image-1\" }),\n *   prompt: \"an isometric office desk, soft studio lighting\",\n *   size: \"1024x1024\",\n * });\n *\n * if (error) console.warn(error.code);\n * else for (const img of data.images) save(img); // { type: \"base64\" | \"url\", ... }\n */\nexport async function image(params: ImageParams): Promise<ImageResult> {\n  const { model, prompt } = params;\n\n  const runId = generateRunId(\"image\");\n  const startedAt = new Date().toISOString();\n  const startPerf = performance.now();\n\n  const usage: Usage = { input: 0, output: 0, total: 0 };\n  let data: ImageData | undefined;\n  let error: AIError | undefined;\n  let status: ImageReport[\"status\"] = \"completed\";\n  let imageCount = 0;\n\n  try {\n    const response = await model.generate(prompt, {\n      count: params.count,\n      size: params.size,\n      quality: params.quality,\n      aspectRatio: params.aspectRatio,\n      negativePrompt: params.negativePrompt,\n      format: params.format,\n      signal: params.signal,\n      ...params.options,\n    });\n\n    // Preserve every usage channel the adapter reported (cached /\n    // reasoning / cache-write, and any adapter-supplied `cost`), mirroring\n    // how the agent path routes provider usage. Then honor a pre-priced\n    // response or compute image cost — `usage.cost ??= …` precedence, same\n    // as the agent path.\n    Object.assign(usage, response.usage);\n\n    if (usage.cost === undefined) {\n      const cost = computeImageCost(usage, response.images.length, params.size, model.pricing);\n      if (cost !== undefined) {\n        usage.cost = cost;\n      }\n    }\n\n    data = { images: response.images };\n    imageCount = response.images.length;\n  } catch (thrown) {\n    error = thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });\n    // A caller-aborted run is \"cancelled\", not \"failed\" — keep the typed\n    // cause but distinguish the terminal status for dashboards/retry policy.\n    status = params.signal?.aborted ? \"cancelled\" : \"failed\";\n  }\n\n  const report: ImageReport = {\n    runId,\n    rootRunId: runId,\n    name: params.name ?? \"image\",\n    type: \"image\",\n    status,\n    error,\n    startedAt,\n    endedAt: new Date().toISOString(),\n    duration: performance.now() - startPerf,\n    usage,\n    children: [],\n    model: { name: model.name, provider: model.provider },\n    imageCount,\n    reportSchemaVersion: REPORT_SCHEMA_VERSION,\n  };\n\n  stampReportLineage(report, { rootRunId: runId, sessionId: params.sessionId });\n\n  await notifyObservers(params.observe, report);\n\n  return { type: \"image\", data, error, usage, report };\n}\n\n/** Best-effort message for a non-`AIError` thrown value. */\nf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