@mgamadeus/ddd-agents 0.6.5 → 0.6.7
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 +6 -1
- package/dist/chunks/realtime-arrival-BfsAPwqQ.js.map +1 -1
- package/dist/types/ui/AgentUIClient.d.ts +5 -0
- package/dist/types/ui/ClientToolRequestRunner.d.ts +6 -2
- package/dist/types/ui/DomScreenReader.d.ts +46 -2
- package/dist/types/ui/agent-ui-state.d.ts +5 -0
- package/dist/types/ui/client-tools.d.ts +2 -0
- package/dist/types/ui/screen-markdown.d.ts +15 -3
- package/dist/types/ui/screen-picture.d.ts +42 -5
- package/dist/ui.js +278 -39
- package/dist/ui.js.map +1 -1
- package/package.json +1 -1
- package/public-api.json +7 -0
package/dist/ui.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui.js","sources":["../src/ui/client-tools.ts","../src/ui/ClientToolRequestRunner.ts","../src/ui/AgentUIClient.ts","../src/ui/useAgentUIClient.ts","../src/ui/screen-markdown.ts","../src/ui/DomScreenReader.ts","../src/ui/DomScreenHighlighter.ts","../src/ui/DomScreenTargetSource.ts","../src/ui/DomScreenPathGuide.ts","../src/ui/screen-picture.ts","../src/ui/agent-window.ts","../src/ui/account-realtime.ts"],"sourcesContent":["/**\n * The client half of the agent's client tools: a tool on the\n * server sends a request to the client (a browser tab, an app) that shows the conversation; the client executes it through the\n * application's adapters and posts the answer. Everything here is generic: no menu, no route, no word of one\n * application. The application supplies the four adapters (`ScreenAdapters`).\n *\n * Pure (no React, no app imports), so the logic tests cover it.\n */\n\n/** What the server asks a tab to do (`AgentClientToolRequest::TYPE_*`). */\nexport type ClientToolRequestType = 'READ_SCREEN' | 'LIST_TARGETS' | 'OPEN_TARGET' | 'HIGHLIGHT' | 'SET_WINDOW_MODE';\n\n/** A request as the run-state read delivers it. */\nexport interface ClientToolRequestDelivery {\n id: number;\n requestType: ClientToolRequestType | string;\n argumentsJson: string;\n secondsLeft: number;\n}\n\n/** The answer a tab posts: `OK` or a refusal code, the text, small facts. */\nexport interface ClientToolAnswer {\n outcome: string;\n text: string;\n details: Record<string, string | number | boolean | null>;\n /** A picture of the screen (base64 of WebP, JPEG or PNG), only for a `READ_SCREEN` request with `format: picture` */\n pictureBase64?: string;\n}\n\n/** A tab never starts a request with fewer seconds left: it would finish after the tool gave up. */\nexport const MIN_SECONDS_LEFT_TO_START = 3;\n\n/** The most characters of an answer text (the server refuses more). */\nexport const MAX_ANSWER_TEXT_CHARS = 24000;\n\n/** The refusal codes a tab answers with. */\nexport const CLIENT_TOOL_OUTCOMES = {\n ok: 'OK',\n unsavedChanges: 'UNSAVED_CHANGES',\n unsavedStateUnknown: 'UNSAVED_STATE_UNKNOWN',\n dialogOpen: 'DIALOG_OPEN',\n unknownTarget: 'UNKNOWN_TARGET',\n missingParameter: 'MISSING_PARAMETER',\n unknownTab: 'UNKNOWN_TAB',\n unknownFilter: 'UNKNOWN_FILTER',\n notOnScreen: 'NOT_ON_SCREEN',\n expiredBeforeStart: 'EXPIRED_BEFORE_START',\n readFailed: 'READ_FAILED',\n unknownRequest: 'UNKNOWN_REQUEST',\n unknownMode: 'UNKNOWN_MODE',\n pictureUnavailable: 'PICTURE_UNAVAILABLE',\n} as const;\n\n// ── The navigation targets ───────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ScreenTargetFilter {\n /** The query parameter, e.g. `customerId` */\n key: string;\n}\n\n/** A screen the user can open: a menu entry, a record screen or a page below one. */\nexport interface ScreenTarget {\n /** Stable key the agent passes to openScreen: the menu key, the record kind, or a dotted path below one */\n key: string;\n /** What the user calls it (translated) */\n label: string;\n /** The menu groups above it (translated), e.g. `Maintenance` */\n group: string | null;\n /** The route with `:parameter` segments, e.g. `/orders/:orderId` */\n routePattern: string;\n /** The route parameters in order (a nested record screen has two) */\n parameters: string[];\n /** The tabs (route segments after the pattern) */\n tabs: string[];\n /** The URL filters of a list screen */\n filters: ScreenTargetFilter[];\n /** The views of a list screen (`?view=`) */\n views: string[];\n}\n\n// ── The adapters an application supplies ─────────────────────────────────────────────────────────────────────────────\n\n/** Where the browser is. */\nexport interface ScreenLocation {\n /** The route without the basePath, with the query string */\n route: string;\n /** The document title or page heading */\n title: string;\n}\n\n/** Why a navigation would lose the user's work. */\nexport interface ScreenNavigationBlocker {\n outcome: string;\n /** A short sentence for the model */\n reason: string;\n}\n\nexport interface ScreenOpenRequest {\n recordIds: number[];\n tab: string | null;\n filters: Record<string, string>;\n}\n\n/** The screen as Markdown, with the references `highlightOnScreen` takes. */\nexport interface ScreenSnapshot {\n markdown: string;\n route: string;\n title: string;\n /** reference → label, for the answer of a mark */\n references: Record<string, string>;\n}\n\nexport interface ScreenMarkResult {\n /** reference → label of the marked elements */\n marked: Record<string, string>;\n /** references that are not on the screen */\n missing: string[];\n /** references marked but out of view or covered */\n outOfView: string[];\n /** references inside a collapsed section: the section header is marked instead */\n collapsed: string[];\n}\n\n/** Reads the navigation the user really has (rights applied). */\nexport interface ScreenTargetSource {\n listTargets(): ScreenTarget[];\n}\n\n/** Navigates with the application's router and guards. */\nexport interface ScreenNavigator {\n describeBlockers(): ScreenNavigationBlocker | null;\n open(target: ScreenTarget, request: ScreenOpenRequest): Promise<ScreenLocation>;\n currentLocation(): ScreenLocation;\n}\n\n/** Turns the current screen into Markdown. */\nexport interface ScreenReader {\n read(options: { focus?: string; maxChars: number }): ScreenSnapshot;\n}\n\n/** Marks elements by the references of the newest read. */\nexport interface ScreenHighlighter {\n mark(references: string[], note: string | null): ScreenMarkResult;\n clear(): void;\n}\n\n/** The size presets of a screen picture (`pictureSize` of `getCurrentScreen`). */\nexport type ScreenPictureSize = 'small' | 'medium' | 'large';\n\n/** How a screen picture is rendered (`renderMode` of `getCurrentScreen`). */\nexport type ScreenPictureRenderMode = 'colour' | 'greyscale' | 'machine';\n\nexport interface ScreenPictureRequest {\n pictureSize: ScreenPictureSize;\n renderMode: ScreenPictureRenderMode;\n}\n\n/** A captured picture of the screen. */\nexport interface ScreenPicture {\n /** base64 of the encoded bytes, without a `data:` prefix */\n base64: string;\n mimeType: 'image/webp' | 'image/jpeg' | 'image/png';\n width: number;\n height: number;\n byteSize: number;\n}\n\n/** Captures the open screen as a picture (`createDomScreenPictureCapturer()` is the DOM default). */\nexport interface ScreenPictureCapturer {\n capture(request: ScreenPictureRequest): Promise<ScreenPicture | null>;\n}\n\n/** The agent window of the application: steps aside before the agent works on the screen, takes a requested mode. */\nexport interface AgentWindowAdapter {\n /** Makes room for the screen (the default before `OPEN_TARGET`, `HIGHLIGHT` and a picture) */\n stepAside(requestType: ClientToolRequestType): void | Promise<void>;\n /** Back to the mode before `stepAside()` */\n restore(): void | Promise<void>;\n /** A mode the application knows (`SET_WINDOW_MODE`); false = unknown mode */\n setMode(mode: string): boolean | Promise<boolean>;\n /** Whether the window steps aside before a request of the type; default true for the three screen requests */\n shouldStepAsideBefore?(requestType: ClientToolRequestType): boolean;\n}\n\n/** Shows the user the way to a target before it opens (`createDomScreenPathGuide()` is the DOM default). */\nexport interface ScreenPathGuide {\n /**\n * Shows the path to the target; never awaited by the runner, so it never delays the answer. Returns false when it\n * shows nothing (reduced motion, already on the target, no element of the path on the screen).\n */\n guide(target: ScreenTarget, request: ScreenOpenRequest): boolean;\n /** Stops a guide still running */\n cancel(): void;\n}\n\n/** A request type the application handles itself (a type a host or package registered on the server). */\nexport type ClientToolRequestHandler = (parameters: Record<string, unknown>, delivery: ClientToolRequestDelivery) => ClientToolAnswer | Promise<ClientToolAnswer>;\n\nexport interface ScreenAdapters {\n targets: ScreenTargetSource;\n navigator: ScreenNavigator;\n reader: ScreenReader;\n highlighter: ScreenHighlighter;\n /** Whether the client is visible now */\n isVisible: () => boolean;\n /** Optional: captures the screen as a picture; without it a picture request is answered `PICTURE_UNAVAILABLE` */\n picture?: ScreenPictureCapturer;\n /** Optional: the agent window; without it `SET_WINDOW_MODE` is answered `UNKNOWN_MODE` */\n agentWindow?: AgentWindowAdapter;\n /** Optional: the path guide shown before `OPEN_TARGET` */\n pathGuide?: ScreenPathGuide;\n /** Optional: handlers of further request types, by type; a type of the package is never replaced */\n requestHandlers?: Record<string, ClientToolRequestHandler>;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** The arguments of a delivery as an object; anything else is empty. */\nexport const parseClientToolArguments = (argumentsJson: string): Record<string, unknown> => {\n try {\n const parsed: unknown = JSON.parse(argumentsJson);\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n};\n\n/** A text cut to the answer's cap. */\nexport const capAnswerText = (text: string): string =>\n text.length <= MAX_ANSWER_TEXT_CHARS ? text : `${text.slice(0, MAX_ANSWER_TEXT_CHARS - 1)}…`;\n\n/** Lower-case words of a search text. */\nconst searchWordsOf = (searchText: string): string[] =>\n searchText\n .toLowerCase()\n .split(/\\s+/)\n .filter(word => word !== '');\n\n/** One line of a target in the `listScreens` answer. */\nexport const formatScreenTargetLine = (target: ScreenTarget): string => {\n const parts = [target.key, target.group ? `${target.group} › ${target.label}` : target.label];\n if (target.parameters.length > 0) parts[1] = `${parts[1]} (${target.parameters.join(', ')})`;\n if (target.tabs.length > 0) parts.push(`tabs ${target.tabs.join(', ')}`);\n if (target.filters.length > 0) parts.push(`filters ${target.filters.map(filter => filter.key).join(', ')}`);\n if (target.views.length > 0) parts.push(`views ${target.views.join(', ')}`);\n return `- ${parts.join(' · ')}`;\n};\n\n/** The most characters of a `listScreens` answer. */\nexport const MAX_TARGET_LIST_CHARS = 4500;\n\n/** The `listScreens` answer: the targets whose line contains every word of the search text, capped. */\nexport const formatScreenTargetList = (targets: ScreenTarget[], searchText: string): string => {\n const searchWords = searchWordsOf(searchText);\n const lines = targets\n .map(formatScreenTargetLine)\n .filter(line => searchWords.every(word => line.toLowerCase().includes(word)));\n if (lines.length === 0) return 'No screen matches. Call listScreens without searchText for all of them.';\n const header = `Screens this user can open (${lines.length}). Pass the key to openScreen.`;\n const kept: string[] = [];\n let chars = header.length;\n for (const line of lines) {\n if (chars + line.length + 1 > MAX_TARGET_LIST_CHARS) {\n kept.push(`… ${lines.length - kept.length} more; narrow with searchText.`);\n break;\n }\n kept.push(line);\n chars += line.length + 1;\n }\n return [header, ...kept].join('\\n');\n};\n\n/** A reference, a key, a tab or a filter key: what the server lets through. */\nconst TOKEN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;\n\nexport const isClientToolToken = (value: unknown): value is string => typeof value === 'string' && TOKEN_PATTERN.test(value);\n\n/** The route of a target for the given record ids and tab; `null` when a record id is missing. */\nexport const buildTargetRoute = (target: ScreenTarget, recordIds: number[], tab: string | null): string | null => {\n let parameterIndex = 0;\n const segments: string[] = [];\n for (const segment of target.routePattern.split('/').filter(part => part !== '')) {\n if (!segment.startsWith(':')) {\n segments.push(segment);\n continue;\n }\n const recordId = recordIds[parameterIndex];\n parameterIndex += 1;\n if (recordId === undefined || !Number.isInteger(recordId) || recordId <= 0) return null;\n segments.push(String(recordId));\n }\n if (tab) segments.push(tab);\n return `/${segments.join('/')}`;\n};\n","import {\n buildTargetRoute,\n CLIENT_TOOL_OUTCOMES,\n type ClientToolAnswer,\n type ClientToolRequestDelivery,\n capAnswerText,\n formatScreenTargetList,\n isClientToolToken,\n MIN_SECONDS_LEFT_TO_START,\n parseClientToolArguments,\n type ClientToolRequestType,\n type ScreenAdapters,\n type ScreenPictureRenderMode,\n type ScreenPictureSize,\n type ScreenTarget,\n} from \"./client-tools\";\n\n/** The request types of the package; a handler of the application never replaces them. */\nconst PACKAGE_REQUEST_TYPES: string[] = ['READ_SCREEN', 'LIST_TARGETS', 'OPEN_TARGET', 'HIGHLIGHT', 'SET_WINDOW_MODE'];\n\n/** The request types the agent window steps aside for by default. */\nconst STEP_ASIDE_REQUEST_TYPES: ClientToolRequestType[] = ['OPEN_TARGET', 'HIGHLIGHT', 'READ_SCREEN'];\n\nconst PICTURE_SIZES: ScreenPictureSize[] = ['small', 'medium', 'large'];\n\nconst RENDER_MODES: ScreenPictureRenderMode[] = ['colour', 'greyscale', 'machine'];\n\n/** The most characters of screen content in one answer (the server cuts at 8,000 again). */\nexport const MAX_SCREEN_CHARS = 6000;\n\n/** How many request ids a runner remembers, so a redelivery never runs a request twice. */\nconst REMEMBERED_REQUEST_IDS = 50;\n\n/** Posts an answer; the transport is the application's. */\nexport type ClientToolAnswerSender = (requestId: number, answer: ClientToolAnswer) => Promise<void>;\n\n/**\n * Runs the requests the run-state read delivers, one at a time, through the application's adapters, and posts each\n * answer once. Generic: it knows the four request types and the refusal codes, nothing of a menu or a route.\n */\nexport class ClientToolRequestRunner {\n protected readonly handledRequestIds: number[] = [];\n\n protected running: Promise<void> = Promise.resolve();\n\n protected readonly adapters: ScreenAdapters;\n\n constructor(adapters: ScreenAdapters) {\n this.adapters = adapters;\n }\n\n /**\n * Takes a delivery and posts its answer through `sendAnswer`; a request already taken is ignored (the server\n * redelivers an unanswered one after 5 s).\n */\n accept(delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void {\n if (this.handledRequestIds.includes(delivery.id)) return;\n this.handledRequestIds.push(delivery.id);\n if (this.handledRequestIds.length > REMEMBERED_REQUEST_IDS) this.handledRequestIds.shift();\n const receivedAt = Date.now();\n this.running = this.running.then(() => this.runAndAnswer(delivery, receivedAt, sendAnswer));\n }\n\n /** Resolves when every accepted request was answered (tests). */\n whenIdle(): Promise<void> {\n return this.running;\n }\n\n protected async runAndAnswer(delivery: ClientToolRequestDelivery, receivedAt: number, sendAnswer: ClientToolAnswerSender): Promise<void> {\n const answer = await this.run(delivery, receivedAt);\n try {\n await sendAnswer(delivery.id, { ...answer, text: capAnswerText(answer.text) });\n } catch {\n // the tool answers \"no answer\" after its wait; nothing else to do in the tab\n }\n }\n\n /** The answer of one request. Exposed for the tests. */\n async run(delivery: ClientToolRequestDelivery, receivedAt: number = Date.now()): Promise<ClientToolAnswer> {\n const secondsLeft = delivery.secondsLeft - (Date.now() - receivedAt) / 1000;\n if (secondsLeft < MIN_SECONDS_LEFT_TO_START) return refusal(CLIENT_TOOL_OUTCOMES.expiredBeforeStart);\n const parameters = parseClientToolArguments(delivery.argumentsJson);\n try {\n switch (delivery.requestType) {\n case 'READ_SCREEN':\n if (parameters.format === 'picture') {\n await this.stepAgentWindowAside('READ_SCREEN');\n try {\n return await this.readScreenPicture(parameters);\n } finally {\n await this.adapters.agentWindow?.restore();\n }\n }\n return this.readScreen(parameters);\n case 'LIST_TARGETS':\n return this.listTargets(parameters);\n case 'OPEN_TARGET':\n return await this.openTarget(parameters);\n case 'HIGHLIGHT':\n await this.stepAgentWindowAside('HIGHLIGHT');\n return this.highlight(parameters);\n case 'SET_WINDOW_MODE':\n return await this.setWindowMode(parameters);\n default:\n return await this.runRequestOfApplication(delivery, parameters);\n }\n } catch {\n return refusal(CLIENT_TOOL_OUTCOMES.readFailed);\n }\n }\n\n /** A request type the application registered: its handler, else `UNKNOWN_REQUEST`. */\n protected async runRequestOfApplication(delivery: ClientToolRequestDelivery, parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const handler = PACKAGE_REQUEST_TYPES.includes(delivery.requestType) ? undefined : this.adapters.requestHandlers?.[delivery.requestType];\n if (!handler) return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);\n return handler(parameters, delivery);\n }\n\n /** Lets the agent window make room before the agent works on the screen (the default for the screen requests). */\n protected async stepAgentWindowAside(requestType: ClientToolRequestType): Promise<void> {\n const agentWindow = this.adapters.agentWindow;\n if (!agentWindow) return;\n const shouldStepAside = agentWindow.shouldStepAsideBefore\n ? agentWindow.shouldStepAsideBefore(requestType)\n : STEP_ASIDE_REQUEST_TYPES.includes(requestType);\n if (shouldStepAside) await agentWindow.stepAside(requestType);\n }\n\n protected async setWindowMode(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const agentWindow = this.adapters.agentWindow;\n if (!agentWindow || !isClientToolToken(parameters.mode)) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);\n if (parameters.mode === 'restore') {\n await agentWindow.restore();\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details: { mode: 'restore' } };\n }\n const accepted = await agentWindow.setMode(parameters.mode);\n if (!accepted) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details: { mode: parameters.mode } };\n }\n\n protected async readScreenPicture(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const capturer = this.adapters.picture;\n if (!capturer) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);\n const pictureSize = PICTURE_SIZES.find(size => size === parameters.pictureSize) ?? 'medium';\n const renderMode = RENDER_MODES.find(mode => mode === parameters.renderMode) ?? 'colour';\n const picture = await capturer.capture({ pictureSize, renderMode });\n if (!picture) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);\n const location = this.adapters.navigator.currentLocation();\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: '',\n details: {\n route: location.route,\n visible: this.adapters.isVisible(),\n width: picture.width,\n height: picture.height,\n bytes: picture.byteSize,\n renderMode,\n },\n pictureBase64: picture.base64,\n };\n }\n\n protected readScreen(parameters: Record<string, unknown>): ClientToolAnswer {\n const focus = isClientToolToken(parameters.focus) ? parameters.focus : undefined;\n const snapshot = this.adapters.reader.read({ focus, maxChars: MAX_SCREEN_CHARS });\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: snapshot.markdown,\n details: { route: snapshot.route, visible: this.adapters.isVisible(), chars: snapshot.markdown.length },\n };\n }\n\n protected listTargets(parameters: Record<string, unknown>): ClientToolAnswer {\n const searchText = typeof parameters.searchText === 'string' ? parameters.searchText : '';\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: formatScreenTargetList(this.adapters.targets.listTargets(), searchText),\n details: {},\n };\n }\n\n protected async openTarget(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const target = this.findTarget(parameters.target);\n if (!target) return refusal(CLIENT_TOOL_OUTCOMES.unknownTarget);\n const tab = isClientToolToken(parameters.tab) ? parameters.tab : null;\n if (tab !== null && !target.tabs.includes(tab)) return refusal(CLIENT_TOOL_OUTCOMES.unknownTab);\n const filters: Record<string, string> = {};\n for (const filter of Array.isArray(parameters.filters) ? parameters.filters : []) {\n const [key, ...valueParts] = String(filter).split('=');\n if (!target.filters.some(targetFilter => targetFilter.key === key) || valueParts.length === 0) {\n return refusal(CLIENT_TOOL_OUTCOMES.unknownFilter);\n }\n filters[key] = valueParts.join('=');\n }\n const recordIds = typeof parameters.recordId === 'number' ? [parameters.recordId] : [];\n if (buildTargetRoute(target, recordIds, tab) === null) return refusal(CLIENT_TOOL_OUTCOMES.missingParameter);\n const blocker = this.adapters.navigator.describeBlockers();\n if (blocker) return { outcome: blocker.outcome, text: blocker.reason, details: {} };\n await this.stepAgentWindowAside('OPEN_TARGET');\n const openRequest = { recordIds, tab, filters };\n try {\n this.adapters.pathGuide?.guide(target, openRequest);\n } catch {\n // a guide is decoration: the navigation goes on without it\n }\n const location = await this.adapters.navigator.open(target, openRequest);\n const details = { route: location.route, title: location.title };\n if (parameters.includeScreen !== true) return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details };\n const snapshot = this.adapters.reader.read({ maxChars: MAX_SCREEN_CHARS });\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: snapshot.markdown, details };\n }\n\n protected highlight(parameters: Record<string, unknown>): ClientToolAnswer {\n const references = (Array.isArray(parameters.references) ? parameters.references : []).filter(isClientToolToken);\n const note = typeof parameters.note === 'string' && parameters.note.trim() !== '' ? parameters.note : null;\n const result = this.adapters.highlighter.mark(references, note);\n const markedReferences = Object.keys(result.marked);\n const lines = markedReferences.map(reference => {\n const suffix = result.outOfView.includes(reference)\n ? ' (scrolled into view)'\n : result.collapsed.includes(reference)\n ? ' (inside a closed section: its header is marked)'\n : '';\n return `Marked ${reference} \"${result.marked[reference]}\"${suffix}.`;\n });\n if (result.missing.length > 0) lines.push(`Not on the screen: ${result.missing.join(', ')}.`);\n const outcome = markedReferences.length > 0 ? CLIENT_TOOL_OUTCOMES.ok : CLIENT_TOOL_OUTCOMES.notOnScreen;\n return { outcome, text: lines.join('\\n'), details: { marked: markedReferences.length } };\n }\n\n protected findTarget(key: unknown): ScreenTarget | null {\n if (!isClientToolToken(key)) return null;\n return this.adapters.targets.listTargets().find(target => target.key === key) ?? null;\n }\n}\n\nconst refusal = (outcome: string): ClientToolAnswer => ({ outcome, text: '', details: {} });\n","import type { AgentUIState, AgentUIStateSource } from \"./agent-ui-state\";\nimport { createAgentUIClientId } from \"./agent-ui-state\";\nimport { type ClientToolAnswerSender, ClientToolRequestRunner } from \"./ClientToolRequestRunner\";\nimport type { ClientToolRequestDelivery, ScreenAdapters } from \"./client-tools\";\n\n/**\n * What a conversation client binding needs from the UI side of `Agent.UI` (`AgentsHttpConversationClientOptions.uiClient`):\n * the client id and UI state it sends with every message and run-state read, and where a delivered client tool\n * request goes. The binding posts the answer.\n */\nexport interface AgentUIClientBinding {\n readonly clientId: string;\n readUIState(): AgentUIState | null;\n acceptClientToolRequest(conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void;\n}\n\n/**\n * The UI side of `Agent.UI` in one object: a client id per mount, the UI state source, and the runner that executes\n * the delivered requests through the application's four adapters. Framework-free; the React hook\n * (`useAgentUIClient`) creates one per mount.\n */\nexport class AgentUIClient implements AgentUIClientBinding {\n readonly clientId: string;\n\n protected readonly runner: ClientToolRequestRunner;\n\n protected readonly uiStateSource: AgentUIStateSource | null;\n\n protected acceptedClientToolRequestCount = 0;\n\n constructor(adapters: ScreenAdapters, uiStateSource: AgentUIStateSource | null = null, clientId: string = createAgentUIClientId()) {\n this.clientId = clientId;\n this.runner = new ClientToolRequestRunner(adapters);\n this.uiStateSource = uiStateSource;\n }\n\n readUIState(): AgentUIState | null {\n try {\n return this.uiStateSource?.readUIState() ?? null;\n } catch {\n return null;\n }\n }\n\n acceptClientToolRequest(_conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void {\n this.acceptedClientToolRequestCount += 1;\n this.runner.accept(delivery, sendAnswer);\n }\n\n /** How many client tool requests were delivered to this client so far (a repeat delivery counts again). */\n countAcceptedClientToolRequests(): number {\n return this.acceptedClientToolRequestCount;\n }\n\n /** Resolves when every accepted request was answered (tests). */\n whenIdle(): Promise<void> {\n return this.runner.whenIdle();\n }\n}\n","import { useRef } from \"react\";\nimport type { AgentUIStateSource } from \"./agent-ui-state\";\nimport { AgentUIClient } from \"./AgentUIClient\";\nimport type { ScreenAdapters } from \"./client-tools\";\n\n/**\n * One `AgentUIClient` per mount of the agent window: a stable client id and the runner of the delivered requests. The\n * adapters are read through the latest render (a ref), so an application may pass a new object on every render. Hand\n * the result to the conversation client binding (`createAgentsHttpConversationClient({ uiClient })`).\n */\nexport const useAgentUIClient = (adapters: ScreenAdapters, uiStateSource: AgentUIStateSource | null = null): AgentUIClient => {\n const adaptersRef = useRef(adapters);\n adaptersRef.current = adapters;\n const uiStateSourceRef = useRef(uiStateSource);\n uiStateSourceRef.current = uiStateSource;\n const clientRef = useRef<AgentUIClient | null>(null);\n if (clientRef.current === null) {\n const latestAdapters: ScreenAdapters = {\n targets: { listTargets: () => adaptersRef.current.targets.listTargets() },\n navigator: {\n describeBlockers: () => adaptersRef.current.navigator.describeBlockers(),\n open: (target, request) => adaptersRef.current.navigator.open(target, request),\n currentLocation: () => adaptersRef.current.navigator.currentLocation(),\n },\n reader: { read: options => adaptersRef.current.reader.read(options) },\n highlighter: {\n mark: (references, note) => adaptersRef.current.highlighter.mark(references, note),\n clear: () => adaptersRef.current.highlighter.clear(),\n },\n isVisible: () => adaptersRef.current.isVisible(),\n };\n // the optional adapters: present on the object when the latest render has them\n Object.defineProperties(latestAdapters, {\n picture: { enumerable: true, get: () => adaptersRef.current.picture },\n agentWindow: { enumerable: true, get: () => adaptersRef.current.agentWindow },\n pathGuide: { enumerable: true, get: () => adaptersRef.current.pathGuide },\n requestHandlers: { enumerable: true, get: () => adaptersRef.current.requestHandlers },\n });\n clientRef.current = new AgentUIClient(latestAdapters, { readUIState: () => uiStateSourceRef.current?.readUIState() ?? null });\n }\n return clientRef.current;\n};\n","/**\n * The pure half of the screen reader: references and the Markdown lines of fields, tables, buttons and messages.\n * The DOM walk (`domScreenReader.ts`) collects plain values and these functions write them, so the logic tests cover\n * the format without a DOM.\n *\n * References (stable within one read, `highlightOnScreen` takes them):\n * - `f.<name>` a form field (its `name`, else its label as a slug)\n * - `row.<key>` a table row (the row key: `data-row-key`, else the visible id cell)\n * - `b.<slug>` a button or link that acts\n * - `s.<slug>` a section (its heading)\n * - `t.<slug>` a tab\n * - `a.<anchor>` an anchor the application set (`data-agent-anchor`)\n */\n\n/** The most rows of one table in a read. */\nexport const MAX_TABLE_ROWS = 25;\n\n/** The most characters of one value in a read (a long text says how long it is; `focus` reads it whole). */\nexport const MAX_VALUE_CHARS = 200;\n\n/** The most buttons in a read. */\nexport const MAX_BUTTONS = 30;\n\n/** A value standing in for a secret. */\nexport const HIDDEN_VALUE = '(hidden)';\n\n/** A slug for a reference: lower case letters, digits and `-`, at most 40 characters. */\nexport const slugOf = (text: string): string =>\n text\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '') || 'x';\n\n/** A reference name from a field name (`order.endDate` stays, other characters become `-`). */\nexport const fieldReferenceNameOf = (name: string): string =>\n name.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 60) || 'x';\n\n/** One line of text: whitespace collapsed. */\nexport const oneLine = (text: string): string => text.replace(/\\s+/g, ' ').trim();\n\n/** A value cut to {@link MAX_VALUE_CHARS}, saying how long it was. */\nexport const capValue = (value: string, maxChars: number = MAX_VALUE_CHARS): string => {\n const flat = oneLine(value);\n return flat.length <= maxChars ? flat : `${flat.slice(0, maxChars)}… (${flat.length} characters)`;\n};\n\n/** Makes a reference unique within one read by a number suffix. */\nexport class ReferenceNames {\n protected readonly used = new Set<string>();\n\n take(reference: string): string {\n let candidate = reference;\n for (let suffix = 2; this.used.has(candidate); suffix += 1) candidate = `${reference}-${suffix}`;\n this.used.add(candidate);\n return candidate;\n }\n}\n\nexport interface FieldFacts {\n reference: string;\n label: string;\n value: string;\n kind: string;\n required?: boolean;\n disabled?: boolean;\n invalidMessage?: string | null;\n isSecret?: boolean;\n}\n\n/** `- End date (f.endDate, date): 2026-12-31 · required · error \"…\"` */\nexport const formatFieldLine = (field: FieldFacts): string => {\n const value = field.isSecret ? HIDDEN_VALUE : field.value.trim() === '' ? '(empty)' : capValue(field.value);\n const flags: string[] = [];\n if (field.required) flags.push('required');\n if (field.disabled) flags.push('read-only');\n if (field.invalidMessage) flags.push(`error \"${capValue(field.invalidMessage, 120)}\"`);\n return `- ${capValue(field.label, 80) || field.reference} (${field.reference}, ${field.kind}): ${value}${flags.length > 0 ? ` · ${flags.join(' · ')}` : ''}`;\n};\n\nexport interface TableFacts {\n caption: string | null;\n columns: string[];\n rows: { reference: string; cells: string[]; selected?: boolean }[];\n /** All rows of the table in the DOM (more than shown) */\n totalRows: number;\n}\n\n/** A table as `| … |` lines with the row reference first, at most {@link MAX_TABLE_ROWS} rows. */\nexport const formatTable = (table: TableFacts, maxRows: number = MAX_TABLE_ROWS): string[] => {\n const lines: string[] = [];\n const shownRows = table.rows.slice(0, maxRows);\n lines.push(`Table${table.caption ? ` \"${capValue(table.caption, 80)}\"` : ''}: ${table.totalRows} rows on screen`);\n lines.push(`| ref | ${table.columns.map(column => capValue(column, 40) || '-').join(' | ')} |`);\n for (const row of shownRows) {\n const cells = row.cells.map(cell => capValue(cell, 80).replace(/\\|/g, '/'));\n lines.push(`| ${row.reference}${row.selected ? ' (selected)' : ''} | ${cells.join(' | ')} |`);\n }\n if (table.totalRows > shownRows.length) lines.push(`… ${table.totalRows - shownRows.length} more rows on screen`);\n return lines;\n};\n\nexport interface ButtonFacts {\n reference: string;\n label: string;\n disabled?: boolean;\n}\n\n/** `Buttons: b.save \"Save\" · b.delete \"Delete\" (disabled)` */\nexport const formatButtons = (buttons: ButtonFacts[]): string | null => {\n if (buttons.length === 0) return null;\n const shown = buttons.slice(0, MAX_BUTTONS).map(button => `${button.reference} \"${capValue(button.label, 40)}\"${button.disabled ? ' (disabled)' : ''}`);\n const more = buttons.length > MAX_BUTTONS ? ` · … ${buttons.length - MAX_BUTTONS} more` : '';\n return `Buttons: ${shown.join(' · ')}${more}`;\n};\n\n/** Joins the parts of a read and cuts the whole at `maxChars`, saying so. */\nexport const joinScreenParts = (parts: string[], maxChars: number): string => {\n const text = parts.filter(part => part !== '').join('\\n');\n if (text.length <= maxChars) return text;\n const cut = text.slice(0, maxChars);\n const lastLineBreak = cut.lastIndexOf('\\n');\n return `${lastLineBreak > maxChars * 0.8 ? cut.slice(0, lastLineBreak) : cut}\\n… (screen cut at ${maxChars} of ${text.length} characters; read one part with focus)`;\n};\n","import type { ScreenReader, ScreenSnapshot } from \"./client-tools\";\nimport {\n type ButtonFacts,\n capValue,\n type FieldFacts,\n fieldReferenceNameOf,\n formatButtons,\n formatFieldLine,\n formatTable,\n joinScreenParts,\n MAX_TABLE_ROWS,\n oneLine,\n ReferenceNames,\n slugOf,\n type TableFacts,\n} from \"./screen-markdown\";\n\n/** The attributes an application (and `@mgamadeus/ddd-admin-ui`) sets for the agent. */\nexport const AGENT_ATTRIBUTES = {\n /** A stable handle: `a.<value>` */\n anchor: 'data-agent-anchor',\n /** The value is never read (a key, a token) */\n secret: 'data-agent-secret',\n /** The element and everything in it is never read (the agent window itself) */\n skip: 'data-agent-skip',\n /** The key of a table row (@mgamadeus/ddd-admin-ui) */\n rowKey: 'data-row-key',\n} as const;\n\n/** Elements never read. */\nconst SKIPPED_SELECTOR = `[${AGENT_ATTRIBUTES.skip}], script, style, noscript, template, svg, [aria-hidden=\"true\"], [hidden]`;\n\n/** Fields whose value is never read. */\nconst SECRET_FIELD_SELECTOR = `[${AGENT_ATTRIBUTES.secret}] , input[type=\"password\"], input[autocomplete=\"one-time-code\"]`;\n\nconst FIELD_SELECTOR = 'input:not([type=\"hidden\"]):not([type=\"submit\"]):not([type=\"button\"]), textarea, select, [role=\"combobox\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"radiogroup\"]';\n\nconst BUTTON_SELECTOR = 'button, [role=\"button\"], a[href]';\n\n/** The most tabs of the page a read names. */\nconst MAX_PAGE_TABS = 16;\n\n/** Column headers that name the id column (for a host table whose rows carry no `data-row-key`). */\nconst ID_COLUMN_LABELS = new Set(['id', '#', 'nr', 'no']);\n\n/** The references of the newest read: reference → element. The highlighter marks by them. */\nexport class ScreenReferenceRegistry {\n protected elements = new Map<string, Element>();\n\n replace(elements: Map<string, Element>): void {\n this.elements = elements;\n }\n\n find(reference: string): Element | null {\n const element = this.elements.get(reference);\n return element?.isConnected ? element : null;\n }\n\n /** An anchor is found on the page even without a read. */\n findAnchor(reference: string): Element | null {\n if (!reference.startsWith('a.')) return null;\n const anchorName = reference.slice(2);\n for (const element of Array.from(document.querySelectorAll(`[${AGENT_ATTRIBUTES.anchor}]`))) {\n if (element.getAttribute(AGENT_ATTRIBUTES.anchor) === anchorName && !element.closest(`[${AGENT_ATTRIBUTES.skip}]`)) return element;\n }\n return null;\n }\n\n labelOf(reference: string): string {\n const element = this.find(reference) ?? this.findAnchor(reference);\n return element ? labelOfElement(element) : reference;\n }\n}\n\nconst isRendered = (element: Element): boolean => {\n if (element.closest(SKIPPED_SELECTOR)) return false;\n const htmlElement = element as HTMLElement;\n if (typeof htmlElement.getClientRects === 'function' && htmlElement.getClientRects().length === 0) return false;\n return true;\n};\n\nconst textOf = (element: Element | null | undefined): string => {\n if (!element) return '';\n const htmlElement = element as HTMLElement;\n // biome-ignore lint/performance/useDomNodeTextContent: the rendered text (no hidden parts) is what the user sees\n return oneLine(htmlElement.innerText ?? element.textContent ?? '');\n};\n\n/** The accessible label of an element: aria-label, labelledby, a `<label for>`, the wrapping label, its text. */\nexport const labelOfElement = (element: Element): string => {\n const ariaLabel = element.getAttribute('aria-label');\n if (ariaLabel) return oneLine(ariaLabel);\n const labelledBy = element.getAttribute('aria-labelledby');\n if (labelledBy) {\n const text = labelledBy\n .split(/\\s+/)\n .map(id => textOf(document.getElementById(id)))\n .join(' ');\n if (text.trim() !== '') return oneLine(text);\n }\n const id = element.getAttribute('id');\n if (id) {\n const label = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n if (label) return textOf(label);\n }\n const wrappingLabel = element.closest('label');\n if (wrappingLabel) return textOf(wrappingLabel);\n const placeholder = element.getAttribute('placeholder');\n if (placeholder) return oneLine(placeholder);\n return textOf(element).slice(0, 80);\n};\n\n/**\n * The key of a table row: `data-row-key` (the package's list rows and cards, 0.3.10); a table of the host without it\n * falls back to the visible id cell, then to the row's position.\n */\nexport const rowKeyOf = (row: Element, idColumnIndex: number | null, rowIndex: number): string => {\n const rowKey = row.getAttribute(AGENT_ATTRIBUTES.rowKey);\n if (rowKey) return slugOf(rowKey);\n if (idColumnIndex !== null) {\n const idText = textOf(row.children.item(idColumnIndex)).replace(/^#/, '');\n if (/^[A-Za-z0-9-]{1,40}$/.test(idText)) return idText;\n }\n return `n${rowIndex + 1}`;\n};\n\nconst valueOfField = (field: Element): { value: string; kind: string } => {\n if (field instanceof HTMLInputElement) {\n if (field.type === 'checkbox' || field.type === 'radio') return { value: field.checked ? 'on' : 'off', kind: field.type };\n return { value: field.value, kind: field.type || 'text' };\n }\n if (field instanceof HTMLTextAreaElement) return { value: field.value, kind: 'text area' };\n if (field instanceof HTMLSelectElement) return { value: textOf(field.selectedOptions.item(0)), kind: 'select' };\n const role = field.getAttribute('role') ?? '';\n if (role === 'switch' || role === 'checkbox') return { value: field.getAttribute('aria-checked') === 'true' ? 'on' : 'off', kind: role };\n if (role === 'radiogroup') {\n const checked = field.querySelector('[aria-checked=\"true\"], [data-state=\"checked\"]');\n return { value: checked ? labelOfElement(checked) : '', kind: 'choice' };\n }\n return { value: textOf(field), kind: role || 'field' };\n};\n\nconst invalidMessageOf = (field: Element): string | null => {\n if (field.getAttribute('aria-invalid') !== 'true') return null;\n const describedBy = field.getAttribute('aria-describedby') ?? field.getAttribute('aria-errormessage');\n const message = (describedBy ?? '')\n .split(/\\s+/)\n .map(id => textOf(document.getElementById(id)))\n .join(' ')\n .trim();\n return message !== '' ? message : 'invalid';\n};\n\nexport interface DomScreenReaderOptions {\n /** The content root (the page, without the shell) */\n findRoot: () => Element | null;\n /** The current route and title */\n currentLocation: () => { route: string; title: string };\n /** Whether the open screen has unsaved changes: `no`, or `yes (<form> (<fields>))` */\n describeUnsavedChanges: () => string;\n registry: ScreenReferenceRegistry;\n}\n\n/**\n * Reads the open screen from the DOM: title and route, tabs, open dialogs, messages, then per section its fields,\n * tables and buttons. Never the agent window (`data-agent-skip`), never a secret's value.\n */\nexport class DomScreenReader implements ScreenReader {\n constructor(protected readonly options: DomScreenReaderOptions) {}\n\n read({ focus, maxChars }: { focus?: string; maxChars: number }): ScreenSnapshot {\n const location = this.options.currentLocation();\n if (focus) {\n const focused = this.options.registry.find(focus) ?? this.options.registry.findAnchor(focus);\n if (!focused) {\n return { markdown: `${focus} is not on the screen any more. Read the screen again without focus.`, route: location.route, title: location.title, references: {} };\n }\n const value = focused.matches(SECRET_FIELD_SELECTOR) || focused.closest(`[${AGENT_ATTRIBUTES.secret}]`) ? '(hidden)' : this.readWhole(focused);\n return { markdown: joinScreenParts([`${focus} \"${labelOfElement(focused)}\" in full:`, value], maxChars), route: location.route, title: location.title, references: {} };\n }\n const elements = new Map<string, Element>();\n const references: Record<string, string> = {};\n const names = new ReferenceNames();\n const register = (reference: string, element: Element): string => {\n const unique = names.take(reference);\n elements.set(unique, element);\n references[unique] = labelOfElement(element);\n return unique;\n };\n\n const parts: string[] = [`# ${capValue(location.title, 120)}`, `Route: ${location.route}`];\n const unsaved = this.options.describeUnsavedChanges();\n parts.push(`Unsaved changes: ${unsaved}`);\n\n const root = this.options.findRoot();\n const dialogs = Array.from(document.querySelectorAll('[role=\"dialog\"], [role=\"alertdialog\"]')).filter(isRendered);\n for (const dialog of dialogs) {\n parts.push(`## Dialog \"${capValue(labelOfElement(dialog), 80)}\" (open)`);\n parts.push(...this.readContainer(dialog, register));\n }\n if (root) {\n // the page's own tabs only: a tab list inside a form is a field's (the language tabs of a translatable text,\n // 14 per field on a long form); its open tab shows in the field's value\n const tabs = Array.from(root.querySelectorAll('[role=\"tab\"], nav[aria-label] a[aria-current]'))\n .filter(tab => isRendered(tab) && tab.closest('form, fieldset') === null)\n .slice(0, MAX_PAGE_TABS);\n if (tabs.length > 0) {\n const tabNames = tabs.map(tab => {\n const reference = register(`t.${slugOf(textOf(tab))}`, tab);\n const current = tab.getAttribute('aria-selected') === 'true' || tab.getAttribute('aria-current') !== null;\n return `${reference} \"${capValue(textOf(tab), 40)}\"${current ? ' (open)' : ''}`;\n });\n parts.push(`Tabs: ${tabNames.join(' · ')}`);\n }\n const messages = Array.from(root.querySelectorAll('[role=\"alert\"], [role=\"status\"]')).filter(isRendered);\n for (const message of messages) {\n const text = textOf(message);\n if (text !== '') parts.push(`Message: ${capValue(text, 200)}`);\n }\n parts.push(...this.readContainer(root, register));\n } else {\n parts.push('(no page content)');\n }\n const anchors = Array.from(document.querySelectorAll(`[${AGENT_ATTRIBUTES.anchor}]`)).filter(isRendered);\n if (anchors.length > 0) {\n parts.push(`Anchors: ${anchors.map(anchor => register(`a.${anchor.getAttribute(AGENT_ATTRIBUTES.anchor)}`, anchor)).join(' · ')}`);\n }\n this.options.registry.replace(elements);\n return { markdown: joinScreenParts(parts, maxChars), route: location.route, title: location.title, references };\n }\n\n protected readWhole(element: Element): string {\n if (element.matches(FIELD_SELECTOR)) return valueOfField(element).value;\n // biome-ignore lint/performance/useDomNodeTextContent: the rendered text (no hidden parts) is what the user sees\n return (element as HTMLElement).innerText ?? element.textContent ?? '';\n }\n\n /** The sections of a container (by headings), each with its fields, tables and buttons. */\n protected readContainer(container: Element, register: (reference: string, element: Element) => string): string[] {\n const lines: string[] = [];\n const seen = new Set<Element>();\n const headings = Array.from(container.querySelectorAll('h1, h2, h3, h4, [role=\"heading\"]')).filter(isRendered);\n for (const heading of headings) {\n const section = heading.closest('section, fieldset, [data-slot=\"card\"], form') ?? heading.parentElement;\n const text = textOf(heading);\n if (text === '') continue;\n const reference = register(`s.${slugOf(text)}`, section ?? heading);\n const collapsed = section?.querySelector('[aria-expanded=\"false\"]') && !section.querySelector(FIELD_SELECTOR) ? ' (closed)' : '';\n lines.push(`## ${capValue(text, 80)} (${reference})${collapsed}`);\n if (section) lines.push(...this.readElements(section, register, seen));\n }\n lines.push(...this.readElements(container, register, seen));\n return lines;\n }\n\n protected readElements(container: Element, register: (reference: string, element: Element) => string, seen: Set<Element>): string[] {\n const lines: string[] = [];\n for (const field of Array.from(container.querySelectorAll(FIELD_SELECTOR))) {\n if (seen.has(field) || !isRendered(field) || field.closest('[role=\"radiogroup\"]') !== null && field.getAttribute('role') !== 'radiogroup') continue;\n seen.add(field);\n const name = field.getAttribute('name') ?? field.getAttribute('id') ?? labelOfElement(field);\n const { value, kind } = valueOfField(field);\n const facts: FieldFacts = {\n reference: register(`f.${fieldReferenceNameOf(name.includes(' ') ? slugOf(name) : name)}`, field),\n label: labelOfElement(field),\n value,\n kind,\n required: field.hasAttribute('required') || field.getAttribute('aria-required') === 'true',\n disabled: field.hasAttribute('disabled') || field.getAttribute('aria-readonly') === 'true' || field.hasAttribute('readonly'),\n invalidMessage: invalidMessageOf(field),\n isSecret: field.matches(SECRET_FIELD_SELECTOR) || field.closest(`[${AGENT_ATTRIBUTES.secret}]`) !== null,\n };\n lines.push(formatFieldLine(facts));\n }\n for (const table of Array.from(container.querySelectorAll('table, [role=\"grid\"], [role=\"table\"]'))) {\n if (seen.has(table) || !isRendered(table)) continue;\n seen.add(table);\n lines.push(...formatTable(this.readTable(table, register)));\n }\n // the cards of a card grid (`EntityListGrid` sets `data-row-key` on each)\n const cards = Array.from(container.querySelectorAll(`[${AGENT_ATTRIBUTES.rowKey}]`)).filter(\n card => !seen.has(card) && !card.closest('table, [role=\"grid\"], [role=\"table\"]') && isRendered(card)\n );\n if (cards.length > 0) {\n lines.push(`Cards: ${cards.length} on screen`);\n for (const card of cards.slice(0, MAX_TABLE_ROWS)) {\n seen.add(card);\n for (const inner of Array.from(card.querySelectorAll(BUTTON_SELECTOR))) seen.add(inner);\n lines.push(`- ${register(`row.${rowKeyOf(card, null, 0)}`, card)}: ${capValue(textOf(card), 160)}`);\n }\n if (cards.length > MAX_TABLE_ROWS) lines.push(`… ${cards.length - MAX_TABLE_ROWS} more cards on screen`);\n }\n const buttons: ButtonFacts[] = [];\n for (const button of Array.from(container.querySelectorAll(BUTTON_SELECTOR))) {\n if (seen.has(button) || !isRendered(button) || button.closest('table, [role=\"grid\"], [role=\"tablist\"]')) continue;\n seen.add(button);\n const label = labelOfElement(button);\n if (label === '') continue;\n buttons.push({\n reference: register(`b.${slugOf(label)}`, button),\n label,\n disabled: button.hasAttribute('disabled') || button.getAttribute('aria-disabled') === 'true',\n });\n }\n const buttonLine = formatButtons(buttons);\n if (buttonLine) lines.push(buttonLine);\n return lines;\n }\n\n protected readTable(table: Element, register: (reference: string, element: Element) => string): TableFacts {\n const headerCells = Array.from(table.querySelectorAll('thead th, [role=\"columnheader\"]'));\n const columns = headerCells.map(cell => textOf(cell));\n const idColumnIndex = columns.findIndex(column => ID_COLUMN_LABELS.has(column.toLowerCase()));\n const bodyRows = Array.from(table.querySelectorAll('tbody tr, [role=\"row\"]')).filter(\n row => row.querySelector('th[scope=\"col\"], [role=\"columnheader\"]') === null && isRendered(row)\n );\n const rows = bodyRows.slice(0, MAX_TABLE_ROWS).map((row, rowIndex) => ({\n reference: register(`row.${rowKeyOf(row, idColumnIndex >= 0 ? idColumnIndex : null, rowIndex)}`, row),\n cells: Array.from(row.children).map(cell => {\n const secret = cell.closest(`[${AGENT_ATTRIBUTES.secret}]`) !== null || cell.querySelector(`[${AGENT_ATTRIBUTES.secret}]`) !== null;\n return secret ? '(hidden)' : textOf(cell);\n }),\n selected: row.getAttribute('aria-selected') === 'true' || row.getAttribute('data-state') === 'selected',\n }));\n return { caption: textOf(table.querySelector('caption')) || table.getAttribute('aria-label'), columns, rows, totalRows: bodyRows.length };\n }\n}\n","import type { ScreenHighlighter, ScreenMarkResult } from \"./client-tools\";\nimport { AGENT_ATTRIBUTES, labelOfElement, type ScreenReferenceRegistry } from \"./DomScreenReader\";\n\n/** How long a mark stays. */\nexport const MARK_VISIBLE_MS = 8000;\n\n/** The most characters of a note. */\nconst MAX_NOTE_CHARS = 120;\n\n/** A region of the viewport in CSS pixels (a `DOMRect` fits). */\nexport interface ScreenOccludingRect {\n top: number;\n left: number;\n right: number;\n bottom: number;\n}\n\n/** What a mark did, for the application (e.g. to shrink or move its agent window). */\nexport interface ScreenHighlightEvent {\n /** The references that were marked */\n references: string[];\n /** The marked elements, the first one scrolled into view */\n elements: Element[];\n /** The region the application reported as covering the page (its agent window), or null */\n occludingRect: ScreenOccludingRect | null;\n /** True when the first element stays covered by that region after the scroll (too tall for the free band, or a side panel over it) */\n coveredAfterScroll: boolean;\n}\n\n/** How to scroll a marked element so that it lands beside a covering region. */\nexport interface HighlightScrollPlan {\n /** Scroll margins applied for the one `scrollIntoView` call, in pixels */\n scrollMarginTop: number;\n scrollMarginBottom: number;\n /** True when the element cannot be scrolled out from under the region */\n coveredAfterScroll: boolean;\n}\n\n/** A region at least this share of the viewport height is a side panel: vertical scrolling cannot clear it. */\nexport const SIDE_PANEL_MIN_HEIGHT_SHARE = 0.6;\n\n/** The space kept between a marked element and the edge of the free band. */\nconst FREE_BAND_PADDING_PX = 16;\n\nexport interface DomScreenHighlighterOptions {\n registry: ScreenReferenceRegistry;\n /** The sentence the live region reads, e.g. \"The assistant marked: End date\" (translated by the application) */\n announce: (labels: string[]) => string;\n /** The region that covers the page now (the agent window in the viewport), or null; marks are scrolled beside it */\n getOccludingRect?: () => ScreenOccludingRect | null;\n /** Called after each mark, e.g. to make the agent window smaller or move it when the element stays covered */\n onHighlight?: (event: ScreenHighlightEvent) => void;\n}\n\n/**\n * Where a marked element must scroll to stay clear of a covering region: a sheet at the bottom (or top) of the\n * viewport that overlaps the element horizontally adds its height as a scroll margin, so `block: 'center'` centers the\n * element in the free band; a side panel (taller than {@link SIDE_PANEL_MIN_HEIGHT_SHARE} of the viewport) over the\n * element cannot be cleared by scrolling and is reported as covered.\n */\nexport const planHighlightScroll = (\n targetRect: ScreenOccludingRect,\n occludingRect: ScreenOccludingRect | null,\n viewportHeight: number,\n): HighlightScrollPlan => {\n const plan: HighlightScrollPlan = { scrollMarginTop: 0, scrollMarginBottom: 0, coveredAfterScroll: false };\n if (!occludingRect || occludingRect.bottom <= occludingRect.top || occludingRect.right <= occludingRect.left) return plan;\n const overlapsHorizontally = occludingRect.left < targetRect.right && occludingRect.right > targetRect.left;\n if (!overlapsHorizontally) return plan;\n const occludingHeight = Math.min(occludingRect.bottom, viewportHeight) - Math.max(occludingRect.top, 0);\n if (occludingHeight <= 0) return plan;\n if (occludingHeight >= viewportHeight * SIDE_PANEL_MIN_HEIGHT_SHARE) {\n plan.coveredAfterScroll = true;\n return plan;\n }\n const targetHeight = targetRect.bottom - targetRect.top;\n const occludesBottom = (occludingRect.top + occludingRect.bottom) / 2 >= viewportHeight / 2;\n if (occludesBottom) {\n plan.scrollMarginBottom = Math.max(0, viewportHeight - occludingRect.top);\n plan.coveredAfterScroll = targetHeight > Math.max(0, occludingRect.top) - FREE_BAND_PADDING_PX;\n } else {\n plan.scrollMarginTop = Math.max(0, occludingRect.bottom);\n plan.coveredAfterScroll = targetHeight > viewportHeight - Math.max(0, occludingRect.bottom) - FREE_BAND_PADDING_PX;\n }\n return plan;\n};\n\n/**\n * Marks elements with a calm outline (the theme's `--ring`) in an overlay above the page, a short note beside the\n * first one, and one sentence in a polite live region. The overlay never takes a click (`pointer-events: none`) and is\n * never read (`data-agent-skip`). Marks follow scrolling and leave after {@link MARK_VISIBLE_MS}, on Escape or on the\n * next mark. With `getOccludingRect` the first element is scrolled beside the application's agent window, and a\n * mark that stays covered counts as out of view; `onHighlight` tells the application after every mark.\n */\nexport class DomScreenHighlighter implements ScreenHighlighter {\n protected overlay: HTMLElement | null = null;\n\n protected liveRegion: HTMLElement | null = null;\n\n protected frame = 0;\n\n protected timer: ReturnType<typeof setTimeout> | null = null;\n\n protected marked: { element: Element; box: HTMLElement }[] = [];\n\n protected note: HTMLElement | null = null;\n\n constructor(protected readonly options: DomScreenHighlighterOptions) {}\n\n mark(references: string[], note: string | null): ScreenMarkResult {\n this.clear();\n const result: ScreenMarkResult = { marked: {}, missing: [], outOfView: [], collapsed: [] };\n const targets: Element[] = [];\n for (const reference of references) {\n let element = this.options.registry.find(reference) ?? this.options.registry.findAnchor(reference);\n if (!element) {\n result.missing.push(reference);\n continue;\n }\n // inside a closed section: mark what opens it\n const closedDisclosure = element.closest('[data-state=\"closed\"]');\n if (closedDisclosure && closedDisclosure !== element) {\n const trigger = closedDisclosure.parentElement?.querySelector('[aria-expanded=\"false\"]');\n if (trigger) {\n element = trigger;\n result.collapsed.push(reference);\n }\n }\n const rect = element.getBoundingClientRect();\n if (rect.bottom < 0 || rect.top > window.innerHeight) result.outOfView.push(reference);\n result.marked[reference] = labelOfElement(element) || reference;\n targets.push(element);\n }\n if (targets.length === 0) return result;\n const occludingRect = this.readOccludingRect();\n const plan = this.scrollIntoFreeBand(targets[0], occludingRect);\n const firstReference = Object.keys(result.marked)[0];\n if (plan.coveredAfterScroll && firstReference !== undefined && !result.outOfView.includes(firstReference)) {\n result.outOfView.push(firstReference);\n }\n this.draw(targets, note ? note.slice(0, MAX_NOTE_CHARS) : null);\n this.announce(this.options.announce(Object.values(result.marked)));\n try {\n this.options.onHighlight?.({\n references: Object.keys(result.marked),\n elements: targets,\n occludingRect,\n coveredAfterScroll: plan.coveredAfterScroll,\n });\n } catch {\n // the application's hook never breaks the mark\n }\n return result;\n }\n\n /** The application's covering region now; a failing callback counts as none. */\n protected readOccludingRect(): ScreenOccludingRect | null {\n try {\n return this.options.getOccludingRect?.() ?? null;\n } catch {\n return null;\n }\n }\n\n /** Scrolls the element to the center of the band the covering region leaves free (the whole viewport without one). */\n protected scrollIntoFreeBand(element: Element, occludingRect: ScreenOccludingRect | null): HighlightScrollPlan {\n const plan = planHighlightScroll(element.getBoundingClientRect(), occludingRect, window.innerHeight);\n const style = (element as HTMLElement).style as CSSStyleDeclaration | undefined;\n const marginTopBefore = style?.scrollMarginTop ?? '';\n const marginBottomBefore = style?.scrollMarginBottom ?? '';\n if (style) {\n if (plan.scrollMarginTop > 0) style.scrollMarginTop = `${plan.scrollMarginTop}px`;\n if (plan.scrollMarginBottom > 0) style.scrollMarginBottom = `${plan.scrollMarginBottom}px`;\n }\n try {\n // the scroll position is computed in the call: the margins can go right after it\n element.scrollIntoView({ block: 'center', behavior: 'smooth' });\n } finally {\n if (style) {\n style.scrollMarginTop = marginTopBefore;\n style.scrollMarginBottom = marginBottomBefore;\n }\n }\n return plan;\n }\n\n clear(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n if (this.frame) cancelAnimationFrame(this.frame);\n this.frame = 0;\n this.overlay?.remove();\n this.overlay = null;\n this.marked = [];\n this.note = null;\n document.removeEventListener('keydown', this.clearOnEscape);\n }\n\n protected clearOnEscape = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') this.clear();\n };\n\n protected draw(elements: Element[], note: string | null): void {\n const overlay = document.createElement('div');\n overlay.setAttribute(AGENT_ATTRIBUTES.skip, '');\n overlay.setAttribute('aria-hidden', 'true');\n overlay.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483000;';\n document.body.appendChild(overlay);\n this.overlay = overlay;\n this.marked = elements.map(element => {\n const box = document.createElement('div');\n box.style.cssText =\n 'position:fixed;border-radius:8px;box-shadow:0 0 0 2px var(--ring, #06d6e3),0 0 0 6px color-mix(in oklab, var(--ring, #06d6e3) 25%, transparent);transition:opacity 200ms ease;';\n overlay.appendChild(box);\n return { element, box };\n });\n if (note) {\n const noteElement = document.createElement('div');\n noteElement.textContent = note;\n noteElement.style.cssText =\n 'position:fixed;max-width:280px;padding:6px 10px;border-radius:8px;font-size:13px;line-height:1.35;background:var(--popover, #fff);color:var(--popover-foreground, #0b0948);box-shadow:0 4px 16px rgb(0 0 0 / 0.16);';\n overlay.appendChild(noteElement);\n this.note = noteElement;\n }\n const follow = (): void => {\n for (const { element, box } of this.marked) {\n const rect = element.getBoundingClientRect();\n box.style.left = `${rect.left - 4}px`;\n box.style.top = `${rect.top - 4}px`;\n box.style.width = `${rect.width + 8}px`;\n box.style.height = `${rect.height + 8}px`;\n box.style.opacity = element.isConnected ? '1' : '0';\n }\n if (this.note && this.marked[0]) {\n const rect = this.marked[0].element.getBoundingClientRect();\n // the note stays out of the agent window: a sheet below the element ends the room below\n const occludingRect = this.readOccludingRect();\n const coversBelow =\n occludingRect !== null &&\n occludingRect.left < rect.right &&\n occludingRect.right > rect.left &&\n occludingRect.top >= rect.bottom;\n const roomBottom = coversBelow ? occludingRect.top : window.innerHeight;\n const below = rect.bottom + 10 + 60 < roomBottom;\n this.note.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 296))}px`;\n this.note.style.top = below ? `${rect.bottom + 10}px` : `${Math.max(8, rect.top - 70)}px`;\n }\n this.frame = requestAnimationFrame(follow);\n };\n follow();\n document.addEventListener('keydown', this.clearOnEscape);\n this.timer = setTimeout(() => this.clear(), MARK_VISIBLE_MS);\n }\n\n protected announce(sentence: string): void {\n if (!this.liveRegion?.isConnected) {\n const liveRegion = document.createElement('div');\n liveRegion.setAttribute('role', 'status');\n liveRegion.setAttribute('aria-live', 'polite');\n liveRegion.setAttribute(AGENT_ATTRIBUTES.skip, '');\n liveRegion.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;';\n document.body.appendChild(liveRegion);\n this.liveRegion = liveRegion;\n }\n this.liveRegion.textContent = '';\n const liveRegion = this.liveRegion;\n setTimeout(() => {\n liveRegion.textContent = sentence;\n }, 50);\n }\n}\n","import type { ScreenTarget, ScreenTargetSource } from \"./client-tools\";\nimport { isClientToolToken } from \"./client-tools\";\n\n/** The attribute that marks an element as a screen the user can open; its value is the target key. */\nexport const AGENT_ANCHOR_ATTRIBUTE = 'data-agent-anchor';\n\n/** The attribute that puts a mark into a group (`groupKey` of `createDomScreenTargetSource()`). */\nexport const AGENT_ANCHOR_GROUP_ATTRIBUTE = 'data-agent-anchor-group';\n\nexport interface DomScreenTargetSourceOptions {\n /** Where the marks are looked for; default the document */\n root?: () => ParentNode | null;\n /** Only the marks of this group (`data-agent-anchor-group`); default every mark */\n groupKey?: string;\n}\n\nconst listAttribute = (element: Element, attributeName: string): string[] =>\n (element.getAttribute(attributeName) ?? '')\n .split(',')\n .map(part => part.trim())\n .filter(part => part !== '');\n\n/** The route of a mark: `data-agent-route`, else the path of its link. */\nconst routeOfMark = (element: Element): string | null => {\n const route = element.getAttribute('data-agent-route');\n if (route) return route;\n const href = element.getAttribute('href');\n if (!href) return null;\n try {\n const url = new URL(href, 'http://screen.invalid');\n return url.pathname;\n } catch {\n return null;\n }\n};\n\n/**\n * Reads one `ScreenTarget` from a mark, or null when it lacks a valid key or a route. The attributes:\n * `data-agent-anchor` (the key), `data-agent-label` (else the text), `data-agent-group`, `data-agent-route` (else the\n * link's path), and the comma lists `data-agent-parameters`, `data-agent-tabs`, `data-agent-filters`,\n * `data-agent-views`.\n */\nexport const readScreenTargetOfMark = (element: Element): ScreenTarget | null => {\n const key = element.getAttribute(AGENT_ANCHOR_ATTRIBUTE)?.trim() ?? '';\n if (!isClientToolToken(key)) return null;\n const routePattern = routeOfMark(element);\n if (!routePattern) return null;\n const label = (element.getAttribute('data-agent-label') ?? element.textContent ?? '').replace(/\\s+/g, ' ').trim() || key;\n return {\n key,\n label,\n group: element.getAttribute('data-agent-group')?.trim() || null,\n routePattern,\n parameters: listAttribute(element, 'data-agent-parameters'),\n tabs: listAttribute(element, 'data-agent-tabs'),\n filters: listAttribute(element, 'data-agent-filters').map(filterKey => ({ key: filterKey })),\n views: listAttribute(element, 'data-agent-views'),\n };\n};\n\n/**\n * A `ScreenTargetSource` from the marks of the rendered navigation: every element with `data-agent-anchor` the user\n * sees is a screen the user may open (the application renders only what its rights allow, so the marks carry its\n * rights). The first mark of a key wins. An application with a route table of its own writes its own source instead.\n */\nexport const createDomScreenTargetSource = (options: DomScreenTargetSourceOptions = {}): ScreenTargetSource => ({\n listTargets: (): ScreenTarget[] => {\n const root = options.root?.() ?? (typeof document !== 'undefined' ? document : null);\n if (!root) return [];\n const targets: ScreenTarget[] = [];\n const seenKeys = new Set<string>();\n for (const element of Array.from(root.querySelectorAll(`[${AGENT_ANCHOR_ATTRIBUTE}]`))) {\n if (options.groupKey !== undefined && element.getAttribute(AGENT_ANCHOR_GROUP_ATTRIBUTE) !== options.groupKey) continue;\n const target = readScreenTargetOfMark(element);\n if (!target || seenKeys.has(target.key)) continue;\n seenKeys.add(target.key);\n targets.push(target);\n }\n return targets;\n },\n});\n","import type { ScreenOpenRequest, ScreenPathGuide, ScreenTarget } from \"./client-tools\";\nimport { buildTargetRoute } from \"./client-tools\";\n\n/** How many times a target is guided before the agent just opens it (`shouldGuide` default). */\nexport const DEFAULT_GUIDES_PER_TARGET = 2;\n\n/** The key prefix of the guide counts in localStorage. */\nexport const PATH_GUIDE_COUNT_KEY_PREFIX = 'ddd-agents:pathGuide:';\n\n/** How long one step of the path stays marked, in ms. */\nexport const PATH_GUIDE_STEP_MS = 700;\n\n/** The class a marked step of the path carries; the step also gets an outline in the theme's `--ring` (inline, restored after). */\nexport const PATH_GUIDE_CLASS = 'agents-path-guide-step';\n\n/**\n * The default `shouldGuide`: the first `limit` opens of a target are guided, counted per key in localStorage; without\n * storage (private window, blocked) every open is guided once per page life.\n */\nexport const createGuideCounter = (\n limit: number = DEFAULT_GUIDES_PER_TARGET,\n readStorage: () => Pick<Storage, 'getItem' | 'setItem'> | null = () => window.localStorage,\n): ((targetKey: string) => boolean) => {\n const counts = new Map<string, number>();\n return (targetKey: string): boolean => {\n const storageKey = `${PATH_GUIDE_COUNT_KEY_PREFIX}${targetKey}`;\n let count = counts.get(targetKey) ?? 0;\n try {\n count = Math.max(count, Number.parseInt(readStorage()?.getItem(storageKey) ?? '0', 10) || 0);\n } catch {\n // no storage: the count of this page life\n }\n if (count >= limit) return false;\n counts.set(targetKey, count + 1);\n try {\n readStorage()?.setItem(storageKey, String(count + 1));\n } catch {\n // no storage\n }\n return true;\n };\n};\n\nexport interface DomScreenPathGuideOptions {\n /** The elements of the way to the target in order (menu group, menu entry, tab); missing ones are skipped */\n findPathElements: (target: ScreenTarget, request: ScreenOpenRequest) => Element[];\n /** The route the user is on (without the basePath and query) */\n currentRoute: () => string;\n /** Whether this open of the target is guided; default the first `DEFAULT_GUIDES_PER_TARGET` per key */\n shouldGuide?: (targetKey: string) => boolean;\n stepMs?: number;\n}\n\nconst PATH_GUIDE_OUTLINE = '2px solid var(--ring, #2563eb)';\n\nconst markStep = (element: Element, outlinesBefore: Map<Element, string>): void => {\n element.classList.add(PATH_GUIDE_CLASS);\n if (element instanceof HTMLElement) {\n outlinesBefore.set(element, element.style.outline);\n element.style.outline = PATH_GUIDE_OUTLINE;\n }\n};\n\nconst unmarkStep = (element: Element, outlinesBefore: Map<Element, string>): void => {\n element.classList.remove(PATH_GUIDE_CLASS);\n if (element instanceof HTMLElement && outlinesBefore.has(element)) {\n element.style.outline = outlinesBefore.get(element) ?? '';\n outlinesBefore.delete(element);\n }\n};\n\nconst prefersReducedMotion = (): boolean => {\n try {\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n } catch {\n return false;\n }\n};\n\n/**\n * The DOM default of `ScreenPathGuide`: marks the elements of the way to the target one after the other\n * (`PATH_GUIDE_CLASS`), so the user learns where the screen lives. It runs beside the navigation and never delays the\n * answer. Skipped under reduced motion, when the user already is on the target, when no element of the way is on the\n * screen (plain navigation), and when `shouldGuide` says so. Esc or a click cancels it.\n */\nexport const createDomScreenPathGuide = (options: DomScreenPathGuideOptions): ScreenPathGuide => {\n const shouldGuide = options.shouldGuide ?? createGuideCounter();\n const stepMs = options.stepMs ?? PATH_GUIDE_STEP_MS;\n let timers: ReturnType<typeof setTimeout>[] = [];\n let markedElements: Element[] = [];\n const outlinesBefore = new Map<Element, string>();\n let removeListeners: (() => void) | null = null;\n\n const cancel = (): void => {\n timers.forEach(timer => clearTimeout(timer));\n timers = [];\n markedElements.forEach(element => unmarkStep(element, outlinesBefore));\n markedElements = [];\n removeListeners?.();\n removeListeners = null;\n };\n\n const guide = (target: ScreenTarget, request: ScreenOpenRequest): boolean => {\n cancel();\n if (prefersReducedMotion()) return false;\n const targetRoute = buildTargetRoute(target, request.recordIds, request.tab);\n const currentRoute = options.currentRoute().split('?')[0];\n if (targetRoute !== null && currentRoute === targetRoute) return false;\n const pathElements = options.findPathElements(target, request).filter(element => element.isConnected);\n if (pathElements.length === 0) return false;\n if (!shouldGuide(target.key)) return false;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') cancel();\n };\n const onPointerDown = (): void => cancel();\n document.addEventListener('keydown', onKeyDown, true);\n document.addEventListener('pointerdown', onPointerDown, true);\n removeListeners = () => {\n document.removeEventListener('keydown', onKeyDown, true);\n document.removeEventListener('pointerdown', onPointerDown, true);\n };\n pathElements.forEach((element, stepIndex) => {\n timers.push(\n setTimeout(() => {\n markedElements.forEach(marked => unmarkStep(marked, outlinesBefore));\n markStep(element, outlinesBefore);\n markedElements = [element];\n }, stepIndex * stepMs),\n );\n });\n timers.push(setTimeout(cancel, pathElements.length * stepMs));\n return true;\n };\n\n return { guide, cancel };\n};\n","import type { ScreenPicture, ScreenPictureCapturer, ScreenPictureRenderMode, ScreenPictureRequest, ScreenPictureSize } from \"./client-tools\";\n\n/**\n * What a picture of the screen cannot show. The same sentences as `AgentUIMCPPackage::PICTURE_LIMITATIONS` of the\n * server (a contract test compares them): the model reads them beside every picture.\n */\nexport const PICTURE_LIMITATIONS: readonly string[] = [\n 'content of other origins (embedded frames, some images and fonts) can be blank or replaced',\n 'video, canvas and WebGL content can be blank',\n 'password fields show dots; fields the application marks secret or skipped are left out',\n 'scrolled-away parts of a scroll container are shown expanded, so the picture can be longer than the window',\n];\n\n/** The budgets of one size preset: the long edge, the pixels and the encoded bytes. */\nexport interface ScreenPicturePreset {\n maxLongEdge: number;\n maxPixels: number;\n maxBytes: number;\n}\n\n/** The three size presets; `large` stays below the server's caps (4,000,000 pixels, 614,400 bytes). */\nexport const SCREEN_PICTURE_PRESETS: Record<ScreenPictureSize, ScreenPicturePreset> = {\n small: { maxLongEdge: 1024, maxPixels: 786_432, maxBytes: 150_000 },\n medium: { maxLongEdge: 1600, maxPixels: 1_920_000, maxBytes: 350_000 },\n large: { maxLongEdge: 2048, maxPixels: 3_750_000, maxBytes: 600_000 },\n};\n\n/** The machine mode: 64 grey levels, 75 % of the size, half the byte budget (a picture for the model, not a person). */\nexport const MACHINE_MODE_GREY_LEVELS = 64;\nexport const MACHINE_MODE_SIZE_FACTOR = 0.75;\nexport const MACHINE_MODE_BYTE_FACTOR = 0.5;\n\n/** The most encodings of one capture; each retry scales down from the source. */\nexport const MAX_PICTURE_ENCODE_ATTEMPTS = 4;\n\n/** The most elements a capture copies (a larger page keeps its first elements). */\nexport const MAX_PICTURE_ELEMENTS = 8000;\n\n/** The attribute that leaves an element out of a picture. */\nexport const AGENT_SKIP_ATTRIBUTE = 'data-agent-skip';\n\n/** The attribute that blanks an element's content in a picture (its box stays). */\nexport const AGENT_SECRET_ATTRIBUTE = 'data-agent-secret';\n\nexport interface ScreenPictureDimensions {\n width: number;\n height: number;\n /** The factor from the source size */\n scale: number;\n}\n\n/** The byte budget of a preset in a render mode. */\nexport const computePictureByteBudget = (pictureSize: ScreenPictureSize, renderMode: ScreenPictureRenderMode): number => {\n const preset = SCREEN_PICTURE_PRESETS[pictureSize];\n return Math.floor(renderMode === 'machine' ? preset.maxBytes * MACHINE_MODE_BYTE_FACTOR : preset.maxBytes);\n};\n\n/**\n * The size of the picture of a source: within the long edge and the pixels of the preset (never larger than the\n * source), 75 % of it in the machine mode, times `retryScale` (a retry's factor, always taken from the source size).\n */\nexport const computePictureDimensions = (\n sourceWidth: number,\n sourceHeight: number,\n request: ScreenPictureRequest,\n retryScale: number = 1,\n): ScreenPictureDimensions => {\n const preset = SCREEN_PICTURE_PRESETS[request.pictureSize];\n const safeWidth = Math.max(1, sourceWidth);\n const safeHeight = Math.max(1, sourceHeight);\n let scale = Math.min(1, preset.maxLongEdge / Math.max(safeWidth, safeHeight), Math.sqrt(preset.maxPixels / (safeWidth * safeHeight)));\n if (request.renderMode === 'machine') scale *= MACHINE_MODE_SIZE_FACTOR;\n scale *= retryScale;\n return {\n width: Math.max(1, Math.floor(safeWidth * scale)),\n height: Math.max(1, Math.floor(safeHeight * scale)),\n scale,\n };\n};\n\n/**\n * The factor of the next attempt after an encoding of `encodedBytes` missed the budget: the bytes shrink about with the\n * pixels, so the side shrinks with the square root, with a margin. Applied to the source size, never to the last\n * picture (no blur piling up over retries).\n */\nexport const computeRetryScale = (previousRetryScale: number, encodedBytes: number, byteBudget: number): number => {\n if (encodedBytes <= 0) return previousRetryScale;\n return previousRetryScale * Math.min(0.9, Math.sqrt(byteBudget / encodedBytes) * 0.9);\n};\n\n/** Turns RGBA pixels grey in place; with `greyLevels` the grey is quantized to that many levels. */\nexport const convertPixelsToGrey = (pixels: Uint8ClampedArray, greyLevels: number | null = null): void => {\n const levelStep = greyLevels !== null && greyLevels > 1 ? 255 / (greyLevels - 1) : null;\n for (let index = 0; index < pixels.length; index += 4) {\n let grey = 0.2126 * pixels[index] + 0.7152 * pixels[index + 1] + 0.0722 * pixels[index + 2];\n if (levelStep !== null) grey = Math.round(grey / levelStep) * levelStep;\n pixels[index] = grey;\n pixels[index + 1] = grey;\n pixels[index + 2] = grey;\n }\n};\n\n/** Whether an element scrolls its own content vertically (its scrolled-away part is shown expanded). */\nconst isScrollContainer = (element: Element, style: CSSStyleDeclaration): boolean =>\n element.scrollHeight > element.clientHeight + 1 && (style.overflowY === 'auto' || style.overflowY === 'scroll');\n\n/** Copies the computed style of an element onto its clone as inline style. */\nconst copyComputedStyle = (style: CSSStyleDeclaration, clone: HTMLElement | SVGElement): void => {\n const declarations: string[] = [];\n for (let index = 0; index < style.length; index += 1) {\n const property = style.item(index);\n declarations.push(`${property}:${style.getPropertyValue(property)}`);\n }\n clone.setAttribute('style', declarations.join(';'));\n};\n\n/** The value of a form field written into its clone, a password as dots. */\nconst copyFieldValue = (original: Element, clone: Element): void => {\n if (original instanceof HTMLInputElement && clone instanceof HTMLInputElement) {\n if (original.type === 'password') {\n clone.setAttribute('value', '•'.repeat(Math.min(original.value.length, 24)));\n clone.type = 'text';\n } else if (original.type === 'checkbox' || original.type === 'radio') {\n if (original.checked) clone.setAttribute('checked', '');\n else clone.removeAttribute('checked');\n } else {\n clone.setAttribute('value', original.value);\n }\n } else if (original instanceof HTMLTextAreaElement) {\n clone.textContent = original.value;\n } else if (original instanceof HTMLSelectElement && clone instanceof HTMLSelectElement) {\n Array.from(clone.options).forEach((option, optionIndex) => {\n if (optionIndex === original.selectedIndex) option.setAttribute('selected', '');\n else option.removeAttribute('selected');\n });\n }\n};\n\n/** Elements never copied into a picture. */\nconst LEFT_OUT_TAGS = new Set(['SCRIPT', 'NOSCRIPT', 'TEMPLATE', 'LINK', 'META']);\n\n/**\n * A copy of `root` ready to be drawn: computed styles inlined, form values written (passwords as dots), elements with\n * `data-agent-skip` left out, the content of elements with `data-agent-secret` blanked (the box stays), scroll\n * containers expanded. `copyStyles` false skips the styles (tests).\n */\nexport const prepareScreenCloneForPicture = (root: Element, copyStyles: boolean = true): Element => {\n const clone = root.cloneNode(false) as Element;\n let copiedElements = 0;\n const copyInto = (original: Element, target: Element): void => {\n const view = original.ownerDocument.defaultView;\n const style = copyStyles && view ? view.getComputedStyle(original) : null;\n if (style && (target instanceof HTMLElement || target instanceof SVGElement)) {\n copyComputedStyle(style, target);\n if (target instanceof HTMLElement && isScrollContainer(original, style)) {\n target.style.overflowY = 'visible';\n target.style.height = 'auto';\n target.style.maxHeight = 'none';\n }\n } else if (!copyStyles && target instanceof HTMLElement && original.scrollHeight > original.clientHeight + 1) {\n target.style.overflowY = 'visible';\n target.style.height = 'auto';\n target.style.maxHeight = 'none';\n }\n copyFieldValue(original, target);\n if (original.hasAttribute(AGENT_SECRET_ATTRIBUTE)) {\n target.textContent = '';\n if (target instanceof HTMLElement) target.style.background = '#9e9e9e';\n return;\n }\n if (original instanceof HTMLTextAreaElement) return;\n for (const childNode of Array.from(original.childNodes)) {\n if (childNode.nodeType === Node.TEXT_NODE) {\n target.appendChild(childNode.cloneNode(false));\n continue;\n }\n if (!(childNode instanceof Element)) continue;\n if (LEFT_OUT_TAGS.has(childNode.tagName) || childNode.hasAttribute(AGENT_SKIP_ATTRIBUTE)) continue;\n if (copiedElements >= MAX_PICTURE_ELEMENTS) return;\n copiedElements += 1;\n const childClone = childNode.cloneNode(false) as Element;\n target.appendChild(childClone);\n copyInto(childNode, childClone);\n }\n };\n copyInto(root, clone);\n return clone;\n};\n\n/** Measures the height of a prepared clone laid out at `width`, off screen. */\nconst measureCloneHeight = (clone: Element, width: number, documentOfRoot: Document): number => {\n const holder = documentOfRoot.createElement('div');\n holder.setAttribute('aria-hidden', 'true');\n holder.style.cssText = `position:fixed;left:-100000px;top:0;width:${width}px;visibility:hidden;pointer-events:none;`;\n const measured = clone.cloneNode(true) as Element;\n holder.appendChild(measured);\n documentOfRoot.body.appendChild(holder);\n try {\n return Math.ceil(Math.max(holder.scrollHeight, (measured as HTMLElement).scrollHeight ?? 0));\n } finally {\n holder.remove();\n }\n};\n\nconst loadImage = (url: string): Promise<HTMLImageElement> =>\n new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error('the screen could not be drawn'));\n image.src = url;\n });\n\nconst encodeCanvas = (canvas: HTMLCanvasElement, mimeType: string, quality: number): Promise<Blob | null> =>\n new Promise(resolve => {\n try {\n canvas.toBlob(blob => resolve(blob), mimeType, quality);\n } catch {\n resolve(null);\n }\n });\n\nconst encodeBase64 = async (blob: Blob): Promise<string> => {\n const bytes = new Uint8Array(await blob.arrayBuffer());\n let binary = '';\n const chunkSize = 0x8000;\n for (let offset = 0; offset < bytes.length; offset += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));\n }\n return btoa(binary);\n};\n\nexport interface DomScreenPictureCapturerOptions {\n /** The element pictured; default the document element */\n root?: () => Element | null;\n /** The quality of the first encoding (default 0.8); a retry lowers it once to 0.65 */\n quality?: number;\n}\n\n/**\n * The DOM default of `ScreenPictureCapturer`: draws a styled copy of the page (SVG foreignObject onto a canvas) at the\n * size of the preset, grey in `greyscale` and `machine` (64 levels), and encodes it as WebP (JPEG where the browser\n * has no WebP encoder) within the byte budget; a miss retries from the source size, at most\n * `MAX_PICTURE_ENCODE_ATTEMPTS` times. No dependency; what it cannot show is `PICTURE_LIMITATIONS`. Returns null when\n * the browser refuses (a tainted canvas, no canvas), and the runner answers `PICTURE_UNAVAILABLE`.\n */\nexport const createDomScreenPictureCapturer = (options: DomScreenPictureCapturerOptions = {}): ScreenPictureCapturer => ({\n capture: async (request: ScreenPictureRequest): Promise<ScreenPicture | null> => {\n if (typeof document === 'undefined') return null;\n const root = options.root?.() ?? document.documentElement;\n if (!root) return null;\n try {\n const sourceWidth = Math.max(1, Math.ceil(window.innerWidth || root.clientWidth));\n const clone = prepareScreenCloneForPicture(root);\n const sourceHeight = Math.max(1, Math.min(measureCloneHeight(clone, sourceWidth, document), sourceWidth * 8));\n const serialized = new XMLSerializer().serializeToString(clone);\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${sourceWidth}\" height=\"${sourceHeight}\">` +\n `<foreignObject x=\"0\" y=\"0\" width=\"100%\" height=\"100%\">${serialized}</foreignObject></svg>`;\n const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`);\n const byteBudget = computePictureByteBudget(request.pictureSize, request.renderMode);\n let retryScale = 1;\n let quality = options.quality ?? 0.8;\n for (let attempt = 1; attempt <= MAX_PICTURE_ENCODE_ATTEMPTS; attempt += 1) {\n const dimensions = computePictureDimensions(sourceWidth, sourceHeight, request, retryScale);\n const canvas = document.createElement('canvas');\n canvas.width = dimensions.width;\n canvas.height = dimensions.height;\n const context = canvas.getContext('2d');\n if (!context) return null;\n context.fillStyle = '#ffffff';\n context.fillRect(0, 0, dimensions.width, dimensions.height);\n context.drawImage(image, 0, 0, dimensions.width, dimensions.height);\n if (request.renderMode !== 'colour') {\n const imageData = context.getImageData(0, 0, dimensions.width, dimensions.height);\n convertPixelsToGrey(imageData.data, request.renderMode === 'machine' ? MACHINE_MODE_GREY_LEVELS : null);\n context.putImageData(imageData, 0, 0);\n }\n let blob = await encodeCanvas(canvas, 'image/webp', quality);\n if (blob && blob.type !== 'image/webp') blob = await encodeCanvas(canvas, 'image/jpeg', quality);\n if (!blob) return null;\n if (blob.size <= byteBudget || attempt === MAX_PICTURE_ENCODE_ATTEMPTS) {\n if (blob.size > byteBudget) return null;\n return {\n base64: await encodeBase64(blob),\n mimeType: blob.type === 'image/webp' ? 'image/webp' : 'image/jpeg',\n width: dimensions.width,\n height: dimensions.height,\n byteSize: blob.size,\n };\n }\n retryScale = computeRetryScale(retryScale, blob.size, byteBudget);\n quality = Math.min(quality, 0.65);\n }\n return null;\n } catch {\n return null;\n }\n },\n});\n","import type { AgentWindowAdapter, ClientToolRequestType } from \"./client-tools\";\n\nexport interface AgentWindowAdapterOptions {\n /** The mode the window shows now */\n getMode: () => string;\n /** Shows a mode; called only with a mode of `modes` */\n applyMode: (mode: string) => void | Promise<void>;\n /** The modes the application knows (`setAgentWindowMode` refuses others) */\n modes: string[];\n /** The mode of `stepAside()`; default `aside` */\n asideMode?: string;\n /** The request types the window steps aside for; default `OPEN_TARGET`, `HIGHLIGHT`, a picture (`READ_SCREEN`) */\n stepAsideFor?: ClientToolRequestType[];\n}\n\n/**\n * An `AgentWindowAdapter` over the application's own window state: `stepAside()` remembers the mode and shows the\n * aside mode, `restore()` goes back to the remembered mode, `setMode()` shows a known mode. Stepping aside before the\n * agent opens a screen, marks elements or takes a picture is the default.\n */\nexport const createAgentWindowAdapter = (options: AgentWindowAdapterOptions): AgentWindowAdapter => {\n const asideMode = options.asideMode ?? 'aside';\n const stepAsideFor = options.stepAsideFor ?? ['OPEN_TARGET', 'HIGHLIGHT', 'READ_SCREEN'];\n let modeBeforeAside: string | null = null;\n return {\n stepAside: async () => {\n const currentMode = options.getMode();\n if (currentMode === asideMode) return;\n modeBeforeAside = currentMode;\n await options.applyMode(asideMode);\n },\n restore: async () => {\n if (modeBeforeAside === null) return;\n const mode = modeBeforeAside;\n modeBeforeAside = null;\n await options.applyMode(mode);\n },\n setMode: async (mode: string) => {\n if (!options.modes.includes(mode)) return false;\n modeBeforeAside = null;\n await options.applyMode(mode);\n return true;\n },\n shouldStepAsideBefore: (requestType: ClientToolRequestType) => stepAsideFor.includes(requestType),\n };\n};\n","import type { AgentRealtimeListenerCredential, AgentRealtimeMessageDelivery } from \"./realtime-arrival\";\n\n/**\n * The account-level realtime read (`GET …/realtimeMessages`, `AgentAccountRealtimeMessagesGetResponseDto`): the open\n * messages of the realtime port addressed to the signed-in account — what reaches a client that shows no conversation,\n * e.g. a call's ring — and the credential to listen on the host's transport without a conversation.\n */\nexport interface AccountRealtimeRead {\n messages: AgentRealtimeMessageDelivery[];\n /** Null without a transport: the client then keeps polling the read. */\n listenerCredential: AgentRealtimeListenerCredential | null;\n}\n\n/** The pause between two account reads while no transport is bound. */\nexport const ACCOUNT_REALTIME_POLL_INTERVAL_MS = 5_000;\n\n/** The pause before the one re-read of `readAfterPing` when the first read brought nothing new. */\nexport const ACCOUNT_REALTIME_PING_REREAD_DELAY_MS = 400;\n\n/** What a subscriber of the poll is told; each hook is optional. */\nexport interface AccountRealtimePollSubscriber {\n /**\n * A message that arrived: every message once per type, key and payload (a replacement with a new payload arrives\n * again; a message cleared and sent again after a read saw it gone arrives again). From the poll and from the\n * transport.\n */\n onMessage?: (message: AgentRealtimeMessageDelivery) => void;\n /**\n * A message that is open no more: a read answered without any message of its type and key (it was answered or\n * withdrawn on the server, or its time is over). Called once, after the arrivals of the same read. A subscriber is\n * told the clear only of a message it was handed, as an arrival or in the hand-over of `subscribe`, and with that\n * message as it was handed to it last. A replacement under the same type and key is an arrival, never a clear. Only\n * a read tells it, and only of a message that was known when the read started: while a transport is bound, the next\n * `readNow()` or `readAfterPing()`.\n */\n onMessageCleared?: (message: AgentRealtimeMessageDelivery) => void;\n}\n\nexport interface AccountRealtimePollOptions extends AccountRealtimePollSubscriber {\n /**\n * The account read of the binding (`AgentsConversationClient.getAccountRealtimeMessages`), called with the\n * `clientId` option (undefined without one). The read always states a client id (the HTTP binding: query parameter\n * `clientId`), by which the server knows a client that only polls; which id is the binding's word: the one handed\n * in, else the id of its `uiClient`, else one it creates once and keeps while it lives. A binding of the host's own\n * states one the same way.\n */\n readAccountRealtime: (clientId?: string) => Promise<AccountRealtimeRead>;\n /**\n * The client id the account read states, for a host that manages its own ids (8 to 64 letters, digits and `-`): it\n * wins over the binding's `uiClient` and over the id the binding creates. Default: none — the binding decides.\n */\n clientId?: string;\n /** The credential of every read (null without a transport) — the host binds its transport with it. */\n onListenerCredential?: (credential: AgentRealtimeListenerCredential | null) => void;\n /**\n * Whether the host's transport is bound now: while true the poll skips its reads (the transport delivers through\n * `acceptArrivedMessage` or pings `readAfterPing`). Default: never bound — the poll reads every interval.\n */\n isTransportBound?: () => boolean;\n /** The pause between two reads. Default `ACCOUNT_REALTIME_POLL_INTERVAL_MS`. */\n intervalMs?: number;\n /** The pause before the one re-read after a ping. Default `ACCOUNT_REALTIME_PING_REREAD_DELAY_MS`. */\n rereadDelayMs?: number;\n /** A failed read (the next interval reads again; nothing arrives and nothing is cleared). Default: ignored. */\n onReadFailed?: (error: unknown) => void;\n}\n\nexport interface AccountRealtimePoll {\n /**\n * Reads at once (also while a transport is bound); resolves with the number of messages that arrived new. An answer\n * that comes back after the answer of a read started later is left out (0).\n */\n readNow: () => Promise<number>;\n /**\n * The arrival adapter for a host transport that carries the message: hands it to `onMessage` unless it already\n * arrived. Returns whether it arrived new.\n */\n acceptArrivedMessage: (message: AgentRealtimeMessageDelivery) => boolean;\n /**\n * The arrival adapter for a host transport that only pings: reads the account; when that read brought nothing new —\n * the ping overtook the server's write — it reads once more after the re-read delay. Resolves with whether a\n * message arrived.\n */\n readAfterPing: () => Promise<boolean>;\n /**\n * Adds a subscriber after the poll was created; the hooks the poll was created with keep working beside it. The\n * subscriber gets, before `subscribe` returns, the messages open now (those the last read saw and the transport\n * delivered since, inside their `secondsLeft`), then every arrival and the clear of every message it was handed: a\n * message past its `secondsLeft` when the subscriber came is not handed to it, and neither is its clear. Returns\n * the function that removes it; the poll keeps running.\n */\n subscribe: (subscriber: AccountRealtimePollSubscriber) => () => void;\n /**\n * Stops the poll (a read in flight still hands its messages). Nothing is reported as cleared and no subscriber is\n * removed: what `readNow()` or `acceptArrivedMessage()` bring afterwards still reaches them.\n */\n stop: () => void;\n}\n\n/** What makes two deliveries the same message: a new payload under the same type and key is a new message. */\nconst identityOf = (message: AgentRealtimeMessageDelivery): string =>\n `${message.messageType}\\u0000${message.messageKey}\\u0000${message.payloadJson}`;\n\n/** Where a message stands on the realtime port: a replacement stands at the same place. */\nconst placeOf = (message: AgentRealtimeMessageDelivery): string => `${message.messageType}\\u0000${message.messageKey}`;\n\ninterface AccountRealtimePollSubscription {\n subscriber: AccountRealtimePollSubscriber;\n}\n\ninterface KnownAccountRealtimeMessage {\n message: AgentRealtimeMessageDelivery;\n /** How many reads had started when the message became known: none of them can tell that it is gone. */\n startedReadCount: number;\n /** When its `secondsLeft` are over on this client's clock. */\n expiresAtMs: number;\n /** The subscribers the message was handed to, as an arrival or when they came: only they are told its clear. */\n handedTo: Set<AccountRealtimePollSubscription>;\n}\n\n/**\n * The account-level realtime poll of a client that shows no conversation: reads the account at once, then every\n * interval while no transport is bound, hands each new message to `onMessage` once (the same message from the poll and\n * the transport arrives once) and each message a read finds gone to `onMessageCleared` once. Further subscribers come\n * and go through `subscribe`. The client of a conversation keeps its run-state read; this is the read without one.\n */\nexport const createAccountRealtimePoll = (options: AccountRealtimePollOptions): AccountRealtimePoll => {\n const intervalMs = options.intervalMs ?? ACCOUNT_REALTIME_POLL_INTERVAL_MS;\n const rereadDelayMs = options.rereadDelayMs ?? ACCOUNT_REALTIME_PING_REREAD_DELAY_MS;\n /**\n * The messages the last read saw (and the transport delivered since), by identity: one gone from a read may arrive\n * again. A read reports as cleared only what was known when it started.\n */\n let knownMessages = new Map<string, KnownAccountRealtimeMessage>();\n /** The hooks of the options first, then the subscribers in the order they came. */\n const subscriptions = new Set<AccountRealtimePollSubscription>([{ subscriber: options }]);\n let startedReadCount = 0;\n let newestAnsweredRead = 0;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const knownMessageOf = (message: AgentRealtimeMessageDelivery, nowMs: number): KnownAccountRealtimeMessage => ({\n message,\n startedReadCount,\n expiresAtMs: nowMs + message.secondsLeft * 1000,\n handedTo: new Set(),\n });\n\n /** Hands a message to a subscriber and notes it on the message, also for a subscriber without the hook. */\n const handMessage = (knownMessage: KnownAccountRealtimeMessage, subscription: AccountRealtimePollSubscription): void => {\n knownMessage.handedTo.add(subscription);\n subscription.subscriber.onMessage?.(knownMessage.message);\n };\n\n /**\n * A subscriber that came during the hand-over already got the open messages; one that left gets nothing more. Each\n * cleared place comes with its gone messages, the oldest first: a subscriber is told the newest one it was handed,\n * and nothing when it was handed none.\n */\n const handToSubscribers = (\n arrivedMessages: KnownAccountRealtimeMessage[],\n goneMessagesOfClearedPlaces: KnownAccountRealtimeMessage[][],\n ): void => {\n const subscriptionsNow = [...subscriptions];\n for (const arrivedMessage of arrivedMessages) {\n for (const subscription of subscriptionsNow) {\n if (subscriptions.has(subscription)) handMessage(arrivedMessage, subscription);\n }\n }\n for (const goneMessages of goneMessagesOfClearedPlaces) {\n for (const subscription of subscriptionsNow) {\n if (!subscriptions.has(subscription)) continue;\n const handedMessage = goneMessages.filter(goneMessage => goneMessage.handedTo.has(subscription)).pop();\n if (handedMessage !== undefined) subscription.subscriber.onMessageCleared?.(handedMessage.message);\n }\n }\n };\n\n const acceptArrivedMessage = (message: AgentRealtimeMessageDelivery): boolean => {\n const identity = identityOf(message);\n if (knownMessages.has(identity)) return false;\n const knownMessage = knownMessageOf(message, Date.now());\n knownMessages.set(identity, knownMessage);\n handToSubscribers([knownMessage], []);\n return true;\n };\n\n const readNow = async (): Promise<number> => {\n startedReadCount += 1;\n const readNumber = startedReadCount;\n const read = await options.readAccountRealtime(options.clientId);\n // the answer of a read started later is already in: this one tells an older state\n if (readNumber < newestAnsweredRead) return 0;\n newestAnsweredRead = readNumber;\n\n const nowMs = Date.now();\n const knownAfterRead = new Map<string, KnownAccountRealtimeMessage>();\n const openPlaces = new Set<string>();\n const arrivedMessages: KnownAccountRealtimeMessage[] = [];\n for (const message of read.messages) {\n const identity = identityOf(message);\n const knownMessage = knownMessages.get(identity) ?? knownMessageOf(message, nowMs);\n if (!knownMessages.has(identity)) arrivedMessages.push(knownMessage);\n knownAfterRead.set(identity, knownMessage);\n openPlaces.add(placeOf(message));\n }\n const goneMessages: KnownAccountRealtimeMessage[] = [];\n for (const [identity, knownMessage] of knownMessages) {\n if (knownAfterRead.has(identity)) continue;\n if (knownMessage.startedReadCount >= readNumber) {\n // it became known after this read had started (from the transport, or from a read answered in between):\n // this read cannot tell that it is gone\n knownAfterRead.set(identity, knownMessage);\n openPlaces.add(placeOf(knownMessage.message));\n } else {\n goneMessages.push(knownMessage);\n }\n }\n /** By place: a replaced message is no clear, and the gone messages of one place are one clear. */\n const goneMessagesByClearedPlace = new Map<string, KnownAccountRealtimeMessage[]>();\n for (const goneMessage of goneMessages) {\n const place = placeOf(goneMessage.message);\n if (openPlaces.has(place)) continue;\n goneMessagesByClearedPlace.set(place, [...(goneMessagesByClearedPlace.get(place) ?? []), goneMessage]);\n }\n knownMessages = knownAfterRead;\n\n handToSubscribers(arrivedMessages, [...goneMessagesByClearedPlace.values()]);\n options.onListenerCredential?.(read.listenerCredential);\n return arrivedMessages.length;\n };\n\n const subscribe = (subscriber: AccountRealtimePollSubscriber): (() => void) => {\n const subscription: AccountRealtimePollSubscription = { subscriber };\n subscriptions.add(subscription);\n const nowMs = Date.now();\n for (const knownMessage of [...knownMessages.values()]) {\n if (knownMessage.expiresAtMs > nowMs) handMessage(knownMessage, subscription);\n }\n return () => {\n subscriptions.delete(subscription);\n };\n };\n\n const schedule = (): void => {\n if (stopped) return;\n timer = setTimeout(tick, intervalMs);\n };\n\n const readIgnoringFailure = async (): Promise<number> => {\n try {\n return await readNow();\n } catch (error) {\n options.onReadFailed?.(error);\n return 0;\n }\n };\n\n const tick = async (): Promise<void> => {\n timer = null;\n if (stopped) return;\n if (!(options.isTransportBound?.() ?? false)) await readIgnoringFailure();\n schedule();\n };\n\n const readAfterPing = async (): Promise<boolean> => {\n if ((await readIgnoringFailure()) > 0) return true;\n await new Promise<void>(resolve => setTimeout(resolve, rereadDelayMs));\n return (await readIgnoringFailure()) > 0;\n };\n\n // the first read always happens: it carries the credential the host binds its transport with\n void readIgnoringFailure().then(schedule);\n\n return {\n readNow,\n acceptArrivedMessage,\n readAfterPing,\n subscribe,\n stop: () => {\n stopped = true;\n if (timer !== null) clearTimeout(timer);\n timer = null;\n },\n };\n};\n"],"names":["id","liveRegion"],"mappings":";;;;AA8BO,MAAM,4BAA4B;AAGlC,MAAM,wBAAwB;AAG9B,MAAM,uBAAuB;AAAA,EAClC,IAAI;AAAA,EACJ,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,eAAe;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","../src/ui/AgentUIClient.ts","../src/ui/useAgentUIClient.ts","../src/ui/screen-markdown.ts","../src/ui/DomScreenReader.ts","../src/ui/DomScreenHighlighter.ts","../src/ui/DomScreenTargetSource.ts","../src/ui/DomScreenPathGuide.ts","../src/ui/screen-picture.ts","../src/ui/agent-window.ts","../src/ui/account-realtime.ts"],"sourcesContent":["/**\n * The client half of the agent's client tools: a tool on the\n * server sends a request to the client (a browser tab, an app) that shows the conversation; the client executes it through the\n * application's adapters and posts the answer. Everything here is generic: no menu, no route, no word of one\n * application. The application supplies the four adapters (`ScreenAdapters`).\n *\n * Pure (no React, no app imports), so the logic tests cover it.\n */\n\n/** What the server asks a tab to do (`AgentClientToolRequest::TYPE_*`). */\nexport type ClientToolRequestType = 'READ_SCREEN' | 'LIST_TARGETS' | 'OPEN_TARGET' | 'HIGHLIGHT' | 'SET_WINDOW_MODE';\n\n/** A request as the run-state read delivers it. */\nexport interface ClientToolRequestDelivery {\n id: number;\n requestType: ClientToolRequestType | string;\n argumentsJson: string;\n secondsLeft: number;\n}\n\n/** The answer a tab posts: `OK` or a refusal code, the text, small facts. */\nexport interface ClientToolAnswer {\n outcome: string;\n text: string;\n details: Record<string, string | number | boolean | null>;\n /** A picture of the screen (base64 of WebP, JPEG or PNG), only for a `READ_SCREEN` request with `format: picture` */\n pictureBase64?: string;\n}\n\n/** A tab never starts a request with fewer seconds left: it would finish after the tool gave up. */\nexport const MIN_SECONDS_LEFT_TO_START = 3;\n\n/** The most characters of an answer text (the server refuses more). */\nexport const MAX_ANSWER_TEXT_CHARS = 24000;\n\n/** The refusal codes a tab answers with. */\nexport const CLIENT_TOOL_OUTCOMES = {\n ok: 'OK',\n unsavedChanges: 'UNSAVED_CHANGES',\n unsavedStateUnknown: 'UNSAVED_STATE_UNKNOWN',\n dialogOpen: 'DIALOG_OPEN',\n unknownTarget: 'UNKNOWN_TARGET',\n missingParameter: 'MISSING_PARAMETER',\n unknownTab: 'UNKNOWN_TAB',\n unknownFilter: 'UNKNOWN_FILTER',\n notOnScreen: 'NOT_ON_SCREEN',\n expiredBeforeStart: 'EXPIRED_BEFORE_START',\n readFailed: 'READ_FAILED',\n unknownRequest: 'UNKNOWN_REQUEST',\n unknownMode: 'UNKNOWN_MODE',\n pictureUnavailable: 'PICTURE_UNAVAILABLE',\n} as const;\n\n// ── The navigation targets ───────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ScreenTargetFilter {\n /** The query parameter, e.g. `customerId` */\n key: string;\n}\n\n/** A screen the user can open: a menu entry, a record screen or a page below one. */\nexport interface ScreenTarget {\n /** Stable key the agent passes to openScreen: the menu key, the record kind, or a dotted path below one */\n key: string;\n /** What the user calls it (translated) */\n label: string;\n /** The menu groups above it (translated), e.g. `Maintenance` */\n group: string | null;\n /** The route with `:parameter` segments, e.g. `/orders/:orderId` */\n routePattern: string;\n /** The route parameters in order (a nested record screen has two) */\n parameters: string[];\n /** The tabs (route segments after the pattern) */\n tabs: string[];\n /** The URL filters of a list screen */\n filters: ScreenTargetFilter[];\n /** The views of a list screen (`?view=`) */\n views: string[];\n}\n\n// ── The adapters an application supplies ─────────────────────────────────────────────────────────────────────────────\n\n/** Where the browser is. */\nexport interface ScreenLocation {\n /** The route without the basePath, with the query string */\n route: string;\n /** The document title or page heading */\n title: string;\n}\n\n/** Why a navigation would lose the user's work. */\nexport interface ScreenNavigationBlocker {\n outcome: string;\n /** A short sentence for the model */\n reason: string;\n}\n\nexport interface ScreenOpenRequest {\n recordIds: number[];\n tab: string | null;\n filters: Record<string, string>;\n}\n\n/** The screen as Markdown, with the references `highlightOnScreen` takes. */\nexport interface ScreenSnapshot {\n markdown: string;\n route: string;\n title: string;\n /** reference → label, for the answer of a mark */\n references: Record<string, string>;\n}\n\nexport interface ScreenMarkResult {\n /** reference → label of the marked elements */\n marked: Record<string, string>;\n /** references that are not on the screen */\n missing: string[];\n /** references marked but out of view or covered */\n outOfView: string[];\n /** references inside a collapsed section: the section header is marked instead */\n collapsed: string[];\n}\n\n/** Reads the navigation the user really has (rights applied). */\nexport interface ScreenTargetSource {\n listTargets(): ScreenTarget[];\n}\n\n/** Navigates with the application's router and guards. */\nexport interface ScreenNavigator {\n describeBlockers(): ScreenNavigationBlocker | null;\n open(target: ScreenTarget, request: ScreenOpenRequest): Promise<ScreenLocation>;\n currentLocation(): ScreenLocation;\n}\n\n/** Turns the current screen into Markdown. */\nexport interface ScreenReader {\n read(options: { focus?: string; maxChars: number }): ScreenSnapshot;\n}\n\n/** Marks elements by the references of the newest read. */\nexport interface ScreenHighlighter {\n mark(references: string[], note: string | null): ScreenMarkResult;\n clear(): void;\n}\n\n/** The size presets of a screen picture (`pictureSize` of `getCurrentScreen`). */\nexport type ScreenPictureSize = 'small' | 'medium' | 'large';\n\n/** How a screen picture is rendered (`renderMode` of `getCurrentScreen`). */\nexport type ScreenPictureRenderMode = 'colour' | 'greyscale' | 'machine';\n\nexport interface ScreenPictureRequest {\n pictureSize: ScreenPictureSize;\n renderMode: ScreenPictureRenderMode;\n}\n\n/** A captured picture of the screen. */\nexport interface ScreenPicture {\n /** base64 of the encoded bytes, without a `data:` prefix */\n base64: string;\n mimeType: 'image/webp' | 'image/jpeg' | 'image/png';\n width: number;\n height: number;\n byteSize: number;\n}\n\n/** Captures the open screen as a picture (`createDomScreenPictureCapturer()` is the DOM default). */\nexport interface ScreenPictureCapturer {\n capture(request: ScreenPictureRequest): Promise<ScreenPicture | null>;\n}\n\n/** The agent window of the application: steps aside before the agent works on the screen, takes a requested mode. */\nexport interface AgentWindowAdapter {\n /** Makes room for the screen (the default before `OPEN_TARGET`, `HIGHLIGHT` and a picture) */\n stepAside(requestType: ClientToolRequestType): void | Promise<void>;\n /** Back to the mode before `stepAside()` */\n restore(): void | Promise<void>;\n /** A mode the application knows (`SET_WINDOW_MODE`); false = unknown mode */\n setMode(mode: string): boolean | Promise<boolean>;\n /** Whether the window steps aside before a request of the type; default true for the three screen requests */\n shouldStepAsideBefore?(requestType: ClientToolRequestType): boolean;\n /** The mode the window shows now: the UI state reports it, so the agent knows whether the user sees the page */\n getMode?(): string;\n}\n\n/** Shows the user the way to a target before it opens (`createDomScreenPathGuide()` is the DOM default). */\nexport interface ScreenPathGuide {\n /**\n * Shows the path to the target; never awaited by the runner, so it never delays the answer. Returns false when it\n * shows nothing (reduced motion, already on the target, no element of the path on the screen).\n */\n guide(target: ScreenTarget, request: ScreenOpenRequest): boolean;\n /** Stops a guide still running */\n cancel(): void;\n}\n\n/** A request type the application handles itself (a type a host or package registered on the server). */\nexport type ClientToolRequestHandler = (parameters: Record<string, unknown>, delivery: ClientToolRequestDelivery) => ClientToolAnswer | Promise<ClientToolAnswer>;\n\nexport interface ScreenAdapters {\n targets: ScreenTargetSource;\n navigator: ScreenNavigator;\n reader: ScreenReader;\n highlighter: ScreenHighlighter;\n /** Whether the client is visible now */\n isVisible: () => boolean;\n /** Optional: captures the screen as a picture; without it a picture request is answered `PICTURE_UNAVAILABLE` */\n picture?: ScreenPictureCapturer;\n /** Optional: the agent window; without it `SET_WINDOW_MODE` is answered `UNKNOWN_MODE` */\n agentWindow?: AgentWindowAdapter;\n /** Optional: the path guide shown before `OPEN_TARGET` */\n pathGuide?: ScreenPathGuide;\n /** Optional: handlers of further request types, by type; a type of the package is never replaced */\n requestHandlers?: Record<string, ClientToolRequestHandler>;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** The arguments of a delivery as an object; anything else is empty. */\nexport const parseClientToolArguments = (argumentsJson: string): Record<string, unknown> => {\n try {\n const parsed: unknown = JSON.parse(argumentsJson);\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n};\n\n/** A text cut to the answer's cap. */\nexport const capAnswerText = (text: string): string =>\n text.length <= MAX_ANSWER_TEXT_CHARS ? text : `${text.slice(0, MAX_ANSWER_TEXT_CHARS - 1)}…`;\n\n/** Lower-case words of a search text. */\nconst searchWordsOf = (searchText: string): string[] =>\n searchText\n .toLowerCase()\n .split(/\\s+/)\n .filter(word => word !== '');\n\n/** One line of a target in the `listScreens` answer. */\nexport const formatScreenTargetLine = (target: ScreenTarget): string => {\n const parts = [target.key, target.group ? `${target.group} › ${target.label}` : target.label];\n if (target.parameters.length > 0) parts[1] = `${parts[1]} (${target.parameters.join(', ')})`;\n if (target.tabs.length > 0) parts.push(`tabs ${target.tabs.join(', ')}`);\n if (target.filters.length > 0) parts.push(`filters ${target.filters.map(filter => filter.key).join(', ')}`);\n if (target.views.length > 0) parts.push(`views ${target.views.join(', ')}`);\n return `- ${parts.join(' · ')}`;\n};\n\n/** The most characters of a `listScreens` answer. */\nexport const MAX_TARGET_LIST_CHARS = 4500;\n\n/** The `listScreens` answer: the targets whose line contains every word of the search text, capped. */\nexport const formatScreenTargetList = (targets: ScreenTarget[], searchText: string): string => {\n const searchWords = searchWordsOf(searchText);\n const lines = targets\n .map(formatScreenTargetLine)\n .filter(line => searchWords.every(word => line.toLowerCase().includes(word)));\n if (lines.length === 0) return 'No screen matches. Call listScreens without searchText for all of them.';\n const header = `Screens this user can open (${lines.length}). Pass the key to openScreen.`;\n const kept: string[] = [];\n let chars = header.length;\n for (const line of lines) {\n if (chars + line.length + 1 > MAX_TARGET_LIST_CHARS) {\n kept.push(`… ${lines.length - kept.length} more; narrow with searchText.`);\n break;\n }\n kept.push(line);\n chars += line.length + 1;\n }\n return [header, ...kept].join('\\n');\n};\n\n/** A reference, a key, a tab or a filter key: what the server lets through. */\nconst TOKEN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;\n\nexport const isClientToolToken = (value: unknown): value is string => typeof value === 'string' && TOKEN_PATTERN.test(value);\n\n/** The route of a target for the given record ids and tab; `null` when a record id is missing. */\nexport const buildTargetRoute = (target: ScreenTarget, recordIds: number[], tab: string | null): string | null => {\n let parameterIndex = 0;\n const segments: string[] = [];\n for (const segment of target.routePattern.split('/').filter(part => part !== '')) {\n if (!segment.startsWith(':')) {\n segments.push(segment);\n continue;\n }\n const recordId = recordIds[parameterIndex];\n parameterIndex += 1;\n if (recordId === undefined || !Number.isInteger(recordId) || recordId <= 0) return null;\n segments.push(String(recordId));\n }\n if (tab) segments.push(tab);\n return `/${segments.join('/')}`;\n};\n","import {\n buildTargetRoute,\n CLIENT_TOOL_OUTCOMES,\n type ClientToolAnswer,\n type ClientToolRequestDelivery,\n capAnswerText,\n formatScreenTargetList,\n isClientToolToken,\n MAX_ANSWER_TEXT_CHARS,\n MIN_SECONDS_LEFT_TO_START,\n parseClientToolArguments,\n type ClientToolRequestType,\n type ScreenAdapters,\n type ScreenPictureRenderMode,\n type ScreenPictureSize,\n type ScreenTarget,\n} from \"./client-tools\";\n\n/** The request types of the package; a handler of the application never replaces them. */\nconst PACKAGE_REQUEST_TYPES: string[] = ['READ_SCREEN', 'LIST_TARGETS', 'OPEN_TARGET', 'HIGHLIGHT', 'SET_WINDOW_MODE'];\n\n/** The request types the agent window steps aside for by default. */\nconst STEP_ASIDE_REQUEST_TYPES: ClientToolRequestType[] = ['OPEN_TARGET', 'HIGHLIGHT', 'READ_SCREEN'];\n\nconst PICTURE_SIZES: ScreenPictureSize[] = ['small', 'medium', 'large'];\n\nconst RENDER_MODES: ScreenPictureRenderMode[] = ['colour', 'greyscale', 'machine'];\n\n/**\n * The most characters of screen content in one answer: half the answer's cap ({@link MAX_ANSWER_TEXT_CHARS}), the\n * same number as the server's cut (`AgentUIToolResponseDto::MAX_CONTENT_CHARS`, a contract test compares them). With\n * 6,000 a list page was cut before its table; the reader's own caps (rows, cells, section text) keep a read short.\n */\nexport const MAX_SCREEN_CHARS = MAX_ANSWER_TEXT_CHARS / 2;\n\n/** How many request ids a runner remembers, so a redelivery never runs a request twice. */\nconst REMEMBERED_REQUEST_IDS = 50;\n\n/** Posts an answer; the transport is the application's. */\nexport type ClientToolAnswerSender = (requestId: number, answer: ClientToolAnswer) => Promise<void>;\n\n/**\n * Runs the requests the run-state read delivers, one at a time, through the application's adapters, and posts each\n * answer once. Generic: it knows the four request types and the refusal codes, nothing of a menu or a route.\n */\nexport class ClientToolRequestRunner {\n protected readonly handledRequestIds: number[] = [];\n\n protected running: Promise<void> = Promise.resolve();\n\n protected readonly adapters: ScreenAdapters;\n\n constructor(adapters: ScreenAdapters) {\n this.adapters = adapters;\n }\n\n /**\n * Takes a delivery and posts its answer through `sendAnswer`; a request already taken is ignored (the server\n * redelivers an unanswered one after 5 s).\n */\n accept(delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void {\n if (this.handledRequestIds.includes(delivery.id)) return;\n this.handledRequestIds.push(delivery.id);\n if (this.handledRequestIds.length > REMEMBERED_REQUEST_IDS) this.handledRequestIds.shift();\n const receivedAt = Date.now();\n this.running = this.running.then(() => this.runAndAnswer(delivery, receivedAt, sendAnswer));\n }\n\n /** Resolves when every accepted request was answered (tests). */\n whenIdle(): Promise<void> {\n return this.running;\n }\n\n protected async runAndAnswer(delivery: ClientToolRequestDelivery, receivedAt: number, sendAnswer: ClientToolAnswerSender): Promise<void> {\n const answer = await this.run(delivery, receivedAt);\n try {\n await sendAnswer(delivery.id, { ...answer, text: capAnswerText(answer.text) });\n } catch {\n // the tool answers \"no answer\" after its wait; nothing else to do in the tab\n }\n }\n\n /** The answer of one request. Exposed for the tests. */\n async run(delivery: ClientToolRequestDelivery, receivedAt: number = Date.now()): Promise<ClientToolAnswer> {\n const secondsLeft = delivery.secondsLeft - (Date.now() - receivedAt) / 1000;\n if (secondsLeft < MIN_SECONDS_LEFT_TO_START) return refusal(CLIENT_TOOL_OUTCOMES.expiredBeforeStart);\n const parameters = parseClientToolArguments(delivery.argumentsJson);\n try {\n switch (delivery.requestType) {\n case 'READ_SCREEN':\n if (parameters.format === 'picture') {\n await this.stepAgentWindowAside('READ_SCREEN');\n try {\n return await this.readScreenPicture(parameters);\n } finally {\n await this.adapters.agentWindow?.restore();\n }\n }\n return this.readScreen(parameters);\n case 'LIST_TARGETS':\n return this.listTargets(parameters);\n case 'OPEN_TARGET':\n return await this.openTarget(parameters);\n case 'HIGHLIGHT':\n await this.stepAgentWindowAside('HIGHLIGHT');\n return this.highlight(parameters);\n case 'SET_WINDOW_MODE':\n return await this.setWindowMode(parameters);\n default:\n return await this.runRequestOfApplication(delivery, parameters);\n }\n } catch {\n return refusal(CLIENT_TOOL_OUTCOMES.readFailed);\n }\n }\n\n /** A request type the application registered: its handler, else `UNKNOWN_REQUEST`. */\n protected async runRequestOfApplication(delivery: ClientToolRequestDelivery, parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const handler = PACKAGE_REQUEST_TYPES.includes(delivery.requestType) ? undefined : this.adapters.requestHandlers?.[delivery.requestType];\n if (!handler) return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);\n return handler(parameters, delivery);\n }\n\n /** Lets the agent window make room before the agent works on the screen (the default for the screen requests). */\n protected async stepAgentWindowAside(requestType: ClientToolRequestType): Promise<void> {\n const agentWindow = this.adapters.agentWindow;\n if (!agentWindow) return;\n const shouldStepAside = agentWindow.shouldStepAsideBefore\n ? agentWindow.shouldStepAsideBefore(requestType)\n : STEP_ASIDE_REQUEST_TYPES.includes(requestType);\n if (shouldStepAside) await agentWindow.stepAside(requestType);\n }\n\n protected async setWindowMode(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const agentWindow = this.adapters.agentWindow;\n if (!agentWindow || !isClientToolToken(parameters.mode)) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);\n if (parameters.mode === 'restore') {\n await agentWindow.restore();\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details: { mode: 'restore' } };\n }\n const accepted = await agentWindow.setMode(parameters.mode);\n if (!accepted) return refusal(CLIENT_TOOL_OUTCOMES.unknownMode);\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details: { mode: parameters.mode } };\n }\n\n protected async readScreenPicture(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const capturer = this.adapters.picture;\n if (!capturer) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);\n const pictureSize = PICTURE_SIZES.find(size => size === parameters.pictureSize) ?? 'medium';\n const renderMode = RENDER_MODES.find(mode => mode === parameters.renderMode) ?? 'colour';\n const picture = await capturer.capture({ pictureSize, renderMode });\n if (!picture) return refusal(CLIENT_TOOL_OUTCOMES.pictureUnavailable);\n const location = this.adapters.navigator.currentLocation();\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: '',\n details: {\n route: location.route,\n visible: this.adapters.isVisible(),\n width: picture.width,\n height: picture.height,\n bytes: picture.byteSize,\n renderMode,\n },\n pictureBase64: picture.base64,\n };\n }\n\n protected readScreen(parameters: Record<string, unknown>): ClientToolAnswer {\n const focus = isClientToolToken(parameters.focus) ? parameters.focus : undefined;\n const snapshot = this.adapters.reader.read({ focus, maxChars: MAX_SCREEN_CHARS });\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: snapshot.markdown,\n details: { route: snapshot.route, visible: this.adapters.isVisible(), chars: snapshot.markdown.length },\n };\n }\n\n protected listTargets(parameters: Record<string, unknown>): ClientToolAnswer {\n const searchText = typeof parameters.searchText === 'string' ? parameters.searchText : '';\n return {\n outcome: CLIENT_TOOL_OUTCOMES.ok,\n text: formatScreenTargetList(this.adapters.targets.listTargets(), searchText),\n details: {},\n };\n }\n\n protected async openTarget(parameters: Record<string, unknown>): Promise<ClientToolAnswer> {\n const target = this.findTarget(parameters.target);\n if (!target) return refusal(CLIENT_TOOL_OUTCOMES.unknownTarget);\n const tab = isClientToolToken(parameters.tab) ? parameters.tab : null;\n if (tab !== null && !target.tabs.includes(tab)) return refusal(CLIENT_TOOL_OUTCOMES.unknownTab);\n const filters: Record<string, string> = {};\n for (const filter of Array.isArray(parameters.filters) ? parameters.filters : []) {\n const [key, ...valueParts] = String(filter).split('=');\n if (!target.filters.some(targetFilter => targetFilter.key === key) || valueParts.length === 0) {\n return refusal(CLIENT_TOOL_OUTCOMES.unknownFilter);\n }\n filters[key] = valueParts.join('=');\n }\n const recordIds = typeof parameters.recordId === 'number' ? [parameters.recordId] : [];\n if (buildTargetRoute(target, recordIds, tab) === null) return refusal(CLIENT_TOOL_OUTCOMES.missingParameter);\n const blocker = this.adapters.navigator.describeBlockers();\n if (blocker) return { outcome: blocker.outcome, text: blocker.reason, details: {} };\n await this.stepAgentWindowAside('OPEN_TARGET');\n const openRequest = { recordIds, tab, filters };\n try {\n this.adapters.pathGuide?.guide(target, openRequest);\n } catch {\n // a guide is decoration: the navigation goes on without it\n }\n const location = await this.adapters.navigator.open(target, openRequest);\n const details = { route: location.route, title: location.title };\n if (parameters.includeScreen !== true) return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: '', details };\n const snapshot = this.adapters.reader.read({ maxChars: MAX_SCREEN_CHARS });\n return { outcome: CLIENT_TOOL_OUTCOMES.ok, text: snapshot.markdown, details };\n }\n\n protected highlight(parameters: Record<string, unknown>): ClientToolAnswer {\n const references = (Array.isArray(parameters.references) ? parameters.references : []).filter(isClientToolToken);\n const note = typeof parameters.note === 'string' && parameters.note.trim() !== '' ? parameters.note : null;\n const result = this.adapters.highlighter.mark(references, note);\n const markedReferences = Object.keys(result.marked);\n const lines = markedReferences.map(reference => {\n const suffix = result.outOfView.includes(reference)\n ? ' (scrolled into view)'\n : result.collapsed.includes(reference)\n ? ' (inside a closed section: its header is marked)'\n : '';\n return `Marked ${reference} \"${result.marked[reference]}\"${suffix}.`;\n });\n if (result.missing.length > 0) lines.push(`Not on the screen: ${result.missing.join(', ')}.`);\n const outcome = markedReferences.length > 0 ? CLIENT_TOOL_OUTCOMES.ok : CLIENT_TOOL_OUTCOMES.notOnScreen;\n return { outcome, text: lines.join('\\n'), details: { marked: markedReferences.length } };\n }\n\n protected findTarget(key: unknown): ScreenTarget | null {\n if (!isClientToolToken(key)) return null;\n return this.adapters.targets.listTargets().find(target => target.key === key) ?? null;\n }\n}\n\nconst refusal = (outcome: string): ClientToolAnswer => ({ outcome, text: '', details: {} });\n","import type { AgentUIState, AgentUIStateSource } from \"./agent-ui-state\";\nimport { createAgentUIClientId } from \"./agent-ui-state\";\nimport { type ClientToolAnswerSender, ClientToolRequestRunner } from \"./ClientToolRequestRunner\";\nimport type { ClientToolRequestDelivery, ScreenAdapters } from \"./client-tools\";\n\n/**\n * What a conversation client binding needs from the UI side of `Agent.UI` (`AgentsHttpConversationClientOptions.uiClient`):\n * the client id and UI state it sends with every message and run-state read, and where a delivered client tool\n * request goes. The binding posts the answer.\n */\nexport interface AgentUIClientBinding {\n readonly clientId: string;\n readUIState(): AgentUIState | null;\n acceptClientToolRequest(conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void;\n}\n\n/**\n * The UI side of `Agent.UI` in one object: a client id per mount, the UI state source, and the runner that executes\n * the delivered requests through the application's four adapters. Framework-free; the React hook\n * (`useAgentUIClient`) creates one per mount.\n */\nexport class AgentUIClient implements AgentUIClientBinding {\n readonly clientId: string;\n\n protected readonly runner: ClientToolRequestRunner;\n\n protected readonly uiStateSource: AgentUIStateSource | null;\n\n protected readonly adapters: ScreenAdapters;\n\n protected acceptedClientToolRequestCount = 0;\n\n constructor(adapters: ScreenAdapters, uiStateSource: AgentUIStateSource | null = null, clientId: string = createAgentUIClientId()) {\n this.clientId = clientId;\n this.adapters = adapters;\n this.runner = new ClientToolRequestRunner(adapters);\n this.uiStateSource = uiStateSource;\n }\n\n /**\n * The source's UI state with the agent window's mode (the window adapter) and the browser window's size, unless the\n * source reports them itself: the agent learns whether its window covers the page and whether a panel fits beside it.\n */\n readUIState(): AgentUIState | null {\n try {\n const uiState = this.uiStateSource?.readUIState() ?? null;\n if (uiState === null) return null;\n const completedUIState: AgentUIState = { ...uiState };\n const agentWindowMode = uiState.agentWindow ?? this.adapters.agentWindow?.getMode?.() ?? null;\n if (agentWindowMode !== null) completedUIState.agentWindow = agentWindowMode;\n if (typeof window !== 'undefined') {\n completedUIState.viewportWidth = uiState.viewportWidth ?? Math.round(window.innerWidth);\n completedUIState.viewportHeight = uiState.viewportHeight ?? Math.round(window.innerHeight);\n }\n return completedUIState;\n } catch {\n return null;\n }\n }\n\n acceptClientToolRequest(_conversationId: number, delivery: ClientToolRequestDelivery, sendAnswer: ClientToolAnswerSender): void {\n this.acceptedClientToolRequestCount += 1;\n this.runner.accept(delivery, sendAnswer);\n }\n\n /** How many client tool requests were delivered to this client so far (a repeat delivery counts again). */\n countAcceptedClientToolRequests(): number {\n return this.acceptedClientToolRequestCount;\n }\n\n /** Resolves when every accepted request was answered (tests). */\n whenIdle(): Promise<void> {\n return this.runner.whenIdle();\n }\n}\n","import { useRef } from \"react\";\nimport type { AgentUIStateSource } from \"./agent-ui-state\";\nimport { AgentUIClient } from \"./AgentUIClient\";\nimport type { ScreenAdapters } from \"./client-tools\";\n\n/**\n * One `AgentUIClient` per mount of the agent window: a stable client id and the runner of the delivered requests. The\n * adapters are read through the latest render (a ref), so an application may pass a new object on every render. Hand\n * the result to the conversation client binding (`createAgentsHttpConversationClient({ uiClient })`).\n */\nexport const useAgentUIClient = (adapters: ScreenAdapters, uiStateSource: AgentUIStateSource | null = null): AgentUIClient => {\n const adaptersRef = useRef(adapters);\n adaptersRef.current = adapters;\n const uiStateSourceRef = useRef(uiStateSource);\n uiStateSourceRef.current = uiStateSource;\n const clientRef = useRef<AgentUIClient | null>(null);\n if (clientRef.current === null) {\n const latestAdapters: ScreenAdapters = {\n targets: { listTargets: () => adaptersRef.current.targets.listTargets() },\n navigator: {\n describeBlockers: () => adaptersRef.current.navigator.describeBlockers(),\n open: (target, request) => adaptersRef.current.navigator.open(target, request),\n currentLocation: () => adaptersRef.current.navigator.currentLocation(),\n },\n reader: { read: options => adaptersRef.current.reader.read(options) },\n highlighter: {\n mark: (references, note) => adaptersRef.current.highlighter.mark(references, note),\n clear: () => adaptersRef.current.highlighter.clear(),\n },\n isVisible: () => adaptersRef.current.isVisible(),\n };\n // the optional adapters: present on the object when the latest render has them\n Object.defineProperties(latestAdapters, {\n picture: { enumerable: true, get: () => adaptersRef.current.picture },\n agentWindow: { enumerable: true, get: () => adaptersRef.current.agentWindow },\n pathGuide: { enumerable: true, get: () => adaptersRef.current.pathGuide },\n requestHandlers: { enumerable: true, get: () => adaptersRef.current.requestHandlers },\n });\n clientRef.current = new AgentUIClient(latestAdapters, { readUIState: () => uiStateSourceRef.current?.readUIState() ?? null });\n }\n return clientRef.current;\n};\n","/**\n * The pure half of the screen reader: references and the Markdown lines of fields, tables, buttons and messages.\n * The DOM walk (`domScreenReader.ts`) collects plain values and these functions write them, so the logic tests cover\n * the format without a DOM.\n *\n * References (stable within one read, `highlightOnScreen` takes them):\n * - `f.<name>` a form field (its `name`, else its label as a slug)\n * - `row.<key>` a table row (the row key: `data-row-key`, else the visible id cell)\n * - `b.<slug>` a button or link that acts\n * - `s.<slug>` a section (its heading)\n * - `t.<slug>` a tab\n * - `a.<anchor>` an anchor the application set (`data-agent-anchor`)\n * - `nav.<key>` an entry or group of the application's main menu (`data-nav-key`, `data-nav-group`)\n */\n\n/**\n * The most rows of one table (and cards of one grid) in a read. A list of 200 loaded rows filled the whole read with\n * rows before; the rest of the page never reached the model. `focus` on a row reads it whole.\n */\nexport const MAX_TABLE_ROWS = 15;\n\n/** The most characters of one table cell in a read (a cell says how long it was; `focus` on the row reads it whole). */\nexport const MAX_CELL_CHARS = 60;\n\n/** The most characters of the plain text of one section (`Text: …`). */\nexport const MAX_SECTION_TEXT_CHARS = 1200;\n\n/** The most characters of one value in a read (a long text says how long it is; `focus` reads it whole). */\nexport const MAX_VALUE_CHARS = 200;\n\n/** The most buttons in a read. */\nexport const MAX_BUTTONS = 30;\n\n/** A value standing in for a secret. */\nexport const HIDDEN_VALUE = '(hidden)';\n\n/** A slug for a reference: lower case letters, digits and `-`, at most 40 characters. */\nexport const slugOf = (text: string): string =>\n text\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '') || 'x';\n\n/** A reference name from a field name (`order.endDate` stays, other characters become `-`). */\nexport const fieldReferenceNameOf = (name: string): string =>\n name.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 60) || 'x';\n\n/** One line of text: whitespace collapsed. */\nexport const oneLine = (text: string): string => text.replace(/\\s+/g, ' ').trim();\n\n/** A value cut to {@link MAX_VALUE_CHARS}, saying how long it was. */\nexport const capValue = (value: string, maxChars: number = MAX_VALUE_CHARS): string => {\n const flat = oneLine(value);\n return flat.length <= maxChars ? flat : `${flat.slice(0, maxChars)}… (${flat.length} characters)`;\n};\n\n/** Makes a reference unique within one read by a number suffix. */\nexport class ReferenceNames {\n protected readonly used = new Set<string>();\n\n take(reference: string): string {\n let candidate = reference;\n for (let suffix = 2; this.used.has(candidate); suffix += 1) candidate = `${reference}-${suffix}`;\n this.used.add(candidate);\n return candidate;\n }\n}\n\nexport interface FieldFacts {\n reference: string;\n label: string;\n value: string;\n kind: string;\n required?: boolean;\n disabled?: boolean;\n invalidMessage?: string | null;\n isSecret?: boolean;\n}\n\n/** `- End date (f.endDate, date): 2026-12-31 · required · error \"…\"` */\nexport const formatFieldLine = (field: FieldFacts): string => {\n const value = field.isSecret ? HIDDEN_VALUE : field.value.trim() === '' ? '(empty)' : capValue(field.value);\n const flags: string[] = [];\n if (field.required) flags.push('required');\n if (field.disabled) flags.push('read-only');\n if (field.invalidMessage) flags.push(`error \"${capValue(field.invalidMessage, 120)}\"`);\n return `- ${capValue(field.label, 80) || field.reference} (${field.reference}, ${field.kind}): ${value}${flags.length > 0 ? ` · ${flags.join(' · ')}` : ''}`;\n};\n\nexport interface TableFacts {\n caption: string | null;\n columns: string[];\n rows: { reference: string; cells: string[]; selected?: boolean }[];\n /** All rows of the table in the DOM (more than shown) */\n totalRows: number;\n}\n\n/**\n * A table as `| … |` lines with the row reference first, at most {@link MAX_TABLE_ROWS} rows, cells cut to\n * {@link MAX_CELL_CHARS}. A column without text in every shown row (a selection box, an actions menu) is left out: the\n * selection shows as `(selected)` on the row.\n */\nexport const formatTable = (table: TableFacts, maxRows: number = MAX_TABLE_ROWS): string[] => {\n const lines: string[] = [];\n const shownRows = table.rows.slice(0, maxRows);\n const columnCount = Math.max(table.columns.length, ...shownRows.map(row => row.cells.length));\n const keptColumns: number[] = [];\n for (let column = 0; column < columnCount; column += 1) {\n if (shownRows.length === 0 || shownRows.some(row => (row.cells[column] ?? '').trim() !== '')) keptColumns.push(column);\n }\n lines.push(`Table${table.caption ? ` \"${capValue(table.caption, 80)}\"` : ''}: ${table.totalRows} rows on screen`);\n lines.push(`| ref | ${keptColumns.map(column => capValue(table.columns[column] ?? '', 40) || '-').join(' | ')} |`);\n for (const row of shownRows) {\n const cells = keptColumns.map(column => capValue(row.cells[column] ?? '', MAX_CELL_CHARS).replace(/\\|/g, '/'));\n lines.push(`| ${row.reference}${row.selected ? ' (selected)' : ''} | ${cells.join(' | ')} |`);\n }\n if (table.totalRows > shownRows.length) lines.push(`… ${table.totalRows - shownRows.length} more rows on screen`);\n return lines;\n};\n\nexport interface ButtonFacts {\n reference: string;\n label: string;\n disabled?: boolean;\n}\n\n/** `Buttons: b.save \"Save\" · b.delete \"Delete\" (disabled)` */\nexport const formatButtons = (buttons: ButtonFacts[]): string | null => {\n if (buttons.length === 0) return null;\n const shown = buttons.slice(0, MAX_BUTTONS).map(button => `${button.reference} \"${capValue(button.label, 40)}\"${button.disabled ? ' (disabled)' : ''}`);\n const more = buttons.length > MAX_BUTTONS ? ` · … ${buttons.length - MAX_BUTTONS} more` : '';\n return `Buttons: ${shown.join(' · ')}${more}`;\n};\n\n/** Joins the parts of a read and cuts the whole at `maxChars`, saying so. */\nexport const joinScreenParts = (parts: string[], maxChars: number): string => {\n const text = parts.filter(part => part !== '').join('\\n');\n if (text.length <= maxChars) return text;\n const cut = text.slice(0, maxChars);\n const lastLineBreak = cut.lastIndexOf('\\n');\n return `${lastLineBreak > maxChars * 0.8 ? cut.slice(0, lastLineBreak) : cut}\\n… (screen cut at ${maxChars} of ${text.length} characters; read one part with focus)`;\n};\n","import type { ScreenReader, ScreenSnapshot } from \"./client-tools\";\nimport {\n type ButtonFacts,\n capValue,\n type FieldFacts,\n fieldReferenceNameOf,\n formatButtons,\n formatFieldLine,\n formatTable,\n joinScreenParts,\n MAX_SECTION_TEXT_CHARS,\n MAX_TABLE_ROWS,\n oneLine,\n ReferenceNames,\n slugOf,\n type TableFacts,\n} from \"./screen-markdown\";\n\n/** The attributes an application (and `@mgamadeus/ddd-admin-ui`) sets for the agent. */\nexport const AGENT_ATTRIBUTES = {\n /** A stable handle: `a.<value>` */\n anchor: 'data-agent-anchor',\n /** The value is never read (a key, a token) */\n secret: 'data-agent-secret',\n /** The element and everything in it is never read (the agent window itself) */\n skip: 'data-agent-skip',\n /** The key of a table row (@mgamadeus/ddd-admin-ui) */\n rowKey: 'data-row-key',\n /** The key of a main menu entry (@mgamadeus/ddd-admin-ui): `nav.<value>` */\n navKey: 'data-nav-key',\n /** The key of a main menu group (@mgamadeus/ddd-admin-ui): `nav.<value>`; its entries sit inside it */\n navGroup: 'data-nav-group',\n} as const;\n\n/** Elements never read. */\nconst SKIPPED_SELECTOR = `[${AGENT_ATTRIBUTES.skip}], script, style, noscript, template, svg, [aria-hidden=\"true\"], [hidden]`;\n\n/** Fields whose value is never read. */\nconst SECRET_FIELD_SELECTOR = `[${AGENT_ATTRIBUTES.secret}] , input[type=\"password\"], input[autocomplete=\"one-time-code\"]`;\n\nconst FIELD_SELECTOR = 'input:not([type=\"hidden\"]):not([type=\"submit\"]):not([type=\"button\"]), textarea, select, [role=\"combobox\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"radiogroup\"]';\n\nconst BUTTON_SELECTOR = 'button, [role=\"button\"], a[href]';\n\nconst TABLE_SELECTOR = 'table, [role=\"grid\"], [role=\"table\"]';\n\n/**\n * The selection checkbox of a row: a field of its own it is not. On a list of 200 rows the checkboxes gave 201 field\n * lines (\"Select ticket …\") before any table, and the read was cut before the table; the row says `(selected)` instead.\n */\nconst ROW_CHECKBOX_SELECTOR = [TABLE_SELECTOR, `[${AGENT_ATTRIBUTES.rowKey}]`]\n .flatMap(container => container.split(', ').flatMap(part => [`${part} input[type=\"checkbox\"]`, `${part} [role=\"checkbox\"]`]))\n .join(', ');\n\n/**\n * Text the read writes already (fields and their labels, tables, cards, buttons and links, headings, tabs, dialogs,\n * messages) or never reads (the agent window, secrets, the menu, hidden parts): the `Text:` line leaves it out.\n */\nconst TEXT_SKIPPED_SELECTOR = [\n SKIPPED_SELECTOR,\n `[${AGENT_ATTRIBUTES.secret}]`,\n 'nav',\n 'input, textarea, select, label, [role=\"combobox\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"radiogroup\"]',\n '[contenteditable=\"true\"]',\n `${TABLE_SELECTOR}, [${AGENT_ATTRIBUTES.rowKey}]`,\n 'button, [role=\"button\"], a[href], [role=\"tablist\"], [role=\"tab\"], [role=\"menu\"], [role=\"listbox\"]',\n 'h1, h2, h3, h4, [role=\"heading\"]',\n '[role=\"dialog\"], [role=\"alertdialog\"], [role=\"alert\"], [role=\"status\"]',\n].join(', ');\n\n/** The heading of the main menu part of a read. */\nexport const MAIN_MENU_HEADING = '## Main menu (highlightOnScreen marks an entry by its nav. reference)';\n\n/** The most tabs of the page a read names. */\nconst MAX_PAGE_TABS = 16;\n\n/** Column headers that name the id column (for a host table whose rows carry no `data-row-key`). */\nconst ID_COLUMN_LABELS = new Set(['id', '#', 'nr', 'no']);\n\n/** The references of the newest read: reference → element. The highlighter marks by them. */\nexport class ScreenReferenceRegistry {\n protected elements = new Map<string, Element>();\n\n replace(elements: Map<string, Element>): void {\n this.elements = elements;\n }\n\n find(reference: string): Element | null {\n const element = this.elements.get(reference);\n return element?.isConnected ? element : null;\n }\n\n /** An anchor is found on the page even without a read. */\n findAnchor(reference: string): Element | null {\n if (!reference.startsWith('a.')) return null;\n const anchorName = reference.slice(2);\n for (const element of Array.from(document.querySelectorAll(`[${AGENT_ATTRIBUTES.anchor}]`))) {\n if (element.getAttribute(AGENT_ATTRIBUTES.anchor) === anchorName && !element.closest(`[${AGENT_ATTRIBUTES.skip}]`)) return element;\n }\n return null;\n }\n\n labelOf(reference: string): string {\n const element = this.find(reference) ?? this.findAnchor(reference);\n return element ? labelOfElement(element) : reference;\n }\n}\n\nconst isRendered = (element: Element): boolean => {\n if (element.closest(SKIPPED_SELECTOR)) return false;\n const htmlElement = element as HTMLElement;\n if (typeof htmlElement.getClientRects === 'function' && htmlElement.getClientRects().length === 0) return false;\n return true;\n};\n\nconst isChecked = (checkbox: Element): boolean =>\n checkbox instanceof HTMLInputElement ? checkbox.checked : checkbox.getAttribute('aria-checked') === 'true';\n\nconst textOf = (element: Element | null | undefined): string => {\n if (!element) return '';\n const htmlElement = element as HTMLElement;\n // biome-ignore lint/performance/useDomNodeTextContent: the rendered text (no hidden parts) is what the user sees\n return oneLine(htmlElement.innerText ?? element.textContent ?? '');\n};\n\n/** The accessible label of an element: aria-label, labelledby, a `<label for>`, the wrapping label, its text. */\nexport const labelOfElement = (element: Element): string => {\n const ariaLabel = element.getAttribute('aria-label');\n if (ariaLabel) return oneLine(ariaLabel);\n const labelledBy = element.getAttribute('aria-labelledby');\n if (labelledBy) {\n const text = labelledBy\n .split(/\\s+/)\n .map(id => textOf(document.getElementById(id)))\n .join(' ');\n if (text.trim() !== '') return oneLine(text);\n }\n const id = element.getAttribute('id');\n if (id) {\n const label = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n if (label) return textOf(label);\n }\n const wrappingLabel = element.closest('label');\n if (wrappingLabel) return textOf(wrappingLabel);\n const placeholder = element.getAttribute('placeholder');\n if (placeholder) return oneLine(placeholder);\n return textOf(element).slice(0, 80);\n};\n\n/**\n * The key of a table row: `data-row-key` (the package's list rows and cards, 0.3.10); a table of the host without it\n * falls back to the visible id cell, then to the row's position.\n */\nexport const rowKeyOf = (row: Element, idColumnIndex: number | null, rowIndex: number): string => {\n const rowKey = row.getAttribute(AGENT_ATTRIBUTES.rowKey);\n if (rowKey) return slugOf(rowKey);\n if (idColumnIndex !== null) {\n const idText = textOf(row.children.item(idColumnIndex)).replace(/^#/, '');\n if (/^[A-Za-z0-9-]{1,40}$/.test(idText)) return idText;\n }\n return `n${rowIndex + 1}`;\n};\n\nconst valueOfField = (field: Element): { value: string; kind: string } => {\n if (field instanceof HTMLInputElement) {\n if (field.type === 'checkbox' || field.type === 'radio') return { value: field.checked ? 'on' : 'off', kind: field.type };\n return { value: field.value, kind: field.type || 'text' };\n }\n if (field instanceof HTMLTextAreaElement) return { value: field.value, kind: 'text area' };\n if (field instanceof HTMLSelectElement) return { value: textOf(field.selectedOptions.item(0)), kind: 'select' };\n const role = field.getAttribute('role') ?? '';\n if (role === 'switch' || role === 'checkbox') return { value: field.getAttribute('aria-checked') === 'true' ? 'on' : 'off', kind: role };\n if (role === 'radiogroup') {\n const checked = field.querySelector('[aria-checked=\"true\"], [data-state=\"checked\"]');\n return { value: checked ? labelOfElement(checked) : '', kind: 'choice' };\n }\n return { value: textOf(field), kind: role || 'field' };\n};\n\nconst invalidMessageOf = (field: Element): string | null => {\n if (field.getAttribute('aria-invalid') !== 'true') return null;\n const describedBy = field.getAttribute('aria-describedby') ?? field.getAttribute('aria-errormessage');\n const message = (describedBy ?? '')\n .split(/\\s+/)\n .map(id => textOf(document.getElementById(id)))\n .join(' ')\n .trim();\n return message !== '' ? message : 'invalid';\n};\n\nexport interface DomScreenReaderOptions {\n /** The content root (the page, without the shell) */\n findRoot: () => Element | null;\n /** The current route and title */\n currentLocation: () => { route: string; title: string };\n /** Whether the open screen has unsaved changes: `no`, or `yes (<form> (<fields>))` */\n describeUnsavedChanges: () => string;\n registry: ScreenReferenceRegistry;\n /**\n * Optional: the application's main menu (outside the content root). Its entries (`data-nav-key`) and groups\n * (`data-nav-group`) on the screen are read as `nav.<key>` references, so the agent can name and mark them.\n */\n findNavigation?: () => Element | null;\n /**\n * Optional: where the agent window is, e.g. `full screen: it covers the whole page`. The read writes it with the\n * browser window's size (`Agent window: … · browser 1440×900 px`), so the agent knows what the user sees beside it.\n */\n describeAgentWindow?: () => string | null;\n}\n\n/**\n * Reads the open screen from the DOM: title and route, the agent window and the browser size, tabs, open dialogs,\n * messages, then per section its plain text (`Text: …`), tables, cards, fields and buttons, and the main menu. Never\n * the agent window (`data-agent-skip`), never a secret's value.\n */\nexport class DomScreenReader implements ScreenReader {\n /** The containers whose text this read wrote already (a section before the page around it). */\n protected textReadContainers = new Set<Element>();\n\n constructor(protected readonly options: DomScreenReaderOptions) {}\n\n read({ focus, maxChars }: { focus?: string; maxChars: number }): ScreenSnapshot {\n const location = this.options.currentLocation();\n if (focus) {\n const focused = this.options.registry.find(focus) ?? this.options.registry.findAnchor(focus);\n if (!focused) {\n return { markdown: `${focus} is not on the screen any more. Read the screen again without focus.`, route: location.route, title: location.title, references: {} };\n }\n const value = focused.matches(SECRET_FIELD_SELECTOR) || focused.closest(`[${AGENT_ATTRIBUTES.secret}]`) ? '(hidden)' : this.readWhole(focused);\n return { markdown: joinScreenParts([`${focus} \"${labelOfElement(focused)}\" in full:`, value], maxChars), route: location.route, title: location.title, references: {} };\n }\n const elements = new Map<string, Element>();\n const references: Record<string, string> = {};\n const names = new ReferenceNames();\n const register = (reference: string, element: Element): string => {\n const unique = names.take(reference);\n elements.set(unique, element);\n references[unique] = labelOfElement(element);\n return unique;\n };\n\n this.textReadContainers = new Set<Element>();\n const parts: string[] = [`# ${capValue(location.title, 120)}`, `Route: ${location.route}`];\n const unsaved = this.options.describeUnsavedChanges();\n parts.push(`Unsaved changes: ${unsaved}`);\n parts.push(this.describeWindow());\n\n const root = this.options.findRoot();\n const dialogs = Array.from(document.querySelectorAll('[role=\"dialog\"], [role=\"alertdialog\"]')).filter(isRendered);\n for (const dialog of dialogs) {\n parts.push(`## Dialog \"${capValue(labelOfElement(dialog), 80)}\" (open)`);\n parts.push(...this.readContainer(dialog, register));\n }\n if (root) {\n // the page's own tabs only: a tab list inside a form is a field's (the language tabs of a translatable text,\n // 14 per field on a long form); its open tab shows in the field's value\n const tabs = Array.from(root.querySelectorAll('[role=\"tab\"], nav[aria-label] a[aria-current]'))\n .filter(tab => isRendered(tab) && tab.closest('form, fieldset') === null)\n .slice(0, MAX_PAGE_TABS);\n if (tabs.length > 0) {\n const tabNames = tabs.map(tab => {\n const reference = register(`t.${slugOf(textOf(tab))}`, tab);\n const current = tab.getAttribute('aria-selected') === 'true' || tab.getAttribute('aria-current') !== null;\n return `${reference} \"${capValue(textOf(tab), 40)}\"${current ? ' (open)' : ''}`;\n });\n parts.push(`Tabs: ${tabNames.join(' · ')}`);\n }\n const messages = Array.from(root.querySelectorAll('[role=\"alert\"], [role=\"status\"]')).filter(isRendered);\n for (const message of messages) {\n const text = textOf(message);\n if (text !== '') parts.push(`Message: ${capValue(text, 200)}`);\n }\n parts.push(...this.readContainer(root, register));\n } else {\n parts.push('(no page content)');\n }\n const anchors = Array.from(document.querySelectorAll(`[${AGENT_ATTRIBUTES.anchor}]`)).filter(isRendered);\n if (anchors.length > 0) {\n parts.push(`Anchors: ${anchors.map(anchor => register(`a.${anchor.getAttribute(AGENT_ATTRIBUTES.anchor)}`, anchor)).join(' · ')}`);\n }\n // the menu goes last and is never cut away by a long page: the page gets the characters the menu leaves\n const menu = this.readNavigation(register).join('\\n');\n this.options.registry.replace(elements);\n const page = joinScreenParts(parts, Math.max(maxChars - (menu === '' ? 0 : menu.length + 1), Math.floor(maxChars / 2)));\n return { markdown: menu === '' ? page : `${page}\\n${menu}`, route: location.route, title: location.title, references };\n }\n\n /** `Agent window: … · browser 1440×900 px`, or `Browser window: 1440×900 px` without a description of the window. */\n protected describeWindow(): string {\n const size = typeof window === 'undefined' ? 'unknown' : `${Math.round(window.innerWidth)}×${Math.round(window.innerHeight)} px`;\n const agentWindow = this.options.describeAgentWindow?.() ?? null;\n return agentWindow ? `Agent window: ${oneLine(agentWindow)} · browser ${size}` : `Browser window: ${size}`;\n }\n\n /**\n * The main menu: its entries (`data-nav-key`) and groups (`data-nav-group`) on the screen, as `nav.<key>`\n * references (the menu of a compact layout shows icons only: an entry's name is its aria-label). A closed group\n * shows only itself.\n */\n protected readNavigation(register: (reference: string, element: Element) => string): string[] {\n const navigation = this.options.findNavigation?.() ?? null;\n if (!navigation) return [];\n const groups = new Map<string, string[]>();\n const readKeys = new Set<string>();\n for (const mark of Array.from(navigation.querySelectorAll(`[${AGENT_ATTRIBUTES.navKey}], [${AGENT_ATTRIBUTES.navGroup}]`))) {\n const groupKey = mark.getAttribute(AGENT_ATTRIBUTES.navGroup);\n const key = mark.getAttribute(AGENT_ATTRIBUTES.navKey) ?? groupKey;\n // a group of a list is the whole `<li>` with its entries: its row is the first child\n const element = mark.tagName === 'LI' ? (mark.firstElementChild ?? mark) : mark;\n if (key === null || readKeys.has(key) || !isRendered(element)) continue;\n const label = labelOfElement(element);\n if (label === '') continue;\n readKeys.add(key);\n const reference = register(`nav.${slugOf(key)}`, element);\n const entry = `${reference} \"${capValue(label, 40)}\"${mark.getAttribute('aria-current') !== null ? ' (open)' : ''}`;\n if (groupKey !== null) {\n const isExpanded = Array.from(mark.querySelectorAll(`[${AGENT_ATTRIBUTES.navKey}]`)).some(isRendered);\n groups.set(groupKey, [isExpanded ? `${capValue(label, 40)} (${reference}):` : `${entry} (closed group)`]);\n continue;\n }\n const owningGroup = mark.parentElement?.closest(`[${AGENT_ATTRIBUTES.navGroup}]`)?.getAttribute(AGENT_ATTRIBUTES.navGroup) ?? '';\n groups.set(owningGroup, [...(groups.get(owningGroup) ?? []), entry]);\n }\n if (readKeys.size === 0) return [];\n const lines = [MAIN_MENU_HEADING];\n for (const [groupKey, entries] of groups) {\n if (groupKey === '') {\n lines.push(`- ${entries.join(' · ')}`);\n continue;\n }\n const [head, ...rest] = entries;\n lines.push(rest.length > 0 ? `- ${head} ${rest.join(' · ')}` : `- ${head}`);\n }\n return lines;\n }\n\n protected readWhole(element: Element): string {\n if (element.matches(FIELD_SELECTOR)) return valueOfField(element).value;\n // biome-ignore lint/performance/useDomNodeTextContent: the rendered text (no hidden parts) is what the user sees\n return (element as HTMLElement).innerText ?? element.textContent ?? '';\n }\n\n /** The sections of a container (by headings), each with its fields, tables and buttons. */\n protected readContainer(container: Element, register: (reference: string, element: Element) => string): string[] {\n const lines: string[] = [];\n const seen = new Set<Element>();\n const headings = Array.from(container.querySelectorAll('h1, h2, h3, h4, [role=\"heading\"]')).filter(isRendered);\n for (const heading of headings) {\n const section = heading.closest('section, fieldset, [data-slot=\"card\"], form') ?? heading.parentElement;\n const text = textOf(heading);\n if (text === '') continue;\n const reference = register(`s.${slugOf(text)}`, section ?? heading);\n const collapsed = section?.querySelector('[aria-expanded=\"false\"]') && !section.querySelector(FIELD_SELECTOR) ? ' (closed)' : '';\n lines.push(`## ${capValue(text, 80)} (${reference})${collapsed}`);\n if (section) lines.push(...this.readElements(section, register, seen));\n }\n lines.push(...this.readElements(container, register, seen));\n return lines;\n }\n\n /**\n * The plain text, tables, cards, fields and buttons of a container. Tables and cards go before the fields: a page's\n * filters and forms never push its list out of the read.\n */\n protected readElements(container: Element, register: (reference: string, element: Element) => string, seen: Set<Element>): string[] {\n const lines: string[] = [];\n const text = this.readPlainText(container);\n this.textReadContainers.add(container);\n if (text !== '') lines.push(`Text: ${text}`);\n for (const checkbox of Array.from(container.querySelectorAll(ROW_CHECKBOX_SELECTOR))) seen.add(checkbox);\n lines.push(...this.readTablesAndCards(container, register, seen));\n for (const field of Array.from(container.querySelectorAll(FIELD_SELECTOR))) {\n if (seen.has(field) || !isRendered(field) || field.closest('[role=\"radiogroup\"]') !== null && field.getAttribute('role') !== 'radiogroup') continue;\n seen.add(field);\n const name = field.getAttribute('name') ?? field.getAttribute('id') ?? labelOfElement(field);\n const { value, kind } = valueOfField(field);\n const facts: FieldFacts = {\n reference: register(`f.${fieldReferenceNameOf(name.includes(' ') ? slugOf(name) : name)}`, field),\n label: labelOfElement(field),\n value,\n kind,\n required: field.hasAttribute('required') || field.getAttribute('aria-required') === 'true',\n disabled: field.hasAttribute('disabled') || field.getAttribute('aria-readonly') === 'true' || field.hasAttribute('readonly'),\n invalidMessage: invalidMessageOf(field),\n isSecret: field.matches(SECRET_FIELD_SELECTOR) || field.closest(`[${AGENT_ATTRIBUTES.secret}]`) !== null,\n };\n lines.push(formatFieldLine(facts));\n }\n const buttons: ButtonFacts[] = [];\n for (const button of Array.from(container.querySelectorAll(BUTTON_SELECTOR))) {\n if (seen.has(button) || !isRendered(button) || button.closest('table, [role=\"grid\"], [role=\"tablist\"]')) continue;\n seen.add(button);\n const label = labelOfElement(button);\n if (label === '') continue;\n buttons.push({\n reference: register(`b.${slugOf(label)}`, button),\n label,\n disabled: button.hasAttribute('disabled') || button.getAttribute('aria-disabled') === 'true',\n });\n }\n const buttonLine = formatButtons(buttons);\n if (buttonLine) lines.push(buttonLine);\n return lines;\n }\n\n /** The tables of a container and the cards of a card grid (`EntityListGrid` sets `data-row-key` on each). */\n protected readTablesAndCards(container: Element, register: (reference: string, element: Element) => string, seen: Set<Element>): string[] {\n const lines: string[] = [];\n for (const table of Array.from(container.querySelectorAll(TABLE_SELECTOR))) {\n if (seen.has(table) || !isRendered(table)) continue;\n seen.add(table);\n lines.push(...formatTable(this.readTable(table, register)));\n }\n const cards = Array.from(container.querySelectorAll(`[${AGENT_ATTRIBUTES.rowKey}]`)).filter(\n card => !seen.has(card) && !card.closest(TABLE_SELECTOR) && isRendered(card)\n );\n if (cards.length > 0) {\n lines.push(`Cards: ${cards.length} on screen`);\n for (const card of cards) seen.add(card);\n for (const card of cards.slice(0, MAX_TABLE_ROWS)) {\n for (const inner of Array.from(card.querySelectorAll(BUTTON_SELECTOR))) seen.add(inner);\n const checkbox = card.querySelector('input[type=\"checkbox\"], [role=\"checkbox\"]');\n const selected = checkbox !== null && isChecked(checkbox) ? ' (selected)' : '';\n lines.push(`- ${register(`row.${rowKeyOf(card, null, 0)}`, card)}${selected}: ${capValue(textOf(card), 160)}`);\n }\n if (cards.length > MAX_TABLE_ROWS) lines.push(`… ${cards.length - MAX_TABLE_ROWS} more cards on screen`);\n }\n return lines;\n }\n\n /**\n * The visible text of a container that no field, table, card or button line carries, its pieces joined with \" · \"\n * (pieces of one block with a space), without the text of a section read before: a message, a record's facts or a\n * dashboard figure the user reads.\n */\n protected readPlainText(container: Element): string {\n // two headings in one section read it twice: its text goes once\n if (this.textReadContainers.has(container)) return '';\n let text = '';\n let previousBlock: Element | null = null;\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);\n for (let node = walker.nextNode(); node !== null && text.length < MAX_SECTION_TEXT_CHARS; node = walker.nextNode()) {\n const piece = oneLine(node.textContent ?? '');\n const parent = node.parentElement;\n if (piece === '' || parent === null) continue;\n // a dialog read as a container is not left out by its own role, only what sits inside it\n const skipped = parent.closest(TEXT_SKIPPED_SELECTOR);\n if (skipped !== null && skipped !== container && container.contains(skipped)) continue;\n if (!isRendered(parent) || this.isInsideReadSection(parent, container)) continue;\n const block = this.blockOf(parent, container);\n text = text === '' ? piece : `${text}${block === previousBlock ? ' ' : ' · '}${piece}`;\n previousBlock = block;\n }\n return text.length <= MAX_SECTION_TEXT_CHARS ? text : `${text.slice(0, MAX_SECTION_TEXT_CHARS - 1)}…`;\n }\n\n /** The nearest ancestor that is not laid out inline (the container at the latest). */\n protected blockOf(element: Element, container: Element): Element {\n for (let ancestor: Element | null = element; ancestor !== null && ancestor !== container; ancestor = ancestor.parentElement) {\n if (!window.getComputedStyle(ancestor).display.startsWith('inline')) return ancestor;\n }\n return container;\n }\n\n protected isInsideReadSection(element: Element, container: Element): boolean {\n for (let ancestor: Element | null = element; ancestor !== null && ancestor !== container; ancestor = ancestor.parentElement) {\n if (this.textReadContainers.has(ancestor)) return true;\n }\n return false;\n }\n\n protected readTable(table: Element, register: (reference: string, element: Element) => string): TableFacts {\n const headerCells = Array.from(table.querySelectorAll('thead th, [role=\"columnheader\"]'));\n const columns = headerCells.map(cell => textOf(cell));\n const idColumnIndex = columns.findIndex(column => ID_COLUMN_LABELS.has(column.toLowerCase()));\n const bodyRows = Array.from(table.querySelectorAll('tbody tr, [role=\"row\"]')).filter(\n row => row.querySelector('th[scope=\"col\"], [role=\"columnheader\"]') === null && isRendered(row)\n );\n const rows = bodyRows.slice(0, MAX_TABLE_ROWS).map((row, rowIndex) => ({\n reference: register(`row.${rowKeyOf(row, idColumnIndex >= 0 ? idColumnIndex : null, rowIndex)}`, row),\n cells: Array.from(row.children).map(cell => {\n const secret = cell.closest(`[${AGENT_ATTRIBUTES.secret}]`) !== null || cell.querySelector(`[${AGENT_ATTRIBUTES.secret}]`) !== null;\n return secret ? '(hidden)' : textOf(cell);\n }),\n selected: row.getAttribute('aria-selected') === 'true' || row.getAttribute('data-state') === 'selected' || this.isRowChecked(row),\n }));\n return { caption: textOf(table.querySelector('caption')) || table.getAttribute('aria-label'), columns, rows, totalRows: bodyRows.length };\n }\n\n /** Whether the row's selection checkbox is checked. */\n protected isRowChecked(row: Element): boolean {\n const checkbox = row.querySelector('input[type=\"checkbox\"], [role=\"checkbox\"]');\n return checkbox !== null && isChecked(checkbox);\n }\n}\n","import type { ScreenHighlighter, ScreenMarkResult } from \"./client-tools\";\nimport { AGENT_ATTRIBUTES, labelOfElement, type ScreenReferenceRegistry } from \"./DomScreenReader\";\n\n/** How long a mark stays. */\nexport const MARK_VISIBLE_MS = 8000;\n\n/** The most characters of a note. */\nconst MAX_NOTE_CHARS = 120;\n\n/** A region of the viewport in CSS pixels (a `DOMRect` fits). */\nexport interface ScreenOccludingRect {\n top: number;\n left: number;\n right: number;\n bottom: number;\n}\n\n/** What a mark did, for the application (e.g. to shrink or move its agent window). */\nexport interface ScreenHighlightEvent {\n /** The references that were marked */\n references: string[];\n /** The marked elements, the first one scrolled into view */\n elements: Element[];\n /** The region the application reported as covering the page (its agent window), or null */\n occludingRect: ScreenOccludingRect | null;\n /** True when the first element stays covered by that region after the scroll (too tall for the free band, or a side panel over it) */\n coveredAfterScroll: boolean;\n}\n\n/** How to scroll a marked element so that it lands beside a covering region. */\nexport interface HighlightScrollPlan {\n /** Scroll margins applied for the one `scrollIntoView` call, in pixels */\n scrollMarginTop: number;\n scrollMarginBottom: number;\n /** True when the element cannot be scrolled out from under the region */\n coveredAfterScroll: boolean;\n}\n\n/** A region at least this share of the viewport height is a side panel: vertical scrolling cannot clear it. */\nexport const SIDE_PANEL_MIN_HEIGHT_SHARE = 0.6;\n\n/** The space kept between a marked element and the edge of the free band. */\nconst FREE_BAND_PADDING_PX = 16;\n\nexport interface DomScreenHighlighterOptions {\n registry: ScreenReferenceRegistry;\n /** The sentence the live region reads, e.g. \"The assistant marked: End date\" (translated by the application) */\n announce: (labels: string[]) => string;\n /** The region that covers the page now (the agent window in the viewport), or null; marks are scrolled beside it */\n getOccludingRect?: () => ScreenOccludingRect | null;\n /** Called after each mark, e.g. to make the agent window smaller or move it when the element stays covered */\n onHighlight?: (event: ScreenHighlightEvent) => void;\n}\n\n/**\n * Where a marked element must scroll to stay clear of a covering region: a sheet at the bottom (or top) of the\n * viewport that overlaps the element horizontally adds its height as a scroll margin, so `block: 'center'` centers the\n * element in the free band; a side panel (taller than {@link SIDE_PANEL_MIN_HEIGHT_SHARE} of the viewport) over the\n * element cannot be cleared by scrolling and is reported as covered.\n */\nexport const planHighlightScroll = (\n targetRect: ScreenOccludingRect,\n occludingRect: ScreenOccludingRect | null,\n viewportHeight: number,\n): HighlightScrollPlan => {\n const plan: HighlightScrollPlan = { scrollMarginTop: 0, scrollMarginBottom: 0, coveredAfterScroll: false };\n if (!occludingRect || occludingRect.bottom <= occludingRect.top || occludingRect.right <= occludingRect.left) return plan;\n const overlapsHorizontally = occludingRect.left < targetRect.right && occludingRect.right > targetRect.left;\n if (!overlapsHorizontally) return plan;\n const occludingHeight = Math.min(occludingRect.bottom, viewportHeight) - Math.max(occludingRect.top, 0);\n if (occludingHeight <= 0) return plan;\n if (occludingHeight >= viewportHeight * SIDE_PANEL_MIN_HEIGHT_SHARE) {\n plan.coveredAfterScroll = true;\n return plan;\n }\n const targetHeight = targetRect.bottom - targetRect.top;\n const occludesBottom = (occludingRect.top + occludingRect.bottom) / 2 >= viewportHeight / 2;\n if (occludesBottom) {\n plan.scrollMarginBottom = Math.max(0, viewportHeight - occludingRect.top);\n plan.coveredAfterScroll = targetHeight > Math.max(0, occludingRect.top) - FREE_BAND_PADDING_PX;\n } else {\n plan.scrollMarginTop = Math.max(0, occludingRect.bottom);\n plan.coveredAfterScroll = targetHeight > viewportHeight - Math.max(0, occludingRect.bottom) - FREE_BAND_PADDING_PX;\n }\n return plan;\n};\n\n/**\n * Marks elements with a calm outline (the theme's `--ring`) in an overlay above the page, a short note beside the\n * first one, and one sentence in a polite live region. The overlay never takes a click (`pointer-events: none`) and is\n * never read (`data-agent-skip`). Marks follow scrolling and leave after {@link MARK_VISIBLE_MS}, on Escape or on the\n * next mark. With `getOccludingRect` the first element is scrolled beside the application's agent window, and a\n * mark that stays covered counts as out of view; `onHighlight` tells the application after every mark.\n */\nexport class DomScreenHighlighter implements ScreenHighlighter {\n protected overlay: HTMLElement | null = null;\n\n protected liveRegion: HTMLElement | null = null;\n\n protected frame = 0;\n\n protected timer: ReturnType<typeof setTimeout> | null = null;\n\n protected marked: { element: Element; box: HTMLElement }[] = [];\n\n protected note: HTMLElement | null = null;\n\n constructor(protected readonly options: DomScreenHighlighterOptions) {}\n\n mark(references: string[], note: string | null): ScreenMarkResult {\n this.clear();\n const result: ScreenMarkResult = { marked: {}, missing: [], outOfView: [], collapsed: [] };\n const targets: Element[] = [];\n for (const reference of references) {\n let element = this.options.registry.find(reference) ?? this.options.registry.findAnchor(reference);\n if (!element) {\n result.missing.push(reference);\n continue;\n }\n // inside a closed section: mark what opens it\n const closedDisclosure = element.closest('[data-state=\"closed\"]');\n if (closedDisclosure && closedDisclosure !== element) {\n const trigger = closedDisclosure.parentElement?.querySelector('[aria-expanded=\"false\"]');\n if (trigger) {\n element = trigger;\n result.collapsed.push(reference);\n }\n }\n const rect = element.getBoundingClientRect();\n if (rect.bottom < 0 || rect.top > window.innerHeight) result.outOfView.push(reference);\n result.marked[reference] = labelOfElement(element) || reference;\n targets.push(element);\n }\n if (targets.length === 0) return result;\n const occludingRect = this.readOccludingRect();\n const plan = this.scrollIntoFreeBand(targets[0], occludingRect);\n const firstReference = Object.keys(result.marked)[0];\n if (plan.coveredAfterScroll && firstReference !== undefined && !result.outOfView.includes(firstReference)) {\n result.outOfView.push(firstReference);\n }\n this.draw(targets, note ? note.slice(0, MAX_NOTE_CHARS) : null);\n this.announce(this.options.announce(Object.values(result.marked)));\n try {\n this.options.onHighlight?.({\n references: Object.keys(result.marked),\n elements: targets,\n occludingRect,\n coveredAfterScroll: plan.coveredAfterScroll,\n });\n } catch {\n // the application's hook never breaks the mark\n }\n return result;\n }\n\n /** The application's covering region now; a failing callback counts as none. */\n protected readOccludingRect(): ScreenOccludingRect | null {\n try {\n return this.options.getOccludingRect?.() ?? null;\n } catch {\n return null;\n }\n }\n\n /** Scrolls the element to the center of the band the covering region leaves free (the whole viewport without one). */\n protected scrollIntoFreeBand(element: Element, occludingRect: ScreenOccludingRect | null): HighlightScrollPlan {\n const plan = planHighlightScroll(element.getBoundingClientRect(), occludingRect, window.innerHeight);\n const style = (element as HTMLElement).style as CSSStyleDeclaration | undefined;\n const marginTopBefore = style?.scrollMarginTop ?? '';\n const marginBottomBefore = style?.scrollMarginBottom ?? '';\n if (style) {\n if (plan.scrollMarginTop > 0) style.scrollMarginTop = `${plan.scrollMarginTop}px`;\n if (plan.scrollMarginBottom > 0) style.scrollMarginBottom = `${plan.scrollMarginBottom}px`;\n }\n try {\n // the scroll position is computed in the call: the margins can go right after it\n element.scrollIntoView({ block: 'center', behavior: 'smooth' });\n } finally {\n if (style) {\n style.scrollMarginTop = marginTopBefore;\n style.scrollMarginBottom = marginBottomBefore;\n }\n }\n return plan;\n }\n\n clear(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n if (this.frame) cancelAnimationFrame(this.frame);\n this.frame = 0;\n this.overlay?.remove();\n this.overlay = null;\n this.marked = [];\n this.note = null;\n document.removeEventListener('keydown', this.clearOnEscape);\n }\n\n protected clearOnEscape = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') this.clear();\n };\n\n protected draw(elements: Element[], note: string | null): void {\n const overlay = document.createElement('div');\n overlay.setAttribute(AGENT_ATTRIBUTES.skip, '');\n overlay.setAttribute('aria-hidden', 'true');\n overlay.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483000;';\n document.body.appendChild(overlay);\n this.overlay = overlay;\n this.marked = elements.map(element => {\n const box = document.createElement('div');\n box.style.cssText =\n 'position:fixed;border-radius:8px;box-shadow:0 0 0 2px var(--ring, #06d6e3),0 0 0 6px color-mix(in oklab, var(--ring, #06d6e3) 25%, transparent);transition:opacity 200ms ease;';\n overlay.appendChild(box);\n return { element, box };\n });\n if (note) {\n const noteElement = document.createElement('div');\n noteElement.textContent = note;\n noteElement.style.cssText =\n 'position:fixed;max-width:280px;padding:6px 10px;border-radius:8px;font-size:13px;line-height:1.35;background:var(--popover, #fff);color:var(--popover-foreground, #0b0948);box-shadow:0 4px 16px rgb(0 0 0 / 0.16);';\n overlay.appendChild(noteElement);\n this.note = noteElement;\n }\n const follow = (): void => {\n for (const { element, box } of this.marked) {\n const rect = element.getBoundingClientRect();\n box.style.left = `${rect.left - 4}px`;\n box.style.top = `${rect.top - 4}px`;\n box.style.width = `${rect.width + 8}px`;\n box.style.height = `${rect.height + 8}px`;\n box.style.opacity = element.isConnected ? '1' : '0';\n }\n if (this.note && this.marked[0]) {\n const rect = this.marked[0].element.getBoundingClientRect();\n // the note stays out of the agent window: a sheet below the element ends the room below\n const occludingRect = this.readOccludingRect();\n const coversBelow =\n occludingRect !== null &&\n occludingRect.left < rect.right &&\n occludingRect.right > rect.left &&\n occludingRect.top >= rect.bottom;\n const roomBottom = coversBelow ? occludingRect.top : window.innerHeight;\n const below = rect.bottom + 10 + 60 < roomBottom;\n this.note.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 296))}px`;\n this.note.style.top = below ? `${rect.bottom + 10}px` : `${Math.max(8, rect.top - 70)}px`;\n }\n this.frame = requestAnimationFrame(follow);\n };\n follow();\n document.addEventListener('keydown', this.clearOnEscape);\n this.timer = setTimeout(() => this.clear(), MARK_VISIBLE_MS);\n }\n\n protected announce(sentence: string): void {\n if (!this.liveRegion?.isConnected) {\n const liveRegion = document.createElement('div');\n liveRegion.setAttribute('role', 'status');\n liveRegion.setAttribute('aria-live', 'polite');\n liveRegion.setAttribute(AGENT_ATTRIBUTES.skip, '');\n liveRegion.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;';\n document.body.appendChild(liveRegion);\n this.liveRegion = liveRegion;\n }\n this.liveRegion.textContent = '';\n const liveRegion = this.liveRegion;\n setTimeout(() => {\n liveRegion.textContent = sentence;\n }, 50);\n }\n}\n","import type { ScreenTarget, ScreenTargetSource } from \"./client-tools\";\nimport { isClientToolToken } from \"./client-tools\";\n\n/** The attribute that marks an element as a screen the user can open; its value is the target key. */\nexport const AGENT_ANCHOR_ATTRIBUTE = 'data-agent-anchor';\n\n/** The attribute that puts a mark into a group (`groupKey` of `createDomScreenTargetSource()`). */\nexport const AGENT_ANCHOR_GROUP_ATTRIBUTE = 'data-agent-anchor-group';\n\nexport interface DomScreenTargetSourceOptions {\n /** Where the marks are looked for; default the document */\n root?: () => ParentNode | null;\n /** Only the marks of this group (`data-agent-anchor-group`); default every mark */\n groupKey?: string;\n}\n\nconst listAttribute = (element: Element, attributeName: string): string[] =>\n (element.getAttribute(attributeName) ?? '')\n .split(',')\n .map(part => part.trim())\n .filter(part => part !== '');\n\n/** The route of a mark: `data-agent-route`, else the path of its link. */\nconst routeOfMark = (element: Element): string | null => {\n const route = element.getAttribute('data-agent-route');\n if (route) return route;\n const href = element.getAttribute('href');\n if (!href) return null;\n try {\n const url = new URL(href, 'http://screen.invalid');\n return url.pathname;\n } catch {\n return null;\n }\n};\n\n/**\n * Reads one `ScreenTarget` from a mark, or null when it lacks a valid key or a route. The attributes:\n * `data-agent-anchor` (the key), `data-agent-label` (else the text), `data-agent-group`, `data-agent-route` (else the\n * link's path), and the comma lists `data-agent-parameters`, `data-agent-tabs`, `data-agent-filters`,\n * `data-agent-views`.\n */\nexport const readScreenTargetOfMark = (element: Element): ScreenTarget | null => {\n const key = element.getAttribute(AGENT_ANCHOR_ATTRIBUTE)?.trim() ?? '';\n if (!isClientToolToken(key)) return null;\n const routePattern = routeOfMark(element);\n if (!routePattern) return null;\n const label = (element.getAttribute('data-agent-label') ?? element.textContent ?? '').replace(/\\s+/g, ' ').trim() || key;\n return {\n key,\n label,\n group: element.getAttribute('data-agent-group')?.trim() || null,\n routePattern,\n parameters: listAttribute(element, 'data-agent-parameters'),\n tabs: listAttribute(element, 'data-agent-tabs'),\n filters: listAttribute(element, 'data-agent-filters').map(filterKey => ({ key: filterKey })),\n views: listAttribute(element, 'data-agent-views'),\n };\n};\n\n/**\n * A `ScreenTargetSource` from the marks of the rendered navigation: every element with `data-agent-anchor` the user\n * sees is a screen the user may open (the application renders only what its rights allow, so the marks carry its\n * rights). The first mark of a key wins. An application with a route table of its own writes its own source instead.\n */\nexport const createDomScreenTargetSource = (options: DomScreenTargetSourceOptions = {}): ScreenTargetSource => ({\n listTargets: (): ScreenTarget[] => {\n const root = options.root?.() ?? (typeof document !== 'undefined' ? document : null);\n if (!root) return [];\n const targets: ScreenTarget[] = [];\n const seenKeys = new Set<string>();\n for (const element of Array.from(root.querySelectorAll(`[${AGENT_ANCHOR_ATTRIBUTE}]`))) {\n if (options.groupKey !== undefined && element.getAttribute(AGENT_ANCHOR_GROUP_ATTRIBUTE) !== options.groupKey) continue;\n const target = readScreenTargetOfMark(element);\n if (!target || seenKeys.has(target.key)) continue;\n seenKeys.add(target.key);\n targets.push(target);\n }\n return targets;\n },\n});\n","import type { ScreenOpenRequest, ScreenPathGuide, ScreenTarget } from \"./client-tools\";\nimport { buildTargetRoute } from \"./client-tools\";\n\n/** How many times a target is guided before the agent just opens it (`shouldGuide` default). */\nexport const DEFAULT_GUIDES_PER_TARGET = 2;\n\n/** The key prefix of the guide counts in localStorage. */\nexport const PATH_GUIDE_COUNT_KEY_PREFIX = 'ddd-agents:pathGuide:';\n\n/** How long one step of the path stays marked, in ms. */\nexport const PATH_GUIDE_STEP_MS = 700;\n\n/** The class a marked step of the path carries; the step also gets an outline in the theme's `--ring` (inline, restored after). */\nexport const PATH_GUIDE_CLASS = 'agents-path-guide-step';\n\n/**\n * The default `shouldGuide`: the first `limit` opens of a target are guided, counted per key in localStorage; without\n * storage (private window, blocked) every open is guided once per page life.\n */\nexport const createGuideCounter = (\n limit: number = DEFAULT_GUIDES_PER_TARGET,\n readStorage: () => Pick<Storage, 'getItem' | 'setItem'> | null = () => window.localStorage,\n): ((targetKey: string) => boolean) => {\n const counts = new Map<string, number>();\n return (targetKey: string): boolean => {\n const storageKey = `${PATH_GUIDE_COUNT_KEY_PREFIX}${targetKey}`;\n let count = counts.get(targetKey) ?? 0;\n try {\n count = Math.max(count, Number.parseInt(readStorage()?.getItem(storageKey) ?? '0', 10) || 0);\n } catch {\n // no storage: the count of this page life\n }\n if (count >= limit) return false;\n counts.set(targetKey, count + 1);\n try {\n readStorage()?.setItem(storageKey, String(count + 1));\n } catch {\n // no storage\n }\n return true;\n };\n};\n\nexport interface DomScreenPathGuideOptions {\n /** The elements of the way to the target in order (menu group, menu entry, tab); missing ones are skipped */\n findPathElements: (target: ScreenTarget, request: ScreenOpenRequest) => Element[];\n /** The route the user is on (without the basePath and query) */\n currentRoute: () => string;\n /** Whether this open of the target is guided; default the first `DEFAULT_GUIDES_PER_TARGET` per key */\n shouldGuide?: (targetKey: string) => boolean;\n stepMs?: number;\n}\n\nconst PATH_GUIDE_OUTLINE = '2px solid var(--ring, #2563eb)';\n\nconst markStep = (element: Element, outlinesBefore: Map<Element, string>): void => {\n element.classList.add(PATH_GUIDE_CLASS);\n if (element instanceof HTMLElement) {\n outlinesBefore.set(element, element.style.outline);\n element.style.outline = PATH_GUIDE_OUTLINE;\n }\n};\n\nconst unmarkStep = (element: Element, outlinesBefore: Map<Element, string>): void => {\n element.classList.remove(PATH_GUIDE_CLASS);\n if (element instanceof HTMLElement && outlinesBefore.has(element)) {\n element.style.outline = outlinesBefore.get(element) ?? '';\n outlinesBefore.delete(element);\n }\n};\n\nconst prefersReducedMotion = (): boolean => {\n try {\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n } catch {\n return false;\n }\n};\n\n/**\n * The DOM default of `ScreenPathGuide`: marks the elements of the way to the target one after the other\n * (`PATH_GUIDE_CLASS`), so the user learns where the screen lives. It runs beside the navigation and never delays the\n * answer. Skipped under reduced motion, when the user already is on the target, when no element of the way is on the\n * screen (plain navigation), and when `shouldGuide` says so. Esc or a click cancels it.\n */\nexport const createDomScreenPathGuide = (options: DomScreenPathGuideOptions): ScreenPathGuide => {\n const shouldGuide = options.shouldGuide ?? createGuideCounter();\n const stepMs = options.stepMs ?? PATH_GUIDE_STEP_MS;\n let timers: ReturnType<typeof setTimeout>[] = [];\n let markedElements: Element[] = [];\n const outlinesBefore = new Map<Element, string>();\n let removeListeners: (() => void) | null = null;\n\n const cancel = (): void => {\n timers.forEach(timer => clearTimeout(timer));\n timers = [];\n markedElements.forEach(element => unmarkStep(element, outlinesBefore));\n markedElements = [];\n removeListeners?.();\n removeListeners = null;\n };\n\n const guide = (target: ScreenTarget, request: ScreenOpenRequest): boolean => {\n cancel();\n if (prefersReducedMotion()) return false;\n const targetRoute = buildTargetRoute(target, request.recordIds, request.tab);\n const currentRoute = options.currentRoute().split('?')[0];\n if (targetRoute !== null && currentRoute === targetRoute) return false;\n const pathElements = options.findPathElements(target, request).filter(element => element.isConnected);\n if (pathElements.length === 0) return false;\n if (!shouldGuide(target.key)) return false;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') cancel();\n };\n const onPointerDown = (): void => cancel();\n document.addEventListener('keydown', onKeyDown, true);\n document.addEventListener('pointerdown', onPointerDown, true);\n removeListeners = () => {\n document.removeEventListener('keydown', onKeyDown, true);\n document.removeEventListener('pointerdown', onPointerDown, true);\n };\n pathElements.forEach((element, stepIndex) => {\n timers.push(\n setTimeout(() => {\n markedElements.forEach(marked => unmarkStep(marked, outlinesBefore));\n markStep(element, outlinesBefore);\n markedElements = [element];\n }, stepIndex * stepMs),\n );\n });\n timers.push(setTimeout(cancel, pathElements.length * stepMs));\n return true;\n };\n\n return { guide, cancel };\n};\n","import type { ScreenPicture, ScreenPictureCapturer, ScreenPictureRenderMode, ScreenPictureRequest, ScreenPictureSize } from \"./client-tools\";\n\n/**\n * What a picture of the screen cannot show. The same sentences as `AgentUIMCPPackage::PICTURE_LIMITATIONS` of the\n * server (a contract test compares them): the model reads them beside every picture.\n */\nexport const PICTURE_LIMITATIONS: readonly string[] = [\n 'content of other origins (embedded frames, some images and fonts) can be blank or replaced',\n 'video, canvas and WebGL content can be blank',\n 'password fields show dots; fields the application marks secret or skipped are left out',\n 'only what is in the browser window is shown; parts scrolled out of view are left out (the text read has them)',\n];\n\n/** The budgets of one size preset: the long edge, the pixels and the encoded bytes. */\nexport interface ScreenPicturePreset {\n maxLongEdge: number;\n maxPixels: number;\n maxBytes: number;\n}\n\n/** The three size presets; `large` stays below the server's caps (4,000,000 pixels, 614,400 bytes). */\nexport const SCREEN_PICTURE_PRESETS: Record<ScreenPictureSize, ScreenPicturePreset> = {\n small: { maxLongEdge: 1024, maxPixels: 786_432, maxBytes: 150_000 },\n medium: { maxLongEdge: 1600, maxPixels: 1_920_000, maxBytes: 350_000 },\n large: { maxLongEdge: 2048, maxPixels: 3_750_000, maxBytes: 600_000 },\n};\n\n/** The machine mode: 64 grey levels, 75 % of the size, half the byte budget (a picture for the model, not a person). */\nexport const MACHINE_MODE_GREY_LEVELS = 64;\nexport const MACHINE_MODE_SIZE_FACTOR = 0.75;\nexport const MACHINE_MODE_BYTE_FACTOR = 0.5;\n\n/** The most encodings of one capture; each retry scales down from the source. */\nexport const MAX_PICTURE_ENCODE_ATTEMPTS = 4;\n\n/** The most elements a capture copies (a larger page keeps its first elements). */\nexport const MAX_PICTURE_ELEMENTS = 8000;\n\n/** The attribute that leaves an element out of a picture. */\nexport const AGENT_SKIP_ATTRIBUTE = 'data-agent-skip';\n\n/** The attribute that blanks an element's content in a picture (its box stays). */\nexport const AGENT_SECRET_ATTRIBUTE = 'data-agent-secret';\n\nexport interface ScreenPictureDimensions {\n width: number;\n height: number;\n /** The factor from the source size */\n scale: number;\n}\n\n/** The byte budget of a preset in a render mode. */\nexport const computePictureByteBudget = (pictureSize: ScreenPictureSize, renderMode: ScreenPictureRenderMode): number => {\n const preset = SCREEN_PICTURE_PRESETS[pictureSize];\n return Math.floor(renderMode === 'machine' ? preset.maxBytes * MACHINE_MODE_BYTE_FACTOR : preset.maxBytes);\n};\n\n/**\n * The size of the picture of a source: within the long edge and the pixels of the preset (never larger than the\n * source), 75 % of it in the machine mode, times `retryScale` (a retry's factor, always taken from the source size).\n */\nexport const computePictureDimensions = (\n sourceWidth: number,\n sourceHeight: number,\n request: ScreenPictureRequest,\n retryScale: number = 1,\n): ScreenPictureDimensions => {\n const preset = SCREEN_PICTURE_PRESETS[request.pictureSize];\n const safeWidth = Math.max(1, sourceWidth);\n const safeHeight = Math.max(1, sourceHeight);\n let scale = Math.min(1, preset.maxLongEdge / Math.max(safeWidth, safeHeight), Math.sqrt(preset.maxPixels / (safeWidth * safeHeight)));\n if (request.renderMode === 'machine') scale *= MACHINE_MODE_SIZE_FACTOR;\n scale *= retryScale;\n return {\n width: Math.max(1, Math.floor(safeWidth * scale)),\n height: Math.max(1, Math.floor(safeHeight * scale)),\n scale,\n };\n};\n\n/**\n * The factor of the next attempt after an encoding of `encodedBytes` missed the budget: the bytes shrink about with the\n * pixels, so the side shrinks with the square root, with a margin. Applied to the source size, never to the last\n * picture (no blur piling up over retries).\n */\nexport const computeRetryScale = (previousRetryScale: number, encodedBytes: number, byteBudget: number): number => {\n if (encodedBytes <= 0) return previousRetryScale;\n return previousRetryScale * Math.min(0.9, Math.sqrt(byteBudget / encodedBytes) * 0.9);\n};\n\n/** Turns RGBA pixels grey in place; with `greyLevels` the grey is quantized to that many levels. */\nexport const convertPixelsToGrey = (pixels: Uint8ClampedArray, greyLevels: number | null = null): void => {\n const levelStep = greyLevels !== null && greyLevels > 1 ? 255 / (greyLevels - 1) : null;\n for (let index = 0; index < pixels.length; index += 4) {\n let grey = 0.2126 * pixels[index] + 0.7152 * pixels[index + 1] + 0.0722 * pixels[index + 2];\n if (levelStep !== null) grey = Math.round(grey / levelStep) * levelStep;\n pixels[index] = grey;\n pixels[index + 1] = grey;\n pixels[index + 2] = grey;\n }\n};\n\n/** Whether an element scrolls its own content vertically (its scrolled-away part is shown expanded). */\nconst isScrollContainer = (element: Element, style: CSSStyleDeclaration): boolean =>\n element.scrollHeight > element.clientHeight + 1 && (style.overflowY === 'auto' || style.overflowY === 'scroll');\n\n/** A box in window coordinates. */\nexport interface PictureBox {\n top: number;\n left: number;\n bottom: number;\n right: number;\n}\n\n/**\n * The style an element has without any style of the page: the browser's default for its tag. A clone's inline style\n * carries only what differs from it, so the copy holds tens of declarations per element instead of all ~350 computed\n * ones (measured: about 20 KB per element, 10 MB for 516 elements of a list page).\n */\nexport interface DefaultStyleSource {\n /** The default value of `property` for an element of `tagName` (`namespaceUri` for SVG) */\n valueOf(tagName: string, namespaceUri: string | null, property: string): string;\n /** Frees what the source holds (a frame) */\n dispose(): void;\n}\n\n/** The defaults by tag, kept for the page's life: a browser's defaults do not change. */\nconst defaultStylesByTag = new Map<string, Map<string, string>>();\n\n/**\n * The browser defaults read from an empty frame (no style sheet of the page reaches it), cached per tag. Without a\n * frame (no document, a sandbox refusing it) every value is unknown and every declaration is copied, as before.\n */\nexport const createFrameDefaultStyleSource = (documentOfRoot: Document): DefaultStyleSource => {\n let frame: HTMLIFrameElement | null = null;\n const frameDocument = (): Document | null => {\n if (frame === null) {\n frame = documentOfRoot.createElement('iframe');\n frame.setAttribute('aria-hidden', 'true');\n frame.setAttribute(AGENT_SKIP_ATTRIBUTE, '');\n frame.style.cssText = 'position:fixed;left:-100000px;top:0;width:10px;height:10px;visibility:hidden;border:0;';\n documentOfRoot.body.appendChild(frame);\n }\n return frame.contentDocument;\n };\n return {\n valueOf: (tagName, namespaceUri, property) => {\n const cacheKey = `${namespaceUri ?? ''} ${tagName}`;\n let defaults = defaultStylesByTag.get(cacheKey);\n if (defaults === undefined) {\n defaults = new Map<string, string>();\n const emptyDocument = frameDocument();\n const view = emptyDocument?.defaultView;\n if (emptyDocument?.body && view) {\n const element = namespaceUri ? emptyDocument.createElementNS(namespaceUri, tagName) : emptyDocument.createElement(tagName);\n emptyDocument.body.appendChild(element);\n const style = view.getComputedStyle(element);\n for (let index = 0; index < style.length; index += 1) {\n const name = style.item(index);\n defaults.set(name, style.getPropertyValue(name));\n }\n element.remove();\n defaultStylesByTag.set(cacheKey, defaults);\n }\n }\n return defaults.get(property) ?? '';\n },\n dispose: () => {\n (frame as HTMLIFrameElement | null)?.remove();\n frame = null;\n },\n };\n};\n\n/**\n * The display types whose height the table layout computes from their rows. A copy of a list holds fewer rows than\n * the page (rows out of view, the element cap): with the page's height (17,769 px for 200 rows) the layout stretched\n * the copied rows over it and the picture showed the header and at most one row. Their height is never copied.\n */\nconst TABLE_LAYOUT_DISPLAYS = new Set(['table', 'inline-table', 'table-row-group', 'table-header-group', 'table-footer-group', 'table-row']);\n\n/**\n * Properties copied whatever their value: their computed value depends on another property (a border width computes\n * to 0 under `border-style: none`), so a page's `solid` border of 0 px matches the default 0 and was dropped, and the\n * clone drew the initial `medium` width (3 px) around every element.\n */\nconst ALWAYS_COPIED_PROPERTY = /^(border-.*-width|outline-width|column-rule-width)$/;\n\n/** Properties never copied onto a table part (see {@link TABLE_LAYOUT_DISPLAYS}). */\nconst TABLE_LAYOUT_HEIGHT_PROPERTIES = new Set(['height', 'block-size']);\n\n/**\n * Copies the computed style of an element onto its clone as inline style: a declaration only when it differs from the\n * tag's default or from the parent's value (the clone's parent carries that value, so an inherited one matches it).\n * Custom properties (`--*`) are never copied: every property is copied with its resolved value, and a page's design\n * tokens (273 inherited variables of a Tailwind page, 7.6 KB on every element) would be copied onto each element.\n */\nconst copyComputedStyle = (\n style: CSSStyleDeclaration,\n clone: HTMLElement | SVGElement,\n original: Element,\n parentStyle: CSSStyleDeclaration | null,\n defaults: DefaultStyleSource | null,\n): void => {\n const declarations: string[] = [];\n const isTablePart = TABLE_LAYOUT_DISPLAYS.has(style.display);\n const namespaceUri = original.namespaceURI === 'http://www.w3.org/1999/xhtml' ? null : original.namespaceURI;\n for (let index = 0; index < style.length; index += 1) {\n const property = style.item(index);\n if (property.startsWith('--') || (isTablePart && TABLE_LAYOUT_HEIGHT_PROPERTIES.has(property))) continue;\n const value = style.getPropertyValue(property);\n const isDefault = defaults !== null && value === defaults.valueOf(original.localName, namespaceUri, property);\n if (isDefault && !ALWAYS_COPIED_PROPERTY.test(property) && (parentStyle === null || parentStyle.getPropertyValue(property) === value)) continue;\n declarations.push(`${property}:${value}`);\n }\n clone.setAttribute('style', declarations.join(';'));\n};\n\n/** The part of `box` inside `clip`; null when they do not meet. */\nconst intersectBoxes = (box: PictureBox, clip: PictureBox): PictureBox | null => {\n const top = Math.max(box.top, clip.top);\n const left = Math.max(box.left, clip.left);\n const bottom = Math.min(box.bottom, clip.bottom);\n const right = Math.min(box.right, clip.right);\n return bottom > top && right > left ? { top, left, bottom, right } : null;\n};\n\n/** Whether an element lies wholly outside the visible box (an element without a size is never out: its children may show). */\nconst isOutOfView = (element: Element, visibleBox: PictureBox): boolean => {\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) return false;\n return intersectBoxes({ top: rect.top, left: rect.left, bottom: rect.bottom, right: rect.right }, visibleBox) === null;\n};\n\n/** The visible box for the children of an element: clipped by it when it hides its overflow. */\nconst clipBoxOf = (element: Element, style: CSSStyleDeclaration | null, visibleBox: PictureBox): PictureBox => {\n if (style === null) return visibleBox;\n if (style.position === 'fixed') return windowBox();\n if (style.overflowX === 'visible' && style.overflowY === 'visible') return visibleBox;\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) return visibleBox;\n return intersectBoxes({ top: rect.top, left: rect.left, bottom: rect.bottom, right: rect.right }, visibleBox) ?? { top: 0, left: 0, bottom: 0, right: 0 };\n};\n\n/** The browser window in window coordinates. */\nconst windowBox = (): PictureBox => ({ top: 0, left: 0, bottom: window.innerHeight, right: window.innerWidth });\n\nexport interface ScreenCloneOptions {\n /** Whether computed styles are inlined; false in tests (default true) */\n copyStyles?: boolean;\n /**\n * Only elements with a part inside this box are copied (window coordinates; default the browser window); `null`\n * copies the whole page with its scroll containers expanded. A long list's rows below the window are left out:\n * the picture shows what the user sees, and the copy stays small.\n */\n visibleBox?: PictureBox | null;\n /** The defaults a declaration is compared with (default: an empty frame, {@link createFrameDefaultStyleSource}) */\n defaultStyles?: DefaultStyleSource | null;\n}\n\n/** The value of a form field written into its clone, a password as dots. */\nconst copyFieldValue = (original: Element, clone: Element): void => {\n if (original instanceof HTMLInputElement && clone instanceof HTMLInputElement) {\n if (original.type === 'password') {\n clone.setAttribute('value', '•'.repeat(Math.min(original.value.length, 24)));\n clone.type = 'text';\n } else if (original.type === 'checkbox' || original.type === 'radio') {\n if (original.checked) clone.setAttribute('checked', '');\n else clone.removeAttribute('checked');\n } else {\n clone.setAttribute('value', original.value);\n }\n } else if (original instanceof HTMLTextAreaElement) {\n clone.textContent = original.value;\n } else if (original instanceof HTMLSelectElement && clone instanceof HTMLSelectElement) {\n Array.from(clone.options).forEach((option, optionIndex) => {\n if (optionIndex === original.selectedIndex) option.setAttribute('selected', '');\n else option.removeAttribute('selected');\n });\n }\n};\n\n/** Elements never copied into a picture. */\nconst LEFT_OUT_TAGS = new Set(['SCRIPT', 'NOSCRIPT', 'TEMPLATE', 'LINK', 'META']);\n\n/**\n * A copy of `root` ready to be drawn: the elements in the browser window only (`visibleBox`), computed styles inlined\n * where they differ from the tag's default, form values written (passwords as dots), elements with `data-agent-skip`\n * left out, the content of elements with `data-agent-secret` blanked (the box stays). With `visibleBox: null` the whole\n * page is copied and scroll containers are expanded. `false` instead of options skips the styles (tests).\n */\nexport const prepareScreenCloneForPicture = (root: Element, cloneOptions: boolean | ScreenCloneOptions = true): Element => {\n const options: ScreenCloneOptions = typeof cloneOptions === 'boolean' ? { copyStyles: cloneOptions } : cloneOptions;\n const copyStyles = options.copyStyles ?? true;\n const visibleBox = options.visibleBox === undefined ? (typeof window === 'undefined' ? null : windowBox()) : options.visibleBox;\n const ownsDefaults = copyStyles && options.defaultStyles === undefined;\n const defaults = ownsDefaults ? createFrameDefaultStyleSource(root.ownerDocument) : (options.defaultStyles ?? null);\n try {\n return copyScreenClone(root, copyStyles, visibleBox, defaults);\n } finally {\n if (ownsDefaults) defaults?.dispose();\n }\n};\n\nconst copyScreenClone = (root: Element, copyStyles: boolean, rootVisibleBox: PictureBox | null, defaults: DefaultStyleSource | null): Element => {\n const clone = root.cloneNode(false) as Element;\n let copiedElements = 0;\n const copyInto = (original: Element, target: Element, parentStyle: CSSStyleDeclaration | null, visibleBox: PictureBox | null): void => {\n const view = original.ownerDocument.defaultView;\n // the style is read for the copy and for the clip of the window part\n const style = view && (copyStyles || visibleBox !== null) ? view.getComputedStyle(original) : null;\n if (copyStyles && style && (target instanceof HTMLElement || target instanceof SVGElement)) {\n copyComputedStyle(style, target, original, parentStyle, defaults);\n if (visibleBox === null && target instanceof HTMLElement && isScrollContainer(original, style)) {\n target.style.overflowY = 'visible';\n target.style.height = 'auto';\n target.style.maxHeight = 'none';\n }\n } else if (visibleBox === null && !copyStyles && target instanceof HTMLElement && original.scrollHeight > original.clientHeight + 1) {\n target.style.overflowY = 'visible';\n target.style.height = 'auto';\n target.style.maxHeight = 'none';\n }\n copyFieldValue(original, target);\n if (original.hasAttribute(AGENT_SECRET_ATTRIBUTE)) {\n target.textContent = '';\n if (target instanceof HTMLElement) target.style.background = '#9e9e9e';\n return;\n }\n if (original instanceof HTMLTextAreaElement) return;\n const childVisibleBox = visibleBox === null ? null : clipBoxOf(original, style, visibleBox);\n for (const childNode of Array.from(original.childNodes)) {\n if (childNode.nodeType === Node.TEXT_NODE) {\n target.appendChild(childNode.cloneNode(false));\n continue;\n }\n if (!(childNode instanceof Element)) continue;\n if (LEFT_OUT_TAGS.has(childNode.tagName) || childNode.hasAttribute(AGENT_SKIP_ATTRIBUTE)) continue;\n if (childVisibleBox !== null && isOutOfView(childNode, childVisibleBox)) continue;\n if (copiedElements >= MAX_PICTURE_ELEMENTS) return;\n copiedElements += 1;\n const childClone = childNode.cloneNode(false) as Element;\n target.appendChild(childClone);\n copyInto(childNode, childClone, copyStyles ? style : null, childVisibleBox);\n }\n };\n copyInto(root, clone, null, rootVisibleBox);\n return clone;\n};\n\n/** Measures the height of a prepared clone laid out at `width`, off screen. */\nconst measureCloneHeight = (clone: Element, width: number, documentOfRoot: Document): number => {\n const holder = documentOfRoot.createElement('div');\n holder.setAttribute('aria-hidden', 'true');\n holder.style.cssText = `position:fixed;left:-100000px;top:0;width:${width}px;visibility:hidden;pointer-events:none;`;\n const measured = clone.cloneNode(true) as Element;\n holder.appendChild(measured);\n documentOfRoot.body.appendChild(holder);\n try {\n return Math.ceil(Math.max(holder.scrollHeight, (measured as HTMLElement).scrollHeight ?? 0));\n } finally {\n holder.remove();\n }\n};\n\nconst loadImage = (url: string): Promise<HTMLImageElement> =>\n new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error('the screen could not be drawn'));\n image.src = url;\n });\n\nconst encodeCanvas = (canvas: HTMLCanvasElement, mimeType: string, quality: number): Promise<Blob | null> =>\n new Promise(resolve => {\n try {\n canvas.toBlob(blob => resolve(blob), mimeType, quality);\n } catch {\n resolve(null);\n }\n });\n\nconst encodeBase64 = async (blob: Blob): Promise<string> => {\n const bytes = new Uint8Array(await blob.arrayBuffer());\n let binary = '';\n const chunkSize = 0x8000;\n for (let offset = 0; offset < bytes.length; offset += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));\n }\n return btoa(binary);\n};\n\nexport interface DomScreenPictureCapturerOptions {\n /** The element pictured; default the document element */\n root?: () => Element | null;\n /** The quality of the first encoding (default 0.8); a retry lowers it once to 0.65 */\n quality?: number;\n}\n\n/**\n * The DOM default of `ScreenPictureCapturer`: draws a styled copy of what the browser window shows (SVG foreignObject\n * onto a canvas; elements out of view are not copied, styles only where they differ from the browser's default) at the\n * size of the preset, grey in `greyscale` and `machine` (64 levels), and encodes it as WebP (JPEG where the browser\n * has no WebP encoder) within the byte budget; a miss retries from the source size, at most\n * `MAX_PICTURE_ENCODE_ATTEMPTS` times. No dependency; what it cannot show is `PICTURE_LIMITATIONS`. Returns null when\n * the browser refuses (a tainted canvas, no canvas), and the runner answers `PICTURE_UNAVAILABLE`.\n */\nexport const createDomScreenPictureCapturer = (options: DomScreenPictureCapturerOptions = {}): ScreenPictureCapturer => ({\n capture: async (request: ScreenPictureRequest): Promise<ScreenPicture | null> => {\n if (typeof document === 'undefined') return null;\n const root = options.root?.() ?? document.documentElement;\n if (!root) return null;\n try {\n const sourceWidth = Math.max(1, Math.ceil(window.innerWidth || root.clientWidth));\n const clone = prepareScreenCloneForPicture(root);\n // the window's part of the page: the copy holds only what is in it\n const sourceHeight = Math.max(1, Math.min(measureCloneHeight(clone, sourceWidth, document), Math.ceil(window.innerHeight || sourceWidth * 8)));\n const serialized = new XMLSerializer().serializeToString(clone);\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${sourceWidth}\" height=\"${sourceHeight}\">` +\n `<foreignObject x=\"0\" y=\"0\" width=\"100%\" height=\"100%\">${serialized}</foreignObject></svg>`;\n const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`);\n const byteBudget = computePictureByteBudget(request.pictureSize, request.renderMode);\n let retryScale = 1;\n let quality = options.quality ?? 0.8;\n for (let attempt = 1; attempt <= MAX_PICTURE_ENCODE_ATTEMPTS; attempt += 1) {\n const dimensions = computePictureDimensions(sourceWidth, sourceHeight, request, retryScale);\n const canvas = document.createElement('canvas');\n canvas.width = dimensions.width;\n canvas.height = dimensions.height;\n const context = canvas.getContext('2d');\n if (!context) return null;\n context.fillStyle = '#ffffff';\n context.fillRect(0, 0, dimensions.width, dimensions.height);\n context.drawImage(image, 0, 0, dimensions.width, dimensions.height);\n if (request.renderMode !== 'colour') {\n const imageData = context.getImageData(0, 0, dimensions.width, dimensions.height);\n convertPixelsToGrey(imageData.data, request.renderMode === 'machine' ? MACHINE_MODE_GREY_LEVELS : null);\n context.putImageData(imageData, 0, 0);\n }\n let blob = await encodeCanvas(canvas, 'image/webp', quality);\n if (blob && blob.type !== 'image/webp') blob = await encodeCanvas(canvas, 'image/jpeg', quality);\n if (!blob) return null;\n if (blob.size <= byteBudget || attempt === MAX_PICTURE_ENCODE_ATTEMPTS) {\n if (blob.size > byteBudget) return null;\n return {\n base64: await encodeBase64(blob),\n mimeType: blob.type === 'image/webp' ? 'image/webp' : 'image/jpeg',\n width: dimensions.width,\n height: dimensions.height,\n byteSize: blob.size,\n };\n }\n retryScale = computeRetryScale(retryScale, blob.size, byteBudget);\n quality = Math.min(quality, 0.65);\n }\n return null;\n } catch {\n return null;\n }\n },\n});\n","import type { AgentWindowAdapter, ClientToolRequestType } from \"./client-tools\";\n\nexport interface AgentWindowAdapterOptions {\n /** The mode the window shows now */\n getMode: () => string;\n /** Shows a mode; called only with a mode of `modes` */\n applyMode: (mode: string) => void | Promise<void>;\n /** The modes the application knows (`setAgentWindowMode` refuses others) */\n modes: string[];\n /** The mode of `stepAside()`; default `aside` */\n asideMode?: string;\n /** The request types the window steps aside for; default `OPEN_TARGET`, `HIGHLIGHT`, a picture (`READ_SCREEN`) */\n stepAsideFor?: ClientToolRequestType[];\n}\n\n/**\n * An `AgentWindowAdapter` over the application's own window state: `stepAside()` remembers the mode and shows the\n * aside mode, `restore()` goes back to the remembered mode, `setMode()` shows a known mode. Stepping aside before the\n * agent opens a screen, marks elements or takes a picture is the default.\n */\nexport const createAgentWindowAdapter = (options: AgentWindowAdapterOptions): AgentWindowAdapter => {\n const asideMode = options.asideMode ?? 'aside';\n const stepAsideFor = options.stepAsideFor ?? ['OPEN_TARGET', 'HIGHLIGHT', 'READ_SCREEN'];\n let modeBeforeAside: string | null = null;\n return {\n stepAside: async () => {\n const currentMode = options.getMode();\n if (currentMode === asideMode) return;\n modeBeforeAside = currentMode;\n await options.applyMode(asideMode);\n },\n restore: async () => {\n if (modeBeforeAside === null) return;\n const mode = modeBeforeAside;\n modeBeforeAside = null;\n await options.applyMode(mode);\n },\n setMode: async (mode: string) => {\n if (!options.modes.includes(mode)) return false;\n modeBeforeAside = null;\n await options.applyMode(mode);\n return true;\n },\n shouldStepAsideBefore: (requestType: ClientToolRequestType) => stepAsideFor.includes(requestType),\n getMode: () => options.getMode(),\n };\n};\n","import type { AgentRealtimeListenerCredential, AgentRealtimeMessageDelivery } from \"./realtime-arrival\";\n\n/**\n * The account-level realtime read (`GET …/realtimeMessages`, `AgentAccountRealtimeMessagesGetResponseDto`): the open\n * messages of the realtime port addressed to the signed-in account — what reaches a client that shows no conversation,\n * e.g. a call's ring — and the credential to listen on the host's transport without a conversation.\n */\nexport interface AccountRealtimeRead {\n messages: AgentRealtimeMessageDelivery[];\n /** Null without a transport: the client then keeps polling the read. */\n listenerCredential: AgentRealtimeListenerCredential | null;\n}\n\n/** The pause between two account reads while no transport is bound. */\nexport const ACCOUNT_REALTIME_POLL_INTERVAL_MS = 5_000;\n\n/** The pause before the one re-read of `readAfterPing` when the first read brought nothing new. */\nexport const ACCOUNT_REALTIME_PING_REREAD_DELAY_MS = 400;\n\n/** What a subscriber of the poll is told; each hook is optional. */\nexport interface AccountRealtimePollSubscriber {\n /**\n * A message that arrived: every message once per type, key and payload (a replacement with a new payload arrives\n * again; a message cleared and sent again after a read saw it gone arrives again). From the poll and from the\n * transport.\n */\n onMessage?: (message: AgentRealtimeMessageDelivery) => void;\n /**\n * A message that is open no more: a read answered without any message of its type and key (it was answered or\n * withdrawn on the server, or its time is over). Called once, after the arrivals of the same read. A subscriber is\n * told the clear only of a message it was handed, as an arrival or in the hand-over of `subscribe`, and with that\n * message as it was handed to it last. A replacement under the same type and key is an arrival, never a clear. Only\n * a read tells it, and only of a message that was known when the read started: while a transport is bound, the next\n * `readNow()` or `readAfterPing()`.\n */\n onMessageCleared?: (message: AgentRealtimeMessageDelivery) => void;\n}\n\nexport interface AccountRealtimePollOptions extends AccountRealtimePollSubscriber {\n /**\n * The account read of the binding (`AgentsConversationClient.getAccountRealtimeMessages`), called with the\n * `clientId` option (undefined without one). The read always states a client id (the HTTP binding: query parameter\n * `clientId`), by which the server knows a client that only polls; which id is the binding's word: the one handed\n * in, else the id of its `uiClient`, else one it creates once and keeps while it lives. A binding of the host's own\n * states one the same way.\n */\n readAccountRealtime: (clientId?: string) => Promise<AccountRealtimeRead>;\n /**\n * The client id the account read states, for a host that manages its own ids (8 to 64 letters, digits and `-`): it\n * wins over the binding's `uiClient` and over the id the binding creates. Default: none — the binding decides.\n */\n clientId?: string;\n /** The credential of every read (null without a transport) — the host binds its transport with it. */\n onListenerCredential?: (credential: AgentRealtimeListenerCredential | null) => void;\n /**\n * Whether the host's transport is bound now: while true the poll skips its reads (the transport delivers through\n * `acceptArrivedMessage` or pings `readAfterPing`). Default: never bound — the poll reads every interval.\n */\n isTransportBound?: () => boolean;\n /** The pause between two reads. Default `ACCOUNT_REALTIME_POLL_INTERVAL_MS`. */\n intervalMs?: number;\n /** The pause before the one re-read after a ping. Default `ACCOUNT_REALTIME_PING_REREAD_DELAY_MS`. */\n rereadDelayMs?: number;\n /** A failed read (the next interval reads again; nothing arrives and nothing is cleared). Default: ignored. */\n onReadFailed?: (error: unknown) => void;\n}\n\nexport interface AccountRealtimePoll {\n /**\n * Reads at once (also while a transport is bound); resolves with the number of messages that arrived new. An answer\n * that comes back after the answer of a read started later is left out (0).\n */\n readNow: () => Promise<number>;\n /**\n * The arrival adapter for a host transport that carries the message: hands it to `onMessage` unless it already\n * arrived. Returns whether it arrived new.\n */\n acceptArrivedMessage: (message: AgentRealtimeMessageDelivery) => boolean;\n /**\n * The arrival adapter for a host transport that only pings: reads the account; when that read brought nothing new —\n * the ping overtook the server's write — it reads once more after the re-read delay. Resolves with whether a\n * message arrived.\n */\n readAfterPing: () => Promise<boolean>;\n /**\n * Adds a subscriber after the poll was created; the hooks the poll was created with keep working beside it. The\n * subscriber gets, before `subscribe` returns, the messages open now (those the last read saw and the transport\n * delivered since, inside their `secondsLeft`), then every arrival and the clear of every message it was handed: a\n * message past its `secondsLeft` when the subscriber came is not handed to it, and neither is its clear. Returns\n * the function that removes it; the poll keeps running.\n */\n subscribe: (subscriber: AccountRealtimePollSubscriber) => () => void;\n /**\n * Stops the poll (a read in flight still hands its messages). Nothing is reported as cleared and no subscriber is\n * removed: what `readNow()` or `acceptArrivedMessage()` bring afterwards still reaches them.\n */\n stop: () => void;\n}\n\n/** What makes two deliveries the same message: a new payload under the same type and key is a new message. */\nconst identityOf = (message: AgentRealtimeMessageDelivery): string =>\n `${message.messageType}\\u0000${message.messageKey}\\u0000${message.payloadJson}`;\n\n/** Where a message stands on the realtime port: a replacement stands at the same place. */\nconst placeOf = (message: AgentRealtimeMessageDelivery): string => `${message.messageType}\\u0000${message.messageKey}`;\n\ninterface AccountRealtimePollSubscription {\n subscriber: AccountRealtimePollSubscriber;\n}\n\ninterface KnownAccountRealtimeMessage {\n message: AgentRealtimeMessageDelivery;\n /** How many reads had started when the message became known: none of them can tell that it is gone. */\n startedReadCount: number;\n /** When its `secondsLeft` are over on this client's clock. */\n expiresAtMs: number;\n /** The subscribers the message was handed to, as an arrival or when they came: only they are told its clear. */\n handedTo: Set<AccountRealtimePollSubscription>;\n}\n\n/**\n * The account-level realtime poll of a client that shows no conversation: reads the account at once, then every\n * interval while no transport is bound, hands each new message to `onMessage` once (the same message from the poll and\n * the transport arrives once) and each message a read finds gone to `onMessageCleared` once. Further subscribers come\n * and go through `subscribe`. The client of a conversation keeps its run-state read; this is the read without one.\n */\nexport const createAccountRealtimePoll = (options: AccountRealtimePollOptions): AccountRealtimePoll => {\n const intervalMs = options.intervalMs ?? ACCOUNT_REALTIME_POLL_INTERVAL_MS;\n const rereadDelayMs = options.rereadDelayMs ?? ACCOUNT_REALTIME_PING_REREAD_DELAY_MS;\n /**\n * The messages the last read saw (and the transport delivered since), by identity: one gone from a read may arrive\n * again. A read reports as cleared only what was known when it started.\n */\n let knownMessages = new Map<string, KnownAccountRealtimeMessage>();\n /** The hooks of the options first, then the subscribers in the order they came. */\n const subscriptions = new Set<AccountRealtimePollSubscription>([{ subscriber: options }]);\n let startedReadCount = 0;\n let newestAnsweredRead = 0;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const knownMessageOf = (message: AgentRealtimeMessageDelivery, nowMs: number): KnownAccountRealtimeMessage => ({\n message,\n startedReadCount,\n expiresAtMs: nowMs + message.secondsLeft * 1000,\n handedTo: new Set(),\n });\n\n /** Hands a message to a subscriber and notes it on the message, also for a subscriber without the hook. */\n const handMessage = (knownMessage: KnownAccountRealtimeMessage, subscription: AccountRealtimePollSubscription): void => {\n knownMessage.handedTo.add(subscription);\n subscription.subscriber.onMessage?.(knownMessage.message);\n };\n\n /**\n * A subscriber that came during the hand-over already got the open messages; one that left gets nothing more. Each\n * cleared place comes with its gone messages, the oldest first: a subscriber is told the newest one it was handed,\n * and nothing when it was handed none.\n */\n const handToSubscribers = (\n arrivedMessages: KnownAccountRealtimeMessage[],\n goneMessagesOfClearedPlaces: KnownAccountRealtimeMessage[][],\n ): void => {\n const subscriptionsNow = [...subscriptions];\n for (const arrivedMessage of arrivedMessages) {\n for (const subscription of subscriptionsNow) {\n if (subscriptions.has(subscription)) handMessage(arrivedMessage, subscription);\n }\n }\n for (const goneMessages of goneMessagesOfClearedPlaces) {\n for (const subscription of subscriptionsNow) {\n if (!subscriptions.has(subscription)) continue;\n const handedMessage = goneMessages.filter(goneMessage => goneMessage.handedTo.has(subscription)).pop();\n if (handedMessage !== undefined) subscription.subscriber.onMessageCleared?.(handedMessage.message);\n }\n }\n };\n\n const acceptArrivedMessage = (message: AgentRealtimeMessageDelivery): boolean => {\n const identity = identityOf(message);\n if (knownMessages.has(identity)) return false;\n const knownMessage = knownMessageOf(message, Date.now());\n knownMessages.set(identity, knownMessage);\n handToSubscribers([knownMessage], []);\n return true;\n };\n\n const readNow = async (): Promise<number> => {\n startedReadCount += 1;\n const readNumber = startedReadCount;\n const read = await options.readAccountRealtime(options.clientId);\n // the answer of a read started later is already in: this one tells an older state\n if (readNumber < newestAnsweredRead) return 0;\n newestAnsweredRead = readNumber;\n\n const nowMs = Date.now();\n const knownAfterRead = new Map<string, KnownAccountRealtimeMessage>();\n const openPlaces = new Set<string>();\n const arrivedMessages: KnownAccountRealtimeMessage[] = [];\n for (const message of read.messages) {\n const identity = identityOf(message);\n const knownMessage = knownMessages.get(identity) ?? knownMessageOf(message, nowMs);\n if (!knownMessages.has(identity)) arrivedMessages.push(knownMessage);\n knownAfterRead.set(identity, knownMessage);\n openPlaces.add(placeOf(message));\n }\n const goneMessages: KnownAccountRealtimeMessage[] = [];\n for (const [identity, knownMessage] of knownMessages) {\n if (knownAfterRead.has(identity)) continue;\n if (knownMessage.startedReadCount >= readNumber) {\n // it became known after this read had started (from the transport, or from a read answered in between):\n // this read cannot tell that it is gone\n knownAfterRead.set(identity, knownMessage);\n openPlaces.add(placeOf(knownMessage.message));\n } else {\n goneMessages.push(knownMessage);\n }\n }\n /** By place: a replaced message is no clear, and the gone messages of one place are one clear. */\n const goneMessagesByClearedPlace = new Map<string, KnownAccountRealtimeMessage[]>();\n for (const goneMessage of goneMessages) {\n const place = placeOf(goneMessage.message);\n if (openPlaces.has(place)) continue;\n goneMessagesByClearedPlace.set(place, [...(goneMessagesByClearedPlace.get(place) ?? []), goneMessage]);\n }\n knownMessages = knownAfterRead;\n\n handToSubscribers(arrivedMessages, [...goneMessagesByClearedPlace.values()]);\n options.onListenerCredential?.(read.listenerCredential);\n return arrivedMessages.length;\n };\n\n const subscribe = (subscriber: AccountRealtimePollSubscriber): (() => void) => {\n const subscription: AccountRealtimePollSubscription = { subscriber };\n subscriptions.add(subscription);\n const nowMs = Date.now();\n for (const knownMessage of [...knownMessages.values()]) {\n if (knownMessage.expiresAtMs > nowMs) handMessage(knownMessage, subscription);\n }\n return () => {\n subscriptions.delete(subscription);\n };\n };\n\n const schedule = (): void => {\n if (stopped) return;\n timer = setTimeout(tick, intervalMs);\n };\n\n const readIgnoringFailure = async (): Promise<number> => {\n try {\n return await readNow();\n } catch (error) {\n options.onReadFailed?.(error);\n return 0;\n }\n };\n\n const tick = async (): Promise<void> => {\n timer = null;\n if (stopped) return;\n if (!(options.isTransportBound?.() ?? false)) await readIgnoringFailure();\n schedule();\n };\n\n const readAfterPing = async (): Promise<boolean> => {\n if ((await readIgnoringFailure()) > 0) return true;\n await new Promise<void>(resolve => setTimeout(resolve, rereadDelayMs));\n return (await readIgnoringFailure()) > 0;\n };\n\n // the first read always happens: it carries the credential the host binds its transport with\n void readIgnoringFailure().then(schedule);\n\n return {\n readNow,\n acceptArrivedMessage,\n readAfterPing,\n subscribe,\n stop: () => {\n stopped = true;\n if (timer !== null) clearTimeout(timer);\n timer = null;\n },\n };\n};\n"],"names":["id","liveRegion"],"mappings":";;;;AA8BO,MAAM,4BAA4B;AAGlC,MAAM,wBAAwB;AAG9B,MAAM,uBAAuB;AAAA,EAClC,IAAI;AAAA,EACJ,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,oBAAoB;AACtB;AA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