@mgamadeus/ddd-agents 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ The second part is the peer set (React 19 assumed present; `axios` ^0.28.0 only
17
17
  The agent skills come with the Composer package (`vendor/mgamadeus/ddd-agents/.claude/skills`), not with this one.
18
18
 
19
19
  Entries: `@mgamadeus/ddd-agents` (provider and setup), `/provider` (the provider alone), `/chat`, `/renderer`, `/widgets`, `/kit`, `/contract`,
20
- `/client`, `/client/testing`, `/preview`, `/image-render`, and the stylesheet `@mgamadeus/ddd-agents/styles.css`
20
+ `/client`, `/client/testing`, `/preview`, `/image-render`, `/ui`, and the stylesheet `@mgamadeus/ddd-agents/styles.css`
21
21
  (import it once). Non-code files (widget documentation, preview fixtures, contracts, the node schema, the
22
22
  sandbox frame, SCSS tokens) are exported one subpath per file at their path below `src`. React 19 and the libraries listed under `peerDependencies` come from the application.
23
23
 
@@ -92,6 +92,33 @@ those endpoints. With 0 the store drops the cache entry the moment the first rea
92
92
  flight when a second read of the same key arrives — the chat then shows an empty conversation after a page load with a
93
93
  conversation in the URL. Keep the default (or any value above 0) and let the forced reads refresh the entry.
94
94
 
95
+ ## Agent.UI on the client (`/ui`)
96
+
97
+ The UI tools of the agent (`getCurrentScreen`, `listScreens`, `openScreen`, `highlightOnScreen`, optionally
98
+ `setAgentWindowMode`) send requests to the user's open client; `useAgentUIClient(adapters)` runs them and the
99
+ conversation client posts the answers (`createAgentsHttpConversationClient({ uiClient })`).
100
+
101
+ ```ts
102
+ const uiClient = useAgentUIClient({
103
+ targets: createDomScreenTargetSource(), // the data-agent-anchor marks of the navigation
104
+ navigator, reader, highlighter, // the application's router, DomScreenReader, DomScreenHighlighter
105
+ isVisible: () => document.visibilityState === 'visible',
106
+ picture: createDomScreenPictureCapturer(), // optional: getCurrentScreen(format: picture)
107
+ pathGuide: createDomScreenPathGuide({ findPathElements, currentRoute }), // optional
108
+ agentWindow: createAgentWindowAdapter({ getMode, applyMode, modes: ['docked', 'aside'] }), // optional
109
+ });
110
+ ```
111
+
112
+ - A mark: `<a href="/orders" data-agent-anchor="orders" data-agent-group="Sales" data-agent-filters="customerId">`;
113
+ further attributes `data-agent-label`, `data-agent-route` (`/orders/:orderId`), `data-agent-parameters`,
114
+ `data-agent-tabs`, `data-agent-views`, `data-agent-anchor-group` (with `groupKey`).
115
+ - In a picture, passwords show as dots, `data-agent-secret` content is blanked and `data-agent-skip` elements are left
116
+ out (mark the agent window `data-agent-skip`); what a picture cannot show is `PICTURE_LIMITATIONS`.
117
+ - The agent window steps aside before a screen is opened, marked or pictured, and comes back after a picture.
118
+ - A host push transport hands each message to `acceptArrivedRealtimeMessage(conversationId, message, uiClient, sendAnswer)`;
119
+ without one the run-state read delivers. `runClientToolRequestForDevelopment(uiClient, 'LIST_TARGETS')` tries the
120
+ adapters without a model.
121
+
95
122
  ## Texts and translations
96
123
 
97
124
  Every interface text of the package goes through `AgentsEnvironment.texts.translate(key, replacements, context)`; the key
@@ -0,0 +1,45 @@
1
+ "use client";
2
+ const CLIENT_TOOL_REQUEST_MESSAGE_TYPE = "agent.ui.clientToolRequest";
3
+ const readClientToolRequestOfRealtimeMessage = (message) => {
4
+ if (message.messageType !== CLIENT_TOOL_REQUEST_MESSAGE_TYPE) return null;
5
+ try {
6
+ const payload = JSON.parse(message.payloadJson);
7
+ if (typeof payload !== "object" || payload === null) return null;
8
+ const { id, requestType, argumentsJson, secondsLeft } = payload;
9
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || typeof requestType !== "string") return null;
10
+ return {
11
+ id,
12
+ requestType,
13
+ argumentsJson: typeof argumentsJson === "string" ? argumentsJson : "{}",
14
+ // the transport's own clock: the message's seconds left win when the payload's are older
15
+ secondsLeft: Math.min(typeof secondsLeft === "number" ? secondsLeft : message.secondsLeft, message.secondsLeft)
16
+ };
17
+ } catch {
18
+ return null;
19
+ }
20
+ };
21
+ const acceptArrivedRealtimeMessage = (conversationId, message, acceptor, sendAnswer, onOtherMessage) => {
22
+ const delivery = readClientToolRequestOfRealtimeMessage(message);
23
+ if (delivery) {
24
+ acceptor.acceptClientToolRequest(conversationId, delivery, sendAnswer);
25
+ return true;
26
+ }
27
+ onOtherMessage?.(conversationId, message);
28
+ return false;
29
+ };
30
+ let developmentRequestId = 9e12;
31
+ const runClientToolRequestForDevelopment = (acceptor, requestType, parameters = {}, secondsLeft = 30) => new Promise((resolve) => {
32
+ developmentRequestId += 1;
33
+ acceptor.acceptClientToolRequest(
34
+ 0,
35
+ { id: developmentRequestId, requestType, argumentsJson: JSON.stringify(parameters), secondsLeft },
36
+ async (_requestId, answer) => resolve(answer)
37
+ );
38
+ });
39
+ export {
40
+ CLIENT_TOOL_REQUEST_MESSAGE_TYPE as C,
41
+ acceptArrivedRealtimeMessage as a,
42
+ runClientToolRequestForDevelopment as b,
43
+ readClientToolRequestOfRealtimeMessage as r
44
+ };
45
+ //# sourceMappingURL=realtime-arrival-DUJjwt2M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realtime-arrival-DUJjwt2M.js","sources":["../../src/ui/realtime-arrival.ts"],"sourcesContent":["import type { ClientToolAnswerSender } from \"./ClientToolRequestRunner\";\nimport type { ClientToolAnswer, ClientToolRequestDelivery, ClientToolRequestType } from \"./client-tools\";\n\n/** The message type of a client tool request on the realtime port (`AgentUIRealtimeMessageTypeProviderService`). */\nexport const CLIENT_TOOL_REQUEST_MESSAGE_TYPE = 'agent.ui.clientToolRequest';\n\n/** A message of the realtime port as the run-state read or the host's transport delivers it (`AgentRealtimeMessageDelivery`). */\nexport interface AgentRealtimeMessageDelivery {\n messageType: string;\n messageKey: string;\n /** One JSON object */\n payloadJson: string;\n secondsLeft: number;\n}\n\n/** What a client needs to listen on the host's transport (`AgentRealtimeListenerCredential`). */\nexport interface AgentRealtimeListenerCredential {\n transportName: string;\n credential: string;\n listenPath?: string | null;\n expiresAt?: string | null;\n}\n\n/** The client tool request a realtime message carries, or null for another type or a payload that does not parse. */\nexport const readClientToolRequestOfRealtimeMessage = (message: AgentRealtimeMessageDelivery): ClientToolRequestDelivery | null => {\n if (message.messageType !== CLIENT_TOOL_REQUEST_MESSAGE_TYPE) return null;\n try {\n const payload: unknown = JSON.parse(message.payloadJson);\n if (typeof payload !== 'object' || payload === null) return null;\n const { id, requestType, argumentsJson, secondsLeft } = payload as Record<string, unknown>;\n if (typeof id !== 'number' || !Number.isSafeInteger(id) || typeof requestType !== 'string') return null;\n return {\n id,\n requestType,\n argumentsJson: typeof argumentsJson === 'string' ? argumentsJson : '{}',\n // the transport's own clock: the message's seconds left win when the payload's are older\n secondsLeft: Math.min(typeof secondsLeft === 'number' ? secondsLeft : message.secondsLeft, message.secondsLeft),\n };\n } catch {\n return null;\n }\n};\n\n/** What takes an arrived client tool request (an `AgentUIClient`). */\nexport interface ClientToolRequestAcceptor {\n acceptClientToolRequest(conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void;\n}\n\n/**\n * The arrival adapter for a host transport: hand it every message the transport receives for a conversation; a\n * client tool request goes to the UI client (which runs a request id once, so the run-state read delivering the same\n * request is harmless), any other type to `onOtherMessage`. Returns whether the message was a client tool request.\n */\nexport const acceptArrivedRealtimeMessage = (\n conversationId: number,\n message: AgentRealtimeMessageDelivery,\n acceptor: ClientToolRequestAcceptor,\n sendAnswer: ClientToolAnswerSender,\n onOtherMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void,\n): boolean => {\n const delivery = readClientToolRequestOfRealtimeMessage(message);\n if (delivery) {\n acceptor.acceptClientToolRequest(conversationId, delivery, sendAnswer);\n return true;\n }\n onOtherMessage?.(conversationId, message);\n return false;\n};\n\nlet developmentRequestId = 9_000_000_000_000;\n\n/**\n * The dev helper: runs a request through the UI client as if the server had sent it and resolves with the answer, so\n * an application tries its adapters without a model (e.g. from the browser console in development).\n */\nexport const runClientToolRequestForDevelopment = (\n acceptor: ClientToolRequestAcceptor,\n requestType: ClientToolRequestType | string,\n parameters: Record<string, unknown> = {},\n secondsLeft: number = 30,\n): Promise<ClientToolAnswer> =>\n new Promise(resolve => {\n developmentRequestId += 1;\n acceptor.acceptClientToolRequest(\n 0,\n { id: developmentRequestId, requestType, argumentsJson: JSON.stringify(parameters), secondsLeft },\n async (_requestId, answer) => resolve(answer),\n );\n });\n"],"names":[],"mappings":";AAIO,MAAM,mCAAmC;AAoBzC,MAAM,yCAAyC,CAAC,YAA4E;AACjI,MAAI,QAAQ,gBAAgB,iCAAkC,QAAO;AACrE,MAAI;AACF,UAAM,UAAmB,KAAK,MAAM,QAAQ,WAAW;AACvD,QAAI,OAAO,YAAY,YAAY,YAAY,KAAM,QAAO;AAC5D,UAAM,EAAE,IAAI,aAAa,eAAe,gBAAgB;AACxD,QAAI,OAAO,OAAO,YAAY,CAAC,OAAO,cAAc,EAAE,KAAK,OAAO,gBAAgB,SAAU,QAAO;AACnG,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,eAAe,OAAO,kBAAkB,WAAW,gBAAgB;AAAA;AAAA,MAEnE,aAAa,KAAK,IAAI,OAAO,gBAAgB,WAAW,cAAc,QAAQ,aAAa,QAAQ,WAAW;AAAA,IAAA;AAAA,EAElH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAYO,MAAM,+BAA+B,CAC1C,gBACA,SACA,UACA,YACA,mBACY;AACZ,QAAM,WAAW,uCAAuC,OAAO;AAC/D,MAAI,UAAU;AACZ,aAAS,wBAAwB,gBAAgB,UAAU,UAAU;AACrE,WAAO;AAAA,EACT;AACA,mBAAiB,gBAAgB,OAAO;AACxC,SAAO;AACT;AAEA,IAAI,uBAAuB;AAMpB,MAAM,qCAAqC,CAChD,UACA,aACA,aAAsC,CAAA,GACtC,cAAsB,OAEtB,IAAI,QAAQ,CAAA,YAAW;AACrB,0BAAwB;AACxB,WAAS;AAAA,IACP;AAAA,IACA,EAAE,IAAI,sBAAsB,aAAa,eAAe,KAAK,UAAU,UAAU,GAAG,YAAA;AAAA,IACpF,OAAO,YAAY,WAAW,QAAQ,MAAM;AAAA,EAAA;AAEhD,CAAC;"}
package/dist/client.js CHANGED
@@ -3,6 +3,7 @@ import { A, u, a } from "./chunks/AgentsConversationClientContext-C4T7g_Qk.js";
3
3
  import { w as withPollingChangeSubscription } from "./chunks/withPollingChangeSubscription-CWavoKjJ.js";
4
4
  import { P, a as a2, b, c, d, r } from "./chunks/withPollingChangeSubscription-CWavoKjJ.js";
5
5
  import { A as AGENTS_CLIENT_CONTEXT_LIMITS, a as AgentsClientError, b as AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED } from "./chunks/conversation-CbWEHPbL.js";
6
+ import { a as acceptArrivedRealtimeMessage } from "./chunks/realtime-arrival-DUJjwt2M.js";
6
7
  import { c as composeAttachmentMessageText } from "./chunks/compose-attachment-message-text-FvVJbrge.js";
7
8
  const RUN_STATES = [
8
9
  "IDLE",
@@ -243,13 +244,15 @@ class AgentsHttpConversationClient {
243
244
  path: `/${conversationId}/runState`,
244
245
  query: uiClient ? { clientId: uiClient.clientId, uiStateJson: uiState ? JSON.stringify(uiState) : void 0 } : void 0
245
246
  });
247
+ const sendAnswer = (requestId, answer) => this.answerClientToolRequest(conversationId, requestId, answer);
246
248
  if (uiClient && response.clientToolRequest) {
247
- uiClient.acceptClientToolRequest(
248
- conversationId,
249
- response.clientToolRequest,
250
- (requestId, answer) => this.answerClientToolRequest(conversationId, requestId, answer)
251
- );
249
+ uiClient.acceptClientToolRequest(conversationId, response.clientToolRequest, sendAnswer);
252
250
  }
251
+ for (const message of readWireSetElements(response.realtimeMessages)) {
252
+ if (uiClient) acceptArrivedRealtimeMessage(conversationId, message, uiClient, sendAnswer, this.options.onRealtimeMessage);
253
+ else this.options.onRealtimeMessage?.(conversationId, message);
254
+ }
255
+ this.options.onRealtimeListenerCredential?.(conversationId, response.realtimeListenerCredential ?? null);
253
256
  return mapWireConversationRunState(response);
254
257
  };
255
258
  this.answerClientToolRequest = async (conversationId, requestId, answer) => {
@@ -261,7 +264,9 @@ class AgentsHttpConversationClient {
261
264
  clientId: this.options.uiClient?.clientId ?? "",
262
265
  outcome: answer.outcome,
263
266
  text: answer.text,
264
- detailsJson: JSON.stringify(answer.details ?? {})
267
+ detailsJson: JSON.stringify(answer.details ?? {}),
268
+ pictureBase64: answer.pictureBase64,
269
+ uiStateJson: this.readUIStateJsonAfterAnswer()
265
270
  }
266
271
  });
267
272
  };
@@ -402,6 +407,11 @@ class AgentsHttpConversationClient {
402
407
  };
403
408
  if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;
404
409
  }
410
+ /** What the UI shows after the request was carried out, so the server's `[SIGNAL:ui]` note is current at once. */
411
+ readUIStateJsonAfterAnswer() {
412
+ const uiState = this.options.uiClient?.readUIState() ?? null;
413
+ return uiState ? JSON.stringify(uiState) : void 0;
414
+ }
405
415
  async readMessagesPage(operation, conversationId, pageSize, filters) {
406
416
  const response = await this.request({
407
417
  operation,
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../src/client/http/agents-http-mappers.ts","../src/client/http/createAgentsHttpConversationClient.ts"],"sourcesContent":["import {\n AGENTS_CLIENT_CONTEXT_LIMITS,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsClientErrorKind,\n type AgentsConversation,\n type AgentsConversationMessage,\n type ConversationActivity,\n type ConversationActivityElement,\n type ConversationMessageAuthorType,\n type ConversationMessageRole,\n type ConversationMessageSearchHit,\n type ConversationMessageStatus,\n type ConversationMessageType,\n type ConversationProgressStep,\n type ConversationRunState,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSubAgent,\n type SelectableModel,\n} from \"../../contract/conversation\";\nimport type {\n WireActivityLine,\n WireClientContext,\n WireClientContextRouteParameter,\n WireConversation,\n WireConversationActivityResponse,\n WireConversationMessage,\n WireConversationRunStateResponse,\n WireConversationSearchGroup,\n WireCustomerProgressStep,\n WireDelegationSubAgentRecord,\n WireErrorBody,\n WireSelectableModel,\n WireSemanticSearchHit,\n WireSet,\n} from \"./agents-http-wire\";\n\n// The vocabularies of the contract: a wire value outside one maps to null.\nconst RUN_STATES: readonly ConversationRunState[] = [\n \"IDLE\",\n \"QUEUED\",\n \"RUNNING\",\n \"AWAITING_DELEGATES\",\n \"FAILED\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nconst MESSAGE_ROLES: readonly ConversationMessageRole[] = [\"SYSTEM\", \"USER\", \"ASSISTANT\"];\nconst MESSAGE_TYPES: readonly ConversationMessageType[] = [\n \"TEXT\",\n \"TOOL_CALL\",\n \"CHECKPOINT\",\n \"ERROR\",\n \"SIGNAL\",\n \"TOOL_MESSAGE\",\n];\nconst MESSAGE_STATUSES: readonly ConversationMessageStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"COMPLETED\",\n \"FAILED\",\n];\nconst AUTHOR_TYPES: readonly ConversationMessageAuthorType[] = [\"USER\", \"ASSISTANT\", \"AGENT\", \"TOOL\"];\nconst PROGRESS_STEP_STATUSES: readonly ConversationProgressStep[\"status\"][] = [\"done\", \"active\", \"upcoming\"];\nconst ACTIVITY_STATES: readonly NonNullable<ConversationActivityElement[\"state\"]>[] = [\n \"queued\",\n \"running\",\n \"finished\",\n \"failed\",\n \"skipped\",\n];\nconst ACTIVITY_KINDS: readonly NonNullable<ConversationActivityElement[\"kind\"]>[] = [\n \"tool\",\n \"delegation\",\n \"background\",\n \"long\",\n \"turnStart\",\n];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a serialized set (`{ elements: [...] }`), a plain array, or the values of a keyed object. */\nexport const readWireSetElements = <Element>(\n wireSet: WireSet<Element> | Record<string, Element> | null | undefined,\n): Element[] => {\n if (!wireSet) return [];\n if (Array.isArray(wireSet)) return wireSet;\n if (typeof wireSet === \"object\" && \"elements\" in wireSet) {\n const elements = (wireSet as { elements?: Element[] | null }).elements;\n return Array.isArray(elements) ? elements : [];\n }\n return Object.values(wireSet as Record<string, Element>);\n};\n\nconst mapWireProgressStep = (wireStep: WireCustomerProgressStep): ConversationProgressStep => ({\n key: wireStep.key ?? \"\",\n label: wireStep.customerLabel ?? \"\",\n status: readVocabularyValue(PROGRESS_STEP_STATUSES, wireStep.status) ?? \"upcoming\",\n});\n\n/** An `AIConversation` as the contract's conversation. */\nexport const mapWireConversation = (wireConversation: WireConversation): AgentsConversation => {\n const conversation: AgentsConversation = {\n id: wireConversation.id ?? 0,\n agentSpaceKey: readNumberOrNull(wireConversation.agentSpaceId),\n runState: readVocabularyValue(RUN_STATES, wireConversation.runState),\n agentTurnOwedAt: readStringOrNull(wireConversation.agentTurnOwedAt),\n title: readStringOrNull(wireConversation.summary?.title),\n titleManuallyEdited: wireConversation.summary?.manuallyEdited === true,\n summary: readStringOrNull(wireConversation.summary?.text),\n created: readStringOrNull(wireConversation.created ?? wireConversation.changeHistory?.createdTime),\n updated: readStringOrNull(wireConversation.updated ?? wireConversation.changeHistory?.modifiedTime),\n purposeName: readStringOrNull(wireConversation.purposeName),\n initiatorType: readStringOrNull(wireConversation.initiatorType),\n scheduleId: readNumberOrNull(wireConversation.scheduleId),\n entryPointKey: readStringOrNull(wireConversation.entryPointKey),\n progressSteps: readWireSetElements(wireConversation.customerProgressSteps).map(mapWireProgressStep),\n };\n if (wireConversation.lastMessageId !== undefined) conversation.lastMessageId = readNumberOrNull(wireConversation.lastMessageId);\n if (wireConversation.aiPromptExtensionId !== undefined) {\n conversation.promptExtensionId = readNumberOrNull(wireConversation.aiPromptExtensionId);\n }\n return conversation;\n};\n\nconst mapWireSubAgent = (wireSubAgent: WireDelegationSubAgentRecord | null | undefined): ConversationSubAgent | null =>\n wireSubAgent\n ? {\n currentRunNumber: readNumberOrNull(wireSubAgent.currentRunNumber),\n runs: readWireSetElements(wireSubAgent.runs).map((wireRun) => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n })),\n }\n : null;\n\n/** An `AIConversationMessage` as the contract's message. */\nexport const mapWireConversationMessage = (wireMessage: WireConversationMessage): AgentsConversationMessage => {\n const message: AgentsConversationMessage = {\n id: wireMessage.id ?? 0,\n conversationId: readNumberOrNull(wireMessage.aiConversationId),\n indexInConversation: readNumberOrNull(wireMessage.indexInConversation),\n role: readVocabularyValue(MESSAGE_ROLES, wireMessage.role),\n messageType: readVocabularyValue(MESSAGE_TYPES, wireMessage.messageType),\n status: readVocabularyValue(MESSAGE_STATUSES, wireMessage.status),\n authorType: readVocabularyValue(AUTHOR_TYPES, wireMessage.authorType),\n signalSource: readStringOrNull(wireMessage.signalSource),\n message: wireMessage.message ?? \"\",\n createdDate: readStringOrNull(wireMessage.createdDate),\n toolCall: wireMessage.toolCall\n ? {\n toolCallId: readStringOrNull(wireMessage.toolCall.toolCallId),\n name: readStringOrNull(wireMessage.toolCall.name),\n arguments: wireMessage.toolCall.arguments ?? null,\n status: readStringOrNull(wireMessage.toolCall.status),\n }\n : null,\n delegatedConversations: readWireSetElements(wireMessage.delegatedConversations).map((delegated) => ({\n id: delegated.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, delegated.runState),\n })),\n subAgent: mapWireSubAgent(wireMessage.delegationResults?.subAgent),\n };\n const hasForensics =\n wireMessage.inputTokens != null || wireMessage.outputTokens != null || wireMessage.requestSnapshot != null;\n if (hasForensics) {\n message.forensics = {\n inputTokens: readNumberOrNull(wireMessage.inputTokens),\n outputTokens: readNumberOrNull(wireMessage.outputTokens),\n costInUSD: readNumberOrNull(wireMessage.costInUSD),\n requestSnapshot: wireMessage.requestSnapshot ?? null,\n };\n }\n return message;\n};\n\n/** The run-state read (`AIConversationRunStateGetResponseDto`). */\nexport const mapWireConversationRunState = (wireRunState: WireConversationRunStateResponse): ConversationRunStateRead => ({\n id: wireRunState.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, wireRunState.runState),\n agentTurnOwedAt: readStringOrNull(wireRunState.agentTurnOwedAt),\n lastMessageId: readNumberOrNull(wireRunState.lastMessageId),\n title: readStringOrNull(wireRunState.title),\n titleManuallyEdited: wireRunState.titleManuallyEdited === true,\n summary: readStringOrNull(wireRunState.summary),\n updated: readStringOrNull(wireRunState.updated),\n});\n\nconst mapWireActivityLine = (wireLine: WireActivityLine): ConversationActivityElement => ({\n toolCallMessageId: wireLine.toolCallMessageId ?? 0,\n batchId: readStringOrNull(wireLine.batchId),\n state: readVocabularyValue(ACTIVITY_STATES, wireLine.state),\n kind: readVocabularyValue(ACTIVITY_KINDS, wireLine.kind),\n childCount: readNumberOrNull(wireLine.childCount),\n helperIndex: readNumberOrNull(wireLine.helperIndex),\n line: readStringOrNull(wireLine.line),\n});\n\n/** The activity of a turn (`AIConversationActivityGetResponseDto`). */\nexport const mapWireConversationActivity = (wireActivity: WireConversationActivityResponse): ConversationActivity => ({\n turnMessageId: readNumberOrNull(wireActivity.turnMessageId),\n turnRunning: wireActivity.turnRunning === true,\n elements: readWireSetElements(wireActivity.elements).map(mapWireActivityLine),\n});\n\n/** A `SemanticSearchHit`. */\nexport const mapWireSearchHit = (wireHit: WireSemanticSearchHit): ConversationMessageSearchHit => ({\n messageId: readNumberOrNull(wireHit.messageId),\n conversationId: readNumberOrNull(wireHit.conversationId),\n indexInConversation: readNumberOrNull(wireHit.indexInConversation),\n role: readStringOrNull(wireHit.role),\n excerpt: wireHit.excerpt ?? \"\",\n relevance: readNumberOrNull(wireHit.relevance) ?? 0,\n created: readStringOrNull(wireHit.created),\n updated: readStringOrNull(wireHit.updated),\n title: readStringOrNull(wireHit.title),\n});\n\n/** An `AIConversationSearchGroup`. */\nexport const mapWireSearchGroup = (wireGroup: WireConversationSearchGroup): ConversationSearchGroup => ({\n conversationId: readNumberOrNull(wireGroup.conversationId),\n title: readStringOrNull(wireGroup.title),\n summary: readStringOrNull(wireGroup.summary),\n created: readStringOrNull(wireGroup.created),\n updated: readStringOrNull(wireGroup.updated),\n relevance: readNumberOrNull(wireGroup.relevance) ?? 0,\n hits: readWireSetElements(wireGroup.hits).map(mapWireSearchHit),\n});\n\n/** An `AgentCustomerSelectableModel`. */\nexport const mapWireSelectableModel = (wireModel: WireSelectableModel): SelectableModel => ({\n name: wireModel.name ?? \"\",\n displayName: wireModel.displayName ?? wireModel.name ?? \"\",\n description: wireModel.description ?? \"\",\n strengthLevel: readNumberOrNull(wireModel.strengthLevel),\n speedLevel: readNumberOrNull(wireModel.speedLevel),\n creditsMultiplier: readNumberOrNull(wireModel.creditsMultiplier),\n});\n\n/** The stable codes of the server's refusals the chat tells apart. */\nconst ERROR_KIND_BY_CODE: Readonly<Record<string, AgentsClientErrorKind>> = {\n AI_BUDGET_REACHED: \"budget\",\n RATE_LIMIT_EXCEEDED: \"rateLimit\",\n CONVERSATION_CLOSED: \"closed\",\n};\n\n/**\n * A refused request as the port's error: the stable code first (`errorCode` of the JSON body), then the status — 429\n * `rateLimit` (with `Retry-After`), 404 `notFound`, 403 and 401 `forbidden`, 5xx `network`, everything else `other`.\n */\nexport const mapHttpFailureToAgentsClientError = (\n httpStatus: number,\n wireErrorBody: WireErrorBody | null,\n retryAfterHeader: string | null,\n): AgentsClientError => {\n const code = wireErrorBody?.errorCode ?? wireErrorBody?.code ?? null;\n const message = wireErrorBody?.error ?? wireErrorBody?.message ?? undefined;\n const retryAfterOfHeader = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader) : null;\n const retryAfterSeconds = readNumberOrNull(wireErrorBody?.retryAfterSeconds) ?? retryAfterOfHeader;\n const kindOfCode = code !== null ? ERROR_KIND_BY_CODE[code] : undefined;\n const kind: AgentsClientErrorKind =\n kindOfCode ??\n (httpStatus === 429\n ? \"rateLimit\"\n : httpStatus === 404\n ? \"notFound\"\n : httpStatus === 403 || httpStatus === 401\n ? \"forbidden\"\n : httpStatus >= 500\n ? \"network\"\n : \"other\");\n return new AgentsClientError(kind, { message: message ?? undefined, code, retryAfterSeconds, httpStatus });\n};\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f]/;\n\n/** A text field of the client context as it goes out: trimmed, or left out when empty, over its cap or not one line. */\nconst readClientContextText = (value: string | number | null | undefined, maxChars: number): string | undefined => {\n if (value === null || value === undefined) return undefined;\n const text = String(value).trim();\n if (text === \"\" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return undefined;\n return text;\n};\n\n/**\n * The client context as the body field `clientContext` carries it (`AgentClientContext`): the route parameters as a\n * list of `{name, value}`. A field over its cap ({@link AGENTS_CLIENT_CONTEXT_LIMITS}) or with a control character is\n * left out — never cut — so a send never fails on the context; the route parameters go together or not at all.\n * Undefined when nothing is left.\n */\nexport const mapClientContextToWire = (clientContext: AgentsClientContext | null | undefined): WireClientContext | undefined => {\n if (!clientContext) return undefined;\n const wireClientContext: WireClientContext = {};\n const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);\n if (routePath !== undefined) wireClientContext.routePath = routePath;\n const routeParameters: WireClientContextRouteParameter[] = Object.entries(clientContext.routeParameters ?? {})\n .filter(([name, value]) => name.trim() !== \"\" && value !== null && value !== undefined)\n .map(([name, value]) => ({ name, value: String(value) }));\n const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join(\"&\");\n if (\n routeParameters.length > 0 &&\n routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount &&\n routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars &&\n !CONTROL_CHARACTERS.test(routeParametersText)\n ) {\n wireClientContext.routeParameters = routeParameters;\n }\n const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);\n if (recordKind !== undefined) wireClientContext.recordKind = recordKind;\n const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);\n if (recordId !== undefined) wireClientContext.recordId = recordId;\n const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);\n if (tab !== undefined) wireClientContext.tab = tab;\n return Object.keys(wireClientContext).length > 0 ? wireClientContext : undefined;\n};\n","import type {\n AgentsConversationClient,\n AgentsConversationClientBindingOptions,\n AgentsConversationOperation,\n} from \"../AgentsConversationClient\";\nimport {\n AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsConversation,\n type ChangedConversationMessages,\n type ChangedMessagesRequest,\n type ConversationActivity,\n type ConversationAttachmentReference,\n type ConversationListQueryOptions,\n type ConversationMessageSearchHit,\n type ConversationMessagesPage,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSearchOptions,\n type ConversationSignal,\n type PostedMessage,\n type SelectableModel,\n type StartedConversation,\n} from \"../../contract/conversation\";\nimport type { AgentUIState } from \"../../ui/agent-ui-state\";\nimport type { AgentUIClientBinding } from \"../../ui/AgentUIClient\";\nimport type { ClientToolAnswer } from \"../../ui/client-tools\";\nimport { composeAttachmentMessageText } from \"../compose-attachment-message-text\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../polling/withPollingChangeSubscription\";\nimport {\n mapClientContextToWire,\n mapHttpFailureToAgentsClientError,\n mapWireConversation,\n mapWireConversationActivity,\n mapWireConversationMessage,\n mapWireConversationRunState,\n mapWireSearchGroup,\n mapWireSearchHit,\n mapWireSelectableModel,\n readWireSetElements,\n} from \"./agents-http-mappers\";\nimport type {\n WireConversationActivityResponse,\n WireConversationMessageSearchResponse,\n WireConversationMessagesResponse,\n WireConversationResponse,\n WireConversationRunStateResponse,\n WireConversationSearchResponse,\n WireConversationsResponse,\n WireConversationStartResponse,\n WireErrorBody,\n WireSelectableModelsResponse,\n} from \"./agents-http-wire\";\n\n/** What every request of the binding carries from the host: headers, credentials, mode, cache. */\nexport type AgentsHttpFetchOptions = Omit<RequestInit, \"method\" | \"body\">;\n\nexport interface AgentsHttpConversationClientOptions extends AgentsConversationClientBindingOptions {\n /**\n * Where the application's conversations controller is mounted (its `#[Route]`): a path such as\n * `/api/agents/conversations` or an absolute URL. The module's routes are relative to it.\n */\n baseUrl: string;\n /**\n * Request options every request carries (credentials, an authorization header). A function is called per request,\n * so it may hand out a fresh token. Default: none (the browser's defaults: same-origin credentials).\n */\n fetchOptions?: AgentsHttpFetchOptions | (() => AgentsHttpFetchOptions | Promise<AgentsHttpFetchOptions>);\n /** The fetch function. Default: the global `fetch`. */\n fetch?: typeof fetch;\n /**\n * The application's start route below `baseUrl` (`AgentConversationStartTrait` declares none). Default: `/start` for\n * a start without an agent space (key 0), `/start/{agentSpaceKey}` otherwise — the start DTO reads `agentSpaceId`\n * from the path.\n */\n buildStartPath?: (agentSpaceKey: number) => string;\n /**\n * The controller uses `AgentSelectableModelsTrait` (`GET …/selectable-models`): the client offers\n * `getSelectableModels` and the chat shows the model picker. Default false.\n */\n hasSelectableModelsRoute?: boolean;\n /**\n * The live updates: the polling default over the run-state read (`withPollingChangeSubscription`), which also reads\n * at once after a post, a signal or a retry the server accepted. The intervals of\n * `PollingConversationChangeSubscriptionOptions`; `false` = no subscription (the host adds its own push transport).\n * Default: polling with the default intervals.\n */\n polling?: PollingConversationChangeSubscriptionOptions | false;\n /**\n * What the owner's client shows, read on every start, posted message and injected signal and sent as the body field\n * `clientContext` (the route, its parameters, the record on screen, the tab). The agent reads the newest one as one\n * line beside the owner's newest message. A field over its cap is left out, never cut. Default: none.\n */\n clientContext?: (operation: AgentsClientContextOperation) => AgentsClientContext | null | undefined;\n /**\n * The UI side of `Agent.UI` (`AgentUIClient` of `@mgamadeus/ddd-agents/ui`): its client id and UI state ride on every\n * write and every run-state read; a client tool request the run-state read delivers goes to it, and the binding\n * posts its answer (`POST /{conversationId}/clientToolRequests/{requestId}/answer`). Default: none.\n */\n uiClient?: AgentUIClientBinding;\n}\n\n/** The writes that carry the client context. */\nexport type AgentsClientContextOperation = \"startConversation\" | \"postMessage\" | \"injectSignal\";\n\n/** The page size of a changed-messages read when the request names none (as the chat sends it). */\nexport const AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE = 50;\n\n/** The expand of every message page: the delegated children with the two fields the chat reads. */\nconst MESSAGES_EXPAND = \"delegatedConversations(select=id,runState)\";\n\nconst defaultBuildStartPath = (agentSpaceKey: number): string => (agentSpaceKey > 0 ? `/start/${agentSpaceKey}` : \"/start\");\n\ntype QueryParameters = Record<string, string | number | boolean | undefined | null>;\n\ninterface HttpRequest {\n operation: AgentsConversationOperation;\n method: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: QueryParameters;\n body?: unknown;\n}\n\n/** A filter value as the query-options grammar writes it: quoted. */\nconst quoteFilterValue = (value: number | string): string => `'${String(value).replace(/'/g, \"\\\\'\")}'`;\n\n/** The module's conversation routes over fetch: one request per port function, the wire mapped onto the contract. */\nclass AgentsHttpConversationClient implements AgentsConversationClient {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n\n constructor(protected readonly options: AgentsHttpConversationClientOptions) {\n if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;\n }\n\n // ── Reads ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n getConversationMetadata = async (conversationId: number): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"getConversationMetadata\",\n method: \"GET\",\n path: `/${conversationId}`,\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n getConversationRunState = async (conversationId: number): Promise<ConversationRunStateRead> => {\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n const response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n query: uiClient ? { clientId: uiClient.clientId, uiStateJson: uiState ? JSON.stringify(uiState) : undefined } : undefined,\n });\n if (uiClient && response.clientToolRequest) {\n uiClient.acceptClientToolRequest(conversationId, response.clientToolRequest, (requestId, answer) =>\n this.answerClientToolRequest(conversationId, requestId, answer),\n );\n }\n return mapWireConversationRunState(response);\n };\n\n /** Posts the answer of the UI client to a client tool request (`Agent.UI`); a refused answer is the server's word. */\n answerClientToolRequest = async (conversationId: number, requestId: number, answer: ClientToolAnswer): Promise<void> => {\n await this.request<unknown>({\n operation: \"answerClientToolRequest\",\n method: \"POST\",\n path: `/${conversationId}/clientToolRequests/${requestId}/answer`,\n body: {\n clientId: this.options.uiClient?.clientId ?? \"\",\n outcome: answer.outcome,\n text: answer.text,\n detailsJson: JSON.stringify(answer.details ?? {}),\n },\n });\n };\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\"getNewestMessagesPage\", conversationId, pageSize, undefined);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\n \"getOlderMessagesPage\",\n conversationId,\n pageSize,\n `indexInConversation lt ${quoteFilterValue(beforeIndex)}`,\n );\n\n getChangedMessages = async (\n conversationId: number,\n request: ChangedMessagesRequest,\n ): Promise<ChangedConversationMessages> => {\n const page = await this.readMessagesPage(\n \"getChangedMessages\",\n conversationId,\n request.pageSize ?? AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE,\n `(id gt ${quoteFilterValue(request.highestKnownId)} or indexInConversation ge ${quoteFilterValue(request.fromIndex)})`,\n );\n return { messages: page.messages };\n };\n\n listConversations = async (agentSpaceKey: number, options: ConversationListQueryOptions = {}): Promise<AgentsConversation[]> => {\n const filters = [\"rootConversationId eq null\"];\n if (agentSpaceKey > 0) filters.push(`agentSpaceId eq ${quoteFilterValue(agentSpaceKey)}`);\n const response = await this.request<WireConversationsResponse>({\n operation: \"listConversations\",\n method: \"GET\",\n path: \"/listAllConversations\",\n query: {\n filters: filters.join(\" and \"),\n orderBy: \"id desc\",\n top: options.paging?.top,\n skip: options.paging?.skip,\n },\n });\n const conversations = readWireSetElements(response.aiConversations).map(mapWireConversation);\n // Without a summary there is no title yet; the list leaves such a conversation out unless asked for it.\n return options.includeUnsummarized ? conversations : conversations.filter((conversation) => conversation.title !== null);\n };\n\n searchConversations = async (text: string, options: ConversationSearchOptions = {}): Promise<ConversationSearchGroup[]> => {\n const response = await this.request<WireConversationSearchResponse>({\n operation: \"searchConversations\",\n method: \"GET\",\n path: \"/search\",\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.conversations).map(mapWireSearchGroup);\n };\n\n searchConversationMessages = async (\n conversationId: number,\n text: string,\n options: ConversationSearchOptions = {},\n ): Promise<ConversationMessageSearchHit[]> => {\n const response = await this.request<WireConversationMessageSearchResponse>({\n operation: \"searchConversationMessages\",\n method: \"GET\",\n path: `/${conversationId}/messages/search`,\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.hits).map(mapWireSearchHit);\n };\n\n getConversationActivity = async (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> => {\n const response = await this.request<WireConversationActivityResponse>({\n operation: \"getConversationActivity\",\n method: \"GET\",\n path: `/${conversationId}/activity`,\n query: { turnMessageId: turnMessageId ?? undefined },\n });\n return mapWireConversationActivity(response);\n };\n\n composeSentMessageText = (text: string, attachments: ConversationAttachmentReference[] | undefined): string =>\n composeAttachmentMessageText(text, attachments);\n\n // ── Writes ────────────────────────────────────────────────────────────────────────────────────────────────────\n\n startConversation = async (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> => {\n const buildStartPath = this.options.buildStartPath ?? defaultBuildStartPath;\n const response = await this.request<WireConversationStartResponse>({\n operation: \"startConversation\",\n method: \"POST\",\n path: buildStartPath(request.agentSpaceKey),\n query: { aiModelName: request.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(request.text, request.attachments) },\n ...(request.startSignalText ? { signalText: request.startSignalText } : {}),\n ...(request.entryPointKey ? { entryPointKey: request.entryPointKey } : {}),\n ...this.readClientContextBody(\"startConversation\"),\n },\n });\n const wireConversation = response.aiConversation ?? {};\n const reopenedExisting = response.reopenedExistingConversation === true;\n return {\n conversation: mapWireConversation(wireConversation),\n messages: reopenedExisting ? [] : readWireSetElements(wireConversation.messages).map(mapWireConversationMessage),\n reopenedExisting,\n };\n };\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"postMessage\",\n method: \"POST\",\n path: `/${conversationId}/postMessage`,\n query: { aiModelName: message.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) },\n ...this.readClientContextBody(\"postMessage\"),\n },\n });\n return { messages: readWireSetElements(response.aiConversation?.messages).map(mapWireConversationMessage) };\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"injectSignal\",\n method: \"POST\",\n path: `/${conversationId}/injectSignal`,\n body: {\n signalText: signal.text,\n ...(signal.source ? { signalSource: signal.source } : {}),\n ...this.readClientContextBody(\"injectSignal\"),\n },\n });\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"retryConversation\",\n method: \"POST\",\n path: `/${conversationId}/retry`,\n });\n };\n\n renameConversation = async (conversationId: number, title: string): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"renameConversation\",\n method: \"PATCH\",\n path: `/${conversationId}/title`,\n body: { title },\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n deleteConversation = async (conversationId: number): Promise<void> => {\n await this.request<unknown>({ operation: \"deleteConversation\", method: \"DELETE\", path: `/${conversationId}` });\n };\n\n // ── Transport ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n protected readSelectableModels = async (): Promise<SelectableModel[]> => {\n const response = await this.request<WireSelectableModelsResponse>({\n operation: \"getSelectableModels\",\n method: \"GET\",\n path: \"/selectable-models\",\n });\n return readWireSetElements(response.models).map(mapWireSelectableModel);\n };\n\n protected async readMessagesPage(\n operation: AgentsConversationOperation,\n conversationId: number,\n pageSize: number,\n filters: string | undefined,\n ): Promise<ConversationMessagesPage> {\n const response = await this.request<WireConversationMessagesResponse>({\n operation,\n method: \"GET\",\n path: `/${conversationId}/messages`,\n query: { filters, orderBy: \"indexInConversation desc\", top: pageSize, expand: MESSAGES_EXPAND },\n });\n return {\n messages: readWireSetElements(response.messages).map(mapWireConversationMessage),\n hasMoreOlder: response.hasMoreOlder === true,\n };\n }\n\n /** The body field `clientContext` of a write, from the host's option; nothing when it gives none. */\n protected readClientContextBody(operation: AgentsClientContextOperation): {\n clientContext?: ReturnType<typeof mapClientContextToWire>;\n clientId?: string;\n uiState?: AgentUIState;\n } {\n const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n return {\n ...(wireClientContext ? { clientContext: wireClientContext } : {}),\n ...(uiClient ? { clientId: uiClient.clientId } : {}),\n ...(uiState ? { uiState } : {}),\n };\n }\n\n /** The URL of a route: the base, the path, the binding's query parameters with the host's extra ones over them. */\n protected buildUrl(request: HttpRequest): string {\n const searchParameters = new URLSearchParams();\n const extraParameters = this.options.extraRequestParameters?.(request.operation) ?? {};\n for (const [name, value] of Object.entries({ ...request.query, ...extraParameters })) {\n if (value !== undefined && value !== null) searchParameters.set(name, String(value));\n }\n const query = searchParameters.toString();\n const baseUrl = this.options.baseUrl.replace(/\\/+$/, \"\");\n return `${baseUrl}${request.path}${query ? `?${query}` : \"\"}`;\n }\n\n protected async readFetchOptions(): Promise<AgentsHttpFetchOptions> {\n const { fetchOptions } = this.options;\n return typeof fetchOptions === \"function\" ? await fetchOptions() : (fetchOptions ?? {});\n }\n\n /** One request; every failure becomes an `AgentsClientError` (the port's one error shape). */\n protected async request<ResponseBody>(request: HttpRequest): Promise<ResponseBody> {\n const fetchFunction = this.options.fetch ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n const fetchOptions = await this.readFetchOptions();\n const headers = new Headers(fetchOptions.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (request.body !== undefined && !headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n response = await fetchFunction(this.buildUrl(request), {\n ...fetchOptions,\n headers,\n method: request.method,\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n });\n } catch (failure) {\n if (failure instanceof AgentsClientError) throw failure;\n const isAbort = failure instanceof Error && failure.name === \"AbortError\";\n throw isAbort\n ? new AgentsClientError(\"other\", { code: AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED, message: \"The request was cancelled.\" })\n : new AgentsClientError(\"network\", { message: failure instanceof Error ? failure.message : \"The request failed.\" });\n }\n const responseText = await response.text().catch(() => \"\");\n const responseBody = readJsonBody(responseText);\n if (!response.ok) {\n throw mapHttpFailureToAgentsClientError(\n response.status,\n isPlainObject(responseBody) ? (responseBody as WireErrorBody) : null,\n response.headers.get(\"Retry-After\"),\n );\n }\n return (responseBody ?? {}) as ResponseBody;\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readJsonBody = (text: string): unknown => {\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\n/**\n * The conversation client over the module's own conversation routes (`AgentConversationReadsTrait`,\n * `AgentConversationWritesTrait`, the application's start route of `AgentConversationStartTrait`, optionally\n * `AgentSelectableModelsTrait`): `baseUrl` is where the application mounted its conversations controller, `fetchOptions`\n * what every request carries. Every function rejects with `AgentsClientError`. The client comes with live updates —\n * the polling default over the run-state read, which also reads at once after an accepted send — unless `polling` is\n * `false`.\n *\n * ```ts\n * const client = createAgentsHttpConversationClient({\n * baseUrl: \"/api/agents/conversations\",\n * fetchOptions: () => ({ headers: { Authorization: `Bearer ${readToken()}` } }),\n * });\n * <AgentsProvider client={client}><AgentChat /></AgentsProvider>\n * ```\n */\nexport const createAgentsHttpConversationClient = (options: AgentsHttpConversationClientOptions): AgentsConversationClient => {\n const client = new AgentsHttpConversationClient(options);\n return options.polling === false ? client : withPollingChangeSubscription(client, options.polling);\n};\n"],"names":["options"],"mappings":";;;;;;AAuCA,MAAM,aAA8C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,gBAAoD,CAAC,UAAU,QAAQ,WAAW;AACxF,MAAM,gBAAoD;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mBAAyD;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,eAAyD,CAAC,QAAQ,aAAa,SAAS,MAAM;AACpG,MAAM,yBAAwE,CAAC,QAAQ,UAAU,UAAU;AAC3G,MAAM,kBAAgF;AAAA,EACpF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,iBAA8E;AAAA,EAClF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,sBAAsB,CAAuB,YAA8B,UAC/E,OAAO,UAAU,YAAa,WAAiC,SAAS,KAAK,IAAK,QAAkB;AAEtG,MAAM,mBAAmB,CAAC,UACxB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AAEhE,MAAM,mBAAmB,CAAC,UAAmC,OAAO,UAAU,WAAW,QAAQ;AAG1F,MAAM,sB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AC,MAAM,QAAQ,KAAK;AAErE,MAAM,eAAe,CAAC,SAA0B;AAC9C,MAAI,KAAK,WAAW,GAAI,QAAO;AAC/B,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAkBO,MAAM,qCAAqC,CAAC,YAA2E;AAC5H,QAAM,SAAS,IAAI,6BAA6B,OAAO;AACvD,SAAO,QAAQ,YAAY,QAAQ,SAAS,8BAA8B,QAAQ,QAAQ,OAAO;AACnG;"}
1
+ {"version":3,"file":"client.js","sources":["../src/client/http/agents-http-mappers.ts","../src/client/http/createAgentsHttpConversationClient.ts"],"sourcesContent":["import {\n AGENTS_CLIENT_CONTEXT_LIMITS,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsClientErrorKind,\n type AgentsConversation,\n type AgentsConversationMessage,\n type ConversationActivity,\n type ConversationActivityElement,\n type ConversationMessageAuthorType,\n type ConversationMessageRole,\n type ConversationMessageSearchHit,\n type ConversationMessageStatus,\n type ConversationMessageType,\n type ConversationProgressStep,\n type ConversationRunState,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSubAgent,\n type SelectableModel,\n} from \"../../contract/conversation\";\nimport type {\n WireActivityLine,\n WireClientContext,\n WireClientContextRouteParameter,\n WireConversation,\n WireConversationActivityResponse,\n WireConversationMessage,\n WireConversationRunStateResponse,\n WireConversationSearchGroup,\n WireCustomerProgressStep,\n WireDelegationSubAgentRecord,\n WireErrorBody,\n WireSelectableModel,\n WireSemanticSearchHit,\n WireSet,\n} from \"./agents-http-wire\";\n\n// The vocabularies of the contract: a wire value outside one maps to null.\nconst RUN_STATES: readonly ConversationRunState[] = [\n \"IDLE\",\n \"QUEUED\",\n \"RUNNING\",\n \"AWAITING_DELEGATES\",\n \"FAILED\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nconst MESSAGE_ROLES: readonly ConversationMessageRole[] = [\"SYSTEM\", \"USER\", \"ASSISTANT\"];\nconst MESSAGE_TYPES: readonly ConversationMessageType[] = [\n \"TEXT\",\n \"TOOL_CALL\",\n \"CHECKPOINT\",\n \"ERROR\",\n \"SIGNAL\",\n \"TOOL_MESSAGE\",\n];\nconst MESSAGE_STATUSES: readonly ConversationMessageStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"COMPLETED\",\n \"FAILED\",\n];\nconst AUTHOR_TYPES: readonly ConversationMessageAuthorType[] = [\"USER\", \"ASSISTANT\", \"AGENT\", \"TOOL\"];\nconst PROGRESS_STEP_STATUSES: readonly ConversationProgressStep[\"status\"][] = [\"done\", \"active\", \"upcoming\"];\nconst ACTIVITY_STATES: readonly NonNullable<ConversationActivityElement[\"state\"]>[] = [\n \"queued\",\n \"running\",\n \"finished\",\n \"failed\",\n \"skipped\",\n];\nconst ACTIVITY_KINDS: readonly NonNullable<ConversationActivityElement[\"kind\"]>[] = [\n \"tool\",\n \"delegation\",\n \"background\",\n \"long\",\n \"turnStart\",\n];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a serialized set (`{ elements: [...] }`), a plain array, or the values of a keyed object. */\nexport const readWireSetElements = <Element>(\n wireSet: WireSet<Element> | Record<string, Element> | null | undefined,\n): Element[] => {\n if (!wireSet) return [];\n if (Array.isArray(wireSet)) return wireSet;\n if (typeof wireSet === \"object\" && \"elements\" in wireSet) {\n const elements = (wireSet as { elements?: Element[] | null }).elements;\n return Array.isArray(elements) ? elements : [];\n }\n return Object.values(wireSet as Record<string, Element>);\n};\n\nconst mapWireProgressStep = (wireStep: WireCustomerProgressStep): ConversationProgressStep => ({\n key: wireStep.key ?? \"\",\n label: wireStep.customerLabel ?? \"\",\n status: readVocabularyValue(PROGRESS_STEP_STATUSES, wireStep.status) ?? \"upcoming\",\n});\n\n/** An `AIConversation` as the contract's conversation. */\nexport const mapWireConversation = (wireConversation: WireConversation): AgentsConversation => {\n const conversation: AgentsConversation = {\n id: wireConversation.id ?? 0,\n agentSpaceKey: readNumberOrNull(wireConversation.agentSpaceId),\n runState: readVocabularyValue(RUN_STATES, wireConversation.runState),\n agentTurnOwedAt: readStringOrNull(wireConversation.agentTurnOwedAt),\n title: readStringOrNull(wireConversation.summary?.title),\n titleManuallyEdited: wireConversation.summary?.manuallyEdited === true,\n summary: readStringOrNull(wireConversation.summary?.text),\n created: readStringOrNull(wireConversation.created ?? wireConversation.changeHistory?.createdTime),\n updated: readStringOrNull(wireConversation.updated ?? wireConversation.changeHistory?.modifiedTime),\n purposeName: readStringOrNull(wireConversation.purposeName),\n initiatorType: readStringOrNull(wireConversation.initiatorType),\n scheduleId: readNumberOrNull(wireConversation.scheduleId),\n entryPointKey: readStringOrNull(wireConversation.entryPointKey),\n progressSteps: readWireSetElements(wireConversation.customerProgressSteps).map(mapWireProgressStep),\n };\n if (wireConversation.lastMessageId !== undefined) conversation.lastMessageId = readNumberOrNull(wireConversation.lastMessageId);\n if (wireConversation.aiPromptExtensionId !== undefined) {\n conversation.promptExtensionId = readNumberOrNull(wireConversation.aiPromptExtensionId);\n }\n return conversation;\n};\n\nconst mapWireSubAgent = (wireSubAgent: WireDelegationSubAgentRecord | null | undefined): ConversationSubAgent | null =>\n wireSubAgent\n ? {\n currentRunNumber: readNumberOrNull(wireSubAgent.currentRunNumber),\n runs: readWireSetElements(wireSubAgent.runs).map((wireRun) => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n })),\n }\n : null;\n\n/** An `AIConversationMessage` as the contract's message. */\nexport const mapWireConversationMessage = (wireMessage: WireConversationMessage): AgentsConversationMessage => {\n const message: AgentsConversationMessage = {\n id: wireMessage.id ?? 0,\n conversationId: readNumberOrNull(wireMessage.aiConversationId),\n indexInConversation: readNumberOrNull(wireMessage.indexInConversation),\n role: readVocabularyValue(MESSAGE_ROLES, wireMessage.role),\n messageType: readVocabularyValue(MESSAGE_TYPES, wireMessage.messageType),\n status: readVocabularyValue(MESSAGE_STATUSES, wireMessage.status),\n authorType: readVocabularyValue(AUTHOR_TYPES, wireMessage.authorType),\n signalSource: readStringOrNull(wireMessage.signalSource),\n message: wireMessage.message ?? \"\",\n createdDate: readStringOrNull(wireMessage.createdDate),\n toolCall: wireMessage.toolCall\n ? {\n toolCallId: readStringOrNull(wireMessage.toolCall.toolCallId),\n name: readStringOrNull(wireMessage.toolCall.name),\n arguments: wireMessage.toolCall.arguments ?? null,\n status: readStringOrNull(wireMessage.toolCall.status),\n }\n : null,\n delegatedConversations: readWireSetElements(wireMessage.delegatedConversations).map((delegated) => ({\n id: delegated.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, delegated.runState),\n })),\n subAgent: mapWireSubAgent(wireMessage.delegationResults?.subAgent),\n };\n const hasForensics =\n wireMessage.inputTokens != null || wireMessage.outputTokens != null || wireMessage.requestSnapshot != null;\n if (hasForensics) {\n message.forensics = {\n inputTokens: readNumberOrNull(wireMessage.inputTokens),\n outputTokens: readNumberOrNull(wireMessage.outputTokens),\n costInUSD: readNumberOrNull(wireMessage.costInUSD),\n requestSnapshot: wireMessage.requestSnapshot ?? null,\n };\n }\n return message;\n};\n\n/** The run-state read (`AIConversationRunStateGetResponseDto`). */\nexport const mapWireConversationRunState = (wireRunState: WireConversationRunStateResponse): ConversationRunStateRead => ({\n id: wireRunState.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, wireRunState.runState),\n agentTurnOwedAt: readStringOrNull(wireRunState.agentTurnOwedAt),\n lastMessageId: readNumberOrNull(wireRunState.lastMessageId),\n title: readStringOrNull(wireRunState.title),\n titleManuallyEdited: wireRunState.titleManuallyEdited === true,\n summary: readStringOrNull(wireRunState.summary),\n updated: readStringOrNull(wireRunState.updated),\n});\n\nconst mapWireActivityLine = (wireLine: WireActivityLine): ConversationActivityElement => ({\n toolCallMessageId: wireLine.toolCallMessageId ?? 0,\n batchId: readStringOrNull(wireLine.batchId),\n state: readVocabularyValue(ACTIVITY_STATES, wireLine.state),\n kind: readVocabularyValue(ACTIVITY_KINDS, wireLine.kind),\n childCount: readNumberOrNull(wireLine.childCount),\n helperIndex: readNumberOrNull(wireLine.helperIndex),\n line: readStringOrNull(wireLine.line),\n});\n\n/** The activity of a turn (`AIConversationActivityGetResponseDto`). */\nexport const mapWireConversationActivity = (wireActivity: WireConversationActivityResponse): ConversationActivity => ({\n turnMessageId: readNumberOrNull(wireActivity.turnMessageId),\n turnRunning: wireActivity.turnRunning === true,\n elements: readWireSetElements(wireActivity.elements).map(mapWireActivityLine),\n});\n\n/** A `SemanticSearchHit`. */\nexport const mapWireSearchHit = (wireHit: WireSemanticSearchHit): ConversationMessageSearchHit => ({\n messageId: readNumberOrNull(wireHit.messageId),\n conversationId: readNumberOrNull(wireHit.conversationId),\n indexInConversation: readNumberOrNull(wireHit.indexInConversation),\n role: readStringOrNull(wireHit.role),\n excerpt: wireHit.excerpt ?? \"\",\n relevance: readNumberOrNull(wireHit.relevance) ?? 0,\n created: readStringOrNull(wireHit.created),\n updated: readStringOrNull(wireHit.updated),\n title: readStringOrNull(wireHit.title),\n});\n\n/** An `AIConversationSearchGroup`. */\nexport const mapWireSearchGroup = (wireGroup: WireConversationSearchGroup): ConversationSearchGroup => ({\n conversationId: readNumberOrNull(wireGroup.conversationId),\n title: readStringOrNull(wireGroup.title),\n summary: readStringOrNull(wireGroup.summary),\n created: readStringOrNull(wireGroup.created),\n updated: readStringOrNull(wireGroup.updated),\n relevance: readNumberOrNull(wireGroup.relevance) ?? 0,\n hits: readWireSetElements(wireGroup.hits).map(mapWireSearchHit),\n});\n\n/** An `AgentCustomerSelectableModel`. */\nexport const mapWireSelectableModel = (wireModel: WireSelectableModel): SelectableModel => ({\n name: wireModel.name ?? \"\",\n displayName: wireModel.displayName ?? wireModel.name ?? \"\",\n description: wireModel.description ?? \"\",\n strengthLevel: readNumberOrNull(wireModel.strengthLevel),\n speedLevel: readNumberOrNull(wireModel.speedLevel),\n creditsMultiplier: readNumberOrNull(wireModel.creditsMultiplier),\n});\n\n/** The stable codes of the server's refusals the chat tells apart. */\nconst ERROR_KIND_BY_CODE: Readonly<Record<string, AgentsClientErrorKind>> = {\n AI_BUDGET_REACHED: \"budget\",\n RATE_LIMIT_EXCEEDED: \"rateLimit\",\n CONVERSATION_CLOSED: \"closed\",\n};\n\n/**\n * A refused request as the port's error: the stable code first (`errorCode` of the JSON body), then the status — 429\n * `rateLimit` (with `Retry-After`), 404 `notFound`, 403 and 401 `forbidden`, 5xx `network`, everything else `other`.\n */\nexport const mapHttpFailureToAgentsClientError = (\n httpStatus: number,\n wireErrorBody: WireErrorBody | null,\n retryAfterHeader: string | null,\n): AgentsClientError => {\n const code = wireErrorBody?.errorCode ?? wireErrorBody?.code ?? null;\n const message = wireErrorBody?.error ?? wireErrorBody?.message ?? undefined;\n const retryAfterOfHeader = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader) : null;\n const retryAfterSeconds = readNumberOrNull(wireErrorBody?.retryAfterSeconds) ?? retryAfterOfHeader;\n const kindOfCode = code !== null ? ERROR_KIND_BY_CODE[code] : undefined;\n const kind: AgentsClientErrorKind =\n kindOfCode ??\n (httpStatus === 429\n ? \"rateLimit\"\n : httpStatus === 404\n ? \"notFound\"\n : httpStatus === 403 || httpStatus === 401\n ? \"forbidden\"\n : httpStatus >= 500\n ? \"network\"\n : \"other\");\n return new AgentsClientError(kind, { message: message ?? undefined, code, retryAfterSeconds, httpStatus });\n};\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f]/;\n\n/** A text field of the client context as it goes out: trimmed, or left out when empty, over its cap or not one line. */\nconst readClientContextText = (value: string | number | null | undefined, maxChars: number): string | undefined => {\n if (value === null || value === undefined) return undefined;\n const text = String(value).trim();\n if (text === \"\" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return undefined;\n return text;\n};\n\n/**\n * The client context as the body field `clientContext` carries it (`AgentClientContext`): the route parameters as a\n * list of `{name, value}`. A field over its cap ({@link AGENTS_CLIENT_CONTEXT_LIMITS}) or with a control character is\n * left out — never cut — so a send never fails on the context; the route parameters go together or not at all.\n * Undefined when nothing is left.\n */\nexport const mapClientContextToWire = (clientContext: AgentsClientContext | null | undefined): WireClientContext | undefined => {\n if (!clientContext) return undefined;\n const wireClientContext: WireClientContext = {};\n const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);\n if (routePath !== undefined) wireClientContext.routePath = routePath;\n const routeParameters: WireClientContextRouteParameter[] = Object.entries(clientContext.routeParameters ?? {})\n .filter(([name, value]) => name.trim() !== \"\" && value !== null && value !== undefined)\n .map(([name, value]) => ({ name, value: String(value) }));\n const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join(\"&\");\n if (\n routeParameters.length > 0 &&\n routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount &&\n routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars &&\n !CONTROL_CHARACTERS.test(routeParametersText)\n ) {\n wireClientContext.routeParameters = routeParameters;\n }\n const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);\n if (recordKind !== undefined) wireClientContext.recordKind = recordKind;\n const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);\n if (recordId !== undefined) wireClientContext.recordId = recordId;\n const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);\n if (tab !== undefined) wireClientContext.tab = tab;\n return Object.keys(wireClientContext).length > 0 ? wireClientContext : undefined;\n};\n","import type {\n AgentsConversationClient,\n AgentsConversationClientBindingOptions,\n AgentsConversationOperation,\n} from \"../AgentsConversationClient\";\nimport {\n AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED,\n AgentsClientError,\n type AgentsClientContext,\n type AgentsConversation,\n type ChangedConversationMessages,\n type ChangedMessagesRequest,\n type ConversationActivity,\n type ConversationAttachmentReference,\n type ConversationListQueryOptions,\n type ConversationMessageSearchHit,\n type ConversationMessagesPage,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSearchOptions,\n type ConversationSignal,\n type PostedMessage,\n type SelectableModel,\n type StartedConversation,\n} from \"../../contract/conversation\";\nimport type { AgentUIState } from \"../../ui/agent-ui-state\";\nimport type { AgentUIClientBinding } from \"../../ui/AgentUIClient\";\nimport type { ClientToolAnswer } from \"../../ui/client-tools\";\nimport {\n acceptArrivedRealtimeMessage,\n type AgentRealtimeListenerCredential,\n type AgentRealtimeMessageDelivery,\n} from \"../../ui/realtime-arrival\";\nimport { composeAttachmentMessageText } from \"../compose-attachment-message-text\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../polling/withPollingChangeSubscription\";\nimport {\n mapClientContextToWire,\n mapHttpFailureToAgentsClientError,\n mapWireConversation,\n mapWireConversationActivity,\n mapWireConversationMessage,\n mapWireConversationRunState,\n mapWireSearchGroup,\n mapWireSearchHit,\n mapWireSelectableModel,\n readWireSetElements,\n} from \"./agents-http-mappers\";\nimport type {\n WireConversationActivityResponse,\n WireConversationMessageSearchResponse,\n WireConversationMessagesResponse,\n WireConversationResponse,\n WireConversationRunStateResponse,\n WireConversationSearchResponse,\n WireConversationsResponse,\n WireConversationStartResponse,\n WireErrorBody,\n WireSelectableModelsResponse,\n} from \"./agents-http-wire\";\n\n/** What every request of the binding carries from the host: headers, credentials, mode, cache. */\nexport type AgentsHttpFetchOptions = Omit<RequestInit, \"method\" | \"body\">;\n\nexport interface AgentsHttpConversationClientOptions extends AgentsConversationClientBindingOptions {\n /**\n * Where the application's conversations controller is mounted (its `#[Route]`): a path such as\n * `/api/agents/conversations` or an absolute URL. The module's routes are relative to it.\n */\n baseUrl: string;\n /**\n * Request options every request carries (credentials, an authorization header). A function is called per request,\n * so it may hand out a fresh token. Default: none (the browser's defaults: same-origin credentials).\n */\n fetchOptions?: AgentsHttpFetchOptions | (() => AgentsHttpFetchOptions | Promise<AgentsHttpFetchOptions>);\n /** The fetch function. Default: the global `fetch`. */\n fetch?: typeof fetch;\n /**\n * The application's start route below `baseUrl` (`AgentConversationStartTrait` declares none). Default: `/start` for\n * a start without an agent space (key 0), `/start/{agentSpaceKey}` otherwise — the start DTO reads `agentSpaceId`\n * from the path.\n */\n buildStartPath?: (agentSpaceKey: number) => string;\n /**\n * The controller uses `AgentSelectableModelsTrait` (`GET …/selectable-models`): the client offers\n * `getSelectableModels` and the chat shows the model picker. Default false.\n */\n hasSelectableModelsRoute?: boolean;\n /**\n * The live updates: the polling default over the run-state read (`withPollingChangeSubscription`), which also reads\n * at once after a post, a signal or a retry the server accepted. The intervals of\n * `PollingConversationChangeSubscriptionOptions`; `false` = no subscription (the host adds its own push transport).\n * Default: polling with the default intervals.\n */\n polling?: PollingConversationChangeSubscriptionOptions | false;\n /**\n * What the owner's client shows, read on every start, posted message and injected signal and sent as the body field\n * `clientContext` (the route, its parameters, the record on screen, the tab). The agent reads the newest one as one\n * line beside the owner's newest message. A field over its cap is left out, never cut. Default: none.\n */\n clientContext?: (operation: AgentsClientContextOperation) => AgentsClientContext | null | undefined;\n /**\n * The UI side of `Agent.UI` (`AgentUIClient` of `@mgamadeus/ddd-agents/ui`): its client id and UI state ride on every\n * write and every run-state read; a client tool request the run-state read delivers goes to it, and the binding\n * posts its answer (`POST /{conversationId}/clientToolRequests/{requestId}/answer`). Default: none.\n */\n uiClient?: AgentUIClientBinding;\n /**\n * The open messages of the realtime port of other types than a client tool request (types other packages\n * registered), as the run-state read delivers them; a client acts on one type and key once. Default: none.\n */\n onRealtimeMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void;\n /** What the client needs to listen on the host's transport, with every run-state read (null without one). Default: none. */\n onRealtimeListenerCredential?: (conversationId: number, credential: AgentRealtimeListenerCredential | null) => void;\n}\n\n/** The writes that carry the client context. */\nexport type AgentsClientContextOperation = \"startConversation\" | \"postMessage\" | \"injectSignal\";\n\n/** The page size of a changed-messages read when the request names none (as the chat sends it). */\nexport const AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE = 50;\n\n/** The expand of every message page: the delegated children with the two fields the chat reads. */\nconst MESSAGES_EXPAND = \"delegatedConversations(select=id,runState)\";\n\nconst defaultBuildStartPath = (agentSpaceKey: number): string => (agentSpaceKey > 0 ? `/start/${agentSpaceKey}` : \"/start\");\n\ntype QueryParameters = Record<string, string | number | boolean | undefined | null>;\n\ninterface HttpRequest {\n operation: AgentsConversationOperation;\n method: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: QueryParameters;\n body?: unknown;\n}\n\n/** A filter value as the query-options grammar writes it: quoted. */\nconst quoteFilterValue = (value: number | string): string => `'${String(value).replace(/'/g, \"\\\\'\")}'`;\n\n/** The module's conversation routes over fetch: one request per port function, the wire mapped onto the contract. */\nclass AgentsHttpConversationClient implements AgentsConversationClient {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n\n constructor(protected readonly options: AgentsHttpConversationClientOptions) {\n if (options.hasSelectableModelsRoute) this.getSelectableModels = this.readSelectableModels;\n }\n\n // ── Reads ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\n getConversationMetadata = async (conversationId: number): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"getConversationMetadata\",\n method: \"GET\",\n path: `/${conversationId}`,\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n getConversationRunState = async (conversationId: number): Promise<ConversationRunStateRead> => {\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n const response = await this.request<WireConversationRunStateResponse>({\n operation: \"getConversationRunState\",\n method: \"GET\",\n path: `/${conversationId}/runState`,\n query: uiClient ? { clientId: uiClient.clientId, uiStateJson: uiState ? JSON.stringify(uiState) : undefined } : undefined,\n });\n const sendAnswer = (requestId: number, answer: ClientToolAnswer): Promise<void> =>\n this.answerClientToolRequest(conversationId, requestId, answer);\n if (uiClient && response.clientToolRequest) {\n uiClient.acceptClientToolRequest(conversationId, response.clientToolRequest, sendAnswer);\n }\n for (const message of readWireSetElements(response.realtimeMessages)) {\n if (uiClient) acceptArrivedRealtimeMessage(conversationId, message, uiClient, sendAnswer, this.options.onRealtimeMessage);\n else this.options.onRealtimeMessage?.(conversationId, message);\n }\n this.options.onRealtimeListenerCredential?.(conversationId, response.realtimeListenerCredential ?? null);\n return mapWireConversationRunState(response);\n };\n\n /** Posts the answer of the UI client to a client tool request (`Agent.UI`); a refused answer is the server's word. */\n answerClientToolRequest = async (conversationId: number, requestId: number, answer: ClientToolAnswer): Promise<void> => {\n await this.request<unknown>({\n operation: \"answerClientToolRequest\",\n method: \"POST\",\n path: `/${conversationId}/clientToolRequests/${requestId}/answer`,\n body: {\n clientId: this.options.uiClient?.clientId ?? \"\",\n outcome: answer.outcome,\n text: answer.text,\n detailsJson: JSON.stringify(answer.details ?? {}),\n pictureBase64: answer.pictureBase64,\n uiStateJson: this.readUIStateJsonAfterAnswer(),\n },\n });\n };\n\n /** What the UI shows after the request was carried out, so the server's `[SIGNAL:ui]` note is current at once. */\n protected readUIStateJsonAfterAnswer(): string | undefined {\n const uiState: AgentUIState | null = this.options.uiClient?.readUIState() ?? null;\n return uiState ? JSON.stringify(uiState) : undefined;\n }\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\"getNewestMessagesPage\", conversationId, pageSize, undefined);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.readMessagesPage(\n \"getOlderMessagesPage\",\n conversationId,\n pageSize,\n `indexInConversation lt ${quoteFilterValue(beforeIndex)}`,\n );\n\n getChangedMessages = async (\n conversationId: number,\n request: ChangedMessagesRequest,\n ): Promise<ChangedConversationMessages> => {\n const page = await this.readMessagesPage(\n \"getChangedMessages\",\n conversationId,\n request.pageSize ?? AGENTS_HTTP_DEFAULT_CHANGED_MESSAGES_PAGE_SIZE,\n `(id gt ${quoteFilterValue(request.highestKnownId)} or indexInConversation ge ${quoteFilterValue(request.fromIndex)})`,\n );\n return { messages: page.messages };\n };\n\n listConversations = async (agentSpaceKey: number, options: ConversationListQueryOptions = {}): Promise<AgentsConversation[]> => {\n const filters = [\"rootConversationId eq null\"];\n if (agentSpaceKey > 0) filters.push(`agentSpaceId eq ${quoteFilterValue(agentSpaceKey)}`);\n const response = await this.request<WireConversationsResponse>({\n operation: \"listConversations\",\n method: \"GET\",\n path: \"/listAllConversations\",\n query: {\n filters: filters.join(\" and \"),\n orderBy: \"id desc\",\n top: options.paging?.top,\n skip: options.paging?.skip,\n },\n });\n const conversations = readWireSetElements(response.aiConversations).map(mapWireConversation);\n // Without a summary there is no title yet; the list leaves such a conversation out unless asked for it.\n return options.includeUnsummarized ? conversations : conversations.filter((conversation) => conversation.title !== null);\n };\n\n searchConversations = async (text: string, options: ConversationSearchOptions = {}): Promise<ConversationSearchGroup[]> => {\n const response = await this.request<WireConversationSearchResponse>({\n operation: \"searchConversations\",\n method: \"GET\",\n path: \"/search\",\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.conversations).map(mapWireSearchGroup);\n };\n\n searchConversationMessages = async (\n conversationId: number,\n text: string,\n options: ConversationSearchOptions = {},\n ): Promise<ConversationMessageSearchHit[]> => {\n const response = await this.request<WireConversationMessageSearchResponse>({\n operation: \"searchConversationMessages\",\n method: \"GET\",\n path: `/${conversationId}/messages/search`,\n query: { query: text, limit: options.limit, excerptChars: options.excerptLength },\n });\n return readWireSetElements(response.hits).map(mapWireSearchHit);\n };\n\n getConversationActivity = async (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> => {\n const response = await this.request<WireConversationActivityResponse>({\n operation: \"getConversationActivity\",\n method: \"GET\",\n path: `/${conversationId}/activity`,\n query: { turnMessageId: turnMessageId ?? undefined },\n });\n return mapWireConversationActivity(response);\n };\n\n composeSentMessageText = (text: string, attachments: ConversationAttachmentReference[] | undefined): string =>\n composeAttachmentMessageText(text, attachments);\n\n // ── Writes ────────────────────────────────────────────────────────────────────────────────────────────────────\n\n startConversation = async (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> => {\n const buildStartPath = this.options.buildStartPath ?? defaultBuildStartPath;\n const response = await this.request<WireConversationStartResponse>({\n operation: \"startConversation\",\n method: \"POST\",\n path: buildStartPath(request.agentSpaceKey),\n query: { aiModelName: request.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(request.text, request.attachments) },\n ...(request.startSignalText ? { signalText: request.startSignalText } : {}),\n ...(request.entryPointKey ? { entryPointKey: request.entryPointKey } : {}),\n ...this.readClientContextBody(\"startConversation\"),\n },\n });\n const wireConversation = response.aiConversation ?? {};\n const reopenedExisting = response.reopenedExistingConversation === true;\n return {\n conversation: mapWireConversation(wireConversation),\n messages: reopenedExisting ? [] : readWireSetElements(wireConversation.messages).map(mapWireConversationMessage),\n reopenedExisting,\n };\n };\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"postMessage\",\n method: \"POST\",\n path: `/${conversationId}/postMessage`,\n query: { aiModelName: message.model },\n body: {\n aiConversationMessage: { message: composeAttachmentMessageText(message.text, message.attachments) },\n ...this.readClientContextBody(\"postMessage\"),\n },\n });\n return { messages: readWireSetElements(response.aiConversation?.messages).map(mapWireConversationMessage) };\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"injectSignal\",\n method: \"POST\",\n path: `/${conversationId}/injectSignal`,\n body: {\n signalText: signal.text,\n ...(signal.source ? { signalSource: signal.source } : {}),\n ...this.readClientContextBody(\"injectSignal\"),\n },\n });\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.request<WireConversationResponse>({\n operation: \"retryConversation\",\n method: \"POST\",\n path: `/${conversationId}/retry`,\n });\n };\n\n renameConversation = async (conversationId: number, title: string): Promise<AgentsConversation> => {\n const response = await this.request<WireConversationResponse>({\n operation: \"renameConversation\",\n method: \"PATCH\",\n path: `/${conversationId}/title`,\n body: { title },\n });\n return mapWireConversation(response.aiConversation ?? {});\n };\n\n deleteConversation = async (conversationId: number): Promise<void> => {\n await this.request<unknown>({ operation: \"deleteConversation\", method: \"DELETE\", path: `/${conversationId}` });\n };\n\n // ── Transport ─────────────────────────────────────────────────────────────────────────────────────────────────\n\n protected readSelectableModels = async (): Promise<SelectableModel[]> => {\n const response = await this.request<WireSelectableModelsResponse>({\n operation: \"getSelectableModels\",\n method: \"GET\",\n path: \"/selectable-models\",\n });\n return readWireSetElements(response.models).map(mapWireSelectableModel);\n };\n\n protected async readMessagesPage(\n operation: AgentsConversationOperation,\n conversationId: number,\n pageSize: number,\n filters: string | undefined,\n ): Promise<ConversationMessagesPage> {\n const response = await this.request<WireConversationMessagesResponse>({\n operation,\n method: \"GET\",\n path: `/${conversationId}/messages`,\n query: { filters, orderBy: \"indexInConversation desc\", top: pageSize, expand: MESSAGES_EXPAND },\n });\n return {\n messages: readWireSetElements(response.messages).map(mapWireConversationMessage),\n hasMoreOlder: response.hasMoreOlder === true,\n };\n }\n\n /** The body field `clientContext` of a write, from the host's option; nothing when it gives none. */\n protected readClientContextBody(operation: AgentsClientContextOperation): {\n clientContext?: ReturnType<typeof mapClientContextToWire>;\n clientId?: string;\n uiState?: AgentUIState;\n } {\n const wireClientContext = mapClientContextToWire(this.options.clientContext?.(operation));\n const uiClient = this.options.uiClient;\n const uiState = uiClient?.readUIState() ?? null;\n return {\n ...(wireClientContext ? { clientContext: wireClientContext } : {}),\n ...(uiClient ? { clientId: uiClient.clientId } : {}),\n ...(uiState ? { uiState } : {}),\n };\n }\n\n /** The URL of a route: the base, the path, the binding's query parameters with the host's extra ones over them. */\n protected buildUrl(request: HttpRequest): string {\n const searchParameters = new URLSearchParams();\n const extraParameters = this.options.extraRequestParameters?.(request.operation) ?? {};\n for (const [name, value] of Object.entries({ ...request.query, ...extraParameters })) {\n if (value !== undefined && value !== null) searchParameters.set(name, String(value));\n }\n const query = searchParameters.toString();\n const baseUrl = this.options.baseUrl.replace(/\\/+$/, \"\");\n return `${baseUrl}${request.path}${query ? `?${query}` : \"\"}`;\n }\n\n protected async readFetchOptions(): Promise<AgentsHttpFetchOptions> {\n const { fetchOptions } = this.options;\n return typeof fetchOptions === \"function\" ? await fetchOptions() : (fetchOptions ?? {});\n }\n\n /** One request; every failure becomes an `AgentsClientError` (the port's one error shape). */\n protected async request<ResponseBody>(request: HttpRequest): Promise<ResponseBody> {\n const fetchFunction = this.options.fetch ?? globalThis.fetch.bind(globalThis);\n let response: Response;\n try {\n const fetchOptions = await this.readFetchOptions();\n const headers = new Headers(fetchOptions.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (request.body !== undefined && !headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n response = await fetchFunction(this.buildUrl(request), {\n ...fetchOptions,\n headers,\n method: request.method,\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n });\n } catch (failure) {\n if (failure instanceof AgentsClientError) throw failure;\n const isAbort = failure instanceof Error && failure.name === \"AbortError\";\n throw isAbort\n ? new AgentsClientError(\"other\", { code: AGENTS_CLIENT_ERROR_CODE_REQUEST_ABORTED, message: \"The request was cancelled.\" })\n : new AgentsClientError(\"network\", { message: failure instanceof Error ? failure.message : \"The request failed.\" });\n }\n const responseText = await response.text().catch(() => \"\");\n const responseBody = readJsonBody(responseText);\n if (!response.ok) {\n throw mapHttpFailureToAgentsClientError(\n response.status,\n isPlainObject(responseBody) ? (responseBody as WireErrorBody) : null,\n response.headers.get(\"Retry-After\"),\n );\n }\n return (responseBody ?? {}) as ResponseBody;\n }\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readJsonBody = (text: string): unknown => {\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\n/**\n * The conversation client over the module's own conversation routes (`AgentConversationReadsTrait`,\n * `AgentConversationWritesTrait`, the application's start route of `AgentConversationStartTrait`, optionally\n * `AgentSelectableModelsTrait`): `baseUrl` is where the application mounted its conversations controller, `fetchOptions`\n * what every request carries. Every function rejects with `AgentsClientError`. The client comes with live updates —\n * the polling default over the run-state read, which also reads at once after an accepted send — unless `polling` is\n * `false`.\n *\n * ```ts\n * const client = createAgentsHttpConversationClient({\n * baseUrl: \"/api/agents/conversations\",\n * fetchOptions: () => ({ headers: { Authorization: `Bearer ${readToken()}` } }),\n * });\n * <AgentsProvider client={client}><AgentChat /></AgentsProvider>\n * ```\n */\nexport const createAgentsHttpConversationClient = (options: AgentsHttpConversationClientOptions): AgentsConversationClient => {\n const client = new AgentsHttpConversationClient(options);\n return options.polling === false ? client : withPollingChangeSubscription(client, options.polling);\n};\n"],"names":["options"],"mappings":";;;;;;;AAuCA,MAAM,aAA8C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,gBAAoD,CAAC,UAAU,QAAQ,WAAW;AACxF,MAAM,gBAAoD;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mBAAyD;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,eAAyD,CAAC,QAAQ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@ -166,6 +166,20 @@ export interface WireConversationRunStateResponse {
166
166
  argumentsJson: string;
167
167
  secondsLeft: number;
168
168
  } | null;
169
+ /** The open messages of the realtime port for the reading client (`AgentRealtimeMessageDeliveries`) */
170
+ realtimeMessages?: WireSet<{
171
+ messageType: string;
172
+ messageKey: string;
173
+ payloadJson: string;
174
+ secondsLeft: number;
175
+ }> | null;
176
+ /** What the client needs to listen on the host's transport (`AgentRealtimeListenerCredential`) */
177
+ realtimeListenerCredential?: {
178
+ transportName: string;
179
+ credential: string;
180
+ listenPath?: string | null;
181
+ expiresAt?: string | null;
182
+ } | null;
169
183
  }
170
184
  /** `AIConversationActivityGetResponseDto`. */
171
185
  export interface WireConversationActivityResponse {
@@ -1,6 +1,7 @@
1
1
  import type { AgentsConversationClient, AgentsConversationClientBindingOptions } from "../AgentsConversationClient";
2
2
  import { type AgentsClientContext } from "../../contract/conversation";
3
3
  import type { AgentUIClientBinding } from "../../ui/AgentUIClient";
4
+ import { type AgentRealtimeListenerCredential, type AgentRealtimeMessageDelivery } from "../../ui/realtime-arrival";
4
5
  import type { PollingConversationChangeSubscriptionOptions } from "../polling/createPollingConversationChangeSubscription";
5
6
  /** What every request of the binding carries from the host: headers, credentials, mode, cache. */
6
7
  export type AgentsHttpFetchOptions = Omit<RequestInit, "method" | "body">;
@@ -47,6 +48,13 @@ export interface AgentsHttpConversationClientOptions extends AgentsConversationC
47
48
  * posts its answer (`POST /{conversationId}/clientToolRequests/{requestId}/answer`). Default: none.
48
49
  */
49
50
  uiClient?: AgentUIClientBinding;
51
+ /**
52
+ * The open messages of the realtime port of other types than a client tool request (types other packages
53
+ * registered), as the run-state read delivers them; a client acts on one type and key once. Default: none.
54
+ */
55
+ onRealtimeMessage?: (conversationId: number, message: AgentRealtimeMessageDelivery) => void;
56
+ /** What the client needs to listen on the host's transport, with every run-state read (null without one). Default: none. */
57
+ onRealtimeListenerCredential?: (conversationId: number, credential: AgentRealtimeListenerCredential | null) => void;
50
58
  }
51
59
  /** The writes that carry the client context. */
52
60
  export type AgentsClientContextOperation = "startConversation" | "postMessage" | "injectSignal";
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * `@mgamadeus/ddd-agents/ui` — the client side of `Agent.UI`: the runner of the client tool requests, the four
3
3
  * adapter contracts an application implements (`ScreenTargetSource`, `ScreenNavigator`, `ScreenReader`,
4
- * `ScreenHighlighter`), the Markdown writer and reference registry, DOM defaults for reader and highlighter, the UI
5
- * state the client reports, and the hook.
4
+ * `ScreenHighlighter`, optionally `ScreenPictureCapturer`, `AgentWindowAdapter`, `ScreenPathGuide` and handlers of
5
+ * further request types), the Markdown writer and reference registry, DOM defaults (reader, highlighter, target
6
+ * source from `data-agent-anchor` marks, picture capturer, path guide), the agent-window adapter, the realtime arrival
7
+ * adapter and dev helper, the UI state the client reports, and the hook.
6
8
  */
7
9
  export * from "../ui/client-tools";
8
10
  export * from "../ui/agent-ui-state";
@@ -12,3 +14,8 @@ export { useAgentUIClient } from "../ui/useAgentUIClient";
12
14
  export * from "../ui/screen-markdown";
13
15
  export * from "../ui/DomScreenReader";
14
16
  export * from "../ui/DomScreenHighlighter";
17
+ export * from "../ui/DomScreenTargetSource";
18
+ export * from "../ui/DomScreenPathGuide";
19
+ export * from "../ui/screen-picture";
20
+ export * from "../ui/agent-window";
21
+ export * from "../ui/realtime-arrival";
@@ -1,4 +1,4 @@
1
- import { type ClientToolAnswer, type ClientToolRequestDelivery, type ScreenAdapters, type ScreenTarget } from "./client-tools";
1
+ import { type ClientToolAnswer, type ClientToolRequestDelivery, type ClientToolRequestType, type ScreenAdapters, type ScreenTarget } from "./client-tools";
2
2
  /** The most characters of screen content in one answer (the server cuts at 8,000 again). */
3
3
  export declare const MAX_SCREEN_CHARS = 6000;
4
4
  /** Posts an answer; the transport is the application's. */
@@ -22,6 +22,12 @@ export declare class ClientToolRequestRunner {
22
22
  protected runAndAnswer(delivery: ClientToolRequestDelivery, receivedAt: number, sendAnswer: ClientToolAnswerSender): Promise<void>;
23
23
  /** The answer of one request. Exposed for the tests. */
24
24
  run(delivery: ClientToolRequestDelivery, receivedAt?: number): Promise<ClientToolAnswer>;
25
+ /** A request type the application registered: its handler, else `UNKNOWN_REQUEST`. */
26
+ protected runRequestOfApplication(delivery: ClientToolRequestDelivery, parameters: Record<string, unknown>): Promise<ClientToolAnswer>;
27
+ /** Lets the agent window make room before the agent works on the screen (the default for the screen requests). */
28
+ protected stepAgentWindowAside(requestType: ClientToolRequestType): Promise<void>;
29
+ protected setWindowMode(parameters: Record<string, unknown>): Promise<ClientToolAnswer>;
30
+ protected readScreenPicture(parameters: Record<string, unknown>): Promise<ClientToolAnswer>;
25
31
  protected readScreen(parameters: Record<string, unknown>): ClientToolAnswer;
26
32
  protected listTargets(parameters: Record<string, unknown>): ClientToolAnswer;
27
33
  protected openTarget(parameters: Record<string, unknown>): Promise<ClientToolAnswer>;
@@ -0,0 +1,30 @@
1
+ import type { ScreenOpenRequest, ScreenPathGuide, ScreenTarget } from "./client-tools";
2
+ /** How many times a target is guided before the agent just opens it (`shouldGuide` default). */
3
+ export declare const DEFAULT_GUIDES_PER_TARGET = 2;
4
+ /** The key prefix of the guide counts in localStorage. */
5
+ export declare const PATH_GUIDE_COUNT_KEY_PREFIX = "ddd-agents:pathGuide:";
6
+ /** How long one step of the path stays marked, in ms. */
7
+ export declare const PATH_GUIDE_STEP_MS = 700;
8
+ /** The class a marked step of the path carries; the step also gets an outline in the theme's `--ring` (inline, restored after). */
9
+ export declare const PATH_GUIDE_CLASS = "agents-path-guide-step";
10
+ /**
11
+ * The default `shouldGuide`: the first `limit` opens of a target are guided, counted per key in localStorage; without
12
+ * storage (private window, blocked) every open is guided once per page life.
13
+ */
14
+ export declare const createGuideCounter: (limit?: number, readStorage?: () => Pick<Storage, 'getItem' | 'setItem'> | null) => ((targetKey: string) => boolean);
15
+ export interface DomScreenPathGuideOptions {
16
+ /** The elements of the way to the target in order (menu group, menu entry, tab); missing ones are skipped */
17
+ findPathElements: (target: ScreenTarget, request: ScreenOpenRequest) => Element[];
18
+ /** The route the user is on (without the basePath and query) */
19
+ currentRoute: () => string;
20
+ /** Whether this open of the target is guided; default the first `DEFAULT_GUIDES_PER_TARGET` per key */
21
+ shouldGuide?: (targetKey: string) => boolean;
22
+ stepMs?: number;
23
+ }
24
+ /**
25
+ * The DOM default of `ScreenPathGuide`: marks the elements of the way to the target one after the other
26
+ * (`PATH_GUIDE_CLASS`), so the user learns where the screen lives. It runs beside the navigation and never delays the
27
+ * answer. Skipped under reduced motion, when the user already is on the target, when no element of the way is on the
28
+ * screen (plain navigation), and when `shouldGuide` says so. Esc or a click cancels it.
29
+ */
30
+ export declare const createDomScreenPathGuide: (options: DomScreenPathGuideOptions) => ScreenPathGuide;
@@ -0,0 +1,24 @@
1
+ import type { ScreenTarget, ScreenTargetSource } from "./client-tools";
2
+ /** The attribute that marks an element as a screen the user can open; its value is the target key. */
3
+ export declare const AGENT_ANCHOR_ATTRIBUTE = "data-agent-anchor";
4
+ /** The attribute that puts a mark into a group (`groupKey` of `createDomScreenTargetSource()`). */
5
+ export declare const AGENT_ANCHOR_GROUP_ATTRIBUTE = "data-agent-anchor-group";
6
+ export interface DomScreenTargetSourceOptions {
7
+ /** Where the marks are looked for; default the document */
8
+ root?: () => ParentNode | null;
9
+ /** Only the marks of this group (`data-agent-anchor-group`); default every mark */
10
+ groupKey?: string;
11
+ }
12
+ /**
13
+ * Reads one `ScreenTarget` from a mark, or null when it lacks a valid key or a route. The attributes:
14
+ * `data-agent-anchor` (the key), `data-agent-label` (else the text), `data-agent-group`, `data-agent-route` (else the
15
+ * link's path), and the comma lists `data-agent-parameters`, `data-agent-tabs`, `data-agent-filters`,
16
+ * `data-agent-views`.
17
+ */
18
+ export declare const readScreenTargetOfMark: (element: Element) => ScreenTarget | null;
19
+ /**
20
+ * A `ScreenTargetSource` from the marks of the rendered navigation: every element with `data-agent-anchor` the user
21
+ * sees is a screen the user may open (the application renders only what its rights allow, so the marks carry its
22
+ * rights). The first mark of a key wins. An application with a route table of its own writes its own source instead.
23
+ */
24
+ export declare const createDomScreenTargetSource: (options?: DomScreenTargetSourceOptions) => ScreenTargetSource;
@@ -0,0 +1,19 @@
1
+ import type { AgentWindowAdapter, ClientToolRequestType } from "./client-tools";
2
+ export interface AgentWindowAdapterOptions {
3
+ /** The mode the window shows now */
4
+ getMode: () => string;
5
+ /** Shows a mode; called only with a mode of `modes` */
6
+ applyMode: (mode: string) => void | Promise<void>;
7
+ /** The modes the application knows (`setAgentWindowMode` refuses others) */
8
+ modes: string[];
9
+ /** The mode of `stepAside()`; default `aside` */
10
+ asideMode?: string;
11
+ /** The request types the window steps aside for; default `OPEN_TARGET`, `HIGHLIGHT`, a picture (`READ_SCREEN`) */
12
+ stepAsideFor?: ClientToolRequestType[];
13
+ }
14
+ /**
15
+ * An `AgentWindowAdapter` over the application's own window state: `stepAside()` remembers the mode and shows the
16
+ * aside mode, `restore()` goes back to the remembered mode, `setMode()` shows a known mode. Stepping aside before the
17
+ * agent opens a screen, marks elements or takes a picture is the default.
18
+ */
19
+ export declare const createAgentWindowAdapter: (options: AgentWindowAdapterOptions) => AgentWindowAdapter;