@mastra/core
Version:
1 lines • 32.3 kB
Source Map (JSON)
{"version":3,"file":"channels-Dp9ZT859.cjs","names":["AgentChannels","MastraFGAPermissions","ChannelSessionRejectedError"],"sources":["../src/channels/agent-controller-channels.ts"],"sourcesContent":["import type { Message, Thread } from 'chat';\n\nimport type { Agent } from '../agent/agent';\nimport type { MastraProviderMetadata } from '../agent/message-list/state/types';\nimport type { AgentSignalContents, AgentSignalInput } from '../agent/signals';\nimport type { AgentController } from '../agent-controller/agent-controller';\nimport type { Session } from '../agent-controller/session';\nimport type { AgentControllerRequestContext } from '../agent-controller/types';\nimport { MastraFGAPermissions } from '../auth/ee';\nimport type { Mastra } from '../mastra';\nimport type { StorageThreadType } from '../memory/types';\nimport type { RequestContext } from '../request-context';\n\nimport { AgentChannels } from './agent-channels';\nimport { ChannelSessionRejectedError } from './errors';\nimport type { ThreadHistoryLogContext } from './thread-history';\nimport type { ChannelConfig } from './types';\n\n/** Context passed to {@link AgentControllerChannelsConfig.onSessionStart}. */\nexport interface ChannelSessionStartContext {\n /**\n * The controller session, already bound to `thread`. Bound before the hook\n * runs on purpose: session settings persist to the bound thread's metadata,\n * so a hook that writes settings must not race the thread switch.\n */\n session: Session<any>;\n /** The mapped Mastra thread the session is bound to. */\n thread: Pick<StorageThreadType, 'id' | 'resourceId'>;\n /** Request context of the message that started the session, when there is one. */\n requestContext?: RequestContext;\n}\n\n/**\n * Configure a session the first time a channel thread reaches it, before the\n * inbound message is dispatched.\n *\n * The seam exists because a host can name a session (`resolveResourceId`) but\n * never receives the `Session` object — it is created here, inside the channel\n * machinery. Without this hook a host that resolves its own resourceIds can\n * only ever configure sessions the web UI created, and channel-created sessions\n * silently run on the SDK's built-in defaults.\n *\n * Errors are logged and swallowed: configuration is best-effort and must not\n * drop the message that triggered it.\n */\nexport type ChannelSessionStart = (ctx: ChannelSessionStartContext) => void | Promise<void>;\n\n/** Context passed to {@link AgentControllerChannelsConfig.resolveSession}. */\nexport interface ChannelSessionResolveContext {\n /**\n * The bound controller. The resolver must create its session through this\n * controller so the channels instance stays the single owner of outbound\n * delivery for that session.\n */\n controller: AgentController<any>;\n /** The mapped Mastra thread the returned session will be bound to. */\n thread: Pick<StorageThreadType, 'id' | 'resourceId'>;\n /** Request context of the inbound message or approval action, when there is one. */\n requestContext?: RequestContext;\n}\n\n/**\n * Create the controller session for a mapped channel thread, replacing the\n * default `controller.createSession({ resourceId: thread.resourceId, ... })`.\n *\n * `onSessionStart` cannot serve this purpose: it runs after the session already\n * exists and its errors are swallowed, so a host cannot use it to authorize or\n * route. This hook runs *before* any session is created and its errors\n * propagate, which is what makes fail-closed authorization possible — a host\n * that rejects the request ends up with no session, no model call, and no\n * output.\n *\n * It also runs on approval continuations, so a shared install can revalidate\n * the execution principal on every approve/decline rather than only on the\n * message that opened the session.\n *\n * The returned session must own the mapped thread, i.e. be created under\n * `thread.resourceId` — a session can only bind threads it owns. Hosts that\n * want a different session identity choose it on both ends, by pairing this\n * with the channels `resolveResourceId` option.\n *\n * Create the session with `threadId: thread.id` so it binds the mapped thread\n * directly. Without it, a session scoped by tags or `projectPath` auto-selects\n * or creates a different thread and is only switched onto the mapped one\n * afterwards, leaving an extra empty thread behind.\n */\nexport type ChannelSessionResolve = (ctx: ChannelSessionResolveContext) => Session<any> | Promise<Session<any>>;\n\n/** Context passed to {@link AgentControllerChannelsConfig.onStaleToolApproval}. */\nexport interface ChannelStaleToolApprovalContext {\n /** Which button the user pressed on the approval card. */\n decision: 'approve' | 'decline';\n /** The tool call the action referred to. */\n toolCallId: string;\n /**\n * The run the approval card was rendered for — the run the user actually\n * answered. This is the id to settle against: after a restart it is the only\n * one that still identifies that attempt.\n */\n runId: string;\n /**\n * The run currently on the session, when there is one. Usually `null` for a\n * restart-recovered action, and a *different* run when the session has since\n * moved on — never assume it matches {@link runId}.\n */\n currentRunId: string | null;\n /** Request context of the approval action. */\n requestContext: RequestContext;\n /** The mapped thread/resource the approval card belongs to. */\n memory: { thread: string; resource: string };\n /** The session the action resolved to. */\n session: Session<any>;\n}\n\n/**\n * Called when an approval action arrives with no matching parked approval gate\n * — the usual cause being a process restart, which drops the in-memory gate and\n * makes every recovered approval stale.\n *\n * Core still never executes the tool action; the hook exists so a durable host\n * can settle that exact attempt (mark it interrupted, retryable, expired)\n * instead of silently dropping the user's click. Errors propagate.\n */\nexport type ChannelStaleToolApproval = (ctx: ChannelStaleToolApprovalContext) => void | Promise<void>;\n\n/** Configuration for {@link AgentControllerChannels}. */\nexport interface AgentControllerChannelsConfig extends ChannelConfig {\n /**\n * Called once per session per process, after the session is bound to its\n * thread and before the first message dispatches. Concurrent messages on a\n * new session wait for the hook to settle rather than dispatching on an\n * unconfigured session. See {@link ChannelSessionStart}.\n */\n onSessionStart?: ChannelSessionStart;\n /**\n * Creates the session instead of the built-in `createSession` call, before\n * any session exists. Use this — not `onSessionStart` — for authorization and\n * routing: it can fail closed. See {@link ChannelSessionResolve}.\n */\n resolveSession?: ChannelSessionResolve;\n /**\n * Called when an approval action has no matching parked gate, typically after\n * a restart. See {@link ChannelStaleToolApproval}.\n */\n onStaleToolApproval?: ChannelStaleToolApproval;\n}\n\n/**\n * Runs an AgentController inside chat channels (Slack, Discord, ...).\n *\n * Extends {@link AgentChannels} so all inbound machinery (thread mapping,\n * history, attachments, event context) and all outbound rendering\n * (`ChatChannelOutputProcessor` with native streaming, tool cards, typing\n * status) are reused unchanged. Only the dispatch seams differ: instead of\n * routing into a bare agent, inbound messages route into a controller\n * `Session` — one durable session per chat thread, keyed by the mapped\n * Mastra thread's `resourceId`.\n *\n * V1 targets long-lived servers: controller sessions are in-memory objects\n * and do not survive process restarts.\n */\nexport class AgentControllerChannels extends AgentChannels {\n private controller: AgentController<any> | null = null;\n\n /**\n * Session resourceIds whose adapter can't render approval buttons, so their\n * runs must auto-approve tools (`requireToolApproval: false`) instead of\n * parking forever on an approval nobody can answer. Kept outside session\n * state on purpose: state is validated against the controller's\n * `stateSchema`, which would strip (or reject) an injected flag. Refreshed\n * on every inbound message; in-memory only, matching the v1 long-lived\n * server scope.\n */\n private autoApproveResourceIds = new Set<string>();\n\n /** See {@link AgentControllerChannelsConfig.onSessionStart}. */\n private readonly onSessionStart: ChannelSessionStart | undefined;\n\n /** See {@link AgentControllerChannelsConfig.resolveSession}. */\n private readonly resolveSession: ChannelSessionResolve | undefined;\n\n /** See {@link AgentControllerChannelsConfig.onStaleToolApproval}. */\n private readonly onStaleToolApproval: ChannelStaleToolApproval | undefined;\n\n /**\n * One start-hook invocation per session resourceId. A map of promises rather\n * than a set of ids: concurrent messages on a new thread must all WAIT for\n * the hook, not just skip it, or the losers dispatch on an unconfigured\n * session. In-memory, matching the v1 scope where sessions themselves don't\n * survive a restart: a session rebuilt after a restart is a new session and\n * gets configured again. Keyed by session rather than by thread because a\n * `resolveSession` host can hand back a different session for the same thread\n * (per-principal routing), and each of those is a session that has never been\n * configured.\n */\n private sessionStartRuns = new WeakMap<Session<any>, Promise<void>>();\n\n constructor(config: AgentControllerChannelsConfig) {\n super(config);\n this.onSessionStart = config.onSessionStart;\n this.resolveSession = config.resolveSession;\n this.onStaleToolApproval = config.onStaleToolApproval;\n }\n\n /** @internal Called by AgentController's constructor to bind itself. */\n __setController(controller: AgentController<any>): void {\n this.controller = controller;\n }\n\n /**\n * @internal Consulted by the controller's run-option builder: `true` when\n * the session's channel adapter can't render approval buttons and tool\n * calls must auto-approve (the session-side equivalent of the base agent\n * path's `autoResumeSuspendedTools`).\n */\n __isAutoApproveResource(resourceId: string): boolean {\n return this.autoApproveResourceIds.has(resourceId);\n }\n\n /**\n * @internal No-op override. The controller attaches this instance to its\n * mode agents via `Agent.setChannels`, which calls `__setAgent(agent)` —\n * with multiple mode agents the last one would win. Every `this.agent` use\n * is overridden in this subclass, so keep the base field unset rather than\n * holding a misleading ref.\n */\n override __setAgent(_agent: Agent<any, any, any, any>): void {}\n\n protected override getOwnerId(): string | null {\n return this.controller?.id ?? null;\n }\n\n protected override getWebhookBasePath(): string {\n return `/api/agent-controllers/${this.getOwnerId()}`;\n }\n\n protected override getMastra(): Mastra | undefined {\n return this.controller?.getMastra();\n }\n\n /**\n * One session per chat thread: unless the user supplied a custom\n * `resolveResourceId`, key new Mastra threads (and therefore controller\n * sessions) off the platform + external thread id.\n */\n protected override resolveChannelResourceId(args: {\n platform: string;\n chatThread: Thread;\n message: Message;\n defaultResourceId: string;\n requestContext: RequestContext;\n }): string | (() => string | Promise<string>) {\n const base = super.resolveChannelResourceId(args);\n // The base returns a thunk only when a custom resolveResourceId was\n // configured — honor it. Otherwise derive the channel-thread key. The\n // adapter's thread id is already platform-prefixed (e.g. `slack:C123:ts`),\n // so don't prepend the platform again or the key double-prefixes.\n if (typeof base === 'function') return base;\n return `channel:${args.chatThread.id}`;\n }\n\n /**\n * Route an inbound chat message into the controller session bound to this\n * chat thread. Output renders back to the platform through the channels\n * output processor: the `requestContext` built by the base class (carrying\n * the channel context and render context) flows through the session into\n * the run.\n */\n protected override async dispatchInboundMessage(args: {\n signalContents: AgentSignalContents;\n attributes: Record<string, string | undefined>;\n signalMetadata: Record<string, unknown>;\n providerOptions: MastraProviderMetadata;\n requestContext: RequestContext;\n thread: StorageThreadType;\n memory: { thread: string; resource: string };\n autoResumeSuspendedTools: true | undefined;\n }): Promise<void> {\n const {\n signalContents,\n attributes,\n signalMetadata,\n providerOptions,\n requestContext,\n thread,\n autoResumeSuspendedTools,\n } = args;\n\n // The tenant, when there is one, is already stamped on `requestContext` by\n // the channel handler that accepted this message — a host that maps\n // platform senders to Mastra users writes `user` before calling\n // `defaultHandler`, and gating an unlinked sender means not calling it at\n // all. Core dispatches whatever reaches it.\n const session = await this.getSessionForThread(thread, requestContext);\n\n // The session equivalent of the base path's `autoResumeSuspendedTools`:\n // controller runs set `requireToolApproval` from this marker, so on\n // adapters that can't render approval buttons the run auto-approves\n // instead of parking forever on an approval nobody can answer. Tracked\n // outside session state so the controller's `stateSchema` (which would\n // strip or reject an injected key) never sees it.\n const sessionResourceId = thread.resourceId;\n if (autoResumeSuspendedTools) {\n this.autoApproveResourceIds.add(sessionResourceId);\n } else {\n this.autoApproveResourceIds.delete(sessionResourceId);\n }\n\n const result = session.sendSignal(\n {\n type: 'user',\n tagName: 'user',\n contents: signalContents,\n attributes,\n ...(Object.keys(signalMetadata).length > 0 ? { metadata: signalMetadata } : {}),\n providerOptions,\n },\n // Await the agent's real acceptance decision. Stream setup (workspace,\n // instructions, tools, model resolution) runs before the run span opens\n // and before the user message is persisted; without this, a throw there\n // rejects after the next tick and the message vanishes with no trace,\n // no log, and no reply. Rejecting here reaches handleChatMessage's\n // error boundary, which tells the sender.\n // Keep the run open until background tasks finish: it carries the channel's render\n // context, so it's the run that posts their results to the chat.\n { requestContext, requireDelivery: true, untilIdle: true },\n );\n await result.accepted;\n }\n\n /**\n * Persist first-mention thread history into the controller session's own\n * thread. The session is resolved once, before the rows are built, and is\n * not guarded: a `resolveSession` refusal or resource mismatch propagates\n * out of the hook to the handler's error boundary exactly as it would from\n * the trigger dispatch a moment later. `onSessionStart` therefore runs\n * before the history rows rather than at trigger dispatch.\n *\n * Rows are written straight to the session agent's memory (see the base\n * class for why `session.sendSignal` cannot be used). Like the base class,\n * a session agent without memory or a failed write returns `false` so the\n * history still reaches the agent as the legacy text block.\n */\n protected override async persistThreadHistorySignals(args: {\n buildSignals: () => Promise<AgentSignalInput[]>;\n requestContext: RequestContext;\n thread: StorageThreadType;\n memory: { thread: string; resource: string };\n logContext: ThreadHistoryLogContext;\n }): Promise<boolean> {\n const session = await this.getSessionForThread(args.thread, args.requestContext);\n const memory = await session.machinery.getAgent().getMemory({ requestContext: args.requestContext });\n if (!memory) return false;\n return this.saveThreadHistorySignals({\n buildSignals: args.buildSignals,\n memory,\n target: { thread: session.thread.getId() ?? args.memory.thread, resource: session.identity.getResourceId() },\n logContext: args.logContext,\n });\n }\n\n /**\n * Resolve an approval-card \"approve\" action against the controller session's\n * parked tool-approval gate. The run engine — awaiting the gate inside its\n * stream-consumer loop — performs the actual resume itself and keeps\n * consuming, so the continuation renders through the output processor.\n */\n protected override async dispatchApproval(args: {\n runId: string;\n toolCallId: string;\n requestContext: RequestContext;\n memory: { thread: string; resource: string };\n }): Promise<void> {\n await this.respondToSessionApproval({ decision: 'approve', ...args });\n }\n\n /**\n * Resolve an approval-card \"deny\" action against the controller session's\n * parked tool-approval gate (see {@link dispatchApproval}).\n */\n protected override async dispatchDecline(args: {\n runId: string;\n toolCallId: string;\n requestContext: RequestContext;\n memory: { thread: string; resource: string };\n }): Promise<void> {\n await this.respondToSessionApproval({ decision: 'decline', ...args });\n }\n\n /**\n * Shared approve/decline path. Never calls the session's internal\n * `approveToolCall`/`declineToolCall` executors directly — the engine parked\n * at the gate owns the resume. `respondToToolApproval` is a silent no-op\n * when nothing is armed or the toolCallId mismatches, so staleness is\n * pre-checked explicitly (an armed gate does not survive process restarts,\n * so restart-recovered approvals are always stale — consistent with the\n * v1 long-lived-server scope).\n */\n private async respondToSessionApproval({\n decision,\n runId,\n toolCallId,\n requestContext,\n memory,\n }: {\n decision: 'approve' | 'decline';\n runId: string;\n toolCallId: string;\n requestContext: RequestContext;\n memory: { thread: string; resource: string };\n }): Promise<void> {\n // The action's requestContext flows in so a `resolveSession` host revalidates\n // the execution principal on every continuation, not just on the message\n // that opened the session.\n // Don't bind the thread yet: when several threads share one session, switching\n // threads aborts whatever run is live on the other one. A gate can only be armed\n // for the thread the session is on, so a click from any other thread is stale.\n const session = await this.getSessionForThread({ id: memory.thread, resourceId: memory.resource }, requestContext, {\n bindThread: false,\n });\n const onThread = session.thread.getId() === memory.thread;\n if (!onThread || !session.approval.isArmed({ toolCallId })) {\n this.log(\n 'info',\n `Ignoring stale tool ${decision === 'approve' ? 'approval' : 'denial'} action (no matching parked approval)`,\n {\n threadId: memory.thread,\n toolCallId,\n },\n );\n // Core still refuses to execute the action. The hook only lets a durable\n // host settle the attempt the click referred to, which is otherwise\n // dropped with nothing but a log line.\n await this.onStaleToolApproval?.({\n decision,\n toolCallId,\n // The action's own runId, not the session's: the point of the hook is\n // settling an attempt from before a restart, and by then the session's\n // current run is null or something else entirely.\n runId,\n currentRunId: session.getCurrentRunId(),\n requestContext,\n memory,\n session,\n });\n return;\n }\n // The requestContext carries the channel render context, so the resumed\n // stream renders back to the platform through the output processor.\n session.respondToToolApproval({ decision, toolCallId, requestContext });\n }\n\n /**\n * Get-or-create the durable controller session for a mapped channel thread\n * and bind it to that thread. Keyed off the thread's own `resourceId` so\n * pre-existing threads (custom resolveResourceId, or created before this\n * feature) always pass the session's thread-ownership check.\n */\n protected async getSessionForThread(\n thread: Pick<StorageThreadType, 'id' | 'resourceId'>,\n requestContext?: RequestContext,\n { bindThread = true }: { bindThread?: boolean } = {},\n ): Promise<Session<any>> {\n const controller = this.requireController();\n const channelResourceId = thread.resourceId;\n // A caller that skips binding may get back a live session without going through\n // createSession or the resolver, so it must pass the same EXECUTE check they do.\n if (this.resolveSession || !bindThread) {\n await controller.requireAgentControllerFGA({\n permission: MastraFGAPermissions.AGENT_CONTROLLER_EXECUTE,\n requestContext,\n resourceId: channelResourceId,\n });\n }\n // `createSession` is get-or-create keyed by resourceId, so follow-up messages\n // on the same thread reuse the cached session bound to this thread. The\n // dispatch requestContext must flow in: a dynamic workspace factory is\n // resolved once at session creation with THIS context, and it may need the\n // stamped tenant (`user`) to authorize a repo-backed session workspace.\n // The resolver replaces this call entirely and its errors propagate, so a\n // host can refuse the request before a session, a model call, or any output\n // exists. It gets the same controller so this channels instance stays the\n // owner of outbound delivery for whatever session it returns. A throw is\n // tagged as a refusal so the channel error boundary keeps it out of the\n // chat thread instead of posting the host's authorization message there.\n // createSession rebinds an existing session to the requested thread, which is\n // exactly what a caller that doesn't want to bind is avoiding. A resolver that\n // follows the documented pattern calls createSession too, so when the live\n // session is on another thread, return it without asking the resolver. The\n // caller treats that as stale and acts on nothing. When the live session is\n // already on this thread, the resolver still runs so the host can revalidate.\n if (!bindThread) {\n const existing = await controller.getSession(channelResourceId, requestContext);\n if (\n existing &&\n existing.identity.getResourceId() === channelResourceId &&\n (!this.resolveSession || existing.thread.getId() !== thread.id)\n ) {\n return existing;\n }\n }\n const session = this.resolveSession\n ? await this.resolveChannelSession({ controller, thread, requestContext })\n : await controller.createSession({\n resourceId: channelResourceId,\n id: channelResourceId,\n ownerId: controller.id,\n // The mapped thread is authoritative: bind it at creation so a scoped\n // session never auto-selects or creates a different thread. Without\n // binding, only resume: a session registered after the lookup above must\n // not be switched to this thread.\n ...(bindThread ? { threadId: thread.id } : { resumeOnly: true }),\n requestContext,\n });\n // A session may only bind threads it owns, and the mapped thread's owner is\n // fixed by the channel's resourceId mapping. Catching the mismatch here\n // turns an opaque \"Thread not found\" from deep inside the session into the\n // actual instruction: line the two up, which hosts do by pairing this\n // resolver with `resolveResourceId`.\n if (this.resolveSession && session.identity.getResourceId() !== channelResourceId) {\n throw new Error(\n `resolveSession returned a session for resourceId=\"${session.identity.getResourceId()}\", but the mapped channel thread belongs to resourceId=\"${channelResourceId}\". A session can only bind threads it owns — resolve the session under the thread's resourceId, or map the thread onto the session's resourceId with the channels \\`resolveResourceId\\` option.`,\n );\n }\n // Bind the mapped thread. Guard is mandatory: `switch` aborts any active\n // run, so never re-switch when the session is already on this thread. The\n // inbound context flows in so the bind's history load resolves memory as\n // the stamped tenant.\n if (!bindThread) return session;\n if (session.thread.getId() !== thread.id) {\n await session.thread.switch({ threadId: thread.id, requestContext });\n }\n await this.runSessionStartHook(session, thread, requestContext);\n return session;\n }\n\n /**\n * Only render Approve/Deny controls when the session actually arms a human\n * gate. `allow` tools auto-approve and `deny` tools auto-decline inside the\n * session run, so a card for them would offer a decision nobody is waiting\n * on. The session is looked up in the controller's live registry by the\n * run's session id; when it isn't live, controls are rendered as a fallback.\n *\n * @internal\n */\n override async shouldRenderToolApproval(\n requestContext: RequestContext | undefined,\n toolName: string,\n ): Promise<boolean> {\n const ctx = requestContext?.get('controller') as AgentControllerRequestContext | undefined;\n if (!this.controller || !ctx?.sessionId) return true;\n const session = await this.controller.getSession(ctx.sessionId, requestContext);\n if (!session) return true;\n return session.resolveToolApproval(toolName, requestContext) === 'ask';\n }\n\n /**\n * Call the host's resolver and tag anything it throws as a refusal. Covers\n * synchronous throws too — the hook may return a `Session` directly, so a\n * plain `.catch()` on the return value would miss them.\n */\n private async resolveChannelSession(ctx: ChannelSessionResolveContext): Promise<Session<any>> {\n try {\n return await this.resolveSession!(ctx);\n } catch (cause) {\n throw new ChannelSessionRejectedError(cause);\n }\n }\n\n /**\n * Run the configured session-start hook at most once per session. Fires after\n * the thread binding above, so a hook that persists session settings writes\n * them to the thread the session actually ends up on.\n */\n private async runSessionStartHook(\n session: Session<any>,\n thread: Pick<StorageThreadType, 'id' | 'resourceId'>,\n requestContext?: RequestContext,\n ): Promise<void> {\n const onSessionStart = this.onSessionStart;\n if (!onSessionStart) return;\n // Memoize before the first await: two messages arriving together on a new\n // thread both reach this point. The first starts the hook; every later\n // caller awaits the same run, so no message dispatches before the session\n // is configured.\n let run = this.sessionStartRuns.get(session);\n if (!run) {\n run = (async () => {\n try {\n await onSessionStart({ session, thread, requestContext });\n } catch (error) {\n // Best-effort by contract: a session that couldn't be configured\n // still answers the message, on whatever defaults it was created\n // with.\n this.log('error', 'Channel session-start hook failed', { resourceId: thread.resourceId, error });\n }\n })();\n this.sessionStartRuns.set(session, run);\n }\n await run;\n }\n\n private requireController(): AgentController<any> {\n if (!this.controller) {\n throw new Error(\n 'AgentControllerChannels is not bound to an AgentController. Pass it via `channels` in AgentControllerConfig.',\n );\n }\n return this.controller;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiKA,IAAa,0BAAb,cAA6CA,qBAAAA,cAAc;CACzD,aAAkD;;;;;;;;;;CAWlD,yCAAiC,IAAI,IAAY;;CAGjD;;CAGA;;CAGA;;;;;;;;;;;;CAaA,mCAA2B,IAAI,QAAqC;CAEpE,YAAY,QAAuC;EACjD,MAAM,MAAM;EACZ,KAAK,iBAAiB,OAAO;EAC7B,KAAK,iBAAiB,OAAO;EAC7B,KAAK,sBAAsB,OAAO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