dsh-builtin-browser 1.0.3 → 1.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.
- package/CHANGELOG.md +16 -1
- package/README.en.md +89 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/desktop-bridge/desktop-identity.json +10 -2
- package/desktop-bridge/install.mjs +28 -2
- package/docs/issue-replies-2026-11-28.md +141 -0
- package/dsh-host-patch/apply.mjs +1 -1
- package/dsh-host-patch/rc3.json +4 -4
- package/dsh-host-patch/rc5.json +4 -4
- package/dsh-host-patch/v023-alpha2.json +2 -2
- package/lib/browser-electron/bridge-status.js +24 -1
- package/lib/browser-electron/desktop-identity.js +47 -8
- package/lib/client.js +2 -1
- package/native-host/install.mjs +5 -0
- package/package.json +20 -2
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +69 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +40 -0
- package/scripts/install-electron.mjs +101 -0
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +58 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +98 -0
- package/skills/dsh-builtin-browser/references/batch.md +68 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +578 -0
- package/src/browser/takeover-target.ts +45 -0
- package/src/browser/types.ts +870 -0
- package/src/browser-electron/authenticated-route.ts +109 -0
- package/src/browser-electron/automatic-maintenance.ts +736 -0
- package/src/browser-electron/bridge-auto.ts +159 -0
- package/src/browser-electron/bridge-connection.ts +386 -0
- package/src/browser-electron/bridge-endpoint.ts +129 -0
- package/src/browser-electron/bridge-install.ts +290 -0
- package/src/browser-electron/bridge-maintenance.ts +189 -0
- package/src/browser-electron/bridge-status.ts +412 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +400 -0
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +347 -0
- package/src/browser-electron/entry.ts +1378 -0
- package/src/browser-electron/ephemeral-profile.ts +189 -0
- package/src/browser-electron/extension-browser.ts +230 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +177 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +716 -0
- package/src/browser-electron/guest-runtime.ts +408 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +120 -0
- package/src/browser-electron/history-store.ts +224 -0
- package/src/browser-electron/host-main.ts +1385 -0
- package/src/browser-electron/host-patch-maintenance.ts +121 -0
- package/src/browser-electron/http-body.ts +65 -0
- package/src/browser-electron/json-reply.ts +47 -0
- package/src/browser-electron/maintenance-broker.ts +166 -0
- package/src/browser-electron/maintenance-lifecycle.ts +91 -0
- package/src/browser-electron/maintenance-route.ts +68 -0
- package/src/browser-electron/missing-system-browser.ts +114 -0
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +25 -0
- package/src/browser-electron/preferred-browser.ts +130 -0
- package/src/browser-electron/preview-route.ts +215 -0
- package/src/browser-electron/process-ownership.ts +174 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +47 -0
- package/src/browser-electron/profile-extension.ts +129 -0
- package/src/browser-electron/profile-lease.ts +211 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +666 -0
- package/src/browser-electron/reference-route.ts +598 -0
- package/src/browser-electron/remote-host.ts +1538 -0
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/rpc-ops.ts +41 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/runtime-route.ts +105 -0
- package/src/browser-electron/runtime-status.ts +309 -0
- package/src/browser-electron/settings-route.ts +64 -0
- package/src/browser-electron/settings-store.ts +593 -0
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +300 -0
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +1850 -0
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/virtual-cursor.ts +162 -0
- package/src/browser-electron/windows-system.ts +24 -0
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1346 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +106 -0
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +182 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +56 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +36 -0
- package/src/client/electron/ElectronWebViewImpl.ts +371 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
- package/src/client/electron/NativeChildPresentation.ts +53 -0
- package/src/client/electron/NativeViewPage.ts +265 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +333 -0
- package/src/client/locales.ts +860 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +208 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +447 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +72 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +512 -0
- package/src/client/reference/client/production/http-transport.ts +212 -0
- package/src/client/reference/client/production/production-submission.ts +70 -0
- package/src/client/reference/client/production/protocol.ts +234 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1056 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +99 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +67 -0
- package/src/client/reference/client/reveal.ts +109 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +42 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +2773 -0
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +300 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +315 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +365 -0
- package/src/client/view/StartPage.tsx +598 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/compat/host-features.ts +92 -0
- package/src/index.ts +110 -0
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +219 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +28 -0
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +555 -0
- package/src/tool-browser/code-worker.ts +725 -0
- package/src/tool-browser/element-fields.ts +167 -0
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +265 -0
- package/src/tool-browser/page-probe.ts +675 -0
- package/src/tool-browser/panel-page.ts +126 -0
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +199 -0
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/types/electron-shim.d.ts +144 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +35 -0
- package/tools/accept-desktop.mjs +148 -0
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +0 -218
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +0 -260
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dsh_browser_code REPL worker: one child process per task, like Browser Use 1.0's
|
|
3
|
+
* repl/worker.py. It keeps one vm context alive across calls (variables and functions survive),
|
|
4
|
+
* prints the last expression, and reaches the browser only by asking the parent to run a
|
|
5
|
+
* registered dsh_browser_* tool. A runaway cell is stopped by killing this process; the browser
|
|
6
|
+
* and the parent are never blocked by it.
|
|
7
|
+
*/
|
|
8
|
+
import { Script, createContext, runInContext } from 'node:vm'
|
|
9
|
+
import { inspect } from 'node:util'
|
|
10
|
+
|
|
11
|
+
type Reply = { readonly type: 'reply'; readonly id: number; readonly value?: unknown; readonly text?: string; readonly error?: string; readonly code?: string }
|
|
12
|
+
type Run = { readonly type: 'run'; readonly code: string }
|
|
13
|
+
|
|
14
|
+
const send = (message: unknown): void => { process.send?.(message) }
|
|
15
|
+
const pending = new Map<number, { resolve: (reply: Reply) => void }>()
|
|
16
|
+
let seq = 0
|
|
17
|
+
|
|
18
|
+
function format(value: unknown): string {
|
|
19
|
+
if (typeof value === 'string') return value
|
|
20
|
+
if (value === undefined) return 'undefined'
|
|
21
|
+
if (typeof value === 'function') return inspect(value)
|
|
22
|
+
try { return JSON.stringify(value) ?? String(value) } catch { return inspect(value, { depth: 4 }) }
|
|
23
|
+
}
|
|
24
|
+
const log = (...values: unknown[]): void => { send({ type: 'log', text: values.map(format).join(' ') }) }
|
|
25
|
+
|
|
26
|
+
const SLEEP_HINT_AFTER = 3
|
|
27
|
+
const SLEEP_HINT = `[hint] sleep() called ${SLEEP_HINT_AFTER} times in this cell; wait on the condition instead: wait_for_element, wait_for_text, wait_for_gone, wait_until(expr) or wait_for_response(url, trigger).`
|
|
28
|
+
let sleepsThisCell = 0
|
|
29
|
+
|
|
30
|
+
/** A failed browser tool call (a helper or `tools.*`), named after the tool, like DSH run_code's ToolCallError. */
|
|
31
|
+
class ToolCallError extends Error {
|
|
32
|
+
readonly toolName: string
|
|
33
|
+
readonly code: string | undefined
|
|
34
|
+
constructor(toolName: string, message: string, code?: string) {
|
|
35
|
+
super(message)
|
|
36
|
+
this.name = 'ToolCallError'
|
|
37
|
+
this.toolName = toolName
|
|
38
|
+
this.code = code
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function ask(name: string, args: Record<string, unknown> = {}): Promise<Reply> {
|
|
43
|
+
const id = ++seq
|
|
44
|
+
const reply = await new Promise<Reply>(resolve => { pending.set(id, { resolve }); send({ type: 'call', id, name, args }) })
|
|
45
|
+
if (reply.error !== undefined) {
|
|
46
|
+
if (name.startsWith('__')) throw new Error(reply.error)
|
|
47
|
+
throw new ToolCallError(name.startsWith('dsh_browser_') ? name : `dsh_browser_${name}`, reply.error, reply.code)
|
|
48
|
+
}
|
|
49
|
+
return reply
|
|
50
|
+
}
|
|
51
|
+
const value = async (name: string, args?: Record<string, unknown>): Promise<unknown> => (await ask(name, args)).value
|
|
52
|
+
|
|
53
|
+
/** DSH run_code-style bindings: `await tools.dsh_browser_snapshot({})` resolves to the tool's JSON value. */
|
|
54
|
+
const tools: Record<string, (args?: Record<string, unknown>) => Promise<unknown>> = new Proxy(Object.create(null), {
|
|
55
|
+
get: (_target, name) => typeof name !== 'string' || name === 'then' ? undefined : (args: Record<string, unknown> = {}) => value(name, args),
|
|
56
|
+
})
|
|
57
|
+
interface TabRow { readonly id: string; readonly url: string; readonly active: boolean }
|
|
58
|
+
/** The task's tabs, read without a trace entry (wait_for_new_tab polls this). */
|
|
59
|
+
const tabs = async (): Promise<readonly TabRow[]> => ((await value('__tabs')) as { tabs?: readonly TabRow[] }).tabs ?? []
|
|
60
|
+
const text = async (name: string, args?: Record<string, unknown>): Promise<string> => (await ask(name, args)).text ?? ''
|
|
61
|
+
|
|
62
|
+
export type Target = string | { css?: string; text?: string; xpath?: string; by?: string; value?: string; index?: number; x?: number; y?: number }
|
|
63
|
+
|
|
64
|
+
const HTML_TAGS = new Set(['a', 'button', 'input', 'select', 'textarea', 'form', 'div', 'span', 'li', 'ul', 'ol', 'table', 'tr', 'td', 'th', 'tbody', 'thead', 'img', 'label', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'nav', 'main', 'header', 'footer', 'section', 'article', 'aside', 'option', 'summary', 'details', 'iframe', 'body', 'svg', 'dialog'])
|
|
65
|
+
|
|
66
|
+
function looksLikeSelector(raw: string): boolean {
|
|
67
|
+
if (/^[#.[]\S/.test(raw)) return true
|
|
68
|
+
const tag = /^[a-z][a-z0-9-]*/.exec(raw)?.[0]
|
|
69
|
+
if (tag === undefined || !HTML_TAGS.has(tag)) return false
|
|
70
|
+
const rest = raw.slice(tag.length)
|
|
71
|
+
return rest === '' || /^[#.[:]/.test(rest) || /^\s*>/.test(rest)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Turn a helper target into click/type arguments. A string is visible text unless it reads as a
|
|
76
|
+
* CSS selector or an XPath expression.
|
|
77
|
+
* @param target - text, selector, {css|text|xpath, index}, {by, value} or {x, y}.
|
|
78
|
+
*/
|
|
79
|
+
export function targetArgs(target: Target): Record<string, unknown> {
|
|
80
|
+
if (typeof target === 'string') {
|
|
81
|
+
if (target.startsWith('//') || target.startsWith('(//')) return { target: { by: 'xpath', value: target } }
|
|
82
|
+
return { target: { by: looksLikeSelector(target) ? 'css' : 'text', value: target } }
|
|
83
|
+
}
|
|
84
|
+
if (target === null || typeof target !== 'object') throw new Error(`invalid target ${JSON.stringify(target)}`)
|
|
85
|
+
if (typeof target.x === 'number' && typeof target.y === 'number') return { x: target.x, y: target.y }
|
|
86
|
+
const index = target.index !== undefined ? { index: target.index } : {}
|
|
87
|
+
if (target.css !== undefined) return { target: { by: 'css', value: target.css, ...index } }
|
|
88
|
+
if (target.text !== undefined) return { target: { by: 'text', value: target.text, ...index } }
|
|
89
|
+
if (target.xpath !== undefined) return { target: { by: 'xpath', value: target.xpath, ...index } }
|
|
90
|
+
if (target.value !== undefined) return { target: { by: target.by ?? 'css', value: target.value, ...index } }
|
|
91
|
+
throw new Error(`invalid target ${JSON.stringify(target)}`)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const NOT_EXPRESSION = /^(return|if|for|while|do|switch|try|catch|finally|throw|const|let|var|function|async\s+function|class|import|export|break|continue|else|\}|\)|\]|\/\/|\/\*|\*)/
|
|
95
|
+
const CONTINUES = /[([{,+\-*/%=&|?:.<>!^~]$|=>$/
|
|
96
|
+
const REGEX_BEFORE = new Set(['', '(', '[', '{', ',', ';', ':', '=', '!', '&', '|', '?', '+', '-', '*', '%', '^', '~', '<', '>', '\n'])
|
|
97
|
+
const REGEX_KEYWORDS = new Set(['return', 'throw', 'case', 'in', 'instanceof', 'typeof', 'void', 'delete', 'new', 'await', 'yield', 'else', 'do', 'of'])
|
|
98
|
+
|
|
99
|
+
interface ScanResult {
|
|
100
|
+
readonly rewritten: string
|
|
101
|
+
readonly varNames: readonly string[]
|
|
102
|
+
readonly fnNames: readonly string[]
|
|
103
|
+
readonly hasTopReturn: boolean
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Dedent top-level lines while leaving multiline template literal bodies untouched, so unindented
|
|
108
|
+
* lines inside a template literal do not prevent dedenting the surrounding cell (and trailing
|
|
109
|
+
* parenthesized expressions still get turned into `return (...)` instead of triggering ASI calls).
|
|
110
|
+
*/
|
|
111
|
+
function dedentTopLevel(code: string): { readonly dedented: string; readonly inTemplateStart: readonly boolean[] } {
|
|
112
|
+
const trimmed = code.replace(/\s+$/, '')
|
|
113
|
+
const lines = trimmed.split('\n')
|
|
114
|
+
const inTemplateStart = new Array<boolean>(lines.length).fill(false)
|
|
115
|
+
let lineIdx = 0
|
|
116
|
+
let i = 0
|
|
117
|
+
let prevChar = ''
|
|
118
|
+
let prevWord = ''
|
|
119
|
+
const n = trimmed.length
|
|
120
|
+
|
|
121
|
+
const isIdentStart = (ch: string): boolean => /[A-Za-z_$]/.test(ch)
|
|
122
|
+
const isIdentPart = (ch: string): boolean => /[\w$]/.test(ch)
|
|
123
|
+
const advance = (ch: string): void => { if (ch === '\n') lineIdx++ }
|
|
124
|
+
|
|
125
|
+
const skipRegex = (): void => {
|
|
126
|
+
i++
|
|
127
|
+
let inClass = false
|
|
128
|
+
while (i < n) {
|
|
129
|
+
const ch = trimmed[i]!
|
|
130
|
+
if (ch === '\\') { advance(trimmed[i + 1] ?? ''); i += 2; continue }
|
|
131
|
+
if (ch === '[') inClass = true
|
|
132
|
+
else if (ch === ']') inClass = false
|
|
133
|
+
else if (ch === '/' && !inClass) {
|
|
134
|
+
i++
|
|
135
|
+
while (i < n && /[a-z]/i.test(trimmed[i]!)) i++
|
|
136
|
+
return
|
|
137
|
+
} else if (ch === '\n') return
|
|
138
|
+
i++
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const skipQuoted = (quote: string): void => {
|
|
143
|
+
i++
|
|
144
|
+
while (i < n) {
|
|
145
|
+
const ch = trimmed[i]!
|
|
146
|
+
if (ch === '\\') { advance(trimmed[i + 1] ?? ''); i += 2; continue }
|
|
147
|
+
if (quote === '`' && ch === '$' && trimmed[i + 1] === '{') {
|
|
148
|
+
i += 2
|
|
149
|
+
let exprDepth = 1
|
|
150
|
+
let exprPrev = '{'
|
|
151
|
+
let exprWord = ''
|
|
152
|
+
while (i < n && exprDepth > 0) {
|
|
153
|
+
const c = trimmed[i]!
|
|
154
|
+
if (c === "'" || c === '"' || c === '`') { skipQuoted(c); exprPrev = '"'; exprWord = ''; continue }
|
|
155
|
+
if (c === '/' && trimmed[i + 1] === '/') { while (i < n && trimmed[i] !== '\n') i++; continue }
|
|
156
|
+
if (c === '/' && trimmed[i + 1] === '*') {
|
|
157
|
+
i += 2
|
|
158
|
+
while (i < n && !(trimmed[i] === '*' && trimmed[i + 1] === '/')) { advance(trimmed[i]!); i++ }
|
|
159
|
+
if (i < n) i += 2
|
|
160
|
+
continue
|
|
161
|
+
}
|
|
162
|
+
if (c === '/' && (REGEX_BEFORE.has(exprPrev) || REGEX_KEYWORDS.has(exprWord))) { skipRegex(); exprPrev = '/'; exprWord = ''; continue }
|
|
163
|
+
if (isIdentStart(c)) {
|
|
164
|
+
const start = i
|
|
165
|
+
i++
|
|
166
|
+
while (i < n && isIdentPart(trimmed[i]!)) i++
|
|
167
|
+
exprPrev = 'a'; exprWord = trimmed.slice(start, i)
|
|
168
|
+
continue
|
|
169
|
+
}
|
|
170
|
+
if (c === '{') exprDepth++
|
|
171
|
+
else if (c === '}') exprDepth--
|
|
172
|
+
if (c === '\n') { lineIdx++; exprPrev = '\n'; exprWord = '' }
|
|
173
|
+
else if (!/\s/.test(c)) { exprPrev = c; exprWord = '' }
|
|
174
|
+
i++
|
|
175
|
+
}
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
178
|
+
if (ch === quote) { i++; return }
|
|
179
|
+
if (ch === '\n') {
|
|
180
|
+
lineIdx++
|
|
181
|
+
if (quote === '`' && lineIdx < lines.length) inTemplateStart[lineIdx] = true
|
|
182
|
+
}
|
|
183
|
+
i++
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
while (i < n) {
|
|
188
|
+
const ch = trimmed[i]!
|
|
189
|
+
if (ch === "'" || ch === '"' || ch === '`') { skipQuoted(ch); prevChar = '"'; prevWord = ''; continue }
|
|
190
|
+
if (ch === '/' && trimmed[i + 1] === '/') { while (i < n && trimmed[i] !== '\n') i++; continue }
|
|
191
|
+
if (ch === '/' && trimmed[i + 1] === '*') {
|
|
192
|
+
i += 2
|
|
193
|
+
while (i < n && !(trimmed[i] === '*' && trimmed[i + 1] === '/')) { advance(trimmed[i]!); i++ }
|
|
194
|
+
if (i < n) i += 2
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
if (ch === '/' && (REGEX_BEFORE.has(prevChar) || REGEX_KEYWORDS.has(prevWord))) { skipRegex(); prevChar = '/'; prevWord = ''; continue }
|
|
198
|
+
if (isIdentStart(ch)) {
|
|
199
|
+
const start = i
|
|
200
|
+
i++
|
|
201
|
+
while (i < n && isIdentPart(trimmed[i]!)) i++
|
|
202
|
+
prevChar = 'a'; prevWord = trimmed.slice(start, i)
|
|
203
|
+
continue
|
|
204
|
+
}
|
|
205
|
+
if (ch === '\n') { lineIdx++; prevChar = '\n'; prevWord = '' }
|
|
206
|
+
else if (!/\s/.test(ch)) { prevChar = ch; prevWord = '' }
|
|
207
|
+
i++
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const indents = lines
|
|
211
|
+
.filter((line, idx) => !inTemplateStart[idx] && line.trim() !== '')
|
|
212
|
+
.map(line => /^[ \t]*/.exec(line)?.[0].length ?? 0)
|
|
213
|
+
const indent = indents.length > 0 ? Math.min(...indents) : 0
|
|
214
|
+
const dedented = indent === 0
|
|
215
|
+
? trimmed
|
|
216
|
+
: lines.map((line, idx) => inTemplateStart[idx] ? line : line.slice(indent)).join('\n')
|
|
217
|
+
return { dedented, inTemplateStart }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Lexically scan top-level declarations (skipping comments, strings, nested template literals,
|
|
222
|
+
* regex literals and nested blocks) so destructuring, multiline template strings and hoisted
|
|
223
|
+
* functions all persist cleanly across REPL cells.
|
|
224
|
+
*/
|
|
225
|
+
function scanTopLevel(code: string): ScanResult {
|
|
226
|
+
const varNames = new Set<string>()
|
|
227
|
+
const fnNames = new Set<string>()
|
|
228
|
+
const replacements: { readonly start: number; readonly end: number; readonly text: string }[] = []
|
|
229
|
+
let hasTopReturn = false
|
|
230
|
+
let depth = 0
|
|
231
|
+
let i = 0
|
|
232
|
+
let prevChar = ''
|
|
233
|
+
let prevWord = ''
|
|
234
|
+
const n = code.length
|
|
235
|
+
|
|
236
|
+
const isIdentStart = (ch: string): boolean => /[A-Za-z_$]/.test(ch)
|
|
237
|
+
const isIdentPart = (ch: string): boolean => /[\w$]/.test(ch)
|
|
238
|
+
|
|
239
|
+
const skipSpacesAndComments = (allowNewline = true): void => {
|
|
240
|
+
while (i < n) {
|
|
241
|
+
const ch = code[i]!
|
|
242
|
+
if (ch === ' ' || ch === '\t' || ch === '\r' || (allowNewline && ch === '\n')) { i++; continue }
|
|
243
|
+
if (ch === '/' && code[i + 1] === '/') { while (i < n && code[i] !== '\n') i++; continue }
|
|
244
|
+
if (ch === '/' && code[i + 1] === '*') {
|
|
245
|
+
const end = code.indexOf('*/', i + 2)
|
|
246
|
+
i = end === -1 ? n : end + 2
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
break
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const skipQuoted = (quote: string): void => {
|
|
254
|
+
i++
|
|
255
|
+
while (i < n) {
|
|
256
|
+
const ch = code[i]!
|
|
257
|
+
if (ch === '\\') { i += 2; continue }
|
|
258
|
+
if (quote === '`' && ch === '$' && code[i + 1] === '{') {
|
|
259
|
+
i += 2
|
|
260
|
+
let exprDepth = 1
|
|
261
|
+
while (i < n && exprDepth > 0) {
|
|
262
|
+
const c = code[i]!
|
|
263
|
+
if (c === "'" || c === '"' || c === '`') skipQuoted(c)
|
|
264
|
+
else if (c === '/' && code[i + 1] === '/') { while (i < n && code[i] !== '\n') i++ }
|
|
265
|
+
else if (c === '/' && code[i + 1] === '*') { const end = code.indexOf('*/', i + 2); i = end === -1 ? n : end + 2 }
|
|
266
|
+
else { if (c === '{') exprDepth++; else if (c === '}') exprDepth--; i++ }
|
|
267
|
+
}
|
|
268
|
+
continue
|
|
269
|
+
}
|
|
270
|
+
if (ch === quote) { i++; return }
|
|
271
|
+
i++
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const skipRegex = (): void => {
|
|
276
|
+
i++
|
|
277
|
+
let inClass = false
|
|
278
|
+
while (i < n) {
|
|
279
|
+
const ch = code[i]!
|
|
280
|
+
if (ch === '\\') { i += 2; continue }
|
|
281
|
+
if (ch === '[') inClass = true
|
|
282
|
+
else if (ch === ']') inClass = false
|
|
283
|
+
else if (ch === '/' && !inClass) {
|
|
284
|
+
i++
|
|
285
|
+
while (i < n && /[a-z]/i.test(code[i]!)) i++
|
|
286
|
+
return
|
|
287
|
+
} else if (ch === '\n') return
|
|
288
|
+
i++
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const readIdent = (): string | undefined => {
|
|
293
|
+
if (i >= n || !isIdentStart(code[i]!)) return undefined
|
|
294
|
+
const start = i
|
|
295
|
+
i++
|
|
296
|
+
while (i < n && isIdentPart(code[i]!)) i++
|
|
297
|
+
return code.slice(start, i)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const skipBalancedExpr = (stopChars: string): void => {
|
|
301
|
+
let exprDepth = 0
|
|
302
|
+
let localPrev = '='
|
|
303
|
+
let localWord = ''
|
|
304
|
+
while (i < n) {
|
|
305
|
+
const ch = code[i]!
|
|
306
|
+
if (ch === "'" || ch === '"' || ch === '`') { skipQuoted(ch); localPrev = '"'; localWord = ''; continue }
|
|
307
|
+
if (ch === '/' && code[i + 1] === '/') { while (i < n && code[i] !== '\n') i++; continue }
|
|
308
|
+
if (ch === '/' && code[i + 1] === '*') { const end = code.indexOf('*/', i + 2); i = end === -1 ? n : end + 2; continue }
|
|
309
|
+
if (ch === '/' && (REGEX_BEFORE.has(localPrev) || REGEX_KEYWORDS.has(localWord))) { skipRegex(); localPrev = '/'; localWord = ''; continue }
|
|
310
|
+
if (ch === '(' || ch === '[' || ch === '{') { exprDepth++; i++; localPrev = ch; localWord = ''; continue }
|
|
311
|
+
if (ch === ')' || ch === ']' || ch === '}') {
|
|
312
|
+
if (exprDepth === 0 && stopChars.includes(ch)) return
|
|
313
|
+
exprDepth = Math.max(0, exprDepth - 1); i++; localPrev = ch; localWord = ''; continue
|
|
314
|
+
}
|
|
315
|
+
if (exprDepth === 0 && stopChars.includes(ch)) return
|
|
316
|
+
if (isIdentStart(ch)) {
|
|
317
|
+
const w = readIdent() ?? ''
|
|
318
|
+
localPrev = 'a'; localWord = w; continue
|
|
319
|
+
}
|
|
320
|
+
if (!/\s/.test(ch)) { localPrev = ch; localWord = '' }
|
|
321
|
+
else if (ch === '\n' && exprDepth === 0 && stopChars.includes('\n')) return
|
|
322
|
+
i++
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const parseBindingPattern = (): void => {
|
|
327
|
+
skipSpacesAndComments()
|
|
328
|
+
if (i >= n) return
|
|
329
|
+
if (code.startsWith('...', i)) {
|
|
330
|
+
i += 3
|
|
331
|
+
skipSpacesAndComments()
|
|
332
|
+
const name = readIdent()
|
|
333
|
+
if (name !== undefined) varNames.add(name)
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
if (code[i] === '[') {
|
|
337
|
+
i++
|
|
338
|
+
while (i < n) {
|
|
339
|
+
skipSpacesAndComments()
|
|
340
|
+
if (code[i] === ']') { i++; return }
|
|
341
|
+
if (code[i] === ',') { i++; continue }
|
|
342
|
+
parseBindingPattern()
|
|
343
|
+
skipSpacesAndComments()
|
|
344
|
+
if (code[i] === '=') { i++; skipBalancedExpr(',]') }
|
|
345
|
+
skipSpacesAndComments()
|
|
346
|
+
if (code[i] === ',') i++
|
|
347
|
+
else if (code[i] === ']') { i++; return }
|
|
348
|
+
else break
|
|
349
|
+
}
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
if (code[i] === '{') {
|
|
353
|
+
i++
|
|
354
|
+
while (i < n) {
|
|
355
|
+
skipSpacesAndComments()
|
|
356
|
+
if (code[i] === '}') { i++; return }
|
|
357
|
+
if (code.startsWith('...', i)) {
|
|
358
|
+
i += 3
|
|
359
|
+
skipSpacesAndComments()
|
|
360
|
+
const rest = readIdent()
|
|
361
|
+
if (rest !== undefined) varNames.add(rest)
|
|
362
|
+
} else {
|
|
363
|
+
let keyIdent: string | undefined
|
|
364
|
+
if (code[i] === '[') {
|
|
365
|
+
i++; skipBalancedExpr(']'); if (code[i] === ']') i++
|
|
366
|
+
} else if (code[i] === "'" || code[i] === '"') {
|
|
367
|
+
skipQuoted(code[i]!)
|
|
368
|
+
} else if (isIdentStart(code[i]!)) {
|
|
369
|
+
keyIdent = readIdent()
|
|
370
|
+
} else {
|
|
371
|
+
while (i < n && !/[\s:,=}]/.test(code[i]!)) i++
|
|
372
|
+
}
|
|
373
|
+
skipSpacesAndComments()
|
|
374
|
+
if (code[i] === ':') {
|
|
375
|
+
i++
|
|
376
|
+
parseBindingPattern()
|
|
377
|
+
} else if (keyIdent !== undefined) {
|
|
378
|
+
varNames.add(keyIdent)
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
skipSpacesAndComments()
|
|
382
|
+
if (code[i] === '=') { i++; skipBalancedExpr(',}') }
|
|
383
|
+
skipSpacesAndComments()
|
|
384
|
+
if (code[i] === ',') i++
|
|
385
|
+
else if (code[i] === '}') { i++; return }
|
|
386
|
+
else break
|
|
387
|
+
}
|
|
388
|
+
return
|
|
389
|
+
}
|
|
390
|
+
const name = readIdent()
|
|
391
|
+
if (name !== undefined) varNames.add(name)
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
while (i < n) {
|
|
395
|
+
const ch = code[i]!
|
|
396
|
+
if (ch === "'" || ch === '"' || ch === '`') { skipQuoted(ch); prevChar = '"'; prevWord = ''; continue }
|
|
397
|
+
if (ch === '/' && code[i + 1] === '/') { while (i < n && code[i] !== '\n') i++; continue }
|
|
398
|
+
if (ch === '/' && code[i + 1] === '*') { const end = code.indexOf('*/', i + 2); i = end === -1 ? n : end + 2; continue }
|
|
399
|
+
if (ch === '/' && (REGEX_BEFORE.has(prevChar) || REGEX_KEYWORDS.has(prevWord))) { skipRegex(); prevChar = '/'; prevWord = ''; continue }
|
|
400
|
+
if (ch === '{' || ch === '(' || ch === '[') { depth++; i++; prevChar = ch; prevWord = ''; continue }
|
|
401
|
+
if (ch === '}' || ch === ')' || ch === ']') { depth = Math.max(0, depth - 1); i++; prevChar = ch; prevWord = ''; continue }
|
|
402
|
+
|
|
403
|
+
if (depth === 0 && isIdentStart(ch) && prevChar !== '.') {
|
|
404
|
+
const wordStart = i
|
|
405
|
+
const word = readIdent()!
|
|
406
|
+
if (word === 'const' || word === 'let' || word === 'var') {
|
|
407
|
+
if (word !== 'var') replacements.push({ start: wordStart, end: i, text: 'var' })
|
|
408
|
+
while (i < n) {
|
|
409
|
+
parseBindingPattern()
|
|
410
|
+
skipSpacesAndComments(false)
|
|
411
|
+
if (code[i] === '=') {
|
|
412
|
+
i++
|
|
413
|
+
skipSpacesAndComments(true)
|
|
414
|
+
skipBalancedExpr(',;\n')
|
|
415
|
+
}
|
|
416
|
+
skipSpacesAndComments(false)
|
|
417
|
+
if (code[i] === ',') { i++; continue }
|
|
418
|
+
break
|
|
419
|
+
}
|
|
420
|
+
prevChar = 'a'; prevWord = ''
|
|
421
|
+
continue
|
|
422
|
+
}
|
|
423
|
+
if (word === 'async') {
|
|
424
|
+
const saved = i
|
|
425
|
+
skipSpacesAndComments(false)
|
|
426
|
+
if (code.startsWith('function', i) && !isIdentPart(code[i + 8] ?? '')) {
|
|
427
|
+
i += 8
|
|
428
|
+
skipSpacesAndComments()
|
|
429
|
+
if (code[i] === '*') { i++; skipSpacesAndComments() }
|
|
430
|
+
const fn = readIdent()
|
|
431
|
+
if (fn !== undefined) fnNames.add(fn)
|
|
432
|
+
prevChar = 'a'; prevWord = 'function'
|
|
433
|
+
continue
|
|
434
|
+
}
|
|
435
|
+
i = saved
|
|
436
|
+
}
|
|
437
|
+
if (word === 'function') {
|
|
438
|
+
skipSpacesAndComments()
|
|
439
|
+
if (code[i] === '*') { i++; skipSpacesAndComments() }
|
|
440
|
+
const fn = readIdent()
|
|
441
|
+
if (fn !== undefined) fnNames.add(fn)
|
|
442
|
+
prevChar = 'a'; prevWord = 'function'
|
|
443
|
+
continue
|
|
444
|
+
}
|
|
445
|
+
if (word === 'class') {
|
|
446
|
+
skipSpacesAndComments()
|
|
447
|
+
const cls = readIdent()
|
|
448
|
+
if (cls !== undefined) {
|
|
449
|
+
varNames.add(cls)
|
|
450
|
+
replacements.push({ start: wordStart, end: wordStart + 5, text: `var ${cls} = class` })
|
|
451
|
+
}
|
|
452
|
+
prevChar = 'a'; prevWord = 'class'
|
|
453
|
+
continue
|
|
454
|
+
}
|
|
455
|
+
if (word === 'return') hasTopReturn = true
|
|
456
|
+
prevChar = 'a'; prevWord = word
|
|
457
|
+
continue
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (ch === '\n') { prevChar = '\n'; prevWord = '' }
|
|
461
|
+
else if (!/\s/.test(ch)) { prevChar = ch; prevWord = '' }
|
|
462
|
+
i++
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
let rewritten = code
|
|
466
|
+
for (let idx = replacements.length - 1; idx >= 0; idx--) {
|
|
467
|
+
const rep = replacements[idx]!
|
|
468
|
+
rewritten = rewritten.slice(0, rep.start) + rep.text + rewritten.slice(rep.end)
|
|
469
|
+
}
|
|
470
|
+
return { rewritten, varNames: [...varNames], fnNames: [...fnNames], hasTopReturn }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Make a cell behave like a REPL cell: top-level declarations land on the context (so they
|
|
475
|
+
* survive the call) and a trailing expression is the cell's value.
|
|
476
|
+
* @param code - the model's cell.
|
|
477
|
+
* @returns an async function body.
|
|
478
|
+
*/
|
|
479
|
+
export function prepare(code: string): string {
|
|
480
|
+
const { dedented, inTemplateStart } = dedentTopLevel(code)
|
|
481
|
+
const { rewritten, varNames, fnNames, hasTopReturn } = scanTopLevel(dedented)
|
|
482
|
+
const prelude = fnNames.length === 0 ? '' : fnNames.map(name => `globalThis.${name} = ${name};`).join(' ') + '\n'
|
|
483
|
+
const persist = varNames.length === 0
|
|
484
|
+
? ''
|
|
485
|
+
: varNames.map(name => `try { if (typeof ${name} !== 'undefined' || !(${JSON.stringify(name)} in globalThis)) globalThis.${name} = ${name}; } catch {}`).join(' ')
|
|
486
|
+
const wrap = (body: string): string => {
|
|
487
|
+
if (persist !== '') return `try {\n${prelude}${body}\n} finally {\n${persist}\n}`
|
|
488
|
+
return `${prelude}${body}`
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (hasTopReturn) return wrap(rewritten)
|
|
492
|
+
const lines = rewritten.split('\n')
|
|
493
|
+
const last = lines.length - 1
|
|
494
|
+
const line = lines[last] ?? ''
|
|
495
|
+
const previous = lines.slice(0, last).reverse().find(l => l.trim() !== '')?.trimEnd() ?? ''
|
|
496
|
+
if (inTemplateStart[last] || line === '' || /^\s/.test(line) || NOT_EXPRESSION.test(line) || CONTINUES.test(previous) || /[{,]$/.test(line)) {
|
|
497
|
+
return wrap(rewritten)
|
|
498
|
+
}
|
|
499
|
+
// A one-line cell of several statements returns its last one.
|
|
500
|
+
const split = line.lastIndexOf(';', line.replace(/;\s*$/, '').length - 1)
|
|
501
|
+
const head = split > 0 ? line.slice(0, split + 1) + '\n' : ''
|
|
502
|
+
const tail = (split > 0 ? line.slice(split + 1) : line).trim().replace(/^;\s*/, '').replace(/;\s*$/, '')
|
|
503
|
+
for (const candidate of [`${head}return (${tail})`, `return (${line.replace(/^;\s*/, '').replace(/;\s*$/, '')})`]) {
|
|
504
|
+
const transformed = [...lines.slice(0, last), candidate].join('\n')
|
|
505
|
+
if (tail !== '' && compiles(wrap(transformed))) return wrap(transformed)
|
|
506
|
+
}
|
|
507
|
+
return wrap(rewritten)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function compiles(body: string): boolean {
|
|
511
|
+
try { new Script(`(async () => {\n${body}\n})`); return true } catch { return false }
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Wrap a page expression so its value comes back as JSON text that keeps strings strings and
|
|
516
|
+
* numbers exact; a script with a top-level `return` runs as a function body.
|
|
517
|
+
* @param script - an expression, or statements with `return`.
|
|
518
|
+
*/
|
|
519
|
+
function pageScript(script: string): string {
|
|
520
|
+
const expression = `return (${script.replace(/;\s*$/, '')})`
|
|
521
|
+
const body = compiles(expression) ? expression : script
|
|
522
|
+
return `(async () => { const v = await (async () => {\n${body}\n})(); return JSON.stringify(v === undefined ? null : v) })()`
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const helpers = {
|
|
526
|
+
// Browser Use 1.0 / browser-harness names.
|
|
527
|
+
goto_url: (url: string) => text('open', { url }),
|
|
528
|
+
new_tab: (url: string) => text('open', { url, newTab: true }),
|
|
529
|
+
wait_for_load: async (timeoutMs?: number) => {
|
|
530
|
+
const out = await value('wait', timeoutMs !== undefined ? { timeoutMs } : {}) as { ready: boolean; reason: string }
|
|
531
|
+
if (!out.ready) throw new Error(`page did not finish loading: ${out.reason}`)
|
|
532
|
+
return true
|
|
533
|
+
},
|
|
534
|
+
page_info: () => js('({ url: location.href, title: document.title, w: innerWidth, h: innerHeight, sx: scrollX, sy: scrollY, pw: document.documentElement.scrollWidth, ph: document.documentElement.scrollHeight })'),
|
|
535
|
+
list_tabs: () => value('list_tabs'),
|
|
536
|
+
switch_tab: (tabId: string) => text('switch_tab', { tabId }),
|
|
537
|
+
close_tab: (tabId: string) => text('close_tab', { tabId }),
|
|
538
|
+
wait_for_new_tab: async (trigger?: (() => unknown) | number, timeoutMs?: number): Promise<TabRow> => {
|
|
539
|
+
const budget = typeof trigger === 'number' ? trigger : timeoutMs ?? 10_000
|
|
540
|
+
const known = new Set((await tabs()).map(tab => tab.id))
|
|
541
|
+
if (typeof trigger === 'function') await trigger()
|
|
542
|
+
const deadline = Date.now() + Math.min(Math.max(Number(budget) || 0, 0), 600_000)
|
|
543
|
+
for (;;) {
|
|
544
|
+
const fresh = (await tabs()).filter(tab => !known.has(tab.id))
|
|
545
|
+
if (fresh.length > 0) return fresh[fresh.length - 1]!
|
|
546
|
+
if (Date.now() >= deadline) throw new Error(`no new tab opened within ${budget}ms`)
|
|
547
|
+
await new Promise<void>(done => setTimeout(done, 150))
|
|
548
|
+
}
|
|
549
|
+
},
|
|
550
|
+
with_tab: async <T>(tabId: string, fn: () => T | Promise<T>): Promise<T> => {
|
|
551
|
+
if (typeof fn !== 'function') throw new TypeError('with_tab(tabId, fn) needs a function')
|
|
552
|
+
const previous = (await tabs()).find(tab => tab.active)?.id
|
|
553
|
+
if (previous !== tabId) await text('switch_tab', { tabId })
|
|
554
|
+
try {
|
|
555
|
+
return await fn()
|
|
556
|
+
} finally {
|
|
557
|
+
const now = await tabs()
|
|
558
|
+
if (previous !== undefined && now.find(tab => tab.active)?.id !== previous && now.some(tab => tab.id === previous)) await text('switch_tab', { tabId: previous })
|
|
559
|
+
}
|
|
560
|
+
},
|
|
561
|
+
js: (script: string) => js(script),
|
|
562
|
+
click_at_xy: (x: number, y: number) => text('click', { x, y }),
|
|
563
|
+
type_text: (input: string) => text('type', { text: input }),
|
|
564
|
+
fill_input: (target: Target, input: string) => text('set_value', { ...targetArgs(target), value: input }),
|
|
565
|
+
press_key: (key: string) => text('key', { key }),
|
|
566
|
+
scroll: async (...args: unknown[]) => {
|
|
567
|
+
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null) return text('scroll', args[0] as Record<string, unknown>)
|
|
568
|
+
if (args.length >= 3) {
|
|
569
|
+
const [x, y, dy] = [Number(args[0]), Number(args[1]), Number(args[2])]
|
|
570
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(dy)) {
|
|
571
|
+
throw new Error('scroll(x, y, dy): coordinates and deltaY must be finite numbers')
|
|
572
|
+
}
|
|
573
|
+
return await js(`(() => {
|
|
574
|
+
let el = document.elementFromPoint(${JSON.stringify(x)}, ${JSON.stringify(y)});
|
|
575
|
+
while (el && el !== document.documentElement && el !== document.body) {
|
|
576
|
+
const st = getComputedStyle(el);
|
|
577
|
+
if (/(auto|scroll)/.test(st.overflowY) && el.scrollHeight > el.clientHeight) {
|
|
578
|
+
el.scrollBy({ top: ${JSON.stringify(dy)} });
|
|
579
|
+
return 'Scrolled element.';
|
|
580
|
+
}
|
|
581
|
+
el = el.parentElement;
|
|
582
|
+
}
|
|
583
|
+
window.scrollBy({ top: ${JSON.stringify(dy)} });
|
|
584
|
+
return 'Scrolled window.';
|
|
585
|
+
})()`)
|
|
586
|
+
}
|
|
587
|
+
const deltaY = args.length === 1 ? Number(args[0]) : 600
|
|
588
|
+
return text('scroll', { deltaY })
|
|
589
|
+
},
|
|
590
|
+
screenshot: (opts: Record<string, unknown> = {}) => text('screenshot', opts),
|
|
591
|
+
wait_for_element: async (selector: string, timeoutMs?: number) => {
|
|
592
|
+
const out = await value('wait', { selector, ...timeoutMs !== undefined ? { timeoutMs } : {} }) as { ready: boolean; reason: string }
|
|
593
|
+
if (!out.ready) throw new Error(`wait_for_element: ${out.reason}`)
|
|
594
|
+
return true
|
|
595
|
+
},
|
|
596
|
+
wait_for_network_idle: async (timeoutMs?: number) => {
|
|
597
|
+
const out = await value('do', { steps: [{ wait_idle: {} }], ...timeoutMs !== undefined ? { timeoutMs } : {} }) as { ok: boolean; reason?: string }
|
|
598
|
+
if (!out.ok) throw new Error(`wait_for_network_idle: ${out.reason ?? 'not idle'}`)
|
|
599
|
+
return true
|
|
600
|
+
},
|
|
601
|
+
// Deterministic waits: each returns as soon as its condition holds and throws when it never does.
|
|
602
|
+
wait_for_text: async (needle: string, timeoutMs?: number) => { await doStep('wait_for_text', { wait_text: { text: needle } }, timeoutMs); return true },
|
|
603
|
+
wait_for_gone: async (needle: string, timeoutMs?: number) => { await doStep('wait_for_gone', { wait_gone: { text: needle } }, timeoutMs); return true },
|
|
604
|
+
wait_until: async (expression: string, opts: { timeoutMs?: number; intervalMs?: number } = {}): Promise<unknown> => {
|
|
605
|
+
if (typeof expression !== 'string') throw new Error('wait_until(expression): pass page JavaScript as a string, e.g. wait_until("document.querySelectorAll(\'.row\').length >= 20")')
|
|
606
|
+
const out = await doStep('wait_until', { wait_js: { script: pageScript(expression), ...opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {} } }, opts.timeoutMs ?? 10_000)
|
|
607
|
+
const raw = out.log.at(-1)?.value
|
|
608
|
+
return raw === undefined ? true : JSON.parse(raw)
|
|
609
|
+
},
|
|
610
|
+
wait_for_response: async (urlContains: string, trigger?: (() => unknown) | { status?: number; timeoutMs?: number }, opts: { status?: number; timeoutMs?: number } = {}): Promise<unknown> => {
|
|
611
|
+
if (typeof trigger === 'object' && trigger !== null) { opts = trigger; trigger = undefined }
|
|
612
|
+
// Sent before the trigger runs: the scheduler holds the trigger until the watcher has its cursor.
|
|
613
|
+
const pending = value('wait_for_response', { urlContains, ...opts })
|
|
614
|
+
pending.catch(() => undefined)
|
|
615
|
+
if (typeof trigger === 'function') await trigger()
|
|
616
|
+
const out = await pending as { matched: boolean; reason: string; entry?: unknown }
|
|
617
|
+
if (!out.matched) throw new Error(`wait_for_response: ${out.reason}`)
|
|
618
|
+
return out.entry
|
|
619
|
+
},
|
|
620
|
+
// Data first: what the page already holds, and its JSON APIs read with the page's own cookies.
|
|
621
|
+
inspect_data_sources: () => value('data_sources'),
|
|
622
|
+
fetch_json: async (url: string, init: { method?: string; headers?: Record<string, string>; body?: unknown } = {}): Promise<unknown> => {
|
|
623
|
+
const headers = { ...init.headers }
|
|
624
|
+
let body = init.body
|
|
625
|
+
if (body !== undefined && typeof body !== 'string') {
|
|
626
|
+
body = JSON.stringify(body)
|
|
627
|
+
if (!Object.keys(headers).some(key => key.toLowerCase() === 'content-type')) headers['content-type'] = 'application/json'
|
|
628
|
+
}
|
|
629
|
+
const out = await value('fetch_json', {
|
|
630
|
+
url,
|
|
631
|
+
...init.method !== undefined ? { method: init.method } : {},
|
|
632
|
+
...Object.keys(headers).length > 0 ? { headers } : {},
|
|
633
|
+
...body !== undefined ? { body } : {},
|
|
634
|
+
}) as { body: string }
|
|
635
|
+
return JSON.parse(out.body)
|
|
636
|
+
},
|
|
637
|
+
upload_file: (selector: string, path: string) => text('upload', { target: { by: 'css', value: selector }, path }),
|
|
638
|
+
// Semantic helpers over the dsh tools.
|
|
639
|
+
click: (target: Target) => text('click', targetArgs(target)),
|
|
640
|
+
type: async (target: Target, input?: string | { submit?: boolean }, opts: { submit?: boolean } = {}) => {
|
|
641
|
+
if (typeof input !== 'string' && typeof target !== 'string') {
|
|
642
|
+
throw new Error('type(target, text): text must be a string when target is an object')
|
|
643
|
+
}
|
|
644
|
+
const toolArgs = typeof input === 'string' ? { ...targetArgs(target), text: input } : { text: target as string }
|
|
645
|
+
if (typeof input === 'object' && input !== null) opts = input
|
|
646
|
+
let out = await text('type', toolArgs)
|
|
647
|
+
if (opts.submit === true) out += '\n' + await text('key', { key: 'Enter' })
|
|
648
|
+
return out
|
|
649
|
+
},
|
|
650
|
+
select: (target: Target, optionText: string) => text('select', { ...targetArgs(target), optionText }),
|
|
651
|
+
fill: async (fields: readonly Record<string, unknown>[], opts: { submit?: boolean } = {}) => {
|
|
652
|
+
const out = await value('fill', { fields, ...opts.submit === true ? { submit: true } : {} }) as { fields: { ok: boolean; target?: string; error?: string }[]; submitted?: boolean }
|
|
653
|
+
const failed = out.fields.filter(field => !field.ok)
|
|
654
|
+
if (failed.length > 0) throw new Error(`fill: ${failed.length} field(s) failed: ${failed.map(field => `${field.target ?? '?'}: ${field.error ?? 'failed'}`).join('; ')}`)
|
|
655
|
+
return out
|
|
656
|
+
},
|
|
657
|
+
back: () => text('back'),
|
|
658
|
+
forward: () => text('forward'),
|
|
659
|
+
refresh: () => text('refresh'),
|
|
660
|
+
read: async (opts: Record<string, unknown> = {}) => {
|
|
661
|
+
const out = await value('content', { format: 'markdown', maxChars: 20000, ...opts }) as { content?: string; truncated?: boolean }
|
|
662
|
+
return (out.content ?? '') + (out.truncated === true ? '\n[truncated; pass selector or maxChars]' : '')
|
|
663
|
+
},
|
|
664
|
+
snapshot: (opts: Record<string, unknown> = {}) => text('snapshot', opts),
|
|
665
|
+
find: (needle: string, opts: Record<string, unknown> = {}) => text('find', { text: needle, ...opts }),
|
|
666
|
+
state: () => text('state'),
|
|
667
|
+
refs: {
|
|
668
|
+
capture: (opts: Record<string, unknown> = {}) => text('reference_capture', opts),
|
|
669
|
+
list: (opts: Record<string, unknown> = {}) => text('reference_list', opts),
|
|
670
|
+
reveal: (opts: Record<string, unknown>) => text('reference_reveal', opts),
|
|
671
|
+
},
|
|
672
|
+
call: (name: string, args: Record<string, unknown> = {}) => value(name, args),
|
|
673
|
+
help: (name?: string) => value('__help', name === undefined ? {} : { name }),
|
|
674
|
+
sleep: (ms: number) => {
|
|
675
|
+
if (++sleepsThisCell === SLEEP_HINT_AFTER) log(SLEEP_HINT)
|
|
676
|
+
return new Promise<void>(done => setTimeout(done, Math.min(Math.max(Number(ms) || 0, 0), 60_000)))
|
|
677
|
+
},
|
|
678
|
+
print: log,
|
|
679
|
+
log,
|
|
680
|
+
console: { log, info: log, warn: log, error: log, debug: log },
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async function doStep(label: string, step: Record<string, unknown>, timeoutMs?: number): Promise<{ log: { value?: string }[] }> {
|
|
684
|
+
const out = await value('do', { steps: [step], ...timeoutMs !== undefined ? { timeoutMs } : {} }) as { ok: boolean; reason?: string; log: { value?: string }[] }
|
|
685
|
+
if (!out.ok) throw new Error(`${label}: ${out.reason ?? 'condition never held'}`)
|
|
686
|
+
return out
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
async function js(script: string): Promise<unknown> {
|
|
690
|
+
const out = await value('execute', { script: pageScript(script) }) as { ok: boolean; value?: string; exception?: string }
|
|
691
|
+
if (!out.ok) throw new Error(`js: ${out.exception ?? 'page script failed'}`)
|
|
692
|
+
return out.value === undefined ? undefined : JSON.parse(out.value)
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** How a cell's uncaught error reads in the output: a tool failure names its tool. */
|
|
696
|
+
function describe(error: unknown): string {
|
|
697
|
+
if (!(error instanceof Error)) return String(error)
|
|
698
|
+
if (error instanceof ToolCallError) return `ToolCallError (${error.toolName}): ${error.message}`
|
|
699
|
+
return `${error.name === 'Error' ? '' : `${error.name}: `}${error.message}`
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
const context = createContext({ ...helpers, open: helpers.goto_url, press: helpers.press_key, tools, ToolCallError })
|
|
703
|
+
|
|
704
|
+
process.on('message', (message: Reply | Run) => {
|
|
705
|
+
if (message.type === 'reply') {
|
|
706
|
+
const entry = pending.get(message.id)
|
|
707
|
+
pending.delete(message.id)
|
|
708
|
+
entry?.resolve(message)
|
|
709
|
+
return
|
|
710
|
+
}
|
|
711
|
+
if (message.type === 'run') {
|
|
712
|
+
sleepsThisCell = 0
|
|
713
|
+
void (async () => {
|
|
714
|
+
try {
|
|
715
|
+
const result = await (runInContext(`(async () => {\n${prepare(message.code)}\n})()`, context, { filename: 'cell.js' }) as Promise<unknown>)
|
|
716
|
+
if (result !== undefined) log(result)
|
|
717
|
+
send({ type: 'done', ok: true })
|
|
718
|
+
} catch (error) {
|
|
719
|
+
send({ type: 'done', ok: false, error: describe(error) })
|
|
720
|
+
}
|
|
721
|
+
})()
|
|
722
|
+
}
|
|
723
|
+
})
|
|
724
|
+
process.on('disconnect', () => process.exit(0))
|
|
725
|
+
send({ type: 'ready' })
|