@mgamadeus/ddd-agents 0.6.8 → 0.6.10
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/dist/chat.js +1 -1
- package/dist/chunks/conversation-CbWEHPbL.js.map +1 -1
- package/dist/chunks/{withPollingChangeSubscription-CnQnubfK.js → withPollingChangeSubscription-mWdchMOH.js} +2 -1
- package/dist/chunks/{withPollingChangeSubscription-CnQnubfK.js.map → withPollingChangeSubscription-mWdchMOH.js.map} +1 -1
- package/dist/client.js +24 -2
- package/dist/client.js.map +1 -1
- package/dist/types/client/AgentsConversationClient.d.ts +6 -1
- package/dist/types/client/http/agents-http-wire.d.ts +6 -0
- package/dist/types/contract/conversation.d.ts +30 -0
- package/dist/ui.js +2 -2
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
package/dist/chat.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { jsx, jsxs, Fragment as Fragment$1 } from "react/jsx-runtime";
|
|
3
3
|
import { useRef, useEffect, useMemo, useState, useImperativeHandle, useLayoutEffect, memo, useCallback, Fragment, useReducer } from "react";
|
|
4
4
|
import { u as useAgentsConversationClient, a as useOptionalAgentsConversationClient, A as AgentsConversationClientProvider } from "./chunks/AgentsConversationClientContext-C4T7g_Qk.js";
|
|
5
|
-
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-
|
|
5
|
+
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-mWdchMOH.js";
|
|
6
6
|
import { s as Text, F as classNames, I as Icon, ab as useAgentsTexts, G as GlowFrame, v as Tooltip, B as Button, n as Skeleton, j as Markdown, K as getAgentDisplayName, a3 as useAgentsBudgetLimit, a5 as useAgentsEnvironment, h as InteractiveSurface, L as LoadingSpinner, a1 as translateText, p as SplitView, _ as reportRunningTurn, a2 as useAgentsActiveAgentSpaceKey, P as ProgressBar } from "./chunks/link-navigation-BUcy5qWW.js";
|
|
7
7
|
import { i as isAgentsClientError, a as AgentsClientError } from "./chunks/conversation-CbWEHPbL.js";
|
|
8
8
|
import { n as normalizeServerMessageToMarkdown, V as VoiceBarsIcon, b as ConversationMessageHeader, a as ConversationMessageUser, C as ConversationMessageWidgets } from "./chunks/VoiceBarsIcon-BIcURsBF.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-CbWEHPbL.js","sources":["../../src/contract/conversation.ts"],"sourcesContent":["/**\n * The conversation contract of the package: plain TypeScript types the conversation client port\n * (`client/AgentsConversationClient.ts`) returns and the chat reads. Every field is derived from what the chat files and\n * the chat controller read from the server today (the host application's generated `AIConversation`, `AIConversationMessage`,\n * `AgentActivityLine`, `SemanticSearchHit`, `AIConversationSearchGroup`, `AgentCustomerSelectableModel`); nothing the\n * chat does not read is here.\n *\n * Naming: a field keeps the wire name where the name is neutral (`message`, `indexInConversation`, `role`, `status`,\n * `toolCall`); a name that carries an app's vocabulary is renamed (`aiConversationId` → `conversationId`,\n * the app's own key of the thing the agent works for → `agentSpaceKey`, `summary.title` → `title`). Each field carries a\n * one-line note:\n * - `generic` — every app that runs the agent conversation backend has it;\n * - `app extension` — read by the chat today but specific to one app's backend or debug surface; optional, and a\n * binding may leave it out.\n *\n * Client-side state is NOT part of the contract: the `fresh` tag of a live-arrived message, the optimistic user\n * message without an id and the `isNewConversation` / `isReopenedConversation` flags belong to the package store.\n */\n\n// ── Vocabulary ───────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** The run state of a conversation as the server stores it (`AIConversationRunState`). */\nexport type ConversationRunState =\n | \"IDLE\"\n | \"QUEUED\"\n | \"RUNNING\"\n | \"AWAITING_DELEGATES\"\n | \"FAILED\"\n | \"COMPLETED\"\n | \"CANCELLED\";\n\n/** The three-value run status the live-update signal speaks; the chat keys its indicator and error card off it. */\nexport type ConversationRunStatus = \"running\" | \"idle\" | \"failed\";\n\nexport type ConversationMessageRole = \"SYSTEM\" | \"USER\" | \"ASSISTANT\";\n\nexport type ConversationMessageType = \"TEXT\" | \"TOOL_CALL\" | \"CHECKPOINT\" | \"ERROR\" | \"SIGNAL\" | \"TOOL_MESSAGE\";\n\nexport type ConversationMessageStatus =\n | \"PENDING\"\n | \"RUNNING\"\n | \"CANCEL_REQUESTED\"\n | \"CANCELLED\"\n | \"COMPLETED\"\n | \"FAILED\";\n\nexport type ConversationMessageAuthorType = \"USER\" | \"ASSISTANT\" | \"AGENT\" | \"TOOL\";\n\n/** Run states after which nothing runs any more and the server refuses further customer input. */\nexport const CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION: readonly ConversationRunState[] = [\n \"COMPLETED\",\n \"CANCELLED\",\n];\n\n/** Maps a stored run state onto the signal's three-value status (`runStateToSignalStatus` of the live-update hook). */\nexport const readConversationRunStatusOfRunState = (\n runState: string | null | undefined,\n): ConversationRunStatus | null => {\n if (!runState) return null;\n if (runState === \"FAILED\") return \"failed\";\n if (runState === \"RUNNING\" || runState === \"AWAITING_DELEGATES\" || runState === \"QUEUED\") return \"running\";\n return \"idle\";\n};\n\n// ── Conversation ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** One step of the progress stepper a purposed conversation declares (`CustomerProgressStep`). */\nexport interface ConversationProgressStep {\n /** generic */\n key: string;\n /** generic — already in the owner's language */\n label: string;\n /** generic */\n status: \"done\" | \"active\" | \"upcoming\";\n}\n\n/** A conversation as the chat, the conversation list and the window around the chat read it. */\nexport interface AgentsConversation {\n /** generic */\n id: number;\n /** generic — the key of the agent space the conversation belongs to */\n agentSpaceKey: number | null;\n /** generic */\n runState: ConversationRunState | null;\n /**\n * generic — set while the server owes a turn on an IDLE conversation (a failed hand-over the recovery re-drives);\n * an IDLE conversation with this set counts as running (`effectiveRunState`)\n */\n agentTurnOwedAt: string | null;\n /** generic — the display title (`summary.title`); null until the first title was generated */\n title: string | null;\n /** generic — the owner set the title by hand; the generated title never replaces it then */\n titleManuallyEdited: boolean;\n /** generic — the generated summary of what the conversation is about (`summary.text`); null until generated */\n summary: string | null;\n /** generic — when the conversation was created, in the server's date-time format */\n created: string | null;\n /** generic — when the conversation was last modified, in the server's date-time format */\n updated: string | null;\n /** generic — the purpose of a purposed conversation (e.g. `Example.Build`, a first-run setup purpose); null otherwise */\n purposeName: string | null;\n /** generic — who started the conversation (`SCHEDULE` for a run of a scheduled task) */\n initiatorType: string | null;\n /** generic — the scheduled task a `SCHEDULE` conversation is a run of */\n scheduleId: number | null;\n /** generic — the entry point a start came from; a start from the same entry point reopens this conversation */\n entryPointKey: string | null;\n /** generic — empty unless the purpose declares a progress stepper */\n progressSteps: ConversationProgressStep[];\n /**\n * generic — the id of the newest stored message; null before the first. The polling default of the live updates\n * (`client/polling/`) reads it to see a new message while the run status stays the same, and hands it to the rules as\n * the signal's `lastMessageId`. Optional: a binding with a push transport may leave it out (the host application's metadata\n * read does not carry it); without it the poller treats every poll of a running turn as a change.\n */\n lastMessageId?: number | null;\n /** app extension — the prompt extension of the host application's older AI-Extensions chat */\n promptExtensionId?: number | null;\n /** app extension — the category of that prompt extension (its colour and product name in the conversation list) */\n promptExtensionCategory?: { alias: string | null; name: string | null } | null;\n}\n\n/**\n * What the server's run-state read answers (`GET …/{id}/runState`): the lean subset of a conversation the live updates\n * poll. Every `AgentsConversation` is one, so a binding without the read may answer it with the metadata read.\n */\nexport type ConversationRunStateRead = Pick<\n AgentsConversation,\n \"id\" | \"runState\" | \"agentTurnOwedAt\" | \"title\" | \"titleManuallyEdited\" | \"summary\" | \"updated\"\n> & {\n /** generic — the id of the newest stored message; null before the first */\n lastMessageId?: number | null;\n};\n\n// ── Messages ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** A sub-agent conversation a delegation started, as far as the chat reads it (`delegatedConversations(select=id,runState)`). */\nexport interface ConversationDelegatedConversation {\n /** generic */\n id: number;\n /** generic */\n runState: ConversationRunState | null;\n}\n\n/** One run of a sub-agent, as the activity derivation reads it (`DelegationSubAgentRun`). */\nexport interface ConversationSubAgentRun {\n /** generic */\n runNumber: number | null;\n /** generic */\n status: string | null;\n}\n\n/** The sub-agent record a newer `delegate` call row carries instead of expanded children (`DelegationSubAgentRecord`). */\nexport interface ConversationSubAgent {\n /** generic */\n currentRunNumber: number | null;\n /** generic */\n runs: ConversationSubAgentRun[];\n}\n\n/** The tool call a `TOOL_CALL` row carries, as far as the chat reads it. */\nexport interface ConversationToolCall {\n /** generic */\n toolCallId: string | null;\n /** generic */\n name: string | null;\n /** generic — the call's arguments as the model wrote them (the `delegate` call's `tasks` is read) */\n arguments: unknown;\n /** generic — the call's own progress; a row's `status` says nothing about it */\n status: string | null;\n}\n\n/** The admin debug numbers of one message (the message forensics panel). */\nexport interface ConversationMessageForensics {\n /** app extension */\n inputTokens: number | null;\n /** app extension */\n outputTokens: number | null;\n /** app extension */\n costInUSD: number | null;\n /** app extension — the stored request snapshot of the model call (model name, reasoning effort, sent at) */\n requestSnapshot: unknown;\n}\n\n/** One stored message of a conversation. */\nexport interface AgentsConversationMessage {\n /** generic */\n id: number;\n /** generic */\n conversationId: number | null;\n /** generic — the position in the conversation; the merge key of every page */\n indexInConversation: number | null;\n /** generic */\n role: ConversationMessageRole | null;\n /** generic */\n messageType: ConversationMessageType | null;\n /** generic — non-final only on a waiting signal row */\n status: ConversationMessageStatus | null;\n /** generic */\n authorType: ConversationMessageAuthorType | null;\n /** generic — the source of a SIGNAL or ERROR row (`AI_BUDGET_REACHED`, `FRONTEND_WIDGET_CLICK`, …) */\n signalSource: string | null;\n /** generic — the text in markdown, widget blocks included */\n message: string;\n /** generic */\n createdDate: string | null;\n /** generic */\n toolCall: ConversationToolCall | null;\n /** generic — the sub-agent conversations a `delegate` call started (older rows) */\n delegatedConversations: ConversationDelegatedConversation[];\n /** generic — the sub-agent record of a `delegate` call (newer rows) */\n subAgent: ConversationSubAgent | null;\n /** app extension — admin debug numbers; absent outside the admin surfaces */\n forensics?: ConversationMessageForensics;\n}\n\n/** A file from the app's media library that rides along with a message. */\nexport interface ConversationAttachmentReference {\n /** generic — the app's id of the file (host application: the media manager file id) */\n fileId: string | number | null;\n /** generic */\n fileName: string | null;\n /** generic — a URL the model and the tools can fetch */\n publicUrl: string | null;\n}\n\n// ── Pages and results of the port ────────────────────────────────────────────────────────────────────────────────\n\n/** A page of messages read newest first (the newest page on open, an older page on scroll-up). */\nexport interface ConversationMessagesPage {\n /** generic — in any order; the store merges by `indexInConversation` */\n messages: AgentsConversationMessage[];\n /** generic — an older page exists */\n hasMoreOlder: boolean;\n}\n\n/**\n * What a live update reads: every message written since the newest known id, plus every message from the lowest\n * loaded index that can still change (`build-live-refetch-query.ts`). The package computes both values.\n */\nexport interface ChangedMessagesRequest {\n /** generic — the highest message id loaded */\n highestKnownId: number;\n /** generic — the lowest index that can still change, never below the newest page */\n fromIndex: number;\n /** generic — the page size of the read; the binding's default (host application: 50, as the chat sends) when omitted */\n pageSize?: number;\n}\n\n/** The answer of a changed-messages read; it says nothing about older pages (the store keeps `hasMoreOlder`). */\nexport interface ChangedConversationMessages {\n /** generic */\n messages: AgentsConversationMessage[];\n}\n\n/** The answer of a start: the new conversation with what it holds so far, or the reopened one of the entry point. */\nexport interface StartedConversation {\n /** generic */\n conversation: AgentsConversation;\n /** generic — the stored messages of a new conversation; empty for a reopened one (the chat reads its newest page) */\n messages: AgentsConversationMessage[];\n /** generic — the start returned the recent conversation of its entry point; nothing was appended, no turn started */\n reopenedExisting: boolean;\n}\n\n/** The answer of a post: the conversation's messages so far (the reply arrives through live updates). */\nexport interface PostedMessage {\n /** generic */\n messages: AgentsConversationMessage[];\n}\n\n/** A model-visible, owner-invisible note into a conversation (a widget click, a render report, a correction). */\n/**\n * What the owner's client shows while the owner writes: the route, its parameters, the record on screen and the tab.\n * Sent with a start, a posted message and an injected signal; the server stores it on that owner row and the agent reads\n * the newest one as one line beside the owner's newest message. Each field is optional and capped\n * ({@link AGENTS_CLIENT_CONTEXT_LIMITS}); the server refuses a request with a field over its cap (HTTP 400).\n */\nexport interface AgentsClientContext {\n /** The path of the route the client shows, e.g. `/tickets/42`. */\n routePath?: string | null;\n /** The parameters of that route by name, values as text. */\n routeParameters?: Record<string, string> | null;\n /** The kind of the record on screen, as the application names it, e.g. `ticket`. */\n recordKind?: string | null;\n /** The id of the record on screen. */\n recordId?: string | number | null;\n /** The tab the client shows. */\n tab?: string | null;\n}\n\n/** The caps of {@link AgentsClientContext} (characters; the route parameters as their `name=value&…` text). */\nexport const AGENTS_CLIENT_CONTEXT_LIMITS = {\n routePathChars: 512,\n routeParametersChars: 512,\n routeParameterCount: 20,\n recordKindChars: 64,\n recordIdChars: 128,\n tabChars: 64,\n} as const;\n\nexport interface ConversationSignal {\n /** generic */\n text: string;\n /** generic — the signal source; the server's default applies when omitted (a widget click) */\n source?: string;\n}\n\n/** How a list read pages and which conversations it includes. */\nexport interface ConversationListQueryOptions {\n /** generic — include conversations that have no summary (title) yet, e.g. a just-started one */\n includeUnsummarized?: boolean;\n /** generic — the host application's history reads the newest 50 */\n paging?: { top?: number; skip?: number };\n}\n\n/** The size of a search answer. */\nexport interface ConversationSearchOptions {\n /** generic — the most groups (or hits) returned; the host application's chat asks for 10 */\n limit?: number;\n /** generic — the excerpt length in characters; the host application's chat asks for 420 */\n excerptLength?: number;\n}\n\n/** app extension — the reconstructed request a model call was sent with (the admin details panel); opaque data. */\nexport type ConversationMessageSentPayload = unknown[];\n\n/** One matched message of a message search (`SemanticSearchHit`). */\nexport interface ConversationMessageSearchHit {\n /** generic */\n messageId: number | null;\n /** generic */\n conversationId: number | null;\n /** generic */\n indexInConversation: number | null;\n /** generic */\n role: string | null;\n /** generic */\n excerpt: string;\n /** generic */\n relevance: number;\n /** generic */\n created: string | null;\n /** generic */\n updated: string | null;\n /** generic — the conversation's title */\n title: string | null;\n}\n\n/** One conversation of a search across conversations, with its matched messages (`AIConversationSearchGroup`). */\nexport interface ConversationSearchGroup {\n /** generic */\n conversationId: number | null;\n /** generic */\n title: string | null;\n /** generic */\n summary: string | null;\n /** generic */\n created: string | null;\n /** generic */\n updated: string | null;\n /** generic */\n relevance: number;\n /** generic */\n hits: ConversationMessageSearchHit[];\n}\n\n/** One generated line of what the agent is doing (`AgentActivityLine`). */\nexport interface ConversationActivityElement {\n /** generic — the row the line narrates; the merge key */\n toolCallMessageId: number;\n /** generic */\n batchId: string | null;\n /** generic */\n state: \"queued\" | \"running\" | \"finished\" | \"failed\" | \"skipped\" | null;\n /** generic */\n kind: \"tool\" | \"delegation\" | \"background\" | \"long\" | \"turnStart\" | null;\n /** generic */\n childCount: number | null;\n /** generic — the 1-based delegation helper that ran the step; null for the assistant's own steps */\n helperIndex: number | null;\n /** generic — the sentence; null while the narrator has not answered */\n line: string | null;\n}\n\n/** The activity of one turn (`GET …/activity`). */\nexport interface ConversationActivity {\n /** generic — the message that started the narrated turn */\n turnMessageId: number | null;\n /** generic */\n turnRunning: boolean;\n /** generic */\n elements: ConversationActivityElement[];\n}\n\n/** A model the owner (host application: an impersonating admin) may pick for the next turns (`AgentCustomerSelectableModel`). */\nexport interface SelectableModel {\n /** generic — the name a send carries */\n name: string;\n /** generic */\n displayName: string;\n /** generic */\n description: string;\n /** generic */\n strengthLevel: number | null;\n /** generic */\n speedLevel: number | null;\n /** app extension — the host application's credit multiplier of the model */\n creditsMultiplier?: number | null;\n}\n\n// ── Live updates ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * What a live update carries: a claim check, never content. The chat reads the conversation again when\n * `changeCounter` advances, at once on a terminal status, and until `lastMessageId` is loaded.\n */\nexport interface ConversationChangeSignal {\n /** generic — advances on every change of the conversation */\n changeCounter: number;\n /** generic — the newest message the server wrote; null before the first */\n lastMessageId: number | null;\n /** generic */\n runStatus: ConversationRunStatus | null;\n /** generic — advances when the title or summary was generated again (a light metadata read is enough then) */\n summaryUpdatedAt: number | null;\n /**\n * generic — the binding produced this emission from a run-state read, not from a pushed change (a binding without\n * push, or a push transport whose path is not proven readable, or a check that corrects a stale status). It carries\n * only `runStatus` as news: `changeCounter`, `lastMessageId` and `summaryUpdatedAt` repeat the last pushed values\n * (before any push: a counter that counts down from -1, never equal to a pushed one). The package sets the status\n * from it and reads the conversation again on a status change while the push path is not alive (`isPushPathAlive`).\n */\n isStatusCheck?: boolean;\n /**\n * generic, on a status-check emission — the binding's push path delivers: a pushed change arrived and the path was not\n * denied since. False after a denied read until a push arrives again; then the status checks are the live path and a\n * status change reads the conversation again. A binding without push leaves it out: the package then counts the\n * pushed changes it saw itself.\n */\n isPushPathAlive?: boolean;\n}\n\n/** Why a subscription ended for good: the conversation was deleted or is no longer readable, or the account lost access. */\nexport type ConversationSubscriptionEndReason = \"gone\" | \"forbidden\";\n\n// ── Errors ───────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * What went wrong, as the chat tells the owner. The codes the chat's error handling reads today map\n * onto it: `AI_BUDGET_REACHED` → `budget`, HTTP 429 / `RATE_LIMIT_EXCEEDED` → `rateLimit`, `CONVERSATION_CLOSED` →\n * `closed`, the not-found and no-access answers → `notFound` / `forbidden` (`conversation-not-found.ts`), no answer or a\n * server failure → `network`, everything else (a refused retry, a cancelled request) → `other` with its `code`.\n */\nexport type AgentsClientErrorKind = \"budget\" | \"rateLimit\" | \"closed\" | \"notFound\" | \"forbidden\" | \"network\" | \"other\";\n\n/** The code `other` carries for a request the client cancelled; the chat shows no error card for it. */\nexport const AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED = \"REQUEST_ABORTED\";\n\n/** The one error shape every port function rejects with. */\nexport class AgentsClientError extends Error {\n readonly kind: AgentsClientErrorKind;\n /** The server's stable error code, or the client's own code (`REQUEST_ABORTED`); null when none arrived. */\n readonly code: string | null;\n /** Seconds until a quota frees up again; set only for `rateLimit`. */\n readonly retryAfterSeconds: number | null;\n /** The HTTP status when one arrived (not part of the contract's shape; kept for diagnostics). */\n readonly httpStatus: number | null;\n\n constructor(\n kind: AgentsClientErrorKind,\n details: { message?: string; code?: string | null; retryAfterSeconds?: number | null; httpStatus?: number | null } = {},\n ) {\n super(details.message ?? kind);\n this.name = \"AgentsClientError\";\n this.kind = kind;\n this.code = details.code ?? null;\n this.retryAfterSeconds = kind === \"rateLimit\" ? (details.retryAfterSeconds ?? null) : null;\n this.httpStatus = details.httpStatus ?? null;\n }\n}\n\nexport const isAgentsClientError = (value: unknown): value is AgentsClientError => value instanceof AgentsClientError;\n"],"names":[],"mappings":";AAiDO,MAAM,oDAAqF;AAAA,EAChG;AAAA,EACA;AACF;AAGO,MAAM,sCAAsC,CACjD,aACiC;AACjC,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI,aAAa,SAAU,QAAO;AAClC,MAAI,aAAa,aAAa,aAAa,wBAAwB,aAAa,SAAU,QAAO;AACjG,SAAO;AACT;AAsOO,MAAM,+BAA+B;AAAA,EAC1C,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,UAAU;AACZ;AA8JO,MAAM,2CAA2C;AAGjD,MAAM,0BAA0B,MAAM;AAAA,EAS3C,YACE,MACA,UAAqH,IACrH;AACA,UAAM,QAAQ,WAAW,IAAI;AAC7B,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,oBAAoB,SAAS,cAAe,QAAQ,qBAAqB,OAAQ;AACtF,SAAK,aAAa,QAAQ,cAAc;AAAA,EAC1C;AACF;AAEO,MAAM,sBAAsB,CAAC,UAA+C,iBAAiB;"}
|
|
1
|
+
{"version":3,"file":"conversation-CbWEHPbL.js","sources":["../../src/contract/conversation.ts"],"sourcesContent":["/**\n * The conversation contract of the package: plain TypeScript types the conversation client port\n * (`client/AgentsConversationClient.ts`) returns and the chat reads. Every field is derived from what the chat files and\n * the chat controller read from the server today (the host application's generated `AIConversation`, `AIConversationMessage`,\n * `AgentActivityLine`, `SemanticSearchHit`, `AIConversationSearchGroup`, `AgentCustomerSelectableModel`); nothing the\n * chat does not read is here.\n *\n * Naming: a field keeps the wire name where the name is neutral (`message`, `indexInConversation`, `role`, `status`,\n * `toolCall`); a name that carries an app's vocabulary is renamed (`aiConversationId` → `conversationId`,\n * the app's own key of the thing the agent works for → `agentSpaceKey`, `summary.title` → `title`). Each field carries a\n * one-line note:\n * - `generic` — every app that runs the agent conversation backend has it;\n * - `app extension` — read by the chat today but specific to one app's backend or debug surface; optional, and a\n * binding may leave it out.\n *\n * Client-side state is NOT part of the contract: the `fresh` tag of a live-arrived message, the optimistic user\n * message without an id and the `isNewConversation` / `isReopenedConversation` flags belong to the package store.\n */\n\n// ── Vocabulary ───────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** The run state of a conversation as the server stores it (`AIConversationRunState`). */\nexport type ConversationRunState =\n | \"IDLE\"\n | \"QUEUED\"\n | \"RUNNING\"\n | \"AWAITING_DELEGATES\"\n | \"FAILED\"\n | \"COMPLETED\"\n | \"CANCELLED\";\n\n/** The three-value run status the live-update signal speaks; the chat keys its indicator and error card off it. */\nexport type ConversationRunStatus = \"running\" | \"idle\" | \"failed\";\n\nexport type ConversationMessageRole = \"SYSTEM\" | \"USER\" | \"ASSISTANT\";\n\nexport type ConversationMessageType = \"TEXT\" | \"TOOL_CALL\" | \"CHECKPOINT\" | \"ERROR\" | \"SIGNAL\" | \"TOOL_MESSAGE\";\n\nexport type ConversationMessageStatus =\n | \"PENDING\"\n | \"RUNNING\"\n | \"CANCEL_REQUESTED\"\n | \"CANCELLED\"\n | \"COMPLETED\"\n | \"FAILED\";\n\nexport type ConversationMessageAuthorType = \"USER\" | \"ASSISTANT\" | \"AGENT\" | \"TOOL\";\n\n/** Run states after which nothing runs any more and the server refuses further customer input. */\nexport const CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION: readonly ConversationRunState[] = [\n \"COMPLETED\",\n \"CANCELLED\",\n];\n\n/** Maps a stored run state onto the signal's three-value status (`runStateToSignalStatus` of the live-update hook). */\nexport const readConversationRunStatusOfRunState = (\n runState: string | null | undefined,\n): ConversationRunStatus | null => {\n if (!runState) return null;\n if (runState === \"FAILED\") return \"failed\";\n if (runState === \"RUNNING\" || runState === \"AWAITING_DELEGATES\" || runState === \"QUEUED\") return \"running\";\n return \"idle\";\n};\n\n// ── Conversation ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** One step of the progress stepper a purposed conversation declares (`CustomerProgressStep`). */\nexport interface ConversationProgressStep {\n /** generic */\n key: string;\n /** generic — already in the owner's language */\n label: string;\n /** generic */\n status: \"done\" | \"active\" | \"upcoming\";\n}\n\n/** A conversation as the chat, the conversation list and the window around the chat read it. */\nexport interface AgentsConversation {\n /** generic */\n id: number;\n /** generic — the key of the agent space the conversation belongs to */\n agentSpaceKey: number | null;\n /** generic */\n runState: ConversationRunState | null;\n /**\n * generic — set while the server owes a turn on an IDLE conversation (a failed hand-over the recovery re-drives);\n * an IDLE conversation with this set counts as running (`effectiveRunState`)\n */\n agentTurnOwedAt: string | null;\n /** generic — the display title (`summary.title`); null until the first title was generated */\n title: string | null;\n /** generic — the owner set the title by hand; the generated title never replaces it then */\n titleManuallyEdited: boolean;\n /** generic — the generated summary of what the conversation is about (`summary.text`); null until generated */\n summary: string | null;\n /** generic — when the conversation was created, in the server's date-time format */\n created: string | null;\n /** generic — when the conversation was last modified, in the server's date-time format */\n updated: string | null;\n /** generic — the purpose of a purposed conversation (e.g. `Example.Build`, a first-run setup purpose); null otherwise */\n purposeName: string | null;\n /** generic — who started the conversation (`SCHEDULE` for a run of a scheduled task) */\n initiatorType: string | null;\n /** generic — the scheduled task a `SCHEDULE` conversation is a run of */\n scheduleId: number | null;\n /** generic — the entry point a start came from; a start from the same entry point reopens this conversation */\n entryPointKey: string | null;\n /** generic — empty unless the purpose declares a progress stepper */\n progressSteps: ConversationProgressStep[];\n /**\n * generic — the id of the newest stored message; null before the first. The polling default of the live updates\n * (`client/polling/`) reads it to see a new message while the run status stays the same, and hands it to the rules as\n * the signal's `lastMessageId`. Optional: a binding with a push transport may leave it out (the host application's metadata\n * read does not carry it); without it the poller treats every poll of a running turn as a change.\n */\n lastMessageId?: number | null;\n /** app extension — the prompt extension of the host application's older AI-Extensions chat */\n promptExtensionId?: number | null;\n /** app extension — the category of that prompt extension (its colour and product name in the conversation list) */\n promptExtensionCategory?: { alias: string | null; name: string | null } | null;\n}\n\n/**\n * What the server's run-state read answers (`GET …/{id}/runState`): the lean subset of a conversation the live updates\n * poll. Every `AgentsConversation` is one, so a binding without the read may answer it with the metadata read.\n */\nexport type ConversationRunStateRead = Pick<\n AgentsConversation,\n \"id\" | \"runState\" | \"agentTurnOwedAt\" | \"title\" | \"titleManuallyEdited\" | \"summary\" | \"updated\"\n> & {\n /** generic — the id of the newest stored message; null before the first */\n lastMessageId?: number | null;\n};\n\n// ── Messages ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** A sub-agent conversation a delegation started, as far as the chat reads it (`delegatedConversations(select=id,runState)`). */\nexport interface ConversationDelegatedConversation {\n /** generic */\n id: number;\n /** generic */\n runState: ConversationRunState | null;\n}\n\n/** One run of a sub-agent, as the activity derivation reads it (`DelegationSubAgentRun`). */\nexport interface ConversationSubAgentRun {\n /** generic */\n runNumber: number | null;\n /** generic */\n status: string | null;\n}\n\n/** The sub-agent record a newer `delegate` call row carries instead of expanded children (`DelegationSubAgentRecord`). */\nexport interface ConversationSubAgent {\n /** generic */\n currentRunNumber: number | null;\n /** generic */\n runs: ConversationSubAgentRun[];\n}\n\n/** The tool call a `TOOL_CALL` row carries, as far as the chat reads it. */\nexport interface ConversationToolCall {\n /** generic */\n toolCallId: string | null;\n /** generic */\n name: string | null;\n /** generic — the call's arguments as the model wrote them (the `delegate` call's `tasks` is read) */\n arguments: unknown;\n /** generic — the call's own progress; a row's `status` says nothing about it */\n status: string | null;\n}\n\n/** The admin debug numbers of one message (the message forensics panel). */\nexport interface ConversationMessageForensics {\n /** app extension */\n inputTokens: number | null;\n /** app extension */\n outputTokens: number | null;\n /** app extension */\n costInUSD: number | null;\n /** app extension — the stored request snapshot of the model call (model name, reasoning effort, sent at) */\n requestSnapshot: unknown;\n}\n\n/** One stored message of a conversation. */\nexport interface AgentsConversationMessage {\n /** generic */\n id: number;\n /** generic */\n conversationId: number | null;\n /** generic — the position in the conversation; the merge key of every page */\n indexInConversation: number | null;\n /** generic */\n role: ConversationMessageRole | null;\n /** generic */\n messageType: ConversationMessageType | null;\n /** generic — non-final only on a waiting signal row */\n status: ConversationMessageStatus | null;\n /** generic */\n authorType: ConversationMessageAuthorType | null;\n /** generic — the source of a SIGNAL or ERROR row (`AI_BUDGET_REACHED`, `FRONTEND_WIDGET_CLICK`, …) */\n signalSource: string | null;\n /** generic — the text in markdown, widget blocks included */\n message: string;\n /** generic */\n createdDate: string | null;\n /** generic */\n toolCall: ConversationToolCall | null;\n /** generic — the sub-agent conversations a `delegate` call started (older rows) */\n delegatedConversations: ConversationDelegatedConversation[];\n /** generic — the sub-agent record of a `delegate` call (newer rows) */\n subAgent: ConversationSubAgent | null;\n /** app extension — admin debug numbers; absent outside the admin surfaces */\n forensics?: ConversationMessageForensics;\n}\n\n/** A file from the app's media library that rides along with a message. */\nexport interface ConversationAttachmentReference {\n /** generic — the app's id of the file (host application: the media manager file id) */\n fileId: string | number | null;\n /** generic */\n fileName: string | null;\n /** generic — a URL the model and the tools can fetch */\n publicUrl: string | null;\n}\n\n// ── Pages and results of the port ────────────────────────────────────────────────────────────────────────────────\n\n/** A page of messages read newest first (the newest page on open, an older page on scroll-up). */\nexport interface ConversationMessagesPage {\n /** generic — in any order; the store merges by `indexInConversation` */\n messages: AgentsConversationMessage[];\n /** generic — an older page exists */\n hasMoreOlder: boolean;\n}\n\n/**\n * What a live update reads: every message written since the newest known id, plus every message from the lowest\n * loaded index that can still change (`build-live-refetch-query.ts`). The package computes both values.\n */\nexport interface ChangedMessagesRequest {\n /** generic — the highest message id loaded */\n highestKnownId: number;\n /** generic — the lowest index that can still change, never below the newest page */\n fromIndex: number;\n /** generic — the page size of the read; the binding's default (host application: 50, as the chat sends) when omitted */\n pageSize?: number;\n}\n\n/** The answer of a changed-messages read; it says nothing about older pages (the store keeps `hasMoreOlder`). */\nexport interface ChangedConversationMessages {\n /** generic */\n messages: AgentsConversationMessage[];\n}\n\n/** The answer of a start: the new conversation with what it holds so far, or the reopened one of the entry point. */\nexport interface StartedConversation {\n /** generic */\n conversation: AgentsConversation;\n /** generic — the stored messages of a new conversation; empty for a reopened one (the chat reads its newest page) */\n messages: AgentsConversationMessage[];\n /** generic — the start returned the recent conversation of its entry point; nothing was appended, no turn started */\n reopenedExisting: boolean;\n}\n\n/**\n * The record a purposed conversation works on: the entity class as the record's `objectType` and its id. The server\n * checks both (a record the user cannot read answers 404).\n */\nexport interface PurposeSubject {\n /** generic — the record's entity class, e.g. `App\\\\Domain\\\\Support\\\\Entities\\\\Tickets\\\\SupportTicket` */\n entityClass: string;\n /** generic */\n entityId: number;\n}\n\n/** The start of a purposed conversation (`startPurpose`). */\nexport interface PurposeStartRequest {\n /** generic — the purpose's name, e.g. `Support.AnswerTicket` */\n purposeId: string;\n /** generic — the space the purpose runs in; omitted when the application's route answers its own space */\n agentSpaceKey?: number;\n /** generic — with a subject the open conversation of the same space, purpose and record is reopened */\n subject?: PurposeSubject;\n /** generic — text added to the kickoff of a NEW conversation (at most 4,000 characters) */\n prefill?: string;\n}\n\n/** The conversation a purposed start opened or reopened; the client opens it by its id. */\nexport interface StartedPurposeConversation {\n /** generic */\n conversationId: number;\n /** generic — the open conversation of the same space, purpose (and subject) was reopened */\n resumedExisting: boolean;\n /** generic — the prefill reached the kickoff (false on a reopen and without a prefill) */\n prefillDelivered: boolean;\n}\n\n/** The answer of a post: the conversation's messages so far (the reply arrives through live updates). */\nexport interface PostedMessage {\n /** generic */\n messages: AgentsConversationMessage[];\n}\n\n/** A model-visible, owner-invisible note into a conversation (a widget click, a render report, a correction). */\n/**\n * What the owner's client shows while the owner writes: the route, its parameters, the record on screen and the tab.\n * Sent with a start, a posted message and an injected signal; the server stores it on that owner row and the agent reads\n * the newest one as one line beside the owner's newest message. Each field is optional and capped\n * ({@link AGENTS_CLIENT_CONTEXT_LIMITS}); the server refuses a request with a field over its cap (HTTP 400).\n */\nexport interface AgentsClientContext {\n /** The path of the route the client shows, e.g. `/tickets/42`. */\n routePath?: string | null;\n /** The parameters of that route by name, values as text. */\n routeParameters?: Record<string, string> | null;\n /** The kind of the record on screen, as the application names it, e.g. `ticket`. */\n recordKind?: string | null;\n /** The id of the record on screen. */\n recordId?: string | number | null;\n /** The tab the client shows. */\n tab?: string | null;\n}\n\n/** The caps of {@link AgentsClientContext} (characters; the route parameters as their `name=value&…` text). */\nexport const AGENTS_CLIENT_CONTEXT_LIMITS = {\n routePathChars: 512,\n routeParametersChars: 512,\n routeParameterCount: 20,\n recordKindChars: 64,\n recordIdChars: 128,\n tabChars: 64,\n} as const;\n\nexport interface ConversationSignal {\n /** generic */\n text: string;\n /** generic — the signal source; the server's default applies when omitted (a widget click) */\n source?: string;\n}\n\n/** How a list read pages and which conversations it includes. */\nexport interface ConversationListQueryOptions {\n /** generic — include conversations that have no summary (title) yet, e.g. a just-started one */\n includeUnsummarized?: boolean;\n /** generic — the host application's history reads the newest 50 */\n paging?: { top?: number; skip?: number };\n}\n\n/** The size of a search answer. */\nexport interface ConversationSearchOptions {\n /** generic — the most groups (or hits) returned; the host application's chat asks for 10 */\n limit?: number;\n /** generic — the excerpt length in characters; the host application's chat asks for 420 */\n excerptLength?: number;\n}\n\n/** app extension — the reconstructed request a model call was sent with (the admin details panel); opaque data. */\nexport type ConversationMessageSentPayload = unknown[];\n\n/** One matched message of a message search (`SemanticSearchHit`). */\nexport interface ConversationMessageSearchHit {\n /** generic */\n messageId: number | null;\n /** generic */\n conversationId: number | null;\n /** generic */\n indexInConversation: number | null;\n /** generic */\n role: string | null;\n /** generic */\n excerpt: string;\n /** generic */\n relevance: number;\n /** generic */\n created: string | null;\n /** generic */\n updated: string | null;\n /** generic — the conversation's title */\n title: string | null;\n}\n\n/** One conversation of a search across conversations, with its matched messages (`AIConversationSearchGroup`). */\nexport interface ConversationSearchGroup {\n /** generic */\n conversationId: number | null;\n /** generic */\n title: string | null;\n /** generic */\n summary: string | null;\n /** generic */\n created: string | null;\n /** generic */\n updated: string | null;\n /** generic */\n relevance: number;\n /** generic */\n hits: ConversationMessageSearchHit[];\n}\n\n/** One generated line of what the agent is doing (`AgentActivityLine`). */\nexport interface ConversationActivityElement {\n /** generic — the row the line narrates; the merge key */\n toolCallMessageId: number;\n /** generic */\n batchId: string | null;\n /** generic */\n state: \"queued\" | \"running\" | \"finished\" | \"failed\" | \"skipped\" | null;\n /** generic */\n kind: \"tool\" | \"delegation\" | \"background\" | \"long\" | \"turnStart\" | null;\n /** generic */\n childCount: number | null;\n /** generic — the 1-based delegation helper that ran the step; null for the assistant's own steps */\n helperIndex: number | null;\n /** generic — the sentence; null while the narrator has not answered */\n line: string | null;\n}\n\n/** The activity of one turn (`GET …/activity`). */\nexport interface ConversationActivity {\n /** generic — the message that started the narrated turn */\n turnMessageId: number | null;\n /** generic */\n turnRunning: boolean;\n /** generic */\n elements: ConversationActivityElement[];\n}\n\n/** A model the owner (host application: an impersonating admin) may pick for the next turns (`AgentCustomerSelectableModel`). */\nexport interface SelectableModel {\n /** generic — the name a send carries */\n name: string;\n /** generic */\n displayName: string;\n /** generic */\n description: string;\n /** generic */\n strengthLevel: number | null;\n /** generic */\n speedLevel: number | null;\n /** app extension — the host application's credit multiplier of the model */\n creditsMultiplier?: number | null;\n}\n\n// ── Live updates ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * What a live update carries: a claim check, never content. The chat reads the conversation again when\n * `changeCounter` advances, at once on a terminal status, and until `lastMessageId` is loaded.\n */\nexport interface ConversationChangeSignal {\n /** generic — advances on every change of the conversation */\n changeCounter: number;\n /** generic — the newest message the server wrote; null before the first */\n lastMessageId: number | null;\n /** generic */\n runStatus: ConversationRunStatus | null;\n /** generic — advances when the title or summary was generated again (a light metadata read is enough then) */\n summaryUpdatedAt: number | null;\n /**\n * generic — the binding produced this emission from a run-state read, not from a pushed change (a binding without\n * push, or a push transport whose path is not proven readable, or a check that corrects a stale status). It carries\n * only `runStatus` as news: `changeCounter`, `lastMessageId` and `summaryUpdatedAt` repeat the last pushed values\n * (before any push: a counter that counts down from -1, never equal to a pushed one). The package sets the status\n * from it and reads the conversation again on a status change while the push path is not alive (`isPushPathAlive`).\n */\n isStatusCheck?: boolean;\n /**\n * generic, on a status-check emission — the binding's push path delivers: a pushed change arrived and the path was not\n * denied since. False after a denied read until a push arrives again; then the status checks are the live path and a\n * status change reads the conversation again. A binding without push leaves it out: the package then counts the\n * pushed changes it saw itself.\n */\n isPushPathAlive?: boolean;\n}\n\n/** Why a subscription ended for good: the conversation was deleted or is no longer readable, or the account lost access. */\nexport type ConversationSubscriptionEndReason = \"gone\" | \"forbidden\";\n\n// ── Errors ───────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * What went wrong, as the chat tells the owner. The codes the chat's error handling reads today map\n * onto it: `AI_BUDGET_REACHED` → `budget`, HTTP 429 / `RATE_LIMIT_EXCEEDED` → `rateLimit`, `CONVERSATION_CLOSED` →\n * `closed`, the not-found and no-access answers → `notFound` / `forbidden` (`conversation-not-found.ts`), no answer or a\n * server failure → `network`, everything else (a refused retry, a cancelled request) → `other` with its `code`.\n */\nexport type AgentsClientErrorKind = \"budget\" | \"rateLimit\" | \"closed\" | \"notFound\" | \"forbidden\" | \"network\" | \"other\";\n\n/** The code `other` carries for a request the client cancelled; the chat shows no error card for it. */\nexport const AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED = \"REQUEST_ABORTED\";\n\n/** The one error shape every port function rejects with. */\nexport class AgentsClientError extends Error {\n readonly kind: AgentsClientErrorKind;\n /** The server's stable error code, or the client's own code (`REQUEST_ABORTED`); null when none arrived. */\n readonly code: string | null;\n /** Seconds until a quota frees up again; set only for `rateLimit`. */\n readonly retryAfterSeconds: number | null;\n /** The HTTP status when one arrived (not part of the contract's shape; kept for diagnostics). */\n readonly httpStatus: number | null;\n\n constructor(\n kind: AgentsClientErrorKind,\n details: { message?: string; code?: string | null; retryAfterSeconds?: number | null; httpStatus?: number | null } = {},\n ) {\n super(details.message ?? kind);\n this.name = \"AgentsClientError\";\n this.kind = kind;\n this.code = details.code ?? null;\n this.retryAfterSeconds = kind === \"rateLimit\" ? (details.retryAfterSeconds ?? null) : null;\n this.httpStatus = details.httpStatus ?? null;\n }\n}\n\nexport const isAgentsClientError = (value: unknown): value is AgentsClientError => value instanceof AgentsClientError;\n"],"names":[],"mappings":";AAiDO,MAAM,oDAAqF;AAAA,EAChG;AAAA,EACA;AACF;AAGO,MAAM,sCAAsC,CACjD,aACiC;AACjC,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI,aAAa,SAAU,QAAO;AAClC,MAAI,aAAa,aAAa,aAAa,wBAAwB,aAAa,SAAU,QAAO;AACjG,SAAO;AACT;AAuQO,MAAM,+BAA+B;AAAA,EAC1C,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,UAAU;AACZ;AA8JO,MAAM,2CAA2C;AAGjD,MAAM,0BAA0B,MAAM;AAAA,EAS3C,YACE,MACA,UAAqH,IACrH;AACA,UAAM,QAAQ,WAAW,IAAI;AAC7B,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,oBAAoB,SAAS,cAAe,QAAQ,qBAAqB,OAAQ;AACtF,SAAK,aAAa,QAAQ,cAAc;AAAA,EAC1C;AACF;AAEO,MAAM,sBAAsB,CAAC,UAA+C,iBAAiB;"}
|
|
@@ -232,6 +232,7 @@ class PollingAgentsConversationClient {
|
|
|
232
232
|
this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);
|
|
233
233
|
this.getConversationRunState = binding.getConversationRunState?.bind(binding);
|
|
234
234
|
this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);
|
|
235
|
+
this.startPurpose = binding.startPurpose?.bind(binding);
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
238
|
const withPollingChangeSubscription = (client, options) => {
|
|
@@ -253,4 +254,4 @@ export {
|
|
|
253
254
|
readPolledRunStatus as r,
|
|
254
255
|
withPollingChangeSubscription as w
|
|
255
256
|
};
|
|
256
|
-
//# sourceMappingURL=withPollingChangeSubscription-
|
|
257
|
+
//# sourceMappingURL=withPollingChangeSubscription-mWdchMOH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withPollingChangeSubscription-CnQnubfK.js","sources":["../../src/client/polling/createPollingConversationChangeSubscription.ts","../../src/client/polling/withPollingChangeSubscription.ts"],"sourcesContent":["import {\n type ConversationChangeSignal,\n type ConversationRunStateRead,\n type ConversationRunStatus,\n type ConversationSubscriptionEndReason,\n CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,\n isAgentsClientError,\n readConversationRunStatusOfRunState,\n} from \"../../contract/conversation\";\n\n/** Read interval while a turn runs (or right after a local send). */\nexport const POLLING_RUNNING_INTERVAL_MS = 2_000;\n/** Read interval while the conversation is idle or failed. */\nexport const POLLING_IDLE_INTERVAL_MS = 20_000;\n/** Ceiling of the exponential backoff after failed reads. */\nexport const POLLING_MAX_BACKOFF_MS = 60_000;\n/**\n * How long after a local send the poller keeps the running interval although the conversation still reads idle: the\n * server may store the owner's message before it marks the turn as running.\n */\nexport const POLLING_LOCAL_ACTIVITY_WINDOW_MS = 10_000;\n\n/**\n * Reads a conversation's run state — the port's `getConversationRunState`, or its `getConversationMetadata` (every\n * conversation carries the fields the poller reads).\n */\nexport type ConversationMetadataReader = (conversationId: number) => Promise<ConversationRunStateRead>;\n\n/** The timer functions the poller uses; a spec hands in fake ones. */\nexport interface PollingTimers {\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (timerHandle: unknown) => void;\n now: () => number;\n}\n\n/** Whether the page is hidden, and a way to hear when that changes; a spec hands in its own. */\nexport interface PollingDocumentVisibility {\n isHidden: () => boolean;\n /** Calls `listener` on every visibility change; returns the function that stops it. */\n listen: (listener: () => void) => () => void;\n}\n\nexport interface PollingConversationChangeSubscriptionOptions {\n /** Default `POLLING_RUNNING_INTERVAL_MS` (2 s). */\n runningIntervalMs?: number;\n /** Default `POLLING_IDLE_INTERVAL_MS` (20 s). */\n idleIntervalMs?: number;\n /** Default `POLLING_MAX_BACKOFF_MS` (60 s). */\n maxBackoffMs?: number;\n /** Default `POLLING_LOCAL_ACTIVITY_WINDOW_MS` (10 s). */\n localActivityWindowMs?: number;\n /** Default: the global `setTimeout` / `clearTimeout` and `Date.now`. */\n timers?: PollingTimers;\n /** Default: the browser `document`; `null` = the page counts as always visible (no `document`, a worker). */\n documentVisibility?: PollingDocumentVisibility | null;\n}\n\n/**\n * The polling default of the live updates: the port's `subscribeToConversationChanges` plus\n * `notifyLocalActivity`, which `withPollingChangeSubscription` calls after every send the server accepted.\n */\nexport interface PollingConversationChangeSubscription {\n subscribeToConversationChanges: (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ) => () => void;\n /** Reads the conversation's metadata now and keeps the running interval for the local-activity window. */\n notifyLocalActivity: (conversationId: number) => void;\n}\n\ninterface ResolvedPollingOptions {\n runningIntervalMs: number;\n idleIntervalMs: number;\n maxBackoffMs: number;\n localActivityWindowMs: number;\n timers: PollingTimers;\n documentVisibility: PollingDocumentVisibility | null;\n}\n\n/** The global timer functions, looked up on each call (so a spec's fake timers installed later still apply). */\nclass GlobalPollingTimers implements PollingTimers {\n setTimeout = (callback: () => void, delayMs: number): unknown => globalThis.setTimeout(callback, delayMs);\n\n clearTimeout = (timerHandle: unknown): void => globalThis.clearTimeout(timerHandle as ReturnType<typeof setTimeout>);\n\n now = (): number => Date.now();\n}\n\n/** The browser document's `visibilityState` and `visibilitychange` event. */\nclass BrowserDocumentVisibility implements PollingDocumentVisibility {\n constructor(protected readonly browserDocument: Document) {}\n\n isHidden = (): boolean => this.browserDocument.visibilityState === \"hidden\";\n\n listen = (listener: () => void): (() => void) => {\n this.browserDocument.addEventListener(\"visibilitychange\", listener);\n return this.browserDocument.removeEventListener.bind(this.browserDocument, \"visibilitychange\", listener);\n };\n}\n\n/**\n * The three-value run status a polled read reports: the stored run state, and \"running\" for an idle conversation the\n * server owes a turn (`agentTurnOwedAt`), as the chat's own derivation does.\n */\nexport const readPolledRunStatus = (\n conversation: Pick<ConversationRunStateRead, \"runState\" | \"agentTurnOwedAt\">,\n): ConversationRunStatus | null => {\n const runStatus = readConversationRunStatusOfRunState(conversation.runState);\n return runStatus === \"idle\" && conversation.agentTurnOwedAt ? \"running\" : runStatus;\n};\n\n/** The end of a subscription a failed read means: a vanished conversation or lost access; null for a passing failure. */\nconst readSubscriptionEndReasonOfReadFailure = (failure: unknown): ConversationSubscriptionEndReason | null => {\n if (!isAgentsClientError(failure)) return null;\n if (failure.kind === \"notFound\") return \"gone\";\n if (failure.kind === \"forbidden\") return \"forbidden\";\n return null;\n};\n\n/**\n * One subscription: reads the conversation's metadata on a timer and turns each read into the change signal.\n *\n * Numbering (the signal leaves it open; the metadata carries no server change counter): the poller keeps its own counter. It\n * starts at 0 with the first read and advances by one whenever a read differs from the previous one in the run status,\n * `lastMessageId` or `updated` — so every polled signal is an ordinary change signal (no `isStatusCheck`) and the\n * package rules apply unchanged: an advance reads the changed tail (throttled), a terminal status reads at once,\n * re-reads the metadata and converges on `lastMessageId`. A status check would carry only the run status as news and\n * would miss a new message under an unchanged status. Without `lastMessageId` in the metadata every poll of a running\n * turn counts as a change (the changed tail is read every poll). `summaryUpdatedAt` is a second local counter that\n * advances when `title` or `summary` changed. A read with no change emits nothing.\n */\nclass ConversationMetadataPoller {\n protected isStopped = false;\n protected isReading = false;\n protected readAgainAfterCurrentRead = false;\n protected timerHandle: unknown = null;\n protected consecutiveFailedReads = 0;\n protected changeCounter = 0;\n protected summaryRevision = 0;\n protected previousChangeFingerprint: string | null = null;\n protected previousSummaryFingerprint: string | null = null;\n protected runStatus: ConversationRunStatus | null = null;\n protected hasConversationEnded = false;\n protected runningIntervalUntil = 0;\n protected stopListeningToVisibility: (() => void) | null = null;\n\n constructor(\n readonly conversationId: number,\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly onSignal: (signal: ConversationChangeSignal) => void,\n protected readonly onEnded: (reason: ConversationSubscriptionEndReason) => void,\n protected readonly options: ResolvedPollingOptions,\n protected readonly activePollers: Set<ConversationMetadataPoller>,\n ) {}\n\n start = (): void => {\n this.activePollers.add(this);\n this.stopListeningToVisibility = this.options.documentVisibility?.listen(this.receiveVisibilityChange) ?? null;\n this.readNow();\n };\n\n /** The unsubscribe: no read, no timer and no signal after it; a read in flight is dropped. */\n stop = (): void => {\n this.isStopped = true;\n this.activePollers.delete(this);\n this.clearTimer();\n this.stopListeningToVisibility?.();\n this.stopListeningToVisibility = null;\n };\n\n receiveLocalActivity = (): void => {\n this.runningIntervalUntil = this.options.timers.now() + this.options.localActivityWindowMs;\n this.readNow();\n };\n\n /** Reads now; a read already in flight is followed by one more read instead (two reads never overlap). */\n protected readNow = (): void => {\n if (this.isStopped) return;\n if (this.isReading) {\n this.readAgainAfterCurrentRead = true;\n return;\n }\n this.clearTimer();\n this.isReading = true;\n void this.readMetadataOnce();\n };\n\n protected async readMetadataOnce(): Promise<void> {\n let conversation: ConversationRunStateRead;\n try {\n conversation = await this.readMetadata(this.conversationId);\n } catch (failure) {\n this.isReading = false;\n this.receiveReadFailure(failure);\n return;\n }\n this.isReading = false;\n if (this.isStopped) return;\n this.consecutiveFailedReads = 0;\n this.receiveConversation(conversation);\n this.continueAfterRead(this.readIntervalMs());\n }\n\n protected receiveConversation(conversation: ConversationRunStateRead): void {\n const runStatus = readPolledRunStatus(conversation);\n const reportsLastMessageId = conversation.lastMessageId !== undefined;\n const changeFingerprint = JSON.stringify([runStatus, conversation.lastMessageId ?? null, conversation.updated]);\n const summaryFingerprint = JSON.stringify([conversation.title, conversation.summary]);\n const isFirstRead = this.previousChangeFingerprint === null;\n const hasChanged =\n changeFingerprint !== this.previousChangeFingerprint || (!reportsLastMessageId && runStatus === \"running\");\n const hasSummaryChanged = !isFirstRead && summaryFingerprint !== this.previousSummaryFingerprint;\n if (!isFirstRead && hasChanged) this.changeCounter += 1;\n if (hasSummaryChanged) this.summaryRevision += 1;\n this.previousChangeFingerprint = changeFingerprint;\n this.previousSummaryFingerprint = summaryFingerprint;\n this.runStatus = runStatus;\n this.hasConversationEnded =\n conversation.runState !== null && CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION.includes(conversation.runState);\n if (!isFirstRead && !hasChanged && !hasSummaryChanged) return;\n this.onSignal({\n changeCounter: this.changeCounter,\n lastMessageId: conversation.lastMessageId ?? null,\n runStatus,\n summaryUpdatedAt: this.summaryRevision,\n });\n }\n\n protected receiveReadFailure(failure: unknown): void {\n if (this.isStopped) return;\n const endReason = readSubscriptionEndReasonOfReadFailure(failure);\n if (endReason !== null) {\n this.stop();\n this.onEnded(endReason);\n return;\n }\n this.consecutiveFailedReads += 1;\n const backoffMs = this.readIntervalMs() * 2 ** this.consecutiveFailedReads;\n this.continueAfterRead(Math.min(backoffMs, this.options.maxBackoffMs));\n }\n\n protected continueAfterRead(nextReadDelayMs: number): void {\n if (this.readAgainAfterCurrentRead) {\n this.readAgainAfterCurrentRead = false;\n this.readNow();\n return;\n }\n // A completed or cancelled conversation changes no more: only a local send or the page's return reads it again.\n if (this.hasConversationEnded) return;\n this.scheduleRead(nextReadDelayMs);\n }\n\n protected readIntervalMs(): number {\n const isShortIntervalDue = this.runStatus === \"running\" || this.options.timers.now() < this.runningIntervalUntil;\n return isShortIntervalDue ? this.options.runningIntervalMs : this.options.idleIntervalMs;\n }\n\n /** Arms the next read — not while the page is hidden; its return reads at once. */\n protected scheduleRead(delayMs: number): void {\n this.clearTimer();\n if (this.isStopped || this.options.documentVisibility?.isHidden()) return;\n this.timerHandle = this.options.timers.setTimeout(this.readOnTimer, delayMs);\n }\n\n protected readOnTimer = (): void => {\n this.timerHandle = null;\n this.readNow();\n };\n\n protected receiveVisibilityChange = (): void => {\n if (this.isStopped) return;\n if (this.options.documentVisibility?.isHidden()) {\n this.clearTimer();\n return;\n }\n this.readNow();\n };\n\n protected clearTimer(): void {\n if (this.timerHandle === null) return;\n this.options.timers.clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n}\n\n/** Every subscription of one polling default; `notifyLocalActivity` reaches the subscriptions of a conversation. */\nclass PollingConversationChangeSubscriptions implements PollingConversationChangeSubscription {\n protected readonly activePollers = new Set<ConversationMetadataPoller>();\n\n constructor(\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly options: ResolvedPollingOptions,\n ) {}\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => {\n const poller = new ConversationMetadataPoller(\n conversationId,\n this.readMetadata,\n onSignal,\n onEnded,\n this.options,\n this.activePollers,\n );\n poller.start();\n return poller.stop;\n };\n\n notifyLocalActivity = (conversationId: number): void => {\n for (const poller of [...this.activePollers]) {\n if (poller.conversationId === conversationId) poller.receiveLocalActivity();\n }\n };\n}\n\nconst readDefaultDocumentVisibility = (): PollingDocumentVisibility | null =>\n typeof document === \"undefined\" ? null : new BrowserDocumentVisibility(document);\n\n/**\n * The polling default of `subscribeToConversationChanges` over a metadata read: every 2 s while a turn\n * runs, every 20 s while idle, at once after `notifyLocalActivity`; paused while the page is hidden and read once when\n * it shows again; exponential backoff on failed reads up to 60 s; a `notFound` / `forbidden` read ends the subscription\n * with `gone` / `forbidden`. One poller per subscription; see `ConversationMetadataPoller` for how a read becomes a\n * signal.\n */\nexport const createPollingConversationChangeSubscription = (\n readMetadata: ConversationMetadataReader,\n options: PollingConversationChangeSubscriptionOptions = {},\n): PollingConversationChangeSubscription =>\n new PollingConversationChangeSubscriptions(readMetadata, {\n runningIntervalMs: options.runningIntervalMs ?? POLLING_RUNNING_INTERVAL_MS,\n idleIntervalMs: options.idleIntervalMs ?? POLLING_IDLE_INTERVAL_MS,\n maxBackoffMs: options.maxBackoffMs ?? POLLING_MAX_BACKOFF_MS,\n localActivityWindowMs: options.localActivityWindowMs ?? POLLING_LOCAL_ACTIVITY_WINDOW_MS,\n timers: options.timers ?? new GlobalPollingTimers(),\n documentVisibility: options.documentVisibility === undefined ? readDefaultDocumentVisibility() : options.documentVisibility,\n });\n","import type { AgentsConversationClient } from \"../AgentsConversationClient\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n AgentsConversation,\n ChangedConversationMessages,\n ChangedMessagesRequest,\n ConversationActivity,\n ConversationAttachmentReference,\n ConversationChangeSignal,\n ConversationListQueryOptions,\n ConversationMessageSearchHit,\n ConversationMessageSentPayload,\n ConversationMessagesPage,\n ConversationRunStateRead,\n ConversationSearchGroup,\n ConversationSearchOptions,\n ConversationSignal,\n ConversationSubscriptionEndReason,\n PostedMessage,\n SelectableModel,\n StartedConversation,\n} from \"../../contract/conversation\";\nimport {\n createPollingConversationChangeSubscription,\n type PollingConversationChangeSubscription,\n type PollingConversationChangeSubscriptionOptions,\n} from \"./createPollingConversationChangeSubscription\";\n\n/** A conversation client whose `subscribeToConversationChanges` is present. */\nexport type AgentsConversationClientWithChangeSubscription = AgentsConversationClient &\n Required<Pick<AgentsConversationClient, \"subscribeToConversationChanges\">>;\n\n/**\n * A binding without push, with the polling default as its subscription. Every port function goes to the binding; the\n * three that make the server start a turn on an existing conversation (post, signal, retry) tell the poller once the\n * server accepted them, so the first read does not wait for the idle interval. A start needs no notice: the chat\n * subscribes to the new conversation afterwards, and a subscription reads at once.\n */\nclass PollingAgentsConversationClient implements AgentsConversationClientWithChangeSubscription {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n readonly composeSentMessageText?: (text: string, attachments: ConversationAttachmentReference[] | undefined) => string;\n readonly getMessageSentPayload?: (conversationId: number, messageId: number) => Promise<ConversationMessageSentPayload>;\n readonly getConversationRunState?: (conversationId: number) => Promise<ConversationRunStateRead>;\n readonly getAccountRealtimeMessages?: (clientId?: string) => Promise<AccountRealtimeRead>;\n\n constructor(\n protected readonly binding: AgentsConversationClient,\n protected readonly polling: PollingConversationChangeSubscription,\n ) {\n // The optional functions exist exactly when the binding has them (the chat reads their presence).\n this.getSelectableModels = binding.getSelectableModels?.bind(binding);\n this.composeSentMessageText = binding.composeSentMessageText?.bind(binding);\n this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);\n this.getConversationRunState = binding.getConversationRunState?.bind(binding);\n this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);\n }\n\n getConversationMetadata = (conversationId: number): Promise<AgentsConversation> =>\n this.binding.getConversationMetadata(conversationId);\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getNewestMessagesPage(conversationId, pageSize);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getOlderMessagesPage(conversationId, beforeIndex, pageSize);\n\n getChangedMessages = (conversationId: number, request: ChangedMessagesRequest): Promise<ChangedConversationMessages> =>\n this.binding.getChangedMessages(conversationId, request);\n\n startConversation = (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> =>\n this.binding.startConversation(request);\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const postedMessage = await this.binding.postMessage(conversationId, message);\n this.polling.notifyLocalActivity(conversationId);\n return postedMessage;\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.binding.injectSignal(conversationId, signal);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.binding.retryConversation(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n renameConversation = (conversationId: number, title: string): Promise<AgentsConversation> =>\n this.binding.renameConversation(conversationId, title);\n\n deleteConversation = (conversationId: number): Promise<void> => this.binding.deleteConversation(conversationId);\n\n listConversations = (agentSpaceKey: number, options?: ConversationListQueryOptions): Promise<AgentsConversation[]> =>\n this.binding.listConversations(agentSpaceKey, options);\n\n searchConversations = (text: string, options?: ConversationSearchOptions): Promise<ConversationSearchGroup[]> =>\n this.binding.searchConversations(text, options);\n\n searchConversationMessages = (\n conversationId: number,\n text: string,\n options?: ConversationSearchOptions,\n ): Promise<ConversationMessageSearchHit[]> => this.binding.searchConversationMessages(conversationId, text, options);\n\n getConversationActivity = (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> =>\n this.binding.getConversationActivity(conversationId, turnMessageId);\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => this.polling.subscribeToConversationChanges(conversationId, onSignal, onEnded);\n}\n\n/**\n * The client with live updates: a client that brings its own `subscribeToConversationChanges` (a push\n * transport — the host application's Firebase binding) is returned as it is; any other gets the polling default over its\n * `getConversationRunState` when it has one, else over its `getConversationMetadata`\n * (`createPollingConversationChangeSubscription`, `options` tune the intervals). A post, a signal or a retry the server\n * accepted reads at once. The default `AgentChat` calls this by itself.\n */\nexport const withPollingChangeSubscription = (\n client: AgentsConversationClient,\n options?: PollingConversationChangeSubscriptionOptions,\n): AgentsConversationClientWithChangeSubscription => {\n if (client.subscribeToConversationChanges) return client as AgentsConversationClientWithChangeSubscription;\n return new PollingAgentsConversationClient(\n client,\n createPollingConversationChangeSubscription(\n client.getConversationRunState ? client.getConversationRunState.bind(client) : client.getConversationMetadata.bind(client),\n options,\n ),\n );\n};\n"],"names":[],"mappings":";;AAWO,MAAM,8BAA8B;AAEpC,MAAM,2BAA2B;AAEjC,MAAM,yBAAyB;AAK/B,MAAM,mCAAmC;AA6DhD,MAAM,oBAA6C;AAAA,EAAnD,cAAA;AACE,SAAA,aAAa,CAAC,UAAsB,YAA6B,WAAW,WAAW,UAAU,OA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BACA,MACA,YAC4C,KAAK,QAAQ,2BAA2B,gBAAgB,MAAM,OAAO;AAEnH,SAAA,0BAA0B,CAAC,gBAAwB,kBACjD,KAAK,QAAQ,wBAAwB,gBAAgB,aAAa;AAEpE,SAAA,iCAAiC,CAC/B,gBACA,UACA,YACiB,KAAK,QAAQ,+BAA+B,gBAAgB,UAAU,OAAO;AAjE9F,SAAK,sBAAsB,QAAQ,qBAAqB,KAAK,OAAO;AACpE,SAAK,yBAAyB,QAAQ,wBAAwB,KAAK,OAAO;AAC1E,SAAK,wBAAwB,QAAQ,uBAAuB,KAAK,OAAO;AACxE,SAAK,0BAA0B,QAAQ,yBAAyB,KAAK,OAAO;AAC5E,SAAK,6BAA6B,QAAQ,4BAA4B,KAAK,OAAO;AAAA,EACpF;AA6DF;AASO,MAAM,gCAAgC,CAC3C,QACA,YACmD;AACnD,MAAI,OAAO,+BAAgC,QAAO;AAClD,SAAO,IAAI;AAAA,IACT;AAAA,IACA;AAAA,MACE,OAAO,0BAA0B,OAAO,wBAAwB,KAAK,MAAM,IAAI,OAAO,wBAAwB,KAAK,MAAM;AAAA,MACzH;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"withPollingChangeSubscription-mWdchMOH.js","sources":["../../src/client/polling/createPollingConversationChangeSubscription.ts","../../src/client/polling/withPollingChangeSubscription.ts"],"sourcesContent":["import {\n type ConversationChangeSignal,\n type ConversationRunStateRead,\n type ConversationRunStatus,\n type ConversationSubscriptionEndReason,\n CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,\n isAgentsClientError,\n readConversationRunStatusOfRunState,\n} from \"../../contract/conversation\";\n\n/** Read interval while a turn runs (or right after a local send). */\nexport const POLLING_RUNNING_INTERVAL_MS = 2_000;\n/** Read interval while the conversation is idle or failed. */\nexport const POLLING_IDLE_INTERVAL_MS = 20_000;\n/** Ceiling of the exponential backoff after failed reads. */\nexport const POLLING_MAX_BACKOFF_MS = 60_000;\n/**\n * How long after a local send the poller keeps the running interval although the conversation still reads idle: the\n * server may store the owner's message before it marks the turn as running.\n */\nexport const POLLING_LOCAL_ACTIVITY_WINDOW_MS = 10_000;\n\n/**\n * Reads a conversation's run state — the port's `getConversationRunState`, or its `getConversationMetadata` (every\n * conversation carries the fields the poller reads).\n */\nexport type ConversationMetadataReader = (conversationId: number) => Promise<ConversationRunStateRead>;\n\n/** The timer functions the poller uses; a spec hands in fake ones. */\nexport interface PollingTimers {\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (timerHandle: unknown) => void;\n now: () => number;\n}\n\n/** Whether the page is hidden, and a way to hear when that changes; a spec hands in its own. */\nexport interface PollingDocumentVisibility {\n isHidden: () => boolean;\n /** Calls `listener` on every visibility change; returns the function that stops it. */\n listen: (listener: () => void) => () => void;\n}\n\nexport interface PollingConversationChangeSubscriptionOptions {\n /** Default `POLLING_RUNNING_INTERVAL_MS` (2 s). */\n runningIntervalMs?: number;\n /** Default `POLLING_IDLE_INTERVAL_MS` (20 s). */\n idleIntervalMs?: number;\n /** Default `POLLING_MAX_BACKOFF_MS` (60 s). */\n maxBackoffMs?: number;\n /** Default `POLLING_LOCAL_ACTIVITY_WINDOW_MS` (10 s). */\n localActivityWindowMs?: number;\n /** Default: the global `setTimeout` / `clearTimeout` and `Date.now`. */\n timers?: PollingTimers;\n /** Default: the browser `document`; `null` = the page counts as always visible (no `document`, a worker). */\n documentVisibility?: PollingDocumentVisibility | null;\n}\n\n/**\n * The polling default of the live updates: the port's `subscribeToConversationChanges` plus\n * `notifyLocalActivity`, which `withPollingChangeSubscription` calls after every send the server accepted.\n */\nexport interface PollingConversationChangeSubscription {\n subscribeToConversationChanges: (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ) => () => void;\n /** Reads the conversation's metadata now and keeps the running interval for the local-activity window. */\n notifyLocalActivity: (conversationId: number) => void;\n}\n\ninterface ResolvedPollingOptions {\n runningIntervalMs: number;\n idleIntervalMs: number;\n maxBackoffMs: number;\n localActivityWindowMs: number;\n timers: PollingTimers;\n documentVisibility: PollingDocumentVisibility | null;\n}\n\n/** The global timer functions, looked up on each call (so a spec's fake timers installed later still apply). */\nclass GlobalPollingTimers implements PollingTimers {\n setTimeout = (callback: () => void, delayMs: number): unknown => globalThis.setTimeout(callback, delayMs);\n\n clearTimeout = (timerHandle: unknown): void => globalThis.clearTimeout(timerHandle as ReturnType<typeof setTimeout>);\n\n now = (): number => Date.now();\n}\n\n/** The browser document's `visibilityState` and `visibilitychange` event. */\nclass BrowserDocumentVisibility implements PollingDocumentVisibility {\n constructor(protected readonly browserDocument: Document) {}\n\n isHidden = (): boolean => this.browserDocument.visibilityState === \"hidden\";\n\n listen = (listener: () => void): (() => void) => {\n this.browserDocument.addEventListener(\"visibilitychange\", listener);\n return this.browserDocument.removeEventListener.bind(this.browserDocument, \"visibilitychange\", listener);\n };\n}\n\n/**\n * The three-value run status a polled read reports: the stored run state, and \"running\" for an idle conversation the\n * server owes a turn (`agentTurnOwedAt`), as the chat's own derivation does.\n */\nexport const readPolledRunStatus = (\n conversation: Pick<ConversationRunStateRead, \"runState\" | \"agentTurnOwedAt\">,\n): ConversationRunStatus | null => {\n const runStatus = readConversationRunStatusOfRunState(conversation.runState);\n return runStatus === \"idle\" && conversation.agentTurnOwedAt ? \"running\" : runStatus;\n};\n\n/** The end of a subscription a failed read means: a vanished conversation or lost access; null for a passing failure. */\nconst readSubscriptionEndReasonOfReadFailure = (failure: unknown): ConversationSubscriptionEndReason | null => {\n if (!isAgentsClientError(failure)) return null;\n if (failure.kind === \"notFound\") return \"gone\";\n if (failure.kind === \"forbidden\") return \"forbidden\";\n return null;\n};\n\n/**\n * One subscription: reads the conversation's metadata on a timer and turns each read into the change signal.\n *\n * Numbering (the signal leaves it open; the metadata carries no server change counter): the poller keeps its own counter. It\n * starts at 0 with the first read and advances by one whenever a read differs from the previous one in the run status,\n * `lastMessageId` or `updated` — so every polled signal is an ordinary change signal (no `isStatusCheck`) and the\n * package rules apply unchanged: an advance reads the changed tail (throttled), a terminal status reads at once,\n * re-reads the metadata and converges on `lastMessageId`. A status check would carry only the run status as news and\n * would miss a new message under an unchanged status. Without `lastMessageId` in the metadata every poll of a running\n * turn counts as a change (the changed tail is read every poll). `summaryUpdatedAt` is a second local counter that\n * advances when `title` or `summary` changed. A read with no change emits nothing.\n */\nclass ConversationMetadataPoller {\n protected isStopped = false;\n protected isReading = false;\n protected readAgainAfterCurrentRead = false;\n protected timerHandle: unknown = null;\n protected consecutiveFailedReads = 0;\n protected changeCounter = 0;\n protected summaryRevision = 0;\n protected previousChangeFingerprint: string | null = null;\n protected previousSummaryFingerprint: string | null = null;\n protected runStatus: ConversationRunStatus | null = null;\n protected hasConversationEnded = false;\n protected runningIntervalUntil = 0;\n protected stopListeningToVisibility: (() => void) | null = null;\n\n constructor(\n readonly conversationId: number,\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly onSignal: (signal: ConversationChangeSignal) => void,\n protected readonly onEnded: (reason: ConversationSubscriptionEndReason) => void,\n protected readonly options: ResolvedPollingOptions,\n protected readonly activePollers: Set<ConversationMetadataPoller>,\n ) {}\n\n start = (): void => {\n this.activePollers.add(this);\n this.stopListeningToVisibility = this.options.documentVisibility?.listen(this.receiveVisibilityChange) ?? null;\n this.readNow();\n };\n\n /** The unsubscribe: no read, no timer and no signal after it; a read in flight is dropped. */\n stop = (): void => {\n this.isStopped = true;\n this.activePollers.delete(this);\n this.clearTimer();\n this.stopListeningToVisibility?.();\n this.stopListeningToVisibility = null;\n };\n\n receiveLocalActivity = (): void => {\n this.runningIntervalUntil = this.options.timers.now() + this.options.localActivityWindowMs;\n this.readNow();\n };\n\n /** Reads now; a read already in flight is followed by one more read instead (two reads never overlap). */\n protected readNow = (): void => {\n if (this.isStopped) return;\n if (this.isReading) {\n this.readAgainAfterCurrentRead = true;\n return;\n }\n this.clearTimer();\n this.isReading = true;\n void this.readMetadataOnce();\n };\n\n protected async readMetadataOnce(): Promise<void> {\n let conversation: ConversationRunStateRead;\n try {\n conversation = await this.readMetadata(this.conversationId);\n } catch (failure) {\n this.isReading = false;\n this.receiveReadFailure(failure);\n return;\n }\n this.isReading = false;\n if (this.isStopped) return;\n this.consecutiveFailedReads = 0;\n this.receiveConversation(conversation);\n this.continueAfterRead(this.readIntervalMs());\n }\n\n protected receiveConversation(conversation: ConversationRunStateRead): void {\n const runStatus = readPolledRunStatus(conversation);\n const reportsLastMessageId = conversation.lastMessageId !== undefined;\n const changeFingerprint = JSON.stringify([runStatus, conversation.lastMessageId ?? null, conversation.updated]);\n const summaryFingerprint = JSON.stringify([conversation.title, conversation.summary]);\n const isFirstRead = this.previousChangeFingerprint === null;\n const hasChanged =\n changeFingerprint !== this.previousChangeFingerprint || (!reportsLastMessageId && runStatus === \"running\");\n const hasSummaryChanged = !isFirstRead && summaryFingerprint !== this.previousSummaryFingerprint;\n if (!isFirstRead && hasChanged) this.changeCounter += 1;\n if (hasSummaryChanged) this.summaryRevision += 1;\n this.previousChangeFingerprint = changeFingerprint;\n this.previousSummaryFingerprint = summaryFingerprint;\n this.runStatus = runStatus;\n this.hasConversationEnded =\n conversation.runState !== null && CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION.includes(conversation.runState);\n if (!isFirstRead && !hasChanged && !hasSummaryChanged) return;\n this.onSignal({\n changeCounter: this.changeCounter,\n lastMessageId: conversation.lastMessageId ?? null,\n runStatus,\n summaryUpdatedAt: this.summaryRevision,\n });\n }\n\n protected receiveReadFailure(failure: unknown): void {\n if (this.isStopped) return;\n const endReason = readSubscriptionEndReasonOfReadFailure(failure);\n if (endReason !== null) {\n this.stop();\n this.onEnded(endReason);\n return;\n }\n this.consecutiveFailedReads += 1;\n const backoffMs = this.readIntervalMs() * 2 ** this.consecutiveFailedReads;\n this.continueAfterRead(Math.min(backoffMs, this.options.maxBackoffMs));\n }\n\n protected continueAfterRead(nextReadDelayMs: number): void {\n if (this.readAgainAfterCurrentRead) {\n this.readAgainAfterCurrentRead = false;\n this.readNow();\n return;\n }\n // A completed or cancelled conversation changes no more: only a local send or the page's return reads it again.\n if (this.hasConversationEnded) return;\n this.scheduleRead(nextReadDelayMs);\n }\n\n protected readIntervalMs(): number {\n const isShortIntervalDue = this.runStatus === \"running\" || this.options.timers.now() < this.runningIntervalUntil;\n return isShortIntervalDue ? this.options.runningIntervalMs : this.options.idleIntervalMs;\n }\n\n /** Arms the next read — not while the page is hidden; its return reads at once. */\n protected scheduleRead(delayMs: number): void {\n this.clearTimer();\n if (this.isStopped || this.options.documentVisibility?.isHidden()) return;\n this.timerHandle = this.options.timers.setTimeout(this.readOnTimer, delayMs);\n }\n\n protected readOnTimer = (): void => {\n this.timerHandle = null;\n this.readNow();\n };\n\n protected receiveVisibilityChange = (): void => {\n if (this.isStopped) return;\n if (this.options.documentVisibility?.isHidden()) {\n this.clearTimer();\n return;\n }\n this.readNow();\n };\n\n protected clearTimer(): void {\n if (this.timerHandle === null) return;\n this.options.timers.clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n}\n\n/** Every subscription of one polling default; `notifyLocalActivity` reaches the subscriptions of a conversation. */\nclass PollingConversationChangeSubscriptions implements PollingConversationChangeSubscription {\n protected readonly activePollers = new Set<ConversationMetadataPoller>();\n\n constructor(\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly options: ResolvedPollingOptions,\n ) {}\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => {\n const poller = new ConversationMetadataPoller(\n conversationId,\n this.readMetadata,\n onSignal,\n onEnded,\n this.options,\n this.activePollers,\n );\n poller.start();\n return poller.stop;\n };\n\n notifyLocalActivity = (conversationId: number): void => {\n for (const poller of [...this.activePollers]) {\n if (poller.conversationId === conversationId) poller.receiveLocalActivity();\n }\n };\n}\n\nconst readDefaultDocumentVisibility = (): PollingDocumentVisibility | null =>\n typeof document === \"undefined\" ? null : new BrowserDocumentVisibility(document);\n\n/**\n * The polling default of `subscribeToConversationChanges` over a metadata read: every 2 s while a turn\n * runs, every 20 s while idle, at once after `notifyLocalActivity`; paused while the page is hidden and read once when\n * it shows again; exponential backoff on failed reads up to 60 s; a `notFound` / `forbidden` read ends the subscription\n * with `gone` / `forbidden`. One poller per subscription; see `ConversationMetadataPoller` for how a read becomes a\n * signal.\n */\nexport const createPollingConversationChangeSubscription = (\n readMetadata: ConversationMetadataReader,\n options: PollingConversationChangeSubscriptionOptions = {},\n): PollingConversationChangeSubscription =>\n new PollingConversationChangeSubscriptions(readMetadata, {\n runningIntervalMs: options.runningIntervalMs ?? POLLING_RUNNING_INTERVAL_MS,\n idleIntervalMs: options.idleIntervalMs ?? POLLING_IDLE_INTERVAL_MS,\n maxBackoffMs: options.maxBackoffMs ?? POLLING_MAX_BACKOFF_MS,\n localActivityWindowMs: options.localActivityWindowMs ?? POLLING_LOCAL_ACTIVITY_WINDOW_MS,\n timers: options.timers ?? new GlobalPollingTimers(),\n documentVisibility: options.documentVisibility === undefined ? readDefaultDocumentVisibility() : options.documentVisibility,\n });\n","import type { AgentsConversationClient } from \"../AgentsConversationClient\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n AgentsConversation,\n ChangedConversationMessages,\n ChangedMessagesRequest,\n ConversationActivity,\n ConversationAttachmentReference,\n ConversationChangeSignal,\n ConversationListQueryOptions,\n ConversationMessageSearchHit,\n ConversationMessageSentPayload,\n ConversationMessagesPage,\n ConversationRunStateRead,\n ConversationSearchGroup,\n ConversationSearchOptions,\n ConversationSignal,\n ConversationSubscriptionEndReason,\n PostedMessage,\n SelectableModel,\n PurposeStartRequest,\n StartedConversation,\n StartedPurposeConversation,\n} from \"../../contract/conversation\";\nimport {\n createPollingConversationChangeSubscription,\n type PollingConversationChangeSubscription,\n type PollingConversationChangeSubscriptionOptions,\n} from \"./createPollingConversationChangeSubscription\";\n\n/** A conversation client whose `subscribeToConversationChanges` is present. */\nexport type AgentsConversationClientWithChangeSubscription = AgentsConversationClient &\n Required<Pick<AgentsConversationClient, \"subscribeToConversationChanges\">>;\n\n/**\n * A binding without push, with the polling default as its subscription. Every port function goes to the binding; the\n * three that make the server start a turn on an existing conversation (post, signal, retry) tell the poller once the\n * server accepted them, so the first read does not wait for the idle interval. A start needs no notice: the chat\n * subscribes to the new conversation afterwards, and a subscription reads at once.\n */\nclass PollingAgentsConversationClient implements AgentsConversationClientWithChangeSubscription {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n readonly composeSentMessageText?: (text: string, attachments: ConversationAttachmentReference[] | undefined) => string;\n readonly getMessageSentPayload?: (conversationId: number, messageId: number) => Promise<ConversationMessageSentPayload>;\n readonly getConversationRunState?: (conversationId: number) => Promise<ConversationRunStateRead>;\n readonly getAccountRealtimeMessages?: (clientId?: string) => Promise<AccountRealtimeRead>;\n readonly startPurpose?: (request: PurposeStartRequest) => Promise<StartedPurposeConversation>;\n\n constructor(\n protected readonly binding: AgentsConversationClient,\n protected readonly polling: PollingConversationChangeSubscription,\n ) {\n // The optional functions exist exactly when the binding has them (the chat reads their presence).\n this.getSelectableModels = binding.getSelectableModels?.bind(binding);\n this.composeSentMessageText = binding.composeSentMessageText?.bind(binding);\n this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);\n this.getConversationRunState = binding.getConversationRunState?.bind(binding);\n this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);\n this.startPurpose = binding.startPurpose?.bind(binding);\n }\n\n getConversationMetadata = (conversationId: number): Promise<AgentsConversation> =>\n this.binding.getConversationMetadata(conversationId);\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getNewestMessagesPage(conversationId, pageSize);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getOlderMessagesPage(conversationId, beforeIndex, pageSize);\n\n getChangedMessages = (conversationId: number, request: ChangedMessagesRequest): Promise<ChangedConversationMessages> =>\n this.binding.getChangedMessages(conversationId, request);\n\n startConversation = (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> =>\n this.binding.startConversation(request);\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const postedMessage = await this.binding.postMessage(conversationId, message);\n this.polling.notifyLocalActivity(conversationId);\n return postedMessage;\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.binding.injectSignal(conversationId, signal);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.binding.retryConversation(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n renameConversation = (conversationId: number, title: string): Promise<AgentsConversation> =>\n this.binding.renameConversation(conversationId, title);\n\n deleteConversation = (conversationId: number): Promise<void> => this.binding.deleteConversation(conversationId);\n\n listConversations = (agentSpaceKey: number, options?: ConversationListQueryOptions): Promise<AgentsConversation[]> =>\n this.binding.listConversations(agentSpaceKey, options);\n\n searchConversations = (text: string, options?: ConversationSearchOptions): Promise<ConversationSearchGroup[]> =>\n this.binding.searchConversations(text, options);\n\n searchConversationMessages = (\n conversationId: number,\n text: string,\n options?: ConversationSearchOptions,\n ): Promise<ConversationMessageSearchHit[]> => this.binding.searchConversationMessages(conversationId, text, options);\n\n getConversationActivity = (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> =>\n this.binding.getConversationActivity(conversationId, turnMessageId);\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => this.polling.subscribeToConversationChanges(conversationId, onSignal, onEnded);\n}\n\n/**\n * The client with live updates: a client that brings its own `subscribeToConversationChanges` (a push\n * transport — the host application's Firebase binding) is returned as it is; any other gets the polling default over its\n * `getConversationRunState` when it has one, else over its `getConversationMetadata`\n * (`createPollingConversationChangeSubscription`, `options` tune the intervals). A post, a signal or a retry the server\n * accepted reads at once. The default `AgentChat` calls this by itself.\n */\nexport const withPollingChangeSubscription = (\n client: AgentsConversationClient,\n options?: PollingConversationChangeSubscriptionOptions,\n): AgentsConversationClientWithChangeSubscription => {\n if (client.subscribeToConversationChanges) return client as AgentsConversationClientWithChangeSubscription;\n return new PollingAgentsConversationClient(\n client,\n createPollingConversationChangeSubscription(\n client.getConversationRunState ? client.getConversationRunState.bind(client) : client.getConversationMetadata.bind(client),\n options,\n ),\n );\n};\n"],"names":[],"mappings":";;AAWO,MAAM,8BAA8B;AAEpC,MAAM,2BAA2B;AAEjC,MAAM,yBAAyB;AAK/B,MAAM,mCAAmC;AA6DhD,MAAM,oBAA6C;AAAA,EAAnD,cAAA;AACE,SAAA,aAAa,CAAC,UAAsB,YAA6B,WAAW,WAAW,UAAU,OAAO;AAExG,SAAA,eAAe,CAAC,gBAA+B,WAAW,aAAa,WAA4C;AAEnH,SAAA,MAAM,MAAc,KAAK,IAAA;AAAA,EAAI;AAC/B;AAGA,MAAM,0BAA+D;AAAA,EACnE,YAA+B,iBAA2B;AAA3B,SAAA,kBAAA;AAE/B,SAAA,WAAW,MAAe,KAAK,gBAAgB,oBAAoB;AAEnE,SAAA,SAAS,CAAC,aAAuC;AAC/C,WAAK,gBAAgB,iBAAiB,oBAAoB,QAAQ;AAClE,aAAO,KAAK,gBAAgB,oBAAoB,KAAK,KAAK,iBAAiB,oBAAoB,QAAQ;AAAA,IACzG;AAAA,EAP2D;AAQ7D;AAMO,MAAM,sBAAsB,CACjC,iBACiC;AACjC,QAAM,YAAY,oCAAoC,aAAa,QAAQ;AAC3E,SAAO,cAAc,UAAU,aAAa,kBAAkB,YAAY;AAC5E;AAGA,MAAM,yCAAyC,CAAC,YAA+D;AAC7G,MAAI,CAAC,oBAAoB,OAAO,EAAG,QAAO;AAC1C,MAAI,QAAQ,SAAS,WAAY,QAAO;AACxC,M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BAA0B,OAAO,wBAAwB,KAAK,MAAM,IAAI,OAAO,wBAAwB,KAAK,MAAM;AAAA,MACzH;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
3
|
+
import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-mWdchMOH.js";
|
|
4
|
+
import { P, a as a2, b, c, d, r } from "./chunks/withPollingChangeSubscription-mWdchMOH.js";
|
|
5
5
|
import { A as AGENTS_CLIENT_CONTEXT_LIMITS, a as AgentsClientError, b as AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED } from "./chunks/conversation-CbWEHPbL.js";
|
|
6
6
|
import { a as acceptArrivedRealtimeMessage, c as createAgentUIClientId } from "./chunks/realtime-arrival-BfsAPwqQ.js";
|
|
7
7
|
import { c as composeAttachmentMessageText } from "./chunks/compose-attachment-message-text-FvVJbrge.js";
|
|
@@ -365,6 +365,28 @@ class AgentsHttpConversationClient {
|
|
|
365
365
|
reopenedExisting
|
|
366
366
|
};
|
|
367
367
|
};
|
|
368
|
+
this.startPurpose = async (request) => {
|
|
369
|
+
const response = await this.request({
|
|
370
|
+
operation: "startPurpose",
|
|
371
|
+
method: "POST",
|
|
372
|
+
path: "/startPurpose",
|
|
373
|
+
body: {
|
|
374
|
+
purposeId: request.purposeId,
|
|
375
|
+
...request.agentSpaceKey ? { agentSpaceId: request.agentSpaceKey } : {},
|
|
376
|
+
...request.subject ? { subject: { subjectEntityClass: request.subject.entityClass, subjectEntityId: request.subject.entityId } } : {},
|
|
377
|
+
...request.prefill ? { prefill: request.prefill } : {}
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
const conversationId = Number(response.aiConversationId ?? 0);
|
|
381
|
+
if (!Number.isInteger(conversationId) || conversationId < 1) {
|
|
382
|
+
throw new AgentsClientError("other", { message: "The purposed start answered no conversation id." });
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
conversationId,
|
|
386
|
+
resumedExisting: response.resumedExistingConversation === true,
|
|
387
|
+
prefillDelivered: response.prefillDelivered === true
|
|
388
|
+
};
|
|
389
|
+
};
|
|
368
390
|
this.postMessage = async (conversationId, message) => {
|
|
369
391
|
const response = await this.request({
|
|
370
392
|
operation: "postMessage",
|