{"version":3,"file":"AIConversationController.mjs","names":[],"sources":["../../../../../../src/plugins/AIComponents/Conversation/controller/AIConversationController.ts"],"sourcesContent":["import { StateStore } from '@stream-io/state-store';\n\nimport {\n  type AIMessageComposerStore,\n  createAIMessageComposerStore,\n} from '../../AIMessageComposer/store';\nimport type { AIChatOption } from '../../AIMessageComposer/ChatOptions';\nimport type { AIMessageRating, AIReplyActionsProps } from '../../Message/AIReplyActions';\nimport type { AIToolApprover } from '../../ToolCalls/AIToolApprover';\nimport type { AIMessage, AIPendingMessage } from '../types';\nimport { AIAgentError } from './AIAgentError';\nimport {\n  AIConversationExchange,\n  generateId,\n  hasEmptyContent,\n} from './AIConversationExchange';\nimport { editActionOf, latestUserMessageIdOf, replyActionsOf } from './offers';\nimport {\n  type AIAgentActivity,\n  AIAgentActivityStates,\n  type AIConversationActions,\n  type AIConversationFeed,\n  type AIConversationRequest,\n  type AIConversationStatus,\n  type AIConversationTransport,\n  isAIConversationAnswering,\n} from './types';\n\nexport type AIConversationControllerState<Message extends AIMessage = AIMessage> = {\n  /** The conversation as it shows, oldest message first. */\n  messages: readonly Message[];\n  /**\n   * The message the person sent last that is not in the conversation yet. It stays until its\n   * reply starts, and after it was stopped or failed, while `retry()` can send it again.\n   */\n  pendingMessage: AIPendingMessage | undefined;\n  /** Where the latest exchange with the agent is. */\n  status: AIConversationStatus;\n  /**\n   * Why the latest request failed, or, as an `AIAgentError`, what the agent said when it couldn't\n   * answer or that it didn't answer in time. It stays until the next request, or until a reply\n   * starts after all.\n   */\n  error: Error | undefined;\n  /** What the agent says it is doing besides what its reply shows, such as checking sources. */\n  activity: AIAgentActivity | undefined;\n  /** Whether the conversation has messages before the first one, which `loadOlderMessages` loads. */\n  hasOlderMessages: boolean;\n  /**\n   * How the person rated replies, by the reply's id: the rating they gave in the browser, or else\n   * the reply's own `rating`.\n   */\n  ratings: Readonly<Record<string, AIMessageRating>>;\n};\n\nexport type AIConversationControllerOptions<Message extends AIMessage = AIMessage> = {\n  /** How the conversation reaches the agent and learns what it holds. Connected straight away. */\n  transport: AIConversationTransport<Message>;\n  /** What the conversation's views offer. All of them by default. */\n  actions?: AIConversationActions;\n  /** Who answers tool calls' questions and sign-ins in the browser, which the conversation asks them. */\n  approver?: AIToolApprover;\n  /** What the person writes, such as a store the app fills itself. A new one by default. */\n  composer?: StateStore<AIMessageComposerStore>;\n  /**\n   * How many milliseconds the controller waits, once the agent has the request, for the agent to\n   * start its reply or say what it is doing, before it shows an `AIAgentError`. While the agent\n   * says it is working, such as thinking, it waits as long as that takes. Five minutes by default;\n   * `null` or `Infinity` waits as long as it takes.\n   */\n  replyTimeout?: number | null;\n};\n\n/** What the person sends: what `AIMessageComposer` hands on. */\nexport type AIConversationSendData = {\n  text: string;\n  /** The files the person picked. */\n  attachments?: File[];\n  /** The option the person picked in the composer. */\n  chatOption?: AIChatOption;\n  custom?: Record<string, unknown>;\n};\n\nconst DEFAULT_REPLY_TIMEOUT = 5 * 60 * 1000;\n// The longest `setTimeout` waits; anything longer waits as long as it takes.\nconst MAX_TIMEOUT = 2 ** 31 - 1;\n\nconst ALL_ACTIONS: Required<AIConversationActions> = {\n  edit: true,\n  rate: true,\n  regenerate: true,\n};\n\nconst isAbortError = (error: unknown) =>\n  (error as { name?: unknown } | null)?.name === 'AbortError';\n\nconst asError = (error: unknown) =>\n  error instanceof Error ? error : new Error(String(error));\n\nconst sameItems = <T>(a: readonly T[], b: readonly T[]) =>\n  a.length === b.length && a.every((item, index) => item === b[index]);\n\nconst sameRatings = (\n  a: Readonly<Record<string, AIMessageRating>>,\n  b: Readonly<Record<string, AIMessageRating>>,\n) => {\n  const keys = Object.keys(a);\n  return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);\n};\n\n// A rating the person gave a reply in the browser, shown in place of the reply's own.\ntype RatingChange = {\n  shown: AIMessageRating | null;\n  // What the transport has, which the rating goes back to when it can't take a new one.\n  sent: AIMessageRating | null;\n  // Tells the latest rating of the reply apart from those before it.\n  attempt: number;\n  // Sends the latest rating, after those before it.\n  sending?: Promise<void>;\n};\n\n/**\n * The state behind an AI conversation, and what the person does in it.\n *\n * It holds the conversation's messages, where the latest exchange with the agent is and why it\n * failed, and it sends what the person asks through its `AIConversationTransport`. Give it to\n * `AIConversation` and `AIMessageComposer` as `conversation`, which show it and act on it:\n * sending, stopping, regenerating and rating replies, and editing the person's latest message.\n *\n * Create it in an effect and dispose of it in that effect's cleanup, so React's StrictMode,\n * which runs effects twice, ends with a controller that is connected:\n *\n * ```tsx\n * const [conversation, setConversation] = useState<AIConversationController>();\n * useEffect(() => {\n *   const controller = new AIConversationController({ transport });\n *   setConversation(controller);\n *   return () => controller.dispose();\n * }, [transport]);\n *\n * if (!conversation) return null;\n * <AIConversation conversation={conversation} />\n * <AIMessageComposer conversation={conversation}>…</AIMessageComposer>\n * ```\n *\n * What the person sends shows straight away, and the agent thinks until its reply starts. While\n * a reply is written again, or a message the person edited is answered again, the messages it\n * replaces are left out of `messages` until the new reply starts.\n */\nexport class AIConversationController<Message extends AIMessage = AIMessage> {\n  /** The conversation's state, to follow with `useStateStore`. */\n  readonly state: StateStore<AIConversationControllerState<Message>>;\n  /** What the person is writing: `AIMessageComposer` shows it, and editing a message fills it. */\n  readonly composer: StateStore<AIMessageComposerStore>;\n  /** Who answers tool calls' questions and sign-ins in the browser. */\n  readonly approver: AIToolApprover | undefined;\n  /** What the conversation's views offer the person to do with its messages. */\n  readonly actions: Required<AIConversationActions>;\n\n  private readonly transport: AIConversationTransport<Message>;\n  private readonly replyTimeout: number | null;\n  private readonly disconnect: (() => void) | undefined;\n  private disposed = false;\n  // The messages as the transport last told them, including those left out of `messages`.\n  private received: readonly Message[] = [];\n  // The latest request, until its reply starts or another request takes its place.\n  private exchange: AIConversationExchange<Message> | undefined;\n  // Counts the requests and stops, so the outcome of one that was overtaken is ignored.\n  private generation = 0;\n  // Replies stopped while they were written, which are finished whatever they say.\n  private stopped = new Set<string>();\n  private activity: AIAgentActivity | undefined;\n  // Whether what the agent says it is doing is ignored, after it was stopped, until it stops\n  // saying anything.\n  private ignoresActivity = false;\n  private error: Error | undefined;\n  private hasOlderMessages = false;\n  // The latest stop, which the next request waits for: the agent would stop that one too.\n  private stopping: Promise<void> | undefined;\n  // Ends the wait for the latest request's reply when the agent says nothing for too long.\n  private replyTimer: ReturnType<typeof setTimeout> | undefined;\n  private edited: Message | undefined;\n  private ratingChanges = new Map<string, RatingChange>();\n  private ratingAttempts = 0;\n  private isLoadingOlderMessages = false;\n  // The object URLs the files the person picked show from while their message is on its way.\n  private fileURLs = new Map<File, string>();\n\n  constructor({\n    actions,\n    approver,\n    composer,\n    replyTimeout = DEFAULT_REPLY_TIMEOUT,\n    transport,\n  }: AIConversationControllerOptions<Message>) {\n    this.transport = transport;\n    this.composer = composer ?? createAIMessageComposerStore();\n    this.approver = approver;\n    this.actions = { ...ALL_ACTIONS, ...actions };\n    this.replyTimeout = replyTimeout;\n    this.state = new StateStore<AIConversationControllerState<Message>>({\n      activity: undefined,\n      error: undefined,\n      hasOlderMessages: false,\n      messages: [],\n      pendingMessage: undefined,\n      ratings: {},\n      status: 'ready',\n    });\n    const disconnect = transport.connect(this.makeFeed());\n    this.disconnect = typeof disconnect === 'function' ? disconnect : undefined;\n  }\n\n  /**\n   * The person's message they are editing in the composer, which the next message they send\n   * replaces. The composer shows that they are editing it, with a button that cancels it.\n   */\n  get editingMessage() {\n    return this.composer.getLatestValue().isEditing ? this.edited : undefined;\n  }\n\n  /** Stops following the transport and lets go of what is on its way. */\n  dispose() {\n    if (this.disposed) return;\n    this.disposed = true;\n    this.clearReplyTimer();\n    this.disconnect?.();\n    if (typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {\n      this.fileURLs.forEach((url) => URL.revokeObjectURL(url));\n    }\n    this.fileURLs.clear();\n  }\n\n  // What the person does\n\n  /** Sends a message, or the person's edit of the message they are editing. */\n  send({ attachments = [], chatOption, custom, text }: AIConversationSendData) {\n    if (text.trim() === '' && attachments.length === 0) return;\n    const editing = this.editingMessage;\n    this.edited = undefined;\n    if (this.composer.getLatestValue().isEditing)\n      this.composer.partialNext({ isEditing: false });\n    this.start({\n      attachments,\n      chatOption,\n      custom,\n      kind: editing ? 'edit' : 'message',\n      message: editing,\n      messageId: generateId(),\n      text,\n    });\n  }\n\n  /**\n   * Stops the reply the agent is writing. What it wrote so far stays. When the reply hasn't\n   * started yet, the person's message stays, and a reply that still arrives is finished whatever\n   * it says.\n   */\n  stop() {\n    if (!isAIConversationAnswering(this.state.getLatestValue().status)) return;\n    const id = ++this.generation;\n    this.activity = undefined;\n    this.ignoresActivity = true;\n    if (this.exchange?.state === 'waiting') this.exchange.state = 'stopped';\n    const writing = this.writingReply;\n    if (writing) this.stopped.add(writing);\n    this.refresh();\n    this.stopping = (async () => {\n      try {\n        await this.transport.stop();\n      } catch (error) {\n        this.stopFailed(id, writing, error);\n      }\n    })();\n  }\n\n  /** Asks the agent for a new reply in place of `reply`, and of those after it. */\n  regenerate(reply: Message) {\n    const index = this.indexOf(reply);\n    if (index < 0 || this.received[index].role === 'user') return;\n    this.start(this.regenerateRequest(index));\n  }\n\n  /** Puts a message of the person's in the composer to edit. The next message they send replaces it. */\n  edit(message: Message) {\n    if (message.role !== 'user') return;\n    this.edited = message;\n    this.composer.partialNext({ isEditing: true, text: message.text });\n  }\n\n  /** Stops editing a message, and empties the composer. */\n  cancelEditing() {\n    if (!this.editingMessage) return;\n    this.edited = undefined;\n    this.composer.partialNext({ isEditing: false, text: '' });\n  }\n\n  /**\n   * Tries again after `error`: sends the request that failed again, with the same message id, or\n   * asks the agent again for the reply it couldn't write.\n   */\n  retry() {\n    const { exchange } = this;\n    if (!exchange?.hasFailed) return;\n    this.start(exchange.retryRequest(this.received));\n  }\n\n  /** Forgets `error`, and the request that failed. */\n  clearError() {\n    this.error = undefined;\n    if (this.exchange?.hasFailed) this.exchange = undefined;\n    this.refresh();\n  }\n\n  /**\n   * Rates a reply, or takes the rating back with `null`. Ratings reach the transport in the order\n   * the person gives them, and the reply's rating goes back to the one the transport has if it\n   * can't take the new one.\n   */\n  rate(reply: Message, rating: AIMessageRating | null) {\n    const current = this.state.getLatestValue().ratings[reply.id] ?? null;\n    if (current === rating) return;\n    const attempt = ++this.ratingAttempts;\n    const change = this.ratingChanges.get(reply.id) ?? {\n      attempt: 0,\n      sent: current,\n      shown: current,\n    };\n    const earlier = change.sending;\n    change.shown = rating;\n    change.attempt = attempt;\n    change.sending = (async () => {\n      await earlier;\n      await this.sendRating(rating, reply, attempt);\n    })();\n    this.ratingChanges.set(reply.id, change);\n    this.refresh();\n  }\n\n  /**\n   * Loads the messages before the first one, while there are any. Rejects when they couldn't load,\n   * so the conversation waits before it asks again.\n   */\n  loadOlderMessages = async () => {\n    if (!this.hasOlderMessages || this.isLoadingOlderMessages) return;\n    this.isLoadingOlderMessages = true;\n    try {\n      await this.transport.loadOlderMessages?.();\n    } finally {\n      this.isLoadingOlderMessages = false;\n    }\n  };\n\n  // What the conversation's views offer\n\n  /**\n   * What the person can do with a finished reply: rate it, and write it again while it is the\n   * latest and the agent isn't answering.\n   */\n  replyActions(\n    reply: Message,\n    isLatestReply: boolean,\n  ): Omit<AIReplyActionsProps, 'text'> {\n    return replyActionsOf(this, this.state.getLatestValue(), reply, isLatestReply);\n  }\n\n  /** Edits a message of the person's, when it is their latest and the agent isn't answering. */\n  editAction(message: Message): (() => void) | undefined {\n    const { messages, status } = this.state.getLatestValue();\n    return editActionOf(\n      this,\n      { latestUserMessageId: latestUserMessageIdOf(messages), status },\n      message,\n    );\n  }\n\n  // What the transport says\n\n  private makeFeed(): AIConversationFeed<Message> {\n    const isDisposed = () => this.disposed;\n    return {\n      get isConnected() {\n        return !isDisposed();\n      },\n      updateActivity: (activity) => {\n        if (!this.disposed) this.receiveActivity(activity);\n      },\n      updateHasOlderMessages: (hasOlderMessages) => {\n        if (this.disposed || this.hasOlderMessages === hasOlderMessages) return;\n        this.hasOlderMessages = hasOlderMessages;\n        this.refresh();\n      },\n      updateMessages: (messages) => {\n        if (!this.disposed) this.receiveMessages(messages);\n      },\n    };\n  }\n\n  private receiveMessages(messages: readonly Message[]) {\n    this.received = messages;\n    const { exchange } = this;\n    const reply = exchange?.reply(messages);\n    if (exchange && reply) this.receiveReply(reply, exchange);\n    this.refresh();\n  }\n\n  private receiveActivity(activity: AIAgentActivity | undefined) {\n    if (!activity) {\n      this.ignoresActivity = false;\n      this.activity = undefined;\n      // The agent stopped saying it is working without starting its reply.\n      if (this.exchange?.state === 'waiting') this.waitForReply(this.exchange.id);\n      this.refresh();\n      return;\n    }\n    if (this.ignoresActivity) return;\n    this.activity = activity;\n    if (activity.state === AIAgentActivityStates.error) {\n      this.agentCouldNotAnswer(new AIAgentError(activity.text));\n    } else {\n      // The agent is working on it, however long it thinks.\n      this.clearReplyTimer();\n    }\n    this.refresh();\n  }\n\n  // Private\n\n  private start(request: AIConversationRequest<Message>) {\n    const id = ++this.generation;\n    this.error = undefined;\n    this.activity = undefined;\n    this.ignoresActivity = false;\n    this.stopped = new Set();\n    this.clearReplyTimer();\n    this.exchange = new AIConversationExchange(id, request, this.received, this.urlOf);\n    this.refresh();\n    const previousStop = this.stopping;\n    void (async () => {\n      // The agent would stop a request that reaches it before the stop made before it.\n      await previousStop;\n      if (this.disposed) return;\n      try {\n        await this.transport.send(request);\n        this.requestSent(id);\n      } catch (error) {\n        this.requestFailed(id, error);\n      }\n    })();\n  }\n\n  // The reply to the latest request arrived: once it shows something, or as soon as it arrives\n  // after the person stopped the request.\n  private receiveReply(reply: Message, exchange: AIConversationExchange<Message>) {\n    if (exchange.state === 'stopped') {\n      if (reply.isGenerating) this.stopped.add(reply.id);\n      this.exchange = undefined;\n    } else if (!hasEmptyContent(reply) || !reply.isGenerating) {\n      this.exchange = undefined;\n      this.clearReplyTimer();\n      if (exchange.hasFailed) {\n        // The agent answered after all.\n        this.error = undefined;\n        this.stopped.delete(reply.id);\n      }\n    }\n  }\n\n  private requestSent(id: number) {\n    const { exchange } = this;\n    // The agent may already say it is working on it.\n    if (\n      this.disposed ||\n      exchange?.id !== id ||\n      exchange.state !== 'waiting' ||\n      this.activity\n    ) {\n      return;\n    }\n    this.waitForReply(id);\n  }\n\n  private requestFailed(id: number, error: unknown) {\n    const { exchange } = this;\n    // Its reply started, so the agent had it, another request took its place, or it already\n    // failed.\n    if (this.disposed || exchange?.id !== id || exchange.hasFailed) return;\n    if (isAbortError(error)) {\n      this.exchange = undefined;\n    } else {\n      exchange.state = 'failed';\n      this.error = asError(error);\n    }\n    this.refresh();\n  }\n\n  // The agent goes on answering, and the composer offers to stop it again.\n  private stopFailed(id: number, writing: string | undefined, error: unknown) {\n    if (this.disposed || id !== this.generation || isAbortError(error)) return;\n    if (writing) this.stopped.delete(writing);\n    const { exchange } = this;\n    if (exchange?.state === 'stopped') {\n      exchange.state = 'waiting';\n      this.waitForReply(exchange.id);\n    }\n    this.ignoresActivity = false;\n    this.refresh();\n  }\n\n  // The agent couldn't answer the latest request, or the latest message: what it was writing is\n  // finished, and `retry()` asks it again.\n  private agentCouldNotAnswer(error: AIAgentError) {\n    const writing = this.writingReply;\n    if (writing) this.stopped.add(writing);\n    const request = this.exchange ? undefined : this.answerAgainRequest;\n    if (request) {\n      this.exchange = new AIConversationExchange(\n        ++this.generation,\n        request,\n        this.received,\n        this.urlOf,\n      );\n    }\n    if (this.exchange) this.exchange.state = 'unanswered';\n    this.clearReplyTimer();\n    this.error = error;\n  }\n\n  private waitForReply(id: number) {\n    this.clearReplyTimer();\n    const timeout = this.replyTimeout;\n    if (timeout === null || !Number.isFinite(timeout) || timeout > MAX_TIMEOUT) return;\n    this.replyTimer = setTimeout(() => this.replyTimedOut(id), Math.max(timeout, 0));\n  }\n\n  private clearReplyTimer() {\n    if (this.replyTimer !== undefined) clearTimeout(this.replyTimer);\n    this.replyTimer = undefined;\n  }\n\n  private replyTimedOut(id: number) {\n    this.replyTimer = undefined;\n    const { exchange } = this;\n    if (this.disposed || exchange?.id !== id || exchange.state !== 'waiting') return;\n    this.agentCouldNotAnswer(new AIAgentError());\n    this.refresh();\n  }\n\n  // Sends the latest rating of a reply. Those it replaced while one was on its way aren't.\n  private async sendRating(\n    rating: AIMessageRating | null,\n    reply: Message,\n    attempt: number,\n  ) {\n    if (this.disposed || this.ratingChanges.get(reply.id)?.attempt !== attempt) return;\n    try {\n      await this.transport.rate?.(reply, rating);\n      const change = this.ratingChanges.get(reply.id);\n      if (change) change.sent = rating;\n    } catch {\n      const change = this.ratingChanges.get(reply.id);\n      if (this.disposed || !change || change.attempt !== attempt) return;\n      change.shown = change.sent;\n      this.refresh();\n    }\n  }\n\n  // Asks for a new reply in place of the one at `index`, to the person's message before it.\n  private regenerateRequest(index: number): AIConversationRequest<Message> {\n    const prompt = this.received\n      .slice(0, index)\n      .reverse()\n      .find((message) => message.role === 'user');\n    return {\n      attachments: [],\n      kind: 'regenerate',\n      message: this.received[index],\n      messageId: generateId(),\n      text: prompt?.text ?? '',\n    };\n  }\n\n  // Asks again for the latest message's reply: the reply written again, or one to the person's\n  // message, which has none.\n  private get answerAgainRequest(): AIConversationRequest<Message> | undefined {\n    const last = this.received.length - 1;\n    if (last < 0) return undefined;\n    if (this.received[last].role !== 'user') return this.regenerateRequest(last);\n    return {\n      attachments: [],\n      kind: 'regenerate',\n      messageId: generateId(),\n      text: this.received[last].text,\n    };\n  }\n\n  // Where a file the person picked shows from while their message is on its way: one object URL\n  // per file, made once, and let go of once the controller is disposed.\n  private urlOf = (file: File) => {\n    const known = this.fileURLs.get(file);\n    if (known !== undefined || this.disposed) return known;\n    if (typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') {\n      return undefined;\n    }\n    const url = URL.createObjectURL(file);\n    this.fileURLs.set(file, url);\n    return url;\n  };\n\n  // The latest reply, while the agent writes it.\n  private get writingReply() {\n    const last = this.received[this.received.length - 1];\n    return last && last.role !== 'user' && last.isGenerating ? last.id : undefined;\n  }\n\n  private indexOf(message: Message) {\n    return this.received.findIndex((item) => item.id === message.id);\n  }\n\n  // Works out what the conversation shows and where it is, after anything changes.\n  private refresh() {\n    const current = this.state.getLatestValue();\n    const replaced =\n      this.exchange?.state === 'waiting' ? this.exchange.replaced : undefined;\n    let messages: readonly Message[] =\n      !replaced && this.stopped.size === 0\n        ? this.received\n        : this.received.filter(\n            (message) =>\n              // A reply stopped before it showed anything has nothing to show, and the\n              // conversation would think it is still on its way.\n              !replaced?.has(message.id) &&\n              !(this.stopped.has(message.id) && hasEmptyContent(message)),\n          );\n    if (sameItems(messages, current.messages)) messages = current.messages;\n    const shownPending = this.exchange?.shownPending;\n    const pendingMessage =\n      current.pendingMessage?.id === shownPending?.id\n        ? current.pendingMessage\n        : shownPending;\n    const nextRatings = this.currentRatings();\n    const ratings = sameRatings(nextRatings, current.ratings)\n      ? current.ratings\n      : nextRatings;\n    const next: AIConversationControllerState<Message> = {\n      activity: this.activity,\n      error: this.error,\n      hasOlderMessages: this.hasOlderMessages,\n      messages,\n      pendingMessage,\n      ratings,\n      status: this.currentStatus(messages),\n    };\n    const changed = (Object.keys(next) as (keyof typeof next)[]).some(\n      (key) => next[key] !== current[key],\n    );\n    if (changed) this.state.next(next);\n  }\n\n  private currentRatings() {\n    const ratings: Record<string, AIMessageRating> = {};\n    for (const message of this.received) {\n      if (message.role !== 'user' && message.rating) ratings[message.id] = message.rating;\n    }\n    for (const [id, change] of this.ratingChanges) {\n      if (change.shown) ratings[id] = change.shown;\n      else delete ratings[id];\n    }\n    return ratings;\n  }\n\n  private currentStatus(messages: readonly Message[]): AIConversationStatus {\n    if (this.exchange?.state === 'waiting') return 'submitted';\n    const last = messages[messages.length - 1];\n    if (last && last.role !== 'user' && last.isGenerating && !this.stopped.has(last.id)) {\n      return hasEmptyContent(last) ? 'submitted' : 'streaming';\n    }\n    // The agent is working on the person's latest message, whose reply isn't here yet.\n    if (\n      this.activity &&\n      this.activity.state !== AIAgentActivityStates.error &&\n      (!last || last.role === 'user')\n    ) {\n      return 'submitted';\n    }\n    return this.error ? 'error' : 'ready';\n  }\n}\n"],"mappings":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