@roll-agent/browser-use-agent 0.7.4 → 0.7.5
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.
- package/SKILL.md +100 -4
- package/dist/index.js +1 -1
- package/dist/tools/zhipin-diagnose-browser-state.d.ts +307 -0
- package/dist/tools/zhipin-scroll-view.d.ts +3 -3
- package/package.json +1 -1
package/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: browser-use-agent
|
|
3
|
-
description: 浏览器操控 Agent
|
|
3
|
+
description: 浏览器操控 Agent。控制浏览器操作招聘平台——读取消息、打开聊天、发送回复、换微信、滚动动态列表、查看推荐列表、打招呼、查看简历,并提供 BOSS直聘 CDP/页面 attach 风控触发点的分阶段诊断工具。
|
|
4
4
|
metadata:
|
|
5
5
|
roll-env-file: references/env.yaml
|
|
6
6
|
---
|
|
@@ -31,8 +31,101 @@ metadata:
|
|
|
31
31
|
## 调试 Tools
|
|
32
32
|
|
|
33
33
|
- `attach_browser_session()` — 调试工具。显式执行一次 `connectOverCDP()`,用于隔离验证“仅 attach”是否会触发站点风控
|
|
34
|
+
- `zhipin_diagnose_browser_state(phase?, targetPageId?, watchMs?, networkEventLimit?)` — BOSS直聘分阶段诊断工具。默认 `phase="native"`,只通过原生 CDP `/json/list` 枚举页面;`phase="browser-attach"` 会执行 Playwright Browser CDP attach 并追加 `watchMs` 的原生 URL 观察窗口,用于捕捉 attach 成功后异步回退;只有显式传更深 `phase` 才会继续执行 Page attach、网络监听、最小 `evaluate()`、检测指纹快照和 storage/cookie 脱敏摘要读取。用于定位“哪个阶段触发 Boss 自动回退/风控”,不用于正常招聘业务流程
|
|
34
35
|
- `zhipin_scroll_view(surface, direction?, steps?, distance?, settleMs?)` — 滚动 BOSS直聘页面内部动态列表容器,用于调试或显式翻页。`surface` 支持 `chat-list`、`chat-history`、`recommend-list`;不传 `direction` 时使用该 surface 的默认方向
|
|
35
36
|
|
|
37
|
+
## BOSS直聘 — CDP/风控诊断流程
|
|
38
|
+
|
|
39
|
+
`zhipin_diagnose_browser_state` 的目标是把黑盒风控触发拆成可观测阶段。它不能替代 `zhipin_read_messages`,也不负责规避检测。
|
|
40
|
+
|
|
41
|
+
触发场景:
|
|
42
|
+
|
|
43
|
+
- 调用 `zhipin_read_messages`、`zhipin_get_username`、`zhipin_open_chat_page` 等 BOSS 工具后,页面自动 `history.goBack()` 或回到上一页
|
|
44
|
+
- 某个账号/某个浏览器 profile 触发,但其它账号或其它浏览器实例不触发
|
|
45
|
+
- 需要对比“仅 CDP 连接”、“页面绑定”、“执行 `evaluate()`”、“读取 storage/cookie”哪个阶段开始异常
|
|
46
|
+
|
|
47
|
+
不要在正常业务路径里默认调用该工具。只有出现上述异常或用户明确要求诊断时,orchestrator 才使用它。
|
|
48
|
+
|
|
49
|
+
阶段模型:
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
低侵入分支:
|
|
53
|
+
native -> native-watch
|
|
54
|
+
|
|
55
|
+
attach / 网络分支:
|
|
56
|
+
native -> browser-attach -> browser-attach-watch -> page-attach -> network-watch
|
|
57
|
+
|
|
58
|
+
evaluate / storage 分支:
|
|
59
|
+
native -> browser-attach -> browser-attach-watch -> page-attach -> page-evaluate -> detector-fingerprint -> storage-summary
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
阶段含义:
|
|
63
|
+
|
|
64
|
+
| `phase` | 动作 | 诊断问题 |
|
|
65
|
+
| --- | --- | --- |
|
|
66
|
+
| `native` | 只调用原生 CDP `/json/list` 枚举页面 | 当前有哪些 BOSS target;最低风险默认阶段 |
|
|
67
|
+
| `native-watch` | 不 attach,只在 `watchMs` 内重复读取原生 target URL/title | 不连接 Playwright 时页面是否自己跳转或回退 |
|
|
68
|
+
| `browser-attach` | 执行 `runtime.getBrowser()`,随后用原生 CDP 在 `watchMs` 内观察 URL/title | 仅建立 Playwright Browser CDP 连接是否触发异步回退 |
|
|
69
|
+
| `page-attach` | 执行 `ctxManager.getPage("zhipin")` | 绑定具体 BOSS 页面/context 是否触发 |
|
|
70
|
+
| `network-watch` | 在 `watchMs` 内监听相关 request/response 和 frame navigation | attach 后是否出现 `device-action-report` / APM / security 请求,或 URL 自动变化 |
|
|
71
|
+
| `page-evaluate` | 最小读取 `location.href`、`document.title`、`visibilityState` | 页面 JS evaluate 是否触发 |
|
|
72
|
+
| `detector-fingerprint` | 读取 `navigator.webdriver`、`window.cdc_*`、`__playwright__binding__` 等检测标志 | attach/evaluate 后是否暴露自动化指纹 |
|
|
73
|
+
| `storage-summary` | 读取 `localStorage`、`sessionStorage`、cookies 摘要 | storage/cookie 读取是否触发 |
|
|
74
|
+
|
|
75
|
+
orchestrator 使用规则:
|
|
76
|
+
|
|
77
|
+
1. 先调用 `zhipin_diagnose_browser_state()` 或 `zhipin_diagnose_browser_state({ phase: "native" })`
|
|
78
|
+
2. 如果 `nativePages` 中只有一个 BOSS 页,可继续递进;如果有多个 BOSS 页,后续必须传 `targetPageId`
|
|
79
|
+
3. 高风险账号先跑 `native-watch`,确认不 attach 时 URL 是否已经变化
|
|
80
|
+
4. 每次只推进一个阶段,并在每次调用后观察页面是否自动回退
|
|
81
|
+
5. 如果 `phase="browser-attach"` 返回 `success=false`,或 `nativeTimeline` 中出现 `phase="browser-attach-watch"` 且 `urlChangedFromPrevious=true`,立即停止;不要继续调用任何 Playwright-backed BOSS 工具,包括 `zhipin_read_messages`、`zhipin_open_chat_page`、`zhipin_open_recommend_page`、`zhipin_send_reply`
|
|
82
|
+
6. 要验证“是否上报”,只能在 `browser-attach` 未触发 URL 变化后继续跑 `page-attach` / `network-watch`;工具会在可行时先挂网络监听再绑定 page
|
|
83
|
+
7. 一旦某个阶段触发回退,停止继续加深,记录该阶段的 `phases`、`nativeTimeline`、`networkEvents`、`navigationEvents`、`warnings`
|
|
84
|
+
8. `storage-summary` 返回的是脱敏摘要;禁止要求或传播 cookie/localStorage/sessionStorage 原始值
|
|
85
|
+
|
|
86
|
+
典型测试序列:
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{ "phase": "browser-attach", "targetPageId": "<nativePages[].pageId>" }
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{ "phase": "page-attach", "targetPageId": "<nativePages[].pageId>" }
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{ "phase": "network-watch", "targetPageId": "<nativePages[].pageId>", "watchMs": 3000 }
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```json
|
|
105
|
+
{ "phase": "page-evaluate", "targetPageId": "<nativePages[].pageId>" }
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```json
|
|
109
|
+
{ "phase": "detector-fingerprint", "targetPageId": "<nativePages[].pageId>" }
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
{ "phase": "storage-summary", "targetPageId": "<nativePages[].pageId>", "watchMs": 3000 }
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
返回结果重点:
|
|
117
|
+
|
|
118
|
+
- `nativePages`:原生 CDP 页面列表,`pageId` 可作为后续 `targetPageId`
|
|
119
|
+
- `targetPage`:本次绑定/诊断的 BOSS 页面
|
|
120
|
+
- `browserAttached` / `pageAttached`:是否已经进入更深 attach 阶段
|
|
121
|
+
- `nativeTimeline`:每个阶段后的原生 target URL/title 快照;`browser-attach-watch` 表示 Browser attach 成功后的后置观察窗口;如果 `urlChangedFromPrevious=true`,优先认为该阶段和自动回退相关
|
|
122
|
+
- `networkEvents`:只记录相关 APM/security 请求,不抓请求体;用于判断是否出现 `device-action-report` / `boss_risk_report` 等上报端点
|
|
123
|
+
- `navigationEvents`:记录 attach 后 frame URL 变化,用于定位自动 `history.back()` / 跳转发生在哪个阶段
|
|
124
|
+
- `detectorFingerprint`:读取自动化相关公开标志,如 `navigator.webdriver`、`window.cdc_*`、Playwright binding 标记
|
|
125
|
+
- `phases`:每个阶段的成功状态、耗时、错误
|
|
126
|
+
- `warnings`:多页面、未找到目标页、目标页不是 BOSS 页面、Browser attach 后 URL 变化等边界提示
|
|
127
|
+
- `storage`:只包含 key、value 长度、JSON 顶层形状、计数器差分、cookie 域/path/过期/HttpOnly/Secure/SameSite,不包含任何 token 或原始值
|
|
128
|
+
|
|
36
129
|
## BOSS直聘 — 聊天 Tools
|
|
37
130
|
|
|
38
131
|
- `zhipin_read_messages(limit?, onlyUnread?, sortBy?, autoScroll?, maxScrolls?)` — 读取消息列表中的候选人,默认返回全部消息;若只看未读,显式传 `onlyUnread=true`。默认 `autoScroll=true`,会向下滚动左侧消息列表内部容器并按 `conversationId` 合并去重;`maxScrolls` 默认 `4`,用于限制动态列表采集成本
|
|
@@ -52,7 +145,8 @@ metadata:
|
|
|
52
145
|
- BOSS 左侧消息列表是虚拟列表,DOM 只保留当前窗口内的若干条记录
|
|
53
146
|
- 点击会话、发送消息、收到新消息后,列表会实时重排
|
|
54
147
|
- 同一个人上一轮是 `index=3`,下一轮可能已经变成 `index=0`
|
|
55
|
-
-
|
|
148
|
+
- `zhipin_open_chat` 不复用 `zhipin_read_messages` 的 DOM 句柄或索引缓存;它会重新读取当前页面上的 `.geek-item`,再按 `conversationId` > `candidateName` > `index` 匹配
|
|
149
|
+
- 因此 `index` 只适合“当前可见 DOM、没有滚动/过滤/重排后的即时兜底”,不适合跨 tool / 跨 agent 透传,也不能作为 `zhipin_read_messages` 到 `zhipin_open_chat` 的稳定点击映射
|
|
56
150
|
|
|
57
151
|
编排要求:
|
|
58
152
|
|
|
@@ -60,8 +154,9 @@ metadata:
|
|
|
60
154
|
2. 一旦返回了 `conversationId` / `candidateId`,后续所有 related tool 都复用这两个值
|
|
61
155
|
3. 调 `zhipin_open_chat` / `zhipin_get_candidate_info` / `zhipin_exchange_wechat` 时,优先传 `conversationId`
|
|
62
156
|
4. 调 `smart-reply-agent.generate_reply(..., target)` 时,`target.conversationId` / `target.candidateId` 必须直接来自 `browser-use-agent` 的真实输出
|
|
63
|
-
5. 禁止把 `zhipin_read_messages` 返回数组里的 `index`
|
|
64
|
-
6. 只有在当前轮次拿不到 `conversationId` 时,才允许临时退回 `candidateName`
|
|
157
|
+
5. 禁止把 `zhipin_read_messages` 返回数组里的 `index` 当作后续 `zhipin_open_chat(index)` 的稳定句柄或会话主键
|
|
158
|
+
6. 只有在当前轮次拿不到 `conversationId` 时,才允许临时退回 `candidateName`
|
|
159
|
+
7. 只有在刚读取当前可见 DOM、且未发生滚动/过滤/列表重排时,才允许临时退回 `index`
|
|
65
160
|
|
|
66
161
|
动态列表要求:
|
|
67
162
|
|
|
@@ -72,6 +167,7 @@ metadata:
|
|
|
72
167
|
|
|
73
168
|
错误做法:
|
|
74
169
|
|
|
170
|
+
- 认为 `zhipin_read_messages` 已经建立了可复用的 `index -> DOM element` 点击映射
|
|
75
171
|
- `zhipin_read_messages` 拿到 `index=2`,几轮之后再调用 `zhipin_open_chat(index=2)`
|
|
76
172
|
- 用 `candidateName` 重新模糊匹配一个会话,再把历史 `candidateId` 假定为同一个人
|
|
77
173
|
- `smart-reply-agent` 的 `target` 不用 `browser-use-agent` 返回的 `conversationId/candidateId`,而是由 orch 自己重建
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineAgent as e,createAgentLogger as t}from"@roll-agent/sdk";import{BrowserRuntimeConfigSchema as n}from"@roll-agent/browser";import{defineTool as a}from"@roll-agent/sdk";import{z as r}from"zod";import{createAgentLogger as o}from"@roll-agent/sdk";import{BrowserRuntime as i,BrowserContextManager as s,SessionStore as c}from"@roll-agent/browser";var l,d,u,m=!1,g=o("browser-use-agent");async function f(e){l||(m=!1,u=new c(e.sessionsDir),l=new i(e),await l.start(),d=new s(l,u))}function p(){if(!l)throw new Error("BrowserRuntime not initialized. Call initRuntime() first.");return l}function h(){if(!d)throw new Error("BrowserContextManager not initialized. Call initRuntime() first.");return d}function w(){if(!u)throw new Error("SessionStore not initialized. Call initRuntime() first.");return u}function y(e){m=e}function b(){return m}async function v(){const e=d,t=l,n=[];if(d=void 0,l=void 0,u=void 0,m=!1,e){g.info("Closing browser contexts...");try{await e.closeAll()}catch(e){n.push(new Error("Failed to close browser contexts",{cause:e})),g.error(`Failed to close browser contexts: ${e instanceof Error?e.stack??e.message:String(e)}`)}}if(t){g.info("Stopping browser process...");try{await t.stop()}catch(e){n.push(new Error("Failed to stop browser runtime",{cause:e})),g.error(`Failed to stop browser runtime: ${e instanceof Error?e.stack??e.message:String(e)}`)}}if(g.info("Browser runtime shutdown complete"),n.length>0)throw new AggregateError(n,"Browser runtime shutdown failed")}var x=r.object({success:r.boolean(),mode:r.string(),connected:r.boolean()}),S=a({name:"attach_browser_session",description:"调试工具:显式执行一次 connectOverCDP(),仅建立 Playwright Browser 连接,不做页面导航或 DOM 操作。",input:r.object({}),output:x,execute:async(e,t)=>{const n=p();return t.logger.info("Attaching Playwright browser session over CDP"),await n.getBrowser(),{success:!0,mode:n.mode,connected:!0}}});import{defineTool as C}from"@roll-agent/sdk";import{z as A}from"zod";import{BrowserStatusSchema as k}from"@roll-agent/browser";import{createHash as I}from"node:crypto";import{z as M}from"zod";var R=["REPLY_AUTHORITY_KEYS_URL","BROWSER_VISUAL_CURSOR","BROWSER_VISUAL_ACTIVITY"],B=/^[0-9a-f]{8}$/,E=M.object({present:M.boolean(),fingerprint:M.string().regex(B).optional()}),P=M.record(E);function $(e,t=process.env){return Object.fromEntries(e.map(e=>{const n=t[e];return"string"==typeof n&&n.length>0?[e,{present:!0,fingerprint:_(n)}]:[e,{present:!1}]}))}function _(e){return I("sha256").update(e).digest("hex").slice(0,8)}var q,N=180,T=60,L=280,z="roll-agent-visual-cursor-root",F="__rollVisualCursorState";function O(e){if(void 0!==e)return"true"===e||"false"!==e&&void 0}function j(){return void 0!==q?q:O(process.env.BROWSER_VISUAL_CURSOR)??!0}async function V(e){return await e.evaluate(e=>{const t=e.getBoundingClientRect();return t.width<=0||t.height<=0?null:{x:Math.round(t.left+t.width/2),y:Math.round(t.top+t.height/2)}})}async function D(e,t){await e.evaluate(e=>{const t="roll-agent-visual-cursor-root",n="roll-agent-visual-cursor-pointer",a="__rollVisualCursorState",r=(()=>{const e=document.getElementById(t);if(e)return e;const a=document.createElement("div");a.id=t,a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.width="0",a.style.height="0",a.style.pointerEvents="none",a.style.zIndex="2147483647";const r=document.createElement("div");return r.id=n,r.setAttribute("aria-hidden","true"),r.style.position="fixed",r.style.left="0",r.style.top="0",r.style.width="24px",r.style.height="24px",r.style.opacity="0",r.style.transform="translate(-9999px, -9999px)",r.style.willChange="transform, opacity",r.style.filter="drop-shadow(0 4px 8px rgba(15, 23, 42, 0.28))",r.innerHTML='<svg viewBox="0 0 24 24" width="24" height="24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 2L18 14L11.4 15.3L14.6 22L10.7 23.5L7.6 16.8L3 21V2Z" fill="#FFFFFF" stroke="#0F172A" stroke-width="1.5" stroke-linejoin="round"/></svg>',a.append(r),document.documentElement.append(a),a})(),o=r.querySelector(`#${n}`);if(!o)return;const i=window[a],s=e.point,c=e.durationMs,l=s.x-2,d=s.y-2;if(i?o.style.transition=`transform ${c}ms cubic-bezier(0.22, 1, 0.36, 1), opacity 120ms ease`:(o.style.transition="opacity 120ms ease",o.style.transform=`translate(${l}px, ${d}px)`),o.style.opacity="1",o.style.transform=`translate(${l}px, ${d}px)`,window[a]={x:s.x,y:s.y},!e.clickPulse)return;const u=document.createElement("div");u.setAttribute("aria-hidden","true"),u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.width="18px",u.style.height="18px",u.style.borderRadius="9999px",u.style.border="2px solid rgba(20, 184, 166, 0.95)",u.style.background="rgba(20, 184, 166, 0.18)",u.style.pointerEvents="none",u.style.opacity="0.9",u.style.transform=`translate(${s.x-9}px, ${s.y-9}px) scale(0.55)`,u.style.transition=`transform ${e.pulseDurationMs}ms ease, opacity ${e.pulseDurationMs}ms ease`,r.append(u),requestAnimationFrame(()=>{u.style.opacity="0",u.style.transform=`translate(${s.x-18}px, ${s.y-18}px) scale(2)`}),globalThis.setTimeout(()=>{u.remove()},e.pulseDurationMs+40)},{point:t.point,durationMs:t.durationMs,clickPulse:t.clickPulse,pulseDurationMs:t.pulseDurationMs})}function U(e){const t=[e],n="function"==typeof e.frames?e.frames():[];return t.push(...n),t}async function H(e){await e.evaluate(({rootId:e,stateKey:t})=>{document.getElementById(e)?.remove(),delete window[t]},{rootId:z,stateKey:F})}async function W(e,t={}){if(e.isClosed())return!1;let n=!1;for(const a of U(e))if(a!==t.preserveTarget)try{await H(a),n=!0}catch{}return n}async function Z(e,t,n={}){if(!j()||e.isClosed())return!1;try{await t.scrollIntoViewIfNeeded();const a=await V(t);if(!a)return!1;const r=n.durationMs??N,o=n.settleMs??T,i=n.target??e;return await W(e,{preserveTarget:i}),await D(n.target??e,{point:a,durationMs:r,clickPulse:!1,pulseDurationMs:L}),await e.waitForTimeout(Math.max(r+o,0)),!0}catch{return!1}}async function G(e,t,n={}){if(!j()||e.isClosed())return!1;try{const a=await V(t);if(!a)return!1;const r=n.pulseDurationMs??L,o=n.target??e;return await W(e,{preserveTarget:o}),await D(o,{point:a,durationMs:0,clickPulse:!0,pulseDurationMs:r}),await e.waitForTimeout(r),!0}catch{return!1}}async function Y(e,t,n){return await Z(e,e.locator(t).first(),n)}async function K(e,t){return await G(e,e.locator(t).first())}var J,X={info:{accent:"#14b8a6",accentSoft:"rgba(20, 184, 166, 0.42)",accentGlow:"rgba(20, 184, 166, 0.18)",capsuleBg:"rgba(15, 23, 42, 0.82)",capsuleBorder:"rgba(45, 212, 191, 0.38)",text:"#F8FAFC",dot:"#2DD4BF"},success:{accent:"#22c55e",accentSoft:"rgba(34, 197, 94, 0.42)",accentGlow:"rgba(34, 197, 94, 0.18)",capsuleBg:"rgba(10, 24, 16, 0.86)",capsuleBorder:"rgba(74, 222, 128, 0.38)",text:"#F0FDF4",dot:"#4ADE80"},error:{accent:"#f59e0b",accentSoft:"rgba(245, 158, 11, 0.42)",accentGlow:"rgba(245, 158, 11, 0.2)",capsuleBg:"rgba(41, 24, 10, 0.88)",capsuleBorder:"rgba(251, 191, 36, 0.4)",text:"#FFFBEB",dot:"#FBBF24"}},Q=14,ee=720;function te(e){if(void 0!==e)return"true"===e||"false"!==e&&void 0}function ne(e="info"){return X[e]}function ae(){return void 0!==J?J:te(process.env.BROWSER_VISUAL_ACTIVITY)??!0}async function re(e,t=Q){return await e.evaluate((e,t)=>{const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const a=globalThis.innerWidth,r=globalThis.innerHeight,o=Math.max(t,0),i=Math.max(n.left-o,0),s=Math.max(n.top-o,0),c=Math.min(n.right+o,a),l=Math.min(n.bottom+o,r);return{x:Math.round(i),y:Math.round(s),width:Math.max(Math.round(c-i),0),height:Math.max(Math.round(l-s),0)}},t)}async function oe(e,t){await e.evaluate(e=>{const t="roll-agent-visual-activity-style",n="roll-agent-visual-activity-root",a="roll-agent-visual-activity-viewport",r="roll-agent-visual-activity-region",o="roll-agent-visual-activity-region-shine",i="roll-agent-visual-activity-capsule",s="roll-agent-visual-activity-dot",c="roll-agent-visual-activity-label",l=(e,t,n,a=!1)=>{a&&(e.style.transition="none",t.style.transition="none",n.style.transition="none"),e.style.opacity="0",e.style.transform="scale(0.995)",t.style.opacity="0",n.style.opacity="0",n.style.transform="translate(-50%, -8px)",t.style.transform="translate(-9999px, -9999px)",a&&requestAnimationFrame(()=>{e.style.transition="opacity 180ms ease, transform 220ms ease",t.style.transition="transform 220ms cubic-bezier(0.22, 1, 0.36, 1), width 220ms ease, height 220ms ease, opacity 180ms ease",n.style.transition="opacity 180ms ease, transform 220ms ease"})};(()=>{if(document.getElementById(t))return;const e=document.createElement("style");e.id=t,e.textContent="\n @keyframes roll-visual-activity-breathe {\n 0%, 100% { transform: translate(-50%, 0px) scale(1); }\n 50% { transform: translate(-50%, -1px) scale(1.01); }\n }\n @keyframes roll-visual-activity-scan {\n 0% { transform: translateX(-140%) skewX(-18deg); }\n 100% { transform: translateX(200%) skewX(-18deg); }\n }\n ",document.head.append(e)})(),(()=>{const e=document.getElementById(n);if(e)return e;const t=document.createElement("div");t.id=n,t.style.position="fixed",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="2147483646";const l=document.createElement("div");l.id=a,l.setAttribute("aria-hidden","true"),l.style.position="fixed",l.style.inset="10px",l.style.borderRadius="20px",l.style.opacity="0",l.style.transform="scale(0.995)",l.style.transition="opacity 180ms ease, transform 220ms ease";const d=document.createElement("div");d.id=r,d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.width="0",d.style.height="0",d.style.borderRadius="18px",d.style.opacity="0",d.style.overflow="hidden",d.style.transform="translate(-9999px, -9999px)",d.style.transition="transform 220ms cubic-bezier(0.22, 1, 0.36, 1), width 220ms ease, height 220ms ease, opacity 180ms ease";const u=document.createElement("div");u.id=o,u.setAttribute("aria-hidden","true"),u.style.position="absolute",u.style.inset="0",u.style.animation="roll-visual-activity-scan 1.6s linear infinite",u.style.opacity="0.9",d.append(u);const m=document.createElement("div");m.id=i,m.setAttribute("aria-hidden","true"),m.style.position="fixed",m.style.left="50%",m.style.top="20px",m.style.display="inline-flex",m.style.alignItems="center",m.style.gap="10px",m.style.padding="10px 14px",m.style.borderRadius="999px",m.style.opacity="0",m.style.transform="translate(-50%, -8px)",m.style.transition="opacity 180ms ease, transform 220ms ease",m.style.backdropFilter="blur(12px)",m.style.animation="roll-visual-activity-breathe 1.8s ease-in-out infinite",m.style.fontSize="13px",m.style.fontWeight="600",m.style.lineHeight="18px",m.style.letterSpacing="0.01em",m.style.whiteSpace="nowrap";const g=document.createElement("div");g.id=s,g.setAttribute("aria-hidden","true"),g.style.width="8px",g.style.height="8px",g.style.borderRadius="999px",g.style.flex="0 0 auto";const f=document.createElement("div");f.id=c,f.setAttribute("aria-live","polite"),m.append(g,f),t.append(l,d,m),document.documentElement.append(t)})();const d=document.getElementById(a),u=document.getElementById(r),m=document.getElementById(o),g=document.getElementById(i),f=document.getElementById(s),p=document.getElementById(c);if(!(d&&u&&m&&g&&f&&p))return;const h=window.__rollVisualActivityTimers??={};if(void 0!==h.hideTimer&&(globalThis.clearTimeout(h.hideTimer),delete h.hideTimer),"clear"===e.mode)return void l(d,u,g,!0);const w=e.theme;if(void 0!==w&&(d.style.border=`1px solid ${w.accentSoft}`,d.style.boxShadow=`inset 0 0 0 1px ${w.accentSoft}, 0 0 52px ${w.accentGlow}`,g.style.border=`1px solid ${w.capsuleBorder}`,g.style.background=w.capsuleBg,g.style.color=w.text,g.style.boxShadow=`0 18px 46px rgba(15, 23, 42, 0.24), 0 0 0 1px ${w.capsuleBorder}`,f.style.background=w.dot,f.style.boxShadow=`0 0 0 5px ${w.accentGlow}`,u.style.border=`1px solid ${w.accentSoft}`,u.style.background=w.accentGlow,u.style.boxShadow=`0 0 0 1px ${w.accentSoft}, 0 16px 42px ${w.accentGlow}`,m.style.background="linear-gradient(115deg, transparent 0%, rgba(255,255,255,0.08) 24%, rgba(255,255,255,0.42) 50%, transparent 76%)"),void 0!==e.label&&(p.textContent=e.label),g.style.opacity="1",g.style.transform="translate(-50%, 0)",d.style.opacity="complete"===e.mode?"0.9":"0.72",d.style.transform="scale(1)","begin"===e.mode)return u.style.opacity="0",void(u.style.transform="translate(-9999px, -9999px)");if(void 0!==e.rect&&(u.style.width=`${e.rect.width}px`,u.style.height=`${e.rect.height}px`,u.style.transform=`translate(${e.rect.x}px, ${e.rect.y}px)`,u.style.opacity="1"),"complete"!==e.mode)return;const y=Math.max(e.lingerMs??0,0);h.hideTimer=globalThis.setTimeout(()=>{l(d,u,g),delete h.hideTimer},y)},t)}async function ie(e,t){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"begin",label:t.label,theme:ne(t.tone??"info")}),!0}catch{return!1}}async function se(e,t,n={}){if(!ae()||e.isClosed())return!1;try{await t.scrollIntoViewIfNeeded();const a=await re(t,n.padding??Q);return!!a&&(await oe(n.target??e,{mode:"highlight",...void 0!==n.label?{label:n.label}:{},theme:ne(n.tone??"info"),rect:a}),!0)}catch{return!1}}async function ce(e,t,n){return await se(e,e.locator(t).first(),n)}async function le(e,t){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"complete",label:t.label,theme:ne("error"===t.status?"error":"success"),lingerMs:t.lingerMs??ee}),!0}catch{return!1}}async function de(e,t={}){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"clear"}),!0}catch{return!1}}var ue=k.extend({replyAuthorityKeysLoaded:A.boolean(),visualCursorEnabled:A.boolean(),visualActivityEnabled:A.boolean(),effectiveEnvSources:P}),me=C({name:"browser_status",description:"查询浏览器运行状态和活跃 session 信息",input:A.object({}),output:ue,execute:async(e,t)=>{t.logger.info("Querying browser status");const n=p(),a=h(),r=w(),o=n.isRunning(),{headless:i,mode:s}=n.getConfig(),c=a.getActivePlatforms(),l=[];for(const e of c){const t=a.getPageCount(e),o=a.getCurrentUrl(e);let i=null,s="unknown";if(n.shouldRestoreSessionSnapshot()){const[t,n]=await Promise.all([r.loadCookies(e),r.loadLocalStorage(e)]);i=void 0!==t&&t.length>0||void 0!==n&&Object.keys(n).length>0,s=i?"snapshot":"none"}else n.usesPersistentProfile()&&(i=null,s="profile");l.push({platform:e,pagesOpen:t,currentUrl:o,hasLoginState:i,loginStateSource:s})}return{running:o,headless:i,mode:s,activeSessions:l,replyAuthorityKeysLoaded:b(),visualCursorEnabled:j(),visualActivityEnabled:ae(),effectiveEnvSources:$(R)}}});import{defineTool as ge}from"@roll-agent/sdk";import{BrowserPageInfoSchema as fe,PlatformSchema as pe}from"@roll-agent/browser";import{z as he}from"zod";import{PLATFORMS as we}from"@roll-agent/browser";var ye={zhipin:"https://www.zhipin.com",yupao:"https://www.yupao.com"};function be(e){return new URL(ye[e]).host}function ve(e,t){try{return new URL(e).host.includes(be(t))}catch{return!1}}function xe(e){return we.find(t=>ve(e,t))}function Se(e,t){const n=xe(t.url)??null;return{pageId:t.targetId,url:t.url,title:t.title,boundPlatform:e.getBoundPlatformForNativePage(t.targetId)??null,detectedPlatform:n,isSelectedForPlatform:e.isNativePageSelected(t.targetId)}}async function Ce(e,t){const n=t.url();return{pageId:e.getPageId(t),url:n,title:await t.title().catch(()=>""),boundPlatform:e.getBoundPlatformForPage(t)??null,detectedPlatform:xe(n)??null,isSelectedForPlatform:e.isSelectedPageForPlatform(t)}}var Ae=he.object({platform:pe.optional().describe("可选:仅返回指定平台相关的页面")}),ke=he.object({pages:he.array(fe)}),Ie=ge({name:"list_pages",description:"通过原生 CDP 列出当前浏览器可见页面及其可选择的 pageId;登录前该值等同于原生 targetId。",input:Ae,output:ke,execute:async(e,t)=>{const n=h();t.logger.info("Listing browser pages");const a=(await n.listNativePages()).map(e=>Se(n,e));return{pages:void 0===e.platform?a:a.filter(t=>t.boundPlatform===e.platform||t.detectedPlatform===e.platform)}}});import{defineTool as Me}from"@roll-agent/sdk";import{BrowserPageInfoSchema as Re}from"@roll-agent/browser";import{z as Be}from"zod";async function Ee(e,t){return e.useTrackedPage(t,e=>ve(e.url(),t))}async function Pe(e,t){return(await e.listNativePages()).find(e=>ve(e.url,t))}async function $e(e,t){const n=await Pe(e,t);if(n)return await e.activateNativePage(n.targetId),{page:n,reusedExistingPage:!0};return{page:await e.openNativePage(ye[t]),reusedExistingPage:!1}}var _e,qe=Be.object({url:Be.string().url().describe("要导航到的目标 URL")}),Ne=Be.object({success:Be.boolean(),page:Re});function Te(){return{getContextManager:h,detectPlatformFromUrl:xe,matchesPlatformHost:ve,findTrackedPlatformPage:Ee,toAttachedPageInfo:Ce,..._e}}async function Le(e,t,n){const a=(await e.listNativePages()).find(e=>t.matchesPlatformHost(e.url,n));if(a)return await e.selectNativePage(n,a.targetId),await e.getPage(n)}async function ze(e,t,n,a){const r=t.detectPlatformFromUrl(n);if(!r){const t=await e.getActivePage();if(!t)throw new Error("No active browser tab detected. Use open_platform or select_page first.");return{page:t}}const o=await t.findTrackedPlatformPage(e,r);if(o)return a.info(`Reusing tracked ${r} page instead of navigating the current unrelated tab`),{page:o,platform:r};const i=await Le(e,t,r);if(i)return a.info(`Reusing native ${r} page instead of navigating the current unrelated tab`),{page:i,platform:r};const s=await e.getActivePage();if(!s)throw new Error("No active browser tab detected. Use open_platform or select_page first.");return a.warn(`No existing ${r} page found; falling back to navigating the current active tab`),{page:s,platform:r}}async function Fe(e,t,n){return await e.selectAttachedPage(n,e.getPageId(t))}async function Oe(e,t){e.url()!==t&&await e.goto(t,{waitUntil:"domcontentloaded"})}var je=Me({name:"navigate_active_tab",description:"导航到指定 URL;若 URL 属于已知平台(Boss/鱼泡),优先复用已打开的平台页,避免把无关 tab 导航成第二个平台页。",input:qe,output:Ne,execute:async(e,t)=>{const n=Te(),a=n.getContextManager();t.logger.info(`Navigating active tab to ${e.url}`);const{page:r,platform:o}=await ze(a,n,e.url,t.logger);await r.bringToFront().catch(()=>{}),await Oe(r,e.url);const i=o??n.detectPlatformFromUrl(r.url()),s=i?await Fe(a,r,i):r;return i?t.logger.info(`Bound navigated page to ${i}`):a.clearBindingForPage(r),{success:!0,page:await n.toAttachedPageInfo(a,s)}}});import{defineTool as Ve}from"@roll-agent/sdk";import{BrowserPageInfoSchema as De,PlatformSchema as Ue}from"@roll-agent/browser";import{z as He}from"zod";var We=He.object({platform:Ue.describe("目标平台:`zhipin` 代表 BOSS直聘,`yupao` 代表鱼泡")}),Ze=He.object({success:He.boolean(),page:De,reusedExistingTab:He.boolean()}),Ge=Ve({name:"open_platform",description:"打开并聚焦招聘平台主页,供用户手动登录或后续执行站内操作。",input:We,output:Ze,execute:async(e,t)=>{const{platform:n}=e,a=p(),r=h();t.logger.info(`Opening platform page for ${n}`);const{page:o,reusedExistingPage:i}=await $e(a,n);return r.rememberNativePageSelection(n,o),{success:!0,page:Se(r,o),reusedExistingTab:i}}});import{defineTool as Ye}from"@roll-agent/sdk";import{BrowserPageInfoSchema as Ke,PlatformSchema as Je}from"@roll-agent/browser";import{z as Xe}from"zod";var Qe=Xe.object({platform:Je.describe("要将该页面绑定为当前活跃页的平台"),pageId:Xe.string().describe("通过 list_pages 返回的 pageId;登录前就是原生 targetId,登录后仍可作为稳定选择句柄")}),et=Xe.object({success:Xe.boolean(),page:Ke}),tt=Ye({name:"select_page",description:"将指定 pageId 绑定为平台当前活跃页,并切换到前台;登录前走原生 CDP target 激活。",input:Qe,output:et,execute:async(e,t)=>{const n=h();t.logger.info(`Selecting page ${e.pageId} for ${e.platform}`);const a=await n.selectNativePage(e.platform,e.pageId);return{success:!0,page:Se(n,a)}}});import{defineTool as nt}from"@roll-agent/sdk";import{z as at}from"zod";import{setTimeout as rt}from"node:timers/promises";async function ot(e,t=300,n=800){const a=Math.floor(Math.random()*(n-t))+t;await e.waitForTimeout(a)}async function it(e){const t=Math.random();let n;n=t<.5?800+1200*Math.random():t<.8?500+300*Math.random():t<.95?2e3+2e3*Math.random():4e3+2e3*Math.random(),await e.waitForTimeout(Math.floor(n))}async function st(e,t){const n=t?.minDistance??50,a=t?.maxDistance??200,r=t?.direction??"both",o=Math.floor(Math.random()*(a-n))+n,i="up"===r?-1:"down"===r||Math.random()>.5?1:-1;await e.evaluate(e=>{window.scrollBy({top:e,behavior:"smooth"})},o*i),await ot(e,200,500)}function ct(e=.3){return Math.random()<e}var lt=".geek-item.selected";async function dt(e){try{await e.waitForSelector(lt,{timeout:5e3})}catch{return null}const t=await e.evaluate(()=>{const e=document.querySelector(".geek-item.selected");if(!e)return null;const t=e.getAttribute("data-id")??e.closest('[role="listitem"]')?.getAttribute("key")??"";return{conversationId:t,candidateId:e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??t,candidateName:e.querySelector('[class*="name"], .nickname, .geek-name, .candidate-name')?.textContent?.trim()??""}});return t&&"string"==typeof t.conversationId&&"string"==typeof t.candidateId&&0!==t.conversationId.length&&0!==t.candidateId.length?t:null}async function ut(e){const t=await e.evaluate(()=>{const e=[".chat-conversation",".conversation-box",".conversation-message"],t=[".base-info-single-detial .name-box",".base-info-content .name-box",".base-info-single-container .name-box",".base-info-content .base-name",".chat-user-name",".name-box",".base-name"];for(const n of e){const e=document.querySelector(n);if(e)for(const n of t){const t=e.querySelector(n)?.textContent?.trim()??"";if(t.length>0)return{candidateName:t}}}return null});return t&&"string"==typeof t.candidateName&&0!==t.candidateName.length?t:null}var mt="https://www.zhipin.com/web/geek/chat",gt=".chat-list-wrap, .geek-item",ft=new Set(["消息"]),pt="data-roll-chat-entry-target",ht="data-roll-chat-item-target";function wt(e){return e.trim().toLocaleLowerCase("zh-CN")}function yt(e,t){const n=wt(e),a=wt(t);return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}function bt(e,t){let n=0;for(const a of e)t.includes(a)&&(n+=1);return n}function vt(e,t){if(void 0!==t.conversationId){const n=e.find(e=>e.conversationId===t.conversationId);if(n)return n}const n=t.candidateName;if(n){const t=wt(n),a=e.filter(e=>e.name.length>0);let r=a.find(e=>wt(e.name)===t);if(r)return r;if(r=a.find(e=>{const n=wt(e.name);return n.includes(t)||t.includes(n)}),r)return r;const o=t.length<=2?1:t.length<=4?.75:.6;if(r=a.find(e=>{const n=wt(e.name);return bt(t,n)>=Math.ceil(Math.min(t.length,n.length)*o)}),r)return r}if(void 0!==t.index)return e[t.index]}function xt(e){return e.includes("/web/geek/chat")||e.includes("/web/chat")}async function St(e,t=1e4){try{return await e.waitForSelector(gt,{timeout:t}),!0}catch{return!1}}async function Ct(e,t){const n=(await e.listAttachedPages()).find(e=>e!==t&&xt(e.url()));if(n)return await e.selectAttachedPage("zhipin",e.getPageId(n))}async function At(e,t){await e.evaluate(e=>{document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)})},t).catch(()=>{})}async function kt(e,t){const n=e.locator(t).first();await n.scrollIntoViewIfNeeded(),await Z(e,n),await n.hover(),await ot(e,200,400),await G(e,n),await n.click()}async function It(e){const t=await e.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},n=t=>e.messageLabels.some(e=>t===e||t.includes(e));document.querySelectorAll(`[${e.markerAttr}]`).forEach(t=>{t.removeAttribute(e.markerAttr)});const a=Array.from(document.querySelectorAll('a[href*="/web/geek/chat"], a[href*="/web/chat"]'));for(const n of a)if(t(n))return n.setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`};const r=Array.from(document.querySelectorAll('a, button, [role="link"], [role="button"], span, div'));for(const a of r){if(n(a.textContent?.trim()??"")&&t(a))return a.setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`}}return{found:!1}},{markerAttr:pt,messageLabels:[...ft]});if(!t.found)return!1;try{return await kt(e,t.selector),!0}finally{await At(e,pt)}}function Mt(e){return e instanceof Error&&/ERR_ABORTED/i.test(e.message)}async function Rt(e){try{return await e.goto(mt,{waitUntil:"domcontentloaded"}),!0}catch(t){return!!Mt(t)&&(!!xt(e.url())||await St(e,2e3))}}async function Bt(e,t){if(!await It(t))return!1;if(await St(t,5e3))return!0;const n=await Ct(e,t);return!!n&&await St(n,5e3)}async function Et(e,t){if(xt(t.url())&&await St(t))return!0;const n=await Ct(e,t);if(n&&await St(n))return!0;if(await Bt(e,t))return!0;if(!await Rt(t))return!1;if(await St(t))return!0;await rt(300);const a=await Ct(e,t);return!!a&&await St(a,5e3)}async function Pt(e){return e.evaluate(()=>Array.from(document.querySelectorAll(".geek-item")).map((e,t)=>{const n=e.getAttribute("data-id")??e.closest('[role="listitem"]')?.getAttribute("key")??"",a=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??n,r=e.querySelector('[class*="name"], .nickname, .geek-name, .candidate-name'),o=r?.textContent?.trim()??"",i=e.querySelector(".source-job")?.textContent?.trim()??"",s=e.querySelector(".badge-count"),c=parseInt(s?.textContent?.trim()??"0",10)||0;return{conversationId:n,candidateId:a,name:o,index:t,position:i,hasUnread:c>0||null!==e.querySelector(".red-dot"),unreadCount:c,lastMessageTime:e.querySelector(".time, .time-shadow")?.textContent?.trim()??"",messagePreview:(e.querySelector(".push-text, .chat-last-msg")?.textContent?.trim()??"").slice(0,100)}}))}async function $t(e,t){const n=await e.evaluate(e=>{document.querySelectorAll(`[${e.markerAttr}]`).forEach(t=>{t.removeAttribute(e.markerAttr)});const t=Array.from(document.querySelectorAll(".geek-item")),n=t.find(t=>(t.getAttribute("data-id")??t.closest('[role="listitem"]')?.getAttribute("key")??"")===e.targetConversationId)??t[e.targetIndex];if(!n)return{found:!1};return(n.querySelector(".chat-item-content")??n).setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`}},{markerAttr:ht,targetConversationId:t.conversationId,targetIndex:t.index});if(!n.found)return!1;try{return await kt(e,n.selector),!0}finally{await At(e,ht)}}async function _t(e,t){if(0===t.conversationId.length&&0===t.name.length)return await ot(e,500,900),!0;try{return await e.waitForFunction(e=>{const t=e=>e.trim().toLocaleLowerCase("zh-CN"),n=document.querySelector(".geek-item.selected"),a=n?.getAttribute("data-id")??n?.closest('[role="listitem"]')?.getAttribute("key")??"",r=0===e.conversationId.length||a===e.conversationId,o=(()=>{const e=[".chat-conversation",".conversation-box",".conversation-message"],t=[".base-info-single-detial .name-box",".base-info-content .name-box",".base-info-single-container .name-box",".base-info-content .base-name",".chat-user-name",".name-box",".base-name"];for(const n of e){const e=document.querySelector(n);if(e)for(const n of t){const t=e.querySelector(n)?.textContent?.trim()??"";if(t.length>0)return t}}return""})(),i=0===e.candidateName.length||((e,n)=>{const a=t(e),r=t(n);return a.length>0&&r.length>0&&(a===r||a.includes(r)||r.includes(a))})(e.candidateName,o);return r&&i},{conversationId:t.conversationId,candidateName:t.name},{timeout:5e3}),!0}catch{return await ot(e,800,1200),!1}}async function qt(e,t,n){if(void 0===n.conversationId&&void 0===n.candidateName&&void 0===n.index)return;if(!await Et(e,t))return{found:!1,conversationId:"",candidateId:"",name:"",index:-1,position:"",hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:"消息列表未加载"};const a=await e.getPage("zhipin"),r=vt(await Pt(a),n);if(!r){return{found:!1,conversationId:"",candidateId:"",name:"",index:-1,position:"",hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:`未找到候选人: ${n.conversationId??n.candidateName??`index ${n.index}`}`}}if(!await $t(a,r))return{...r,found:!1,error:`打开候选人聊天失败: ${r.name||`index ${r.index}`}`};let o=await _t(a,r);if(!o){await $t(a,r)&&(o=await _t(a,r))}if(!o)return{...r,found:!1,error:`打开候选人聊天后,右侧会话未同步切换到 ${r.name||r.conversationId}`};const i=await dt(a);if(!i||i.conversationId!==r.conversationId)return{...r,found:!1,error:`当前选中会话与目标会话不一致: ${r.name||r.conversationId}`};const s=await ut(a);return!(r.name.length>0)||s&&yt(r.name,s.candidateName)?{...r,found:!0}:{...r,found:!1,error:`右侧聊天面板仍未切换到 ${r.name}`}}var Nt=["chat-list","chat-history","recommend-list"],Tt={"chat-list":{surface:"chat-list",defaultDirection:"down",containerSelectors:[".chat-user .user-container",".chat-user .b-scroll-stable",".chat-list-wrap",".chat-user"],itemSelector:".geek-item",highlightSelector:".chat-user .user-container, .chat-list-wrap, .chat-user"},"chat-history":{surface:"chat-history",defaultDirection:"up",containerSelectors:[".conversation-message",".chat-message-list",".conversation-main",".conversation-box"],itemSelector:".chat-message-list > .message-item, .conversation-message .message-item",highlightSelector:".conversation-message, .chat-message-list, .conversation-main"},"recommend-list":{surface:"recommend-list",defaultDirection:"down",containerSelectors:[".recommend-list-wrap",".recommend-list",".candidate-list",".geek-list",".list-wrap",".recommendV2"],itemSelector:".candidate-card-wrap, [data-geek], .geek-item",highlightSelector:".candidate-card-wrap, [data-geek], .geek-item"}};function Lt(e){return Tt[e]}var zt=["target-count","boundary","no-new-items","max-steps"],Ft=4,Ot=700,jt=2,Vt=2;function Dt(e){return e.direction??"down"}function Ut(e){const t=e.steps??Ft;return Math.max(0,Math.floor(t))}function Ht(e){return Math.max(0,Math.floor(e.settleMs??Ot))}function Wt(e,t){return"up"===t?e.atStart:e.atEnd}async function Zt(e,t){return await e.evaluate(e=>{const t=e=>{const t=window.getComputedStyle(e).overflowY;return"hidden"!==t&&"clip"!==t&&e.scrollHeight>e.clientHeight+2},{element:n,label:a,found:r}=(()=>{for(const n of e.containerSelectors){const e=document.querySelector(n);if(e&&t(e))return{element:e,label:n,found:!0}}const n=document.querySelector(e.itemSelector);let a=n?.parentElement??null;for(;a&&a!==document.body&&a!==document.documentElement;){if(t(a))return{element:a,label:"item-ancestor",found:!0};a=a.parentElement}const r=document.scrollingElement??document.documentElement;return{element:r,label:"document",found:r.scrollHeight>r.clientHeight+2}})(),o=Math.max(0,n.scrollTop),i=o<=2,s=o>=Math.max(0,n.scrollHeight-n.clientHeight)-2;return{containerFound:r,containerLabel:a,scrollTop:o,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,itemCount:document.querySelectorAll(e.itemSelector).length,atStart:i,atEnd:s}},t)}async function Gt(e,t,n={}){const a=Dt(n),r=Ut(n),o=Ht(n),i=n.stopOnBoundary??!0,s=await Zt(e,t);let c=s,l=0;for(let s=0;s<r&&(!i||!Wt(c,a));s++)c=await e.evaluate(e=>{const t=e=>{const t=window.getComputedStyle(e).overflowY;return"hidden"!==t&&"clip"!==t&&e.scrollHeight>e.clientHeight+2},{element:n,label:a,found:r}=(()=>{for(const n of e.containerSelectors){const e=document.querySelector(n);if(e&&t(e))return{element:e,label:n,found:!0}}const n=document.querySelector(e.itemSelector);let a=n?.parentElement??null;for(;a&&a!==document.body&&a!==document.documentElement;){if(t(a))return{element:a,label:"item-ancestor",found:!0};a=a.parentElement}const r=document.scrollingElement??document.documentElement;return{element:r,label:"document",found:r.scrollHeight>r.clientHeight+2}})(),o=e.distance??Math.max(120,Math.floor(.85*n.clientHeight)),i="up"===e.direction?-o:o;n.scrollBy({top:i,behavior:"auto"});const s=Math.max(0,n.scrollTop),c=Math.max(0,n.scrollHeight-n.clientHeight);return{containerFound:r,containerLabel:a,scrollTop:s,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,itemCount:document.querySelectorAll(e.itemSelector).length,atStart:s<=2,atEnd:s>=c-2}},{...t,direction:a,distance:n.distance}),l+=1,o>0&&await e.waitForTimeout(o),c=await Zt(e,t);return{success:s.containerFound||c.containerFound,direction:a,stepsRequested:r,stepsCompleted:l,reachedBoundary:Wt(c,a),before:s,after:c}}async function Yt(e,t,n,a,r={}){const o=Dt(r),i=Ut(r),s=Ht(r),c=r.targetCount,l=r.maxNoNewRounds??jt,d=Math.max(0,Math.floor(r.boundaryLoadRetries??Vt)),u=Math.max(0,Math.floor(r.boundarySettleMs??s)),m=await Zt(e,t),g=new Map;let f=0,p=0,h=m,w=0,y="max-steps";const b=async()=>{let e=0;const t=await n();for(const n of t){const t=a(n);void 0!==t&&0!==t.length&&(g.has(t)?f+=1:(g.set(t,n),e+=1))}return e};await b();for(let n=0;n<i;n++){if(void 0!==c&&g.size>=c){y="target-count";break}if(Wt(h,o)){let n=!1;for(let a=0;a<d;a++){u>0&&await e.waitForTimeout(u);const a=await b(),r=await Zt(e,t),i=a>0||r.scrollHeight>h.scrollHeight||r.itemCount>h.itemCount||!Wt(r,o);if(h=r,i){a>0&&(p=0),n=!0;break}}if(!n){y="boundary";break}if(void 0!==c&&g.size>=c){y="target-count";break}}if(p>=l){y="no-new-items";break}const n=await Gt(e,t,{direction:o,steps:1,settleMs:s,...void 0!==r.distance?{distance:r.distance}:{},...void 0!==r.stopOnBoundary?{stopOnBoundary:r.stopOnBoundary}:{}});w+=n.stepsCompleted,h=n.after;p=await b()>0?0:p+1}return void 0!==c&&g.size>=c?y="target-count":w>=i&&(y="max-steps"),{success:m.containerFound||h.containerFound,direction:o,stepsRequested:i,stepsCompleted:w,reachedBoundary:Wt(h,o),before:m,after:h,items:[...g.values()],uniqueCount:g.size,duplicateCount:f,noNewRounds:p,stopReason:y}}function Kt(e){return"function"==typeof e.page}function Jt(e){return Kt(e)?e.page():e}var Xt=class{page;target;constructor(e){this.page=Jt(e),this.target=e}async retarget(e){if(e===this.target)return this.page=Jt(e),this.target=e,!0;const t=this.page,n=this.target;return await de(t,{target:n}),this.page=Jt(e),this.target=e,!0}async begin(e,t="info"){return await ie(this.page,{label:e,tone:t,target:this.target})}async highlightSelector(e,t={}){return await ce(this.page,e,{...t,target:this.target})}async highlightLocator(e,t={}){return await se(this.page,e,{...t,target:this.target})}async succeed(e,t){return await le(this.page,{label:e,...void 0!==t?{lingerMs:t}:{},status:"success",target:this.target})}async fail(e,t){return await le(this.page,{label:e,...void 0!==t?{lingerMs:t}:{},status:"error",target:this.target})}async clear(){return await de(this.page,{target:this.target})}},Qt=at.object({name:at.string(),conversationId:at.string(),candidateId:at.string(),position:at.string(),time:at.string(),preview:at.string(),unreadCount:at.number(),hasUnread:at.boolean(),index:at.number()}),en=at.object({success:at.boolean(),candidates:at.array(Qt),total:at.number(),stats:at.object({withName:at.number(),withUnread:at.number()})});function tn(e){return e.conversationId.length>0?e.conversationId:e.candidateId.length>0?e.candidateId:0!==e.name.length?[e.name,e.position,e.lastMessageTime].join("|"):void 0}var nn=nt({name:"zhipin_read_messages",description:"读取 BOSS直聘消息列表,默认返回全部候选人;若只看未读消息,传 onlyUnread=true",input:at.object({limit:at.number().optional().describe("最多返回条数"),onlyUnread:at.boolean().default(!1).describe("是否只返回有未读消息的候选人;用户说“全部/所有消息列表”时应为 false,说“未读消息”时应为 true"),sortBy:at.enum(["time","unreadCount","name"]).default("time"),autoScroll:at.boolean().default(!0).describe("是否自动向下滚动消息列表并合并采集结果"),maxScrolls:at.number().int().min(0).max(50).default(4).describe("自动滚动的最大步数")}),output:en,execute:async(e,t)=>{const n=e.onlyUnread??!1;t.logger.info(`Reading zhipin messages (limit: ${e.limit??"all"}, onlyUnread: ${n})`);const a=h(),r=await a.getPage("zhipin"),o=new Xt(r),i=n?"正在读取未读消息列表":"正在读取消息列表";await o.begin("正在打开消息列表");try{const s=await Et(a,r),c=await a.getPage("zhipin");if(await o.retarget(c),!s)return await o.fail("未找到消息列表"),{success:!1,candidates:[],total:0,stats:{withName:0,withUnread:0}};await o.begin(i),await o.highlightSelector(".user-list.b-scroll-stable, .chat-user .user-container, .chat-list-wrap",{label:i,padding:8});const l=e.autoScroll??!0,d=e.maxScrolls??4,u=n||void 0===e.limit?{}:{targetCount:e.limit},m=(l&&d>0?(await Yt(c,Lt("chat-list"),()=>Pt(c),tn,{direction:"down",steps:d,...u})).items:await Pt(c)).map(e=>({name:e.name,conversationId:e.conversationId,candidateId:e.candidateId,position:e.position,time:e.lastMessageTime,preview:e.messagePreview,unreadCount:e.unreadCount,hasUnread:e.hasUnread,index:e.index}));let g=n?m.filter(e=>e.hasUnread):m;const f=e.sortBy??"time";"time"===f||("unreadCount"===f?g.sort((e,t)=>t.unreadCount-e.unreadCount):"name"===f&&g.sort((e,t)=>e.name.localeCompare(t.name))),void 0!==e.limit&&(g=g.slice(0,e.limit));const p={withName:m.filter(e=>e.name.length>0).length,withUnread:m.filter(e=>e.hasUnread).length};return await o.succeed(n?`已读取 ${g.length} 条未读消息`:`已读取 ${g.length} 条消息`),t.logger.info(`Found ${g.length} candidates (${p.withUnread} with unread)`),{success:!0,candidates:g,total:m.length,stats:p}}catch(e){throw await o.fail("读取消息列表失败"),e}}});import{defineTool as an}from"@roll-agent/sdk";import{BrowserPageInfoSchema as rn}from"@roll-agent/browser";import{z as on}from"zod";var sn={login:{notLoggedIn:".header-login-btn"},unread:{container:".chat-list-wrap",listItem:'[role="listitem"]',geekItemWrap:".geek-item-wrap",item:".chat-item",unreadBadge:".badge-count",unreadBadgeNew:".badge-count.badge-count-common-less",unreadBadgeSpan:".badge-count span",unreadDot:".red-dot",figure:".figure",badge:".badge",candidateName:".candidate-name",candidateNameAlt:".chat-item-name",candidateNameSelectors:'[class*="name"], .nickname, .geek-name',candidateNameNew:".geek-name",jobTitle:".source-job",lastMessage:".push-text",lastMessageAlt:".chat-last-msg",messageTime:".time, .time-shadow",clickArea:".chat-item-content",unreadCandidates:".geek-item"},chat:{chatContainer:".chat-container",messageList:".message-list",messageItem:".message-item",messageContent:".message-content",messageText:".text-content",userMessage:".message-right",candidateMessage:".message-left",messageTime:".message-time",senderName:".sender-name",inputBox:".chat-input",inputTextarea:"textarea.chat-input",inputEditorId:"#boss-chat-editor-input",sendButton:".btn-send",conversationEditor:".conversation-editor",submitButton:".submit-content .submit",submitButtonActive:".submit-content .submit.active",submitContent:".submit-content",sendButtonAlt:".conversation-editor .submit-content",sendIcon:".submit-content .icon-send",systemMessage:".system-msg"},chatDetails:{candidateInfoContainer:".base-info-single-container, .base-info-content",candidateName:".name-box, .geek-name, .base-name",candidateInfoItem:".geek-info-item, .base-info-item, .base-info-single-detial > div",candidateTag:".geek-tag, .high-light-boss",communicationPosition:".position-name",communicationPositionAlt:".position-item:not(.expect) .value.high-light-boss",candidateExpectContainer:".position-item.expect",candidateExpectValue:".position-item.expect .value.job",candidateExpectSalary:".position-item.expect .high-light-orange",candidatePosition:".geek-position, .position-name",candidatePositionAlt:".position-content .value, .position-item .value",chatMessageContainer:".conversation-message, .message-list",messageItem:".message-item",messageTime:".message-time .time",messageTextSpan:".text span",systemMessage:".item-system",friendMessage:".item-friend",myMessage:".item-myself",resumeMessage:".item-resume",readStatus:".status-read"},exchangeWechat:{exchangeButtonPath:"#container > div:nth-child(1) > div > div.chat-box > div.chat-container > div.chat-conversation > div.conversation-box > div.conversation-operate > div.toolbar-box > div.toolbar-box-right > div.operate-exchange-left > div:nth-child(3) > span.operate-btn",exchangeButtonFallback:".operate-exchange-left .operate-btn",confirmDialog:".exchange-tooltip",confirmButton:".exchange-tooltip .btn-box .boss-btn-primary.boss-btn",confirmButtonPath:"#container > div:nth-child(1) > div > div.chat-box > div.chat-container > div.chat-conversation > div.conversation-box > div.conversation-operate > div.toolbar-box > div.toolbar-box-right > div.operate-exchange-left > div:nth-child(3) > div > div > span.boss-btn-primary.boss-btn",cancelButton:".exchange-tooltip .btn-box .boss-btn-outline.boss-btn",wechatCard:".message-card-top-wrap",wechatCardAlt:'[class*="d-top-text"]'},username:{primary:".nav-item.nav-logout .user-name",fallbacks:["#header > div > div > div.nav-item.nav-logout > div.top-profile-logout.ui-dropmenu.ui-dropmenu-drop-arrow > div.ui-dropmenu-label > div > span.user-name",".ui-dropmenu-label .user-name",".nav-logout .user-name","#header .user-name",".top-profile .user-name",".nav-user .user-name",".user-name",'[class*="user-name"]','[class*="username"]','[data-qa="user-name"]',".header-user-name","#header .label-name"]},nav:{sidebar:".side-wrap.side-wrap-v2",chatLink:'.side-wrap.side-wrap-v2 a[href*="/web/chat/index"]',recommendLink:'.side-wrap.side-wrap-v2 a[href*="/web/geek/recommend"]'},recommend:{iframe:"#recommendFrame",resumeIframe:'iframe[src*="c-resume"]',filterButton:".recommend-filter .filter-label, .filter-label-wrap .filter-label, .filter-label",filterPanel:".filter-panel",candidateItem:"[data-geek], .geek-item",candidateName:".name",candidateBaseInfo:".base-info",workExps:".timeline-wrap.work-exps",expectInfo:".row-flex, .timeline-wrap.expect",salaryWrap:".salary-wrap",tagsWrap:".tags-wrap",greetButton:".btn-greet, .op-btn",resumeCanvas:"div#resume > canvas#resume, canvas#resume",closeResumeBtn:".close-btn, .dialog-close",closeResumeBtnV2:".recommendV2 .close-btn"},candidateProfile:{panel:".candidate-info, .resume-info, .geek-info",name:".candidate-info .name, .geek-info .name",age:".candidate-info .age, .geek-info .age",gender:".candidate-info .gender, .geek-info .gender",experience:".candidate-info .experience, .geek-info .work-exp",education:".candidate-info .education, .geek-info .edu",expectedSalary:".candidate-info .salary, .geek-info .expect-salary",expectedPosition:".candidate-info .position, .geek-info .expect-position",activeTime:".candidate-info .active-time, .geek-info .active"}},cn={chat:"沟通",recommend:"推荐牛人"};function ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function dn(e){for(const t of e)try{if(await t.count()>0&&await t.first().isVisible())return t.first()}catch{}return null}function un(e){return cn[e]}async function mn(e,t){const n=e.locator(sn.nav.sidebar).first(),a=un(t),r=new RegExp(`^${ln(a)}(?:\\s|$)`),o="recommend"===t?[sn.nav.recommendLink]:[sn.nav.chatLink],i=[n.getByRole("link",{name:r}).first(),...o.map(e=>n.locator(e).first()),n.locator(`a:has-text("${a}")`).first(),e.getByRole("link",{name:r}).first()];return await dn(i)}function gn(e){return!!e.url().includes("/web/geek/recommend")||(null!==e.frame("recommendFrame")||e.frames().some(e=>e.url().includes("recommend")))}async function fn(e){if(e.url().includes("/web/chat/index"))return!0;try{const t=e.locator("#container.chat-container-private").first();return await t.count()>0&&await t.isVisible()}catch{return!1}}async function pn(e,t=1e4,n=250){const a=Date.now()+t;for(;Date.now()<a;){if(gn(e))return!0;if(e.isClosed())return!1;await e.waitForTimeout(Math.min(n,Math.max(a-Date.now(),0)))}return gn(e)}async function hn(e,t=1e4,n=250){const a=Date.now()+t;for(;Date.now()<a;){if(await fn(e))return!0;if(e.isClosed())return!1;await e.waitForTimeout(Math.min(n,Math.max(a-Date.now(),0)))}return await fn(e)}var wn,yn=on.object({success:on.boolean(),alreadyOnChat:on.boolean(),usedSidebarClick:on.boolean(),chatReady:on.boolean(),page:rn.optional(),error:on.string().optional()});function bn(){return{getContextManager:h,findZhipinSidebarSectionLink:mn,isZhipinChatSurfaceOpen:fn,waitForZhipinChatSurface:hn,moveVisualCursorToLocator:Z,showVisualClickOnLocator:G,randomDelay:ot,toAttachedPageInfo:Ce,createVisualActivitySession:e=>new Xt(e),...wn}}async function vn(e,t,n){return await t.toAttachedPageInfo(e,n)}async function xn(e,t,n,a,r,o){return await n.fail(r),{success:!1,...o,page:await vn(e,t,a),error:r}}async function Sn(e,t,n,a){await n.scrollIntoViewIfNeeded(),await t.moveVisualCursorToLocator(e,n,{durationMs:110,settleMs:30}),await n.hover(),await t.randomDelay(e,100,180),await t.showVisualClickOnLocator(e,n,{pulseDurationMs:180}),await n.click(),a.info("Clicked Boss sidebar nav: 沟通")}var Cn=an({name:"zhipin_open_chat_page",description:"通过点击 Boss 左侧导航切换回「沟通」页,避免让编排器依赖站内 URL 猜测。",input:on.object({}),output:yn,execute:async(e,t)=>{const n=bn(),a=n.getContextManager();t.logger.info("Opening Boss chat page via sidebar navigation");const r=await a.getPage("zhipin");await r.bringToFront().catch(()=>{});const o=n.createVisualActivitySession(r),i="正在切换到沟通页";if(await o.begin(i),await o.highlightSelector(sn.nav.sidebar,{label:i,padding:10}),await n.isZhipinChatSurfaceOpen(r))return await o.succeed("已在沟通页"),{success:!0,alreadyOnChat:!0,usedSidebarClick:!1,chatReady:!0,page:await vn(a,n,r)};const s=await n.findZhipinSidebarSectionLink(r,"chat");if(!s)return await xn(a,n,o,r,"未找到沟通导航",{alreadyOnChat:!1,usedSidebarClick:!1,chatReady:!1});try{await Sn(r,n,s,t.logger)}catch(e){return await xn(a,n,o,r,e instanceof Error?e.message:"点击沟通导航失败",{alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!1})}return await n.waitForZhipinChatSurface(r)?(await o.succeed("已切换到沟通页"),{success:!0,alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!0,page:await vn(a,n,r)}):await xn(a,n,o,r,"沟通页未就绪",{alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!1})}});import{defineTool as An}from"@roll-agent/sdk";import{z as kn}from"zod";var In=kn.object({success:kn.boolean(),conversationId:kn.string(),candidateId:kn.string(),candidateName:kn.string(),index:kn.number(),hasUnread:kn.boolean(),unreadCount:kn.number(),lastMessageTime:kn.string(),messagePreview:kn.string(),error:kn.string().optional()}),Mn=An({name:"zhipin_open_chat",description:"打开指定候选人的聊天窗口(优先按 conversationId,其次姓名,最后才用索引)",input:kn.object({conversationId:kn.string().optional().describe("会话 ID。若已从 `zhipin_read_messages` 获取,优先传这个,最稳定"),candidateName:kn.string().optional().describe("候选人姓名。若用户说“打开鲁倩的聊天”,这里应提取为“鲁倩”"),index:kn.number().optional().describe("候选人在列表中的索引。仅在缺少 conversationId 时兜底"),preferUnread:kn.boolean().default(!1).describe("优先选择有未读消息的候选人")}),output:In,execute:async(e,t)=>{t.logger.info(`Opening chat: name=${e.candidateName??"N/A"}, index=${e.index??"N/A"}`);const n=h(),a=await n.getPage("zhipin");let r={conversationId:e.conversationId,candidateName:e.candidateName,index:e.index};if(e.preferUnread&&void 0===e.conversationId&&void 0===e.candidateName&&void 0===e.index){if(!await Et(n,a))return{success:!1,conversationId:"",candidateId:"",candidateName:"",index:-1,hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:"消息列表未加载"};const e=await n.getPage("zhipin"),t=(await Pt(e)).find(e=>e.hasUnread);t&&(r={conversationId:t.conversationId,candidateName:t.name,index:t.index})}const o=await qt(n,a,r);return o&&o.found?(t.logger.info(`Opened chat with ${o.name} (index: ${o.index})`),{success:!0,conversationId:o.conversationId,candidateId:o.candidateId,candidateName:o.name,index:o.index,hasUnread:o.hasUnread,unreadCount:o.unreadCount,lastMessageTime:o.lastMessageTime,messagePreview:o.messagePreview}):{success:!1,conversationId:"",candidateId:"",candidateName:e.candidateName??"",index:e.index??-1,hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:o?.error??`未找到候选人: ${e.candidateName??`index ${e.index}`}`}}});import{defineTool as Rn}from"@roll-agent/sdk";import{z as Bn}from"zod";var En="·",Pn=/[--—–]/;function $n(e){return(e??"").trim()}function _n(e){const t=$n(e);if(!t||!Pn.test(t))return;const[n=""]=t.split(Pn);return $n(n)||void 0}function qn(e){const t=$n(e);if(!t)return{expectedLocation:"",expectedPosition:""};const[n="",a=""]=t.split(En).map(e=>$n(e));return{expectedLocation:n,expectedPosition:a}}function Nn(e){const t=$n(e.communicationPosition),{expectedLocation:n,expectedPosition:a}=qn(e.expectedJobText),r=_n(t);return{communicationPosition:t,expectedLocation:n,expectedPosition:a,...void 0!==r?{preferredBrand:r}:{}}}var Tn=Bn.object({index:Bn.number(),sender:Bn.enum(["candidate","recruiter","system"]),messageType:Bn.enum(["text","system","resume","wechat-exchange"]),content:Bn.string(),time:Bn.string()}),Ln=Bn.object({name:Bn.string(),age:Bn.string(),experience:Bn.string(),education:Bn.string(),communicationPosition:Bn.string(),expectedPosition:Bn.string(),expectedLocation:Bn.string(),expectedSalary:Bn.string(),tags:Bn.array(Bn.string())}),zn=Bn.object({success:Bn.boolean(),conversationId:Bn.string(),candidateId:Bn.string(),candidateInfo:Ln,preferredBrand:Bn.string().optional(),chatMessages:Bn.array(Tn),formattedHistory:Bn.array(Bn.string()),stats:Bn.object({totalMessages:Bn.number(),candidateMessages:Bn.number(),recruiterMessages:Bn.number(),systemMessages:Bn.number()}),error:Bn.string().optional()});function Fn(){return{name:"",age:"",experience:"",education:"",communicationPosition:"",expectedPosition:"",expectedLocation:"",expectedSalary:"",tags:[]}}function On(e){return{success:!1,conversationId:"",candidateId:"",candidateInfo:Fn(),chatMessages:[],formattedHistory:[],stats:{totalMessages:0,candidateMessages:0,recruiterMessages:0,systemMessages:0},error:e}}function jn(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var Vn=Rn({name:"zhipin_get_candidate_info",description:"提取候选人资料和完整聊天记录。可指定 conversationId 或 candidateName 自动打开对应聊天;若已从 `zhipin_read_messages` 获取 conversationId,优先传它。",input:Bn.object({conversationId:Bn.string().optional().describe("会话 ID。若已从 `zhipin_read_messages` 获取,优先传这个,最稳定"),candidateName:Bn.string().optional().describe("候选人姓名。若用户说“查看鲁倩的聊天详情”,这里应提取为“鲁倩”"),index:Bn.number().optional().describe("候选人在列表中的索引(可选,仅兜底)"),maxMessages:Bn.number().default(100).describe("最多返回的消息条数")}),output:zn,execute:async(e,t)=>{const n=e.maxMessages??100,a=h(),r=await a.getPage("zhipin"),o=new Xt(r),i=void 0!==e.conversationId||void 0!==e.candidateName||void 0!==e.index?"正在打开目标聊天":"正在准备当前聊天",s="正在提取聊天记录",c=async(e,t)=>(await o.fail(e),On(t));await o.begin(i);try{const i=await qt(a,r,{conversationId:e.conversationId,candidateName:e.candidateName,index:e.index}),l=await a.getPage("zhipin");if(await o.retarget(l),i&&!i.found)return await c("打开聊天失败",i.error??"打开聊天失败");t.logger.info("Extracting candidate info"+(i?` for ${i.name}`:" (current window)")),await o.begin(s),await o.highlightSelector(".chat-conversation, .conversation-box, .conversation-message",{label:s,padding:12});const d=i?.name??e.candidateName??"",u=await ut(l);if(d.length>0&&(!u||!jn(d,u.candidateName)))return await c("聊天面板未同步",`右侧聊天面板未切换到 ${d}`);const m=await dt(l);if(!m)return await c("未识别当前会话","未能提取当前选中聊天的 conversationId/candidateId");if(i&&m.conversationId!==i.conversationId)return await c("当前会话不一致",`当前选中会话与目标会话不一致: ${i.name||i.conversationId}`);if(u&&m.candidateName.length>0&&!jn(m.candidateName,u.candidateName))return await c("左右面板不一致",`左侧选中会话与右侧聊天面板不一致: ${m.candidateName} / ${u.candidateName}`);try{await l.waitForSelector(".chat-message-list .message-item, .conversation-message .message-item",{timeout:8e3})}catch{}const g=await l.evaluate(e=>{const t=document.querySelector(".chat-conversation")??document.querySelector(".conversation-box")??document,n=t.querySelector(".base-info-single-detial, .base-info-content, .base-info-single-container"),a=n?.querySelector(".name-box, .base-name, .chat-user-name, .geek-name")?.textContent?.trim()??"",r=n?n.querySelectorAll(":scope > div"):t.querySelectorAll(".geek-info-item, .base-info-item"),o=[];r.forEach(e=>{const t=e.textContent?.trim();t&&o.push(t)});const i=o.join(" "),s=i.match(/(\d{2,3})岁/),c=s?s[1]+"岁":"",l=i.match(/(\d+年(?:以上)?|应届生|在校生)/),d=l?.[1]??"",u=i.match(/(初中|高中|中专|大专|本科|硕士|博士)/)?.[1]??"";let m="";const g=t.querySelector(".position-name");if(g){const e=g.cloneNode(!0);e.querySelectorAll(".popover-wrap, .tooltip-job").forEach(e=>e.remove()),m=e.textContent?.trim()??""}let f="";const p=t.querySelector(".position-item.expect .value.job");p&&(f=p.textContent?.trim()??"");const h=t.querySelector(".position-item.expect .high-light-orange")?.textContent?.trim()??"",w=[];n&&n.querySelectorAll(".geek-tag, .base-info-item .high-light-boss").forEach(e=>{const t=e.textContent?.trim();t&&!t.includes("更换职位")&&t.length<20&&w.push(t)});const y=t.querySelectorAll(".chat-message-list > .message-item, .conversation-message .message-item"),b=/\d{1,2}:\d{2}(?::\d{2})?|\d{4}-\d{2}-\d{2}/,v=[];let x=0;return y.forEach(t=>{if(x>=e)return;const n=null!==t.querySelector(".item-friend"),a=null!==t.querySelector(".item-myself"),r=null!==t.querySelector(".item-system"),o=null!==t.querySelector(".item-resume"),i=null!==t.querySelector(".message-dialog-center");let s="system",c="text";n?s="candidate":a?s="recruiter":(r||i)&&(s="system",c="system"),o&&(c="resume");const l=t.querySelector(".message-card-top-wrap, [class*='d-top-text']");if(l){const e=l.textContent??"";(e.includes("微信")||e.includes("WeChat"))&&(c="wechat-exchange")}const d=t.querySelector(".message-time .time, .message-time"),u=(d?.textContent??"").match(b),m=u?u[0]:"";let g="";if("wechat-exchange"===c&&l){const e=l.textContent??"",t=e.match(/\b(\d{8,15})\b/),n=e.match(/微信[::号]*\s*([a-zA-Z0-9_-]{5,20})/);g=t?`[微信号: ${t[1]}]`:n?`[微信号: ${n[1]}]`:"[交换微信]"}else if(l){const e=t.querySelector(".message-card-top-title"),n=t.querySelector(".dialog-content, .message-card-top-text");g=(e?.textContent?.trim()??n?.textContent?.trim()??"").trim()}else{const e=t.querySelector(".text span, .text-content, .text");e&&(g=(e.textContent?.trim()??"").replace(b,"").replace("已读","").trim())}(g||"text"!==c)&&(v.push({index:x,sender:s,messageType:c,content:g,time:m}),x++)}),{candidateInfo:{name:a,age:c,experience:d,education:u,communicationPosition:m,expectedJobText:f,expectedSalary:h,tags:w},messages:v}},n),f=Nn({communicationPosition:g.candidateInfo.communicationPosition,expectedJobText:g.candidateInfo.expectedJobText}),p=g.messages.filter(e=>"candidate"===e.sender||"recruiter"===e.sender).map(e=>`${"candidate"===e.sender?"求职者":"我"}: ${e.content}`),h={totalMessages:g.messages.length,candidateMessages:g.messages.filter(e=>"candidate"===e.sender).length,recruiterMessages:g.messages.filter(e=>"recruiter"===e.sender).length,systemMessages:g.messages.filter(e=>"system"===e.sender).length};return await o.succeed(`已提取 ${h.totalMessages} 条聊天记录`),t.logger.info(`Extracted info for ${g.candidateInfo.name}: ${h.totalMessages} messages`),{success:!0,conversationId:m.conversationId,candidateId:m.candidateId,candidateInfo:{name:g.candidateInfo.name,age:g.candidateInfo.age,experience:g.candidateInfo.experience,education:g.candidateInfo.education,communicationPosition:f.communicationPosition,expectedPosition:f.expectedPosition,expectedLocation:f.expectedLocation,expectedSalary:g.candidateInfo.expectedSalary,tags:g.candidateInfo.tags},...void 0!==f.preferredBrand?{preferredBrand:f.preferredBrand}:{},chatMessages:g.messages,formattedHistory:p,stats:h}}catch(e){throw await o.fail("提取聊天记录失败"),e}}});import{defineTool as Dn}from"@roll-agent/sdk";import{z as Un}from"zod";var Hn=30,Wn=new Set(["招聘规范","消息","首页","推荐牛人","看简历","我的客服","面试","招聘数据","账号权益","升级VIP","职位","职位管理","牛人","公司","数据统计","设置","帮助中心","登录","注册","退出登录","退出","BOSS直聘","下载APP","搜索","发布职位"]);function Zn(e){const t=e.trim();return!(0===t.length||t.length>Hn)&&(!Wn.has(t)&&!/登录|注册|退出|下载|帮助|设置|管理/.test(t))}function Gn(e){const t=[],n=/(link|button|menuitem|img|heading)\s+"([^"]+)"/g;let a;for(;null!==(a=n.exec(e));){const e=a[2]?.trim()??"";e.length>0&&t.push({role:a[1]??"",name:e})}return t}function Yn(e){let t=e.priority;return Wn.has(e.text.trim())&&(t+=10),e.text.trim().length>10&&(t+=5),/^[\u4e00-\u9fff]{2,4}$/.test(e.text.trim())&&(t-=.5),void 0!==e.xRatio&&(t-=4*(e.xRatio-.5)),t}function Kn(e){const t=e.filter(e=>Zn(e.text));if(0===t.length)return{found:!1};const n=new Map;for(const e of t){const t=e.text.trim(),a=n.get(t)??new Set;a.add(e.strategy),n.set(t,a)}const a=t.map(e=>{let t=Yn(e);const a=n.get(e.text.trim())?.size??1;return a>1&&(t-=.5*a),{evidence:e,score:t}}).sort((e,t)=>e.score-t.score)[0];return a?{found:!0,username:a.evidence.text.trim(),strategy:a.evidence.strategy,source:a.evidence.source}:{found:!1}}async function Jn(e){const t=[e.getByRole("banner"),e.locator("header").first(),e.getByRole("navigation").first(),e.locator("#header")];for(const e of t)try{if(await e.count()>0&&await e.first().isVisible())return e.first()}catch{}return null}async function Xn(e,t,n,a){const r=[],o=t.viewportSize(),i=o?.width??1280;try{const t=await e.getByRole(n).all();for(const e of t)try{if(!await e.isVisible())continue;const t=(await e.textContent()??"").trim();if(t.length>0&&t.length<=Hn){let o;try{const t=await e.boundingBox();t&&(o=(t.x+t.width/2)/i)}catch{}r.push({text:t,strategy:a,priority:1,source:`role:${n}`,xRatio:o})}}catch{}}catch{}return r}async function Qn(e){const t=[];try{const n=Gn(await e.ariaSnapshot({timeout:3e3}));for(const{role:e,name:a}of n)a.length>0&&a.length<=Hn&&t.push({text:a,strategy:"aria-snapshot",priority:2,source:`aria:${e}:${a}`})}catch{}return t}async function ea(e){const t=[];try{const n=await e.evaluate((e,t)=>{const n=[],a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode.textContent?.trim();e&&e.length>0&&e.length<=t&&n.push(e)}return n},Hn);for(const e of n)t.push({text:e,strategy:"leaf-text",priority:3,source:"leaf-text"})}catch{}return t}async function ta(e){const t=[];try{const n=[sn.username.primary,...sn.username.fallbacks],a=await e.evaluate(e=>e.map(e=>{try{return{selector:e,text:document.querySelector(e)?.textContent?.trim()??""}}catch{return{selector:e,text:""}}}),n);for(const{selector:e,text:n}of a)n.length>0&&n.length<=Hn&&t.push({text:n,strategy:"css-fallback",priority:4,source:e})}catch{}return t}async function na(e){const t=await Jn(e),n=t?(await Promise.all([Xn(t,e,"link","role-link"),Xn(t,e,"button","role-button"),Qn(t)])).flat():[],a=Kn(n);if(a.found){const e=a.username;if(new Set(n.filter(t=>t.text.trim()===e).map(e=>e.strategy)).size>=2)return n}const r=(await Promise.all([t?ea(t):Promise.resolve([]),ta(e)])).flat();return[...n,...r]}async function aa(e,t=na){const n=Kn(await t(e));if(!n.found)throw new Error("未找到用户名,请确认当前页面已登录招聘者账号。");return{platform:"zhipin",username:n.username,strategy:n.strategy,source:n.source}}function ra(e,t){return void 0!==t.accountId?e.accountId===t.accountId:e.username===t.username}import{z as oa}from"zod";var ia="reply-authority-service",sa="browser-use-agent/zhipin_send_reply",ca="zhipin",la=60,da=oa.object({platform:oa.literal(ca),username:oa.string().min(1),accountId:oa.string().min(1).optional()}),ua=oa.object({v:oa.literal(2),iss:oa.literal(ia),kid:oa.string().min(1),jti:oa.string().min(1),iat:oa.number().int(),exp:oa.number().int(),aud:oa.literal(sa),platform:oa.literal(ca),tenantId:oa.string().min(1),conversationId:oa.string().min(1),candidateId:oa.string().min(1),reply:oa.string(),policyVersion:oa.string().min(1),recruiterBinding:da}),ma=oa.object({kid:oa.string().min(1),algorithm:oa.literal("Ed25519"),publicKey:oa.string().min(1),validFrom:oa.string().min(1),validUntil:oa.string().optional()}),ga=oa.object({keys:oa.array(ma)}),fa=new Map;function pa(e){for(const[t,n]of fa)n<e-la&&fa.delete(t)}function ha(e,t=Math.floor(Date.now()/1e3)){return pa(t),fa.has(e)}function wa(e,t,n=Math.floor(Date.now()/1e3)){pa(n),fa.set(e,t)}import{createPublicKey as ya,verify as ba}from"node:crypto";var va=new Map,xa=null;function Sa(){const e=process.env.REPLY_AUTHORITY_KEYS_URL?.trim();if(!e)throw new Error("REPLY_AUTHORITY_KEYS_URL 未配置,browser-use-agent 无法拉取 Reply Authority 公钥。");return e}function Ca(e){return va=new Map(e.map(e=>[e.kid,e]))}async function Aa(){if(xa)return xa;xa=(async()=>{const e=await fetch(Sa()),t=await e.json();if(!e.ok)throw new Error(`Reply Authority 公钥拉取失败 (${e.status})`);return Ca(ga.parse(t).keys)})();try{return await xa}finally{xa=null}}async function ka(){await Aa()}async function Ia(e){const t=va.get(e);if(t)return t;const n=(await Aa()).get(e);if(!n)throw new Error(`Unknown key ID: ${e}`);return n}function Ma(e){if("object"==typeof e&&null!==e&&"v"in e&&"number"==typeof e.v&&2!==e.v)throw new Error("unexpected envelope version")}function Ra(e){const t=e.split("."),n=t[0],a=t[1];if(2!==t.length||void 0===n||void 0===a||0===n.length||0===a.length)throw new Error("Invalid signed envelope format");let r,o="";try{o=Buffer.from(n,"base64url").toString("utf-8")}catch{throw new Error("Invalid signed envelope format")}try{r=JSON.parse(o)}catch{throw new Error("Envelope payload schema validation failed")}Ma(r);const i=ua.safeParse(r);if(!i.success)throw new Error("Envelope payload schema validation failed");return{payload:i.data,payloadJson:o,signatureBase64:a}}function Ba(e,t){if(e.exp<=e.iat)throw new Error("Envelope expiry must be after issue time");if(e.exp<t-la)throw new Error("Envelope expired");if(e.iat>t+la)throw new Error("Envelope issued in the future")}async function Ea(e,t=Math.floor(Date.now()/1e3)){const n=Ra(e),a=await Ia(n.payload.kid),r=ya({key:Buffer.from(a.publicKey,"base64url"),format:"der",type:"spki"});if(!ba(null,Buffer.from(n.payloadJson,"utf-8"),r,Buffer.from(n.signatureBase64,"base64url")))throw new Error("Signature verification failed");return Ba(n.payload,t),n.payload}var Pa=Un.object({success:Un.boolean(),sentMessage:Un.string(),error:Un.string().optional()});function $a(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var _a=Dn({name:"zhipin_send_reply",description:"发送消息。只接受由 Reply Authority Service 签发的 signedEnvelope;可指定 candidateName 自动打开对应聊天后发送,或不传则发送到当前选中的聊天窗口。",input:Un.object({signedEnvelope:Un.string().describe("Reply Authority Service 返回的紧凑签名信封"),candidateName:Un.string().optional().describe("候选人姓名。若用户说“回复鲁倩”,这里应提取为“鲁倩”"),index:Un.number().optional().describe("候选人在列表中的索引(可选)")}),output:Pa,execute:async(e,t)=>{let n="";if(!b()){const e="Reply Authority 公钥尚未成功预加载,当前无法发送签名回复。请检查启动日志、`REPLY_AUTHORITY_KEYS_URL` 配置,以及 `browser_status.replyAuthorityKeysLoaded`。";return t.logger.error(e),{success:!1,sentMessage:n,error:e}}const a=h(),r=await a.getPage("zhipin");let o=r;try{const i=await Ea(e.signedEnvelope);if(n=i.reply,ha(i.jti))return{success:!1,sentMessage:n,error:"token 已消费,禁止重放"};const s=await qt(a,r,{conversationId:i.conversationId,candidateName:e.candidateName,index:e.index});if(s&&!s.found)return{success:!1,sentMessage:n,error:s.error};if(!s){if(!await Et(a,r))return{success:!1,sentMessage:n,error:"消息列表未加载"}}o=await a.getPage("zhipin");const c=await ut(o),l=await dt(o);if(!l)return{success:!1,sentMessage:n,error:"未能提取当前聊天的 conversationId/candidateId"};if(c&&l.candidateName.length>0&&!$a(l.candidateName,c.candidateName))return{success:!1,sentMessage:n,error:`左侧选中会话与右侧聊天面板不一致: ${l.candidateName} / ${c.candidateName}`};if(l.conversationId!==i.conversationId||l.candidateId!==i.candidateId)return{success:!1,sentMessage:n,error:"发送目标与签名不匹配"};const d=await aa(o);if(!ra(d,i.recruiterBinding))return{success:!1,sentMessage:n,error:`recruiter 绑定不匹配:当前账号 ${d.username} 与签发时 ${i.recruiterBinding.username} 不一致`};t.logger.info(`Sending message (${n.length} chars) to ${l.candidateName||l.candidateId}`);const u="#boss-chat-editor-input, textarea.chat-input, .chat-input";await o.waitForSelector(u,{timeout:5e3});const m=o.locator(u).first();await Z(o,m);await o.evaluate(e=>{const t=document.querySelector(e);return"true"===t?.getAttribute("contenteditable")},u)?(await m.focus(),await o.evaluate(e=>{const t=document.querySelector(e.sel);t&&(t.innerHTML=e.msg.split("\n").map(e=>`<p>${e}</p>`).join(""))},{sel:u,msg:n}),await m.dispatchEvent("input",{bubbles:!0})):await o.fill(u,n),await ot(o,200,500);const g=await o.evaluate(()=>{document.querySelectorAll("[data-roll-send-btn]").forEach(e=>{e.removeAttribute("data-roll-send-btn")});const e=[".submit-content .submit.active",".submit-content .submit",".submit-content",".btn-send"];for(const t of e){const e=document.querySelector(t);if(e&&e.offsetWidth>0)return{found:!0,selector:t}}const t=Array.from(document.querySelectorAll("span"));for(const e of t)if("发送"===e.textContent?.trim()&&e.offsetWidth>0)return e.setAttribute("data-roll-send-btn","true"),{found:!0,selector:'[data-roll-send-btn="true"]'};return{found:!1}});if(!g.found)return{success:!1,sentMessage:n,error:"未找到发送按钮"};const f=o.locator(g.selector).first();return await f.scrollIntoViewIfNeeded(),await Z(o,f),await f.hover(),await it(o),await G(o,f),await f.click(),await ot(o,500,1200),wa(i.jti,i.exp),t.logger.info("Message sent successfully"),{success:!0,sentMessage:n}}catch(e){return{success:!1,sentMessage:n,error:e instanceof Error?e.message:String(e)}}finally{await o.evaluate(()=>{document.querySelectorAll("[data-roll-send-btn]").forEach(e=>{e.removeAttribute("data-roll-send-btn")})}).catch(()=>{})}}});import{defineTool as qa}from"@roll-agent/sdk";import{z as Na}from"zod";var Ta=Na.object({success:Na.boolean(),exchanged:Na.boolean(),wechatNumber:Na.string().optional(),error:Na.string().optional()}),La="data-roll-wechat-btn",za="data-roll-confirm-btn";function Fa(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var Oa=qa({name:"zhipin_exchange_wechat",description:'换微信。可指定 candidateName 自动打开对应聊天后执行,或不传则在当前窗口执行;例如"和鲁倩换微信"应提取 candidateName=鲁倩。',input:Na.object({conversationId:Na.string().optional().describe("会话 ID。若已从消息列表拿到,优先传这个"),candidateName:Na.string().optional().describe('候选人姓名。若用户说"和鲁倩换微信",这里应提取为"鲁倩"'),index:Na.number().optional().describe("候选人在列表中的索引(可选)")}),output:Ta,execute:async(e,t)=>{const n=h(),a=await n.getPage("zhipin"),r=await qt(n,a,{conversationId:e.conversationId,candidateName:e.candidateName,index:e.index});if(r&&!r.found)return{success:!1,exchanged:!1,error:r.error};t.logger.info("Starting WeChat exchange"+(r?` with ${r.name}`:""));const o=await n.getPage("zhipin");try{const e=await dt(o);if(!e)return{success:!1,exchanged:!1,error:"未选中聊天联系人,无法点击当前聊天输入区的「换微信」按钮"};const n=await ut(o);if(n&&e.candidateName.length>0&&!Fa(e.candidateName,n.candidateName))return{success:!1,exchanged:!1,error:`左侧选中会话与右侧聊天面板不一致: ${e.candidateName} / ${n.candidateName}`};if(!(await o.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},n=e=>e.replace(/\s+/g,"").trim();document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)});const a=[".chat-conversation .conversation-operate .operate-exchange-left span.operate-btn",".chat-conversation .conversation-operate span.operate-btn",".conversation-box .conversation-operate .operate-exchange-left span.operate-btn",".conversation-box .conversation-operate span.operate-btn",".conversation-operate .operate-exchange-left span.operate-btn",".conversation-operate .operate-exchange-left span"];for(const r of a){const a=Array.from(document.querySelectorAll(r));for(const r of a){const a=n(r.textContent??"");if("换微信"===a&&t(r))return r.setAttribute(e,"true"),{found:!0,text:a}}}return{found:!1}},La)).found)return{success:!1,exchanged:!1,error:"未找到当前聊天输入区的「换微信」按钮"};await ot(o,200,400),await Y(o,`[${La}="true"]`),await K(o,`[${La}="true"]`),await o.click(`[${La}="true"]`),await o.evaluate(()=>{document.querySelector("[data-roll-wechat-btn]")?.removeAttribute("data-roll-wechat-btn")}),await ot(o,400,800);let a=!1;for(let e=0;e<8;e++){if(await o.evaluate(()=>{const e=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},t=document.querySelector(".exchange-tooltip");if(t&&e(t))return!0;const n=document.querySelectorAll("div, section, aside");for(const t of Array.from(n)){if((t.textContent??"").includes("交换微信")&&t.querySelector(".boss-btn-primary, .boss-btn")&&e(t))return!0}return!1})){a=!0;break}await ot(o,400,800)}if(!a)return{success:!1,exchanged:!1,error:"确认对话框未弹出"};await it(o);if(!(await o.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0};document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)});const n=document.querySelector(".exchange-tooltip");if(n){const a=[".btn-box .boss-btn-primary.boss-btn",".btn-box span.boss-btn-primary","span.boss-btn-primary",".boss-btn-primary"];for(const r of a){const a=n.querySelector(r);if(a&&t(a))return a.setAttribute(e,"true"),{found:!0,text:a.textContent?.trim()??""}}}const a=document.querySelectorAll("div, section, aside");for(const n of Array.from(a)){if(!(n.textContent??"").includes("交换微信"))continue;const a=n.querySelectorAll("span.boss-btn-primary, button.boss-btn-primary, span.boss-btn, button.boss-btn");for(const n of Array.from(a)){const a=n.textContent?.trim()??"";if("确定"===a&&t(n))return n.setAttribute(e,"true"),{found:!0,text:a}}}return{found:!1}},za)).found)return{success:!1,exchanged:!1,error:"未找到确认按钮"};await ot(o,200,400),await Y(o,`[${za}="true"]`),await K(o,`[${za}="true"]`),await o.click(`[${za}="true"]`),await o.evaluate(()=>{document.querySelector("[data-roll-confirm-btn]")?.removeAttribute("data-roll-confirm-btn")}),await ot(o,1500,2500);const r=await o.evaluate(()=>{const e=[".message-card-top-wrap",'[class*="d-top-text"]',".message-card-top-title"];for(const t of e){const e=Array.from(document.querySelectorAll(t));for(let t=e.length-1;t>=0;t--){const n=e[t]?.textContent??"",a=n.match(/\b(\d{8,15})\b/);if(a)return a[1];const r=n.match(/微信[::号]*\s*([a-zA-Z0-9_-]{5,20})/);if(r)return r[1];const o=n.match(/\b([a-zA-Z][a-zA-Z0-9_-]{5,19})\b/);if(o&&!["微信","WeChat"].includes(o[1]))return o[1]}}const t=Array.from(document.querySelectorAll(".message-item"));for(let e=t.length-1;e>=0;e--){const n=t[e]?.querySelector('.message-card-top-wrap, [class*="d-top-text"]');if(n){const e=(n.textContent??"").match(/\b(\d{8,15})\b/);if(e)return e[1]}}return null});return t.logger.info("WeChat exchanged"+(r?`, number: ${r}`:"")),{success:!0,exchanged:!0,...null!==r?{wechatNumber:r}:{}}}catch(e){return{success:!1,exchanged:!1,error:e instanceof Error?e.message:String(e)}}finally{await o.evaluate(e=>{for(const t of e)document.querySelectorAll(`[${t}]`).forEach(e=>{e.removeAttribute(t)})},[La,za]).catch(()=>{})}}});import{defineTool as ja}from"@roll-agent/sdk";import{z as Va}from"zod";var Da,Ua=Va.object({success:Va.boolean(),username:Va.string(),usedSelector:Va.string().optional(),usedStrategy:Va.string().optional(),source:Va.string().optional(),error:Va.string().optional()});function Ha(){return{getContextManager:h,findHeaderScope:Jn,getCurrentZhipinRecruiterIdentity:aa,createVisualActivitySession:e=>new Xt(e),...Da}}var Wa=ja({name:"zhipin_get_username",description:"获取当前登录的招聘者用户名",input:Va.object({}),output:Ua,execute:async(e,t)=>{t.logger.info("Getting zhipin username");const n=Ha();let a;try{const e=n.getContextManager(),r=await e.getPage("zhipin");a=n.createVisualActivitySession(r),await r.bringToFront().catch(()=>{}),await a.begin("正在识别登录账号");const o=await n.findHeaderScope(r);o&&await a.highlightLocator(o,{label:"正在识别登录账号",padding:10});const i=await n.getCurrentZhipinRecruiterIdentity(r);return await a.succeed(`已识别账号:${i.username}`),t.logger.info(`Username: ${i.username} (strategy: ${i.strategy}, source: ${i.source})`),{success:!0,username:i.username,usedSelector:"css-fallback"===i.strategy?i.source:void 0,usedStrategy:i.strategy,source:i.source}}catch(e){return await(a?.fail("获取用户名失败")),{success:!1,username:"",error:e instanceof Error?`获取用户名失败:${e.message}`:"获取用户名失败"}}}});import{defineTool as Za}from"@roll-agent/sdk";import{z as Ga}from"zod";var Ya=".candidate-card-wrap",Ka="[data-geek], .geek-item",Ja=`${Ya}, ${Ka}`;function Xa(e){return e.evaluate(e=>document.querySelectorAll(e.primarySelector).length>0?e.primarySelector:e.fallbackSelector,{primarySelector:Ya,fallbackSelector:Ka})}function Qa(e){return e.frame("recommendFrame")??e.frames().find(e=>e.url().includes("recommend"))??e}async function er(e,t=1e4){try{return await e.waitForSelector(Ja,{timeout:t}),!0}catch{return!1}}async function tr(e,t){const n=await Xa(e),a=e.locator(n);if(await a.count()<=t)return{found:!1,cardSelector:n,candidateId:"",name:"",hasGreetButton:!1,error:"索引超出范围"};const r=a.nth(t),o=await r.evaluate(e=>{const t=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??"",n=e.querySelector(".name")?.textContent?.trim()??"",a=e.querySelector("button.btn.btn-greet");return{candidateId:t,name:n,hasGreetButton:null!==a&&a.offsetWidth>0}});return{found:!0,cardSelector:n,candidateId:o.candidateId,name:o.name,hasGreetButton:o.hasGreetButton}}var nr=Ga.object({containerFound:Ga.boolean(),containerLabel:Ga.string(),scrollTop:Ga.number(),scrollHeight:Ga.number(),clientHeight:Ga.number(),itemCount:Ga.number(),atStart:Ga.boolean(),atEnd:Ga.boolean()}),ar=Ga.object({success:Ga.boolean(),surface:Ga.enum(Nt),direction:Ga.enum(["up","down"]),stepsRequested:Ga.number(),stepsCompleted:Ga.number(),reachedBoundary:Ga.boolean(),before:nr,after:nr,error:Ga.string().optional()});async function rr(e){const t=h(),n=await t.getPage("zhipin");if("chat-list"===e){const e=await Et(t,n),a=await t.getPage("zhipin");return{target:a,session:new Xt(a),ready:e}}if("recommend-list"===e){const e=Qa(n),t=await er(e);return{target:e,session:new Xt(e),ready:t}}try{const t=Lt(e);return await n.waitForSelector(t.itemSelector,{timeout:3e3}),{target:n,session:new Xt(n),ready:!0}}catch{return{target:n,session:new Xt(n),ready:!1}}}var or=Za({name:"zhipin_scroll_view",description:"滚动 BOSS直聘页面内部动态列表容器。用于调试或显式翻页,支持 chat-list、chat-history、recommend-list。",input:Ga.object({surface:Ga.enum(Nt).describe("要滚动的页面区域"),direction:Ga.enum(["up","down"]).optional().describe("滚动方向;不传则使用该区域默认方向"),steps:Ga.number().int().min(1).max(20).default(1).describe("滚动步数"),distance:Ga.number().int().positive().optional().describe("每步滚动像素;不传则按容器高度估算"),settleMs:Ga.number().int().min(0).max(5e3).default(700).describe("每步后等待 DOM 更新的毫秒数")}),output:ar,execute:async(e,t)=>{const n=Lt(e.surface),a=e.direction??n.defaultDirection,r=e.steps??1,o=e.settleMs??700,{target:i,session:s,ready:c}=await rr(e.surface),l=`正在滚动 ${e.surface}`;if(await s.begin(l),await s.highlightSelector(n.highlightSelector,{label:l,padding:8}),!c){await s.fail("列表未加载");const t={containerFound:!1,containerLabel:"",scrollTop:0,scrollHeight:0,clientHeight:0,itemCount:0,atStart:!0,atEnd:!0};return{success:!1,surface:e.surface,direction:a,stepsRequested:r,stepsCompleted:0,reachedBoundary:!0,before:t,after:t,error:"列表未加载"}}try{const c=await Gt(i,n,{direction:a,steps:r,settleMs:o,...void 0!==e.distance?{distance:e.distance}:{}});return await s.succeed(`已滚动 ${c.stepsCompleted}/${c.stepsRequested} 步`),t.logger.info(`Scrolled ${e.surface}: ${c.stepsCompleted}/${c.stepsRequested}, items ${c.before.itemCount} -> ${c.after.itemCount}`),{success:c.success,surface:e.surface,direction:c.direction,stepsRequested:c.stepsRequested,stepsCompleted:c.stepsCompleted,reachedBoundary:c.reachedBoundary,before:c.before,after:c.after}}catch(e){throw await s.fail("滚动失败"),e}}});import{defineTool as ir}from"@roll-agent/sdk";import{z as sr}from"zod";var cr=["不限","男","女"],lr=["不限","刚刚活跃","今日活跃","3日内活跃","本周活跃","本月活跃"],dr=["applied","recommend_not_ready","filter_not_found","requires_vip","age_not_applied","submit_failed","error"],ur=16,mr=50,gr=650,fr=10,pr=.015,hr=["data-roll-recommend-filter-button","data-roll-recommend-filter-option","data-roll-recommend-filter-submit","data-roll-recommend-filter-age-track","data-roll-recommend-filter-age-min-handle","data-roll-recommend-filter-age-max-handle"],wr="active|selected|checked|current|choose|chosen",yr="button, a, label, li, span, div, [role='button'], [role='radio']";async function br(e,t,n,a){a&&(await a.moveToLocator(e,n,{durationMs:100,settleMs:25,target:t}),await a.showClickOnLocator(e,n,{pulseDurationMs:170,target:t}))}function vr(e,t,n={}){return{status:t,requested:e,...void 0!==n.applied?{applied:n.applied}:{},...void 0!==n.filterButtonText?{filterButtonText:n.filterButtonText}:{},...void 0!==n.error?{error:n.error}:{}}}async function xr(e,t=1e4){try{return await e.waitForSelector(`${sn.recommend.filterButton}, .candidate-card-wrap, ${sn.recommend.candidateItem}`,{timeout:t}),!0}catch{return!1}}async function Sr(e){try{const t=await e.locator(sn.recommend.filterButton).first().textContent({timeout:1e3});return t?.replace(/\s+/g," ").trim()}catch{return}}async function Cr(e){return await e.evaluate(()=>{const e=e=>(e??"").replace(/\s+/g," ").trim(),t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},n=n=>{const a=Array.from(n.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>t(e));for(const t of a){const n=e(t.textContent);if(/^(取消|不应用|否|关闭|稍后)$/.test(n))return t.click(),!0}return!1},a=Array.from(document.body.querySelectorAll("div, section, aside")).filter(e=>t(e)).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return n.width*n.height-a.width*a.height});for(const t of a){const a=e(t.textContent);if(a.includes("是否应用上次")||a.includes("上次的筛选条件"))return n(t)}return!1})}async function Ar(e,t,n){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=(e,t)=>{let n=e;for(;n&&n!==t.parentElement;){const e=n.tagName.toLowerCase(),t=n.getAttribute("role")??"";if("button"===e||"a"===e||"label"===e||"li"===e||"button"===t||"radio"===t)return n;n=n.parentElement}return e};document.querySelectorAll(`[${e.markerAttribute}]`).forEach(t=>t.removeAttribute(e.markerAttribute));const o=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!o)return!1;const i=Array.from(o.querySelectorAll("div, li, dl, dd, section, ul")).filter(a=>{const r=t(a.textContent);return n(a)&&r.includes(e.rowLabel)&&r.includes(e.optionLabel)}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length});for(const o of i){const i=Array.from(o.querySelectorAll(e.clickableOptionSelector)).filter(e=>n(e)).filter(n=>t(n.textContent)===e.optionLabel).sort((e,t)=>a(e)-a(t))[0];if(i)return r(i,o).setAttribute(e.markerAttribute,"1"),!0}return!1},{panelSelector:sn.recommend.filterPanel,rowLabel:t,optionLabel:n,markerAttribute:"data-roll-recommend-filter-option",clickableOptionSelector:yr})}async function kr(e,t,n,a,r){if(!await Ar(e,n,a))return!1;try{const n=e.locator('[data-roll-recommend-filter-option="1"]').first();return await br(t,e,n,r),await n.click({timeout:2e3}),await e.waitForTimeout(120),!0}catch{return!1}}async function Ir(e){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=e=>"string"==typeof e.className?e.className:"",o=e=>{const t=r(e),n=e.getAttribute("role")??"";return/slider|range|track|bar/i.test(t)||"slider"===n},i=e=>{const t=e.getBoundingClientRect(),n=r(e);return"slider"===(e.getAttribute("role")??"")||/handle|handler|button|thumb|slider-btn|dot|point|circle|knob/i.test(n)&&t.width<=80&&t.height<=80};for(const t of e.markerAttributes)document.querySelectorAll(`[${t}]`).forEach(e=>e.removeAttribute(t));const s=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!s)return{ok:!1,error:"未找到筛选面板"};const c=Array.from(s.querySelectorAll("div, li, section, dl, dd")).filter(e=>{const a=t(e.textContent);return n(e)&&a.includes("年龄")&&Array.from(e.querySelectorAll("*")).some(e=>o(e)||i(e))}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length})[0];if(!c)return{ok:!1,error:"未找到年龄滑块"};const l=Array.from(c.querySelectorAll(".vue-slider-dot")).filter(e=>n(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),d=Array.from(c.querySelectorAll("*")).filter(e=>n(e)&&i(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),u=l.length>=2?l:d;if(u.length<2)return{ok:!1,error:"未找到年龄滑块双手柄"};const m=u[0],g=u[u.length-1];if(!m||!g)return{ok:!1,error:"未找到年龄滑块双手柄"};const f=m.getBoundingClientRect(),p=g.getBoundingClientRect(),h=Math.max(40,p.left-f.left),w=Array.from(c.querySelectorAll(".vue-slider-rail, .vue-slider")).filter(e=>{if(!n(e))return!1;const t=e.getBoundingClientRect();return t.width>=h&&t.height<=80}).sort((e,t)=>{const n=r(e),a=r(t);if(/vue-slider-rail/.test(n)&&!/vue-slider-rail/.test(a))return-1;if(!/vue-slider-rail/.test(n)&&/vue-slider-rail/.test(a))return 1;const o=e.getBoundingClientRect(),i=t.getBoundingClientRect(),s=o.height-i.height;return 0!==s?s:i.width-o.width}),y=Array.from(c.querySelectorAll("*")).filter(e=>{if(!n(e)||!o(e))return!1;const t=e.getBoundingClientRect();return t.width>=Math.max(80,h)&&t.height<=80&&t.left<=f.left+f.width&&t.right>=p.right-p.width}).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),r=n.height-a.height;return 0!==r?r:a.width-n.width}),b=Array.from(c.querySelectorAll("*")).filter(e=>{if(!n(e)||!e.contains(m)||!e.contains(g))return!1;const t=e.getBoundingClientRect();return t.width>=h&&t.height<=140}).sort((e,t)=>{const n=a(e)-a(t);return 0!==n?n:e.getBoundingClientRect().height-t.getBoundingClientRect().height}),v=w[0]??y[0]??b[0];return v?(v.setAttribute("data-roll-recommend-filter-age-track","1"),m.setAttribute("data-roll-recommend-filter-age-min-handle","1"),g.setAttribute("data-roll-recommend-filter-age-max-handle","1"),{ok:!0,current:(e=>{const n=t(e),a=n.includes("年龄")?n.slice(n.indexOf("年龄")+2):n,r=Array.from(a.matchAll(/\d+/g),e=>Number.parseInt(e[0],10)).filter(e=>Number.isInteger(e)),o=r[0],i=a.includes("不限")?void 0:r[1];return{...void 0!==o?{ageMin:o}:{},...void 0!==i?{ageMax:i}:{}}})(t(c.textContent))}):{ok:!1,error:"未找到年龄滑块轨道"}},{panelSelector:sn.recommend.filterPanel,markerAttributes:hr})}async function Mr(e){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{if(e.includes("不限"))return;const t=e.match(/\d+/);return t?Number.parseInt(t[0],10):void 0},a=(e,t)=>{const n=e.style.left;if(n.endsWith("%")){const e=Number.parseFloat(n);if(Number.isFinite(e))return Math.max(0,Math.min(1,e/100))}const a=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(!(r.width<=0))return Math.max(0,Math.min(1,(a.left+a.width/2-r.left)/r.width))},r=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},o=e=>{const t=e.getBoundingClientRect();return t.width*t.height},i=e=>{const t=(e=>"string"==typeof e.className?e.className:"")(e),n=e.getAttribute("role")??"";return/slider|range|track|bar/i.test(t)||"slider"===n},s=Array.from(document.querySelectorAll(e)).filter(e=>r(e)).sort((e,t)=>o(e)-o(t))[0];if(!s)return{};const c=Array.from(s.querySelectorAll("div, li, section, dl, dd")).filter(e=>{const n=t(e.textContent);return r(e)&&n.includes("年龄")&&(/\d+|不限/.test(n)||Array.from(e.querySelectorAll("*")).some(i))}).sort((e,n)=>{const a=o(e)-o(n);return 0!==a?a:t(e.textContent).length-t(n.textContent).length})[0];if(!c)return{};const l=Array.from(c.querySelectorAll(".vue-slider-dot")).filter(e=>r(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),d=c.querySelector(".vue-slider-rail, .vue-slider");if(l.length>=2){const e=l[0],r=l[l.length-1],o=t(e?.querySelector(".vue-slider-dot-tooltip-text")?.textContent),i=t(r?.querySelector(".vue-slider-dot-tooltip-text")?.textContent),s=n(o),c=n(i);return{...void 0!==s?{ageMin:s}:{},...void 0!==c?{ageMax:c}:{},...d&&e?{minRatio:a(e,d)}:{},...d&&r?{maxRatio:a(r,d)}:{}}}return(e=>{const n=t(e),a=n.includes("年龄")?n.slice(n.indexOf("年龄")+2):n,r=Array.from(a.matchAll(/\d+/g),e=>Number.parseInt(e[0],10)).filter(e=>Number.isInteger(e)),o=r[0],i=a.includes("不限")?void 0:r[1];return{...void 0!==o?{ageMin:o}:{},...void 0!==i?{ageMax:i}:{}}})(t(c.textContent))},sn.recommend.filterPanel)}async function Rr(e,t,n,a,r){if(!(await Ir(e)).ok)return!1;const o=e.locator('[data-roll-recommend-filter-age-track="1"]').first(),i="min"===n?'[data-roll-recommend-filter-age-min-handle="1"]':'[data-roll-recommend-filter-age-max-handle="1"]',s=e.locator(i).first(),c=await o.boundingBox();if(!c)return!1;const l=Math.max(0,Math.min(c.width,c.width*a)),d=Math.max(1,c.height/2);try{return r&&await r.moveToLocator(t,s,{durationMs:90,settleMs:20,target:e}),await s.dragTo(o,{force:!0,targetPosition:{x:l,y:d},timeout:2e3}),await e.waitForTimeout(gr),!0}catch{return!1}}function Br(e){return Math.max(0,Math.min(1,(e-ur)/(mr-ur)))}function Er(e,t,n){return Math.max(t,Math.min(n,e))}async function Pr(e,t,n,a,r){const o=await Mr(e),i=o.minRatio??0,s=o.maxRatio??1;let c="min"===n?0:Math.min(1,i+pr),l="min"===n?Math.max(0,s-pr):1,d=Er(Br(a),c,l);for(let o=0;o<fr;o+=1){if(!await Rr(e,t,n,d,r))return!1;const o=await Mr(e),i="min"===n?o.ageMin:o.ageMax;if(i===a)return!0;void 0===i?"max"===n?l=d:c=d:i<a?c=d:l=d;const s=(c+l)/2;if(Math.abs(s-d)<.001)break;d=Er(s,c,l)}const u=await Mr(e);return"min"===n?u.ageMin===a:u.ageMax===a}function $r(e,t,n){return e.ageMin===t&&e.ageMax===n}async function _r(e,t,n,a){const r=n.ageMin??ur,o=n.ageMax,i=await Ir(e);if(!i.ok)return{success:!1,error:i.error};if(!await Rr(e,t,"max",1,a))return{success:!1,error:"年龄上限无法重置为不限"};if(!await Pr(e,t,"min",r,a))return{success:!1,error:`年龄下限无法设置为 ${r}`};if(void 0===o){if(!await Rr(e,t,"max",1,a))return{success:!1,error:"年龄上限无法设置为不限"}}else if(!await Pr(e,t,"max",o,a))return{success:!1,error:`年龄上限无法设置为 ${o}`};const s=await Mr(e);if(!$r(s,r,o)){const e=void 0===s.ageMax?"不限":String(s.ageMax);return{success:!1,error:`年龄筛选未精确生效,当前为 ${s.ageMin??"未知"}-${e}`}}return{success:!0,state:s}}async function qr(e){return await e.evaluate(()=>{const e=e=>(e??"").replace(/\s+/g," ").trim(),t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},n=/(购买VIP|VIP账号|开通VIP|开启VIP|专享筛选特权|扫码支付|立即开通|支付金额)/;if(!Array.from(document.body.querySelectorAll("div, section, aside")).filter(a=>t(a)&&n.test(e(a.textContent))).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return n.width*n.height-a.width*a.height})[0])return!1;const a=Array.from(document.querySelectorAll(".boss-dialog__close, .dialog-close, .close-btn, [class*='close'], button, span, i")).filter(e=>t(e));for(const t of a){const n=e(t.textContent),a="string"==typeof t.className?t.className:"";if("×"===n||"关闭"===n||/close/i.test(a)){t.click();break}}return!0})}async function Nr(e,t){return!!await qr(t)||!(t===e||!await qr(e))}async function Tr(e,t,n){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!r)return e.fallback;const o=Array.from(r.querySelectorAll("div, li, dl, dd, section, ul")).filter(a=>{const r=t(a.textContent);return n(a)&&r.includes(e.rowLabel)}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length})[0];if(!o)return e.fallback;return Array.from(o.querySelectorAll(e.clickableOptionSelector)).filter(t=>n(t)&&(t=>{const n="string"==typeof t.className?t.className:"";return new RegExp(e.selectedClassPattern,"i").test(n)||"true"===t.getAttribute("aria-checked")||"true"===t.getAttribute("aria-selected")})(t)).map(e=>t(e.textContent)).find(t=>""!==t&&t!==e.rowLabel)??e.fallback},{panelSelector:sn.recommend.filterPanel,rowLabel:t,fallback:n,selectedClassPattern:wr,clickableOptionSelector:yr})}async function Lr(e,t,n){return{...void 0!==n.ageMin?{ageMin:n.ageMin}:{},...void 0!==n.ageMax?{ageMax:n.ageMax}:{},gender:await Tr(e,"性别",t.gender),activity:await Tr(e,"活跃度",t.activity)}}async function zr(e,t,n){if(!await e.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity};document.querySelectorAll(`[${e.markerAttribute}]`).forEach(t=>t.removeAttribute(e.markerAttribute));const n=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>t(e))[0];if(!n)return!1;const a=Array.from(n.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>t(e)).find(e=>"确定"===(e.textContent??"").replace(/\s+/g," ").trim());return!!a&&(a.setAttribute(e.markerAttribute,"1"),!0)},{panelSelector:sn.recommend.filterPanel,markerAttribute:"data-roll-recommend-filter-submit"}))return!1;try{const a=e.locator('[data-roll-recommend-filter-submit="1"]').first();return await br(t,e,a,n),await a.click({timeout:2e3}),await e.waitForSelector(sn.recommend.filterPanel,{state:"hidden",timeout:4e3}),await e.waitForTimeout(600),!0}catch{return!1}}async function Fr(e,t,n){const a=async()=>await e.evaluate(e=>{const t=e=>"string"==typeof e.className?e.className:"",n=e=>{const n=t(e),a=e.parentElement?t(e.parentElement):"",r=null!==e.closest(".recommend-filter, .filter-label-wrap, .filter-wrap")?"recommend-filter":"";let o=0;for(const e of[n,a,r])/recommend-filter/.test(e)?o+=3:/filter-label/.test(e)?o+=2:/filter/.test(e)&&(o+=1);return o};for(const t of e.markerAttributes)document.querySelectorAll(`[${t}]`).forEach(e=>e.removeAttribute(t));const a=[...Array.from(document.querySelectorAll(e.filterButtonSelector)),...Array.from(document.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>/^筛选(?:·\d+)?$/.test((e.textContent??"").replace(/\s+/g," ").trim()))].filter(e=>(e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity})(e)).sort((e,t)=>{const a=n(t)-n(e);if(0!==a)return a;const r=e.getBoundingClientRect(),o=t.getBoundingClientRect();return r.width*r.height-o.width*o.height})[0];return!!a&&(a.setAttribute(e.markerAttribute,"1"),!0)},{filterButtonSelector:sn.recommend.filterButton,markerAttribute:"data-roll-recommend-filter-button",markerAttributes:hr}),r=async()=>{try{const a=e.locator(sn.recommend.filterButton).first();if(await a.count()>0&&await a.isVisible())return await a.scrollIntoViewIfNeeded(),await br(t,e,a,n),await a.click({timeout:2e3}),!0}catch{}if(!await a())return!1;const r=e.locator('[data-roll-recommend-filter-button="1"]').first();return await br(t,e,r,n),await r.click({timeout:2e3}),!0};if(await(async()=>{try{const t=e.locator(sn.recommend.filterPanel).first();return await t.count()>0&&await t.isVisible()}catch{return!1}})())return!0;for(let t=0;t<3;t+=1){await Cr(e);try{if(await r())return await e.waitForSelector(sn.recommend.filterPanel,{state:"visible",timeout:4e3}),await Cr(e),!0}catch{}await e.waitForTimeout(300)}return!1}async function Or(e,t,n,a){const r=await xr(t,3e3);if(!await Fr(t,e,a))return vr(n,r?"filter_not_found":"recommend_not_ready",{error:r?"未找到或无法打开筛选按钮":"推荐牛人页未就绪"});if(await Nr(e,t))return vr(n,"requires_vip",{error:"筛选条件触发 VIP 弹窗"});if(!await kr(t,e,"性别",n.gender,a))return vr(n,"filter_not_found",{error:`未找到性别筛选项:${n.gender}`});if(!await kr(t,e,"活跃度",n.activity,a))return vr(n,"filter_not_found",{error:`未找到活跃度筛选项:${n.activity}`});const o=await _r(t,e,n,a);if(!o.success)return vr(n,"age_not_applied",{error:o.error});if(await Nr(e,t))return vr(n,"requires_vip",{error:"年龄筛选触发 VIP 弹窗"});const i=await Lr(t,n,o.state);if(!await zr(t,e,a))return vr(n,"submit_failed",{applied:i,error:"筛选确认失败"});const s=await Sr(t);return vr(n,"applied",{applied:i,...void 0!==s?{filterButtonText:s}:{}})}async function jr(e,t,n,a){const r=await Or(e,t,n,a);if(t!==e&&("filter_not_found"===r.status||"recommend_not_ready"===r.status)){const t=await Or(e,e,n,a);if("filter_not_found"!==t.status&&"recommend_not_ready"!==t.status)return t}return r}var Vr,Dr=sr.object({ageMin:sr.number().int().min(16).optional(),ageMax:sr.number().int().min(16).optional(),gender:sr.enum(cr),activity:sr.enum(lr)}),Ur=sr.object({ageMin:sr.number().optional(),ageMax:sr.number().optional(),gender:sr.string(),activity:sr.string()}),Hr=sr.object({success:sr.boolean(),status:sr.enum(dr),requested:Dr,applied:Ur.optional(),filterButtonText:sr.string().optional(),error:sr.string().optional()}),Wr=sr.object({ageMin:sr.number().int().min(16).optional().describe("年龄下限;未传则重置为 16"),ageMax:sr.number().int().min(16).optional().describe("年龄上限;未传则重置为不限"),gender:sr.enum(cr).default("不限").describe("性别筛选,只支持:不限、男、女"),activity:sr.enum(lr).default("不限").describe("活跃度[单选],只支持:不限、刚刚活跃、今日活跃、3日内活跃、本周活跃、本月活跃")}).refine(e=>void 0===e.ageMin||void 0===e.ageMax||e.ageMin<=e.ageMax,{path:["ageMax"],message:"ageMax must be greater than or equal to ageMin"});function Zr(){return{getContextManager:h,getRecommendTarget:Qa,waitForRecommendFilterSurface:xr,applyRecommendFilter:jr,moveVisualCursorToLocator:Z,showVisualClickOnLocator:G,createVisualActivitySession:e=>new Xt(e),...Vr}}function Gr(e){const t=e.gender??"不限",n=e.activity??"不限";return{...void 0!==e.ageMin?{ageMin:e.ageMin}:{},...void 0!==e.ageMax?{ageMax:e.ageMax}:{},gender:t,activity:n}}function Yr(e){return{success:"applied"===e.status,status:e.status,requested:e.requested,...void 0!==e.applied?{applied:e.applied}:{},...void 0!==e.filterButtonText?{filterButtonText:e.filterButtonText}:{},...void 0!==e.error?{error:e.error}:{}}}var Kr=ir({name:"zhipin_filter_recommend_candidates",description:"在 BOSS「推荐牛人」页打开筛选面板,只设置年龄、性别、活跃度[单选] 三个维度并提交。",input:Wr,output:Hr,execute:async(e,t)=>{const n=Zr(),a=Gr(e);t.logger.info(`Filtering Boss recommend candidates: gender=${a.gender}, activity=${a.activity}, ageMin=${a.ageMin??"16"}, ageMax=${a.ageMax??"不限"}`);const r=n.getContextManager(),o=await r.getPage("zhipin");await o.bringToFront().catch(()=>{});let i=n.getRecommendTarget(o);const s=n.createVisualActivitySession(i);await s.begin("正在打开推荐筛选");let c=await n.waitForRecommendFilterSurface(i);if(c||(i=n.getRecommendTarget(o),await s.retarget(i),c=await n.waitForRecommendFilterSurface(i,2500)),!c)return await s.fail("推荐牛人页未就绪"),Yr({status:"recommend_not_ready",requested:a,error:"推荐牛人页未就绪"});await s.retarget(i),await s.begin("正在设置推荐筛选"),await s.highlightSelector(sn.recommend.filterButton,{label:"正在设置推荐筛选",padding:8});const l=await n.applyRecommendFilter(o,i,a,{moveToLocator:n.moveVisualCursorToLocator,showClickOnLocator:n.showVisualClickOnLocator});return"applied"===l.status?await s.succeed("已应用推荐筛选"):await s.fail(l.error??l.status),Yr(l)}});import{defineTool as Jr}from"@roll-agent/sdk";import{z as Xr}from"zod";var Qr,eo=Xr.object({index:Xr.number(),candidateId:Xr.string(),name:Xr.string(),age:Xr.string(),experience:Xr.string(),education:Xr.string(),workStatus:Xr.string(),company:Xr.string(),currentPosition:Xr.string(),expectedLocation:Xr.string(),expectedPosition:Xr.string(),expectedSalary:Xr.string(),tags:Xr.array(Xr.string()),buttonText:Xr.string()}),to=Xr.object({containerLabel:Xr.string(),stepsRequested:Xr.number(),stepsCompleted:Xr.number(),reachedBoundary:Xr.boolean(),stopReason:Xr.enum(zt),uniqueCount:Xr.number(),duplicateCount:Xr.number(),noNewRounds:Xr.number(),beforeItemCount:Xr.number(),afterItemCount:Xr.number(),beforeScrollHeight:Xr.number(),afterScrollHeight:Xr.number()}),no=Xr.object({success:Xr.boolean(),candidates:Xr.array(eo),total:Xr.number(),scrollStats:to.optional(),error:Xr.string().optional()});function ao(){return{getContextManager:h,getRecommendTarget:Qa,waitForRecommendList:er,createVisualActivitySession:e=>new Xt(e),...Qr}}async function ro(e){return await e.evaluate(()=>{let e=Array.from(document.querySelectorAll(".candidate-card-wrap"));0===e.length&&(e=Array.from(document.querySelectorAll("[data-geek], .geek-item")));const t=[];return e.forEach((e,n)=>{const a=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??"",r=e.querySelector(".name")?.textContent?.trim()??"";let o="",i="",s="",c="";const l=e.querySelector(".base-info.join-text-wrap, .base-info");if(l){const e=[];if(l.querySelectorAll(":scope > *").forEach(t=>{const n=t.textContent?.trim();n&&e.push(n)}),e.length<=1&&(e.length=0,l.childNodes.forEach(t=>{if(t.nodeType===Node.TEXT_NODE){const n=t.textContent?.trim();n&&e.push(n)}})),e.length<=1){const t=l.textContent?.trim()??"";e.length=0,t.split(/[丨·|]/).forEach(t=>{const n=t.trim();n&&e.push(n)})}for(const t of e)!o&&t.includes("岁")?o=t:!i&&(t.includes("年")||t.includes("应届")||t.includes("在校"))?i=t:!s&&/(初中|高中|中专|中技|大专|本科|硕士|博士)/.test(t)?s=t:!c&&/(在职|离职|在校)/.test(t)&&(c=t)}const d=e.querySelector(".timeline-wrap.work-exps .content.join-text-wrap")??e.querySelector(".timeline-wrap.work-exps .content"),u=(d?.textContent?.trim()??"").split("·").map(e=>e.trim()),m=u[0]??"",g=u[1]??"";let f="",p="";const h=e.querySelector(".row-flex:not(.geek-desc)");if(h){const e=h.querySelector(".label"),t=h.querySelector(".content"),n=e?.textContent??"";if((n.includes("期望")||n.includes("最近关注"))&&t){const e=(t.textContent?.trim()??"").split("·").map(e=>e.trim());f=e[0]??"",p=e[1]??""}}if(!f){const t=e.querySelector(".timeline-wrap.expect .content.join-text-wrap")??e.querySelector(".timeline-wrap.expect .content");if(t){const e=(t.textContent?.trim()??"").split("·").map(e=>e.trim());f=e[0]??"",p=e[1]??""}}const w=e.querySelector(".salary-wrap")?.textContent?.trim()??"",y=[];e.querySelectorAll(".tags-wrap .tag-item, .tags-wrap .tag, .tags-wrap span").forEach(e=>{const t=e.textContent?.trim();t&&y.push(t)});const b=e.querySelector("button.btn.btn-greet")?.textContent?.trim()??"";t.push({index:n,candidateId:a,name:r,age:o,experience:i,education:s,workStatus:c,company:m,currentPosition:g,expectedLocation:f,expectedPosition:p,expectedSalary:w,tags:y,buttonText:b})}),t})}function oo(e){return e.candidateId.length>0?e.candidateId:0!==e.name.length?[e.name,e.age,e.experience,e.expectedLocation,e.expectedPosition,e.expectedSalary].join("|"):void 0}var io=Jr({name:"zhipin_get_candidate_list",description:"获取推荐列表页的候选人卡片信息",input:Xr.object({maxResults:Xr.number().optional().describe("最多返回条数"),autoScroll:Xr.boolean().default(!0).describe("是否自动向下滚动动态列表并合并采集结果"),maxScrolls:Xr.number().int().min(0).max(50).default(4).describe("自动滚动的最大步数")}),output:no,execute:async(e,t)=>{t.logger.info("Getting candidate list from recommend page");const n=ao(),a=n.getContextManager(),r=await a.getPage("zhipin");let o=n.getRecommendTarget(r);const i=n.createVisualActivitySession(o);await i.begin("正在打开推荐列表");const s=await n.waitForRecommendList(o);if(o=n.getRecommendTarget(r),await i.retarget(o),!s)return await i.fail("推荐列表未加载"),{success:!1,candidates:[],total:0,error:"推荐列表未加载"};try{const n="正在读取推荐列表";await i.begin(n),await i.highlightSelector(".candidate-card-wrap, [data-geek], .geek-item",{label:n,padding:8});const a=e.autoScroll??!0,r=e.maxScrolls??4;let s,c;if(a&&r>0){const t=await Yt(o,Lt("recommend-list"),()=>ro(o),oo,{direction:"down",steps:r,settleMs:900,maxNoNewRounds:4,boundaryLoadRetries:4,boundarySettleMs:1200,...void 0!==e.maxResults?{targetCount:e.maxResults}:{}});c=[...t.items],s={containerLabel:t.after.containerLabel,stepsRequested:t.stepsRequested,stepsCompleted:t.stepsCompleted,reachedBoundary:t.reachedBoundary,stopReason:t.stopReason,uniqueCount:t.uniqueCount,duplicateCount:t.duplicateCount,noNewRounds:t.noNewRounds,beforeItemCount:t.before.itemCount,afterItemCount:t.after.itemCount,beforeScrollHeight:t.before.scrollHeight,afterScrollHeight:t.after.scrollHeight}}else c=await ro(o);const l=void 0!==e.maxResults?c.slice(0,e.maxResults):c;return await i.succeed(`已读取 ${l.length} 位候选人`),t.logger.info(`Found ${l.length} candidates in recommend list`+(s?`, scroll stop: ${s.stopReason}`:"")),{success:!0,candidates:l,total:l.length,...void 0!==s?{scrollStats:s}:{}}}catch(e){throw await i.fail("读取推荐列表失败"),e}}});import{defineTool as so}from"@roll-agent/sdk";import{BrowserPageInfoSchema as co}from"@roll-agent/browser";import{z as lo}from"zod";var uo,mo=lo.object({success:lo.boolean(),alreadyOnRecommend:lo.boolean(),usedSidebarClick:lo.boolean(),recommendReady:lo.boolean(),page:co.optional(),error:lo.string().optional()});function go(){return{getContextManager:h,getRecommendTarget:Qa,findZhipinSidebarSectionLink:mn,isZhipinRecommendSurfaceOpen:gn,waitForZhipinRecommendSurface:pn,moveVisualCursorToLocator:Z,showVisualClickOnLocator:G,randomDelay:ot,toAttachedPageInfo:Ce,createVisualActivitySession:e=>new Xt(e),...uo}}async function fo(e,t,n){return await t.toAttachedPageInfo(e,n)}async function po(e,t,n,a,r,o){return await n.fail(r),{success:!1,...o,page:await fo(e,t,a),error:r}}async function ho(e,t,n,a){await n.scrollIntoViewIfNeeded(),await t.moveVisualCursorToLocator(e,n,{durationMs:110,settleMs:30}),await n.hover(),await t.randomDelay(e,100,180),await t.showVisualClickOnLocator(e,n,{pulseDurationMs:180}),await n.click(),a.info("Clicked Boss sidebar nav: 推荐牛人")}var wo=so({name:"zhipin_open_recommend_page",description:"通过点击 Boss 左侧导航切换到「推荐牛人」页,避免让编排器依赖站内 URL 猜测。",input:lo.object({}),output:mo,execute:async(e,t)=>{const n=go(),a=n.getContextManager();t.logger.info("Opening Boss recommend page via sidebar navigation");const r=await a.getPage("zhipin");await r.bringToFront().catch(()=>{});const o=n.createVisualActivitySession(r),i="正在切换到推荐牛人页";if(await o.begin(i),await o.highlightSelector(sn.nav.sidebar,{label:i,padding:10}),n.isZhipinRecommendSurfaceOpen(r))return await o.retarget(n.getRecommendTarget(r)),await o.succeed("已在推荐牛人页"),{success:!0,alreadyOnRecommend:!0,usedSidebarClick:!1,recommendReady:!0,page:await fo(a,n,r)};const s=await n.findZhipinSidebarSectionLink(r,"recommend");if(!s)return await po(a,n,o,r,"未找到推荐牛人导航",{alreadyOnRecommend:!1,usedSidebarClick:!1,recommendReady:!1});try{await ho(r,n,s,t.logger)}catch(e){return await po(a,n,o,r,e instanceof Error?e.message:"点击推荐牛人导航失败",{alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!1})}const c=await n.waitForZhipinRecommendSurface(r);return await o.retarget(n.getRecommendTarget(r)),c?(await o.succeed("已切换到推荐牛人页"),{success:!0,alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!0,page:await fo(a,n,r)}):await po(a,n,o,r,"推荐牛人页未就绪",{alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!1})}});import{defineTool as yo}from"@roll-agent/sdk";import{z as bo}from"zod";var vo,xo=bo.object({index:bo.number(),candidateName:bo.string(),candidateId:bo.string(),success:bo.boolean(),error:bo.string().optional()}),So=bo.object({success:bo.boolean(),results:bo.array(xo),summary:bo.object({total:bo.number(),succeeded:bo.number(),failed:bo.number()})});function Co(){return{getContextManager:h,getRecommendTarget:Qa,waitForRecommendList:er,inspectRecommendCard:tr,moveVisualCursorToLocator:Z,showVisualClickOnLocator:G,humanDelay:it,shouldAddRandomBehavior:ct,performRandomScroll:st,createVisualActivitySession:e=>new Xt(e),...vo}}var Ao=yo({name:"zhipin_say_hello",description:"在推荐列表页对候选人点击「打招呼」按钮(支持批量)",input:bo.object({indices:bo.array(bo.number()).describe("要打招呼的候选人索引列表")}),output:So,execute:async(e,t)=>{t.logger.info(`Saying hello to ${e.indices.length} candidates`);const n=Co(),a=n.getContextManager(),r=await a.getPage("zhipin");let o=n.getRecommendTarget(r);const i=n.createVisualActivitySession(o),s=e.indices.length>1?"正在批量打招呼":"正在打招呼";await i.begin("正在打开推荐列表");const c=await n.waitForRecommendList(o);if(o=n.getRecommendTarget(r),await i.retarget(o),!c){await i.fail("推荐列表未加载");const t=e.indices.map(e=>({index:e,candidateName:"",candidateId:"",success:!1,error:"推荐列表未加载"}));return{success:!1,results:t,summary:{total:t.length,succeeded:0,failed:t.length}}}await i.begin(s),await i.highlightSelector(".candidate-card-wrap, [data-geek], .geek-item",{label:s,padding:8});const l=[];for(const t of e.indices)try{const e=await n.inspectRecommendCard(o,t);if(e.found)if(e.hasGreetButton){const a=o.locator(e.cardSelector).nth(t),s=a.locator("button.btn.btn-greet").first();await i.highlightLocator(a,{label:`正在定位第 ${t+1} 位候选人`,padding:10}),await s.scrollIntoViewIfNeeded(),await n.moveVisualCursorToLocator(r,s,{durationMs:90,settleMs:20,target:o}),await s.hover(),await n.showVisualClickOnLocator(r,s,{pulseDurationMs:160,target:o}),await s.click(),l.push({index:t,candidateName:e.name,candidateId:e.candidateId,success:!0})}else l.push({index:t,candidateName:e.name,candidateId:e.candidateId,success:!1,error:"未找到打招呼按钮"});else l.push({index:t,candidateName:"",candidateId:"",success:!1,...void 0!==e.error?{error:e.error}:{}});await n.humanDelay(r),n.shouldAddRandomBehavior(.3)&&await n.performRandomScroll(r)}catch(e){l.push({index:t,candidateName:"",candidateId:"",success:!1,error:e instanceof Error?e.message:String(e)})}const d={total:l.length,succeeded:l.filter(e=>e.success).length,failed:l.filter(e=>!e.success).length};return 0===d.failed?await i.succeed(`已完成 ${d.succeeded}/${d.total} 位候选人`):await i.fail(`已完成 ${d.succeeded}/${d.total} 位候选人`),t.logger.info(`Say hello: ${d.succeeded}/${d.total} succeeded`),{success:0===d.failed,results:l,summary:d}}});import{defineTool as ko}from"@roll-agent/sdk";import{z as Io}from"zod";var Mo=Io.object({success:Io.boolean(),candidateName:Io.string(),candidateId:Io.string(),error:Io.string().optional()}),Ro=ko({name:"zhipin_open_resume",description:"在推荐列表页点击候选人卡片打开简历详情弹窗",input:Io.object({index:Io.number().describe("候选人在列表中的索引")}),output:Mo,execute:async(e,t)=>{t.logger.info(`Opening resume for candidate at index ${e.index}`);const n=h(),a=await n.getPage("zhipin"),r=Qa(a);if(!await er(r))return{success:!1,candidateName:"",candidateId:"",error:"推荐列表未加载"};const o=await tr(r,e.index);if(!o.found)return{success:!1,candidateName:"",candidateId:"",error:o.error??`索引 ${e.index} 超出范围`};const i=r.locator(o.cardSelector).nth(e.index),s=await i.locator("[data-geek], .card-inner, .geek-item").count()>0?i.locator("[data-geek], .card-inner, .geek-item").first():i;return await s.scrollIntoViewIfNeeded(),await Z(a,s,{target:r}),await s.hover(),await ot(a,200,400),await G(a,s,{target:r}),await s.click(),await ot(a,1e3,2e3),t.logger.info(`Opened resume for ${o.name}`),{success:!0,candidateName:o.name,candidateId:o.candidateId}}});import{defineTool as Bo}from"@roll-agent/sdk";import{z as Eo}from"zod";var Po=Eo.object({x:Eo.number(),y:Eo.number(),width:Eo.number(),height:Eo.number()}),$o=Eo.object({success:Eo.boolean(),screenshotArea:Po.optional(),canvasInfo:Eo.object({width:Eo.number(),height:Eo.number()}).optional(),error:Eo.string().optional()}),_o=Bo({name:"zhipin_locate_resume_canvas",description:"定位简历详情中嵌套 iframe 内的 canvas 元素坐标(用于截图)",input:Eo.object({}),output:$o,execute:async(e,t)=>{t.logger.info("Locating resume canvas in nested iframes");const n=h(),a=await n.getPage("zhipin");try{const e=a.frame("recommendFrame")??a.frames().find(e=>e.url().includes("recommend"));if(!e)return{success:!1,error:"未找到推荐页 iframe"};const n=await e.$('iframe[src*="c-resume"]');if(!n)return{success:!1,error:"未找到简历 iframe"};const r=await n.contentFrame();if(!r)return{success:!1,error:"无法访问简历 iframe 内容"};try{await r.waitForSelector("canvas#resume, div#resume canvas",{timeout:5e3})}catch{return{success:!1,error:"简历 canvas 未加载"}}const o=await r.evaluate(()=>{const e=document.querySelector("canvas#resume, div#resume canvas");if(!e)return null;const t=e.getBoundingClientRect();return{width:e.width,height:e.height,clientWidth:t.width,clientHeight:t.height,x:t.x,y:t.y}});if(!o)return{success:!1,error:"无法获取 canvas 信息"};const i=await a.evaluate(()=>{const e=document.querySelector("#recommendFrame");if(!e)return null;const t=e.getBoundingClientRect();return{x:t.x,y:t.y}}),s=await e.evaluate(()=>{const e=document.querySelector('iframe[src*="c-resume"]');if(!e)return null;const t=e.getBoundingClientRect();return{x:t.x,y:t.y}}),c=(i?.x??0)+(s?.x??0),l=(i?.y??0)+(s?.y??0);return t.logger.info(`Canvas located at (${c+o.x}, ${l+o.y})`),{success:!0,screenshotArea:{x:Math.round(c+o.x),y:Math.round(l+o.y),width:Math.round(o.clientWidth),height:Math.round(o.clientHeight)},canvasInfo:{width:o.width,height:o.height}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}});import{defineTool as qo}from"@roll-agent/sdk";import{z as No}from"zod";var To=No.object({success:No.boolean(),closed:No.boolean(),error:No.string().optional()}),Lo=[".recommendV2 .boss-popup__close",".dialog-lib-resume .boss-popup__close",".boss-dialog .boss-popup__close",".boss-popup__close",".close-btn",".dialog-close"],zo=[".boss-popup__close",".close-btn",".dialog-close",".modal-close"],Fo=qo({name:"zhipin_close_resume",description:"关闭简历详情弹窗",input:No.object({}),output:To,execute:async(e,t)=>{t.logger.info("Closing resume detail modal");const n=h(),a=await n.getPage("zhipin"),r=a.frame("recommendFrame")??a.frames().find(e=>e.url().includes("recommend"));if(!await(async()=>{if(r)for(const e of Lo){const t=r.locator(e).first();if(await t.isVisible())return await Z(a,t,{target:r}),await G(a,t,{target:r}),await t.click(),!0}for(const e of zo){const t=a.locator(e).first();if(await t.isVisible())return await Z(a,t),await G(a,t),await t.click(),!0}return!1})())return{success:!1,closed:!1,error:"未找到关闭按钮"};let o=!1;for(let e=0;e<5;e++){await a.waitForTimeout(300);const e=r?await r.$(".boss-popup__wrapper, .dialog-lib-resume, .boss-dialog"):await a.$(".boss-popup__wrapper");if(!e||!await e.isVisible()){o=!0;break}}return t.logger.info(o?"Resume modal closed and verified":"Resume modal close unverified"),{success:!0,closed:!0}}});import{defineTool as Oo}from"@roll-agent/sdk";import{z as jo}from"zod";import{waitForSelector as Vo}from"@roll-agent/browser";var Do={login:{qrCode:".login-qr img, .qr-code img",loginSuccess:".user-info, .header-user"},messageList:{container:".chat-list, .msg-list",item:".chat-item, .msg-item",candidateName:".chat-item .name, .msg-item .name",lastMessage:".chat-item .msg, .msg-item .content",unreadBadge:".chat-item .unread, .msg-item .badge",timestamp:".chat-item .time, .msg-item .time"},chat:{input:".chat-input textarea, .msg-input textarea",sendButton:".btn-send, .send-btn",messageItem:".chat-msg, .msg-bubble",messageText:".chat-msg .text, .msg-bubble .text"}};import{navigateTo as Uo,waitForSelector as Ho}from"@roll-agent/browser";var Wo="https://www.yupao.com",Zo=`${Wo}/chat`,Go=`${Wo}/login`;async function Yo(e){e.url().includes("/chat")||await Uo(e,Zo),await Ho(e,Do.messageList.container,{timeout:15e3})}async function Ko(e,t){const n=`${Wo}/chat?id=${encodeURIComponent(t)}`;await Uo(e,n),await Ho(e,Do.chat.input,{timeout:15e3})}async function Jo(e,t){await Yo(e),await Vo(e,Do.messageList.item,{timeout:1e4});const n=Do.messageList;return await e.$$eval(n.item,(e,t)=>{const n=[],a=t.maxItems?e.slice(0,t.maxItems):e;for(const e of a){const a=e.querySelector(t.sel.candidateName),r=e.querySelector(t.sel.lastMessage),o=e.querySelector(t.sel.unreadBadge),i=e.querySelector(t.sel.timestamp),s=e.getAttribute("data-id")??e.getAttribute("data-conversation-id")??e.querySelector("a")?.getAttribute("href")?.match(/id=([^&]+)/)?.[1]??"";n.push({conversationId:s,candidateName:a?.textContent?.trim()??"",lastMessage:r?.textContent?.trim()??"",unreadCount:parseInt(o?.textContent?.trim()??"0",10)||0,timestamp:i?.textContent?.trim()??""})}return n},{sel:n,maxItems:t})}var Xo=jo.object({limit:jo.number().optional().describe("最多返回的消息条数")}),Qo=jo.object({conversationId:jo.string(),candidateName:jo.string(),lastMessage:jo.string(),unreadCount:jo.number(),timestamp:jo.string()}),ei=jo.object({messages:jo.array(Qo),total:jo.number()}),ti=Oo({name:"yupao_read_messages",description:"读取鱼泡未读消息列表",input:Xo,output:ei,execute:async(e,t)=>{t.logger.info(`Reading yupao messages (limit: ${e.limit??"all"})`);const n=h(),a=await n.getPage("yupao"),r=await Jo(a,e.limit);return t.logger.info(`Found ${r.length} messages`),{messages:r.map(e=>({...e})),total:r.length}}});import{defineTool as ni}from"@roll-agent/sdk";import{z as ai}from"zod";import{waitForSelector as ri,typeText as oi,clickElement as ii}from"@roll-agent/browser";async function si(e,t,n){try{return await Ko(e,t),await oi(e,Do.chat.input,n),await ii(e,Do.chat.sendButton),await ri(e,Do.chat.messageItem,{timeout:5e3}),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}var ci=ai.object({conversationId:ai.string().describe("对话 ID"),message:ai.string().describe("要发送的回复消息")}),li=ai.object({success:ai.boolean(),conversationId:ai.string(),sentMessage:ai.string(),error:ai.string().optional()}),di=ni({name:"yupao_send_reply",description:"向鱼泡指定对话发送回复消息",input:ci,output:li,execute:async(e,t)=>{const{conversationId:n,message:a}=e;t.logger.info(`Sending reply to yupao conversation ${n}`);const r=h(),o=await r.getPage("yupao"),i=await si(o,n,a);return i.success?t.logger.info("Reply sent successfully"):t.logger.error(`Failed to send reply: ${i.error}`),{success:i.success,conversationId:n,sentMessage:a,error:i.error}}}),ui=t("browser-use-agent");function mi(e){if(void 0!==e){if("true"===e)return!0;if("false"===e)return!1;throw new Error(`Expected boolean env value "true" or "false", received "${e}".`)}}function gi(e,t){if(void 0===e)return;const n=Number.parseInt(e,10);if(!Number.isInteger(n))throw new Error(`${t} must be an integer, received "${e}".`);return n}function fi(e){if(void 0===e)return;const t=JSON.parse(e);if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))throw new Error("BROWSER_ARGS_JSON must be a JSON string array.");return t}function pi(){return n.parse({mode:process.env.BROWSER_MODE,headless:mi(process.env.BROWSER_HEADLESS),cdpUrl:process.env.BROWSER_CDP_URL,cdpHost:process.env.BROWSER_CDP_HOST,cdpPort:gi(process.env.BROWSER_CDP_PORT,"BROWSER_CDP_PORT"),channel:process.env.BROWSER_CHANNEL,executablePath:process.env.BROWSER_EXECUTABLE_PATH,userDataDir:process.env.BROWSER_USER_DATA_DIR,args:fi(process.env.BROWSER_ARGS_JSON),sessionsDir:process.env.BROWSER_SESSIONS_DIR})}var hi=e({name:"browser-use-agent",tools:[me,Ie,je,Ge,tt,nn,Cn,Mn,Vn,_a,Oa,Wa,or,wo,Kr,io,Ao,Ro,_o,Fo,ti,di,S]},{onShutdown:v});async function wi(){await f(pi());try{await ka(),y(!0)}catch(e){y(!1),ui.error(`Failed to preload Reply Authority keys during startup; browser_status.replyAuthorityKeysLoaded=false. ${e instanceof Error?e.stack??e.message:String(e)}`)}await hi.listen({transport:{type:"http",port:parseInt(process.env.BROWSER_AGENT_PORT??"3100",10),host:process.env.BROWSER_AGENT_HOST??"127.0.0.1"}})}wi().catch(async e=>{ui.error(`Fatal error: ${e instanceof Error?e.stack??e.message:String(e)}`),await v().catch(()=>{}),process.exit(1)});
|
|
1
|
+
import{defineAgent as e,createAgentLogger as t}from"@roll-agent/sdk";import{BrowserRuntimeConfigSchema as n}from"@roll-agent/browser";import{defineTool as a}from"@roll-agent/sdk";import{z as r}from"zod";import{createAgentLogger as o}from"@roll-agent/sdk";import{BrowserRuntime as i,BrowserContextManager as s,SessionStore as c}from"@roll-agent/browser";var l,u,d,m=!1,g=o("browser-use-agent");async function f(e){l||(m=!1,d=new c(e.sessionsDir),l=new i(e),await l.start(),u=new s(l,d))}function p(){if(!l)throw new Error("BrowserRuntime not initialized. Call initRuntime() first.");return l}function h(){if(!u)throw new Error("BrowserContextManager not initialized. Call initRuntime() first.");return u}function w(){if(!d)throw new Error("SessionStore not initialized. Call initRuntime() first.");return d}function y(e){m=e}function b(){return m}async function v(){const e=u,t=l,n=[];if(u=void 0,l=void 0,d=void 0,m=!1,e){g.info("Closing browser contexts...");try{await e.closeAll()}catch(e){n.push(new Error("Failed to close browser contexts",{cause:e})),g.error(`Failed to close browser contexts: ${e instanceof Error?e.stack??e.message:String(e)}`)}}if(t){g.info("Stopping browser process...");try{await t.stop()}catch(e){n.push(new Error("Failed to stop browser runtime",{cause:e})),g.error(`Failed to stop browser runtime: ${e instanceof Error?e.stack??e.message:String(e)}`)}}if(g.info("Browser runtime shutdown complete"),n.length>0)throw new AggregateError(n,"Browser runtime shutdown failed")}var x=r.object({success:r.boolean(),mode:r.string(),connected:r.boolean()}),S=a({name:"attach_browser_session",description:"调试工具:显式执行一次 connectOverCDP(),仅建立 Playwright Browser 连接,不做页面导航或 DOM 操作。",input:r.object({}),output:x,execute:async(e,t)=>{const n=p();return t.logger.info("Attaching Playwright browser session over CDP"),await n.getBrowser(),{success:!0,mode:n.mode,connected:!0}}});import{defineTool as C}from"@roll-agent/sdk";import{z as k}from"zod";import{BrowserStatusSchema as A}from"@roll-agent/browser";import{createHash as I}from"node:crypto";import{z as R}from"zod";var M=["REPLY_AUTHORITY_KEYS_URL","BROWSER_VISUAL_CURSOR","BROWSER_VISUAL_ACTIVITY"],P=/^[0-9a-f]{8}$/,B=R.object({present:R.boolean(),fingerprint:R.string().regex(P).optional()}),E=R.record(B);function _(e,t=process.env){return Object.fromEntries(e.map(e=>{const n=t[e];return"string"==typeof n&&n.length>0?[e,{present:!0,fingerprint:T(n)}]:[e,{present:!1}]}))}function T(e){return I("sha256").update(e).digest("hex").slice(0,8)}var q,$=180,N=60,L=280,z="roll-agent-visual-cursor-root",F="__rollVisualCursorState";function j(e){if(void 0!==e)return"true"===e||"false"!==e&&void 0}function O(){return void 0!==q?q:j(process.env.BROWSER_VISUAL_CURSOR)??!0}async function D(e){return await e.evaluate(e=>{const t=e.getBoundingClientRect();return t.width<=0||t.height<=0?null:{x:Math.round(t.left+t.width/2),y:Math.round(t.top+t.height/2)}})}async function U(e,t){await e.evaluate(e=>{const t="roll-agent-visual-cursor-root",n="roll-agent-visual-cursor-pointer",a="__rollVisualCursorState",r=(()=>{const e=document.getElementById(t);if(e)return e;const a=document.createElement("div");a.id=t,a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.width="0",a.style.height="0",a.style.pointerEvents="none",a.style.zIndex="2147483647";const r=document.createElement("div");return r.id=n,r.setAttribute("aria-hidden","true"),r.style.position="fixed",r.style.left="0",r.style.top="0",r.style.width="24px",r.style.height="24px",r.style.opacity="0",r.style.transform="translate(-9999px, -9999px)",r.style.willChange="transform, opacity",r.style.filter="drop-shadow(0 4px 8px rgba(15, 23, 42, 0.28))",r.innerHTML='<svg viewBox="0 0 24 24" width="24" height="24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 2L18 14L11.4 15.3L14.6 22L10.7 23.5L7.6 16.8L3 21V2Z" fill="#FFFFFF" stroke="#0F172A" stroke-width="1.5" stroke-linejoin="round"/></svg>',a.append(r),document.documentElement.append(a),a})(),o=r.querySelector(`#${n}`);if(!o)return;const i=window[a],s=e.point,c=e.durationMs,l=s.x-2,u=s.y-2;if(i?o.style.transition=`transform ${c}ms cubic-bezier(0.22, 1, 0.36, 1), opacity 120ms ease`:(o.style.transition="opacity 120ms ease",o.style.transform=`translate(${l}px, ${u}px)`),o.style.opacity="1",o.style.transform=`translate(${l}px, ${u}px)`,window[a]={x:s.x,y:s.y},!e.clickPulse)return;const d=document.createElement("div");d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.width="18px",d.style.height="18px",d.style.borderRadius="9999px",d.style.border="2px solid rgba(20, 184, 166, 0.95)",d.style.background="rgba(20, 184, 166, 0.18)",d.style.pointerEvents="none",d.style.opacity="0.9",d.style.transform=`translate(${s.x-9}px, ${s.y-9}px) scale(0.55)`,d.style.transition=`transform ${e.pulseDurationMs}ms ease, opacity ${e.pulseDurationMs}ms ease`,r.append(d),requestAnimationFrame(()=>{d.style.opacity="0",d.style.transform=`translate(${s.x-18}px, ${s.y-18}px) scale(2)`}),globalThis.setTimeout(()=>{d.remove()},e.pulseDurationMs+40)},{point:t.point,durationMs:t.durationMs,clickPulse:t.clickPulse,pulseDurationMs:t.pulseDurationMs})}function V(e){const t=[e],n="function"==typeof e.frames?e.frames():[];return t.push(...n),t}async function H(e){await e.evaluate(({rootId:e,stateKey:t})=>{document.getElementById(e)?.remove(),delete window[t]},{rootId:z,stateKey:F})}async function W(e,t={}){if(e.isClosed())return!1;let n=!1;for(const a of V(e))if(a!==t.preserveTarget)try{await H(a),n=!0}catch{}return n}async function K(e,t,n={}){if(!O()||e.isClosed())return!1;try{await t.scrollIntoViewIfNeeded();const a=await D(t);if(!a)return!1;const r=n.durationMs??$,o=n.settleMs??N,i=n.target??e;return await W(e,{preserveTarget:i}),await U(n.target??e,{point:a,durationMs:r,clickPulse:!1,pulseDurationMs:L}),await e.waitForTimeout(Math.max(r+o,0)),!0}catch{return!1}}async function Z(e,t,n={}){if(!O()||e.isClosed())return!1;try{const a=await D(t);if(!a)return!1;const r=n.pulseDurationMs??L,o=n.target??e;return await W(e,{preserveTarget:o}),await U(o,{point:a,durationMs:0,clickPulse:!0,pulseDurationMs:r}),await e.waitForTimeout(r),!0}catch{return!1}}async function G(e,t,n){return await K(e,e.locator(t).first(),n)}async function Y(e,t){return await Z(e,e.locator(t).first())}var J,X={info:{accent:"#14b8a6",accentSoft:"rgba(20, 184, 166, 0.42)",accentGlow:"rgba(20, 184, 166, 0.18)",capsuleBg:"rgba(15, 23, 42, 0.82)",capsuleBorder:"rgba(45, 212, 191, 0.38)",text:"#F8FAFC",dot:"#2DD4BF"},success:{accent:"#22c55e",accentSoft:"rgba(34, 197, 94, 0.42)",accentGlow:"rgba(34, 197, 94, 0.18)",capsuleBg:"rgba(10, 24, 16, 0.86)",capsuleBorder:"rgba(74, 222, 128, 0.38)",text:"#F0FDF4",dot:"#4ADE80"},error:{accent:"#f59e0b",accentSoft:"rgba(245, 158, 11, 0.42)",accentGlow:"rgba(245, 158, 11, 0.2)",capsuleBg:"rgba(41, 24, 10, 0.88)",capsuleBorder:"rgba(251, 191, 36, 0.4)",text:"#FFFBEB",dot:"#FBBF24"}},Q=14,ee=720;function te(e){if(void 0!==e)return"true"===e||"false"!==e&&void 0}function ne(e="info"){return X[e]}function ae(){return void 0!==J?J:te(process.env.BROWSER_VISUAL_ACTIVITY)??!0}async function re(e,t=Q){return await e.evaluate((e,t)=>{const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const a=globalThis.innerWidth,r=globalThis.innerHeight,o=Math.max(t,0),i=Math.max(n.left-o,0),s=Math.max(n.top-o,0),c=Math.min(n.right+o,a),l=Math.min(n.bottom+o,r);return{x:Math.round(i),y:Math.round(s),width:Math.max(Math.round(c-i),0),height:Math.max(Math.round(l-s),0)}},t)}async function oe(e,t){await e.evaluate(e=>{const t="roll-agent-visual-activity-style",n="roll-agent-visual-activity-root",a="roll-agent-visual-activity-viewport",r="roll-agent-visual-activity-region",o="roll-agent-visual-activity-region-shine",i="roll-agent-visual-activity-capsule",s="roll-agent-visual-activity-dot",c="roll-agent-visual-activity-label",l=(e,t,n,a=!1)=>{a&&(e.style.transition="none",t.style.transition="none",n.style.transition="none"),e.style.opacity="0",e.style.transform="scale(0.995)",t.style.opacity="0",n.style.opacity="0",n.style.transform="translate(-50%, -8px)",t.style.transform="translate(-9999px, -9999px)",a&&requestAnimationFrame(()=>{e.style.transition="opacity 180ms ease, transform 220ms ease",t.style.transition="transform 220ms cubic-bezier(0.22, 1, 0.36, 1), width 220ms ease, height 220ms ease, opacity 180ms ease",n.style.transition="opacity 180ms ease, transform 220ms ease"})};(()=>{if(document.getElementById(t))return;const e=document.createElement("style");e.id=t,e.textContent="\n @keyframes roll-visual-activity-breathe {\n 0%, 100% { transform: translate(-50%, 0px) scale(1); }\n 50% { transform: translate(-50%, -1px) scale(1.01); }\n }\n @keyframes roll-visual-activity-scan {\n 0% { transform: translateX(-140%) skewX(-18deg); }\n 100% { transform: translateX(200%) skewX(-18deg); }\n }\n ",document.head.append(e)})(),(()=>{const e=document.getElementById(n);if(e)return e;const t=document.createElement("div");t.id=n,t.style.position="fixed",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="2147483646";const l=document.createElement("div");l.id=a,l.setAttribute("aria-hidden","true"),l.style.position="fixed",l.style.inset="10px",l.style.borderRadius="20px",l.style.opacity="0",l.style.transform="scale(0.995)",l.style.transition="opacity 180ms ease, transform 220ms ease";const u=document.createElement("div");u.id=r,u.setAttribute("aria-hidden","true"),u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.width="0",u.style.height="0",u.style.borderRadius="18px",u.style.opacity="0",u.style.overflow="hidden",u.style.transform="translate(-9999px, -9999px)",u.style.transition="transform 220ms cubic-bezier(0.22, 1, 0.36, 1), width 220ms ease, height 220ms ease, opacity 180ms ease";const d=document.createElement("div");d.id=o,d.setAttribute("aria-hidden","true"),d.style.position="absolute",d.style.inset="0",d.style.animation="roll-visual-activity-scan 1.6s linear infinite",d.style.opacity="0.9",u.append(d);const m=document.createElement("div");m.id=i,m.setAttribute("aria-hidden","true"),m.style.position="fixed",m.style.left="50%",m.style.top="20px",m.style.display="inline-flex",m.style.alignItems="center",m.style.gap="10px",m.style.padding="10px 14px",m.style.borderRadius="999px",m.style.opacity="0",m.style.transform="translate(-50%, -8px)",m.style.transition="opacity 180ms ease, transform 220ms ease",m.style.backdropFilter="blur(12px)",m.style.animation="roll-visual-activity-breathe 1.8s ease-in-out infinite",m.style.fontSize="13px",m.style.fontWeight="600",m.style.lineHeight="18px",m.style.letterSpacing="0.01em",m.style.whiteSpace="nowrap";const g=document.createElement("div");g.id=s,g.setAttribute("aria-hidden","true"),g.style.width="8px",g.style.height="8px",g.style.borderRadius="999px",g.style.flex="0 0 auto";const f=document.createElement("div");f.id=c,f.setAttribute("aria-live","polite"),m.append(g,f),t.append(l,u,m),document.documentElement.append(t)})();const u=document.getElementById(a),d=document.getElementById(r),m=document.getElementById(o),g=document.getElementById(i),f=document.getElementById(s),p=document.getElementById(c);if(!(u&&d&&m&&g&&f&&p))return;const h=window.__rollVisualActivityTimers??={};if(void 0!==h.hideTimer&&(globalThis.clearTimeout(h.hideTimer),delete h.hideTimer),"clear"===e.mode)return void l(u,d,g,!0);const w=e.theme;if(void 0!==w&&(u.style.border=`1px solid ${w.accentSoft}`,u.style.boxShadow=`inset 0 0 0 1px ${w.accentSoft}, 0 0 52px ${w.accentGlow}`,g.style.border=`1px solid ${w.capsuleBorder}`,g.style.background=w.capsuleBg,g.style.color=w.text,g.style.boxShadow=`0 18px 46px rgba(15, 23, 42, 0.24), 0 0 0 1px ${w.capsuleBorder}`,f.style.background=w.dot,f.style.boxShadow=`0 0 0 5px ${w.accentGlow}`,d.style.border=`1px solid ${w.accentSoft}`,d.style.background=w.accentGlow,d.style.boxShadow=`0 0 0 1px ${w.accentSoft}, 0 16px 42px ${w.accentGlow}`,m.style.background="linear-gradient(115deg, transparent 0%, rgba(255,255,255,0.08) 24%, rgba(255,255,255,0.42) 50%, transparent 76%)"),void 0!==e.label&&(p.textContent=e.label),g.style.opacity="1",g.style.transform="translate(-50%, 0)",u.style.opacity="complete"===e.mode?"0.9":"0.72",u.style.transform="scale(1)","begin"===e.mode)return d.style.opacity="0",void(d.style.transform="translate(-9999px, -9999px)");if(void 0!==e.rect&&(d.style.width=`${e.rect.width}px`,d.style.height=`${e.rect.height}px`,d.style.transform=`translate(${e.rect.x}px, ${e.rect.y}px)`,d.style.opacity="1"),"complete"!==e.mode)return;const y=Math.max(e.lingerMs??0,0);h.hideTimer=globalThis.setTimeout(()=>{l(u,d,g),delete h.hideTimer},y)},t)}async function ie(e,t){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"begin",label:t.label,theme:ne(t.tone??"info")}),!0}catch{return!1}}async function se(e,t,n={}){if(!ae()||e.isClosed())return!1;try{await t.scrollIntoViewIfNeeded();const a=await re(t,n.padding??Q);return!!a&&(await oe(n.target??e,{mode:"highlight",...void 0!==n.label?{label:n.label}:{},theme:ne(n.tone??"info"),rect:a}),!0)}catch{return!1}}async function ce(e,t,n){return await se(e,e.locator(t).first(),n)}async function le(e,t){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"complete",label:t.label,theme:ne("error"===t.status?"error":"success"),lingerMs:t.lingerMs??ee}),!0}catch{return!1}}async function ue(e,t={}){if(!ae()||e.isClosed())return!1;try{return await oe(t.target??e,{mode:"clear"}),!0}catch{return!1}}var de=A.extend({replyAuthorityKeysLoaded:k.boolean(),visualCursorEnabled:k.boolean(),visualActivityEnabled:k.boolean(),effectiveEnvSources:E}),me=C({name:"browser_status",description:"查询浏览器运行状态和活跃 session 信息",input:k.object({}),output:de,execute:async(e,t)=>{t.logger.info("Querying browser status");const n=p(),a=h(),r=w(),o=n.isRunning(),{headless:i,mode:s}=n.getConfig(),c=a.getActivePlatforms(),l=[];for(const e of c){const t=a.getPageCount(e),o=a.getCurrentUrl(e);let i=null,s="unknown";if(n.shouldRestoreSessionSnapshot()){const[t,n]=await Promise.all([r.loadCookies(e),r.loadLocalStorage(e)]);i=void 0!==t&&t.length>0||void 0!==n&&Object.keys(n).length>0,s=i?"snapshot":"none"}else n.usesPersistentProfile()&&(i=null,s="profile");l.push({platform:e,pagesOpen:t,currentUrl:o,hasLoginState:i,loginStateSource:s})}return{running:o,headless:i,mode:s,activeSessions:l,replyAuthorityKeysLoaded:b(),visualCursorEnabled:O(),visualActivityEnabled:ae(),effectiveEnvSources:_(M)}}});import{defineTool as ge}from"@roll-agent/sdk";import{BrowserPageInfoSchema as fe,PlatformSchema as pe}from"@roll-agent/browser";import{z as he}from"zod";import{PLATFORMS as we}from"@roll-agent/browser";var ye={zhipin:"https://www.zhipin.com",yupao:"https://www.yupao.com"};function be(e){return new URL(ye[e]).host}function ve(e,t){try{return new URL(e).host.includes(be(t))}catch{return!1}}function xe(e){return we.find(t=>ve(e,t))}function Se(e,t){const n=xe(t.url)??null;return{pageId:t.targetId,url:t.url,title:t.title,boundPlatform:e.getBoundPlatformForNativePage(t.targetId)??null,detectedPlatform:n,isSelectedForPlatform:e.isNativePageSelected(t.targetId)}}async function Ce(e,t){const n=t.url();return{pageId:e.getPageId(t),url:n,title:await t.title().catch(()=>""),boundPlatform:e.getBoundPlatformForPage(t)??null,detectedPlatform:xe(n)??null,isSelectedForPlatform:e.isSelectedPageForPlatform(t)}}var ke=he.object({platform:pe.optional().describe("可选:仅返回指定平台相关的页面")}),Ae=he.object({pages:he.array(fe)}),Ie=ge({name:"list_pages",description:"通过原生 CDP 列出当前浏览器可见页面及其可选择的 pageId;登录前该值等同于原生 targetId。",input:ke,output:Ae,execute:async(e,t)=>{const n=h();t.logger.info("Listing browser pages");const a=(await n.listNativePages()).map(e=>Se(n,e));return{pages:void 0===e.platform?a:a.filter(t=>t.boundPlatform===e.platform||t.detectedPlatform===e.platform)}}});import{defineTool as Re}from"@roll-agent/sdk";import{BrowserPageInfoSchema as Me}from"@roll-agent/browser";import{z as Pe}from"zod";async function Be(e,t){return e.useTrackedPage(t,e=>ve(e.url(),t))}async function Ee(e,t){return(await e.listNativePages()).find(e=>ve(e.url,t))}async function _e(e,t){const n=await Ee(e,t);if(n)return await e.activateNativePage(n.targetId),{page:n,reusedExistingPage:!0};return{page:await e.openNativePage(ye[t]),reusedExistingPage:!1}}var Te,qe=Pe.object({url:Pe.string().url().describe("要导航到的目标 URL")}),$e=Pe.object({success:Pe.boolean(),page:Me});function Ne(){return{getContextManager:h,detectPlatformFromUrl:xe,matchesPlatformHost:ve,findTrackedPlatformPage:Be,toAttachedPageInfo:Ce,...Te}}async function Le(e,t,n){const a=(await e.listNativePages()).find(e=>t.matchesPlatformHost(e.url,n));if(a)return await e.selectNativePage(n,a.targetId),await e.getPage(n)}async function ze(e,t,n,a){const r=t.detectPlatformFromUrl(n);if(!r){const t=await e.getActivePage();if(!t)throw new Error("No active browser tab detected. Use open_platform or select_page first.");return{page:t}}const o=await t.findTrackedPlatformPage(e,r);if(o)return a.info(`Reusing tracked ${r} page instead of navigating the current unrelated tab`),{page:o,platform:r};const i=await Le(e,t,r);if(i)return a.info(`Reusing native ${r} page instead of navigating the current unrelated tab`),{page:i,platform:r};const s=await e.getActivePage();if(!s)throw new Error("No active browser tab detected. Use open_platform or select_page first.");return a.warn(`No existing ${r} page found; falling back to navigating the current active tab`),{page:s,platform:r}}async function Fe(e,t,n){return await e.selectAttachedPage(n,e.getPageId(t))}async function je(e,t){e.url()!==t&&await e.goto(t,{waitUntil:"domcontentloaded"})}var Oe=Re({name:"navigate_active_tab",description:"导航到指定 URL;若 URL 属于已知平台(Boss/鱼泡),优先复用已打开的平台页,避免把无关 tab 导航成第二个平台页。",input:qe,output:$e,execute:async(e,t)=>{const n=Ne(),a=n.getContextManager();t.logger.info(`Navigating active tab to ${e.url}`);const{page:r,platform:o}=await ze(a,n,e.url,t.logger);await r.bringToFront().catch(()=>{}),await je(r,e.url);const i=o??n.detectPlatformFromUrl(r.url()),s=i?await Fe(a,r,i):r;return i?t.logger.info(`Bound navigated page to ${i}`):a.clearBindingForPage(r),{success:!0,page:await n.toAttachedPageInfo(a,s)}}});import{defineTool as De}from"@roll-agent/sdk";import{BrowserPageInfoSchema as Ue,PlatformSchema as Ve}from"@roll-agent/browser";import{z as He}from"zod";var We=He.object({platform:Ve.describe("目标平台:`zhipin` 代表 BOSS直聘,`yupao` 代表鱼泡")}),Ke=He.object({success:He.boolean(),page:Ue,reusedExistingTab:He.boolean()}),Ze=De({name:"open_platform",description:"打开并聚焦招聘平台主页,供用户手动登录或后续执行站内操作。",input:We,output:Ke,execute:async(e,t)=>{const{platform:n}=e,a=p(),r=h();t.logger.info(`Opening platform page for ${n}`);const{page:o,reusedExistingPage:i}=await _e(a,n);return r.rememberNativePageSelection(n,o),{success:!0,page:Se(r,o),reusedExistingTab:i}}});import{defineTool as Ge}from"@roll-agent/sdk";import{BrowserPageInfoSchema as Ye,PlatformSchema as Je}from"@roll-agent/browser";import{z as Xe}from"zod";var Qe=Xe.object({platform:Je.describe("要将该页面绑定为当前活跃页的平台"),pageId:Xe.string().describe("通过 list_pages 返回的 pageId;登录前就是原生 targetId,登录后仍可作为稳定选择句柄")}),et=Xe.object({success:Xe.boolean(),page:Ye}),tt=Ge({name:"select_page",description:"将指定 pageId 绑定为平台当前活跃页,并切换到前台;登录前走原生 CDP target 激活。",input:Qe,output:et,execute:async(e,t)=>{const n=h();t.logger.info(`Selecting page ${e.pageId} for ${e.platform}`);const a=await n.selectNativePage(e.platform,e.pageId);return{success:!0,page:Se(n,a)}}});import{defineTool as nt}from"@roll-agent/sdk";import{BrowserPageInfoSchema as at}from"@roll-agent/browser";import{z as rt}from"zod";var ot=["native","native-watch","browser-attach","page-attach","network-watch","page-evaluate","detector-fingerprint","storage-summary"],it=[...ot,"browser-attach-watch"],st=rt.enum(["localStorage","sessionStorage"]),ct=rt.enum(["array","object","string","number","boolean","null"]),lt=rt.enum(["empty","json","string"]),ut=rt.enum(ot),dt=rt.enum(it),mt=rt.enum(["request","response"]),gt=rt.enum(["apm-action-log","device-action-report","boss-risk-report","zhipin-security"]),ft=rt.object({area:st,key:rt.string(),valueLength:rt.number().int().nonnegative(),valueKind:lt,jsonKind:ct.optional(),jsonTopLevelKeys:rt.array(rt.string()).optional(),jsonArrayLength:rt.number().int().nonnegative().optional(),numericFields:rt.record(rt.number()).optional(),booleanFields:rt.record(rt.boolean()).optional(),arrayLengths:rt.record(rt.number().int().nonnegative()).optional()}),pt=rt.object({name:rt.string(),domain:rt.string(),path:rt.string(),expires:rt.string(),valueLength:rt.number().int().nonnegative(),httpOnly:rt.boolean(),secure:rt.boolean(),sameSite:rt.string().optional()}),ht=rt.object({before:rt.number().optional(),after:rt.number().optional(),delta:rt.number().optional()}),wt=rt.object({before:rt.boolean().optional(),after:rt.boolean().optional()}),yt=rt.object({before:rt.number().int().nonnegative().optional(),after:rt.number().int().nonnegative().optional(),delta:rt.number().int().optional()}),bt=rt.object({area:st,key:rt.string(),beforePresent:rt.boolean(),afterPresent:rt.boolean(),numericDeltas:rt.record(ht).optional(),booleanChanges:rt.record(wt).optional(),arrayLengthDeltas:rt.record(yt).optional()}),vt=rt.object({url:rt.string(),title:rt.string(),visibilityState:rt.string(),hasFocus:rt.boolean()}),xt=rt.object({navigatorWebdriver:rt.boolean().optional(),userAgentContainsHeadless:rt.boolean(),languagesLength:rt.number().int().nonnegative(),pluginsLength:rt.number().int().nonnegative(),hasChromeRuntime:rt.boolean(),permissionQueryIsNative:rt.boolean().optional(),hasPlaywrightBinding:rt.boolean(),hasPwInitScripts:rt.boolean(),cdcKeys:rt.array(rt.string()),webdriverKeys:rt.array(rt.string()),automationLikeWindowKeys:rt.array(rt.string())}),St=rt.object({phase:ut,success:rt.boolean(),durationMs:rt.number().int().nonnegative(),error:rt.string().optional()}),Ct=rt.object({phase:dt,capturedAt:rt.string(),targetFound:rt.boolean(),page:at.optional(),urlChangedFromPrevious:rt.boolean(),titleChangedFromPrevious:rt.boolean(),previousUrl:rt.string().optional(),currentUrl:rt.string().optional(),previousTitle:rt.string().optional(),currentTitle:rt.string().optional()}),kt=rt.object({kind:mt,reason:gt,capturedAt:rt.string(),url:rt.string(),method:rt.string().optional(),resourceType:rt.string().optional(),status:rt.number().int().optional()}),At=rt.object({capturedAt:rt.string(),url:rt.string()}),It=rt.object({phase:ut.default("native").describe("诊断阶段。默认 native 只枚举原生 CDP target;需要显式传更深阶段才会 attach browser/page、监听网络、evaluate、读取检测指纹或读取 storage。"),targetPageId:rt.string().optional().describe("可选:通过 list_pages 或本工具 native 阶段看到的 BOSS 页面 pageId/targetId。"),watchMs:rt.number().int().min(500).max(1e4).default(3e3).describe("native-watch / browser-attach 后置观察 / network-watch / storage-summary 内部等待窗口,单位毫秒。"),networkEventLimit:rt.number().int().min(1).max(100).default(30).describe("network-watch 最多返回的相关 request/response 事件数。")}),Rt=rt.object({success:rt.boolean(),requestedPhase:ut,mode:rt.string(),nativePages:rt.array(at),targetPage:at.optional(),browserAttached:rt.boolean(),pageAttached:rt.boolean(),nativeTimeline:rt.array(Ct),networkEvents:rt.array(kt).optional(),navigationEvents:rt.array(At).optional(),evaluate:vt.optional(),detectorFingerprint:xt.optional(),storage:rt.object({localStorage:rt.array(ft),sessionStorage:rt.array(ft),cookies:rt.array(pt),counterDiffs:rt.array(bt)}).optional(),phases:rt.array(St),warnings:rt.array(rt.string())}),Mt=["_AEG_CNT","_ZP_CNT_","__local__sec__store___"],Pt=new Set(Mt);function Bt(e){if(null===e)return"null";if(Array.isArray(e))return"array";switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":default:return"string";case"object":return"object"}}function Et(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _t(e){try{return JSON.parse(e)}catch{return}}function Tt(e){const t=Object.fromEntries(Object.entries(e).filter(e=>"number"==typeof e[1])),n=Object.fromEntries(Object.entries(e).filter(e=>"boolean"==typeof e[1])),a=Object.fromEntries(Object.entries(e).filter(e=>Array.isArray(e[1])).map(([e,t])=>[e,t.length]));return{...Object.keys(t).length>0?{numericFields:t}:{},...Object.keys(n).length>0?{booleanFields:n}:{},...Object.keys(a).length>0?{arrayLengths:a}:{}}}function qt(e){return new Promise(t=>{setTimeout(t,e)})}function $t(e){return Pt.has(e)}function Nt(e,t){if(0===t.value.length)return{area:e,key:t.key,valueLength:0,valueKind:"empty"};const n=_t(t.value);if(void 0===n)return{area:e,key:t.key,valueLength:t.value.length,valueKind:"string"};const a=Bt(n),r=Et(n)&&$t(t.key)?Tt(n):{};return{area:e,key:t.key,valueLength:t.value.length,valueKind:"json",jsonKind:a,...Et(n)?{jsonTopLevelKeys:Object.keys(n)}:{},...Array.isArray(n)?{jsonArrayLength:n.length}:{},...r}}function Lt(e){return{name:e.name,domain:e.domain,path:e.path,expires:e.expires>0?new Date(1e3*e.expires).toISOString():"Session",valueLength:e.value.length,httpOnly:e.httpOnly,secure:e.secure,...void 0!==e.sameSite?{sameSite:e.sameSite}:{}}}async function zt(e,t){const n=Date.now();try{return{result:await t(),phaseResult:{phase:e,success:!0,durationMs:Date.now()-n}}}catch(t){return{phaseResult:{phase:e,success:!1,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}}}}function Ft(e,t,n){if(void 0!==t){const a=e.find(e=>e.targetId===t);return a?ve(a.url,"zhipin")?a:void n.push(`targetPageId "${t}" is not a zhipin page.`):void n.push(`targetPageId "${t}" not found in native pages.`)}const a=e.filter(e=>ve(e.url,"zhipin"));if(1===a.length)return a[0];0===a.length?n.push("No zhipin native page found. Open Boss first or pass targetPageId."):n.push("Multiple zhipin native pages found. Pass targetPageId to avoid ambiguity.")}function jt(e,t,n,a){const r=n?.url,o=n?.title,i=a?.currentUrl,s=a?.currentTitle;return{phase:t,capturedAt:(new Date).toISOString(),targetFound:void 0!==n,...void 0!==n?{page:Se(e,n)}:{},urlChangedFromPrevious:void 0!==i&&void 0!==r&&i!==r,titleChangedFromPrevious:void 0!==s&&void 0!==o&&s!==o,...void 0!==i?{previousUrl:i}:{},...void 0!==r?{currentUrl:r}:{},...void 0!==s?{previousTitle:s}:{},...void 0!==o?{currentTitle:o}:{}}}async function Ot(e,t,n,a){const r=await e.listNativePages();return jt(e,t,void 0!==n?r.find(e=>e.targetId===n):r.filter(e=>ve(e.url,"zhipin"))[0],a)}async function Dt(e,t,n,a,r){try{const o=t[t.length-1],i=await Ot(e,n,a,o);t.push(i),i.urlChangedFromPrevious&&r.push(`Target URL changed after ${n}: ${i.previousUrl??"(unknown)"} -> ${i.currentUrl??"(missing)"}.`)}catch(e){r.push(`Failed to capture native snapshot after ${n}: ${e instanceof Error?e.message:String(e)}.`)}}async function Ut(e,t,n,a,r,o){const i=t.length,s=Date.now();for(;;){await Dt(e,t,n,a,o);const i=r-(Date.now()-s);if(i<=0)break;await qt(Math.min(500,i))}return t.slice(i).some(e=>e.urlChangedFromPrevious)}function Vt(e){const t=e.toLowerCase();return t.includes("device-action-report")?"device-action-report":t.includes("boss_risk_report")?"boss-risk-report":t.includes("apm-fe.zhipin.com")||t.includes("/wapi/zpapm/actionlog/")?"apm-action-log":t.includes("zhipin-security")||t.includes("/security/")?"zhipin-security":void 0}async function Ht(e,t,n){const a=[],r=[],o=e=>{a.length<n&&a.push(e)},i=e=>{const t=e.url(),n=Vt(t);void 0!==n&&o({kind:"request",reason:n,capturedAt:(new Date).toISOString(),url:t,method:e.method(),resourceType:e.resourceType()})},s=e=>{const t=e.url(),n=Vt(t);if(void 0===n)return;const a=e.request();o({kind:"response",reason:n,capturedAt:(new Date).toISOString(),url:t,method:a.method(),resourceType:a.resourceType(),status:e.status()})},c=e=>{r.push({capturedAt:(new Date).toISOString(),url:e.url()})};e.on("request",i),e.on("response",s),e.on("framenavigated",c);try{await qt(t)}finally{e.off("request",i),e.off("response",s),e.off("framenavigated",c)}return{networkEvents:a,navigationEvents:r}}function Wt(e,t){const n=e.contexts().flatMap(e=>e.pages()).filter(e=>!e.isClosed()&&ve(e.url(),"zhipin"));return n.find(e=>e.url()===t.url)??n[0]}function Kt(e,t){return{networkEvents:e.flatMap(e=>e.networkEvents).slice(0,t),navigationEvents:e.flatMap(e=>e.navigationEvents)}}async function Zt(e,t){return await e.evaluate(e=>{const t="localStorage"===e?window.localStorage:window.sessionStorage;return Array.from({length:t.length},(e,n)=>{const a=t.key(n)??"";return{key:a,value:a.length>0?t.getItem(a)??"":""}}).filter(e=>e.key.length>0)},t)}async function Gt(e){return(await e.evaluate(e=>{const t=["localStorage","sessionStorage"],n=[];for(const a of t){const t="localStorage"===a?window.localStorage:window.sessionStorage;for(const r of e){const e=t.getItem(r);null!==e&&n.push({area:a,key:r,value:e})}}return n},Mt)).map(e=>Nt(e.area,{key:e.key,value:e.value}))}async function Yt(e){return await e.evaluate(()=>({url:location.href,title:document.title,visibilityState:document.visibilityState,hasFocus:document.hasFocus()}))}async function Jt(e){return await e.evaluate(()=>{const e=window,t=Object.keys(e),n=t.filter(e=>e.startsWith("cdc_")||e.includes("_cdc_")).slice(0,20),a=t.filter(e=>e.toLowerCase().includes("webdriver")).slice(0,20),r=t.filter(e=>{const t=e.toLowerCase();return t.includes("playwright")||t.includes("puppeteer")||t.includes("selenium")||t.includes("chromedriver")}).slice(0,20),o=navigator.permissions?.query,i="function"==typeof o?o.toString().includes("[native code]"):void 0;return{..."boolean"==typeof navigator.webdriver?{navigatorWebdriver:navigator.webdriver}:{},userAgentContainsHeadless:navigator.userAgent.toLowerCase().includes("headless"),languagesLength:navigator.languages?.length??0,pluginsLength:navigator.plugins?.length??0,hasChromeRuntime:"object"==typeof e.chrome&&null!==e.chrome&&"runtime"in e.chrome,...void 0!==i?{permissionQueryIsNative:i}:{},hasPlaywrightBinding:"__playwright__binding__"in e,hasPwInitScripts:"__pwInitScripts"in e,cdcKeys:n,webdriverKeys:a,automationLikeWindowKeys:r}})}function Xt(e){return new Map(e.map(e=>[`${e.area}:${e.key}`,e]))}function Qt(e,t){return[...new Set([...Object.keys(e??{}),...Object.keys(t??{})])]}function en(e,t){return{...void 0!==e?{before:e}:{},...void 0!==t?{after:t}:{},...void 0!==e&&void 0!==t?{delta:t-e}:{}}}function tn(e,t){return{...void 0!==e?{before:e}:{},...void 0!==t?{after:t}:{},...void 0!==e&&void 0!==t?{delta:t-e}:{}}}function nn(e,t){const n=Xt(e),a=Xt(t),r=[...new Set([...n.keys(),...a.keys()])],o=[];for(const e of r){const t=n.get(e),r=a.get(e),i=r??t;if(!i)continue;const s={};for(const e of Qt(t?.numericFields,r?.numericFields)){const n=t?.numericFields?.[e],a=r?.numericFields?.[e];n!==a&&(s[e]=en(n,a))}const c={};for(const e of Qt(t?.booleanFields,r?.booleanFields)){const n=t?.booleanFields?.[e],a=r?.booleanFields?.[e];n!==a&&(c[e]={...void 0!==n?{before:n}:{},...void 0!==a?{after:a}:{}})}const l={};for(const e of Qt(t?.arrayLengths,r?.arrayLengths)){const n=t?.arrayLengths?.[e],a=r?.arrayLengths?.[e];n!==a&&(l[e]=tn(n,a))}void 0!==t&&void 0!==r&&0===Object.keys(s).length&&0===Object.keys(c).length&&0===Object.keys(l).length||o.push({area:i.area,key:i.key,beforePresent:void 0!==t,afterPresent:void 0!==r,...Object.keys(s).length>0?{numericDeltas:s}:{},...Object.keys(c).length>0?{booleanChanges:c}:{},...Object.keys(l).length>0?{arrayLengthDeltas:l}:{}})}return o}async function an(e,t){const[n,a,r]=await Promise.all([Zt(e,"localStorage"),Zt(e,"sessionStorage"),e.context().cookies()]),o=[...n.filter(e=>$t(e.key)).map(e=>Nt("localStorage",e)),...a.filter(e=>$t(e.key)).map(e=>Nt("sessionStorage",e))];return{localStorage:n.map(e=>Nt("localStorage",e)),sessionStorage:a.map(e=>Nt("sessionStorage",e)),cookies:r.filter(e=>e.domain.includes("zhipin.com")||e.domain.includes("bosszhipin.com")).map(e=>Lt(e)),counterDiffs:nn(t,o)}}var rn=nt({name:"zhipin_diagnose_browser_state",description:"分阶段诊断 Boss 页面在 CDP attach、页面绑定、网络上报、evaluate、检测指纹、storage/cookie 读取时的状态;browser-attach 会追加 native URL 观察窗口;默认只做 native target 枚举,所有 storage/cookie 值均脱敏。",input:It,output:Rt,execute:async(e,t)=>{const n=e.phase??"native",a=e.watchMs??3e3,r=e.networkEventLimit??30,o=h(),i=p(),s=[],c=[],l=[];let u,d,m,g=!1,f=!1,w=e.targetPageId;t.logger.info(`Diagnosing zhipin browser state (phase: ${n})`);const y=await zt("native",async()=>await o.listNativePages());c.push(y.phaseResult);const b=y.result??[],v=b.map(e=>Se(o,e)),x=Ft(b,e.targetPageId,s);if(x&&(u=Se(o,x),w=x.targetId,l.push(jt(o,"native",x,void 0))),!y.phaseResult.success||"native"===n)return{success:y.phaseResult.success,requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};if("native-watch"===n)return await Ut(o,l,"native-watch",w,a,s),{success:y.phaseResult.success&&void 0!==w,requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};if(!x)return{success:!1,requestedPhase:n,mode:i.mode,nativePages:v,browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};const S=await zt("browser-attach",async()=>await i.getBrowser());c.push(S.phaseResult);const C=S.result;g=S.phaseResult.success,await Dt(o,l,"browser-attach",w,s);const k=await Ut(o,l,"browser-attach-watch",w,a,s);if(k&&s.push("Browser attach was followed by a native URL change; treat this account/browser profile as unsafe for Playwright-backed zhipin tools."),!S.phaseResult.success||"browser-attach"===n)return{success:c.every(e=>e.success)&&!k,requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};if(k)return{success:!1,requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};const A=[];let I;"network-watch"===n&&void 0!==C&&(I=Wt(C,x),I?A.push(Ht(I,a,r)):s.push("No attached zhipin page found before page-attach; network-watch starts after page-attach.")),o.rememberNativePageSelection("zhipin",x);const R=await zt("page-attach",async()=>await o.getPage("zhipin"));c.push(R.phaseResult);const M=R.result;if(f=R.phaseResult.success,M&&(u=await Ce(o,M)),await Dt(o,l,"page-attach",w,s),!R.phaseResult.success||!M){if("network-watch"===n&&A.length>0){const e=await zt("network-watch",async()=>Kt(await Promise.all(A),r));c.push(e.phaseResult),e.result&&(d=e.result.networkEvents,m=e.result.navigationEvents)}return{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,...void 0!==d?{networkEvents:d}:{},...void 0!==m?{navigationEvents:m}:{},phases:c,warnings:s}}if("page-attach"===n)return{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,phases:c,warnings:s};if("network-watch"===n){I!==M&&A.push(Ht(M,a,r));const e=await zt("network-watch",async()=>Kt(await Promise.all(A),r));return c.push(e.phaseResult),e.result&&(d=e.result.networkEvents,m=e.result.navigationEvents),await Dt(o,l,"network-watch",w,s),{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,...void 0!==d?{networkEvents:d}:{},...void 0!==m?{navigationEvents:m}:{},phases:c,warnings:s}}let P=[];if("storage-summary"===n){try{P=await Gt(M)}catch(e){s.push(`Failed to read storage counter baseline: ${e instanceof Error?e.message:String(e)}.`)}a>0&&await qt(a)}const B=await zt("page-evaluate",async()=>await Yt(M));c.push(B.phaseResult);const E=B.result;if(await Dt(o,l,"page-evaluate",w,s),!B.phaseResult.success||"page-evaluate"===n)return{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,...void 0!==E?{evaluate:E}:{},phases:c,warnings:s};const _=await zt("detector-fingerprint",async()=>await Jt(M));c.push(_.phaseResult);const T=_.result;if(await Dt(o,l,"detector-fingerprint",w,s),!_.phaseResult.success||"detector-fingerprint"===n)return{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,...void 0!==E?{evaluate:E}:{},...void 0!==T?{detectorFingerprint:T}:{},phases:c,warnings:s};const q=await zt("storage-summary",async()=>await an(M,P));c.push(q.phaseResult);const $=q.result;return await Dt(o,l,"storage-summary",w,s),{success:c.every(e=>e.success),requestedPhase:n,mode:i.mode,nativePages:v,...void 0!==u?{targetPage:u}:{},browserAttached:g,pageAttached:f,nativeTimeline:l,...void 0!==E?{evaluate:E}:{},...void 0!==T?{detectorFingerprint:T}:{},...void 0!==$?{storage:$}:{},phases:c,warnings:s}}});import{defineTool as on}from"@roll-agent/sdk";import{z as sn}from"zod";import{setTimeout as cn}from"node:timers/promises";async function ln(e,t=300,n=800){const a=Math.floor(Math.random()*(n-t))+t;await e.waitForTimeout(a)}async function un(e){const t=Math.random();let n;n=t<.5?800+1200*Math.random():t<.8?500+300*Math.random():t<.95?2e3+2e3*Math.random():4e3+2e3*Math.random(),await e.waitForTimeout(Math.floor(n))}async function dn(e,t){const n=t?.minDistance??50,a=t?.maxDistance??200,r=t?.direction??"both",o=Math.floor(Math.random()*(a-n))+n,i="up"===r?-1:"down"===r||Math.random()>.5?1:-1;await e.evaluate(e=>{window.scrollBy({top:e,behavior:"smooth"})},o*i),await ln(e,200,500)}function mn(e=.3){return Math.random()<e}var gn=".geek-item.selected";async function fn(e){try{await e.waitForSelector(gn,{timeout:5e3})}catch{return null}const t=await e.evaluate(()=>{const e=document.querySelector(".geek-item.selected");if(!e)return null;const t=e.getAttribute("data-id")??e.closest('[role="listitem"]')?.getAttribute("key")??"";return{conversationId:t,candidateId:e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??t,candidateName:e.querySelector('[class*="name"], .nickname, .geek-name, .candidate-name')?.textContent?.trim()??""}});return t&&"string"==typeof t.conversationId&&"string"==typeof t.candidateId&&0!==t.conversationId.length&&0!==t.candidateId.length?t:null}async function pn(e){const t=await e.evaluate(()=>{const e=[".chat-conversation",".conversation-box",".conversation-message"],t=[".base-info-single-detial .name-box",".base-info-content .name-box",".base-info-single-container .name-box",".base-info-content .base-name",".chat-user-name",".name-box",".base-name"];for(const n of e){const e=document.querySelector(n);if(e)for(const n of t){const t=e.querySelector(n)?.textContent?.trim()??"";if(t.length>0)return{candidateName:t}}}return null});return t&&"string"==typeof t.candidateName&&0!==t.candidateName.length?t:null}var hn="https://www.zhipin.com/web/geek/chat",wn=".chat-list-wrap, .geek-item",yn=new Set(["消息"]),bn="data-roll-chat-entry-target",vn="data-roll-chat-item-target";function xn(e){return e.trim().toLocaleLowerCase("zh-CN")}function Sn(e,t){const n=xn(e),a=xn(t);return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}function Cn(e,t){let n=0;for(const a of e)t.includes(a)&&(n+=1);return n}function kn(e,t){if(void 0!==t.conversationId){const n=e.find(e=>e.conversationId===t.conversationId);if(n)return n}const n=t.candidateName;if(n){const t=xn(n),a=e.filter(e=>e.name.length>0);let r=a.find(e=>xn(e.name)===t);if(r)return r;if(r=a.find(e=>{const n=xn(e.name);return n.includes(t)||t.includes(n)}),r)return r;const o=t.length<=2?1:t.length<=4?.75:.6;if(r=a.find(e=>{const n=xn(e.name);return Cn(t,n)>=Math.ceil(Math.min(t.length,n.length)*o)}),r)return r}if(void 0!==t.index)return e[t.index]}function An(e){return e.includes("/web/geek/chat")||e.includes("/web/chat")}async function In(e,t=1e4){try{return await e.waitForSelector(wn,{timeout:t}),!0}catch{return!1}}async function Rn(e,t){const n=(await e.listAttachedPages()).find(e=>e!==t&&An(e.url()));if(n)return await e.selectAttachedPage("zhipin",e.getPageId(n))}async function Mn(e,t){await e.evaluate(e=>{document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)})},t).catch(()=>{})}async function Pn(e,t){const n=e.locator(t).first();await n.scrollIntoViewIfNeeded(),await K(e,n),await n.hover(),await ln(e,200,400),await Z(e,n),await n.click()}async function Bn(e){const t=await e.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},n=t=>e.messageLabels.some(e=>t===e||t.includes(e));document.querySelectorAll(`[${e.markerAttr}]`).forEach(t=>{t.removeAttribute(e.markerAttr)});const a=Array.from(document.querySelectorAll('a[href*="/web/geek/chat"], a[href*="/web/chat"]'));for(const n of a)if(t(n))return n.setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`};const r=Array.from(document.querySelectorAll('a, button, [role="link"], [role="button"], span, div'));for(const a of r){if(n(a.textContent?.trim()??"")&&t(a))return a.setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`}}return{found:!1}},{markerAttr:bn,messageLabels:[...yn]});if(!t.found)return!1;try{return await Pn(e,t.selector),!0}finally{await Mn(e,bn)}}function En(e){return e instanceof Error&&/ERR_ABORTED/i.test(e.message)}async function _n(e){try{return await e.goto(hn,{waitUntil:"domcontentloaded"}),!0}catch(t){return!!En(t)&&(!!An(e.url())||await In(e,2e3))}}async function Tn(e,t){if(!await Bn(t))return!1;if(await In(t,5e3))return!0;const n=await Rn(e,t);return!!n&&await In(n,5e3)}async function qn(e,t){if(An(t.url())&&await In(t))return!0;const n=await Rn(e,t);if(n&&await In(n))return!0;if(await Tn(e,t))return!0;if(!await _n(t))return!1;if(await In(t))return!0;await cn(300);const a=await Rn(e,t);return!!a&&await In(a,5e3)}async function $n(e){return e.evaluate(()=>Array.from(document.querySelectorAll(".geek-item")).map((e,t)=>{const n=e.getAttribute("data-id")??e.closest('[role="listitem"]')?.getAttribute("key")??"",a=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??n,r=e.querySelector('[class*="name"], .nickname, .geek-name, .candidate-name'),o=r?.textContent?.trim()??"",i=e.querySelector(".source-job")?.textContent?.trim()??"",s=e.querySelector(".badge-count"),c=parseInt(s?.textContent?.trim()??"0",10)||0;return{conversationId:n,candidateId:a,name:o,index:t,position:i,hasUnread:c>0||null!==e.querySelector(".red-dot"),unreadCount:c,lastMessageTime:e.querySelector(".time, .time-shadow")?.textContent?.trim()??"",messagePreview:(e.querySelector(".push-text, .chat-last-msg")?.textContent?.trim()??"").slice(0,100)}}))}async function Nn(e,t){const n=await e.evaluate(e=>{document.querySelectorAll(`[${e.markerAttr}]`).forEach(t=>{t.removeAttribute(e.markerAttr)});const t=Array.from(document.querySelectorAll(".geek-item")),n=t.find(t=>(t.getAttribute("data-id")??t.closest('[role="listitem"]')?.getAttribute("key")??"")===e.targetConversationId)??t[e.targetIndex];if(!n)return{found:!1};return(n.querySelector(".chat-item-content")??n).setAttribute(e.markerAttr,"true"),{found:!0,selector:`[${e.markerAttr}="true"]`}},{markerAttr:vn,targetConversationId:t.conversationId,targetIndex:t.index});if(!n.found)return!1;try{return await Pn(e,n.selector),!0}finally{await Mn(e,vn)}}async function Ln(e,t){if(0===t.conversationId.length&&0===t.name.length)return await ln(e,500,900),!0;try{return await e.waitForFunction(e=>{const t=e=>e.trim().toLocaleLowerCase("zh-CN"),n=document.querySelector(".geek-item.selected"),a=n?.getAttribute("data-id")??n?.closest('[role="listitem"]')?.getAttribute("key")??"",r=0===e.conversationId.length||a===e.conversationId,o=(()=>{const e=[".chat-conversation",".conversation-box",".conversation-message"],t=[".base-info-single-detial .name-box",".base-info-content .name-box",".base-info-single-container .name-box",".base-info-content .base-name",".chat-user-name",".name-box",".base-name"];for(const n of e){const e=document.querySelector(n);if(e)for(const n of t){const t=e.querySelector(n)?.textContent?.trim()??"";if(t.length>0)return t}}return""})(),i=0===e.candidateName.length||((e,n)=>{const a=t(e),r=t(n);return a.length>0&&r.length>0&&(a===r||a.includes(r)||r.includes(a))})(e.candidateName,o);return r&&i},{conversationId:t.conversationId,candidateName:t.name},{timeout:5e3}),!0}catch{return await ln(e,800,1200),!1}}async function zn(e,t,n){if(void 0===n.conversationId&&void 0===n.candidateName&&void 0===n.index)return;if(!await qn(e,t))return{found:!1,conversationId:"",candidateId:"",name:"",index:-1,position:"",hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:"消息列表未加载"};const a=await e.getPage("zhipin"),r=kn(await $n(a),n);if(!r){return{found:!1,conversationId:"",candidateId:"",name:"",index:-1,position:"",hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:`未找到候选人: ${n.conversationId??n.candidateName??`index ${n.index}`}`}}if(!await Nn(a,r))return{...r,found:!1,error:`打开候选人聊天失败: ${r.name||`index ${r.index}`}`};let o=await Ln(a,r);if(!o){await Nn(a,r)&&(o=await Ln(a,r))}if(!o)return{...r,found:!1,error:`打开候选人聊天后,右侧会话未同步切换到 ${r.name||r.conversationId}`};const i=await fn(a);if(!i||i.conversationId!==r.conversationId)return{...r,found:!1,error:`当前选中会话与目标会话不一致: ${r.name||r.conversationId}`};const s=await pn(a);return!(r.name.length>0)||s&&Sn(r.name,s.candidateName)?{...r,found:!0}:{...r,found:!1,error:`右侧聊天面板仍未切换到 ${r.name}`}}var Fn=["chat-list","chat-history","recommend-list"],jn={"chat-list":{surface:"chat-list",defaultDirection:"down",containerSelectors:[".chat-user .user-container",".chat-user .b-scroll-stable",".chat-list-wrap",".chat-user"],itemSelector:".geek-item",highlightSelector:".chat-user .user-container, .chat-list-wrap, .chat-user"},"chat-history":{surface:"chat-history",defaultDirection:"up",containerSelectors:[".conversation-message",".chat-message-list",".conversation-main",".conversation-box"],itemSelector:".chat-message-list > .message-item, .conversation-message .message-item",highlightSelector:".conversation-message, .chat-message-list, .conversation-main"},"recommend-list":{surface:"recommend-list",defaultDirection:"down",containerSelectors:[".recommend-list-wrap",".recommend-list",".candidate-list",".geek-list",".list-wrap",".recommendV2"],itemSelector:".candidate-card-wrap, [data-geek], .geek-item",highlightSelector:".candidate-card-wrap, [data-geek], .geek-item"}};function On(e){return jn[e]}var Dn=["target-count","boundary","no-new-items","max-steps"],Un=4,Vn=700,Hn=2,Wn=2;function Kn(e){return e.direction??"down"}function Zn(e){const t=e.steps??Un;return Math.max(0,Math.floor(t))}function Gn(e){return Math.max(0,Math.floor(e.settleMs??Vn))}function Yn(e,t){return"up"===t?e.atStart:e.atEnd}async function Jn(e,t){return await e.evaluate(e=>{const t=e=>{const t=window.getComputedStyle(e).overflowY;return"hidden"!==t&&"clip"!==t&&e.scrollHeight>e.clientHeight+2},{element:n,label:a,found:r}=(()=>{for(const n of e.containerSelectors){const e=document.querySelector(n);if(e&&t(e))return{element:e,label:n,found:!0}}const n=document.querySelector(e.itemSelector);let a=n?.parentElement??null;for(;a&&a!==document.body&&a!==document.documentElement;){if(t(a))return{element:a,label:"item-ancestor",found:!0};a=a.parentElement}const r=document.scrollingElement??document.documentElement;return{element:r,label:"document",found:r.scrollHeight>r.clientHeight+2}})(),o=Math.max(0,n.scrollTop),i=o<=2,s=o>=Math.max(0,n.scrollHeight-n.clientHeight)-2;return{containerFound:r,containerLabel:a,scrollTop:o,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,itemCount:document.querySelectorAll(e.itemSelector).length,atStart:i,atEnd:s}},t)}async function Xn(e,t,n={}){const a=Kn(n),r=Zn(n),o=Gn(n),i=n.stopOnBoundary??!0,s=await Jn(e,t);let c=s,l=0;for(let s=0;s<r&&(!i||!Yn(c,a));s++)c=await e.evaluate(e=>{const t=e=>{const t=window.getComputedStyle(e).overflowY;return"hidden"!==t&&"clip"!==t&&e.scrollHeight>e.clientHeight+2},{element:n,label:a,found:r}=(()=>{for(const n of e.containerSelectors){const e=document.querySelector(n);if(e&&t(e))return{element:e,label:n,found:!0}}const n=document.querySelector(e.itemSelector);let a=n?.parentElement??null;for(;a&&a!==document.body&&a!==document.documentElement;){if(t(a))return{element:a,label:"item-ancestor",found:!0};a=a.parentElement}const r=document.scrollingElement??document.documentElement;return{element:r,label:"document",found:r.scrollHeight>r.clientHeight+2}})(),o=e.distance??Math.max(120,Math.floor(.85*n.clientHeight)),i="up"===e.direction?-o:o;n.scrollBy({top:i,behavior:"auto"});const s=Math.max(0,n.scrollTop),c=Math.max(0,n.scrollHeight-n.clientHeight);return{containerFound:r,containerLabel:a,scrollTop:s,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,itemCount:document.querySelectorAll(e.itemSelector).length,atStart:s<=2,atEnd:s>=c-2}},{...t,direction:a,distance:n.distance}),l+=1,o>0&&await e.waitForTimeout(o),c=await Jn(e,t);return{success:s.containerFound||c.containerFound,direction:a,stepsRequested:r,stepsCompleted:l,reachedBoundary:Yn(c,a),before:s,after:c}}async function Qn(e,t,n,a,r={}){const o=Kn(r),i=Zn(r),s=Gn(r),c=r.targetCount,l=r.maxNoNewRounds??Hn,u=Math.max(0,Math.floor(r.boundaryLoadRetries??Wn)),d=Math.max(0,Math.floor(r.boundarySettleMs??s)),m=await Jn(e,t),g=new Map;let f=0,p=0,h=m,w=0,y="max-steps";const b=async()=>{let e=0;const t=await n();for(const n of t){const t=a(n);void 0!==t&&0!==t.length&&(g.has(t)?f+=1:(g.set(t,n),e+=1))}return e};await b();for(let n=0;n<i;n++){if(void 0!==c&&g.size>=c){y="target-count";break}if(Yn(h,o)){let n=!1;for(let a=0;a<u;a++){d>0&&await e.waitForTimeout(d);const a=await b(),r=await Jn(e,t),i=a>0||r.scrollHeight>h.scrollHeight||r.itemCount>h.itemCount||!Yn(r,o);if(h=r,i){a>0&&(p=0),n=!0;break}}if(!n){y="boundary";break}if(void 0!==c&&g.size>=c){y="target-count";break}}if(p>=l){y="no-new-items";break}const n=await Xn(e,t,{direction:o,steps:1,settleMs:s,...void 0!==r.distance?{distance:r.distance}:{},...void 0!==r.stopOnBoundary?{stopOnBoundary:r.stopOnBoundary}:{}});w+=n.stepsCompleted,h=n.after;p=await b()>0?0:p+1}return void 0!==c&&g.size>=c?y="target-count":w>=i&&(y="max-steps"),{success:m.containerFound||h.containerFound,direction:o,stepsRequested:i,stepsCompleted:w,reachedBoundary:Yn(h,o),before:m,after:h,items:[...g.values()],uniqueCount:g.size,duplicateCount:f,noNewRounds:p,stopReason:y}}function ea(e){return"function"==typeof e.page}function ta(e){return ea(e)?e.page():e}var na=class{page;target;constructor(e){this.page=ta(e),this.target=e}async retarget(e){if(e===this.target)return this.page=ta(e),this.target=e,!0;const t=this.page,n=this.target;return await ue(t,{target:n}),this.page=ta(e),this.target=e,!0}async begin(e,t="info"){return await ie(this.page,{label:e,tone:t,target:this.target})}async highlightSelector(e,t={}){return await ce(this.page,e,{...t,target:this.target})}async highlightLocator(e,t={}){return await se(this.page,e,{...t,target:this.target})}async succeed(e,t){return await le(this.page,{label:e,...void 0!==t?{lingerMs:t}:{},status:"success",target:this.target})}async fail(e,t){return await le(this.page,{label:e,...void 0!==t?{lingerMs:t}:{},status:"error",target:this.target})}async clear(){return await ue(this.page,{target:this.target})}},aa=sn.object({name:sn.string(),conversationId:sn.string(),candidateId:sn.string(),position:sn.string(),time:sn.string(),preview:sn.string(),unreadCount:sn.number(),hasUnread:sn.boolean(),index:sn.number()}),ra=sn.object({success:sn.boolean(),candidates:sn.array(aa),total:sn.number(),stats:sn.object({withName:sn.number(),withUnread:sn.number()})});function oa(e){return e.conversationId.length>0?e.conversationId:e.candidateId.length>0?e.candidateId:0!==e.name.length?[e.name,e.position,e.lastMessageTime].join("|"):void 0}var ia=on({name:"zhipin_read_messages",description:"读取 BOSS直聘消息列表,默认返回全部候选人;若只看未读消息,传 onlyUnread=true",input:sn.object({limit:sn.number().optional().describe("最多返回条数"),onlyUnread:sn.boolean().default(!1).describe("是否只返回有未读消息的候选人;用户说“全部/所有消息列表”时应为 false,说“未读消息”时应为 true"),sortBy:sn.enum(["time","unreadCount","name"]).default("time"),autoScroll:sn.boolean().default(!0).describe("是否自动向下滚动消息列表并合并采集结果"),maxScrolls:sn.number().int().min(0).max(50).default(4).describe("自动滚动的最大步数")}),output:ra,execute:async(e,t)=>{const n=e.onlyUnread??!1;t.logger.info(`Reading zhipin messages (limit: ${e.limit??"all"}, onlyUnread: ${n})`);const a=h(),r=await a.getPage("zhipin"),o=new na(r),i=n?"正在读取未读消息列表":"正在读取消息列表";await o.begin("正在打开消息列表");try{const s=await qn(a,r),c=await a.getPage("zhipin");if(await o.retarget(c),!s)return await o.fail("未找到消息列表"),{success:!1,candidates:[],total:0,stats:{withName:0,withUnread:0}};await o.begin(i),await o.highlightSelector(".user-list.b-scroll-stable, .chat-user .user-container, .chat-list-wrap",{label:i,padding:8});const l=e.autoScroll??!0,u=e.maxScrolls??4,d=n||void 0===e.limit?{}:{targetCount:e.limit},m=(l&&u>0?(await Qn(c,On("chat-list"),()=>$n(c),oa,{direction:"down",steps:u,...d})).items:await $n(c)).map(e=>({name:e.name,conversationId:e.conversationId,candidateId:e.candidateId,position:e.position,time:e.lastMessageTime,preview:e.messagePreview,unreadCount:e.unreadCount,hasUnread:e.hasUnread,index:e.index}));let g=n?m.filter(e=>e.hasUnread):m;const f=e.sortBy??"time";"time"===f||("unreadCount"===f?g.sort((e,t)=>t.unreadCount-e.unreadCount):"name"===f&&g.sort((e,t)=>e.name.localeCompare(t.name))),void 0!==e.limit&&(g=g.slice(0,e.limit));const p={withName:m.filter(e=>e.name.length>0).length,withUnread:m.filter(e=>e.hasUnread).length};return await o.succeed(n?`已读取 ${g.length} 条未读消息`:`已读取 ${g.length} 条消息`),t.logger.info(`Found ${g.length} candidates (${p.withUnread} with unread)`),{success:!0,candidates:g,total:m.length,stats:p}}catch(e){throw await o.fail("读取消息列表失败"),e}}});import{defineTool as sa}from"@roll-agent/sdk";import{BrowserPageInfoSchema as ca}from"@roll-agent/browser";import{z as la}from"zod";var ua={login:{notLoggedIn:".header-login-btn"},unread:{container:".chat-list-wrap",listItem:'[role="listitem"]',geekItemWrap:".geek-item-wrap",item:".chat-item",unreadBadge:".badge-count",unreadBadgeNew:".badge-count.badge-count-common-less",unreadBadgeSpan:".badge-count span",unreadDot:".red-dot",figure:".figure",badge:".badge",candidateName:".candidate-name",candidateNameAlt:".chat-item-name",candidateNameSelectors:'[class*="name"], .nickname, .geek-name',candidateNameNew:".geek-name",jobTitle:".source-job",lastMessage:".push-text",lastMessageAlt:".chat-last-msg",messageTime:".time, .time-shadow",clickArea:".chat-item-content",unreadCandidates:".geek-item"},chat:{chatContainer:".chat-container",messageList:".message-list",messageItem:".message-item",messageContent:".message-content",messageText:".text-content",userMessage:".message-right",candidateMessage:".message-left",messageTime:".message-time",senderName:".sender-name",inputBox:".chat-input",inputTextarea:"textarea.chat-input",inputEditorId:"#boss-chat-editor-input",sendButton:".btn-send",conversationEditor:".conversation-editor",submitButton:".submit-content .submit",submitButtonActive:".submit-content .submit.active",submitContent:".submit-content",sendButtonAlt:".conversation-editor .submit-content",sendIcon:".submit-content .icon-send",systemMessage:".system-msg"},chatDetails:{candidateInfoContainer:".base-info-single-container, .base-info-content",candidateName:".name-box, .geek-name, .base-name",candidateInfoItem:".geek-info-item, .base-info-item, .base-info-single-detial > div",candidateTag:".geek-tag, .high-light-boss",communicationPosition:".position-name",communicationPositionAlt:".position-item:not(.expect) .value.high-light-boss",candidateExpectContainer:".position-item.expect",candidateExpectValue:".position-item.expect .value.job",candidateExpectSalary:".position-item.expect .high-light-orange",candidatePosition:".geek-position, .position-name",candidatePositionAlt:".position-content .value, .position-item .value",chatMessageContainer:".conversation-message, .message-list",messageItem:".message-item",messageTime:".message-time .time",messageTextSpan:".text span",systemMessage:".item-system",friendMessage:".item-friend",myMessage:".item-myself",resumeMessage:".item-resume",readStatus:".status-read"},exchangeWechat:{exchangeButtonPath:"#container > div:nth-child(1) > div > div.chat-box > div.chat-container > div.chat-conversation > div.conversation-box > div.conversation-operate > div.toolbar-box > div.toolbar-box-right > div.operate-exchange-left > div:nth-child(3) > span.operate-btn",exchangeButtonFallback:".operate-exchange-left .operate-btn",confirmDialog:".exchange-tooltip",confirmButton:".exchange-tooltip .btn-box .boss-btn-primary.boss-btn",confirmButtonPath:"#container > div:nth-child(1) > div > div.chat-box > div.chat-container > div.chat-conversation > div.conversation-box > div.conversation-operate > div.toolbar-box > div.toolbar-box-right > div.operate-exchange-left > div:nth-child(3) > div > div > span.boss-btn-primary.boss-btn",cancelButton:".exchange-tooltip .btn-box .boss-btn-outline.boss-btn",wechatCard:".message-card-top-wrap",wechatCardAlt:'[class*="d-top-text"]'},username:{primary:".nav-item.nav-logout .user-name",fallbacks:["#header > div > div > div.nav-item.nav-logout > div.top-profile-logout.ui-dropmenu.ui-dropmenu-drop-arrow > div.ui-dropmenu-label > div > span.user-name",".ui-dropmenu-label .user-name",".nav-logout .user-name","#header .user-name",".top-profile .user-name",".nav-user .user-name",".user-name",'[class*="user-name"]','[class*="username"]','[data-qa="user-name"]',".header-user-name","#header .label-name"]},nav:{sidebar:".side-wrap.side-wrap-v2",chatLink:'.side-wrap.side-wrap-v2 a[href*="/web/chat/index"]',recommendLink:'.side-wrap.side-wrap-v2 a[href*="/web/geek/recommend"]'},recommend:{iframe:"#recommendFrame",resumeIframe:'iframe[src*="c-resume"]',filterButton:".recommend-filter .filter-label, .filter-label-wrap .filter-label, .filter-label",filterPanel:".filter-panel",candidateItem:"[data-geek], .geek-item",candidateName:".name",candidateBaseInfo:".base-info",workExps:".timeline-wrap.work-exps",expectInfo:".row-flex, .timeline-wrap.expect",salaryWrap:".salary-wrap",tagsWrap:".tags-wrap",greetButton:".btn-greet, .op-btn",resumeCanvas:"div#resume > canvas#resume, canvas#resume",closeResumeBtn:".close-btn, .dialog-close",closeResumeBtnV2:".recommendV2 .close-btn"},candidateProfile:{panel:".candidate-info, .resume-info, .geek-info",name:".candidate-info .name, .geek-info .name",age:".candidate-info .age, .geek-info .age",gender:".candidate-info .gender, .geek-info .gender",experience:".candidate-info .experience, .geek-info .work-exp",education:".candidate-info .education, .geek-info .edu",expectedSalary:".candidate-info .salary, .geek-info .expect-salary",expectedPosition:".candidate-info .position, .geek-info .expect-position",activeTime:".candidate-info .active-time, .geek-info .active"}},da={chat:"沟通",recommend:"推荐牛人"};function ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ga(e){for(const t of e)try{if(await t.count()>0&&await t.first().isVisible())return t.first()}catch{}return null}function fa(e){return da[e]}async function pa(e,t){const n=e.locator(ua.nav.sidebar).first(),a=fa(t),r=new RegExp(`^${ma(a)}(?:\\s|$)`),o="recommend"===t?[ua.nav.recommendLink]:[ua.nav.chatLink],i=[n.getByRole("link",{name:r}).first(),...o.map(e=>n.locator(e).first()),n.locator(`a:has-text("${a}")`).first(),e.getByRole("link",{name:r}).first()];return await ga(i)}function ha(e){return!!e.url().includes("/web/geek/recommend")||(null!==e.frame("recommendFrame")||e.frames().some(e=>e.url().includes("recommend")))}async function wa(e){if(e.url().includes("/web/chat/index"))return!0;try{const t=e.locator("#container.chat-container-private").first();return await t.count()>0&&await t.isVisible()}catch{return!1}}async function ya(e,t=1e4,n=250){const a=Date.now()+t;for(;Date.now()<a;){if(ha(e))return!0;if(e.isClosed())return!1;await e.waitForTimeout(Math.min(n,Math.max(a-Date.now(),0)))}return ha(e)}async function ba(e,t=1e4,n=250){const a=Date.now()+t;for(;Date.now()<a;){if(await wa(e))return!0;if(e.isClosed())return!1;await e.waitForTimeout(Math.min(n,Math.max(a-Date.now(),0)))}return await wa(e)}var va,xa=la.object({success:la.boolean(),alreadyOnChat:la.boolean(),usedSidebarClick:la.boolean(),chatReady:la.boolean(),page:ca.optional(),error:la.string().optional()});function Sa(){return{getContextManager:h,findZhipinSidebarSectionLink:pa,isZhipinChatSurfaceOpen:wa,waitForZhipinChatSurface:ba,moveVisualCursorToLocator:K,showVisualClickOnLocator:Z,randomDelay:ln,toAttachedPageInfo:Ce,createVisualActivitySession:e=>new na(e),...va}}async function Ca(e,t,n){return await t.toAttachedPageInfo(e,n)}async function ka(e,t,n,a,r,o){return await n.fail(r),{success:!1,...o,page:await Ca(e,t,a),error:r}}async function Aa(e,t,n,a){await n.scrollIntoViewIfNeeded(),await t.moveVisualCursorToLocator(e,n,{durationMs:110,settleMs:30}),await n.hover(),await t.randomDelay(e,100,180),await t.showVisualClickOnLocator(e,n,{pulseDurationMs:180}),await n.click(),a.info("Clicked Boss sidebar nav: 沟通")}var Ia=sa({name:"zhipin_open_chat_page",description:"通过点击 Boss 左侧导航切换回「沟通」页,避免让编排器依赖站内 URL 猜测。",input:la.object({}),output:xa,execute:async(e,t)=>{const n=Sa(),a=n.getContextManager();t.logger.info("Opening Boss chat page via sidebar navigation");const r=await a.getPage("zhipin");await r.bringToFront().catch(()=>{});const o=n.createVisualActivitySession(r),i="正在切换到沟通页";if(await o.begin(i),await o.highlightSelector(ua.nav.sidebar,{label:i,padding:10}),await n.isZhipinChatSurfaceOpen(r))return await o.succeed("已在沟通页"),{success:!0,alreadyOnChat:!0,usedSidebarClick:!1,chatReady:!0,page:await Ca(a,n,r)};const s=await n.findZhipinSidebarSectionLink(r,"chat");if(!s)return await ka(a,n,o,r,"未找到沟通导航",{alreadyOnChat:!1,usedSidebarClick:!1,chatReady:!1});try{await Aa(r,n,s,t.logger)}catch(e){return await ka(a,n,o,r,e instanceof Error?e.message:"点击沟通导航失败",{alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!1})}return await n.waitForZhipinChatSurface(r)?(await o.succeed("已切换到沟通页"),{success:!0,alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!0,page:await Ca(a,n,r)}):await ka(a,n,o,r,"沟通页未就绪",{alreadyOnChat:!1,usedSidebarClick:!0,chatReady:!1})}});import{defineTool as Ra}from"@roll-agent/sdk";import{z as Ma}from"zod";var Pa=Ma.object({success:Ma.boolean(),conversationId:Ma.string(),candidateId:Ma.string(),candidateName:Ma.string(),index:Ma.number(),hasUnread:Ma.boolean(),unreadCount:Ma.number(),lastMessageTime:Ma.string(),messagePreview:Ma.string(),error:Ma.string().optional()}),Ba=Ra({name:"zhipin_open_chat",description:"打开指定候选人的聊天窗口(优先按 conversationId,其次姓名,最后才用索引)",input:Ma.object({conversationId:Ma.string().optional().describe("会话 ID。若已从 `zhipin_read_messages` 获取,优先传这个,最稳定"),candidateName:Ma.string().optional().describe("候选人姓名。若用户说“打开鲁倩的聊天”,这里应提取为“鲁倩”"),index:Ma.number().optional().describe("候选人在列表中的索引。仅在缺少 conversationId 时兜底"),preferUnread:Ma.boolean().default(!1).describe("优先选择有未读消息的候选人")}),output:Pa,execute:async(e,t)=>{t.logger.info(`Opening chat: name=${e.candidateName??"N/A"}, index=${e.index??"N/A"}`);const n=h(),a=await n.getPage("zhipin");let r={conversationId:e.conversationId,candidateName:e.candidateName,index:e.index};if(e.preferUnread&&void 0===e.conversationId&&void 0===e.candidateName&&void 0===e.index){if(!await qn(n,a))return{success:!1,conversationId:"",candidateId:"",candidateName:"",index:-1,hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:"消息列表未加载"};const e=await n.getPage("zhipin"),t=(await $n(e)).find(e=>e.hasUnread);t&&(r={conversationId:t.conversationId,candidateName:t.name,index:t.index})}const o=await zn(n,a,r);return o&&o.found?(t.logger.info(`Opened chat with ${o.name} (index: ${o.index})`),{success:!0,conversationId:o.conversationId,candidateId:o.candidateId,candidateName:o.name,index:o.index,hasUnread:o.hasUnread,unreadCount:o.unreadCount,lastMessageTime:o.lastMessageTime,messagePreview:o.messagePreview}):{success:!1,conversationId:"",candidateId:"",candidateName:e.candidateName??"",index:e.index??-1,hasUnread:!1,unreadCount:0,lastMessageTime:"",messagePreview:"",error:o?.error??`未找到候选人: ${e.candidateName??`index ${e.index}`}`}}});import{defineTool as Ea}from"@roll-agent/sdk";import{z as _a}from"zod";var Ta="·",qa=/[--—–]/;function $a(e){return(e??"").trim()}function Na(e){const t=$a(e);if(!t||!qa.test(t))return;const[n=""]=t.split(qa);return $a(n)||void 0}function La(e){const t=$a(e);if(!t)return{expectedLocation:"",expectedPosition:""};const[n="",a=""]=t.split(Ta).map(e=>$a(e));return{expectedLocation:n,expectedPosition:a}}function za(e){const t=$a(e.communicationPosition),{expectedLocation:n,expectedPosition:a}=La(e.expectedJobText),r=Na(t);return{communicationPosition:t,expectedLocation:n,expectedPosition:a,...void 0!==r?{preferredBrand:r}:{}}}var Fa=_a.object({index:_a.number(),sender:_a.enum(["candidate","recruiter","system"]),messageType:_a.enum(["text","system","resume","wechat-exchange"]),content:_a.string(),time:_a.string()}),ja=_a.object({name:_a.string(),age:_a.string(),experience:_a.string(),education:_a.string(),communicationPosition:_a.string(),expectedPosition:_a.string(),expectedLocation:_a.string(),expectedSalary:_a.string(),tags:_a.array(_a.string())}),Oa=_a.object({success:_a.boolean(),conversationId:_a.string(),candidateId:_a.string(),candidateInfo:ja,preferredBrand:_a.string().optional(),chatMessages:_a.array(Fa),formattedHistory:_a.array(_a.string()),stats:_a.object({totalMessages:_a.number(),candidateMessages:_a.number(),recruiterMessages:_a.number(),systemMessages:_a.number()}),error:_a.string().optional()});function Da(){return{name:"",age:"",experience:"",education:"",communicationPosition:"",expectedPosition:"",expectedLocation:"",expectedSalary:"",tags:[]}}function Ua(e){return{success:!1,conversationId:"",candidateId:"",candidateInfo:Da(),chatMessages:[],formattedHistory:[],stats:{totalMessages:0,candidateMessages:0,recruiterMessages:0,systemMessages:0},error:e}}function Va(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var Ha=Ea({name:"zhipin_get_candidate_info",description:"提取候选人资料和完整聊天记录。可指定 conversationId 或 candidateName 自动打开对应聊天;若已从 `zhipin_read_messages` 获取 conversationId,优先传它。",input:_a.object({conversationId:_a.string().optional().describe("会话 ID。若已从 `zhipin_read_messages` 获取,优先传这个,最稳定"),candidateName:_a.string().optional().describe("候选人姓名。若用户说“查看鲁倩的聊天详情”,这里应提取为“鲁倩”"),index:_a.number().optional().describe("候选人在列表中的索引(可选,仅兜底)"),maxMessages:_a.number().default(100).describe("最多返回的消息条数")}),output:Oa,execute:async(e,t)=>{const n=e.maxMessages??100,a=h(),r=await a.getPage("zhipin"),o=new na(r),i=void 0!==e.conversationId||void 0!==e.candidateName||void 0!==e.index?"正在打开目标聊天":"正在准备当前聊天",s="正在提取聊天记录",c=async(e,t)=>(await o.fail(e),Ua(t));await o.begin(i);try{const i=await zn(a,r,{conversationId:e.conversationId,candidateName:e.candidateName,index:e.index}),l=await a.getPage("zhipin");if(await o.retarget(l),i&&!i.found)return await c("打开聊天失败",i.error??"打开聊天失败");t.logger.info("Extracting candidate info"+(i?` for ${i.name}`:" (current window)")),await o.begin(s),await o.highlightSelector(".chat-conversation, .conversation-box, .conversation-message",{label:s,padding:12});const u=i?.name??e.candidateName??"",d=await pn(l);if(u.length>0&&(!d||!Va(u,d.candidateName)))return await c("聊天面板未同步",`右侧聊天面板未切换到 ${u}`);const m=await fn(l);if(!m)return await c("未识别当前会话","未能提取当前选中聊天的 conversationId/candidateId");if(i&&m.conversationId!==i.conversationId)return await c("当前会话不一致",`当前选中会话与目标会话不一致: ${i.name||i.conversationId}`);if(d&&m.candidateName.length>0&&!Va(m.candidateName,d.candidateName))return await c("左右面板不一致",`左侧选中会话与右侧聊天面板不一致: ${m.candidateName} / ${d.candidateName}`);try{await l.waitForSelector(".chat-message-list .message-item, .conversation-message .message-item",{timeout:8e3})}catch{}const g=await l.evaluate(e=>{const t=document.querySelector(".chat-conversation")??document.querySelector(".conversation-box")??document,n=t.querySelector(".base-info-single-detial, .base-info-content, .base-info-single-container"),a=n?.querySelector(".name-box, .base-name, .chat-user-name, .geek-name")?.textContent?.trim()??"",r=n?n.querySelectorAll(":scope > div"):t.querySelectorAll(".geek-info-item, .base-info-item"),o=[];r.forEach(e=>{const t=e.textContent?.trim();t&&o.push(t)});const i=o.join(" "),s=i.match(/(\d{2,3})岁/),c=s?s[1]+"岁":"",l=i.match(/(\d+年(?:以上)?|应届生|在校生)/),u=l?.[1]??"",d=i.match(/(初中|高中|中专|大专|本科|硕士|博士)/)?.[1]??"";let m="";const g=t.querySelector(".position-name");if(g){const e=g.cloneNode(!0);e.querySelectorAll(".popover-wrap, .tooltip-job").forEach(e=>e.remove()),m=e.textContent?.trim()??""}let f="";const p=t.querySelector(".position-item.expect .value.job");p&&(f=p.textContent?.trim()??"");const h=t.querySelector(".position-item.expect .high-light-orange")?.textContent?.trim()??"",w=[];n&&n.querySelectorAll(".geek-tag, .base-info-item .high-light-boss").forEach(e=>{const t=e.textContent?.trim();t&&!t.includes("更换职位")&&t.length<20&&w.push(t)});const y=t.querySelectorAll(".chat-message-list > .message-item, .conversation-message .message-item"),b=/\d{1,2}:\d{2}(?::\d{2})?|\d{4}-\d{2}-\d{2}/,v=[];let x=0;return y.forEach(t=>{if(x>=e)return;const n=null!==t.querySelector(".item-friend"),a=null!==t.querySelector(".item-myself"),r=null!==t.querySelector(".item-system"),o=null!==t.querySelector(".item-resume"),i=null!==t.querySelector(".message-dialog-center");let s="system",c="text";n?s="candidate":a?s="recruiter":(r||i)&&(s="system",c="system"),o&&(c="resume");const l=t.querySelector(".message-card-top-wrap, [class*='d-top-text']");if(l){const e=l.textContent??"";(e.includes("微信")||e.includes("WeChat"))&&(c="wechat-exchange")}const u=t.querySelector(".message-time .time, .message-time"),d=(u?.textContent??"").match(b),m=d?d[0]:"";let g="";if("wechat-exchange"===c&&l){const e=l.textContent??"",t=e.match(/\b(\d{8,15})\b/),n=e.match(/微信[::号]*\s*([a-zA-Z0-9_-]{5,20})/);g=t?`[微信号: ${t[1]}]`:n?`[微信号: ${n[1]}]`:"[交换微信]"}else if(l){const e=t.querySelector(".message-card-top-title"),n=t.querySelector(".dialog-content, .message-card-top-text");g=(e?.textContent?.trim()??n?.textContent?.trim()??"").trim()}else{const e=t.querySelector(".text span, .text-content, .text");e&&(g=(e.textContent?.trim()??"").replace(b,"").replace("已读","").trim())}(g||"text"!==c)&&(v.push({index:x,sender:s,messageType:c,content:g,time:m}),x++)}),{candidateInfo:{name:a,age:c,experience:u,education:d,communicationPosition:m,expectedJobText:f,expectedSalary:h,tags:w},messages:v}},n),f=za({communicationPosition:g.candidateInfo.communicationPosition,expectedJobText:g.candidateInfo.expectedJobText}),p=g.messages.filter(e=>"candidate"===e.sender||"recruiter"===e.sender).map(e=>`${"candidate"===e.sender?"求职者":"我"}: ${e.content}`),h={totalMessages:g.messages.length,candidateMessages:g.messages.filter(e=>"candidate"===e.sender).length,recruiterMessages:g.messages.filter(e=>"recruiter"===e.sender).length,systemMessages:g.messages.filter(e=>"system"===e.sender).length};return await o.succeed(`已提取 ${h.totalMessages} 条聊天记录`),t.logger.info(`Extracted info for ${g.candidateInfo.name}: ${h.totalMessages} messages`),{success:!0,conversationId:m.conversationId,candidateId:m.candidateId,candidateInfo:{name:g.candidateInfo.name,age:g.candidateInfo.age,experience:g.candidateInfo.experience,education:g.candidateInfo.education,communicationPosition:f.communicationPosition,expectedPosition:f.expectedPosition,expectedLocation:f.expectedLocation,expectedSalary:g.candidateInfo.expectedSalary,tags:g.candidateInfo.tags},...void 0!==f.preferredBrand?{preferredBrand:f.preferredBrand}:{},chatMessages:g.messages,formattedHistory:p,stats:h}}catch(e){throw await o.fail("提取聊天记录失败"),e}}});import{defineTool as Wa}from"@roll-agent/sdk";import{z as Ka}from"zod";var Za=30,Ga=new Set(["招聘规范","消息","首页","推荐牛人","看简历","我的客服","面试","招聘数据","账号权益","升级VIP","职位","职位管理","牛人","公司","数据统计","设置","帮助中心","登录","注册","退出登录","退出","BOSS直聘","下载APP","搜索","发布职位"]);function Ya(e){const t=e.trim();return!(0===t.length||t.length>Za)&&(!Ga.has(t)&&!/登录|注册|退出|下载|帮助|设置|管理/.test(t))}function Ja(e){const t=[],n=/(link|button|menuitem|img|heading)\s+"([^"]+)"/g;let a;for(;null!==(a=n.exec(e));){const e=a[2]?.trim()??"";e.length>0&&t.push({role:a[1]??"",name:e})}return t}function Xa(e){let t=e.priority;return Ga.has(e.text.trim())&&(t+=10),e.text.trim().length>10&&(t+=5),/^[\u4e00-\u9fff]{2,4}$/.test(e.text.trim())&&(t-=.5),void 0!==e.xRatio&&(t-=4*(e.xRatio-.5)),t}function Qa(e){const t=e.filter(e=>Ya(e.text));if(0===t.length)return{found:!1};const n=new Map;for(const e of t){const t=e.text.trim(),a=n.get(t)??new Set;a.add(e.strategy),n.set(t,a)}const a=t.map(e=>{let t=Xa(e);const a=n.get(e.text.trim())?.size??1;return a>1&&(t-=.5*a),{evidence:e,score:t}}).sort((e,t)=>e.score-t.score)[0];return a?{found:!0,username:a.evidence.text.trim(),strategy:a.evidence.strategy,source:a.evidence.source}:{found:!1}}async function er(e){const t=[e.getByRole("banner"),e.locator("header").first(),e.getByRole("navigation").first(),e.locator("#header")];for(const e of t)try{if(await e.count()>0&&await e.first().isVisible())return e.first()}catch{}return null}async function tr(e,t,n,a){const r=[],o=t.viewportSize(),i=o?.width??1280;try{const t=await e.getByRole(n).all();for(const e of t)try{if(!await e.isVisible())continue;const t=(await e.textContent()??"").trim();if(t.length>0&&t.length<=Za){let o;try{const t=await e.boundingBox();t&&(o=(t.x+t.width/2)/i)}catch{}r.push({text:t,strategy:a,priority:1,source:`role:${n}`,xRatio:o})}}catch{}}catch{}return r}async function nr(e){const t=[];try{const n=Ja(await e.ariaSnapshot({timeout:3e3}));for(const{role:e,name:a}of n)a.length>0&&a.length<=Za&&t.push({text:a,strategy:"aria-snapshot",priority:2,source:`aria:${e}:${a}`})}catch{}return t}async function ar(e){const t=[];try{const n=await e.evaluate((e,t)=>{const n=[],a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode.textContent?.trim();e&&e.length>0&&e.length<=t&&n.push(e)}return n},Za);for(const e of n)t.push({text:e,strategy:"leaf-text",priority:3,source:"leaf-text"})}catch{}return t}async function rr(e){const t=[];try{const n=[ua.username.primary,...ua.username.fallbacks],a=await e.evaluate(e=>e.map(e=>{try{return{selector:e,text:document.querySelector(e)?.textContent?.trim()??""}}catch{return{selector:e,text:""}}}),n);for(const{selector:e,text:n}of a)n.length>0&&n.length<=Za&&t.push({text:n,strategy:"css-fallback",priority:4,source:e})}catch{}return t}async function or(e){const t=await er(e),n=t?(await Promise.all([tr(t,e,"link","role-link"),tr(t,e,"button","role-button"),nr(t)])).flat():[],a=Qa(n);if(a.found){const e=a.username;if(new Set(n.filter(t=>t.text.trim()===e).map(e=>e.strategy)).size>=2)return n}const r=(await Promise.all([t?ar(t):Promise.resolve([]),rr(e)])).flat();return[...n,...r]}async function ir(e,t=or){const n=Qa(await t(e));if(!n.found)throw new Error("未找到用户名,请确认当前页面已登录招聘者账号。");return{platform:"zhipin",username:n.username,strategy:n.strategy,source:n.source}}function sr(e,t){return void 0!==t.accountId?e.accountId===t.accountId:e.username===t.username}import{z as cr}from"zod";var lr="reply-authority-service",ur="browser-use-agent/zhipin_send_reply",dr="zhipin",mr=60,gr=cr.object({platform:cr.literal(dr),username:cr.string().min(1),accountId:cr.string().min(1).optional()}),fr=cr.object({v:cr.literal(2),iss:cr.literal(lr),kid:cr.string().min(1),jti:cr.string().min(1),iat:cr.number().int(),exp:cr.number().int(),aud:cr.literal(ur),platform:cr.literal(dr),tenantId:cr.string().min(1),conversationId:cr.string().min(1),candidateId:cr.string().min(1),reply:cr.string(),policyVersion:cr.string().min(1),recruiterBinding:gr}),pr=cr.object({kid:cr.string().min(1),algorithm:cr.literal("Ed25519"),publicKey:cr.string().min(1),validFrom:cr.string().min(1),validUntil:cr.string().optional()}),hr=cr.object({keys:cr.array(pr)}),wr=new Map;function yr(e){for(const[t,n]of wr)n<e-mr&&wr.delete(t)}function br(e,t=Math.floor(Date.now()/1e3)){return yr(t),wr.has(e)}function vr(e,t,n=Math.floor(Date.now()/1e3)){yr(n),wr.set(e,t)}import{createPublicKey as xr,verify as Sr}from"node:crypto";var Cr=new Map,kr=null;function Ar(){const e=process.env.REPLY_AUTHORITY_KEYS_URL?.trim();if(!e)throw new Error("REPLY_AUTHORITY_KEYS_URL 未配置,browser-use-agent 无法拉取 Reply Authority 公钥。");return e}function Ir(e){return Cr=new Map(e.map(e=>[e.kid,e]))}async function Rr(){if(kr)return kr;kr=(async()=>{const e=await fetch(Ar()),t=await e.json();if(!e.ok)throw new Error(`Reply Authority 公钥拉取失败 (${e.status})`);return Ir(hr.parse(t).keys)})();try{return await kr}finally{kr=null}}async function Mr(){await Rr()}async function Pr(e){const t=Cr.get(e);if(t)return t;const n=(await Rr()).get(e);if(!n)throw new Error(`Unknown key ID: ${e}`);return n}function Br(e){if("object"==typeof e&&null!==e&&"v"in e&&"number"==typeof e.v&&2!==e.v)throw new Error("unexpected envelope version")}function Er(e){const t=e.split("."),n=t[0],a=t[1];if(2!==t.length||void 0===n||void 0===a||0===n.length||0===a.length)throw new Error("Invalid signed envelope format");let r,o="";try{o=Buffer.from(n,"base64url").toString("utf-8")}catch{throw new Error("Invalid signed envelope format")}try{r=JSON.parse(o)}catch{throw new Error("Envelope payload schema validation failed")}Br(r);const i=fr.safeParse(r);if(!i.success)throw new Error("Envelope payload schema validation failed");return{payload:i.data,payloadJson:o,signatureBase64:a}}function _r(e,t){if(e.exp<=e.iat)throw new Error("Envelope expiry must be after issue time");if(e.exp<t-mr)throw new Error("Envelope expired");if(e.iat>t+mr)throw new Error("Envelope issued in the future")}async function Tr(e,t=Math.floor(Date.now()/1e3)){const n=Er(e),a=await Pr(n.payload.kid),r=xr({key:Buffer.from(a.publicKey,"base64url"),format:"der",type:"spki"});if(!Sr(null,Buffer.from(n.payloadJson,"utf-8"),r,Buffer.from(n.signatureBase64,"base64url")))throw new Error("Signature verification failed");return _r(n.payload,t),n.payload}var qr=Ka.object({success:Ka.boolean(),sentMessage:Ka.string(),error:Ka.string().optional()});function $r(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var Nr=Wa({name:"zhipin_send_reply",description:"发送消息。只接受由 Reply Authority Service 签发的 signedEnvelope;可指定 candidateName 自动打开对应聊天后发送,或不传则发送到当前选中的聊天窗口。",input:Ka.object({signedEnvelope:Ka.string().describe("Reply Authority Service 返回的紧凑签名信封"),candidateName:Ka.string().optional().describe("候选人姓名。若用户说“回复鲁倩”,这里应提取为“鲁倩”"),index:Ka.number().optional().describe("候选人在列表中的索引(可选)")}),output:qr,execute:async(e,t)=>{let n="";if(!b()){const e="Reply Authority 公钥尚未成功预加载,当前无法发送签名回复。请检查启动日志、`REPLY_AUTHORITY_KEYS_URL` 配置,以及 `browser_status.replyAuthorityKeysLoaded`。";return t.logger.error(e),{success:!1,sentMessage:n,error:e}}const a=h(),r=await a.getPage("zhipin");let o=r;try{const i=await Tr(e.signedEnvelope);if(n=i.reply,br(i.jti))return{success:!1,sentMessage:n,error:"token 已消费,禁止重放"};const s=await zn(a,r,{conversationId:i.conversationId,candidateName:e.candidateName,index:e.index});if(s&&!s.found)return{success:!1,sentMessage:n,error:s.error};if(!s){if(!await qn(a,r))return{success:!1,sentMessage:n,error:"消息列表未加载"}}o=await a.getPage("zhipin");const c=await pn(o),l=await fn(o);if(!l)return{success:!1,sentMessage:n,error:"未能提取当前聊天的 conversationId/candidateId"};if(c&&l.candidateName.length>0&&!$r(l.candidateName,c.candidateName))return{success:!1,sentMessage:n,error:`左侧选中会话与右侧聊天面板不一致: ${l.candidateName} / ${c.candidateName}`};if(l.conversationId!==i.conversationId||l.candidateId!==i.candidateId)return{success:!1,sentMessage:n,error:"发送目标与签名不匹配"};const u=await ir(o);if(!sr(u,i.recruiterBinding))return{success:!1,sentMessage:n,error:`recruiter 绑定不匹配:当前账号 ${u.username} 与签发时 ${i.recruiterBinding.username} 不一致`};t.logger.info(`Sending message (${n.length} chars) to ${l.candidateName||l.candidateId}`);const d="#boss-chat-editor-input, textarea.chat-input, .chat-input";await o.waitForSelector(d,{timeout:5e3});const m=o.locator(d).first();await K(o,m);await o.evaluate(e=>{const t=document.querySelector(e);return"true"===t?.getAttribute("contenteditable")},d)?(await m.focus(),await o.evaluate(e=>{const t=document.querySelector(e.sel);t&&(t.innerHTML=e.msg.split("\n").map(e=>`<p>${e}</p>`).join(""))},{sel:d,msg:n}),await m.dispatchEvent("input",{bubbles:!0})):await o.fill(d,n),await ln(o,200,500);const g=await o.evaluate(()=>{document.querySelectorAll("[data-roll-send-btn]").forEach(e=>{e.removeAttribute("data-roll-send-btn")});const e=[".submit-content .submit.active",".submit-content .submit",".submit-content",".btn-send"];for(const t of e){const e=document.querySelector(t);if(e&&e.offsetWidth>0)return{found:!0,selector:t}}const t=Array.from(document.querySelectorAll("span"));for(const e of t)if("发送"===e.textContent?.trim()&&e.offsetWidth>0)return e.setAttribute("data-roll-send-btn","true"),{found:!0,selector:'[data-roll-send-btn="true"]'};return{found:!1}});if(!g.found)return{success:!1,sentMessage:n,error:"未找到发送按钮"};const f=o.locator(g.selector).first();return await f.scrollIntoViewIfNeeded(),await K(o,f),await f.hover(),await un(o),await Z(o,f),await f.click(),await ln(o,500,1200),vr(i.jti,i.exp),t.logger.info("Message sent successfully"),{success:!0,sentMessage:n}}catch(e){return{success:!1,sentMessage:n,error:e instanceof Error?e.message:String(e)}}finally{await o.evaluate(()=>{document.querySelectorAll("[data-roll-send-btn]").forEach(e=>{e.removeAttribute("data-roll-send-btn")})}).catch(()=>{})}}});import{defineTool as Lr}from"@roll-agent/sdk";import{z as zr}from"zod";var Fr=zr.object({success:zr.boolean(),exchanged:zr.boolean(),wechatNumber:zr.string().optional(),error:zr.string().optional()}),jr="data-roll-wechat-btn",Or="data-roll-confirm-btn";function Dr(e,t){const n=e.trim().toLocaleLowerCase("zh-CN"),a=t.trim().toLocaleLowerCase("zh-CN");return n.length>0&&a.length>0&&(n===a||n.includes(a)||a.includes(n))}var Ur=Lr({name:"zhipin_exchange_wechat",description:'换微信。可指定 candidateName 自动打开对应聊天后执行,或不传则在当前窗口执行;例如"和鲁倩换微信"应提取 candidateName=鲁倩。',input:zr.object({conversationId:zr.string().optional().describe("会话 ID。若已从消息列表拿到,优先传这个"),candidateName:zr.string().optional().describe('候选人姓名。若用户说"和鲁倩换微信",这里应提取为"鲁倩"'),index:zr.number().optional().describe("候选人在列表中的索引(可选)")}),output:Fr,execute:async(e,t)=>{const n=h(),a=await n.getPage("zhipin"),r=await zn(n,a,{conversationId:e.conversationId,candidateName:e.candidateName,index:e.index});if(r&&!r.found)return{success:!1,exchanged:!1,error:r.error};t.logger.info("Starting WeChat exchange"+(r?` with ${r.name}`:""));const o=await n.getPage("zhipin");try{const e=await fn(o);if(!e)return{success:!1,exchanged:!1,error:"未选中聊天联系人,无法点击当前聊天输入区的「换微信」按钮"};const n=await pn(o);if(n&&e.candidateName.length>0&&!Dr(e.candidateName,n.candidateName))return{success:!1,exchanged:!1,error:`左侧选中会话与右侧聊天面板不一致: ${e.candidateName} / ${n.candidateName}`};if(!(await o.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},n=e=>e.replace(/\s+/g,"").trim();document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)});const a=[".chat-conversation .conversation-operate .operate-exchange-left span.operate-btn",".chat-conversation .conversation-operate span.operate-btn",".conversation-box .conversation-operate .operate-exchange-left span.operate-btn",".conversation-box .conversation-operate span.operate-btn",".conversation-operate .operate-exchange-left span.operate-btn",".conversation-operate .operate-exchange-left span"];for(const r of a){const a=Array.from(document.querySelectorAll(r));for(const r of a){const a=n(r.textContent??"");if("换微信"===a&&t(r))return r.setAttribute(e,"true"),{found:!0,text:a}}}return{found:!1}},jr)).found)return{success:!1,exchanged:!1,error:"未找到当前聊天输入区的「换微信」按钮"};await ln(o,200,400),await G(o,`[${jr}="true"]`),await Y(o,`[${jr}="true"]`),await o.click(`[${jr}="true"]`),await o.evaluate(()=>{document.querySelector("[data-roll-wechat-btn]")?.removeAttribute("data-roll-wechat-btn")}),await ln(o,400,800);let a=!1;for(let e=0;e<8;e++){if(await o.evaluate(()=>{const e=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0},t=document.querySelector(".exchange-tooltip");if(t&&e(t))return!0;const n=document.querySelectorAll("div, section, aside");for(const t of Array.from(n)){if((t.textContent??"").includes("交换微信")&&t.querySelector(".boss-btn-primary, .boss-btn")&&e(t))return!0}return!1})){a=!0;break}await ln(o,400,800)}if(!a)return{success:!1,exchanged:!1,error:"确认对话框未弹出"};await un(o);if(!(await o.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect();return t.width>0&&t.height>0};document.querySelectorAll(`[${e}]`).forEach(t=>{t.removeAttribute(e)});const n=document.querySelector(".exchange-tooltip");if(n){const a=[".btn-box .boss-btn-primary.boss-btn",".btn-box span.boss-btn-primary","span.boss-btn-primary",".boss-btn-primary"];for(const r of a){const a=n.querySelector(r);if(a&&t(a))return a.setAttribute(e,"true"),{found:!0,text:a.textContent?.trim()??""}}}const a=document.querySelectorAll("div, section, aside");for(const n of Array.from(a)){if(!(n.textContent??"").includes("交换微信"))continue;const a=n.querySelectorAll("span.boss-btn-primary, button.boss-btn-primary, span.boss-btn, button.boss-btn");for(const n of Array.from(a)){const a=n.textContent?.trim()??"";if("确定"===a&&t(n))return n.setAttribute(e,"true"),{found:!0,text:a}}}return{found:!1}},Or)).found)return{success:!1,exchanged:!1,error:"未找到确认按钮"};await ln(o,200,400),await G(o,`[${Or}="true"]`),await Y(o,`[${Or}="true"]`),await o.click(`[${Or}="true"]`),await o.evaluate(()=>{document.querySelector("[data-roll-confirm-btn]")?.removeAttribute("data-roll-confirm-btn")}),await ln(o,1500,2500);const r=await o.evaluate(()=>{const e=[".message-card-top-wrap",'[class*="d-top-text"]',".message-card-top-title"];for(const t of e){const e=Array.from(document.querySelectorAll(t));for(let t=e.length-1;t>=0;t--){const n=e[t]?.textContent??"",a=n.match(/\b(\d{8,15})\b/);if(a)return a[1];const r=n.match(/微信[::号]*\s*([a-zA-Z0-9_-]{5,20})/);if(r)return r[1];const o=n.match(/\b([a-zA-Z][a-zA-Z0-9_-]{5,19})\b/);if(o&&!["微信","WeChat"].includes(o[1]))return o[1]}}const t=Array.from(document.querySelectorAll(".message-item"));for(let e=t.length-1;e>=0;e--){const n=t[e]?.querySelector('.message-card-top-wrap, [class*="d-top-text"]');if(n){const e=(n.textContent??"").match(/\b(\d{8,15})\b/);if(e)return e[1]}}return null});return t.logger.info("WeChat exchanged"+(r?`, number: ${r}`:"")),{success:!0,exchanged:!0,...null!==r?{wechatNumber:r}:{}}}catch(e){return{success:!1,exchanged:!1,error:e instanceof Error?e.message:String(e)}}finally{await o.evaluate(e=>{for(const t of e)document.querySelectorAll(`[${t}]`).forEach(e=>{e.removeAttribute(t)})},[jr,Or]).catch(()=>{})}}});import{defineTool as Vr}from"@roll-agent/sdk";import{z as Hr}from"zod";var Wr,Kr=Hr.object({success:Hr.boolean(),username:Hr.string(),usedSelector:Hr.string().optional(),usedStrategy:Hr.string().optional(),source:Hr.string().optional(),error:Hr.string().optional()});function Zr(){return{getContextManager:h,findHeaderScope:er,getCurrentZhipinRecruiterIdentity:ir,createVisualActivitySession:e=>new na(e),...Wr}}var Gr=Vr({name:"zhipin_get_username",description:"获取当前登录的招聘者用户名",input:Hr.object({}),output:Kr,execute:async(e,t)=>{t.logger.info("Getting zhipin username");const n=Zr();let a;try{const e=n.getContextManager(),r=await e.getPage("zhipin");a=n.createVisualActivitySession(r),await r.bringToFront().catch(()=>{}),await a.begin("正在识别登录账号");const o=await n.findHeaderScope(r);o&&await a.highlightLocator(o,{label:"正在识别登录账号",padding:10});const i=await n.getCurrentZhipinRecruiterIdentity(r);return await a.succeed(`已识别账号:${i.username}`),t.logger.info(`Username: ${i.username} (strategy: ${i.strategy}, source: ${i.source})`),{success:!0,username:i.username,usedSelector:"css-fallback"===i.strategy?i.source:void 0,usedStrategy:i.strategy,source:i.source}}catch(e){return await(a?.fail("获取用户名失败")),{success:!1,username:"",error:e instanceof Error?`获取用户名失败:${e.message}`:"获取用户名失败"}}}});import{defineTool as Yr}from"@roll-agent/sdk";import{z as Jr}from"zod";var Xr=".candidate-card-wrap",Qr="[data-geek], .geek-item",eo=`${Xr}, ${Qr}`;function to(e){return e.evaluate(e=>document.querySelectorAll(e.primarySelector).length>0?e.primarySelector:e.fallbackSelector,{primarySelector:Xr,fallbackSelector:Qr})}function no(e){return e.frame("recommendFrame")??e.frames().find(e=>e.url().includes("recommend"))??e}async function ao(e,t=1e4){try{return await e.waitForSelector(eo,{timeout:t}),!0}catch{return!1}}async function ro(e,t){const n=await to(e),a=e.locator(n);if(await a.count()<=t)return{found:!1,cardSelector:n,candidateId:"",name:"",hasGreetButton:!1,error:"索引超出范围"};const r=a.nth(t),o=await r.evaluate(e=>{const t=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??"",n=e.querySelector(".name")?.textContent?.trim()??"",a=e.querySelector("button.btn.btn-greet");return{candidateId:t,name:n,hasGreetButton:null!==a&&a.offsetWidth>0}});return{found:!0,cardSelector:n,candidateId:o.candidateId,name:o.name,hasGreetButton:o.hasGreetButton}}var oo=Jr.object({containerFound:Jr.boolean(),containerLabel:Jr.string(),scrollTop:Jr.number(),scrollHeight:Jr.number(),clientHeight:Jr.number(),itemCount:Jr.number(),atStart:Jr.boolean(),atEnd:Jr.boolean()}),io=Jr.object({success:Jr.boolean(),surface:Jr.enum(Fn),direction:Jr.enum(["up","down"]),stepsRequested:Jr.number(),stepsCompleted:Jr.number(),reachedBoundary:Jr.boolean(),before:oo,after:oo,error:Jr.string().optional()});async function so(e){const t=h(),n=await t.getPage("zhipin");if("chat-list"===e){const e=await qn(t,n),a=await t.getPage("zhipin");return{target:a,session:new na(a),ready:e}}if("recommend-list"===e){const e=no(n),t=await ao(e);return{target:e,session:new na(e),ready:t}}try{const t=On(e);return await n.waitForSelector(t.itemSelector,{timeout:3e3}),{target:n,session:new na(n),ready:!0}}catch{return{target:n,session:new na(n),ready:!1}}}var co=Yr({name:"zhipin_scroll_view",description:"滚动 BOSS直聘页面内部动态列表容器。用于调试或显式翻页,支持 chat-list、chat-history、recommend-list。",input:Jr.object({surface:Jr.enum(Fn).describe("要滚动的页面区域"),direction:Jr.enum(["up","down"]).optional().describe("滚动方向;不传则使用该区域默认方向"),steps:Jr.number().int().min(1).max(20).default(1).describe("滚动步数"),distance:Jr.number().int().positive().optional().describe("每步滚动像素;不传则按容器高度估算"),settleMs:Jr.number().int().min(0).max(5e3).default(700).describe("每步后等待 DOM 更新的毫秒数")}),output:io,execute:async(e,t)=>{const n=On(e.surface),a=e.direction??n.defaultDirection,r=e.steps??1,o=e.settleMs??700,{target:i,session:s,ready:c}=await so(e.surface),l=`正在滚动 ${e.surface}`;if(await s.begin(l),await s.highlightSelector(n.highlightSelector,{label:l,padding:8}),!c){await s.fail("列表未加载");const t={containerFound:!1,containerLabel:"",scrollTop:0,scrollHeight:0,clientHeight:0,itemCount:0,atStart:!0,atEnd:!0};return{success:!1,surface:e.surface,direction:a,stepsRequested:r,stepsCompleted:0,reachedBoundary:!0,before:t,after:t,error:"列表未加载"}}try{const c=await Xn(i,n,{direction:a,steps:r,settleMs:o,...void 0!==e.distance?{distance:e.distance}:{}});return await s.succeed(`已滚动 ${c.stepsCompleted}/${c.stepsRequested} 步`),t.logger.info(`Scrolled ${e.surface}: ${c.stepsCompleted}/${c.stepsRequested}, items ${c.before.itemCount} -> ${c.after.itemCount}`),{success:c.success,surface:e.surface,direction:c.direction,stepsRequested:c.stepsRequested,stepsCompleted:c.stepsCompleted,reachedBoundary:c.reachedBoundary,before:c.before,after:c.after}}catch(e){throw await s.fail("滚动失败"),e}}});import{defineTool as lo}from"@roll-agent/sdk";import{z as uo}from"zod";var mo=["不限","男","女"],go=["不限","刚刚活跃","今日活跃","3日内活跃","本周活跃","本月活跃"],fo=["applied","recommend_not_ready","filter_not_found","requires_vip","age_not_applied","submit_failed","error"],po=16,ho=50,wo=650,yo=10,bo=.015,vo=["data-roll-recommend-filter-button","data-roll-recommend-filter-option","data-roll-recommend-filter-submit","data-roll-recommend-filter-age-track","data-roll-recommend-filter-age-min-handle","data-roll-recommend-filter-age-max-handle"],xo="active|selected|checked|current|choose|chosen",So="button, a, label, li, span, div, [role='button'], [role='radio']";async function Co(e,t,n,a){a&&(await a.moveToLocator(e,n,{durationMs:100,settleMs:25,target:t}),await a.showClickOnLocator(e,n,{pulseDurationMs:170,target:t}))}function ko(e,t,n={}){return{status:t,requested:e,...void 0!==n.applied?{applied:n.applied}:{},...void 0!==n.filterButtonText?{filterButtonText:n.filterButtonText}:{},...void 0!==n.error?{error:n.error}:{}}}async function Ao(e,t=1e4){try{return await e.waitForSelector(`${ua.recommend.filterButton}, .candidate-card-wrap, ${ua.recommend.candidateItem}`,{timeout:t}),!0}catch{return!1}}async function Io(e){try{const t=await e.locator(ua.recommend.filterButton).first().textContent({timeout:1e3});return t?.replace(/\s+/g," ").trim()}catch{return}}async function Ro(e){return await e.evaluate(()=>{const e=e=>(e??"").replace(/\s+/g," ").trim(),t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},n=n=>{const a=Array.from(n.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>t(e));for(const t of a){const n=e(t.textContent);if(/^(取消|不应用|否|关闭|稍后)$/.test(n))return t.click(),!0}return!1},a=Array.from(document.body.querySelectorAll("div, section, aside")).filter(e=>t(e)).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return n.width*n.height-a.width*a.height});for(const t of a){const a=e(t.textContent);if(a.includes("是否应用上次")||a.includes("上次的筛选条件"))return n(t)}return!1})}async function Mo(e,t,n){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=(e,t)=>{let n=e;for(;n&&n!==t.parentElement;){const e=n.tagName.toLowerCase(),t=n.getAttribute("role")??"";if("button"===e||"a"===e||"label"===e||"li"===e||"button"===t||"radio"===t)return n;n=n.parentElement}return e};document.querySelectorAll(`[${e.markerAttribute}]`).forEach(t=>t.removeAttribute(e.markerAttribute));const o=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!o)return!1;const i=Array.from(o.querySelectorAll("div, li, dl, dd, section, ul")).filter(a=>{const r=t(a.textContent);return n(a)&&r.includes(e.rowLabel)&&r.includes(e.optionLabel)}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length});for(const o of i){const i=Array.from(o.querySelectorAll(e.clickableOptionSelector)).filter(e=>n(e)).filter(n=>t(n.textContent)===e.optionLabel).sort((e,t)=>a(e)-a(t))[0];if(i)return r(i,o).setAttribute(e.markerAttribute,"1"),!0}return!1},{panelSelector:ua.recommend.filterPanel,rowLabel:t,optionLabel:n,markerAttribute:"data-roll-recommend-filter-option",clickableOptionSelector:So})}async function Po(e,t,n,a,r){if(!await Mo(e,n,a))return!1;try{const n=e.locator('[data-roll-recommend-filter-option="1"]').first();return await Co(t,e,n,r),await n.click({timeout:2e3}),await e.waitForTimeout(120),!0}catch{return!1}}async function Bo(e){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=e=>"string"==typeof e.className?e.className:"",o=e=>{const t=r(e),n=e.getAttribute("role")??"";return/slider|range|track|bar/i.test(t)||"slider"===n},i=e=>{const t=e.getBoundingClientRect(),n=r(e);return"slider"===(e.getAttribute("role")??"")||/handle|handler|button|thumb|slider-btn|dot|point|circle|knob/i.test(n)&&t.width<=80&&t.height<=80};for(const t of e.markerAttributes)document.querySelectorAll(`[${t}]`).forEach(e=>e.removeAttribute(t));const s=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!s)return{ok:!1,error:"未找到筛选面板"};const c=Array.from(s.querySelectorAll("div, li, section, dl, dd")).filter(e=>{const a=t(e.textContent);return n(e)&&a.includes("年龄")&&Array.from(e.querySelectorAll("*")).some(e=>o(e)||i(e))}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length})[0];if(!c)return{ok:!1,error:"未找到年龄滑块"};const l=Array.from(c.querySelectorAll(".vue-slider-dot")).filter(e=>n(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),u=Array.from(c.querySelectorAll("*")).filter(e=>n(e)&&i(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),d=l.length>=2?l:u;if(d.length<2)return{ok:!1,error:"未找到年龄滑块双手柄"};const m=d[0],g=d[d.length-1];if(!m||!g)return{ok:!1,error:"未找到年龄滑块双手柄"};const f=m.getBoundingClientRect(),p=g.getBoundingClientRect(),h=Math.max(40,p.left-f.left),w=Array.from(c.querySelectorAll(".vue-slider-rail, .vue-slider")).filter(e=>{if(!n(e))return!1;const t=e.getBoundingClientRect();return t.width>=h&&t.height<=80}).sort((e,t)=>{const n=r(e),a=r(t);if(/vue-slider-rail/.test(n)&&!/vue-slider-rail/.test(a))return-1;if(!/vue-slider-rail/.test(n)&&/vue-slider-rail/.test(a))return 1;const o=e.getBoundingClientRect(),i=t.getBoundingClientRect(),s=o.height-i.height;return 0!==s?s:i.width-o.width}),y=Array.from(c.querySelectorAll("*")).filter(e=>{if(!n(e)||!o(e))return!1;const t=e.getBoundingClientRect();return t.width>=Math.max(80,h)&&t.height<=80&&t.left<=f.left+f.width&&t.right>=p.right-p.width}).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect(),r=n.height-a.height;return 0!==r?r:a.width-n.width}),b=Array.from(c.querySelectorAll("*")).filter(e=>{if(!n(e)||!e.contains(m)||!e.contains(g))return!1;const t=e.getBoundingClientRect();return t.width>=h&&t.height<=140}).sort((e,t)=>{const n=a(e)-a(t);return 0!==n?n:e.getBoundingClientRect().height-t.getBoundingClientRect().height}),v=w[0]??y[0]??b[0];return v?(v.setAttribute("data-roll-recommend-filter-age-track","1"),m.setAttribute("data-roll-recommend-filter-age-min-handle","1"),g.setAttribute("data-roll-recommend-filter-age-max-handle","1"),{ok:!0,current:(e=>{const n=t(e),a=n.includes("年龄")?n.slice(n.indexOf("年龄")+2):n,r=Array.from(a.matchAll(/\d+/g),e=>Number.parseInt(e[0],10)).filter(e=>Number.isInteger(e)),o=r[0],i=a.includes("不限")?void 0:r[1];return{...void 0!==o?{ageMin:o}:{},...void 0!==i?{ageMax:i}:{}}})(t(c.textContent))}):{ok:!1,error:"未找到年龄滑块轨道"}},{panelSelector:ua.recommend.filterPanel,markerAttributes:vo})}async function Eo(e){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{if(e.includes("不限"))return;const t=e.match(/\d+/);return t?Number.parseInt(t[0],10):void 0},a=(e,t)=>{const n=e.style.left;if(n.endsWith("%")){const e=Number.parseFloat(n);if(Number.isFinite(e))return Math.max(0,Math.min(1,e/100))}const a=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(!(r.width<=0))return Math.max(0,Math.min(1,(a.left+a.width/2-r.left)/r.width))},r=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},o=e=>{const t=e.getBoundingClientRect();return t.width*t.height},i=e=>{const t=(e=>"string"==typeof e.className?e.className:"")(e),n=e.getAttribute("role")??"";return/slider|range|track|bar/i.test(t)||"slider"===n},s=Array.from(document.querySelectorAll(e)).filter(e=>r(e)).sort((e,t)=>o(e)-o(t))[0];if(!s)return{};const c=Array.from(s.querySelectorAll("div, li, section, dl, dd")).filter(e=>{const n=t(e.textContent);return r(e)&&n.includes("年龄")&&(/\d+|不限/.test(n)||Array.from(e.querySelectorAll("*")).some(i))}).sort((e,n)=>{const a=o(e)-o(n);return 0!==a?a:t(e.textContent).length-t(n.textContent).length})[0];if(!c)return{};const l=Array.from(c.querySelectorAll(".vue-slider-dot")).filter(e=>r(e)).sort((e,t)=>e.getBoundingClientRect().left-t.getBoundingClientRect().left),u=c.querySelector(".vue-slider-rail, .vue-slider");if(l.length>=2){const e=l[0],r=l[l.length-1],o=t(e?.querySelector(".vue-slider-dot-tooltip-text")?.textContent),i=t(r?.querySelector(".vue-slider-dot-tooltip-text")?.textContent),s=n(o),c=n(i);return{...void 0!==s?{ageMin:s}:{},...void 0!==c?{ageMax:c}:{},...u&&e?{minRatio:a(e,u)}:{},...u&&r?{maxRatio:a(r,u)}:{}}}return(e=>{const n=t(e),a=n.includes("年龄")?n.slice(n.indexOf("年龄")+2):n,r=Array.from(a.matchAll(/\d+/g),e=>Number.parseInt(e[0],10)).filter(e=>Number.isInteger(e)),o=r[0],i=a.includes("不限")?void 0:r[1];return{...void 0!==o?{ageMin:o}:{},...void 0!==i?{ageMax:i}:{}}})(t(c.textContent))},ua.recommend.filterPanel)}async function _o(e,t,n,a,r){if(!(await Bo(e)).ok)return!1;const o=e.locator('[data-roll-recommend-filter-age-track="1"]').first(),i="min"===n?'[data-roll-recommend-filter-age-min-handle="1"]':'[data-roll-recommend-filter-age-max-handle="1"]',s=e.locator(i).first(),c=await o.boundingBox();if(!c)return!1;const l=Math.max(0,Math.min(c.width,c.width*a)),u=Math.max(1,c.height/2);try{return r&&await r.moveToLocator(t,s,{durationMs:90,settleMs:20,target:e}),await s.dragTo(o,{force:!0,targetPosition:{x:l,y:u},timeout:2e3}),await e.waitForTimeout(wo),!0}catch{return!1}}function To(e){return Math.max(0,Math.min(1,(e-po)/(ho-po)))}function qo(e,t,n){return Math.max(t,Math.min(n,e))}async function $o(e,t,n,a,r){const o=await Eo(e),i=o.minRatio??0,s=o.maxRatio??1;let c="min"===n?0:Math.min(1,i+bo),l="min"===n?Math.max(0,s-bo):1,u=qo(To(a),c,l);for(let o=0;o<yo;o+=1){if(!await _o(e,t,n,u,r))return!1;const o=await Eo(e),i="min"===n?o.ageMin:o.ageMax;if(i===a)return!0;void 0===i?"max"===n?l=u:c=u:i<a?c=u:l=u;const s=(c+l)/2;if(Math.abs(s-u)<.001)break;u=qo(s,c,l)}const d=await Eo(e);return"min"===n?d.ageMin===a:d.ageMax===a}function No(e,t,n){return e.ageMin===t&&e.ageMax===n}async function Lo(e,t,n,a){const r=n.ageMin??po,o=n.ageMax,i=await Bo(e);if(!i.ok)return{success:!1,error:i.error};if(!await _o(e,t,"max",1,a))return{success:!1,error:"年龄上限无法重置为不限"};if(!await $o(e,t,"min",r,a))return{success:!1,error:`年龄下限无法设置为 ${r}`};if(void 0===o){if(!await _o(e,t,"max",1,a))return{success:!1,error:"年龄上限无法设置为不限"}}else if(!await $o(e,t,"max",o,a))return{success:!1,error:`年龄上限无法设置为 ${o}`};const s=await Eo(e);if(!No(s,r,o)){const e=void 0===s.ageMax?"不限":String(s.ageMax);return{success:!1,error:`年龄筛选未精确生效,当前为 ${s.ageMin??"未知"}-${e}`}}return{success:!0,state:s}}async function zo(e){return await e.evaluate(()=>{const e=e=>(e??"").replace(/\s+/g," ").trim(),t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},n=/(购买VIP|VIP账号|开通VIP|开启VIP|专享筛选特权|扫码支付|立即开通|支付金额)/;if(!Array.from(document.body.querySelectorAll("div, section, aside")).filter(a=>t(a)&&n.test(e(a.textContent))).sort((e,t)=>{const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return n.width*n.height-a.width*a.height})[0])return!1;const a=Array.from(document.querySelectorAll(".boss-dialog__close, .dialog-close, .close-btn, [class*='close'], button, span, i")).filter(e=>t(e));for(const t of a){const n=e(t.textContent),a="string"==typeof t.className?t.className:"";if("×"===n||"关闭"===n||/close/i.test(a)){t.click();break}}return!0})}async function Fo(e,t){return!!await zo(t)||!(t===e||!await zo(e))}async function jo(e,t,n){return await e.evaluate(e=>{const t=e=>(e??"").replace(/\s+/g," ").trim(),n=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity},a=e=>{const t=e.getBoundingClientRect();return t.width*t.height},r=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>n(e)).sort((e,t)=>a(e)-a(t))[0];if(!r)return e.fallback;const o=Array.from(r.querySelectorAll("div, li, dl, dd, section, ul")).filter(a=>{const r=t(a.textContent);return n(a)&&r.includes(e.rowLabel)}).sort((e,n)=>{const r=a(e)-a(n);return 0!==r?r:t(e.textContent).length-t(n.textContent).length})[0];if(!o)return e.fallback;return Array.from(o.querySelectorAll(e.clickableOptionSelector)).filter(t=>n(t)&&(t=>{const n="string"==typeof t.className?t.className:"";return new RegExp(e.selectedClassPattern,"i").test(n)||"true"===t.getAttribute("aria-checked")||"true"===t.getAttribute("aria-selected")})(t)).map(e=>t(e.textContent)).find(t=>""!==t&&t!==e.rowLabel)??e.fallback},{panelSelector:ua.recommend.filterPanel,rowLabel:t,fallback:n,selectedClassPattern:xo,clickableOptionSelector:So})}async function Oo(e,t,n){return{...void 0!==n.ageMin?{ageMin:n.ageMin}:{},...void 0!==n.ageMax?{ageMax:n.ageMax}:{},gender:await jo(e,"性别",t.gender),activity:await jo(e,"活跃度",t.activity)}}async function Do(e,t,n){if(!await e.evaluate(e=>{const t=e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity};document.querySelectorAll(`[${e.markerAttribute}]`).forEach(t=>t.removeAttribute(e.markerAttribute));const n=Array.from(document.querySelectorAll(e.panelSelector)).filter(e=>t(e))[0];if(!n)return!1;const a=Array.from(n.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>t(e)).find(e=>"确定"===(e.textContent??"").replace(/\s+/g," ").trim());return!!a&&(a.setAttribute(e.markerAttribute,"1"),!0)},{panelSelector:ua.recommend.filterPanel,markerAttribute:"data-roll-recommend-filter-submit"}))return!1;try{const a=e.locator('[data-roll-recommend-filter-submit="1"]').first();return await Co(t,e,a,n),await a.click({timeout:2e3}),await e.waitForSelector(ua.recommend.filterPanel,{state:"hidden",timeout:4e3}),await e.waitForTimeout(600),!0}catch{return!1}}async function Uo(e,t,n){const a=async()=>await e.evaluate(e=>{const t=e=>"string"==typeof e.className?e.className:"",n=e=>{const n=t(e),a=e.parentElement?t(e.parentElement):"",r=null!==e.closest(".recommend-filter, .filter-label-wrap, .filter-wrap")?"recommend-filter":"";let o=0;for(const e of[n,a,r])/recommend-filter/.test(e)?o+=3:/filter-label/.test(e)?o+=2:/filter/.test(e)&&(o+=1);return o};for(const t of e.markerAttributes)document.querySelectorAll(`[${t}]`).forEach(e=>e.removeAttribute(t));const a=[...Array.from(document.querySelectorAll(e.filterButtonSelector)),...Array.from(document.querySelectorAll("button, a, span, div, [role='button']")).filter(e=>/^筛选(?:·\d+)?$/.test((e.textContent??"").replace(/\s+/g," ").trim()))].filter(e=>(e=>{const t=e.getBoundingClientRect(),n=window.getComputedStyle(e);return t.width>0&&t.height>0&&"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity})(e)).sort((e,t)=>{const a=n(t)-n(e);if(0!==a)return a;const r=e.getBoundingClientRect(),o=t.getBoundingClientRect();return r.width*r.height-o.width*o.height})[0];return!!a&&(a.setAttribute(e.markerAttribute,"1"),!0)},{filterButtonSelector:ua.recommend.filterButton,markerAttribute:"data-roll-recommend-filter-button",markerAttributes:vo}),r=async()=>{try{const a=e.locator(ua.recommend.filterButton).first();if(await a.count()>0&&await a.isVisible())return await a.scrollIntoViewIfNeeded(),await Co(t,e,a,n),await a.click({timeout:2e3}),!0}catch{}if(!await a())return!1;const r=e.locator('[data-roll-recommend-filter-button="1"]').first();return await Co(t,e,r,n),await r.click({timeout:2e3}),!0};if(await(async()=>{try{const t=e.locator(ua.recommend.filterPanel).first();return await t.count()>0&&await t.isVisible()}catch{return!1}})())return!0;for(let t=0;t<3;t+=1){await Ro(e);try{if(await r())return await e.waitForSelector(ua.recommend.filterPanel,{state:"visible",timeout:4e3}),await Ro(e),!0}catch{}await e.waitForTimeout(300)}return!1}async function Vo(e,t,n,a){const r=await Ao(t,3e3);if(!await Uo(t,e,a))return ko(n,r?"filter_not_found":"recommend_not_ready",{error:r?"未找到或无法打开筛选按钮":"推荐牛人页未就绪"});if(await Fo(e,t))return ko(n,"requires_vip",{error:"筛选条件触发 VIP 弹窗"});if(!await Po(t,e,"性别",n.gender,a))return ko(n,"filter_not_found",{error:`未找到性别筛选项:${n.gender}`});if(!await Po(t,e,"活跃度",n.activity,a))return ko(n,"filter_not_found",{error:`未找到活跃度筛选项:${n.activity}`});const o=await Lo(t,e,n,a);if(!o.success)return ko(n,"age_not_applied",{error:o.error});if(await Fo(e,t))return ko(n,"requires_vip",{error:"年龄筛选触发 VIP 弹窗"});const i=await Oo(t,n,o.state);if(!await Do(t,e,a))return ko(n,"submit_failed",{applied:i,error:"筛选确认失败"});const s=await Io(t);return ko(n,"applied",{applied:i,...void 0!==s?{filterButtonText:s}:{}})}async function Ho(e,t,n,a){const r=await Vo(e,t,n,a);if(t!==e&&("filter_not_found"===r.status||"recommend_not_ready"===r.status)){const t=await Vo(e,e,n,a);if("filter_not_found"!==t.status&&"recommend_not_ready"!==t.status)return t}return r}var Wo,Ko=uo.object({ageMin:uo.number().int().min(16).optional(),ageMax:uo.number().int().min(16).optional(),gender:uo.enum(mo),activity:uo.enum(go)}),Zo=uo.object({ageMin:uo.number().optional(),ageMax:uo.number().optional(),gender:uo.string(),activity:uo.string()}),Go=uo.object({success:uo.boolean(),status:uo.enum(fo),requested:Ko,applied:Zo.optional(),filterButtonText:uo.string().optional(),error:uo.string().optional()}),Yo=uo.object({ageMin:uo.number().int().min(16).optional().describe("年龄下限;未传则重置为 16"),ageMax:uo.number().int().min(16).optional().describe("年龄上限;未传则重置为不限"),gender:uo.enum(mo).default("不限").describe("性别筛选,只支持:不限、男、女"),activity:uo.enum(go).default("不限").describe("活跃度[单选],只支持:不限、刚刚活跃、今日活跃、3日内活跃、本周活跃、本月活跃")}).refine(e=>void 0===e.ageMin||void 0===e.ageMax||e.ageMin<=e.ageMax,{path:["ageMax"],message:"ageMax must be greater than or equal to ageMin"});function Jo(){return{getContextManager:h,getRecommendTarget:no,waitForRecommendFilterSurface:Ao,applyRecommendFilter:Ho,moveVisualCursorToLocator:K,showVisualClickOnLocator:Z,createVisualActivitySession:e=>new na(e),...Wo}}function Xo(e){const t=e.gender??"不限",n=e.activity??"不限";return{...void 0!==e.ageMin?{ageMin:e.ageMin}:{},...void 0!==e.ageMax?{ageMax:e.ageMax}:{},gender:t,activity:n}}function Qo(e){return{success:"applied"===e.status,status:e.status,requested:e.requested,...void 0!==e.applied?{applied:e.applied}:{},...void 0!==e.filterButtonText?{filterButtonText:e.filterButtonText}:{},...void 0!==e.error?{error:e.error}:{}}}var ei=lo({name:"zhipin_filter_recommend_candidates",description:"在 BOSS「推荐牛人」页打开筛选面板,只设置年龄、性别、活跃度[单选] 三个维度并提交。",input:Yo,output:Go,execute:async(e,t)=>{const n=Jo(),a=Xo(e);t.logger.info(`Filtering Boss recommend candidates: gender=${a.gender}, activity=${a.activity}, ageMin=${a.ageMin??"16"}, ageMax=${a.ageMax??"不限"}`);const r=n.getContextManager(),o=await r.getPage("zhipin");await o.bringToFront().catch(()=>{});let i=n.getRecommendTarget(o);const s=n.createVisualActivitySession(i);await s.begin("正在打开推荐筛选");let c=await n.waitForRecommendFilterSurface(i);if(c||(i=n.getRecommendTarget(o),await s.retarget(i),c=await n.waitForRecommendFilterSurface(i,2500)),!c)return await s.fail("推荐牛人页未就绪"),Qo({status:"recommend_not_ready",requested:a,error:"推荐牛人页未就绪"});await s.retarget(i),await s.begin("正在设置推荐筛选"),await s.highlightSelector(ua.recommend.filterButton,{label:"正在设置推荐筛选",padding:8});const l=await n.applyRecommendFilter(o,i,a,{moveToLocator:n.moveVisualCursorToLocator,showClickOnLocator:n.showVisualClickOnLocator});return"applied"===l.status?await s.succeed("已应用推荐筛选"):await s.fail(l.error??l.status),Qo(l)}});import{defineTool as ti}from"@roll-agent/sdk";import{z as ni}from"zod";var ai,ri=ni.object({index:ni.number(),candidateId:ni.string(),name:ni.string(),age:ni.string(),experience:ni.string(),education:ni.string(),workStatus:ni.string(),company:ni.string(),currentPosition:ni.string(),expectedLocation:ni.string(),expectedPosition:ni.string(),expectedSalary:ni.string(),tags:ni.array(ni.string()),buttonText:ni.string()}),oi=ni.object({containerLabel:ni.string(),stepsRequested:ni.number(),stepsCompleted:ni.number(),reachedBoundary:ni.boolean(),stopReason:ni.enum(Dn),uniqueCount:ni.number(),duplicateCount:ni.number(),noNewRounds:ni.number(),beforeItemCount:ni.number(),afterItemCount:ni.number(),beforeScrollHeight:ni.number(),afterScrollHeight:ni.number()}),ii=ni.object({success:ni.boolean(),candidates:ni.array(ri),total:ni.number(),scrollStats:oi.optional(),error:ni.string().optional()});function si(){return{getContextManager:h,getRecommendTarget:no,waitForRecommendList:ao,createVisualActivitySession:e=>new na(e),...ai}}async function ci(e){return await e.evaluate(()=>{let e=Array.from(document.querySelectorAll(".candidate-card-wrap"));0===e.length&&(e=Array.from(document.querySelectorAll("[data-geek], .geek-item")));const t=[];return e.forEach((e,n)=>{const a=e.getAttribute("data-geek")??e.querySelector("[data-geek]")?.getAttribute("data-geek")??"",r=e.querySelector(".name")?.textContent?.trim()??"";let o="",i="",s="",c="";const l=e.querySelector(".base-info.join-text-wrap, .base-info");if(l){const e=[];if(l.querySelectorAll(":scope > *").forEach(t=>{const n=t.textContent?.trim();n&&e.push(n)}),e.length<=1&&(e.length=0,l.childNodes.forEach(t=>{if(t.nodeType===Node.TEXT_NODE){const n=t.textContent?.trim();n&&e.push(n)}})),e.length<=1){const t=l.textContent?.trim()??"";e.length=0,t.split(/[丨·|]/).forEach(t=>{const n=t.trim();n&&e.push(n)})}for(const t of e)!o&&t.includes("岁")?o=t:!i&&(t.includes("年")||t.includes("应届")||t.includes("在校"))?i=t:!s&&/(初中|高中|中专|中技|大专|本科|硕士|博士)/.test(t)?s=t:!c&&/(在职|离职|在校)/.test(t)&&(c=t)}const u=e.querySelector(".timeline-wrap.work-exps .content.join-text-wrap")??e.querySelector(".timeline-wrap.work-exps .content"),d=(u?.textContent?.trim()??"").split("·").map(e=>e.trim()),m=d[0]??"",g=d[1]??"";let f="",p="";const h=e.querySelector(".row-flex:not(.geek-desc)");if(h){const e=h.querySelector(".label"),t=h.querySelector(".content"),n=e?.textContent??"";if((n.includes("期望")||n.includes("最近关注"))&&t){const e=(t.textContent?.trim()??"").split("·").map(e=>e.trim());f=e[0]??"",p=e[1]??""}}if(!f){const t=e.querySelector(".timeline-wrap.expect .content.join-text-wrap")??e.querySelector(".timeline-wrap.expect .content");if(t){const e=(t.textContent?.trim()??"").split("·").map(e=>e.trim());f=e[0]??"",p=e[1]??""}}const w=e.querySelector(".salary-wrap")?.textContent?.trim()??"",y=[];e.querySelectorAll(".tags-wrap .tag-item, .tags-wrap .tag, .tags-wrap span").forEach(e=>{const t=e.textContent?.trim();t&&y.push(t)});const b=e.querySelector("button.btn.btn-greet")?.textContent?.trim()??"";t.push({index:n,candidateId:a,name:r,age:o,experience:i,education:s,workStatus:c,company:m,currentPosition:g,expectedLocation:f,expectedPosition:p,expectedSalary:w,tags:y,buttonText:b})}),t})}function li(e){return e.candidateId.length>0?e.candidateId:0!==e.name.length?[e.name,e.age,e.experience,e.expectedLocation,e.expectedPosition,e.expectedSalary].join("|"):void 0}var ui=ti({name:"zhipin_get_candidate_list",description:"获取推荐列表页的候选人卡片信息",input:ni.object({maxResults:ni.number().optional().describe("最多返回条数"),autoScroll:ni.boolean().default(!0).describe("是否自动向下滚动动态列表并合并采集结果"),maxScrolls:ni.number().int().min(0).max(50).default(4).describe("自动滚动的最大步数")}),output:ii,execute:async(e,t)=>{t.logger.info("Getting candidate list from recommend page");const n=si(),a=n.getContextManager(),r=await a.getPage("zhipin");let o=n.getRecommendTarget(r);const i=n.createVisualActivitySession(o);await i.begin("正在打开推荐列表");const s=await n.waitForRecommendList(o);if(o=n.getRecommendTarget(r),await i.retarget(o),!s)return await i.fail("推荐列表未加载"),{success:!1,candidates:[],total:0,error:"推荐列表未加载"};try{const n="正在读取推荐列表";await i.begin(n),await i.highlightSelector(".candidate-card-wrap, [data-geek], .geek-item",{label:n,padding:8});const a=e.autoScroll??!0,r=e.maxScrolls??4;let s,c;if(a&&r>0){const t=await Qn(o,On("recommend-list"),()=>ci(o),li,{direction:"down",steps:r,settleMs:900,maxNoNewRounds:4,boundaryLoadRetries:4,boundarySettleMs:1200,...void 0!==e.maxResults?{targetCount:e.maxResults}:{}});c=[...t.items],s={containerLabel:t.after.containerLabel,stepsRequested:t.stepsRequested,stepsCompleted:t.stepsCompleted,reachedBoundary:t.reachedBoundary,stopReason:t.stopReason,uniqueCount:t.uniqueCount,duplicateCount:t.duplicateCount,noNewRounds:t.noNewRounds,beforeItemCount:t.before.itemCount,afterItemCount:t.after.itemCount,beforeScrollHeight:t.before.scrollHeight,afterScrollHeight:t.after.scrollHeight}}else c=await ci(o);const l=void 0!==e.maxResults?c.slice(0,e.maxResults):c;return await i.succeed(`已读取 ${l.length} 位候选人`),t.logger.info(`Found ${l.length} candidates in recommend list`+(s?`, scroll stop: ${s.stopReason}`:"")),{success:!0,candidates:l,total:l.length,...void 0!==s?{scrollStats:s}:{}}}catch(e){throw await i.fail("读取推荐列表失败"),e}}});import{defineTool as di}from"@roll-agent/sdk";import{BrowserPageInfoSchema as mi}from"@roll-agent/browser";import{z as gi}from"zod";var fi,pi=gi.object({success:gi.boolean(),alreadyOnRecommend:gi.boolean(),usedSidebarClick:gi.boolean(),recommendReady:gi.boolean(),page:mi.optional(),error:gi.string().optional()});function hi(){return{getContextManager:h,getRecommendTarget:no,findZhipinSidebarSectionLink:pa,isZhipinRecommendSurfaceOpen:ha,waitForZhipinRecommendSurface:ya,moveVisualCursorToLocator:K,showVisualClickOnLocator:Z,randomDelay:ln,toAttachedPageInfo:Ce,createVisualActivitySession:e=>new na(e),...fi}}async function wi(e,t,n){return await t.toAttachedPageInfo(e,n)}async function yi(e,t,n,a,r,o){return await n.fail(r),{success:!1,...o,page:await wi(e,t,a),error:r}}async function bi(e,t,n,a){await n.scrollIntoViewIfNeeded(),await t.moveVisualCursorToLocator(e,n,{durationMs:110,settleMs:30}),await n.hover(),await t.randomDelay(e,100,180),await t.showVisualClickOnLocator(e,n,{pulseDurationMs:180}),await n.click(),a.info("Clicked Boss sidebar nav: 推荐牛人")}var vi=di({name:"zhipin_open_recommend_page",description:"通过点击 Boss 左侧导航切换到「推荐牛人」页,避免让编排器依赖站内 URL 猜测。",input:gi.object({}),output:pi,execute:async(e,t)=>{const n=hi(),a=n.getContextManager();t.logger.info("Opening Boss recommend page via sidebar navigation");const r=await a.getPage("zhipin");await r.bringToFront().catch(()=>{});const o=n.createVisualActivitySession(r),i="正在切换到推荐牛人页";if(await o.begin(i),await o.highlightSelector(ua.nav.sidebar,{label:i,padding:10}),n.isZhipinRecommendSurfaceOpen(r))return await o.retarget(n.getRecommendTarget(r)),await o.succeed("已在推荐牛人页"),{success:!0,alreadyOnRecommend:!0,usedSidebarClick:!1,recommendReady:!0,page:await wi(a,n,r)};const s=await n.findZhipinSidebarSectionLink(r,"recommend");if(!s)return await yi(a,n,o,r,"未找到推荐牛人导航",{alreadyOnRecommend:!1,usedSidebarClick:!1,recommendReady:!1});try{await bi(r,n,s,t.logger)}catch(e){return await yi(a,n,o,r,e instanceof Error?e.message:"点击推荐牛人导航失败",{alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!1})}const c=await n.waitForZhipinRecommendSurface(r);return await o.retarget(n.getRecommendTarget(r)),c?(await o.succeed("已切换到推荐牛人页"),{success:!0,alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!0,page:await wi(a,n,r)}):await yi(a,n,o,r,"推荐牛人页未就绪",{alreadyOnRecommend:!1,usedSidebarClick:!0,recommendReady:!1})}});import{defineTool as xi}from"@roll-agent/sdk";import{z as Si}from"zod";var Ci,ki=Si.object({index:Si.number(),candidateName:Si.string(),candidateId:Si.string(),success:Si.boolean(),error:Si.string().optional()}),Ai=Si.object({success:Si.boolean(),results:Si.array(ki),summary:Si.object({total:Si.number(),succeeded:Si.number(),failed:Si.number()})});function Ii(){return{getContextManager:h,getRecommendTarget:no,waitForRecommendList:ao,inspectRecommendCard:ro,moveVisualCursorToLocator:K,showVisualClickOnLocator:Z,humanDelay:un,shouldAddRandomBehavior:mn,performRandomScroll:dn,createVisualActivitySession:e=>new na(e),...Ci}}var Ri=xi({name:"zhipin_say_hello",description:"在推荐列表页对候选人点击「打招呼」按钮(支持批量)",input:Si.object({indices:Si.array(Si.number()).describe("要打招呼的候选人索引列表")}),output:Ai,execute:async(e,t)=>{t.logger.info(`Saying hello to ${e.indices.length} candidates`);const n=Ii(),a=n.getContextManager(),r=await a.getPage("zhipin");let o=n.getRecommendTarget(r);const i=n.createVisualActivitySession(o),s=e.indices.length>1?"正在批量打招呼":"正在打招呼";await i.begin("正在打开推荐列表");const c=await n.waitForRecommendList(o);if(o=n.getRecommendTarget(r),await i.retarget(o),!c){await i.fail("推荐列表未加载");const t=e.indices.map(e=>({index:e,candidateName:"",candidateId:"",success:!1,error:"推荐列表未加载"}));return{success:!1,results:t,summary:{total:t.length,succeeded:0,failed:t.length}}}await i.begin(s),await i.highlightSelector(".candidate-card-wrap, [data-geek], .geek-item",{label:s,padding:8});const l=[];for(const t of e.indices)try{const e=await n.inspectRecommendCard(o,t);if(e.found)if(e.hasGreetButton){const a=o.locator(e.cardSelector).nth(t),s=a.locator("button.btn.btn-greet").first();await i.highlightLocator(a,{label:`正在定位第 ${t+1} 位候选人`,padding:10}),await s.scrollIntoViewIfNeeded(),await n.moveVisualCursorToLocator(r,s,{durationMs:90,settleMs:20,target:o}),await s.hover(),await n.showVisualClickOnLocator(r,s,{pulseDurationMs:160,target:o}),await s.click(),l.push({index:t,candidateName:e.name,candidateId:e.candidateId,success:!0})}else l.push({index:t,candidateName:e.name,candidateId:e.candidateId,success:!1,error:"未找到打招呼按钮"});else l.push({index:t,candidateName:"",candidateId:"",success:!1,...void 0!==e.error?{error:e.error}:{}});await n.humanDelay(r),n.shouldAddRandomBehavior(.3)&&await n.performRandomScroll(r)}catch(e){l.push({index:t,candidateName:"",candidateId:"",success:!1,error:e instanceof Error?e.message:String(e)})}const u={total:l.length,succeeded:l.filter(e=>e.success).length,failed:l.filter(e=>!e.success).length};return 0===u.failed?await i.succeed(`已完成 ${u.succeeded}/${u.total} 位候选人`):await i.fail(`已完成 ${u.succeeded}/${u.total} 位候选人`),t.logger.info(`Say hello: ${u.succeeded}/${u.total} succeeded`),{success:0===u.failed,results:l,summary:u}}});import{defineTool as Mi}from"@roll-agent/sdk";import{z as Pi}from"zod";var Bi=Pi.object({success:Pi.boolean(),candidateName:Pi.string(),candidateId:Pi.string(),error:Pi.string().optional()}),Ei=Mi({name:"zhipin_open_resume",description:"在推荐列表页点击候选人卡片打开简历详情弹窗",input:Pi.object({index:Pi.number().describe("候选人在列表中的索引")}),output:Bi,execute:async(e,t)=>{t.logger.info(`Opening resume for candidate at index ${e.index}`);const n=h(),a=await n.getPage("zhipin"),r=no(a);if(!await ao(r))return{success:!1,candidateName:"",candidateId:"",error:"推荐列表未加载"};const o=await ro(r,e.index);if(!o.found)return{success:!1,candidateName:"",candidateId:"",error:o.error??`索引 ${e.index} 超出范围`};const i=r.locator(o.cardSelector).nth(e.index),s=await i.locator("[data-geek], .card-inner, .geek-item").count()>0?i.locator("[data-geek], .card-inner, .geek-item").first():i;return await s.scrollIntoViewIfNeeded(),await K(a,s,{target:r}),await s.hover(),await ln(a,200,400),await Z(a,s,{target:r}),await s.click(),await ln(a,1e3,2e3),t.logger.info(`Opened resume for ${o.name}`),{success:!0,candidateName:o.name,candidateId:o.candidateId}}});import{defineTool as _i}from"@roll-agent/sdk";import{z as Ti}from"zod";var qi=Ti.object({x:Ti.number(),y:Ti.number(),width:Ti.number(),height:Ti.number()}),$i=Ti.object({success:Ti.boolean(),screenshotArea:qi.optional(),canvasInfo:Ti.object({width:Ti.number(),height:Ti.number()}).optional(),error:Ti.string().optional()}),Ni=_i({name:"zhipin_locate_resume_canvas",description:"定位简历详情中嵌套 iframe 内的 canvas 元素坐标(用于截图)",input:Ti.object({}),output:$i,execute:async(e,t)=>{t.logger.info("Locating resume canvas in nested iframes");const n=h(),a=await n.getPage("zhipin");try{const e=a.frame("recommendFrame")??a.frames().find(e=>e.url().includes("recommend"));if(!e)return{success:!1,error:"未找到推荐页 iframe"};const n=await e.$('iframe[src*="c-resume"]');if(!n)return{success:!1,error:"未找到简历 iframe"};const r=await n.contentFrame();if(!r)return{success:!1,error:"无法访问简历 iframe 内容"};try{await r.waitForSelector("canvas#resume, div#resume canvas",{timeout:5e3})}catch{return{success:!1,error:"简历 canvas 未加载"}}const o=await r.evaluate(()=>{const e=document.querySelector("canvas#resume, div#resume canvas");if(!e)return null;const t=e.getBoundingClientRect();return{width:e.width,height:e.height,clientWidth:t.width,clientHeight:t.height,x:t.x,y:t.y}});if(!o)return{success:!1,error:"无法获取 canvas 信息"};const i=await a.evaluate(()=>{const e=document.querySelector("#recommendFrame");if(!e)return null;const t=e.getBoundingClientRect();return{x:t.x,y:t.y}}),s=await e.evaluate(()=>{const e=document.querySelector('iframe[src*="c-resume"]');if(!e)return null;const t=e.getBoundingClientRect();return{x:t.x,y:t.y}}),c=(i?.x??0)+(s?.x??0),l=(i?.y??0)+(s?.y??0);return t.logger.info(`Canvas located at (${c+o.x}, ${l+o.y})`),{success:!0,screenshotArea:{x:Math.round(c+o.x),y:Math.round(l+o.y),width:Math.round(o.clientWidth),height:Math.round(o.clientHeight)},canvasInfo:{width:o.width,height:o.height}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}});import{defineTool as Li}from"@roll-agent/sdk";import{z as zi}from"zod";var Fi=zi.object({success:zi.boolean(),closed:zi.boolean(),error:zi.string().optional()}),ji=[".recommendV2 .boss-popup__close",".dialog-lib-resume .boss-popup__close",".boss-dialog .boss-popup__close",".boss-popup__close",".close-btn",".dialog-close"],Oi=[".boss-popup__close",".close-btn",".dialog-close",".modal-close"],Di=Li({name:"zhipin_close_resume",description:"关闭简历详情弹窗",input:zi.object({}),output:Fi,execute:async(e,t)=>{t.logger.info("Closing resume detail modal");const n=h(),a=await n.getPage("zhipin"),r=a.frame("recommendFrame")??a.frames().find(e=>e.url().includes("recommend"));if(!await(async()=>{if(r)for(const e of ji){const t=r.locator(e).first();if(await t.isVisible())return await K(a,t,{target:r}),await Z(a,t,{target:r}),await t.click(),!0}for(const e of Oi){const t=a.locator(e).first();if(await t.isVisible())return await K(a,t),await Z(a,t),await t.click(),!0}return!1})())return{success:!1,closed:!1,error:"未找到关闭按钮"};let o=!1;for(let e=0;e<5;e++){await a.waitForTimeout(300);const e=r?await r.$(".boss-popup__wrapper, .dialog-lib-resume, .boss-dialog"):await a.$(".boss-popup__wrapper");if(!e||!await e.isVisible()){o=!0;break}}return t.logger.info(o?"Resume modal closed and verified":"Resume modal close unverified"),{success:!0,closed:!0}}});import{defineTool as Ui}from"@roll-agent/sdk";import{z as Vi}from"zod";import{waitForSelector as Hi}from"@roll-agent/browser";var Wi={login:{qrCode:".login-qr img, .qr-code img",loginSuccess:".user-info, .header-user"},messageList:{container:".chat-list, .msg-list",item:".chat-item, .msg-item",candidateName:".chat-item .name, .msg-item .name",lastMessage:".chat-item .msg, .msg-item .content",unreadBadge:".chat-item .unread, .msg-item .badge",timestamp:".chat-item .time, .msg-item .time"},chat:{input:".chat-input textarea, .msg-input textarea",sendButton:".btn-send, .send-btn",messageItem:".chat-msg, .msg-bubble",messageText:".chat-msg .text, .msg-bubble .text"}};import{navigateTo as Ki,waitForSelector as Zi}from"@roll-agent/browser";var Gi="https://www.yupao.com",Yi=`${Gi}/chat`,Ji=`${Gi}/login`;async function Xi(e){e.url().includes("/chat")||await Ki(e,Yi),await Zi(e,Wi.messageList.container,{timeout:15e3})}async function Qi(e,t){const n=`${Gi}/chat?id=${encodeURIComponent(t)}`;await Ki(e,n),await Zi(e,Wi.chat.input,{timeout:15e3})}async function es(e,t){await Xi(e),await Hi(e,Wi.messageList.item,{timeout:1e4});const n=Wi.messageList;return await e.$$eval(n.item,(e,t)=>{const n=[],a=t.maxItems?e.slice(0,t.maxItems):e;for(const e of a){const a=e.querySelector(t.sel.candidateName),r=e.querySelector(t.sel.lastMessage),o=e.querySelector(t.sel.unreadBadge),i=e.querySelector(t.sel.timestamp),s=e.getAttribute("data-id")??e.getAttribute("data-conversation-id")??e.querySelector("a")?.getAttribute("href")?.match(/id=([^&]+)/)?.[1]??"";n.push({conversationId:s,candidateName:a?.textContent?.trim()??"",lastMessage:r?.textContent?.trim()??"",unreadCount:parseInt(o?.textContent?.trim()??"0",10)||0,timestamp:i?.textContent?.trim()??""})}return n},{sel:n,maxItems:t})}var ts=Vi.object({limit:Vi.number().optional().describe("最多返回的消息条数")}),ns=Vi.object({conversationId:Vi.string(),candidateName:Vi.string(),lastMessage:Vi.string(),unreadCount:Vi.number(),timestamp:Vi.string()}),as=Vi.object({messages:Vi.array(ns),total:Vi.number()}),rs=Ui({name:"yupao_read_messages",description:"读取鱼泡未读消息列表",input:ts,output:as,execute:async(e,t)=>{t.logger.info(`Reading yupao messages (limit: ${e.limit??"all"})`);const n=h(),a=await n.getPage("yupao"),r=await es(a,e.limit);return t.logger.info(`Found ${r.length} messages`),{messages:r.map(e=>({...e})),total:r.length}}});import{defineTool as os}from"@roll-agent/sdk";import{z as is}from"zod";import{waitForSelector as ss,typeText as cs,clickElement as ls}from"@roll-agent/browser";async function us(e,t,n){try{return await Qi(e,t),await cs(e,Wi.chat.input,n),await ls(e,Wi.chat.sendButton),await ss(e,Wi.chat.messageItem,{timeout:5e3}),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}var ds=is.object({conversationId:is.string().describe("对话 ID"),message:is.string().describe("要发送的回复消息")}),ms=is.object({success:is.boolean(),conversationId:is.string(),sentMessage:is.string(),error:is.string().optional()}),gs=os({name:"yupao_send_reply",description:"向鱼泡指定对话发送回复消息",input:ds,output:ms,execute:async(e,t)=>{const{conversationId:n,message:a}=e;t.logger.info(`Sending reply to yupao conversation ${n}`);const r=h(),o=await r.getPage("yupao"),i=await us(o,n,a);return i.success?t.logger.info("Reply sent successfully"):t.logger.error(`Failed to send reply: ${i.error}`),{success:i.success,conversationId:n,sentMessage:a,error:i.error}}}),fs=t("browser-use-agent");function ps(e){if(void 0!==e){if("true"===e)return!0;if("false"===e)return!1;throw new Error(`Expected boolean env value "true" or "false", received "${e}".`)}}function hs(e,t){if(void 0===e)return;const n=Number.parseInt(e,10);if(!Number.isInteger(n))throw new Error(`${t} must be an integer, received "${e}".`);return n}function ws(e){if(void 0===e)return;const t=JSON.parse(e);if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))throw new Error("BROWSER_ARGS_JSON must be a JSON string array.");return t}function ys(){return n.parse({mode:process.env.BROWSER_MODE,headless:ps(process.env.BROWSER_HEADLESS),cdpUrl:process.env.BROWSER_CDP_URL,cdpHost:process.env.BROWSER_CDP_HOST,cdpPort:hs(process.env.BROWSER_CDP_PORT,"BROWSER_CDP_PORT"),channel:process.env.BROWSER_CHANNEL,executablePath:process.env.BROWSER_EXECUTABLE_PATH,userDataDir:process.env.BROWSER_USER_DATA_DIR,args:ws(process.env.BROWSER_ARGS_JSON),sessionsDir:process.env.BROWSER_SESSIONS_DIR})}var bs=e({name:"browser-use-agent",tools:[me,Ie,Oe,Ze,tt,rn,ia,Ia,Ba,Ha,Nr,Ur,Gr,co,vi,ei,ui,Ri,Ei,Ni,Di,rs,gs,S]},{onShutdown:v});async function vs(){await f(ys());try{await Mr(),y(!0)}catch(e){y(!1),fs.error(`Failed to preload Reply Authority keys during startup; browser_status.replyAuthorityKeysLoaded=false. ${e instanceof Error?e.stack??e.message:String(e)}`)}await bs.listen({transport:{type:"http",port:parseInt(process.env.BROWSER_AGENT_PORT??"3100",10),host:process.env.BROWSER_AGENT_HOST??"127.0.0.1"}})}vs().catch(async e=>{fs.error(`Fatal error: ${e instanceof Error?e.stack??e.message:String(e)}`),await v().catch(()=>{}),process.exit(1)});
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
declare const StorageAreaSchema: z.ZodEnum<["localStorage", "sessionStorage"]>;
|
|
3
|
+
declare const StorageEntrySummarySchema: z.ZodObject<{
|
|
4
|
+
area: z.ZodEnum<["localStorage", "sessionStorage"]>;
|
|
5
|
+
key: z.ZodString;
|
|
6
|
+
valueLength: z.ZodNumber;
|
|
7
|
+
valueKind: z.ZodEnum<["empty", "json", "string"]>;
|
|
8
|
+
jsonKind: z.ZodOptional<z.ZodEnum<["array", "object", "string", "number", "boolean", "null"]>>;
|
|
9
|
+
jsonTopLevelKeys: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
10
|
+
jsonArrayLength: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
numericFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
12
|
+
booleanFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
|
|
13
|
+
arrayLengths: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
14
|
+
}, "strip", z.ZodTypeAny, {
|
|
15
|
+
key: string;
|
|
16
|
+
area: "localStorage" | "sessionStorage";
|
|
17
|
+
valueLength: number;
|
|
18
|
+
valueKind: "string" | "empty" | "json";
|
|
19
|
+
jsonKind?: "string" | "number" | "boolean" | "object" | "array" | "null" | undefined;
|
|
20
|
+
jsonTopLevelKeys?: string[] | undefined;
|
|
21
|
+
jsonArrayLength?: number | undefined;
|
|
22
|
+
numericFields?: Record<string, number> | undefined;
|
|
23
|
+
booleanFields?: Record<string, boolean> | undefined;
|
|
24
|
+
arrayLengths?: Record<string, number> | undefined;
|
|
25
|
+
}, {
|
|
26
|
+
key: string;
|
|
27
|
+
area: "localStorage" | "sessionStorage";
|
|
28
|
+
valueLength: number;
|
|
29
|
+
valueKind: "string" | "empty" | "json";
|
|
30
|
+
jsonKind?: "string" | "number" | "boolean" | "object" | "array" | "null" | undefined;
|
|
31
|
+
jsonTopLevelKeys?: string[] | undefined;
|
|
32
|
+
jsonArrayLength?: number | undefined;
|
|
33
|
+
numericFields?: Record<string, number> | undefined;
|
|
34
|
+
booleanFields?: Record<string, boolean> | undefined;
|
|
35
|
+
arrayLengths?: Record<string, number> | undefined;
|
|
36
|
+
}>;
|
|
37
|
+
declare const CookieSummarySchema: z.ZodObject<{
|
|
38
|
+
name: z.ZodString;
|
|
39
|
+
domain: z.ZodString;
|
|
40
|
+
path: z.ZodString;
|
|
41
|
+
expires: z.ZodString;
|
|
42
|
+
valueLength: z.ZodNumber;
|
|
43
|
+
httpOnly: z.ZodBoolean;
|
|
44
|
+
secure: z.ZodBoolean;
|
|
45
|
+
sameSite: z.ZodOptional<z.ZodString>;
|
|
46
|
+
}, "strip", z.ZodTypeAny, {
|
|
47
|
+
path: string;
|
|
48
|
+
name: string;
|
|
49
|
+
valueLength: number;
|
|
50
|
+
domain: string;
|
|
51
|
+
expires: string;
|
|
52
|
+
httpOnly: boolean;
|
|
53
|
+
secure: boolean;
|
|
54
|
+
sameSite?: string | undefined;
|
|
55
|
+
}, {
|
|
56
|
+
path: string;
|
|
57
|
+
name: string;
|
|
58
|
+
valueLength: number;
|
|
59
|
+
domain: string;
|
|
60
|
+
expires: string;
|
|
61
|
+
httpOnly: boolean;
|
|
62
|
+
secure: boolean;
|
|
63
|
+
sameSite?: string | undefined;
|
|
64
|
+
}>;
|
|
65
|
+
declare const StorageCounterDiffSchema: z.ZodObject<{
|
|
66
|
+
area: z.ZodEnum<["localStorage", "sessionStorage"]>;
|
|
67
|
+
key: z.ZodString;
|
|
68
|
+
beforePresent: z.ZodBoolean;
|
|
69
|
+
afterPresent: z.ZodBoolean;
|
|
70
|
+
numericDeltas: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
71
|
+
before: z.ZodOptional<z.ZodNumber>;
|
|
72
|
+
after: z.ZodOptional<z.ZodNumber>;
|
|
73
|
+
delta: z.ZodOptional<z.ZodNumber>;
|
|
74
|
+
}, "strip", z.ZodTypeAny, {
|
|
75
|
+
before?: number | undefined;
|
|
76
|
+
after?: number | undefined;
|
|
77
|
+
delta?: number | undefined;
|
|
78
|
+
}, {
|
|
79
|
+
before?: number | undefined;
|
|
80
|
+
after?: number | undefined;
|
|
81
|
+
delta?: number | undefined;
|
|
82
|
+
}>>>;
|
|
83
|
+
booleanChanges: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
84
|
+
before: z.ZodOptional<z.ZodBoolean>;
|
|
85
|
+
after: z.ZodOptional<z.ZodBoolean>;
|
|
86
|
+
}, "strip", z.ZodTypeAny, {
|
|
87
|
+
before?: boolean | undefined;
|
|
88
|
+
after?: boolean | undefined;
|
|
89
|
+
}, {
|
|
90
|
+
before?: boolean | undefined;
|
|
91
|
+
after?: boolean | undefined;
|
|
92
|
+
}>>>;
|
|
93
|
+
arrayLengthDeltas: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
94
|
+
before: z.ZodOptional<z.ZodNumber>;
|
|
95
|
+
after: z.ZodOptional<z.ZodNumber>;
|
|
96
|
+
delta: z.ZodOptional<z.ZodNumber>;
|
|
97
|
+
}, "strip", z.ZodTypeAny, {
|
|
98
|
+
before?: number | undefined;
|
|
99
|
+
after?: number | undefined;
|
|
100
|
+
delta?: number | undefined;
|
|
101
|
+
}, {
|
|
102
|
+
before?: number | undefined;
|
|
103
|
+
after?: number | undefined;
|
|
104
|
+
delta?: number | undefined;
|
|
105
|
+
}>>>;
|
|
106
|
+
}, "strip", z.ZodTypeAny, {
|
|
107
|
+
key: string;
|
|
108
|
+
area: "localStorage" | "sessionStorage";
|
|
109
|
+
beforePresent: boolean;
|
|
110
|
+
afterPresent: boolean;
|
|
111
|
+
numericDeltas?: Record<string, {
|
|
112
|
+
before?: number | undefined;
|
|
113
|
+
after?: number | undefined;
|
|
114
|
+
delta?: number | undefined;
|
|
115
|
+
}> | undefined;
|
|
116
|
+
booleanChanges?: Record<string, {
|
|
117
|
+
before?: boolean | undefined;
|
|
118
|
+
after?: boolean | undefined;
|
|
119
|
+
}> | undefined;
|
|
120
|
+
arrayLengthDeltas?: Record<string, {
|
|
121
|
+
before?: number | undefined;
|
|
122
|
+
after?: number | undefined;
|
|
123
|
+
delta?: number | undefined;
|
|
124
|
+
}> | undefined;
|
|
125
|
+
}, {
|
|
126
|
+
key: string;
|
|
127
|
+
area: "localStorage" | "sessionStorage";
|
|
128
|
+
beforePresent: boolean;
|
|
129
|
+
afterPresent: boolean;
|
|
130
|
+
numericDeltas?: Record<string, {
|
|
131
|
+
before?: number | undefined;
|
|
132
|
+
after?: number | undefined;
|
|
133
|
+
delta?: number | undefined;
|
|
134
|
+
}> | undefined;
|
|
135
|
+
booleanChanges?: Record<string, {
|
|
136
|
+
before?: boolean | undefined;
|
|
137
|
+
after?: boolean | undefined;
|
|
138
|
+
}> | undefined;
|
|
139
|
+
arrayLengthDeltas?: Record<string, {
|
|
140
|
+
before?: number | undefined;
|
|
141
|
+
after?: number | undefined;
|
|
142
|
+
delta?: number | undefined;
|
|
143
|
+
}> | undefined;
|
|
144
|
+
}>;
|
|
145
|
+
type StorageArea = z.infer<typeof StorageAreaSchema>;
|
|
146
|
+
type StorageEntrySummary = z.infer<typeof StorageEntrySummarySchema>;
|
|
147
|
+
type CookieSummary = z.infer<typeof CookieSummarySchema>;
|
|
148
|
+
type StorageCounterDiff = z.infer<typeof StorageCounterDiffSchema>;
|
|
149
|
+
type RawStorageEntry = {
|
|
150
|
+
readonly key: string;
|
|
151
|
+
readonly value: string;
|
|
152
|
+
};
|
|
153
|
+
export declare function summarizeStorageEntry(area: StorageArea, entry: RawStorageEntry): StorageEntrySummary;
|
|
154
|
+
export declare function summarizeCookie(cookie: {
|
|
155
|
+
readonly name: string;
|
|
156
|
+
readonly value: string;
|
|
157
|
+
readonly domain: string;
|
|
158
|
+
readonly path: string;
|
|
159
|
+
readonly expires: number;
|
|
160
|
+
readonly httpOnly: boolean;
|
|
161
|
+
readonly secure: boolean;
|
|
162
|
+
readonly sameSite?: string;
|
|
163
|
+
}): CookieSummary;
|
|
164
|
+
export declare function diffStorageCounters(beforeEntries: ReadonlyArray<StorageEntrySummary>, afterEntries: ReadonlyArray<StorageEntrySummary>): StorageCounterDiff[];
|
|
165
|
+
export declare const zhipinDiagnoseBrowserState: import("@roll-agent/sdk").ToolDefinition<{
|
|
166
|
+
phase?: "native" | "native-watch" | "browser-attach" | "page-attach" | "network-watch" | "page-evaluate" | "detector-fingerprint" | "storage-summary" | undefined;
|
|
167
|
+
targetPageId?: string | undefined;
|
|
168
|
+
watchMs?: number | undefined;
|
|
169
|
+
networkEventLimit?: number | undefined;
|
|
170
|
+
}, {
|
|
171
|
+
mode: string;
|
|
172
|
+
success: boolean;
|
|
173
|
+
requestedPhase: "native" | "native-watch" | "browser-attach" | "page-attach" | "network-watch" | "page-evaluate" | "detector-fingerprint" | "storage-summary";
|
|
174
|
+
nativePages: {
|
|
175
|
+
url: string;
|
|
176
|
+
title: string;
|
|
177
|
+
pageId: string;
|
|
178
|
+
boundPlatform: "zhipin" | "yupao" | null;
|
|
179
|
+
detectedPlatform: "zhipin" | "yupao" | null;
|
|
180
|
+
isSelectedForPlatform: boolean;
|
|
181
|
+
}[];
|
|
182
|
+
browserAttached: boolean;
|
|
183
|
+
pageAttached: boolean;
|
|
184
|
+
nativeTimeline: {
|
|
185
|
+
phase: "native" | "native-watch" | "browser-attach" | "page-attach" | "network-watch" | "page-evaluate" | "detector-fingerprint" | "storage-summary" | "browser-attach-watch";
|
|
186
|
+
capturedAt: string;
|
|
187
|
+
targetFound: boolean;
|
|
188
|
+
urlChangedFromPrevious: boolean;
|
|
189
|
+
titleChangedFromPrevious: boolean;
|
|
190
|
+
currentUrl?: string | undefined;
|
|
191
|
+
page?: {
|
|
192
|
+
url: string;
|
|
193
|
+
title: string;
|
|
194
|
+
pageId: string;
|
|
195
|
+
boundPlatform: "zhipin" | "yupao" | null;
|
|
196
|
+
detectedPlatform: "zhipin" | "yupao" | null;
|
|
197
|
+
isSelectedForPlatform: boolean;
|
|
198
|
+
} | undefined;
|
|
199
|
+
previousUrl?: string | undefined;
|
|
200
|
+
previousTitle?: string | undefined;
|
|
201
|
+
currentTitle?: string | undefined;
|
|
202
|
+
}[];
|
|
203
|
+
phases: {
|
|
204
|
+
success: boolean;
|
|
205
|
+
durationMs: number;
|
|
206
|
+
phase: "native" | "native-watch" | "browser-attach" | "page-attach" | "network-watch" | "page-evaluate" | "detector-fingerprint" | "storage-summary";
|
|
207
|
+
error?: string | undefined;
|
|
208
|
+
}[];
|
|
209
|
+
warnings: string[];
|
|
210
|
+
targetPage?: {
|
|
211
|
+
url: string;
|
|
212
|
+
title: string;
|
|
213
|
+
pageId: string;
|
|
214
|
+
boundPlatform: "zhipin" | "yupao" | null;
|
|
215
|
+
detectedPlatform: "zhipin" | "yupao" | null;
|
|
216
|
+
isSelectedForPlatform: boolean;
|
|
217
|
+
} | undefined;
|
|
218
|
+
networkEvents?: {
|
|
219
|
+
url: string;
|
|
220
|
+
capturedAt: string;
|
|
221
|
+
kind: "request" | "response";
|
|
222
|
+
reason: "apm-action-log" | "device-action-report" | "boss-risk-report" | "zhipin-security";
|
|
223
|
+
status?: number | undefined;
|
|
224
|
+
method?: string | undefined;
|
|
225
|
+
resourceType?: string | undefined;
|
|
226
|
+
}[] | undefined;
|
|
227
|
+
navigationEvents?: {
|
|
228
|
+
url: string;
|
|
229
|
+
capturedAt: string;
|
|
230
|
+
}[] | undefined;
|
|
231
|
+
evaluate?: {
|
|
232
|
+
url: string;
|
|
233
|
+
title: string;
|
|
234
|
+
visibilityState: string;
|
|
235
|
+
hasFocus: boolean;
|
|
236
|
+
} | undefined;
|
|
237
|
+
detectorFingerprint?: {
|
|
238
|
+
userAgentContainsHeadless: boolean;
|
|
239
|
+
languagesLength: number;
|
|
240
|
+
pluginsLength: number;
|
|
241
|
+
hasChromeRuntime: boolean;
|
|
242
|
+
hasPlaywrightBinding: boolean;
|
|
243
|
+
hasPwInitScripts: boolean;
|
|
244
|
+
cdcKeys: string[];
|
|
245
|
+
webdriverKeys: string[];
|
|
246
|
+
automationLikeWindowKeys: string[];
|
|
247
|
+
navigatorWebdriver?: boolean | undefined;
|
|
248
|
+
permissionQueryIsNative?: boolean | undefined;
|
|
249
|
+
} | undefined;
|
|
250
|
+
storage?: {
|
|
251
|
+
cookies: {
|
|
252
|
+
path: string;
|
|
253
|
+
name: string;
|
|
254
|
+
valueLength: number;
|
|
255
|
+
domain: string;
|
|
256
|
+
expires: string;
|
|
257
|
+
httpOnly: boolean;
|
|
258
|
+
secure: boolean;
|
|
259
|
+
sameSite?: string | undefined;
|
|
260
|
+
}[];
|
|
261
|
+
localStorage: {
|
|
262
|
+
key: string;
|
|
263
|
+
area: "localStorage" | "sessionStorage";
|
|
264
|
+
valueLength: number;
|
|
265
|
+
valueKind: "string" | "empty" | "json";
|
|
266
|
+
jsonKind?: "string" | "number" | "boolean" | "object" | "array" | "null" | undefined;
|
|
267
|
+
jsonTopLevelKeys?: string[] | undefined;
|
|
268
|
+
jsonArrayLength?: number | undefined;
|
|
269
|
+
numericFields?: Record<string, number> | undefined;
|
|
270
|
+
booleanFields?: Record<string, boolean> | undefined;
|
|
271
|
+
arrayLengths?: Record<string, number> | undefined;
|
|
272
|
+
}[];
|
|
273
|
+
sessionStorage: {
|
|
274
|
+
key: string;
|
|
275
|
+
area: "localStorage" | "sessionStorage";
|
|
276
|
+
valueLength: number;
|
|
277
|
+
valueKind: "string" | "empty" | "json";
|
|
278
|
+
jsonKind?: "string" | "number" | "boolean" | "object" | "array" | "null" | undefined;
|
|
279
|
+
jsonTopLevelKeys?: string[] | undefined;
|
|
280
|
+
jsonArrayLength?: number | undefined;
|
|
281
|
+
numericFields?: Record<string, number> | undefined;
|
|
282
|
+
booleanFields?: Record<string, boolean> | undefined;
|
|
283
|
+
arrayLengths?: Record<string, number> | undefined;
|
|
284
|
+
}[];
|
|
285
|
+
counterDiffs: {
|
|
286
|
+
key: string;
|
|
287
|
+
area: "localStorage" | "sessionStorage";
|
|
288
|
+
beforePresent: boolean;
|
|
289
|
+
afterPresent: boolean;
|
|
290
|
+
numericDeltas?: Record<string, {
|
|
291
|
+
before?: number | undefined;
|
|
292
|
+
after?: number | undefined;
|
|
293
|
+
delta?: number | undefined;
|
|
294
|
+
}> | undefined;
|
|
295
|
+
booleanChanges?: Record<string, {
|
|
296
|
+
before?: boolean | undefined;
|
|
297
|
+
after?: boolean | undefined;
|
|
298
|
+
}> | undefined;
|
|
299
|
+
arrayLengthDeltas?: Record<string, {
|
|
300
|
+
before?: number | undefined;
|
|
301
|
+
after?: number | undefined;
|
|
302
|
+
delta?: number | undefined;
|
|
303
|
+
}> | undefined;
|
|
304
|
+
}[];
|
|
305
|
+
} | undefined;
|
|
306
|
+
}>;
|
|
307
|
+
export {};
|
|
@@ -6,9 +6,6 @@ export declare const zhipinScrollView: import("@roll-agent/sdk").ToolDefinition<
|
|
|
6
6
|
settleMs?: number | undefined;
|
|
7
7
|
}, {
|
|
8
8
|
success: boolean;
|
|
9
|
-
direction: "up" | "down";
|
|
10
|
-
stepsRequested: number;
|
|
11
|
-
stepsCompleted: number;
|
|
12
9
|
before: {
|
|
13
10
|
containerFound: boolean;
|
|
14
11
|
containerLabel: string;
|
|
@@ -29,6 +26,9 @@ export declare const zhipinScrollView: import("@roll-agent/sdk").ToolDefinition<
|
|
|
29
26
|
atEnd: boolean;
|
|
30
27
|
itemCount: number;
|
|
31
28
|
};
|
|
29
|
+
direction: "up" | "down";
|
|
30
|
+
stepsRequested: number;
|
|
31
|
+
stepsCompleted: number;
|
|
32
32
|
reachedBoundary: boolean;
|
|
33
33
|
surface: "chat-list" | "chat-history" | "recommend-list";
|
|
34
34
|
error?: string | undefined;
|