@opentiny/next-sdk 0.3.3 → 0.4.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 (134) hide show
  1. package/agent/AgentModelProvider.ts +78 -81
  2. package/agent/type.ts +6 -9
  3. package/agent/utils/getAISDKTools.ts +0 -1
  4. package/agent/utils/getBuiltinMcpTools.ts +7 -7
  5. package/core.ts +1 -3
  6. package/dist/SimulatorMask-BHVXyogh-iNUb4dyF.js +361 -0
  7. package/dist/agent/type.d.ts +4 -12
  8. package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
  9. package/dist/core.d.ts +1 -1
  10. package/dist/core.js +18 -18
  11. package/dist/index-CXK8CcKq.js +6076 -0
  12. package/dist/index.d.ts +2 -4
  13. package/dist/index.js +57 -2783
  14. package/dist/initialize-builtin-WebMCP-rALfqS-o.js +6389 -0
  15. package/dist/page-tools/a11y/build.d.ts +11 -0
  16. package/dist/page-tools/a11y/constants.d.ts +9 -0
  17. package/dist/page-tools/a11y/search.d.ts +17 -0
  18. package/dist/page-tools/a11y/types.d.ts +104 -0
  19. package/dist/page-tools/a11y/utils.d.ts +34 -0
  20. package/dist/page-tools/a11y/vnode.d.ts +37 -0
  21. package/dist/page-tools/a11y-tree.d.ts +12 -0
  22. package/dist/page-tools/bridge.d.ts +0 -6
  23. package/dist/page-tools/constants.d.ts +22 -0
  24. package/dist/page-tools/context.d.ts +28 -0
  25. package/dist/page-tools/handlers/browserState.d.ts +8 -0
  26. package/dist/page-tools/handlers/click.d.ts +8 -0
  27. package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
  28. package/dist/page-tools/handlers/fill.d.ts +8 -0
  29. package/dist/page-tools/handlers/scroll.d.ts +8 -0
  30. package/dist/page-tools/handlers/searchTree.d.ts +8 -0
  31. package/dist/page-tools/handlers/select.d.ts +8 -0
  32. package/dist/page-tools/initialize-builtin-WebMCP.d.ts +1 -0
  33. package/dist/page-tools/page-agent-highlight/index.d.ts +9 -0
  34. package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +14 -0
  35. package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
  36. package/dist/page-tools/page-agent-tool.d.ts +4 -0
  37. package/dist/page-tools/page-state-cache.d.ts +36 -0
  38. package/dist/page-tools/schema.d.ts +43 -0
  39. package/dist/page-tools/utils/dom.d.ts +6 -0
  40. package/dist/page-tools/utils/scroll.d.ts +15 -0
  41. package/dist/runtime.d.ts +4 -0
  42. package/dist/runtime.js +744 -0
  43. package/dist/utils/builtinProxy.d.ts +1 -1
  44. package/index.ts +2 -19
  45. package/package.json +14 -18
  46. package/page-tools/a11y/build.ts +70 -0
  47. package/page-tools/a11y/constants.ts +110 -0
  48. package/page-tools/a11y/search.ts +129 -0
  49. package/page-tools/a11y/types.ts +108 -0
  50. package/page-tools/a11y/utils.ts +266 -0
  51. package/page-tools/a11y/vnode.ts +229 -0
  52. package/page-tools/a11y-tree.ts +13 -0
  53. package/page-tools/bridge.ts +49 -15
  54. package/page-tools/constants.ts +72 -0
  55. package/page-tools/context.ts +13 -0
  56. package/page-tools/handlers/browserState.ts +12 -0
  57. package/page-tools/handlers/click.ts +26 -0
  58. package/page-tools/handlers/executeJavascript.ts +22 -0
  59. package/page-tools/handlers/fill.ts +60 -0
  60. package/page-tools/handlers/scroll.ts +66 -0
  61. package/page-tools/handlers/searchTree.ts +30 -0
  62. package/page-tools/handlers/select.ts +34 -0
  63. package/page-tools/initialize-builtin-WebMCP.ts +20 -0
  64. package/page-tools/page-agent-highlight/index.ts +198 -0
  65. package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
  66. package/page-tools/page-agent-mask/SimulatorMask.ts +279 -0
  67. package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
  68. package/page-tools/page-agent-mask/cursor-border.svg +3 -0
  69. package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
  70. package/page-tools/page-agent-mask/cursor.module.css +70 -0
  71. package/page-tools/page-agent-prompt.md +139 -0
  72. package/page-tools/page-agent-tool.ts +175 -0
  73. package/page-tools/page-state-cache.ts +78 -0
  74. package/page-tools/schema.ts +51 -0
  75. package/page-tools/utils/dom.ts +155 -0
  76. package/page-tools/utils/scroll.ts +58 -0
  77. package/runtime.ts +13 -0
  78. package/utils/builtinProxy.ts +45 -13
  79. package/vite.config.runtime.ts +22 -0
  80. package/vite.config.ts +52 -8
  81. package/McpSdk.ts +0 -14
  82. package/WebAgent.ts +0 -5
  83. package/WebMcp.ts +0 -20
  84. package/Zod.ts +0 -1
  85. package/dist/AgentModelProvider-CwqOT28f.js +0 -4198
  86. package/dist/McpSdk.d.ts +0 -14
  87. package/dist/WebAgent.d.ts +0 -5
  88. package/dist/WebMcp.d.ts +0 -20
  89. package/dist/Zod.d.ts +0 -1
  90. package/dist/index.es.dev.js +0 -53427
  91. package/dist/index.es.js +0 -42147
  92. package/dist/index.umd.dev.js +0 -53820
  93. package/dist/index.umd.js +0 -814
  94. package/dist/mcpsdk@1.25.3.dev.js +0 -22621
  95. package/dist/mcpsdk@1.25.3.es.dev.js +0 -22619
  96. package/dist/mcpsdk@1.25.3.es.js +0 -16802
  97. package/dist/mcpsdk@1.25.3.js +0 -43
  98. package/dist/transport/ExtensionClientTransport.d.ts +0 -24
  99. package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
  100. package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
  101. package/dist/transport/messages.d.ts +0 -9
  102. package/dist/vite.config.mcpSdk.d.ts +0 -2
  103. package/dist/vite.config.webAgent.d.ts +0 -2
  104. package/dist/vite.config.webMcp.d.ts +0 -2
  105. package/dist/vite.config.webMcpFull.d.ts +0 -2
  106. package/dist/vite.config.zod.d.ts +0 -2
  107. package/dist/webagent.dev.js +0 -47597
  108. package/dist/webagent.es.dev.js +0 -47204
  109. package/dist/webagent.es.js +0 -37494
  110. package/dist/webagent.js +0 -634
  111. package/dist/webmcp-full.dev.js +0 -24430
  112. package/dist/webmcp-full.es.dev.js +0 -24426
  113. package/dist/webmcp-full.es.js +0 -18333
  114. package/dist/webmcp-full.js +0 -43
  115. package/dist/webmcp.dev.js +0 -1595
  116. package/dist/webmcp.es.dev.js +0 -1589
  117. package/dist/webmcp.es.js +0 -1406
  118. package/dist/webmcp.js +0 -1
  119. package/dist/zod@3.25.76.dev.js +0 -4037
  120. package/dist/zod@3.25.76.es.dev.js +0 -4033
  121. package/dist/zod@3.25.76.es.js +0 -2945
  122. package/dist/zod@3.25.76.js +0 -1
  123. package/transport/ExtensionClientTransport.ts +0 -100
  124. package/transport/ExtensionContentServerTransport.ts +0 -162
  125. package/transport/ExtensionPageServerTransport.ts +0 -149
  126. package/transport/messages.ts +0 -63
  127. package/vite-build-tsc.ts +0 -63
  128. package/vite-env.d.ts +0 -5
  129. package/vite.config.mcpSdk.ts +0 -28
  130. package/vite.config.webAgent.ts +0 -19
  131. package/vite.config.webMcp.ts +0 -40
  132. package/vite.config.webMcpFull.ts +0 -19
  133. package/vite.config.zod.ts +0 -23
  134. /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
@@ -0,0 +1,72 @@
1
+ /** 校验错误默认选择器:ARIA 标准 + 主流 UI 框架 */
2
+ export const DEFAULT_ERROR_SELECTORS: string[] = [
3
+ // W3C ARIA 标准(最可靠,框架无关)
4
+ '[role="alert"]',
5
+ '[aria-invalid="true"]',
6
+ // Tiny3 / Lego(华为云)
7
+ '.ti3-unifyvalid-error',
8
+ '.ti3-error',
9
+ '.ti-error',
10
+ '.lego-text-error',
11
+ '.lego-error',
12
+ // Element UI / Element Plus
13
+ '.el-form-item__error',
14
+ // Ant Design
15
+ '.ant-form-item-explain-error',
16
+ // Bootstrap
17
+ '.is-invalid',
18
+ '.invalid-feedback',
19
+ // Angular
20
+ '.ng-invalid',
21
+ // 通用命名约定
22
+ '.error-msg',
23
+ '.error-message',
24
+ '.error-text',
25
+ '.field-error',
26
+ '.form-error',
27
+ '.is-error',
28
+ '.has-error',
29
+ '.validate-error',
30
+ '.valid-error'
31
+ ]
32
+
33
+ /** 模态弹窗默认选择器:ARIA 标准 + 主流 UI 框架 */
34
+ export const DEFAULT_DIALOG_SELECTORS: string[] = [
35
+ // W3C ARIA 标准
36
+ '[role="dialog"]',
37
+ '[role="alertdialog"]',
38
+ // Tiny3 / Lego(华为云)
39
+ '[class*="ti3-modal"]',
40
+ '[class*="ti3-message-box"]',
41
+ // Element UI / Element Plus
42
+ '[class*="el-dialog"]',
43
+ '[class*="el-message-box"]',
44
+ // Ant Design
45
+ '[class*="ant-modal"]',
46
+ // Bootstrap
47
+ '[class*="modal-content"]',
48
+ // Vuetify
49
+ '[class*="v-dialog"]',
50
+ // Naive UI
51
+ '[class*="n-modal"]'
52
+ ]
53
+
54
+ export interface PageAgentToolOptions {
55
+ /** 允许在无障碍树节点中额外暴露的 DOM 属性白名单 */
56
+ exposedAttributes?: string[]
57
+ /** 是否启用元素高亮 */
58
+ enableHighlight?: boolean
59
+ }
60
+
61
+ declare global {
62
+ interface Window {
63
+ __webmcpcli_interactiveWhitelist?: Element[]
64
+ __webmcpcli_interactiveBlacklist?: Element[]
65
+ __webmcpcli_exposedAttributes?: string[]
66
+ __webmcpcli_beforeGetBrowserState?: (() => void) | null
67
+ /** 校验错误元素 CSS 选择器列表(覆盖默认,用于检测页面可见的校验错误) */
68
+ __webmcpcli_errorSelectors?: string[]
69
+ /** 模态弹窗元素 CSS 选择器列表(覆盖默认,用于检测阻塞交互的弹窗) */
70
+ __webmcpcli_dialogSelectors?: string[]
71
+ }
72
+ }
@@ -0,0 +1,13 @@
1
+ import type { PageController } from '@page-agent/page-controller'
2
+ import type { PageStateCache } from './page-state-cache'
3
+ import type { RefMap } from './a11y-tree'
4
+
5
+ export interface ActionContext {
6
+ pageController: PageController
7
+ stateCache: PageStateCache
8
+ getRefMap: () => RefMap
9
+ setRefMap: (map: RefMap) => void
10
+ buildBrowserStateResponse: (mode?: 'full' | 'diff' | 'both') => Promise<{ content: Array<{ type: 'text'; text: string }> }>
11
+ refreshOnStaleRef: (action: string, index: number) => Promise<{ content: Array<{ type: 'text'; text: string }> }>
12
+ errContent: (msg: string) => Promise<{ content: Array<{ type: 'text'; text: string }> }>
13
+ }
@@ -0,0 +1,12 @@
1
+ import type { ActionContext } from '../context'
2
+
3
+ export async function handleBrowserState(args: any, ctx: ActionContext) {
4
+ if (window.__webmcpcli_beforeGetBrowserState) {
5
+ try {
6
+ window.__webmcpcli_beforeGetBrowserState()
7
+ } catch (e) {
8
+ console.warn('__webmcpcli_beforeGetBrowserState error:', e)
9
+ }
10
+ }
11
+ return ctx.buildBrowserStateResponse(args.responseMode ?? 'diff')
12
+ }
@@ -0,0 +1,26 @@
1
+ import { clickElement } from '@page-agent/page-controller'
2
+ import { waitForDomSettled } from '../utils/dom'
3
+ import type { ActionContext } from '../context'
4
+
5
+ export async function handleClick(args: any, ctx: ActionContext) {
6
+ const mode = args.responseMode ?? 'diff'
7
+ if (args.index === undefined) return ctx.errContent('点击结果: 缺少元素索引')
8
+ const el = ctx.getRefMap().get(args.index)
9
+ if (!el) return ctx.refreshOnStaleRef('点击', args.index)
10
+
11
+ // 若 ref 指向 shadow host,解析其内部真正的可点击元素
12
+ let targetEl = el as HTMLElement
13
+ if (el.shadowRoot && !(el instanceof HTMLButtonElement) && !(el instanceof HTMLAnchorElement)) {
14
+ const innerClickable = el.shadowRoot.querySelector(
15
+ 'button, a, [role="button"], [role="link"]'
16
+ ) as HTMLElement | null
17
+ if (innerClickable) {
18
+ targetEl = innerClickable
19
+ }
20
+ }
21
+ await clickElement(targetEl)
22
+ // 等待框架异步插入的校验错误/条件渲染内容稳定后再采集状态
23
+ await waitForDomSettled()
24
+ // 操作成功后自动返回 diff/both/full
25
+ return ctx.buildBrowserStateResponse(mode)
26
+ }
@@ -0,0 +1,22 @@
1
+ import type { ActionContext } from '../context'
2
+
3
+ export async function handleExecuteJavascript(args: any, ctx: ActionContext) {
4
+ if (!args.script) return ctx.errContent('脚本执行异常: 缺少javascript代码')
5
+ // eslint-disable-next-line no-new-func
6
+ // 方式1:将脚本包裹在 async IIFE 中执行,允许 return 语句
7
+ let result = await new Function(`return (async () => { ${args.script} })()`)()
8
+ // 方式2:若 result 为 undefined(脚本没有 return),降级尝试以表达式方式求值
9
+ // 场景:Agent 写了 "Array.from(...).map(...)" 但没有 return 关键字
10
+ if (result === undefined) {
11
+ try {
12
+ // eslint-disable-next-line no-new-func
13
+ result = await new Function(`return (async () => (${args.script}))()`)()
14
+ } catch {
15
+ // 表达式求值也失败(如含 await/let/const 等语句),保持 undefined
16
+ }
17
+ }
18
+ await ctx.pageController.hideMask()
19
+ return {
20
+ content: [{ type: 'text' as const, text: `脚本执行结果: ${JSON.stringify(result)}` }]
21
+ }
22
+ }
@@ -0,0 +1,60 @@
1
+ import { inputTextElement } from '@page-agent/page-controller'
2
+ import { dispatchComposedEvents, isInShadowDom, waitForDomSettled } from '../utils/dom'
3
+ import type { ActionContext } from '../context'
4
+
5
+ export async function handleFill(args: any, ctx: ActionContext) {
6
+ const mode = args.responseMode ?? 'diff'
7
+ if (args.index === undefined || typeof args.text !== 'string') return ctx.errContent('填写结果: 缺少元素索引或文本内容')
8
+ const el = ctx.getRefMap().get(args.index)
9
+ if (!el) return ctx.refreshOnStaleRef('填写', args.index)
10
+
11
+ let targetEl = el
12
+ if (!(targetEl instanceof HTMLInputElement) && !(targetEl instanceof HTMLTextAreaElement)) {
13
+ // querySelector 不穿透 shadow boundary,对 shadow host 补查其 shadowRoot
14
+ const innerInput = el.querySelector('input, textarea')
15
+ ?? (el.shadowRoot?.querySelector('input, textarea') as HTMLElement | null)
16
+ if (innerInput) {
17
+ targetEl = innerInput as HTMLElement
18
+ }
19
+ }
20
+
21
+ if (targetEl instanceof HTMLInputElement && targetEl.readOnly) {
22
+ targetEl.value = args.text
23
+ // composed:true 确保事件穿透 shadow boundary,事件委托框架可捕获
24
+ dispatchComposedEvents(targetEl, 'input', 'change', 'blur')
25
+ } else {
26
+ // 优先尝试标准方式(支持 contenteditable、普通 input/textarea)
27
+ let fillSuccess = false
28
+ try {
29
+ await inputTextElement(targetEl, args.text)
30
+ fillSuccess = true
31
+ } catch (fillErr) {
32
+ // inputTextElement 失败时(如 Angular/React 组件包装的密码框),
33
+ // 降级使用原生 input value 描述符触发框架变更检测
34
+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
35
+ (targetEl instanceof HTMLTextAreaElement ? HTMLTextAreaElement : HTMLInputElement).prototype,
36
+ 'value'
37
+ )?.set
38
+ if (nativeInputValueSetter && (targetEl instanceof HTMLInputElement || targetEl instanceof HTMLTextAreaElement)) {
39
+ nativeInputValueSetter.call(targetEl, args.text)
40
+ // 发送完整事件序列,触发 Angular ngModel / React 合成事件的变更检测
41
+ targetEl.dispatchEvent(new Event('focus', { bubbles: true, composed: true }))
42
+ targetEl.dispatchEvent(new Event('input', { bubbles: true, composed: true }))
43
+ targetEl.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
44
+ targetEl.dispatchEvent(new Event('blur', { bubbles: true, composed: true }))
45
+ fillSuccess = true
46
+ }
47
+ }
48
+ if (!fillSuccess) {
49
+ return ctx.errContent(`填写结果: 无法填写元素 ${args.index},元素不是 input、textarea 或 contenteditable`)
50
+ }
51
+ // shadow DOM 内元素:inputTextElement 派发的合成事件 composed:false,
52
+ // 补发 composed:true 事件确保事件委托框架(如 React)能收到
53
+ if (isInShadowDom(targetEl)) {
54
+ dispatchComposedEvents(targetEl, 'input', 'change')
55
+ }
56
+ }
57
+ // 等待框架异步插入的校验错误/条件渲染内容稳定后再采集状态
58
+ await waitForDomSettled()
59
+ return ctx.buildBrowserStateResponse(mode)
60
+ }
@@ -0,0 +1,66 @@
1
+ import { getScrollInfo, waitForScrollEnd } from '../utils/scroll'
2
+ import type { ActionContext } from '../context'
3
+
4
+ export async function handleScroll(args: any, ctx: ActionContext) {
5
+ const mode = args.responseMode ?? 'diff'
6
+ if (args.down === undefined && args.right === undefined) return ctx.errContent('滚动结果: 缺少滚动方向参数')
7
+
8
+ // 确定滚动目标(有 index 时滚动该元素容器,否则滚动整个文档)
9
+ let scrollTarget: Element | Window = window
10
+ if (args.index !== undefined) {
11
+ const el = ctx.getRefMap().get(args.index)
12
+ if (!el) return ctx.refreshOnStaleRef('滚动', args.index)
13
+ scrollTarget = el
14
+ }
15
+
16
+ // 滚动前快照
17
+ const before = getScrollInfo(scrollTarget)
18
+
19
+ if (args.right !== undefined) {
20
+ const pixels = args.pixels ?? 300
21
+ scrollTarget.scrollBy({ left: args.right ? pixels : -pixels, behavior: 'smooth' })
22
+ } else {
23
+ const pixels = args.pixels ?? Math.round((args.numPages ?? 1) * window.innerHeight)
24
+ scrollTarget.scrollBy({ top: args.down ? pixels : -pixels, behavior: 'smooth' })
25
+ }
26
+
27
+ // 等待滚动动画完成后再采集状态(scrollend + 超时兜底)
28
+ await waitForScrollEnd(scrollTarget)
29
+
30
+ // 滚动后快照,计算实际位移
31
+ const after = getScrollInfo(scrollTarget)
32
+ const deltaY = Math.round(after.scrollY - before.scrollY)
33
+ const deltaX = Math.round(after.scrollX - before.scrollX)
34
+ const isHorizontal = args.right !== undefined
35
+
36
+ let scrollMsg: string
37
+ if (Math.abs(deltaY) < 1 && Math.abs(deltaX) < 1) {
38
+ // 实际未发生位移,说明已到达边界
39
+ if (isHorizontal) {
40
+ scrollMsg = args.right ? '⚠️ 已到达右边界,无法继续向右滚动' : '⚠️ 已到达左边界,无法继续向左滚动'
41
+ } else {
42
+ scrollMsg = args.down ? '⚠️ 已到达底部,无法继续向下滚动' : '⚠️ 已到达顶部,无法继续向上滚动'
43
+ }
44
+ } else {
45
+ const axis = isHorizontal ? `水平滚动 ${deltaX}px` : `垂直滚动 ${deltaY}px`
46
+ let boundary = ''
47
+ if (isHorizontal) {
48
+ if (args.right && after.atRight) boundary = ',已到达右边界'
49
+ else if (!args.right && after.atLeft) boundary = ',已到达左边界'
50
+ } else {
51
+ if (args.down && after.atBottom) boundary = ',已到达底部'
52
+ else if (!args.down && after.atTop) boundary = ',已到达顶部'
53
+ }
54
+ scrollMsg = `✅ ${axis}${boundary}`
55
+ }
56
+
57
+ // 附加位置信息(参考 page-agent getPageInfo 格式)
58
+ const posInfo = args.right !== undefined
59
+ ? `当前水平滚动位置: scrollX=${Math.round(after.scrollX)}px,左侧 ${after.pagesAbove.toFixed(1)} 屏,右侧 ${after.pagesBelow.toFixed(1)} 屏`
60
+ : `当前滚动位置: scrollY=${Math.round(after.scrollY)}px,上方 ${after.pagesAbove.toFixed(1)} 屏,下方 ${after.pagesBelow.toFixed(1)} 屏`
61
+ const scrollResult = `[滚动结果] ${scrollMsg}\n${posInfo}`
62
+
63
+ const stateResult = await ctx.buildBrowserStateResponse(mode)
64
+ stateResult.content[0].text = `${scrollResult}\n\n${stateResult.content[0].text}`
65
+ return stateResult
66
+ }
@@ -0,0 +1,30 @@
1
+ import { searchA11yTree } from '../a11y-tree'
2
+ import { detectPageDialog, detectValidationErrors } from '../utils/dom'
3
+ import { DEFAULT_ERROR_SELECTORS } from '../constants'
4
+ import type { ActionContext } from '../context'
5
+
6
+ export async function handleSearchTree(args: any, ctx: ActionContext) {
7
+ if (!args.query) return ctx.errContent('搜索失败: 缺少 query 参数')
8
+ const blacklist = (window.__webmcpcli_interactiveBlacklist ?? []) as Element[]
9
+ const whitelist = (window.__webmcpcli_interactiveWhitelist ?? []) as Element[]
10
+ const exposedAttributes = (window.__webmcpcli_exposedAttributes ?? []) as string[]
11
+ const result = searchA11yTree(args.query, document.body, blacklist, whitelist, {
12
+ contextLines: args.contextLines,
13
+ maxMatches: args.maxMatches,
14
+ exposedAttributes,
15
+ errorSelectors: (window.__webmcpcli_errorSelectors ?? DEFAULT_ERROR_SELECTORS).join(', '),
16
+ })
17
+
18
+ ctx.setRefMap(result.refMap)
19
+ ctx.stateCache.update(window.location.href, result.yaml)
20
+
21
+ await ctx.pageController.hideMask()
22
+ // 检测页面弹窗/遮罩层,帮助 AI 发现可能遮挡目标的确认弹窗
23
+ const dialogAlert = detectPageDialog()
24
+ // 检测表单校验错误,提醒 AI 优先修复
25
+ const validationErrors = detectValidationErrors()
26
+ const alerts = `${dialogAlert}${validationErrors}`
27
+ return {
28
+ content: [{ type: 'text' as const, text: alerts ? `${alerts}\n${result.text}` : result.text }]
29
+ }
30
+ }
@@ -0,0 +1,34 @@
1
+ import { selectOptionElement } from '@page-agent/page-controller'
2
+ import { dispatchComposedEvents, isInShadowDom, waitForDomSettled } from '../utils/dom'
3
+ import type { ActionContext } from '../context'
4
+
5
+ export async function handleSelect(args: any, ctx: ActionContext) {
6
+ const mode = args.responseMode ?? 'diff'
7
+ if (args.index === undefined || typeof args.text !== 'string') return ctx.errContent('选择结果: 缺少元素索引或文本内容')
8
+ let el = ctx.getRefMap().get(args.index) as HTMLSelectElement | HTMLElement | undefined
9
+ if (!el) return ctx.refreshOnStaleRef('选择', args.index)
10
+ // 若 ref 指向 shadow host,解析其内部真正的 <select>(与 fill 一致)
11
+ let targetSelect: HTMLSelectElement | null = null
12
+ if (el instanceof HTMLSelectElement) {
13
+ targetSelect = el
14
+ } else {
15
+ const innerSelect = el.querySelector('select')
16
+ ?? (el.shadowRoot?.querySelector('select') as HTMLSelectElement | null)
17
+ if (innerSelect) {
18
+ targetSelect = innerSelect
19
+ }
20
+ }
21
+
22
+ if (!targetSelect) {
23
+ return ctx.errContent(`选择结果: 无法选择元素 ${args.index},未找到对应的 <select> 元素`)
24
+ }
25
+
26
+ await selectOptionElement(targetSelect, args.text)
27
+ // shadow DOM 内元素:补发 composed:true 的 change 事件
28
+ if (isInShadowDom(targetSelect)) {
29
+ dispatchComposedEvents(targetSelect, 'change')
30
+ }
31
+ // 等待框架异步插入的校验错误/条件渲染内容稳定后再采集状态
32
+ await waitForDomSettled()
33
+ return ctx.buildBrowserStateResponse(mode)
34
+ }
@@ -0,0 +1,20 @@
1
+ import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill'
2
+ import { setupModelContextBridge } from './bridge'
3
+ import { isBrowser } from '../utils/env'
4
+
5
+ let initialized = false
6
+
7
+ export const initializeBuiltinWebMCP = () => {
8
+ if (isBrowser()) {
9
+ try {
10
+ if (initialized) return
11
+
12
+ initializeWebMCPPolyfill()
13
+ setupModelContextBridge()
14
+
15
+ initialized = true
16
+ } catch (err) {
17
+ console.warn('[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:', err)
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,198 @@
1
+ import { type RefMap } from '../a11y-tree'
2
+
3
+ export const HIGHLIGHT_CONTAINER_ID = 'webmcpcli-highlight-container'
4
+ export const HIGHLIGHT_CONTAINER_STYLE_ID = 'webmcpcli-highlight-container-style'
5
+ const colors = [
6
+ '#FF0000',
7
+ '#00FF00',
8
+ '#0000FF',
9
+ '#FFA500',
10
+ '#800080',
11
+ '#008080',
12
+ '#FF69B4',
13
+ '#4B0082',
14
+ '#FF4500',
15
+ '#2E8B57',
16
+ '#DC143C',
17
+ '#4682B4'
18
+ ]
19
+ // border + label opacity
20
+ const opacity = Math.floor(0.3 * 255)
21
+ .toString(16)
22
+ .padStart(2, '0')
23
+
24
+ const injectStyles = `
25
+ #${HIGHLIGHT_CONTAINER_ID} {
26
+ position: fixed;
27
+ pointer-events: none;
28
+ top: 0;
29
+ left: 0;
30
+ width: 100%;
31
+ height: 100%;
32
+ z-index: 2147483640;
33
+ background-color: transparent;
34
+ }
35
+
36
+ #${HIGHLIGHT_CONTAINER_ID} div {
37
+ position: fixed;
38
+ pointer-events: none;
39
+ background-color: transparent;
40
+ text-align: right;
41
+ box-sizing: border-box;
42
+ border-radius: 4px;
43
+ }
44
+
45
+ #${HIGHLIGHT_CONTAINER_ID} div span {
46
+ display: inline-block;
47
+ color: #fff;
48
+ padding: 0 2px;
49
+ border-radius: 4px;
50
+ }
51
+ `
52
+
53
+ function isElementViewport(element: HTMLElement) {
54
+ const rect = element.getBoundingClientRect()
55
+ return (
56
+ rect.top >= 0 &&
57
+ rect.left >= 0 &&
58
+ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
59
+ rect.right <= (window.innerWidth || document.documentElement.clientWidth)
60
+ )
61
+ }
62
+
63
+ const doHighlight = (refMap: RefMap, parentIframe: HTMLIFrameElement | null = null) => {
64
+ // 1、保证注入脚本
65
+ if (!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)) {
66
+ const style = document.head.appendChild(document.createElement('style'))
67
+ style.id = HIGHLIGHT_CONTAINER_STYLE_ID
68
+ style.textContent = injectStyles
69
+ document.head.appendChild(style)
70
+ }
71
+
72
+ // 2、保证contrainer( container 在 a11y 时已加入黑名单)
73
+ let container = document.getElementById(HIGHLIGHT_CONTAINER_ID)
74
+ if (!container) {
75
+ container = document.createElement('div')
76
+ container.id = HIGHLIGHT_CONTAINER_ID
77
+
78
+ document.body.appendChild(container)
79
+ } else {
80
+ container.innerHTML = ''
81
+ }
82
+
83
+ let iframeOffset = { x: 0, y: 0 }
84
+ if (parentIframe) {
85
+ const iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe offset
86
+ iframeOffset.x = iframeRect.left
87
+ iframeOffset.y = iframeRect.top
88
+ }
89
+ const fragment = document.createDocumentFragment()
90
+ const overlays = []
91
+
92
+ // 3、 遍历 refMap
93
+ for (const [index, el] of refMap.entries()) {
94
+ if (!isElementViewport(el)) continue
95
+
96
+ const color = colors[index % colors.length]
97
+ const textColor = color + opacity
98
+
99
+ const rect = el.getBoundingClientRect()
100
+ if (rect.width === 0 || rect.height === 0) continue
101
+
102
+ const overlay = document.createElement('div')
103
+ overlay.style.border = `2px solid ${textColor}`
104
+
105
+ const top = rect.top + iframeOffset.y
106
+ const left = rect.left + iframeOffset.x
107
+
108
+ overlay.style.top = `${top}px`
109
+ overlay.style.left = `${left}px`
110
+ overlay.style.width = `${rect.width}px`
111
+ overlay.style.height = `${rect.height}px`
112
+
113
+ // 文字
114
+ const text = document.createElement('span')
115
+ text.style.backgroundColor = textColor
116
+ text.style.height = `${rect.height - 4}px`
117
+ text.style.lineHeight = `${rect.height - 4}px`
118
+ text.textContent = index.toString()
119
+ overlay.appendChild(text)
120
+
121
+ fragment.appendChild(overlay)
122
+ overlays.push({ element: overlay, initialRect: rect })
123
+ }
124
+
125
+ container.appendChild(fragment)
126
+ }
127
+
128
+ export const highlight = (refMap: RefMap, parentIframe: HTMLIFrameElement | null = null) => {
129
+ doHighlight(refMap, parentIframe)
130
+
131
+ // 4、监听滚动和resize事件,更新位置
132
+ const updatePositions = () => doHighlight(refMap, parentIframe)
133
+ const throttleFunction = (func: (...args: any[]) => void, delay: number) => {
134
+ let lastCall = 0
135
+ return (...args: any[]) => {
136
+ const now = performance.now()
137
+ if (now - lastCall < delay) return
138
+ lastCall = now
139
+ return func(...args)
140
+ }
141
+ }
142
+
143
+ const throttledUpdatePositions = throttleFunction(updatePositions, 16)
144
+ window.addEventListener('scroll', throttledUpdatePositions, true)
145
+ window.addEventListener('resize', throttledUpdatePositions)
146
+
147
+ const cleanupFn = () => {
148
+ window.removeEventListener('scroll', throttledUpdatePositions, true)
149
+ window.removeEventListener('resize', throttledUpdatePositions)
150
+ }
151
+ const win = window as any
152
+ ;(win._highlightCleanupFunctions = win._highlightCleanupFunctions || []).push(cleanupFn)
153
+ }
154
+
155
+ /** 移除高亮, 可反复调用 */
156
+ export const unhighlight = () => {
157
+ document.getElementById(HIGHLIGHT_CONTAINER_ID)?.remove()
158
+
159
+ const cleanupFunctions = (window as any)._highlightCleanupFunctions || []
160
+ for (const cleanup of cleanupFunctions) {
161
+ if (typeof cleanup === 'function') {
162
+ cleanup()
163
+ }
164
+ }
165
+
166
+ ;(window as any)._highlightCleanupFunctions = []
167
+ }
168
+
169
+ /** 全局监听变化,随时准备移除高亮, 可反复调用 */
170
+ export const globalRemoveListener = () => {
171
+ if ((window as any).__registerGlobalRemoveListener) return
172
+ ;(window as any).__registerGlobalRemoveListener = true
173
+ window.addEventListener('popstate', () => {
174
+ unhighlight()
175
+ })
176
+ window.addEventListener('hashchange', () => {
177
+ unhighlight()
178
+ })
179
+ window.addEventListener('beforeunload', () => {
180
+ unhighlight()
181
+ })
182
+
183
+ const navigation = (window as any).navigation
184
+ if (navigation && typeof navigation.addEventListener === 'function') {
185
+ navigation.addEventListener('navigate', () => {
186
+ unhighlight()
187
+ })
188
+ } else {
189
+ // 定时器
190
+ let currentUrl = window.location.href
191
+ setInterval(() => {
192
+ if (window.location.href !== currentUrl) {
193
+ currentUrl = window.location.href
194
+ unhighlight()
195
+ }
196
+ }, 500)
197
+ }
198
+ }
@@ -0,0 +1,14 @@
1
+ .webmcp-page-agent-wrapper {
2
+ position: fixed;
3
+ inset: 0;
4
+ z-index: 2147483641;
5
+ /* 确保在所有元素之上,除了 panel */
6
+ cursor: wait;
7
+ overflow: hidden;
8
+
9
+ display: none;
10
+ }
11
+
12
+ .webmcp-page-agent-wrapper.visible {
13
+ display: block;
14
+ }