dsh-chrome-bridge 1.16.4 → 1.18.0

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/README.en.md ADDED
@@ -0,0 +1,30 @@
1
+ # Chrome Bridge
2
+
3
+ Lets DSH work in the Chrome you already use: real clicks and typing, a cursor you can see on the page, and your own logins.
4
+
5
+ - Pages it opens go into a separate window, so your own window gets no new tabs and keeps focus.
6
+ - It never touches the page you are looking at on its own.
7
+ - Pause it any time: click the DSH Bridge icon in Chrome's toolbar and turn off "Let DSH control the browser".
8
+
9
+ ## Install
10
+
11
+ 1. In DSH, open **Plugins**, click **Add plugin**, enter `dsh-chrome-bridge`, then restart DSH.
12
+ 2. Add the DSH Bridge extension from the [Chrome Web Store](https://chromewebstore.google.com/detail/bippcbbbipppmhjkjomgdnjbooecbimo).
13
+
14
+ Once both are in, the plugin shows "Connected" on the Plugins page.
15
+
16
+ ## Update
17
+
18
+ Open it on the Plugins page and click "Update to …". A new version can be installed about a day after it is released.
19
+
20
+ ## Languages
21
+
22
+ - The extension panel in Chrome follows Chrome's language: English, Chinese or Russian.
23
+ - The settings card on the Plugins page follows DSH's language.
24
+ - To give the model English or Russian tool descriptions too, see "Tool descriptions in English or Russian" in the [full guide](https://github.com/OrderG-X/dsh-chrome-bridge#-tool-descriptions-in-english-or-russian).
25
+
26
+ ## Requirements
27
+
28
+ macOS, Windows or Linux, and Chrome 116 or newer.
29
+
30
+ Full guide: https://github.com/OrderG-X/dsh-chrome-bridge
package/README.md CHANGED
@@ -1,26 +1,32 @@
1
- # DSH Bridge · dsh-chrome-bridge
1
+ # Chrome 浏览器控制
2
2
 
3
- A DeepSeek Harness (DSH) plugin that drives the Chrome you already use: real clicks and typing, a visible on-page cursor, and your own logins. It provides 12 `browser_*` tools over native messaging and the Chrome debugger, with no listening port.
3
+ 让 DSH 直接操作你正在用的 Chrome:真点击、真输入,页面里看得到它的光标,你的登录状态都在。
4
4
 
5
- 让 DSH 直接操作你正在用的 Chrome:真点击、真输入,页面里看得到光标,登录状态都在。提供 12 个 `browser_*` 工具,走 native messaging 和 Chrome 调试接口,不开监听端口。
5
+ - 它新开的页放进一个单独的窗口,不往你正在用的窗口里塞,也不抢焦点。
6
+ - 它不会擅自去动你正在看的那一页。
7
+ - 随时能暂停:点 Chrome 工具栏上的 DSH Bridge 图标,关掉「允许 DSH 控制浏览器」。
6
8
 
7
- Pages the agent opens go into a separate background window of your Chrome, so your own window keeps its tabs and focus.
8
- agent 新开的页放进你 Chrome 里一个单独的后台窗口,你自己的窗口不多标签页、焦点不动。
9
+ ## 怎么装
9
10
 
10
- ## Install / 安装
11
+ 1. 在 DSH「插件」页点「添加插件」,填 `dsh-chrome-bridge`,然后重启 DSH。
12
+ 2. 从 [Chrome 应用商店](https://chromewebstore.google.com/detail/bippcbbbipppmhjkjomgdnjbooecbimo) 装上 DSH Bridge 扩展。
11
13
 
12
- 1. In DSH, open **Plugins**, click **Add plugin**, enter `dsh-chrome-bridge`, then restart DSH.
13
- 在 DSH「插件」页点「添加插件」,填 `dsh-chrome-bridge`,重启 DSH。DSH 连不上 npm 时会自动换国内镜像。
14
- 2. Add the DSH Bridge extension to Chrome from the [Chrome Web Store](https://chromewebstore.google.com/detail/bippcbbbipppmhjkjomgdnjbooecbimo).
15
- 从 [Chrome 应用商店](https://chromewebstore.google.com/detail/bippcbbbipppmhjkjomgdnjbooecbimo) 装上 DSH Bridge 扩展。
14
+ 装好后,插件页上它会显示「已连接」。
16
15
 
17
- Requirements: macOS, Windows or Linux, Chrome 116+, Node.js 18+.
18
- 系统要求:macOS、Windows 或 Linux,Chrome 116+,Node.js 18+。
16
+ ## 怎么更新
19
17
 
20
- ## Updating / 更新
18
+ 在「插件」页点开它,点「更新到 …」。新版发布后大约一天才装得到。
21
19
 
22
- On DSH 0.2.2 or later, open the plugin on the Plugins page and click "Update to …". On older DSH, uninstall it and add it again. A new version can be installed about a day after it is released, because the pnpm that DSH uses skips brand-new versions by default.
20
+ ## 语言
23
21
 
24
- DSH 0.2.2 起,在「插件」页点开它,点「更新到 …」;更老的 DSH 先卸载,再添加一次。DSH 用 pnpm 安装插件,而 pnpm 默认不装刚发布的版本,所以新版大约发布一天后才装得到。
22
+ - Chrome 里的扩展面板跟着 Chrome 的语言走:中文、英文、俄文。
23
+ - 插件页上的这张设置卡片跟着 DSH 的语言走。
24
+ - 想让模型看到的工具说明也换成英文或俄文,看[完整说明](https://github.com/OrderG-X/dsh-chrome-bridge/blob/main/README.zh.md)里「工具描述支持英文 / 俄文」那一节。
25
25
 
26
- Full documentation / 完整说明:https://github.com/OrderG-X/dsh-chrome-bridge
26
+ ## 系统要求
27
+
28
+ macOS、Windows 或 Linux,Chrome 116 或更新。
29
+
30
+ 完整说明:https://github.com/OrderG-X/dsh-chrome-bridge
31
+
32
+ English: https://github.com/OrderG-X/dsh-chrome-bridge/blob/main/plugin/README.en.md
package/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * dsh-chrome-bridge 的网页端:DSH「插件」页里我们这张卡的设置页。
3
3
  *
4
- * 连接状态(扩展 / 本地宿主、版本、正在控制哪些标签页)+ 全部松手
4
+ * 连接状态(扩展 / 本机程序、版本、正在控制哪些标签页)+ 全部放开;文字有中 / 英 / 俄三份,跟着 DSH 的界面语言
5
5
  * 三个开关:允许 DSH 控制浏览器(这里只能关)、页面里显示 DSH 光标、新页开在单独窗口
6
6
  * 没连上时:差哪一步、一键帮你打开安装页
7
7
  *
@@ -49,20 +49,20 @@ window.__ModuleLoader__.load({
49
49
  localBuild: '本地版',
50
50
  controlling: '正在控制 %n 个标签页',
51
51
  controllingIdle: '没有在控制的标签页',
52
- releaseAll: '全部松手',
53
- released: '已全部松手',
52
+ releaseAll: '全部放开',
53
+ released: '已全部放开',
54
54
  allowControl: '允许 DSH 控制浏览器',
55
- allowControlHint: '关掉后,DSH 的浏览器操作会被直接拒绝。重新打开要到 Chrome 工具栏的 DSH Bridge 面板里点 —— 这样模型自己没法把它打开。',
56
- resumeInChrome: '要恢复,请点 Chrome 工具栏上的 DSH Bridge 图标,打开「允许 DSH 控制浏览器」。',
55
+ allowControlHint: '关掉后,DSH 碰不了浏览器。要重新打开,得去 Chrome 工具栏点 DSH Bridge 图标——DSH 自己打不开。',
56
+ resumeInChrome: '要恢复:点 Chrome 工具栏上的 DSH Bridge 图标,在里面把控制重新打开。',
57
57
  showCursor: '页面里显示 DSH 光标',
58
- showCursorHint: '关掉只是不画光标,点击、输入照做。',
58
+ showCursorHint: '关掉只是不显示光标,点击、输入照做。',
59
59
  ownWindow: '新页开在单独窗口',
60
- ownWindowHint: 'DSH 新开的页放进一个单独的 Chrome 窗口(登录状态照样在),不往你正在用的窗口里塞标签页、不抢焦点。关掉就开在你当前窗口的后台。',
61
- ownWindowOld: 'Chrome 里的扩展更新到 1.13 后才有这个开关;现在新页开在你当前窗口的后台。',
62
- outdated: 'Chrome 里的扩展版本较旧,更新后才能在这里切换开关。',
60
+ ownWindowHint: 'DSH 新开的页放进一个单独的 Chrome 窗口,登录状态照样在,不往你正在用的窗口里塞,也不抢焦点。关掉就开在你当前窗口的后台。',
61
+ ownWindowOld: 'Chrome 里的扩展更新后才有这个开关,现在新页开在你当前窗口的后台。',
62
+ outdated: 'Chrome 里的扩展版本旧了,更新后才能在这里改开关。',
63
63
  setupTitle: '还差一步:把扩展装进 Chrome',
64
- setupStoreTitle: '扩展装了,但没连上',
65
- setupStep1: '打开 Chrome,地址栏进入 chrome://extensions,右上角打开「开发者模式」',
64
+ setupStoreTitle: '扩展装好了,但还没连上',
65
+ setupStep1: '打开 Chrome,地址栏输入 chrome://extensions,打开右上角的「开发者模式」',
66
66
  setupStep2: '点「加载已解压的扩展程序」,选这个文件夹:',
67
67
  setupStep3: '装好后这里会自动变成「已连接」',
68
68
  setupStoreAlt: '更省事:直接从 Chrome 应用商店装,不用开发者模式。',
@@ -76,7 +76,7 @@ window.__ModuleLoader__.load({
76
76
  pathCopiedWin: ',文件夹路径也复制好了(粘进文件框顶上的地址栏、回车)',
77
77
  plugin: '插件 v%v',
78
78
  guide: '使用说明',
79
- failed: '操作没成功:%e',
79
+ failed: '没成功:%e',
80
80
  unreachable: '读不到插件状态,重启 DSH 后再试',
81
81
  }
82
82
  const en = {
@@ -97,16 +97,16 @@ window.__ModuleLoader__.load({
97
97
  releaseAll: 'Release all',
98
98
  released: 'Released all tabs',
99
99
  allowControl: 'Allow DSH to control the browser',
100
- allowControlHint: 'When off, DSH browser actions are refused. Turning it back on is done from the DSH Bridge panel in Chrome\'s toolbar, so the model cannot re-enable it itself.',
101
- resumeInChrome: 'To resume, click the DSH Bridge icon in Chrome\'s toolbar and turn on "Allow DSH to control the browser".',
100
+ allowControlHint: 'When off, DSH can\'t touch the browser. To turn it back on, click the DSH Bridge icon in Chrome\'s toolbar; DSH can\'t do that itself.',
101
+ resumeInChrome: 'To resume, click the DSH Bridge icon in Chrome\'s toolbar and turn control back on there.',
102
102
  showCursor: 'Show the DSH cursor on pages',
103
103
  showCursorHint: 'Off only hides the cursor; clicks and typing still happen.',
104
104
  ownWindow: 'Open new pages in a separate window',
105
- ownWindowHint: 'Pages DSH opens go into their own Chrome window (same profile, so your logins work) instead of piling tabs into the window you are using, and never take focus. Off: they open as background tabs in your current window.',
106
- ownWindowOld: 'This switch needs extension 1.13 or newer in Chrome; for now new pages open as background tabs in your current window.',
107
- outdated: 'The extension in Chrome is outdated; update it to change these switches here.',
105
+ ownWindowHint: 'Pages DSH opens go into their own Chrome window, with your logins, instead of piling up in the window you are using, and never take focus. Off: background tabs in your current window.',
106
+ ownWindowOld: 'Update the extension in Chrome to get this switch; for now new pages open as background tabs in your current window.',
107
+ outdated: 'The extension in Chrome is out of date; update it to change these switches here.',
108
108
  setupTitle: 'One step left: add the extension to Chrome',
109
- setupStoreTitle: 'The extension is installed but not connected',
109
+ setupStoreTitle: 'The extension is installed but not connected yet',
110
110
  setupStep1: 'Open chrome://extensions in Chrome and turn on Developer mode (top right)',
111
111
  setupStep2: 'Click "Load unpacked" and choose this folder:',
112
112
  setupStep3: 'This page turns to "Connected" once it is loaded',
@@ -125,6 +125,52 @@ window.__ModuleLoader__.load({
125
125
  unreachable: 'Could not read the plugin status; restart DSH and try again',
126
126
  }
127
127
 
128
+ const ru = {
129
+ title: 'Управление Chrome',
130
+ checking: 'Проверка…',
131
+ connected: 'Подключено',
132
+ paused: 'Пауза',
133
+ disconnected: 'Не подключено',
134
+ unsupported: 'Работает только на macOS, Windows и Linux',
135
+ summaryOn: 'Подключено · вкладок под управлением: %n',
136
+ summaryIdle: 'Подключено, вкладок под управлением нет',
137
+ summaryOff: 'Chrome ещё не подключён — откройте, чтобы увидеть шаги',
138
+ summaryPaused: 'Пауза: DSH не может работать с браузером',
139
+ storeBuild: 'Из магазина',
140
+ localBuild: 'Локальная',
141
+ controlling: 'Вкладок под управлением: %n',
142
+ controllingIdle: 'Вкладок под управлением нет',
143
+ releaseAll: 'Отпустить все',
144
+ released: 'Все вкладки отпущены',
145
+ allowControl: 'Разрешить DSH управлять браузером',
146
+ allowControlHint: 'Выкл.: DSH не может трогать браузер. Включить обратно можно только через значок DSH Bridge на панели инструментов Chrome — сам DSH этого сделать не может.',
147
+ resumeInChrome: 'Чтобы продолжить, нажмите значок DSH Bridge на панели инструментов Chrome и снова включите управление.',
148
+ showCursor: 'Показывать курсор DSH',
149
+ showCursorHint: 'Выкл. только скрывает курсор, клики и ввод продолжаются.',
150
+ ownWindow: 'Новые страницы в отдельном окне',
151
+ ownWindowHint: 'Страницы, которые открывает DSH, попадают в отдельное окно Chrome (ваши входы в аккаунты сохраняются), не засоряют ваше окно и не перехватывают фокус. Выкл.: фоновые вкладки в текущем окне.',
152
+ ownWindowOld: 'Обновите расширение в Chrome, чтобы появился этот переключатель; пока новые страницы открываются фоном в текущем окне.',
153
+ outdated: 'Расширение в Chrome устарело; обновите его, чтобы менять переключатели здесь.',
154
+ setupTitle: 'Остался один шаг: добавить расширение в Chrome',
155
+ setupStoreTitle: 'Расширение установлено, но ещё не подключено',
156
+ setupStep1: 'Откройте в Chrome chrome://extensions и включите «Режим разработчика» справа вверху',
157
+ setupStep2: 'Нажмите «Загрузить распакованное расширение» и выберите эту папку:',
158
+ setupStep3: 'Как только расширение загрузится, здесь появится «Подключено»',
159
+ setupStoreAlt: 'Проще: установить из Chrome Web Store, режим разработчика не нужен.',
160
+ openStore: 'Открыть магазин',
161
+ storeOpened: 'Страница магазина открыта в Chrome — нажмите «Установить»',
162
+ setupStore1: 'Проверьте, что Chrome запущен, а расширение DSH Bridge включено',
163
+ setupStore2: 'Если не помогло — перезапустите Chrome',
164
+ openInstall: 'Открыть страницу установки',
165
+ installOpened: 'Страница расширений открыта в Chrome',
166
+ pathCopied: '; путь к папке скопирован (в окне выбора файлов ⌘⇧G, затем ⌘V)',
167
+ pathCopiedWin: '; путь к папке скопирован (вставьте его в адресную строку окна выбора файлов)',
168
+ plugin: 'Плагин v%v',
169
+ guide: 'Инструкция',
170
+ failed: 'Не получилось: %e',
171
+ unreachable: 'Не удалось прочитать состояние плагина; перезапустите DSH и попробуйте снова',
172
+ }
173
+
128
174
  const fmt = (s, vars) => String(s).replace(/%([a-z])/g, (m, k) => (vars && k in vars ? String(vars[k]) : m))
129
175
 
130
176
  const CSS = `
@@ -335,7 +381,7 @@ window.__ModuleLoader__.load({
335
381
  function apply(ctx) {
336
382
  const t = ctx.locale && typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NS) : (k) => zh[k] || k
337
383
  if (ctx.locale && typeof ctx.locale.register === 'function') {
338
- ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-chrome-bridge: dictionaries')
384
+ ctx.effect(() => ctx.locale.register(NS, { zh, en, ru }), 'dsh-chrome-bridge: dictionaries')
339
385
  }
340
386
  const Card = makeCard(t)
341
387
  const mount = (name, key) => {
package/drag.js CHANGED
@@ -15,14 +15,23 @@ import { refElementJs } from './refs.js'
15
15
 
16
16
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
17
17
 
18
- /** 按可见文字找元素:包含这段文字、看得见的元素里面积最小的那个(最贴近文字本身)。 */
18
+ /**
19
+ * 按可见文字找元素:看得见、包含这段文字的元素里,文字正好就是这段的优先
20
+ * (不然「顺序:Item A, Item B…」这种把几项连在一起的小段落会比列表项本身还小,抢走匹配),
21
+ * 同一档里取面积最小的那个(最贴近文字本身)。
22
+ */
19
23
  const textElementJs = (text) => `((t) => {
20
- let best = null, area = Infinity;
24
+ const norm = (s) => String(s || '').replace(/\\s+/g, ' ').trim();
25
+ const want = norm(t);
26
+ let best = null, area = Infinity, exact = false;
21
27
  for (const el of document.body.querySelectorAll('*')) {
22
28
  if (!(el.textContent || '').includes(t) || !(el.innerText || '').includes(t)) continue;
23
29
  const r = el.getBoundingClientRect();
24
- if (r.width < 1 || r.height < 1 || r.width * r.height >= area) continue;
25
- best = el; area = r.width * r.height;
30
+ if (r.width < 1 || r.height < 1) continue;
31
+ const ex = norm(el.innerText) === want;
32
+ if (exact && !ex) continue;
33
+ if (ex === exact && r.width * r.height >= area) continue;
34
+ best = el; area = r.width * r.height; exact = ex;
26
35
  }
27
36
  return best;
28
37
  })(${JSON.stringify(String(text))})`
@@ -46,6 +55,7 @@ const PLAN_JS = (from, to) => `(async () => {
46
55
  const dst = ${elementJs(to)};
47
56
  if (${isElementEnd(from)} && !src) return { missing: 'from' };
48
57
  if (${isElementEnd(to)} && !dst) return { missing: 'to' };
58
+ if (src && src === dst) return { same: true };
49
59
  if (src) {
50
60
  src.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' });
51
61
  // 后台标签页会暂停 rAF,定时器兜底
@@ -92,6 +102,7 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
92
102
  throw new Error(`没找到${plan.missing === 'from' ? '起点' : '终点'} ${describe(end)}` +
93
103
  (hasRef(end) ? '(编号可能已失效,重新 snapshot)' : ''))
94
104
  }
105
+ if (plan.same) throw new Error(`起点 ${describe(from)} 和终点 ${describe(to)} 找到的是同一个元素——换个更具体的写法(ref 或 selector)`)
95
106
  const { a, b } = plan
96
107
  if (!plan.bIn) throw new Error(`终点 ${describe(to)} 不在当前屏幕里——先滚动让起点和终点都露出来`)
97
108
 
package/i18n/en.js ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Server-side dictionary (English). Same keys as zh.js, which stays the reference
3
+ * dictionary: a key missing here falls back to Chinese, and so does a translation
4
+ * that drops a placeholder the Chinese text needs (see i18n/index.js).
5
+ *
6
+ * This layer is model-facing: tool descriptions, parameter docs and error messages.
7
+ * Keep the operational detail — the model reads these as instructions.
8
+ */
9
+ export default {
10
+ // ── shared ──────────────────────────────────────────────────────────────
11
+ 'param.tab': 'Tab id (number), or "active" for the tab the user is currently looking at. When omitted, the tab this session opened or last acted on is reused; with none, the call fails — it never falls back to the tab the user is on',
12
+ 'param.ref': 'Element ref: the [N] numbers listed by browser_read(what=snapshot). Most reliable — when you have a ref, do not guess a selector',
13
+
14
+ // ── browser_tabs ───────────────────────────────────────────────────────
15
+ 'tool.tabs.desc': 'List / find / open / close / switch Chrome tabs. Every other browser_* tool takes a tab argument, so call this first to get an id. It drives the user\'s real Chrome (logins intact) and never spins up a clean browser. Pages opened with open go by default into a separate "DSH work window" in the background without stealing focus, so the page the user is looking at is left alone.',
16
+ 'tool.tabs.action': 'list all; find filters by title/URL; open opens a new tab (background work window by default); close closes it; activate brings it to the front (that pulls the window in front of the user — do not use it unless asked)',
17
+ 'tool.tabs.query': 'Keyword for action=find (matches title or URL)',
18
+ 'tool.tabs.url': 'URL to open when action=open',
19
+ 'tool.tabs.tab': 'Tab id for action=close/activate',
20
+
21
+ // ── browser_read ───────────────────────────────────────────────────────
22
+ 'tool.read.desc': 'Read page content. what=snapshot lists the elements you can click/fill, each with a [N] ref — call it first when you are about to act, then pass ref=N straight to browser_click / browser_input; that beats guessing selectors (elements inside same-origin iframes are listed too and can be used by ref); text returns the visible text (best for scraping content); html returns the outer HTML; attr returns one attribute; info returns title/URL/viewport and tells you whether an alert/confirm/prompt dialog is blocking the page (if so, call browser_dialog first).',
23
+ 'tool.read.what': 'What to read',
24
+ 'tool.read.selector': 'CSS selector; for snapshot/text/html it defaults to the whole page',
25
+ 'tool.read.name': 'Attribute to read when what=attr, e.g. href',
26
+ 'tool.read.limit': 'Maximum characters to return; default 6000 (8000 for snapshot)',
27
+
28
+ // ── browser_click ──────────────────────────────────────────────────────
29
+ 'tool.click.desc': 'Click something on the page. Most reliable is ref (the number browser_read what=snapshot gave you); next selector or text (find by visible text); failing that, fall back to x/y coordinates. It sends real mouse events (can trigger new windows, dialogs, focus), not synthetic JS clicks. A small cursor appears on the user\'s screen while clicking.',
30
+ 'tool.click.selector': 'CSS selector',
31
+ 'tool.click.text': 'Find the element by its visible text and click it (survives redesigns better than a selector)',
32
+ 'tool.click.x': 'Viewport X coordinate (with y)',
33
+ 'tool.click.y': 'Viewport Y coordinate (with x)',
34
+ 'tool.click.count': 'Number of clicks; default 1 (2 = double click)',
35
+
36
+ // ── browser_input ──────────────────────────────────────────────────────
37
+ 'tool.input.desc': 'Type into the page: type enters text (focusing selector first if given), key presses keys (combos like meta+a work), select picks a dropdown option, upload attaches files, focus focuses, hover hovers, scroll scrolls.',
38
+ 'tool.input.action': 'Input action to perform',
39
+ 'tool.input.text': 'Text to enter when action=type',
40
+ 'tool.input.ref': '%ref; can replace selector',
41
+ 'tool.input.selector': 'CSS selector (for type it is clicked first to focus; select/upload/focus/hover need it or ref)',
42
+ 'tool.input.key': 'Key for action=key, e.g. Enter / Escape / "meta+a" / "ctrl+shift+k"',
43
+ 'tool.input.value': 'Value or option label to pick when action=select',
44
+ 'tool.input.files': 'Absolute local file paths for action=upload (only regular, non-hidden files under the session working directory or the system temp directory)',
45
+ 'tool.input.dy': 'Vertical scroll amount for action=scroll; default 600 (positive scrolls down)',
46
+ 'tool.input.dx': 'Horizontal scroll amount for action=scroll; default 0',
47
+ 'tool.input.x': 'Viewport X for action=hover when no selector is given',
48
+ 'tool.input.y': 'Viewport Y for action=hover when no selector is given',
49
+
50
+ // ── browser_nav ────────────────────────────────────────────────────────
51
+ 'tool.nav.desc': 'Go to a URL (action=go, the default), or go back, forward or reload. All of them wait for the page to finish loading.',
52
+ 'tool.nav.action': 'go navigates to url (default); back / forward / reload need no url',
53
+ 'tool.nav.url': 'Target URL when action=go',
54
+
55
+ // ── browser_screenshot ─────────────────────────────────────────────────
56
+ 'tool.screenshot.desc': 'Screenshot the page; the image is handed straight to you. mode=viewport captures the visible viewport, full the whole page, element a single element (needs ref or selector). The in-page cursor is captured too, so you see the same picture the user does.',
57
+ 'tool.screenshot.mode': 'How much to capture',
58
+ 'tool.screenshot.ref': 'Element to capture when mode=element: %ref',
59
+ 'tool.screenshot.selector': 'Element to capture when mode=element (CSS selector)',
60
+ 'tool.screenshot.format': 'png (default) or jpeg',
61
+
62
+ // ── browser_eval ───────────────────────────────────────────────────────
63
+ 'tool.eval.desc': 'Run a snippet of JS in the page and get the return value back. Good for state that selectors cannot reach, inspecting the DOM, and triggering the page\'s own functions. The return value is JSON-serialized. Note: it runs in page context — do not use it to click (use browser_click).',
64
+ 'tool.eval.expression': 'JS expression to run; wrap multiple statements in an IIFE and return',
65
+
66
+ // ── browser_wait ───────────────────────────────────────────────────────
67
+ 'tool.wait.desc': 'Wait until the page reaches a state, then continue — more reliable than sleep. Pick exactly one of: selector waits for the element to appear (and be visible), text waits for a piece of text to show up, url waits for the URL to contain a substring (handy after a redirect or login). gone=true waits for it to disappear instead (a spinner, say).',
68
+ 'tool.wait.selector': 'CSS selector',
69
+ 'tool.wait.text': 'Text that must appear in the page\'s visible text',
70
+ 'tool.wait.url': 'Substring the URL must contain',
71
+ 'tool.wait.gone': 'true = wait for it to disappear; default false',
72
+ 'tool.wait.timeoutMs': 'Timeout in milliseconds; default 15000, max %max',
73
+
74
+ // ── browser_dialog ─────────────────────────────────────────────────────
75
+ 'tool.dialog.desc': 'Handle alert / confirm / prompt dialogs. A blocking dialog freezes every later action on the page, so when browser_read(what=info) reports one, call this first.',
76
+ 'tool.dialog.action': 'accept confirms, dismiss cancels',
77
+ 'tool.dialog.text': 'Text to enter into a prompt dialog',
78
+
79
+ // ── browser_drag ───────────────────────────────────────────────────────
80
+ 'tool.drag.desc': 'Drag something to another place: sortable lists, kanban cards, sliders, dropping files into a box, canvases and so on. Give the start and the end each as a ref (snapshot number), selector, text (visible text) or x/y coordinates; drop zones ("drop here" boxes) usually have no ref, so toText is the easiest way to find them. Both HTML5 draggable drag-and-drop and mouse-driven components are handled; screenshot or read the page afterwards to confirm the result.',
81
+ 'tool.drag.fromRef': 'Start: %ref',
82
+ 'tool.drag.fromSelector': 'Start: CSS selector',
83
+ 'tool.drag.fromText': 'Start: find the element by visible text',
84
+ 'tool.drag.fromX': 'Start: viewport X (with fromY)',
85
+ 'tool.drag.fromY': 'Start: viewport Y',
86
+ 'tool.drag.toRef': 'End: element ref',
87
+ 'tool.drag.toSelector': 'End: CSS selector',
88
+ 'tool.drag.toText': 'End: find the element by visible text (best for drop zones)',
89
+ 'tool.drag.toX': 'End: viewport X (with toY)',
90
+ 'tool.drag.toY': 'End: viewport Y',
91
+ 'tool.drag.steps': 'How many mouse steps the drag takes; default 12 (raise it for finer slider control)',
92
+
93
+ // ── browser_download ───────────────────────────────────────────────────
94
+ 'tool.download.desc': 'Download the file a link points to (invoice, report, PDF, image …) onto this machine, with the user\'s Chrome logins. Give one of ref (a link\'s snapshot number), selector or url; relative addresses resolve against the page, and blob: / data: links work too. Saved into the "Downloads" folder by default, or into the session working directory with to=workdir; existing files are not overwritten — (1) is appended. If the download control is not a link (the file only exists after a click): click it with browser_click, then find the file URL with browser_devtools action=network and pass that here.',
95
+ 'tool.download.selector': 'CSS selector (pointing at an element with an address: a / img / video / source …)',
96
+ 'tool.download.url': 'URL to download; a relative address is fine',
97
+ 'tool.download.filename': 'File name to save as; defaults to the server-provided name or the name in the URL',
98
+ 'tool.download.to': 'downloads (default) saves into the "Downloads" folder; workdir saves into the session working directory',
99
+
100
+ // ── browser_devtools ───────────────────────────────────────────────────
101
+ 'tool.devtools.desc': 'Inspect a page the way devtools does: console shows console output and JS errors; network shows network requests (status, timing); response shows the body a particular request returned (JSON from an API, say); clear wipes this tab\'s records. When a page "does nothing when clicked", "shows no data" or "is blank", look here first.',
102
+ 'tool.devtools.action': 'What to inspect',
103
+ 'tool.devtools.level': 'action=console: error shows errors only, warning shows errors+warnings, default all',
104
+ 'tool.devtools.filter': 'console/network: keep only entries containing this text (URL, method or content counts)',
105
+ 'tool.devtools.reload': 'action=network: reload the page first to capture every request of the load (only requests after the debugger attached are recorded)',
106
+ 'tool.devtools.request': 'action=response: the number after # in the network list',
107
+ 'tool.devtools.limit': 'console/network: how many entries (default 40); response: how many characters (default 6000)',
108
+
109
+ // ── errors ─────────────────────────────────────────────────────────────
110
+ 'err.dirNotOwned': '%dir is not a directory that belongs only to the current user; refusing to use it',
111
+ 'err.bridgeDown': 'The browser bridge is not running (cannot find %sock): Chrome is not open, or the extension is not loaded.\n%hint',
112
+ 'err.badJson': 'The host returned bad JSON',
113
+ 'err.unknownHostError': 'Unknown error',
114
+ 'err.connect': 'Cannot reach the browser bridge: %message\n%hint',
115
+ 'err.closed': 'The browser bridge connection was closed',
116
+ 'err.timeout': 'Timed out waiting for the browser bridge (%ms)',
117
+ 'err.noActiveTab': 'No active tab',
118
+ 'err.badTab': 'tab must be a tab id (number) or "active"; got "%tab"',
119
+ 'err.noTab': 'No tab given (tab). Use browser_tabs to open (open) or find (list / find) the page you want first, then pass its id as tab; to act on the page the user is looking at, pass tab="active" explicitly. Without tab only the tab you opened or named yourself is reused — the page the user is on is never touched',
120
+ 'err.uploadAbs': 'upload needs absolute paths; got: %path',
121
+ 'err.uploadMissing': 'File not found: %path',
122
+ 'err.uploadHidden': 'Cannot upload a hidden directory / hidden file: %path',
123
+ 'err.uploadOutsideCwd': 'Only files under the session working directory (%cwd) or the system temp directory can be uploaded: %path',
124
+ 'err.uploadOutside': 'Only files under the session working directory or the system temp directory can be uploaded: %path',
125
+ 'err.uploadNotFile': 'Not a regular file: %path',
126
+ 'err.openNeedsUrl': 'action=open needs a url',
127
+ 'err.unknownAction': 'Unknown action: %action',
128
+ 'err.attrNeeds': 'what=attr needs selector and name',
129
+ 'err.unknownWhat': 'Unknown what: %what',
130
+ 'err.clickNeeds': 'Give one of ref, selector, text or x+y',
131
+ 'err.shadowUnsupported': 'Ref %ref is inside the shadow DOM or an iframe, where %action does not support refs yet — use browser_eval instead',
132
+ 'err.typeNeedsText': 'action=type needs text',
133
+ 'err.keyNeedsKey': 'action=key needs key',
134
+ 'err.selectNeedsTarget': 'action=select needs ref or selector',
135
+ 'err.selectNeedsValue': 'action=select needs value',
136
+ 'err.uploadNeedsTarget': 'action=upload needs ref or selector',
137
+ 'err.uploadNeedsFiles': 'action=upload needs files',
138
+ 'err.focusNeedsTarget': 'action=focus needs ref or selector',
139
+ 'err.hoverNeedsTarget': 'action=hover needs ref or selector, or x/y coordinates',
140
+ 'err.navNeedsUrl': 'action=go needs a url',
141
+ 'err.shotNeedsTarget': 'mode=element needs ref or selector',
142
+ 'err.shotZeroSize': 'That element has no size (it may be hidden), so it cannot be captured',
143
+ 'err.waitNeedsOne': 'Give exactly one of selector / text / url',
144
+ 'err.dragNeedsEnd': '%which needs one of %ref, %sel, %txt or %xy',
145
+ 'err.noWorkdir': 'Cannot determine the session working directory; drop to=workdir to save into the "Downloads" folder',
146
+ 'which.start': 'The start',
147
+ 'which.end': 'The end',
148
+
149
+ // ── setup hints appended to errors ─────────────────────────────────────
150
+ 'hint.extOpened': 'I opened chrome://extensions for you (background tab)%store',
151
+ 'hint.extOpenedStore': '; check that DSH Bridge is enabled there',
152
+ 'hint.copied': 'The extension folder path is already on the clipboard (%how)',
153
+ 'hint.copiedMac': 'in the file picker press ⌘⇧G, then ⌘V and Enter',
154
+ 'hint.copiedWin': 'paste it into the file picker\'s address bar and press Enter',
155
+ 'hint.notes': '\n(%notes)',
156
+ 'hint.notesSep': '; ',
157
+ }
package/i18n/index.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 服务端 i18n:工具描述 / 参数说明 / 报错文案的多语言。
3
+ *
4
+ * 为什么不复用 DSH 的 locale 服务:那个(client-locale)只给浏览器端的界面文字用,
5
+ * 工具是注册进模型上下文里的,注册那一刻就得是最终语言。所以这里自己拿字典,
6
+ * 由 config.locale 选一份(见 index.js 的 apply)。
7
+ *
8
+ * 约定和 client.js 一致:字典是普通对象、zh 是基准、缺 key 回落 zh。
9
+ * 占位符用 %name(不是 DSH 的 {name},那个会跟宿主自己的插值撞),支持多字母。
10
+ */
11
+
12
+ import zh from './zh.js'
13
+ import en from './en.js'
14
+ import ru from './ru.js'
15
+
16
+ /** 基准语言:别的字典缺 key 时回落到这里,也是 config.locale 没给/给错时的默认。 */
17
+ export const DEFAULT_LOCALE = 'zh'
18
+
19
+ export const DICTS = { zh, en, ru }
20
+ export const LOCALES = Object.keys(DICTS)
21
+
22
+ /** "en-US" / "EN" → "en";认不出的(含空值)→ 基准语言,不报错。 */
23
+ export function normalizeLocale(value) {
24
+ if (typeof value !== 'string') return DEFAULT_LOCALE
25
+ const tag = value.trim().toLowerCase().split(/[-_]/)[0]
26
+ return LOCALES.includes(tag) ? tag : DEFAULT_LOCALE
27
+ }
28
+
29
+ /** 模板里用到的占位符名字集合;t() 用它判断译文有没有漏掉参数,test-i18n.mjs 用它做对齐检查。 */
30
+ export function placeholders(template) {
31
+ const found = String(template).match(/%[A-Za-z_]\w*/g) || []
32
+ return new Set(found.map((s) => s.slice(1)))
33
+ }
34
+
35
+ /** %name 替换。没给值的占位符原样留着——漏参数要看得见,不能悄悄吞掉。 */
36
+ export function fmt(template, vars) {
37
+ return String(template).replace(/%([A-Za-z_]\w*)/g, (m, key) => (vars && key in vars ? String(vars[key]) : m))
38
+ }
39
+
40
+ /**
41
+ * 按语言造一个 t()。
42
+ * 缺 key → 回落 zh
43
+ * 译文漏了 zh 用到的参数 → 同样回落 zh(不然报错里会少一段细节)
44
+ * key 在 zh 里也没有 → 原样返回 key(方便一眼看出是漏配)
45
+ *
46
+ * dicts 只在测试里传(造一份缺 key / 缺占位符的字典验证兜底),正常调用不用管。
47
+ */
48
+ export function createT(locale, dicts = DICTS) {
49
+ const base = dicts[DEFAULT_LOCALE] || DICTS[DEFAULT_LOCALE]
50
+ const dict = dicts[normalizeLocale(locale)] || base
51
+ return function t(key, vars) {
52
+ let text = Object.hasOwn(dict, key) ? dict[key] : base[key]
53
+ if (text === undefined) return key
54
+ if (vars) {
55
+ const needed = placeholders(base[key])
56
+ if (needed.size) {
57
+ const have = placeholders(text)
58
+ if ([...needed].some((name) => !have.has(name))) text = base[key]
59
+ }
60
+ return fmt(text, vars)
61
+ }
62
+ return text
63
+ }
64
+ }