@linxin666/dsh-remote-bridge 0.4.9 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +28 -4
  3. package/README.zh.md +27 -4
  4. package/lib/client.js +511 -9
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +8671 -148
  7. package/lib/types/client/UiPresentRow.d.ts +13 -0
  8. package/lib/types/client/index.d.ts +4 -0
  9. package/lib/types/client/locales.d.ts +15 -2
  10. package/lib/types/client/toolview-slot.d.ts +68 -0
  11. package/lib/types/client/ui-card.d.ts +160 -0
  12. package/lib/types/core/connection.d.ts +38 -0
  13. package/lib/types/core/devices.d.ts +4 -0
  14. package/lib/types/core/extension.d.ts +13 -0
  15. package/lib/types/core/hub.d.ts +64 -0
  16. package/lib/types/core/protocol.d.ts +71 -7
  17. package/lib/types/core/push.d.ts +10 -2
  18. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  19. package/lib/types/core/ui.d.ts +238 -0
  20. package/lib/types/host/ui-tools.d.ts +80 -0
  21. package/lib/types/host/watchers.d.ts +7 -0
  22. package/lib/types/index.d.ts +29 -1
  23. package/package.json +3 -2
  24. package/src/client/UiPresentRow.tsx +149 -0
  25. package/src/client/index.ts +11 -0
  26. package/src/client/locales.ts +22 -2
  27. package/src/client/toolview-slot.ts +84 -0
  28. package/src/client/ui-card.ts +368 -0
  29. package/src/client/ui-present.module.css +87 -0
  30. package/src/core/connection.ts +169 -6
  31. package/src/core/devices.ts +116 -2
  32. package/src/core/extension.ts +20 -0
  33. package/src/core/hub.ts +156 -1
  34. package/src/core/protocol.ts +78 -6
  35. package/src/core/push.ts +34 -3
  36. package/src/core/turn-end-quiet.ts +388 -0
  37. package/src/core/ui.ts +398 -0
  38. package/src/host/ui-tools.ts +233 -0
  39. package/src/host/watchers.ts +27 -3
  40. package/src/index.ts +70 -2
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The transcript row of one `ui.present` call: the whole page an agent handed
3
+ * into the session, drawn in a controlled frame (protocol §35.11).
4
+ *
5
+ * The row renders and does not answer. The frame carries `srcdoc` and the one
6
+ * sandbox value §35.7 allows — never `allow-same-origin`, which is what turns a
7
+ * sandboxed document back into a same-origin one and would hand an agent page the
8
+ * GUI's own storage and cookies. There is no host request on any path here: an
9
+ * action the page posts arrives as one visible sentence telling the operator to
10
+ * answer on the phone, and nothing is forwarded, stored or sent.
11
+ *
12
+ * Height is measured from the inside because the frame is opaque from the
13
+ * outside: the injected reporter posts the document's own content height, the
14
+ * presenter's suggested `height` carries the first frame, and the measurement
15
+ * replaces it as soon as one arrives. The theme is handed in as variables read
16
+ * off the GUI root, so a card follows the running theme without importing one;
17
+ * a theme that cannot be read costs the injected variables, never the card.
18
+ */
19
+ import { useEffect, useMemo, useRef, useState } from 'react'
20
+ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
21
+ import {
22
+ CARD_DEFAULT_HEIGHT,
23
+ FRAME_HEIGHT_CHANNEL,
24
+ FRAME_PERMISSIONS,
25
+ FRAME_SANDBOX,
26
+ cardThemeTokens,
27
+ clampCardHeight,
28
+ frameDocument,
29
+ frameEventOf,
30
+ presentReadOf,
31
+ type ThemeToken,
32
+ } from './ui-card.ts'
33
+ import { PLUGIN_ATTR } from './semantic.ts'
34
+ import css from './ui-present.module.css'
35
+
36
+ export type UiPresentRowProps = PropsLocale<'remote-bridge'> & {
37
+ /** The stage the Tool slot published (`preparing`, `start` or `result`). */
38
+ readonly phase?: unknown
39
+ /** The call material of that stage: the argument view, argument text, meta. */
40
+ readonly block?: unknown
41
+ }
42
+
43
+ /** @returns the GUI root's theme tokens, or none when the theme cannot be read. */
44
+ function readThemeTokens(): readonly ThemeToken[] {
45
+ try {
46
+ return cardThemeTokens(getComputedStyle(document.documentElement))
47
+ } catch {
48
+ return []
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Render one card, or the neutral line of a call that carries no page.
54
+ * @param props - the stage, the call material and the locale seat.
55
+ * @returns the card body placed inside the official tool row.
56
+ */
57
+ export function UiPresentRow({ phase, block, t }: UiPresentRowProps) {
58
+ const read = useMemo(() => presentReadOf(phase, block), [phase, block])
59
+ const card = read.kind === 'card' ? read.card : undefined
60
+ const frame = useRef<HTMLIFrameElement | null>(null)
61
+ // Read once, before the first paint: a token list that arrived after mount
62
+ // would be a second document load for a card that already showed one.
63
+ const [tokens, setTokens] = useState<readonly ThemeToken[]>(readThemeTokens)
64
+ const [measured, setMeasured] = useState<number | undefined>(undefined)
65
+ const [interacted, setInteracted] = useState(false)
66
+
67
+ // The GUI switches between light and dark while a card is on screen; the
68
+ // document is rebuilt from the tokens of whichever theme is now in force.
69
+ useEffect(() => {
70
+ let media: MediaQueryList | undefined
71
+ try {
72
+ media = window.matchMedia('(prefers-color-scheme: dark)')
73
+ } catch {
74
+ return
75
+ }
76
+ const sync = (): void => { setTokens(readThemeTokens()) }
77
+ if (typeof media.addEventListener === 'function') {
78
+ media.addEventListener('change', sync)
79
+ return () => { media.removeEventListener('change', sync) }
80
+ }
81
+ media.addListener(sync)
82
+ return () => { media.removeListener(sync) }
83
+ }, [])
84
+
85
+ // A new page is a new measurement and a new notice: carrying either across
86
+ // would size the next card to the previous one's content.
87
+ const html = card?.html
88
+ useEffect(() => {
89
+ setMeasured(undefined)
90
+ setInteracted(false)
91
+ }, [html])
92
+
93
+ useEffect(() => {
94
+ const onMessage = (event: MessageEvent): void => {
95
+ const element = frame.current
96
+ // Identity is the frame element, not the origin: a sandboxed document has
97
+ // an opaque origin and can assert nothing about itself.
98
+ if (element === null || element.contentWindow === null || event.source !== element.contentWindow) return
99
+ const frameEvent = frameEventOf(event.data)
100
+ if (frameEvent === undefined) return
101
+ if (frameEvent.kind === 'height') {
102
+ setMeasured(clampCardHeight(frameEvent.height))
103
+ return
104
+ }
105
+ // The page asked the desktop for an answer. Nothing leaves this row; the
106
+ // operator is told where answering actually happens.
107
+ setInteracted(true)
108
+ }
109
+ window.addEventListener('message', onMessage)
110
+ return () => { window.removeEventListener('message', onMessage) }
111
+ }, [])
112
+
113
+ const srcdoc = useMemo(
114
+ () => (card === undefined ? '' : frameDocument(card.html, tokens, FRAME_HEIGHT_CHANNEL)),
115
+ [card, tokens],
116
+ )
117
+
118
+ if (card === undefined) {
119
+ return (
120
+ <div className={css.row} data-dsh-plugin={PLUGIN_ATTR} data-tone={read.kind}>
121
+ <p className={css.notice} role="status">{read.kind === 'oversize' ? t('card.oversize') : t('card.empty')}</p>
122
+ </div>
123
+ )
124
+ }
125
+
126
+ const height = measured ?? clampCardHeight(card.height ?? CARD_DEFAULT_HEIGHT)
127
+
128
+ return (
129
+ <section className={css.card} data-dsh-plugin={PLUGIN_ATTR} data-state={card.state}>
130
+ <header className={css.head}>
131
+ {card.title !== undefined && <span className={css.title}>{card.title}</span>}
132
+ <span className={css.badge}>{card.state === 'open' ? t('card.waiting') : t('card.settled')}</span>
133
+ </header>
134
+ <iframe
135
+ ref={frame}
136
+ className={css.frame}
137
+ style={{ height: `${height}px` }}
138
+ title={card.title ?? t('card.frameLabel')}
139
+ srcDoc={srcdoc}
140
+ sandbox={FRAME_SANDBOX}
141
+ allow={FRAME_PERMISSIONS}
142
+ referrerPolicy="no-referrer"
143
+ />
144
+ <p className={css.notice} role="status">
145
+ {interacted ? t('card.interacted') : t('card.answerOnPhone')}
146
+ </p>
147
+ </section>
148
+ )
149
+ }
@@ -11,6 +11,10 @@
11
11
  * the events are untouched — and it does not touch `dsh-remote-web-ui`'s pairing
12
12
  * service, its roster, or its browser cookie path.
13
13
  *
14
+ * The half also draws the transcript side of §35.11: one keyed `tool.call.toolview`
15
+ * entry renders a `ui.present` call's whole page in a controlled frame, while the
16
+ * phone stays the only place an action can be answered.
17
+ *
14
18
  * Export discipline (packages/AGENTS.md): the /client surface carries only what
15
19
  * cordis loading needs plus types.
16
20
  */
@@ -25,6 +29,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
25
29
  import { writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
26
30
  import { PairEntry } from './PairEntry.tsx'
27
31
  import { readPairToken } from './pair-token.ts'
32
+ import { registerPresentToolview } from './toolview-slot.ts'
28
33
  import { en, zh, type RemoteBridgeKey } from './locales.ts'
29
34
 
30
35
  declare module '@deepseek-ai/dsh-client-ui-slots' {
@@ -73,6 +78,12 @@ export function apply(ctx: ClientContext): void {
73
78
  return () => {}
74
79
  }
75
80
  })
81
+
82
+ // The transcript card of an interactive presentation (§35.11): one keyed
83
+ // registration under the wire Tool name draws the body of a `ui.present` call,
84
+ // so the official Tool row keeps everything else — identity, timing and the
85
+ // dispatch tree — and no Chat Node renderer is shadowed.
86
+ registerPresentToolview(ctx, NS)
76
87
  }
77
88
 
78
89
  export type { PairEntryProps } from './PairEntry.tsx'
@@ -1,11 +1,17 @@
1
1
  /**
2
- * `remote-bridge` namespace dictionaries: the protocol v1 pairing panel copy.
2
+ * `remote-bridge` namespace dictionaries: the protocol v1 pairing panel copy and
3
+ * the header of an interactive card (§35.11).
3
4
  *
4
5
  * The panel has one job — put the live one-shot code in front of the operator as
5
- * a QR symbol — so the copy carries exactly four things: what to do with the
6
+ * a QR symbol — so its copy carries exactly four things: what to do with the
6
7
  * symbol, how long it lives, which address the phone will actually dial, and why
7
8
  * the code is single-use. No key states how the host finds its public address:
8
9
  * that is an implementation fact the reader cannot act on.
10
+ *
11
+ * The card's keys say only what the transcript row can act on: whether the page
12
+ * is still waiting for the operator, that it is over, that this desktop renders
13
+ * without answering, and that a page carrying nothing or too much draws a
14
+ * sentence instead of a frame.
9
15
  */
10
16
 
11
17
  /** Simplified Chinese dictionary (the key-set source of truth). */
@@ -32,6 +38,13 @@ export const zh = {
32
38
  'action.copied': '已复制',
33
39
  'action.copyFailed': '复制失败',
34
40
  'action.retry': '重试',
41
+ 'card.waiting': '等你操作',
42
+ 'card.settled': '已结算',
43
+ 'card.answerOnPhone': '在手机上作答',
44
+ 'card.interacted': '已收到页面上的操作,但桌面端不作答:在手机上作答',
45
+ 'card.frameLabel': '整页卡片',
46
+ 'card.empty': '这次调用没有可渲染的页面',
47
+ 'card.oversize': '页面超出大小上限,未渲染',
35
48
  } as const
36
49
 
37
50
  /** English dictionary, key-for-key with the zh source. */
@@ -58,6 +71,13 @@ export const en: Record<RemoteBridgeKey, string> = {
58
71
  'action.copied': 'Copied',
59
72
  'action.copyFailed': 'Copy failed',
60
73
  'action.retry': 'Retry',
74
+ 'card.waiting': 'Waiting for you',
75
+ 'card.settled': 'Settled',
76
+ 'card.answerOnPhone': 'Answer on the phone',
77
+ 'card.interacted': 'The page sent an action, but this desktop does not answer: answer on the phone',
78
+ 'card.frameLabel': 'Page card',
79
+ 'card.empty': 'This call carried no page to render',
80
+ 'card.oversize': 'The page is over the size limit and was not rendered',
61
81
  }
62
82
 
63
83
  /** Every key the `remote-bridge` namespace carries. */
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The one seam through which this package registers its keyed Tool view.
3
+ *
4
+ * `tool.call.toolview` is declared by `@deepseek-ai/dsh-client-ui-tool`
5
+ * (`lib/types/client/contract/slots.d.ts`). That package is not installed in this
6
+ * workspace, so its types cannot be imported — a type-only import would itself be
7
+ * a new dependency, and a local `declare module` extension of the SDK's `SlotMap`
8
+ * would duplicate a contract another package owns and collide with the real
9
+ * declaration wherever both are loaded. This module therefore narrows
10
+ * `ctx.slots` to the two members the registration needs and states the slot's own
11
+ * shape locally:
12
+ *
13
+ * - the slot is keyed and session-scoped, and its key is the wire Tool name
14
+ * (`ui.present`), which is what makes one registration draw the card's body
15
+ * without shadowing the official `tool-call` renderer;
16
+ * - the owner publishes the call identity plus a stage union, mirrored here from
17
+ * the upstream `ToolCallPhaseProps`: `preparing`, `start` and `result`. The
18
+ * row reads the arguments at every stage but `result`, which is the only arm
19
+ * that carries the result node.
20
+ *
21
+ * Upstream changing that shape is a change to this file: the phase names, the
22
+ * keyed dispatch and the `locale` seat are the three facts the mirror carries.
23
+ *
24
+ * Technical debt, recorded rather than hidden: when this package next takes a
25
+ * dependency pass, adding `@deepseek-ai/dsh-client-ui-tool` as a devDependency
26
+ * lets this seam be replaced by `PropsRuntime<'tool.call.toolview'>` and by the
27
+ * typed `ctx.slots.register` overload directly.
28
+ * @module dsh-remote-bridge/client/toolview-slot
29
+ */
30
+
31
+ import type { ComponentType } from 'react'
32
+ import { UiPresentRow, type UiPresentRowProps } from './UiPresentRow.tsx'
33
+
34
+ /** The keyed Tool view slot the official row dispatches into. */
35
+ export const TOOLVIEW_SLOT = 'tool.call.toolview'
36
+
37
+ /** The wire Tool name this package renders: the keyed cell it claims. */
38
+ export const PRESENT_TOOL = 'ui.present'
39
+
40
+ /** The registration options this seam needs. */
41
+ export interface ToolviewRegistration {
42
+ /** Exact SlotMap key. */
43
+ readonly name: 'tool.call.toolview'
44
+ /** Keyed cell: the wire Tool name the owner dispatches by. */
45
+ readonly key: string
46
+ /** Dictionary namespace the render machinery synthesizes `t` from. */
47
+ readonly locale: string
48
+ }
49
+
50
+ /** The narrowed face of `ctx.slots` this package uses. */
51
+ export interface ToolviewSlotPort {
52
+ /** Run `seats` once the slot is declared; drop them if the declarer leaves. */
53
+ inject(name: string, seats: () => (() => void) | Iterable<() => void>): void
54
+ /** Contribute one view to one keyed cell; the answer is its disposer. */
55
+ register(options: ToolviewRegistration, view: ComponentType<UiPresentRowProps>): () => void
56
+ }
57
+
58
+ /** The host this seam needs: the client Context, structurally. */
59
+ export interface ToolviewSlotHost {
60
+ readonly slots: unknown
61
+ }
62
+
63
+ /**
64
+ * Contribute the `ui.present` card into the Tool row.
65
+ *
66
+ * The contribution is declaration-aware: `inject` waits for the official slot
67
+ * declaration, so a GUI composed without a Tool layer has no keyed cell and thus
68
+ * no card — that is the capability being absent, not an error to report. A
69
+ * registration refused by the registry (an occupied cell at the same priority)
70
+ * is swallowed the same way it is for this package's other seat, so one occupied
71
+ * slot never takes the sidebar entry down with it.
72
+ * @param host - the client Context.
73
+ * @param locale - the dictionary namespace this package registered.
74
+ */
75
+ export function registerPresentToolview(host: ToolviewSlotHost, locale: string): void {
76
+ const slots = host.slots as unknown as ToolviewSlotPort
77
+ slots.inject(TOOLVIEW_SLOT, () => {
78
+ try {
79
+ return slots.register({ name: TOOLVIEW_SLOT, key: PRESENT_TOOL, locale }, UiPresentRow)
80
+ } catch {
81
+ return () => {}
82
+ }
83
+ })
84
+ }
@@ -0,0 +1,368 @@
1
+ /**
2
+ * The transcript reading of one `ui.present` call (protocol §35.10, §35.11):
3
+ * what the desktop row draws, decided without touching the DOM.
4
+ *
5
+ * A card has two sources and neither may be dropped. While the call is still
6
+ * running the arguments are the only material on the wire, so the page comes out
7
+ * of `args` and the header says the operator has not acted yet. Once the result
8
+ * lands, the presentation payload `meta.ui` is the card's own record — its
9
+ * `state`, its `title` and the very document that crossed — and the arguments
10
+ * are only the fallback for a result that carries no payload.
11
+ *
12
+ * The argument view is read by shape rather than by import: a toolview receives a
13
+ * lazy `PartialArguments` when the call arrived as argument text and a plain
14
+ * payload when the call was dispatched as an object, and §35.10 fixes neither. A
15
+ * field reader therefore answers from all three shapes it can meet (lazy view,
16
+ * JSON text, parsed object) so a page is never lost to a shape this row did not
17
+ * anticipate.
18
+ *
19
+ * Two rules live here rather than in the renderer. A document above 256 KiB is
20
+ * never handed to a frame (§35.2 caps it on this side too), and a frame message is
21
+ * read by shape alone: the sandboxed document has an opaque origin, so identity
22
+ * comes from the frame element the row owns, never from what the message claims.
23
+ * Nothing read here is forwarded anywhere — the desktop renders and does not
24
+ * answer (§35.11).
25
+ * @module dsh-remote-bridge/client/ui-card
26
+ */
27
+
28
+ import { UI_HTML_MAX_BYTES, type UiState } from '../core/ui.ts'
29
+
30
+ /**
31
+ * The Tool slot's stage literals, as the composing contract publishes them
32
+ * (`ToolCallPhaseProps`). `result` is the settled arm; every other stage still
33
+ * has the call's arguments only.
34
+ */
35
+ export type PresentPhase = 'preparing' | 'start' | 'result'
36
+
37
+ /** One card as a row draws it, whichever source it came from. */
38
+ export interface PresentCard {
39
+ /** The whole self-contained document, `<!doctype html>` first. */
40
+ readonly html: string
41
+ /** Whether the card still holds the call (`open`) or is only a notice. */
42
+ readonly state: UiState
43
+ /** One header line; absent when the presenter named none. */
44
+ readonly title?: string
45
+ /** The presenter's suggested first height in points; the measurement wins. */
46
+ readonly height?: number
47
+ /** `"<sessionId>/<callId>"`, when the payload carries the card identity. */
48
+ readonly key?: string
49
+ }
50
+
51
+ /** What one row read produced. */
52
+ export type PresentRead =
53
+ | { readonly kind: 'card'; readonly card: PresentCard }
54
+ /** A page over {@link UI_HTML_MAX_BYTES}: refused visibly, never rendered. */
55
+ | { readonly kind: 'oversize' }
56
+ /** No page in either source: the row keeps a neutral line instead of a card. */
57
+ | { readonly kind: 'empty' }
58
+
59
+ /** The call material one row can read at its stage. */
60
+ interface PresentBlock {
61
+ /** The lazy argument view (`ToolArgs`), or a parsed payload. */
62
+ readonly args?: unknown
63
+ /** Finished argument text, for a stage that publishes it beside the view. */
64
+ readonly argsRaw?: unknown
65
+ /** `ToolResultNode.meta`, carried verbatim by the protocol. */
66
+ readonly meta?: unknown
67
+ }
68
+
69
+ /** One theme token as it is handed to a card's document. */
70
+ export type ThemeToken = readonly [name: string, value: string]
71
+
72
+ /**
73
+ * The theme tokens a card inherits from the GUI's own root element.
74
+ *
75
+ * Four roles and no more: the page needs a text colour it can trust, a quieter
76
+ * one, a surface and a border. A token the running theme does not define is
77
+ * simply not injected — the page then falls back to its own CSS, which is why an
78
+ * unreadable theme is a degraded look rather than a broken card.
79
+ */
80
+ export const CARD_THEME_TOKENS = [
81
+ '--dsw-alias-label-primary',
82
+ '--dsw-alias-label-secondary',
83
+ '--dsw-alias-bg-layer-1',
84
+ '--dsw-alias-border-l2',
85
+ ] as const
86
+
87
+ /** The one sandbox value a card frame is allowed (§35.7, §35.11). */
88
+ export const FRAME_SANDBOX = 'allow-scripts'
89
+
90
+ /**
91
+ * The permissions a card frame is explicitly denied.
92
+ *
93
+ * §35.7 refuses camera, microphone, location and clipboard reads on both ends.
94
+ * A sandboxed document already has an opaque origin, and this policy states the
95
+ * denial where the browser enforces it rather than leaving it to the default.
96
+ */
97
+ export const FRAME_PERMISSIONS = [
98
+ "camera 'none'",
99
+ "microphone 'none'",
100
+ "geolocation 'none'",
101
+ "clipboard-read 'none'",
102
+ ].join('; ')
103
+
104
+ /** The message type the injected reporter uses to publish the content height. */
105
+ export const FRAME_HEIGHT_CHANNEL = 'dsh-ui-card-height'
106
+
107
+ /** The first height of a card whose presenter suggested none. */
108
+ export const CARD_DEFAULT_HEIGHT = 320
109
+
110
+ /** The smallest and largest heights a measured card may take, in CSS pixels. */
111
+ export const CARD_MIN_HEIGHT = 96
112
+ export const CARD_MAX_HEIGHT = 720
113
+
114
+ /**
115
+ * Read one field as text out of every argument shape a toolview can receive.
116
+ * @param args - the lazy view, finished JSON text, or a parsed payload.
117
+ * @param name - the top-level field name.
118
+ * @returns the field's decoded string, or undefined when absent or not a string.
119
+ */
120
+ function fieldText(args: unknown, name: string): string | undefined {
121
+ if (typeof args === 'string') {
122
+ const parsed = parseJson(args)
123
+ return parsed === undefined ? undefined : fieldText(parsed, name)
124
+ }
125
+ if (typeof args !== 'object' || args === null) return undefined
126
+ const view = args as Record<string, unknown> & { text?: unknown }
127
+ if (typeof view.text === 'function') {
128
+ const read: unknown = (view.text as (key: string) => unknown).call(args, name)
129
+ return typeof read === 'string' ? read : undefined
130
+ }
131
+ const direct = view[name]
132
+ return typeof direct === 'string' ? direct : undefined
133
+ }
134
+
135
+ /**
136
+ * Read one field as any completed value out of the same three shapes.
137
+ * @param args - the lazy view, finished JSON text, or a parsed payload.
138
+ * @param name - the top-level field name.
139
+ * @returns the value, or undefined when absent.
140
+ */
141
+ function fieldValue(args: unknown, name: string): unknown {
142
+ if (typeof args === 'string') {
143
+ const parsed = parseJson(args)
144
+ return parsed === undefined ? undefined : fieldValue(parsed, name)
145
+ }
146
+ if (typeof args !== 'object' || args === null) return undefined
147
+ const view = args as Record<string, unknown> & { value?: unknown }
148
+ if (typeof view.value === 'function') return (view.value as (key: string) => unknown).call(args, name)
149
+ return view[name]
150
+ }
151
+
152
+ /** @returns the parsed payload, or undefined when the text is not one object. */
153
+ function parseJson(text: string): unknown {
154
+ try {
155
+ return JSON.parse(text) as unknown
156
+ } catch {
157
+ return undefined
158
+ }
159
+ }
160
+
161
+ /** @returns one suggested height as a whole number of CSS pixels, when usable. */
162
+ function heightOf(raw: unknown): number | undefined {
163
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) return undefined
164
+ return Math.ceil(raw)
165
+ }
166
+
167
+ /**
168
+ * Read the presentation payload a settled call carries (§35.10).
169
+ *
170
+ * The payload is the card's own record, so it is read only when it is one: a
171
+ * `html` that is not a string is no card at all, which keeps a malformed payload
172
+ * from becoming an empty frame. `state` outside the frozen pair reads as
173
+ * `settled` — a result-phase payload is a finished card by definition, and the
174
+ * `open` arm exists for a presenter that answers before its first event.
175
+ * @param meta - the result's `meta` value, carried verbatim.
176
+ * @returns the card, or undefined when this result carries no presentation.
177
+ */
178
+ export function readPresentation(meta: unknown): PresentCard | undefined {
179
+ if (typeof meta !== 'object' || meta === null) return undefined
180
+ const ui = (meta as { ui?: unknown }).ui
181
+ if (typeof ui !== 'object' || ui === null) return undefined
182
+ const record = ui as Record<string, unknown>
183
+ const html = record.html
184
+ if (typeof html !== 'string') return undefined
185
+ const title = record.title
186
+ const key = record.key
187
+ const height = heightOf(record.height)
188
+ return {
189
+ html,
190
+ state: record.state === 'open' ? 'open' : 'settled',
191
+ ...(typeof title === 'string' ? { title } : {}),
192
+ ...(height === undefined ? {} : { height }),
193
+ ...(typeof key === 'string' ? { key } : {}),
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Build the card a running call shows from its own arguments.
199
+ * @param block - the call material of the current stage.
200
+ * @returns the card, or undefined when the arguments carry no page.
201
+ */
202
+ function argumentCard(block: PresentBlock): PresentCard | undefined {
203
+ const html = fieldText(block.args, 'html') ?? fieldText(block.argsRaw, 'html')
204
+ if (html === undefined) return undefined
205
+ const title = fieldText(block.args, 'title') ?? fieldText(block.argsRaw, 'title')
206
+ const height = heightOf(fieldValue(block.args, 'height') ?? fieldValue(block.argsRaw, 'height'))
207
+ return {
208
+ html,
209
+ state: 'open',
210
+ ...(title === undefined ? {} : { title }),
211
+ ...(height === undefined ? {} : { height }),
212
+ }
213
+ }
214
+
215
+ /** @returns whether one document is within {@link UI_HTML_MAX_BYTES}. */
216
+ export function cardHtmlFits(html: string): boolean {
217
+ return new TextEncoder().encode(html).length <= UI_HTML_MAX_BYTES
218
+ }
219
+
220
+ /**
221
+ * Decide what the row draws at one stage of the call.
222
+ *
223
+ * The settled stage prefers `meta.ui`, because that payload is the presentation
224
+ * the host published and carries its ending. A result without the payload falls
225
+ * back to the arguments — and then the card is still over, so it reads
226
+ * `settled`: the stage decides that, not a field that is absent.
227
+ * @param phase - the stage the Tool slot published.
228
+ * @param block - the call material of that stage.
229
+ * @returns a card, a refusal, or the neutral line.
230
+ */
231
+ export function presentReadOf(phase: unknown, block: unknown): PresentRead {
232
+ if (typeof block !== 'object' || block === null) return { kind: 'empty' }
233
+ const material = block as PresentBlock
234
+ const card = phase === 'result'
235
+ ? readPresentation(material.meta) ?? settledFromArguments(material)
236
+ : argumentCard(material)
237
+ if (card === undefined) return { kind: 'empty' }
238
+ return cardHtmlFits(card.html) ? { kind: 'card', card } : { kind: 'oversize' }
239
+ }
240
+
241
+ /** @returns the argument page of a settled call, as a finished card. */
242
+ function settledFromArguments(material: PresentBlock): PresentCard | undefined {
243
+ const card = argumentCard(material)
244
+ return card === undefined ? undefined : { ...card, state: 'settled' }
245
+ }
246
+
247
+ /**
248
+ * Read the theme tokens off a computed style, skipping the ones it does not carry.
249
+ * @param style - the GUI root element's computed style.
250
+ * @returns the tokens, in {@link CARD_THEME_TOKENS} order.
251
+ */
252
+ export function cardThemeTokens(style: { getPropertyValue(name: string): string }): readonly ThemeToken[] {
253
+ const tokens: ThemeToken[] = []
254
+ for (const name of CARD_THEME_TOKENS) {
255
+ let value = ''
256
+ try {
257
+ value = style.getPropertyValue(name)
258
+ } catch {
259
+ value = ''
260
+ }
261
+ const trimmed = value.trim()
262
+ if (trimmed !== '') tokens.push([name, trimmed])
263
+ }
264
+ return tokens
265
+ }
266
+
267
+ /** @returns the `<style>` handing the theme tokens to a card's document. */
268
+ function themeStyle(tokens: readonly ThemeToken[]): string {
269
+ if (tokens.length === 0) return ''
270
+ const body = tokens.map(([name, value]) => `${name}:${value}`).join(';')
271
+ return `<style data-dsh-card-theme>:root{${body}}</style>`
272
+ }
273
+
274
+ /**
275
+ * The reporter a card's document runs to publish its own content height.
276
+ *
277
+ * The frame cannot be measured from the outside — the document is opaque and
278
+ * cross-origin — so the measurement has to be pushed out. It is deliberately the
279
+ * only code this row adds to a page: it reads a height and posts a number, and a
280
+ * page that removes it only loses the measurement, never the card.
281
+ * @param channel - the message type the parent listens for.
282
+ * @returns one script element as text.
283
+ */
284
+ function heightReporter(channel: string): string {
285
+ const parts = [
286
+ '<script data-dsh-card-frame>(function(){',
287
+ 'function post(){try{',
288
+ 'var d=document.documentElement,b=document.body;',
289
+ 'var h=Math.max(d?d.scrollHeight:0,b?b.scrollHeight:0);',
290
+ 'if(h>0){parent.postMessage({type:' + JSON.stringify(channel) + ',height:h},"*")}',
291
+ '}catch(e){}}',
292
+ 'window.addEventListener("load",post);',
293
+ 'document.addEventListener("DOMContentLoaded",post);',
294
+ 'try{if(typeof ResizeObserver==="function"){var ro=new ResizeObserver(post);',
295
+ 'if(document.documentElement)ro.observe(document.documentElement);',
296
+ 'if(document.body)ro.observe(document.body)}}catch(e){}',
297
+ 'post()})()</script>',
298
+ ]
299
+ return parts.join('')
300
+ }
301
+
302
+ /**
303
+ * Put one snippet inside an existing element rather than before the document.
304
+ * @param html - the card document.
305
+ * @param closingTag - the tag to insert ahead of, lower case.
306
+ * @param snippet - the markup to insert.
307
+ * @returns the document with the snippet inside it.
308
+ */
309
+ function injectBefore(html: string, closingTag: string, snippet: string): string {
310
+ if (snippet === '') return html
311
+ const at = html.toLowerCase().lastIndexOf(closingTag)
312
+ return at < 0 ? html + snippet : html.slice(0, at) + snippet + html.slice(at)
313
+ }
314
+
315
+ /**
316
+ * Build the document handed to a card's frame.
317
+ *
318
+ * The agent's page stays byte for byte what crossed; this only adds the theme
319
+ * variables its CSS may use and the height reporter. Insertion happens ahead of
320
+ * the closing tags rather than at the start of the string, because a snippet
321
+ * placed before `<!doctype html>` would put the document into quirks mode.
322
+ * @param html - the card document as the presenter wrote it.
323
+ * @param tokens - the theme tokens to hand the page.
324
+ * @param channel - the message type the reporter publishes on.
325
+ * @returns the frame document; the original page when it takes no injection.
326
+ */
327
+ export function frameDocument(html: string, tokens: readonly ThemeToken[], channel: string = FRAME_HEIGHT_CHANNEL): string {
328
+ const style = themeStyle(tokens)
329
+ const withTheme = style === '' ? html : injectBefore(html, '</head>', style)
330
+ return injectBefore(withTheme, '</body>', heightReporter(channel))
331
+ }
332
+
333
+ /** One message a card's frame sent the parent. */
334
+ export type FrameEvent =
335
+ | { readonly kind: 'height'; readonly height: number }
336
+ /** Anything else the page posted: an action this desktop never answers. */
337
+ | { readonly kind: 'interaction' }
338
+
339
+ /**
340
+ * Read one message a card's frame posted.
341
+ *
342
+ * Only the shape is read. The frame's origin is opaque, so the parent identifies
343
+ * the sender by the frame element it owns; what is left to decide here is what
344
+ * the payload means, and a page's own `{type, payload}` action means nothing
345
+ * beyond "the operator tried to act here".
346
+ * @param data - the message payload.
347
+ * @returns the event, or undefined when the message is not one this row reads.
348
+ */
349
+ export function frameEventOf(data: unknown): FrameEvent | undefined {
350
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) return undefined
351
+ const record = data as Record<string, unknown>
352
+ if (record.type === FRAME_HEIGHT_CHANNEL) {
353
+ const height = record.height
354
+ if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) return undefined
355
+ return { kind: 'height', height: Math.ceil(height) }
356
+ }
357
+ return typeof record.type === 'string' && record.type !== '' ? { kind: 'interaction' } : undefined
358
+ }
359
+
360
+ /**
361
+ * Hold a measured height inside the range a card may occupy.
362
+ * @param height - the content height the frame reported, in CSS pixels.
363
+ * @returns the height the card takes.
364
+ */
365
+ export function clampCardHeight(height: number): number {
366
+ if (!Number.isFinite(height)) return CARD_DEFAULT_HEIGHT
367
+ return Math.min(CARD_MAX_HEIGHT, Math.max(CARD_MIN_HEIGHT, Math.ceil(height)))
368
+ }