@mgamadeus/ddd-agents 0.5.16 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +170 -6
- package/boundary.json +13 -0
- package/dist/chat.js +148 -773
- package/dist/chat.js.map +1 -1
- package/dist/chunks/{canvas-title-slot-context-DK4sfhkl.js → ConversationMarkdown-BsCjyhj4.js} +14 -43
- package/dist/chunks/ConversationMarkdown-BsCjyhj4.js.map +1 -0
- package/dist/chunks/{ConversationMessageInputComposerWidgets-B3Zf69rD.js → ConversationMessageInputComposerWidgets-CE8LpyXY.js} +10 -37
- package/dist/chunks/ConversationMessageInputComposerWidgets-CE8LpyXY.js.map +1 -0
- package/dist/chunks/VoiceBarsIcon-BIcURsBF.js +643 -0
- package/dist/chunks/VoiceBarsIcon-BIcURsBF.js.map +1 -0
- package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js → WebSearchResultsConversationWidget-DXhfSikV.js} +2 -2
- package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js.map → WebSearchResultsConversationWidget-DXhfSikV.js.map} +1 -1
- package/dist/chunks/browser-request-interception-BnzFbH0m.js +335 -0
- package/dist/chunks/browser-request-interception-BnzFbH0m.js.map +1 -0
- package/dist/chunks/{canvas-reducers-CwFA3rQ6.js → canvas-reducers-D-YxAR4B.js} +2 -2
- package/dist/chunks/{canvas-reducers-CwFA3rQ6.js.map → canvas-reducers-D-YxAR4B.js.map} +1 -1
- package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js +36 -0
- package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js.map +1 -0
- package/dist/chunks/{canvasBodies-C7qqThc9.js → canvasBodies-CQEBkIVw.js} +4 -4
- package/dist/chunks/{canvasBodies-C7qqThc9.js.map → canvasBodies-CQEBkIVw.js.map} +1 -1
- package/dist/chunks/{canvasStorage-i2wKVSBf.js → canvasStorage-BbEI3h-8.js} +2 -2
- package/dist/chunks/{canvasStorage-i2wKVSBf.js.map → canvasStorage-BbEI3h-8.js.map} +1 -1
- package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js +10 -0
- package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js.map +1 -0
- package/dist/chunks/{link-navigation-CNX8Am2L.js → link-navigation-BUcy5qWW.js} +2 -2
- package/dist/chunks/{link-navigation-CNX8Am2L.js.map → link-navigation-BUcy5qWW.js.map} +1 -1
- package/dist/chunks/{realtime-arrival-BTLE3jjt.js → realtime-arrival-BfsAPwqQ.js} +8 -3
- package/dist/chunks/realtime-arrival-BfsAPwqQ.js.map +1 -0
- package/dist/chunks/use-agents-chat-store-CuIkCz9v.js +34 -0
- package/dist/chunks/use-agents-chat-store-CuIkCz9v.js.map +1 -0
- package/dist/chunks/{widget-name-resolver-BVEuAsW5.js → widget-name-resolver-B9k-s_cF.js} +3 -3
- package/dist/chunks/{widget-name-resolver-BVEuAsW5.js.map → widget-name-resolver-B9k-s_cF.js.map} +1 -1
- package/dist/chunks/withPollingChangeSubscription-CnQnubfK.js.map +1 -1
- package/dist/client-testing.js +4 -4
- package/dist/client.js +14 -3
- package/dist/client.js.map +1 -1
- package/dist/files/i18n-keys.json +1128 -100
- package/dist/image-render.js +65 -38
- package/dist/image-render.js.map +1 -1
- package/dist/index.js +6 -6
- package/dist/kit.js +2 -2
- package/dist/preview.js +23 -26
- package/dist/preview.js.map +1 -1
- package/dist/provider.js +1 -1
- package/dist/renderer.js +25 -24
- package/dist/renderer.js.map +1 -1
- package/dist/styles.css +531 -93
- package/dist/types/client/AgentsConversationClient.d.ts +4 -1
- package/dist/types/client/http/createAgentsHttpConversationClient.d.ts +2 -1
- package/dist/types/entries/voice-admin.d.ts +7 -0
- package/dist/types/entries/voice.d.ts +24 -0
- package/dist/types/image-render/frozen-widget-requests.d.ts +11 -2
- package/dist/types/image-render/widget-image-google-map.d.ts +5 -0
- package/dist/types/image-render/widget-image-static-assets.d.ts +2 -0
- package/dist/types/preview/widget-preview-requests.d.ts +6 -5
- package/dist/types/request-interception/browser-request-interception.d.ts +48 -0
- package/dist/types/request-interception/intercepted-xml-http-request-upload.d.ts +15 -0
- package/dist/types/ui/account-realtime.d.ts +50 -11
- package/dist/types/voice/AgentVoiceCallBand/AgentVoiceCallBand.d.ts +49 -0
- package/dist/types/voice/AgentVoiceCallBand/agent-voice-call-outcome-title-text-key.d.ts +8 -0
- package/dist/types/voice/AgentVoiceCallCaptions/AgentVoiceCallCaptions.d.ts +15 -0
- package/dist/types/voice/AgentVoiceCallCaptions/saved-messages-of-agent-voice-chat.d.ts +12 -0
- package/dist/types/voice/AgentVoiceCallProvider/AgentVoiceCallProvider.d.ts +21 -0
- package/dist/types/voice/AgentVoiceCallProvider/agent-voice-call-context.d.ts +17 -0
- package/dist/types/voice/AgentVoiceChatStartButton/AgentVoiceChatStartButton.d.ts +15 -0
- package/dist/types/voice/AgentVoiceIcons/AgentVoiceIcons.d.ts +10 -0
- package/dist/types/voice/AgentVoiceIncomingCall/AgentVoiceIncomingCall.d.ts +28 -0
- package/dist/types/voice/AgentVoiceInputGlow/AgentVoiceInputGlow.d.ts +11 -0
- package/dist/types/voice/AgentVoiceInputGlow/agent-voice-input-glow-voice.d.ts +8 -0
- package/dist/types/voice/admin/AgentVoiceCallConversationLink/AgentVoiceCallConversationLink.d.ts +10 -0
- package/dist/types/voice/admin/AgentVoiceCallDetailScreen/AgentVoiceCallDetailScreen.d.ts +27 -0
- package/dist/types/voice/admin/AgentVoiceCallStateBadges/AgentVoiceCallStateBadges.d.ts +12 -0
- package/dist/types/voice/admin/AgentVoiceCallsScreen/AgentVoiceCallsScreen.d.ts +33 -0
- package/dist/types/voice/admin/agent-voice-admin-api.d.ts +59 -0
- package/dist/types/voice/admin/agent-voice-admin-format.d.ts +38 -0
- package/dist/types/voice/admin/agent-voice-admin-types.d.ts +110 -0
- package/dist/types/voice/agent-voice-api.d.ts +114 -0
- package/dist/types/voice/call/agent-voice-call-elapsed-seconds.d.ts +6 -0
- package/dist/types/voice/call/agent-voice-call-end-reasons.d.ts +3 -0
- package/dist/types/voice/call/agent-voice-call-store.d.ts +111 -0
- package/dist/types/voice/call/agent-voice-call-turn.d.ts +4 -0
- package/dist/types/voice/call/build-unsaved-agent-voice-call-lines.d.ts +14 -0
- package/dist/types/voice/call/format-agent-voice-call-duration.d.ts +2 -0
- package/dist/types/voice/call/use-agent-voice-call-elapsed-seconds.d.ts +3 -0
- package/dist/types/voice/call/use-agent-voice-call-server-end.d.ts +15 -0
- package/dist/types/voice/call/use-agent-voice-call.d.ts +12 -0
- package/dist/types/voice/call/use-follow-agent-voice-call-conversation.d.ts +9 -0
- package/dist/types/voice/ring/agent-voice-caller-label.d.ts +21 -0
- package/dist/types/voice/ring/agent-voice-incoming-ring-list.d.ts +10 -0
- package/dist/types/voice/ring/agent-voice-incoming-ring-store.d.ts +47 -0
- package/dist/types/voice/ring/agent-voice-ring-source.d.ts +75 -0
- package/dist/types/voice/ring/agent-voice-ring.d.ts +35 -0
- package/dist/types/voice/ring/answer-incoming-agent-voice-call.d.ts +13 -0
- package/dist/types/voice/ring/use-agent-voice-incoming-rings.d.ts +14 -0
- package/dist/types/voice/ring/use-agent-voice-ring-tone.d.ts +6 -0
- package/dist/ui.js +82 -19
- package/dist/ui.js.map +1 -1
- package/dist/voice-admin.js +738 -0
- package/dist/voice-admin.js.map +1 -0
- package/dist/voice.js +1586 -0
- package/dist/voice.js.map +1 -0
- package/dist/widgets.js +4 -4
- package/package.json +23 -4
- package/public-api.json +156 -0
- package/dist/chunks/ConversationMessageInputComposerWidgets-B3Zf69rD.js.map +0 -1
- package/dist/chunks/canvas-title-slot-context-DK4sfhkl.js.map +0 -1
- package/dist/chunks/realtime-arrival-BTLE3jjt.js.map +0 -1
- package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js +0 -25
- package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withPollingChangeSubscription-CnQnubfK.js","sources":["../../src/client/polling/createPollingConversationChangeSubscription.ts","../../src/client/polling/withPollingChangeSubscription.ts"],"sourcesContent":["import {\n type ConversationChangeSignal,\n type ConversationRunStateRead,\n type ConversationRunStatus,\n type ConversationSubscriptionEndReason,\n CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,\n isAgentsClientError,\n readConversationRunStatusOfRunState,\n} from \"../../contract/conversation\";\n\n/** Read interval while a turn runs (or right after a local send). */\nexport const POLLING_RUNNING_INTERVAL_MS = 2_000;\n/** Read interval while the conversation is idle or failed. */\nexport const POLLING_IDLE_INTERVAL_MS = 20_000;\n/** Ceiling of the exponential backoff after failed reads. */\nexport const POLLING_MAX_BACKOFF_MS = 60_000;\n/**\n * How long after a local send the poller keeps the running interval although the conversation still reads idle: the\n * server may store the owner's message before it marks the turn as running.\n */\nexport const POLLING_LOCAL_ACTIVITY_WINDOW_MS = 10_000;\n\n/**\n * Reads a conversation's run state — the port's `getConversationRunState`, or its `getConversationMetadata` (every\n * conversation carries the fields the poller reads).\n */\nexport type ConversationMetadataReader = (conversationId: number) => Promise<ConversationRunStateRead>;\n\n/** The timer functions the poller uses; a spec hands in fake ones. */\nexport interface PollingTimers {\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (timerHandle: unknown) => void;\n now: () => number;\n}\n\n/** Whether the page is hidden, and a way to hear when that changes; a spec hands in its own. */\nexport interface PollingDocumentVisibility {\n isHidden: () => boolean;\n /** Calls `listener` on every visibility change; returns the function that stops it. */\n listen: (listener: () => void) => () => void;\n}\n\nexport interface PollingConversationChangeSubscriptionOptions {\n /** Default `POLLING_RUNNING_INTERVAL_MS` (2 s). */\n runningIntervalMs?: number;\n /** Default `POLLING_IDLE_INTERVAL_MS` (20 s). */\n idleIntervalMs?: number;\n /** Default `POLLING_MAX_BACKOFF_MS` (60 s). */\n maxBackoffMs?: number;\n /** Default `POLLING_LOCAL_ACTIVITY_WINDOW_MS` (10 s). */\n localActivityWindowMs?: number;\n /** Default: the global `setTimeout` / `clearTimeout` and `Date.now`. */\n timers?: PollingTimers;\n /** Default: the browser `document`; `null` = the page counts as always visible (no `document`, a worker). */\n documentVisibility?: PollingDocumentVisibility | null;\n}\n\n/**\n * The polling default of the live updates: the port's `subscribeToConversationChanges` plus\n * `notifyLocalActivity`, which `withPollingChangeSubscription` calls after every send the server accepted.\n */\nexport interface PollingConversationChangeSubscription {\n subscribeToConversationChanges: (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ) => () => void;\n /** Reads the conversation's metadata now and keeps the running interval for the local-activity window. */\n notifyLocalActivity: (conversationId: number) => void;\n}\n\ninterface ResolvedPollingOptions {\n runningIntervalMs: number;\n idleIntervalMs: number;\n maxBackoffMs: number;\n localActivityWindowMs: number;\n timers: PollingTimers;\n documentVisibility: PollingDocumentVisibility | null;\n}\n\n/** The global timer functions, looked up on each call (so a spec's fake timers installed later still apply). */\nclass GlobalPollingTimers implements PollingTimers {\n setTimeout = (callback: () => void, delayMs: number): unknown => globalThis.setTimeout(callback, delayMs);\n\n clearTimeout = (timerHandle: unknown): void => globalThis.clearTimeout(timerHandle as ReturnType<typeof setTimeout>);\n\n now = (): number => Date.now();\n}\n\n/** The browser document's `visibilityState` and `visibilitychange` event. */\nclass BrowserDocumentVisibility implements PollingDocumentVisibility {\n constructor(protected readonly browserDocument: Document) {}\n\n isHidden = (): boolean => this.browserDocument.visibilityState === \"hidden\";\n\n listen = (listener: () => void): (() => void) => {\n this.browserDocument.addEventListener(\"visibilitychange\", listener);\n return this.browserDocument.removeEventListener.bind(this.browserDocument, \"visibilitychange\", listener);\n };\n}\n\n/**\n * The three-value run status a polled read reports: the stored run state, and \"running\" for an idle conversation the\n * server owes a turn (`agentTurnOwedAt`), as the chat's own derivation does.\n */\nexport const readPolledRunStatus = (\n conversation: Pick<ConversationRunStateRead, \"runState\" | \"agentTurnOwedAt\">,\n): ConversationRunStatus | null => {\n const runStatus = readConversationRunStatusOfRunState(conversation.runState);\n return runStatus === \"idle\" && conversation.agentTurnOwedAt ? \"running\" : runStatus;\n};\n\n/** The end of a subscription a failed read means: a vanished conversation or lost access; null for a passing failure. */\nconst readSubscriptionEndReasonOfReadFailure = (failure: unknown): ConversationSubscriptionEndReason | null => {\n if (!isAgentsClientError(failure)) return null;\n if (failure.kind === \"notFound\") return \"gone\";\n if (failure.kind === \"forbidden\") return \"forbidden\";\n return null;\n};\n\n/**\n * One subscription: reads the conversation's metadata on a timer and turns each read into the change signal.\n *\n * Numbering (the signal leaves it open; the metadata carries no server change counter): the poller keeps its own counter. It\n * starts at 0 with the first read and advances by one whenever a read differs from the previous one in the run status,\n * `lastMessageId` or `updated` — so every polled signal is an ordinary change signal (no `isStatusCheck`) and the\n * package rules apply unchanged: an advance reads the changed tail (throttled), a terminal status reads at once,\n * re-reads the metadata and converges on `lastMessageId`. A status check would carry only the run status as news and\n * would miss a new message under an unchanged status. Without `lastMessageId` in the metadata every poll of a running\n * turn counts as a change (the changed tail is read every poll). `summaryUpdatedAt` is a second local counter that\n * advances when `title` or `summary` changed. A read with no change emits nothing.\n */\nclass ConversationMetadataPoller {\n protected isStopped = false;\n protected isReading = false;\n protected readAgainAfterCurrentRead = false;\n protected timerHandle: unknown = null;\n protected consecutiveFailedReads = 0;\n protected changeCounter = 0;\n protected summaryRevision = 0;\n protected previousChangeFingerprint: string | null = null;\n protected previousSummaryFingerprint: string | null = null;\n protected runStatus: ConversationRunStatus | null = null;\n protected hasConversationEnded = false;\n protected runningIntervalUntil = 0;\n protected stopListeningToVisibility: (() => void) | null = null;\n\n constructor(\n readonly conversationId: number,\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly onSignal: (signal: ConversationChangeSignal) => void,\n protected readonly onEnded: (reason: ConversationSubscriptionEndReason) => void,\n protected readonly options: ResolvedPollingOptions,\n protected readonly activePollers: Set<ConversationMetadataPoller>,\n ) {}\n\n start = (): void => {\n this.activePollers.add(this);\n this.stopListeningToVisibility = this.options.documentVisibility?.listen(this.receiveVisibilityChange) ?? null;\n this.readNow();\n };\n\n /** The unsubscribe: no read, no timer and no signal after it; a read in flight is dropped. */\n stop = (): void => {\n this.isStopped = true;\n this.activePollers.delete(this);\n this.clearTimer();\n this.stopListeningToVisibility?.();\n this.stopListeningToVisibility = null;\n };\n\n receiveLocalActivity = (): void => {\n this.runningIntervalUntil = this.options.timers.now() + this.options.localActivityWindowMs;\n this.readNow();\n };\n\n /** Reads now; a read already in flight is followed by one more read instead (two reads never overlap). */\n protected readNow = (): void => {\n if (this.isStopped) return;\n if (this.isReading) {\n this.readAgainAfterCurrentRead = true;\n return;\n }\n this.clearTimer();\n this.isReading = true;\n void this.readMetadataOnce();\n };\n\n protected async readMetadataOnce(): Promise<void> {\n let conversation: ConversationRunStateRead;\n try {\n conversation = await this.readMetadata(this.conversationId);\n } catch (failure) {\n this.isReading = false;\n this.receiveReadFailure(failure);\n return;\n }\n this.isReading = false;\n if (this.isStopped) return;\n this.consecutiveFailedReads = 0;\n this.receiveConversation(conversation);\n this.continueAfterRead(this.readIntervalMs());\n }\n\n protected receiveConversation(conversation: ConversationRunStateRead): void {\n const runStatus = readPolledRunStatus(conversation);\n const reportsLastMessageId = conversation.lastMessageId !== undefined;\n const changeFingerprint = JSON.stringify([runStatus, conversation.lastMessageId ?? null, conversation.updated]);\n const summaryFingerprint = JSON.stringify([conversation.title, conversation.summary]);\n const isFirstRead = this.previousChangeFingerprint === null;\n const hasChanged =\n changeFingerprint !== this.previousChangeFingerprint || (!reportsLastMessageId && runStatus === \"running\");\n const hasSummaryChanged = !isFirstRead && summaryFingerprint !== this.previousSummaryFingerprint;\n if (!isFirstRead && hasChanged) this.changeCounter += 1;\n if (hasSummaryChanged) this.summaryRevision += 1;\n this.previousChangeFingerprint = changeFingerprint;\n this.previousSummaryFingerprint = summaryFingerprint;\n this.runStatus = runStatus;\n this.hasConversationEnded =\n conversation.runState !== null && CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION.includes(conversation.runState);\n if (!isFirstRead && !hasChanged && !hasSummaryChanged) return;\n this.onSignal({\n changeCounter: this.changeCounter,\n lastMessageId: conversation.lastMessageId ?? null,\n runStatus,\n summaryUpdatedAt: this.summaryRevision,\n });\n }\n\n protected receiveReadFailure(failure: unknown): void {\n if (this.isStopped) return;\n const endReason = readSubscriptionEndReasonOfReadFailure(failure);\n if (endReason !== null) {\n this.stop();\n this.onEnded(endReason);\n return;\n }\n this.consecutiveFailedReads += 1;\n const backoffMs = this.readIntervalMs() * 2 ** this.consecutiveFailedReads;\n this.continueAfterRead(Math.min(backoffMs, this.options.maxBackoffMs));\n }\n\n protected continueAfterRead(nextReadDelayMs: number): void {\n if (this.readAgainAfterCurrentRead) {\n this.readAgainAfterCurrentRead = false;\n this.readNow();\n return;\n }\n // A completed or cancelled conversation changes no more: only a local send or the page's return reads it again.\n if (this.hasConversationEnded) return;\n this.scheduleRead(nextReadDelayMs);\n }\n\n protected readIntervalMs(): number {\n const isShortIntervalDue = this.runStatus === \"running\" || this.options.timers.now() < this.runningIntervalUntil;\n return isShortIntervalDue ? this.options.runningIntervalMs : this.options.idleIntervalMs;\n }\n\n /** Arms the next read — not while the page is hidden; its return reads at once. */\n protected scheduleRead(delayMs: number): void {\n this.clearTimer();\n if (this.isStopped || this.options.documentVisibility?.isHidden()) return;\n this.timerHandle = this.options.timers.setTimeout(this.readOnTimer, delayMs);\n }\n\n protected readOnTimer = (): void => {\n this.timerHandle = null;\n this.readNow();\n };\n\n protected receiveVisibilityChange = (): void => {\n if (this.isStopped) return;\n if (this.options.documentVisibility?.isHidden()) {\n this.clearTimer();\n return;\n }\n this.readNow();\n };\n\n protected clearTimer(): void {\n if (this.timerHandle === null) return;\n this.options.timers.clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n}\n\n/** Every subscription of one polling default; `notifyLocalActivity` reaches the subscriptions of a conversation. */\nclass PollingConversationChangeSubscriptions implements PollingConversationChangeSubscription {\n protected readonly activePollers = new Set<ConversationMetadataPoller>();\n\n constructor(\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly options: ResolvedPollingOptions,\n ) {}\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => {\n const poller = new ConversationMetadataPoller(\n conversationId,\n this.readMetadata,\n onSignal,\n onEnded,\n this.options,\n this.activePollers,\n );\n poller.start();\n return poller.stop;\n };\n\n notifyLocalActivity = (conversationId: number): void => {\n for (const poller of [...this.activePollers]) {\n if (poller.conversationId === conversationId) poller.receiveLocalActivity();\n }\n };\n}\n\nconst readDefaultDocumentVisibility = (): PollingDocumentVisibility | null =>\n typeof document === \"undefined\" ? null : new BrowserDocumentVisibility(document);\n\n/**\n * The polling default of `subscribeToConversationChanges` over a metadata read: every 2 s while a turn\n * runs, every 20 s while idle, at once after `notifyLocalActivity`; paused while the page is hidden and read once when\n * it shows again; exponential backoff on failed reads up to 60 s; a `notFound` / `forbidden` read ends the subscription\n * with `gone` / `forbidden`. One poller per subscription; see `ConversationMetadataPoller` for how a read becomes a\n * signal.\n */\nexport const createPollingConversationChangeSubscription = (\n readMetadata: ConversationMetadataReader,\n options: PollingConversationChangeSubscriptionOptions = {},\n): PollingConversationChangeSubscription =>\n new PollingConversationChangeSubscriptions(readMetadata, {\n runningIntervalMs: options.runningIntervalMs ?? POLLING_RUNNING_INTERVAL_MS,\n idleIntervalMs: options.idleIntervalMs ?? POLLING_IDLE_INTERVAL_MS,\n maxBackoffMs: options.maxBackoffMs ?? POLLING_MAX_BACKOFF_MS,\n localActivityWindowMs: options.localActivityWindowMs ?? POLLING_LOCAL_ACTIVITY_WINDOW_MS,\n timers: options.timers ?? new GlobalPollingTimers(),\n documentVisibility: options.documentVisibility === undefined ? readDefaultDocumentVisibility() : options.documentVisibility,\n });\n","import type { AgentsConversationClient } from \"../AgentsConversationClient\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n AgentsConversation,\n ChangedConversationMessages,\n ChangedMessagesRequest,\n ConversationActivity,\n ConversationAttachmentReference,\n ConversationChangeSignal,\n ConversationListQueryOptions,\n ConversationMessageSearchHit,\n ConversationMessageSentPayload,\n ConversationMessagesPage,\n ConversationRunStateRead,\n ConversationSearchGroup,\n ConversationSearchOptions,\n ConversationSignal,\n ConversationSubscriptionEndReason,\n PostedMessage,\n SelectableModel,\n StartedConversation,\n} from \"../../contract/conversation\";\nimport {\n createPollingConversationChangeSubscription,\n type PollingConversationChangeSubscription,\n type PollingConversationChangeSubscriptionOptions,\n} from \"./createPollingConversationChangeSubscription\";\n\n/** A conversation client whose `subscribeToConversationChanges` is present. */\nexport type AgentsConversationClientWithChangeSubscription = AgentsConversationClient &\n Required<Pick<AgentsConversationClient, \"subscribeToConversationChanges\">>;\n\n/**\n * A binding without push, with the polling default as its subscription. Every port function goes to the binding; the\n * three that make the server start a turn on an existing conversation (post, signal, retry) tell the poller once the\n * server accepted them, so the first read does not wait for the idle interval. A start needs no notice: the chat\n * subscribes to the new conversation afterwards, and a subscription reads at once.\n */\nclass PollingAgentsConversationClient implements AgentsConversationClientWithChangeSubscription {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n readonly composeSentMessageText?: (text: string, attachments: ConversationAttachmentReference[] | undefined) => string;\n readonly getMessageSentPayload?: (conversationId: number, messageId: number) => Promise<ConversationMessageSentPayload>;\n readonly getConversationRunState?: (conversationId: number) => Promise<ConversationRunStateRead>;\n readonly getAccountRealtimeMessages?: () => Promise<AccountRealtimeRead>;\n\n constructor(\n protected readonly binding: AgentsConversationClient,\n protected readonly polling: PollingConversationChangeSubscription,\n ) {\n // The optional functions exist exactly when the binding has them (the chat reads their presence).\n this.getSelectableModels = binding.getSelectableModels?.bind(binding);\n this.composeSentMessageText = binding.composeSentMessageText?.bind(binding);\n this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);\n this.getConversationRunState = binding.getConversationRunState?.bind(binding);\n this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);\n }\n\n getConversationMetadata = (conversationId: number): Promise<AgentsConversation> =>\n this.binding.getConversationMetadata(conversationId);\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getNewestMessagesPage(conversationId, pageSize);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getOlderMessagesPage(conversationId, beforeIndex, pageSize);\n\n getChangedMessages = (conversationId: number, request: ChangedMessagesRequest): Promise<ChangedConversationMessages> =>\n this.binding.getChangedMessages(conversationId, request);\n\n startConversation = (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> =>\n this.binding.startConversation(request);\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const postedMessage = await this.binding.postMessage(conversationId, message);\n this.polling.notifyLocalActivity(conversationId);\n return postedMessage;\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.binding.injectSignal(conversationId, signal);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.binding.retryConversation(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n renameConversation = (conversationId: number, title: string): Promise<AgentsConversation> =>\n this.binding.renameConversation(conversationId, title);\n\n deleteConversation = (conversationId: number): Promise<void> => this.binding.deleteConversation(conversationId);\n\n listConversations = (agentSpaceKey: number, options?: ConversationListQueryOptions): Promise<AgentsConversation[]> =>\n this.binding.listConversations(agentSpaceKey, options);\n\n searchConversations = (text: string, options?: ConversationSearchOptions): Promise<ConversationSearchGroup[]> =>\n this.binding.searchConversations(text, options);\n\n searchConversationMessages = (\n conversationId: number,\n text: string,\n options?: ConversationSearchOptions,\n ): Promise<ConversationMessageSearchHit[]> => this.binding.searchConversationMessages(conversationId, text, options);\n\n getConversationActivity = (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> =>\n this.binding.getConversationActivity(conversationId, turnMessageId);\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => this.polling.subscribeToConversationChanges(conversationId, onSignal, onEnded);\n}\n\n/**\n * The client with live updates: a client that brings its own `subscribeToConversationChanges` (a push\n * transport — the host application's Firebase binding) is returned as it is; any other gets the polling default over its\n * `getConversationRunState` when it has one, else over its `getConversationMetadata`\n * (`createPollingConversationChangeSubscription`, `options` tune the intervals). A post, a signal or a retry the server\n * accepted reads at once. The default `AgentChat` calls this by itself.\n */\nexport const withPollingChangeSubscription = (\n client: AgentsConversationClient,\n options?: PollingConversationChangeSubscriptionOptions,\n): AgentsConversationClientWithChangeSubscription => {\n if (client.subscribeToConversationChanges) return client as AgentsConversationClientWithChangeSubscription;\n return new PollingAgentsConversationClient(\n client,\n createPollingConversationChangeSubscription(\n client.getConversationRunState ? client.getConversationRunState.bind(client) : client.getConversationMetadata.bind(client),\n options,\n ),\n );\n};\n"],"names":[],"mappings":";;AAWO,MAAM,8BAA8B;AAEpC,MAAM,2BAA2B;AAEjC,MAAM,yBAAyB;AAK/B,MAAM,mCAAmC;AA6DhD,MAAM,oBAA6C;AAAA,EAAnD,cAAA;AACE,SAAA,aAAa,CAAC,UAAsB,YAA6B,WAAW,WAAW,UAAU,OAAO;AAExG,SAAA,eAAe,CAAC,gBAA+B,WAAW,aAAa,WAA4C;AAEnH,SAAA,MAAM,MAAc,KAAK,IAAA;AAAA,EAAI;AAC/B;AAGA,MAAM,0BAA+D;AAAA,EACnE,YAA+B,iBAA2B;AAA3B,SAAA,kBAAA;AAE/B,SAAA,WAAW,MAAe,KAAK,gBAAgB,oBAAoB;AAEnE,SAAA,SAAS,CAAC,aAAuC;AAC/C,WAAK,gBAAgB,iBAAiB,oBAAoB,QAAQ;AAClE,aAAO,K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AAO;AAC1E,SAAK,wBAAwB,QAAQ,uBAAuB,KAAK,OAAO;AACxE,SAAK,0BAA0B,QAAQ,yBAAyB,KAAK,OAAO;AAC5E,SAAK,6BAA6B,QAAQ,4BAA4B,KAAK,OAAO;AAAA,EACpF;AA6DF;AASO,MAAM,gCAAgC,CAC3C,QACA,YACmD;AACnD,MAAI,OAAO,+BAAgC,QAAO;AAClD,SAAO,IAAI;AAAA,IACT;AAAA,IACA;AAAA,MACE,OAAO,0BAA0B,OAAO,wBAAwB,KAAK,MAAM,IAAI,OAAO,wBAAwB,KAAK,MAAM;AAAA,MACzH;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"withPollingChangeSubscription-CnQnubfK.js","sources":["../../src/client/polling/createPollingConversationChangeSubscription.ts","../../src/client/polling/withPollingChangeSubscription.ts"],"sourcesContent":["import {\n type ConversationChangeSignal,\n type ConversationRunStateRead,\n type ConversationRunStatus,\n type ConversationSubscriptionEndReason,\n CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,\n isAgentsClientError,\n readConversationRunStatusOfRunState,\n} from \"../../contract/conversation\";\n\n/** Read interval while a turn runs (or right after a local send). */\nexport const POLLING_RUNNING_INTERVAL_MS = 2_000;\n/** Read interval while the conversation is idle or failed. */\nexport const POLLING_IDLE_INTERVAL_MS = 20_000;\n/** Ceiling of the exponential backoff after failed reads. */\nexport const POLLING_MAX_BACKOFF_MS = 60_000;\n/**\n * How long after a local send the poller keeps the running interval although the conversation still reads idle: the\n * server may store the owner's message before it marks the turn as running.\n */\nexport const POLLING_LOCAL_ACTIVITY_WINDOW_MS = 10_000;\n\n/**\n * Reads a conversation's run state — the port's `getConversationRunState`, or its `getConversationMetadata` (every\n * conversation carries the fields the poller reads).\n */\nexport type ConversationMetadataReader = (conversationId: number) => Promise<ConversationRunStateRead>;\n\n/** The timer functions the poller uses; a spec hands in fake ones. */\nexport interface PollingTimers {\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (timerHandle: unknown) => void;\n now: () => number;\n}\n\n/** Whether the page is hidden, and a way to hear when that changes; a spec hands in its own. */\nexport interface PollingDocumentVisibility {\n isHidden: () => boolean;\n /** Calls `listener` on every visibility change; returns the function that stops it. */\n listen: (listener: () => void) => () => void;\n}\n\nexport interface PollingConversationChangeSubscriptionOptions {\n /** Default `POLLING_RUNNING_INTERVAL_MS` (2 s). */\n runningIntervalMs?: number;\n /** Default `POLLING_IDLE_INTERVAL_MS` (20 s). */\n idleIntervalMs?: number;\n /** Default `POLLING_MAX_BACKOFF_MS` (60 s). */\n maxBackoffMs?: number;\n /** Default `POLLING_LOCAL_ACTIVITY_WINDOW_MS` (10 s). */\n localActivityWindowMs?: number;\n /** Default: the global `setTimeout` / `clearTimeout` and `Date.now`. */\n timers?: PollingTimers;\n /** Default: the browser `document`; `null` = the page counts as always visible (no `document`, a worker). */\n documentVisibility?: PollingDocumentVisibility | null;\n}\n\n/**\n * The polling default of the live updates: the port's `subscribeToConversationChanges` plus\n * `notifyLocalActivity`, which `withPollingChangeSubscription` calls after every send the server accepted.\n */\nexport interface PollingConversationChangeSubscription {\n subscribeToConversationChanges: (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ) => () => void;\n /** Reads the conversation's metadata now and keeps the running interval for the local-activity window. */\n notifyLocalActivity: (conversationId: number) => void;\n}\n\ninterface ResolvedPollingOptions {\n runningIntervalMs: number;\n idleIntervalMs: number;\n maxBackoffMs: number;\n localActivityWindowMs: number;\n timers: PollingTimers;\n documentVisibility: PollingDocumentVisibility | null;\n}\n\n/** The global timer functions, looked up on each call (so a spec's fake timers installed later still apply). */\nclass GlobalPollingTimers implements PollingTimers {\n setTimeout = (callback: () => void, delayMs: number): unknown => globalThis.setTimeout(callback, delayMs);\n\n clearTimeout = (timerHandle: unknown): void => globalThis.clearTimeout(timerHandle as ReturnType<typeof setTimeout>);\n\n now = (): number => Date.now();\n}\n\n/** The browser document's `visibilityState` and `visibilitychange` event. */\nclass BrowserDocumentVisibility implements PollingDocumentVisibility {\n constructor(protected readonly browserDocument: Document) {}\n\n isHidden = (): boolean => this.browserDocument.visibilityState === \"hidden\";\n\n listen = (listener: () => void): (() => void) => {\n this.browserDocument.addEventListener(\"visibilitychange\", listener);\n return this.browserDocument.removeEventListener.bind(this.browserDocument, \"visibilitychange\", listener);\n };\n}\n\n/**\n * The three-value run status a polled read reports: the stored run state, and \"running\" for an idle conversation the\n * server owes a turn (`agentTurnOwedAt`), as the chat's own derivation does.\n */\nexport const readPolledRunStatus = (\n conversation: Pick<ConversationRunStateRead, \"runState\" | \"agentTurnOwedAt\">,\n): ConversationRunStatus | null => {\n const runStatus = readConversationRunStatusOfRunState(conversation.runState);\n return runStatus === \"idle\" && conversation.agentTurnOwedAt ? \"running\" : runStatus;\n};\n\n/** The end of a subscription a failed read means: a vanished conversation or lost access; null for a passing failure. */\nconst readSubscriptionEndReasonOfReadFailure = (failure: unknown): ConversationSubscriptionEndReason | null => {\n if (!isAgentsClientError(failure)) return null;\n if (failure.kind === \"notFound\") return \"gone\";\n if (failure.kind === \"forbidden\") return \"forbidden\";\n return null;\n};\n\n/**\n * One subscription: reads the conversation's metadata on a timer and turns each read into the change signal.\n *\n * Numbering (the signal leaves it open; the metadata carries no server change counter): the poller keeps its own counter. It\n * starts at 0 with the first read and advances by one whenever a read differs from the previous one in the run status,\n * `lastMessageId` or `updated` — so every polled signal is an ordinary change signal (no `isStatusCheck`) and the\n * package rules apply unchanged: an advance reads the changed tail (throttled), a terminal status reads at once,\n * re-reads the metadata and converges on `lastMessageId`. A status check would carry only the run status as news and\n * would miss a new message under an unchanged status. Without `lastMessageId` in the metadata every poll of a running\n * turn counts as a change (the changed tail is read every poll). `summaryUpdatedAt` is a second local counter that\n * advances when `title` or `summary` changed. A read with no change emits nothing.\n */\nclass ConversationMetadataPoller {\n protected isStopped = false;\n protected isReading = false;\n protected readAgainAfterCurrentRead = false;\n protected timerHandle: unknown = null;\n protected consecutiveFailedReads = 0;\n protected changeCounter = 0;\n protected summaryRevision = 0;\n protected previousChangeFingerprint: string | null = null;\n protected previousSummaryFingerprint: string | null = null;\n protected runStatus: ConversationRunStatus | null = null;\n protected hasConversationEnded = false;\n protected runningIntervalUntil = 0;\n protected stopListeningToVisibility: (() => void) | null = null;\n\n constructor(\n readonly conversationId: number,\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly onSignal: (signal: ConversationChangeSignal) => void,\n protected readonly onEnded: (reason: ConversationSubscriptionEndReason) => void,\n protected readonly options: ResolvedPollingOptions,\n protected readonly activePollers: Set<ConversationMetadataPoller>,\n ) {}\n\n start = (): void => {\n this.activePollers.add(this);\n this.stopListeningToVisibility = this.options.documentVisibility?.listen(this.receiveVisibilityChange) ?? null;\n this.readNow();\n };\n\n /** The unsubscribe: no read, no timer and no signal after it; a read in flight is dropped. */\n stop = (): void => {\n this.isStopped = true;\n this.activePollers.delete(this);\n this.clearTimer();\n this.stopListeningToVisibility?.();\n this.stopListeningToVisibility = null;\n };\n\n receiveLocalActivity = (): void => {\n this.runningIntervalUntil = this.options.timers.now() + this.options.localActivityWindowMs;\n this.readNow();\n };\n\n /** Reads now; a read already in flight is followed by one more read instead (two reads never overlap). */\n protected readNow = (): void => {\n if (this.isStopped) return;\n if (this.isReading) {\n this.readAgainAfterCurrentRead = true;\n return;\n }\n this.clearTimer();\n this.isReading = true;\n void this.readMetadataOnce();\n };\n\n protected async readMetadataOnce(): Promise<void> {\n let conversation: ConversationRunStateRead;\n try {\n conversation = await this.readMetadata(this.conversationId);\n } catch (failure) {\n this.isReading = false;\n this.receiveReadFailure(failure);\n return;\n }\n this.isReading = false;\n if (this.isStopped) return;\n this.consecutiveFailedReads = 0;\n this.receiveConversation(conversation);\n this.continueAfterRead(this.readIntervalMs());\n }\n\n protected receiveConversation(conversation: ConversationRunStateRead): void {\n const runStatus = readPolledRunStatus(conversation);\n const reportsLastMessageId = conversation.lastMessageId !== undefined;\n const changeFingerprint = JSON.stringify([runStatus, conversation.lastMessageId ?? null, conversation.updated]);\n const summaryFingerprint = JSON.stringify([conversation.title, conversation.summary]);\n const isFirstRead = this.previousChangeFingerprint === null;\n const hasChanged =\n changeFingerprint !== this.previousChangeFingerprint || (!reportsLastMessageId && runStatus === \"running\");\n const hasSummaryChanged = !isFirstRead && summaryFingerprint !== this.previousSummaryFingerprint;\n if (!isFirstRead && hasChanged) this.changeCounter += 1;\n if (hasSummaryChanged) this.summaryRevision += 1;\n this.previousChangeFingerprint = changeFingerprint;\n this.previousSummaryFingerprint = summaryFingerprint;\n this.runStatus = runStatus;\n this.hasConversationEnded =\n conversation.runState !== null && CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION.includes(conversation.runState);\n if (!isFirstRead && !hasChanged && !hasSummaryChanged) return;\n this.onSignal({\n changeCounter: this.changeCounter,\n lastMessageId: conversation.lastMessageId ?? null,\n runStatus,\n summaryUpdatedAt: this.summaryRevision,\n });\n }\n\n protected receiveReadFailure(failure: unknown): void {\n if (this.isStopped) return;\n const endReason = readSubscriptionEndReasonOfReadFailure(failure);\n if (endReason !== null) {\n this.stop();\n this.onEnded(endReason);\n return;\n }\n this.consecutiveFailedReads += 1;\n const backoffMs = this.readIntervalMs() * 2 ** this.consecutiveFailedReads;\n this.continueAfterRead(Math.min(backoffMs, this.options.maxBackoffMs));\n }\n\n protected continueAfterRead(nextReadDelayMs: number): void {\n if (this.readAgainAfterCurrentRead) {\n this.readAgainAfterCurrentRead = false;\n this.readNow();\n return;\n }\n // A completed or cancelled conversation changes no more: only a local send or the page's return reads it again.\n if (this.hasConversationEnded) return;\n this.scheduleRead(nextReadDelayMs);\n }\n\n protected readIntervalMs(): number {\n const isShortIntervalDue = this.runStatus === \"running\" || this.options.timers.now() < this.runningIntervalUntil;\n return isShortIntervalDue ? this.options.runningIntervalMs : this.options.idleIntervalMs;\n }\n\n /** Arms the next read — not while the page is hidden; its return reads at once. */\n protected scheduleRead(delayMs: number): void {\n this.clearTimer();\n if (this.isStopped || this.options.documentVisibility?.isHidden()) return;\n this.timerHandle = this.options.timers.setTimeout(this.readOnTimer, delayMs);\n }\n\n protected readOnTimer = (): void => {\n this.timerHandle = null;\n this.readNow();\n };\n\n protected receiveVisibilityChange = (): void => {\n if (this.isStopped) return;\n if (this.options.documentVisibility?.isHidden()) {\n this.clearTimer();\n return;\n }\n this.readNow();\n };\n\n protected clearTimer(): void {\n if (this.timerHandle === null) return;\n this.options.timers.clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n}\n\n/** Every subscription of one polling default; `notifyLocalActivity` reaches the subscriptions of a conversation. */\nclass PollingConversationChangeSubscriptions implements PollingConversationChangeSubscription {\n protected readonly activePollers = new Set<ConversationMetadataPoller>();\n\n constructor(\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly options: ResolvedPollingOptions,\n ) {}\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => {\n const poller = new ConversationMetadataPoller(\n conversationId,\n this.readMetadata,\n onSignal,\n onEnded,\n this.options,\n this.activePollers,\n );\n poller.start();\n return poller.stop;\n };\n\n notifyLocalActivity = (conversationId: number): void => {\n for (const poller of [...this.activePollers]) {\n if (poller.conversationId === conversationId) poller.receiveLocalActivity();\n }\n };\n}\n\nconst readDefaultDocumentVisibility = (): PollingDocumentVisibility | null =>\n typeof document === \"undefined\" ? null : new BrowserDocumentVisibility(document);\n\n/**\n * The polling default of `subscribeToConversationChanges` over a metadata read: every 2 s while a turn\n * runs, every 20 s while idle, at once after `notifyLocalActivity`; paused while the page is hidden and read once when\n * it shows again; exponential backoff on failed reads up to 60 s; a `notFound` / `forbidden` read ends the subscription\n * with `gone` / `forbidden`. One poller per subscription; see `ConversationMetadataPoller` for how a read becomes a\n * signal.\n */\nexport const createPollingConversationChangeSubscription = (\n readMetadata: ConversationMetadataReader,\n options: PollingConversationChangeSubscriptionOptions = {},\n): PollingConversationChangeSubscription =>\n new PollingConversationChangeSubscriptions(readMetadata, {\n runningIntervalMs: options.runningIntervalMs ?? POLLING_RUNNING_INTERVAL_MS,\n idleIntervalMs: options.idleIntervalMs ?? POLLING_IDLE_INTERVAL_MS,\n maxBackoffMs: options.maxBackoffMs ?? POLLING_MAX_BACKOFF_MS,\n localActivityWindowMs: options.localActivityWindowMs ?? POLLING_LOCAL_ACTIVITY_WINDOW_MS,\n timers: options.timers ?? new GlobalPollingTimers(),\n documentVisibility: options.documentVisibility === undefined ? readDefaultDocumentVisibility() : options.documentVisibility,\n });\n","import type { AgentsConversationClient } from \"../AgentsConversationClient\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n AgentsConversation,\n ChangedConversationMessages,\n ChangedMessagesRequest,\n ConversationActivity,\n ConversationAttachmentReference,\n ConversationChangeSignal,\n ConversationListQueryOptions,\n ConversationMessageSearchHit,\n ConversationMessageSentPayload,\n ConversationMessagesPage,\n ConversationRunStateRead,\n ConversationSearchGroup,\n ConversationSearchOptions,\n ConversationSignal,\n ConversationSubscriptionEndReason,\n PostedMessage,\n SelectableModel,\n StartedConversation,\n} from \"../../contract/conversation\";\nimport {\n createPollingConversationChangeSubscription,\n type PollingConversationChangeSubscription,\n type PollingConversationChangeSubscriptionOptions,\n} from \"./createPollingConversationChangeSubscription\";\n\n/** A conversation client whose `subscribeToConversationChanges` is present. */\nexport type AgentsConversationClientWithChangeSubscription = AgentsConversationClient &\n Required<Pick<AgentsConversationClient, \"subscribeToConversationChanges\">>;\n\n/**\n * A binding without push, with the polling default as its subscription. Every port function goes to the binding; the\n * three that make the server start a turn on an existing conversation (post, signal, retry) tell the poller once the\n * server accepted them, so the first read does not wait for the idle interval. A start needs no notice: the chat\n * subscribes to the new conversation afterwards, and a subscription reads at once.\n */\nclass PollingAgentsConversationClient implements AgentsConversationClientWithChangeSubscription {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n readonly composeSentMessageText?: (text: string, attachments: ConversationAttachmentReference[] | undefined) => string;\n readonly getMessageSentPayload?: (conversationId: number, messageId: number) => Promise<ConversationMessageSentPayload>;\n readonly getConversationRunState?: (conversationId: number) => Promise<ConversationRunStateRead>;\n readonly getAccountRealtimeMessages?: (clientId?: string) => Promise<AccountRealtimeRead>;\n\n constructor(\n protected readonly binding: AgentsConversationClient,\n protected readonly polling: PollingConversationChangeSubscription,\n ) {\n // The optional functions exist exactly when the binding has them (the chat reads their presence).\n this.getSelectableModels = binding.getSelectableModels?.bind(binding);\n this.composeSentMessageText = binding.composeSentMessageText?.bind(binding);\n this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);\n this.getConversationRunState = binding.getConversationRunState?.bind(binding);\n this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);\n }\n\n getConversationMetadata = (conversationId: number): Promise<AgentsConversation> =>\n this.binding.getConversationMetadata(conversationId);\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getNewestMessagesPage(conversationId, pageSize);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getOlderMessagesPage(conversationId, beforeIndex, pageSize);\n\n getChangedMessages = (conversationId: number, request: ChangedMessagesRequest): Promise<ChangedConversationMessages> =>\n this.binding.getChangedMessages(conversationId, request);\n\n startConversation = (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> =>\n this.binding.startConversation(request);\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const postedMessage = await this.binding.postMessage(conversationId, message);\n this.polling.notifyLocalActivity(conversationId);\n return postedMessage;\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.binding.injectSignal(conversationId, signal);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.binding.retryConversation(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n renameConversation = (conversationId: number, title: string): Promise<AgentsConversation> =>\n this.binding.renameConversation(conversationId, title);\n\n deleteConversation = (conversationId: number): Promise<void> => this.binding.deleteConversation(conversationId);\n\n listConversations = (agentSpaceKey: number, options?: ConversationListQueryOptions): Promise<AgentsConversation[]> =>\n this.binding.listConversations(agentSpaceKey, options);\n\n searchConversations = (text: string, options?: ConversationSearchOptions): Promise<ConversationSearchGroup[]> =>\n this.binding.searchConversations(text, options);\n\n searchConversationMessages = (\n conversationId: number,\n text: string,\n options?: ConversationSearchOptions,\n ): Promise<ConversationMessageSearchHit[]> => this.binding.searchConversationMessages(conversationId, text, options);\n\n getConversationActivity = (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> =>\n this.binding.getConversationActivity(conversationId, turnMessageId);\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => this.polling.subscribeToConversationChanges(conversationId, onSignal, onEnded);\n}\n\n/**\n * The client with live updates: a client that brings its own `subscribeToConversationChanges` (a push\n * transport — the host application's Firebase binding) is returned as it is; any other gets the polling default over its\n * `getConversationRunState` when it has one, else over its `getConversationMetadata`\n * (`createPollingConversationChangeSubscription`, `options` tune the intervals). A post, a signal or a retry the server\n * accepted reads at once. The default `AgentChat` calls this by itself.\n */\nexport const withPollingChangeSubscription = (\n client: AgentsConversationClient,\n options?: PollingConversationChangeSubscriptionOptions,\n): AgentsConversationClientWithChangeSubscription => {\n if (client.subscribeToConversationChanges) return client as AgentsConversationClientWithChangeSubscription;\n return new PollingAgentsConversationClient(\n client,\n createPollingConversationChangeSubscription(\n client.getConversationRunState ? client.getConversationRunState.bind(client) : client.getConversationMetadata.bind(client),\n options,\n ),\n );\n};\n"],"names":[],"mappings":";;AAWO,MAAM,8BAA8B;AAEpC,MAAM,2BAA2B;AAEjC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KAAK,QAAQ,kBAAkB,eAAe,OAAO;AAEvD,SAAA,sBAAsB,CAAC,MAAc,YACnC,KAAK,QAAQ,oBAAoB,MAAM,OAAO;AAEhD,SAAA,6BAA6B,CAC3B,gBACA,MACA,YAC4C,KAAK,QAAQ,2BAA2B,gBAAgB,MAAM,OAAO;AAEnH,SAAA,0BAA0B,CAAC,gBAAwB,kBACjD,KAAK,QAAQ,wBAAwB,gBAAgB,aAAa;AAEpE,SAAA,iCAAiC,CAC/B,gBACA,UACA,YACiB,KAAK,QAAQ,+BAA+B,gBAAgB,UAAU,OAAO;AAjE9F,SAAK,sBAAsB,QAAQ,qBAAqB,KAAK,OAAO;AACpE,SAAK,yBAAyB,QAAQ,wBAAwB,KAAK,OAAO;AAC1E,SAAK,wBAAwB,QAAQ,uBAAuB,KAAK,OAAO;AACxE,SAAK,0BAA0B,QAAQ,yBAAyB,KAAK,OAAO;AAC5E,SAAK,6BAA6B,QAAQ,4BAA4B,KAAK,OAAO;AAAA,EACpF;AA6DF;AASO,MAAM,gCAAgC,CAC3C,QACA,YACmD;AACnD,MAAI,OAAO,+BAAgC,QAAO;AAClD,SAAO,IAAI;AAAA,IACT;AAAA,IACA;AAAA,MACE,OAAO,0BAA0B,OAAO,wBAAwB,KAAK,MAAM,IAAI,OAAO,wBAAwB,KAAK,MAAM;AAAA,MACzH;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
package/dist/client-testing.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { a as AgentsClientError, C as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION, r as readConversationRunStatusOfRunState } from "./chunks/conversation-CbWEHPbL.js";
|
|
3
3
|
import { c as composeAttachmentMessageText } from "./chunks/compose-attachment-message-text-FvVJbrge.js";
|
|
4
|
-
import { l as listWidgetHydratorTypes, j as getWidgetHydrator, g as registerWidgetHydrator, k as abandonWidgetHydrationReads, u as unregisterWidgetHydrator } from "./chunks/WebSearchResultsConversationWidget-
|
|
5
|
-
import { j as conversationWidgetRegistry, k as replaceConversationWidgetRegistryEntries } from "./chunks/widget-name-resolver-
|
|
6
|
-
import { l, s } from "./chunks/widget-name-resolver-
|
|
7
|
-
import { c, r, s as s2 } from "./chunks/canvasStorage-
|
|
4
|
+
import { l as listWidgetHydratorTypes, j as getWidgetHydrator, g as registerWidgetHydrator, k as abandonWidgetHydrationReads, u as unregisterWidgetHydrator } from "./chunks/WebSearchResultsConversationWidget-DXhfSikV.js";
|
|
5
|
+
import { j as conversationWidgetRegistry, k as replaceConversationWidgetRegistryEntries } from "./chunks/widget-name-resolver-B9k-s_cF.js";
|
|
6
|
+
import { l, s } from "./chunks/widget-name-resolver-B9k-s_cF.js";
|
|
7
|
+
import { c, r, s as s2 } from "./chunks/canvasStorage-BbEI3h-8.js";
|
|
8
8
|
const DEFAULT_SCRIPTED_ASSISTANT_ANSWER = "Done.";
|
|
9
9
|
const DEFAULT_PAGE_SIZE = 50;
|
|
10
10
|
const copyOf = (value) => JSON.parse(JSON.stringify(value));
|
package/dist/client.js
CHANGED
|
@@ -3,7 +3,7 @@ import { A, u, a } from "./chunks/AgentsConversationClientContext-C4T7g_Qk.js";
|
|
|
3
3
|
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-CnQnubfK.js";
|
|
4
4
|
import { P, a as a2, b, c, d, r } from "./chunks/withPollingChangeSubscription-CnQnubfK.js";
|
|
5
5
|
import { A as AGENTS_CLIENT_CONTEXT_LIMITS, a as AgentsClientError, b as AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED } from "./chunks/conversation-CbWEHPbL.js";
|
|
6
|
-
import { a as acceptArrivedRealtimeMessage } from "./chunks/realtime-arrival-
|
|
6
|
+
import { a as acceptArrivedRealtimeMessage, c as createAgentUIClientId } from "./chunks/realtime-arrival-BfsAPwqQ.js";
|
|
7
7
|
import { c as composeAttachmentMessageText } from "./chunks/compose-attachment-message-text-FvVJbrge.js";
|
|
8
8
|
const RUN_STATES = [
|
|
9
9
|
"IDLE",
|
|
@@ -255,12 +255,12 @@ class AgentsHttpConversationClient {
|
|
|
255
255
|
this.options.onRealtimeListenerCredential?.(conversationId, response.realtimeListenerCredential ?? null);
|
|
256
256
|
return mapWireConversationRunState(response);
|
|
257
257
|
};
|
|
258
|
-
this.getAccountRealtimeMessages = async () => {
|
|
258
|
+
this.getAccountRealtimeMessages = async (clientId) => {
|
|
259
259
|
const response = await this.request({
|
|
260
260
|
operation: "getAccountRealtimeMessages",
|
|
261
261
|
method: "GET",
|
|
262
262
|
path: "/realtimeMessages",
|
|
263
|
-
query:
|
|
263
|
+
query: { clientId: this.resolveAccountReadClientId(clientId) }
|
|
264
264
|
});
|
|
265
265
|
return {
|
|
266
266
|
messages: readWireSetElements(response.realtimeMessages),
|
|
@@ -419,6 +419,17 @@ class AgentsHttpConversationClient {
|
|
|
419
419
|
};
|
|
420
420
|
if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;
|
|
421
421
|
}
|
|
422
|
+
/**
|
|
423
|
+
* The client id the account read states, decided here and nowhere else: the caller's, else the bound `uiClient`'s,
|
|
424
|
+
* else one this client creates once and keeps while it lives. Only the account read asks: every other request
|
|
425
|
+
* states a client id only with a `uiClient`.
|
|
426
|
+
*/
|
|
427
|
+
resolveAccountReadClientId(clientId) {
|
|
428
|
+
if (clientId) return clientId;
|
|
429
|
+
if (this.options.uiClient) return this.options.uiClient.clientId;
|
|
430
|
+
this.ownAccountReadClientId ??= createAgentUIClientId();
|
|
431
|
+
return this.ownAccountReadClientId;
|
|
432
|
+
}
|
|
422
433
|
/** What the UI shows after the request was carried out, so the server's `[SIGNAL:ui]` note is current at once. */
|
|
423
434
|
readUIStateJsonAfterAnswer() {
|
|
424
435
|
const uiState = this.options.uiClient?.readUIState() ?? null;
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../src/client/http/agents-http-mappers.ts","../src/client/http/createAgentsHttpConversationClient.ts"],"sourcesContent":["import {\n AGENTS_CLIENT_CONTEXT_LIMITS,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsClientErrorKind,\n type AgentsConversation,\n type AgentsConversationMessage,\n type ConversationActivity,\n type ConversationActivityElement,\n type ConversationMessageAuthorType,\n type ConversationMessageRole,\n type ConversationMessageSearchHit,\n type ConversationMessageStatus,\n type ConversationMessageType,\n type ConversationProgressStep,\n type ConversationRunState,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSubAgent,\n type SelectableModel,\n} from \"../../contract/conversation\";\nimport type {\n WireActivityLine,\n WireClientContext,\n WireClientContextRouteParameter,\n WireConversation,\n WireConversationActivityResponse,\n WireConversationMessage,\n WireConversationRunStateResponse,\n WireConversationSearchGroup,\n WireCustomerProgressStep,\n WireDelegationSubAgentRecord,\n WireErrorBody,\n WireSelectableModel,\n WireSemanticSearchHit,\n WireSet,\n} from \"./agents-http-wire\";\n\n// The vocabularies of the contract: a wire value outside one maps to null.\nconst RUN_STATES: readonly ConversationRunState[] = [\n \"IDLE\",\n \"QUEUED\",\n \"RUNNING\",\n \"AWAITING_DELEGATES\",\n \"FAILED\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nconst MESSAGE_ROLES: readonly ConversationMessageRole[] = [\"SYSTEM\", \"USER\", \"ASSISTANT\"];\nconst MESSAGE_TYPES: readonly ConversationMessageType[] = [\n \"TEXT\",\n \"TOOL_CALL\",\n \"CHECKPOINT\",\n \"ERROR\",\n \"SIGNAL\",\n \"TOOL_MESSAGE\",\n];\nconst MESSAGE_STATUSES: readonly ConversationMessageStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"COMPLETED\",\n \"FAILED\",\n];\nconst AUTHOR_TYPES: readonly ConversationMessageAuthorType[] = [\"USER\", \"ASSISTANT\", \"AGENT\", \"TOOL\"];\nconst PROGRESS_STEP_STATUSES: readonly ConversationProgressStep[\"status\"][] = [\"done\", \"active\", \"upcoming\"];\nconst ACTIVITY_STATES: readonly NonNullable<ConversationActivityElement[\"state\"]>[] = [\n \"queued\",\n \"running\",\n \"finished\",\n \"failed\",\n \"skipped\",\n];\nconst ACTIVITY_KINDS: readonly NonNullable<ConversationActivityElement[\"kind\"]>[] = [\n \"tool\",\n \"delegation\",\n \"background\",\n \"long\",\n \"turnStart\",\n];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a serialized set (`{ elements: [...] }`), a plain array, or the values of a keyed object. */\nexport const readWireSetElements = <Element>(\n wireSet: WireSet<Element> | Record<string, Element> | null | undefined,\n): Element[] => {\n if (!wireSet) return [];\n if (Array.isArray(wireSet)) return wireSet;\n if (typeof wireSet === \"object\" && \"elements\" in wireSet) {\n const elements = (wireSet as { elements?: Element[] | null }).elements;\n return Array.isArray(elements) ? elements : [];\n }\n return Object.values(wireSet as Record<string, Element>);\n};\n\nconst mapWireProgressStep = (wireStep: WireCustomerProgressStep): ConversationProgressStep => ({\n key: wireStep.key ?? \"\",\n label: wireStep.customerLabel ?? \"\",\n status: readVocabularyValue(PROGRESS_STEP_STATUSES, wireStep.status) ?? \"upcoming\",\n});\n\n/** An `AIConversation` as the contract's conversation. */\nexport const mapWireConversation = (wireConversation: WireConversation): AgentsConversation => {\n const conversation: AgentsConversation = {\n id: wireConversation.id ?? 0,\n agentSpaceKey: readNumberOrNull(wireConversation.agentSpaceId),\n runState: readVocabularyValue(RUN_STATES, wireConversation.runState),\n agentTurnOwedAt: readStringOrNull(wireConversation.agentTurnOwedAt),\n title: readStringOrNull(wireConversation.summary?.title),\n titleManuallyEdited: wireConversation.summary?.manuallyEdited === true,\n summary: readStringOrNull(wireConversation.summary?.text),\n created: readStringOrNull(wireConversation.created ?? wireConversation.changeHistory?.createdTime),\n updated: readStringOrNull(wireConversation.updated ?? wireConversation.changeHistory?.modifiedTime),\n purposeName: readStringOrNull(wireConversation.purposeName),\n initiatorType: readStringOrNull(wireConversation.initiatorType),\n scheduleId: readNumberOrNull(wireConversation.scheduleId),\n entryPointKey: readStringOrNull(wireConversation.entryPointKey),\n progressSteps: readWireSetElements(wireConversation.customerProgressSteps).map(mapWireProgressStep),\n };\n if (wireConversation.lastMessageId !== undefined) conversation.lastMessageId = readNumberOrNull(wireConversation.lastMessageId);\n if (wireConversation.aiPromptExtensionId !== undefined) {\n conversation.promptExtensionId = readNumberOrNull(wireConversation.aiPromptExtensionId);\n }\n return conversation;\n};\n\nconst mapWireSubAgent = (wireSubAgent: WireDelegationSubAgentRecord | null | undefined): ConversationSubAgent | null =>\n wireSubAgent\n ? {\n currentRunNumber: readNumberOrNull(wireSubAgent.currentRunNumber),\n runs: readWireSetElements(wireSubAgent.runs).map((wireRun) => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n })),\n }\n : null;\n\n/** An `AIConversationMessage` as the contract's message. */\nexport const mapWireConversationMessage = (wireMessage: WireConversationMessage): AgentsConversationMessage => {\n const message: AgentsConversationMessage = {\n id: wireMessage.id ?? 0,\n conversationId: readNumberOrNull(wireMessage.aiConversationId),\n indexInConversation: readNumberOrNull(wireMessage.indexInConversation),\n role: readVocabularyValue(MESSAGE_ROLES, wireMessage.role),\n messageType: readVocabularyValue(MESSAGE_TYPES, wireMessage.messageType),\n status: readVocabularyValue(MESSAGE_STATUSES, wireMessage.status),\n authorType: readVocabularyValue(AUTHOR_TYPES, wireMessage.authorType),\n signalSource: readStringOrNull(wireMessage.signalSource),\n message: wireMessage.message ?? \"\",\n createdDate: readStringOrNull(wireMessage.createdDate),\n toolCall: wireMessage.toolCall\n ? {\n toolCallId: readStringOrNull(wireMessage.toolCall.toolCallId),\n name: readStringOrNull(wireMessage.toolCall.name),\n arguments: wireMessage.toolCall.arguments ?? null,\n status: readStringOrNull(wireMessage.toolCall.status),\n }\n : null,\n delegatedConversations: readWireSetElements(wireMessage.delegatedConversations).map((delegated) => ({\n id: delegated.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, delegated.runState),\n })),\n subAgent: mapWireSubAgent(wireMessage.delegationResults?.subAgent),\n };\n const hasForensics =\n wireMessage.inputTokens != null || wireMessage.outputTokens != null || wireMessage.requestSnapshot != null;\n if (hasForensics) {\n message.forensics = {\n inputTokens: readNumberOrNull(wireMessage.inputTokens),\n outputTokens: readNumberOrNull(wireMessage.outputTokens),\n costInUSD: readNumberOrNull(wireMessage.costInUSD),\n requestSnapshot: wireMessage.requestSnapshot ?? null,\n };\n }\n return message;\n};\n\n/** The run-state read (`AIConversationRunStateGetResponseDto`). */\nexport const mapWireConversationRunState = (wireRunState: WireConversationRunStateResponse): ConversationRunStateRead => ({\n id: wireRunState.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, wireRunState.runState),\n agentTurnOwedAt: readStringOrNull(wireRunState.agentTurnOwedAt),\n lastMessageId: readNumberOrNull(wireRunState.lastMessageId),\n title: readStringOrNull(wireRunState.title),\n titleManuallyEdited: wireRunState.titleManuallyEdited === true,\n summary: readStringOrNull(wireRunState.summary),\n updated: readStringOrNull(wireRunState.updated),\n});\n\nconst mapWireActivityLine = (wireLine: WireActivityLine): ConversationActivityElement => ({\n toolCallMessageId: wireLine.toolCallMessageId ?? 0,\n batchId: readStringOrNull(wireLine.batchId),\n state: readVocabularyValue(ACTIVITY_STATES, wireLine.state),\n kind: readVocabularyValue(ACTIVITY_KINDS, wireLine.kind),\n childCount: readNumberOrNull(wireLine.childCount),\n helperIndex: readNumberOrNull(wireLine.helperIndex),\n line: readStringOrNull(wireLine.line),\n});\n\n/** The activity of a turn (`AIConversationActivityGetResponseDto`). */\nexport const mapWireConversationActivity = (wireActivity: WireConversationActivityResponse): ConversationActivity => ({\n turnMessageId: readNumberOrNull(wireActivity.turnMessageId),\n turnRunning: wireActivity.turnRunning === true,\n elements: readWireSetElements(wireActivity.elements).map(mapWireActivityLine),\n});\n\n/** A `SemanticSearchHit`. */\nexport const mapWireSearchHit = (wireHit: WireSemanticSearchHit): ConversationMessageSearchHit => ({\n messageId: readNumberOrNull(wireHit.messageId),\n conversationId: readNumberOrNull(wireHit.conversationId),\n indexInConversation: readNumberOrNull(wireHit.indexInConversation),\n role: readStringOrNull(wireHit.role),\n excerpt: wireHit.excerpt ?? \"\",\n relevance: readNumberOrNull(wireHit.relevance) ?? 0,\n created: readStringOrNull(wireHit.created),\n updated: readStringOrNull(wireHit.updated),\n title: readStringOrNull(wireHit.title),\n});\n\n/** An `AIConversationSearchGroup`. */\nexport const mapWireSearchGroup = (wireGroup: WireConversationSearchGroup): ConversationSearchGroup => ({\n conversationId: readNumberOrNull(wireGroup.conversationId),\n title: readStringOrNull(wireGroup.title),\n summary: readStringOrNull(wireGroup.summary),\n created: readStringOrNull(wireGroup.created),\n updated: readStringOrNull(wireGroup.updated),\n relevance: readNumberOrNull(wireGroup.relevance) ?? 0,\n hits: readWireSetElements(wireGroup.hits).map(mapWireSearchHit),\n});\n\n/** An `AgentCustomerSelectableModel`. */\nexport const mapWireSelectableModel = (wireModel: WireSelectableModel): SelectableModel => ({\n name: wireModel.name ?? \"\",\n displayName: wireModel.displayName ?? wireModel.name ?? \"\",\n description: wireModel.description ?? \"\",\n strengthLevel: readNumberOrNull(wireModel.strengthLevel),\n speedLevel: readNumberOrNull(wireModel.speedLevel),\n creditsMultiplier: readNumberOrNull(wireModel.creditsMultiplier),\n});\n\n/** The stable codes of the server's refusals the chat tells apart. */\nconst ERROR_KIND_BY_CODE: Readonly<Record<string, AgentsClientErrorKind>> = {\n AI_BUDGET_REACHED: \"budget\",\n RATE_LIMIT_EXCEEDED: \"rateLimit\",\n CONVERSATION_CLOSED: \"closed\",\n};\n\n/**\n * A refused request as the port's error: the stable code first (`errorCode` of the JSON body), then the status — 429\n * `rateLimit` (with `Retry-After`), 404 `notFound`, 403 and 401 `forbidden`, 5xx `network`, everything else `other`.\n */\nexport const mapHttpFailureToAgentsClientError = (\n httpStatus: number,\n wireErrorBody: WireErrorBody | null,\n retryAfterHeader: string | null,\n): AgentsClientError => {\n const code = wireErrorBody?.errorCode ?? wireErrorBody?.code ?? null;\n const message = wireErrorBody?.error ?? wireErrorBody?.message ?? undefined;\n const retryAfterOfHeader = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader) : null;\n const retryAfterSeconds = readNumberOrNull(wireErrorBody?.retryAfterSeconds) ?? retryAfterOfHeader;\n const kindOfCode = code !== null ? ERROR_KIND_BY_CODE[code] : undefined;\n const kind: AgentsClientErrorKind =\n kindOfCode ??\n (httpStatus === 429\n ? \"rateLimit\"\n : httpStatus === 404\n ? \"notFound\"\n : httpStatus === 403 || httpStatus === 401\n ? \"forbidden\"\n : httpStatus >= 500\n ? \"network\"\n : \"other\");\n return new AgentsClientError(kind, { message: message ?? undefined, code, retryAfterSeconds, httpStatus });\n};\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f]/;\n\n/** A text field of the client context as it goes out: trimmed, or left out when empty, over its cap or not one line. */\nconst readClientContextText = (value: string | number | null | undefined, maxChars: number): string | undefined => {\n if (value === null || value === undefined) return undefined;\n const text = String(value).trim();\n if (text === \"\" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return undefined;\n return text;\n};\n\n/**\n * The client context as the body field `clientContext` carries it (`AgentClientContext`): the route parameters as a\n * list of `{name, value}`. A field over its cap ({@link AGENTS_CLIENT_CONTEXT_LIMITS}) or with a control character is\n * left out — never cut — so a send never fails on the context; the route parameters go together or not at all.\n * Undefined when nothing is left.\n */\nexport const mapClientContextToWire = (clientContext: AgentsClientContext | null | undefined): WireClientContext | undefined => {\n if (!clientContext) return undefined;\n const wireClientContext: WireClientContext = {};\n const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);\n if (routePath !== undefined) wireClientContext.routePath = routePath;\n const routeParameters: WireClientContextRouteParameter[] = Object.entries(clientContext.routeParameters ?? {})\n .filter(([name, value]) => name.trim() !== \"\" && value !== null && value !== undefined)\n .map(([name, value]) => ({ name, value: String(value) }));\n const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join(\"&\");\n if (\n routeParameters.length > 0 &&\n routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount &&\n routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars &&\n !CONTROL_CHARACTERS.test(routeParametersText)\n ) {\n wireClientContext.routeParameters = routeParameters;\n }\n const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);\n if (recordKind !== undefined) wireClientContext.recordKind = recordKind;\n const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);\n if (recordId !== undefined) wireClientContext.recordId = recordId;\n const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);\n if (tab !== undefined) wireClientContext.tab = tab;\n return Object.keys(wireClientContext).length > 0 ? wireClientContext : undefined;\n};\n","import type {\n AgentsConversationClient,\n AgentsConversationClientBindingOptions,\n AgentsConversationOperation,\n} from \"../AgentsConversationClient\";\nimport {\n AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsConversation,\n type ChangedConversationMessages,\n type ChangedMessagesRequest,\n type ConversationActivity,\n type ConversationAttachmentReference,\n type ConversationListQueryOptions,\n type ConversationMessageSearchHit,\n type ConversationMessagesPage,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSearchOptions,\n type ConversationSignal,\n type PostedMessage,\n type SelectableModel,\n type StartedConversation,\n} from \"../../contract/conversation\";\nimport type { AgentUIState } from \"../../ui/agent-ui-state\";\nimport type { AgentUIClientBinding } from \"../../ui/AgentUIClient\";\nimport type { ClientToolAnswer } from \"../../ui/client-tools\";\nimport {\n acceptArrivedRealtimeMessage,\n type AgentRealtimeListenerCredential,\n type AgentRealtimeMessageDelivery,\n} from \"../../ui/realtime-arrival\";\nimport { composeAttachmentMessageText } from \"../compose-attachment-message-text\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../polling/withPollingChangeSubscription\";\nimport {\n mapClientContextToWire,\n mapHttpFailureToAgentsClientError,\n mapWireConversation,\n mapWireConversationActivity,\n mapWireConversationMessage,\n mapWireConversationRunState,\n mapWireSearchGroup,\n mapWireSearchHit,\n mapWireSelectableModel,\n readWireSetElements,\n} from \"./agents-http-mappers\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n WireAccountRealtimeMessagesResponse,\n WireConversationActivityResponse,\n WireConversationMessageSearchResponse,\n WireConversationMessagesResponse,\n WireConversationResponse,\n WireConversationRunStateResponse,\n WireConversationSearchResponse,\n WireConversationsResponse,\n WireConversationStartResponse,\n WireErrorBody,\n WireSelectableModelsResponse,\n} from \"./agents-http-wire\";\n\n/** What every request of the binding carries from the host: headers, credentials, mode, cache. */\nexport type AgentsHttpFetchOptions = Omit<RequestInit, \"method\" | \"body\">;\n\nexport interface AgentsHttpConversationClientOptions extends AgentsConversationClientBindingOptions {\n /**\n * Where the application's conversations controller is mounted (its `#[Route]`): a path such as\n * `/api/agents/conversations` or an absolute URL. The module's routes are relative to it.\n */\n baseUrl: string;\n /**\n * Request options every request carries (credentials, an authorization header). A function is called per request,\n * so it may hand out a fresh token. Default: none (the browser's defaults: same-origin credentials).\n */\n fetchOptions?: AgentsHttpFetchOptions | (() => AgentsHttpFetchOptions | Promise<AgentsHttpFetchOptions>);\n /** The fetch function. Default: the global `fetch`. */\n fetch?: typeof fetch;\n /**\n * The application's start route below `baseUrl` (`AgentConversationStartTrait` declares none). Default: `/start` for\n * a start without an agent space (key 0), `/start/{agentSpaceKey}` otherwise — the start DTO reads `agentSpaceId`\n * from the path.\n */\n buildStartPath?: (agentSpaceKey: number) => string;\n /**\n * The controller uses `AgentSelectableModelsTrait` (`GET …/selectable-models`): the client offers\n * `getSelectableModels` and the chat shows the model picker. Default false.\n */\n hasSelectableModelsRoute?: boolean;\n /**\n * The live updates: the polling default over the run-state read (`withPollingChangeSubscription`), which also reads\n * at once after a post, a signal or a retry the server accepted. The intervals of\n * `PollingConversationChangeSubscriptionOptions`; `false` = no subscription (the host adds its own push transport).\n * Default: polling with the default intervals.\n */\n polling?: PollingConversationChangeSubscriptionOptions | false;\n /**\n * What the owner's client shows, read on every start, posted message and injected signal and sent as the body field\n * `clientContext` (the route, its parameters, the record on screen, the tab). The agent reads the newest one as one\n * line beside the owner's newest message. A field over its cap is left out, never cut. Default: none.\n */\n clientContext?: (operation: AgentsClientContextOperation) => AgentsClientContext | null | undefined;\n /**\n * The UI side of `Agent.UI` (`AgentUIClient` of `@mgamadeus/ddd-agents/ui`): its client id and UI state ride on every\n * write and every run-state read; a client tool request the run-state read delivers goes to it, and the binding\n * posts its answer (`POST /{conversationId}/clientToolRequests/{requestId}/answer`). Default: none.\n */\n uiClient?: AgentUIClientBinding;\n /**\n * The open messages of the realtime port of other types than a client tool request (types other packages\n * registered), as the run-state read delivers them; a client acts on one type and key once. Default: none.\n */\n onRealtimeMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void;\n /** What the client needs to listen on the host's transport, with every run-state read (null without one). Default: none. */\n onRealtimeListenerCredential?: (conversationId: number, credential: AgentRealtimeListenerCredential | null) => void;\n}\n\n/** The writes that carry the client context. */\nexport type AgentsClientContextOperation = \"startConversation\" | \"postMessage\" | \"injectSignal\";\n\n/** The page size of a changed-messages read when the request names none (as the chat sends it). */\nexport const AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE = 50;\n\n/** The expand of every message page: the delegated children with the two fields the chat reads. */\nconst MESSAGES_EXPAND = \"delegatedConversations(select=id,runState)\";\n\nconst defaultBuildStartPath = (agentSpaceKey: number): string => (agentSpaceKey > 0 ? `/start/${agentSpaceKey}` : \"/start\");\n\ntype QueryParameters = Record<string, string | number | boolean | undefined | null>;\n\ninterface HttpRequest {\n operation: AgentsConversationOperation;\n method: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: QueryParameters;\n body?: unknown;\n}\n\n/** A filter value as the query-options grammar writes it: quoted. */\nconst quoteFilterValue = (value: number | string): string => `'${String(value).replace(/'/g, \"\\\\'\")}'`;\n\n/** The module's conversation routes over fetch: one request per port function, the wire mapped onto the contract. */\nclass AgentsHttpConversationClient implements AgentsConversationClient {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n\n constructor(protected readonly options: AgentsHttpConversationClientOptions) {\n if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;\n }\n\n // ── Reads ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n getConversationMetadata = async (conversationId: number): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"getConversationMetadata\",\n method: \"GET\",\n path: `/${conversationId}`,\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n getConversationRunState = async (conversationId: number): Promise<ConversationRunStateRead> => {\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n const response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n query: uiClient ? { clientId: uiClient.clientId, uiStateJson: uiState ? JSON.stringify(uiState) : undefined } : undefined,\n });\n const sendAnswer = (requestId: number, answer: ClientToolAnswer): Promise<void> =>\n this.answerClientToolRequest(conversationId, requestId, answer);\n if (uiClient && response.clientToolRequest) {\n uiClient.acceptClientToolRequest(conversationId, response.clientToolRequest, sendAnswer);\n }\n for (const message of readWireSetElements(response.realtimeMessages)) {\n if (uiClient) acceptArrivedRealtimeMessage(conversationId, message, uiClient, sendAnswer, this.options.onRealtimeMessage);\n else this.options.onRealtimeMessage?.(conversationId, message);\n }\n this.options.onRealtimeListenerCredential?.(conversationId, response.realtimeListenerCredential ?? null);\n return mapWireConversationRunState(response);\n };\n\n /**\n * The account-level realtime read (`GET /realtimeMessages`): the messages addressed to the signed-in account for this\n * client (the `uiClient`'s id when bound) and the listener credential without a conversation. Arrival is the\n * caller's (`createAccountRealtimePoll` of `/ui`).\n */\n getAccountRealtimeMessages = async (): Promise<AccountRealtimeRead> => {\n const response = await this.request<WireAccountRealtimeMessagesResponse>({\n operation: \"getAccountRealtimeMessages\",\n method: \"GET\",\n path: \"/realtimeMessages\",\n query: this.options.uiClient ? { clientId: this.options.uiClient.clientId } : undefined,\n });\n return {\n messages: readWireSetElements(response.realtimeMessages),\n listenerCredential: response.realtimeListenerCredential ?? null,\n };\n };\n\n /** Posts the answer of the UI client to a client tool request (`Agent.UI`); a refused answer is the server's word. */\n answerClientToolRequest = async (conversationId: number, requestId: number, answer: ClientToolAnswer): Promise<void> => {\n await this.request<unknown>({\n operation: \"answerClientToolRequest\",\n method: \"POST\",\n path: `/${conversationId}/clientToolRequests/${requestId}/answer`,\n body: {\n clientId: this.options.uiClient?.clientId ?? \"\",\n outcome: answer.outcome,\n text: answer.text,\n detailsJson: JSON.stringify(answer.details ?? {}),\n pictureBase64: answer.pictureBase64,\n uiStateJson: this.readUIStateJsonAfterAnswer(),\n },\n });\n };\n\n /** What the UI shows after the request was carried out, so the server's `[SIGNAL:ui]` note is current at once. */\n protected readUIStateJsonAfterAnswer(): string | undefined {\n const uiState: AgentUIState | null = this.options.uiClient?.readUIState() ?? null;\n return uiState ? JSON.stringify(uiState) : undefined;\n }\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\"getNewestMessagesPage\", conversationId, pageSize, undefined);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\n \"getOlderMessagesPage\",\n conversationId,\n pageSize,\n `indexInConversation lt ${quoteFilterValue(beforeIndex)}`,\n );\n\n getChangedMessages = async (\n conversationId: number,\n request: ChangedMessagesRequest,\n ): Promise<ChangedConversationMessages> => {\n const page = await this.readMessagesPage(\n \"getChangedMessages\",\n conversationId,\n request.pageSize ?? AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE,\n `(id gt ${quoteFilterValue(request.highestKnownId)} or indexInConversation ge ${quoteFilterValue(request.fromIndex)})`,\n );\n return { messages: page.messages };\n };\n\n listConversations = async (agentSpaceKey: number, options: ConversationListQueryOptions = {}): Promise<AgentsConversation[]> => {\n const filters = [\"rootConversationId eq null\"];\n if (agentSpaceKey > 0) filters.push(`agentSpaceId eq ${quoteFilterValue(agentSpaceKey)}`);\n const response = await this.request<WireConversationsResponse>({\n operation: \"listConversations\",\n method: \"GET\",\n path: \"/listAllConversations\",\n query: {\n filters: filters.join(\" and \"),\n orderBy: \"id desc\",\n top: options.paging?.top,\n skip: options.paging?.skip,\n },\n });\n const conversations = readWireSetElements(response.aiConversations).map(mapWireConversation);\n // Without a summary there is no title yet; the list leaves such a conversation out unless asked for it.\n return options.includeUnsummarized ? conversations : conversations.filter((conversation) => conversation.title !== null);\n };\n\n searchConversations = async (text: string, options: ConversationSearchOptions = {}): Promise<ConversationSearchGroup[]> => {\n const response = await this.request<WireConversationSearchResponse>({\n operation: \"searchConversations\",\n method: \"GET\",\n path: \"/search\",\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.conversations).map(mapWireSearchGroup);\n };\n\n searchConversationMessages = async (\n conversationId: number,\n text: string,\n options: ConversationSearchOptions = {},\n ): Promise<ConversationMessageSearchHit[]> => {\n const response = await this.request<WireConversationMessageSearchResponse>({\n operation: \"searchConversationMessages\",\n method: \"GET\",\n path: `/${conversationId}/messages/search`,\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.hits).map(mapWireSearchHit);\n };\n\n getConversationActivity = async (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> => {\n const response = await this.request<WireConversationActivityResponse>({\n operation: \"getConversationActivity\",\n method: \"GET\",\n path: `/${conversationId}/activity`,\n query: { turnMessageId: turnMessageId ?? undefined },\n });\n return mapWireConversationActivity(response);\n };\n\n composeSentMessageText = (text: string, attachments: ConversationAttachmentReference[] | undefined): string =>\n composeAttachmentMessageText(text, attachments);\n\n // ── Writes ────────────────────────────────────────────────────────────────────────────────────────────────────\n\n startConversation = async (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> => {\n const buildStartPath = this.options.buildStartPath ?? defaultBuildStartPath;\n const response = await this.request<WireConversationStartResponse>({\n operation: \"startConversation\",\n method: \"POST\",\n path: buildStartPath(request.agentSpaceKey),\n query: { aiModelName: request.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(request.text, request.attachments) },\n ...(request.startSignalText ? { signalText: request.startSignalText } : {}),\n ...(request.entryPointKey ? { entryPointKey: request.entryPointKey } : {}),\n ...this.readClientContextBody(\"startConversation\"),\n },\n });\n const wireConversation = response.aiConversation ?? {};\n const reopenedExisting = response.reopenedExistingConversation === true;\n return {\n conversation: mapWireConversation(wireConversation),\n messages: reopenedExisting ? [] : readWireSetElements(wireConversation.messages).map(mapWireConversationMessage),\n reopenedExisting,\n };\n };\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"postMessage\",\n method: \"POST\",\n path: `/${conversationId}/postMessage`,\n query: { aiModelName: message.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) },\n ...this.readClientContextBody(\"postMessage\"),\n },\n });\n return { messages: readWireSetElements(response.aiConversation?.messages).map(mapWireConversationMessage) };\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"injectSignal\",\n method: \"POST\",\n path: `/${conversationId}/injectSignal`,\n body: {\n signalText: signal.text,\n ...(signal.source ? { signalSource: signal.source } : {}),\n ...this.readClientContextBody(\"injectSignal\"),\n },\n });\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"retryConversation\",\n method: \"POST\",\n path: `/${conversationId}/retry`,\n });\n };\n\n renameConversation = async (conversationId: number, title: string): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"renameConversation\",\n method: \"PATCH\",\n path: `/${conversationId}/title`,\n body: { title },\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n deleteConversation = async (conversationId: number): Promise<void> => {\n await this.request<unknown>({ operation: \"deleteConversation\", method: \"DELETE\", path: `/${conversationId}` });\n };\n\n // ── Transport ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n protected readSelectableModels = async (): Promise<SelectableModel[]> => {\n const response = await this.request<WireSelectableModelsResponse>({\n operation: \"getSelectableModels\",\n method: \"GET\",\n path: \"/selectable-models\",\n });\n return readWireSetElements(response.models).map(mapWireSelectableModel);\n };\n\n protected async readMessagesPage(\n operation: AgentsConversationOperation,\n conversationId: number,\n pageSize: number,\n filters: string | undefined,\n ): Promise<ConversationMessagesPage> {\n const response = await this.request<WireConversationMessagesResponse>({\n operation,\n method: \"GET\",\n path: `/${conversationId}/messages`,\n query: { filters, orderBy: \"indexInConversation desc\", top: pageSize, expand: MESSAGES_EXPAND },\n });\n return {\n messages: readWireSetElements(response.messages).map(mapWireConversationMessage),\n hasMoreOlder: response.hasMoreOlder === true,\n };\n }\n\n /** The body field `clientContext` of a write, from the host's option; nothing when it gives none. */\n protected readClientContextBody(operation: AgentsClientContextOperation): {\n clientContext?: ReturnType<typeof mapClientContextToWire>;\n clientId?: string;\n uiState?: AgentUIState;\n } {\n const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n return {\n ...(wireClientContext ? { clientContext: wireClientContext } : {}),\n ...(uiClient ? { clientId: uiClient.clientId } : {}),\n ...(uiState ? { uiState } : {}),\n };\n }\n\n /** The URL of a route: the base, the path, the binding's query parameters with the host's extra ones over them. */\n protected buildUrl(request: HttpRequest): string {\n const searchParameters = new URLSearchParams();\n const extraParameters = this.options.extraRequestParameters?.(request.operation) ?? {};\n for (const [name, value] of Object.entries({ ...request.query, ...extraParameters })) {\n if (value !== undefined && value !== null) searchParameters.set(name, String(value));\n }\n const query = searchParameters.toString();\n const baseUrl = this.options.baseUrl.replace(/\\/+$/, \"\");\n return `${baseUrl}${request.path}${query ? `?${query}` : \"\"}`;\n }\n\n protected async readFetchOptions(): Promise<AgentsHttpFetchOptions> {\n const { fetchOptions } = this.options;\n return typeof fetchOptions === \"function\" ? await fetchOptions() : (fetchOptions ?? {});\n }\n\n /** One request; every failure becomes an `AgentsClientError` (the port's one error shape). */\n protected async request<ResponseBody>(request: HttpRequest): Promise<ResponseBody> {\n const fetchFunction = this.options.fetch ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n const fetchOptions = await this.readFetchOptions();\n const headers = new Headers(fetchOptions.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (request.body !== undefined && !headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n response = await fetchFunction(this.buildUrl(request), {\n ...fetchOptions,\n headers,\n method: request.method,\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n });\n } catch (failure) {\n if (failure instanceof AgentsClientError) throw failure;\n const isAbort = failure instanceof Error && failure.name === \"AbortError\";\n throw isAbort\n ? new AgentsClientError(\"other\", { code: AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED, message: \"The request was cancelled.\" })\n : new AgentsClientError(\"network\", { message: failure instanceof Error ? failure.message : \"The request failed.\" });\n }\n const responseText = await response.text().catch(() => \"\");\n const responseBody = readJsonBody(responseText);\n if (!response.ok) {\n throw mapHttpFailureToAgentsClientError(\n response.status,\n isPlainObject(responseBody) ? (responseBody as WireErrorBody) : null,\n response.headers.get(\"Retry-After\"),\n );\n }\n return (responseBody ?? {}) as ResponseBody;\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readJsonBody = (text: string): unknown => {\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\n/**\n * The conversation client over the module's own conversation routes (`AgentConversationReadsTrait`,\n * `AgentConversationWritesTrait`, the application's start route of `AgentConversationStartTrait`, optionally\n * `AgentSelectableModelsTrait`): `baseUrl` is where the application mounted its conversations controller, `fetchOptions`\n * what every request carries. Every function rejects with `AgentsClientError`. The client comes with live updates —\n * the polling default over the run-state read, which also reads at once after an accepted send — unless `polling` is\n * `false`.\n *\n * ```ts\n * const client = createAgentsHttpConversationClient({\n * baseUrl: \"/api/agents/conversations\",\n * fetchOptions: () => ({ headers: { Authorization: `Bearer ${readToken()}` } }),\n * });\n * <AgentsProvider client={client}><AgentChat /></AgentsProvider>\n * ```\n */\nexport const createAgentsHttpConversationClient = (options: AgentsHttpConversationClientOptions): AgentsConversationClient => {\n const client = new AgentsHttpConversationClient(options);\n return options.polling === false ? client : withPollingChangeSubscription(client, options.polling);\n};\n"],"names":["options"],"mappings":";;;;;;;AAuCA,MAAM,aAA8C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,gBAAoD,CAAC,UAAU,QAAQ,WAAW;AACxF,MAAM,gBAAoD;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mBAAyD;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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AAC,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,eAAe,CAAC,SAA0B;AAC9C,MAAI,KAAK,WAAW,GAAI,QAAO;AAC/B,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAkBO,MAAM,qCAAqC,CAAC,YAA2E;AAC5H,QAAM,SAAS,IAAI,6BAA6B,OAAO;AACvD,SAAO,QAAQ,YAAY,QAAQ,SAAS,8BAA8B,QAAQ,QAAQ,OAAO;AACnG;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../src/client/http/agents-http-mappers.ts","../src/client/http/createAgentsHttpConversationClient.ts"],"sourcesContent":["import {\n AGENTS_CLIENT_CONTEXT_LIMITS,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsClientErrorKind,\n type AgentsConversation,\n type AgentsConversationMessage,\n type ConversationActivity,\n type ConversationActivityElement,\n type ConversationMessageAuthorType,\n type ConversationMessageRole,\n type ConversationMessageSearchHit,\n type ConversationMessageStatus,\n type ConversationMessageType,\n type ConversationProgressStep,\n type ConversationRunState,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSubAgent,\n type SelectableModel,\n} from \"../../contract/conversation\";\nimport type {\n WireActivityLine,\n WireClientContext,\n WireClientContextRouteParameter,\n WireConversation,\n WireConversationActivityResponse,\n WireConversationMessage,\n WireConversationRunStateResponse,\n WireConversationSearchGroup,\n WireCustomerProgressStep,\n WireDelegationSubAgentRecord,\n WireErrorBody,\n WireSelectableModel,\n WireSemanticSearchHit,\n WireSet,\n} from \"./agents-http-wire\";\n\n// The vocabularies of the contract: a wire value outside one maps to null.\nconst RUN_STATES: readonly ConversationRunState[] = [\n \"IDLE\",\n \"QUEUED\",\n \"RUNNING\",\n \"AWAITING_DELEGATES\",\n \"FAILED\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nconst MESSAGE_ROLES: readonly ConversationMessageRole[] = [\"SYSTEM\", \"USER\", \"ASSISTANT\"];\nconst MESSAGE_TYPES: readonly ConversationMessageType[] = [\n \"TEXT\",\n \"TOOL_CALL\",\n \"CHECKPOINT\",\n \"ERROR\",\n \"SIGNAL\",\n \"TOOL_MESSAGE\",\n];\nconst MESSAGE_STATUSES: readonly ConversationMessageStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"COMPLETED\",\n \"FAILED\",\n];\nconst AUTHOR_TYPES: readonly ConversationMessageAuthorType[] = [\"USER\", \"ASSISTANT\", \"AGENT\", \"TOOL\"];\nconst PROGRESS_STEP_STATUSES: readonly ConversationProgressStep[\"status\"][] = [\"done\", \"active\", \"upcoming\"];\nconst ACTIVITY_STATES: readonly NonNullable<ConversationActivityElement[\"state\"]>[] = [\n \"queued\",\n \"running\",\n \"finished\",\n \"failed\",\n \"skipped\",\n];\nconst ACTIVITY_KINDS: readonly NonNullable<ConversationActivityElement[\"kind\"]>[] = [\n \"tool\",\n \"delegation\",\n \"background\",\n \"long\",\n \"turnStart\",\n];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a serialized set (`{ elements: [...] }`), a plain array, or the values of a keyed object. */\nexport const readWireSetElements = <Element>(\n wireSet: WireSet<Element> | Record<string, Element> | null | undefined,\n): Element[] => {\n if (!wireSet) return [];\n if (Array.isArray(wireSet)) return wireSet;\n if (typeof wireSet === \"object\" && \"elements\" in wireSet) {\n const elements = (wireSet as { elements?: Element[] | null }).elements;\n return Array.isArray(elements) ? elements : [];\n }\n return Object.values(wireSet as Record<string, Element>);\n};\n\nconst mapWireProgressStep = (wireStep: WireCustomerProgressStep): ConversationProgressStep => ({\n key: wireStep.key ?? \"\",\n label: wireStep.customerLabel ?? \"\",\n status: readVocabularyValue(PROGRESS_STEP_STATUSES, wireStep.status) ?? \"upcoming\",\n});\n\n/** An `AIConversation` as the contract's conversation. */\nexport const mapWireConversation = (wireConversation: WireConversation): AgentsConversation => {\n const conversation: AgentsConversation = {\n id: wireConversation.id ?? 0,\n agentSpaceKey: readNumberOrNull(wireConversation.agentSpaceId),\n runState: readVocabularyValue(RUN_STATES, wireConversation.runState),\n agentTurnOwedAt: readStringOrNull(wireConversation.agentTurnOwedAt),\n title: readStringOrNull(wireConversation.summary?.title),\n titleManuallyEdited: wireConversation.summary?.manuallyEdited === true,\n summary: readStringOrNull(wireConversation.summary?.text),\n created: readStringOrNull(wireConversation.created ?? wireConversation.changeHistory?.createdTime),\n updated: readStringOrNull(wireConversation.updated ?? wireConversation.changeHistory?.modifiedTime),\n purposeName: readStringOrNull(wireConversation.purposeName),\n initiatorType: readStringOrNull(wireConversation.initiatorType),\n scheduleId: readNumberOrNull(wireConversation.scheduleId),\n entryPointKey: readStringOrNull(wireConversation.entryPointKey),\n progressSteps: readWireSetElements(wireConversation.customerProgressSteps).map(mapWireProgressStep),\n };\n if (wireConversation.lastMessageId !== undefined) conversation.lastMessageId = readNumberOrNull(wireConversation.lastMessageId);\n if (wireConversation.aiPromptExtensionId !== undefined) {\n conversation.promptExtensionId = readNumberOrNull(wireConversation.aiPromptExtensionId);\n }\n return conversation;\n};\n\nconst mapWireSubAgent = (wireSubAgent: WireDelegationSubAgentRecord | null | undefined): ConversationSubAgent | null =>\n wireSubAgent\n ? {\n currentRunNumber: readNumberOrNull(wireSubAgent.currentRunNumber),\n runs: readWireSetElements(wireSubAgent.runs).map((wireRun) => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n })),\n }\n : null;\n\n/** An `AIConversationMessage` as the contract's message. */\nexport const mapWireConversationMessage = (wireMessage: WireConversationMessage): AgentsConversationMessage => {\n const message: AgentsConversationMessage = {\n id: wireMessage.id ?? 0,\n conversationId: readNumberOrNull(wireMessage.aiConversationId),\n indexInConversation: readNumberOrNull(wireMessage.indexInConversation),\n role: readVocabularyValue(MESSAGE_ROLES, wireMessage.role),\n messageType: readVocabularyValue(MESSAGE_TYPES, wireMessage.messageType),\n status: readVocabularyValue(MESSAGE_STATUSES, wireMessage.status),\n authorType: readVocabularyValue(AUTHOR_TYPES, wireMessage.authorType),\n signalSource: readStringOrNull(wireMessage.signalSource),\n message: wireMessage.message ?? \"\",\n createdDate: readStringOrNull(wireMessage.createdDate),\n toolCall: wireMessage.toolCall\n ? {\n toolCallId: readStringOrNull(wireMessage.toolCall.toolCallId),\n name: readStringOrNull(wireMessage.toolCall.name),\n arguments: wireMessage.toolCall.arguments ?? null,\n status: readStringOrNull(wireMessage.toolCall.status),\n }\n : null,\n delegatedConversations: readWireSetElements(wireMessage.delegatedConversations).map((delegated) => ({\n id: delegated.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, delegated.runState),\n })),\n subAgent: mapWireSubAgent(wireMessage.delegationResults?.subAgent),\n };\n const hasForensics =\n wireMessage.inputTokens != null || wireMessage.outputTokens != null || wireMessage.requestSnapshot != null;\n if (hasForensics) {\n message.forensics = {\n inputTokens: readNumberOrNull(wireMessage.inputTokens),\n outputTokens: readNumberOrNull(wireMessage.outputTokens),\n costInUSD: readNumberOrNull(wireMessage.costInUSD),\n requestSnapshot: wireMessage.requestSnapshot ?? null,\n };\n }\n return message;\n};\n\n/** The run-state read (`AIConversationRunStateGetResponseDto`). */\nexport const mapWireConversationRunState = (wireRunState: WireConversationRunStateResponse): ConversationRunStateRead => ({\n id: wireRunState.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, wireRunState.runState),\n agentTurnOwedAt: readStringOrNull(wireRunState.agentTurnOwedAt),\n lastMessageId: readNumberOrNull(wireRunState.lastMessageId),\n title: readStringOrNull(wireRunState.title),\n titleManuallyEdited: wireRunState.titleManuallyEdited === true,\n summary: readStringOrNull(wireRunState.summary),\n updated: readStringOrNull(wireRunState.updated),\n});\n\nconst mapWireActivityLine = (wireLine: WireActivityLine): ConversationActivityElement => ({\n toolCallMessageId: wireLine.toolCallMessageId ?? 0,\n batchId: readStringOrNull(wireLine.batchId),\n state: readVocabularyValue(ACTIVITY_STATES, wireLine.state),\n kind: readVocabularyValue(ACTIVITY_KINDS, wireLine.kind),\n childCount: readNumberOrNull(wireLine.childCount),\n helperIndex: readNumberOrNull(wireLine.helperIndex),\n line: readStringOrNull(wireLine.line),\n});\n\n/** The activity of a turn (`AIConversationActivityGetResponseDto`). */\nexport const mapWireConversationActivity = (wireActivity: WireConversationActivityResponse): ConversationActivity => ({\n turnMessageId: readNumberOrNull(wireActivity.turnMessageId),\n turnRunning: wireActivity.turnRunning === true,\n elements: readWireSetElements(wireActivity.elements).map(mapWireActivityLine),\n});\n\n/** A `SemanticSearchHit`. */\nexport const mapWireSearchHit = (wireHit: WireSemanticSearchHit): ConversationMessageSearchHit => ({\n messageId: readNumberOrNull(wireHit.messageId),\n conversationId: readNumberOrNull(wireHit.conversationId),\n indexInConversation: readNumberOrNull(wireHit.indexInConversation),\n role: readStringOrNull(wireHit.role),\n excerpt: wireHit.excerpt ?? \"\",\n relevance: readNumberOrNull(wireHit.relevance) ?? 0,\n created: readStringOrNull(wireHit.created),\n updated: readStringOrNull(wireHit.updated),\n title: readStringOrNull(wireHit.title),\n});\n\n/** An `AIConversationSearchGroup`. */\nexport const mapWireSearchGroup = (wireGroup: WireConversationSearchGroup): ConversationSearchGroup => ({\n conversationId: readNumberOrNull(wireGroup.conversationId),\n title: readStringOrNull(wireGroup.title),\n summary: readStringOrNull(wireGroup.summary),\n created: readStringOrNull(wireGroup.created),\n updated: readStringOrNull(wireGroup.updated),\n relevance: readNumberOrNull(wireGroup.relevance) ?? 0,\n hits: readWireSetElements(wireGroup.hits).map(mapWireSearchHit),\n});\n\n/** An `AgentCustomerSelectableModel`. */\nexport const mapWireSelectableModel = (wireModel: WireSelectableModel): SelectableModel => ({\n name: wireModel.name ?? \"\",\n displayName: wireModel.displayName ?? wireModel.name ?? \"\",\n description: wireModel.description ?? \"\",\n strengthLevel: readNumberOrNull(wireModel.strengthLevel),\n speedLevel: readNumberOrNull(wireModel.speedLevel),\n creditsMultiplier: readNumberOrNull(wireModel.creditsMultiplier),\n});\n\n/** The stable codes of the server's refusals the chat tells apart. */\nconst ERROR_KIND_BY_CODE: Readonly<Record<string, AgentsClientErrorKind>> = {\n AI_BUDGET_REACHED: \"budget\",\n RATE_LIMIT_EXCEEDED: \"rateLimit\",\n CONVERSATION_CLOSED: \"closed\",\n};\n\n/**\n * A refused request as the port's error: the stable code first (`errorCode` of the JSON body), then the status — 429\n * `rateLimit` (with `Retry-After`), 404 `notFound`, 403 and 401 `forbidden`, 5xx `network`, everything else `other`.\n */\nexport const mapHttpFailureToAgentsClientError = (\n httpStatus: number,\n wireErrorBody: WireErrorBody | null,\n retryAfterHeader: string | null,\n): AgentsClientError => {\n const code = wireErrorBody?.errorCode ?? wireErrorBody?.code ?? null;\n const message = wireErrorBody?.error ?? wireErrorBody?.message ?? undefined;\n const retryAfterOfHeader = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader) : null;\n const retryAfterSeconds = readNumberOrNull(wireErrorBody?.retryAfterSeconds) ?? retryAfterOfHeader;\n const kindOfCode = code !== null ? ERROR_KIND_BY_CODE[code] : undefined;\n const kind: AgentsClientErrorKind =\n kindOfCode ??\n (httpStatus === 429\n ? \"rateLimit\"\n : httpStatus === 404\n ? \"notFound\"\n : httpStatus === 403 || httpStatus === 401\n ? \"forbidden\"\n : httpStatus >= 500\n ? \"network\"\n : \"other\");\n return new AgentsClientError(kind, { message: message ?? undefined, code, retryAfterSeconds, httpStatus });\n};\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f]/;\n\n/** A text field of the client context as it goes out: trimmed, or left out when empty, over its cap or not one line. */\nconst readClientContextText = (value: string | number | null | undefined, maxChars: number): string | undefined => {\n if (value === null || value === undefined) return undefined;\n const text = String(value).trim();\n if (text === \"\" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return undefined;\n return text;\n};\n\n/**\n * The client context as the body field `clientContext` carries it (`AgentClientContext`): the route parameters as a\n * list of `{name, value}`. A field over its cap ({@link AGENTS_CLIENT_CONTEXT_LIMITS}) or with a control character is\n * left out — never cut — so a send never fails on the context; the route parameters go together or not at all.\n * Undefined when nothing is left.\n */\nexport const mapClientContextToWire = (clientContext: AgentsClientContext | null | undefined): WireClientContext | undefined => {\n if (!clientContext) return undefined;\n const wireClientContext: WireClientContext = {};\n const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);\n if (routePath !== undefined) wireClientContext.routePath = routePath;\n const routeParameters: WireClientContextRouteParameter[] = Object.entries(clientContext.routeParameters ?? {})\n .filter(([name, value]) => name.trim() !== \"\" && value !== null && value !== undefined)\n .map(([name, value]) => ({ name, value: String(value) }));\n const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join(\"&\");\n if (\n routeParameters.length > 0 &&\n routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount &&\n routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars &&\n !CONTROL_CHARACTERS.test(routeParametersText)\n ) {\n wireClientContext.routeParameters = routeParameters;\n }\n const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);\n if (recordKind !== undefined) wireClientContext.recordKind = recordKind;\n const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);\n if (recordId !== undefined) wireClientContext.recordId = recordId;\n const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);\n if (tab !== undefined) wireClientContext.tab = tab;\n return Object.keys(wireClientContext).length > 0 ? wireClientContext : undefined;\n};\n","import type {\n AgentsConversationClient,\n AgentsConversationClientBindingOptions,\n AgentsConversationOperation,\n} from \"../AgentsConversationClient\";\nimport {\n AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsConversation,\n type ChangedConversationMessages,\n type ChangedMessagesRequest,\n type ConversationActivity,\n type ConversationAttachmentReference,\n type ConversationListQueryOptions,\n type ConversationMessageSearchHit,\n type ConversationMessagesPage,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSearchOptions,\n type ConversationSignal,\n type PostedMessage,\n type SelectableModel,\n type StartedConversation,\n} from \"../../contract/conversation\";\nimport { type AgentUIState, createAgentUIClientId } from \"../../ui/agent-ui-state\";\nimport type { AgentUIClientBinding } from \"../../ui/AgentUIClient\";\nimport type { ClientToolAnswer } from \"../../ui/client-tools\";\nimport {\n acceptArrivedRealtimeMessage,\n type AgentRealtimeListenerCredential,\n type AgentRealtimeMessageDelivery,\n} from \"../../ui/realtime-arrival\";\nimport { composeAttachmentMessageText } from \"../compose-attachment-message-text\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../polling/withPollingChangeSubscription\";\nimport {\n mapClientContextToWire,\n mapHttpFailureToAgentsClientError,\n mapWireConversation,\n mapWireConversationActivity,\n mapWireConversationMessage,\n mapWireConversationRunState,\n mapWireSearchGroup,\n mapWireSearchHit,\n mapWireSelectableModel,\n readWireSetElements,\n} from \"./agents-http-mappers\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n WireAccountRealtimeMessagesResponse,\n WireConversationActivityResponse,\n WireConversationMessageSearchResponse,\n WireConversationMessagesResponse,\n WireConversationResponse,\n WireConversationRunStateResponse,\n WireConversationSearchResponse,\n WireConversationsResponse,\n WireConversationStartResponse,\n WireErrorBody,\n WireSelectableModelsResponse,\n} from \"./agents-http-wire\";\n\n/** What every request of the binding carries from the host: headers, credentials, mode, cache. */\nexport type AgentsHttpFetchOptions = Omit<RequestInit, \"method\" | \"body\">;\n\nexport interface AgentsHttpConversationClientOptions extends AgentsConversationClientBindingOptions {\n /**\n * Where the application's conversations controller is mounted (its `#[Route]`): a path such as\n * `/api/agents/conversations` or an absolute URL. The module's routes are relative to it.\n */\n baseUrl: string;\n /**\n * Request options every request carries (credentials, an authorization header). A function is called per request,\n * so it may hand out a fresh token. Default: none (the browser's defaults: same-origin credentials).\n */\n fetchOptions?: AgentsHttpFetchOptions | (() => AgentsHttpFetchOptions | Promise<AgentsHttpFetchOptions>);\n /** The fetch function. Default: the global `fetch`. */\n fetch?: typeof fetch;\n /**\n * The application's start route below `baseUrl` (`AgentConversationStartTrait` declares none). Default: `/start` for\n * a start without an agent space (key 0), `/start/{agentSpaceKey}` otherwise — the start DTO reads `agentSpaceId`\n * from the path.\n */\n buildStartPath?: (agentSpaceKey: number) => string;\n /**\n * The controller uses `AgentSelectableModelsTrait` (`GET …/selectable-models`): the client offers\n * `getSelectableModels` and the chat shows the model picker. Default false.\n */\n hasSelectableModelsRoute?: boolean;\n /**\n * The live updates: the polling default over the run-state read (`withPollingChangeSubscription`), which also reads\n * at once after a post, a signal or a retry the server accepted. The intervals of\n * `PollingConversationChangeSubscriptionOptions`; `false` = no subscription (the host adds its own push transport).\n * Default: polling with the default intervals.\n */\n polling?: PollingConversationChangeSubscriptionOptions | false;\n /**\n * What the owner's client shows, read on every start, posted message and injected signal and sent as the body field\n * `clientContext` (the route, its parameters, the record on screen, the tab). The agent reads the newest one as one\n * line beside the owner's newest message. A field over its cap is left out, never cut. Default: none.\n */\n clientContext?: (operation: AgentsClientContextOperation) => AgentsClientContext | null | undefined;\n /**\n * The UI side of `Agent.UI` (`AgentUIClient` of `@mgamadeus/ddd-agents/ui`): its client id and UI state ride on every\n * write and every run-state read; a client tool request the run-state read delivers goes to it, and the binding\n * posts its answer (`POST /{conversationId}/clientToolRequests/{requestId}/answer`). Default: none; the account\n * read alone then states a client id the binding creates once (`getAccountRealtimeMessages`).\n */\n uiClient?: AgentUIClientBinding;\n /**\n * The open messages of the realtime port of other types than a client tool request (types other packages\n * registered), as the run-state read delivers them; a client acts on one type and key once. Default: none.\n */\n onRealtimeMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void;\n /** What the client needs to listen on the host's transport, with every run-state read (null without one). Default: none. */\n onRealtimeListenerCredential?: (conversationId: number, credential: AgentRealtimeListenerCredential | null) => void;\n}\n\n/** The writes that carry the client context. */\nexport type AgentsClientContextOperation = \"startConversation\" | \"postMessage\" | \"injectSignal\";\n\n/** The page size of a changed-messages read when the request names none (as the chat sends it). */\nexport const AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE = 50;\n\n/** The expand of every message page: the delegated children with the two fields the chat reads. */\nconst MESSAGES_EXPAND = \"delegatedConversations(select=id,runState)\";\n\nconst defaultBuildStartPath = (agentSpaceKey: number): string => (agentSpaceKey > 0 ? `/start/${agentSpaceKey}` : \"/start\");\n\ntype QueryParameters = Record<string, string | number | boolean | undefined | null>;\n\ninterface HttpRequest {\n operation: AgentsConversationOperation;\n method: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: QueryParameters;\n body?: unknown;\n}\n\n/** A filter value as the query-options grammar writes it: quoted. */\nconst quoteFilterValue = (value: number | string): string => `'${String(value).replace(/'/g, \"\\\\'\")}'`;\n\n/** The module's conversation routes over fetch: one request per port function, the wire mapped onto the contract. */\nclass AgentsHttpConversationClient implements AgentsConversationClient {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n\n /** The client id this client created for its account read (no `uiClient` bound): once, kept while it lives. */\n protected ownAccountReadClientId: string | undefined;\n\n constructor(protected readonly options: AgentsHttpConversationClientOptions) {\n if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;\n }\n\n // ── Reads ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n getConversationMetadata = async (conversationId: number): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"getConversationMetadata\",\n method: \"GET\",\n path: `/${conversationId}`,\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n getConversationRunState = async (conversationId: number): Promise<ConversationRunStateRead> => {\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n const response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n query: uiClient ? { clientId: uiClient.clientId, uiStateJson: uiState ? JSON.stringify(uiState) : undefined } : undefined,\n });\n const sendAnswer = (requestId: number, answer: ClientToolAnswer): Promise<void> =>\n this.answerClientToolRequest(conversationId, requestId, answer);\n if (uiClient && response.clientToolRequest) {\n uiClient.acceptClientToolRequest(conversationId, response.clientToolRequest, sendAnswer);\n }\n for (const message of readWireSetElements(response.realtimeMessages)) {\n if (uiClient) acceptArrivedRealtimeMessage(conversationId, message, uiClient, sendAnswer, this.options.onRealtimeMessage);\n else this.options.onRealtimeMessage?.(conversationId, message);\n }\n this.options.onRealtimeListenerCredential?.(conversationId, response.realtimeListenerCredential ?? null);\n return mapWireConversationRunState(response);\n };\n\n /**\n * The account-level realtime read (`GET /realtimeMessages?clientId=…`): the messages addressed to the signed-in\n * account for this client and the listener credential without a conversation. It always states a client id\n * (`resolveAccountReadClientId`), so the server knows a client that only polls. Arrival is the caller's\n * (`createAccountRealtimePoll` of `/ui`).\n *\n * @param clientId the client id the caller wants stated (the `clientId` option of the poll)\n */\n getAccountRealtimeMessages = async (clientId?: string): Promise<AccountRealtimeRead> => {\n const response = await this.request<WireAccountRealtimeMessagesResponse>({\n operation: \"getAccountRealtimeMessages\",\n method: \"GET\",\n path: \"/realtimeMessages\",\n query: { clientId: this.resolveAccountReadClientId(clientId) },\n });\n return {\n messages: readWireSetElements(response.realtimeMessages),\n listenerCredential: response.realtimeListenerCredential ?? null,\n };\n };\n\n /**\n * The client id the account read states, decided here and nowhere else: the caller's, else the bound `uiClient`'s,\n * else one this client creates once and keeps while it lives. Only the account read asks: every other request\n * states a client id only with a `uiClient`.\n */\n protected resolveAccountReadClientId(clientId: string | undefined): string {\n if (clientId) return clientId;\n if (this.options.uiClient) return this.options.uiClient.clientId;\n this.ownAccountReadClientId ??= createAgentUIClientId();\n return this.ownAccountReadClientId;\n }\n\n /** Posts the answer of the UI client to a client tool request (`Agent.UI`); a refused answer is the server's word. */\n answerClientToolRequest = async (conversationId: number, requestId: number, answer: ClientToolAnswer): Promise<void> => {\n await this.request<unknown>({\n operation: \"answerClientToolRequest\",\n method: \"POST\",\n path: `/${conversationId}/clientToolRequests/${requestId}/answer`,\n body: {\n clientId: this.options.uiClient?.clientId ?? \"\",\n outcome: answer.outcome,\n text: answer.text,\n detailsJson: JSON.stringify(answer.details ?? {}),\n pictureBase64: answer.pictureBase64,\n uiStateJson: this.readUIStateJsonAfterAnswer(),\n },\n });\n };\n\n /** What the UI shows after the request was carried out, so the server's `[SIGNAL:ui]` note is current at once. */\n protected readUIStateJsonAfterAnswer(): string | undefined {\n const uiState: AgentUIState | null = this.options.uiClient?.readUIState() ?? null;\n return uiState ? JSON.stringify(uiState) : undefined;\n }\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\"getNewestMessagesPage\", conversationId, pageSize, undefined);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\n \"getOlderMessagesPage\",\n conversationId,\n pageSize,\n `indexInConversation lt ${quoteFilterValue(beforeIndex)}`,\n );\n\n getChangedMessages = async (\n conversationId: number,\n request: ChangedMessagesRequest,\n ): Promise<ChangedConversationMessages> => {\n const page = await this.readMessagesPage(\n \"getChangedMessages\",\n conversationId,\n request.pageSize ?? AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE,\n `(id gt ${quoteFilterValue(request.highestKnownId)} or indexInConversation ge ${quoteFilterValue(request.fromIndex)})`,\n );\n return { messages: page.messages };\n };\n\n listConversations = async (agentSpaceKey: number, options: ConversationListQueryOptions = {}): Promise<AgentsConversation[]> => {\n const filters = [\"rootConversationId eq null\"];\n if (agentSpaceKey > 0) filters.push(`agentSpaceId eq ${quoteFilterValue(agentSpaceKey)}`);\n const response = await this.request<WireConversationsResponse>({\n operation: \"listConversations\",\n method: \"GET\",\n path: \"/listAllConversations\",\n query: {\n filters: filters.join(\" and \"),\n orderBy: \"id desc\",\n top: options.paging?.top,\n skip: options.paging?.skip,\n },\n });\n const conversations = readWireSetElements(response.aiConversations).map(mapWireConversation);\n // Without a summary there is no title yet; the list leaves such a conversation out unless asked for it.\n return options.includeUnsummarized ? conversations : conversations.filter((conversation) => conversation.title !== null);\n };\n\n searchConversations = async (text: string, options: ConversationSearchOptions = {}): Promise<ConversationSearchGroup[]> => {\n const response = await this.request<WireConversationSearchResponse>({\n operation: \"searchConversations\",\n method: \"GET\",\n path: \"/search\",\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.conversations).map(mapWireSearchGroup);\n };\n\n searchConversationMessages = async (\n conversationId: number,\n text: string,\n options: ConversationSearchOptions = {},\n ): Promise<ConversationMessageSearchHit[]> => {\n const response = await this.request<WireConversationMessageSearchResponse>({\n operation: \"searchConversationMessages\",\n method: \"GET\",\n path: `/${conversationId}/messages/search`,\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.hits).map(mapWireSearchHit);\n };\n\n getConversationActivity = async (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> => {\n const response = await this.request<WireConversationActivityResponse>({\n operation: \"getConversationActivity\",\n method: \"GET\",\n path: `/${conversationId}/activity`,\n query: { turnMessageId: turnMessageId ?? undefined },\n });\n return mapWireConversationActivity(response);\n };\n\n composeSentMessageText = (text: string, attachments: ConversationAttachmentReference[] | undefined): string =>\n composeAttachmentMessageText(text, attachments);\n\n // ── Writes ────────────────────────────────────────────────────────────────────────────────────────────────────\n\n startConversation = async (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> => {\n const buildStartPath = this.options.buildStartPath ?? defaultBuildStartPath;\n const response = await this.request<WireConversationStartResponse>({\n operation: \"startConversation\",\n method: \"POST\",\n path: buildStartPath(request.agentSpaceKey),\n query: { aiModelName: request.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(request.text, request.attachments) },\n ...(request.startSignalText ? { signalText: request.startSignalText } : {}),\n ...(request.entryPointKey ? { entryPointKey: request.entryPointKey } : {}),\n ...this.readClientContextBody(\"startConversation\"),\n },\n });\n const wireConversation = response.aiConversation ?? {};\n const reopenedExisting = response.reopenedExistingConversation === true;\n return {\n conversation: mapWireConversation(wireConversation),\n messages: reopenedExisting ? [] : readWireSetElements(wireConversation.messages).map(mapWireConversationMessage),\n reopenedExisting,\n };\n };\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"postMessage\",\n method: \"POST\",\n path: `/${conversationId}/postMessage`,\n query: { aiModelName: message.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) },\n ...this.readClientContextBody(\"postMessage\"),\n },\n });\n return { messages: readWireSetElements(response.aiConversation?.messages).map(mapWireConversationMessage) };\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"injectSignal\",\n method: \"POST\",\n path: `/${conversationId}/injectSignal`,\n body: {\n signalText: signal.text,\n ...(signal.source ? { signalSource: signal.source } : {}),\n ...this.readClientContextBody(\"injectSignal\"),\n },\n });\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"retryConversation\",\n method: \"POST\",\n path: `/${conversationId}/retry`,\n });\n };\n\n renameConversation = async (conversationId: number, title: string): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"renameConversation\",\n method: \"PATCH\",\n path: `/${conversationId}/title`,\n body: { title },\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n deleteConversation = async (conversationId: number): Promise<void> => {\n await this.request<unknown>({ operation: \"deleteConversation\", method: \"DELETE\", path: `/${conversationId}` });\n };\n\n // ── Transport ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n protected readSelectableModels = async (): Promise<SelectableModel[]> => {\n const response = await this.request<WireSelectableModelsResponse>({\n operation: \"getSelectableModels\",\n method: \"GET\",\n path: \"/selectable-models\",\n });\n return readWireSetElements(response.models).map(mapWireSelectableModel);\n };\n\n protected async readMessagesPage(\n operation: AgentsConversationOperation,\n conversationId: number,\n pageSize: number,\n filters: string | undefined,\n ): Promise<ConversationMessagesPage> {\n const response = await this.request<WireConversationMessagesResponse>({\n operation,\n method: \"GET\",\n path: `/${conversationId}/messages`,\n query: { filters, orderBy: \"indexInConversation desc\", top: pageSize, expand: MESSAGES_EXPAND },\n });\n return {\n messages: readWireSetElements(response.messages).map(mapWireConversationMessage),\n hasMoreOlder: response.hasMoreOlder === true,\n };\n }\n\n /** The body field `clientContext` of a write, from the host's option; nothing when it gives none. */\n protected readClientContextBody(operation: AgentsClientContextOperation): {\n clientContext?: ReturnType<typeof mapClientContextToWire>;\n clientId?: string;\n uiState?: AgentUIState;\n } {\n const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n return {\n ...(wireClientContext ? { clientContext: wireClientContext } : {}),\n ...(uiClient ? { clientId: uiClient.clientId } : {}),\n ...(uiState ? { uiState } : {}),\n };\n }\n\n /** The URL of a route: the base, the path, the binding's query parameters with the host's extra ones over them. */\n protected buildUrl(request: HttpRequest): string {\n const searchParameters = new URLSearchParams();\n const extraParameters = this.options.extraRequestParameters?.(request.operation) ?? {};\n for (const [name, value] of Object.entries({ ...request.query, ...extraParameters })) {\n if (value !== undefined && value !== null) searchParameters.set(name, String(value));\n }\n const query = searchParameters.toString();\n const baseUrl = this.options.baseUrl.replace(/\\/+$/, \"\");\n return `${baseUrl}${request.path}${query ? `?${query}` : \"\"}`;\n }\n\n protected async readFetchOptions(): Promise<AgentsHttpFetchOptions> {\n const { fetchOptions } = this.options;\n return typeof fetchOptions === \"function\" ? await fetchOptions() : (fetchOptions ?? {});\n }\n\n /** One request; every failure becomes an `AgentsClientError` (the port's one error shape). */\n protected async request<ResponseBody>(request: HttpRequest): Promise<ResponseBody> {\n const fetchFunction = this.options.fetch ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n const fetchOptions = await this.readFetchOptions();\n const headers = new Headers(fetchOptions.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (request.body !== undefined && !headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n response = await fetchFunction(this.buildUrl(request), {\n ...fetchOptions,\n headers,\n method: request.method,\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n });\n } catch (failure) {\n if (failure instanceof AgentsClientError) throw failure;\n const isAbort = failure instanceof Error && failure.name === \"AbortError\";\n throw isAbort\n ? new AgentsClientError(\"other\", { code: AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED, message: \"The request was cancelled.\" })\n : new AgentsClientError(\"network\", { message: failure instanceof Error ? failure.message : \"The request failed.\" });\n }\n const responseText = await response.text().catch(() => \"\");\n const responseBody = readJsonBody(responseText);\n if (!response.ok) {\n throw mapHttpFailureToAgentsClientError(\n response.status,\n isPlainObject(responseBody) ? (responseBody as WireErrorBody) : null,\n response.headers.get(\"Retry-After\"),\n );\n }\n return (responseBody ?? {}) as ResponseBody;\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readJsonBody = (text: string): unknown => {\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\n/**\n * The conversation client over the module's own conversation routes (`AgentConversationReadsTrait`,\n * `AgentConversationWritesTrait`, the application's start route of `AgentConversationStartTrait`, optionally\n * `AgentSelectableModelsTrait`): `baseUrl` is where the application mounted its conversations controller, `fetchOptions`\n * what every request carries. Every function rejects with `AgentsClientError`. The client comes with live updates —\n * the polling default over the run-state read, which also reads at once after an accepted send — unless `polling` is\n * `false`.\n *\n * ```ts\n * const client = createAgentsHttpConversationClient({\n * baseUrl: \"/api/agents/conversations\",\n * fetchOptions: () => ({ headers: { Authorization: `Bearer ${readToken()}` } }),\n * });\n * <AgentsProvider client={client}><AgentChat /></AgentsProvider>\n * ```\n */\nexport const createAgentsHttpConversationClient = (options: AgentsHttpConversationClientOptions): AgentsConversationClient => {\n const client = new AgentsHttpConversationClient(options);\n return options.polling === false ? client : withPollingChangeSubscription(client, options.polling);\n};\n"],"names":["options"],"mappings":";;;;;;;AAuCA,MAAM,aAA8C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,gBAAoD,CAAC,UAAU,QAAQ,WAAW;AACxF,MAAM,gBAAoD;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mBAAyD;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,eAAyD,CAAC,QAAQ,aAAa,SAAS,MAAM;AACpG,MAAM,yBAAwE,CAAC,QAAQ,UAAU,UAAU;AAC3G,MAAM,kBAAgF;AAAA,EACpF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,iBAA8E;AAAA,EAClF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,sBAAsB,CAAuB,YAA8B,UAC/E,OAAO,UAAU,YAA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