{"version":3,"file":"tool_call-Cfaj-6zK.mjs","names":["#id","#kind","#mimeType","#filename","#source","#trustTier","#modalityHazard","#reader","#stash","#id","#tool","#args","#checksum","#isComplete","#isError","#results","#payload","#replayCompatibility","#fromArtifactTool","#inline","#createdAt","#updatedAt","#completedAt"],"sources":["../src/lib/helpers/base64.ts","../src/lib/contracts/media_reader.ts","../src/lib/classes/media.ts","../src/lib/classes/tool_call.ts"],"sourcesContent":["/**\n * Cross-environment base64 helpers for `Uint8Array` payloads.\n *\n * @module\n *\n * @remarks\n * Used by {@link @nhtio/adk!Media}'s `asBase64()` and by the in-memory reader handle path\n * (`describe()`/resolver), which inlines its buffer as base64 because it owns no external locator. Both\n * directions prefer Node's `Buffer` when present and fall back to `btoa`/`atob` with a chunked window so\n * large buffers do not overflow the call stack.\n */\n\ninterface MinimalBuffer {\n  from(input: Uint8Array): { toString(enc: string): string }\n  from(input: string, enc: string): Uint8Array\n}\n\nconst getBuffer = (): MinimalBuffer | undefined => {\n  return (globalThis as { Buffer?: MinimalBuffer }).Buffer\n}\n\n/**\n * Encode a `Uint8Array` as a base64 string.\n *\n * @remarks\n * Prefers `Buffer.from(bytes).toString('base64')` when `globalThis.Buffer` exists; otherwise\n * chunk-encodes through `btoa` with a `0x8000`-byte window to avoid `Maximum call stack size exceeded`\n * on large buffers.\n *\n * @param bytes - The buffer to encode.\n * @returns The base64 representation.\n */\nexport const encodeBase64 = (bytes: Uint8Array): string => {\n  const buffer = getBuffer()\n  if (buffer && typeof buffer.from === 'function') {\n    return buffer.from(bytes).toString('base64')\n  }\n  const chunkSize = 0x8000\n  let binary = ''\n  for (let i = 0; i < bytes.length; i += chunkSize) {\n    const chunk = bytes.subarray(i, i + chunkSize)\n    binary += String.fromCharCode.apply(null, Array.from(chunk) as number[])\n  }\n  return btoa(binary)\n}\n\n/**\n * Decode a base64 string back into a `Uint8Array`.\n *\n * @remarks\n * Inverse of {@link encodeBase64}. Prefers `Buffer.from(b64, 'base64')` when `globalThis.Buffer` exists;\n * otherwise decodes through `atob` byte-by-byte.\n *\n * @param b64 - The base64 string to decode.\n * @returns The decoded bytes.\n */\nexport const decodeBase64 = (b64: string): Uint8Array => {\n  const buffer = getBuffer()\n  if (buffer && typeof buffer.from === 'function') {\n    const decoded = buffer.from(b64, 'base64')\n    // `Buffer` is a `Uint8Array` subclass; return a plain view over the same bytes.\n    return new Uint8Array(decoded)\n  }\n  const binary = atob(b64)\n  const out = new Uint8Array(binary.length)\n  for (let i = 0; i < binary.length; i++) {\n    out[i] = binary.charCodeAt(i)\n  }\n  return out\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { ReaderDescriptor } from './reader_descriptor'\n\n/**\n * Re-openable byte source contract for a Media instance.\n *\n * @remarks\n * Peer to {@link @nhtio/adk!SpoolReader} but tuned for binary streaming rather than line-indexed text.\n * Each `stream()` call must return a fresh, drainable `ReadableStream` over the same underlying\n * bytes — implementations model replay: in-memory readers reconstitute the stream from the\n * buffer, file-backed readers reopen the file handle, HTTP-backed readers re-issue the fetch,\n * cloud blob readers re-issue the GET. The implementor owns the storage and the cost of keeping\n * the underlying source addressable. Implementors whose underlying source is genuinely\n * non-replayable (a raw HTTP body they were handed once) are responsible for caching locally\n * before constructing the Media.\n *\n * Both methods may be synchronous or asynchronous to accommodate both in-memory and I/O-backed\n * implementations without forcing unnecessary promise overhead on simple cases.\n */\nexport interface MediaReader {\n  /**\n   * Re-opens the underlying byte source and returns a fresh ReadableStream.\n   *\n   * @remarks\n   * Each call yields a new, drainable stream over the same bytes. Render code that needs the\n   * full buffer (e.g. base64-encoding an inline image_url) drains the stream; render code that\n   * can forward the stream (e.g. multipart upload) passes the stream through without buffering.\n   *\n   * @returns A drainable ReadableStream of Uint8Array chunks over the underlying bytes.\n   */\n  stream(): ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>\n\n  /**\n   * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n   *\n   * @remarks\n   * Used for telemetry, budget checks, and pre-flight provider size validation without forcing\n   * a stream drain. Sources of unknown length may return `undefined` — absence is treated as\n   * \"unknown\", not \"zero\".\n   *\n   * @returns The byte length of the underlying data, or `undefined` when unknown.\n   */\n  byteLength(): number | undefined | Promise<number | undefined>\n\n  /**\n   * Optionally emit a serialisable {@link ReaderDescriptor} so a {@link @nhtio/adk!Media} backed by this\n   * reader can round-trip through `encode()`/`decode()` as a **handle**.\n   *\n   * @remarks\n   * Synchronous by contract — the encoder's `[ENCODE_METHOD]()` is synchronous and cannot await, so a\n   * reader whose handle is only obtainable asynchronously (e.g. draining a `Blob`) must NOT implement\n   * this method; encoding such a `Media` throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE}. The\n   * descriptor describes *where the bytes live* (a key, a URL, or an inlined buffer) — never the live\n   * binding (`Disk`, OPFS root, `fetch`), which the matching resolver re-injects on decode.\n   *\n   * A reader that omits this method is treated as non-describable: the bytes still stream normally at\n   * runtime, the `Media` simply cannot be serialised.\n   *\n   * @returns A tagged, serialisable handle, or `undefined`/absent when the reader cannot describe itself.\n   */\n  describe?(): ReaderDescriptor | undefined\n}\n\n/**\n * Validator schema used to validate a MediaReader value.\n *\n * @remarks\n * Because MediaReader is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be an object, class instance, or function with `stream` and\n * `byteLength` present as callable properties. Arity is not enforced.\n */\nexport const mediaReaderSchema = validator\n  .any()\n  .required()\n  .custom((value, helpers) => {\n    if (\n      value !== null &&\n      value !== undefined &&\n      typeof (value as any).stream === 'function' &&\n      typeof (value as any).byteLength === 'function'\n    ) {\n      return value as MediaReader\n    }\n    return helpers.error('any.invalid')\n  })\n\n/**\n * Returns `true` if `value` implements the MediaReader interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `stream` and `byteLength` as callable\n * functions. Does not use `instanceof` — there is no MediaReader constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the MediaReader interface.\n */\nexport const implementsMediaReader = (value: unknown): value is MediaReader => {\n  return passesSchema(mediaReaderSchema, value)\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Registry } from './registry'\nimport { isError } from '../utils/guards'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '../utils/guards'\nimport { encodeBase64 } from '../helpers/base64'\nimport { validateOrThrow } from '../utils/validation'\nimport { resolveMediaReader } from '../contracts/reader_resolvers'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { implementsMediaReader, mediaReaderSchema } from '../contracts/media_reader'\nimport {\n  E_INVALID_INITIAL_MEDIA_VALUE,\n  E_NOT_A_MEDIA_READER,\n  E_READER_NOT_DESCRIBABLE,\n} from '../exceptions/runtime'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { MediaReader } from '../contracts/media_reader'\nimport type { ReaderDescriptor } from '../contracts/reader_descriptor'\n\n/**\n * The set of supported media kinds.\n *\n * @remarks\n * Modality coverage is asymmetric across providers. The framework defines no\n * `supportedModalities` field — how a battery handles a modality it cannot natively render is\n * the battery author's call (see `unsupportedMediaPolicy` on the OpenAI Chat Completions\n * battery).\n */\nexport const MediaKind = ['image', 'audio', 'video', 'document'] as const\n\n/**\n * Union of all recognised media kind identifier strings.\n */\nexport type MediaKind = (typeof MediaKind)[number]\n\n/**\n * Provenance axis. *Who is the framework willing to vouch for as the source of these bytes?*\n *\n * @remarks\n * Mirrors `RetrievableTrustTier` deliberately — same vocabulary, same question:\n * *did this content come from a place the agent should treat as authoritative?*\n *\n * - `'first-party'` — deployer-vetted bytes (tool output the operator authored, signed\n *   internal assets).\n * - `'third-party-public'` — open-web fetches, public APIs, public corpora.\n * - `'third-party-private'` — user uploads, partner APIs, private corpora.\n */\nexport const MediaTrustTier = ['first-party', 'third-party-public', 'third-party-private'] as const\nexport type MediaTrustTier = (typeof MediaTrustTier)[number]\n\n/**\n * Modality-hazard axis. *How dangerous is it to let the model decode these bytes?*\n *\n * @remarks\n * Orthogonal to provenance — a first-party trusted PDF can still carry hidden text layers; a\n * third-party-public raw image can still be encoded as opaque pixels with adversarial\n * perturbations.\n *\n * - `'inert'` — bytes the model never decodes as instructions (e.g. a handle that is never\n *   inlined into the prompt).\n * - `'extractable-instructions'` — text-bearing media: PDFs, screenshots with UI text, documents.\n *   Hazard is OCR / embedded-text-layer reads.\n * - `'opaque-perceptual'` — raw vision/audio/video the model encodes directly. Hazard is\n *   steganographic LSB prompts, adversarial perturbations, ultrasonic audio — invisible to any\n *   pre-screen.\n *\n * See `/the-loop/trust-tiers/media` and its research sub-page `/the-loop/trust-tiers/media/research`.\n */\nexport const MediaModalityHazard = [\n  'inert',\n  'extractable-instructions',\n  'opaque-perceptual',\n] as const\nexport type MediaModalityHazard = (typeof MediaModalityHazard)[number]\n\n/**\n * Per-entry shape stored in a {@link Media}'s `stash` register.\n *\n * @remarks\n * Each entry carries its own trust tier so render code can route derived text (OCR, captions,\n * transcripts) through its own envelope independent of the parent media. How a battery or\n * middleware assigns those entry-level tiers is the implementor's call — the primitive contract\n * does not enforce a \"downgrade derived interpretation from possibly-adversarial bytes\" policy.\n */\nexport interface MediaStashEntry {\n  /** The value of the entry — any serialisable shape the consumer wants to store. */\n  value: unknown\n  /** Trust tier for this specific entry; routed independently of the parent media. */\n  trustTier: MediaTrustTier\n  /** Optional pointer to the parent Media id this entry was derived from. */\n  derivedFromMedia?: string\n}\n\n/**\n * Plain input object supplied to {@link Media} at construction time.\n *\n * @remarks\n * Validated against `rawMediaSchema` before the `Media` instance is created.\n */\nexport interface RawMedia {\n  /**\n   * Stable unique identifier for this media instance. Required for strict symmetry with\n   * `Message.id` and `ToolCall.id`. When omitted, a fresh UUIDv6 is assigned at construction\n   * time.\n   */\n  id?: string\n  /** The media kind. See {@link MediaKind}. */\n  kind: MediaKind\n  /** The MIME type of the underlying bytes. */\n  mimeType: string\n  /** Filename used by providers that key on it (e.g. OpenAI `file.filename`). */\n  filename: string\n  /** Re-openable byte source. See {@link @nhtio/adk!MediaReader}. */\n  reader: MediaReader\n  /**\n   * Trust tier declared at construction time. Required — there is NO default.\n   * See {@link MediaTrustTier}.\n   */\n  trustTier: MediaTrustTier\n  /**\n   * Modality hazard declared at construction time. Required — there is NO default.\n   * See {@link MediaModalityHazard}.\n   */\n  modalityHazard: MediaModalityHazard\n  /** Optional provenance pointer (URL, tool name, etc.) for audit / events. */\n  source?: string\n  /**\n   * Free-form per-instance metadata register. Middleware pipelines append to this — typically\n   * with a text description, transcript, caption, or alt-text — so downstream code that cannot\n   * consume the media natively has a model-readable fallback. No keys are reserved by the\n   * framework. Defaults to `{}`.\n   */\n  stash?: Record<string, MediaStashEntry>\n}\n\nconst stashEntrySchema = validator\n  .object<MediaStashEntry>({\n    value: validator.any().required(),\n    trustTier: validator\n      .string()\n      .valid(...MediaTrustTier)\n      .required(),\n    derivedFromMedia: validator.string().optional(),\n  })\n  .unknown(false)\n\n/**\n * Validator schema used to validate a {@link RawMedia} before constructing a {@link Media}.\n */\nconst rawMediaSchema = validator.object<RawMedia>({\n  id: validator.string().optional(),\n  kind: validator\n    .string()\n    .valid(...MediaKind)\n    .required(),\n  mimeType: validator.string().required(),\n  filename: validator.string().required(),\n  reader: mediaReaderSchema.required(),\n  trustTier: validator\n    .string()\n    .valid(...MediaTrustTier)\n    .required(),\n  modalityHazard: validator\n    .string()\n    .valid(...MediaModalityHazard)\n    .required(),\n  source: validator.string().optional(),\n  stash: validator.object().pattern(validator.string(), stashEntrySchema).optional(),\n})\n\ninterface ResolvedMedia {\n  id?: string\n  kind: MediaKind\n  mimeType: string\n  filename: string\n  reader: MediaReader\n  trustTier: MediaTrustTier\n  modalityHazard: MediaModalityHazard\n  source?: string\n  stash?: Record<string, MediaStashEntry>\n}\n\nconst conservativeHazardForKind = (kind: MediaKind): MediaModalityHazard => {\n  return kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n}\n\n/**\n * Shape returned by {@link Media.toJSON}. Metadata-only — bytes and the reader are stripped so\n * naive event/log serialisation never materialises bytes.\n */\n/** The plain-object, JSON-safe form of a {@link Media} produced by {@link Media.toJSON}. */\nexport interface SerializedMedia {\n  /** Stable identifier for this media asset. */\n  id: string\n  /** High-level modality of the asset (e.g. image, audio, document). */\n  kind: MediaKind\n  /** MIME type of the underlying bytes (e.g. `image/png`). */\n  mimeType: string\n  /** Original or suggested file name for the asset. */\n  filename: string\n  /** Optional provenance string (URL, path, or other origin marker). */\n  source?: string\n  /** Trust tier governing how the asset's content is framed to the model. */\n  trustTier: MediaTrustTier\n  /** Whether the modality can carry hidden instructions (`extractable-instructions`) or is opaque-perceptual. */\n  modalityHazard: MediaModalityHazard\n  /** Adapter-scoped side-channel data keyed by name (e.g. provider upload handles). */\n  stash: Record<string, MediaStashEntry>\n  /** Size of the underlying bytes in bytes, when known. */\n  byteLength?: number\n}\n\n/**\n * Lazy, re-openable view over a binary asset (image, audio, video, document).\n *\n * @remarks\n * Dual-peer to {@link @nhtio/adk!Tokenizable} (silo) and {@link @nhtio/adk!SpooledArtifact}\n * (handle). Wraps a {@link @nhtio/adk!MediaReader} contract — the framework owns the contract, the\n * implementor owns the storage backend. Bytes are reached only through the reader; the primitive\n * itself never inlines bytes.\n *\n * Construction requires `trustTier` and `modalityHazard` — the framework refuses to guess\n * provenance or decoding hazard. Ergonomic factories ({@link Media.userAttachment},\n * {@link Media.toolGenerated}, {@link Media.retrievedPublic}, {@link Media.retrievedPrivate})\n * force the labelling decision at the call site without becoming defaults on the bare\n * constructor.\n */\nexport class Media {\n  /**\n   * Validator schema that accepts a {@link RawMedia} object.\n   */\n  public static schema = rawMediaSchema\n\n  /**\n   * The set of recognised media kinds. Exposed for downstream schemas that need to discriminate\n   * on `kind`.\n   */\n  public static MediaKind = MediaKind\n\n  /**\n   * The set of recognised trust tiers.\n   */\n  public static MediaTrustTier = MediaTrustTier\n\n  /**\n   * The set of recognised modality hazards.\n   */\n  public static MediaModalityHazard = MediaModalityHazard\n\n  /**\n   * Returns `true` if `value` is a {@link Media} instance.\n   *\n   * @remarks\n   * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n   *\n   * @param value - The value to test.\n   * @returns `true` when `value` is a {@link Media} instance.\n   */\n  public static isMedia(value: unknown): value is Media {\n    return isInstanceOf(value, 'Media', Media)\n  }\n\n  /** Stable unique identifier. */\n  declare readonly id: string\n  /** Media kind. */\n  declare readonly kind: MediaKind\n  /** MIME type of the underlying bytes. */\n  declare readonly mimeType: string\n  /** Filename surfaced to providers that key on it. */\n  declare readonly filename: string\n  /** Optional provenance pointer. */\n  declare readonly source: string | undefined\n  /** Trust tier declared at construction time. */\n  declare readonly trustTier: MediaTrustTier\n  /** Modality hazard declared at construction time. */\n  declare readonly modalityHazard: MediaModalityHazard\n  /** Mutable per-instance metadata register; middleware pipelines append to this. */\n  declare readonly stash: Registry\n\n  #id: string\n  #kind: MediaKind\n  #mimeType: string\n  #filename: string\n  #source?: string\n  #trustTier: MediaTrustTier\n  #modalityHazard: MediaModalityHazard\n  #reader: MediaReader\n  #stash: Registry\n\n  /**\n   * @param raw - The raw media input validated against `rawMediaSchema`.\n   * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_MEDIA_VALUE} when `raw` does not satisfy the schema.\n   * @throws {@link @nhtio/adk/exceptions!E_NOT_A_MEDIA_READER} when `raw.reader` does not implement {@link @nhtio/adk!MediaReader}.\n   */\n  constructor(raw: RawMedia) {\n    let resolved: ResolvedMedia\n    try {\n      resolved = validateOrThrow<ResolvedMedia>(rawMediaSchema, raw, true)\n    } catch (err) {\n      throw new E_INVALID_INITIAL_MEDIA_VALUE({ cause: isError(err) ? err : undefined })\n    }\n    if (!implementsMediaReader(resolved.reader)) {\n      throw new E_NOT_A_MEDIA_READER()\n    }\n    this.#id = resolved.id ?? uuidv6()\n    this.#kind = resolved.kind\n    this.#mimeType = resolved.mimeType\n    this.#filename = resolved.filename\n    this.#source = resolved.source\n    this.#trustTier = resolved.trustTier\n    this.#modalityHazard = resolved.modalityHazard\n    this.#reader = resolved.reader\n    this.#stash = new Registry(resolved.stash as Record<string, unknown> | undefined)\n\n    Object.defineProperties(this, {\n      id: {\n        get: () => this.#id,\n        enumerable: true,\n        configurable: false,\n      },\n      kind: {\n        get: () => this.#kind,\n        enumerable: true,\n        configurable: false,\n      },\n      mimeType: {\n        get: () => this.#mimeType,\n        enumerable: true,\n        configurable: false,\n      },\n      filename: {\n        get: () => this.#filename,\n        enumerable: true,\n        configurable: false,\n      },\n      source: {\n        get: () => this.#source,\n        enumerable: true,\n        configurable: false,\n      },\n      trustTier: {\n        get: () => this.#trustTier,\n        enumerable: true,\n        configurable: false,\n      },\n      modalityHazard: {\n        get: () => this.#modalityHazard,\n        enumerable: true,\n        configurable: false,\n      },\n      stash: {\n        get: () => this.#stash,\n        enumerable: true,\n        configurable: false,\n      },\n    })\n  }\n\n  /**\n   * Re-opens the underlying byte source and returns a fresh ReadableStream.\n   *\n   * @returns A drainable `ReadableStream` over the underlying bytes.\n   */\n  async stream(): Promise<ReadableStream<Uint8Array>> {\n    return this.#reader.stream()\n  }\n\n  /**\n   * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n   *\n   * @returns The byte length, or `undefined` when the underlying source cannot report it.\n   */\n  async byteLength(): Promise<number | undefined> {\n    return this.#reader.byteLength()\n  }\n\n  /**\n   * Drains the reader's stream and returns the underlying bytes as a single `Uint8Array`.\n   *\n   * @remarks\n   * Convenience for callers that need the full buffer (e.g. inline base64 encoding). Forces\n   * full materialisation — large assets should be piped through {@link Media.stream} instead.\n   */\n  async asBytes(): Promise<Uint8Array> {\n    const stream = await this.stream()\n    const reader = stream.getReader()\n    const chunks: Uint8Array[] = []\n    let total = 0\n    while (true) {\n      const { value, done } = await reader.read()\n      if (done) break\n      if (value) {\n        chunks.push(value)\n        total += value.byteLength\n      }\n    }\n    const out = new Uint8Array(total)\n    let offset = 0\n    for (const chunk of chunks) {\n      out.set(chunk, offset)\n      offset += chunk.byteLength\n    }\n    return out\n  }\n\n  /**\n   * Drains the reader's stream and returns the underlying bytes as a base64 string.\n   *\n   * @remarks\n   * Cross-environment: prefers Node's `Buffer.from(buf).toString('base64')` when available;\n   * otherwise chunk-encodes through `btoa` with a 0x8000-byte window to avoid stack overflow\n   * on large buffers.\n   */\n  async asBase64(): Promise<string> {\n    const bytes = await this.asBytes()\n    return encodeBase64(bytes)\n  }\n\n  /**\n   * Returns the metadata-only serialisation of this Media. Bytes and the reader are stripped\n   * so naive event/log serialisation never materialises bytes.\n   *\n   * @remarks\n   * Implementations that have cheap, already-cached `byteLength` may opt to include it; this\n   * default implementation omits it to preserve the \"lazy by default\" invariant. Consumers that\n   * need byteLength on the serialised payload should call `await media.byteLength()` and merge\n   * the result.\n   */\n  toJSON(): SerializedMedia {\n    return {\n      id: this.#id,\n      kind: this.#kind,\n      mimeType: this.#mimeType,\n      filename: this.#filename,\n      source: this.#source,\n      trustTier: this.#trustTier,\n      modalityHazard: this.#modalityHazard,\n      stash: this.#stash.all() as Record<string, MediaStashEntry>,\n    }\n  }\n\n  /**\n   * Serialise this Media into an `@nhtio/encoder` snapshot — the **handle**, never the bytes.\n   *\n   * @remarks\n   * Emits every metadata field plus the reader's {@link @nhtio/adk!ReaderDescriptor} (via its\n   * `describe()` method). The bytes are not inlined: decode re-binds the reader from the descriptor\n   * through a registered resolver. Throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the backing\n   * reader cannot describe itself (e.g. a `fromWebFile` Blob reader) — there is no serialisable handle to\n   * write, and silently dropping the reader would decode into a handle pointing at nothing.\n   *\n   * @returns A snapshot consumed by {@link Media.[DECODE_METHOD]} / the encoder.\n   * @throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the reader has no `describe()`.\n   */\n  [ENCODE_METHOD](): AdkEncodableSnapshot {\n    const descriptor = this.#reader.describe?.()\n    if (!descriptor) {\n      throw new E_READER_NOT_DESCRIBABLE(['reader'])\n    }\n    return {\n      id: this.#id,\n      kind: this.#kind,\n      mimeType: this.#mimeType,\n      filename: this.#filename,\n      source: this.#source,\n      trustTier: this.#trustTier,\n      modalityHazard: this.#modalityHazard,\n      stash: this.#stash.all(),\n      reader: descriptor,\n    }\n  }\n\n  /**\n   * Reconstruct a {@link Media} from an {@link Media.[ENCODE_METHOD]} snapshot.\n   *\n   * @remarks\n   * Re-binds the reader from the captured descriptor through the registered resolver\n   * ({@link @nhtio/adk!resolveMediaReader}), then re-validates via the normal constructor. Throws\n   * {@link @nhtio/adk!E_NO_READER_RESOLVER} when no resolver is registered for the descriptor's tag.\n   *\n   * @param data - The snapshot produced by {@link Media.[ENCODE_METHOD]}.\n   * @returns A fully-validated {@link Media} backed by a freshly-resolved reader.\n   */\n  static [DECODE_METHOD](data: AdkEncodableSnapshot): Media {\n    const snapshot = data as {\n      id: string\n      kind: MediaKind\n      mimeType: string\n      filename: string\n      source?: string\n      trustTier: MediaTrustTier\n      modalityHazard: MediaModalityHazard\n      stash?: Record<string, MediaStashEntry>\n      reader: ReaderDescriptor\n    }\n    return new Media({\n      id: snapshot.id,\n      kind: snapshot.kind,\n      mimeType: snapshot.mimeType,\n      filename: snapshot.filename,\n      source: snapshot.source,\n      trustTier: snapshot.trustTier,\n      modalityHazard: snapshot.modalityHazard,\n      stash: snapshot.stash,\n      reader: resolveMediaReader(snapshot.reader),\n    })\n  }\n\n  /**\n   * Factory: constructs a {@link Media} representing a user-supplied attachment.\n   *\n   * @remarks\n   * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`\n   * (`document` → `'extractable-instructions'`; everything else → `'opaque-perceptual'`).\n   * Use the bare constructor when the conservative kind→hazard mapping is wrong for your case.\n   */\n  public static userAttachment(args: {\n    id?: string\n    kind: MediaKind\n    mimeType: string\n    filename: string\n    reader: MediaReader\n    source?: string\n    stash?: Record<string, MediaStashEntry>\n  }): Media {\n    return new Media({\n      ...args,\n      trustTier: 'third-party-private',\n      modalityHazard: conservativeHazardForKind(args.kind),\n    })\n  }\n\n  /**\n   * Factory: constructs a {@link Media} produced by a first-party tool.\n   *\n   * @remarks\n   * Pre-fills `trustTier: 'first-party'` and derives `modalityHazard` from `kind`.\n   */\n  public static toolGenerated(args: {\n    id?: string\n    kind: MediaKind\n    mimeType: string\n    filename: string\n    reader: MediaReader\n    source?: string\n    stash?: Record<string, MediaStashEntry>\n  }): Media {\n    return new Media({\n      ...args,\n      trustTier: 'first-party',\n      modalityHazard: conservativeHazardForKind(args.kind),\n    })\n  }\n\n  /**\n   * Factory: constructs a {@link Media} retrieved from a public third-party source.\n   *\n   * @remarks\n   * Pre-fills `trustTier: 'third-party-public'` and derives `modalityHazard` from `kind`.\n   */\n  public static retrievedPublic(args: {\n    id?: string\n    kind: MediaKind\n    mimeType: string\n    filename: string\n    reader: MediaReader\n    source?: string\n    stash?: Record<string, MediaStashEntry>\n  }): Media {\n    return new Media({\n      ...args,\n      trustTier: 'third-party-public',\n      modalityHazard: conservativeHazardForKind(args.kind),\n    })\n  }\n\n  /**\n   * Factory: constructs a {@link Media} retrieved from a private third-party source.\n   *\n   * @remarks\n   * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`.\n   */\n  public static retrievedPrivate(args: {\n    id?: string\n    kind: MediaKind\n    mimeType: string\n    filename: string\n    reader: MediaReader\n    source?: string\n    stash?: Record<string, MediaStashEntry>\n  }): Media {\n    return new Media({\n      ...args,\n      trustTier: 'third-party-private',\n      modalityHazard: conservativeHazardForKind(args.kind),\n    })\n  }\n}\n\n/**\n * Returns `true` if `value` is a {@link Media} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Media.isMedia}. Uses {@link @nhtio/adk!isInstanceOf} for\n * cross-realm safety.\n */\nexport const isMedia = (value: unknown): value is Media => {\n  return isInstanceOf(value, 'Media', Media)\n}\n","import { Media } from './media'\nimport { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isObject, isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_INVALID_INITIAL_TOOL_CALL_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { AdkEncodableSnapshot } from './encodable'\n\n/**\n * Union of every shape a {@link ToolCall.results} field may carry.\n *\n * @remarks\n * Three silos with distinct render-time semantics:\n *\n * - {@link @nhtio/adk!Tokenizable} — always singular. The {@link @nhtio/adk!ArtifactTool}\n *   carve-out: a model-visible text answer that explicitly opts out of artifact wrapping to\n *   break the recursive grep-on-the-grep-result loop.\n * - {@link @nhtio/adk!SpooledArtifact} or `SpooledArtifact[]` — bounded text output spooled to durable\n *   storage. A single tool call may legitimately produce multiple artifacts (e.g. one tool\n *   that returns N PR bodies). LLM adapters render either inline (full body in trust envelope)\n *   or as a handle reference (forged artifact-query tools).\n * - {@link @nhtio/adk!Media} or `Media[]` — binary modality output (image, audio, video, document).\n *   Adapters render as provider-specific content blocks (`image_url`, `input_audio`, `file`,\n *   etc.). Bytes are lazy — reached only through {@link @nhtio/adk!Media.stream}.\n */\nexport type ToolCallResults = Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n\nconst isToolCallResults = (value: unknown): value is ToolCallResults => {\n  if (Tokenizable.isTokenizable(value)) return true\n  if (SpooledArtifact.isSpooledArtifact(value)) return true\n  if (Media.isMedia(value)) return true\n  if (Array.isArray(value) && value.length > 0) {\n    const allMedia = value.every((entry) => Media.isMedia(entry))\n    if (allMedia) return true\n    const allSpooled = value.every((entry) => SpooledArtifact.isSpooledArtifact(entry))\n    if (allSpooled) return true\n  }\n  return false\n}\n\n/**\n * Plain input object supplied to {@link ToolCall} at construction time.\n *\n * @remarks\n * Validated against `rawToolCallSchema` before the `ToolCall` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawToolCall {\n  /** Stable unique identifier for this tool call; correlates the request with its result. */\n  id: string\n  /** Name of the tool the model has requested. */\n  tool: string\n  /**\n   * Arguments the model supplied for this tool call.\n   *\n   * @remarks\n   * Accepts either a plain object or a JSON-encoded string that deserialises to an object.\n   * Always exposed as a plain object on the constructed {@link ToolCall} instance.\n   */\n  args: string | Record<string, unknown>\n  /** Integrity checksum over `tool` and `args`; can be used to detect tampering before execution. */\n  checksum: string\n  /** `true` once the tool call has finished (successfully or not). */\n  isComplete: boolean\n  /** `true` when the tool execution produced an error; inspect `results` for detail. */\n  isError: boolean\n  /**\n   * Result returned by the tool, or error detail when `isError` is `true`.\n   *\n   * @remarks\n   * Three silos with distinct render-time semantics — see {@link ToolCallResults}:\n   *\n   * - For a normal {@link @nhtio/adk!Tool} call whose handler returned `string` or\n   *   `Uint8Array`, this is a {@link @nhtio/adk!SpooledArtifact} (or one of its subclasses) wrapping the\n   *   spooled bytes. Tools that legitimately produce multiple bounded artifacts may return\n   *   a `SpooledArtifact[]`.\n   * - For a `Tool` call whose handler returned a {@link @nhtio/adk!Media} or `Media[]`, this is the same\n   *   media handle(s) — the explicit-modality silo bypasses `SpooledArtifact` wrapping because\n   *   the bytes are binary and rendered as provider-specific content blocks, not text.\n   * - For an {@link @nhtio/adk!ArtifactTool} call (a forged artifact-query tool),\n   *   this is a {@link @nhtio/adk!Tokenizable} holding the raw model-visible answer — `ArtifactTool`\n   *   explicitly opts out of wrapping to break the recursive grep-on-the-grep-result loop.\n   *\n   * The ADK sets {@link RawToolCall.fromArtifactTool} on calls produced by an\n   * `ArtifactTool` so subsequent `forgeTools(ctx)` invocations can filter them out of the\n   * `callId` enum.\n   */\n  results: ToolCallResults\n  /**\n   * Optional vendor-opaque payload that round-trips back to a matching model wire.\n   *\n   * @remarks\n   * Carries provider metadata the ADK cannot interpret, such as Gemini's `thought_signature`\n   * on a function call, GPT-OSS's commentary-channel tag, or other vendor-opaque metadata\n   * that a provider needs echoed back.\n   *\n   * A present `payload` requires a present {@link RawToolCall.replayCompatibility} so the\n   * matching adapter wire shape is known.\n   *\n   * @defaultValue `undefined`\n   */\n  payload?: unknown\n  /**\n   * Optional free-form identifier describing which adapter wire-shape this tool call can be\n   * safely replayed into.\n   *\n   * @remarks\n   * A `replayCompatibility` without a `payload` is allowed — it documents intent without\n   * requiring an opaque blob.\n   *\n   * @defaultValue `undefined`\n   */\n  replayCompatibility?: string\n  /**\n   * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n   * invocation. Defaults to `false`.\n   *\n   * @remarks\n   * Set by the ADK's result-wrapping touch sites when `ArtifactTool.isArtifactTool(tool)`\n   * holds. Read by `SpooledArtifact.forgeTools(ctx)` when building each descriptor's `callId`\n   * enum — calls with this flag set are excluded so the model can't `artifact_grep` on a\n   * previous `artifact_grep` result. Optional in the raw shape (defaults to `false`); always\n   * defined on the constructed {@link ToolCall}.\n   *\n   * @defaultValue `false`\n   */\n  fromArtifactTool?: boolean\n  /**\n   * When `false` (the default), the adapter surfaces a {@link @nhtio/adk!SpooledArtifact} result as a\n   * \"handle\" — a directions-bearing envelope that tells the model which forged artifact-query tools to\n   * call against this `tc.id` to read the content incrementally, keeping the body OUT of the prompt.\n   * When `true`, the adapter renders the result inline — the full stringified body wrapped in the\n   * adapter's trust envelope and sent to the model as the `tool` role content.\n   *\n   * @remarks\n   * Handle-by-default is the secure, budget-aligned posture: the LLM batteries already spool-wrap every\n   * non-{@link @nhtio/adk!Media}, non-{@link @nhtio/adk!ArtifactTool} tool result into a `SpooledArtifact`,\n   * so a result that could be arbitrarily large never lands in the next prompt just because nobody\n   * touched a flag — the core ADK context-window-diet principle (see the Budgets / Artifacts docs).\n   * Inlining is the OPT-IN: a producer that knows its output is small sets `inline: true` so the model\n   * sees the body verbatim without a query round-trip.\n   *\n   * Policy is the producer's or middleware's call (LLM adapters obey the flag — they never size-check\n   * the result or silently switch modes). Set per call at construction, or flip mid-turn via\n   * `ctx.mutateToolCall(tc.id, { inline: true })`.\n   *\n   * Handles only make sense for `SpooledArtifact` (the only result kind the forged artifact-query tools\n   * can read). For a {@link @nhtio/adk!Tokenizable} result (e.g. an `ArtifactTool` answer or an error\n   * string) the flag is moot — the adapter renders it inline regardless, since there is no queryable\n   * artifact to hand back.\n   *\n   * @defaultValue `false`\n   */\n  inline?: boolean\n  /** When this tool call was first created. */\n  createdAt: string | number | Date | DateTime\n  /** When this tool call was last modified. */\n  updatedAt: string | number | Date | DateTime\n  /** When the tool call completed. */\n  completedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawToolCall} where temporal fields have been normalised to Luxon\n * `DateTime` instances.\n *\n * @remarks\n * Used internally by the {@link ToolCall} constructor to assign private fields with\n * guaranteed types.\n */\ninterface ResolvedToolCall {\n  id: string\n  tool: string\n  args: Record<string, unknown>\n  checksum: string\n  isComplete: boolean\n  isError: boolean\n  results: ToolCallResults\n  payload?: unknown\n  replayCompatibility?: string\n  fromArtifactTool: boolean\n  inline: boolean\n  createdAt: DateTime\n  updatedAt: DateTime\n  completedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawToolCall} before constructing a {@link ToolCall}.\n *\n * @remarks\n * Validates all fields of {@link RawToolCall}:\n * - `id` — required non-empty string.\n * - `tool` — required non-empty string.\n * - `args` — required; either a plain object or a JSON string that deserialises to an object.\n *   Strings are parsed and the resulting object is stored.\n * - `checksum` — required string.\n * - `isComplete` — required boolean.\n * - `isError` — required boolean.\n * - `results` — required; one of {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}, a non-empty\n *   `SpooledArtifact[]`, {@link @nhtio/adk!Media}, or a non-empty `Media[]`. Arrays must be homogeneous.\n * - `createdAt` / `updatedAt` / `completedAt` — required datetime-parseable values, normalised to `DateTime`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} (via the {@link ToolCall} constructor) when\n * validation fails.\n */\nconst rawToolCallSchema = validator\n  .object<RawToolCall>({\n    id: validator.string().required(),\n    tool: validator.string().required(),\n    args: validator\n      .alternatives(\n        validator.object().unknown(true),\n        validator.string().custom((value, helpers) => {\n          try {\n            const parsed = JSON.parse(value)\n            if (!isObject(parsed)) {\n              return helpers.error('any.invalid')\n            }\n            return parsed\n          } catch {\n            return helpers.error('any.invalid')\n          }\n        })\n      )\n      .required(),\n    checksum: validator.string().required(),\n    isComplete: validator.boolean().required(),\n    isError: validator.boolean().required(),\n    results: validator\n      .any()\n      .custom((value, helpers) => {\n        if (isToolCallResults(value)) {\n          return value\n        }\n        return helpers.error('any.invalid')\n      })\n      .required(),\n    payload: validator.any().optional(),\n    replayCompatibility: validator.string().min(1).optional(),\n    fromArtifactTool: validator.boolean().default(false),\n    inline: validator.boolean().default(false),\n    createdAt: validator.datetime().required(),\n    updatedAt: validator.datetime().required(),\n    completedAt: validator.datetime().required(),\n  })\n  .custom((value, helpers) => {\n    const v = value as RawToolCall\n    const hasPayload = v.payload !== undefined && v.payload !== null\n    if (hasPayload && (v.replayCompatibility === undefined || v.replayCompatibility === null)) {\n      return helpers.error('any.invalid')\n    }\n    return value\n  })\n\n/**\n * An immutable, validated tool call record associated with a turn.\n *\n * @remarks\n * Represents a completed tool invocation from the conversation history — `results`,\n * `completedAt`, `isComplete`, and `isError` are all present and required.\n * Temporal fields are normalised to Luxon `DateTime` instances at construction time.\n */\nexport class ToolCall {\n  /**\n   * Validator schema that accepts a {@link RawToolCall} object.\n   *\n   * @remarks\n   * Reusable fragment for any schema that needs to validate or nest a tool call entry.\n   */\n  public static schema = rawToolCallSchema\n\n  /**\n   * Returns `true` if `value` is a {@link ToolCall} instance.\n   *\n   * @remarks\n   * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety — `instanceof` would fail for instances\n   * created in a different module copy or VM context.\n   *\n   * @param value - The value to test.\n   * @returns `true` when `value` is a {@link ToolCall} instance.\n   */\n  public static isToolCall(value: unknown): value is ToolCall {\n    return isInstanceOf(value, 'ToolCall', ToolCall)\n  }\n\n  /** Stable unique identifier for this tool call; correlates the request with its result. */\n  declare readonly id: string\n  /** Name of the tool the model has requested. */\n  declare readonly tool: string\n  /** Arguments the model supplied for this tool call, always as a plain object. */\n  declare readonly args: Record<string, unknown>\n  /** Integrity checksum over `tool` and `args`. */\n  declare readonly checksum: string\n  /** `true` once the tool call has finished (successfully or not). */\n  declare readonly isComplete: boolean\n  /** `true` when the tool execution produced an error; inspect `results` for detail. */\n  declare readonly isError: boolean\n  /**\n   * Result returned by the tool, or error detail when `isError` is `true`.\n   *\n   * @remarks\n   * One of three silos — see {@link ToolCallResults}. {@link @nhtio/adk!SpooledArtifact} or\n   * `SpooledArtifact[]` for normal text-output {@link @nhtio/adk!Tool} calls;\n   * {@link @nhtio/adk!Media} or `Media[]` for tool calls whose handler returned binary modality output;\n   * {@link @nhtio/adk!Tokenizable} for {@link @nhtio/adk!ArtifactTool} calls\n   * (see {@link ToolCall.fromArtifactTool}).\n   */\n  declare readonly results: ToolCallResults\n  /**\n   * Optional vendor-opaque payload that round-trips back to a matching model wire.\n   * See {@link RawToolCall.payload}.\n   */\n  declare readonly payload: unknown\n  /**\n   * Optional wire-shape identifier describing which adapter can safely replay this tool call.\n   * See {@link RawToolCall.replayCompatibility}.\n   */\n  declare readonly replayCompatibility: string | undefined\n  /**\n   * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n   * invocation. Used by `SpooledArtifact.forgeTools(ctx)` to filter out forged-tool results from\n   * the `callId` enum it builds.\n   */\n  declare readonly fromArtifactTool: boolean\n  /**\n   * `false` (default) instructs LLM adapters to surface a `SpooledArtifact` result as a handle\n   * reference (body kept out of the prompt); `true` renders the result inline. See\n   * {@link RawToolCall.inline}.\n   */\n  declare readonly inline: boolean\n  /** When this tool call was first created. */\n  declare readonly createdAt: DateTime\n  /** When this tool call was last modified. */\n  declare readonly updatedAt: DateTime\n  /** When the tool call completed. */\n  declare readonly completedAt: DateTime\n\n  #id: string\n  #tool: string\n  #args: Record<string, unknown>\n  #checksum: string\n  #isComplete: boolean\n  #isError: boolean\n  #results: ToolCallResults\n  #payload: unknown\n  #replayCompatibility: string | undefined\n  #fromArtifactTool: boolean\n  #inline: boolean\n  #createdAt: DateTime\n  #updatedAt: DateTime\n  #completedAt: DateTime\n\n  /**\n   * @param raw - The raw tool call input validated against `rawToolCallSchema`.\n   * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} when `raw` does not satisfy the schema.\n   */\n  constructor(raw: RawToolCall) {\n    let resolved: ResolvedToolCall\n    try {\n      resolved = validateOrThrow<ResolvedToolCall>(rawToolCallSchema, raw, true)\n    } catch (err) {\n      throw new E_INVALID_INITIAL_TOOL_CALL_VALUE({ cause: isError(err) ? err : undefined })\n    }\n    this.#id = resolved.id\n    this.#tool = resolved.tool\n    this.#args = resolved.args\n    this.#checksum = resolved.checksum\n    this.#isComplete = resolved.isComplete\n    this.#isError = resolved.isError\n    this.#results = resolved.results\n    this.#payload = resolved.payload\n    this.#replayCompatibility = resolved.replayCompatibility\n    this.#fromArtifactTool = resolved.fromArtifactTool\n    this.#inline = resolved.inline\n    this.#createdAt = resolved.createdAt\n    this.#updatedAt = resolved.updatedAt\n    this.#completedAt = resolved.completedAt\n\n    Object.defineProperties(this, {\n      id: {\n        get: () => this.#id,\n        enumerable: true,\n        configurable: false,\n      },\n      tool: {\n        get: () => this.#tool,\n        enumerable: true,\n        configurable: false,\n      },\n      args: {\n        get: () => this.#args,\n        enumerable: true,\n        configurable: false,\n      },\n      checksum: {\n        get: () => this.#checksum,\n        enumerable: true,\n        configurable: false,\n      },\n      isComplete: {\n        get: () => this.#isComplete,\n        enumerable: true,\n        configurable: false,\n      },\n      isError: {\n        get: () => this.#isError,\n        enumerable: true,\n        configurable: false,\n      },\n      results: {\n        get: () => this.#results,\n        enumerable: true,\n        configurable: false,\n      },\n      payload: {\n        get: () => this.#payload,\n        enumerable: true,\n        configurable: false,\n      },\n      replayCompatibility: {\n        get: () => this.#replayCompatibility,\n        enumerable: true,\n        configurable: false,\n      },\n      fromArtifactTool: {\n        get: () => this.#fromArtifactTool,\n        enumerable: true,\n        configurable: false,\n      },\n      inline: {\n        get: () => this.#inline,\n        enumerable: true,\n        configurable: false,\n      },\n      createdAt: {\n        get: () => this.#createdAt,\n        enumerable: true,\n        configurable: false,\n      },\n      updatedAt: {\n        get: () => this.#updatedAt,\n        enumerable: true,\n        configurable: false,\n      },\n      completedAt: {\n        get: () => this.#completedAt,\n        enumerable: true,\n        configurable: false,\n      },\n    })\n  }\n\n  /**\n   * Serialise this ToolCall into an `@nhtio/encoder` snapshot.\n   *\n   * @remarks\n   * Emits a {@link RawToolCall}-shaped object. `results` is the live {@link ToolCallResults} union —\n   * a {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}(s), or {@link @nhtio/adk!Media}(s) —\n   * which the encoder recurses into; reader-backed results round-trip as handles (and throw\n   * {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} if a backing reader cannot describe itself). The `args`\n   * object and the producer-supplied `checksum` are emitted verbatim, so the constructor's\n   * checksum re-validation passes on decode. Round-trips via {@link ToolCall.[DECODE_METHOD]}.\n   *\n   * @returns A {@link RawToolCall}-shaped snapshot.\n   */\n  [ENCODE_METHOD](): AdkEncodableSnapshot {\n    return {\n      id: this.#id,\n      tool: this.#tool,\n      args: this.#args,\n      checksum: this.#checksum,\n      isComplete: this.#isComplete,\n      isError: this.#isError,\n      results: this.#results,\n      payload: this.#payload,\n      replayCompatibility: this.#replayCompatibility,\n      fromArtifactTool: this.#fromArtifactTool,\n      inline: this.#inline,\n      createdAt: this.#createdAt,\n      updatedAt: this.#updatedAt,\n      completedAt: this.#completedAt,\n    }\n  }\n\n  /**\n   * Reconstruct a {@link ToolCall} from a {@link ToolCall.[ENCODE_METHOD]} snapshot.\n   *\n   * @param data - The snapshot produced by {@link ToolCall.[ENCODE_METHOD]}.\n   * @returns A fully-validated {@link ToolCall}.\n   */\n  static [DECODE_METHOD](data: AdkEncodableSnapshot): ToolCall {\n    return new ToolCall(data as RawToolCall)\n  }\n}\n"],"mappings":";;;;;;;AAiBA,IAAM,kBAA6C;CACjD,OAAQ,WAA0C;AACpD;;;;;;;;;;;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