@michael-joseph-miller/ant-bot 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +42 -5
  2. package/README.md +69 -24
  3. package/dist/{browser-OHRD7YI3.js → browser-4ZHHBD6J.js} +132 -4
  4. package/dist/browser-4ZHHBD6J.js.map +7 -0
  5. package/dist/{bundled-46DUK5PG.js → bundled-26SJR7EB.js} +5 -5
  6. package/dist/{bundled-46DUK5PG.js.map → bundled-26SJR7EB.js.map} +1 -1
  7. package/dist/{chunk-DYIJTUMY.js → chunk-AON76FHD.js} +113 -83
  8. package/dist/chunk-AON76FHD.js.map +7 -0
  9. package/dist/{chunk-AHAON6J7.js → chunk-CNCHYZVD.js} +2 -2
  10. package/dist/{chunk-AHAON6J7.js.map → chunk-CNCHYZVD.js.map} +1 -1
  11. package/dist/{chunk-Z2YT2PZN.js → chunk-GYWJUW4E.js} +6 -6
  12. package/dist/{chunk-Z2YT2PZN.js.map → chunk-GYWJUW4E.js.map} +3 -3
  13. package/dist/{chunk-7BOHBPB2.js → chunk-JCZBDGBA.js} +3 -3
  14. package/dist/{chunk-7BOHBPB2.js.map → chunk-JCZBDGBA.js.map} +1 -1
  15. package/dist/{chunk-KSQOVWP5.js → chunk-MSSHR6SW.js} +6 -6
  16. package/dist/chunk-MSSHR6SW.js.map +7 -0
  17. package/dist/index.js +28 -28
  18. package/dist/index.js.map +2 -2
  19. package/dist/{install-IY2M3OUQ.js → install-KTEW2CW3.js} +3 -3
  20. package/dist/{plugin-POMHVGD4.js → plugin-WYUCG6F7.js} +2 -2
  21. package/dist/{plugin-POMHVGD4.js.map → plugin-WYUCG6F7.js.map} +1 -1
  22. package/dist/{scheduler-Q7OHNGP6.js → scheduler-VZVHQWGD.js} +3 -3
  23. package/dist/scheduler-VZVHQWGD.js.map +7 -0
  24. package/dist/server.js +58 -41
  25. package/dist/server.js.map +3 -3
  26. package/dist/{skills-66WRX64H.js → skills-JUHWFBD6.js} +2 -2
  27. package/dist/skills-spec.js +2 -2
  28. package/dist/skills-spec.js.map +1 -1
  29. package/dist/{tools-P5537ASX.js → tools-YNE7ZRPR.js} +2 -2
  30. package/dist/{tools-P5537ASX.js.map → tools-YNE7ZRPR.js.map} +1 -1
  31. package/package.json +1 -1
  32. package/skills/README.md +1 -1
  33. package/web/dist/assets/index-BBZbK10k.js +130 -0
  34. package/web/dist/assets/index-BKrFsCQD.css +2 -0
  35. package/web/dist/index.html +2 -2
  36. package/dist/browser-OHRD7YI3.js.map +0 -7
  37. package/dist/chunk-DYIJTUMY.js.map +0 -7
  38. package/dist/chunk-KSQOVWP5.js.map +0 -7
  39. package/dist/scheduler-Q7OHNGP6.js.map +0 -7
  40. package/web/dist/assets/index-BLQ8rPiN.js +0 -130
  41. package/web/dist/assets/index-IEIkG_jd.css +0 -2
  42. /package/dist/{install-IY2M3OUQ.js.map → install-KTEW2CW3.js.map} +0 -0
  43. /package/dist/{skills-66WRX64H.js.map → skills-JUHWFBD6.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -4,7 +4,46 @@ All notable changes to ant-bot are recorded here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
5
  [semantic versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [Unreleased]
7
+ ## [0.1.2] — 2026-08-23
8
+
9
+ ### Added
10
+
11
+ - **Browser takeover forwards mouse and keyboard.** The screencast websocket is now
12
+ bidirectional: clicks, typing, scrolling and paste are dispatched into the page while a screen
13
+ is taken over, so a human can finish a login or 2FA prompt and hand control back. Gated on
14
+ takeover with a hard refusal — input is never queued, so a late click cannot land after control
15
+ was returned. Closes the takeover gap in USER-GUIDE §22.
16
+
17
+ ### Fixed
18
+
19
+ - **The screencast no longer sits blank on a static page.** Chromium emits frames only on
20
+ repaint, so a page that was not moving — a login form waiting for input, the exact case
21
+ takeover exists for — delivered nothing at all. One screenshot is now seeded on connect.
22
+ - **Taking over says what it did.** The daemon has always returned an explanation ("this computer
23
+ is running headless, there is no window to bring to the front…"); the UI discarded it, so the
24
+ button flipped to "Return control" and nothing told you what had changed.
25
+
26
+ ## [0.1.1] — 2026-08-23
27
+
28
+ ### Changed
29
+
30
+ - **Repo layout flattened.** The four workspace packages moved out of `packages/` to the repo
31
+ root as `contract/`, `daemon/`, `ui/` and `cli/`, and their npm names follow
32
+ (`@antbot/shared` → `@antbot/contract`, `@antbot/server` → `@antbot/daemon`,
33
+ `@antbot/web` → `@antbot/ui`). Each now has a README saying what it is and why it exists.
34
+ No behaviour change; the published package is unaffected.
35
+ - **README leads with where your data lives** — a map of `~/.ant-bot`, what each directory holds,
36
+ and why `workspace/` is the security boundary rather than just a folder.
37
+
38
+ ### Added
39
+
40
+ - **`fable` and `haiku` model tiers for Bots.** `haiku` was already valid in the schema but no
41
+ picker offered it; `fable` is new. Both pickers now render the shared `MODEL_TIERS` list, so the
42
+ UI cannot offer a tier the API rejects, or hide one it accepts.
43
+
44
+ ## [0.1.0] — 2026-08-23
45
+
46
+ First published release: `npm i -g @michael-joseph-miller/ant-bot`.
8
47
 
9
48
  ### Added
10
49
 
@@ -34,7 +73,5 @@ All notable changes to ant-bot are recorded here. The format follows
34
73
  - Published as **`@michael-joseph-miller/ant-bot`**, not `ant-bot`. npm's name-similarity guard
35
74
  refuses the unscoped name as too close to `antbot`, a security holding package from 2022 that
36
75
  cannot be claimed. Scoped names are exempt from that check. The binary is still `antbot`.
37
-
38
- ## [0.1.0]
39
-
40
- Initial version: the ant-bot daemon, web UI and CLI.
76
+ - The release procedure, the provenance requirements and the packaging traps now live in
77
+ `CLAUDE.md` under "Releasing"; `docs/PACKAGING-PLAN.md` has served its purpose and is deleted.
package/README.md CHANGED
@@ -107,11 +107,41 @@ ln -s "$PWD/antbot" ~/.local/bin/antbot # or /usr/local/bin, or anywhere on yo
107
107
  The launcher resolves symlinks, so it still finds the repo and rebuilds when sources change.
108
108
  From the repo root you can also skip the `./` with `pnpm antbot status`.
109
109
 
110
- ### Data directory
110
+ ### Where your data lives
111
111
 
112
- Data lives under `~/.ant-bot` by default (database, workspace, skills, attachments, browser
113
- profile, logs, backups). Set **`ANTBOT_HOME`** to point the daemon and CLI at a different data
114
- directory, e.g. for a second profile or a test instance:
112
+ Everything ant-bot creates lives in one directory you own, in plain files you can read. Nothing
113
+ is hidden in a service, and nothing leaves the machine. Go and look:
114
+
115
+ ```
116
+ ~/.ant-bot/
117
+ ├── antbot.db SQLite: bots, threads, messages, approvals, rules, routines, usage
118
+ ├── config.toml port and host (re-read each boot) + first-run setting defaults
119
+ ├── workspace/ ← the Bots' computer. This is the security boundary.
120
+ │ ├── bots/<slug>/ each Bot's own folder: its files, and memory/*.md
121
+ │ └── projects/ shared project files — durable work lives here
122
+ ├── skills/ installed skills, as a local Claude plugin
123
+ │ └── skills/<slug>/SKILL.md
124
+ ├── attachments/ files you upload into threads
125
+ ├── browser-profile/ the shared Chromium profile: cookies, logins, sessions
126
+ ├── backups/ `antbot backup` archives, and pre-migration DB snapshots
127
+ └── logs/ daemon logs
128
+ ```
129
+
130
+ **`workspace/` is the important one.** It is the Bots' computer, and everything outside it is
131
+ *your* machine. A tool call that reaches outside the workspace is denied, or forced to a human
132
+ prompt, depending on your `localExecution` setting — and that check runs *before* any "allow" rule
133
+ you have written, so a broad rule cannot be used to reach `~/.ssh`. Work inside the workspace runs
134
+ without a prompt; work outside it does not. See [`docs/SECURITY.md`](docs/SECURITY.md).
135
+
136
+ **`workspace/bots/<slug>/memory/*.md`** is worth knowing about: those markdown files are read back
137
+ into that Bot's system prompt every turn. Editing one edits what the Bot remembers. Deleting one
138
+ makes it forget.
139
+
140
+ A Bot's folder outlives the Bot — deleting a Bot removes its threads and routines but leaves its
141
+ files, since the workspace is shared and other Bots may depend on them.
142
+
143
+ Set **`ANTBOT_HOME`** to point the daemon and CLI at a different data directory, e.g. for a second
144
+ profile or a test instance:
115
145
 
116
146
  ```bash
117
147
  ANTBOT_HOME=/path/to/alt-home ./antbot start --port 4791
@@ -168,7 +198,7 @@ ANTBOT_HOME=/path/to/alt-home ./antbot start --port 4791
168
198
  │ └──────┬──────────────────────────────────────────┘ │
169
199
  │ │ │
170
200
  │ ┌──────────────────────▼───────────────┐ ┌──────────────────────────────────────────────┐ │
171
- │ │ Computer service (packages/server/ │ │ Storage: SQLite (better-sqlite3, WAL) — │ │
201
+ │ │ Computer service (daemon/ │ │ Storage: SQLite (better-sqlite3, WAL) — │ │
172
202
  │ │ src/computer): Playwright persistent │ │ bots, threads, messages, approvals, rules, │ │
173
203
  │ │ profile, per-bot screen lock, │ │ skills, routines, mailbox, usage, settings + │ │
174
204
  │ │ screencast, takeover │ │ ~/.ant-bot/workspace + attachments on disk │ │
@@ -184,7 +214,7 @@ Permission Gateway before the tool is allowed to run — this is true for the bu
184
214
 
185
215
  ## CLI commands
186
216
 
187
- All commands are implemented in `packages/cli`. Run them as `./antbot <command>` from the repo
217
+ All commands are implemented in `cli`. Run them as `./antbot <command>` from the repo
188
218
  root, or as plain `antbot <command>` once it is [on your `PATH`](#putting-antbot-on-your-path).
189
219
 
190
220
  | Command | Description |
@@ -204,24 +234,40 @@ Every command takes `--help`, e.g. `antbot start --help`.
204
234
 
205
235
  ## Project layout
206
236
 
237
+ Four workspace packages at the repo root, each with its own README explaining what it is and why
238
+ it exists. The dependency direction only ever points one way:
239
+
240
+ ```
241
+ contract ← daemon ← cli
242
+
243
+ └──── ui
244
+ ```
245
+
207
246
  | Path | What it is |
208
247
  |---|---|
209
- | `packages/shared` | Zod schemas + TypeScript types for every entity and API request/response, `LIMITS` constants, the WS event union imported by both server and web |
210
- | `packages/server` | The daemon: Fastify API + WS (`src/api`), Bot lifecycle and queue (`src/bots`), Agent SDK wrapper (`src/agent`), Permission Gateway + rules + secrets (`src/permissions`), scheduler/cron (`src/scheduler`), skills store (`src/skills`), browser/computer service (`src/computer`), SQLite layer (`src/db`), config + paths (`src/config`) |
211
- | `packages/web` | React 19 + Vite UI: sidebar, thread view, approval cards, rules/settings/routines/usage screens, workspace browser, command palette |
212
- | `packages/cli` | The `antbot` CLI: start/stop/restart/status/doctor/open/skill/backup/restore |
213
- | `skills/` | The skills that ship with ant-bot — `bug-repro`, `deep-research`, `inbox-digest`, `skill-author`, `weekly-report` — plus `SPEC.md`, the Agent Skills spec they all conform to. Installed into `~/.ant-bot/skills` on every start and refreshed on upgrade unless you have edited or deleted your copy |
214
- | `computer/` | Placeholder for an optional containerized "computer" image **not implemented** (see Status below) |
215
- | `docs/` | This plan, the design-doctrine outline it's translated from, and the frozen API contract |
248
+ | [`contract/`](contract/) | **The shared vocabulary.** Zod schemas and types for every entity, request, response and websocket event, plus `LIMITS`. Both the daemon and the UI import from here; it imports from nothing. One declaration per shape, so the two sides cannot drift. |
249
+ | [`daemon/`](daemon/) | **The thing that runs.** Fastify API + websocket, Bot turn queue, the Agent SDK wrapper, the Permission Gateway, the scheduler, the skills store, the browser service, and SQLite. Start reading at `src/app.ts`. |
250
+ | [`ui/`](ui/) | **The web interface.** React 19 + Vite + Tailwind v4. Built to `ui/dist/` and served by the daemon itself — there is no separate frontend server. |
251
+ | [`cli/`](cli/) | **The `antbot` command.** start/stop/status/doctor/open/skill/backup/restore/update. Kept separate from the daemon so `antbot doctor` still works when the daemon does not. |
252
+ | [`skills/`](skills/) | The skills that ship with ant-bot, plus [`SPEC.md`](skills/SPEC.md), the Agent Skills spec they conform to. Synced into `~/.ant-bot/skills` on every start, and never overwritten if you have edited your copy. |
253
+ | [`docs/`](docs/) | [`USER-GUIDE.md`](docs/USER-GUIDE.md) (the manual), [`SECURITY.md`](docs/SECURITY.md) (the trust model), [`API-CONTRACT.md`](docs/API-CONTRACT.md) (frozen HTTP/WS contract), [`SKILLS.md`](docs/SKILLS.md). Plus two historical design records that are deliberately not kept in sync with the code. |
254
+ | [`scripts/`](scripts/) | `build-package.mjs`, which assembles the publishable npm package into `dist-npm/`. |
255
+ | [`CLAUDE.md`](CLAUDE.md) | Guidance for agents — and the densest description of the invariants and traps in this codebase. Worth reading even if you are human. |
256
+
257
+ ### Where to start reading
258
+
259
+ 1. **Using it?** [`docs/USER-GUIDE.md`](docs/USER-GUIDE.md).
260
+ 2. **Evaluating whether to trust it?** [`docs/SECURITY.md`](docs/SECURITY.md), then "Where your data lives" above.
261
+ 3. **Changing it?** [`CLAUDE.md`](CLAUDE.md), then `daemon/src/app.ts` — the composition root, which builds every subsystem in order.
216
262
 
217
263
  ## Testing
218
264
 
219
265
  Each package uses Vitest. Run all of them from the repo root with `pnpm test`, or per package:
220
266
 
221
267
  ```bash
222
- pnpm --filter @antbot/shared test
223
- pnpm --filter @antbot/server test
224
- pnpm --filter @antbot/web test
268
+ pnpm --filter @antbot/contract test
269
+ pnpm --filter @antbot/daemon test
270
+ pnpm --filter @antbot/ui test
225
271
  pnpm --filter @antbot/cli test
226
272
  ```
227
273
 
@@ -229,20 +275,19 @@ Current totals, as run against this checkout:
229
275
 
230
276
  | Package | Test files | Tests |
231
277
  |---|---|---|
232
- | `@antbot/shared` | 1 | 19 |
233
- | `@antbot/server` | 19 | 450 |
234
- | `@antbot/web` | 7 | 49 |
235
- | `@antbot/cli` | 7 | 114 |
236
- | **Total** | **34** | **632** |
278
+ | `@antbot/contract` | 1 | 22 |
279
+ | `@antbot/daemon` | 20 | 468 |
280
+ | `@antbot/ui` | 7 | 52 |
281
+ | `@antbot/cli` | 7 | 116 |
282
+ | **Total** | **35** | **658** |
237
283
 
238
284
  ## Status / not built
239
285
 
240
286
  Honestly, as of this checkout:
241
287
 
242
288
  - **Container computer mode** — `computer.mode` is a valid `"host" | "container"` setting in the
243
- schema and shows up in Settings, but only `host` mode has an implementation; the `computer/`
244
- directory in the repo is an empty placeholder. There is no container image, and selecting
245
- `container` does not change daemon behavior.
289
+ schema and shows up in Settings, but only `host` mode has an implementation. There is no
290
+ container image, and selecting `container` does not change daemon behavior.
246
291
  - **Teach-by-demonstration** — not implemented. There is no trace recording, no draft-skill-from-
247
292
  recording flow, and no "Teach a task" UI affordance anywhere in the codebase.
248
293
  - **Event-trigger webhooks** — not implemented. Routines only fire on a cron schedule
@@ -2,13 +2,37 @@ import { createRequire as __antbotCreateRequire } from 'node:module';
2
2
  const require = __antbotCreateRequire(import.meta.url);
3
3
  import {
4
4
  logger
5
- } from "./chunk-AHAON6J7.js";
5
+ } from "./chunk-CNCHYZVD.js";
6
6
 
7
- // packages/server/src/computer/browser.ts
7
+ // daemon/src/computer/browser.ts
8
8
  import fs from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
  import { chromium } from "playwright";
12
+
13
+ // daemon/src/computer/input.ts
14
+ function toPageCoords(norm, frame) {
15
+ if (!frame) return null;
16
+ if (!Number.isFinite(frame.width) || !Number.isFinite(frame.height)) return null;
17
+ if (frame.width <= 0 || frame.height <= 0) return null;
18
+ if (!Number.isFinite(norm.x) || !Number.isFinite(norm.y)) return null;
19
+ const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
20
+ return {
21
+ x: Math.min(Math.round(clamp01(norm.x) * frame.width), frame.width - 1),
22
+ y: Math.min(Math.round(clamp01(norm.y) * frame.height), frame.height - 1)
23
+ };
24
+ }
25
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set(["F5", "F11", "F12", "BrowserRefresh", "BrowserBack", "BrowserForward"]);
26
+ function isForwardableKey(key) {
27
+ return key.length > 0 && !BLOCKED_KEYS.has(key);
28
+ }
29
+ function clampWheel(delta) {
30
+ if (!Number.isFinite(delta)) return 0;
31
+ const MAX = 1e3;
32
+ return Math.max(-MAX, Math.min(MAX, Math.round(delta)));
33
+ }
34
+
35
+ // daemon/src/computer/browser.ts
12
36
  var log = logger("browser");
13
37
  var BrowserUnavailableError = class extends Error {
14
38
  constructor(reason) {
@@ -32,6 +56,12 @@ var InvalidUrlError = class extends Error {
32
56
  this.name = "InvalidUrlError";
33
57
  }
34
58
  };
59
+ var ScreenNotTakenOverError = class extends Error {
60
+ constructor(message = "This screen is not taken over.") {
61
+ super(message);
62
+ this.name = "ScreenNotTakenOverError";
63
+ }
64
+ };
35
65
  var ScreenTakenOverError = class extends Error {
36
66
  constructor() {
37
67
  super("The human has taken control of this screen; wait until they return it.");
@@ -121,6 +151,14 @@ var BrowserService = class {
121
151
  screencastListeners = /* @__PURE__ */ new Map();
122
152
  screencastThrottles = /* @__PURE__ */ new Map();
123
153
  viewerCounts = /* @__PURE__ */ new Map();
154
+ /**
155
+ * Last known viewport, per bot. Seeded from the page and refreshed by screencast frames.
156
+ * Input coordinates scale against this, NOT against frame arrival: Chromium only emits
157
+ * screencast frames on visual change, so a static page delivers none at all and a
158
+ * frame-dependent geometry would drop every click on exactly the pages a human is most
159
+ * likely to be rescuing (a login form sitting still, waiting for input).
160
+ */
161
+ lastFrameSize = /* @__PURE__ */ new Map();
124
162
  get isHeadless() {
125
163
  return this.headlessMode;
126
164
  }
@@ -401,9 +439,10 @@ ${this.orientLine(o)}`;
401
439
  session.on("Page.screencastFrame", (evt) => {
402
440
  void session.send("Page.screencastFrameAck", { sessionId: evt.sessionId }).catch(() => {
403
441
  });
404
- if (!throttle.shouldEmit()) return;
405
442
  const w = evt.metadata?.deviceWidth ?? 0;
406
443
  const h = evt.metadata?.deviceHeight ?? 0;
444
+ if (w > 0 && h > 0) this.lastFrameSize.set(botId, { width: w, height: h });
445
+ if (!throttle.shouldEmit()) return;
407
446
  for (const l of listeners) {
408
447
  try {
409
448
  l(evt.data, w, h);
@@ -413,6 +452,7 @@ ${this.orientLine(o)}`;
413
452
  }
414
453
  });
415
454
  await session.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1280, everyNthFrame: 2 });
455
+ void this.seedFirstFrame(botId, page).catch((err) => log.warn("screencast seed frame failed", err));
416
456
  }
417
457
  let stopped = false;
418
458
  return () => {
@@ -426,6 +466,7 @@ ${this.orientLine(o)}`;
426
466
  this.screencastSessions.delete(botId);
427
467
  this.screencastThrottles.delete(botId);
428
468
  this.screencastListeners.delete(botId);
469
+ this.lastFrameSize.delete(botId);
429
470
  if (session) {
430
471
  void session.send("Page.stopScreencast").catch(() => {
431
472
  }).then(() => session.detach().catch(() => {
@@ -470,6 +511,92 @@ ${this.orientLine(o)}`;
470
511
  returnControl(botId) {
471
512
  this.takenOver.delete(botId);
472
513
  }
514
+ /** One immediate JPEG so a static page is not a blank pane. See startScreencast. */
515
+ async seedFirstFrame(botId, page) {
516
+ const listeners = this.screencastListeners.get(botId);
517
+ if (!listeners?.size) return;
518
+ const buf = await page.screenshot({ type: "jpeg", quality: 60 });
519
+ const vp = page.viewportSize() ?? { width: 0, height: 0 };
520
+ if (vp.width > 0 && vp.height > 0) this.lastFrameSize.set(botId, vp);
521
+ for (const l of listeners) {
522
+ try {
523
+ l(buf.toString("base64"), vp.width, vp.height);
524
+ } catch (err) {
525
+ log.warn("screencast seed listener threw", err);
526
+ }
527
+ }
528
+ }
529
+ /**
530
+ * The page's CSS viewport, which is what input coordinates are in.
531
+ *
532
+ * `viewportSize()` is synchronous and correct whenever the context sets one; a persistent
533
+ * context launched without an explicit viewport returns null, so fall back to asking the page.
534
+ * The cached value is only a last resort for a page that has since closed.
535
+ */
536
+ async viewportOf(botId, page) {
537
+ const vp = page.viewportSize();
538
+ if (vp && vp.width > 0 && vp.height > 0) {
539
+ this.lastFrameSize.set(botId, { width: vp.width, height: vp.height });
540
+ return vp;
541
+ }
542
+ try {
543
+ const inner = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
544
+ if (inner.width > 0 && inner.height > 0) {
545
+ this.lastFrameSize.set(botId, inner);
546
+ return inner;
547
+ }
548
+ } catch {
549
+ }
550
+ return this.lastFrameSize.get(botId);
551
+ }
552
+ /**
553
+ * Dispatches human input into a taken-over page.
554
+ *
555
+ * The takeover check is the whole security model here, and it is deliberately a hard refusal
556
+ * rather than a queue: input is only ever legitimate while the bot is blocked, and silently
557
+ * buffering it would let a stale click land after control was returned — into a page the bot
558
+ * has since navigated. Input does not pass the Permission Gateway, because the gateway governs
559
+ * what *bots* do; this is the human acting as themselves on their own computer.
560
+ *
561
+ * Dispatch goes through Playwright's `page.mouse` / `page.keyboard` rather than raw CDP so the
562
+ * key-code mapping is the SDK's problem, matching how `click()` and `type()` above work.
563
+ */
564
+ async forwardInput(botId, ev) {
565
+ if (!this.takenOver.has(botId)) {
566
+ throw new ScreenNotTakenOverError(
567
+ "Input was sent for a screen that is not taken over. Take over the screen first."
568
+ );
569
+ }
570
+ const page = await this.getPage(botId);
571
+ if (ev.kind === "text") {
572
+ await page.keyboard.insertText(ev.text);
573
+ return;
574
+ }
575
+ if (ev.kind === "key") {
576
+ if (!isForwardableKey(ev.key)) return;
577
+ if (ev.action === "down") await page.keyboard.down(ev.key);
578
+ else await page.keyboard.up(ev.key);
579
+ return;
580
+ }
581
+ const pt = toPageCoords({ x: ev.x, y: ev.y }, await this.viewportOf(botId, page));
582
+ if (!pt) return;
583
+ switch (ev.action) {
584
+ case "move":
585
+ await page.mouse.move(pt.x, pt.y);
586
+ break;
587
+ case "down":
588
+ await page.mouse.move(pt.x, pt.y);
589
+ await page.mouse.down({ button: ev.button, clickCount: Math.max(1, ev.clickCount) });
590
+ break;
591
+ case "up":
592
+ await page.mouse.up({ button: ev.button, clickCount: Math.max(1, ev.clickCount) });
593
+ break;
594
+ case "wheel":
595
+ await page.mouse.move(pt.x, pt.y);
596
+ await page.mouse.wheel(clampWheel(ev.deltaX), clampWheel(ev.deltaY));
597
+ break;
598
+ }
599
+ }
473
600
  /* ---------------------------------------------------------------------------------------- */
474
601
  /** Never launches the browser. Reports optimistically until a launch attempt has failed. */
475
602
  status() {
@@ -517,8 +644,9 @@ export {
517
644
  InvalidUrlError,
518
645
  ScreenBusyError,
519
646
  ScreenLock,
647
+ ScreenNotTakenOverError,
520
648
  ScreenTakenOverError,
521
649
  detectBlockFromSignals,
522
650
  normalizeUrl
523
651
  };
524
- //# sourceMappingURL=browser-OHRD7YI3.js.map
652
+ //# sourceMappingURL=browser-4ZHHBD6J.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../daemon/src/computer/browser.ts", "../../daemon/src/computer/input.ts"],
4
+ "sourcesContent": ["import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { chromium } from 'playwright';\nimport type { BrowserContext, CDPSession, Page } from 'playwright';\nimport type { EventBus } from '../util/bus.js';\nimport { toPageCoords, isForwardableKey, clampWheel, type FrameSize } from './input.js';\nimport type { ScreencastInput } from '@antbot/contract';\nimport { logger } from '../util/log.js';\n\nconst log = logger('browser');\n\n/* ------------------------------------------------------------------------------------------- *\n * Errors\n * ------------------------------------------------------------------------------------------- */\n\n/** Thrown when the browser cannot be launched (e.g. Chromium isn't installed). */\nexport class BrowserUnavailableError extends Error {\n constructor(public readonly reason: string) {\n super(`Browser is unavailable: ${reason}. Try: npx playwright install chromium`);\n this.name = 'BrowserUnavailableError';\n }\n}\n\n/** Thrown by ScreenLock when a bot's screen already has a computer-use task in flight. */\nexport class ScreenBusyError extends Error {\n constructor(public readonly botId: string) {\n super(`That bot's screen is already busy with another computer-use task. Wait for it to finish before starting another.`);\n this.name = 'ScreenBusyError';\n }\n}\n\n/** Thrown by normalizeUrl for disallowed / malformed URLs. */\nexport class InvalidUrlError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidUrlError';\n }\n}\n\n/** Thrown when an action targets a bot screen the human currently has taken over. */\nexport class ScreenNotTakenOverError extends Error {\n constructor(message = 'This screen is not taken over.') {\n super(message);\n this.name = 'ScreenNotTakenOverError';\n }\n}\n\nexport class ScreenTakenOverError extends Error {\n constructor() {\n super('The human has taken control of this screen; wait until they return it.');\n this.name = 'ScreenTakenOverError';\n }\n}\n\n/* ------------------------------------------------------------------------------------------- *\n * Pure helpers (no browser required) \u2014 exported for unit testing.\n * ------------------------------------------------------------------------------------------- */\n\n/**\n * Adds `https://` to bare domains/paths, rejects `javascript:` and `file:` URLs outright, and\n * otherwise passes the input through unchanged. Deliberately permissive about other schemes\n * (e.g. `data:`, `about:`) \u2014 computer-use tasks legitimately need to load those in tests and\n * sandboxes; the block list is specifically the two schemes that are dangerous or meaningless\n * for a screen-driving agent.\n */\nexport function normalizeUrl(input: string): string {\n const trimmed = (input ?? '').trim();\n if (!trimmed) throw new InvalidUrlError('URL is empty.');\n const schemeMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);\n if (!schemeMatch) return `https://${trimmed}`;\n const scheme = schemeMatch[1]!.toLowerCase();\n if (scheme === 'javascript') throw new InvalidUrlError('javascript: URLs are not allowed.');\n if (scheme === 'file') throw new InvalidUrlError('file: URLs are not allowed.');\n return trimmed;\n}\n\nexport interface BlockSignals {\n hasPasswordInput: boolean;\n iframeSrcs: string[];\n bodyText: string;\n}\n\nexport interface BlockDetection {\n kind: 'login' | 'captcha' | '2fa';\n message: string;\n}\n\n/**\n * Heuristic login-wall / CAPTCHA / 2FA detector over already-extracted page signals. Kept pure\n * (no Page dependency) so it can run without a browser in unit tests; `BrowserService.detectBlock`\n * gathers the signals from a live Page and delegates here.\n */\nexport function detectBlockFromSignals(signals: BlockSignals): BlockDetection | null {\n const iframeBlob = (signals.iframeSrcs ?? []).join(' ').toLowerCase();\n const body = signals.bodyText ?? '';\n\n if (/recaptcha/i.test(iframeBlob) || /hcaptcha/i.test(iframeBlob)) {\n return { kind: 'captcha', message: 'A CAPTCHA challenge (reCAPTCHA/hCaptcha) is present on this page.' };\n }\n if (/challenges\\.cloudflare\\.com|cf-challenge|turnstile/i.test(iframeBlob) || /checking your browser|cloudflare/i.test(body)) {\n return { kind: 'captcha', message: 'A Cloudflare browser challenge is present on this page.' };\n }\n if (/verify (your \\w+|it'?s you)|two-factor|one-time code/i.test(body)) {\n return { kind: '2fa', message: \"This page is asking for two-factor / one-time-code verification.\" };\n }\n if (signals.hasPasswordInput) {\n return { kind: 'login', message: 'This page has a password field \u2014 it looks like a login wall.' };\n }\n return null;\n}\n\n/**\n * Per-key mutex: `run` executes `fn` immediately if the key is free, otherwise rejects with\n * `ScreenBusyError` rather than queueing \u2014 mirrors \"one computer-use task per Bot screen at a\n * time\" (outline \u00A713): a second concurrent call is a caller bug, not something to serialize.\n */\nexport class ScreenLock {\n private busy = new Set<string>();\n\n isBusy(key: string): boolean {\n return this.busy.has(key);\n }\n\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n if (this.busy.has(key)) throw new ScreenBusyError(key);\n this.busy.add(key);\n try {\n return await fn();\n } finally {\n this.busy.delete(key);\n }\n }\n}\n\n/**\n * Frame-rate limiter for the screencast. `shouldEmit()` returns true at most once per\n * `1000/fps` ms according to the injected clock (defaults to `Date.now`), so tests can drive it\n * deterministically without real timers.\n */\nexport class FrameThrottle {\n private lastEmit = -Infinity;\n\n constructor(\n private readonly fps: number,\n private readonly clock: () => number = () => Date.now(),\n ) {}\n\n get intervalMs(): number {\n return 1000 / this.fps;\n }\n\n shouldEmit(): boolean {\n const now = this.clock();\n if (now - this.lastEmit >= this.intervalMs) {\n this.lastEmit = now;\n return true;\n }\n return false;\n }\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/* ------------------------------------------------------------------------------------------- *\n * BrowserService\n * ------------------------------------------------------------------------------------------- */\n\nexport interface BrowserServiceDeps {\n profileDir: string;\n bus: EventBus;\n headless?: boolean;\n}\n\nexport interface ComputerPageStatus {\n botId: string;\n url: string;\n title: string;\n}\n\nexport interface BrowserStatus {\n available: boolean;\n reason?: string;\n mode: 'host';\n headless: boolean;\n pages: ComputerPageStatus[];\n}\n\nexport interface TakeOverResult {\n ok: boolean;\n mode: 'screencast-only' | 'window';\n message: string;\n}\n\ntype FrameListener = (jpegBase64: string, w: number, h: number) => void;\n\n/**\n * One Playwright persistent browser context shared by every Bot (\"the computer\"), with a\n * dedicated Page (\"screen\") per botId. Because all pages share one persistent context, cookies\n * and logins are shared across bots by design (outline \u00A75: \"one computer, shared by all your\n * Bots\") \u2014 this is intentional, not a bug.\n */\nexport class BrowserService {\n private context: BrowserContext | null = null;\n private launchPromise: Promise<BrowserContext> | null = null;\n private unavailableReason: string | undefined;\n\n private readonly headlessMode: boolean;\n private readonly pages = new Map<string, Page>();\n private readonly titleCache = new Map<string, string>();\n private readonly takenOver = new Set<string>();\n private readonly lock = new ScreenLock();\n\n private readonly screencastSessions = new Map<string, CDPSession>();\n private readonly screencastListeners = new Map<string, Set<FrameListener>>();\n private readonly screencastThrottles = new Map<string, FrameThrottle>();\n private readonly viewerCounts = new Map<string, number>();\n /**\n * Last known viewport, per bot. Seeded from the page and refreshed by screencast frames.\n * Input coordinates scale against this, NOT against frame arrival: Chromium only emits\n * screencast frames on visual change, so a static page delivers none at all and a\n * frame-dependent geometry would drop every click on exactly the pages a human is most\n * likely to be rescuing (a login form sitting still, waiting for input).\n */\n private readonly lastFrameSize = new Map<string, FrameSize>();\n\n constructor(private readonly deps: BrowserServiceDeps) {\n this.headlessMode = deps.headless ?? true;\n }\n\n get isHeadless(): boolean {\n return this.headlessMode;\n }\n\n /** Lazily launches the shared persistent context. Concurrent callers share one launch. */\n private async ensureContext(): Promise<BrowserContext> {\n if (this.context) return this.context;\n if (this.launchPromise) return this.launchPromise;\n\n this.launchPromise = (async () => {\n try {\n fs.mkdirSync(this.deps.profileDir, { recursive: true });\n const ctx = await chromium.launchPersistentContext(this.deps.profileDir, {\n headless: this.headlessMode,\n viewport: { width: 1280, height: 800 },\n });\n this.context = ctx;\n ctx.on('close', () => {\n this.context = null;\n this.launchPromise = null;\n this.pages.clear();\n });\n return ctx;\n } catch (err) {\n this.unavailableReason = errMsg(err);\n this.launchPromise = null;\n throw new BrowserUnavailableError(this.unavailableReason);\n }\n })();\n return this.launchPromise;\n }\n\n /** Returns this bot's dedicated page, creating it lazily. Pages persist across turns. */\n async getPage(botId: string): Promise<Page> {\n const existing = this.pages.get(botId);\n if (existing && !existing.isClosed()) return existing;\n const ctx = await this.ensureContext();\n const page = await ctx.newPage();\n this.pages.set(botId, page);\n page.on('close', () => {\n if (this.pages.get(botId) === page) this.pages.delete(botId);\n });\n return page;\n }\n\n async closePage(botId: string): Promise<void> {\n const page = this.pages.get(botId);\n if (page) {\n await page.close().catch(() => {});\n this.pages.delete(botId);\n }\n this.titleCache.delete(botId);\n this.takenOver.delete(botId);\n }\n\n /** Serializes computer-use tasks per bot screen; a concurrent second call is rejected. */\n async withScreen<T>(botId: string, fn: (page: Page) => Promise<T>): Promise<T> {\n return this.lock.run(botId, async () => {\n if (this.takenOver.has(botId)) throw new ScreenTakenOverError();\n const page = await this.getPage(botId);\n return fn(page);\n });\n }\n\n private async orient(botId: string, page: Page): Promise<{ url: string; title: string }> {\n const url = page.url();\n let title = this.titleCache.get(botId) ?? '';\n try {\n title = await page.title();\n this.titleCache.set(botId, title);\n } catch {\n // page may be mid-navigation or closed; fall back to the cached title.\n }\n return { url, title };\n }\n\n private orientLine(o: { url: string; title: string }): string {\n return `URL: ${o.url}\\nTitle: ${o.title}`;\n }\n\n /** Gathers page signals and runs them through the pure detector. Never throws. */\n async detectBlock(page: Page): Promise<BlockDetection | null> {\n try {\n const hasPasswordInput = (await page.$$('input[type=\"password\"]').catch(() => [])).length > 0;\n const iframeSrcs = await page\n .$$eval('iframe', (els) => els.map((e) => e.getAttribute('src') ?? ''))\n .catch(() => [] as string[]);\n const bodyText = await page\n .evaluate(() => document.body?.innerText ?? '')\n .catch(() => '');\n return detectBlockFromSignals({ hasPasswordInput, iframeSrcs, bodyText: bodyText.slice(0, 4000) });\n } catch {\n return null;\n }\n }\n\n /** If a block is detected, publishes a warn notification and returns the STOP text to prepend. */\n private async checkBlock(botId: string, page: Page): Promise<string | null> {\n const block = await this.detectBlock(page);\n if (!block) return null;\n this.deps.bus.publish({\n type: 'notify',\n botId,\n threadId: null,\n level: 'warn',\n title: 'Browser needs a human',\n body: block.message,\n });\n return (\n `${block.message} STOP: do not attempt to solve or bypass this yourself \u2014 ` +\n `ask the human to take over the computer and wait for them to return control.`\n );\n }\n\n /* ---------------------------------------------------------------------------------------- *\n * Actions \u2014 each returns a short result string including the resulting URL + title, and is\n * safe to call even if the page has navigated away, closed, or errored mid-action.\n * ---------------------------------------------------------------------------------------- */\n\n async navigate(botId: string, url: string): Promise<string> {\n const target = normalizeUrl(url);\n return this.withScreen(botId, async (page) => {\n try {\n await page.goto(target, { waitUntil: 'domcontentloaded', timeout: 30000 });\n } catch (err) {\n return `Navigation to ${target} failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const block = await this.checkBlock(botId, page);\n const o = await this.orient(botId, page);\n return block ? `${block}\\n${this.orientLine(o)}` : `Navigated.\\n${this.orientLine(o)}`;\n });\n }\n\n async click(botId: string, selector: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n await page.click(selector, { timeout: 10000 });\n } catch (err) {\n return `Click on \"${selector}\" failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const block = await this.checkBlock(botId, page);\n const o = await this.orient(botId, page);\n return block ? `${block}\\n${this.orientLine(o)}` : `Clicked \"${selector}\".\\n${this.orientLine(o)}`;\n });\n }\n\n async type(botId: string, selector: string, text: string, opts?: { submit?: boolean }): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n const isPassword = await page\n .$eval(selector, (el) => (el as HTMLInputElement).type === 'password')\n .catch(() => false);\n if (isPassword) {\n return (\n `Refused: \"${selector}\" looks like a password field. Never type credentials into the browser \u2014 ` +\n `ask the human to take over the computer instead.\\n${this.orientLine(await this.orient(botId, page))}`\n );\n }\n await page.fill(selector, text, { timeout: 10000 });\n if (opts?.submit) await page.press(selector, 'Enter');\n } catch (err) {\n return `Type into \"${selector}\" failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const block = await this.checkBlock(botId, page);\n const o = await this.orient(botId, page);\n return block ? `${block}\\n${this.orientLine(o)}` : `Typed into \"${selector}\".\\n${this.orientLine(o)}`;\n });\n }\n\n async pressKey(botId: string, key: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n await page.keyboard.press(key);\n } catch (err) {\n return `Key press \"${key}\" failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n return `Pressed \"${key}\".\\n${this.orientLine(await this.orient(botId, page))}`;\n });\n }\n\n /** Returns visible text (page body, or a selector's text), capped at ~8000 characters. */\n async readText(botId: string, selector?: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n let text: string;\n try {\n text = selector\n ? ((await page.$eval(selector, (el) => (el as HTMLElement).innerText ?? '')) ?? '')\n : await page.evaluate(() => document.body?.innerText ?? '');\n } catch (err) {\n return `Read${selector ? ` of \"${selector}\"` : ''} failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const capped = text.length > 8000 ? `${text.slice(0, 8000)}\\n\u2026(truncated)` : text;\n return `${this.orientLine(await this.orient(botId, page))}\\n---\\n${capped}`;\n });\n }\n\n async readLinks(botId: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n let links: Array<{ text: string; href: string }>;\n try {\n links = await page.$$eval('a[href]', (els) =>\n els\n .slice(0, 200)\n .map((e) => ({ text: (e as HTMLElement).innerText.trim().slice(0, 120), href: (e as HTMLAnchorElement).href })),\n );\n } catch (err) {\n return `Reading links failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const body = links.map((l) => `- ${l.text || '(no text)'} -> ${l.href}`).join('\\n') || '(no links found)';\n return `${this.orientLine(await this.orient(botId, page))}\\n---\\n${body}`;\n });\n }\n\n /** Saves a PNG screenshot (to `filePath`, or a temp file if omitted) and returns its path. */\n async screenshot(botId: string, filePath?: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n const target = filePath ?? path.join(os.tmpdir(), `antbot-screenshot-${botId}-${Date.now()}.png`);\n try {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n await page.screenshot({ path: target });\n } catch (err) {\n return `Screenshot failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n return `Screenshot saved to ${target}\\n${this.orientLine(await this.orient(botId, page))}`;\n });\n }\n\n async currentUrl(botId: string): Promise<string> {\n return this.withScreen(botId, async (page) => this.orientLine(await this.orient(botId, page)));\n }\n\n async waitFor(botId: string, selector: string, timeoutMs: number): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n await page.waitForSelector(selector, { timeout: timeoutMs });\n } catch (err) {\n return `Waiting for \"${selector}\" timed out: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n return `Found \"${selector}\".\\n${this.orientLine(await this.orient(botId, page))}`;\n });\n }\n\n async scroll(botId: string, dy: number): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n await page.mouse.wheel(0, dy);\n } catch (err) {\n return `Scroll failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n return `Scrolled by ${dy}px.\\n${this.orientLine(await this.orient(botId, page))}`;\n });\n }\n\n async goBack(botId: string): Promise<string> {\n return this.withScreen(botId, async (page) => {\n try {\n await page.goBack({ waitUntil: 'domcontentloaded', timeout: 15000 });\n } catch (err) {\n return `Go back failed: ${errMsg(err)}\\n${this.orientLine(await this.orient(botId, page))}`;\n }\n const block = await this.checkBlock(botId, page);\n const o = await this.orient(botId, page);\n return block ? `${block}\\n${this.orientLine(o)}` : `Went back.\\n${this.orientLine(o)}`;\n });\n }\n\n /* ---------------------------------------------------------------------------------------- *\n * Screencast \u2014 CDP-driven JPEG frames, throttled to ~4fps, reference-counted per bot so it\n * auto-stops once the last viewer detaches.\n * ---------------------------------------------------------------------------------------- */\n\n async startScreencast(botId: string, onFrame: FrameListener): Promise<() => void> {\n const page = await this.getPage(botId);\n\n let listeners = this.screencastListeners.get(botId);\n if (!listeners) {\n listeners = new Set();\n this.screencastListeners.set(botId, listeners);\n }\n listeners.add(onFrame);\n this.viewerCounts.set(botId, (this.viewerCounts.get(botId) ?? 0) + 1);\n\n if (!this.screencastSessions.has(botId)) {\n const ctx = await this.ensureContext();\n const session = await ctx.newCDPSession(page);\n const throttle = new FrameThrottle(4);\n this.screencastSessions.set(botId, session);\n this.screencastThrottles.set(botId, throttle);\n\n session.on('Page.screencastFrame', (evt) => {\n void session.send('Page.screencastFrameAck', { sessionId: evt.sessionId }).catch(() => {});\n const w = evt.metadata?.deviceWidth ?? 0;\n const h = evt.metadata?.deviceHeight ?? 0;\n // Recorded on every frame, before the throttle: input must scale against the page's\n // current geometry, which changes on resize and navigation regardless of what the\n // viewer happens to be shown.\n if (w > 0 && h > 0) this.lastFrameSize.set(botId, { width: w, height: h });\n if (!throttle.shouldEmit()) return;\n for (const l of listeners!) {\n try {\n l(evt.data, w, h);\n } catch (err) {\n log.warn('screencast frame listener threw', err);\n }\n }\n });\n\n await session.send('Page.startScreencast', { format: 'jpeg', quality: 60, maxWidth: 1280, everyNthFrame: 2 });\n\n // Chromium emits screencast frames only when something repaints, so a page sitting still\n // \u2014 a login form, a 2FA prompt, exactly what a human takes over to deal with \u2014 delivers\n // nothing and the viewer stays blank forever. Seed it with one screenshot so there is\n // always something on screen; live frames take over from there.\n void this.seedFirstFrame(botId, page).catch((err) => log.warn('screencast seed frame failed', err));\n }\n\n let stopped = false;\n return () => {\n if (stopped) return;\n stopped = true;\n listeners!.delete(onFrame);\n const remaining = Math.max(0, (this.viewerCounts.get(botId) ?? 1) - 1);\n this.viewerCounts.set(botId, remaining);\n if (remaining > 0) return;\n\n const session = this.screencastSessions.get(botId);\n this.screencastSessions.delete(botId);\n this.screencastThrottles.delete(botId);\n this.screencastListeners.delete(botId);\n this.lastFrameSize.delete(botId);\n if (session) {\n void session\n .send('Page.stopScreencast')\n .catch(() => {})\n .then(() => session.detach().catch(() => {}));\n }\n };\n }\n\n /* ---------------------------------------------------------------------------------------- *\n * Takeover \u2014 pauses agent-driven actions on a bot's screen for the human.\n * ---------------------------------------------------------------------------------------- */\n\n isTakenOver(botId: string): boolean {\n return this.takenOver.has(botId);\n }\n\n /**\n * Marks the screen as human-controlled. When headless, there is no window to bring forward\n * (and launching a second headed context on the same profile dir isn't possible \u2014 Chromium\n * locks the profile), so the human acts through the screencast view instead; interactive input\n * forwarding through that view is out of scope here. When headed, brings the real window to\n * the front for the human to drive directly.\n */\n async takeOver(botId: string): Promise<TakeOverResult> {\n this.takenOver.add(botId);\n if (this.headlessMode) {\n return {\n ok: true,\n mode: 'screencast-only',\n message:\n 'This computer is running headless, so there is no window to bring to the front. ' +\n 'Act through the screencast view for the blocked step (password, 2FA, CAPTCHA), then return control. ' +\n 'Never paste secrets into chat.',\n };\n }\n try {\n const page = await this.getPage(botId);\n await page.bringToFront();\n } catch (err) {\n log.warn('failed to bring page to front for takeover', err);\n }\n return {\n ok: true,\n mode: 'window',\n message: 'The browser window for this bot has been brought to the front. Complete the blocked step, then return control.',\n };\n }\n\n returnControl(botId: string): void {\n this.takenOver.delete(botId);\n }\n\n /** One immediate JPEG so a static page is not a blank pane. See startScreencast. */\n private async seedFirstFrame(botId: string, page: Page): Promise<void> {\n const listeners = this.screencastListeners.get(botId);\n if (!listeners?.size) return;\n const buf = await page.screenshot({ type: 'jpeg', quality: 60 });\n const vp = page.viewportSize() ?? { width: 0, height: 0 };\n if (vp.width > 0 && vp.height > 0) this.lastFrameSize.set(botId, vp);\n for (const l of listeners) {\n try {\n l(buf.toString('base64'), vp.width, vp.height);\n } catch (err) {\n log.warn('screencast seed listener threw', err);\n }\n }\n }\n\n /**\n * The page's CSS viewport, which is what input coordinates are in.\n *\n * `viewportSize()` is synchronous and correct whenever the context sets one; a persistent\n * context launched without an explicit viewport returns null, so fall back to asking the page.\n * The cached value is only a last resort for a page that has since closed.\n */\n private async viewportOf(botId: string, page: Page): Promise<FrameSize | undefined> {\n const vp = page.viewportSize();\n if (vp && vp.width > 0 && vp.height > 0) {\n this.lastFrameSize.set(botId, { width: vp.width, height: vp.height });\n return vp;\n }\n try {\n const inner = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));\n if (inner.width > 0 && inner.height > 0) {\n this.lastFrameSize.set(botId, inner);\n return inner;\n }\n } catch { /* page closed or navigating */ }\n return this.lastFrameSize.get(botId);\n }\n\n /**\n * Dispatches human input into a taken-over page.\n *\n * The takeover check is the whole security model here, and it is deliberately a hard refusal\n * rather than a queue: input is only ever legitimate while the bot is blocked, and silently\n * buffering it would let a stale click land after control was returned \u2014 into a page the bot\n * has since navigated. Input does not pass the Permission Gateway, because the gateway governs\n * what *bots* do; this is the human acting as themselves on their own computer.\n *\n * Dispatch goes through Playwright's `page.mouse` / `page.keyboard` rather than raw CDP so the\n * key-code mapping is the SDK's problem, matching how `click()` and `type()` above work.\n */\n async forwardInput(botId: string, ev: ScreencastInput): Promise<void> {\n if (!this.takenOver.has(botId)) {\n throw new ScreenNotTakenOverError(\n 'Input was sent for a screen that is not taken over. Take over the screen first.',\n );\n }\n const page = await this.getPage(botId);\n\n if (ev.kind === 'text') {\n await page.keyboard.insertText(ev.text);\n return;\n }\n\n if (ev.kind === 'key') {\n if (!isForwardableKey(ev.key)) return;\n if (ev.action === 'down') await page.keyboard.down(ev.key);\n else await page.keyboard.up(ev.key);\n return;\n }\n\n const pt = toPageCoords({ x: ev.x, y: ev.y }, await this.viewportOf(botId, page));\n // Geometry genuinely unknown \u2014 a guessed coordinate is a click the human did not aim.\n if (!pt) return;\n\n switch (ev.action) {\n case 'move':\n await page.mouse.move(pt.x, pt.y);\n break;\n case 'down':\n await page.mouse.move(pt.x, pt.y);\n await page.mouse.down({ button: ev.button, clickCount: Math.max(1, ev.clickCount) });\n break;\n case 'up':\n await page.mouse.up({ button: ev.button, clickCount: Math.max(1, ev.clickCount) });\n break;\n case 'wheel':\n await page.mouse.move(pt.x, pt.y);\n await page.mouse.wheel(clampWheel(ev.deltaX), clampWheel(ev.deltaY));\n break;\n }\n }\n\n /* ---------------------------------------------------------------------------------------- */\n\n /** Never launches the browser. Reports optimistically until a launch attempt has failed. */\n status(): BrowserStatus {\n if (this.unavailableReason) {\n return { available: false, reason: this.unavailableReason, mode: 'host', headless: this.headlessMode, pages: [] };\n }\n const pages: ComputerPageStatus[] = [];\n if (this.context) {\n for (const [botId, page] of this.pages) {\n if (page.isClosed()) continue;\n pages.push({ botId, url: page.url(), title: this.titleCache.get(botId) ?? '' });\n }\n }\n return { available: true, mode: 'host', headless: this.headlessMode, pages };\n }\n\n async shutdown(): Promise<void> {\n for (const session of this.screencastSessions.values()) {\n await session\n .send('Page.stopScreencast')\n .catch(() => {})\n .then(() => session.detach().catch(() => {}));\n }\n this.screencastSessions.clear();\n this.screencastListeners.clear();\n this.screencastThrottles.clear();\n this.viewerCounts.clear();\n\n for (const page of this.pages.values()) {\n await page.close().catch(() => {});\n }\n this.pages.clear();\n this.titleCache.clear();\n this.takenOver.clear();\n\n if (this.context) {\n await this.context.close().catch(() => {});\n this.context = null;\n }\n this.launchPromise = null;\n }\n}\n", "// Turning normalised screencast input into page coordinates.\n//\n// The client sends fractions of the frame, not pixels, because neither side knows the other's\n// geometry: the screencast is captured at up to 1280px wide (Chromium picks the scale), and the\n// browser then fits that image into whatever the pane happens to be. Pixels sent from the client\n// would be in a third coordinate space belonging to neither.\n//\n// Pure, so every rounding and clamping case below is testable without a browser.\n\n/** Viewport size reported by the most recent screencast frame, in CSS pixels. */\nexport interface FrameSize {\n width: number;\n height: number;\n}\n\n/**\n * Converts a normalised point to page CSS pixels, or null when the conversion cannot be trusted.\n *\n * Null rather than a clamped guess when the frame size is unknown or degenerate: dispatching a\n * click at (0, 0) because no frame has arrived yet would hit whatever is in the top-left corner,\n * which is exactly the kind of silent wrong action this codebase avoids.\n */\nexport function toPageCoords(\n norm: { x: number; y: number },\n frame: FrameSize | undefined,\n): { x: number; y: number } | null {\n if (!frame) return null;\n if (!Number.isFinite(frame.width) || !Number.isFinite(frame.height)) return null;\n if (frame.width <= 0 || frame.height <= 0) return null;\n if (!Number.isFinite(norm.x) || !Number.isFinite(norm.y)) return null;\n\n const clamp01 = (n: number): number => (n < 0 ? 0 : n > 1 ? 1 : n);\n // Clamped to the last addressable pixel: x = 1.0 would otherwise land one pixel outside the\n // viewport, which Chromium ignores rather than treating as an edge click.\n return {\n x: Math.min(Math.round(clamp01(norm.x) * frame.width), frame.width - 1),\n y: Math.min(Math.round(clamp01(norm.y) * frame.height), frame.height - 1),\n };\n}\n\n/**\n * Keys that must not be forwarded to the page, whatever the client sends.\n *\n * These either close or navigate away from the page the human was asked to unblock \u2014 losing the\n * session they took over to rescue \u2014 or they open browser-level UI the screencast cannot show,\n * leaving the view frozen on a page that is no longer in front. The human still has every normal\n * key, including Tab, Enter and Escape.\n */\nconst BLOCKED_KEYS = new Set(['F5', 'F11', 'F12', 'BrowserRefresh', 'BrowserBack', 'BrowserForward']);\n\n/** Whether a key event is safe to dispatch into a taken-over page. */\nexport function isForwardableKey(key: string): boolean {\n return key.length > 0 && !BLOCKED_KEYS.has(key);\n}\n\n/**\n * Wheel deltas, bounded. An unbounded delta from a malformed client would scroll a page by\n * millions of pixels in one event; clamping keeps a bad frame from being disorienting.\n */\nexport function clampWheel(delta: number): number {\n if (!Number.isFinite(delta)) return 0;\n const MAX = 1000;\n return Math.max(-MAX, Math.min(MAX, Math.round(delta)));\n}\n"],
5
+ "mappings": ";;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,gBAAgB;;;ACmBlB,SAAS,aACd,MACA,OACiC;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,CAAC,OAAO,SAAS,MAAM,KAAK,KAAK,CAAC,OAAO,SAAS,MAAM,MAAM,EAAG,QAAO;AAC5E,MAAI,MAAM,SAAS,KAAK,MAAM,UAAU,EAAG,QAAO;AAClD,MAAI,CAAC,OAAO,SAAS,KAAK,CAAC,KAAK,CAAC,OAAO,SAAS,KAAK,CAAC,EAAG,QAAO;AAEjE,QAAM,UAAU,CAAC,MAAuB,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI;AAGhE,SAAO;AAAA,IACL,GAAG,KAAK,IAAI,KAAK,MAAM,QAAQ,KAAK,CAAC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K,EAAE,OAAO,KAAK,KAAK,IAAI,GAAG,OAAO,KAAK,WAAW,IAAI,KAAK,KAAK,GAAG,CAAC;AAAA,MAChF;AAAA,IACF;AACA,WAAO,EAAE,WAAW,MAAM,MAAM,QAAQ,UAAU,KAAK,cAAc,MAAM;AAAA,EAC7E;AAAA,EAEA,MAAM,WAA0B;AAC9B,eAAW,WAAW,KAAK,mBAAmB,OAAO,GAAG;AACtD,YAAM,QACH,KAAK,qBAAqB,EAC1B,MAAM,MAAM;AAAA,MAAC,CAAC,EACd,KAAK,MAAM,QAAQ,OAAO,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC,CAAC;AAAA,IAChD;AACA,SAAK,mBAAmB,MAAM;AAC9B,SAAK,oBAAoB,MAAM;AAC/B,SAAK,oBAAoB,MAAM;AAC/B,SAAK,aAAa,MAAM;AAExB,eAAW,QAAQ,KAAK,MAAM,OAAO,GAAG;AACtC,YAAM,KAAK,MAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IACnC;AACA,SAAK,MAAM,MAAM;AACjB,SAAK,WAAW,MAAM;AACtB,SAAK,UAAU,MAAM;AAErB,QAAI,KAAK,SAAS;AAChB,YAAM,KAAK,QAAQ,MAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AACzC,WAAK,UAAU;AAAA,IACjB;AACA,SAAK,gBAAgB;AAAA,EACvB;AACF;",
6
+ "names": []
7
+ }
@@ -3,13 +3,13 @@ const require = __antbotCreateRequire(import.meta.url);
3
3
  import {
4
4
  findBundledSkillsDir,
5
5
  nodeLocateDeps
6
- } from "./chunk-Z2YT2PZN.js";
6
+ } from "./chunk-GYWJUW4E.js";
7
7
  import {
8
8
  copyTree
9
- } from "./chunk-7BOHBPB2.js";
10
- import "./chunk-KSQOVWP5.js";
9
+ } from "./chunk-JCZBDGBA.js";
10
+ import "./chunk-MSSHR6SW.js";
11
11
 
12
- // packages/server/src/skills/bundled.ts
12
+ // daemon/src/skills/bundled.ts
13
13
  import fs from "node:fs";
14
14
  import path from "node:path";
15
15
  import crypto from "node:crypto";
@@ -130,4 +130,4 @@ export {
130
130
  syncBundledSkills,
131
131
  writeLedger
132
132
  };
133
- //# sourceMappingURL=bundled-46DUK5PG.js.map
133
+ //# sourceMappingURL=bundled-26SJR7EB.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../packages/server/src/skills/bundled.ts"],
3
+ "sources": ["../../daemon/src/skills/bundled.ts"],
4
4
  "sourcesContent": ["import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { fileURLToPath } from 'node:url';\nimport { copyTree } from './install.js';\nimport { findBundledSkillsDir, nodeLocateDeps } from '../util/locate.js';\n\n/**\n * Skills that ship with ant-bot itself, in the repo's (and the published package's)\n * `skills/` directory, installed into the user's skills directory on boot.\n *\n * The hard part is not copying files, it is deciding what to copy *again*. A bundled skill\n * has two owners: ant-bot ships updates to it, and the user is free to edit or delete it.\n * Refreshing unconditionally throws away the user's edits and resurrects what they deleted;\n * seeding once means a shipped fix never reaches anyone who already has the old copy. So the\n * hash of what we wrote is recorded in a ledger, and on the next boot the on-disk copy is\n * compared against it: untouched copies track upstream, touched ones are left alone. This is\n * the same bargain a package manager makes with an edited config file.\n */\n\nconst LEDGER_FILE = '.managed.json';\nconst LEDGER_VERSION = 1;\n\nexport interface LedgerEntry {\n /** Hash of the skill directory as ant-bot last wrote it. */\n hash: string;\n syncedAt: string;\n}\n\nexport interface Ledger {\n version: number;\n skills: Record<string, LedgerEntry>;\n}\n\nexport type SkillSyncAction =\n /** Not on disk and never seeded \u2014 a first install. */\n | 'install'\n /** Ours, untouched by the user, and the shipped copy changed. */\n | 'update'\n /** Not in the ledger but byte-identical to what ships \u2014 adopt it so it tracks upstream. */\n | 'adopt'\n /** Ours, untouched, already current. */\n | 'unchanged'\n /** Ours, but the user edited it. */\n | 'skip-modified'\n /** Same slug, different content, never seeded by us \u2014 someone else's skill. */\n | 'skip-foreign'\n /** Seeded once and since deleted by the user. */\n | 'skip-deleted';\n\nexport interface SkillSyncState {\n slug: string;\n /** Hash of the skill as it ships with this build. */\n shippedHash: string;\n /** Hash of the copy in the user's skills directory, or null if it is not there. */\n installedHash: string | null;\n /** Hash recorded the last time ant-bot wrote this skill, or undefined if it never did. */\n ledgerHash: string | undefined;\n /** Hashes this skill shipped with in earlier ant-bot versions. See KNOWN_PRIOR_HASHES. */\n priorHashes?: string[];\n}\n\n/**\n * Hashes of skills as earlier ant-bot versions shipped them, before the ledger existed.\n *\n * Without this an upgrade that changes a shipped skill can never reach anyone who already has\n * it: their copy is not in the ledger and no longer matches what ships, so it reads as someone\n * else's skill and is left alone forever. Matching a known prior hash proves the copy is an\n * untouched older version of ours, which is safe to replace. This is the same record dpkg keeps\n * for conffiles, and it is append-only \u2014 add the outgoing hash here whenever a shipped skill\n * changes, never remove one.\n */\nexport const KNOWN_PRIOR_HASHES: Record<string, string[]> = {\n // 0.1.0, seeded from skills-examples/ \u2014 before the skills were renamed to spec-conformant\n // frontmatter names and deep-research got its references/ directory.\n 'bug-repro': ['e8faa77eb98c3ba4d7618731d946c233354d158b3ecae7b1bed5908dce3e9cac'],\n 'deep-research': ['33f7482fa2d136dad53c556b5a25527136838f8bd72d35a9657f45e6c21f391b'],\n 'inbox-digest': ['45e137d9d6ce26ad6e230ef1b0711ad7d6b4be06d744f42accea2700f0039361'],\n 'weekly-report': ['fb05e984b96e8771b236602b47a82f1ec600bd307b44878cd92694cdb658a852'],\n};\n\nexport interface SkillSyncDecision {\n slug: string;\n action: SkillSyncAction;\n}\n\n/**\n * Decide what to do with each bundled skill. Pure, so every branch below is testable without\n * touching a filesystem \u2014 and there are more branches here than the copying deserves.\n */\nexport function planSkillSync(states: SkillSyncState[]): SkillSyncDecision[] {\n return states.map(({ slug, shippedHash, installedHash, ledgerHash, priorHashes }): SkillSyncDecision => {\n if (installedHash === null) {\n // A ledger entry with nothing on disk means the user deleted it. Putting it back on\n // every boot would make deletion impossible.\n return { slug, action: ledgerHash === undefined ? 'install' : 'skip-deleted' };\n }\n if (ledgerHash === undefined) {\n // Never seeded by us. Byte-identical to what ships means a pre-ledger seed from an older\n // ant-bot: adopt it as-is. Matching a hash we are known to have shipped before means an\n // untouched *older* copy of ours, safe to bring up to date. Anything else belongs to\n // whoever put it there (`antbot skill add`, or dropped in by hand) and we keep our hands off.\n if (installedHash === shippedHash) return { slug, action: 'adopt' };\n if (priorHashes?.includes(installedHash)) return { slug, action: 'update' };\n return { slug, action: 'skip-foreign' };\n }\n if (installedHash !== ledgerHash) return { slug, action: 'skip-modified' };\n return { slug, action: installedHash === shippedHash ? 'unchanged' : 'update' };\n });\n}\n\n/** Hash a skill directory: every file's path and contents, in a stable order. */\nexport function hashSkillDir(dir: string): string {\n const h = crypto.createHash('sha256');\n for (const rel of listFilesRecursive(dir).sort()) {\n h.update(rel.split(path.sep).join('/'));\n h.update('\\0');\n h.update(fs.readFileSync(path.join(dir, rel)));\n h.update('\\0');\n }\n return h.digest('hex');\n}\n\nfunction listFilesRecursive(dir: string, prefix = ''): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n // Mirrors copyTree: what is not copied must not be hashed, or a skill would look\n // modified forever.\n if (entry.name === '.git' || entry.name === 'node_modules') continue;\n if (entry.isSymbolicLink()) continue;\n const rel = path.join(prefix, entry.name);\n if (entry.isDirectory()) out.push(...listFilesRecursive(path.join(dir, entry.name), rel));\n else if (entry.isFile()) out.push(rel);\n }\n return out;\n}\n\nexport function readLedger(targetDir: string): Ledger {\n try {\n const raw = fs.readFileSync(path.join(targetDir, LEDGER_FILE), 'utf8');\n const parsed = JSON.parse(raw) as Partial<Ledger>;\n if (parsed.version !== LEDGER_VERSION || typeof parsed.skills !== 'object' || !parsed.skills) {\n return { version: LEDGER_VERSION, skills: {} };\n }\n return { version: LEDGER_VERSION, skills: parsed.skills };\n } catch {\n // No ledger, or an unreadable one. Treating it as empty is safe: every on-disk skill then\n // looks foreign or adoptable, and nothing gets overwritten.\n return { version: LEDGER_VERSION, skills: {} };\n }\n}\n\nexport function writeLedger(targetDir: string, ledger: Ledger): void {\n fs.mkdirSync(targetDir, { recursive: true });\n fs.writeFileSync(path.join(targetDir, LEDGER_FILE), `${JSON.stringify(ledger, null, 2)}\\n`, 'utf8');\n}\n\n/** Location of the skills that ship with ant-bot; see `util/locate.ts` for the candidate order. */\nexport function defaultBundledSkillsDir(): string {\n return findBundledSkillsDir(\n nodeLocateDeps(path.dirname(fileURLToPath(import.meta.url)), () => null),\n );\n}\n\n/**\n * Install or refresh ant-bot's own skills in `targetDir`. Safe to call on every boot; see the\n * module comment for why it is not a plain copy. Returns what it did, for the boot log.\n */\nexport function syncBundledSkills(\n targetDir: string,\n bundledDir: string = defaultBundledSkillsDir(),\n): SkillSyncDecision[] {\n if (!fs.existsSync(bundledDir)) return [];\n\n const ledger = readLedger(targetDir);\n const states: SkillSyncState[] = [];\n const shippedDirs = new Map<string, string>();\n\n for (const entry of fs.readdirSync(bundledDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const src = path.join(bundledDir, entry.name);\n if (!fs.existsSync(path.join(src, 'SKILL.md'))) continue;\n const dest = path.join(targetDir, entry.name);\n shippedDirs.set(entry.name, src);\n states.push({\n slug: entry.name,\n shippedHash: hashSkillDir(src),\n installedHash: fs.existsSync(path.join(dest, 'SKILL.md')) ? hashSkillDir(dest) : null,\n ledgerHash: ledger.skills[entry.name]?.hash,\n priorHashes: KNOWN_PRIOR_HASHES[entry.name],\n });\n }\n if (states.length === 0) return [];\n\n const decisions = planSkillSync(states);\n const byslug = new Map(states.map((s) => [s.slug, s]));\n const syncedAt = new Date().toISOString();\n let ledgerChanged = false;\n\n fs.mkdirSync(targetDir, { recursive: true });\n for (const decision of decisions) {\n const state = byslug.get(decision.slug)!;\n if (decision.action === 'install' || decision.action === 'update') {\n const dest = path.join(targetDir, decision.slug);\n fs.rmSync(dest, { recursive: true, force: true });\n copyTree(shippedDirs.get(decision.slug)!, dest);\n } else if (decision.action !== 'adopt') {\n continue;\n }\n ledger.skills[decision.slug] = { hash: state.shippedHash, syncedAt };\n ledgerChanged = true;\n }\n if (ledgerChanged) writeLedger(targetDir, ledger);\n\n return decisions;\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,YAAY;AACnB,SAAS,qBAAqB;AAiB9B,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAmDhB,IAAM,qBAA+C;AAAA;AAAA;AAAA,EAG1D,aAAa,CAAC,kEAAkE;AAAA,EAChF,iBAAiB,CAAC,kEAAkE;AAAA,EACpF,gBAAgB,CAAC,kEAAkE;AAAA,EACnF,iBAAiB,CAAC,kEAAkE;AACtF;AAWO,SAAS,cAAc,QAA+C;AAC3E,SAAO,OAAO,IAAI,CAAC,EAAE,MAAM,aAAa,eAAe,YAAY,YAAY,MAAyB;AACtG,QAAI,kBAAkB,MAAM;AAG1B,aAAO,EAAE,MAAM,QAAQ,eAAe,SAAY,YAAY,eAAe;AAAA,IAC/E;AACA,QAAI,eAAe,QAAW;AAK5B,UAAI,kBAAkB,YAAa,QAAO,EAAE,MAAM,QAAQ,QAAQ;AAClE,UAAI,aAAa,SAAS,aAAa,EAAG,QAAO,EAAE,MAAM,QAAQ,SAAS;AAC1E,aAAO,EAAE,MAAM,QAAQ,eAAe;AAAA,IACxC;AACA,QAAI,kBAAkB,WAAY,QAAO,EAAE,MAAM,QAAQ,gBAAgB;AACzE,WAAO,EAAE,MAAM,QAAQ,kBAAkB,cAAc,cAAc,SAAS;AAAA,EAChF,CAAC;AACH;AAGO,SAAS,aAAa,KAAqB;AAChD,QAAM,IAAI,OAAO,WAAW,QAAQ;AACpC,aAAW,OAAO,mBAAmB,GAAG,EAAE,KAAK,GAAG;AAChD,MAAE,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG,CAAC;AACtC,MAAE,OAAO,IAAI;AACb,MAA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