somora 2026.930.1
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/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,1337 @@
|
|
|
1
|
+
// Shared browser service — one managed Chromium per profile, driven by
|
|
2
|
+
// agents through the `browser` tool and (stage 2/3) watched and taken
|
|
3
|
+
// over by the user in the web client. Design: private/browser-design.md,
|
|
4
|
+
// spec: somora_feedback/2026-09-07_shared-browser-agent-handoff.md.
|
|
5
|
+
//
|
|
6
|
+
// Ownership model:
|
|
7
|
+
// profile = a Chromium user-data-dir = a cookie jar = ONE process.
|
|
8
|
+
// Every agent has its own (`agent:<name>`) unless
|
|
9
|
+
// config.browser.profiles names a shared one.
|
|
10
|
+
// browser = the running process for a profile, with its tabs.
|
|
11
|
+
// tab = a Playwright Page, owned by the agent+session that
|
|
12
|
+
// opened it, with a `generation` that bumps on every
|
|
13
|
+
// main-frame navigation — refs from an older generation
|
|
14
|
+
// are refused by `act`.
|
|
15
|
+
// view = one agent's window on a process (`<browser id>@<agent>`).
|
|
16
|
+
// A shared profile has ONE process but one view per agent,
|
|
17
|
+
// so hans and lisa each get their own window, tabs, control
|
|
18
|
+
// state and handoff (private/browser-design.md §10).
|
|
19
|
+
// control = per view: agent_control | handoff_requested |
|
|
20
|
+
// human_control | paused. While a human controls a view,
|
|
21
|
+
// that view's agent operations are refused with
|
|
22
|
+
// BROWSER_HUMAN_CONTROL; the other agents keep working.
|
|
23
|
+
//
|
|
24
|
+
// Playwright (playwright-core, no bundled browser) drives the pages —
|
|
25
|
+
// actionability checks, auto-wait, iframes, dialogs — against the host
|
|
26
|
+
// Chromium. The raw CDP session (screencast, wheel, insertText) is
|
|
27
|
+
// stage 2 and lives in screencast.ts.
|
|
28
|
+
//
|
|
29
|
+
// The service exists ONLY in the server process. The MCP tool child
|
|
30
|
+
// (claude-cli/codex-cli) reaches it over HTTP (`POST /browser/op`).
|
|
31
|
+
|
|
32
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
33
|
+
import { readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
34
|
+
import { homedir } from 'node:os';
|
|
35
|
+
import { join } from 'node:path';
|
|
36
|
+
import { randomUUID } from 'node:crypto';
|
|
37
|
+
import { chromium, devices, type BrowserContext, type CDPSession, type Page } from 'playwright-core';
|
|
38
|
+
import type { BrowserConfig } from '../config/types.ts';
|
|
39
|
+
import { logger } from '../server/logger.ts';
|
|
40
|
+
import { checkNavigationAllowed } from './policy.ts';
|
|
41
|
+
import { compactAriaSnapshot } from './snapshot.ts';
|
|
42
|
+
import { planHeaded, startVirtualDisplay, type HeadedPlan, type VirtualDisplay } from './display.ts';
|
|
43
|
+
|
|
44
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
45
|
+
|
|
46
|
+
export type ControlMode = 'agent_control' | 'handoff_requested' | 'human_control' | 'paused';
|
|
47
|
+
|
|
48
|
+
export interface Handoff {
|
|
49
|
+
id: string;
|
|
50
|
+
agent: string;
|
|
51
|
+
session: string;
|
|
52
|
+
reason: string;
|
|
53
|
+
resumeNote?: string;
|
|
54
|
+
requestedAt: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ControlState {
|
|
58
|
+
mode: ControlMode;
|
|
59
|
+
handoff?: Handoff;
|
|
60
|
+
/** Who holds human control (web client connection id), stage 2. */
|
|
61
|
+
humanBy?: string;
|
|
62
|
+
/** The human did something (click, typing, navigation) while in
|
|
63
|
+
* control — a hand-back then wakes the agent even without a pending
|
|
64
|
+
* handoff. A look-and-return leaves it false: no turn is spent. */
|
|
65
|
+
humanTouched?: boolean;
|
|
66
|
+
since: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One agent's window on a browser process. */
|
|
70
|
+
export interface ViewState {
|
|
71
|
+
agent: string;
|
|
72
|
+
control: ControlState;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `<browser id>@<agent>` — what every viewer surface addresses. `@` is
|
|
76
|
+
* safe in a URL path and query and cannot occur in an agent name. */
|
|
77
|
+
export function viewIdOf(browserId: string, agent: string): string {
|
|
78
|
+
return `${browserId}@${agent}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The Chromium process behind a view id; a process id passes through. */
|
|
82
|
+
export function processIdOf(id: string): string {
|
|
83
|
+
const i = id.lastIndexOf('@');
|
|
84
|
+
return i < 0 ? id : id.slice(0, i);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The owning agent of a view id, or undefined for a bare process id. */
|
|
88
|
+
export function agentOfViewId(id: string): string | undefined {
|
|
89
|
+
const i = id.lastIndexOf('@');
|
|
90
|
+
return i < 0 ? undefined : id.slice(i + 1);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface TabRec {
|
|
94
|
+
id: string;
|
|
95
|
+
page: Page;
|
|
96
|
+
agent: string;
|
|
97
|
+
session?: string;
|
|
98
|
+
generation: number;
|
|
99
|
+
createdByAgent: boolean;
|
|
100
|
+
/** The blank page a persistent context always opens; the first
|
|
101
|
+
* `open` without a tab reuses it instead of adding a second tab. */
|
|
102
|
+
initialBlank?: boolean;
|
|
103
|
+
lastUsed: number;
|
|
104
|
+
/** Refs of the last snapshot, keyed by generation — an `act` with a
|
|
105
|
+
* ref that was never in a snapshot of this generation is refused. */
|
|
106
|
+
snapshotRefs: Set<string>;
|
|
107
|
+
snapshotGeneration: number;
|
|
108
|
+
/** Per-tab emulation set by open {device, locale} — reported in TabInfo. */
|
|
109
|
+
emulation?: { device?: string; locale?: string };
|
|
110
|
+
/** CDP session used for emulation (kept for the tab's lifetime). */
|
|
111
|
+
cdp?: CDPSession;
|
|
112
|
+
/** A denied URL the tab was navigated to (redirect, in-page script)
|
|
113
|
+
* and evicted from; reported once by the next op. */
|
|
114
|
+
evictedFrom?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface BrowserRec {
|
|
118
|
+
id: string;
|
|
119
|
+
profile: string;
|
|
120
|
+
profileDir: string;
|
|
121
|
+
ephemeral: boolean;
|
|
122
|
+
/** Agents allowed on this profile. */
|
|
123
|
+
agents: ReadonlySet<string> | 'any';
|
|
124
|
+
context: BrowserContext;
|
|
125
|
+
tabs: Map<string, TabRec>;
|
|
126
|
+
/** One view per agent that has used this process, keyed by agent. */
|
|
127
|
+
views: Map<string, ViewState>;
|
|
128
|
+
lastUsed: number;
|
|
129
|
+
idleTimer: NodeJS.Timeout | null;
|
|
130
|
+
closing: Promise<void> | null;
|
|
131
|
+
/** Launched with a window (browser.headed). */
|
|
132
|
+
headed: boolean;
|
|
133
|
+
/** The Xvfb this browser runs on, when somora started one. */
|
|
134
|
+
display?: VirtualDisplay;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface TabInfo {
|
|
138
|
+
tab_id: string;
|
|
139
|
+
url: string;
|
|
140
|
+
title: string;
|
|
141
|
+
agent: string;
|
|
142
|
+
session?: string;
|
|
143
|
+
generation: number;
|
|
144
|
+
/** Device/locale emulation active on this tab (open {device, locale}). */
|
|
145
|
+
emulation?: { device?: string; locale?: string };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface BrowserInfo {
|
|
149
|
+
/** `<browser id>@<agent>` — what control, attach and restart take. */
|
|
150
|
+
view_id: string;
|
|
151
|
+
/** The agent this window belongs to. */
|
|
152
|
+
agent: string;
|
|
153
|
+
browser_id: string;
|
|
154
|
+
profile: string;
|
|
155
|
+
ephemeral: boolean;
|
|
156
|
+
state: 'running' | 'stopped';
|
|
157
|
+
control: ControlMode;
|
|
158
|
+
handoff?: Handoff;
|
|
159
|
+
tabs: TabInfo[];
|
|
160
|
+
human_by?: string;
|
|
161
|
+
last_used: number;
|
|
162
|
+
/** Launched with a window (browser.headed); absent for stopped entries. */
|
|
163
|
+
headed?: boolean;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface ServiceDeps {
|
|
167
|
+
/** Wake the agent in its session after "Hand back". */
|
|
168
|
+
dispatchWakeTurn?: (args: {
|
|
169
|
+
agent: string;
|
|
170
|
+
session: string;
|
|
171
|
+
text: string;
|
|
172
|
+
/** What to do about it — beside the text (turn-framing.ts). */
|
|
173
|
+
prefix: string;
|
|
174
|
+
/** Which window came back, and why the agent is woken. */
|
|
175
|
+
viewId: string;
|
|
176
|
+
cause: 'handoff' | 'activity';
|
|
177
|
+
handoffId?: string;
|
|
178
|
+
}) => Promise<void>;
|
|
179
|
+
/** Resolve and validate a live session before binding a browser or waking it. */
|
|
180
|
+
resolveSession?: (agent: string, ref: string) => Promise<string>;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export class BrowserOpError extends Error {
|
|
184
|
+
constructor(
|
|
185
|
+
readonly code:
|
|
186
|
+
| 'BROWSER_DISABLED'
|
|
187
|
+
| 'BROWSER_NOT_FOUND'
|
|
188
|
+
| 'BROWSER_HUMAN_CONTROL'
|
|
189
|
+
| 'BROWSER_NAVIGATION_DENIED'
|
|
190
|
+
| 'BROWSER_TAB_NOT_FOUND'
|
|
191
|
+
| 'BROWSER_STALE_REF'
|
|
192
|
+
| 'BROWSER_TAB_LIMIT'
|
|
193
|
+
| 'BROWSER_NOT_ALLOWED'
|
|
194
|
+
| 'BROWSER_LAUNCH_FAILED'
|
|
195
|
+
| 'BROWSER_ACTION_FAILED',
|
|
196
|
+
message: string,
|
|
197
|
+
) {
|
|
198
|
+
super(`${code}: ${message}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const EXECUTABLE_CANDIDATES = [
|
|
203
|
+
'/usr/bin/chromium',
|
|
204
|
+
'/usr/bin/chromium-browser',
|
|
205
|
+
'/usr/bin/google-chrome',
|
|
206
|
+
'/usr/bin/google-chrome-stable',
|
|
207
|
+
'/snap/bin/chromium',
|
|
208
|
+
'/opt/homebrew/bin/chromium',
|
|
209
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
210
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
export function detectExecutable(configured?: string): { path: string | null; tried: string[] } {
|
|
214
|
+
const tried = configured ? [configured] : EXECUTABLE_CANDIDATES;
|
|
215
|
+
for (const p of tried) if (existsSync(p)) return { path: p, tried };
|
|
216
|
+
return { path: null, tried };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function nowMs(): number {
|
|
220
|
+
return Date.now();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Something a viewer should redraw: tabs came or went, control changed.
|
|
224
|
+
* The id is the PROCESS id — a viewer on `<id>@<agent>` redraws too. */
|
|
225
|
+
export type ChangeListener = (browserId: string) => void;
|
|
226
|
+
|
|
227
|
+
/** Pre-§10 state files stored one control per process. Keep only what
|
|
228
|
+
* still means something: a pending handoff, moved to its agent's view. */
|
|
229
|
+
export function migratePersisted(
|
|
230
|
+
saved: Record<string, { control: ControlState }>,
|
|
231
|
+
): Record<string, { control: ControlState }> {
|
|
232
|
+
const out: Record<string, { control: ControlState }> = {};
|
|
233
|
+
for (const [id, entry] of Object.entries(saved)) {
|
|
234
|
+
if (id.includes('@')) {
|
|
235
|
+
out[id] = entry;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const agent = entry?.control?.handoff?.agent;
|
|
239
|
+
if (agent) out[viewIdOf(id, agent)] = entry;
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export class BrowserService {
|
|
245
|
+
private cfg: BrowserConfig;
|
|
246
|
+
private deps: ServiceDeps;
|
|
247
|
+
private writes: Promise<void> = Promise.resolve();
|
|
248
|
+
private operations = new Map<string, Promise<unknown>>();
|
|
249
|
+
private listeners = new Set<ChangeListener>();
|
|
250
|
+
private browsers = new Map<string, BrowserRec>();
|
|
251
|
+
private launching = new Map<string, Promise<BrowserRec>>();
|
|
252
|
+
/** Tab ids are unique across ALL browsers (an agent can have its
|
|
253
|
+
* persistent and an ephemeral browser at once), so a tab id alone
|
|
254
|
+
* identifies the browser too. */
|
|
255
|
+
private nextTab = 1;
|
|
256
|
+
/** Control state survives a stop/restart of the process for the
|
|
257
|
+
* pending-handoff case; persisted per VIEW id (`<browser>@<agent>`). */
|
|
258
|
+
private persisted: Record<string, { control: ControlState }> = {};
|
|
259
|
+
|
|
260
|
+
constructor(cfg: BrowserConfig, deps: ServiceDeps = {}) {
|
|
261
|
+
this.cfg = cfg;
|
|
262
|
+
this.deps = deps;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
static get dir(): string {
|
|
266
|
+
return join(SOMORA_HOME, 'browser');
|
|
267
|
+
}
|
|
268
|
+
static get profilesDir(): string {
|
|
269
|
+
return join(BrowserService.dir, 'profiles');
|
|
270
|
+
}
|
|
271
|
+
static get statePath(): string {
|
|
272
|
+
return join(BrowserService.dir, 'state.json');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
get enabled(): boolean {
|
|
276
|
+
return this.cfg.enabled;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
get config(): BrowserConfig {
|
|
280
|
+
return this.cfg;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
onChange(listener: ChangeListener): () => void {
|
|
284
|
+
this.listeners.add(listener);
|
|
285
|
+
return () => this.listeners.delete(listener);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private emitChange(browserId: string): void {
|
|
289
|
+
for (const l of this.listeners) {
|
|
290
|
+
try {
|
|
291
|
+
l(browserId);
|
|
292
|
+
} catch {
|
|
293
|
+
/* listener errors never reach the service */
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async init(): Promise<void> {
|
|
299
|
+
mkdirSync(BrowserService.profilesDir, { recursive: true });
|
|
300
|
+
try {
|
|
301
|
+
const raw = await readFile(BrowserService.statePath, 'utf8');
|
|
302
|
+
const parsed = JSON.parse(raw) as { browsers?: Record<string, { control: ControlState }> };
|
|
303
|
+
this.persisted = migratePersisted(parsed.browsers ?? {});
|
|
304
|
+
} catch {
|
|
305
|
+
this.persisted = {};
|
|
306
|
+
}
|
|
307
|
+
const exe = detectExecutable(this.cfg.executablePath);
|
|
308
|
+
const headed = planHeaded(this.cfg.headed);
|
|
309
|
+
logger.info({
|
|
310
|
+
msg: 'browser.service_ready',
|
|
311
|
+
enabled: this.cfg.enabled,
|
|
312
|
+
executable: exe.path,
|
|
313
|
+
headed: headed.mode,
|
|
314
|
+
profilesDir: BrowserService.profilesDir,
|
|
315
|
+
pendingHandoffs: Object.values(this.persisted).filter((p) => p.control?.handoff).length,
|
|
316
|
+
});
|
|
317
|
+
if (this.cfg.enabled && headed.mode === 'unavailable') {
|
|
318
|
+
logger.warn({ msg: 'browser.headed_unavailable', reason: headed.reason });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Headed-mode plan for this host (config + DISPLAY + Xvfb), without launching. */
|
|
323
|
+
headedPlan(): HeadedPlan {
|
|
324
|
+
return planHeaded(this.cfg.headed);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Operator-facing warnings for the status route and the browser list. */
|
|
328
|
+
warnings(): string[] {
|
|
329
|
+
const out: string[] = [];
|
|
330
|
+
if (!this.cfg.enabled) return out;
|
|
331
|
+
const exe = detectExecutable(this.cfg.executablePath);
|
|
332
|
+
if (!exe.path) out.push(`no Chromium found (tried ${exe.tried.join(', ')}) — install chromium or set browser.executablePath`);
|
|
333
|
+
const headed = planHeaded(this.cfg.headed);
|
|
334
|
+
if (headed.mode === 'unavailable') out.push(headed.reason);
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Shared by agent operations and viewer input: takeover waits for accepted
|
|
339
|
+
* work, and a queued agent action checks control again before executing. */
|
|
340
|
+
async withBrowserLock<T>(viewOrBrowserId: string, fn: () => Promise<T>): Promise<T> {
|
|
341
|
+
const id = processIdOf(viewOrBrowserId);
|
|
342
|
+
const previous = this.operations.get(id) ?? Promise.resolve();
|
|
343
|
+
const next = previous.catch(() => {}).then(fn);
|
|
344
|
+
this.operations.set(id, next);
|
|
345
|
+
try { return await next; }
|
|
346
|
+
finally { if (this.operations.get(id) === next) this.operations.delete(id); }
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private persist(change?: { browser: BrowserRec; view: ViewState; control: ControlState }): Promise<void> {
|
|
350
|
+
const next = this.writes.catch(() => {}).then(async () => {
|
|
351
|
+
// Build inside the write queue from committed controls. Another browser's
|
|
352
|
+
// pending transition must not leak into this snapshot before its own save.
|
|
353
|
+
const saved = { ...this.persisted };
|
|
354
|
+
for (const b of this.browsers.values()) {
|
|
355
|
+
for (const v of b.views.values()) saved[viewIdOf(b.id, v.agent)] = { control: v.control };
|
|
356
|
+
}
|
|
357
|
+
if (change) saved[viewIdOf(change.browser.id, change.view.agent)] = { control: change.control };
|
|
358
|
+
const tmp = `${BrowserService.statePath}.tmp`;
|
|
359
|
+
await writeFile(tmp, JSON.stringify({ browsers: saved }, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
360
|
+
await rename(tmp, BrowserService.statePath);
|
|
361
|
+
this.persisted = saved;
|
|
362
|
+
if (change) change.view.control = change.control;
|
|
363
|
+
});
|
|
364
|
+
this.writes = next;
|
|
365
|
+
return next;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Publish a control transition only after its durable state write succeeds. */
|
|
369
|
+
private commitControl(browser: BrowserRec, view: ViewState, control: ControlState): Promise<void> {
|
|
370
|
+
return this.persist({ browser, view, control });
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// ── profiles ──────────────────────────────────────────────────────
|
|
374
|
+
|
|
375
|
+
/** The profile an agent works in: a shared one it is listed on, else its own. */
|
|
376
|
+
profileFor(agent: string): { id: string; profile: string; agents: ReadonlySet<string> | 'any'; dir: string } {
|
|
377
|
+
for (const [name, p] of Object.entries(this.cfg.profiles)) {
|
|
378
|
+
if (p.agents.includes(agent)) {
|
|
379
|
+
return { id: `profile:${name}`, profile: name, agents: new Set(p.agents), dir: join(BrowserService.profilesDir, `shared-${name}`) };
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return { id: `agent:${agent}`, profile: agent, agents: new Set([agent]), dir: join(BrowserService.profilesDir, agent) };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private assertAllowed(b: BrowserRec, agent: string): void {
|
|
386
|
+
if (b.agents !== 'any' && !b.agents.has(agent)) {
|
|
387
|
+
throw new BrowserOpError('BROWSER_NOT_ALLOWED', `agent '${agent}' is not allowed on browser '${b.id}'`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The agent's window on this process. Created on first use. */
|
|
392
|
+
private viewOf(b: BrowserRec, agent: string, create = false): ViewState {
|
|
393
|
+
const existing = b.views.get(agent);
|
|
394
|
+
if (existing) return existing;
|
|
395
|
+
if (!create) {
|
|
396
|
+
throw new BrowserOpError('BROWSER_NOT_FOUND', `agent '${agent}' has no window on browser '${b.id}' — call op:"open" first`);
|
|
397
|
+
}
|
|
398
|
+
const view: ViewState = { agent, control: { mode: 'agent_control', since: nowMs() } };
|
|
399
|
+
b.views.set(agent, view);
|
|
400
|
+
return view;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private assertAgentControl(b: BrowserRec, view: ViewState): void {
|
|
404
|
+
if (b.closing || this.browsers.get(b.id) !== b) throw new BrowserOpError('BROWSER_NOT_FOUND', `browser '${b.id}' is no longer running`);
|
|
405
|
+
const id = viewIdOf(b.id, view.agent);
|
|
406
|
+
if (view.control.mode === 'human_control' || view.control.mode === 'paused') {
|
|
407
|
+
throw new BrowserOpError(
|
|
408
|
+
'BROWSER_HUMAN_CONTROL',
|
|
409
|
+
`browser '${id}' is paused for the user — do not retry; end your turn and wait until the user hands control back`,
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
if (view.control.mode === 'handoff_requested') {
|
|
413
|
+
throw new BrowserOpError(
|
|
414
|
+
'BROWSER_HUMAN_CONTROL',
|
|
415
|
+
`browser '${id}' is waiting for the user (handoff requested: ${view.control.handoff?.reason ?? ''}) — end your turn; you will be woken when the user hands control back`,
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Resolve what a viewer addressed: a view id, or a process id while
|
|
421
|
+
* exactly one agent has a window on it. */
|
|
422
|
+
private resolveView(id: string): { browser: BrowserRec; view: ViewState } {
|
|
423
|
+
const browser = this.runningBrowser(processIdOf(id));
|
|
424
|
+
const agent = agentOfViewId(id);
|
|
425
|
+
if (agent) {
|
|
426
|
+
const view = browser.views.get(agent);
|
|
427
|
+
if (!view) throw new BrowserOpError('BROWSER_NOT_FOUND', `browser '${id}' is not running`);
|
|
428
|
+
return { browser, view };
|
|
429
|
+
}
|
|
430
|
+
const views = [...browser.views.values()];
|
|
431
|
+
if (views.length === 1) return { browser, view: views[0]! };
|
|
432
|
+
if (views.length === 0) throw new BrowserOpError('BROWSER_NOT_FOUND', `browser '${id}' has no open window`);
|
|
433
|
+
throw new BrowserOpError(
|
|
434
|
+
'BROWSER_NOT_FOUND',
|
|
435
|
+
`browser '${id}' has ${views.length} windows — address one of ${views.map((v) => viewIdOf(browser.id, v.agent)).join(', ')}`,
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ── lifecycle ─────────────────────────────────────────────────────
|
|
440
|
+
|
|
441
|
+
private async ensureBrowser(agent: string, opts: { ephemeral?: boolean }): Promise<BrowserRec> {
|
|
442
|
+
if (!this.cfg.enabled) throw new BrowserOpError('BROWSER_DISABLED', 'browser.enabled is false in config.yaml');
|
|
443
|
+
const base = this.profileFor(agent);
|
|
444
|
+
const id = opts.ephemeral ? `${base.id}:tmp` : base.id;
|
|
445
|
+
const existing = this.browsers.get(id);
|
|
446
|
+
if (existing && !existing.closing) {
|
|
447
|
+
this.assertAllowed(existing, agent);
|
|
448
|
+
this.viewOf(existing, agent, true);
|
|
449
|
+
this.touch(existing);
|
|
450
|
+
return existing;
|
|
451
|
+
}
|
|
452
|
+
const pending = this.launching.get(id);
|
|
453
|
+
if (pending) return pending;
|
|
454
|
+
const p = this.launch(id, base, Boolean(opts.ephemeral), agent).finally(() => this.launching.delete(id));
|
|
455
|
+
this.launching.set(id, p);
|
|
456
|
+
return p;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
private async launch(
|
|
460
|
+
id: string,
|
|
461
|
+
base: ReturnType<BrowserService['profileFor']>,
|
|
462
|
+
ephemeral: boolean,
|
|
463
|
+
owner: string,
|
|
464
|
+
): Promise<BrowserRec> {
|
|
465
|
+
const exe = detectExecutable(this.cfg.executablePath);
|
|
466
|
+
if (!exe.path) {
|
|
467
|
+
throw new BrowserOpError(
|
|
468
|
+
'BROWSER_LAUNCH_FAILED',
|
|
469
|
+
`no Chromium found (tried ${exe.tried.join(', ')}) — install chromium or set browser.executablePath`,
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const dir = ephemeral ? join(BrowserService.profilesDir, `.tmp-${base.profile}-${randomUUID().slice(0, 8)}`) : base.dir;
|
|
473
|
+
mkdirSync(dir, { recursive: true });
|
|
474
|
+
const t0 = nowMs();
|
|
475
|
+
// Headed: a window on $DISPLAY, or on an Xvfb somora starts for this
|
|
476
|
+
// browser. No display and no Xvfb → refuse, never fall back to
|
|
477
|
+
// headless (that would silently bring the headless signals back).
|
|
478
|
+
const plan = planHeaded(this.cfg.headed);
|
|
479
|
+
if (plan.mode === 'unavailable') throw new BrowserOpError('BROWSER_LAUNCH_FAILED', plan.reason);
|
|
480
|
+
let display: VirtualDisplay | undefined;
|
|
481
|
+
if (plan.mode === 'xvfb') {
|
|
482
|
+
try {
|
|
483
|
+
display = await startVirtualDisplay(plan.xvfb, this.cfg.viewport);
|
|
484
|
+
} catch (err) {
|
|
485
|
+
throw new BrowserOpError('BROWSER_LAUNCH_FAILED', `Xvfb: ${(err as Error).message}`);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const headed = plan.mode !== 'headless';
|
|
489
|
+
let context: BrowserContext;
|
|
490
|
+
try {
|
|
491
|
+
context = await chromium.launchPersistentContext(dir, {
|
|
492
|
+
executablePath: exe.path,
|
|
493
|
+
headless: !headed,
|
|
494
|
+
viewport: { width: this.cfg.viewport.width, height: this.cfg.viewport.height },
|
|
495
|
+
acceptDownloads: false,
|
|
496
|
+
args: [
|
|
497
|
+
'--no-first-run',
|
|
498
|
+
'--disable-background-networking',
|
|
499
|
+
'--disable-sync',
|
|
500
|
+
// Headed = a browser a person could have opened: no automation
|
|
501
|
+
// banner flag and no AutomationControlled blink feature, so
|
|
502
|
+
// navigator.webdriver is false (measured 2026-09-08; the
|
|
503
|
+
// ignoreDefaultArgs alone leaves it true). Headless keeps the
|
|
504
|
+
// HeadlessChrome user agent whatever the flags, so nothing is
|
|
505
|
+
// changed there.
|
|
506
|
+
...(headed ? ['--disable-blink-features=AutomationControlled'] : []),
|
|
507
|
+
...(this.cfg.extraArgs ?? []),
|
|
508
|
+
],
|
|
509
|
+
...(headed ? { ignoreDefaultArgs: ['--enable-automation'] } : {}),
|
|
510
|
+
...(display ? { env: { ...process.env, DISPLAY: display.display } } : {}),
|
|
511
|
+
});
|
|
512
|
+
} catch (err) {
|
|
513
|
+
if (display) await display.stop().catch(() => {});
|
|
514
|
+
throw new BrowserOpError('BROWSER_LAUNCH_FAILED', `${exe.path}: ${(err as Error).message}`);
|
|
515
|
+
}
|
|
516
|
+
const rec: BrowserRec = {
|
|
517
|
+
id,
|
|
518
|
+
profile: base.profile,
|
|
519
|
+
profileDir: dir,
|
|
520
|
+
ephemeral,
|
|
521
|
+
agents: base.agents,
|
|
522
|
+
context,
|
|
523
|
+
tabs: new Map(),
|
|
524
|
+
views: new Map(),
|
|
525
|
+
lastUsed: nowMs(),
|
|
526
|
+
idleTimer: null,
|
|
527
|
+
closing: null,
|
|
528
|
+
headed,
|
|
529
|
+
...(display ? { display } : {}),
|
|
530
|
+
};
|
|
531
|
+
// Every agent that had a window on this process before the restart
|
|
532
|
+
// gets it back. A pending handoff stays pending — the user may still
|
|
533
|
+
// be about to take over. Anything else starts paused, so no stored
|
|
534
|
+
// action is replayed until an agent or the user touches it again.
|
|
535
|
+
for (const [savedId, saved] of Object.entries(this.persisted)) {
|
|
536
|
+
if (processIdOf(savedId) !== id) continue;
|
|
537
|
+
const agent = agentOfViewId(savedId);
|
|
538
|
+
if (!agent) continue;
|
|
539
|
+
rec.views.set(agent, {
|
|
540
|
+
agent,
|
|
541
|
+
control: { ...saved.control, mode: saved.control.handoff ? 'handoff_requested' : 'paused', humanBy: undefined, humanTouched: false },
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
if (!rec.views.has(owner)) rec.views.set(owner, { agent: owner, control: { mode: 'agent_control', since: nowMs() } });
|
|
545
|
+
// Every document request (incl. redirects and target=_blank) runs
|
|
546
|
+
// through the policy — the route is the safety net behind the
|
|
547
|
+
// pre-check in open()/act().
|
|
548
|
+
await context.route('**/*', async (route) => {
|
|
549
|
+
const req = route.request();
|
|
550
|
+
if (req.resourceType() !== 'document') return route.continue();
|
|
551
|
+
const verdict = await checkNavigationAllowed(req.url(), this.cfg);
|
|
552
|
+
if (verdict.ok) return route.continue();
|
|
553
|
+
logger.warn({ msg: 'browser.navigation_denied', browser: id, url: req.url(), reason: verdict.reason });
|
|
554
|
+
return route.abort('blockedbyclient');
|
|
555
|
+
});
|
|
556
|
+
// A popup (target=_blank, window.open) belongs to the window that
|
|
557
|
+
// opened it; only a page with no traceable opener stays unowned.
|
|
558
|
+
context.on('page', (page) => void this.adoptPopup(rec, page));
|
|
559
|
+
context.on('close', () => {
|
|
560
|
+
for (const v of rec.views.values()) {
|
|
561
|
+
this.persisted[viewIdOf(id, v.agent)] = { control: { ...v.control, mode: 'paused', humanBy: undefined, humanTouched: false } };
|
|
562
|
+
}
|
|
563
|
+
this.browsers.delete(id);
|
|
564
|
+
void this.persist().catch((err) => logger.warn({ msg: 'browser.state_persist_failed', err: String(err) }));
|
|
565
|
+
if (rec.display) void rec.display.stop().catch(() => {});
|
|
566
|
+
if (rec.ephemeral) void rm(rec.profileDir, { recursive: true, force: true }).catch(() => {});
|
|
567
|
+
if (rec.idleTimer) clearTimeout(rec.idleTimer);
|
|
568
|
+
logger.info({ msg: 'browser.closed', browser: id });
|
|
569
|
+
this.emitChange(id);
|
|
570
|
+
});
|
|
571
|
+
// Playwright opens one blank page with a persistent context; keep
|
|
572
|
+
// it as the first tab so `open` without a tab reuses it.
|
|
573
|
+
for (const page of context.pages()) this.adoptPage(rec, page, { agent: owner, createdByAgent: false, initialBlank: true });
|
|
574
|
+
this.browsers.set(id, rec);
|
|
575
|
+
this.touch(rec);
|
|
576
|
+
void this.persist().catch((err) => logger.warn({ msg: 'browser.state_persist_failed', err: String(err) }));
|
|
577
|
+
logger.info({ msg: 'browser.launched', browser: id, profile: base.profile, dir, ephemeral, ms: nowMs() - t0, executable: exe.path });
|
|
578
|
+
return rec;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** Attribute a page Chromium opened on its own to the view that opened it. */
|
|
582
|
+
private async adoptPopup(b: BrowserRec, page: Page): Promise<void> {
|
|
583
|
+
let owner: { agent: string; session?: string; createdByAgent: boolean } = { agent: '_user', createdByAgent: false };
|
|
584
|
+
try {
|
|
585
|
+
const opener = await page.opener();
|
|
586
|
+
if (opener) {
|
|
587
|
+
for (const t of b.tabs.values()) {
|
|
588
|
+
if (t.page !== opener) continue;
|
|
589
|
+
owner = { agent: t.agent, ...(t.session ? { session: t.session } : {}), createdByAgent: false };
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
} catch {
|
|
594
|
+
/* the opener may already be gone — the page stays unowned */
|
|
595
|
+
}
|
|
596
|
+
if (page.isClosed()) return;
|
|
597
|
+
this.adoptPage(b, page, owner);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
private adoptPage(b: BrowserRec, page: Page, owner: { agent: string; session?: string; createdByAgent: boolean; initialBlank?: boolean }): TabRec {
|
|
601
|
+
for (const t of b.tabs.values()) if (t.page === page) return t;
|
|
602
|
+
const id = `t${this.nextTab++}`;
|
|
603
|
+
const tab: TabRec = {
|
|
604
|
+
id,
|
|
605
|
+
page,
|
|
606
|
+
agent: owner.agent,
|
|
607
|
+
...(owner.session ? { session: owner.session } : {}),
|
|
608
|
+
generation: 1,
|
|
609
|
+
createdByAgent: owner.createdByAgent,
|
|
610
|
+
...(owner.initialBlank ? { initialBlank: true } : {}),
|
|
611
|
+
lastUsed: nowMs(),
|
|
612
|
+
snapshotRefs: new Set(),
|
|
613
|
+
snapshotGeneration: 0,
|
|
614
|
+
};
|
|
615
|
+
page.on('framenavigated', (frame) => {
|
|
616
|
+
if (frame !== page.mainFrame()) return;
|
|
617
|
+
tab.generation++;
|
|
618
|
+
tab.snapshotRefs = new Set();
|
|
619
|
+
this.emitChange(b.id);
|
|
620
|
+
// Redirect hops are not routed through the request interception
|
|
621
|
+
// (Chromium follows them before Playwright sees a new request), so
|
|
622
|
+
// a page that ended up somewhere the policy forbids is evicted
|
|
623
|
+
// right after the fact: back to about:blank, and the next op on
|
|
624
|
+
// the tab reports where it was sent. Documented limit: the first
|
|
625
|
+
// request to that host has already been made.
|
|
626
|
+
const url = frame.url();
|
|
627
|
+
if (!/^https?:/.test(url)) return;
|
|
628
|
+
void checkNavigationAllowed(url, this.cfg).then((verdict) => {
|
|
629
|
+
if (verdict.ok || page.isClosed()) return;
|
|
630
|
+
tab.evictedFrom = url;
|
|
631
|
+
logger.warn({ msg: 'browser.navigation_evicted', browser: b.id, tab: id, url, reason: verdict.reason });
|
|
632
|
+
page.goto('about:blank').catch(() => {});
|
|
633
|
+
});
|
|
634
|
+
});
|
|
635
|
+
page.on('close', () => {
|
|
636
|
+
b.tabs.delete(id);
|
|
637
|
+
this.emitChange(b.id);
|
|
638
|
+
});
|
|
639
|
+
b.tabs.set(id, tab);
|
|
640
|
+
this.emitChange(b.id);
|
|
641
|
+
return tab;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
private touch(b: BrowserRec): void {
|
|
645
|
+
b.lastUsed = nowMs();
|
|
646
|
+
if (b.idleTimer) clearTimeout(b.idleTimer);
|
|
647
|
+
b.idleTimer = setTimeout(() => {
|
|
648
|
+
// Never stop under a human's hands or with a handoff pending —
|
|
649
|
+
// in ANY of the windows on this process.
|
|
650
|
+
const busy = [...b.views.values()].some((v) => v.control.mode === 'human_control' || v.control.handoff);
|
|
651
|
+
if (busy || this.operations.has(b.id)) {
|
|
652
|
+
this.touch(b);
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
logger.info({ msg: 'browser.idle_stop', browser: b.id, idleMinutes: this.cfg.idleStopMinutes });
|
|
656
|
+
void this.stopBrowser(b);
|
|
657
|
+
}, this.cfg.idleStopMinutes * 60_000);
|
|
658
|
+
b.idleTimer.unref();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
private async stopBrowser(b: BrowserRec): Promise<void> {
|
|
662
|
+
if (b.closing) return b.closing;
|
|
663
|
+
b.closing = (async () => {
|
|
664
|
+
if (b.idleTimer) clearTimeout(b.idleTimer);
|
|
665
|
+
try {
|
|
666
|
+
await b.context.close();
|
|
667
|
+
} catch (err) {
|
|
668
|
+
logger.warn({ msg: 'browser.close_failed', browser: b.id, err: (err as Error).message });
|
|
669
|
+
}
|
|
670
|
+
this.browsers.delete(b.id);
|
|
671
|
+
if (b.display) await b.display.stop().catch(() => {});
|
|
672
|
+
if (b.ephemeral) await rm(b.profileDir, { recursive: true, force: true }).catch(() => {});
|
|
673
|
+
await this.persist();
|
|
674
|
+
})();
|
|
675
|
+
return b.closing;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** The agent's running browsers: persistent first, then ephemeral. */
|
|
679
|
+
private browsersFor(agent: string): BrowserRec[] {
|
|
680
|
+
const id = this.profileFor(agent).id;
|
|
681
|
+
return [this.browsers.get(id), this.browsers.get(`${id}:tmp`)].filter((b): b is BrowserRec => Boolean(b) && !b!.closing);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** The live tabs of one agent's window. */
|
|
685
|
+
private viewTabs(b: BrowserRec, agent: string): TabRec[] {
|
|
686
|
+
return [...b.tabs.values()].filter((t) => t.agent === agent && !t.page.isClosed());
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
private browserOf(agent: string, tabId?: string): BrowserRec {
|
|
690
|
+
const candidates = this.browsersFor(agent);
|
|
691
|
+
if (candidates.length === 0) throw new BrowserOpError('BROWSER_NOT_FOUND', `no running browser for agent '${agent}' — call op:"open" first`);
|
|
692
|
+
const b = tabId ? candidates.find((c) => c.tabs.has(tabId)) ?? candidates[0]! : candidates[0]!;
|
|
693
|
+
this.assertAllowed(b, agent);
|
|
694
|
+
return b;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
private tabOf(b: BrowserRec, tabId: string, agent?: string): TabRec {
|
|
698
|
+
const t = b.tabs.get(tabId);
|
|
699
|
+
if (!t || t.page.isClosed()) throw new BrowserOpError('BROWSER_TAB_NOT_FOUND', `tab '${tabId}' not found in browser '${b.id}' — op:"tabs" lists the open ones`);
|
|
700
|
+
// Tabs belong to one window. In a shared profile that keeps hans out
|
|
701
|
+
// of lisa's tabs even though both drive the same Chromium.
|
|
702
|
+
if (agent && t.agent !== agent) {
|
|
703
|
+
throw new BrowserOpError('BROWSER_TAB_NOT_FOUND', `tab '${tabId}' belongs to another agent's window on browser '${b.id}' — op:"tabs" lists yours`);
|
|
704
|
+
}
|
|
705
|
+
t.lastUsed = nowMs();
|
|
706
|
+
this.touch(b);
|
|
707
|
+
return t;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** Take the pending eviction note off a tab (reported once). */
|
|
711
|
+
private evicted(t: TabRec): string | undefined {
|
|
712
|
+
if (!t.evictedFrom) return undefined;
|
|
713
|
+
const url = t.evictedFrom;
|
|
714
|
+
delete t.evictedFrom;
|
|
715
|
+
return `the page was sent to '${url}', which the navigation policy forbids — the tab was reset to about:blank`;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Per-tab device/locale emulation — what the Chrome DevTools device
|
|
720
|
+
* mode does: user agent, viewport, pixel ratio, touch and language of
|
|
721
|
+
* that one tab. `device` is a Playwright device name ("iPhone 15",
|
|
722
|
+
* "Pixel 7", "iPad Pro 11"); `locale` a BCP-47 tag ("de-AT").
|
|
723
|
+
*/
|
|
724
|
+
private async emulate(tab: TabRec, args: { device?: string; locale?: string }): Promise<void> {
|
|
725
|
+
let descriptor: (typeof devices)[string] | undefined;
|
|
726
|
+
if (args.device) {
|
|
727
|
+
descriptor = devices[args.device];
|
|
728
|
+
if (!descriptor) {
|
|
729
|
+
const known = Object.keys(devices).filter((n) => !/landscape/i.test(n));
|
|
730
|
+
const hint = known.filter((n) => /^(iPhone 15|iPhone 14|Pixel 7|Galaxy S24|iPad Pro 11|iPad Mini|Desktop Chrome)/.test(n)).slice(0, 8);
|
|
731
|
+
throw new BrowserOpError('BROWSER_ACTION_FAILED', `unknown device '${args.device}' — known names include ${hint.join(', ')} (${known.length} in total)`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const cdp = tab.cdp ?? (await tab.page.context().newCDPSession(tab.page));
|
|
735
|
+
tab.cdp = cdp;
|
|
736
|
+
const userAgent = descriptor?.userAgent ?? (await tab.page.evaluate(() => navigator.userAgent));
|
|
737
|
+
await cdp.send('Emulation.setUserAgentOverride', {
|
|
738
|
+
userAgent,
|
|
739
|
+
...(args.locale ? { acceptLanguage: args.locale } : {}),
|
|
740
|
+
...(descriptor?.isMobile ? { platform: /iPhone|iPad/.test(descriptor.userAgent) ? 'iPhone' : 'Linux armv8l' } : {}),
|
|
741
|
+
});
|
|
742
|
+
if (args.locale) await cdp.send('Emulation.setLocaleOverride', { locale: args.locale });
|
|
743
|
+
if (descriptor) {
|
|
744
|
+
await tab.page.setViewportSize({ ...descriptor.viewport });
|
|
745
|
+
await cdp.send('Emulation.setDeviceMetricsOverride', {
|
|
746
|
+
width: descriptor.viewport.width,
|
|
747
|
+
height: descriptor.viewport.height,
|
|
748
|
+
deviceScaleFactor: descriptor.deviceScaleFactor,
|
|
749
|
+
mobile: descriptor.isMobile,
|
|
750
|
+
});
|
|
751
|
+
await cdp.send('Emulation.setTouchEmulationEnabled', { enabled: descriptor.hasTouch });
|
|
752
|
+
}
|
|
753
|
+
tab.emulation = { ...(tab.emulation ?? {}), ...(args.device ? { device: args.device } : {}), ...(args.locale ? { locale: args.locale } : {}) };
|
|
754
|
+
logger.info({ msg: 'browser.emulate', tab: tab.id, device: args.device ?? null, locale: args.locale ?? null });
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
private async tabInfo(t: TabRec): Promise<TabInfo> {
|
|
758
|
+
let title = '';
|
|
759
|
+
try {
|
|
760
|
+
title = await t.page.title();
|
|
761
|
+
} catch {
|
|
762
|
+
/* closed mid-way */
|
|
763
|
+
}
|
|
764
|
+
return {
|
|
765
|
+
tab_id: t.id,
|
|
766
|
+
url: t.page.url(),
|
|
767
|
+
title,
|
|
768
|
+
agent: t.agent,
|
|
769
|
+
...(t.session ? { session: t.session } : {}),
|
|
770
|
+
...(t.emulation ? { emulation: t.emulation } : {}),
|
|
771
|
+
generation: t.generation,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ── operations ────────────────────────────────────────────────────
|
|
776
|
+
|
|
777
|
+
async open(
|
|
778
|
+
agent: string,
|
|
779
|
+
session: string | undefined,
|
|
780
|
+
args: { url: string; tab?: string; ephemeral?: boolean; device?: string; locale?: string },
|
|
781
|
+
): Promise<{ view_id: string; browser_id: string; tab: TabInfo; control: ControlMode; blocked?: string }> {
|
|
782
|
+
if (session && this.deps.resolveSession) session = await this.deps.resolveSession(agent, session);
|
|
783
|
+
const verdict = await checkNavigationAllowed(args.url, this.cfg);
|
|
784
|
+
if (!verdict.ok) throw new BrowserOpError('BROWSER_NAVIGATION_DENIED', verdict.reason!);
|
|
785
|
+
const b = args.tab ? this.browserOf(agent, args.tab) : await this.ensureBrowser(agent, { ephemeral: args.ephemeral });
|
|
786
|
+
return this.withBrowserLock(b.id, async () => {
|
|
787
|
+
// Navigating an existing tab needs an existing window; a fresh
|
|
788
|
+
// `open` may create one (ensureBrowser already did for a new process).
|
|
789
|
+
const view = this.viewOf(b, agent, !args.tab);
|
|
790
|
+
// An explicit new navigation may resume an idle/restarted window; old
|
|
791
|
+
// operations are never replayed, and a pending handoff still blocks it.
|
|
792
|
+
if (view.control.mode === 'paused' && !view.control.handoff) {
|
|
793
|
+
await this.commitControl(b, view, { mode: 'agent_control', since: nowMs() });
|
|
794
|
+
}
|
|
795
|
+
this.assertAgentControl(b, view);
|
|
796
|
+
const own = this.viewTabs(b, agent);
|
|
797
|
+
let tab: TabRec;
|
|
798
|
+
if (args.tab) {
|
|
799
|
+
tab = this.tabOf(b, args.tab, agent);
|
|
800
|
+
} else {
|
|
801
|
+
// Reuse the initial blank tab once; otherwise a new one under the cap.
|
|
802
|
+
const blank = own.find((t) => t.initialBlank && t.page.url() === 'about:blank');
|
|
803
|
+
if (blank) {
|
|
804
|
+
tab = blank;
|
|
805
|
+
delete tab.initialBlank;
|
|
806
|
+
if (session) tab.session = session;
|
|
807
|
+
tab.createdByAgent = true;
|
|
808
|
+
} else {
|
|
809
|
+
if (own.length >= this.cfg.maxTabsPerAgent) {
|
|
810
|
+
throw new BrowserOpError(
|
|
811
|
+
'BROWSER_TAB_LIMIT',
|
|
812
|
+
`your window on browser '${b.id}' already has ${own.length} tabs (browser.maxTabsPerAgent) — close one with op:"close_tab" or reuse one with tab:"t<n>"`,
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
const page = await b.context.newPage();
|
|
816
|
+
tab = this.adoptPage(b, page, { agent, ...(session ? { session } : {}), createdByAgent: true });
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
tab.agent = agent;
|
|
820
|
+
if (session) tab.session = session;
|
|
821
|
+
tab.createdByAgent = true;
|
|
822
|
+
this.touch(b);
|
|
823
|
+
if (args.device || args.locale) await this.emulate(tab, { ...(args.device ? { device: args.device } : {}), ...(args.locale ? { locale: args.locale } : {}) });
|
|
824
|
+
let blocked: string | undefined;
|
|
825
|
+
try {
|
|
826
|
+
await tab.page.goto(args.url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
|
|
827
|
+
} catch (err) {
|
|
828
|
+
const msg = (err as Error).message;
|
|
829
|
+
if (/ERR_BLOCKED_BY_CLIENT|blockedbyclient/i.test(msg)) blocked = 'a redirect target was denied by the navigation policy';
|
|
830
|
+
else throw new BrowserOpError('BROWSER_ACTION_FAILED', `open ${args.url}: ${msg.split('\n')[0]}`);
|
|
831
|
+
}
|
|
832
|
+
await tab.page.waitForTimeout(150);
|
|
833
|
+
blocked = blocked ?? this.evicted(tab);
|
|
834
|
+
if (tab.page.url().startsWith('chrome-error://')) blocked = blocked ?? 'the navigation ended on an error page (unreachable host)';
|
|
835
|
+
this.emitChange(b.id);
|
|
836
|
+
logger.info({ msg: 'browser.open', browser: b.id, tab: tab.id, agent, url: args.url, blocked: blocked ?? null });
|
|
837
|
+
return { view_id: viewIdOf(b.id, agent), browser_id: b.id, tab: await this.tabInfo(tab), control: view.control.mode, ...(blocked ? { blocked } : {}) };
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
async tabs(agent: string): Promise<{ view_id: string; browser_id: string; control: ControlMode; tabs: TabInfo[] }> {
|
|
842
|
+
const bs = this.browsersFor(agent);
|
|
843
|
+
if (bs.length === 0) throw new BrowserOpError('BROWSER_NOT_FOUND', `no running browser for agent '${agent}' — call op:"open" first`);
|
|
844
|
+
for (const b of bs) this.assertAllowed(b, agent);
|
|
845
|
+
// Only this agent's window: a shared profile lists the other agent's
|
|
846
|
+
// tabs nowhere, they are not his to act on.
|
|
847
|
+
const tabs = (await Promise.all(bs.map((b) => Promise.all(this.viewTabs(b, agent).map((t) => this.tabInfo(t)))))).flat();
|
|
848
|
+
const first = bs[0]!;
|
|
849
|
+
return {
|
|
850
|
+
view_id: viewIdOf(first.id, agent),
|
|
851
|
+
browser_id: first.id,
|
|
852
|
+
control: first.views.get(agent)?.control.mode ?? 'paused',
|
|
853
|
+
tabs,
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async status(agent: string): Promise<{
|
|
858
|
+
enabled: boolean;
|
|
859
|
+
executable: string | null;
|
|
860
|
+
profile: string;
|
|
861
|
+
view_id: string;
|
|
862
|
+
browser_id: string;
|
|
863
|
+
running: boolean;
|
|
864
|
+
/** headless | display | xvfb, or unavailable with the reason. */
|
|
865
|
+
headed: HeadedPlan;
|
|
866
|
+
warnings: string[];
|
|
867
|
+
control?: ControlMode;
|
|
868
|
+
handoff?: Handoff;
|
|
869
|
+
tabs?: TabInfo[];
|
|
870
|
+
}> {
|
|
871
|
+
const exe = detectExecutable(this.cfg.executablePath);
|
|
872
|
+
const base = this.profileFor(agent);
|
|
873
|
+
const b = this.browsers.get(base.id);
|
|
874
|
+
const headed = planHeaded(this.cfg.headed);
|
|
875
|
+
const warnings = this.warnings();
|
|
876
|
+
const view = b && !b.closing ? b.views.get(agent) : undefined;
|
|
877
|
+
if (!b || b.closing || !view) {
|
|
878
|
+
return { enabled: this.cfg.enabled, executable: exe.path, profile: base.profile, view_id: viewIdOf(base.id, agent), browser_id: base.id, running: false, headed, warnings };
|
|
879
|
+
}
|
|
880
|
+
const tabs = await Promise.all(this.viewTabs(b, agent).map((t) => this.tabInfo(t)));
|
|
881
|
+
return {
|
|
882
|
+
enabled: this.cfg.enabled,
|
|
883
|
+
executable: exe.path,
|
|
884
|
+
profile: base.profile,
|
|
885
|
+
view_id: viewIdOf(b.id, agent),
|
|
886
|
+
browser_id: b.id,
|
|
887
|
+
running: true,
|
|
888
|
+
headed,
|
|
889
|
+
warnings,
|
|
890
|
+
control: view.control.mode,
|
|
891
|
+
...(view.control.handoff ? { handoff: view.control.handoff } : {}),
|
|
892
|
+
...(view.control.humanBy ? { human_by: view.control.humanBy } : {}),
|
|
893
|
+
tabs,
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
async snapshot(
|
|
898
|
+
agent: string,
|
|
899
|
+
args: { tab: string; full?: boolean; max_chars?: number },
|
|
900
|
+
): Promise<{ tab: TabInfo; generation: number; snapshot: string; truncated: boolean }> {
|
|
901
|
+
const b = this.browserOf(agent, args.tab);
|
|
902
|
+
return this.withBrowserLock(b.id, async () => {
|
|
903
|
+
this.assertAgentControl(b, this.viewOf(b, agent));
|
|
904
|
+
const t = this.tabOf(b, args.tab, agent);
|
|
905
|
+
const raw = await t.page.ariaSnapshot({ mode: 'ai', timeout: 15_000 });
|
|
906
|
+
const gen = t.generation;
|
|
907
|
+
const result = args.full ? { text: raw, truncated: false } : compactAriaSnapshot(raw, args.max_chars ?? 20_000);
|
|
908
|
+
// Playwright numbers refs `e<n>`, prefixed `f<n>` once the page has
|
|
909
|
+
// navigated within the context (frame generation) — accept both.
|
|
910
|
+
t.snapshotRefs = new Set([...raw.matchAll(/\[ref=((?:f\d+)?e\d+)\]/g)].map((m) => m[1]!));
|
|
911
|
+
t.snapshotGeneration = gen;
|
|
912
|
+
return { tab: await this.tabInfo(t), generation: gen, snapshot: result.text, truncated: result.truncated };
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
async act(
|
|
917
|
+
agent: string,
|
|
918
|
+
args: {
|
|
919
|
+
tab: string;
|
|
920
|
+
action: 'click' | 'fill' | 'press' | 'scroll' | 'select';
|
|
921
|
+
ref?: string;
|
|
922
|
+
value?: string;
|
|
923
|
+
generation?: number;
|
|
924
|
+
},
|
|
925
|
+
): Promise<{ tab: TabInfo; generation: number; navigated: boolean; blocked?: string }> {
|
|
926
|
+
const b = this.browserOf(agent, args.tab);
|
|
927
|
+
return this.withBrowserLock(b.id, async () => {
|
|
928
|
+
this.assertAgentControl(b, this.viewOf(b, agent));
|
|
929
|
+
const t = this.tabOf(b, args.tab, agent);
|
|
930
|
+
const genBefore = t.generation;
|
|
931
|
+
if (args.generation !== undefined && args.generation !== t.generation) {
|
|
932
|
+
throw new BrowserOpError(
|
|
933
|
+
'BROWSER_STALE_REF',
|
|
934
|
+
`tab '${t.id}' navigated since generation ${args.generation} (now ${t.generation}) — take a new snapshot before acting`,
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
if (args.ref) {
|
|
938
|
+
if (t.snapshotGeneration !== t.generation || !t.snapshotRefs.has(args.ref)) {
|
|
939
|
+
throw new BrowserOpError(
|
|
940
|
+
'BROWSER_STALE_REF',
|
|
941
|
+
`ref '${args.ref}' is not from a snapshot of the current page state of tab '${t.id}' — take a new snapshot first`,
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const loc = args.ref ? t.page.locator(`aria-ref=${args.ref}`) : null;
|
|
946
|
+
const timeout = 10_000;
|
|
947
|
+
try {
|
|
948
|
+
switch (args.action) {
|
|
949
|
+
case 'click':
|
|
950
|
+
if (!loc) throw new Error('click needs a ref');
|
|
951
|
+
await loc.click({ timeout });
|
|
952
|
+
break;
|
|
953
|
+
case 'fill':
|
|
954
|
+
if (!loc) throw new Error('fill needs a ref');
|
|
955
|
+
await loc.fill(args.value ?? '', { timeout });
|
|
956
|
+
break;
|
|
957
|
+
case 'press':
|
|
958
|
+
if (!args.value) throw new Error('press needs value (a key name like Enter, Tab, Escape, ArrowDown)');
|
|
959
|
+
if (loc) await loc.press(args.value, { timeout });
|
|
960
|
+
else await t.page.keyboard.press(args.value);
|
|
961
|
+
break;
|
|
962
|
+
case 'scroll':
|
|
963
|
+
if (loc) await loc.scrollIntoViewIfNeeded({ timeout });
|
|
964
|
+
else await t.page.mouse.wheel(0, Number(args.value ?? '600') || 600);
|
|
965
|
+
break;
|
|
966
|
+
case 'select':
|
|
967
|
+
if (!loc) throw new Error('select needs a ref');
|
|
968
|
+
await loc.selectOption(args.value ?? '', { timeout });
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
} catch (err) {
|
|
972
|
+
throw new BrowserOpError('BROWSER_ACTION_FAILED', `${args.action}${args.ref ? ` ${args.ref}` : ''}: ${(err as Error).message.split('\n')[0]}`);
|
|
973
|
+
}
|
|
974
|
+
// Give a navigation the action may have started a moment to land.
|
|
975
|
+
await t.page.waitForLoadState('domcontentloaded', { timeout: 5_000 }).catch(() => {});
|
|
976
|
+
await t.page.waitForTimeout(150);
|
|
977
|
+
const navigated = t.generation !== genBefore;
|
|
978
|
+
const blocked = this.evicted(t) ?? (t.page.url().startsWith('chrome-error://') ? 'the navigation ended on an error page (unreachable host)' : undefined);
|
|
979
|
+
return { tab: await this.tabInfo(t), generation: t.generation, navigated, ...(blocked ? { blocked } : {}) };
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
async screenshot(agent: string, args: { tab: string }): Promise<{ tab: TabInfo; png: Buffer }> {
|
|
984
|
+
const b = this.browserOf(agent, args.tab);
|
|
985
|
+
return this.withBrowserLock(b.id, async () => {
|
|
986
|
+
this.assertAgentControl(b, this.viewOf(b, agent));
|
|
987
|
+
const t = this.tabOf(b, args.tab, agent);
|
|
988
|
+
const png = await t.page.screenshot({ type: 'png', timeout: 15_000 });
|
|
989
|
+
return { tab: await this.tabInfo(t), png };
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
async requestHandoff(
|
|
994
|
+
agent: string,
|
|
995
|
+
session: string | undefined,
|
|
996
|
+
args: { reason: string; resume_note?: string },
|
|
997
|
+
): Promise<{ view_id: string; browser_id: string; handoff_id: string; control: ControlMode }> {
|
|
998
|
+
if (session && this.deps.resolveSession) session = await this.deps.resolveSession(agent, session);
|
|
999
|
+
const b = this.browserOf(agent);
|
|
1000
|
+
const id = viewIdOf(b.id, agent);
|
|
1001
|
+
return this.withBrowserLock(b.id, async () => {
|
|
1002
|
+
if (!session) throw new BrowserOpError('BROWSER_ACTION_FAILED', 'request_handoff needs a session to resume in');
|
|
1003
|
+
const view = this.viewOf(b, agent, true);
|
|
1004
|
+
if (view.control.mode === 'human_control') {
|
|
1005
|
+
throw new BrowserOpError('BROWSER_HUMAN_CONTROL', `the user already controls browser '${id}'`);
|
|
1006
|
+
}
|
|
1007
|
+
if (view.control.handoff) {
|
|
1008
|
+
if (view.control.handoff.agent !== agent || view.control.handoff.session !== session)
|
|
1009
|
+
throw new BrowserOpError('BROWSER_HUMAN_CONTROL', 'another session is already waiting for this browser');
|
|
1010
|
+
return { view_id: id, browser_id: b.id, handoff_id: view.control.handoff.id, control: view.control.mode };
|
|
1011
|
+
}
|
|
1012
|
+
const handoff: Handoff = {
|
|
1013
|
+
id: randomUUID(),
|
|
1014
|
+
agent,
|
|
1015
|
+
session,
|
|
1016
|
+
reason: args.reason,
|
|
1017
|
+
...(args.resume_note ? { resumeNote: args.resume_note } : {}),
|
|
1018
|
+
requestedAt: nowMs(),
|
|
1019
|
+
};
|
|
1020
|
+
await this.commitControl(b, view, { mode: 'handoff_requested', handoff, since: nowMs() });
|
|
1021
|
+
this.touch(b);
|
|
1022
|
+
this.emitChange(b.id);
|
|
1023
|
+
logger.info({ msg: 'browser.handoff_requested', browser: id, agent, session, reason: args.reason });
|
|
1024
|
+
return { view_id: id, browser_id: b.id, handoff_id: handoff.id, control: view.control.mode };
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
async closeTab(agent: string, args: { tab: string }): Promise<{ closed: string; remaining: number }> {
|
|
1029
|
+
const b = this.browserOf(agent, args.tab);
|
|
1030
|
+
return this.withBrowserLock(b.id, async () => {
|
|
1031
|
+
this.assertAgentControl(b, this.viewOf(b, agent));
|
|
1032
|
+
const t = this.tabOf(b, args.tab, agent);
|
|
1033
|
+
await t.page.close().catch(() => {});
|
|
1034
|
+
b.tabs.delete(t.id);
|
|
1035
|
+
return { closed: t.id, remaining: this.viewTabs(b, agent).length };
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Close this agent's window. The Chromium process only ends when no
|
|
1041
|
+
* other agent still has one on it — in a shared profile hans must not
|
|
1042
|
+
* pull the browser out from under lisa.
|
|
1043
|
+
*/
|
|
1044
|
+
async stop(agent: string): Promise<{ stopped: string | null }> {
|
|
1045
|
+
const bs = this.browsersFor(agent).filter((b) => b.views.has(agent));
|
|
1046
|
+
if (bs.length === 0) return { stopped: null };
|
|
1047
|
+
for (const b of bs) {
|
|
1048
|
+
this.assertAllowed(b, agent);
|
|
1049
|
+
const view = this.viewOf(b, agent);
|
|
1050
|
+
if (view.control.mode === 'human_control') throw new BrowserOpError('BROWSER_HUMAN_CONTROL', `the user controls browser '${viewIdOf(b.id, agent)}'`);
|
|
1051
|
+
}
|
|
1052
|
+
await Promise.all(bs.map((b) => this.withBrowserLock(b.id, async () => {
|
|
1053
|
+
const view = this.viewOf(b, agent);
|
|
1054
|
+
this.assertAgentControl(b, view);
|
|
1055
|
+
for (const t of this.viewTabs(b, agent)) {
|
|
1056
|
+
await t.page.close().catch(() => {});
|
|
1057
|
+
b.tabs.delete(t.id);
|
|
1058
|
+
}
|
|
1059
|
+
b.views.delete(agent);
|
|
1060
|
+
delete this.persisted[viewIdOf(b.id, agent)];
|
|
1061
|
+
if (b.views.size === 0) await this.stopBrowser(b);
|
|
1062
|
+
else {
|
|
1063
|
+
await this.persist();
|
|
1064
|
+
this.emitChange(b.id);
|
|
1065
|
+
}
|
|
1066
|
+
})));
|
|
1067
|
+
return { stopped: bs.map((b) => viewIdOf(b.id, agent)).join(', ') };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// ── UI / control (stage 3 surfaces; HTTP-testable now) ────────────
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* One entry per open window, not per process: in a shared profile hans
|
|
1074
|
+
* and lisa are two rows with their own tabs and control state. Stopped
|
|
1075
|
+
* browsers are left out the way the tmux list leaves dead sessions out
|
|
1076
|
+
* — except one still holding an unanswered handoff, which is the only
|
|
1077
|
+
* trail back to that request (private/browser-design.md §10.4).
|
|
1078
|
+
*/
|
|
1079
|
+
async listAll(): Promise<BrowserInfo[]> {
|
|
1080
|
+
const out: BrowserInfo[] = [];
|
|
1081
|
+
for (const b of this.browsers.values()) {
|
|
1082
|
+
if (b.closing) continue;
|
|
1083
|
+
for (const view of b.views.values()) {
|
|
1084
|
+
const tabs = await Promise.all(this.viewTabs(b, view.agent).map((t) => this.tabInfo(t)));
|
|
1085
|
+
// An empty window is only worth a row while something is pending.
|
|
1086
|
+
if (tabs.length === 0 && !view.control.handoff && view.control.mode !== 'human_control') continue;
|
|
1087
|
+
out.push({
|
|
1088
|
+
view_id: viewIdOf(b.id, view.agent),
|
|
1089
|
+
agent: view.agent,
|
|
1090
|
+
browser_id: b.id,
|
|
1091
|
+
profile: b.profile,
|
|
1092
|
+
ephemeral: b.ephemeral,
|
|
1093
|
+
state: 'running',
|
|
1094
|
+
control: view.control.mode,
|
|
1095
|
+
...(view.control.handoff ? { handoff: view.control.handoff } : {}),
|
|
1096
|
+
...(view.control.humanBy ? { human_by: view.control.humanBy } : {}),
|
|
1097
|
+
tabs,
|
|
1098
|
+
last_used: b.lastUsed,
|
|
1099
|
+
headed: b.headed,
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
for (const [id, p] of Object.entries(this.persisted)) {
|
|
1104
|
+
const browserId = processIdOf(id);
|
|
1105
|
+
const agent = agentOfViewId(id);
|
|
1106
|
+
if (!agent || !p.control?.handoff) continue;
|
|
1107
|
+
if (this.browsers.get(browserId)?.views.has(agent)) continue;
|
|
1108
|
+
out.push({
|
|
1109
|
+
view_id: id,
|
|
1110
|
+
agent,
|
|
1111
|
+
browser_id: browserId,
|
|
1112
|
+
profile: browserId.replace(/^(agent|profile):/, '').replace(/:tmp$/, ''),
|
|
1113
|
+
ephemeral: browserId.endsWith(':tmp'),
|
|
1114
|
+
state: 'stopped',
|
|
1115
|
+
control: 'paused',
|
|
1116
|
+
handoff: p.control.handoff,
|
|
1117
|
+
tabs: [],
|
|
1118
|
+
last_used: 0,
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
return out;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/** Explicit user recovery starts a blank page in the same profile. */
|
|
1125
|
+
async restartForViewer(viewOrBrowserId: string): Promise<void> {
|
|
1126
|
+
const browserId = processIdOf(viewOrBrowserId);
|
|
1127
|
+
const savedViews = Object.keys(this.persisted).filter((k) => processIdOf(k) === browserId);
|
|
1128
|
+
if (!this.persisted[viewOrBrowserId] && savedViews.length === 0) throw new BrowserOpError('BROWSER_NOT_FOUND', 'unknown browser');
|
|
1129
|
+
const match = /^(agent|profile):(.+?)(:tmp)?$/.exec(browserId);
|
|
1130
|
+
if (!match) throw new BrowserOpError('BROWSER_NOT_FOUND', 'invalid browser id');
|
|
1131
|
+
// The window's own agent restarts the process; for a bare process id
|
|
1132
|
+
// take a saved window, else the first agent the profile still lists.
|
|
1133
|
+
const agent =
|
|
1134
|
+
agentOfViewId(viewOrBrowserId) ??
|
|
1135
|
+
(savedViews.length ? agentOfViewId(savedViews[0]!) : undefined) ??
|
|
1136
|
+
(match[1] === 'profile' ? this.cfg.profiles[match[2]!]?.agents[0] : match[2]);
|
|
1137
|
+
if (!agent || this.profileFor(agent).id + (match[3] ?? '') !== browserId)
|
|
1138
|
+
throw new BrowserOpError('BROWSER_NOT_ALLOWED', 'profile is no longer configured');
|
|
1139
|
+
await this.ensureBrowser(agent, { ephemeral: Boolean(match[3]) });
|
|
1140
|
+
this.emitChange(browserId);
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/**
|
|
1144
|
+
* Human takes or returns ONE window. `agent` = hand back: with a
|
|
1145
|
+
* pending handoff the requesting agent is woken exactly once in its
|
|
1146
|
+
* session (idempotent per handoff id); without one, only the window's
|
|
1147
|
+
* own agent is woken, and only after real activity. The other agents
|
|
1148
|
+
* on a shared profile keep working throughout.
|
|
1149
|
+
*/
|
|
1150
|
+
async setControl(viewId: string, mode: 'human' | 'agent', opts: { by?: string; handoffId?: string } = {}): Promise<ControlState> {
|
|
1151
|
+
return this.withBrowserLock(viewId, async () => {
|
|
1152
|
+
const { browser: b, view } = this.resolveView(viewId);
|
|
1153
|
+
const id = viewIdOf(b.id, view.agent);
|
|
1154
|
+
if (mode === 'human') {
|
|
1155
|
+
await this.commitControl(b, view, { mode: 'human_control', ...(view.control.handoff ? { handoff: view.control.handoff } : {}), ...(opts.by ? { humanBy: opts.by } : {}), since: nowMs() });
|
|
1156
|
+
this.touch(b);
|
|
1157
|
+
logger.info({ msg: 'browser.human_control', browser: id, by: opts.by ?? null });
|
|
1158
|
+
this.emitChange(b.id);
|
|
1159
|
+
return view.control;
|
|
1160
|
+
}
|
|
1161
|
+
const handoff = view.control.handoff;
|
|
1162
|
+
if (opts.handoffId && handoff && opts.handoffId !== handoff.id) {
|
|
1163
|
+
throw new BrowserOpError('BROWSER_ACTION_FAILED', 'stale handoff — refresh before handing back');
|
|
1164
|
+
}
|
|
1165
|
+
if (opts.handoffId && !handoff) return view.control; // duplicate, never release a newer manual takeover
|
|
1166
|
+
if (opts.by && view.control.humanBy && opts.by !== view.control.humanBy) {
|
|
1167
|
+
throw new BrowserOpError('BROWSER_HUMAN_CONTROL', 'another viewer controls this browser');
|
|
1168
|
+
}
|
|
1169
|
+
if (handoff && this.deps.resolveSession) await this.deps.resolveSession(handoff.agent, handoff.session);
|
|
1170
|
+
const touched = view.control.humanTouched === true;
|
|
1171
|
+
await this.commitControl(b, view, { mode: 'agent_control', since: nowMs() });
|
|
1172
|
+
this.touch(b);
|
|
1173
|
+
// Whom to wake: the requesting agent+session when a handoff was
|
|
1174
|
+
// pending; otherwise — only if the human actually did something —
|
|
1175
|
+
// the session of the last tab used IN THIS WINDOW (Rene 2026-09-10).
|
|
1176
|
+
let wake: { agent: string; session: string; text: string; prefix: string; viewId: string; cause: 'handoff' | 'activity'; handoffId?: string } | null = null;
|
|
1177
|
+
if (handoff) {
|
|
1178
|
+
wake = {
|
|
1179
|
+
agent: handoff.agent,
|
|
1180
|
+
session: handoff.session,
|
|
1181
|
+
viewId: id,
|
|
1182
|
+
cause: 'handoff',
|
|
1183
|
+
handoffId: handoff.id,
|
|
1184
|
+
text:
|
|
1185
|
+
`[browser] The user handed browser '${id}' back to you (handoff ${handoff.id}). ` +
|
|
1186
|
+
`Reason you asked for it: ${handoff.reason}.` +
|
|
1187
|
+
(handoff.resumeNote ? ` Your note: ${handoff.resumeNote}.` : ''),
|
|
1188
|
+
prefix: 'Take a fresh snapshot before acting — the page may have changed while the user had it.',
|
|
1189
|
+
};
|
|
1190
|
+
} else if (touched) {
|
|
1191
|
+
const last = this.lastAgentTab(b, view.agent);
|
|
1192
|
+
if (last) {
|
|
1193
|
+
wake = {
|
|
1194
|
+
agent: last.agent,
|
|
1195
|
+
session: last.session,
|
|
1196
|
+
viewId: id,
|
|
1197
|
+
cause: 'activity',
|
|
1198
|
+
text: `[browser] The user took over browser '${id}', did something there (navigation, clicks or typing) and handed it back to you.`,
|
|
1199
|
+
prefix: 'If you still have work in this browser, take a fresh snapshot before acting — the page may have changed. Otherwise just acknowledge briefly.',
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
logger.info({ msg: 'browser.agent_control', browser: id, wake: handoff ? handoff.id : wake ? 'activity' : null, ...(wake ? { agent: wake.agent, session: wake.session } : {}) });
|
|
1204
|
+
this.emitChange(b.id);
|
|
1205
|
+
if (wake && this.deps.dispatchWakeTurn) {
|
|
1206
|
+
void this.deps.dispatchWakeTurn(wake).catch((err) => logger.warn({ msg: 'browser.wake_failed', browser: id, err: String(err) }));
|
|
1207
|
+
}
|
|
1208
|
+
return view.control;
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/** The tab this window's agent used most recently (has a session), or null. */
|
|
1213
|
+
private lastAgentTab(b: BrowserRec, agent: string): { agent: string; session: string } | null {
|
|
1214
|
+
let best: TabRec | null = null;
|
|
1215
|
+
for (const t of this.viewTabs(b, agent)) {
|
|
1216
|
+
if (!t.session || !t.createdByAgent) continue;
|
|
1217
|
+
if (!best || t.lastUsed > best.lastUsed) best = t;
|
|
1218
|
+
}
|
|
1219
|
+
return best && best.session ? { agent: best.agent, session: best.session } : null;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
/** Record human activity in one window (see ControlState.humanTouched). */
|
|
1223
|
+
markHumanActivity(viewId: string, kind: string): void {
|
|
1224
|
+
if (kind === 'mousemove' || kind === 'resize' || kind === 'tab') return;
|
|
1225
|
+
let view: ViewState;
|
|
1226
|
+
try {
|
|
1227
|
+
view = this.resolveView(viewId).view;
|
|
1228
|
+
} catch {
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (view.control.mode !== 'human_control' || view.control.humanTouched) return;
|
|
1232
|
+
view.control.humanTouched = true;
|
|
1233
|
+
void this.persist().catch((err) => logger.warn({ msg: 'browser.state_persist_failed', err: String(err) }));
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// ── viewer surface (stage 2: web client) ──────────────────────────
|
|
1237
|
+
|
|
1238
|
+
/** Running browser by id, for the viewer path. */
|
|
1239
|
+
private runningBrowser(browserId: string): BrowserRec {
|
|
1240
|
+
const b = this.browsers.get(browserId);
|
|
1241
|
+
if (!b || b.closing) throw new BrowserOpError('BROWSER_NOT_FOUND', `browser '${browserId}' is not running`);
|
|
1242
|
+
return b;
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/** Summary of one window for the viewer header. */
|
|
1246
|
+
async browserInfo(viewId: string): Promise<BrowserInfo> {
|
|
1247
|
+
const { browser: b, view } = this.resolveView(viewId);
|
|
1248
|
+
const tabs = await Promise.all(this.viewTabs(b, view.agent).map((t) => this.tabInfo(t)));
|
|
1249
|
+
return {
|
|
1250
|
+
view_id: viewIdOf(b.id, view.agent),
|
|
1251
|
+
agent: view.agent,
|
|
1252
|
+
browser_id: b.id,
|
|
1253
|
+
profile: b.profile,
|
|
1254
|
+
ephemeral: b.ephemeral,
|
|
1255
|
+
state: 'running',
|
|
1256
|
+
control: view.control.mode,
|
|
1257
|
+
...(view.control.handoff ? { handoff: view.control.handoff } : {}),
|
|
1258
|
+
...(view.control.humanBy ? { human_by: view.control.humanBy } : {}),
|
|
1259
|
+
tabs,
|
|
1260
|
+
last_used: b.lastUsed,
|
|
1261
|
+
headed: b.headed,
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/** The page a viewer wants to watch: the given tab of THIS window, else
|
|
1266
|
+
* its most recently used one. Touches the browser (viewers count as
|
|
1267
|
+
* activity). A tab of another agent's window is not reachable here. */
|
|
1268
|
+
viewerPage(viewId: string, tabId?: string): { tabId: string; page: Page; generation: number } {
|
|
1269
|
+
const { browser: b, view } = this.resolveView(viewId);
|
|
1270
|
+
this.touch(b);
|
|
1271
|
+
const live = this.viewTabs(b, view.agent);
|
|
1272
|
+
const t = tabId ? live.find((x) => x.id === tabId) : live.sort((a, c) => c.lastUsed - a.lastUsed)[0];
|
|
1273
|
+
if (!t) throw new BrowserOpError('BROWSER_TAB_NOT_FOUND', `browser '${viewId}' has no open tab`);
|
|
1274
|
+
return { tabId: t.id, page: t.page, generation: t.generation };
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/** True when this viewer connection may drive this window. */
|
|
1278
|
+
humanControls(viewId: string, by: string): boolean {
|
|
1279
|
+
let view: ViewState;
|
|
1280
|
+
try {
|
|
1281
|
+
view = this.resolveView(viewId).view;
|
|
1282
|
+
} catch {
|
|
1283
|
+
return false;
|
|
1284
|
+
}
|
|
1285
|
+
return view.control.mode === 'human_control' && (view.control.humanBy === undefined || view.control.humanBy === by);
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/** Human navigation (URL bar) — same policy as the agent's `open`. */
|
|
1289
|
+
async humanNavigate(viewId: string, tabId: string, url: string): Promise<void> {
|
|
1290
|
+
const verdict = await checkNavigationAllowed(url, this.cfg);
|
|
1291
|
+
if (!verdict.ok) throw new BrowserOpError('BROWSER_NAVIGATION_DENIED', verdict.reason!);
|
|
1292
|
+
const { page } = this.viewerPage(viewId, tabId);
|
|
1293
|
+
this.markHumanActivity(viewId, 'navigate');
|
|
1294
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 }).catch((err) => {
|
|
1295
|
+
throw new BrowserOpError('BROWSER_ACTION_FAILED', (err as Error).message.split('\n')[0]!);
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/** A tab the human opened: it belongs to this window (so the agent can
|
|
1300
|
+
* use it afterwards), but not to the agent (tab cleanup leaves it). */
|
|
1301
|
+
async humanNewTab(viewId: string, _by: string): Promise<string> {
|
|
1302
|
+
const { browser: b, view } = this.resolveView(viewId);
|
|
1303
|
+
const own = this.viewTabs(b, view.agent);
|
|
1304
|
+
if (own.length >= this.cfg.maxTabsPerAgent) throw new BrowserOpError('BROWSER_TAB_LIMIT', `this window already has ${own.length} tabs`);
|
|
1305
|
+
const page = await b.context.newPage();
|
|
1306
|
+
const tab = this.adoptPage(b, page, { agent: view.agent, createdByAgent: false });
|
|
1307
|
+
this.markHumanActivity(viewId, 'newtab');
|
|
1308
|
+
this.touch(b);
|
|
1309
|
+
return tab.id;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
async humanCloseTab(viewId: string, tabId: string): Promise<void> {
|
|
1313
|
+
const { browser: b, view } = this.resolveView(viewId);
|
|
1314
|
+
const t = b.tabs.get(tabId);
|
|
1315
|
+
if (!t || t.agent !== view.agent) return;
|
|
1316
|
+
this.markHumanActivity(viewId, 'closetab');
|
|
1317
|
+
await t.page.close().catch(() => {});
|
|
1318
|
+
b.tabs.delete(tabId);
|
|
1319
|
+
this.emitChange(b.id);
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
async shutdown(): Promise<void> {
|
|
1323
|
+
await Promise.all([...this.browsers.values()].map((b) => this.stopBrowser(b)));
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
let service: BrowserService | null = null;
|
|
1328
|
+
|
|
1329
|
+
export function configureBrowserService(cfg: BrowserConfig, deps: ServiceDeps = {}): BrowserService {
|
|
1330
|
+
service = new BrowserService(cfg, deps);
|
|
1331
|
+
return service;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
export function getBrowserService(): BrowserService {
|
|
1335
|
+
if (!service) throw new BrowserOpError('BROWSER_DISABLED', 'browser service is not configured in this process');
|
|
1336
|
+
return service;
|
|
1337
|
+
}
|