dsh-codex-style-computer-use 2.3.5 → 3.1.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.
@@ -0,0 +1,145 @@
1
+ // lib/browser/setup-page.js — the one page a human opens to pair a browser.
2
+ //
3
+ // Scope, stated because upstream's equivalent did more: this page pairs a
4
+ // browser and shows the extension folder. No annotation toolbar, no app or
5
+ // connector management, no network capture — those were separate upstream
6
+ // features and are not part of this plugin.
7
+ //
8
+ // Served per response with a fresh CSP nonce. `default-src 'none'` means the page
9
+ // cannot fetch, frame or embed anything but its own `/auth/session` and
10
+ // `/setup/pair` posts; the only script is the invitation exchange plus the copy
11
+ // buttons, both inline under the nonce.
12
+
13
+ import { approvalScript } from './approval.js'
14
+
15
+ function escapeHtml (value) {
16
+ return String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
17
+ }
18
+
19
+ export function setupCsp (nonce) {
20
+ return `default-src 'none'; connect-src 'self'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; ` +
21
+ "base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
22
+ }
23
+
24
+ export function setupPage ({ state, nonce }) {
25
+ const copy = (label, value) => `<button type="button" class="copy" data-copy="${escapeHtml(value)}">${escapeHtml(label)}</button>`
26
+ const connected = state.connected
27
+ const pending = state.pending
28
+
29
+ // A code the human can compare is exactly six digits. Anything else is shown
30
+ // as inert text rather than as a row whose "allow" would mean "approve
31
+ // whatever is pending".
32
+ const requests = pending.map(entry => `<li><strong>验证码 ${escapeHtml(/^\d{6}$/.test(entry.code) ? entry.code : '——————')}</strong>
33
+ <form method="post" action="/setup/pair"><input type="hidden" name="key" value="">
34
+ <input type="hidden" name="id" value="${escapeHtml(entry.id)}">
35
+ <button name="action" value="allow" disabled>允许</button>
36
+ <button name="action" value="deny" disabled>拒绝</button></form></li>`).join('')
37
+
38
+ const install = `<div class="step"><span class="number">1</span><div>
39
+ <h2>加载浏览器扩展</h2>
40
+ <p>扩展管理页不能被网页直接打开。请按下面的顺序操作,两个复制按钮共用剪贴板,先复制地址、后复制目录,中间别在别处复制别的路径。</p>
41
+ <ol class="steps">
42
+ <li><strong>先复制管理页地址。</strong>Chrome 用 <code>chrome://extensions</code>,Edge 用 <code>edge://extensions</code>。
43
+ <div class="actions">${copy('复制 Chrome 管理页地址', 'chrome://extensions')}${copy('复制 Edge 管理页地址', 'edge://extensions')}</div></li>
44
+ <li>粘到地址栏,在<strong>新标签页</strong>打开扩展管理页。原标签页先留着,后面要用。</li>
45
+ <li><strong>再回到本页复制扩展目录</strong>——它会覆盖剪贴板里刚才的地址,所以务必先完成上一步。
46
+ <div class="path"><code>${escapeHtml(state.extensionPath)}</code>${copy('复制扩展目录路径', state.extensionPath)}</div>
47
+ <p class="hint">选择器里只会列出子目录,不显示目录中的文件。这个目录里即使有 manifest.json,打开时也可能看起来是空的——这是正常的,直接选中整个文件夹即可,不必进入其中。</p></li>
48
+ <li>回到扩展管理页,开启开发者模式(Edge 称为开发人员模式)。</li>
49
+ <li>点「加载未打包的扩展程序」;Edge 里同一项写作「加载解压缩的扩展」。</li>
50
+ <li>在选择窗口底部的文件夹栏里粘贴刚复制的目录路径,点「选择文件夹」。</li>
51
+ <li>如果只是进入了这个目录、并没有装上,再点一次「选择文件夹」。</li>
52
+ </ol>
53
+ <p class="hint">装好后扩展列表里会出现「DSH Computer Use Browser」,确认它处于启用状态,再继续下一步。已安装可直接进行下一步。</p>
54
+ </div></div>`
55
+
56
+ const pairing = `<section class="card step"><span class="number">2</span><div>
57
+ <h2>核对验证码,确认连接</h2>
58
+ <p>扩展弹窗会显示一个 6 位验证码;点开扩展图标即可看到。与下面某一行一致时点击「允许」。每个验证码只属于一个请求。</p>
59
+ ${requests ? `<ul class="requests">${requests}</ul>`
60
+ : '<div class="waiting"><span class="dot"></span>正在等待扩展发来请求…</div><p class="hint">加载扩展后会自动出现,无需手动输入验证码。</p>'}
61
+ </div></section>`
62
+
63
+ const success = `<section class="success"><h2>连接已就绪</h2>
64
+ <p>桥接端口 ${state.port}</p>
65
+ <p>回到 DSH 用 <kbd>@</kbd> 选择要操作的标签页。只有在对话里被引用的页面才会被操作,登录状态一直留在你的浏览器里。</p>
66
+ <p class="hint">要再连一个浏览器,重复上面两步即可;多个浏览器配置可以同时在线。</p></section>`
67
+
68
+ const help = `<details class="help"><summary>连接帮助与本地 HTML</summary>
69
+ <p>如果扩展显示 OFF,打开扩展弹窗确认「连接 DSH」是打开的,并在「连接设置」里把端口设为 <code>${state.port}</code>。</p>
70
+ <p>本地 HTML:在扩展详情里开启「允许访问文件网址」,之后已打开的 .html 标签页就会出现在列表里。${state.allowFile ? '' : '当前插件设置未允许本地文件页面,开启后才会列出。'}</p>
71
+ <p>扩展只连接本机 ${state.port},不读取也不导出 Cookie;没有给模型的自由 CDP / 脚本执行接口,也没有常驻调试端口。</p>
72
+ <p>浏览器内部页面(chrome://、edge://、扩展页)和扩展商店既不会列出,也不会被操作。</p>
73
+ </details>`
74
+
75
+ const body = `<main><header>
76
+ <div class="mark" aria-hidden="true"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a16 16 0 0 1 0 18 16 16 0 0 1 0-18"/></svg></div>
77
+ <div><h1>连接你的浏览器</h1><p class="product">DSH 电脑操控 · 浏览器连接(本机)</p></div>
78
+ <span role="status" class="badge ${connected ? 'online' : ''}">${connected ? '已连接' : pending.length ? '待确认' : '等待连接'}</span>
79
+ </header>
80
+ <p class="intro">让对话接着你已有的标签页工作:保留登录态,用 <kbd>@</kbd> 选择页面。扩展只连接本机 ${state.port},与你已装的其他浏览器插件互不干扰。</p>
81
+ ${connected ? success : ''}
82
+ ${connected ? `<details><summary>再连接一个浏览器</summary>${install}</details>`
83
+ : `<section class="card">${pending.length ? `<details><summary>扩展已发来请求 · 查看安装步骤</summary>${install}</details>` : install}</section>`}
84
+ ${!connected || requests ? pairing : ''}
85
+ ${help}
86
+ <p id="approval-status" role="status">批准连接前,请从 DSH 的浏览器设置打开本页。</p>
87
+ <footer><span>DSH 电脑操控 · 本机连接</span><a href="/setup">刷新状态</a></footer></main>`
88
+
89
+ const script = `
90
+ ${approvalScript('setup', 'Open this page from the DSH browser settings to confirm the connection.')}
91
+ approvalReady.then(key => {
92
+ for (const form of document.querySelectorAll('form')) {
93
+ form.elements.key.value = key;
94
+ for (const button of form.querySelectorAll('button')) button.disabled = false;
95
+ }
96
+ document.querySelector('#approval-status').textContent = 'DSH 已打开本次确认窗口,请核对扩展弹窗里的验证码';
97
+ }).catch(error => { document.querySelector('#approval-status').textContent = error.message; });
98
+ for (const button of document.querySelectorAll('.copy')) button.addEventListener('click', async () => {
99
+ const value = button.dataset.copy;
100
+ try { await navigator.clipboard.writeText(value); } catch {
101
+ const field = document.createElement('textarea');
102
+ field.value = value;
103
+ document.body.append(field);
104
+ field.select();
105
+ document.execCommand('copy');
106
+ field.remove();
107
+ }
108
+ const label = button.textContent;
109
+ button.textContent = '已复制';
110
+ setTimeout(() => { button.textContent = label; }, 1500);
111
+ });`
112
+
113
+ // Poll only while nothing is pending: a meta refresh would fight the approve
114
+ // buttons the moment the invitation script enables them.
115
+ const refresh = pending.length || connected ? '' : '<meta http-equiv="refresh" content="3">'
116
+
117
+ return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${refresh}
118
+ <title>DSH 电脑操控 · 浏览器连接</title><style>
119
+ :root{color-scheme:light dark;--ink:#242424;--muted:#666;--ground:#fafafa;--surface:#fff;--soft:#f3f3f3;--line:#e2e2e2;--control:#ccc;--focus:#0066cc;--positive:#287447}
120
+ *{box-sizing:border-box}body{margin:0;padding:44px 22px;font:14px/1.7 "Segoe UI","Microsoft YaHei UI","Microsoft YaHei","Noto Sans CJK SC",sans-serif;color:var(--ink);background:var(--ground)}
121
+ main{max-width:760px;margin:auto}header{display:flex;align-items:center;gap:14px}.mark{display:grid;place-items:center;flex:none;color:var(--ink)}
122
+ .product{color:var(--muted);font-size:12px;margin:4px 0 0}h1{font-size:25px;line-height:1.3;letter-spacing:-.5px;margin:0;font-weight:600}
123
+ h2{font-size:16px;margin:0 0 6px;font-weight:600}p{margin:6px 0 12px}.intro{margin:22px 0;color:var(--muted);max-width:65ch}
124
+ .badge{margin-left:auto;white-space:nowrap;border:1px solid var(--line);padding:3px 10px;border-radius:20px;font-size:12px;color:var(--muted)}.online{color:var(--positive)}
125
+ .card,.success{padding:22px;margin:16px 0;background:var(--surface);border:1px solid var(--line);border-radius:12px}.success h2{color:var(--positive)}
126
+ .step{display:flex;gap:16px}.step>div{min-width:0;flex:1}.number{flex-shrink:0;width:26px;height:26px;background:var(--soft);color:var(--muted);border-radius:6px;text-align:center;font-weight:500;font-variant-numeric:tabular-nums}
127
+ .actions{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0}.path{display:flex;align-items:center;gap:12px;padding:12px;background:var(--soft);border-radius:6px}
128
+ .path code{flex:1;min-width:0;overflow-wrap:anywhere;font:12px/1.6 ui-monospace,monospace}
129
+ button{border:1px solid var(--control);background:var(--surface);color:var(--ink);padding:8px 12px;min-height:36px;border-radius:6px;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
130
+ button:hover:not(:disabled){background:var(--soft)}button:disabled{opacity:.5;cursor:default}
131
+ button:focus-visible,a:focus-visible,summary:focus-visible{outline:2px solid var(--focus);outline-offset:3px}
132
+ .hint{color:var(--muted);font-size:12px;margin-top:10px}ul{padding:0;list-style:none;margin:12px 0}
133
+ .steps{padding-left:20px;margin:12px 0}.steps li{margin:6px 0}
134
+ .steps .actions{margin:8px 0 2px}.steps .path{margin:8px 0 2px}.steps .hint{margin-top:6px}
135
+ .requests li{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:12px;border:1px solid var(--line);border-radius:8px;margin-bottom:8px}
136
+ .requests form{display:flex;gap:8px;margin-left:auto}.waiting{display:flex;align-items:center;gap:8px;color:var(--muted);padding:14px 0}
137
+ .dot{width:8px;height:8px;border-radius:50%;background:var(--muted);animation:pulse 1.4s ease-in-out infinite}
138
+ @keyframes pulse{50%{opacity:.25}}@media(prefers-reduced-motion:reduce){.dot{animation:none}}
139
+ .help{margin:18px 0;color:var(--muted)}.help code{font-size:12px;overflow-wrap:anywhere}.help p{font-size:12px}
140
+ kbd{font:12px/1 ui-monospace,monospace;border:1px solid var(--line);border-radius:4px;padding:2px 5px;background:var(--soft)}
141
+ footer{display:flex;justify-content:space-between;gap:12px;margin-top:26px;padding-top:14px;border-top:1px solid var(--line);font-size:12px;color:var(--muted)}
142
+ a{color:var(--ink);text-underline-offset:3px}#approval-status{font-size:12px;color:var(--muted)}
143
+ @media(prefers-color-scheme:dark){:root{--ink:#eee;--muted:#b5b5b5;--ground:#1b1b1b;--surface:#232323;--soft:#2c2c2c;--line:#3a3a3a;--control:#6d6d6d;--focus:#82b5ff;--positive:#5fbf8a}}
144
+ </style><body>${body}<script nonce="${nonce}">${script}</script></body></html>`
145
+ }
@@ -2,6 +2,6 @@
2
2
  "format": 1,
3
3
  "platform": "win32",
4
4
  "architecture": "x64",
5
- "sourceSha256": "96928659d137ba3485d6fc838ae5b601e8696e9313946f8000439405dc7dc003",
6
- "binarySha256": "6ceb7cdc437295198b9d6844fa69a979d8303b6b477b43c15510658fd2ff3892"
5
+ "sourceSha256": "837b42e54f24491ee824f91ec6a08062194519a499268f3789e825cb8499d70a",
6
+ "binarySha256": "30e5ad952ef75d8e68f36dab2af3aab3705c25cf6bb8020180e3bfaff4dd3433"
7
7
  }
package/lib/core/index.js CHANGED
@@ -36,6 +36,14 @@ const URGENT_CONTROL = new Set(['cancelInput', 'abort', 'panic', 'exit', 'endAsk
36
36
  const INPUT_OPS = new Set(['click', 'shiftClick', 'move', 'drag', 'scroll', 'selectRange',
37
37
  'type', 'key', 'uiaAct', 'windowOp', 'activate', 'clipWrite', 'calibrate', 'selftest'])
38
38
  const isInputOp = (op, args = {}) => INPUT_OPS.has(op) || (op === 'focus' && args.refocus === true)
39
+ // Ops that READ the machine and never touch it. A caller outside the tool surface (the `@` menu's
40
+ // running-application inventory) may ask one of these at any time, including while no cycle exists,
41
+ // and must not light the cycle, arm the human monitors or take a desktop lease by doing so.
42
+ //
43
+ // This is an ALLOWLIST ON PURPOSE: anything that could dispatch input, focus, activate, launch or
44
+ // change a window is absent, so a future op cannot silently inherit "passive" by being forgotten
45
+ // here — it simply stays unavailable to `callPassive`.
46
+ const PASSIVE_OPS = new Set(['windows', 'screens', 'cursor', 'ping', 'probe'])
39
47
  // THE CORE'S ASK DEADLINE, AND IT IS A BARE LITERAL ON PURPOSE (merge-design.md §3, §3.2).
40
48
  //
41
49
  // It bounds ONE thing: a wedged worker inside `beginAsk`'s raise sequence (a hung UIA provider), or
@@ -361,6 +369,32 @@ export class ComputerUse extends EventEmitter {
361
369
  return this.inputContext.run({ internalCleanup: true }, () => this.call(op, args, timeoutMs, killOnTimeout, beforeDispatch))
362
370
  }
363
371
 
372
+ /**
373
+ * Read the machine WITHOUT starting, lighting or arming anything.
374
+ *
375
+ * THE DEFECT THIS EXISTS FOR (measured on the real 3.0.0 build): typing `@` in the composer
376
+ * listed running applications, the inventory called `cu.call('windows')`, and `call()` signs
377
+ * EVERY request with `__cycle: true`. The worker treats a signed cycle op as "an agent cycle is
378
+ * live" and lights the cyan breathing border plus the human monitors — off a pure read, before
379
+ * the human had chosen anything, with no driving call behind it and no ordinary way to stop it.
380
+ *
381
+ * A passive read is stamped `__cycle: false`, so the worker's own cycle gate stays shut: nothing
382
+ * is lit, nothing is armed, and the desktop lease is untouched. It is deliberately restricted to
383
+ * `PASSIVE_OPS`, and it never sends `__inputSeries` — it cannot drive the machine even if a
384
+ * caller passes driving-looking arguments.
385
+ *
386
+ * It does NOT clear a brake, resume a cycle or bypass `Panic.CheckOp`: a stopped session still
387
+ * refuses, and an exited one still reports its record. Only the lighting is suppressed.
388
+ */
389
+ callPassive (op, args = {}, timeoutMs = DEFAULT_TIMEOUT_MS, killOnTimeout = false) {
390
+ if (!PASSIVE_OPS.has(op)) throw new Error(`unsupported passive read operation: ${String(op)}`)
391
+ if (isInputOp(op, args)) throw new Error(`unsupported passive read operation: ${String(op)}`)
392
+ // `passive` is its own flag, NOT `internalCleanup`: cleanup is an authority for releasing input,
393
+ // and a future change to it must not silently widen what a read may do. It has exactly two
394
+ // readers in `call()`: the `__cycle` signature and the host-written `__passiveRead` mark.
395
+ return this.inputContext.run({ passive: true }, () => this.call(op, args, timeoutMs, killOnTimeout))
396
+ }
397
+
364
398
  async cancelRequest (requestId, child, reason, killOnFailure = true) {
365
399
  const cleanup = { requestId, workerGeneration: this.workerGeneration, requested: true,
366
400
  cleanupConfirmed: false, cleanupState: 'unconfirmed', workerKilled: false }
@@ -420,7 +454,30 @@ export class ComputerUse extends EventEmitter {
420
454
  requestId: id, workerGeneration: generation, runtime: this.runtime,
421
455
  })
422
456
  // __cycle is signed last. A caller cannot forge another input series or turn.
423
- const signed = { ...args, __cycle: context?.internalCleanup !== true, __kickoff: this.kickoffRequired }
457
+ //
458
+ // `__cycle:false` means "this call does not light or arm the cycle", and there are exactly two
459
+ // authorities for it: internal cleanup (which runs under its own explicit authority) and a
460
+ // passive read (`callPassive`). Neither can dispatch input, so neither can open a cycle.
461
+ //
462
+ // `__passiveRead` is a SEPARATE, narrower mark and it is NOT a licence to skip checks. It exists
463
+ // because `__cycle:false` alone still took the desktop lease: measured in 3.1.0, the `@` candidate
464
+ // list called `windows` through `callPassive`, the worker's `Handle()` ran
465
+ // `EnsureDesktopOwnership(op)` unconditionally and wrote `owner=native cycle: windows`, holding the
466
+ // handle — so another conversation could be refused the machine by a read that never touched it.
467
+ // The worker honours this mark ONLY for a strict allowlist of side-effect-free ops with no
468
+ // arguments of consequence (see `EnsureDesktopOwnership`); every real control, screenshot,
469
+ // inspection and input op keeps its ownership check exactly as before.
470
+ const passive = context?.internalCleanup === true || context?.passive === true
471
+ const signed = { ...args, __cycle: !passive, __kickoff: this.kickoffRequired }
472
+ // THE MARK IS WRITTEN BY THE HOST, NOT MERELY DEFAULTED.
473
+ //
474
+ // `{ ...args }` above copies whatever the caller sent, so a plain `call('windows', {
475
+ // __passiveRead: true })` would otherwise arrive at the worker carrying a forged exemption. Both
476
+ // branches are therefore explicit: a passive read sets `true`, EVERY other call DELETES the key.
477
+ // Stamping only the true case (the previous shape) left a caller-supplied value in place for
478
+ // ordinary calls, which is exactly the contract this marker must not have.
479
+ if (context?.passive === true) signed.__passiveRead = true
480
+ else delete signed.__passiveRead
424
481
  if (input) signed.__inputSeries = context?.inputSeries || randomUUID()
425
482
  // The two host-driving gates travel with EVERY call so the worker can decide per request:
426
483
  // gate 1 = the calling conversation is full permission, gate 2 = debug mode was switched on by
@@ -3592,6 +3592,35 @@ namespace DshComputerUse.Worker
3592
3592
  error.Data["outcome"] = "not-dispatched"; throw error;
3593
3593
  }
3594
3594
  }
3595
+ /// <summary>
3596
+ /// Is this request a PURE READ that must not take, replace or release the desktop lease?
3597
+ ///
3598
+ /// MEASURED IN 3.1.0: the `@` candidate list builds its inventory with
3599
+ /// `createAppInventory({cu}).list('', {refresh:true})`, which reaches `windows`. That read ran
3600
+ /// `EnsureDesktopOwnership("windows")`, so a query that only ENUMERATES windows acquired the
3601
+ /// lease, wrote `owner=native cycle: windows` to the owner file and held the handle — another
3602
+ /// conversation could then be refused the desktop by a call that never touched it.
3603
+ ///
3604
+ /// THREE CONDITIONS, ALL REQUIRED, and none of them can be produced by a caller:
3605
+ /// * `__passiveRead` — written by the HOST (lib/core/index.js), which also DELETES it on
3606
+ /// every ordinary call, so a tool argument of the same name cannot survive;
3607
+ /// * `__cycle` STRICTLY false — a passive read never lights or arms the cycle, and a request
3608
+ /// that asks for a cycle op is by definition not this one;
3609
+ /// * the exact pure-enumeration shape of `windows` — its other modes (`feedbackHwnd`,
3610
+ /// `inspectHwnd`, `appQuery`) take a target and keep the ordinary check.
3611
+ ///
3612
+ /// Anything else keeps the full ownership gate. This is an allowlist: a new op is never exempt
3613
+ /// by being forgotten here.
3614
+ /// </summary>
3615
+ static bool IsPassiveDesktopRead(string op, Dictionary<string, object> a)
3616
+ {
3617
+ if (a == null || !GetB(a, "__passiveRead", false)) return false;
3618
+ if (GetB(a, "__cycle", true)) return false;
3619
+ // `windows` is the ONLY op with a pure enumerating mode.
3620
+ if (op != "windows") return false;
3621
+ // Arguments are inspected, not trusted: the target-carrying forms are different modes.
3622
+ return !a.ContainsKey("feedbackHwnd") && !a.ContainsKey("inspectHwnd") && !a.ContainsKey("appQuery");
3623
+ }
3595
3624
  public static void ReleaseDesktopOwnership()
3596
3625
  {
3597
3626
  lock (InputLock)
@@ -4205,7 +4234,9 @@ namespace DshComputerUse.Worker
4205
4234
  // No other input may use the flag to skip the controls and then dispatch.
4206
4235
  if (dryInput && (op != "click" || !args.ContainsKey("x") || !args.ContainsKey("y")))
4207
4236
  return Err("UNSUPPORTED_DRY_RUN: native input simulation requires a click with x and y; no input was dispatched.");
4208
- EnsureDesktopOwnership(op);
4237
+ // A pure window enumeration neither takes, replaces nor releases the desktop lease: it is
4238
+ // the `@` candidate list, which must stay silent on a machine someone else is driving.
4239
+ if (!IsPassiveDesktopRead(op, args)) EnsureDesktopOwnership(op);
4209
4240
  int requestId = GetI(request, "id", 0);
4210
4241
  bool ignored;
4211
4242
  _activeRequestId = requestId;
package/lib/index.js CHANGED
@@ -44,6 +44,7 @@ import { acknowledge, isAcked, ACK_HINT, isDrivingCall } from './skill-gate.js'
44
44
  import { mkDataDir, snapshotPath, installAudit, appendGate, gateArgSummary, redactReasonText } from './audit.js'
45
45
  import { registerTools, isCycleStateOnly } from './tools.js'
46
46
  import { installToolExposure, ACTIVATION_TOOL } from './exposure.js'
47
+ import { browserPolicyDecision } from './browser/policy.js'
47
48
  import { scopeOf } from '@deepseek-ai/dsh-scope'
48
49
  import { createCycleGate, agentKeyOf } from './cycle.js'
49
50
  import { recoveryProblem } from './recovery.js'
@@ -52,6 +53,50 @@ import { createLeaveTimer } from './leave-timer.js'
52
53
  import { createTerminalCleanup } from './terminal-cleanup.js'
53
54
  import fs from 'node:fs'
54
55
 
56
+ // ---- the browser partition -------------------------------------------------------------------
57
+ //
58
+ // THE BROWSER IS A DIFFERENT KIND OF TARGET FROM THE DESKTOP, and the point of adding it is exactly
59
+ // the difference: a page the human cited stays in THEIR window and THEIR tab, and it is driven in
60
+ // the background — no window is borrowed, nothing is moved, the desktop pointer is never touched.
61
+ //
62
+ // THE IMPORT IS LAZY AND OPTIONAL ON PURPOSE. The browser halves are separate modules with their
63
+ // own (optional) runtime dependencies; a profile that has no browser extension paired must still
64
+ // load this plugin and get every desktop tool. A static import would make a missing `playwright-core`
65
+ // a plugin-load failure for everyone, so `apply()` asks for the module inside a try/catch and the
66
+ // desktop surface degrades to "browser unavailable", which is the truth.
67
+ //
68
+ // `installAppReferences` (lib/references.js, written by another partition) is attached the same way:
69
+ // it is an ENHANCEMENT to the `@` experience, never a precondition for these tools, so a checkout
70
+ // that does not have that file yet keeps loading and testing exactly as before.
71
+ let browserModule = null
72
+ async function loadBrowserModule (log) {
73
+ if (browserModule !== null) return browserModule
74
+ try {
75
+ const [host, bridge] = await Promise.all([
76
+ import('./browser/host.js'),
77
+ import('./browser/bridge.js'),
78
+ ])
79
+ browserModule = { ...host, BrowserBridge: bridge.BrowserBridge }
80
+ } catch (error) {
81
+ browserModule = false
82
+ log?.info?.(`browser partition unavailable: ${error?.message ?? error}`)
83
+ }
84
+ return browserModule
85
+ }
86
+
87
+ /** Load the optional reference integration; absent, unbuilt or broken is a log line, never a throw. */
88
+ async function loadAppReferences (log) {
89
+ try {
90
+ const module = await import('./references.js')
91
+ return typeof module.installAppReferences === 'function' ? module.installAppReferences : null
92
+ } catch (error) {
93
+ if (error?.code !== 'ERR_MODULE_NOT_FOUND') {
94
+ log?.warn?.(`reference integration unavailable: ${error?.message ?? error}`)
95
+ }
96
+ return null
97
+ }
98
+ }
99
+
55
100
  /**
56
101
  * Build a REAL user message for `agent.steer()` / `agent.inject()`.
57
102
  *
@@ -422,6 +467,23 @@ export const Config = Schema.object({
422
467
  Schema.const('stop').description('legacy value; ignored'),
423
468
  Schema.const('recommended').description('legacy value; ignored'),
424
469
  ]).default('stop').description('legacy setting; ignored — ordinary completion releases computer use automatically'),
470
+
471
+ // ---- the browser partition (see lib/browser/host.js) ---------------------------------------
472
+ // The browser tools are NOT part of the desktop surface: they act on a page the human cited, in
473
+ // the human's own browser, without moving a window or the pointer. Their settings therefore stay
474
+ // separate, and every default keeps the feature OFF until a person turns it on.
475
+ browserEnabled: Schema.boolean().default(true)
476
+ .description('enable the browser partition at all (tools appear only for a conversation that cited a page with @ or enabled a browser window)'),
477
+ browserPort: Schema.number().default(43188)
478
+ .description('local port the browser bridge listens on; 0 asks the OS for a free one'),
479
+ browserTools: Schema.union([
480
+ Schema.const('on-demand').description('register per Agent, after a citation or an enabled window (recommended)'),
481
+ Schema.const('always').description('register the browser tools for every Agent'),
482
+ ]).default('on-demand').description('how browser tools are exposed'),
483
+ browserAllowFile: Schema.boolean().default(false)
484
+ .description('allow a local .html/.htm page the user cited with @; UNC and non-HTML files stay refused'),
485
+ browserSnapshotChars: Schema.number().default(2400)
486
+ .description('default character budget for a browser DOM read (400–8000)'),
425
487
  })
426
488
 
427
489
  // ---- host-driving debug gates: the settings page talks to this same-origin route ----
@@ -511,8 +573,7 @@ export function apply (ctx, config) {
511
573
  log.warn('DSH_COMPUTER_USE_KILL=1 — plugin disabled by kill switch')
512
574
  return
513
575
  }
514
- if (!config.enabled) return
515
- // Kept in scope: the gate's diagnostics report whether the legacy-attribution seam is live,
576
+ if (!config.enabled) return // Kept in scope: the gate's diagnostics report whether the legacy-attribution seam is live,
516
577
  // because "the misleading wording reached the model" and "the seam was never installed" are
517
578
  // different bugs and the next report must not have to guess which one happened.
518
579
  const approvalSeam = installApprovalAttribution(ctx, log)
@@ -565,6 +626,185 @@ export function apply (ctx, config) {
565
626
  })
566
627
  const detachAudit = installAudit(cu, dataDir)
567
628
 
629
+ // ---- THE BROWSER PARTITION ------------------------------------------------------------------
630
+ //
631
+ // It is installed LAZILY and independently of the desktop core: a profile with no browser
632
+ // extension, a port already taken, or a missing Playwright install must still get every desktop
633
+ // tool. `installBrowser` therefore never throws into `apply`; it logs and leaves `browserPartition`
634
+ // null, which the pre-execute hook above reports as an honest denial for a browser tool name.
635
+ //
636
+ // WHERE THE TOOLS COME FROM: lib/browser/host.js registers them per Agent, only after that
637
+ // conversation cited a tab with @ or had a window enabled in the sidebar. An ordinary desktop
638
+ // session — including one that already has another browser plugin's tools — keeps zero browser
639
+ // tools of ours, so no duplicate toolbar appears and no other plugin's flow is touched.
640
+ let browserPartition = null
641
+ // ---- THE CONTROL-SURFACE PORTS, AND WHY A SNAPSHOT WAS WRONG -------------------------------
642
+ //
643
+ // A loopback page on a port that serves DSH's own UI is the control surface: reading or clicking
644
+ // it through a browser tab would be a second, unapproved way to press the human's own approval
645
+ // and Stop buttons — precisely what the desktop host gate exists to prevent. The first version of
646
+ // this gathered those ports ONCE, while `apply()` ran, and an independent run on the real DSH
647
+ // process proved the hole: `/api/computer-use/browser/list` still returned the DSH UI's own tab
648
+ // (`hostPageInList:true`) because `webServer.port` was not readable yet at that moment, and the
649
+ // bridge's own bound port (config 0 ⇒ OS-assigned) was not known either.
650
+ //
651
+ // So the port set is LIVE and has THREE sources, in decreasing order of trust:
652
+ // 1. `req.socket.localPort` on an AUTHENTICATED request to our own routes — the port this host
653
+ // actually answered on, taken from the socket. It cannot be forged by a request header, and
654
+ // it is observed at exactly the moment the browser UI is using it.
655
+ // 2. the injected `webServer` service's own `port` (`sctx.webServer.port`), read when it mounts
656
+ // and re-read whenever it can have moved.
657
+ // 3. the bridge's bound port, once it has started (an unbound/`0` config resolves at listen).
658
+ // Every addition updates BOTH `BrowserAccess` and the bridge's `protectedPorts`, and a new port
659
+ // invalidates the cached inventory so a tab listed under the old set cannot stay listed.
660
+ const hostPorts = new Set()
661
+ const rememberHostPort = (value) => {
662
+ const port = Number(value)
663
+ if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) return false
664
+ if (hostPorts.has(port)) return false
665
+ hostPorts.add(port)
666
+ const bridge = browserPartition?.bridge
667
+ if (bridge) {
668
+ const existing = Array.isArray(bridge.protectedPorts) ? bridge.protectedPorts : []
669
+ if (!existing.includes(port)) bridge.protectedPorts = [...existing, port]
670
+ }
671
+ const host = browserPartition?.host
672
+ if (host) {
673
+ host.access.guardPort(port)
674
+ // A port discovered AFTER a listing must invalidate what was cached under the old set, or a
675
+ // tab that became a control surface would stay usable until the next reconnect.
676
+ try { host.revalidateInventory?.() } catch { /* never break the caller */ }
677
+ }
678
+ return true
679
+ }
680
+ const guardedBrowserPorts = () => {
681
+ const ports = new Set(hostPorts)
682
+ // Re-read the live service each call: it is authoritative and may have re-bound.
683
+ try {
684
+ const web = ctx.get?.('webServer')
685
+ const port = Number(web?.port)
686
+ if (Number.isSafeInteger(port) && port > 0) ports.add(port)
687
+ } catch { /* no web server mounted */ }
688
+ try {
689
+ const b = browserPartition?.bridge
690
+ const port = Number(b?.port)
691
+ if (b?.started && Number.isSafeInteger(port) && port > 0) ports.add(port)
692
+ } catch { /* not started yet */ }
693
+ return [...ports]
694
+ }
695
+ const installBrowser = () => {
696
+ if (config.browserEnabled === false) return
697
+ void (async () => {
698
+ const module = await loadBrowserModule(log)
699
+ if (!module) return
700
+ try {
701
+ const bridge = new module.BrowserBridge({
702
+ home: path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'browser-tabs'),
703
+ port: config.browserPort ?? 43188,
704
+ // Whatever ports the host and the bridge itself own are OFF LIMITS as browsing targets,
705
+ // so a page can never read or click DSH's own control surface (its approvals, its Stop
706
+ // button) instead of the human.
707
+ protectedPorts: guardedBrowserPorts(),
708
+ })
709
+ const host = new module.BrowserHost({
710
+ bridge,
711
+ ctx,
712
+ config: { ...config, scopeOf },
713
+ log,
714
+ guardedPorts: guardedBrowserPorts,
715
+ artifacts: path.join(dataDir.root, 'browser-captures'),
716
+ // THE HOST'S OWN COMPILER. The browser tools must be compiled by exactly the same
717
+ // `defineTool` the desktop tools use, so their registry schema cannot be a property map.
718
+ defineTool,
719
+ })
720
+ browserPartition = { module, bridge, host }
721
+ host.installRoutes()
722
+ // Any port learned before the host existed is applied now; `rememberHostPort` skips
723
+ // `undefined` partitions, so a port discovered during bridge start is not lost.
724
+ for (const port of hostPorts) {
725
+ host.access.guardPort(port)
726
+ if (!bridge.protectedPorts.includes(port)) bridge.protectedPorts = [...bridge.protectedPorts, port]
727
+ }
728
+ // THE HOST'S OWN LISTENING PORT, registered where the service actually lives. `webServer` is
729
+ // injected (not read off the root context), and the port is read at mount time and again on
730
+ // every mount callback, so a re-bound server is still guarded. This is the piece the first
731
+ // version was missing: the real DSH process listed its own UI tab because nothing had
732
+ // recorded this port yet.
733
+ try {
734
+ ctx.inject(['webServer'], (sctx) => {
735
+ const port = Number(sctx?.webServer?.port)
736
+ if (rememberHostPort(port)) log.info(`browser: guarding the DSH web server port ${port}`)
737
+ // Some hosts assign the port after this injection callback; re-read when it settles.
738
+ const timer = setTimeout(() => {
739
+ const later = Number(sctx?.webServer?.port)
740
+ if (rememberHostPort(later)) log.info(`browser: guarding the DSH web server port ${later}`)
741
+ }, 1500)
742
+ timer.unref?.()
743
+ sctx.effect?.(() => () => { try { clearTimeout(timer) } catch { /* gone */ } })
744
+ })
745
+ } catch (error) {
746
+ log.info(`browser: could not observe the web server port (${error?.message ?? error})`)
747
+ }
748
+ // Every authenticated request to our own routes also reports the socket's local port, which
749
+ // is the un-forgeable answer to "which port did this host actually serve on".
750
+ host.hostPortHook = rememberHostPort
751
+ // ---- THE FIRST-TURN WINDOW, AT THE ONLY SEAM EARLY ENOUGH ------------------------------
752
+ //
753
+ // Verified against the installed `@deepseek-ai/dsh-agent-loop` (2026-11-28). Inside
754
+ // `preStep`:
755
+ //
756
+ // 683 const claimed = this.inbox.claim(target, position.turn) — emits SYNCHRONOUSLY
757
+ // 686 const toolSet = await this.loopCtx.tools.resolve({...}) — THE ADMISSION SNAPSHOT
758
+ // 698 await this.dispatch.waterfall("agent/pre-step", ...) — too late for this snapshot
759
+ //
760
+ // `Inbox.claim` runs `emit("agent/inbox/claimed", {message, turn})` for every claimed
761
+ // message BEFORE returning, so a synchronous listener here runs before `tools.resolve()`
762
+ // and the tools land in the SAME turn's request header. `agent/pre-step` (line 698) is one
763
+ // snapshot too late — measured: the first request carried only the desktop tools while the
764
+ // `<browser_context>` block was already correct, and the second message worked.
765
+ //
766
+ // `session/event` → `user/message` is later still (it is persisted during the turn), so it
767
+ // cannot be used for this.
768
+ //
769
+ // THE LISTENER MUST NOT AWAIT: a single `await` yields to the microtask queue and lets
770
+ // `tools.resolve()` snapshot first, reintroducing the delay. Registration is therefore
771
+ // synchronous; the GRANT is still decided in the accepted pre-step from the claimed batch.
772
+ ctx.on('agent/inbox/claimed', payload => {
773
+ try {
774
+ host.noteClaimed({ agent: payload?.agent ?? null, message: payload?.message ?? null, turn: payload?.turn ?? null })
775
+ } catch { /* a timing shortcut must never break a turn */ }
776
+ })
777
+ // The citation seam: `agent/pre-step` sees the CLAIMED user input before any context is
778
+ // appended, which is the only place a real `@` citation can be read from.
779
+ ctx.on('agent/pre-step', (payload, next) => host.preStep(payload, next), { prepend: true })
780
+ ctx.on('agent/disposed', (payload) => {
781
+ try {
782
+ host.detach(payload?.agent || payload)
783
+ host.forget(sessionKey((payload?.agent || payload)?.session) || null)
784
+ } catch { /* disposal must never throw into the host */ }
785
+ })
786
+ ctx.effect(() => () => { try { host.close() } catch { } })
787
+ log.info(`browser partition installed (port ${config.browserPort ?? 43188}, exposure ${config.browserTools || 'on-demand'})`)
788
+ } catch (error) {
789
+ log.warn(`browser partition not installed: ${error?.message ?? error}`)
790
+ }
791
+ })()
792
+ }
793
+ installBrowser()
794
+
795
+ // The optional reference integration (lib/references.js, another partition's file). Lazy and
796
+ // optional: if it is absent or broken, the plugin's own behaviour is exactly as before.
797
+ void (async () => {
798
+ const install = await loadAppReferences(log)
799
+ if (typeof install !== 'function') return
800
+ try {
801
+ install(ctx, { cu, log, config })
802
+ log.info('app references installed')
803
+ } catch (error) {
804
+ log.warn(`app references not installed: ${error?.message ?? error}`)
805
+ }
806
+ })()
807
+
568
808
  // ---- the live agent of the session that drives this machine ------------------------------
569
809
  // Captured from the tool execution itself (`exec.agent` is the live Agent object); a session
570
810
  // only ever gets here by having called a computer_* tool.
@@ -1228,7 +1468,49 @@ export function apply (ctx, config) {
1228
1468
  // computer_* calls only.
1229
1469
  try { leaveTimer.observe(exec) } catch (error) { log.warn(`computer-use leave timer observe failed: ${error.message}`) }
1230
1470
  try {
1231
- if (!exec || typeof exec.name !== 'string' || !exec.name.startsWith('computer_')) return next()
1471
+ if (!exec || typeof exec.name !== 'string') return next()
1472
+ // ---- THE BROWSER TOOLS TAKE THE SAME APPROVAL CONTRACT, THROUGH THEIR OWN CLASSIFIER -------
1473
+ // They are `computer_browser_*`, so they reach this hook, and they must keep the SAME
1474
+ // automationMode boundary the desktop tools have: read-only refuses anything that changes a
1475
+ // page, standard asks per actuation, and an unanswerable ask is settled by the identical
1476
+ // applyApprovalChannel rule. The classification lives in lib/browser/policy.js because the
1477
+ // browser surface owns it; the settlement is the shared one, deliberately.
1478
+ //
1479
+ // They deliberately do NOT join the DESKTOP cycle: a browser tab needs no desktop lease, no
1480
+ // input arbitration and no brake, and pushing them through `ensureCycle` would let a page
1481
+ // read open — or block — the machine's exclusive control. Ownership is per tab and lives in
1482
+ // lib/browser/access.js. The human's brake still stops the AGENT: `hooks.askBlocked` refuses
1483
+ // them below like any other call, so a paused machine cannot be worked around with a browser.
1484
+ if (exec.name.startsWith('computer_browser_')) {
1485
+ if (!browserPartition) return { kind: 'deny', reason: 'the browser partition is not loaded in this profile' }
1486
+ const bArgs = exec.arguments || {}
1487
+ if (hooks.askBlocked) {
1488
+ const why = hooks.askBlocked(exec.name)
1489
+ if (why) return { kind: 'deny', reason: why }
1490
+ }
1491
+ const bEnv = readApprovalEnv({
1492
+ ctx,
1493
+ session: (exec.agent && exec.agent.session) || (typeof exec.session === 'object' ? exec.session : null),
1494
+ sessionId: sessionKey(exec.session || (exec.agent && exec.agent.session) || exec.sessionId),
1495
+ durablePermission: typeof sessionPermission === 'function' ? sessionPermission : null,
1496
+ })
1497
+ const bDecision = browserPolicyDecision(exec.name, bArgs, config.automationMode, bEnv)
1498
+ log.info(`gate ${exec.name} ${JSON.stringify(gateArgSummary(exec.name, bArgs))} ` +
1499
+ `automation=${config.automationMode} ${describeApprovalEnv(bEnv)} final=${bDecision.kind}` +
1500
+ (bDecision.kind !== 'allow' && bDecision.reason ? ` — ${redactReasonText(String(bDecision.reason))}` : ''))
1501
+ if (bDecision.kind !== 'allow') {
1502
+ appendGate(dataDir, {
1503
+ ts: Date.now(), tool: exec.name, args: gateArgSummary(exec.name, bArgs),
1504
+ automationMode: config.automationMode, approvalPolicy: bEnv.approvalPolicy, sandbox: bEnv.sandbox,
1505
+ promptsAvailable: bEnv.promptsAvailable, fullAccess: bEnv.fullAccess, delegated: bEnv.delegated === true,
1506
+ envSources: bEnv.sources, raw: bDecision.kind, final: bDecision.kind,
1507
+ ...(bDecision.kind !== 'allow' && bDecision.reason ? { reason: redactReasonText(String(bDecision.reason)).slice(0, 500) } : {}),
1508
+ ...(sessionKey(exec.session || (exec.agent && exec.agent.session)) ? { session: sessionKey(exec.session || (exec.agent && exec.agent.session)) } : {}),
1509
+ })
1510
+ }
1511
+ return bDecision
1512
+ }
1513
+ if (!exec.name.startsWith('computer_')) return next()
1232
1514
  if (exec.name === ACTIVATION_TOOL) return next() // capability discovery does not open a control cycle
1233
1515
  // NOT `bus.agent = exec.agent` (integration bug, 2026-09-13): this hook runs for EVERY
1234
1516
  // computer_* call, including one the cycle gate will refuse as foreign, so rebinding the