dsh-codex-style-computer-use 2.3.4 → 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.
Files changed (37) hide show
  1. package/README.md +60 -5
  2. package/README.zh.md +50 -5
  3. package/client.js +1556 -32
  4. package/lib/browser/APACHE-2.0.txt +202 -0
  5. package/lib/browser/MIT-dsh-doyourweb.txt +21 -0
  6. package/lib/browser/NOTICE.md +53 -0
  7. package/lib/browser/README.md +139 -0
  8. package/lib/browser/access.js +540 -0
  9. package/lib/browser/approval.js +82 -0
  10. package/lib/browser/bridge.js +1048 -0
  11. package/lib/browser/engine.js +669 -0
  12. package/lib/browser/extension/background.js +474 -0
  13. package/lib/browser/extension/config.js +6 -0
  14. package/lib/browser/extension/manifest.json +25 -0
  15. package/lib/browser/extension/popup.css +89 -0
  16. package/lib/browser/extension/popup.html +35 -0
  17. package/lib/browser/extension/popup.js +99 -0
  18. package/lib/browser/host-protocol.js +132 -0
  19. package/lib/browser/host.js +1089 -0
  20. package/lib/browser/model.js +111 -0
  21. package/lib/browser/pairing.js +126 -0
  22. package/lib/browser/policy.js +131 -0
  23. package/lib/browser/protocol.js +171 -0
  24. package/lib/browser/schema.js +82 -0
  25. package/lib/browser/setup-page.js +145 -0
  26. package/lib/core/bin/dsh-computer-use-worker.exe +0 -0
  27. package/lib/core/bin/dsh-computer-use-worker.exe.json +2 -2
  28. package/lib/core/index.js +58 -1
  29. package/lib/core/worker.cs +32 -1
  30. package/lib/host-debug.js +3 -2
  31. package/lib/index.js +286 -4
  32. package/lib/references-apps.js +586 -0
  33. package/lib/references-files.js +77 -0
  34. package/lib/references.js +233 -0
  35. package/package.json +7 -2
  36. package/scripts/check-behavior.mjs +60 -0
  37. package/scripts/verify-browser-integration.mjs +807 -0
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 ----
@@ -450,7 +512,7 @@ function handleHostDebug (req, res, sctx) {
450
512
  const rejection = connection && typeof connection.requestRejection === 'function' ? connection.requestRejection(req) : null
451
513
  if (rejection) { send(403, { error: 'rejected by host', detail: String(rejection) }); return }
452
514
  const url = new URL(req.url, 'http://127.0.0.1')
453
- const sid = url.searchParams.get('session') || process.env.DSH_SESSION_ID || null
515
+ const sid = url.searchParams.get('session') || null
454
516
  const status = () => {
455
517
  const debug = readHostDebug()
456
518
  const perm = sessionPermission(sid)
@@ -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