@termwright/protocol 0.2.0 → 0.3.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 (40) hide show
  1. package/README.md +213 -605
  2. package/dist/action-model-BP9Znu6L.d.ts +219 -0
  3. package/dist/action-model.d.ts +3 -0
  4. package/dist/action-model.js +15 -0
  5. package/dist/action-model.js.map +1 -0
  6. package/dist/capability-graph.d.ts +90 -0
  7. package/dist/capability-graph.js +43 -0
  8. package/dist/capability-graph.js.map +1 -0
  9. package/dist/chunk-B4VUTTUE.js +59 -0
  10. package/dist/chunk-B4VUTTUE.js.map +1 -0
  11. package/dist/chunk-CZK6NNP3.js +389 -0
  12. package/dist/chunk-CZK6NNP3.js.map +1 -0
  13. package/dist/chunk-ODOJRXL6.js +84 -0
  14. package/dist/chunk-ODOJRXL6.js.map +1 -0
  15. package/dist/chunk-PUXRCPGY.js +112 -0
  16. package/dist/chunk-PUXRCPGY.js.map +1 -0
  17. package/dist/chunk-VBLS6E6U.js +1109 -0
  18. package/dist/chunk-VBLS6E6U.js.map +1 -0
  19. package/dist/chunk-ZZIYHDJ4.js +202 -0
  20. package/dist/chunk-ZZIYHDJ4.js.map +1 -0
  21. package/dist/contract-CH9gmj2Y.d.ts +746 -0
  22. package/dist/contract.d.ts +2 -0
  23. package/dist/contract.js +21 -0
  24. package/dist/contract.js.map +1 -0
  25. package/dist/index.d.ts +82 -798
  26. package/dist/index.js +1087 -766
  27. package/dist/index.js.map +1 -1
  28. package/dist/run-events.d.ts +158 -0
  29. package/dist/run-events.js +27 -0
  30. package/dist/run-events.js.map +1 -0
  31. package/dist/run-journal.d.ts +55 -0
  32. package/dist/run-journal.js +10 -0
  33. package/dist/run-journal.js.map +1 -0
  34. package/dist/run-state.d.ts +38 -0
  35. package/dist/run-state.js +19 -0
  36. package/dist/run-state.js.map +1 -0
  37. package/dist/test-provider.d.ts +22 -0
  38. package/dist/test-provider.js +32 -0
  39. package/dist/test-provider.js.map +1 -0
  40. package/package.json +33 -5
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/env.ts","../src/errors.ts","../src/roles.ts","../src/limits.ts","../src/observation.ts","../src/geometry-capabilities.ts","../src/node-schema.ts","../src/probe/ir.ts","../src/node-keys.ts","../src/logs.ts","../src/framing.ts","../src/delta.ts","../src/validate.ts","../src/accesskit.ts","../src/probe/bounds.ts","../src/probe/validate.ts","../src/messages.ts","../src/marker.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\n\n/** Environment variable names injected by the driver before spawning the child. */\nexport const ENV_ENDPOINT = 'TERMWRIGHT_ENDPOINT';\nexport const ENV_TOKEN = 'TERMWRIGHT_TOKEN';\nexport const ENV_PROTOCOL = 'TERMWRIGHT_PROTOCOL';\n\n/** Current protocol major version. */\nexport const PROTOCOL_VERSION = 1 as const;\nexport const PROTOCOL_ID = 'termwright/1' as const;\n/** Qualified observation protocol. V1 remains exported for existing adapters. */\nexport const PROTOCOL_V2_ID = 'termwright/2' as const;\nexport type ProtocolId = typeof PROTOCOL_ID | typeof PROTOCOL_V2_ID;\nexport const SUPPORTED_PROTOCOL_IDS: readonly ProtocolId[] = [PROTOCOL_V2_ID, PROTOCOL_ID];\n\n/** Entropy behind a session token, in bytes (256 bits). */\nexport const TOKEN_BYTES = 32;\n\n/**\n * Mint a session token for `TERMWRIGHT_TOKEN`.\n *\n * **The token is an opaque UTF-8 string end to end.** Whatever lands in the\n * env var is what both sides feed to the HMAC as the key — the driver must not\n * decode it back to bytes, and an adapter must not re-encode it. Honouring\n * that is what keeps non-JS clients (Python, Go, Rust) interoperable, since\n * they only ever see the string.\n *\n * The encoding here (base64url, 43 characters) is therefore a convention, not\n * a constraint: it is compact, shell-safe, and free of `=` padding.\n *\n * @returns A fresh 256-bit token. Never log or embed it; it authenticates the\n * render markers.\n */\nexport function generateToken(): string {\n return randomBytes(TOKEN_BYTES).toString('base64url');\n}\n","/**\n * Typed protocol failures. Everything in this package fails closed: a hostile\n * or merely malformed input never produces a partially-trusted value, it\n * produces a {@link ProtocolViolation} (imperative APIs) or a structured\n * `{ ok: false }` result (validation APIs).\n */\n\n/** Machine-readable reason a value was rejected. */\nexport type ProtocolViolationCode =\n /** Declared frame length exceeds the negotiated ceiling. */\n | 'frame-oversized'\n /** Frame header/body is structurally impossible (zero length, bad JSON). */\n | 'frame-malformed'\n /** Frame body is not well-formed UTF-8. */\n | 'frame-encoding'\n /** Decoder already failed; it is poisoned and refuses further input. */\n | 'decoder-poisoned'\n /** Value is not representable as JSON (undefined, bigint, function, NaN…). */\n | 'dto-scalar'\n /** String contains unpaired surrogates. */\n | 'dto-string'\n /** Object graph is not a tree: the same object is reachable twice. */\n | 'dto-alias'\n /** Property is an accessor (getter/setter) rather than plain data. */\n | 'dto-accessor'\n /** Value carries symbol keys. */\n | 'dto-symbol'\n /** Value is a Proxy, or has a prototype other than Object/Array/null. */\n | 'dto-prototype'\n /** Array has holes or extra own properties. */\n | 'dto-sparse'\n /** Property name is reserved (`__proto__`, `constructor`, `prototype`). */\n | 'dto-key'\n /** Nesting exceeds the permitted depth. */\n | 'dto-depth'\n /** A marker argument is outside its permitted domain. */\n | 'marker-argument';\n\n/**\n * Thrown when untrusted input violates a protocol invariant.\n *\n * Never carries the offending value or the session token — only a code and a\n * short structural description safe to log.\n */\nexport class ProtocolViolation extends Error {\n /** Machine-readable reason. */\n readonly code: ProtocolViolationCode;\n\n constructor(code: ProtocolViolationCode, message: string) {\n super(message);\n this.name = 'ProtocolViolation';\n this.code = code;\n }\n}\n","/**\n * v1 semantic roles. ARIA-aligned; closed set. Unknown roles must be rejected\n * during validation — they never silently acquire behavior.\n */\nexport const SEMANTIC_ROLES = [\n 'application',\n 'region',\n 'dialog',\n 'alert',\n 'status',\n 'list',\n 'listitem',\n 'menu',\n 'menuitem',\n 'button',\n 'checkbox',\n 'radio',\n 'tab',\n 'textbox',\n 'heading',\n 'text',\n 'progressbar',\n 'separator',\n 'scrollbar',\n 'table',\n 'row',\n 'cell',\n 'generic',\n] as const;\n\nexport type SemanticRole = (typeof SEMANTIC_ROLES)[number];\n\n/** Descriptive action capabilities. Diagnostic/strategy hints, never callback endpoints. */\nexport const SEMANTIC_ACTIONS = [\n 'focus',\n 'activate',\n 'toggle',\n 'setValue',\n 'scroll',\n 'select',\n 'expand',\n] as const;\n\nexport type SemanticAction = (typeof SEMANTIC_ACTIONS)[number];\n","/**\n * Conservative defaults and absolute maxima. Callers may tighten defaults but\n * can never widen the absolute maxima.\n */\nexport interface ProtocolLimits {\n readonly maxFrameBytes: number;\n /**\n * Byte ceiling for one snapshot or probe frame.\n *\n * 2 MiB rather than 1: at the measured 217.5 B/node a full `maxNodes` tree\n * is 1 062 KiB before a single provenance byte, so the old default\n * contradicted the node ceiling it shipped with.\n */\n readonly maxSnapshotBytes: number;\n readonly maxNodes: number;\n readonly maxDepth: number;\n readonly maxStringBytes: number;\n readonly maxRelationTargets: number;\n readonly maxQueuedFrames: number;\n readonly maxPendingWaiters: number;\n readonly maxSessions: number;\n /** Byte ceiling for one serialised application log record. */\n readonly maxLogRecordBytes: number;\n /** Log records the driver buffers per session before evicting the oldest. */\n readonly maxLogQueue: number;\n}\n\nexport const DEFAULT_LIMITS: ProtocolLimits = Object.freeze({\n maxFrameBytes: 1 * 1024 * 1024,\n maxSnapshotBytes: 2 * 1024 * 1024,\n maxNodes: 5_000,\n maxDepth: 64,\n maxStringBytes: 16 * 1024,\n maxRelationTargets: 64,\n maxQueuedFrames: 32,\n maxPendingWaiters: 256,\n maxSessions: 16,\n maxLogRecordBytes: 32 * 1024,\n maxLogQueue: 1_000,\n});\n\nexport const ABSOLUTE_LIMITS: ProtocolLimits = Object.freeze({\n maxFrameBytes: 8 * 1024 * 1024,\n maxSnapshotBytes: 8 * 1024 * 1024,\n maxNodes: 50_000,\n maxDepth: 256,\n maxStringBytes: 256 * 1024,\n maxRelationTargets: 1_024,\n maxQueuedFrames: 256,\n maxPendingWaiters: 4_096,\n maxSessions: 128,\n maxLogRecordBytes: 256 * 1024,\n maxLogQueue: 10_000,\n});\n\n/** Default semantic negotiation window (ms) before a session settles as generic. */\nexport const DEFAULT_NEGOTIATION_MS = 250;\n","import type { Rect } from './tree.js';\n\n/** Why a fact could not be observed. Unknown is retryable; unsupported is not. */\nexport type ObservationUnknownReason =\n | 'not-reported'\n | 'temporary'\n | 'clip-unobservable'\n | 'legacy-unqualified';\n\nexport type ObservationAbsentReason = 'detached' | 'not-displayed' | 'not-laid-out';\n\nexport type ObservationUnsupportedReason =\n | 'capability'\n | 'framework-unobservable'\n | 'not-negotiated';\n\nexport type ObservationEvidence =\n | 'adapter'\n | 'probe'\n | 'terminal-grid'\n | 'viewport-clip'\n | 'paint-order'\n | 'hit-grid'\n | 'legacy-v1';\n\n/**\n * A fact with its epistemic state preserved.\n *\n * Consumers must never coerce `unknown`/`unsupported` to false, nor absence to\n * an empty value. That rule prevents assertions from passing because a probe\n * simply could not observe the requested property.\n */\nexport type Observation<T> =\n | { readonly status: 'known'; readonly value: T; readonly evidence: ObservationEvidence }\n | { readonly status: 'absent'; readonly reason: ObservationAbsentReason }\n | { readonly status: 'unknown'; readonly reason: ObservationUnknownReason }\n | {\n readonly status: 'unsupported';\n readonly capability: string;\n readonly reason: ObservationUnsupportedReason;\n };\n\n/** Atomic identity of the screen/tree pair used for an observation. */\nexport interface ObservationStamp {\n readonly sessionId: string;\n readonly screenRevision: number;\n readonly semanticRevision: number | null;\n}\n\nexport type CoordinateSpace = 'viewport-cells' | 'framework-local-cells';\n\nexport interface LocatorGeometry {\n readonly stamp: ObservationStamp;\n readonly coordinateSpace: Observation<CoordinateSpace>;\n readonly intendedRect: Observation<Rect>;\n readonly visibleRect: Observation<Rect>;\n}\n\nexport interface ViewportIntersection {\n /** Half-open intersection in viewport cell coordinates. */\n readonly rect: Rect;\n /** Intersection area / intended area. Zero-area intended rect has ratio 0. */\n readonly ratio: number;\n readonly fullyInside: boolean;\n}\n\nexport interface LocatorVisibility {\n readonly stamp: ObservationStamp;\n readonly attached: Observation<boolean>;\n readonly displayed: Observation<boolean>;\n readonly viewport: Observation<ViewportIntersection>;\n readonly offscreen: Observation<boolean>;\n}\n\nexport interface CellPoint {\n readonly row: number;\n readonly column: number;\n}\n\nexport interface PointerHitTest {\n readonly stamp: ObservationStamp;\n readonly point: Observation<CellPoint>;\n readonly receivesEvents: Observation<boolean>;\n /** Ref of the actual recipient, when the producer can identify it. */\n readonly recipient: Observation<string>;\n}\n\nexport type SpatialRelation =\n | 'contains'\n | 'inside'\n | 'overlaps'\n | 'left-of'\n | 'right-of'\n | 'above'\n | 'below'\n | 'aligned-left'\n | 'aligned-right'\n | 'aligned-top'\n | 'aligned-bottom'\n | 'adjacent-horizontal'\n | 'adjacent-vertical';\n\n/** Correct half-open rectangle intersection. Touching edges do not overlap. */\nexport function intersectRects(a: Rect, b: Rect): Rect {\n const row = Math.max(a.row, b.row);\n const column = Math.max(a.column, b.column);\n return {\n row,\n column,\n width: Math.max(0, Math.min(a.column + a.width, b.column + b.width) - column),\n height: Math.max(0, Math.min(a.row + a.height, b.row + b.height) - row),\n };\n}\n\nexport function rectArea(rect: Rect): number {\n return Math.max(0, rect.width) * Math.max(0, rect.height);\n}\n\nexport function viewportIntersection(rect: Rect, columns: number, rows: number): ViewportIntersection {\n const intersection = intersectRects(rect, { row: 0, column: 0, width: columns, height: rows });\n const area = rectArea(rect);\n const visible = rectArea(intersection);\n return Object.freeze({\n rect: Object.freeze(intersection),\n ratio: area === 0 ? 0 : visible / area,\n fullyInside: area > 0 && visible === area,\n });\n}\n\nexport function spatialRelation(a: Rect, relation: SpatialRelation, b: Rect): boolean {\n const aBottom = a.row + a.height;\n const bBottom = b.row + b.height;\n const aRight = a.column + a.width;\n const bRight = b.column + b.width;\n switch (relation) {\n case 'contains': return a.row <= b.row && a.column <= b.column && aBottom >= bBottom && aRight >= bRight;\n case 'inside': return spatialRelation(b, 'contains', a);\n case 'overlaps': return rectArea(intersectRects(a, b)) > 0;\n case 'left-of': return aRight <= b.column;\n case 'right-of': return bRight <= a.column;\n case 'above': return aBottom <= b.row;\n case 'below': return bBottom <= a.row;\n case 'aligned-left': return a.column === b.column;\n case 'aligned-right': return aRight === bRight;\n case 'aligned-top': return a.row === b.row;\n case 'aligned-bottom': return aBottom === bBottom;\n case 'adjacent-horizontal': return (aRight === b.column || bRight === a.column) && Math.max(a.row, b.row) < Math.min(aBottom, bBottom);\n case 'adjacent-vertical': return (aBottom === b.row || bBottom === a.row) && Math.max(a.column, b.column) < Math.min(aRight, bRight);\n }\n}\n","/** Machine-readable source of truth for geometry/visibility support. */\nexport interface FrameworkObservationCapabilities {\n readonly framework: 'generic' | 'textual' | 'opentui' | 'ink' | 'tview' | 'ratatui' | 'charm';\n readonly identity: 'stable' | 'frame-local' | 'none';\n readonly attached: 'supported';\n readonly displayed: 'supported' | 'conditional' | 'unsupported';\n readonly intendedRect: 'supported' | 'conditional' | 'unsupported';\n readonly visibleRect: 'supported' | 'conditional' | 'unsupported';\n readonly hitTest: 'supported' | 'conditional' | 'unsupported';\n readonly reason: string;\n}\n\nexport type CapabilityAvailability = 'supported' | 'conditional' | 'unsupported';\nexport type GeometryOperation =\n | 'keyboard-actions'\n | 'pointer-actions'\n | 'toBeAttached'\n | 'toBeDetached'\n | 'toBeDisplayed'\n | 'toBeHidden'\n | 'toBeVisible'\n | 'toBeOffscreen'\n | 'toBeInViewport'\n | 'toReceivePointerEvents'\n | 'toHaveBounds'\n | 'toHaveSpatialRelation'\n | 'cellSnapshot';\n\nexport interface FrameworkOperationCapability {\n readonly framework: FrameworkObservationCapabilities['framework'];\n readonly operation: GeometryOperation;\n readonly availability: CapabilityAvailability;\n readonly reason: string;\n}\n\nexport const FRAMEWORK_OBSERVATION_CAPABILITIES: readonly FrameworkObservationCapabilities[] = Object.freeze([\n { framework: 'generic', identity: 'none', attached: 'supported', displayed: 'supported', intendedRect: 'supported', visibleRect: 'supported', hitTest: 'conditional', reason: 'Grid matches are physical cells; pointer delivery still requires terminal mouse mode.' },\n { framework: 'textual', identity: 'stable', attached: 'supported', displayed: 'supported', intendedRect: 'supported', visibleRect: 'supported', hitTest: 'supported', reason: 'The compositor exposes intended/clipped regions and Screen.get_widget_at(), the same fresh-pointer routing lookup.' },\n { framework: 'opentui', identity: 'stable', attached: 'supported', displayed: 'supported', intendedRect: 'supported', visibleRect: 'unsupported', hitTest: 'supported', reason: 'The committed native hit grid proves fresh-pointer ownership; the renderer exposes no per-node visual clip rectangle.' },\n { framework: 'ink', identity: 'stable', attached: 'supported', displayed: 'supported', intendedRect: 'conditional', visibleRect: 'unsupported', hitTest: 'unsupported', reason: 'Intended bounds are conditional on a viewport-stable live region; Ink exposes neither clipping nor pointer ownership.' },\n { framework: 'tview', identity: 'stable', attached: 'supported', displayed: 'supported', intendedRect: 'supported', visibleRect: 'conditional', hitTest: 'unsupported', reason: 'Primitive rectangles do not identify the recipient after overlap.' },\n { framework: 'ratatui', identity: 'frame-local', attached: 'supported', displayed: 'conditional', intendedRect: 'supported', visibleRect: 'conditional', hitTest: 'unsupported', reason: 'Render areas are frame-local and buffer writes do not preserve widget ownership.' },\n { framework: 'charm', identity: 'frame-local', attached: 'supported', displayed: 'conditional', intendedRect: 'unsupported', visibleRect: 'unsupported', hitTest: 'unsupported', reason: 'Bubble Tea hands over a rendered string without attributable widget geometry.' },\n]);\n\nexport function frameworkObservationCapabilities(framework: string): FrameworkObservationCapabilities | undefined {\n return FRAMEWORK_OBSERVATION_CAPABILITIES.find((entry) => entry.framework === framework);\n}\n\nconst weakest = (...values: CapabilityAvailability[]): CapabilityAvailability =>\n values.includes('unsupported') ? 'unsupported' : values.includes('conditional') ? 'conditional' : 'supported';\n\n/**\n * Normative operation matrix, derived from the fact registry. Documentation\n * validates against this export; adapters cannot gain an assertion merely by\n * changing prose.\n */\nexport const FRAMEWORK_OPERATION_CAPABILITIES: readonly FrameworkOperationCapability[] = Object.freeze(\n FRAMEWORK_OBSERVATION_CAPABILITIES.flatMap((row): FrameworkOperationCapability[] => {\n const visibility = weakest(row.displayed, row.visibleRect);\n const viewport = weakest(row.intendedRect, row.visibleRect);\n const reason = row.reason;\n return [\n { framework: row.framework, operation: 'keyboard-actions', availability: 'supported', reason: 'Keyboard input is sent through the PTY and does not require geometry.' },\n {\n framework: row.framework,\n operation: 'pointer-actions',\n availability: row.hitTest === 'unsupported' ? 'unsupported' : 'conditional',\n reason:\n row.hitTest === 'unsupported'\n ? reason\n : 'Requires an exact hit recipient and terminal mouse reporting enabled by the application.',\n },\n { framework: row.framework, operation: 'toBeAttached', availability: 'supported', reason: 'Tree membership is observed directly.' },\n { framework: row.framework, operation: 'toBeDetached', availability: 'supported', reason: 'Tree absence is observed directly without coercing missing layout facts.' },\n { framework: row.framework, operation: 'toBeDisplayed', availability: row.displayed, reason },\n { framework: row.framework, operation: 'toBeHidden', availability: row.displayed, reason },\n { framework: row.framework, operation: 'toBeVisible', availability: visibility, reason },\n { framework: row.framework, operation: 'toBeOffscreen', availability: viewport, reason },\n { framework: row.framework, operation: 'toBeInViewport', availability: viewport, reason },\n { framework: row.framework, operation: 'toReceivePointerEvents', availability: row.hitTest, reason },\n { framework: row.framework, operation: 'toHaveBounds', availability: row.intendedRect, reason },\n { framework: row.framework, operation: 'toHaveSpatialRelation', availability: row.intendedRect, reason },\n { framework: row.framework, operation: 'cellSnapshot', availability: row.visibleRect, reason },\n ];\n }),\n);\n","/**\n * Shared zod schemas for tree data. **Internal**: not re-exported from\n * `index.ts`.\n *\n * Snapshots and tree deltas describe the same nodes, so they must agree on\n * what a node is down to the last byte bound. Keeping one definition here is\n * what stops a delta from accepting a node a snapshot would reject.\n *\n * Schemas depend on the active limits, so they are built per limits object and\n * memoised. Limits are frozen singletons in practice, which keeps schema\n * construction off the per-message path.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport type { ProtocolLimits } from './limits.js';\nimport type { SemanticExtendedValue } from './tree.js';\nimport { SEMANTIC_ACTIONS, SEMANTIC_ROLES } from './roles.js';\nimport { PROVENANCE_SOURCES } from './probe/ir.js';\n\nexport function safeInt(): z.ZodType<number> {\n return z.number().refine(Number.isSafeInteger, 'expected a safe integer');\n}\n\nexport function nonNegativeInt(): z.ZodType<number> {\n return z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\n}\n\nexport function positiveInt(): z.ZodType<number> {\n return z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n}\n\nexport function boundedString(maxStringBytes: number): z.ZodType<string> {\n return z\n .string()\n .refine(\n (s) => Buffer.byteLength(s, 'utf8') <= maxStringBytes,\n `expected at most ${maxStringBytes} UTF-8 bytes`,\n );\n}\n\n/** The schema family for one set of limits. */\nexport interface TreeSchemas {\n readonly text: z.ZodType<string>;\n readonly node: z.ZodType;\n readonly cursor: z.ZodType;\n readonly snapshot: z.ZodType;\n readonly snapshotV1: z.ZodType;\n readonly snapshotV2: z.ZodType;\n /** Field names of `SemanticNode`, read off the schema itself. */\n readonly nodeKeys: readonly string[];\n /** Field names of `SemanticState`, read off the schema itself. */\n readonly stateKeys: readonly string[];\n}\n\nconst cache = new WeakMap<ProtocolLimits, TreeSchemas>();\n\nfunction build(limits: ProtocolLimits): TreeSchemas {\n const text = boundedString(limits.maxStringBytes);\n const relations = z.array(text).max(limits.maxRelationTargets);\n\n const rect = z.strictObject({\n row: safeInt(),\n column: safeInt(),\n width: nonNegativeInt(),\n height: nonNegativeInt(),\n });\n\n const observation = <T extends z.ZodType>(value: T): z.ZodType =>\n z.discriminatedUnion('status', [\n z.strictObject({ status: z.literal('known'), value, evidence: z.enum(['adapter', 'probe', 'terminal-grid', 'viewport-clip', 'paint-order', 'hit-grid', 'legacy-v1']) }),\n z.strictObject({ status: z.literal('absent'), reason: z.enum(['detached', 'not-displayed', 'not-laid-out']) }),\n z.strictObject({ status: z.literal('unknown'), reason: z.enum(['not-reported', 'temporary', 'clip-unobservable', 'legacy-unqualified']) }),\n z.strictObject({ status: z.literal('unsupported'), capability: text, reason: z.enum(['capability', 'framework-unobservable', 'not-negotiated']) }),\n ]);\n\n const state = z.strictObject({\n disabled: z.boolean().optional(),\n focused: z.boolean().optional(),\n selected: z.boolean().optional(),\n checked: z.union([z.boolean(), z.literal('mixed')]).optional(),\n expanded: z.boolean().optional(),\n modal: z.boolean().optional(),\n busy: z.boolean().optional(),\n hidden: z.boolean().optional(),\n offscreen: z.boolean().optional(),\n readonly: z.boolean().optional(),\n multiline: z.boolean().optional(),\n orientation: z.union([z.literal('horizontal'), z.literal('vertical')]).optional(),\n level: positiveInt().optional(),\n positionInSet: positiveInt().optional(),\n setSize: nonNegativeInt().optional(),\n scrollOffset: nonNegativeInt().optional(),\n scrollExtent: nonNegativeInt().optional(),\n });\n\n const textRange = z.strictObject({\n startOffset: nonNegativeInt(),\n endOffset: nonNegativeInt(),\n rect,\n });\n\n const extendedValue: z.ZodType<SemanticExtendedValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z.number().finite().refine(\n (value) => Math.abs(value) <= Number.MAX_SAFE_INTEGER,\n 'expected a finite JSON number in the safe range',\n ),\n text,\n z.array(extendedValue).max(limits.maxRelationTargets),\n z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n ),\n ]),\n );\n const extended = z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n );\n\n const nodeFields = {\n id: text.refine((s) => s.length > 0, 'node id must not be empty'),\n parentId: text.optional(),\n role: z.enum(SEMANTIC_ROLES),\n name: text,\n description: text.optional(),\n value: text.optional(),\n bounds: rect.optional(),\n state: state.optional(),\n extended: extended.optional(),\n actions: z.array(z.enum(SEMANTIC_ACTIONS)).max(SEMANTIC_ACTIONS.length).optional(),\n labelledBy: relations.optional(),\n describedBy: relations.optional(),\n textRanges: z.array(textRange).max(limits.maxRelationTargets).optional(),\n testId: text.optional(),\n frameworkType: text.optional(),\n occlusion: z.enum(['known', 'unknown']).optional(),\n p: z.enum(PROVENANCE_SOURCES).optional(),\n px: z.record(text, z.enum(PROVENANCE_SOURCES)).optional(),\n } as const;\n const node = z.strictObject(nodeFields);\n const geometry = z.strictObject({\n displayed: observation(z.boolean()),\n intendedRect: observation(rect),\n visibleRect: observation(rect),\n });\n const nodeV2 = z.strictObject({\n ...nodeFields,\n bounds: z.never().optional(),\n occlusion: z.never().optional(),\n geometry,\n });\n\n const cursor = z.strictObject({\n row: nonNegativeInt(),\n column: nonNegativeInt(),\n visible: z.boolean(),\n shape: z.union([z.literal('block'), z.literal('underline'), z.literal('bar')]).optional(),\n });\n\n const snapshotV1 = z.strictObject({\n v: z.literal(1),\n sessionId: text.refine((s) => s.length > 0, 'sessionId must not be empty'),\n revision: positiveInt(),\n columns: positiveInt(),\n rows: positiveInt(),\n cursor: cursor.optional(),\n rootIds: z.array(text).max(limits.maxNodes),\n nodes: z.array(node).max(limits.maxNodes),\n });\n const hitRun = z.strictObject({\n rect: z.strictObject({\n row: nonNegativeInt(),\n column: nonNegativeInt(),\n width: positiveInt(),\n height: z.literal(1),\n }),\n recipientId: text,\n });\n const hitGrid = z.strictObject({\n // Canonical row runs make ambiguity validation linear and keep hostile\n // snapshots from forcing an O(n²) rectangle-overlap check.\n regions: z.array(hitRun).max(limits.maxNodes).superRefine((regions, ctx) => {\n let previous: (typeof regions)[number] | undefined;\n for (let index = 0; index < regions.length; index += 1) {\n const current = regions[index]!;\n if (\n previous !== undefined &&\n (current.rect.row < previous.rect.row ||\n (current.rect.row === previous.rect.row &&\n current.rect.column < previous.rect.column + previous.rect.width))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: [index, 'rect'],\n message: 'hit regions must be non-overlapping row-major runs',\n });\n return;\n }\n previous = current;\n }\n }),\n });\n const snapshotV2 = z.strictObject({\n v: z.literal(2),\n sessionId: text.refine((s) => s.length > 0, 'sessionId must not be empty'),\n revision: positiveInt(),\n columns: positiveInt(),\n rows: positiveInt(),\n cursor: cursor.optional(),\n rootIds: z.array(text).max(limits.maxNodes),\n nodes: z.array(nodeV2).max(limits.maxNodes),\n coordinateSpace: observation(z.enum(['viewport-cells', 'framework-local-cells'])),\n hitGrid: observation(hitGrid),\n });\n const snapshot = z.discriminatedUnion('v', [snapshotV1, snapshotV2]);\n\n return {\n text,\n node,\n cursor,\n snapshot,\n snapshotV1,\n snapshotV2,\n nodeKeys: Object.freeze(Object.keys(node.shape)),\n stateKeys: Object.freeze(Object.keys(state.shape)),\n };\n}\n\n/** Memoised schema family for the given limits. */\nexport function treeSchemas(limits: ProtocolLimits): TreeSchemas {\n const cached = cache.get(limits);\n if (cached !== undefined) return cached;\n const built = build(limits);\n cache.set(limits, built);\n return built;\n}\n","/**\n * Probe IR — what an instrumented process **observed**, not what it means.\n *\n * A probe reports facts; a recognizer turns them into the semantic tree. The\n * split exists because the six frameworks disagree about what is even knowable,\n * and collapsing that disagreement early is how a tree ends up asserting things\n * no framework ever said.\n *\n * Three rules shape every type here, each forced by the Phase 0 audits:\n *\n * 1. **Never fabricate identity.** Immediate-mode frameworks have none, and a\n * synthesised ordinal presented as a handle is worse than no handle: a test\n * written against it fails later and looks flaky rather than wrong. Identity\n * is therefore a typed capability with `frame-local` as a first-class value.\n * 2. **Intent is not ownership.** The rectangle a widget was drawn *into* is not\n * the cells it ended up owning; later writes win and no framework records\n * who painted what. The two are separate fields, and only one framework\n * computes the second.\n * 3. **Absent and unobservable are different facts.** A state a framework does\n * not expose is not a state that is off. The IR says which is which, rather\n * than letting `undefined` mean both.\n *\n * Naming note: the words `region` and `area` are avoided throughout. Each\n * carries at least three conflicting meanings across the audited frameworks,\n * and an IR that reuses them inherits every one of those ambiguities.\n */\n\n/**\n * How an object's identity behaves across frames.\n *\n * `frame-local` is a legitimate answer, not a degraded one: in immediate mode\n * the widget is consumed by the render and nothing upstream survives to be\n * named again. A consumer must not correlate `frame-local` values between\n * frames.\n */\nexport type ProbeIdentityKind = 'stable' | 'frame-local';\n\n/** An object's identity, tagged with what it is worth. */\nexport interface ProbeIdentity {\n readonly kind: ProbeIdentityKind;\n /** Unique within its frame; unique across the session only when `stable`. */\n readonly value: string;\n}\n\n/**\n * A rectangle in terminal cells.\n *\n * Deliberately not called a region or an area: `row`/`column` are absolute\n * cell coordinates, and negative origins are legal because a widget may be\n * partly scrolled off.\n */\nexport interface ProbeRect {\n readonly row: number;\n readonly column: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Where an object was drawn.\n *\n * `intendedRect` is where it *asked* to draw. It is a statement of intent, not\n * a claim on cells: frameworks do not clip it, do not validate it against the\n * viewport, and a later write silently wins. For overlapping UIs — popups,\n * modals, shadows — it is not where the object ended up.\n *\n * `visibleRect` is the intersection with the clip imposed by ancestors, which\n * is the closest any framework gets to \"what the user can see\". Only one of\n * the six computes it; everywhere else it is absent, and inferring it from\n * `intendedRect` would be inventing a fact.\n */\nexport interface ProbeGeometry {\n readonly intendedRect?: ProbeRect;\n readonly visibleRect?: ProbeRect;\n}\n\n/** Scroll position, in cells, of a scrollable object's viewport. */\nexport interface ProbeScroll {\n readonly row: number;\n readonly column: number;\n}\n\n/** Total scrollable extent, in cells. Absent where a framework cannot report it. */\nexport interface ProbeExtent {\n readonly rows: number;\n readonly columns: number;\n}\n\n/**\n * State a probe read directly from the framework.\n *\n * Every field is optional, and absence means \"not reported by this probe\".\n * A field the framework is *known* not to expose belongs in\n * {@link ProbeObject.unobservable} instead, so a consumer can tell \"off\" from\n * \"unknowable\".\n *\n * The three selection facts have separate names on purpose. An accessibility\n * `selected` flag, a highlighted collection index and a selected text range\n * are not interchangeable, even though frameworks often call all three\n * \"selection\".\n */\nexport interface ProbeObservedState {\n readonly focused?: boolean;\n readonly disabled?: boolean;\n readonly checked?: boolean | 'mixed';\n readonly expanded?: boolean;\n readonly readonly?: boolean;\n readonly selected?: boolean;\n readonly busy?: boolean;\n readonly multiline?: boolean;\n /**\n * Whether the framework's own display flag is on. Distinct from being\n * scrolled out of view, which shows up as an empty `visibleRect`.\n */\n readonly displayed?: boolean;\n /** Contents of a value-bearing widget. `''` means empty, not absent. */\n readonly value?: string;\n /** Highlighted item in a collection, by index. Not a text selection. */\n readonly selectedIndex?: number;\n /** Selected text range within this object. Not an item selection. */\n readonly textSelection?: { readonly start: number; readonly end: number };\n readonly scroll?: ProbeScroll;\n readonly scrollExtent?: ProbeExtent;\n}\n\n/** Field names a probe can declare unobservable. */\nexport const PROBE_UNOBSERVABLE_FIELDS = [\n 'focused',\n 'disabled',\n 'checked',\n 'expanded',\n 'readonly',\n 'selected',\n 'busy',\n 'multiline',\n 'displayed',\n 'value',\n 'selectedIndex',\n 'textSelection',\n 'scroll',\n 'scrollExtent',\n 'intendedRect',\n 'visibleRect',\n 'paintOrder',\n 'text',\n 'parent',\n] as const;\n\nexport type ProbeUnobservableField = (typeof PROBE_UNOBSERVABLE_FIELDS)[number];\n\n/**\n * Author-supplied annotations carried verbatim.\n *\n * The probe does not interpret these — a recognizer does, at the top of the\n * merge precedence. `role` is deliberately a free string here: it is whatever\n * the author wrote, and validating it against the closed role set is the\n * recognizer's job, which can then report a bad annotation instead of silently\n * dropping it.\n */\nexport interface ProbeAccessibilityHints {\n /** Framework-native accessibility role, in the framework's vocabulary. */\n readonly role?: string;\n readonly name?: string;\n readonly description?: string;\n}\n\nexport interface ProbeAnnotations {\n readonly role?: string;\n readonly name?: string;\n readonly testId?: string;\n readonly description?: string;\n /** Application-domain JSON state, kept outside the portable state flags. */\n readonly extended?: import('../tree.js').SemanticExtendedState;\n /** Descriptive action intent; never callbacks or a second input channel. */\n readonly actions?: readonly import('../roles.js').SemanticAction[];\n /** Probe identity values of author-declared labelling relationships. */\n readonly labelledBy?: readonly string[];\n /** Probe identity values of author-declared description relationships. */\n readonly describedBy?: readonly string[];\n}\n\n/**\n * One object a probe observed in a frame.\n *\n * `frameworkType` is required. It is the framework's own name for the thing —\n * a class name, a constructor name, a widget type — and it is what keeps an\n * unrecognised widget alive as a `generic` node instead of being dropped. Its\n * quality varies enormously (Textual gives a full class ancestry; Ink gives one\n * of four host-element names), so a recognizer must treat it as a hint, not a\n * classification.\n */\nexport interface ProbeObject {\n readonly identity: ProbeIdentity;\n readonly frameworkType: string;\n /** Parent's identity value; absent for a root. */\n readonly parent?: string;\n readonly geometry?: ProbeGeometry;\n readonly state?: ProbeObservedState;\n /** Text the object itself carries, not its descendants'. */\n readonly text?: string;\n /** Accessibility metadata retained by the framework itself, not author SDK data. */\n readonly accessibility?: ProbeAccessibilityHints;\n readonly annotations?: ProbeAnnotations;\n /**\n * Where this object sits in paint order: higher was painted later, and\n * therefore on top.\n *\n * Available in three of the six frameworks (a compositor hit-test, a z-order\n * child list, a paint-order key) and absent in the rest. It is the only fact\n * that makes \"is my target actually the thing at this cell\" answerable\n * without inventing cell ownership, which no framework records.\n */\n readonly paintOrder?: number;\n /**\n * Facts this framework cannot report for this object. Distinct from a field\n * simply being absent, which means the probe did not report it this time.\n */\n readonly unobservable?: readonly ProbeUnobservableField[];\n}\n\n/**\n * A render or layout call the probe intercepted.\n *\n * Only some frameworks expose a call stream, and in immediate mode it is the\n * *only* structure that exists — there is no tree to walk, just an ordered list\n * of \"this type was drawn into this rectangle\". `ordinal` is the position in\n * that stream and is meaningful only within its frame.\n */\nexport interface ProbeOperation {\n readonly kind: 'render' | 'layout';\n readonly ordinal: number;\n /** Identity of the object this call concerned, when the probe can attribute it. */\n readonly target?: ProbeIdentity;\n readonly frameworkType?: string;\n readonly intendedRect?: ProbeRect;\n}\n\n/**\n * One observed frame.\n *\n * `objects` may be empty and `operations` may carry everything: that is what an\n * immediate-mode frame looks like, and a flat op list is a legal degenerate\n * tree rather than an error.\n */\nexport interface ProbeFrame {\n /** Monotonic within the session. Every framework has exactly one of these. */\n readonly frame: number;\n readonly objects: readonly ProbeObject[];\n readonly operations?: readonly ProbeOperation[];\n}\n\n/** Optional abilities a probe declares at handshake time. */\nexport const PROBE_CAPABILITIES = [\n /** Identities survive across frames and may be correlated. */\n 'stable-identity',\n /** `visibleRect` is computed, not guessed. */\n 'visible-rect',\n /** A render/layout call stream is reported. */\n 'operations',\n /** Author annotations are readable. */\n 'annotations',\n /** A frame-start signal is emitted. Absent for most frameworks — see below. */\n 'frame-begin',\n /** `paintOrder` is reported, so occlusion can be reasoned about. */\n 'paint-order',\n] as const;\n\nexport type ProbeCapability = (typeof PROBE_CAPABILITIES)[number];\n\n/**\n * What a probe says about itself when it attaches.\n *\n * @remarks\n * `frame-begin` is optional for a reason that is easy to get wrong. No audited\n * framework offers a hook guaranteed to fire before every frame: one lets a\n * pre-draw hook veto the frame entirely (so the post-draw hook never runs), one\n * exposes only a post-frame hook, and one decouples submission from the flush\n * with a ticker. A consumer must therefore never read \"no frame-begin\" as \"no\n * frame in progress\" — doing so turns four of the six frameworks into a hang\n * rather than an error.\n */\nexport interface ProbeInfo {\n /** Framework name, e.g. `ink`, `textual`, `ratatui`. */\n readonly framework: string;\n readonly frameworkVersion?: string;\n /** Version of the probe itself, so a mismatch is diagnosable. */\n readonly probeVersion: string;\n /** The best identity this probe can offer for any object. */\n readonly identityKind: ProbeIdentityKind;\n readonly capabilities: readonly ProbeCapability[];\n}\n\n/**\n * Where a semantic fact came from.\n *\n * Ranked: an annotation is what the author said, a recognizer is what our rules\n * concluded, `framework` is what the framework itself reported, `correlation`\n * is what matching across sources implied, and `heuristic` is a guess that\n * happened to be useful. The merge precedence follows this order, except that\n * physical facts — bounds, focus, visibility, cells — are never casually\n * overridden by an annotation: an author may name a thing, but may not declare\n * where it is on screen.\n */\nexport const PROVENANCE_SOURCES = [\n 'annotation',\n 'recognizer',\n 'framework',\n 'correlation',\n 'heuristic',\n] as const;\n\nexport type ProvenanceSource = (typeof PROVENANCE_SOURCES)[number];\n","/**\n * The field names of a semantic node and of its state, as data.\n *\n * These exist because a schema is invisible to anything that is not TypeScript.\n * The cross-language vector generator and the client comparators cannot see a\n * zod shape, so until now they carried hand-maintained field lists — and three\n * fields (`frameworkType`, `occlusion`, `p`/`px`) reached three clients late\n * precisely because nobody remembered to extend those lists. A generator that\n * reads this array cannot forget a field the schema already has.\n *\n * Derived from the schema rather than written out, so there is one source of\n * truth and not a third copy to drift. The list does not vary with limits: only\n * the bounds inside the fields do.\n */\n\nimport { DEFAULT_LIMITS } from './limits.js';\nimport { treeSchemas } from './node-schema.js';\nimport type { SemanticNode, SemanticState } from './tree.js';\n\nconst schemas = treeSchemas(DEFAULT_LIMITS);\n\n/**\n * Every field name on `SemanticNode`.\n *\n * The `keyof` annotation is the load-bearing part: a field present in the\n * schema but missing from the interface fails to compile here, which is the\n * half of the drift a runtime test cannot catch early.\n */\nexport const SEMANTIC_NODE_KEYS: readonly (Exclude<keyof SemanticNode, 'geometry'>)[] = Object.freeze(\n schemas.nodeKeys as readonly (Exclude<keyof SemanticNode, 'geometry'>)[],\n);\n\n/** Every field name on `SemanticState`. */\nexport const SEMANTIC_STATE_KEYS: readonly (keyof SemanticState)[] = Object.freeze(\n schemas.stateKeys as readonly (keyof SemanticState)[],\n);\n","/**\n * Application log records carried over the semantic channel.\n *\n * A TUI cannot print diagnostics to the screen without corrupting the render,\n * so applications write them to an internal logger instead. The `logs`\n * capability lets an instrumented adapter forward those records to the driver,\n * where they become assertable test state rather than invisible side effects.\n *\n * Records are bounded exactly like snapshots: projected into frozen plain DTOs\n * before retention, checked against a byte ceiling, and rejected wholesale on\n * any violation. A misbehaving logger degrades into dropped records, never\n * into unbounded driver memory.\n */\n\nimport { Buffer } from 'node:buffer';\nimport type { ProtocolLimits } from './limits.js';\nimport type { ValidationErrorCode } from './validate.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\n\n/**\n * Severity ladder, ordered from least to most severe. Deliberately the\n * intersection of the ladders used by pino, winston, consola, Python\n * `logging`, Go `slog` and Rust `tracing`, so every bridge maps onto it\n * without inventing a level.\n */\nexport const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const;\n\nexport type LogLevel = (typeof LOG_LEVELS)[number];\n\n/** Numeric severity, useful for threshold comparisons. Higher is more severe. */\nexport const LOG_LEVEL_SEVERITY: Readonly<Record<LogLevel, number>> = Object.freeze({\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n});\n\n/**\n * Structured attribute value. Scalars only, by design: nested objects make\n * record size unbounded and depth-dependent, and every bridge already has to\n * flatten for its own transport. `@termwright/logs` does the flattening.\n */\nexport type LogAttrValue = string | number | boolean | null;\n\n/** Maximum number of attribute keys on one record. */\nexport const MAX_LOG_ATTRS = 64;\n\n/**\n * One application log record.\n *\n * @remarks\n * `ts` is **Unix epoch milliseconds**, not session-relative: the adapter has no\n * reliable view of when the driver considers the session to have started, so\n * the only clock both sides can agree on without negotiation is the wall\n * clock. The driver rebases it onto the session/cast timeline.\n */\nexport interface LogRecord {\n /** Unix epoch milliseconds when the record was produced. */\n readonly ts: number;\n readonly level: LogLevel;\n /** Human-readable message, already formatted by the source logger. */\n readonly message: string;\n /** Flat structured context. Nested values are flattened by the bridge. */\n readonly attrs?: Readonly<Record<string, LogAttrValue>>;\n /** Logger/channel name, e.g. `http` or `db.pool`. */\n readonly logger?: string;\n /**\n * Per-session counter assigned by the adapter, **strictly increasing**: every\n * record carries a `seq` greater than the previous one on the same session.\n *\n * The two failure modes are distinguishable on purpose:\n * - a **gap upward** means records were dropped at the source (rate limit,\n * queue overflow) rather than lost in transit, and is expected under load;\n * - a **duplicate or a decrease** means the sender is broken, so the receiver\n * rejects that record and emits a diagnostic instead of retaining it.\n *\n * This is a rule *between* records, not about the shape of one, so\n * {@link validateLogRecord} cannot enforce it — it only checks that `seq` is\n * a non-negative safe integer. Ordering is enforced by the driver, which is\n * the only party that sees the whole session.\n */\n readonly seq: number;\n /** Semantic revision current when the record was produced, when known. */\n readonly revision?: number;\n}\n\n/** Structured result: never throws hostile data onward. */\nexport type LogValidationResult =\n | { readonly ok: true; readonly record: LogRecord }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nfunction fail(code: ValidationErrorCode, detail: string): LogValidationResult {\n return { ok: false, code, detail };\n}\n\nconst LEVELS: ReadonlySet<string> = new Set(LOG_LEVELS);\n\nfunction isSafeNonNegative(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\n/**\n * Validate an untrusted log record.\n *\n * Mirrors {@link import('./validate.js').validateSnapshot}: the value is\n * projected into a frozen plain DTO first (so getters are rejected without\n * being invoked), then measured against the byte ceiling, then checked field\n * by field.\n *\n * @param value - Untrusted candidate record.\n * @param limits - Active limits; `maxLogRecordBytes` and `maxStringBytes` apply.\n * @returns `{ ok: true, record }` with a deep-frozen record, or a typed\n * failure. Never throws.\n */\nexport function validateLogRecord(value: unknown, limits: ProtocolLimits): LogValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) {\n return fail('schema', 'log record is not a JSON object');\n }\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxLogRecordBytes) {\n return fail('bytes', `log record is ${bytes} bytes, ceiling is ${limits.maxLogRecordBytes}`);\n }\n\n if (typeof projected !== 'object' || projected === null || Array.isArray(projected)) {\n return fail('schema', 'log record must be an object');\n }\n const record = projected as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!['ts', 'level', 'message', 'attrs', 'logger', 'seq', 'revision'].includes(key)) {\n return fail('schema', `unknown log record property \"${key}\"`);\n }\n }\n\n if (!isSafeNonNegative(record['ts']) || record['ts'] === 0) {\n return fail('schema', 'ts must be a positive safe integer (epoch milliseconds)');\n }\n if (typeof record['level'] !== 'string' || !LEVELS.has(record['level'])) {\n return fail('schema', `level must be one of ${LOG_LEVELS.join(', ')}`);\n }\n if (typeof record['message'] !== 'string') {\n return fail('schema', 'message must be a string');\n }\n if (Buffer.byteLength(record['message'], 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `message exceeds ${limits.maxStringBytes} UTF-8 bytes`);\n }\n if (!isSafeNonNegative(record['seq'])) {\n return fail('schema', 'seq must be a non-negative safe integer');\n }\n\n if (record['logger'] !== undefined) {\n if (typeof record['logger'] !== 'string') {\n return fail('schema', 'logger must be a string');\n }\n if (Buffer.byteLength(record['logger'], 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `logger exceeds ${limits.maxStringBytes} UTF-8 bytes`);\n }\n }\n\n if (record['revision'] !== undefined) {\n if (!isSafeNonNegative(record['revision']) || record['revision'] === 0) {\n return fail('revision', 'revision must be a positive safe integer');\n }\n }\n\n const attrs = record['attrs'];\n if (attrs !== undefined) {\n if (typeof attrs !== 'object' || attrs === null || Array.isArray(attrs)) {\n return fail('schema', 'attrs must be a flat object');\n }\n const entries = Object.entries(attrs as Record<string, unknown>);\n if (entries.length > MAX_LOG_ATTRS) {\n return fail('count', `attrs carries ${entries.length} keys, ceiling is ${MAX_LOG_ATTRS}`);\n }\n for (const [key, attrValue] of entries) {\n if (Buffer.byteLength(key, 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `attribute key \"${key}\" exceeds the string ceiling`);\n }\n const type = typeof attrValue;\n if (attrValue !== null && type !== 'string' && type !== 'number' && type !== 'boolean') {\n return fail('schema', `attribute \"${key}\" must be a string, number, boolean or null`);\n }\n if (type === 'number' && !Number.isFinite(attrValue)) {\n return fail('schema', `attribute \"${key}\" must be a finite number`);\n }\n if (type === 'string' && Buffer.byteLength(attrValue as string, 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `attribute \"${key}\" exceeds the string ceiling`);\n }\n }\n }\n\n return { ok: true, record: projected as LogRecord };\n}\n","/**\n * Wire framing: 4-byte big-endian unsigned length prefix + UTF-8 JSON body.\n * The length is checked against limits.maxFrameBytes BEFORE any decoding;\n * oversized, partial or duplicated frames fail closed with a typed error.\n * Decoded values MUST be projected into immutable plain DTOs (no accessors,\n * proxies, symbols, functions, non-plain prototypes) before retention.\n */\n\nimport { types } from 'node:util';\nimport { ProtocolViolation } from './errors.js';\nimport { DEFAULT_LIMITS } from './limits.js';\n\nexport interface FrameDecoder {\n /** Feed raw bytes; returns fully decoded, validated, frozen messages. */\n push(chunk: Uint8Array): readonly unknown[];\n /** Bytes currently buffered (bounded by maxFrameBytes + 4). */\n readonly buffered: number;\n}\n\n/** Size of the big-endian length prefix that precedes every frame body. */\nexport const FRAME_HEADER_BYTES = 4;\n\n/**\n * Structural nesting ceiling applied to every decoded frame.\n *\n * The decoder signature carries only a byte ceiling, so projection uses this\n * fixed structural bound; message-specific limits are applied later by\n * `parseAdapterMessage`/`parseDriverMessage` and `validateSnapshot`.\n */\nconst FRAME_PROJECTION_DEPTH = DEFAULT_LIMITS.maxDepth;\n\nconst RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/** Matches any unpaired surrogate code unit. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\nconst encoder = new TextEncoder();\n/** `fatal` makes malformed UTF-8 throw instead of yielding U+FFFD. */\nconst decoder = new TextDecoder('utf-8', { fatal: true });\n\nfunction assertPositiveByteCeiling(maxFrameBytes: number): void {\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0) {\n throw new ProtocolViolation(\n 'frame-malformed',\n 'maxFrameBytes must be a positive safe integer',\n );\n }\n}\n\nclass BufferedFrameDecoder implements FrameDecoder {\n readonly #maxFrameBytes: number;\n #buffer: Uint8Array;\n /** Offset of the first unconsumed byte in `#buffer`. */\n #start = 0;\n /** Offset just past the last buffered byte in `#buffer`. */\n #end = 0;\n #failure: ProtocolViolation | null = null;\n\n constructor(maxFrameBytes: number) {\n assertPositiveByteCeiling(maxFrameBytes);\n this.#maxFrameBytes = maxFrameBytes;\n this.#buffer = new Uint8Array(0);\n }\n\n get buffered(): number {\n return this.#end - this.#start;\n }\n\n push(chunk: Uint8Array): readonly unknown[] {\n if (this.#failure !== null) {\n throw new ProtocolViolation(\n 'decoder-poisoned',\n `decoder failed earlier (${this.#failure.code}) and accepts no further input`,\n );\n }\n try {\n return this.#pushOrThrow(chunk);\n } catch (error) {\n this.#failure =\n error instanceof ProtocolViolation\n ? error\n : new ProtocolViolation('frame-malformed', 'frame decoding failed');\n // Release the buffer: a poisoned decoder never resumes.\n this.#buffer = new Uint8Array(0);\n this.#start = 0;\n this.#end = 0;\n throw this.#failure;\n }\n }\n\n #pushOrThrow(chunk: Uint8Array): readonly unknown[] {\n this.#append(chunk);\n const messages: unknown[] = [];\n\n for (;;) {\n const available = this.#end - this.#start;\n if (available < FRAME_HEADER_BYTES) break;\n\n const length = this.#readLength();\n if (length === 0) {\n throw new ProtocolViolation('frame-malformed', 'frame length must be non-zero');\n }\n if (length > this.#maxFrameBytes) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `frame declares ${length} bytes, ceiling is ${this.#maxFrameBytes}`,\n );\n }\n if (available < FRAME_HEADER_BYTES + length) break; // partial: wait for more\n\n const bodyStart = this.#start + FRAME_HEADER_BYTES;\n const body = this.#buffer.subarray(bodyStart, bodyStart + length);\n messages.push(decodeBody(body));\n this.#start = bodyStart + length;\n }\n\n this.#compact();\n if (this.buffered > this.#maxFrameBytes + FRAME_HEADER_BYTES) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `buffered ${this.buffered} bytes without a complete frame`,\n );\n }\n return messages;\n }\n\n #readLength(): number {\n const b = this.#buffer;\n const i = this.#start;\n // Non-null assertions are safe: the caller checked 4 bytes are available.\n return (\n (b[i]! * 0x1000000 + ((b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!)) >>> 0\n );\n }\n\n #append(chunk: Uint8Array): void {\n const kept = this.#end - this.#start;\n const needed = kept + chunk.length;\n if (needed > this.#buffer.length - this.#start) {\n const next = new Uint8Array(needed);\n next.set(this.#buffer.subarray(this.#start, this.#end), 0);\n this.#buffer = next;\n this.#start = 0;\n this.#end = kept;\n }\n this.#buffer.set(chunk, this.#end);\n this.#end += chunk.length;\n }\n\n #compact(): void {\n if (this.#start === 0) return;\n const kept = this.#end - this.#start;\n if (kept === 0) {\n this.#buffer = new Uint8Array(0);\n } else {\n const next = new Uint8Array(kept);\n next.set(this.#buffer.subarray(this.#start, this.#end), 0);\n this.#buffer = next;\n }\n this.#start = 0;\n this.#end = kept;\n }\n}\n\nfunction decodeBody(body: Uint8Array): unknown {\n let text: string;\n try {\n text = decoder.decode(body);\n } catch {\n throw new ProtocolViolation('frame-encoding', 'frame body is not valid UTF-8');\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n // Also covers RangeError from pathologically nested JSON.\n throw new ProtocolViolation('frame-malformed', 'frame body is not valid JSON');\n }\n return projectDto(parsed, FRAME_PROJECTION_DEPTH);\n}\n\n/**\n * Create a streaming decoder for length-prefixed JSON frames.\n *\n * A frame whose declared length exceeds `maxFrameBytes` is rejected before its\n * body is read. Any violation poisons the decoder permanently: subsequent\n * `push` calls throw rather than resynchronising on attacker-chosen offsets.\n *\n * @param maxFrameBytes - Per-frame byte ceiling; must be a positive safe integer.\n * @throws {ProtocolViolation} On an invalid ceiling, or (from `push`) on any\n * oversized, malformed, non-UTF-8 or non-projectable frame.\n */\nexport function createFrameDecoder(maxFrameBytes: number): FrameDecoder {\n return new BufferedFrameDecoder(maxFrameBytes);\n}\n\n/**\n * Serialise a message into a single length-prefixed frame.\n *\n * @param message - A JSON-representable value.\n * @param maxFrameBytes - Per-frame byte ceiling applied to the encoded body.\n * @returns Header + UTF-8 JSON body, ready to write to the transport.\n * @throws {ProtocolViolation} If the value is not JSON-representable or the\n * encoded body exceeds `maxFrameBytes`.\n */\nexport function encodeFrame(message: unknown, maxFrameBytes: number): Uint8Array {\n assertPositiveByteCeiling(maxFrameBytes);\n\n let text: string | undefined;\n try {\n text = JSON.stringify(message);\n } catch {\n throw new ProtocolViolation('frame-malformed', 'message is not JSON-serialisable');\n }\n if (text === undefined) {\n throw new ProtocolViolation('dto-scalar', 'message serialises to undefined');\n }\n\n const body = encoder.encode(text);\n if (body.length > maxFrameBytes) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `encoded frame is ${body.length} bytes, ceiling is ${maxFrameBytes}`,\n );\n }\n\n const frame = new Uint8Array(FRAME_HEADER_BYTES + body.length);\n const n = body.length;\n frame[0] = (n >>> 24) & 0xff;\n frame[1] = (n >>> 16) & 0xff;\n frame[2] = (n >>> 8) & 0xff;\n frame[3] = n & 0xff;\n frame.set(body, FRAME_HEADER_BYTES);\n return frame;\n}\n\nfunction projectScalar(value: unknown, path: string): string | number | boolean | null {\n if (value === null) return null;\n switch (typeof value) {\n case 'boolean':\n return value;\n case 'number':\n if (!Number.isFinite(value)) {\n throw new ProtocolViolation('dto-scalar', `non-finite number at ${path}`);\n }\n return value;\n case 'string':\n if (LONE_SURROGATE.test(value)) {\n throw new ProtocolViolation('dto-string', `unpaired surrogate at ${path}`);\n }\n return value;\n default:\n throw new ProtocolViolation(\n 'dto-scalar',\n `value of type ${typeof value} is not JSON-representable at ${path}`,\n );\n }\n}\n\nfunction projectNode(value: unknown, depth: number, maxDepth: number, seen: Set<object>, path: string): unknown {\n if (value === null || typeof value !== 'object') {\n return projectScalar(value, path);\n }\n if (depth > maxDepth) {\n throw new ProtocolViolation('dto-depth', `nesting exceeds ${maxDepth} at ${path}`);\n }\n if (types.isProxy(value)) {\n throw new ProtocolViolation('dto-prototype', `proxy at ${path}`);\n }\n if (seen.has(value)) {\n // Covers both cycles and plain aliasing (shared subtrees).\n throw new ProtocolViolation('dto-alias', `value is reachable more than once at ${path}`);\n }\n seen.add(value);\n\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new ProtocolViolation('dto-symbol', `symbol-keyed property at ${path}`);\n }\n\n const proto: unknown = Object.getPrototypeOf(value);\n const result = Array.isArray(value)\n ? projectArray(value, proto, depth, maxDepth, seen, path)\n : projectObject(value, proto, depth, maxDepth, seen, path);\n\n // `seen` is never cleared: a value reachable twice is an alias, not a\n // legitimate repeat, and must be rejected rather than duplicated.\n return Object.freeze(result);\n}\n\nfunction projectArray(\n value: readonly unknown[],\n proto: unknown,\n depth: number,\n maxDepth: number,\n seen: Set<object>,\n path: string,\n): unknown[] {\n if (proto !== Array.prototype) {\n throw new ProtocolViolation('dto-prototype', `array with exotic prototype at ${path}`);\n }\n const length = value.length;\n const out = new Array<unknown>(length);\n for (let i = 0; i < length; i += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, i);\n if (descriptor === undefined) {\n throw new ProtocolViolation('dto-sparse', `hole at ${path}[${i}]`);\n }\n if (!('value' in descriptor)) {\n throw new ProtocolViolation('dto-accessor', `accessor at ${path}[${i}]`);\n }\n out[i] = projectNode(descriptor.value, depth + 1, maxDepth, seen, `${path}[${i}]`);\n }\n // Reject `length` plus anything that is not a dense index we just consumed.\n if (Object.getOwnPropertyNames(value).length !== length + 1) {\n throw new ProtocolViolation('dto-sparse', `array carries extra own properties at ${path}`);\n }\n return out;\n}\n\nfunction projectObject(\n value: object,\n proto: unknown,\n depth: number,\n maxDepth: number,\n seen: Set<object>,\n path: string,\n): Record<string, unknown> {\n if (proto !== Object.prototype && proto !== null) {\n throw new ProtocolViolation('dto-prototype', `non-plain object at ${path}`);\n }\n const out: Record<string, unknown> = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n if (RESERVED_KEYS.has(key)) {\n throw new ProtocolViolation('dto-key', `reserved property name \"${key}\" at ${path}`);\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (!('value' in descriptor)) {\n throw new ProtocolViolation('dto-accessor', `accessor property \"${key}\" at ${path}`);\n }\n if (!descriptor.enumerable) {\n throw new ProtocolViolation('dto-key', `non-enumerable property \"${key}\" at ${path}`);\n }\n if (LONE_SURROGATE.test(key)) {\n throw new ProtocolViolation('dto-string', `unpaired surrogate in key at ${path}`);\n }\n out[key] = projectNode(descriptor.value, depth + 1, maxDepth, seen, `${path}.${key}`);\n }\n return out;\n}\n\n/**\n * Deep-project an untrusted parsed value into a frozen, plain, JSON-safe DTO.\n * Throws ProtocolViolation on aliases, cycles, sparse arrays, accessors,\n * non-JSON scalars, or depth/size beyond limits.\n *\n * Properties are inspected with `Object.getOwnPropertyDescriptor`, so a getter\n * on hostile input is detected and rejected without ever being invoked.\n *\n * @param value - Untrusted input, typically the result of `JSON.parse`.\n * @param maxDepth - Maximum nesting depth; the root sits at depth 0.\n * @returns A structurally identical, deep-frozen copy. The `T` type parameter\n * is an unchecked assertion — validate the shape separately.\n * @throws {ProtocolViolation}\n */\nexport function projectDto<T>(value: unknown, maxDepth: number): T {\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {\n throw new ProtocolViolation('dto-depth', 'maxDepth must be a non-negative safe integer');\n }\n return projectNode(value, 0, maxDepth, new Set<object>(), '$') as T;\n}\n","/**\n * Tree deltas: incremental semantic updates bound to an exact base revision.\n *\n * A delta is only ever applied to the revision it names. There is no\n * speculative patching and no fuzzy rebasing: if the receiver does not hold\n * exactly `baseRevision`, it asks for a full snapshot with `get-tree` and\n * throws the delta away (origin spec §8.3). A wrong tree is far more expensive\n * than a redundant snapshot, because every assertion downstream inherits the\n * error silently.\n *\n * ## Composition semantics\n *\n * The semantic tree is a flat node list joined by `parentId`, so a delta is a\n * set of upserts plus a set of removals:\n *\n * - **`changed`** upserts by id: a node absent from the base is inserted, and\n * a node already present is **replaced wholesale**, never field-merged.\n * Merging would need a third state meaning \"unset this optional field\",\n * which the wire has no way to express.\n * - **`removed`** removes each id **together with its whole subtree**. Cascade\n * is what keeps a delta small — dropping a dialog is one id, not one id per\n * descendant — and it is the only rule that cannot leave orphans behind.\n * - **`rootIds`**, when present, replaces the root list outright. When absent\n * the base roots carry over, minus anything the removals took.\n * - **`cursor`**, when present, replaces the cursor. When absent it is\n * unchanged. Everything else about the viewport — columns, rows, session id\n * — is inherited and cannot be changed by a delta.\n *\n * Order matters: removals are applied first, then upserts. That lets one delta\n * move a node out of a removed subtree by re-adding it in `changed`.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport type { ProtocolLimits } from './limits.js';\nimport type { CursorInfo, SemanticNode, SemanticSnapshot } from './tree.js';\nimport type { ValidationErrorCode, ValidationResult } from './validate.js';\nimport { validateSnapshot } from './validate.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\nimport { treeSchemas } from './node-schema.js';\n\n/**\n * An incremental update to a semantic tree.\n *\n * Carries no viewport or session id: those belong to the snapshot the delta is\n * composed onto, and a change to them requires a full snapshot. The cursor is\n * the exception — it moves far too often to be worth a snapshot each time.\n */\nexport interface TreeDelta {\n /** The revision this delta is composed onto. Must match exactly. */\n readonly baseRevision: number;\n /** The revision produced by applying it. Strictly greater than the base. */\n readonly revision: number;\n /** Nodes to insert or replace, keyed by `id`. */\n readonly changed: readonly SemanticNode[];\n /** Node ids to remove, each together with its subtree. */\n readonly removed: readonly string[];\n /** Replacement root list; absent means the base roots carry over. */\n readonly rootIds?: readonly string[];\n /**\n * Replacement cursor; **absent means unchanged**.\n *\n * Without this a diffs-only session could never move the cursor, which in a\n * TUI moves on nearly every keystroke — the mode would be useless for\n * exactly the interactive applications it exists to make cheap.\n *\n * A delta can set the cursor but **cannot clear it**, and the two are not\n * the same thing: `{ visible: false }` says there is a cursor and it is\n * hidden, while an absent `SemanticSnapshot.cursor` says there is no cursor\n * information at all. `cursor` is the only optional field on a snapshot, so\n * it is the only one with this asymmetry.\n *\n * **Producer obligation:** a producer whose tree transitions from having a\n * cursor to having none MUST send a full snapshot rather than a delta.\n * Emitting a delta there would leave the receiver holding a cursor the\n * application has stopped reporting — stale state that looks live. The same\n * rule already applies to `columns`/`rows`, which a delta also cannot change.\n */\n readonly cursor?: CursorInfo;\n}\n\n/** Structured result: never throws hostile data onward. */\nexport type DeltaValidationResult =\n | { readonly ok: true; readonly delta: TreeDelta }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nfunction fail(code: ValidationErrorCode, detail: string): DeltaValidationResult {\n return { ok: false, code, detail };\n}\n\nconst DELTA_KEYS = ['baseRevision', 'revision', 'changed', 'removed', 'rootIds', 'cursor'];\n\n/**\n * Validate the **shape** of an untrusted delta.\n *\n * This checks everything that can be known without the base tree: bounded\n * sizes, well-formed nodes, unique ids, and a base/revision pair that moves\n * forward. It deliberately cannot check parent existence, acyclicity, depth or\n * whether bounds fall inside the viewport — all of those are properties of the\n * *composed* tree, and {@link applyTreeDelta} checks them there.\n *\n * @param value - Untrusted candidate delta (without the message `type` field).\n * @param limits - Active limits.\n * @returns `{ ok: true, delta }` with a deep-frozen delta, or a typed failure.\n * Never throws.\n */\nexport function validateTreeDelta(value: unknown, limits: ProtocolLimits): DeltaValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) {\n return fail('schema', 'delta is not a JSON object');\n }\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxSnapshotBytes) {\n return fail('bytes', `delta is ${bytes} bytes, ceiling is ${limits.maxSnapshotBytes}`);\n }\n\n if (typeof projected !== 'object' || projected === null || Array.isArray(projected)) {\n return fail('schema', 'delta must be an object');\n }\n const delta = projected as Record<string, unknown>;\n for (const key of Object.keys(delta)) {\n if (!DELTA_KEYS.includes(key)) return fail('schema', `unknown delta property \"${key}\"`);\n }\n\n const { text, node, cursor } = treeSchemas(limits);\n const parsed = deltaSchema(text, node, cursor, limits).safeParse(delta);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n const path = issue.path.map(String);\n const where = path.length > 0 ? path.join('.') : '<root>';\n const code: ValidationErrorCode = path.includes('role')\n ? 'unknown-role'\n : path.includes('revision') || path.includes('baseRevision')\n ? 'revision'\n : path.includes('bounds') || path.includes('rect')\n ? 'bad-rect'\n : issue.code === 'too_big'\n ? 'count'\n : 'schema';\n return fail(code, `${where}: ${issue.message}`);\n }\n\n const typed = delta as unknown as TreeDelta;\n\n if (typed.revision <= typed.baseRevision) {\n return fail(\n 'revision',\n `revision ${typed.revision} must be greater than baseRevision ${typed.baseRevision}`,\n );\n }\n\n const total = typed.changed.length + typed.removed.length;\n if (total > limits.maxNodes) {\n return fail('count', `delta touches ${total} nodes, ceiling is ${limits.maxNodes}`);\n }\n\n const changedIds = new Set<string>();\n for (const entry of typed.changed) {\n if (changedIds.has(entry.id)) {\n return fail('duplicate-id', `node id ${entry.id} appears twice in changed`);\n }\n changedIds.add(entry.id);\n if (entry.parentId === entry.id) {\n return fail('cycle', `node ${entry.id} is its own parent`);\n }\n }\n\n const removedIds = new Set<string>();\n for (const id of typed.removed) {\n if (removedIds.has(id)) return fail('duplicate-id', `node id ${id} appears twice in removed`);\n removedIds.add(id);\n if (changedIds.has(id)) {\n return fail('schema', `node id ${id} is both changed and removed`);\n }\n }\n\n if (typed.rootIds !== undefined) {\n const seen = new Set<string>();\n for (const id of typed.rootIds) {\n if (seen.has(id)) return fail('duplicate-id', `root id ${id} appears twice`);\n seen.add(id);\n }\n }\n\n return { ok: true, delta: typed };\n}\n\nconst deltaCache = new WeakMap<ProtocolLimits, z.ZodType>();\n\nfunction deltaSchema(\n text: z.ZodType<string>,\n node: z.ZodType,\n cursor: z.ZodType,\n limits: ProtocolLimits,\n): z.ZodType {\n const cached = deltaCache.get(limits);\n if (cached !== undefined) return cached;\n const built = z.strictObject({\n baseRevision: z.number().refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer'),\n revision: z.number().refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer'),\n changed: z.array(node).max(limits.maxNodes),\n removed: z.array(text).max(limits.maxNodes),\n rootIds: z.array(text).max(limits.maxNodes).optional(),\n cursor: cursor.optional(),\n });\n deltaCache.set(limits, built);\n return built;\n}\n\n/**\n * Compose a delta onto the snapshot it names, then validate the result.\n *\n * The base revision must match **exactly**; a mismatch is reported rather than\n * patched around, so the caller can fall back to `get-tree` per origin §8.3.\n *\n * All the invariants a delta cannot check on its own — parents exist, the tree\n * is acyclic, depth and counts are within limits, bounds intersect the viewport\n * — are checked here against the composed tree, by running the composed result\n * through {@link validateSnapshot}. A delta is therefore never trusted to\n * produce a valid tree; it is only trusted to describe one.\n *\n * @param base - The snapshot the delta is composed onto.\n * @param delta - A delta that already passed {@link validateTreeDelta}.\n * @param limits - Active limits.\n * @returns The composed, deep-frozen snapshot, or a typed failure. Never throws.\n */\nexport function applyTreeDelta(\n base: SemanticSnapshot,\n delta: TreeDelta,\n limits: ProtocolLimits,\n): ValidationResult {\n if (delta.baseRevision !== base.revision) {\n return {\n ok: false,\n code: 'revision',\n detail:\n `delta is based on revision ${delta.baseRevision} but the held snapshot is ` +\n `revision ${base.revision}; request a full snapshot instead of patching`,\n };\n }\n\n const byId = new Map<string, SemanticNode>();\n for (const node of base.nodes) byId.set(node.id, node);\n\n // Removals cascade, so collect children once rather than rescanning per id.\n const childrenOf = new Map<string, string[]>();\n for (const node of base.nodes) {\n if (node.parentId === undefined) continue;\n const siblings = childrenOf.get(node.parentId);\n if (siblings === undefined) childrenOf.set(node.parentId, [node.id]);\n else siblings.push(node.id);\n }\n\n for (const id of delta.removed) {\n if (!byId.has(id)) {\n return {\n ok: false,\n code: 'missing-parent',\n detail:\n `delta removes unknown node ${id}; the producer's base disagrees with ours, ` +\n 'so the tree must be resynchronised rather than patched',\n };\n }\n // Iterative descent: a hostile delta must not be able to blow the stack.\n const pending = [id];\n while (pending.length > 0) {\n const current = pending.pop()!;\n if (!byId.delete(current)) continue;\n const children = childrenOf.get(current);\n if (children !== undefined) pending.push(...children);\n }\n }\n\n for (const node of delta.changed) byId.set(node.id, node);\n\n // Roots that survived the removals. Adding a NEW root therefore requires\n // sending `rootIds`: a parentless node absent from the root list is exactly\n // what validateSnapshot rejects, so the omission fails loudly.\n const rootIds = delta.rootIds ?? base.rootIds.filter((id) => byId.has(id));\n\n const composed = {\n v: 1 as const,\n sessionId: base.sessionId,\n revision: delta.revision,\n columns: base.columns,\n rows: base.rows,\n // Absent cursor means unchanged, so the base's carries over.\n ...(delta.cursor ?? base.cursor) === undefined\n ? {}\n : { cursor: delta.cursor ?? base.cursor },\n rootIds,\n nodes: [...byId.values()],\n };\n\n return validateSnapshot(composed, limits);\n}\n","import { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport { treeSchemas } from './node-schema.js';\nimport type { SemanticNode, SemanticSnapshot } from './tree.js';\nimport type { ProtocolLimits } from './limits.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\n\n/** Structured result: never throws hostile data onward. */\nexport type ValidationResult =\n | { readonly ok: true; readonly snapshot: SemanticSnapshot }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nexport type ValidationErrorCode =\n | 'schema'\n | 'unknown-role'\n | 'duplicate-id'\n | 'missing-parent'\n | 'cycle'\n | 'depth'\n | 'count'\n | 'string-bytes'\n | 'bad-rect'\n | 'revision'\n | 'bytes';\n\nfunction fail(code: ValidationErrorCode, detail: string): ValidationResult {\n return { ok: false, code, detail };\n}\n\n/**\n * Map a zod issue onto the contract's error taxonomy so callers get a stable\n * code rather than having to interpret schema internals.\n */\nfunction codeForIssue(issue: z.core.$ZodIssue): ValidationErrorCode {\n const path = issue.path.map(String);\n if (path.includes('role')) return 'unknown-role';\n if (path.includes('revision')) return 'revision';\n if (path.includes('bounds') || path.includes('rect')) return 'bad-rect';\n if (issue.code === 'custom' && issue.message?.includes('hit regions')) return 'bad-rect';\n if (issue.code === 'too_big' && (path.includes('nodes') || path.includes('rootIds'))) {\n return 'count';\n }\n if (issue.code === 'custom' && typeof issue.message === 'string' && issue.message.includes('UTF-8 bytes')) {\n return 'string-bytes';\n }\n return 'schema';\n}\n\nfunction describeIssue(issue: z.core.$ZodIssue): string {\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return `${where}: ${issue.message}`;\n}\n\nfunction rectIntersectsViewport(\n rect: { row: number; column: number; width: number; height: number },\n columns: number,\n rows: number,\n): boolean {\n if (rect.width === 0 || rect.height === 0) return false;\n return (\n rect.column < columns &&\n rect.row < rows &&\n rect.column + rect.width > 0 &&\n rect.row + rect.height > 0\n );\n}\n\nfunction checkNodeShape(\n node: SemanticNode,\n snapshot: SemanticSnapshot,\n ids: ReadonlySet<string>,\n limits: ProtocolLimits,\n): ValidationResult | null {\n // D1: `generic` is how an unrecognised widget survives instead of being\n // dropped, but only if it says what it was. A generic node without a\n // framework type carries no more information than the drop it replaced.\n if (node.role === 'generic' && (node.frameworkType === undefined || node.frameworkType === '')) {\n return fail(\n 'schema',\n `node ${node.id} has role 'generic' without a frameworkType; an unrecognised widget must ` +\n 'name what the framework called it',\n );\n }\n\n // Every cell outside the visible area and the node still visible cannot both\n // be true. Refusing the pair keeps `offscreen` a claim about scrolling rather\n // than a second, weaker way of saying \"hidden\".\n if (node.state?.offscreen === true && node.state.hidden !== true) {\n return fail(\n 'schema',\n `node ${node.id}: state.offscreen implies state.hidden — every cell is outside the ` +\n 'visible area, so the node cannot also be visible',\n );\n }\n\n if (node.bounds !== undefined) {\n const { width, height, row, column } = node.bounds;\n if (\n !Number.isSafeInteger(row + height) ||\n !Number.isSafeInteger(column + width)\n ) {\n return fail('bad-rect', `node ${node.id}: bounds overflow the safe-integer range`);\n }\n if (node.state?.hidden !== true && !rectIntersectsViewport(node.bounds, snapshot.columns, snapshot.rows)) {\n return fail(\n 'bad-rect',\n `node ${node.id}: bounds do not intersect the ${snapshot.columns}x${snapshot.rows} viewport and the node is not hidden`,\n );\n }\n }\n\n for (const range of node.textRanges ?? []) {\n if (range.endOffset < range.startOffset) {\n return fail('bad-rect', `node ${node.id}: text range ends before it starts`);\n }\n if (!Number.isSafeInteger(range.rect.row + range.rect.height)) {\n return fail('bad-rect', `node ${node.id}: text range rect overflows the safe-integer range`);\n }\n }\n\n for (const [field, targets] of [\n ['labelledBy', node.labelledBy],\n ['describedBy', node.describedBy],\n ] as const) {\n if (targets === undefined) continue;\n if (targets.length > limits.maxRelationTargets) {\n return fail('count', `node ${node.id}: ${field} exceeds ${limits.maxRelationTargets} targets`);\n }\n for (const target of targets) {\n if (!ids.has(target)) {\n return fail('missing-parent', `node ${node.id}: ${field} references unknown node ${target}`);\n }\n }\n }\n\n return null;\n}\n\n/**\n * Depth of every node, or the id at which a parent chain closes on itself.\n * Roots sit at depth 1.\n */\nfunction computeDepths(\n nodes: readonly SemanticNode[],\n byId: ReadonlyMap<string, SemanticNode>,\n): { readonly depths: ReadonlyMap<string, number> } | { readonly cycleAt: string } {\n const depths = new Map<string, number>();\n\n for (const start of nodes) {\n if (depths.has(start.id)) continue;\n const chain: string[] = [];\n const onChain = new Set<string>();\n let current: SemanticNode | undefined = start;\n\n while (current !== undefined && !depths.has(current.id)) {\n if (onChain.has(current.id)) return { cycleAt: current.id };\n onChain.add(current.id);\n chain.push(current.id);\n current = current.parentId === undefined ? undefined : byId.get(current.parentId);\n }\n\n let depth = current === undefined ? 0 : depths.get(current.id)!;\n for (let i = chain.length - 1; i >= 0; i -= 1) {\n depth += 1;\n depths.set(chain[i]!, depth);\n }\n }\n\n return { depths };\n}\n\n/**\n * Full snapshot validation per spec §8.2: unique ids, existing+acyclic parent\n * relations, dense bounded arrays, Unicode scalar strings within byte bounds,\n * safe-integer rects intersecting the viewport unless state.hidden, strictly\n * increasing revisions (checked by caller against session state), deep\n * immutability of the returned value.\n *\n * The value is first projected with {@link projectDto}, so getters on hostile\n * input are rejected without being invoked and the returned snapshot is a\n * deep-frozen plain copy that shares no references with the input.\n *\n * @param value - Untrusted candidate snapshot.\n * @param limits - Active limits; callers may tighten but never widen these.\n * @returns `{ ok: true, snapshot }` with a deep-frozen snapshot, or\n * `{ ok: false, code, detail }`. Never throws.\n */\nexport function validateSnapshot(value: unknown, limits: ProtocolLimits): ValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n // Projection guarantees JSON-representability, so stringify cannot throw.\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) {\n return fail('schema', 'snapshot is not a JSON object');\n }\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxSnapshotBytes) {\n return fail('bytes', `snapshot is ${bytes} bytes, ceiling is ${limits.maxSnapshotBytes}`);\n }\n\n const parsed = treeSchemas(limits).snapshot.safeParse(projected);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n return fail(codeForIssue(issue), describeIssue(issue));\n }\n\n const snapshot = projected as SemanticSnapshot;\n\n if (snapshot.nodes.length > limits.maxNodes) {\n return fail('count', `snapshot carries ${snapshot.nodes.length} nodes, ceiling is ${limits.maxNodes}`);\n }\n\n const byId = new Map<string, SemanticNode>();\n for (const node of snapshot.nodes) {\n if (byId.has(node.id)) {\n return fail('duplicate-id', `node id ${node.id} appears more than once`);\n }\n byId.set(node.id, node);\n }\n\n const rootIds = new Set<string>();\n for (const id of snapshot.rootIds) {\n if (rootIds.has(id)) {\n return fail('duplicate-id', `root id ${id} appears more than once`);\n }\n rootIds.add(id);\n const node = byId.get(id);\n if (node === undefined) {\n return fail('missing-parent', `rootIds references unknown node ${id}`);\n }\n if (node.parentId !== undefined) {\n return fail('schema', `root node ${id} declares a parent`);\n }\n }\n\n const ids: ReadonlySet<string> = new Set(byId.keys());\n\n if (snapshot.v === 2) {\n if (snapshot.coordinateSpace?.status === 'known' && snapshot.coordinateSpace.value !== 'viewport-cells') {\n // Framework-local geometry is inspectable, but it cannot be addressed by\n // terminal input. Keeping it valid is intentional; pointer ownership is\n // independently qualified by the hit grid.\n }\n if (snapshot.hitGrid?.status === 'known') {\n for (const region of snapshot.hitGrid.value.regions) {\n if (!ids.has(region.recipientId)) {\n return fail('missing-parent', `hitGrid references unknown recipient ${region.recipientId}`);\n }\n if (!rectIntersectsViewport(region.rect, snapshot.columns, snapshot.rows)) {\n return fail('bad-rect', `hitGrid region for ${region.recipientId} does not intersect the viewport`);\n }\n }\n }\n }\n\n for (const node of snapshot.nodes) {\n if (node.parentId === undefined) {\n if (!rootIds.has(node.id)) {\n return fail('schema', `parentless node ${node.id} is missing from rootIds`);\n }\n } else if (!byId.has(node.parentId)) {\n return fail('missing-parent', `node ${node.id} references unknown parent ${node.parentId}`);\n } else if (node.parentId === node.id) {\n return fail('cycle', `node ${node.id} is its own parent`);\n }\n\n const problem = checkNodeShape(node, snapshot, ids, limits);\n if (problem !== null) return problem;\n }\n\n const depthResult = computeDepths(snapshot.nodes, byId);\n if ('cycleAt' in depthResult) {\n return fail('cycle', `parent chain through node ${depthResult.cycleAt} is cyclic`);\n }\n for (const [id, depth] of depthResult.depths) {\n if (depth > limits.maxDepth) {\n return fail('depth', `node ${id} sits at depth ${depth}, ceiling is ${limits.maxDepth}`);\n }\n }\n\n if (snapshot.cursor !== undefined) {\n const { row, column } = snapshot.cursor;\n if (row >= snapshot.rows || column >= snapshot.columns) {\n return fail('bad-rect', `cursor (${row}, ${column}) lies outside the viewport`);\n }\n }\n\n return { ok: true, snapshot };\n}\n","/**\n * AccessKit export: `SemanticSnapshot` → an AccessKit `TreeUpdate`.\n *\n * A pure transformation into AccessKit's serde JSON shape. This module takes\n * **no dependency** on AccessKit — the protocol package depends on `zod` only —\n * so the output is data a bridge can hand to a real adapter, not a binding.\n *\n * ## Why there is no native bridge in 1.0\n *\n * AccessKit's platform adapters attach an accessibility tree to a **native\n * window**: an `NSView` on macOS, an `HWND` on Windows, a toplevel on AT-SPI.\n * A terminal application has none of those. The terminal emulator owns the\n * window, and the application under test is a child process writing bytes to a\n * pseudo-terminal. There is nothing for an adapter to attach to, and nothing an\n * assistive technology could route back to us.\n *\n * The geometry gap is the same problem seen from the other side. Our `bounds`\n * are **terminal cells** — row 3, column 12 — while AccessKit's `Rect` is in\n * physical pixels relative to the window origin. Converting requires the cell\n * size and window position, which live in the emulator, not in the process\n * being tested. Guessing a cell size would produce coordinates that look\n * authoritative and point nowhere.\n *\n * So the export is *bridge-ready*, not a bridge: it is the half of the problem\n * that can be solved correctly without a window. An embedder that does own one\n * (a GUI terminal emulator embedding termwright) can supply {@link\n * AccessKitExportOptions.cellSize} and get real geometry.\n *\n * ## Schema provenance\n *\n * Shapes verified against `accesskit` 0.24.1 (docs.rs, August 2026):\n * `TreeUpdate { nodes, tree, tree_id, focus }`, `Tree { root, toolkit_name,\n * toolkit_version }`, `NodeId(u64)`, `Rect { x0, y0, x1, y1 }`, and\n * `#[serde(rename_all = \"camelCase\")]` on `Role`, `Action` and `Node`.\n * `TreeId` is a UUID, with the nil UUID reserved for the root tree.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { SemanticNode, SemanticSnapshot, Rect } from './tree.js';\nimport type { SemanticAction, SemanticRole } from './roles.js';\nimport { ProtocolViolation } from './errors.js';\n\n/** The nil UUID, which AccessKit reserves for the root tree (`TreeId::ROOT`). */\nexport const ACCESSKIT_ROOT_TREE_ID = '00000000-0000-0000-0000-000000000000';\n\n/** AccessKit's `Rect`: minimum and maximum coordinates, not origin plus size. */\nexport interface AccessKitRect {\n readonly x0: number;\n readonly y0: number;\n readonly x1: number;\n readonly y1: number;\n}\n\n/** AccessKit's `Toggled`, used for tri-state checkboxes. */\nexport type AccessKitToggled = 'false' | 'true' | 'mixed';\n\n/**\n * An AccessKit `Node` in its serde JSON form. Only the properties this export\n * can populate faithfully are modelled.\n */\nexport interface AccessKitNode {\n readonly role: string;\n readonly label?: string;\n readonly description?: string;\n readonly value?: string;\n readonly children?: readonly number[];\n readonly bounds?: AccessKitRect;\n readonly actions?: readonly string[];\n readonly labelledBy?: readonly number[];\n readonly describedBy?: readonly number[];\n readonly disabled?: boolean;\n readonly selected?: boolean;\n readonly expanded?: boolean;\n readonly busy?: boolean;\n readonly modal?: boolean;\n readonly hidden?: boolean;\n readonly readOnly?: boolean;\n readonly toggled?: AccessKitToggled;\n}\n\n/** AccessKit's `Tree`. */\nexport interface AccessKitTree {\n readonly root: number;\n readonly toolkitName?: string;\n readonly toolkitVersion?: string;\n}\n\n/** AccessKit's `TreeUpdate`. */\nexport interface AccessKitTreeUpdate {\n readonly nodes: readonly (readonly [number, AccessKitNode])[];\n readonly tree?: AccessKitTree;\n readonly treeId: string;\n readonly focus: number;\n}\n\n/** Settings for {@link toAccessKitTreeUpdate}. */\nexport interface AccessKitExportOptions {\n /** Tree identity; defaults to the nil UUID AccessKit reserves for the root. */\n readonly treeId?: string;\n readonly toolkitName?: string;\n readonly toolkitVersion?: string;\n /**\n * Pixel size of one terminal cell. Supply it only if you genuinely know it —\n * an embedder that owns the window does; a headless test run does not.\n * Without it `bounds` is omitted and cell rects are reported separately.\n */\n readonly cellSize?: { readonly width: number; readonly height: number };\n}\n\n/** The export, plus the cell geometry AccessKit has nowhere to put. */\nexport interface AccessKitExport {\n readonly update: AccessKitTreeUpdate;\n /**\n * Cell-space rects keyed by AccessKit node id, for every node that had\n * `bounds`. AccessKit's `Node` has no extension point for foreign\n * coordinates, so carrying them alongside is the honest option: a consumer\n * that understands terminal cells can use them, and one that does not is\n * not misled by pixel coordinates that were never measured.\n */\n readonly cellBounds: Readonly<Record<string, Rect>>;\n}\n\n/**\n * ARIA-aligned protocol roles to AccessKit roles.\n *\n * Every target is a real `accesskit::Role` variant in its camelCase serde\n * spelling. `textbox` is resolved per node rather than here, because a\n * multiline textbox maps to a different AccessKit role.\n */\nexport const ACCESSKIT_ROLE_BY_SEMANTIC_ROLE: Readonly<Record<SemanticRole, string>> =\n Object.freeze({\n application: 'application',\n region: 'region',\n dialog: 'dialog',\n alert: 'alert',\n status: 'status',\n list: 'list',\n listitem: 'listItem',\n menu: 'menu',\n menuitem: 'menuItem',\n button: 'button',\n checkbox: 'checkBox',\n radio: 'radioButton',\n tab: 'tab',\n textbox: 'textInput',\n heading: 'heading',\n text: 'label',\n progressbar: 'progressIndicator',\n separator: 'splitter',\n scrollbar: 'scrollBar',\n table: 'table',\n row: 'row',\n cell: 'cell',\n generic: 'genericContainer',\n });\n\n/**\n * Protocol actions to AccessKit actions.\n *\n * `select` is deliberately absent: AccessKit has no selection action, and\n * mapping it onto `click` would claim a behaviour the adapter never described.\n * `toggle` maps to `click` because that is how AccessKit expresses toggling.\n */\nconst ACCESSKIT_ACTION_BY_SEMANTIC_ACTION: Readonly<Partial<Record<SemanticAction, string>>> =\n Object.freeze({\n focus: 'focus',\n activate: 'click',\n toggle: 'click',\n setValue: 'setValue',\n expand: 'expand',\n scroll: 'scrollIntoView',\n });\n\n/**\n * Bits of the digest used for a node id.\n *\n * AccessKit's `NodeId` is a `u64`, but JSON numbers are IEEE doubles and this\n * export is JSON. Staying inside 53 bits keeps every id exactly representable\n * on both sides; the alternative silently rounds ids above 2^53 and produces\n * collisions that look like duplicate nodes.\n */\nconst NODE_ID_BITS = 53n;\nconst NODE_ID_MASK = (1n << NODE_ID_BITS) - 1n;\n\n/**\n * Map a protocol node id (a string) onto an AccessKit node id (a number).\n *\n * Stable across processes and languages: SHA-256 of the UTF-8 id, truncated to\n * 53 bits. At the protocol's 5 000-node ceiling the collision probability is\n * about 1.4e-9, and {@link toAccessKitTreeUpdate} detects a collision rather\n * than silently merging two nodes.\n *\n * @param id - Protocol node id.\n */\nexport function accessKitNodeId(id: string): number {\n const digest = createHash('sha256').update(id, 'utf8').digest();\n const value = digest.readBigUInt64BE(0) & NODE_ID_MASK;\n // 0 is a legal NodeId, but reserving it keeps \"unset\" unambiguous for\n // consumers that treat 0 as absent.\n return value === 0n ? 1 : Number(value);\n}\n\nfunction toggledFor(checked: boolean | 'mixed' | undefined): AccessKitToggled | undefined {\n if (checked === undefined) return undefined;\n if (checked === 'mixed') return 'mixed';\n return checked ? 'true' : 'false';\n}\n\nfunction accessKitRoleFor(node: SemanticNode): string {\n if (node.role === 'textbox' && node.state?.multiline === true) return 'multilineTextInput';\n return ACCESSKIT_ROLE_BY_SEMANTIC_ROLE[node.role];\n}\n\nfunction actionsFor(actions: readonly SemanticAction[] | undefined): readonly string[] | undefined {\n if (actions === undefined || actions.length === 0) return undefined;\n const mapped = new Set<string>();\n for (const action of actions) {\n const target = ACCESSKIT_ACTION_BY_SEMANTIC_ACTION[action];\n if (target !== undefined) mapped.add(target);\n }\n return mapped.size === 0 ? undefined : [...mapped];\n}\n\nfunction boundsFor(\n rect: Rect,\n cellSize: { readonly width: number; readonly height: number },\n): AccessKitRect {\n return {\n x0: rect.column * cellSize.width,\n y0: rect.row * cellSize.height,\n x1: (rect.column + rect.width) * cellSize.width,\n y1: (rect.row + rect.height) * cellSize.height,\n };\n}\n\n/**\n * Convert a validated semantic snapshot into an AccessKit `TreeUpdate`.\n *\n * Two structural differences from our model are worth knowing:\n *\n * - **Focus is a tree-level property.** AccessKit puts `focus` on the\n * `TreeUpdate`, not on a node, so the node carrying `state.focused` becomes\n * the update's focus. If no node claims focus, the root does.\n * - **Children are explicit.** Our tree is a flat list joined by `parentId`;\n * AccessKit nodes carry a `children` array, which is derived here in the\n * snapshot's node order.\n *\n * @param snapshot - A snapshot that already passed `validateSnapshot`.\n * @param options - Tree identity, toolkit metadata and optional cell geometry.\n * @throws {ProtocolViolation} If two node ids collide in the 53-bit id space.\n */\nexport function toAccessKitTreeUpdate(\n snapshot: SemanticSnapshot,\n options: AccessKitExportOptions = {},\n): AccessKitExport {\n const idOf = new Map<string, number>();\n const seen = new Map<number, string>();\n for (const node of snapshot.nodes) {\n const mapped = accessKitNodeId(node.id);\n const previous = seen.get(mapped);\n if (previous !== undefined) {\n throw new ProtocolViolation(\n 'dto-key',\n `node ids \"${previous}\" and \"${node.id}\" collide in the AccessKit id space`,\n );\n }\n seen.set(mapped, node.id);\n idOf.set(node.id, mapped);\n }\n\n const childrenOf = new Map<string, number[]>();\n for (const node of snapshot.nodes) {\n if (node.parentId === undefined) continue;\n const siblings = childrenOf.get(node.parentId);\n if (siblings === undefined) childrenOf.set(node.parentId, [idOf.get(node.id)!]);\n else siblings.push(idOf.get(node.id)!);\n }\n\n const relation = (ids: readonly string[] | undefined): readonly number[] | undefined => {\n if (ids === undefined || ids.length === 0) return undefined;\n const mapped = ids.map((id) => idOf.get(id)).filter((id): id is number => id !== undefined);\n return mapped.length === 0 ? undefined : mapped;\n };\n\n const cellBounds: Record<string, Rect> = {};\n const nodes: (readonly [number, AccessKitNode])[] = [];\n let focus: number | undefined;\n\n for (const node of snapshot.nodes) {\n const id = idOf.get(node.id)!;\n const state = node.state;\n if (state?.focused === true && focus === undefined) focus = id;\n if (node.bounds !== undefined) cellBounds[String(id)] = node.bounds;\n\n const accessKitNode: AccessKitNode = {\n role: accessKitRoleFor(node),\n ...(node.name === '' ? {} : { label: node.name }),\n ...(node.description === undefined ? {} : { description: node.description }),\n ...(node.value === undefined ? {} : { value: node.value }),\n ...(childrenOf.has(node.id) ? { children: childrenOf.get(node.id)! } : {}),\n ...(node.bounds !== undefined && options.cellSize !== undefined\n ? { bounds: boundsFor(node.bounds, options.cellSize) }\n : {}),\n ...(actionsFor(node.actions) === undefined ? {} : { actions: actionsFor(node.actions)! }),\n ...(relation(node.labelledBy) === undefined ? {} : { labelledBy: relation(node.labelledBy)! }),\n ...(relation(node.describedBy) === undefined\n ? {}\n : { describedBy: relation(node.describedBy)! }),\n ...(state?.disabled === undefined ? {} : { disabled: state.disabled }),\n ...(state?.selected === undefined ? {} : { selected: state.selected }),\n ...(state?.expanded === undefined ? {} : { expanded: state.expanded }),\n ...(state?.busy === undefined ? {} : { busy: state.busy }),\n ...(state?.modal === undefined ? {} : { modal: state.modal }),\n ...(state?.hidden === undefined ? {} : { hidden: state.hidden }),\n ...(state?.readonly === undefined ? {} : { readOnly: state.readonly }),\n ...(toggledFor(state?.checked) === undefined\n ? {}\n : { toggled: toggledFor(state?.checked)! }),\n };\n nodes.push(Object.freeze([id, Object.freeze(accessKitNode)] as const));\n }\n\n const rootId = snapshot.rootIds[0];\n const root = rootId === undefined ? undefined : idOf.get(rootId);\n\n const update: AccessKitTreeUpdate = {\n nodes: Object.freeze(nodes),\n ...(root === undefined\n ? {}\n : {\n tree: Object.freeze({\n root,\n ...(options.toolkitName === undefined ? {} : { toolkitName: options.toolkitName }),\n ...(options.toolkitVersion === undefined\n ? {}\n : { toolkitVersion: options.toolkitVersion }),\n }),\n }),\n treeId: options.treeId ?? ACCESSKIT_ROOT_TREE_ID,\n focus: focus ?? root ?? 0,\n };\n\n return Object.freeze({ update: Object.freeze(update), cellBounds: Object.freeze(cellBounds) });\n}\n","/**\n * Resolving IR geometry into the single rectangle a semantic node publishes.\n *\n * The IR keeps `intendedRect` and `visibleRect` apart because they are\n * different facts. `SemanticNode.bounds` is one rectangle, so somewhere the two\n * have to collapse — and that collapse is a decision, not a formatting step.\n *\n * The decision: **`bounds` is always the best known *visible* geometry.** A\n * consumer never has to ask which of the two it is holding, because the answer\n * is always the same one. Publishing both rectangles instead would push \"which\n * of these did you mean\" onto every consumer of the tree — the same one-field-\n * two-jobs problem, moved rather than solved.\n *\n * What a consumer still cannot know from `bounds` alone is whether something\n * else was painted on top. That is what {@link ResolvedBounds.occlusion}\n * carries, and it is why the two are resolved together here rather than in five\n * independent implementations.\n */\n\nimport type { Rect } from '../tree.js';\nimport type { ProbeGeometry, ProbeRect } from './ir.js';\n\n/** Whether occlusion is knowable for this node. */\nexport type OcclusionKnowledge = 'known' | 'unknown';\n\n/** Which of the IR rectangles the published bounds came from. */\nexport type BoundsSource = 'visible' | 'clipped' | 'intended';\n\n/** The rectangle a node publishes, plus what is known about it. */\nexport interface ResolvedBounds {\n readonly rect: Rect;\n /**\n * `known` only when the probe reports paint order. Without it, a rectangle\n * says where a widget is, not whether a pointer aimed there reaches it.\n */\n readonly occlusion: OcclusionKnowledge;\n readonly source: BoundsSource;\n /**\n * True when the clip removed the rectangle entirely — the node exists and is\n * scrolled out of view.\n *\n * A normalizer maps this to **`state.hidden: true` plus\n * `state.offscreen: true`**. Both are needed and they say different things:\n * `hidden` because a zero-area rectangle cannot intersect the viewport and\n * validation refuses it otherwise, and `offscreen` because scrolled-away is\n * not the same state as never-displayed, and a consumer reading the tree has\n * no other way to tell them apart.\n */\n readonly clippedAway: boolean;\n}\n\n/** Settings for {@link resolveNodeBounds}. */\nexport interface ResolveBoundsOptions {\n /**\n * The clip imposed by ancestors, where the framework exposes one and has not\n * already applied it to `visibleRect`.\n */\n readonly clip?: ProbeRect;\n /** Whether the probe reports paint order for this object. */\n readonly paintOrderKnown?: boolean;\n}\n\nfunction intersect(a: ProbeRect, b: ProbeRect): { rect: Rect; empty: boolean } {\n const row = Math.max(a.row, b.row);\n const column = Math.max(a.column, b.column);\n const bottom = Math.min(a.row + a.height, b.row + b.height);\n const right = Math.min(a.column + a.width, b.column + b.width);\n const height = Math.max(0, bottom - row);\n const width = Math.max(0, right - column);\n return { rect: { row, column, width, height }, empty: width === 0 || height === 0 };\n}\n\n/**\n * Collapse IR geometry into the rectangle a semantic node publishes.\n *\n * Three tiers, best first:\n * 1. `visibleRect`, where the framework computed the clip intersection itself;\n * 2. `intendedRect ∩ clip`, where a clip is known but not pre-applied;\n * 3. `intendedRect` alone, as a last resort — it is where the widget *asked* to\n * draw, which is the only thing left when nothing knows about clipping.\n *\n * @param geometry - IR geometry for the object, if it reported any.\n * @param options - Clip and paint-order knowledge.\n * @returns The resolved bounds, or `undefined` when the object reported no\n * geometry at all. A bounds-free node is a legal, expected state — one audited\n * framework hands over a rendered string with no coordinates anywhere — and\n * inventing a rectangle for it would be worse than having none.\n */\nexport function resolveNodeBounds(\n geometry: ProbeGeometry | undefined,\n options: ResolveBoundsOptions = {},\n): ResolvedBounds | undefined {\n const occlusion: OcclusionKnowledge = options.paintOrderKnown === true ? 'known' : 'unknown';\n\n if (geometry?.visibleRect !== undefined) {\n const rect = geometry.visibleRect;\n return {\n rect,\n occlusion,\n source: 'visible',\n clippedAway: rect.width === 0 || rect.height === 0,\n };\n }\n\n if (geometry?.intendedRect === undefined) return undefined;\n\n if (options.clip !== undefined) {\n const { rect, empty } = intersect(geometry.intendedRect, options.clip);\n // A widget whose intended rectangle was already empty was not made\n // offscreen by this clip. Conflating the two would claim that scrolling\n // can reveal a node that never occupied a cell in the first place.\n const occupiedCells = geometry.intendedRect.width > 0 && geometry.intendedRect.height > 0;\n return { rect, occlusion, source: 'clipped', clippedAway: empty && occupiedCells };\n }\n\n return {\n rect: geometry.intendedRect,\n occlusion,\n source: 'intended',\n clippedAway: false,\n };\n}\n","/**\n * Validation for Probe IR frames.\n *\n * Same discipline as the semantic tree: project into a frozen plain DTO first\n * so a getter on hostile input is rejected without running, then measure\n * against the byte ceiling, then check the shape. A probe runs inside the\n * process under test, which may be broken or malicious, so this is a hostile\n * boundary in exactly the way the adapter channel is.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport type { ProtocolLimits } from '../limits.js';\nimport type { ValidationErrorCode } from '../validate.js';\nimport { ProtocolViolation } from '../errors.js';\nimport { encodeFrame, projectDto } from '../framing.js';\nimport {\n PROBE_CAPABILITIES,\n PROBE_UNOBSERVABLE_FIELDS,\n type ProbeAnnotations,\n type ProbeFrame,\n type ProbeInfo,\n} from './ir.js';\nimport { SEMANTIC_ACTIONS } from '../roles.js';\n\n/** Structured result: never throws hostile data onward. */\nexport type ProbeValidationResult =\n | { readonly ok: true; readonly frame: ProbeFrame }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\n/** Result of validating one optional-SDK annotation at the probe boundary. */\nexport type ProbeAnnotationValidationResult =\n | { readonly ok: true; readonly annotations: ProbeAnnotations }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nfunction fail(code: ValidationErrorCode, detail: string): ProbeValidationResult {\n return { ok: false, code, detail };\n}\n\nconst safeInt = z.number().refine(Number.isSafeInteger, 'expected a safe integer');\nconst nonNegative = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\nconst positive = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n\nconst cache = new WeakMap<ProtocolLimits, z.ZodType>();\n\nfunction buildFrameSchema(limits: ProtocolLimits): z.ZodType {\n const text = z\n .string()\n .refine(\n (s) => Buffer.byteLength(s, 'utf8') <= limits.maxStringBytes,\n `expected at most ${limits.maxStringBytes} UTF-8 bytes`,\n );\n\n const rect = z.strictObject({\n row: safeInt,\n column: safeInt,\n width: nonNegative,\n height: nonNegative,\n });\n\n const identity = z.strictObject({\n kind: z.enum(['stable', 'frame-local']),\n value: text.min(1),\n });\n\n const extendedValue: z.ZodType = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z.number().finite().refine(\n (value) => Math.abs(value) <= Number.MAX_SAFE_INTEGER,\n 'expected a finite JSON number in the safe range',\n ),\n text,\n z.array(extendedValue).max(limits.maxRelationTargets),\n z.record(text, extendedValue).refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n ),\n ]),\n );\n const extended = z.record(text, extendedValue).refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n );\n const relations = z.array(text.min(1)).max(limits.maxRelationTargets);\n\n const state = z.strictObject({\n focused: z.boolean().optional(),\n disabled: z.boolean().optional(),\n checked: z.union([z.boolean(), z.literal('mixed')]).optional(),\n expanded: z.boolean().optional(),\n readonly: z.boolean().optional(),\n selected: z.boolean().optional(),\n busy: z.boolean().optional(),\n multiline: z.boolean().optional(),\n displayed: z.boolean().optional(),\n value: text.optional(),\n selectedIndex: nonNegative.optional(),\n textSelection: z.strictObject({ start: nonNegative, end: nonNegative }).optional(),\n scroll: z.strictObject({ row: nonNegative, column: nonNegative }).optional(),\n scrollExtent: z.strictObject({ rows: nonNegative, columns: nonNegative }).optional(),\n });\n\n const object = z.strictObject({\n identity,\n frameworkType: text.min(1),\n parent: text.optional(),\n geometry: z\n .strictObject({ intendedRect: rect.optional(), visibleRect: rect.optional() })\n .optional(),\n state: state.optional(),\n text: text.optional(),\n accessibility: z\n .strictObject({ role: text.optional(), name: text.optional(), description: text.optional() })\n .optional(),\n annotations: z\n .strictObject({\n role: text.optional(),\n name: text.optional(),\n testId: text.optional(),\n description: text.optional(),\n extended: extended.optional(),\n actions: z.array(z.enum(SEMANTIC_ACTIONS)).max(SEMANTIC_ACTIONS.length).optional(),\n labelledBy: relations.optional(),\n describedBy: relations.optional(),\n })\n .optional(),\n paintOrder: safeInt.optional(),\n unobservable: z\n .array(z.enum(PROBE_UNOBSERVABLE_FIELDS))\n .max(PROBE_UNOBSERVABLE_FIELDS.length)\n .optional(),\n });\n\n const operation = z.strictObject({\n kind: z.enum(['render', 'layout']),\n ordinal: nonNegative,\n target: identity.optional(),\n frameworkType: text.optional(),\n intendedRect: rect.optional(),\n });\n\n return z.strictObject({\n frame: positive,\n objects: z.array(object).max(limits.maxNodes),\n operations: z.array(operation).max(limits.maxNodes).optional(),\n });\n}\n\nfunction frameSchema(limits: ProtocolLimits): z.ZodType {\n const cached = cache.get(limits);\n if (cached !== undefined) return cached;\n const built = buildFrameSchema(limits);\n cache.set(limits, built);\n return built;\n}\n\n/** Schema for the handshake block a probe sends about itself. */\nexport const probeInfoSchema = z.strictObject({\n framework: z.string().min(1).max(128),\n frameworkVersion: z.string().max(128).optional(),\n probeVersion: z.string().min(1).max(128),\n identityKind: z.enum(['stable', 'frame-local']),\n capabilities: z.array(z.enum(PROBE_CAPABILITIES)).max(PROBE_CAPABILITIES.length),\n});\n\n/**\n * Validate a probe's self-description.\n *\n * Enforces the one consistency rule the pair has: a probe may not claim the\n * `stable-identity` capability while declaring `identityKind: 'frame-local'`.\n * Those two together would tell a consumer it is safe to correlate objects\n * across frames in a framework where nothing survives the frame.\n */\nexport function validateProbeInfo(\n value: unknown,\n): { readonly ok: true; readonly info: ProbeInfo } | { readonly ok: false; readonly detail: string } {\n const parsed = probeInfoSchema.safeParse(value);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return { ok: false, detail: `${where}: ${issue.message}` };\n }\n const info = parsed.data as ProbeInfo;\n if (info.identityKind === 'frame-local' && info.capabilities.includes('stable-identity')) {\n return {\n ok: false,\n detail:\n \"a probe declaring identityKind 'frame-local' must not claim the 'stable-identity' \" +\n 'capability: nothing in an immediate-mode frame survives to be correlated',\n };\n }\n return { ok: true, info: Object.freeze(info) };\n}\n\n/**\n * Validate an untrusted probe frame.\n *\n * Beyond the shape, three cross-object rules are checked, each of them a way an\n * IR frame can be internally inconsistent rather than merely malformed:\n * identities must be unique within the frame, a declared parent must exist in\n * the same frame, and a field cannot be both reported and declared\n * unobservable.\n *\n * @param value - Untrusted candidate frame.\n * @param limits - Active limits; `maxNodes`, `maxStringBytes` and\n * `maxSnapshotBytes` apply.\n * @returns `{ ok: true, frame }` deep-frozen, or a typed failure. Never throws.\n */\nexport function validateProbeFrame(\n value: unknown,\n limits: ProtocolLimits,\n): ProbeValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) return fail('schema', 'probe frame is not a JSON object');\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxSnapshotBytes) {\n return fail('bytes', `probe frame is ${bytes} bytes, ceiling is ${limits.maxSnapshotBytes}`);\n }\n\n const parsed = frameSchema(limits).safeParse(projected);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n const path = issue.path.map(String);\n const where = path.length > 0 ? path.join('.') : '<root>';\n const code: ValidationErrorCode = path.includes('intendedRect') || path.includes('visibleRect')\n ? 'bad-rect'\n : path.includes('frame')\n ? 'revision'\n : issue.code === 'too_big'\n ? 'count'\n : 'schema';\n return fail(code, `${where}: ${issue.message}`);\n }\n\n const frame = projected as ProbeFrame;\n\n const seen = new Set<string>();\n for (const object of frame.objects) {\n if (seen.has(object.identity.value)) {\n return fail('duplicate-id', `identity ${object.identity.value} appears twice in the frame`);\n }\n seen.add(object.identity.value);\n }\n\n for (const object of frame.objects) {\n if (object.parent !== undefined && !seen.has(object.parent)) {\n return fail(\n 'missing-parent',\n `object ${object.identity.value} names parent ${object.parent}, which is not in the frame`,\n );\n }\n if (object.parent === object.identity.value) {\n return fail('cycle', `object ${object.identity.value} is its own parent`);\n }\n\n const unobservable = object.unobservable;\n if (unobservable === undefined) continue;\n const declared = new Set<string>(unobservable);\n if (declared.size !== unobservable.length) {\n return fail('duplicate-id', `object ${object.identity.value} repeats an unobservable field`);\n }\n // Reporting a value while calling the field unobservable is a contradiction,\n // and the whole point of the three-valued model is that it cannot happen.\n for (const [field, present] of [\n ['text', object.text !== undefined],\n ['parent', object.parent !== undefined],\n ['intendedRect', object.geometry?.intendedRect !== undefined],\n ['visibleRect', object.geometry?.visibleRect !== undefined],\n ['paintOrder', object.paintOrder !== undefined],\n ] as const) {\n if (declared.has(field) && present) {\n return fail(\n 'schema',\n `object ${object.identity.value} reports ${field} and also declares it unobservable`,\n );\n }\n }\n for (const [field, value_] of Object.entries(object.state ?? {})) {\n if (declared.has(field) && value_ !== undefined) {\n return fail(\n 'schema',\n `object ${object.identity.value} reports state.${field} and also declares it unobservable`,\n );\n }\n }\n }\n\n return { ok: true, frame };\n}\n\n/**\n * Validate one developer annotation before adding it to an otherwise trusted\n * framework observation.\n *\n * Annotation registries intentionally use `Symbol.for` so an optional SDK and\n * an injected probe can meet without importing one another. That also makes\n * the registry a hostile boundary: application code can forge an entry with a\n * getter, cycle, oversized value or unknown action. Reusing the complete frame\n * validator here keeps both boundaries byte-for-byte consistent. Callers can\n * then omit only the bad annotation instead of losing the framework frame or\n * closing the probe channel.\n */\nexport function validateProbeAnnotations(\n value: unknown,\n limits: ProtocolLimits,\n): ProbeAnnotationValidationResult {\n const result = validateProbeFrame(\n {\n frame: 1,\n objects: [\n {\n identity: { kind: 'stable', value: 'a' },\n frameworkType: 'A',\n annotations: value,\n },\n ],\n },\n limits,\n );\n if (!result.ok) return { ok: false, code: result.code, detail: result.detail };\n const annotations = result.frame.objects[0]?.annotations;\n if (annotations === undefined) {\n return {\n ok: false,\n code: 'schema',\n detail: 'annotations: expected an annotation object',\n };\n }\n try {\n // A valid snapshot can still be impossible to put on the negotiated wire\n // when maxFrameBytes is tighter than maxSnapshotBytes. Bound the optional\n // payload at its own boundary so one forged SDK entry cannot poison the\n // whole probe channel later.\n encodeFrame({ annotations }, limits.maxFrameBytes);\n } catch (error) {\n return {\n ok: false,\n code: error instanceof ProtocolViolation && error.code === 'frame-oversized'\n ? 'bytes'\n : 'schema',\n detail: error instanceof Error ? error.message : 'annotations could not be framed',\n };\n }\n return { ok: true, annotations };\n}\n","import { z } from 'zod';\nimport type { SemanticSnapshot } from './tree.js';\nimport type { LogRecord } from './logs.js';\nimport type { TreeDelta } from './delta.js';\nimport type { ProbeInfo } from './probe/ir.js';\nimport type { ProtocolLimits } from './limits.js';\nimport { PROTOCOL_ID, PROTOCOL_V2_ID, type ProtocolId } from './env.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\nimport { validateSnapshot } from './validate.js';\nimport { validateLogRecord } from './logs.js';\nimport { validateTreeDelta } from './delta.js';\nimport { probeInfoSchema, validateProbeInfo } from './probe/validate.js';\n\n/**\n * Wire messages. Transport: length-prefixed JSON frames (see framing.ts).\n * CDP-like: adapter pushes commits; driver issues requests; either side may\n * send errors. All messages are validated against limits BEFORE retention.\n */\n\nexport const ADAPTER_CAPABILITIES = [\n 'tree',\n 'bounds',\n 'absolute-bounds',\n 'states',\n 'actions',\n 'text-ranges',\n 'render-revisions',\n 'tree-diffs',\n 'logs',\n 'qualified-observations',\n 'pointer-hit-grid',\n] as const;\nexport type AdapterCapability = (typeof ADAPTER_CAPABILITIES)[number];\n\n/** adapter → driver, exactly once, before any other message. */\nexport interface HelloMessage {\n readonly type: 'hello';\n readonly protocol: ProtocolId;\n readonly token: string;\n readonly adapter: { readonly name: string; readonly version: string };\n readonly capabilities: readonly AdapterCapability[];\n /**\n * Present when the sender is a probe rather than a hand-written adapter.\n *\n * Carries what the probe can actually offer — framework and versions, the\n * best identity it can produce, and its optional abilities — so the driver\n * negotiates against measured capability rather than assuming a floor.\n */\n readonly probe?: ProbeInfo;\n}\n\n/** driver → adapter, reply to hello. */\nexport interface HelloAckMessage {\n readonly type: 'hello-ack';\n readonly protocol: ProtocolId;\n readonly sessionId: string;\n readonly limits: ProtocolLimits;\n /**\n * Which traffic the driver wants pushed.\n *\n * `diffs` is only ever selected for an adapter that announced the\n * `tree-diffs` capability, so an adapter that does not know the value never\n * receives it — the closed set grew without breaking anyone, because the\n * adapter opts in first.\n */\n readonly subscribe: 'snapshots' | 'revisions' | 'diffs';\n /** Marker configuration: producer must emit the signed OSC 8487 commit marker. */\n readonly marker: { readonly enabled: boolean };\n /**\n * Log-channel budget, sent only when the adapter announced the `logs`\n * capability. **Absent means logs are disabled** — an adapter that receives\n * no `logs` field must not emit `log` messages at all.\n *\n * The adapter enforces the rate itself and drops locally when over budget,\n * leaving a gap in `LogRecord.seq` so the driver can report how many records\n * were lost. Enforcing it at the source is what keeps a log storm from\n * consuming the frame budget the semantic tree needs.\n */\n readonly logs?: {\n readonly enabled: boolean;\n /** Sustained ceiling on records per second. */\n readonly maxRecordsPerSecond: number;\n /** Records allowed in a burst on top of the sustained rate. */\n readonly burst: number;\n };\n}\n\n/** adapter → driver after each committed render (always, regardless of mode). */\nexport interface RevisionCommitMessage {\n readonly type: 'revision-commit';\n readonly revision: number;\n}\n\n/** adapter → driver, full snapshot for a revision (subscribe: 'snapshots'). */\nexport interface SnapshotMessage {\n readonly type: 'snapshot';\n readonly snapshot: SemanticSnapshot;\n}\n\n/** driver → adapter, request full snapshot (latest, or a held revision). */\nexport interface GetTreeRequest {\n readonly type: 'get-tree';\n readonly requestId: number;\n readonly revision?: number;\n}\n\n/** adapter → driver, response to get-tree. */\nexport interface GetTreeResponse {\n readonly type: 'get-tree-result';\n readonly requestId: number;\n readonly snapshot?: SemanticSnapshot;\n readonly error?: string;\n}\n\n/**\n * adapter → driver, a frame has started (capability `frame-begin`).\n *\n * **Optional, and its absence means nothing.** No audited framework offers a\n * hook guaranteed to fire before every frame: one lets a pre-draw hook veto the\n * frame entirely, so the post-draw hook never runs; one exposes only a\n * post-frame hook; one decouples submission from the flush with a ticker. A\n * receiver that reads \"no frame-begin\" as \"no frame in progress\" turns four of\n * the six frameworks into a hang rather than an error.\n *\n * `FRAME_END` is the existing `revision-commit`, which stays advisory.\n *\n * **Abandoned frames**: a probe may begin a frame and never finish it — a\n * crash, an interrupted render. A `frame-begin` for revision N implicitly\n * closes every frame below N. Without that rule an open frame waits forever,\n * which is the timeout it replaced, only now wearing a false air of precision.\n */\nexport interface FrameBeginMessage {\n readonly type: 'frame-begin';\n readonly revision: number;\n}\n\n/**\n * adapter → driver, an incremental tree update (capability `tree-diffs`,\n * `subscribe: 'diffs'`).\n *\n * Bound to an exact base revision: see `delta.ts` for composition semantics.\n * A receiver that does not hold `baseRevision` must request a full snapshot\n * with `get-tree` rather than patch speculatively.\n */\nexport interface TreeDeltaMessage extends TreeDelta {\n readonly type: 'tree-delta';\n}\n\n/**\n * adapter → driver, one application log record (capability `logs`).\n *\n * Sent only after the driver enabled logs in `hello-ack`. Records are\n * independent of renders: they are not paired with a revision and never gate\n * snapshot publication.\n */\nexport interface LogMessage {\n readonly type: 'log';\n readonly record: LogRecord;\n}\n\n/** either direction: terminal protocol error; sender closes after emitting. */\nexport interface ProtocolErrorMessage {\n readonly type: 'error';\n readonly code:\n | 'bad-token'\n | 'bad-version'\n | 'malformed'\n | 'limit-exceeded'\n | 'internal';\n readonly message: string;\n}\n\nexport type AdapterToDriverMessage =\n | HelloMessage\n | RevisionCommitMessage\n | SnapshotMessage\n | GetTreeResponse\n | TreeDeltaMessage\n | FrameBeginMessage\n | LogMessage\n | ProtocolErrorMessage;\n\nexport type DriverToAdapterMessage =\n | HelloAckMessage\n | GetTreeRequest\n | ProtocolErrorMessage;\n\n// --------------------------------------------------------------------------\n// Runtime validation\n//\n// The interfaces above are the contract; the schemas below are how untrusted\n// bytes become instances of it. Every parse projects the value into a frozen\n// plain DTO first, so a getter on hostile input is rejected without running.\n// --------------------------------------------------------------------------\n\n/** Outcome of parsing one wire message. Mirrors `ProtocolErrorMessage['code']`. */\nexport type MessageParseResult<T> =\n | { readonly ok: true; readonly message: T }\n | {\n readonly ok: false;\n readonly code: 'bad-version' | 'malformed' | 'limit-exceeded';\n readonly detail: string;\n };\n\n/** Longest token/identifier/message string accepted, in UTF-16 code units. */\nconst MAX_IDENTIFIER_LENGTH = 1024;\n\nconst identifier = z.string().max(MAX_IDENTIFIER_LENGTH);\nconst nonEmptyIdentifier = identifier.min(1);\nconst safeIndex = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\nconst revisionNumber = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n\n/**\n * Limits are an ADDITIVE part of the contract: unknown keys are IGNORED, not\n * rejected. A driver that learns a new ceiling must not break every already\n * published adapter, so this is the one object on the wire read leniently.\n * Known keys stay strict about their type, and every closed set elsewhere\n * (message types, roles, actions, capabilities) stays strict too.\n */\nconst limitsSchema = z.object({\n maxFrameBytes: revisionNumber,\n maxSnapshotBytes: revisionNumber,\n maxNodes: revisionNumber,\n maxDepth: revisionNumber,\n maxStringBytes: revisionNumber,\n maxRelationTargets: revisionNumber,\n maxQueuedFrames: revisionNumber,\n maxPendingWaiters: revisionNumber,\n maxSessions: revisionNumber,\n maxLogRecordBytes: revisionNumber,\n maxLogQueue: revisionNumber,\n});\n\nconst errorFields = {\n type: z.literal('error'),\n code: z.enum(['bad-token', 'bad-version', 'malformed', 'limit-exceeded', 'internal']),\n message: z.string().max(MAX_IDENTIFIER_LENGTH),\n};\n\n/** adapter → driver: strict, this is the hostile-input boundary. */\nconst errorSchema = z.strictObject(errorFields);\n\n/** driver → adapter: tolerant envelope, see the note above `parseDriverMessage`. */\nconst errorFromDriverSchema = z.object(errorFields);\n\n/** adapter → driver schemas. Snapshot bodies are validated separately. */\nconst helloSchema = z.strictObject({\n type: z.literal('hello'),\n protocol: z.union([z.literal(PROTOCOL_ID), z.literal(PROTOCOL_V2_ID)]),\n token: nonEmptyIdentifier,\n adapter: z.strictObject({ name: nonEmptyIdentifier, version: nonEmptyIdentifier }),\n capabilities: z.array(z.enum(ADAPTER_CAPABILITIES)).max(ADAPTER_CAPABILITIES.length),\n probe: probeInfoSchema.optional(),\n});\n\nconst frameBeginSchema = z.strictObject({\n type: z.literal('frame-begin'),\n revision: revisionNumber,\n});\n\nconst revisionCommitSchema = z.strictObject({\n type: z.literal('revision-commit'),\n revision: revisionNumber,\n});\n\nconst snapshotEnvelopeSchema = z.strictObject({\n type: z.literal('snapshot'),\n snapshot: z.unknown(),\n});\n\nconst treeDeltaTypeSchema = z.object({ type: z.literal('tree-delta') });\n\nconst logEnvelopeSchema = z.strictObject({\n type: z.literal('log'),\n record: z.unknown(),\n});\n\nconst getTreeResultSchema = z\n .strictObject({\n type: z.literal('get-tree-result'),\n requestId: safeIndex,\n snapshot: z.unknown().optional(),\n error: z.string().max(MAX_IDENTIFIER_LENGTH).optional(),\n })\n .refine(\n (m) => (m.snapshot === undefined) !== (m.error === undefined),\n 'exactly one of snapshot or error must be present',\n );\n\n/** driver → adapter schemas. */\nconst helloAckSchema = z.object({\n type: z.literal('hello-ack'),\n protocol: z.union([z.literal(PROTOCOL_ID), z.literal(PROTOCOL_V2_ID)]),\n sessionId: nonEmptyIdentifier,\n limits: limitsSchema,\n subscribe: z.enum(['snapshots', 'revisions', 'diffs']),\n marker: z.object({ enabled: z.boolean() }),\n logs: z\n .object({\n enabled: z.boolean(),\n maxRecordsPerSecond: revisionNumber,\n burst: safeIndex,\n })\n .optional(),\n});\n\nconst getTreeRequestSchema = z.object({\n type: z.literal('get-tree'),\n requestId: safeIndex,\n revision: revisionNumber.optional(),\n});\n\nfunction malformed(detail: string): MessageParseResult<never> {\n return { ok: false, code: 'malformed', detail };\n}\n\n/** Projection guard shared by both parsers. */\nfunction project(value: unknown, limits: ProtocolLimits): MessageParseResult<unknown> {\n try {\n return { ok: true, message: projectDto<unknown>(value, limits.maxDepth) };\n } catch (error) {\n const detail =\n error instanceof ProtocolViolation ? error.message : 'value is not a plain JSON DTO';\n return error instanceof ProtocolViolation && error.code === 'dto-depth'\n ? { ok: false, code: 'limit-exceeded', detail }\n : malformed(detail);\n }\n}\n\nfunction messageType(value: unknown): string | null {\n if (typeof value !== 'object' || value === null) return null;\n const type: unknown = (value as { type?: unknown }).type;\n return typeof type === 'string' ? type : null;\n}\n\nfunction check(schema: z.ZodType, value: unknown): string | null {\n const result = schema.safeParse(value);\n if (result.success) return null;\n const issue = result.error.issues[0]!;\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return `${where}: ${issue.message}`;\n}\n\n/**\n * Validate a snapshot carried inside an envelope and map its failure onto the\n * wire error taxonomy: capacity failures are `limit-exceeded`, the rest are\n * `malformed`.\n */\nfunction checkSnapshot(value: unknown, limits: ProtocolLimits): MessageParseResult<never> | null {\n const result = validateSnapshot(value, limits);\n if (result.ok) return null;\n const overCapacity =\n result.code === 'bytes' ||\n result.code === 'count' ||\n result.code === 'depth' ||\n result.code === 'string-bytes';\n return {\n ok: false,\n code: overCapacity ? 'limit-exceeded' : 'malformed',\n detail: `snapshot ${result.code}: ${result.detail}`,\n };\n}\n\n/**\n * Validate a log record carried inside an envelope, mapping capacity failures\n * onto `limit-exceeded` exactly as snapshots do.\n */\nfunction checkLogRecord(value: unknown, limits: ProtocolLimits): MessageParseResult<never> | null {\n const result = validateLogRecord(value, limits);\n if (result.ok) return null;\n const overCapacity =\n result.code === 'bytes' ||\n result.code === 'count' ||\n result.code === 'depth' ||\n result.code === 'string-bytes';\n return {\n ok: false,\n code: overCapacity ? 'limit-exceeded' : 'malformed',\n detail: `log record ${result.code}: ${result.detail}`,\n };\n}\n\n/**\n * Validate a tree delta carried inside an envelope, mapping capacity failures\n * onto `limit-exceeded` exactly as snapshots do.\n */\nfunction checkTreeDelta(value: unknown, limits: ProtocolLimits): MessageParseResult<never> | null {\n const result = validateTreeDelta(value, limits);\n if (result.ok) return null;\n const overCapacity =\n result.code === 'bytes' ||\n result.code === 'count' ||\n result.code === 'depth' ||\n result.code === 'string-bytes';\n return {\n ok: false,\n code: overCapacity ? 'limit-exceeded' : 'malformed',\n detail: `tree delta ${result.code}: ${result.detail}`,\n };\n}\n\n/**\n * Parse and validate one adapter → driver message.\n *\n * **Strict reader**: this is the hostile-input boundary, so unknown fields are\n * rejected rather than ignored. See {@link parseDriverMessage} for why the\n * other direction is tolerant.\n *\n * @param value - Untrusted decoded frame body.\n * @param limits - Active session limits, applied to any embedded snapshot.\n * @returns A frozen message on success, or a typed failure. Never throws.\n */\nexport function parseAdapterMessage(\n value: unknown,\n limits: ProtocolLimits,\n): MessageParseResult<AdapterToDriverMessage> {\n const projected = project(value, limits);\n if (!projected.ok) return projected;\n const dto = projected.message;\n\n switch (messageType(dto)) {\n case 'hello': {\n const protocol: unknown = (dto as { protocol?: unknown }).protocol;\n if (typeof protocol === 'string' && protocol !== PROTOCOL_ID && protocol !== PROTOCOL_V2_ID) {\n return { ok: false, code: 'bad-version', detail: `unsupported protocol ${protocol}` };\n }\n const issue = check(helloSchema, dto);\n if (issue !== null) return malformed(issue);\n const candidate = dto as HelloMessage;\n const qualified = candidate.capabilities.includes('qualified-observations');\n if ((candidate.protocol === PROTOCOL_V2_ID) !== qualified) {\n return malformed(\n candidate.protocol === PROTOCOL_V2_ID\n ? \"termwright/2 requires the 'qualified-observations' capability\"\n : \"'qualified-observations' requires termwright/2\",\n );\n }\n if (candidate.capabilities.includes('pointer-hit-grid') && !qualified) {\n return malformed(\"'pointer-hit-grid' requires qualified observations\");\n }\n // The shape check cannot see the one incoherent pair: a probe declaring\n // frame-local identity while claiming it can be correlated across\n // frames. That rule has to hold on the wire, not only when a caller\n // remembers to run the helper.\n const probe = (dto as { probe?: unknown }).probe;\n if (probe !== undefined) {\n const checked = validateProbeInfo(probe);\n if (!checked.ok) return malformed(`probe: ${checked.detail}`);\n }\n return { ok: true, message: dto as HelloMessage };\n }\n case 'revision-commit': {\n const issue = check(revisionCommitSchema, dto);\n return issue === null\n ? { ok: true, message: dto as RevisionCommitMessage }\n : malformed(issue);\n }\n case 'snapshot': {\n const issue = check(snapshotEnvelopeSchema, dto);\n if (issue !== null) return malformed(issue);\n const bad = checkSnapshot((dto as { snapshot: unknown }).snapshot, limits);\n return bad ?? { ok: true, message: dto as SnapshotMessage };\n }\n case 'get-tree-result': {\n const issue = check(getTreeResultSchema, dto);\n if (issue !== null) return malformed(issue);\n const envelope = dto as { snapshot?: unknown };\n if (envelope.snapshot !== undefined) {\n const bad = checkSnapshot(envelope.snapshot, limits);\n if (bad !== null) return bad;\n }\n return { ok: true, message: dto as GetTreeResponse };\n }\n case 'frame-begin': {\n const issue = check(frameBeginSchema, dto);\n return issue === null\n ? { ok: true, message: dto as FrameBeginMessage }\n : malformed(issue);\n }\n case 'tree-delta': {\n const issue = check(treeDeltaTypeSchema, dto);\n if (issue !== null) return malformed(issue);\n // The delta body is everything but the discriminator.\n const { type: _type, ...body } = dto as Record<string, unknown>;\n const bad = checkTreeDelta(body, limits);\n return bad ?? { ok: true, message: dto as TreeDeltaMessage };\n }\n case 'log': {\n const issue = check(logEnvelopeSchema, dto);\n if (issue !== null) return malformed(issue);\n const bad = checkLogRecord((dto as { record: unknown }).record, limits);\n return bad ?? { ok: true, message: dto as LogMessage };\n }\n case 'error': {\n const issue = check(errorSchema, dto);\n return issue === null\n ? { ok: true, message: dto as ProtocolErrorMessage }\n : malformed(issue);\n }\n default:\n return malformed('unknown or missing message type');\n }\n}\n\n/**\n * Parse and validate one driver → adapter message.\n *\n * **Tolerant reader.** Unlike {@link parseAdapterMessage}, unknown envelope\n * fields are ignored rather than rejected, and are carried through to the\n * caller so a reader that does understand them still can. Known fields stay\n * strictly type-checked, and closed sets (`type`, `code`, `subscribe`) stay\n * closed — an unknown message type is still `malformed`.\n *\n * The asymmetry is about who is speaking, not about the message. The driver is\n * the trusted party and behaviour is governed by negotiated capabilities, so a\n * newer driver may add an optional field without invalidating every adapter\n * already published. Traffic in the other direction crosses the hostile-input\n * boundary and stays strict.\n *\n * @param value - Decoded frame body from the driver.\n * @param limits - Active session limits used for the projection depth bound.\n * @returns A frozen message on success, or a typed failure. Never throws.\n */\nexport function parseDriverMessage(\n value: unknown,\n limits: ProtocolLimits,\n): MessageParseResult<DriverToAdapterMessage> {\n const projected = project(value, limits);\n if (!projected.ok) return projected;\n const dto = projected.message;\n\n switch (messageType(dto)) {\n case 'hello-ack': {\n const protocol: unknown = (dto as { protocol?: unknown }).protocol;\n if (typeof protocol === 'string' && protocol !== PROTOCOL_ID && protocol !== PROTOCOL_V2_ID) {\n return { ok: false, code: 'bad-version', detail: `unsupported protocol ${protocol}` };\n }\n const issue = check(helloAckSchema, dto);\n return issue === null ? { ok: true, message: dto as HelloAckMessage } : malformed(issue);\n }\n case 'get-tree': {\n const issue = check(getTreeRequestSchema, dto);\n return issue === null ? { ok: true, message: dto as GetTreeRequest } : malformed(issue);\n }\n case 'error': {\n const issue = check(errorFromDriverSchema, dto);\n return issue === null\n ? { ok: true, message: dto as ProtocolErrorMessage }\n : malformed(issue);\n }\n default:\n return malformed('unknown or missing message type');\n }\n}\n","/**\n * Render-commit marker: emitted by the adapter into the PTY stdout AFTER the\n * last byte of the render belonging to revision N. It is a frame COMMIT\n * signal (Neovim `flush` semantics), never a data carrier.\n *\n * Encoding: a private OSC sequence terminated by BEL:\n *\n * OSC 8487 ; 'twm;' <revision> ';' <mac> BEL\n * i.e. `\\x1b]8487;twm;{rev};{mac}\\x07`\n *\n * where mac = base64url(HMAC-SHA256(token, `${sessionId}:${revision}`))\n * truncated to 16 bytes. The driver's VT layer registers an OSC handler,\n * verifies the MAC, and removes the sequence from the visible grid. Ordinary\n * application output cannot forge it. Emitted only after a successful\n * handshake; never during a normal (non-instrumented) run.\n *\n * ## Why OSC and not DCS\n *\n * ConPTY rewrites the stream it forwards. A passthrough probe run in CI across\n * the three platforms showed it dropping DCS, APC and OSC 8, while passing\n * private OSC with either terminator, and OSC 133. DCS therefore could not\n * carry a marker on Windows at all.\n *\n * One encoding is used everywhere rather than negotiating per platform: two\n * paths double the surface that has to stay correct, and the path used least\n * is the one that rots unnoticed. BEL is emitted rather than ST because it is\n * the terminator ConPTY was observed to forward most reliably; receivers\n * accept both, since a VT parser consumes the terminator before dispatching\n * anyway.\n *\n * ## Why 8487\n *\n * OSC numbers have no registry, only convention, so the number is chosen to\n * sit clear of everything in use: xterm's allocations (0–14, 46, 50, 52, 104,\n * 110–119), OSC 8 hyperlinks, 9 and 1337 (iTerm2), 99 and 30001 (kitty), 133\n * (FinalTerm shell integration — also the sequence ConPTY is known to\n * forward), 633 (VS Code), 697 (ConEmu) and 777–779 (urxvt/VTE). 8487 is the\n * ASCII codes of `T` and `W` — termwright — and appears in none of them.\n *\n * The `twm;` tag after the number is kept as a self-identifying guard: if\n * anything ever does claim 8487, a marker still says what it is instead of\n * being mistaken for that other feature's payload.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { ProtocolViolation } from './errors.js';\n\n/** The private OSC number carrying render-commit markers. */\nexport const MARKER_OSC_CODE = 8487;\n\n/**\n * The tag opening a marker payload, immediately after `OSC 8487;`.\n *\n * A VT parser hands an OSC handler everything after the number and its\n * separator, which is exactly what {@link verifyMarkerPayload} expects:\n *\n * ```ts\n * term.parser.registerOscHandler(MARKER_OSC_CODE, (data) => {\n * const marker = verifyMarkerPayload(data, token, sessionId);\n * if (marker !== null) commit(marker.revision);\n * return true; // consumed: keeps the sequence out of the visible grid\n * });\n * ```\n */\nexport const MARKER_OSC_PREFIX = 'twm;';\n\n/** Bytes of HMAC-SHA256 output retained in the marker MAC. */\nexport const MARKER_MAC_BYTES = 16;\n\n/** Length of the base64url-encoded MAC (16 bytes, unpadded). */\nconst MARKER_MAC_CHARS = 22;\n\n/** Canonical decimal revision: no sign, no leading zero, no whitespace. */\nconst REVISION_TEXT = /^[1-9][0-9]{0,15}$/;\n\n/** base64url alphabet, exact MAC length. */\nconst MAC_TEXT = new RegExp(`^[A-Za-z0-9_-]{${MARKER_MAC_CHARS}}$`);\n\n/** BEL, the terminator this implementation emits. */\nconst BEL = '\\x07';\n\n/** ST, the terminator a receiver must also accept. */\nconst ST = '\\x1b\\\\';\n\nexport interface RenderMarker {\n readonly revision: number;\n readonly mac: string;\n}\n\nfunction computeMac(token: string, sessionId: string, revision: number): string {\n return createHmac('sha256', token)\n .update(`${sessionId}:${revision}`, 'utf8')\n .digest()\n .subarray(0, MARKER_MAC_BYTES)\n .toString('base64url');\n}\n\n/**\n * Build the full escape sequence for a marker.\n *\n * @param token - Per-launch session token (`TERMWRIGHT_TOKEN`); used as the\n * HMAC key and never appears in the emitted bytes.\n * @param sessionId - Session id from the handshake, bound into the MAC so a\n * marker from one session cannot be replayed into another.\n * @param revision - Positive safe integer identifying the committed render.\n * @returns The complete `OSC … BEL` sequence to write to stdout.\n * @throws {ProtocolViolation} If the revision is not a positive safe integer,\n * or the token/sessionId are empty.\n */\nexport function encodeMarker(token: string, sessionId: string, revision: number): string {\n if (token.length === 0) {\n throw new ProtocolViolation('marker-argument', 'token must not be empty');\n }\n if (sessionId.length === 0) {\n throw new ProtocolViolation('marker-argument', 'sessionId must not be empty');\n }\n if (!Number.isSafeInteger(revision) || revision <= 0) {\n throw new ProtocolViolation('marker-argument', 'revision must be a positive safe integer');\n }\n const mac = computeMac(token, sessionId, revision);\n return `\\x1b]${MARKER_OSC_CODE};${MARKER_OSC_PREFIX}${revision};${mac}${BEL}`;\n}\n\n/**\n * Parse+verify an OSC payload (the part after `OSC 8487;`). Returns null on any mismatch.\n *\n * Total function: hostile payloads yield `null`, never an exception. The MAC\n * comparison is constant-time, and only canonically-formatted revisions are\n * accepted so `1` and `01` cannot both authenticate the same commit.\n *\n * A trailing BEL or ST is tolerated. A VT parser consumes the terminator\n * before dispatching, so a handler normally passes a payload without one,\n * while a caller scanning raw output with a regex may keep it — both must work.\n *\n * @param payload - Everything after `OSC 8487;`, i.e. `twm;{rev};{mac}`.\n * @param token - Per-launch session token used as the HMAC key.\n * @param sessionId - Session id the marker must be bound to.\n */\nexport function verifyMarkerPayload(\n payload: string,\n token: string,\n sessionId: string,\n): RenderMarker | null {\n if (token.length === 0 || sessionId.length === 0) return null;\n\n let text = payload;\n if (text.endsWith(BEL)) text = text.slice(0, -BEL.length);\n else if (text.endsWith(ST)) text = text.slice(0, -ST.length);\n\n if (!text.startsWith(MARKER_OSC_PREFIX)) return null;\n\n const body = text.slice(MARKER_OSC_PREFIX.length);\n const separator = body.indexOf(';');\n if (separator < 0) return null;\n\n const revisionText = body.slice(0, separator);\n const mac = body.slice(separator + 1);\n if (!REVISION_TEXT.test(revisionText)) return null;\n if (!MAC_TEXT.test(mac)) return null;\n\n const revision = Number(revisionText);\n if (!Number.isSafeInteger(revision) || revision <= 0) return null;\n\n const expected = Buffer.from(computeMac(token, sessionId, revision), 'utf8');\n const actual = Buffer.from(mac, 'utf8');\n // Both are MARKER_MAC_CHARS ASCII bytes by construction, but guard anyway:\n // timingSafeEqual throws on a length mismatch.\n if (expected.length !== actual.length) return null;\n if (!timingSafeEqual(expected, actual)) return null;\n\n return Object.freeze({ revision, mac });\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAGrB,IAAM,eAAe;AACrB,IAAM,YAAY;AAClB,IAAM,eAAe;AAGrB,IAAM,mBAAmB;AAC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AG,MAAM;AAC3E,QAAM,SAASA,QAAO,KAAK,KAAK,MAAM;AAGtC,MAAI,SAAS,WAAW,OAAO,OAAQ,QAAO;AAC9C,MAAI,CAAC,gBAAgB,UAAU,MAAM,EAAG,QAAO;AAE/C,SAAO,OAAO,OAAO,EAAE,UAAU,IAAI,CAAC;AACxC;","names":["Buffer","Buffer","Buffer","z","Buffer","fail","Buffer","fail","Buffer","z","Buffer","z","fail","safeInt","z","cache","Buffer","z","z","Buffer","Buffer"]}
1
+ {"version":3,"sources":["../src/env.ts","../src/errors.ts","../src/roles.ts","../src/limits.ts","../src/observation.ts","../src/node-schema.ts","../src/node-keys.ts","../src/logs.ts","../src/framing.ts","../src/accesskit.ts","../src/probe/validate.ts","../src/messages.ts","../src/validate.ts","../src/marker.ts","../src/conpty-host-rpc.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\n\n/** Environment variable names injected by the driver before spawning the child. */\nexport const ENV_ENDPOINT = 'TERMWRIGHT_ENDPOINT';\nexport const ENV_TOKEN = 'TERMWRIGHT_TOKEN';\n\n/** Current and only supported protocol major version. */\nexport const PROTOCOL_VERSION = 2 as const;\nexport const PROTOCOL_ID = 'termwright/2' as const;\nexport type ProtocolId = typeof PROTOCOL_ID;\n\n/** Entropy behind a session token, in bytes (256 bits). */\nexport const TOKEN_BYTES = 32;\n\n/**\n * Mint a session token for `TERMWRIGHT_TOKEN`.\n *\n * **The token is an opaque UTF-8 string end to end.** Whatever lands in the\n * env var is what both sides feed to the HMAC as the key — the driver must not\n * decode it back to bytes, and an adapter must not re-encode it. Honouring\n * that is what keeps non-JS clients (Python, Go, Rust) interoperable, since\n * they only ever see the string.\n *\n * The encoding here (base64url, 43 characters) is therefore a convention, not\n * a constraint: it is compact, shell-safe, and free of `=` padding.\n *\n * @returns A fresh 256-bit token. Never log or embed it; it authenticates the\n * render markers.\n */\nexport function generateToken(): string {\n return randomBytes(TOKEN_BYTES).toString('base64url');\n}\n","/**\n * Typed protocol failures. Everything in this package fails closed: a hostile\n * or merely malformed input never produces a partially-trusted value, it\n * produces a {@link ProtocolViolation} (imperative APIs) or a structured\n * `{ ok: false }` result (validation APIs).\n */\n\n/** Machine-readable reason a value was rejected. */\nexport type ProtocolViolationCode =\n /** Declared frame length exceeds the negotiated ceiling. */\n | 'frame-oversized'\n /** Frame header/body is structurally impossible (zero length, bad JSON). */\n | 'frame-malformed'\n /** Frame body is not well-formed UTF-8. */\n | 'frame-encoding'\n /** Decoder already failed; it is poisoned and refuses further input. */\n | 'decoder-poisoned'\n /** Value is not representable as JSON (undefined, bigint, function, NaN…). */\n | 'dto-scalar'\n /** String contains unpaired surrogates. */\n | 'dto-string'\n /** Object graph is not a tree: the same object is reachable twice. */\n | 'dto-alias'\n /** Property is an accessor (getter/setter) rather than plain data. */\n | 'dto-accessor'\n /** Value carries symbol keys. */\n | 'dto-symbol'\n /** Value is a Proxy, or has a prototype other than Object/Array/null. */\n | 'dto-prototype'\n /** Array has holes or extra own properties. */\n | 'dto-sparse'\n /** Property name is reserved (`__proto__`, `constructor`, `prototype`). */\n | 'dto-key'\n /** Nesting exceeds the permitted depth. */\n | 'dto-depth'\n /** A marker argument is outside its permitted domain. */\n | 'marker-argument';\n\n/**\n * Thrown when untrusted input violates a protocol invariant.\n *\n * Never carries the offending value or the session token — only a code and a\n * short structural description safe to log.\n */\nexport class ProtocolViolation extends Error {\n /** Machine-readable reason. */\n readonly code: ProtocolViolationCode;\n\n constructor(code: ProtocolViolationCode, message: string) {\n super(message);\n this.name = 'ProtocolViolation';\n this.code = code;\n }\n}\n","/**\n * Semantic roles for the current protocol. ARIA-aligned; closed set. Unknown roles must be rejected\n * during validation — they never silently acquire behavior.\n */\nexport const SEMANTIC_ROLES = [\n 'application',\n 'region',\n 'dialog',\n 'alert',\n 'status',\n 'list',\n 'listitem',\n 'menu',\n 'menuitem',\n 'button',\n 'checkbox',\n 'radio',\n 'tab',\n 'textbox',\n 'heading',\n 'text',\n 'progressbar',\n 'separator',\n 'scrollbar',\n 'table',\n 'row',\n 'cell',\n 'generic',\n] as const;\n\nexport type SemanticRole = (typeof SEMANTIC_ROLES)[number];\n\n/** Descriptive action capabilities. Diagnostic/strategy hints, never callback endpoints. */\nexport const SEMANTIC_ACTIONS = [\n 'focus',\n 'activate',\n 'toggle',\n 'setValue',\n 'scroll',\n 'select',\n 'expand',\n] as const;\n\nexport type SemanticAction = (typeof SEMANTIC_ACTIONS)[number];\n\nexport const PHYSICAL_INPUT_RECIPE_ACTIONS = ['focus', 'activate', 'toggle', 'setValue'] as const;\nexport type PhysicalInputRecipeAction = (typeof PHYSICAL_INPUT_RECIPE_ACTIONS)[number];\n\n/** Data-only physical input recipe; integrations never receive an execution callback. */\nexport type PhysicalInputRecipeStep =\n { readonly kind: 'press'; readonly key: string } | { readonly kind: 'insert-action-value' };\n\nexport interface PhysicalInputRecipe {\n readonly action: PhysicalInputRecipeAction;\n readonly requiresFocus: boolean;\n readonly steps: readonly PhysicalInputRecipeStep[];\n}\n","/**\n * Conservative defaults and absolute maxima. Callers may tighten defaults but\n * can never widen the absolute maxima.\n */\nexport interface ProtocolLimits {\n readonly maxFrameBytes: number;\n /**\n * Byte ceiling for one snapshot or probe frame.\n *\n * 2 MiB rather than 1: at the measured 217.5 B/node a full `maxNodes` tree\n * is 1 062 KiB before a single provenance byte, so the old default\n * contradicted the node ceiling it shipped with.\n */\n readonly maxSnapshotBytes: number;\n readonly maxNodes: number;\n readonly maxDepth: number;\n readonly maxStringBytes: number;\n readonly maxRelationTargets: number;\n readonly maxQueuedFrames: number;\n readonly maxPendingWaiters: number;\n readonly maxSessions: number;\n /** Byte ceiling for one serialised application log record. */\n readonly maxLogRecordBytes: number;\n /** Log records the driver buffers per session before evicting the oldest. */\n readonly maxLogQueue: number;\n}\n\nexport const DEFAULT_LIMITS: ProtocolLimits = Object.freeze({\n maxFrameBytes: 1 * 1024 * 1024,\n maxSnapshotBytes: 2 * 1024 * 1024,\n maxNodes: 5_000,\n maxDepth: 64,\n maxStringBytes: 16 * 1024,\n maxRelationTargets: 64,\n maxQueuedFrames: 32,\n maxPendingWaiters: 256,\n maxSessions: 16,\n maxLogRecordBytes: 32 * 1024,\n maxLogQueue: 1_000,\n});\n\nexport const ABSOLUTE_LIMITS: ProtocolLimits = Object.freeze({\n maxFrameBytes: 8 * 1024 * 1024,\n maxSnapshotBytes: 8 * 1024 * 1024,\n maxNodes: 50_000,\n maxDepth: 256,\n maxStringBytes: 256 * 1024,\n maxRelationTargets: 1_024,\n maxQueuedFrames: 256,\n maxPendingWaiters: 4_096,\n maxSessions: 128,\n maxLogRecordBytes: 256 * 1024,\n maxLogQueue: 10_000,\n});\n\n/** Default adapter-discovery window (ms) before an auto-detected session closes admission. */\nexport const DEFAULT_NEGOTIATION_MS = 2_000;\n","import type { Rect } from './tree.js';\nimport type { EvidenceProvenance } from './contract.js';\n\n/**\n * Why a fact is temporarily unsettled.\n *\n * Every value names a revision-domain retry boundary. Permanent inability to\n * observe a fact is `unsupported`, never `unknown`.\n */\nexport type ObservationUnknownReason =\n 'awaiting-revision-pair' | 'provider-refresh' | 'stale-revision';\n\nexport type ObservationAbsentReason = 'detached' | 'not-displayed' | 'not-laid-out';\n\nexport type ObservationUnsupportedReason =\n 'capability' | 'framework-unobservable' | 'not-negotiated';\n\nexport type ObservationEvidence = EvidenceProvenance;\nexport type AuthoritativeObservationEvidence = ObservationEvidence & {\n readonly strength: 'authoritative';\n};\n\n/**\n * A fact with its epistemic state preserved.\n *\n * Consumers must never coerce `unknown`/`unsupported` to false, nor absence to\n * an empty value. That rule prevents assertions from passing because a probe\n * simply could not observe the requested property.\n */\nexport type Observation<T> =\n | { readonly status: 'known'; readonly value: T; readonly evidence: ObservationEvidence }\n | {\n readonly status: 'absent';\n readonly reason: ObservationAbsentReason;\n readonly evidence: AuthoritativeObservationEvidence;\n }\n | { readonly status: 'unknown'; readonly reason: ObservationUnknownReason }\n | {\n readonly status: 'unsupported';\n readonly capability: string;\n readonly reason: ObservationUnsupportedReason;\n };\n\nexport type SemanticValueAbsentReason = ObservationAbsentReason | 'no-value';\nexport type SemanticValueWithheldReason = 'sensitive' | 'artifact-policy' | 'provider-policy';\n\n/** A semantic value never collapses absence, uncertainty, support or confidentiality. */\nexport type SemanticValueObservation =\n | {\n readonly status: 'known';\n readonly value: string;\n readonly sensitivity: 'public' | 'sensitive';\n readonly evidence: ObservationEvidence;\n }\n | {\n readonly status: 'absent';\n readonly reason: SemanticValueAbsentReason;\n readonly evidence: AuthoritativeObservationEvidence;\n }\n | { readonly status: 'unknown'; readonly reason: ObservationUnknownReason }\n | {\n readonly status: 'unsupported';\n readonly capability: 'semantic-value';\n readonly reason: ObservationUnsupportedReason;\n }\n | {\n readonly status: 'withheld';\n readonly reason: SemanticValueWithheldReason;\n readonly sensitivity: 'public' | 'sensitive';\n };\n\n/** Atomic identity of the screen/tree pair used for an observation. */\nexport interface ObservationStamp {\n readonly sessionId: string;\n readonly contractId: string;\n readonly epoch: number;\n /** Monotonic publication order across both screen and semantic revisions. */\n readonly sequence: number;\n readonly screenRevision: number;\n readonly semanticRevision: number | null;\n /** Screen revision paired to semanticRevision, or null when no pair exists. */\n readonly pairedScreenRevision: number | null;\n}\n\nexport type CoordinateSpace = 'viewport-cells' | 'framework-local-cells';\n\nexport interface LocatorGeometry {\n readonly stamp: ObservationStamp;\n readonly coordinateSpace: Observation<CoordinateSpace>;\n readonly intendedRect: Observation<Rect>;\n readonly visibleRect: Observation<Rect>;\n}\n\nexport interface ViewportIntersection {\n /** Half-open intersection in viewport cell coordinates. */\n readonly rect: Rect;\n /** Intersection area / intended area. Zero-area intended rect has ratio 0. */\n readonly ratio: number;\n readonly fullyInside: boolean;\n}\n\nexport interface LocatorVisibility {\n readonly stamp: ObservationStamp;\n readonly attached: Observation<boolean>;\n readonly displayed: Observation<boolean>;\n readonly viewport: Observation<ViewportIntersection>;\n readonly offscreen: Observation<boolean>;\n}\n\nexport interface CellPoint {\n readonly row: number;\n readonly column: number;\n}\n\nexport interface PointerHitTest {\n readonly stamp: ObservationStamp;\n readonly point: Observation<CellPoint>;\n readonly receivesEvents: Observation<boolean>;\n /** Ref of the actual recipient, when the producer can identify it. */\n readonly recipient: Observation<string>;\n}\n\nexport type SpatialRelation =\n | 'contains'\n | 'inside'\n | 'overlaps'\n | 'left-of'\n | 'right-of'\n | 'above'\n | 'below'\n | 'aligned-left'\n | 'aligned-right'\n | 'aligned-top'\n | 'aligned-bottom'\n | 'adjacent-horizontal'\n | 'adjacent-vertical';\n\n/** Correct half-open rectangle intersection. Touching edges do not overlap. */\nexport function intersectRects(a: Rect, b: Rect): Rect {\n const row = Math.max(a.row, b.row);\n const column = Math.max(a.column, b.column);\n return {\n row,\n column,\n width: Math.max(0, Math.min(a.column + a.width, b.column + b.width) - column),\n height: Math.max(0, Math.min(a.row + a.height, b.row + b.height) - row),\n };\n}\n\nexport function rectArea(rect: Rect): number {\n return Math.max(0, rect.width) * Math.max(0, rect.height);\n}\n\nexport function viewportIntersection(\n rect: Rect,\n columns: number,\n rows: number,\n): ViewportIntersection {\n const intersection = intersectRects(rect, { row: 0, column: 0, width: columns, height: rows });\n const area = rectArea(rect);\n const visible = rectArea(intersection);\n return Object.freeze({\n rect: Object.freeze(intersection),\n ratio: area === 0 ? 0 : visible / area,\n fullyInside: area > 0 && visible === area,\n });\n}\n\nexport function spatialRelation(a: Rect, relation: SpatialRelation, b: Rect): boolean {\n const aBottom = a.row + a.height;\n const bBottom = b.row + b.height;\n const aRight = a.column + a.width;\n const bRight = b.column + b.width;\n switch (relation) {\n case 'contains':\n return a.row <= b.row && a.column <= b.column && aBottom >= bBottom && aRight >= bRight;\n case 'inside':\n return spatialRelation(b, 'contains', a);\n case 'overlaps':\n return rectArea(intersectRects(a, b)) > 0;\n case 'left-of':\n return aRight <= b.column;\n case 'right-of':\n return bRight <= a.column;\n case 'above':\n return aBottom <= b.row;\n case 'below':\n return bBottom <= a.row;\n case 'aligned-left':\n return a.column === b.column;\n case 'aligned-right':\n return aRight === bRight;\n case 'aligned-top':\n return a.row === b.row;\n case 'aligned-bottom':\n return aBottom === bBottom;\n case 'adjacent-horizontal':\n return (\n (aRight === b.column || bRight === a.column) &&\n Math.max(a.row, b.row) < Math.min(aBottom, bBottom)\n );\n case 'adjacent-vertical':\n return (\n (aBottom === b.row || bBottom === a.row) &&\n Math.max(a.column, b.column) < Math.min(aRight, bRight)\n );\n }\n}\n","/**\n * Shared zod schemas for tree data. **Internal**: not re-exported from\n * `index.ts`.\n *\n * This is the canonical wire shape for every semantic node.\n *\n * Schemas depend on the active limits, so they are built per limits object and\n * memoised. Limits are frozen singletons in practice, which keeps schema\n * construction off the per-message path.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport type { ProtocolLimits } from './limits.js';\nimport type { SemanticExtendedValue } from './tree.js';\nimport { PHYSICAL_INPUT_RECIPE_ACTIONS, SEMANTIC_ACTIONS, SEMANTIC_ROLES } from './roles.js';\nimport { PROVENANCE_SOURCES } from './probe/ir.js';\n\nexport function safeInt(): z.ZodType<number> {\n return z.number().refine(Number.isSafeInteger, 'expected a safe integer');\n}\n\nexport function nonNegativeInt(): z.ZodType<number> {\n return z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\n}\n\nexport function positiveInt(): z.ZodType<number> {\n return z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n}\n\nexport function boundedString(maxStringBytes: number): z.ZodType<string> {\n return z\n .string()\n .refine(\n (s) => Buffer.byteLength(s, 'utf8') <= maxStringBytes,\n `expected at most ${maxStringBytes} UTF-8 bytes`,\n );\n}\n\n/** The schema family for one set of limits. */\nexport interface TreeSchemas {\n readonly text: z.ZodType<string>;\n readonly node: z.ZodType;\n readonly cursor: z.ZodType;\n readonly snapshot: z.ZodType;\n /** Field names of `SemanticNode`, read off the schema itself. */\n readonly nodeKeys: readonly string[];\n /** Field names of `SemanticState`, read off the schema itself. */\n readonly stateKeys: readonly string[];\n}\n\nconst cache = new WeakMap<ProtocolLimits, TreeSchemas>();\n\nfunction build(limits: ProtocolLimits): TreeSchemas {\n const text = boundedString(limits.maxStringBytes);\n const relations = z.array(text).max(limits.maxRelationTargets);\n\n const rect = z.strictObject({\n row: safeInt(),\n column: safeInt(),\n width: nonNegativeInt(),\n height: nonNegativeInt(),\n });\n\n const evidence = z.strictObject({\n source: z.enum(['framework', 'application', 'terminal', 'recognizer', 'driver']),\n method: z.enum([\n 'native',\n 'instrumented',\n 'declared',\n 'correlated',\n 'measured',\n 'derived',\n 'heuristic',\n ]),\n strength: z.enum(['authoritative', 'diagnostic']),\n providerId: z.string().min(1).max(256),\n });\n const authoritativeEvidence = evidence.extend({\n strength: z.literal('authoritative'),\n });\n\n const observation = <T extends z.ZodType>(value: T): z.ZodType =>\n z.discriminatedUnion('status', [\n z.strictObject({\n status: z.literal('known'),\n value,\n evidence,\n }),\n z.strictObject({\n status: z.literal('absent'),\n reason: z.enum(['detached', 'not-displayed', 'not-laid-out']),\n evidence: authoritativeEvidence,\n }),\n z.strictObject({\n status: z.literal('unknown'),\n reason: z.enum(['awaiting-revision-pair', 'provider-refresh', 'stale-revision']),\n }),\n z.strictObject({\n status: z.literal('unsupported'),\n capability: text,\n reason: z.enum(['capability', 'framework-unobservable', 'not-negotiated']),\n }),\n ]);\n const semanticValue = z.discriminatedUnion('status', [\n z.strictObject({\n status: z.literal('known'),\n value: text,\n sensitivity: z.enum(['public', 'sensitive']),\n evidence,\n }),\n z.strictObject({\n status: z.literal('absent'),\n reason: z.enum(['detached', 'not-displayed', 'not-laid-out', 'no-value']),\n evidence: authoritativeEvidence,\n }),\n z.strictObject({\n status: z.literal('unknown'),\n reason: z.enum(['awaiting-revision-pair', 'provider-refresh', 'stale-revision']),\n }),\n z.strictObject({\n status: z.literal('unsupported'),\n capability: z.literal('semantic-value'),\n reason: z.enum(['capability', 'framework-unobservable', 'not-negotiated']),\n }),\n z.strictObject({\n status: z.literal('withheld'),\n reason: z.enum(['sensitive', 'artifact-policy', 'provider-policy']),\n sensitivity: z.enum(['public', 'sensitive']),\n }),\n ]);\n\n const state = z.strictObject({\n disabled: z.boolean().optional(),\n focused: z.boolean().optional(),\n selected: z.boolean().optional(),\n checked: z.union([z.boolean(), z.literal('mixed')]).optional(),\n expanded: z.boolean().optional(),\n modal: z.boolean().optional(),\n busy: z.boolean().optional(),\n hidden: z.boolean().optional(),\n offscreen: z.boolean().optional(),\n readonly: z.boolean().optional(),\n multiline: z.boolean().optional(),\n required: z.boolean().optional(),\n multiselectable: z.boolean().optional(),\n orientation: z.union([z.literal('horizontal'), z.literal('vertical')]).optional(),\n level: positiveInt().optional(),\n positionInSet: positiveInt().optional(),\n setSize: nonNegativeInt().optional(),\n });\n\n const textRange = z.strictObject({\n startOffset: nonNegativeInt(),\n endOffset: nonNegativeInt(),\n rect,\n });\n\n const extendedValue: z.ZodType<SemanticExtendedValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z\n .number()\n .finite()\n .refine(\n (value) => Math.abs(value) <= Number.MAX_SAFE_INTEGER,\n 'expected a finite JSON number in the safe range',\n ),\n text,\n z.array(extendedValue).max(limits.maxRelationTargets),\n z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n ),\n ]),\n );\n const extended = z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n );\n\n const inputRecipe = z\n .strictObject({\n action: z.enum(PHYSICAL_INPUT_RECIPE_ACTIONS),\n requiresFocus: z.boolean(),\n steps: z\n .array(\n z.union([\n z.strictObject({\n kind: z.literal('press'),\n key: text.refine((s) => s.length > 0, 'key must not be empty'),\n }),\n z.strictObject({ kind: z.literal('insert-action-value') }),\n ]),\n )\n .min(1)\n .max(limits.maxRelationTargets),\n })\n .superRefine((recipe, context) => {\n const inserts = recipe.steps.filter(({ kind }) => kind === 'insert-action-value').length;\n if (\n (recipe.action === 'setValue' && inserts !== 1) ||\n (recipe.action !== 'setValue' && inserts !== 0)\n ) {\n context.addIssue({\n code: 'custom',\n message: 'setValue requires exactly one insert-action-value step',\n });\n }\n if (recipe.action === 'focus' && recipe.requiresFocus) {\n context.addIssue({\n code: 'custom',\n message: 'focus recipe cannot require focus',\n });\n }\n });\n const inputRecipes = z\n .array(inputRecipe)\n .max(PHYSICAL_INPUT_RECIPE_ACTIONS.length)\n .superRefine((recipes, context) => {\n if (new Set(recipes.map(({ action }) => action)).size !== recipes.length) {\n context.addIssue({\n code: 'custom',\n message: 'input recipe actions must be unique',\n });\n }\n });\n\n const regionSpan = z\n .strictObject({\n row: nonNegativeInt(),\n from: nonNegativeInt(),\n to: positiveInt(),\n })\n .refine((span) => span.to > span.from, 'region span must be non-empty');\n const regionSpans = z\n .array(regionSpan)\n .max(limits.maxNodes)\n .superRefine((spans, ctx) => {\n let previous: (typeof spans)[number] | undefined;\n for (let index = 0; index < spans.length; index += 1) {\n const current = spans[index]!;\n if (\n previous !== undefined &&\n (current.row < previous.row ||\n (current.row === previous.row && current.from < previous.to))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: [index],\n message: 'region spans must be non-overlapping row-major runs',\n });\n return;\n }\n previous = current;\n }\n });\n\n const nodeFields = {\n id: text.refine((s) => s.length > 0, 'node id must not be empty'),\n parentId: text.optional(),\n role: z.enum(SEMANTIC_ROLES),\n name: text,\n description: text.optional(),\n value: semanticValue.optional(),\n state: state.optional(),\n extended: extended.optional(),\n actions: z.array(z.enum(SEMANTIC_ACTIONS)).max(SEMANTIC_ACTIONS.length).optional(),\n inputRecipes: inputRecipes.optional(),\n labelledBy: relations.optional(),\n describedBy: relations.optional(),\n textRanges: z.array(textRange).max(limits.maxRelationTargets).optional(),\n testId: text.optional(),\n frameworkType: text.optional(),\n opaqueChildren: z.boolean().optional(),\n p: z.enum(PROVENANCE_SOURCES).optional(),\n px: z.record(text, z.enum(PROVENANCE_SOURCES)).optional(),\n } as const;\n const geometry = z.strictObject({\n displayed: observation(z.boolean()),\n intendedRect: observation(rect),\n visibleRect: observation(rect),\n });\n const nodeV2 = z\n .strictObject({\n ...nodeFields,\n geometry,\n scroll: observation(\n z.strictObject({\n axis: z.enum(['vertical', 'horizontal']),\n offset: nonNegativeInt(),\n viewport: nonNegativeInt(),\n extent: nonNegativeInt(),\n }),\n ).optional(),\n paintedRegion: observation(\n z.strictObject({\n regionBounds: rect,\n spans: regionSpans,\n }),\n ).optional(),\n })\n .superRefine((node, context) => {\n const intents = new Set(node.actions ?? []);\n for (const [index, recipe] of (node.inputRecipes ?? []).entries()) {\n if (!intents.has(recipe.action)) {\n context.addIssue({\n code: 'custom',\n path: ['inputRecipes', index, 'action'],\n message: `input recipe '${recipe.action}' requires the matching semantic action intent`,\n });\n }\n }\n });\n\n const cursor = z.strictObject({\n row: nonNegativeInt(),\n column: nonNegativeInt(),\n visible: z.boolean(),\n shape: z.union([z.literal('block'), z.literal('underline'), z.literal('bar')]).optional(),\n });\n\n const hitRun = z.strictObject({\n rect: z.strictObject({\n row: nonNegativeInt(),\n column: nonNegativeInt(),\n width: positiveInt(),\n height: z.literal(1),\n }),\n recipientId: text,\n });\n const hitGrid = z.strictObject({\n // Canonical row runs make ambiguity validation linear and keep hostile\n // snapshots from forcing an O(n²) rectangle-overlap check.\n regions: z\n .array(hitRun)\n .max(limits.maxNodes)\n .superRefine((regions, ctx) => {\n let previous: (typeof regions)[number] | undefined;\n for (let index = 0; index < regions.length; index += 1) {\n const current = regions[index]!;\n if (\n previous !== undefined &&\n (current.rect.row < previous.rect.row ||\n (current.rect.row === previous.rect.row &&\n current.rect.column < previous.rect.column + previous.rect.width))\n ) {\n ctx.addIssue({\n code: 'custom',\n path: [index, 'rect'],\n message: 'hit regions must be non-overlapping row-major runs',\n });\n return;\n }\n previous = current;\n }\n }),\n });\n const providerPointerRegion = z.strictObject({\n recipientId: text.refine((value) => value.length > 0, 'recipient id must not be empty'),\n regionBounds: rect,\n spans: regionSpans,\n });\n const providerActionRecipes = z.strictObject({\n recipientId: text.refine((value) => value.length > 0, 'recipient id must not be empty'),\n recipes: inputRecipes,\n });\n const providerScrollState = z\n .strictObject({\n recipientId: text.refine((value) => value.length > 0, 'recipient id must not be empty'),\n axis: z.enum(['vertical', 'horizontal']),\n offset: nonNegativeInt(),\n viewport: nonNegativeInt(),\n extent: nonNegativeInt(),\n })\n .superRefine((state, context) => {\n if (\n state.offset > state.extent ||\n state.viewport > state.extent ||\n state.offset + state.viewport > state.extent\n ) {\n context.addIssue({\n code: 'custom',\n message: 'scroll state must fit inside its extent',\n });\n }\n });\n const providerEvidence = z.discriminatedUnion('status', [\n z.strictObject({\n providerId: text.refine((value) => value.length > 0, 'provider id must not be empty'),\n sessionId: text.refine((value) => value.length > 0, 'provider session id must not be empty'),\n revision: positiveInt(),\n status: z.literal('available'),\n evidence: z.strictObject({\n source: z.literal('application'),\n method: z.enum(['native', 'instrumented', 'declared']),\n strength: z.literal('authoritative'),\n providerId: text.refine(\n (value) => value.length > 0,\n 'evidence provider id must not be empty',\n ),\n }),\n pointerRegions: z.array(providerPointerRegion).max(limits.maxNodes),\n paintedRegions: z.array(providerPointerRegion).max(limits.maxNodes).optional(),\n inputModes: z\n .strictObject({\n mouseTracking: z.enum(['none', 'x10', 'vt200', 'drag', 'any']),\n mouseEncoding: z.enum(['default', 'sgr', 'urxvt', 'utf8']),\n focusReporting: z.enum(['on', 'off']),\n })\n .optional(),\n focusState: z\n .discriminatedUnion('status', [\n z.strictObject({\n status: z.literal('focused'),\n recipientId: text.refine(\n (value) => value.length > 0,\n 'focused recipient id must not be empty',\n ),\n }),\n z.strictObject({ status: z.literal('none') }),\n ])\n .optional(),\n actionRecipes: z\n .array(providerActionRecipes)\n .max(limits.maxNodes)\n .superRefine((entries, context) => {\n const seen = new Set<string>();\n for (const [index, entry] of entries.entries()) {\n if (seen.has(entry.recipientId)) {\n context.addIssue({\n code: 'custom',\n path: [index, 'recipientId'],\n message: 'provider action recipe recipients must be unique',\n });\n }\n seen.add(entry.recipientId);\n }\n })\n .optional(),\n scrollStates: z\n .array(providerScrollState)\n .max(limits.maxNodes)\n .superRefine((entries, context) => {\n const seen = new Set<string>();\n for (const [index, entry] of entries.entries()) {\n if (seen.has(entry.recipientId)) {\n context.addIssue({\n code: 'custom',\n path: [index, 'recipientId'],\n message: 'provider scroll recipients must be unique',\n });\n }\n seen.add(entry.recipientId);\n }\n })\n .optional(),\n hitGrid: hitGrid.optional(),\n }),\n z.strictObject({\n providerId: text.refine((value) => value.length > 0, 'provider id must not be empty'),\n sessionId: text.refine((value) => value.length > 0, 'provider session id must not be empty'),\n revision: positiveInt(),\n status: z.literal('lost'),\n reason: text.refine((value) => value.length > 0, 'provider loss reason must not be empty'),\n }),\n z.strictObject({\n providerId: text.refine((value) => value.length > 0, 'provider id must not be empty'),\n sessionId: text.refine((value) => value.length > 0, 'provider session id must not be empty'),\n revision: positiveInt(),\n status: z.literal('violation'),\n reason: text.refine(\n (value) => value.length > 0,\n 'provider violation reason must not be empty',\n ),\n }),\n ]);\n const snapshotV2 = z.strictObject({\n v: z.literal(2),\n sessionId: text.refine((s) => s.length > 0, 'sessionId must not be empty'),\n revision: positiveInt(),\n columns: positiveInt(),\n rows: positiveInt(),\n cursor: cursor.optional(),\n rootIds: z.array(text).max(limits.maxNodes),\n nodes: z.array(nodeV2).max(limits.maxNodes),\n coordinateSpace: observation(z.enum(['viewport-cells', 'framework-local-cells'])),\n hitGrid: observation(hitGrid),\n providerEvidence: z.array(providerEvidence).max(64).optional(),\n });\n const snapshot = snapshotV2;\n\n return {\n text,\n node: nodeV2,\n cursor,\n snapshot,\n nodeKeys: Object.freeze(Object.keys(nodeV2.shape)),\n stateKeys: Object.freeze(Object.keys(state.shape)),\n };\n}\n\n/** Memoised schema family for the given limits. */\nexport function treeSchemas(limits: ProtocolLimits): TreeSchemas {\n const cached = cache.get(limits);\n if (cached !== undefined) return cached;\n const built = build(limits);\n cache.set(limits, built);\n return built;\n}\n","/**\n * The field names of a semantic node and of its state, as data.\n *\n * These exist because a schema is invisible to anything that is not TypeScript.\n * The cross-language vector generator and the client comparators cannot see a\n * zod shape, so until now they carried hand-maintained field lists — and three\n * fields (`frameworkType`, `occlusion`, `p`/`px`) reached three clients late\n * precisely because nobody remembered to extend those lists. A generator that\n * reads this array cannot forget a field the schema already has.\n *\n * Derived from the schema rather than written out, so there is one source of\n * truth and not a third copy to drift. The list does not vary with limits: only\n * the bounds inside the fields do.\n */\n\nimport { DEFAULT_LIMITS } from './limits.js';\nimport { treeSchemas } from './node-schema.js';\nimport type { SemanticNode, SemanticState } from './tree.js';\n\nconst schemas = treeSchemas(DEFAULT_LIMITS);\n\n/**\n * Every field name on `SemanticNode`.\n *\n * The `keyof` annotation is the load-bearing part: a field present in the\n * schema but missing from the interface fails to compile here, which is the\n * half of the drift a runtime test cannot catch early.\n */\nexport const SEMANTIC_NODE_KEYS: readonly Exclude<keyof SemanticNode, 'geometry'>[] = Object.freeze(\n schemas.nodeKeys as readonly Exclude<keyof SemanticNode, 'geometry'>[],\n);\n\n/** Every field name on `SemanticState`. */\nexport const SEMANTIC_STATE_KEYS: readonly (keyof SemanticState)[] = Object.freeze(\n schemas.stateKeys as readonly (keyof SemanticState)[],\n);\n","/**\n * Application log records carried over the semantic channel.\n *\n * A TUI cannot print diagnostics to the screen without corrupting the render,\n * so applications write them to an internal logger instead. The `logs`\n * capability lets an instrumented adapter forward those records to the driver,\n * where they become assertable test state rather than invisible side effects.\n *\n * Records are bounded exactly like snapshots: projected into frozen plain DTOs\n * before retention, checked against a byte ceiling, and rejected wholesale on\n * any violation. A misbehaving logger degrades into dropped records, never\n * into unbounded driver memory.\n */\n\nimport { Buffer } from 'node:buffer';\nimport type { ProtocolLimits } from './limits.js';\nimport type { ValidationErrorCode } from './validate.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\n\n/**\n * Severity ladder, ordered from least to most severe. Deliberately the\n * intersection of the ladders used by pino, winston, consola, Python\n * `logging`, Go `slog` and Rust `tracing`, so every bridge maps onto it\n * without inventing a level.\n */\nexport const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const;\n\nexport type LogLevel = (typeof LOG_LEVELS)[number];\n\n/** Numeric severity, useful for threshold comparisons. Higher is more severe. */\nexport const LOG_LEVEL_SEVERITY: Readonly<Record<LogLevel, number>> = Object.freeze({\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n});\n\n/**\n * Structured attribute value. Scalars only, by design: nested objects make\n * record size unbounded and depth-dependent, and every bridge already has to\n * flatten for its own transport. `@termwright/logs` does the flattening.\n */\nexport type LogAttrValue = string | number | boolean | null;\n\n/** Maximum number of attribute keys on one record. */\nexport const MAX_LOG_ATTRS = 64;\n\n/**\n * One application log record.\n *\n * @remarks\n * `ts` is **Unix epoch milliseconds**, not session-relative: the adapter has no\n * reliable view of when the driver considers the session to have started, so\n * the only clock both sides can agree on without negotiation is the wall\n * clock. The driver rebases it onto the session/cast timeline.\n */\nexport interface LogRecord {\n /** Unix epoch milliseconds when the record was produced. */\n readonly ts: number;\n readonly level: LogLevel;\n /** Human-readable message, already formatted by the source logger. */\n readonly message: string;\n /** Flat structured context. Nested values are flattened by the bridge. */\n readonly attrs?: Readonly<Record<string, LogAttrValue>>;\n /** Logger/channel name, e.g. `http` or `db.pool`. */\n readonly logger?: string;\n /**\n * Per-session counter assigned by the adapter, **strictly increasing**: every\n * record carries a `seq` greater than the previous one on the same session.\n *\n * The two failure modes are distinguishable on purpose:\n * - a **gap upward** means records were dropped at the source (rate limit,\n * queue overflow) rather than lost in transit, and is expected under load;\n * - a **duplicate or a decrease** means the sender is broken, so the receiver\n * rejects that record and emits a diagnostic instead of retaining it.\n *\n * This is a rule *between* records, not about the shape of one, so\n * {@link validateLogRecord} cannot enforce it — it only checks that `seq` is\n * a non-negative safe integer. Ordering is enforced by the driver, which is\n * the only party that sees the whole session.\n */\n readonly seq: number;\n /** Semantic revision current when the record was produced, when known. */\n readonly revision?: number;\n}\n\n/** Structured result: never throws hostile data onward. */\nexport type LogValidationResult =\n | { readonly ok: true; readonly record: LogRecord }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nfunction fail(code: ValidationErrorCode, detail: string): LogValidationResult {\n return { ok: false, code, detail };\n}\n\nconst LEVELS: ReadonlySet<string> = new Set(LOG_LEVELS);\n\nfunction isSafeNonNegative(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\n/**\n * Validate an untrusted log record.\n *\n * Mirrors {@link import('./validate.js').validateSnapshot}: the value is\n * projected into a frozen plain DTO first (so getters are rejected without\n * being invoked), then measured against the byte ceiling, then checked field\n * by field.\n *\n * @param value - Untrusted candidate record.\n * @param limits - Active limits; `maxLogRecordBytes` and `maxStringBytes` apply.\n * @returns `{ ok: true, record }` with a deep-frozen record, or a typed\n * failure. Never throws.\n */\nexport function validateLogRecord(value: unknown, limits: ProtocolLimits): LogValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) {\n return fail('schema', 'log record is not a JSON object');\n }\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxLogRecordBytes) {\n return fail('bytes', `log record is ${bytes} bytes, ceiling is ${limits.maxLogRecordBytes}`);\n }\n\n if (typeof projected !== 'object' || projected === null || Array.isArray(projected)) {\n return fail('schema', 'log record must be an object');\n }\n const record = projected as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (!['ts', 'level', 'message', 'attrs', 'logger', 'seq', 'revision'].includes(key)) {\n return fail('schema', `unknown log record property \"${key}\"`);\n }\n }\n\n if (!isSafeNonNegative(record['ts']) || record['ts'] === 0) {\n return fail('schema', 'ts must be a positive safe integer (epoch milliseconds)');\n }\n if (typeof record['level'] !== 'string' || !LEVELS.has(record['level'])) {\n return fail('schema', `level must be one of ${LOG_LEVELS.join(', ')}`);\n }\n if (typeof record['message'] !== 'string') {\n return fail('schema', 'message must be a string');\n }\n if (Buffer.byteLength(record['message'], 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `message exceeds ${limits.maxStringBytes} UTF-8 bytes`);\n }\n if (!isSafeNonNegative(record['seq'])) {\n return fail('schema', 'seq must be a non-negative safe integer');\n }\n\n if (record['logger'] !== undefined) {\n if (typeof record['logger'] !== 'string') {\n return fail('schema', 'logger must be a string');\n }\n if (Buffer.byteLength(record['logger'], 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `logger exceeds ${limits.maxStringBytes} UTF-8 bytes`);\n }\n }\n\n if (record['revision'] !== undefined) {\n if (!isSafeNonNegative(record['revision']) || record['revision'] === 0) {\n return fail('revision', 'revision must be a positive safe integer');\n }\n }\n\n const attrs = record['attrs'];\n if (attrs !== undefined) {\n if (typeof attrs !== 'object' || attrs === null || Array.isArray(attrs)) {\n return fail('schema', 'attrs must be a flat object');\n }\n const entries = Object.entries(attrs as Record<string, unknown>);\n if (entries.length > MAX_LOG_ATTRS) {\n return fail('count', `attrs carries ${entries.length} keys, ceiling is ${MAX_LOG_ATTRS}`);\n }\n for (const [key, attrValue] of entries) {\n if (Buffer.byteLength(key, 'utf8') > limits.maxStringBytes) {\n return fail('string-bytes', `attribute key \"${key}\" exceeds the string ceiling`);\n }\n const type = typeof attrValue;\n if (attrValue !== null && type !== 'string' && type !== 'number' && type !== 'boolean') {\n return fail('schema', `attribute \"${key}\" must be a string, number, boolean or null`);\n }\n if (type === 'number' && !Number.isFinite(attrValue)) {\n return fail('schema', `attribute \"${key}\" must be a finite number`);\n }\n if (\n type === 'string' &&\n Buffer.byteLength(attrValue as string, 'utf8') > limits.maxStringBytes\n ) {\n return fail('string-bytes', `attribute \"${key}\" exceeds the string ceiling`);\n }\n }\n }\n\n return { ok: true, record: projected as LogRecord };\n}\n","/**\n * Wire framing: 4-byte big-endian unsigned length prefix + UTF-8 JSON body.\n * The length is checked against limits.maxFrameBytes BEFORE any decoding;\n * oversized, partial or duplicated frames fail closed with a typed error.\n * Decoded values MUST be projected into immutable plain DTOs (no accessors,\n * proxies, symbols, functions, non-plain prototypes) before retention.\n */\n\nimport { types } from 'node:util';\nimport { ProtocolViolation } from './errors.js';\nimport { DEFAULT_LIMITS } from './limits.js';\n\nexport interface FrameDecoder {\n /** Feed raw bytes; returns fully decoded, validated, frozen messages. */\n push(chunk: Uint8Array): readonly unknown[];\n /** Bytes currently buffered (bounded by maxFrameBytes + 4). */\n readonly buffered: number;\n}\n\n/** Size of the big-endian length prefix that precedes every frame body. */\nexport const FRAME_HEADER_BYTES = 4;\n\n/**\n * Structural nesting ceiling applied to every decoded frame.\n *\n * The decoder signature carries only a byte ceiling, so projection uses this\n * fixed structural bound; message-specific limits are applied later by\n * `parseAdapterMessage`/`parseDriverMessage` and `validateSnapshot`.\n */\nconst FRAME_PROJECTION_DEPTH = DEFAULT_LIMITS.maxDepth;\n\nconst RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/** Matches any unpaired surrogate code unit. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\nconst encoder = new TextEncoder();\n/** `fatal` makes malformed UTF-8 throw instead of yielding U+FFFD. */\nconst decoder = new TextDecoder('utf-8', { fatal: true });\n\nfunction assertPositiveByteCeiling(maxFrameBytes: number): void {\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0) {\n throw new ProtocolViolation('frame-malformed', 'maxFrameBytes must be a positive safe integer');\n }\n}\n\nclass BufferedFrameDecoder implements FrameDecoder {\n readonly #maxFrameBytes: number;\n #buffer: Uint8Array;\n /** Offset of the first unconsumed byte in `#buffer`. */\n #start = 0;\n /** Offset just past the last buffered byte in `#buffer`. */\n #end = 0;\n #failure: ProtocolViolation | null = null;\n\n constructor(maxFrameBytes: number) {\n assertPositiveByteCeiling(maxFrameBytes);\n this.#maxFrameBytes = maxFrameBytes;\n this.#buffer = new Uint8Array(0);\n }\n\n get buffered(): number {\n return this.#end - this.#start;\n }\n\n push(chunk: Uint8Array): readonly unknown[] {\n if (this.#failure !== null) {\n throw new ProtocolViolation(\n 'decoder-poisoned',\n `decoder failed earlier (${this.#failure.code}) and accepts no further input`,\n );\n }\n try {\n return this.#pushOrThrow(chunk);\n } catch (error) {\n this.#failure =\n error instanceof ProtocolViolation\n ? error\n : new ProtocolViolation('frame-malformed', 'frame decoding failed');\n // Release the buffer: a poisoned decoder never resumes.\n this.#buffer = new Uint8Array(0);\n this.#start = 0;\n this.#end = 0;\n throw this.#failure;\n }\n }\n\n #pushOrThrow(chunk: Uint8Array): readonly unknown[] {\n this.#append(chunk);\n const messages: unknown[] = [];\n\n for (;;) {\n const available = this.#end - this.#start;\n if (available < FRAME_HEADER_BYTES) break;\n\n const length = this.#readLength();\n if (length === 0) {\n throw new ProtocolViolation('frame-malformed', 'frame length must be non-zero');\n }\n if (length > this.#maxFrameBytes) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `frame declares ${length} bytes, ceiling is ${this.#maxFrameBytes}`,\n );\n }\n if (available < FRAME_HEADER_BYTES + length) break; // partial: wait for more\n\n const bodyStart = this.#start + FRAME_HEADER_BYTES;\n const body = this.#buffer.subarray(bodyStart, bodyStart + length);\n messages.push(decodeBody(body));\n this.#start = bodyStart + length;\n }\n\n this.#compact();\n if (this.buffered > this.#maxFrameBytes + FRAME_HEADER_BYTES) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `buffered ${this.buffered} bytes without a complete frame`,\n );\n }\n return messages;\n }\n\n #readLength(): number {\n const b = this.#buffer;\n const i = this.#start;\n // Non-null assertions are safe: the caller checked 4 bytes are available.\n return (b[i]! * 0x1000000 + ((b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!)) >>> 0;\n }\n\n #append(chunk: Uint8Array): void {\n const kept = this.#end - this.#start;\n const needed = kept + chunk.length;\n if (needed > this.#buffer.length - this.#start) {\n const next = new Uint8Array(needed);\n next.set(this.#buffer.subarray(this.#start, this.#end), 0);\n this.#buffer = next;\n this.#start = 0;\n this.#end = kept;\n }\n this.#buffer.set(chunk, this.#end);\n this.#end += chunk.length;\n }\n\n #compact(): void {\n if (this.#start === 0) return;\n const kept = this.#end - this.#start;\n if (kept === 0) {\n this.#buffer = new Uint8Array(0);\n } else {\n const next = new Uint8Array(kept);\n next.set(this.#buffer.subarray(this.#start, this.#end), 0);\n this.#buffer = next;\n }\n this.#start = 0;\n this.#end = kept;\n }\n}\n\nfunction decodeBody(body: Uint8Array): unknown {\n let text: string;\n try {\n text = decoder.decode(body);\n } catch {\n throw new ProtocolViolation('frame-encoding', 'frame body is not valid UTF-8');\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n // Also covers RangeError from pathologically nested JSON.\n throw new ProtocolViolation('frame-malformed', 'frame body is not valid JSON');\n }\n return projectDto(parsed, FRAME_PROJECTION_DEPTH);\n}\n\n/**\n * Create a streaming decoder for length-prefixed JSON frames.\n *\n * A frame whose declared length exceeds `maxFrameBytes` is rejected before its\n * body is read. Any violation poisons the decoder permanently: subsequent\n * `push` calls throw rather than resynchronising on attacker-chosen offsets.\n *\n * @param maxFrameBytes - Per-frame byte ceiling; must be a positive safe integer.\n * @throws {ProtocolViolation} On an invalid ceiling, or (from `push`) on any\n * oversized, malformed, non-UTF-8 or non-projectable frame.\n */\nexport function createFrameDecoder(maxFrameBytes: number): FrameDecoder {\n return new BufferedFrameDecoder(maxFrameBytes);\n}\n\n/**\n * Serialise a message into a single length-prefixed frame.\n *\n * @param message - A JSON-representable value.\n * @param maxFrameBytes - Per-frame byte ceiling applied to the encoded body.\n * @returns Header + UTF-8 JSON body, ready to write to the transport.\n * @throws {ProtocolViolation} If the value is not JSON-representable or the\n * encoded body exceeds `maxFrameBytes`.\n */\nexport function encodeFrame(message: unknown, maxFrameBytes: number): Uint8Array {\n assertPositiveByteCeiling(maxFrameBytes);\n\n let text: string | undefined;\n try {\n text = JSON.stringify(message);\n } catch {\n throw new ProtocolViolation('frame-malformed', 'message is not JSON-serialisable');\n }\n if (text === undefined) {\n throw new ProtocolViolation('dto-scalar', 'message serialises to undefined');\n }\n\n const body = encoder.encode(text);\n if (body.length > maxFrameBytes) {\n throw new ProtocolViolation(\n 'frame-oversized',\n `encoded frame is ${body.length} bytes, ceiling is ${maxFrameBytes}`,\n );\n }\n\n const frame = new Uint8Array(FRAME_HEADER_BYTES + body.length);\n const n = body.length;\n frame[0] = (n >>> 24) & 0xff;\n frame[1] = (n >>> 16) & 0xff;\n frame[2] = (n >>> 8) & 0xff;\n frame[3] = n & 0xff;\n frame.set(body, FRAME_HEADER_BYTES);\n return frame;\n}\n\nfunction projectScalar(value: unknown, path: string): string | number | boolean | null {\n if (value === null) return null;\n switch (typeof value) {\n case 'boolean':\n return value;\n case 'number':\n if (!Number.isFinite(value)) {\n throw new ProtocolViolation('dto-scalar', `non-finite number at ${path}`);\n }\n return value;\n case 'string':\n if (LONE_SURROGATE.test(value)) {\n throw new ProtocolViolation('dto-string', `unpaired surrogate at ${path}`);\n }\n return value;\n default:\n throw new ProtocolViolation(\n 'dto-scalar',\n `value of type ${typeof value} is not JSON-representable at ${path}`,\n );\n }\n}\n\nfunction projectNode(\n value: unknown,\n depth: number,\n maxDepth: number,\n seen: Set<object>,\n path: string,\n): unknown {\n if (value === null || typeof value !== 'object') {\n return projectScalar(value, path);\n }\n if (depth > maxDepth) {\n throw new ProtocolViolation('dto-depth', `nesting exceeds ${maxDepth} at ${path}`);\n }\n if (types.isProxy(value)) {\n throw new ProtocolViolation('dto-prototype', `proxy at ${path}`);\n }\n if (seen.has(value)) {\n // Covers both cycles and plain aliasing (shared subtrees).\n throw new ProtocolViolation('dto-alias', `value is reachable more than once at ${path}`);\n }\n seen.add(value);\n\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new ProtocolViolation('dto-symbol', `symbol-keyed property at ${path}`);\n }\n\n const proto: unknown = Object.getPrototypeOf(value);\n const result = Array.isArray(value)\n ? projectArray(value, proto, depth, maxDepth, seen, path)\n : projectObject(value, proto, depth, maxDepth, seen, path);\n\n // `seen` is never cleared: a value reachable twice is an alias, not a\n // legitimate repeat, and must be rejected rather than duplicated.\n return Object.freeze(result);\n}\n\nfunction projectArray(\n value: readonly unknown[],\n proto: unknown,\n depth: number,\n maxDepth: number,\n seen: Set<object>,\n path: string,\n): unknown[] {\n if (proto !== Array.prototype) {\n throw new ProtocolViolation('dto-prototype', `array with exotic prototype at ${path}`);\n }\n const length = value.length;\n const out = new Array<unknown>(length);\n for (let i = 0; i < length; i += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, i);\n if (descriptor === undefined) {\n throw new ProtocolViolation('dto-sparse', `hole at ${path}[${i}]`);\n }\n if (!('value' in descriptor)) {\n throw new ProtocolViolation('dto-accessor', `accessor at ${path}[${i}]`);\n }\n out[i] = projectNode(descriptor.value, depth + 1, maxDepth, seen, `${path}[${i}]`);\n }\n // Reject `length` plus anything that is not a dense index we just consumed.\n if (Object.getOwnPropertyNames(value).length !== length + 1) {\n throw new ProtocolViolation('dto-sparse', `array carries extra own properties at ${path}`);\n }\n return out;\n}\n\nfunction projectObject(\n value: object,\n proto: unknown,\n depth: number,\n maxDepth: number,\n seen: Set<object>,\n path: string,\n): Record<string, unknown> {\n if (proto !== Object.prototype && proto !== null) {\n throw new ProtocolViolation('dto-prototype', `non-plain object at ${path}`);\n }\n const out: Record<string, unknown> = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n if (RESERVED_KEYS.has(key)) {\n throw new ProtocolViolation('dto-key', `reserved property name \"${key}\" at ${path}`);\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (!('value' in descriptor)) {\n throw new ProtocolViolation('dto-accessor', `accessor property \"${key}\" at ${path}`);\n }\n if (!descriptor.enumerable) {\n throw new ProtocolViolation('dto-key', `non-enumerable property \"${key}\" at ${path}`);\n }\n if (LONE_SURROGATE.test(key)) {\n throw new ProtocolViolation('dto-string', `unpaired surrogate in key at ${path}`);\n }\n out[key] = projectNode(descriptor.value, depth + 1, maxDepth, seen, `${path}.${key}`);\n }\n return out;\n}\n\n/**\n * Deep-project an untrusted parsed value into a frozen, plain, JSON-safe DTO.\n * Throws ProtocolViolation on aliases, cycles, sparse arrays, accessors,\n * non-JSON scalars, or depth/size beyond limits.\n *\n * Properties are inspected with `Object.getOwnPropertyDescriptor`, so a getter\n * on hostile input is detected and rejected without ever being invoked.\n *\n * @param value - Untrusted input, typically the result of `JSON.parse`.\n * @param maxDepth - Maximum nesting depth; the root sits at depth 0.\n * @returns A structurally identical, deep-frozen copy. The `T` type parameter\n * is an unchecked assertion — validate the shape separately.\n * @throws {ProtocolViolation}\n */\nexport function projectDto<T>(value: unknown, maxDepth: number): T {\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {\n throw new ProtocolViolation('dto-depth', 'maxDepth must be a non-negative safe integer');\n }\n return projectNode(value, 0, maxDepth, new Set<object>(), '$') as T;\n}\n","/**\n * AccessKit export: `SemanticSnapshot` → an AccessKit `TreeUpdate`.\n *\n * A pure transformation into AccessKit's serde JSON shape. This module takes\n * **no dependency** on AccessKit — the protocol package depends on `zod` only —\n * so the output is data a bridge can hand to a real adapter, not a binding.\n *\n * ## Why there is no native bridge in 1.0\n *\n * AccessKit's platform adapters attach an accessibility tree to a **native\n * window**: an `NSView` on macOS, an `HWND` on Windows, a toplevel on AT-SPI.\n * A terminal application has none of those. The terminal emulator owns the\n * window, and the application under test is a child process writing bytes to a\n * pseudo-terminal. There is nothing for an adapter to attach to, and nothing an\n * assistive technology could route back to us.\n *\n * The geometry gap is the same problem seen from the other side. Our `bounds`\n * are **terminal cells** — row 3, column 12 — while AccessKit's `Rect` is in\n * physical pixels relative to the window origin. Converting requires the cell\n * size and window position, which live in the emulator, not in the process\n * being tested. Guessing a cell size would produce coordinates that look\n * authoritative and point nowhere.\n *\n * So the export is *bridge-ready*, not a bridge: it is the half of the problem\n * that can be solved correctly without a window. An embedder that does own one\n * (a GUI terminal emulator embedding termwright) can supply {@link\n * AccessKitExportOptions.cellSize} and get real geometry.\n *\n * ## Schema provenance\n *\n * Shapes verified against `accesskit` 0.24.1 (docs.rs, August 2026):\n * `TreeUpdate { nodes, tree, tree_id, focus }`, `Tree { root, toolkit_name,\n * toolkit_version }`, `NodeId(u64)`, `Rect { x0, y0, x1, y1 }`, and\n * `#[serde(rename_all = \"camelCase\")]` on `Role`, `Action` and `Node`.\n * `TreeId` is a UUID, with the nil UUID reserved for the root tree.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { SemanticNode, SemanticSnapshot, Rect } from './tree.js';\nimport type { SemanticAction, SemanticRole } from './roles.js';\nimport { ProtocolViolation } from './errors.js';\n\n/** The nil UUID, which AccessKit reserves for the root tree (`TreeId::ROOT`). */\nexport const ACCESSKIT_ROOT_TREE_ID = '00000000-0000-0000-0000-000000000000';\n\n/** AccessKit's `Rect`: minimum and maximum coordinates, not origin plus size. */\nexport interface AccessKitRect {\n readonly x0: number;\n readonly y0: number;\n readonly x1: number;\n readonly y1: number;\n}\n\n/** AccessKit's `Toggled`, used for tri-state checkboxes. */\nexport type AccessKitToggled = 'false' | 'true' | 'mixed';\n\n/**\n * An AccessKit `Node` in its serde JSON form. Only the properties this export\n * can populate faithfully are modelled.\n */\nexport interface AccessKitNode {\n readonly role: string;\n readonly label?: string;\n readonly description?: string;\n readonly value?: string;\n readonly children?: readonly number[];\n readonly bounds?: AccessKitRect;\n readonly actions?: readonly string[];\n readonly labelledBy?: readonly number[];\n readonly describedBy?: readonly number[];\n readonly disabled?: boolean;\n readonly selected?: boolean;\n readonly expanded?: boolean;\n readonly busy?: boolean;\n readonly modal?: boolean;\n readonly hidden?: boolean;\n readonly readOnly?: boolean;\n readonly required?: boolean;\n readonly multiselectable?: boolean;\n readonly toggled?: AccessKitToggled;\n}\n\n/** AccessKit's `Tree`. */\nexport interface AccessKitTree {\n readonly root: number;\n readonly toolkitName?: string;\n readonly toolkitVersion?: string;\n}\n\n/** AccessKit's `TreeUpdate`. */\nexport interface AccessKitTreeUpdate {\n readonly nodes: readonly (readonly [number, AccessKitNode])[];\n readonly tree?: AccessKitTree;\n readonly treeId: string;\n readonly focus: number;\n}\n\n/** Settings for {@link toAccessKitTreeUpdate}. */\nexport interface AccessKitExportOptions {\n /** Tree identity; defaults to the nil UUID AccessKit reserves for the root. */\n readonly treeId?: string;\n readonly toolkitName?: string;\n readonly toolkitVersion?: string;\n /**\n * Pixel size of one terminal cell. Supply it only if you genuinely know it —\n * an embedder that owns the window does; a headless test run does not.\n * Without it `bounds` is omitted and cell rects are reported separately.\n */\n readonly cellSize?: { readonly width: number; readonly height: number };\n}\n\n/** The export, plus the cell geometry AccessKit has nowhere to put. */\nexport interface AccessKitExport {\n readonly update: AccessKitTreeUpdate;\n /**\n * Cell-space rects keyed by AccessKit node id, for every node that had\n * `bounds`. AccessKit's `Node` has no extension point for foreign\n * coordinates, so carrying them alongside is the honest option: a consumer\n * that understands terminal cells can use them, and one that does not is\n * not misled by pixel coordinates that were never measured.\n */\n readonly cellBounds: Readonly<Record<string, Rect>>;\n}\n\n/**\n * ARIA-aligned protocol roles to AccessKit roles.\n *\n * Every target is a real `accesskit::Role` variant in its camelCase serde\n * spelling. `textbox` is resolved per node rather than here, because a\n * multiline textbox maps to a different AccessKit role.\n */\nexport const ACCESSKIT_ROLE_BY_SEMANTIC_ROLE: Readonly<Record<SemanticRole, string>> =\n Object.freeze({\n application: 'application',\n region: 'region',\n dialog: 'dialog',\n alert: 'alert',\n status: 'status',\n list: 'list',\n listitem: 'listItem',\n menu: 'menu',\n menuitem: 'menuItem',\n button: 'button',\n checkbox: 'checkBox',\n radio: 'radioButton',\n tab: 'tab',\n textbox: 'textInput',\n heading: 'heading',\n text: 'label',\n progressbar: 'progressIndicator',\n separator: 'splitter',\n scrollbar: 'scrollBar',\n table: 'table',\n row: 'row',\n cell: 'cell',\n generic: 'genericContainer',\n });\n\n/**\n * Protocol actions to AccessKit actions.\n *\n * `select` is deliberately absent: AccessKit has no selection action, and\n * mapping it onto `click` would claim a behaviour the adapter never described.\n * `toggle` maps to `click` because that is how AccessKit expresses toggling.\n */\nconst ACCESSKIT_ACTION_BY_SEMANTIC_ACTION: Readonly<Partial<Record<SemanticAction, string>>> =\n Object.freeze({\n focus: 'focus',\n activate: 'click',\n toggle: 'click',\n setValue: 'setValue',\n expand: 'expand',\n scroll: 'scrollIntoView',\n });\n\n/**\n * Bits of the digest used for a node id.\n *\n * AccessKit's `NodeId` is a `u64`, but JSON numbers are IEEE doubles and this\n * export is JSON. Staying inside 53 bits keeps every id exactly representable\n * on both sides; the alternative silently rounds ids above 2^53 and produces\n * collisions that look like duplicate nodes.\n */\nconst NODE_ID_BITS = 53n;\nconst NODE_ID_MASK = (1n << NODE_ID_BITS) - 1n;\n\n/**\n * Map a protocol node id (a string) onto an AccessKit node id (a number).\n *\n * Stable across processes and languages: SHA-256 of the UTF-8 id, truncated to\n * 53 bits. At the protocol's 5 000-node ceiling the collision probability is\n * about 1.4e-9, and {@link toAccessKitTreeUpdate} detects a collision rather\n * than silently merging two nodes.\n *\n * @param id - Protocol node id.\n */\nexport function accessKitNodeId(id: string): number {\n const digest = createHash('sha256').update(id, 'utf8').digest();\n const value = digest.readBigUInt64BE(0) & NODE_ID_MASK;\n // 0 is a legal NodeId, but reserving it keeps \"unset\" unambiguous for\n // consumers that treat 0 as absent.\n return value === 0n ? 1 : Number(value);\n}\n\nfunction toggledFor(checked: boolean | 'mixed' | undefined): AccessKitToggled | undefined {\n if (checked === undefined) return undefined;\n if (checked === 'mixed') return 'mixed';\n return checked ? 'true' : 'false';\n}\n\nfunction accessKitRoleFor(node: SemanticNode): string {\n if (node.role === 'textbox' && node.state?.multiline === true) return 'multilineTextInput';\n return ACCESSKIT_ROLE_BY_SEMANTIC_ROLE[node.role];\n}\n\nfunction actionsFor(actions: readonly SemanticAction[] | undefined): readonly string[] | undefined {\n if (actions === undefined || actions.length === 0) return undefined;\n const mapped = new Set<string>();\n for (const action of actions) {\n const target = ACCESSKIT_ACTION_BY_SEMANTIC_ACTION[action];\n if (target !== undefined) mapped.add(target);\n }\n return mapped.size === 0 ? undefined : [...mapped];\n}\n\nfunction boundsFor(\n rect: Rect,\n cellSize: { readonly width: number; readonly height: number },\n): AccessKitRect {\n return {\n x0: rect.column * cellSize.width,\n y0: rect.row * cellSize.height,\n x1: (rect.column + rect.width) * cellSize.width,\n y1: (rect.row + rect.height) * cellSize.height,\n };\n}\n\n/**\n * Convert a validated semantic snapshot into an AccessKit `TreeUpdate`.\n *\n * Two structural differences from our model are worth knowing:\n *\n * - **Focus is a tree-level property.** AccessKit puts `focus` on the\n * `TreeUpdate`, not on a node, so the node carrying `state.focused` becomes\n * the update's focus. If no node claims focus, the root does.\n * - **Children are explicit.** Our tree is a flat list joined by `parentId`;\n * AccessKit nodes carry a `children` array, which is derived here in the\n * snapshot's node order.\n *\n * @param snapshot - A snapshot that already passed `validateSnapshot`.\n * @param options - Tree identity, toolkit metadata and optional cell geometry.\n * @throws {ProtocolViolation} If two node ids collide in the 53-bit id space.\n */\nexport function toAccessKitTreeUpdate(\n snapshot: SemanticSnapshot,\n options: AccessKitExportOptions = {},\n): AccessKitExport {\n const idOf = new Map<string, number>();\n const seen = new Map<number, string>();\n for (const node of snapshot.nodes) {\n const mapped = accessKitNodeId(node.id);\n const previous = seen.get(mapped);\n if (previous !== undefined) {\n throw new ProtocolViolation(\n 'dto-key',\n `node ids \"${previous}\" and \"${node.id}\" collide in the AccessKit id space`,\n );\n }\n seen.set(mapped, node.id);\n idOf.set(node.id, mapped);\n }\n\n const childrenOf = new Map<string, number[]>();\n for (const node of snapshot.nodes) {\n if (node.parentId === undefined) continue;\n const siblings = childrenOf.get(node.parentId);\n if (siblings === undefined) childrenOf.set(node.parentId, [idOf.get(node.id)!]);\n else siblings.push(idOf.get(node.id)!);\n }\n\n const relation = (ids: readonly string[] | undefined): readonly number[] | undefined => {\n if (ids === undefined || ids.length === 0) return undefined;\n const mapped = ids.map((id) => idOf.get(id)).filter((id): id is number => id !== undefined);\n return mapped.length === 0 ? undefined : mapped;\n };\n\n const cellBounds: Record<string, Rect> = {};\n const nodes: (readonly [number, AccessKitNode])[] = [];\n let focus: number | undefined;\n\n for (const node of snapshot.nodes) {\n const id = idOf.get(node.id)!;\n const state = node.state;\n if (state?.focused === true && focus === undefined) focus = id;\n const visibleRect =\n node.geometry.visibleRect.status === 'known' ? node.geometry.visibleRect.value : undefined;\n if (visibleRect !== undefined) cellBounds[String(id)] = visibleRect;\n\n const accessKitNode: AccessKitNode = {\n role: accessKitRoleFor(node),\n ...(node.name === '' ? {} : { label: node.name }),\n ...(node.description === undefined ? {} : { description: node.description }),\n ...(node.value?.status === 'known' && node.value.sensitivity === 'public'\n ? { value: node.value.value }\n : {}),\n ...(childrenOf.has(node.id) ? { children: childrenOf.get(node.id)! } : {}),\n ...(visibleRect !== undefined && options.cellSize !== undefined\n ? { bounds: boundsFor(visibleRect, options.cellSize) }\n : {}),\n ...(actionsFor(node.actions) === undefined ? {} : { actions: actionsFor(node.actions)! }),\n ...(relation(node.labelledBy) === undefined\n ? {}\n : { labelledBy: relation(node.labelledBy)! }),\n ...(relation(node.describedBy) === undefined\n ? {}\n : { describedBy: relation(node.describedBy)! }),\n ...(state?.disabled === undefined ? {} : { disabled: state.disabled }),\n ...(state?.selected === undefined ? {} : { selected: state.selected }),\n ...(state?.expanded === undefined ? {} : { expanded: state.expanded }),\n ...(state?.busy === undefined ? {} : { busy: state.busy }),\n ...(state?.modal === undefined ? {} : { modal: state.modal }),\n ...(state?.hidden === undefined ? {} : { hidden: state.hidden }),\n ...(state?.readonly === undefined ? {} : { readOnly: state.readonly }),\n ...(state?.required === undefined ? {} : { required: state.required }),\n ...(state?.multiselectable === undefined ? {} : { multiselectable: state.multiselectable }),\n ...(toggledFor(state?.checked) === undefined ? {} : { toggled: toggledFor(state?.checked)! }),\n };\n nodes.push(Object.freeze([id, Object.freeze(accessKitNode)] as const));\n }\n\n const rootId = snapshot.rootIds[0];\n const root = rootId === undefined ? undefined : idOf.get(rootId);\n\n const update: AccessKitTreeUpdate = {\n nodes: Object.freeze(nodes),\n ...(root === undefined\n ? {}\n : {\n tree: Object.freeze({\n root,\n ...(options.toolkitName === undefined ? {} : { toolkitName: options.toolkitName }),\n ...(options.toolkitVersion === undefined\n ? {}\n : { toolkitVersion: options.toolkitVersion }),\n }),\n }),\n treeId: options.treeId ?? ACCESSKIT_ROOT_TREE_ID,\n focus: focus ?? root ?? 0,\n };\n\n return Object.freeze({ update: Object.freeze(update), cellBounds: Object.freeze(cellBounds) });\n}\n","/**\n * Validation for Probe IR frames.\n *\n * Same discipline as the semantic tree: project into a frozen plain DTO first\n * so a getter on hostile input is rejected without running, then measure\n * against the byte ceiling, then check the shape. A probe runs inside the\n * process under test, which may be broken or malicious, so this is a hostile\n * boundary in exactly the way the adapter channel is.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport type { ProtocolLimits } from '../limits.js';\nimport type { ValidationErrorCode } from '../validate.js';\nimport { ProtocolViolation } from '../errors.js';\nimport { encodeFrame, projectDto } from '../framing.js';\nimport {\n PROBE_CAPABILITIES,\n PROBE_DEGRADED_CAPABILITIES,\n PROBE_INJECTION_TIERS,\n PROBE_SEMANTIC_CLASSES,\n PROBE_UNOBSERVABLE_FIELDS,\n type ProbeAnnotations,\n type ProbeFrame,\n type ProbeInfo,\n} from './ir.js';\nimport { PHYSICAL_INPUT_RECIPE_ACTIONS, SEMANTIC_ACTIONS } from '../roles.js';\n\n/** Structured result: never throws hostile data onward. */\nexport type ProbeValidationResult =\n | { readonly ok: true; readonly frame: ProbeFrame }\n | {\n readonly ok: false;\n readonly code: ValidationErrorCode;\n readonly detail: string;\n };\n\n/** Result of validating one optional-SDK annotation at the probe boundary. */\nexport type ProbeAnnotationValidationResult =\n | { readonly ok: true; readonly annotations: ProbeAnnotations }\n | {\n readonly ok: false;\n readonly code: ValidationErrorCode;\n readonly detail: string;\n };\n\nfunction fail(code: ValidationErrorCode, detail: string): ProbeValidationResult {\n return { ok: false, code, detail };\n}\n\nconst safeInt = z.number().refine(Number.isSafeInteger, 'expected a safe integer');\nconst nonNegative = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\nconst positive = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n\nconst cache = new WeakMap<ProtocolLimits, z.ZodType>();\n\nfunction buildFrameSchema(limits: ProtocolLimits): z.ZodType {\n const text = z\n .string()\n .refine(\n (s) => Buffer.byteLength(s, 'utf8') <= limits.maxStringBytes,\n `expected at most ${limits.maxStringBytes} UTF-8 bytes`,\n );\n\n const rect = z.strictObject({\n row: safeInt,\n column: safeInt,\n width: nonNegative,\n height: nonNegative,\n });\n\n const identity = z.strictObject({\n kind: z.enum(['stable', 'frame-local']),\n value: text.min(1),\n });\n\n const extendedValue: z.ZodType = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z\n .number()\n .finite()\n .refine(\n (value) => Math.abs(value) <= Number.MAX_SAFE_INTEGER,\n 'expected a finite JSON number in the safe range',\n ),\n text,\n z.array(extendedValue).max(limits.maxRelationTargets),\n z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n ),\n ]),\n );\n const extended = z\n .record(text, extendedValue)\n .refine(\n (value) => Object.keys(value).length <= limits.maxRelationTargets,\n `expected at most ${limits.maxRelationTargets} properties`,\n );\n const relations = z.array(text.min(1)).max(limits.maxRelationTargets);\n const inputRecipe = z\n .strictObject({\n action: z.enum(PHYSICAL_INPUT_RECIPE_ACTIONS),\n requiresFocus: z.boolean(),\n steps: z\n .array(\n z.union([\n z.strictObject({ kind: z.literal('press'), key: text.min(1) }),\n z.strictObject({ kind: z.literal('insert-action-value') }),\n ]),\n )\n .min(1)\n .max(limits.maxRelationTargets),\n })\n .superRefine((recipe, context) => {\n const inserts = recipe.steps.filter(({ kind }) => kind === 'insert-action-value').length;\n if (\n (recipe.action === 'setValue' && inserts !== 1) ||\n (recipe.action !== 'setValue' && inserts !== 0)\n ) {\n context.addIssue({\n code: 'custom',\n message: 'setValue requires exactly one insert-action-value step',\n });\n }\n if (recipe.action === 'focus' && recipe.requiresFocus) {\n context.addIssue({\n code: 'custom',\n message: 'focus recipe cannot require focus',\n });\n }\n });\n const inputRecipes = z\n .array(inputRecipe)\n .max(PHYSICAL_INPUT_RECIPE_ACTIONS.length)\n .superRefine((recipes, context) => {\n if (new Set(recipes.map(({ action }) => action)).size !== recipes.length) {\n context.addIssue({\n code: 'custom',\n message: 'input recipe actions must be unique',\n });\n }\n });\n\n const state = z.strictObject({\n focused: z.boolean().optional(),\n disabled: z.boolean().optional(),\n checked: z.union([z.boolean(), z.literal('mixed')]).optional(),\n expanded: z.boolean().optional(),\n readonly: z.boolean().optional(),\n selected: z.boolean().optional(),\n busy: z.boolean().optional(),\n multiline: z.boolean().optional(),\n required: z.boolean().optional(),\n multiselectable: z.boolean().optional(),\n displayed: z.boolean().optional(),\n value: text.optional(),\n valueSensitivity: z.enum(['public', 'sensitive']).optional(),\n selectedIndex: nonNegative.optional(),\n textSelection: z.strictObject({ start: nonNegative, end: nonNegative }).optional(),\n scroll: z.strictObject({ row: nonNegative, column: nonNegative }).optional(),\n scrollExtent: z.strictObject({ rows: nonNegative, columns: nonNegative }).optional(),\n });\n\n const object = z.strictObject({\n identity,\n frameworkType: text.min(1),\n parent: text.optional(),\n geometry: z\n .strictObject({\n intendedRect: rect.optional(),\n visibleRect: rect.optional(),\n })\n .optional(),\n state: state.optional(),\n text: text.optional(),\n accessibility: z\n .strictObject({\n role: text.optional(),\n name: text.optional(),\n description: text.optional(),\n })\n .optional(),\n annotations: z\n .strictObject({\n role: text.optional(),\n name: text.optional(),\n testId: text.optional(),\n description: text.optional(),\n extended: extended.optional(),\n actions: z.array(z.enum(SEMANTIC_ACTIONS)).max(SEMANTIC_ACTIONS.length).optional(),\n inputRecipes: inputRecipes.optional(),\n labelledBy: relations.optional(),\n describedBy: relations.optional(),\n })\n .superRefine((annotations, context) => {\n const intents = new Set(annotations.actions ?? []);\n for (const [index, recipe] of (annotations.inputRecipes ?? []).entries()) {\n if (!intents.has(recipe.action)) {\n context.addIssue({\n code: 'custom',\n path: ['inputRecipes', index, 'action'],\n message: `input recipe '${recipe.action}' requires the matching semantic action intent`,\n });\n }\n }\n })\n .optional(),\n paintOrder: safeInt.optional(),\n unobservable: z\n .array(z.enum(PROBE_UNOBSERVABLE_FIELDS))\n .max(PROBE_UNOBSERVABLE_FIELDS.length)\n .optional(),\n });\n\n const operation = z.strictObject({\n kind: z.enum(['render', 'layout']),\n ordinal: nonNegative,\n target: identity.optional(),\n frameworkType: text.optional(),\n intendedRect: rect.optional(),\n });\n\n return z.strictObject({\n frame: positive,\n objects: z.array(object).max(limits.maxNodes),\n operations: z.array(operation).max(limits.maxNodes).optional(),\n });\n}\n\nfunction frameSchema(limits: ProtocolLimits): z.ZodType {\n const cached = cache.get(limits);\n if (cached !== undefined) return cached;\n const built = buildFrameSchema(limits);\n cache.set(limits, built);\n return built;\n}\n\n/** Schema for the handshake block a probe sends about itself. */\nexport const probeInfoSchema = z.strictObject({\n framework: z.string().min(1).max(128),\n frameworkVersion: z.string().max(128).optional(),\n probeVersion: z.string().min(1).max(128),\n identityKind: z.enum(['stable', 'frame-local']),\n capabilities: z.array(z.enum(PROBE_CAPABILITIES)).max(PROBE_CAPABILITIES.length),\n instrumentation: z\n .strictObject({\n highestTier: z.enum(PROBE_INJECTION_TIERS),\n semanticClass: z.enum(PROBE_SEMANTIC_CLASSES),\n degradedCapabilities: z\n .array(z.enum(PROBE_DEGRADED_CAPABILITIES))\n .max(PROBE_DEGRADED_CAPABILITIES.length),\n })\n .optional(),\n});\n\n/**\n * Validate a probe's self-description.\n *\n * Enforces the one consistency rule the pair has: a probe may not claim the\n * `stable-identity` capability while declaring `identityKind: 'frame-local'`.\n * Those two together would tell a consumer it is safe to correlate objects\n * across frames in a framework where nothing survives the frame.\n */\nexport function validateProbeInfo(\n value: unknown,\n):\n | { readonly ok: true; readonly info: ProbeInfo }\n | { readonly ok: false; readonly detail: string } {\n const parsed = probeInfoSchema.safeParse(value);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return { ok: false, detail: `${where}: ${issue.message}` };\n }\n const info = parsed.data as ProbeInfo;\n const degraded = info.instrumentation?.degradedCapabilities;\n if (degraded !== undefined && new Set(degraded).size !== degraded.length) {\n return { ok: false, detail: 'instrumentation.degradedCapabilities: duplicate capability' };\n }\n if (\n info.instrumentation?.semanticClass === 'B' &&\n (!degraded?.includes('intended-geometry') || !degraded.includes('clipped-geometry'))\n ) {\n return {\n ok: false,\n detail:\n \"semantic class B must declare both 'intended-geometry' and 'clipped-geometry' as degraded\",\n };\n }\n if (info.identityKind === 'frame-local' && info.capabilities.includes('stable-identity')) {\n return {\n ok: false,\n detail:\n \"a probe declaring identityKind 'frame-local' must not claim the 'stable-identity' \" +\n 'capability: nothing in an immediate-mode frame survives to be correlated',\n };\n }\n return {\n ok: true,\n info: Object.freeze({\n ...info,\n capabilities: Object.freeze([...info.capabilities]),\n ...(info.instrumentation === undefined\n ? {}\n : {\n instrumentation: Object.freeze({\n ...info.instrumentation,\n degradedCapabilities: Object.freeze([...info.instrumentation.degradedCapabilities]),\n }),\n }),\n }),\n };\n}\n\n/**\n * Validate an untrusted probe frame.\n *\n * Beyond the shape, three cross-object rules are checked, each of them a way an\n * IR frame can be internally inconsistent rather than merely malformed:\n * identities must be unique within the frame, a declared parent must exist in\n * the same frame, and a field cannot be both reported and declared\n * unobservable.\n *\n * @param value - Untrusted candidate frame.\n * @param limits - Active limits; `maxNodes`, `maxStringBytes` and\n * `maxSnapshotBytes` apply.\n * @returns `{ ok: true, frame }` deep-frozen, or a typed failure. Never throws.\n */\nexport function validateProbeFrame(value: unknown, limits: ProtocolLimits): ProbeValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) return fail('schema', 'probe frame is not a JSON object');\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxSnapshotBytes) {\n return fail('bytes', `probe frame is ${bytes} bytes, ceiling is ${limits.maxSnapshotBytes}`);\n }\n\n const parsed = frameSchema(limits).safeParse(projected);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n const path = issue.path.map(String);\n const where = path.length > 0 ? path.join('.') : '<root>';\n const code: ValidationErrorCode =\n path.includes('intendedRect') || path.includes('visibleRect')\n ? 'bad-rect'\n : path.includes('frame')\n ? 'revision'\n : issue.code === 'too_big'\n ? 'count'\n : 'schema';\n return fail(code, `${where}: ${issue.message}`);\n }\n\n const frame = projected as ProbeFrame;\n\n const seen = new Set<string>();\n for (const object of frame.objects) {\n if (seen.has(object.identity.value)) {\n return fail('duplicate-id', `identity ${object.identity.value} appears twice in the frame`);\n }\n seen.add(object.identity.value);\n }\n\n for (const object of frame.objects) {\n if (object.parent !== undefined && !seen.has(object.parent)) {\n return fail(\n 'missing-parent',\n `object ${object.identity.value} names parent ${object.parent}, which is not in the frame`,\n );\n }\n if (object.parent === object.identity.value) {\n return fail('cycle', `object ${object.identity.value} is its own parent`);\n }\n if (object.state?.valueSensitivity !== undefined && object.state.value === undefined) {\n return fail(\n 'schema',\n `object ${object.identity.value} classifies a semantic value it did not report`,\n );\n }\n\n const unobservable = object.unobservable;\n if (unobservable === undefined) continue;\n const declared = new Set<string>(unobservable);\n if (declared.size !== unobservable.length) {\n return fail('duplicate-id', `object ${object.identity.value} repeats an unobservable field`);\n }\n // Reporting a value while calling the field unobservable is a contradiction,\n // and the whole point of the three-valued model is that it cannot happen.\n for (const [field, present] of [\n ['text', object.text !== undefined],\n ['parent', object.parent !== undefined],\n ['intendedRect', object.geometry?.intendedRect !== undefined],\n ['visibleRect', object.geometry?.visibleRect !== undefined],\n ['paintOrder', object.paintOrder !== undefined],\n ] as const) {\n if (declared.has(field) && present) {\n return fail(\n 'schema',\n `object ${object.identity.value} reports ${field} and also declares it unobservable`,\n );\n }\n }\n for (const [field, value_] of Object.entries(object.state ?? {})) {\n if (declared.has(field) && value_ !== undefined) {\n return fail(\n 'schema',\n `object ${object.identity.value} reports state.${field} and also declares it unobservable`,\n );\n }\n }\n }\n\n return { ok: true, frame };\n}\n\n/**\n * Validate one developer annotation before adding it to an otherwise trusted\n * framework observation.\n *\n * Annotation registries intentionally use `Symbol.for` so an optional SDK and\n * an injected probe can meet without importing one another. That also makes\n * the registry a hostile boundary: application code can forge an entry with a\n * getter, cycle, oversized value or unknown action. Reusing the complete frame\n * validator here keeps both boundaries byte-for-byte consistent. Callers can\n * then omit only the bad annotation instead of losing the framework frame or\n * closing the probe channel.\n */\nexport function validateProbeAnnotations(\n value: unknown,\n limits: ProtocolLimits,\n): ProbeAnnotationValidationResult {\n const result = validateProbeFrame(\n {\n frame: 1,\n objects: [\n {\n identity: { kind: 'stable', value: 'a' },\n frameworkType: 'A',\n annotations: value,\n },\n ],\n },\n limits,\n );\n if (!result.ok) return { ok: false, code: result.code, detail: result.detail };\n const annotations = result.frame.objects[0]?.annotations;\n if (annotations === undefined) {\n return {\n ok: false,\n code: 'schema',\n detail: 'annotations: expected an annotation object',\n };\n }\n try {\n // A valid snapshot can still be impossible to put on the negotiated wire\n // when maxFrameBytes is tighter than maxSnapshotBytes. Bound the optional\n // payload at its own boundary so one forged SDK entry cannot poison the\n // whole probe channel later.\n encodeFrame({ annotations }, limits.maxFrameBytes);\n } catch (error) {\n return {\n ok: false,\n code:\n error instanceof ProtocolViolation && error.code === 'frame-oversized' ? 'bytes' : 'schema',\n detail: error instanceof Error ? error.message : 'annotations could not be framed',\n };\n }\n return { ok: true, annotations };\n}\n","import { z } from 'zod';\nimport type { SemanticSnapshot } from './tree.js';\nimport type { LogRecord } from './logs.js';\nimport type { ProbeInfo } from './probe/ir.js';\nimport type { ProtocolLimits } from './limits.js';\nimport { PROTOCOL_ID, type ProtocolId } from './env.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\nimport { validateSnapshot } from './validate.js';\nimport { validateLogRecord } from './logs.js';\nimport { probeInfoSchema, validateProbeInfo } from './probe/validate.js';\nimport {\n ADAPTER_CAPABILITIES,\n EVIDENCE_PROVIDER_CAPABILITIES,\n type AdapterCapability,\n type EvidenceProviderRegistration,\n} from './contract.js';\n\n/**\n * Wire messages. Transport: length-prefixed JSON frames (see framing.ts).\n * CDP-like: adapter pushes commits; driver issues requests; either side may\n * send errors. All messages are validated against limits BEFORE retention.\n */\n\nexport { ADAPTER_CAPABILITIES } from './contract.js';\nexport type { AdapterCapability } from './contract.js';\n\n/** adapter → driver, exactly once, before any other message. */\nexport interface HelloMessage {\n readonly type: 'hello';\n readonly protocol: ProtocolId;\n readonly token: string;\n readonly adapter: { readonly name: string; readonly version: string };\n readonly capabilities: readonly AdapterCapability[];\n /**\n * Present when the sender is a probe rather than a hand-written adapter.\n *\n * Carries what the probe can actually offer — framework and versions, the\n * best identity it can produce, and its optional abilities — so the driver\n * negotiates against measured capability rather than assuming a floor.\n */\n readonly probe?: ProbeInfo;\n /** Application evidence providers frozen into this session contract. */\n readonly providers?: readonly EvidenceProviderRegistration[];\n}\n\n/** driver → adapter, reply to hello. */\nexport interface HelloAckMessage {\n readonly type: 'hello-ack';\n readonly protocol: ProtocolId;\n readonly sessionId: string;\n readonly limits: ProtocolLimits;\n /** Which semantic traffic the driver wants pushed. */\n readonly subscribe: 'snapshots' | 'revisions';\n /** Marker configuration: producer must emit the signed OSC 8487 commit marker. */\n readonly marker: { readonly enabled: boolean };\n /**\n * Log-channel budget, sent only when the adapter announced the `logs`\n * capability. **Absent means logs are disabled** — an adapter that receives\n * no `logs` field must not emit `log` messages at all.\n *\n * The adapter enforces the rate itself and drops locally when over budget,\n * leaving a gap in `LogRecord.seq` so the driver can report how many records\n * were lost. Enforcing it at the source is what keeps a log storm from\n * consuming the frame budget the semantic tree needs.\n */\n readonly logs?: {\n readonly enabled: boolean;\n /** Sustained ceiling on records per second. */\n readonly maxRecordsPerSecond: number;\n /** Records allowed in a burst on top of the sustained rate. */\n readonly burst: number;\n };\n}\n\n/** adapter → driver after each committed render (always, regardless of mode). */\nexport interface RevisionCommitMessage {\n readonly type: 'revision-commit';\n readonly revision: number;\n}\n\n/** adapter → driver, full snapshot for a revision (subscribe: 'snapshots'). */\nexport interface SnapshotMessage {\n readonly type: 'snapshot';\n readonly snapshot: SemanticSnapshot;\n}\n\n/**\n * adapter → driver, a frame has started (capability `frame-begin`).\n *\n * **Optional, and its absence means nothing.** No audited framework offers a\n * hook guaranteed to fire before every frame: one lets a pre-draw hook veto the\n * frame entirely, so the post-draw hook never runs; one exposes only a\n * post-frame hook; one decouples submission from the flush with a ticker. A\n * receiver that reads \"no frame-begin\" as \"no frame in progress\" turns four of\n * the six frameworks into a hang rather than an error.\n *\n * `FRAME_END` is the existing `revision-commit`, which stays advisory.\n *\n * **Abandoned frames**: a probe may begin a frame and never finish it — a\n * crash, an interrupted render. A `frame-begin` for revision N implicitly\n * closes every frame below N. Without that rule an open frame waits forever,\n * which is the timeout it replaced, only now wearing a false air of precision.\n */\nexport interface FrameBeginMessage {\n readonly type: 'frame-begin';\n readonly revision: number;\n}\n\n/**\n * adapter → driver, one application log record (capability `logs`).\n *\n * Sent only after the driver enabled logs in `hello-ack`. Records are\n * independent of renders: they are not paired with a revision and never gate\n * snapshot publication.\n */\nexport interface LogMessage {\n readonly type: 'log';\n readonly record: LogRecord;\n}\n\n/** either direction: terminal protocol error; sender closes after emitting. */\nexport interface ProtocolErrorMessage {\n readonly type: 'error';\n readonly code:\n | 'bad-token'\n | 'bad-version'\n | 'malformed'\n | 'limit-exceeded'\n | 'duplicate-semantic-key'\n | 'adapter-guarantee-violation'\n | 'capability-provider-violation'\n | 'internal';\n readonly message: string;\n}\n\nexport type AdapterToDriverMessage =\n | HelloMessage\n | RevisionCommitMessage\n | SnapshotMessage\n | FrameBeginMessage\n | LogMessage\n | ProtocolErrorMessage;\n\nexport type DriverToAdapterMessage = HelloAckMessage | ProtocolErrorMessage;\n\n// --------------------------------------------------------------------------\n// Runtime validation\n//\n// The interfaces above are the contract; the schemas below are how untrusted\n// bytes become instances of it. Every parse projects the value into a frozen\n// plain DTO first, so a getter on hostile input is rejected without running.\n// --------------------------------------------------------------------------\n\n/** Outcome of parsing one wire message. Mirrors `ProtocolErrorMessage['code']`. */\nexport type MessageParseResult<T> =\n | { readonly ok: true; readonly message: T }\n | {\n readonly ok: false;\n readonly code:\n 'bad-version' | 'malformed' | 'limit-exceeded' | 'capability-provider-violation';\n readonly detail: string;\n };\n\n/** Longest token/identifier/message string accepted, in UTF-16 code units. */\nconst MAX_IDENTIFIER_LENGTH = 1024;\n\nconst identifier = z.string().max(MAX_IDENTIFIER_LENGTH);\nconst nonEmptyIdentifier = identifier.min(1);\nconst safeIndex = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n >= 0, 'expected a non-negative safe integer');\nconst revisionNumber = z\n .number()\n .refine((n) => Number.isSafeInteger(n) && n > 0, 'expected a positive safe integer');\n\n/**\n * Limits are an ADDITIVE part of the contract: unknown keys are IGNORED, not\n * rejected. A driver that learns a new ceiling must not break every already\n * published adapter, so this is the one object on the wire read leniently.\n * Known keys stay strict about their type, and every closed set elsewhere\n * (message types, roles, actions, capabilities) stays strict too.\n */\nconst limitsSchema = z.object({\n maxFrameBytes: revisionNumber,\n maxSnapshotBytes: revisionNumber,\n maxNodes: revisionNumber,\n maxDepth: revisionNumber,\n maxStringBytes: revisionNumber,\n maxRelationTargets: revisionNumber,\n maxQueuedFrames: revisionNumber,\n maxPendingWaiters: revisionNumber,\n maxSessions: revisionNumber,\n maxLogRecordBytes: revisionNumber,\n maxLogQueue: revisionNumber,\n});\n\nconst errorFields = {\n type: z.literal('error'),\n code: z.enum([\n 'bad-token',\n 'bad-version',\n 'malformed',\n 'limit-exceeded',\n 'duplicate-semantic-key',\n 'adapter-guarantee-violation',\n 'capability-provider-violation',\n 'internal',\n ]),\n message: z.string().max(MAX_IDENTIFIER_LENGTH),\n};\n\n/** adapter → driver: strict, this is the hostile-input boundary. */\nconst errorSchema = z.strictObject(errorFields);\n\n/** driver → adapter: tolerant envelope, see the note above `parseDriverMessage`. */\nconst errorFromDriverSchema = z.object(errorFields);\n\n/** adapter → driver schemas. Snapshot bodies are validated separately. */\nconst helloSchema = z.strictObject({\n type: z.literal('hello'),\n protocol: z.literal(PROTOCOL_ID),\n token: nonEmptyIdentifier,\n adapter: z.strictObject({\n name: nonEmptyIdentifier,\n version: nonEmptyIdentifier,\n }),\n capabilities: z.array(z.enum(ADAPTER_CAPABILITIES)).max(ADAPTER_CAPABILITIES.length),\n probe: probeInfoSchema.optional(),\n providers: z\n .array(\n z.strictObject({\n id: nonEmptyIdentifier,\n version: nonEmptyIdentifier,\n method: z.enum(['native', 'declared']),\n capabilities: z\n .array(z.enum(EVIDENCE_PROVIDER_CAPABILITIES))\n .min(1)\n .max(EVIDENCE_PROVIDER_CAPABILITIES.length)\n .refine(\n (values) => new Set(values).size === values.length,\n 'provider capabilities must be unique',\n ),\n }),\n )\n .max(64)\n .superRefine((providers, ctx) => {\n const ids = new Set<string>();\n for (let index = 0; index < providers.length; index += 1) {\n const provider = providers[index]!;\n const id = provider.id;\n if (ids.has(id)) {\n ctx.addIssue({\n code: 'custom',\n path: [index, 'id'],\n message: `duplicate provider id ${id}`,\n });\n return;\n }\n ids.add(id);\n }\n })\n .optional(),\n});\n\nconst frameBeginSchema = z.strictObject({\n type: z.literal('frame-begin'),\n revision: revisionNumber,\n});\n\nconst revisionCommitSchema = z.strictObject({\n type: z.literal('revision-commit'),\n revision: revisionNumber,\n});\n\nconst snapshotEnvelopeSchema = z.strictObject({\n type: z.literal('snapshot'),\n snapshot: z.unknown(),\n});\n\nconst logEnvelopeSchema = z.strictObject({\n type: z.literal('log'),\n record: z.unknown(),\n});\n\n/** driver → adapter schemas. */\nconst helloAckSchema = z.object({\n type: z.literal('hello-ack'),\n protocol: z.literal(PROTOCOL_ID),\n sessionId: nonEmptyIdentifier,\n limits: limitsSchema,\n subscribe: z.enum(['snapshots', 'revisions']),\n marker: z.object({ enabled: z.boolean() }),\n logs: z\n .object({\n enabled: z.boolean(),\n maxRecordsPerSecond: revisionNumber,\n burst: safeIndex,\n })\n .optional(),\n});\n\nfunction malformed(detail: string): MessageParseResult<never> {\n return { ok: false, code: 'malformed', detail };\n}\n\n/** Projection guard shared by both parsers. */\nfunction project(value: unknown, limits: ProtocolLimits): MessageParseResult<unknown> {\n try {\n return { ok: true, message: projectDto<unknown>(value, limits.maxDepth) };\n } catch (error) {\n const detail =\n error instanceof ProtocolViolation ? error.message : 'value is not a plain JSON DTO';\n return error instanceof ProtocolViolation && error.code === 'dto-depth'\n ? { ok: false, code: 'limit-exceeded', detail }\n : malformed(detail);\n }\n}\n\nfunction messageType(value: unknown): string | null {\n if (typeof value !== 'object' || value === null) return null;\n const type: unknown = (value as { type?: unknown }).type;\n return typeof type === 'string' ? type : null;\n}\n\nfunction check(schema: z.ZodType, value: unknown): string | null {\n const result = schema.safeParse(value);\n if (result.success) return null;\n const issue = result.error.issues[0]!;\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return `${where}: ${issue.message}`;\n}\n\n/**\n * Validate a snapshot carried inside an envelope and map its failure onto the\n * wire error taxonomy: capacity failures are `limit-exceeded`; evidence-frame\n * contract failures retain their typed provider classification; the rest are\n * `malformed`.\n */\nfunction checkSnapshot(value: unknown, limits: ProtocolLimits): MessageParseResult<never> | null {\n const result = validateSnapshot(value, limits);\n if (result.ok) return null;\n const overCapacity =\n result.code === 'bytes' ||\n result.code === 'count' ||\n result.code === 'depth' ||\n result.code === 'string-bytes';\n return {\n ok: false,\n code: overCapacity\n ? 'limit-exceeded'\n : result.code === 'provider'\n ? 'capability-provider-violation'\n : 'malformed',\n detail: `snapshot ${result.code}: ${result.detail}`,\n };\n}\n\n/**\n * Validate a log record carried inside an envelope, mapping capacity failures\n * onto `limit-exceeded` exactly as snapshots do.\n */\nfunction checkLogRecord(value: unknown, limits: ProtocolLimits): MessageParseResult<never> | null {\n const result = validateLogRecord(value, limits);\n if (result.ok) return null;\n const overCapacity =\n result.code === 'bytes' ||\n result.code === 'count' ||\n result.code === 'depth' ||\n result.code === 'string-bytes';\n return {\n ok: false,\n code: overCapacity ? 'limit-exceeded' : 'malformed',\n detail: `log record ${result.code}: ${result.detail}`,\n };\n}\n\n/**\n * Parse and validate one adapter → driver message.\n *\n * **Strict reader**: this is the hostile-input boundary, so unknown fields are\n * rejected rather than ignored. See {@link parseDriverMessage} for why the\n * other direction is tolerant.\n *\n * @param value - Untrusted decoded frame body.\n * @param limits - Active session limits, applied to any embedded snapshot.\n * @returns A frozen message on success, or a typed failure. Never throws.\n */\nexport function parseAdapterMessage(\n value: unknown,\n limits: ProtocolLimits,\n): MessageParseResult<AdapterToDriverMessage> {\n const projected = project(value, limits);\n if (!projected.ok) return projected;\n const dto = projected.message;\n\n switch (messageType(dto)) {\n case 'hello': {\n const protocol: unknown = (dto as { protocol?: unknown }).protocol;\n if (typeof protocol === 'string' && protocol !== PROTOCOL_ID) {\n return {\n ok: false,\n code: 'bad-version',\n detail: `unsupported protocol ${protocol}`,\n };\n }\n const issue = check(helloSchema, dto);\n if (issue !== null) return malformed(issue);\n // The shape check cannot see the one incoherent pair: a probe declaring\n // frame-local identity while claiming it can be correlated across\n // frames. That rule has to hold on the wire, not only when a caller\n // remembers to run the helper.\n const probe = (dto as { probe?: unknown }).probe;\n if (probe !== undefined) {\n const checked = validateProbeInfo(probe);\n if (!checked.ok) return malformed(`probe: ${checked.detail}`);\n }\n return { ok: true, message: dto as HelloMessage };\n }\n case 'revision-commit': {\n const issue = check(revisionCommitSchema, dto);\n return issue === null\n ? { ok: true, message: dto as RevisionCommitMessage }\n : malformed(issue);\n }\n case 'snapshot': {\n const issue = check(snapshotEnvelopeSchema, dto);\n if (issue !== null) return malformed(issue);\n const bad = checkSnapshot((dto as { snapshot: unknown }).snapshot, limits);\n return bad ?? { ok: true, message: dto as SnapshotMessage };\n }\n case 'frame-begin': {\n const issue = check(frameBeginSchema, dto);\n return issue === null ? { ok: true, message: dto as FrameBeginMessage } : malformed(issue);\n }\n case 'log': {\n const issue = check(logEnvelopeSchema, dto);\n if (issue !== null) return malformed(issue);\n const bad = checkLogRecord((dto as { record: unknown }).record, limits);\n return bad ?? { ok: true, message: dto as LogMessage };\n }\n case 'error': {\n const issue = check(errorSchema, dto);\n return issue === null ? { ok: true, message: dto as ProtocolErrorMessage } : malformed(issue);\n }\n default:\n return malformed('unknown or missing message type');\n }\n}\n\n/**\n * Parse and validate one driver → adapter message.\n *\n * **Tolerant reader.** Unlike {@link parseAdapterMessage}, unknown envelope\n * fields are ignored rather than rejected, and are carried through to the\n * caller so a reader that does understand them still can. Known fields stay\n * strictly type-checked, and closed sets (`type`, `code`, `subscribe`) stay\n * closed — an unknown message type is still `malformed`.\n *\n * The asymmetry is about who is speaking, not about the message. The driver is\n * the trusted party and behaviour is governed by negotiated capabilities, so a\n * newer driver may add an optional field without invalidating every adapter\n * already published. Traffic in the other direction crosses the hostile-input\n * boundary and stays strict.\n *\n * @param value - Decoded frame body from the driver.\n * @param limits - Active session limits used for the projection depth bound.\n * @returns A frozen message on success, or a typed failure. Never throws.\n */\nexport function parseDriverMessage(\n value: unknown,\n limits: ProtocolLimits,\n): MessageParseResult<DriverToAdapterMessage> {\n const projected = project(value, limits);\n if (!projected.ok) return projected;\n const dto = projected.message;\n\n switch (messageType(dto)) {\n case 'hello-ack': {\n const protocol: unknown = (dto as { protocol?: unknown }).protocol;\n if (typeof protocol === 'string' && protocol !== PROTOCOL_ID) {\n return {\n ok: false,\n code: 'bad-version',\n detail: `unsupported protocol ${protocol}`,\n };\n }\n const issue = check(helloAckSchema, dto);\n return issue === null ? { ok: true, message: dto as HelloAckMessage } : malformed(issue);\n }\n case 'error': {\n const issue = check(errorFromDriverSchema, dto);\n return issue === null ? { ok: true, message: dto as ProtocolErrorMessage } : malformed(issue);\n }\n default:\n return malformed('unknown or missing message type');\n }\n}\n","import { Buffer } from 'node:buffer';\nimport { z } from 'zod';\nimport { treeSchemas } from './node-schema.js';\nimport type { SemanticNode, SemanticSnapshot } from './tree.js';\nimport type { ProtocolLimits } from './limits.js';\nimport { ProtocolViolation } from './errors.js';\nimport { projectDto } from './framing.js';\n\n/** Structured result: never throws hostile data onward. */\nexport type ValidationResult =\n | { readonly ok: true; readonly snapshot: SemanticSnapshot }\n | { readonly ok: false; readonly code: ValidationErrorCode; readonly detail: string };\n\nexport type ValidationErrorCode =\n | 'schema'\n | 'unknown-role'\n | 'duplicate-id'\n | 'missing-parent'\n | 'cycle'\n | 'depth'\n | 'count'\n | 'string-bytes'\n | 'bad-rect'\n | 'provider'\n | 'revision'\n | 'bytes';\n\nfunction fail(code: ValidationErrorCode, detail: string): ValidationResult {\n return { ok: false, code, detail };\n}\n\n/**\n * Map a zod issue onto the contract's error taxonomy so callers get a stable\n * code rather than having to interpret schema internals.\n */\nfunction codeForIssue(issue: z.core.$ZodIssue): ValidationErrorCode {\n const path = issue.path.map(String);\n if (path.includes('role')) return 'unknown-role';\n if (path.includes('revision')) return 'revision';\n if (path.includes('bounds') || ['row', 'column', 'width', 'height'].includes(path.at(-1) ?? ''))\n return 'bad-rect';\n if (issue.code === 'custom' && issue.message?.includes('hit regions')) return 'bad-rect';\n if (issue.code === 'too_big' && (path.includes('nodes') || path.includes('rootIds'))) {\n return 'count';\n }\n if (\n issue.code === 'custom' &&\n typeof issue.message === 'string' &&\n issue.message.includes('UTF-8 bytes')\n ) {\n return 'string-bytes';\n }\n return 'schema';\n}\n\nfunction describeIssue(issue: z.core.$ZodIssue): string {\n const where = issue.path.length > 0 ? issue.path.map(String).join('.') : '<root>';\n return `${where}: ${issue.message}`;\n}\n\nfunction rectIntersectsViewport(\n rect: { row: number; column: number; width: number; height: number },\n columns: number,\n rows: number,\n): boolean {\n if (rect.width === 0 || rect.height === 0) return false;\n return (\n rect.column < columns &&\n rect.row < rows &&\n rect.column + rect.width > 0 &&\n rect.row + rect.height > 0\n );\n}\n\nfunction rectContains(\n outer: { row: number; column: number; width: number; height: number },\n inner: { row: number; column: number; width: number; height: number },\n): boolean {\n return (\n inner.row >= outer.row &&\n inner.column >= outer.column &&\n inner.row + inner.height <= outer.row + outer.height &&\n inner.column + inner.width <= outer.column + outer.width\n );\n}\n\nfunction regionProblem(\n owner: string,\n region: {\n readonly regionBounds: { row: number; column: number; width: number; height: number };\n readonly spans: readonly { row: number; from: number; to: number }[];\n },\n columns: number,\n rows: number,\n): ValidationResult | null {\n for (const span of region.spans) {\n if (span.row >= rows || span.from >= columns || span.to > columns) {\n return fail('bad-rect', `${owner} span lies outside the viewport`);\n }\n if (\n span.row < region.regionBounds.row ||\n span.row >= region.regionBounds.row + region.regionBounds.height ||\n span.from < region.regionBounds.column ||\n span.to > region.regionBounds.column + region.regionBounds.width\n ) {\n return fail('bad-rect', `${owner} span lies outside regionBounds`);\n }\n }\n return null;\n}\n\nfunction checkNodeShape(\n node: SemanticNode,\n snapshot: SemanticSnapshot,\n ids: ReadonlySet<string>,\n limits: ProtocolLimits,\n): ValidationResult | null {\n // D1: `generic` is how an unrecognised widget survives instead of being\n // dropped, but only if it says what it was. A generic node without a\n // framework type carries no more information than the drop it replaced.\n if (node.role === 'generic' && (node.frameworkType === undefined || node.frameworkType === '')) {\n return fail(\n 'schema',\n `node ${node.id} has role 'generic' without a frameworkType; an unrecognised widget must ` +\n 'name what the framework called it',\n );\n }\n\n // Every cell outside the visible area and the node still visible cannot both\n // be true. Refusing the pair keeps `offscreen` a claim about scrolling rather\n // than a second, weaker way of saying \"hidden\".\n if (node.state?.offscreen === true && node.state.hidden !== true) {\n return fail(\n 'schema',\n `node ${node.id}: state.offscreen implies state.hidden — every cell is outside the ` +\n 'visible area, so the node cannot also be visible',\n );\n }\n\n for (const [name, observation] of [\n ['intendedRect', node.geometry.intendedRect],\n ['visibleRect', node.geometry.visibleRect],\n ] as const) {\n if (observation.status !== 'known') continue;\n const { row, column, width, height } = observation.value;\n if (!Number.isSafeInteger(row + height) || !Number.isSafeInteger(column + width)) {\n return fail('bad-rect', `node ${node.id}: ${name} overflows the safe-integer range`);\n }\n }\n\n if (node.paintedRegion?.status === 'known') {\n const problem = regionProblem(\n `node ${node.id} painted region`,\n node.paintedRegion.value,\n snapshot.columns,\n snapshot.rows,\n );\n if (problem !== null) return problem;\n }\n\n const intended = node.geometry.intendedRect;\n const visible = node.geometry.visibleRect;\n if (visible.status === 'known' && visible.value.width > 0 && visible.value.height > 0) {\n if (\n snapshot.coordinateSpace.status === 'known' &&\n snapshot.coordinateSpace.value === 'viewport-cells' &&\n !rectIntersectsViewport(visible.value, snapshot.columns, snapshot.rows)\n ) {\n return fail('bad-rect', `node ${node.id}: visibleRect does not intersect the viewport`);\n }\n if (intended.status === 'known' && !rectContains(intended.value, visible.value)) {\n return fail('bad-rect', `node ${node.id}: visibleRect extends outside intendedRect`);\n }\n }\n\n for (const range of node.textRanges ?? []) {\n if (range.endOffset < range.startOffset) {\n return fail('bad-rect', `node ${node.id}: text range ends before it starts`);\n }\n if (!Number.isSafeInteger(range.rect.row + range.rect.height)) {\n return fail('bad-rect', `node ${node.id}: text range rect overflows the safe-integer range`);\n }\n }\n\n for (const [field, targets] of [\n ['labelledBy', node.labelledBy],\n ['describedBy', node.describedBy],\n ] as const) {\n if (targets === undefined) continue;\n if (targets.length > limits.maxRelationTargets) {\n return fail(\n 'count',\n `node ${node.id}: ${field} exceeds ${limits.maxRelationTargets} targets`,\n );\n }\n for (const target of targets) {\n if (!ids.has(target)) {\n return fail(\n 'missing-parent',\n `node ${node.id}: ${field} references unknown node ${target}`,\n );\n }\n }\n }\n\n return null;\n}\n\n/**\n * Depth of every node, or the id at which a parent chain closes on itself.\n * Roots sit at depth 1.\n */\nfunction computeDepths(\n nodes: readonly SemanticNode[],\n byId: ReadonlyMap<string, SemanticNode>,\n): { readonly depths: ReadonlyMap<string, number> } | { readonly cycleAt: string } {\n const depths = new Map<string, number>();\n\n for (const start of nodes) {\n if (depths.has(start.id)) continue;\n const chain: string[] = [];\n const onChain = new Set<string>();\n let current: SemanticNode | undefined = start;\n\n while (current !== undefined && !depths.has(current.id)) {\n if (onChain.has(current.id)) return { cycleAt: current.id };\n onChain.add(current.id);\n chain.push(current.id);\n current = current.parentId === undefined ? undefined : byId.get(current.parentId);\n }\n\n let depth = current === undefined ? 0 : depths.get(current.id)!;\n for (let i = chain.length - 1; i >= 0; i -= 1) {\n depth += 1;\n depths.set(chain[i]!, depth);\n }\n }\n\n return { depths };\n}\n\n/**\n * Full snapshot validation per spec §8.2: unique ids, existing+acyclic parent\n * relations, dense bounded arrays, Unicode scalar strings within byte bounds,\n * safe-integer rects intersecting the viewport unless state.hidden, strictly\n * increasing revisions (checked by caller against session state), deep\n * immutability of the returned value.\n *\n * The value is first projected with {@link projectDto}, so getters on hostile\n * input are rejected without being invoked and the returned snapshot is a\n * deep-frozen plain copy that shares no references with the input.\n *\n * @param value - Untrusted candidate snapshot.\n * @param limits - Active limits; callers may tighten but never widen these.\n * @returns `{ ok: true, snapshot }` with a deep-frozen snapshot, or\n * `{ ok: false, code, detail }`. Never throws.\n */\nexport function validateSnapshot(value: unknown, limits: ProtocolLimits): ValidationResult {\n let projected: unknown;\n try {\n projected = projectDto<unknown>(value, limits.maxDepth);\n } catch (error) {\n if (error instanceof ProtocolViolation) {\n return fail(error.code === 'dto-depth' ? 'depth' : 'schema', error.message);\n }\n return fail('schema', 'value could not be projected into a plain DTO');\n }\n\n // Projection guarantees JSON-representability, so stringify cannot throw.\n const serialised = JSON.stringify(projected);\n if (serialised === undefined) {\n return fail('schema', 'snapshot is not a JSON object');\n }\n const bytes = Buffer.byteLength(serialised, 'utf8');\n if (bytes > limits.maxSnapshotBytes) {\n return fail('bytes', `snapshot is ${bytes} bytes, ceiling is ${limits.maxSnapshotBytes}`);\n }\n\n const parsed = treeSchemas(limits).snapshot.safeParse(projected);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n return fail(codeForIssue(issue), describeIssue(issue));\n }\n\n const snapshot = projected as SemanticSnapshot;\n\n if (snapshot.nodes.length > limits.maxNodes) {\n return fail(\n 'count',\n `snapshot carries ${snapshot.nodes.length} nodes, ceiling is ${limits.maxNodes}`,\n );\n }\n\n const byId = new Map<string, SemanticNode>();\n for (const node of snapshot.nodes) {\n if (byId.has(node.id)) {\n return fail('duplicate-id', `node id ${node.id} appears more than once`);\n }\n byId.set(node.id, node);\n }\n\n const rootIds = new Set<string>();\n for (const id of snapshot.rootIds) {\n if (rootIds.has(id)) {\n return fail('duplicate-id', `root id ${id} appears more than once`);\n }\n rootIds.add(id);\n const node = byId.get(id);\n if (node === undefined) {\n return fail('missing-parent', `rootIds references unknown node ${id}`);\n }\n if (node.parentId !== undefined) {\n return fail('schema', `root node ${id} declares a parent`);\n }\n }\n\n const ids: ReadonlySet<string> = new Set(byId.keys());\n\n if (\n snapshot.coordinateSpace.status === 'known' &&\n snapshot.coordinateSpace.value !== 'viewport-cells'\n ) {\n // Framework-local geometry is inspectable, but it cannot be addressed by\n // terminal input. Pointer ownership is independently qualified by the hit grid.\n }\n if (snapshot.hitGrid.status === 'known') {\n for (const region of snapshot.hitGrid.value.regions) {\n if (!ids.has(region.recipientId)) {\n return fail('missing-parent', `hitGrid references unknown recipient ${region.recipientId}`);\n }\n if (!rectIntersectsViewport(region.rect, snapshot.columns, snapshot.rows)) {\n return fail(\n 'bad-rect',\n `hitGrid region for ${region.recipientId} does not intersect the viewport`,\n );\n }\n }\n }\n\n const providerIds = new Set<string>();\n for (const provider of snapshot.providerEvidence ?? []) {\n if (providerIds.has(provider.providerId)) {\n return fail('provider', `provider evidence id ${provider.providerId} appears more than once`);\n }\n providerIds.add(provider.providerId);\n if (provider.sessionId !== snapshot.sessionId) {\n return fail(\n 'provider',\n `provider ${provider.providerId} evidence session ${provider.sessionId} does not match snapshot session ${snapshot.sessionId}`,\n );\n }\n if (provider.revision !== snapshot.revision) {\n return fail(\n 'provider',\n `provider ${provider.providerId} evidence revision ${provider.revision} does not match snapshot revision ${snapshot.revision}`,\n );\n }\n if (provider.status !== 'available') continue;\n if (provider.evidence.providerId !== provider.providerId) {\n return fail(\n 'schema',\n `provider ${provider.providerId} evidence provenance names ${provider.evidence.providerId}`,\n );\n }\n if (provider.focusState?.status === 'focused' && !ids.has(provider.focusState.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} focus references unknown recipient ${provider.focusState.recipientId}`,\n );\n }\n for (const region of provider.pointerRegions) {\n if (!ids.has(region.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} references unknown recipient ${region.recipientId}`,\n );\n }\n const problem = regionProblem(\n `provider ${provider.providerId} span for ${region.recipientId}`,\n region,\n snapshot.columns,\n snapshot.rows,\n );\n if (problem !== null) return problem;\n }\n for (const region of provider.paintedRegions ?? []) {\n if (!ids.has(region.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} painted region references unknown recipient ${region.recipientId}`,\n );\n }\n const problem = regionProblem(\n `provider ${provider.providerId} painted region for ${region.recipientId}`,\n region,\n snapshot.columns,\n snapshot.rows,\n );\n if (problem !== null) return problem;\n }\n for (const hit of provider.hitGrid?.regions ?? []) {\n if (!ids.has(hit.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} hitGrid references unknown recipient ${hit.recipientId}`,\n );\n }\n if (!rectIntersectsViewport(hit.rect, snapshot.columns, snapshot.rows)) {\n return fail(\n 'bad-rect',\n `provider ${provider.providerId} hitGrid region for ${hit.recipientId} does not intersect the viewport`,\n );\n }\n }\n for (const entry of provider.actionRecipes ?? []) {\n if (!ids.has(entry.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} action recipes reference unknown recipient ${entry.recipientId}`,\n );\n }\n const node = snapshot.nodes.find(({ id }) => id === entry.recipientId)!;\n const intents = new Set(node.actions ?? []);\n const missingIntent = entry.recipes.find(({ action }) => !intents.has(action));\n if (missingIntent !== undefined) {\n return fail(\n 'provider',\n `provider ${provider.providerId} ${missingIntent.action} recipe has no matching semantic action intent on ${entry.recipientId}`,\n );\n }\n }\n for (const state of provider.scrollStates ?? []) {\n if (!ids.has(state.recipientId)) {\n return fail(\n 'missing-parent',\n `provider ${provider.providerId} scroll state references unknown recipient ${state.recipientId}`,\n );\n }\n }\n }\n\n for (const node of snapshot.nodes) {\n if (node.parentId === undefined) {\n if (!rootIds.has(node.id)) {\n return fail('schema', `parentless node ${node.id} is missing from rootIds`);\n }\n } else if (!byId.has(node.parentId)) {\n return fail('missing-parent', `node ${node.id} references unknown parent ${node.parentId}`);\n } else if (node.parentId === node.id) {\n return fail('cycle', `node ${node.id} is its own parent`);\n }\n\n const problem = checkNodeShape(node, snapshot, ids, limits);\n if (problem !== null) return problem;\n }\n\n const depthResult = computeDepths(snapshot.nodes, byId);\n if ('cycleAt' in depthResult) {\n return fail('cycle', `parent chain through node ${depthResult.cycleAt} is cyclic`);\n }\n for (const [id, depth] of depthResult.depths) {\n if (depth > limits.maxDepth) {\n return fail('depth', `node ${id} sits at depth ${depth}, ceiling is ${limits.maxDepth}`);\n }\n }\n\n if (snapshot.cursor !== undefined) {\n const { row, column } = snapshot.cursor;\n if (row >= snapshot.rows || column >= snapshot.columns) {\n return fail('bad-rect', `cursor (${row}, ${column}) lies outside the viewport`);\n }\n }\n\n return { ok: true, snapshot };\n}\n","/**\n * Render-commit marker: emitted by the adapter into the PTY stdout AFTER the\n * last byte of the render belonging to revision N. It is a frame COMMIT\n * signal (Neovim `flush` semantics), never a data carrier.\n *\n * Encoding: a private OSC sequence terminated by BEL:\n *\n * OSC 8487 ; 'twm;' <revision> ';' <mac> BEL\n * i.e. `\\x1b]8487;twm;{rev};{mac}\\x07`\n *\n * where mac = base64url(HMAC-SHA256(token, `${sessionId}:${revision}`))\n * truncated to 16 bytes. The driver's VT layer registers an OSC handler,\n * verifies the MAC, and removes the sequence from the visible grid. Ordinary\n * application output cannot forge it. Emitted only after a successful\n * handshake; never during a normal (non-instrumented) run.\n *\n * ## Why OSC and not DCS\n *\n * The legacy, frame-based inbox ConPTY rewrote the stream it forwarded. A\n * permeability probe showed it dropping DCS, APC and OSC 8 while passing\n * private OSC with either terminator, and OSC 133. DCS therefore could not\n * carry a marker on the original Windows backend. The pinned passthrough\n * ConPTY now forwards those families, but OSC 8487 remains the single encoding\n * certified across every supported platform.\n *\n * One encoding is used everywhere rather than negotiating per platform: two\n * paths double the surface that has to stay correct, and the path used least\n * is the one that rots unnoticed. BEL is emitted rather than ST because it is\n * the terminator ConPTY was observed to forward most reliably; receivers\n * accept both, since a VT parser consumes the terminator before dispatching\n * anyway.\n *\n * ## Why 8487\n *\n * OSC numbers have no registry, only convention, so the number is chosen to\n * sit clear of everything in use: xterm's allocations (0–14, 46, 50, 52, 104,\n * 110–119), OSC 8 hyperlinks, 9 and 1337 (iTerm2), 99 and 30001 (kitty), 133\n * (FinalTerm shell integration — also the sequence ConPTY is known to\n * forward), 633 (VS Code), 697 (ConEmu) and 777–779 (urxvt/VTE). 8487 is the\n * ASCII codes of `T` and `W` — termwright — and appears in none of them.\n *\n * The `twm;` tag after the number is kept as a self-identifying guard: if\n * anything ever does claim 8487, a marker still says what it is instead of\n * being mistaken for that other feature's payload.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { ProtocolViolation } from './errors.js';\n\n/** The private OSC number carrying render-commit markers. */\nexport const MARKER_OSC_CODE = 8487;\n\n/**\n * The tag opening a marker payload, immediately after `OSC 8487;`.\n *\n * A VT parser hands an OSC handler everything after the number and its\n * separator, which is exactly what {@link verifyMarkerPayload} expects:\n *\n * ```ts\n * term.parser.registerOscHandler(MARKER_OSC_CODE, (data) => {\n * const marker = verifyMarkerPayload(data, token, sessionId);\n * if (marker !== null) commit(marker.revision);\n * return true; // consumed: keeps the sequence out of the visible grid\n * });\n * ```\n */\nexport const MARKER_OSC_PREFIX = 'twm;';\n\n/** Bytes of HMAC-SHA256 output retained in the marker MAC. */\nexport const MARKER_MAC_BYTES = 16;\n\n/** Length of the base64url-encoded MAC (16 bytes, unpadded). */\nconst MARKER_MAC_CHARS = 22;\n\n/** Canonical decimal revision: no sign, no leading zero, no whitespace. */\nconst REVISION_TEXT = /^[1-9][0-9]{0,15}$/;\n\n/** base64url alphabet, exact MAC length. */\nconst MAC_TEXT = new RegExp(`^[A-Za-z0-9_-]{${MARKER_MAC_CHARS}}$`);\n\n/** BEL, the terminator this implementation emits. */\nconst BEL = '\\x07';\n\n/** ST, the terminator a receiver must also accept. */\nconst ST = '\\x1b\\\\';\n\nexport interface RenderMarker {\n readonly revision: number;\n readonly mac: string;\n}\n\nfunction computeMac(token: string, sessionId: string, revision: number): string {\n return createHmac('sha256', token)\n .update(`${sessionId}:${revision}`, 'utf8')\n .digest()\n .subarray(0, MARKER_MAC_BYTES)\n .toString('base64url');\n}\n\n/**\n * Build the full escape sequence for a marker.\n *\n * @param token - Per-launch session token (`TERMWRIGHT_TOKEN`); used as the\n * HMAC key and never appears in the emitted bytes.\n * @param sessionId - Session id from the handshake, bound into the MAC so a\n * marker from one session cannot be replayed into another.\n * @param revision - Positive safe integer identifying the committed render.\n * @returns The complete `OSC … BEL` sequence to write to stdout.\n * @throws {ProtocolViolation} If the revision is not a positive safe integer,\n * or the token/sessionId are empty.\n */\nexport function encodeMarker(token: string, sessionId: string, revision: number): string {\n if (token.length === 0) {\n throw new ProtocolViolation('marker-argument', 'token must not be empty');\n }\n if (sessionId.length === 0) {\n throw new ProtocolViolation('marker-argument', 'sessionId must not be empty');\n }\n if (!Number.isSafeInteger(revision) || revision <= 0) {\n throw new ProtocolViolation('marker-argument', 'revision must be a positive safe integer');\n }\n const mac = computeMac(token, sessionId, revision);\n return `\\x1b]${MARKER_OSC_CODE};${MARKER_OSC_PREFIX}${revision};${mac}${BEL}`;\n}\n\n/**\n * Parse+verify an OSC payload (the part after `OSC 8487;`). Returns null on any mismatch.\n *\n * Total function: hostile payloads yield `null`, never an exception. The MAC\n * comparison is constant-time, and only canonically-formatted revisions are\n * accepted so `1` and `01` cannot both authenticate the same commit.\n *\n * A trailing BEL or ST is tolerated. A VT parser consumes the terminator\n * before dispatching, so a handler normally passes a payload without one,\n * while a caller scanning raw output with a regex may keep it — both must work.\n *\n * @param payload - Everything after `OSC 8487;`, i.e. `twm;{rev};{mac}`.\n * @param token - Per-launch session token used as the HMAC key.\n * @param sessionId - Session id the marker must be bound to.\n */\nexport function verifyMarkerPayload(\n payload: string,\n token: string,\n sessionId: string,\n): RenderMarker | null {\n if (token.length === 0 || sessionId.length === 0) return null;\n\n let text = payload;\n if (text.endsWith(BEL)) text = text.slice(0, -BEL.length);\n else if (text.endsWith(ST)) text = text.slice(0, -ST.length);\n\n if (!text.startsWith(MARKER_OSC_PREFIX)) return null;\n\n const body = text.slice(MARKER_OSC_PREFIX.length);\n const separator = body.indexOf(';');\n if (separator < 0) return null;\n\n const revisionText = body.slice(0, separator);\n const mac = body.slice(separator + 1);\n if (!REVISION_TEXT.test(revisionText)) return null;\n if (!MAC_TEXT.test(mac)) return null;\n\n const revision = Number(revisionText);\n if (!Number.isSafeInteger(revision) || revision <= 0) return null;\n\n const expected = Buffer.from(computeMac(token, sessionId, revision), 'utf8');\n const actual = Buffer.from(mac, 'utf8');\n // Both are MARKER_MAC_CHARS ASCII bytes by construction, but guard anyway:\n // timingSafeEqual throws on a length mismatch.\n if (expected.length !== actual.length) return null;\n if (!timingSafeEqual(expected, actual)) return null;\n\n return Object.freeze({ revision, mac });\n}\n","/** Private, request-addressed cursor synchronization used by Termwright's ConPTY host. */\nexport const CONPTY_HOST_CURSOR_OSC_CODE = 8488;\n\n/** Versioned payload prefix inside the host-reserved OSC 8488 namespace. */\nexport const CONPTY_HOST_CURSOR_PREFIX = 'twh-cpr-v1';\n\nconst TOKEN = '[0-9a-f]{32}';\nconst REQUEST = new RegExp(`^${CONPTY_HOST_CURSOR_PREFIX}:q:(${TOKEN})$`, 'u');\nconst RESPONSE = new RegExp(\n `^\\\\x1b\\\\]${CONPTY_HOST_CURSOR_OSC_CODE};${CONPTY_HOST_CURSOR_PREFIX}:r:(${TOKEN}):([1-9][0-9]{0,4}):([1-9][0-9]{0,4})\\\\x07$`,\n 'u',\n);\nconst MAX_COORDINATE = 32_768;\n\nexport interface ConPtyHostCursorRequest {\n readonly token: string;\n}\n\nexport interface ConPtyHostCursorResponse extends ConPtyHostCursorRequest {\n readonly row: number;\n readonly column: number;\n}\n\n/** Parses the payload delivered by an OSC 8488 handler, after `8488;`. */\nexport function parseConPtyHostCursorRequest(payload: string): ConPtyHostCursorRequest | null {\n const match = REQUEST.exec(payload);\n return match?.[1] === undefined ? null : { token: match[1] };\n}\n\n/** Encodes the only reply the patched native host consumes. Coordinates are one-based. */\nexport function encodeConPtyHostCursorResponse(\n request: ConPtyHostCursorRequest,\n row: number,\n column: number,\n): string {\n if (!new RegExp(`^${TOKEN}$`, 'u').test(request.token)) {\n throw new TypeError('ConPTY host cursor token must be 128-bit lowercase hexadecimal');\n }\n for (const [name, value] of [\n ['row', row],\n ['column', column],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 1 || value > MAX_COORDINATE) {\n throw new RangeError(`ConPTY host cursor ${name} must be an integer from 1 to 32768`);\n }\n }\n return `\\x1b]${CONPTY_HOST_CURSOR_OSC_CODE};${CONPTY_HOST_CURSOR_PREFIX}:r:${request.token}:${row}:${column}\\x07`;\n}\n\n/** Strictly recognizes a complete host reply before the PTY chooses its input transport. */\nexport function parseConPtyHostCursorResponse(\n value: Uint8Array | string,\n): ConPtyHostCursorResponse | null {\n const text =\n typeof value === 'string' ? value : new TextDecoder('ascii', { fatal: true }).decode(value);\n const match = RESPONSE.exec(text);\n if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) return null;\n const row = Number(match[2]);\n const column = Number(match[3]);\n if (row > MAX_COORDINATE || column > MAX_COORDINATE) return null;\n return { token: match[1], row, column };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAGrB,IAAM,eAAe;AACrB,IAAM,YAAY;AAGlB,IAAM,mBAAmB;AACzB,IAAM,cAAc;AAIpB,IAAM,cAAc;AAiBpB,SAAS,gBAAwB;AACtC,SAAO,YAAY,WAAW,EAAE,SAAS,WAAW;AACtD;;;ACaO,IAAM,oBAAN,cAAgC,MAAM;AAAA;AAAA,EAElC;AAAA,EAET,YAAY,MAA6B,SAAiB;AACxD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACjDO,IAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKO,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIO,IAAM,gCAAgC,CAAC,SAAS,YAAY,UAAU,UAAU;;;AClBhF,IAAM,iBAAiC,OAAO,OAAO;AAAA,EAC1D,eAAe,IAAI,OAA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