browser-semantic-serializer.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import type {
  2. AgentSemanticNode,
  3. AgentSemanticTreePage,
  4. SemanticNode,
  5. SemanticPageTree,
  6. SemanticTargetRef,
  7. } from './browser-semantic-tree.js';
  8. const MODEL_CONTEXT_ROLES = new Set([
  9. 'document',
  10. 'main',
  11. 'navigation',
  12. 'region',
  13. 'article',
  14. 'form',
  15. 'dialog',
  16. 'alertdialog',
  17. 'heading',
  18. 'list',
  19. 'listitem',
  20. 'table',
  21. 'row',
  22. 'cell',
  23. 'columnheader',
  24. 'rowheader',
  25. 'group',
  26. 'paragraph',
  27. 'label',
  28. 'caption',
  29. 'note',
  30. 'status',
  31. 'alert',
  32. 'description',
  33. ]);
  34. function subtreeCounts(
  35. node: SemanticNode,
  36. refs: ReadonlyMap<string, SemanticTargetRef>,
  37. allowedRefs: ReadonlySet<string>,
  38. counts: Map<string, { anyActionable: number; allowedActionable: number }>,
  39. ): { anyActionable: number; allowedActionable: number } {
  40. const ownRef = node.targetKey ? refs.get(node.targetKey)?.ref : undefined;
  41. let anyActionable = ownRef ? 1 : 0;
  42. let allowedActionable = ownRef && allowedRefs.has(ownRef) ? 1 : 0;
  43. for (const child of node.children) {
  44. const childCounts = subtreeCounts(child, refs, allowedRefs, counts);
  45. anyActionable += childCounts.anyActionable;
  46. allowedActionable += childCounts.allowedActionable;
  47. }
  48. const result = { anyActionable, allowedActionable };
  49. counts.set(node.id, result);
  50. return result;
  51. }
  52. export function serializeSemanticTreePage(
  53. tree: SemanticPageTree,
  54. refs: ReadonlyMap<string, SemanticTargetRef>,
  55. allowedRefs: ReadonlySet<string>,
  56. options: { maxNodes?: number; maxBytes?: number } = {},
  57. ): AgentSemanticTreePage {
  58. const maxNodes = Math.max(1, options.maxNodes ?? 200);
  59. const maxBytes = Math.max(256, options.maxBytes ?? 12_000);
  60. const counts = new Map<string, { anyActionable: number; allowedActionable: number }>();
  61. tree.roots.forEach((root) => subtreeCounts(root, refs, allowedRefs, counts));
  62. let retainedNodes = 0;
  63. let retainedBytes = 0;
  64. let truncated = tree.truncated;
  65. const actionableFirst = (nodes: readonly SemanticNode[]): SemanticNode[] =>
  66. nodes
  67. .map((node, index) => ({ node, index }))
  68. .sort((left, right) => {
  69. const leftAllowed = counts.get(left.node.id)?.allowedActionable ?? 0;
  70. const rightAllowed = counts.get(right.node.id)?.allowedActionable ?? 0;
  71. return rightAllowed - leftAllowed || left.index - right.index;
  72. })
  73. .map(({ node }) => node);
  74. const serialize = (node: SemanticNode, contextual = false): AgentSemanticNode | null => {
  75. const count = counts.get(node.id) ?? { anyActionable: 0, allowedActionable: 0 };
  76. const targetRef = node.targetKey ? refs.get(node.targetKey) : undefined;
  77. if (targetRef && !allowedRefs.has(targetRef.ref)) return null;
  78. if (!targetRef && count.anyActionable > 0 && count.allowedActionable === 0) return null;
  79. if (
  80. !targetRef &&
  81. count.allowedActionable === 0 &&
  82. !contextual &&
  83. !MODEL_CONTEXT_ROLES.has(node.role)
  84. ) {
  85. return null;
  86. }
  87. const base: AgentSemanticNode = {
  88. role: node.role,
  89. ...(node.name ? { name: node.name } : {}),
  90. ...(node.text ? { text: node.text } : {}),
  91. ...(node.level ? { level: node.level } : {}),
  92. ...(node.state ? { state: node.state } : {}),
  93. ...(targetRef
  94. ? {
  95. ref: targetRef.ref,
  96. frame: targetRef.frameRef,
  97. actionable: true as const,
  98. ...(node.coordinateSpace !== 'unavailable' && node.rect
  99. ? { rect: { ...node.rect } }
  100. : {}),
  101. }
  102. : {}),
  103. };
  104. const estimatedBytes = Buffer.byteLength(JSON.stringify(base), 'utf8');
  105. if (retainedNodes >= maxNodes || retainedBytes + estimatedBytes > maxBytes) {
  106. truncated = true;
  107. return null;
  108. }
  109. retainedNodes += 1;
  110. retainedBytes += estimatedBytes;
  111. const children = actionableFirst(node.children)
  112. .map((child) => serialize(child, count.allowedActionable > 0 || contextual))
  113. .filter((child): child is AgentSemanticNode => child !== null);
  114. return children.length > 0 ? { ...base, children } : base;
  115. };
  116. const roots = actionableFirst(tree.roots)
  117. .map((root) => serialize(root))
  118. .filter((root): root is AgentSemanticNode => root !== null);
  119. return { version: 1, roots, truncated };
  120. }