@mgamadeus/ddd-agents 0.1.2 → 0.1.4
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 +33 -2
- package/dist/chat.js +289 -168
- package/dist/chat.js.map +1 -1
- package/dist/chunks/{ConversationMessageInputComposerWidgets-r_RwCqr7.js → ConversationMessageInputComposerWidgets-BbpB0fZl.js} +2 -2
- package/dist/chunks/{ConversationMessageInputComposerWidgets-r_RwCqr7.js.map → ConversationMessageInputComposerWidgets-BbpB0fZl.js.map} +1 -1
- package/dist/chunks/WebSearchResultsConversationWidget-BXt98hGu.js.map +1 -1
- package/dist/chunks/{canvasBodies-Ds-cTn47.js → canvasBodies-C_pdv17v.js} +2 -2
- package/dist/chunks/{canvasBodies-Ds-cTn47.js.map → canvasBodies-C_pdv17v.js.map} +1 -1
- package/dist/chunks/{contract-Z08LBOqt.js → contract-kmmw_19Y.js} +2 -2
- package/dist/chunks/{contract-Z08LBOqt.js.map → contract-kmmw_19Y.js.map} +1 -1
- package/dist/chunks/{conversation-BEF0aesf.js → conversation-CbWEHPbL.js} +12 -3
- package/dist/chunks/{conversation-BEF0aesf.js.map → conversation-CbWEHPbL.js.map} +1 -1
- package/dist/chunks/link-navigation-DyTApNeA.js.map +1 -1
- package/dist/chunks/{widget-click-signal-sources-Ch-y8gxw.js → widget-click-signal-sources-cjIjjftL.js} +2 -2
- package/dist/chunks/{widget-click-signal-sources-Ch-y8gxw.js.map → widget-click-signal-sources-cjIjjftL.js.map} +1 -1
- package/dist/chunks/{widget-name-resolver-DboFMAq2.js → widget-name-resolver-7WnzCpdG.js} +54 -17
- package/dist/chunks/widget-name-resolver-7WnzCpdG.js.map +1 -0
- package/dist/chunks/{withPollingChangeSubscription-CNXgt3Ri.js → withPollingChangeSubscription-CWavoKjJ.js} +2 -2
- package/dist/chunks/{withPollingChangeSubscription-CNXgt3Ri.js.map → withPollingChangeSubscription-CWavoKjJ.js.map} +1 -1
- package/dist/client-testing.js +3 -3
- package/dist/client.js +45 -6
- package/dist/client.js.map +1 -1
- package/dist/contract.js +6 -5
- package/dist/files/i18n-keys.json +19 -0
- package/dist/image-render.js +2 -2
- package/dist/index.js +2 -2
- package/dist/kit.js +1 -1
- package/dist/preview.js +3 -3
- package/dist/renderer.js +4 -4
- package/dist/styles.css +157 -17
- package/dist/types/chat/AgentChatActivityDots/AgentChatActivityDots.d.ts +11 -0
- package/dist/types/chat/AgentChatActivityIndicator/AgentChatActivityIndicator.d.ts +7 -2
- package/dist/types/chat/AgentChatActivityStack/AgentChatActivityStack.d.ts +15 -0
- package/dist/types/chat/controller/AgentChatController.d.ts +10 -0
- package/dist/types/chat/controller/activity-ticker.d.ts +5 -2
- package/dist/types/chat/controller/chat-activity-timing.d.ts +30 -0
- package/dist/types/chat/controller/use-activity-ticker.d.ts +6 -0
- package/dist/types/chat/controller/use-conversation-activity.d.ts +6 -2
- package/dist/types/client/http/agents-http-mappers.d.ts +9 -2
- package/dist/types/client/http/agents-http-wire.d.ts +13 -0
- package/dist/types/client/http/createAgentsHttpConversationClient.d.ts +9 -0
- package/dist/types/contract/conversation.d.ts +27 -0
- package/dist/types/entries/chat.d.ts +4 -1
- package/dist/types/provider/environment.d.ts +7 -0
- package/dist/types/renderer/ConversationWidgetCallbacksContext.d.ts +5 -1
- package/package.json +1 -1
- package/public-api.json +16 -0
- package/dist/chunks/widget-name-resolver-DboFMAq2.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { r as readConversationRunStatusOfRunState, C as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION, i as isAgentsClientError } from "./conversation-
|
|
2
|
+
import { r as readConversationRunStatusOfRunState, C as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION, i as isAgentsClientError } from "./conversation-CbWEHPbL.js";
|
|
3
3
|
const POLLING_RUNNING_INTERVAL_MS = 2e3;
|
|
4
4
|
const POLLING_IDLE_INTERVAL_MS = 2e4;
|
|
5
5
|
const POLLING_MAX_BACKOFF_MS = 6e4;
|
|
@@ -252,4 +252,4 @@ export {
|
|
|
252
252
|
readPolledRunStatus as r,
|
|
253
253
|
withPollingChangeSubscription as w
|
|
254
254
|
};
|
|
255
|
-
//# sourceMappingURL=withPollingChangeSubscription-
|
|
255
|
+
//# sourceMappingURL=withPollingChangeSubscription-CWavoKjJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withPollingChangeSubscription-CNXgt3Ri.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 {\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\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 }\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,EAC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pE,SAAA,iCAAiC,CAC/B,gBACA,UACA,YACiB,KAAK,QAAQ,+BAA+B,gBAAgB,UAAU,OAAO;AAhE9F,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;AAAA,EAC9E;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-CWavoKjJ.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 {\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\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 }\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,y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Q,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;AAhE9F,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;AAAA,EAC9E;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,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
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
4
|
import { l as listWidgetHydratorTypes, g as getWidgetHydrator, b as registerWidgetHydrator, c as abandonWidgetHydrationReads, u as unregisterWidgetHydrator } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
5
|
-
import { j as conversationWidgetRegistry, k as replaceConversationWidgetRegistryEntries } from "./chunks/widget-name-resolver-
|
|
6
|
-
import { l, s } from "./chunks/widget-name-resolver-
|
|
5
|
+
import { j as conversationWidgetRegistry, k as replaceConversationWidgetRegistryEntries } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
6
|
+
import { l, s } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
7
7
|
import { c, r, s as s2 } from "./chunks/canvasStorage-DHNluopA.js";
|
|
8
8
|
const DEFAULT_SCRIPTED_ASSISTANT_ANSWER = "Done.";
|
|
9
9
|
const DEFAULT_PAGE_SIZE = 50;
|
package/dist/client.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { A, u, a } from "./chunks/AgentsConversationClientContext-C4T7g_Qk.js";
|
|
3
|
-
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-
|
|
4
|
-
import { P, a as a2, b, c, d, r } from "./chunks/withPollingChangeSubscription-
|
|
5
|
-
import { A as
|
|
3
|
+
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-CWavoKjJ.js";
|
|
4
|
+
import { P, a as a2, b, c, d, r } from "./chunks/withPollingChangeSubscription-CWavoKjJ.js";
|
|
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
6
|
import { c as composeAttachmentMessageText } from "./chunks/compose-attachment-message-text-FvVJbrge.js";
|
|
7
7
|
const RUN_STATES = [
|
|
8
8
|
"IDLE",
|
|
@@ -194,6 +194,31 @@ const mapHttpFailureToAgentsClientError = (httpStatus, wireErrorBody, retryAfter
|
|
|
194
194
|
const kind = kindOfCode ?? (httpStatus === 429 ? "rateLimit" : httpStatus === 404 ? "notFound" : httpStatus === 403 || httpStatus === 401 ? "forbidden" : httpStatus >= 500 ? "network" : "other");
|
|
195
195
|
return new AgentsClientError(kind, { message: message ?? void 0, code, retryAfterSeconds, httpStatus });
|
|
196
196
|
};
|
|
197
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
|
|
198
|
+
const readClientContextText = (value, maxChars) => {
|
|
199
|
+
if (value === null || value === void 0) return void 0;
|
|
200
|
+
const text = String(value).trim();
|
|
201
|
+
if (text === "" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return void 0;
|
|
202
|
+
return text;
|
|
203
|
+
};
|
|
204
|
+
const mapClientContextToWire = (clientContext) => {
|
|
205
|
+
if (!clientContext) return void 0;
|
|
206
|
+
const wireClientContext = {};
|
|
207
|
+
const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);
|
|
208
|
+
if (routePath !== void 0) wireClientContext.routePath = routePath;
|
|
209
|
+
const routeParameters = Object.entries(clientContext.routeParameters ?? {}).filter(([name, value]) => name.trim() !== "" && value !== null && value !== void 0).map(([name, value]) => ({ name, value: String(value) }));
|
|
210
|
+
const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join("&");
|
|
211
|
+
if (routeParameters.length > 0 && routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount && routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars && !CONTROL_CHARACTERS.test(routeParametersText)) {
|
|
212
|
+
wireClientContext.routeParameters = routeParameters;
|
|
213
|
+
}
|
|
214
|
+
const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);
|
|
215
|
+
if (recordKind !== void 0) wireClientContext.recordKind = recordKind;
|
|
216
|
+
const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);
|
|
217
|
+
if (recordId !== void 0) wireClientContext.recordId = recordId;
|
|
218
|
+
const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);
|
|
219
|
+
if (tab !== void 0) wireClientContext.tab = tab;
|
|
220
|
+
return Object.keys(wireClientContext).length > 0 ? wireClientContext : void 0;
|
|
221
|
+
};
|
|
197
222
|
const AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE = 50;
|
|
198
223
|
const MESSAGES_EXPAND = "delegatedConversations(select=id,runState)";
|
|
199
224
|
const defaultBuildStartPath = (agentSpaceKey) => agentSpaceKey > 0 ? `/start/${agentSpaceKey}` : "/start";
|
|
@@ -288,7 +313,8 @@ class AgentsHttpConversationClient {
|
|
|
288
313
|
body: {
|
|
289
314
|
aiConversationMessage: { message: composeAttachmentMessageText(request.text, request.attachments) },
|
|
290
315
|
...request.startSignalText ? { signalText: request.startSignalText } : {},
|
|
291
|
-
...request.entryPointKey ? { entryPointKey: request.entryPointKey } : {}
|
|
316
|
+
...request.entryPointKey ? { entryPointKey: request.entryPointKey } : {},
|
|
317
|
+
...this.readClientContextBody("startConversation")
|
|
292
318
|
}
|
|
293
319
|
});
|
|
294
320
|
const wireConversation = response.aiConversation ?? {};
|
|
@@ -305,7 +331,10 @@ class AgentsHttpConversationClient {
|
|
|
305
331
|
method: "POST",
|
|
306
332
|
path: `/${conversationId}/postMessage`,
|
|
307
333
|
query: { aiModelName: message.model },
|
|
308
|
-
body: {
|
|
334
|
+
body: {
|
|
335
|
+
aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) },
|
|
336
|
+
...this.readClientContextBody("postMessage")
|
|
337
|
+
}
|
|
309
338
|
});
|
|
310
339
|
return { messages: readWireSetElements(response.aiConversation?.messages).map(mapWireConversationMessage) };
|
|
311
340
|
};
|
|
@@ -314,7 +343,11 @@ class AgentsHttpConversationClient {
|
|
|
314
343
|
operation: "injectSignal",
|
|
315
344
|
method: "POST",
|
|
316
345
|
path: `/${conversationId}/injectSignal`,
|
|
317
|
-
body: {
|
|
346
|
+
body: {
|
|
347
|
+
signalText: signal.text,
|
|
348
|
+
...signal.source ? { signalSource: signal.source } : {},
|
|
349
|
+
...this.readClientContextBody("injectSignal")
|
|
350
|
+
}
|
|
318
351
|
});
|
|
319
352
|
};
|
|
320
353
|
this.retryConversation = async (conversationId) => {
|
|
@@ -358,6 +391,11 @@ class AgentsHttpConversationClient {
|
|
|
358
391
|
hasMoreOlder: response.hasMoreOlder === true
|
|
359
392
|
};
|
|
360
393
|
}
|
|
394
|
+
/** The body field `clientContext` of a write, from the host's option; nothing when it gives none. */
|
|
395
|
+
readClientContextBody(operation) {
|
|
396
|
+
const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));
|
|
397
|
+
return wireClientContext ? { clientContext: wireClientContext } : {};
|
|
398
|
+
}
|
|
361
399
|
/** The URL of a route: the base, the path, the binding's query parameters with the host's extra ones over them. */
|
|
362
400
|
buildUrl(request) {
|
|
363
401
|
const searchParameters = new URLSearchParams();
|
|
@@ -428,6 +466,7 @@ export {
|
|
|
428
466
|
composeAttachmentMessageText,
|
|
429
467
|
createAgentsHttpConversationClient,
|
|
430
468
|
d as createPollingConversationChangeSubscription,
|
|
469
|
+
mapClientContextToWire,
|
|
431
470
|
mapHttpFailureToAgentsClientError,
|
|
432
471
|
mapWireConversation,
|
|
433
472
|
mapWireConversationActivity,
|
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 AgentsClientError,\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 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","import type {\n AgentsConversationClient,\n AgentsConversationClientBindingOptions,\n AgentsConversationOperation,\n} from \"../AgentsConversationClient\";\nimport {\n AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,\n AgentsClientError,\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 { composeAttachmentMessageText } from \"../compose-attachment-message-text\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../polling/withPollingChangeSubscription\";\nimport {\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 {\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\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 response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n });\n return mapWireConversationRunState(response);\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 },\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: { aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) } },\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: { signalText: signal.text, ...(signal.source ? { signalSource: signal.source } : {}) },\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 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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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 { 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 {\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\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 response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n });\n return mapWireConversationRunState(response);\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): { clientContext?: ReturnType<typeof mapClientContextToWire> } {\n const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));\n return wireClientContext ? { clientContext: wireClientContext } : {};\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;AAA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W,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;"}
|
package/dist/contract.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
3
|
-
import { b } from "./chunks/contract-
|
|
2
|
+
import { A, b, a, C, i, r } from "./chunks/conversation-CbWEHPbL.js";
|
|
3
|
+
import { b as b2 } from "./chunks/contract-kmmw_19Y.js";
|
|
4
4
|
export {
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
A as AGENTS_CLIENT_CONTEXT_LIMITS,
|
|
6
|
+
b as AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,
|
|
7
|
+
a as AgentsClientError,
|
|
7
8
|
C as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,
|
|
8
|
-
|
|
9
|
+
b2 as buildChangedMessagesRequest,
|
|
9
10
|
i as isAgentsClientError,
|
|
10
11
|
r as readConversationRunStatusOfRunState
|
|
11
12
|
};
|
|
@@ -842,6 +842,15 @@
|
|
|
842
842
|
"src/chat/controller/derive-agent-activity.ts"
|
|
843
843
|
]
|
|
844
844
|
},
|
|
845
|
+
{
|
|
846
|
+
"key": "Scroll to the latest message",
|
|
847
|
+
"defaultText": "Scroll to the latest message",
|
|
848
|
+
"placeholders": [],
|
|
849
|
+
"contexts": [],
|
|
850
|
+
"usedIn": [
|
|
851
|
+
"src/chat/ConversationScrollToLatestMessageButton/ConversationScrollToLatestMessageButton.tsx"
|
|
852
|
+
]
|
|
853
|
+
},
|
|
845
854
|
{
|
|
846
855
|
"key": "Search results for \"%query%\"",
|
|
847
856
|
"defaultText": "Search results for \"%query%\"",
|
|
@@ -872,6 +881,15 @@
|
|
|
872
881
|
"src/kit/components/form/Form.composed.tsx"
|
|
873
882
|
]
|
|
874
883
|
},
|
|
884
|
+
{
|
|
885
|
+
"key": "Send message",
|
|
886
|
+
"defaultText": "Send message",
|
|
887
|
+
"placeholders": [],
|
|
888
|
+
"contexts": [],
|
|
889
|
+
"usedIn": [
|
|
890
|
+
"src/chat/ConversationMessageInput/ConversationMessageInput.tsx"
|
|
891
|
+
]
|
|
892
|
+
},
|
|
875
893
|
{
|
|
876
894
|
"key": "Show",
|
|
877
895
|
"defaultText": "Show",
|
|
@@ -1439,6 +1457,7 @@
|
|
|
1439
1457
|
"contexts": [],
|
|
1440
1458
|
"usedIn": [
|
|
1441
1459
|
"src/chat/AgentChatActivityIndicator/AgentChatActivityIndicator.tsx",
|
|
1460
|
+
"src/chat/AgentChatActivityStack/AgentChatActivityStack.tsx",
|
|
1442
1461
|
"src/chat/ConversationMessage/ConversationMessageWidgets/ConversationMessageThinking/ConversationMessageThinking.tsx"
|
|
1443
1462
|
]
|
|
1444
1463
|
},
|
package/dist/image-render.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
3
|
import React, { useRef, useEffect } from "react";
|
|
4
|
-
import { G as resolveWidgetName, j as conversationWidgetRegistry } from "./chunks/widget-name-resolver-
|
|
5
|
-
import { H } from "./chunks/widget-name-resolver-
|
|
4
|
+
import { G as resolveWidgetName, j as conversationWidgetRegistry } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
5
|
+
import { H } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
6
6
|
import { i as ConversationWidgetRenderContext, K as WidgetImageReadinessContext, R as ReadOnlyConversationWidgetProvider, N as WidgetImageRenderContext, O as WidgetImageLiveHydrationContext, j as buildWidgetAgentSpaceKeyProps } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
7
7
|
import { P, Q, T } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
8
8
|
import { r as readWidgetImageReadiness, p as publishWidgetImageReadiness } from "./chunks/widget-image-readiness-signal-C5yaKpJJ.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { h, i } from "./chunks/widget-name-resolver-
|
|
3
|
-
import { g, r, a, b } from "./chunks/canvasBodies-
|
|
2
|
+
import { h, i } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
3
|
+
import { g, r, a, b } from "./chunks/canvasBodies-C_pdv17v.js";
|
|
4
4
|
import { r as r2 } from "./chunks/canvas-feature-flags-BmmxC3bz.js";
|
|
5
5
|
import { r as r3, a as a2, b as b2 } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
6
6
|
import { A, i as i2 } from "./chunks/icon-names-Di6c4zLo.js";
|
package/dist/kit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { A, C, a, b, c, d, e, E, r, f, u, g } from "./chunks/widget-name-resolver-
|
|
2
|
+
import { A, C, a, b, c, d, e, E, r, f, u, g } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
3
3
|
import { M } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
4
4
|
import { E as E2, u as u2 } from "./chunks/entity-detail-name-3A82gDAp.js";
|
|
5
5
|
export {
|
package/dist/preview.js
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { s as Text, Y as getWidgetSelfHydrationKeyFieldName, e as DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME, V as getSandboxLegacyAliases } from "./chunks/link-navigation-DyTApNeA.js";
|
|
4
4
|
import { useRef, useState, useMemo, useEffect, useCallback } from "react";
|
|
5
|
-
import { Q as buildComposedViewComponentRegistry, R as composedViewComponents, G as resolveWidgetName, j as conversationWidgetRegistry, o as ConversationWidgetErrorBoundary, S as ComposedViewComponentsContext } from "./chunks/widget-name-resolver-
|
|
5
|
+
import { Q as buildComposedViewComponentRegistry, R as composedViewComponents, G as resolveWidgetName, j as conversationWidgetRegistry, o as ConversationWidgetErrorBoundary, S as ComposedViewComponentsContext } from "./chunks/widget-name-resolver-7WnzCpdG.js";
|
|
6
6
|
import { X as WidgetSurface, A as readWidgetAgentSpaceKeyAttribute, W as WidgetRenderReportContext, j as buildWidgetAgentSpaceKeyProps, S as StandaloneConversationWidgetProvider, i as ConversationWidgetRenderContext, N as WidgetImageRenderContext, _ as CANVAS_VIABLE_MIN_WIDTH, l as listWidgetHydratorTypes, g as getWidgetHydrator, u as unregisterWidgetHydrator, b as registerWidgetHydrator } from "./chunks/WebSearchResultsConversationWidget-BXt98hGu.js";
|
|
7
|
-
import { c as canvasBodies, E as EntityMentionAskButton } from "./chunks/canvasBodies-
|
|
7
|
+
import { c as canvasBodies, E as EntityMentionAskButton } from "./chunks/canvasBodies-C_pdv17v.js";
|
|
8
8
|
import { c as canvasBehaviourOf } from "./chunks/canvas-behaviours-BpN_1xdZ.js";
|
|
9
9
|
import { f as decideCanvasOpen } from "./chunks/canvas-reducers-CuX6L1zg.js";
|
|
10
10
|
import { p as publishWidgetImageReadiness } from "./chunks/widget-image-readiness-signal-C5yaKpJJ.js";
|
|
11
11
|
import axios from "axios";
|
|
12
|
-
import { C as ConversationWidgetProvider, a as ConversationMessageInputComposerWidgets } from "./chunks/ConversationMessageInputComposerWidgets-
|
|
12
|
+
import { C as ConversationWidgetProvider, a as ConversationMessageInputComposerWidgets } from "./chunks/ConversationMessageInputComposerWidgets-BbpB0fZl.js";
|
|
13
13
|
const page$1 = "agents_page_5VMDeD";
|
|
14
14
|
const chatColumn = "agents_chatColumn_FWcgdJ";
|
|
15
15
|
const widget = "agents_widget_3qpgMy";
|