@mgamadeus/ddd-agents 0.4.2 → 0.5.1

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.
Files changed (49) hide show
  1. package/README.md +31 -2
  2. package/dist/chat.js +8 -8
  3. package/dist/chunks/{ConversationMessageInputComposerWidgets-D5NlHJlV.js → ConversationMessageInputComposerWidgets-CGP-oxpk.js} +6 -6
  4. package/dist/chunks/{ConversationMessageInputComposerWidgets-D5NlHJlV.js.map → ConversationMessageInputComposerWidgets-CGP-oxpk.js.map} +1 -1
  5. package/dist/chunks/{WebSearchResultsConversationWidget-Dpy5qp4j.js → WebSearchResultsConversationWidget-DdlLDOLK.js} +2 -2
  6. package/dist/chunks/{WebSearchResultsConversationWidget-Dpy5qp4j.js.map → WebSearchResultsConversationWidget-DdlLDOLK.js.map} +1 -1
  7. package/dist/chunks/{canvas-reducers-CgL_H6Oc.js → canvas-reducers-DEq2Udt2.js} +2 -2
  8. package/dist/chunks/{canvas-reducers-CgL_H6Oc.js.map → canvas-reducers-DEq2Udt2.js.map} +1 -1
  9. package/dist/chunks/{canvas-title-slot-context-_Kf45ABB.js → canvas-title-slot-context-DZ0l2daI.js} +4 -4
  10. package/dist/chunks/{canvas-title-slot-context-_Kf45ABB.js.map → canvas-title-slot-context-DZ0l2daI.js.map} +1 -1
  11. package/dist/chunks/{canvasBodies-4iDPQLb0.js → canvasBodies-nwpKEfiA.js} +4 -4
  12. package/dist/chunks/{canvasBodies-4iDPQLb0.js.map → canvasBodies-nwpKEfiA.js.map} +1 -1
  13. package/dist/chunks/{canvasStorage-De3tMK4L.js → canvasStorage-BW4VDRos.js} +2 -2
  14. package/dist/chunks/{canvasStorage-De3tMK4L.js.map → canvasStorage-BW4VDRos.js.map} +1 -1
  15. package/dist/chunks/{link-navigation-DH3f2g9a.js → link-navigation-lCSYZSv7.js} +63 -8
  16. package/dist/chunks/link-navigation-lCSYZSv7.js.map +1 -0
  17. package/dist/chunks/realtime-arrival-DUJjwt2M.js +45 -0
  18. package/dist/chunks/realtime-arrival-DUJjwt2M.js.map +1 -0
  19. package/dist/chunks/{widget-image-readiness-signal-yGuEaCVG.js → widget-image-readiness-signal-BTSBUkFK.js} +2 -2
  20. package/dist/chunks/{widget-image-readiness-signal-yGuEaCVG.js.map → widget-image-readiness-signal-BTSBUkFK.js.map} +1 -1
  21. package/dist/chunks/{widget-name-resolver-JEJ1Hd0T.js → widget-name-resolver-Uhp0sE9E.js} +3 -3
  22. package/dist/chunks/{widget-name-resolver-JEJ1Hd0T.js.map → widget-name-resolver-Uhp0sE9E.js.map} +1 -1
  23. package/dist/client-testing.js +4 -4
  24. package/dist/client.js +16 -6
  25. package/dist/client.js.map +1 -1
  26. package/dist/files/i18n-keys.json +4 -2
  27. package/dist/image-render.js +7 -7
  28. package/dist/index.js +6 -6
  29. package/dist/kit.js +2 -2
  30. package/dist/preview.js +7 -7
  31. package/dist/provider.js +1 -1
  32. package/dist/renderer.js +9 -9
  33. package/dist/styles.css +20 -0
  34. package/dist/types/client/http/agents-http-wire.d.ts +14 -0
  35. package/dist/types/client/http/createAgentsHttpConversationClient.d.ts +8 -0
  36. package/dist/types/entries/ui.d.ts +9 -2
  37. package/dist/types/ui/ClientToolRequestRunner.d.ts +7 -1
  38. package/dist/types/ui/DomScreenPathGuide.d.ts +30 -0
  39. package/dist/types/ui/DomScreenTargetSource.d.ts +24 -0
  40. package/dist/types/ui/agent-window.d.ts +19 -0
  41. package/dist/types/ui/client-tools.d.ts +57 -1
  42. package/dist/types/ui/realtime-arrival.d.ts +36 -0
  43. package/dist/types/ui/screen-picture.d.ts +67 -0
  44. package/dist/ui.js +483 -3
  45. package/dist/ui.js.map +1 -1
  46. package/dist/widgets.js +4 -4
  47. package/package.json +1 -1
  48. package/public-api.json +47 -0
  49. package/dist/chunks/link-navigation-DH3f2g9a.js.map +0 -1
package/dist/ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ui.js","sources":["../src/ui/client-tools.ts","../src/ui/agent-ui-state.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"],"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';\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}\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} 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\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}\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","/**\n * What the client reports about its UI with every message and every run-state read (`Agent.UI`): the server keeps\n * only tokens of one pattern (route path, tab, view, references, dialog key) and writes the `[SIGNAL:ui]` note from\n * them and its own screen catalog. Never field values or labels: those reach the model only through `getCurrentScreen`.\n * The wire shape of `AgentUIState` of ddd-agents.\n */\nexport interface AgentUIState {\n /** The path of the route, e.g. `/orders/42` */\n routePath: string | null;\n /** The route's parameters, in order */\n routeParameters?: { name: string; value: string }[] | null;\n tab?: string | null;\n view?: string | null;\n /** The references of the fields with unsaved changes */\n unsavedFieldReferences?: string[];\n /** The references of the fields with a validation message */\n invalidFieldReferences?: string[];\n /** The key of a dialog or drawer open on the screen */\n openDialogKey?: string | null;\n visible?: boolean | null;\n /** ISO time of the capture */\n capturedAt?: string | null;\n}\n\n/** Reads the UI state now; the application's adapter (ddd-admin-ui ships one for screens built from its blocks). */\nexport interface AgentUIStateSource {\n readUIState(): AgentUIState | null;\n}\n\n/** A client id: 8 to 64 letters, digits and `-`, random per mount of the agent window (the server's pattern). */\nexport const createAgentUIClientId = (): string => {\n const randomPart =\n typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\"\n ? crypto.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n return `ui-${randomPart}`.slice(0, 64);\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 ScreenAdapters,\n type ScreenTarget,\n} from \"./client-tools\";\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 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 return this.highlight(parameters);\n default:\n return refusal(CLIENT_TOOL_OUTCOMES.unknownRequest);\n }\n } catch {\n return refusal(CLIENT_TOOL_OUTCOMES.readFailed);\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 const location = await this.adapters.navigator.open(target, { recordIds, tab, filters });\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 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.runner.accept(delivery, sendAnswer);\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 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"],"names":["id","liveRegion"],"mappings":";;AA4BO,MAAM,4BAA4B;AAGlC,MAAM,wBAAwB;AAG9B,MAAM,uBAAuB;AAAA,EAClC,IAAI;AAAA,EACJ,gBA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AAS,KAAK,YAAYA,WAAU;AACpC,WAAK,aAAaA;AAAAA,IACpB;AACA,SAAK,WAAW,cAAc;AAC9B,UAAM,aAAa,KAAK;AACxB,eAAW,MAAM;AACf,iBAAW,cAAc;AAAA,IAC3B,GAAG,EAAE;AAAA,EACP;AACF;"}
1
+ {"version":3,"file":"ui.js","sources":["../src/ui/client-tools.ts","../src/ui/agent-ui-state.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"],"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","/**\n * What the client reports about its UI with every message and every run-state read (`Agent.UI`): the server keeps\n * only tokens of one pattern (route path, tab, view, references, dialog key) and writes the `[SIGNAL:ui]` note from\n * them and its own screen catalog. Never field values or labels: those reach the model only through `getCurrentScreen`.\n * The wire shape of `AgentUIState` of ddd-agents.\n */\nexport interface AgentUIState {\n /** The path of the route, e.g. `/orders/42` */\n routePath: string | null;\n /** The route's parameters, in order */\n routeParameters?: { name: string; value: string }[] | null;\n tab?: string | null;\n view?: string | null;\n /** The references of the fields with unsaved changes */\n unsavedFieldReferences?: string[];\n /** The references of the fields with a validation message */\n invalidFieldReferences?: string[];\n /** The key of a dialog or drawer open on the screen */\n openDialogKey?: string | null;\n visible?: boolean | null;\n /** ISO time of the capture */\n capturedAt?: string | null;\n}\n\n/** Reads the UI state now; the application's adapter (ddd-admin-ui ships one for screens built from its blocks). */\nexport interface AgentUIStateSource {\n readUIState(): AgentUIState | null;\n}\n\n/** A client id: 8 to 64 letters, digits and `-`, random per mount of the agent window (the server's pattern). */\nexport const createAgentUIClientId = (): string => {\n const randomPart =\n typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\"\n ? crypto.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n return `ui-${randomPart}`.slice(0, 64);\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 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.runner.accept(delivery, sendAnswer);\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"],"names":["id","liveRegion"],"mappings":";;;AA8BO,MAAM,4BAA4B;AAGlC,MAAM,wBAAwB;AAG9B,MAAM,uBAAuB;AAAA,EAClC,IAAI;AAAA,EACJ,gBAAgB;AAAA,E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,UAAU,IAAI;AAC5B,aAAO;AAAA,IACT;AAAA,IACA,uBAAuB,CAAC,gBAAuC,aAAa,SAAS,WAAW;AAAA,EAAA;AAEpG;"}
package/dist/widgets.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { a1 as useIsEmailWidgetRender } from "./chunks/WebSearchResultsConversationWidget-Dpy5qp4j.js";
3
- import { ac, ad, ae, af, ae as ae2, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, a_, a$, b0, b1, b2, b3, b4, b5 } from "./chunks/WebSearchResultsConversationWidget-Dpy5qp4j.js";
2
+ import { a1 as useIsEmailWidgetRender } from "./chunks/WebSearchResultsConversationWidget-DdlLDOLK.js";
3
+ import { ac, ad, ae, af, ae as ae2, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, a_, a$, b0, b1, b2, b3, b4, b5 } from "./chunks/WebSearchResultsConversationWidget-DdlLDOLK.js";
4
4
  import { jsx } from "react/jsx-runtime";
5
- import { r as StatusChip, s as Text, F as classNames } from "./chunks/link-navigation-DH3f2g9a.js";
6
- import { g, x } from "./chunks/link-navigation-DH3f2g9a.js";
5
+ import { r as StatusChip, s as Text, F as classNames } from "./chunks/link-navigation-lCSYZSv7.js";
6
+ import { g, x } from "./chunks/link-navigation-lCSYZSv7.js";
7
7
  import { useSyncExternalStore, useState, useEffect } from "react";
8
8
  const WidgetStatusChip = (props) => /* @__PURE__ */ jsx(StatusChip, { ...props });
9
9
  const widgetLabel = "agents_widgetLabel_WecWAw";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mgamadeus/ddd-agents",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "The web frontend of the ddd-agents module: the agent chat, the widget renderer and the composed-view kit.",
5
5
  "keywords": [
6
6
  "ddd",