effect-browser 0.3.0-beta.23 → 0.3.0-beta.25
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/README.md +437 -142
- package/dist/Action.d.mts +1 -1
- package/dist/Action.mjs +61 -9
- package/dist/Action.mjs.map +1 -1
- package/dist/Browser.d.mts +2 -2
- package/dist/Browser.mjs +2 -2
- package/dist/BrowserError.d.mts +2 -2
- package/dist/BrowserError.mjs +194 -41
- package/dist/BrowserError.mjs.map +1 -1
- package/dist/BrowserEvent.d.mts +2 -2
- package/dist/BrowserEvent.mjs +185 -35
- package/dist/BrowserEvent.mjs.map +1 -1
- package/dist/Cdp.d.mts +15 -0
- package/dist/Cdp.mjs +22 -0
- package/dist/Cdp.mjs.map +1 -0
- package/dist/Change.d.mts +2 -2
- package/dist/Change.mjs +40 -7
- package/dist/Change.mjs.map +1 -1
- package/dist/Frame.d.mts +2 -2
- package/dist/Frame.mjs +132 -14
- package/dist/Frame.mjs.map +1 -1
- package/dist/InputStyle.d.mts +153 -0
- package/dist/InputStyle.mjs +2 -0
- package/dist/Layout.d.mts +2 -0
- package/dist/Layout.mjs +123 -0
- package/dist/Layout.mjs.map +1 -0
- package/dist/Overlay.d.mts +2 -0
- package/dist/Overlay.mjs +58 -0
- package/dist/Overlay.mjs.map +1 -0
- package/dist/Page.d.mts +2 -2
- package/dist/Page.mjs +2 -2
- package/dist/PageTime.d.mts +2 -0
- package/dist/PageTime.mjs +17 -0
- package/dist/PageTime.mjs.map +1 -0
- package/dist/Pose.d.mts +2 -0
- package/dist/Pose.mjs +65 -0
- package/dist/Pose.mjs.map +1 -0
- package/dist/Site.d.mts +984 -0
- package/dist/Site.mjs +110 -0
- package/dist/Site.mjs.map +1 -0
- package/dist/Snapshot.d.mts +2 -2
- package/dist/Snapshot.mjs +87 -6
- package/dist/Snapshot.mjs.map +1 -1
- package/dist/Text.d.mts +2 -0
- package/dist/Text.mjs +45 -0
- package/dist/Text.mjs.map +1 -0
- package/dist/Window.d.mts +2 -2
- package/dist/Window.mjs +31 -6
- package/dist/Window.mjs.map +1 -1
- package/dist/ai/BrowserTools.d.mts +4987 -0
- package/dist/ai/BrowserTools.mjs +3 -0
- package/dist/ai/PageControl.d.mts +286 -0
- package/dist/ai/PageControl.mjs +426 -0
- package/dist/ai/PageControl.mjs.map +1 -0
- package/dist/ai/PromptCache.d.mts +16 -0
- package/dist/ai/PromptCache.mjs +72 -0
- package/dist/ai/PromptCache.mjs.map +1 -0
- package/dist/ai/Tabs.d.mts +2 -0
- package/dist/ai/Tabs.mjs +72 -0
- package/dist/ai/Tabs.mjs.map +1 -0
- package/dist/ai/ToolError.d.mts +34 -0
- package/dist/ai/ToolError.mjs +2 -0
- package/dist/ai/index.d.mts +6 -0
- package/dist/ai/index.mjs +6 -0
- package/dist/index.d.mts +7 -15
- package/dist/index.mjs +9 -8
- package/dist/{Action-24sLOubi.d.mts → internal/Action-CkanNTUw.d.mts} +64 -4
- package/dist/{Browser-wZhwZSlG.d.mts → internal/Browser-DD9Vm1c-.d.mts} +80 -10
- package/dist/{Browser-BKPAbyys.mjs → internal/Browser-vzD7i2oj.mjs} +658 -495
- package/dist/internal/Browser-vzD7i2oj.mjs.map +1 -0
- package/dist/{BrowserError-BlcmLVzn.d.mts → internal/BrowserError-CsuRYcDX.d.mts} +187 -28
- package/dist/{BrowserEvent-lLqJ3GJS.d.mts → internal/BrowserEvent-tGPYYf6R.d.mts} +197 -18
- package/dist/internal/BrowserTools-Yi3lOX4h.mjs +497 -0
- package/dist/internal/BrowserTools-Yi3lOX4h.mjs.map +1 -0
- package/dist/{Style-AO4V7Czt.mjs → internal/InputStyle-CPzxoN4g.mjs} +94 -16
- package/dist/internal/InputStyle-CPzxoN4g.mjs.map +1 -0
- package/dist/{moment/Moment.mjs → internal/Moment-CstaX1mR.mjs} +49 -16
- package/dist/internal/Moment-CstaX1mR.mjs.map +1 -0
- package/dist/{moment/Moment.d.mts → internal/Moment-DOcldBdf.d.mts} +54 -21
- package/dist/internal/Page-BfGxn7oN.d.mts +1553 -0
- package/dist/{Page-BF5izr8R.mjs → internal/Page-DqF-tuTx.mjs} +62 -72
- package/dist/internal/Page-DqF-tuTx.mjs.map +1 -0
- package/dist/internal/Release-CFONkPDP.d.mts +39 -0
- package/dist/internal/Stage-D5ymSXDT.mjs +298 -0
- package/dist/internal/Stage-D5ymSXDT.mjs.map +1 -0
- package/dist/internal/Stillness-DCPeAN1a.mjs +1124 -0
- package/dist/internal/Stillness-DCPeAN1a.mjs.map +1 -0
- package/dist/internal/Supervisor-BcY_QNIY.d.mts +108 -0
- package/dist/internal/Supervisor-BcglY23c.mjs +531 -0
- package/dist/internal/Supervisor-BcglY23c.mjs.map +1 -0
- package/dist/internal/Tabs-dXMscIUQ.d.mts +52 -0
- package/dist/internal/TestPage-CYiYbh63.d.mts +159 -0
- package/dist/internal/ToolError-DArsRS2m.mjs +117 -0
- package/dist/internal/ToolError-DArsRS2m.mjs.map +1 -0
- package/dist/{plan/index.d.mts → internal/Walk-BNXcfZ2z.d.mts} +59 -35
- package/dist/{plan/index.mjs → internal/Walk-C5ky7uSf.mjs} +83 -51
- package/dist/internal/Walk-C5ky7uSf.mjs.map +1 -0
- package/dist/{ActionPort.mjs → internal/action-port-B5EkeGOR.mjs} +6 -12
- package/dist/internal/action-port-B5EkeGOR.mjs.map +1 -0
- package/dist/internal/cdp/workerd.d.mts +13 -0
- package/dist/internal/cdp/workerd.mjs +19 -0
- package/dist/internal/cdp/workerd.mjs.map +1 -0
- package/dist/{Clock.mjs → internal/clock-BKSAEf00.mjs} +13 -13
- package/dist/internal/clock-BKSAEf00.mjs.map +1 -0
- package/dist/{connection-2KHI4_KN.d.mts → internal/connection-BaB0vp1o.d.mts} +6 -6
- package/dist/{connection-CK83pvqP.mjs → internal/connection-C2X4GmXM.mjs} +19 -15
- package/dist/internal/connection-C2X4GmXM.mjs.map +1 -0
- package/dist/internal/events-DzCrww-y.mjs +72 -0
- package/dist/internal/events-DzCrww-y.mjs.map +1 -0
- package/dist/internal/fold.inpage-CyVZQHZL.d.mts +49 -0
- package/dist/internal/fold.inpage-uhrT-dOB.mjs +49 -0
- package/dist/internal/fold.inpage-uhrT-dOB.mjs.map +1 -0
- package/dist/internal/functions-jBOs6GKv.mjs +27 -0
- package/dist/internal/functions-jBOs6GKv.mjs.map +1 -0
- package/dist/{Geometry-DJx9qrYy.d.mts → internal/geometry-Dhj_ztJs.d.mts} +3 -3
- package/dist/{Geometry.mjs → internal/geometry-Lxyflb9J.mjs} +3 -12
- package/dist/internal/geometry-Lxyflb9J.mjs.map +1 -0
- package/dist/{Matching.mjs → internal/matching-Cs-UeOY0.mjs} +24 -19
- package/dist/internal/matching-Cs-UeOY0.mjs.map +1 -0
- package/dist/internal/page-DFQb-YOK.mjs +436 -0
- package/dist/internal/page-DFQb-YOK.mjs.map +1 -0
- package/dist/internal/pose.inpage-CBFeWcVa.mjs +1996 -0
- package/dist/internal/pose.inpage-CBFeWcVa.mjs.map +1 -0
- package/dist/{Url.mjs → internal/url-DB0pQYk6.mjs} +3 -12
- package/dist/internal/url-DB0pQYk6.mjs.map +1 -0
- package/dist/policy/Policy.d.mts +60 -6
- package/dist/policy/Policy.mjs +52 -9
- package/dist/policy/Policy.mjs.map +1 -1
- package/dist/policy/index.d.mts +2 -0
- package/dist/policy/index.mjs +2 -0
- package/dist/presentation/Film.d.mts +332 -0
- package/dist/presentation/Film.mjs +298 -0
- package/dist/presentation/Film.mjs.map +1 -0
- package/dist/presentation/Motion.d.mts +5 -1
- package/dist/presentation/Motion.mjs +16 -2
- package/dist/presentation/Motion.mjs.map +1 -1
- package/dist/presentation/Presentation.d.mts +48 -6
- package/dist/presentation/Presentation.mjs +28 -9
- package/dist/presentation/Presentation.mjs.map +1 -1
- package/dist/presentation/Stage.d.mts +40 -6
- package/dist/presentation/Stage.mjs +1 -262
- package/dist/presentation/index.d.mts +5 -0
- package/dist/presentation/index.mjs +5 -0
- package/dist/supervisor/Release.d.mts +2 -0
- package/dist/supervisor/Release.mjs +40 -0
- package/dist/supervisor/Release.mjs.map +1 -0
- package/dist/supervisor/Supervisor.d.mts +2 -104
- package/dist/supervisor/Supervisor.mjs +2 -515
- package/dist/supervisor/index.d.mts +3 -0
- package/dist/supervisor/index.mjs +3 -0
- package/dist/testing/HttpCassette.d.mts +98 -0
- package/dist/testing/HttpCassette.mjs +146 -0
- package/dist/testing/HttpCassette.mjs.map +1 -0
- package/dist/testing/Story.d.mts +31 -0
- package/dist/testing/Story.mjs +76 -0
- package/dist/testing/Story.mjs.map +1 -0
- package/dist/testing/TestBrowser.d.mts +191 -0
- package/dist/testing/TestBrowser.mjs +105 -0
- package/dist/testing/TestBrowser.mjs.map +1 -0
- package/dist/testing/TestModel.d.mts +133 -0
- package/dist/testing/TestModel.mjs +209 -0
- package/dist/testing/TestModel.mjs.map +1 -0
- package/dist/testing/TestPage.d.mts +2 -0
- package/dist/testing/TestPage.mjs +47 -0
- package/dist/testing/TestPage.mjs.map +1 -0
- package/dist/testing/index.d.mts +6 -337
- package/dist/testing/index.mjs +6 -515
- package/dist/timeline/Moment.d.mts +3 -0
- package/dist/timeline/Moment.mjs +3 -0
- package/dist/timeline/Stillness.d.mts +34 -0
- package/dist/timeline/Stillness.mjs +2 -0
- package/dist/timeline/index.d.mts +3 -0
- package/dist/timeline/index.mjs +3 -0
- package/dist/walk/Walk.d.mts +2 -0
- package/dist/walk/Walk.mjs +2 -0
- package/dist/walk/index.d.mts +2 -0
- package/dist/walk/index.mjs +2 -0
- package/package.json +54 -133
- package/src/Action.ts +73 -8
- package/src/Browser.ts +85 -14
- package/src/BrowserError.ts +258 -63
- package/src/BrowserEvent.ts +264 -48
- package/src/Cdp.ts +42 -0
- package/src/Change.ts +75 -4
- package/src/Frame.ts +247 -14
- package/src/{Style.ts → InputStyle.ts} +130 -18
- package/src/Layout.ts +187 -0
- package/src/Overlay.ts +76 -0
- package/src/Page.ts +144 -275
- package/src/PageTime.ts +72 -0
- package/src/Pose.ts +81 -0
- package/src/Site.ts +136 -0
- package/src/Snapshot.ts +179 -3
- package/src/Text.ts +60 -0
- package/src/Window.ts +53 -3
- package/src/ai/BrowserTools.ts +778 -0
- package/src/ai/PageControl.ts +702 -0
- package/src/ai/PromptCache.ts +87 -0
- package/src/ai/Tabs.ts +84 -0
- package/src/ai/ToolError.ts +50 -0
- package/src/ai/index.ts +36 -0
- package/src/ai/internal/crops.ts +38 -0
- package/src/ai/internal/points.ts +57 -0
- package/src/ai/internal/receipts.ts +107 -0
- package/src/index.ts +87 -6
- package/src/{ActionPort.ts → internal/action-port.ts} +3 -3
- package/src/{providers → internal/cdp}/connection.ts +19 -12
- package/src/internal/cdp/workerd.ts +36 -0
- package/src/{Clock.ts → internal/clock.ts} +20 -0
- package/src/internal/input/actions.ts +1 -1
- package/src/internal/input/dispatch.ts +2 -2
- package/src/internal/input/guard.inpage.ts +1 -1
- package/src/internal/input/guard.ts +1 -1
- package/src/internal/input/perform.ts +35 -7
- package/src/internal/input/pointer.ts +9 -6
- package/src/internal/input/targets.inpage.ts +3 -3
- package/src/internal/input/targets.ts +1 -1
- package/src/{Matching.ts → internal/matching.ts} +28 -19
- package/src/internal/page/bridge.ts +67 -35
- package/src/internal/page/clock.inpage.ts +306 -0
- package/src/internal/page/compose.inpage.ts +101 -0
- package/src/internal/page/context.ts +4 -2
- package/src/internal/page/functions.ts +84 -0
- package/src/internal/page/navigation.ts +1 -1
- package/src/internal/page/openings.ts +2 -2
- package/src/internal/page/overlay.inpage.ts +96 -0
- package/src/internal/page/overlay.ts +89 -0
- package/src/internal/page/page.ts +39 -29
- package/src/internal/page/port.ts +14 -8
- package/src/internal/page/pose.inpage.ts +200 -0
- package/src/internal/page/pose.ts +80 -0
- package/src/internal/page/replies.ts +1 -1
- package/src/internal/page/requests.ts +1 -1
- package/src/internal/page/scripts.ts +1 -1
- package/src/internal/page/time.inpage.ts +49 -0
- package/src/internal/page/time.ts +122 -0
- package/src/internal/page/viewport.ts +3 -2
- package/src/internal/pictures/capture.ts +1 -4
- package/src/internal/pictures/dimensions.ts +1 -1
- package/src/internal/pictures/frame.ts +1 -1
- package/src/internal/pictures/pictures.ts +144 -91
- package/src/internal/reading/context.inpage.ts +2 -2
- package/src/internal/reading/expect.inpage.ts +1 -1
- package/src/internal/reading/layout.inpage.ts +193 -0
- package/src/internal/reading/layout.ts +101 -0
- package/src/internal/reading/names.inpage.ts +15 -0
- package/src/internal/reading/outline.inpage.ts +5 -21
- package/src/internal/reading/reading.ts +33 -21
- package/src/internal/reading/ready.inpage.ts +21 -26
- package/src/internal/reading/ready.ts +26 -5
- package/src/internal/reading/subjects.inpage.ts +3 -3
- package/src/internal/reading/text.inpage.ts +3 -16
- package/src/internal/reading/walk.inpage.ts +1 -1
- package/src/internal/timeline/changes.inpage.ts +7 -15
- package/src/internal/timeline/changes.ts +17 -5
- package/src/internal/timeline/record.inpage.ts +15 -6
- package/src/internal/timeline/sight.inpage.ts +2 -2
- package/src/internal/timeline/window.ts +3 -4
- package/src/policy/Policy.ts +70 -16
- package/src/policy/index.ts +12 -0
- package/src/presentation/Film.ts +451 -0
- package/src/presentation/Motion.ts +45 -3
- package/src/presentation/Presentation.ts +60 -14
- package/src/presentation/Stage.ts +73 -35
- package/src/presentation/index.ts +30 -0
- package/src/presentation/{feed.ts → internal/feed.ts} +1 -1
- package/src/supervisor/Release.ts +45 -0
- package/src/supervisor/Supervisor.ts +80 -5
- package/src/supervisor/index.ts +18 -0
- package/src/supervisor/{contract.ts → internal/contract.ts} +14 -10
- package/src/supervisor/{lifecycle.ts → internal/lifecycle.ts} +7 -7
- package/src/supervisor/{runtime.ts → internal/runtime.ts} +7 -7
- package/src/testing/HttpCassette.ts +260 -0
- package/src/testing/Story.ts +103 -0
- package/src/testing/TestBrowser.ts +14 -4
- package/src/testing/TestModel.ts +297 -0
- package/src/testing/TestPage.ts +92 -4
- package/src/testing/index.ts +35 -1
- package/src/testing/{evidence.ts → internal/evidence.ts} +19 -11
- package/src/testing/{model.ts → internal/model.ts} +14 -8
- package/src/testing/{page.ts → internal/page.ts} +55 -51
- package/src/{moment → timeline}/Moment.ts +79 -29
- package/src/{stillness → timeline}/Stillness.ts +89 -46
- package/src/timeline/index.ts +18 -0
- package/src/{stillness/Pixels.ts → timeline/internal/pixels.ts} +27 -1
- package/src/{moment → timeline/internal}/words.ts +2 -2
- package/src/walk/Walk.ts +165 -0
- package/src/walk/index.ts +12 -0
- package/src/{plan → walk/internal}/choose.ts +23 -14
- package/src/{plan → walk/internal}/data.ts +37 -14
- package/src/{plan → walk/internal}/execute.ts +79 -36
- package/src/{plan → walk/internal}/record.ts +6 -6
- package/src/{plan → walk/internal}/targets.ts +35 -25
- package/dist/ActionPort.d.mts +0 -15
- package/dist/ActionPort.mjs.map +0 -1
- package/dist/Browser-BKPAbyys.mjs.map +0 -1
- package/dist/Change-Ba7INmay.d.mts +0 -69
- package/dist/Clock.d.mts +0 -57
- package/dist/Clock.mjs.map +0 -1
- package/dist/Frame-UEH2hO5T.d.mts +0 -124
- package/dist/Geometry.d.mts +0 -2
- package/dist/Geometry.mjs.map +0 -1
- package/dist/Matching.d.mts +0 -37
- package/dist/Matching.mjs.map +0 -1
- package/dist/Page-BF5izr8R.mjs.map +0 -1
- package/dist/Page-CvsOEorc.d.mts +0 -566
- package/dist/Released-tURbFmal.d.mts +0 -15
- package/dist/Snapshot-CtBVOtuu.d.mts +0 -73
- package/dist/Stillness-CNlvayIo.mjs +0 -136
- package/dist/Stillness-CNlvayIo.mjs.map +0 -1
- package/dist/Style-AO4V7Czt.mjs.map +0 -1
- package/dist/Style.d.mts +0 -72
- package/dist/Style.mjs +0 -2
- package/dist/Url.d.mts +0 -26
- package/dist/Url.mjs.map +0 -1
- package/dist/Window-CMddGMt1.d.mts +0 -34
- package/dist/connection-CK83pvqP.mjs.map +0 -1
- package/dist/moment/Moment.mjs.map +0 -1
- package/dist/plan/index.mjs.map +0 -1
- package/dist/presentation/Stage.mjs.map +0 -1
- package/dist/presentation/feed.d.mts +0 -20
- package/dist/presentation/feed.mjs +0 -18
- package/dist/presentation/feed.mjs.map +0 -1
- package/dist/providers/Cdp.d.mts +0 -9
- package/dist/providers/Cdp.mjs +0 -15
- package/dist/providers/Cdp.mjs.map +0 -1
- package/dist/providers/Chromium.d.mts +0 -32
- package/dist/providers/Chromium.mjs +0 -55
- package/dist/providers/Chromium.mjs.map +0 -1
- package/dist/providers/Released.d.mts +0 -2
- package/dist/providers/Released.mjs +0 -12
- package/dist/providers/Released.mjs.map +0 -1
- package/dist/stillness/Stillness.d.mts +0 -12
- package/dist/stillness/Stillness.mjs +0 -2
- package/dist/supervisor/Supervisor.mjs.map +0 -1
- package/dist/testing/index.mjs.map +0 -1
- package/dist/workerd/Cdp.d.mts +0 -8
- package/dist/workerd/Cdp.mjs +0 -13
- package/dist/workerd/Cdp.mjs.map +0 -1
- package/src/plan/index.ts +0 -36
- package/src/providers/Cdp.ts +0 -16
- package/src/providers/Chromium.ts +0 -99
- package/src/providers/Released.ts +0 -13
- package/src/workerd/Cdp.ts +0 -11
- /package/dist/{rolldown-runtime-D7D4PA-g.mjs → internal/rolldown-runtime-D7D4PA-g.mjs} +0 -0
- /package/src/{Geometry.ts → internal/geometry.ts} +0 -0
- /package/src/{Url.ts → internal/url.ts} +0 -0
- /package/src/{stillness → timeline/internal}/utilsBundle.d.ts +0 -0
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import { t as __exportAll } from "../internal/rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { r as millisOf } from "../internal/clock-BKSAEf00.mjs";
|
|
3
|
+
import { Snapshot, read, until } from "../Snapshot.mjs";
|
|
4
|
+
import { read as read$1 } from "../Change.mjs";
|
|
5
|
+
import { Task } from "../policy/Policy.mjs";
|
|
6
|
+
import { a as destination, c as told, o as dispatchOf, r as fromBrowserError, s as followed, t as ToolError } from "../internal/ToolError-DArsRS2m.mjs";
|
|
7
|
+
import { Tabs, follow, make as make$1, selected } from "./Tabs.mjs";
|
|
8
|
+
import { Duration, Effect, Option, Result, Schema } from "effect";
|
|
9
|
+
//#region src/ai/PageControl.ts
|
|
10
|
+
/**
|
|
11
|
+
* effect-browser pages as the controller `BrowserTools` serves: `actions`, which observe a page and
|
|
12
|
+
* act on the refs it observed, and `control`, which inspects, navigates, scrolls, waits, presses
|
|
13
|
+
* keys and selects tabs. Their observations and results are this module's schemas, and they fail
|
|
14
|
+
* with `ToolError`. Yielded Agent defined them as its `BrowserActions` and `BrowserControl` ports
|
|
15
|
+
* until 0.1.0-beta.174 replaced those with Code Mode over CDP; they keep the shapes they had there.
|
|
16
|
+
*
|
|
17
|
+
* Over a `page`, the controller is pinned to it: it lists no tabs, and a tab the page opens stays
|
|
18
|
+
* where it is. Over a `browser`, it acts on the tab the model last saw and lists the others as tabs
|
|
19
|
+
* it may select. A tab an action opens is shown at the next look as `follow` says: `"select"`, the
|
|
20
|
+
* default, makes it current without bringing it to front, so the page on air and an operator's
|
|
21
|
+
* view stay where they are; `"front"` also brings it to front; `"never"` keeps the current tab.
|
|
22
|
+
*
|
|
23
|
+
* An observation is the page's outline, with a ref on each control, and the controls as values. One
|
|
24
|
+
* after an action begins with what followed it: a dialog and how the browser answered it, a
|
|
25
|
+
* navigation, a tab it opened and what its input visibly changed. Every action goes through the
|
|
26
|
+
* page's own input policy, with `task` as the user's task its judge reads, and the browser answers
|
|
27
|
+
* dialogs itself. With `changes`, its outline holds only the lines that changed since the tab's last
|
|
28
|
+
* whole look, when those are fewer. An action that failed before its input reached the browser is `not-dispatched`,
|
|
29
|
+
* one that failed after is `possibly-dispatched`, and nothing is ever retried.
|
|
30
|
+
*
|
|
31
|
+
* @stability stable
|
|
32
|
+
* @since 0.3.0
|
|
33
|
+
*/
|
|
34
|
+
var PageControl_exports = /* @__PURE__ */ __exportAll({
|
|
35
|
+
Action: () => Action,
|
|
36
|
+
ActionResult: () => ActionResult,
|
|
37
|
+
Observation: () => Observation,
|
|
38
|
+
Ref: () => Ref,
|
|
39
|
+
make: () => make
|
|
40
|
+
});
|
|
41
|
+
/**
|
|
42
|
+
* A control's ref in an observation, such as `e12`.
|
|
43
|
+
*
|
|
44
|
+
* @stability stable
|
|
45
|
+
* @category schemas
|
|
46
|
+
* @since 0.3.0
|
|
47
|
+
*/
|
|
48
|
+
const Ref = Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9-]{0,50}$/));
|
|
49
|
+
/**
|
|
50
|
+
* An action on an observed control.
|
|
51
|
+
*
|
|
52
|
+
* @stability stable
|
|
53
|
+
* @category schemas
|
|
54
|
+
* @since 0.3.0
|
|
55
|
+
*/
|
|
56
|
+
const Action = Schema.Union([
|
|
57
|
+
Schema.Struct({
|
|
58
|
+
kind: Schema.Literal("click"),
|
|
59
|
+
ref: Ref
|
|
60
|
+
}),
|
|
61
|
+
Schema.Struct({
|
|
62
|
+
kind: Schema.Literal("fill"),
|
|
63
|
+
ref: Ref,
|
|
64
|
+
value: Schema.String.check(Schema.isMaxLength(65536))
|
|
65
|
+
}),
|
|
66
|
+
Schema.Struct({
|
|
67
|
+
kind: Schema.Literal("select"),
|
|
68
|
+
ref: Ref,
|
|
69
|
+
value: Schema.String.check(Schema.isMaxLength(4096))
|
|
70
|
+
})
|
|
71
|
+
]);
|
|
72
|
+
/** A control as an observation lists it. */
|
|
73
|
+
const Control = Schema.Struct({
|
|
74
|
+
ref: Ref,
|
|
75
|
+
kind: Schema.String,
|
|
76
|
+
name: Schema.String,
|
|
77
|
+
value: Schema.String,
|
|
78
|
+
options: Schema.Array(Schema.String),
|
|
79
|
+
optionCount: Schema.optionalKey(Schema.Natural),
|
|
80
|
+
disabled: Schema.optionalKey(Schema.Boolean),
|
|
81
|
+
checked: Schema.optionalKey(Schema.Boolean),
|
|
82
|
+
editable: Schema.optionalKey(Schema.Boolean)
|
|
83
|
+
});
|
|
84
|
+
/**
|
|
85
|
+
* The page's outline and its controls, where the page is scrolled, and a browser's tabs.
|
|
86
|
+
*
|
|
87
|
+
* @stability stable
|
|
88
|
+
* @category schemas
|
|
89
|
+
* @since 0.3.0
|
|
90
|
+
*/
|
|
91
|
+
const Observation = Schema.Struct({
|
|
92
|
+
text: Schema.String,
|
|
93
|
+
controls: Schema.Array(Control),
|
|
94
|
+
page: Schema.Struct({
|
|
95
|
+
title: Schema.String,
|
|
96
|
+
scrollY: Schema.Finite,
|
|
97
|
+
viewportHeight: Schema.Finite,
|
|
98
|
+
documentHeight: Schema.Finite
|
|
99
|
+
}),
|
|
100
|
+
truncated: Schema.Boolean,
|
|
101
|
+
tabs: Schema.optionalKey(Schema.Array(Schema.Struct({
|
|
102
|
+
ref: Ref,
|
|
103
|
+
url: Schema.String,
|
|
104
|
+
active: Schema.Boolean
|
|
105
|
+
})))
|
|
106
|
+
});
|
|
107
|
+
const Dispatch = Schema.Literals([
|
|
108
|
+
"not-dispatched",
|
|
109
|
+
"acknowledged",
|
|
110
|
+
"possibly-dispatched"
|
|
111
|
+
]);
|
|
112
|
+
/**
|
|
113
|
+
* What actions did: how many completed, the first one's failure, the page after them unless the
|
|
114
|
+
* caller asked not to look, and whether the input reached the browser. Never replay an input
|
|
115
|
+
* whose dispatch is not `not-dispatched`.
|
|
116
|
+
*
|
|
117
|
+
* @stability stable
|
|
118
|
+
* @category schemas
|
|
119
|
+
* @since 0.3.0
|
|
120
|
+
*/
|
|
121
|
+
const ActionResult = Schema.Struct({
|
|
122
|
+
completed: Schema.Natural,
|
|
123
|
+
error: Schema.NullOr(Schema.String),
|
|
124
|
+
observation: Schema.NullOr(Observation),
|
|
125
|
+
dispatch: Dispatch
|
|
126
|
+
});
|
|
127
|
+
const invalid = (message) => Effect.fail(new ToolError({
|
|
128
|
+
code: "invalid",
|
|
129
|
+
message
|
|
130
|
+
}));
|
|
131
|
+
/** A snapshot as an observation: the outline, the controls and where the page is. */
|
|
132
|
+
const observation = (snapshot, extra) => ({
|
|
133
|
+
text: [...extra.followed ?? [], snapshot.rendered].join("\n"),
|
|
134
|
+
controls: snapshot.controls.map((control) => ({
|
|
135
|
+
ref: control.ref,
|
|
136
|
+
kind: control.kind,
|
|
137
|
+
name: control.name,
|
|
138
|
+
value: control.value,
|
|
139
|
+
options: control.options ?? [],
|
|
140
|
+
...control.optionCount === void 0 ? {} : { optionCount: control.optionCount },
|
|
141
|
+
...control.disabled === void 0 ? {} : { disabled: control.disabled },
|
|
142
|
+
...control.checked === void 0 ? {} : { checked: control.checked },
|
|
143
|
+
...control.editable === void 0 ? {} : { editable: control.editable }
|
|
144
|
+
})),
|
|
145
|
+
page: {
|
|
146
|
+
title: snapshot.title,
|
|
147
|
+
scrollY: snapshot.scroll.y,
|
|
148
|
+
viewportHeight: snapshot.viewport.height,
|
|
149
|
+
documentHeight: snapshot.scroll.height
|
|
150
|
+
},
|
|
151
|
+
truncated: snapshot.truncated,
|
|
152
|
+
...extra.tabs === void 0 ? {} : { tabs: extra.tabs }
|
|
153
|
+
});
|
|
154
|
+
/** The tabs the controller follows in a browser: which one is current, and a stable ref for each. */
|
|
155
|
+
const following = (browser, follow$1, initial) => Effect.gen(function* () {
|
|
156
|
+
let state = initial ?? make$1((yield* browser.pages).map((tab) => tab.id));
|
|
157
|
+
const become = (tab) => Effect.gen(function* () {
|
|
158
|
+
if (follow$1 === "front" && state.shown !== void 0 && tab.id !== state.shown) yield* tab.bringToFront;
|
|
159
|
+
state = new Tabs({
|
|
160
|
+
...state,
|
|
161
|
+
shown: tab.id
|
|
162
|
+
});
|
|
163
|
+
return tab;
|
|
164
|
+
});
|
|
165
|
+
const look = Effect.gen(function* () {
|
|
166
|
+
const open = yield* browser.pages;
|
|
167
|
+
const next = follow(state, open.map((tab) => tab.id), follow$1);
|
|
168
|
+
const tab = open.find((tab) => tab.id === next.selected) ?? (yield* browser.firstPage);
|
|
169
|
+
yield* become(tab);
|
|
170
|
+
state = next.state;
|
|
171
|
+
return tab;
|
|
172
|
+
});
|
|
173
|
+
const tabs = Effect.gen(function* () {
|
|
174
|
+
const open = yield* browser.pages;
|
|
175
|
+
state = new Tabs({
|
|
176
|
+
...state,
|
|
177
|
+
refs: follow(state, open.map((tab) => tab.id), "never").state.refs
|
|
178
|
+
});
|
|
179
|
+
return yield* Effect.forEach(open, (tab) => {
|
|
180
|
+
const ref = state.refs[tab.id];
|
|
181
|
+
if (ref === void 0) return Effect.die("registered tab is missing its stable ref");
|
|
182
|
+
return Effect.map(tab.url, (url) => ({
|
|
183
|
+
ref,
|
|
184
|
+
url: url.startsWith("data:") ? "data:" : url,
|
|
185
|
+
active: tab.id === state.shown
|
|
186
|
+
}));
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
const select = (ref) => Effect.gen(function* () {
|
|
190
|
+
const open = yield* browser.pages;
|
|
191
|
+
const id = selected(state, open.map((tab) => tab.id), ref);
|
|
192
|
+
const tab = open.find((tab) => tab.id === id);
|
|
193
|
+
if (tab === void 0) return Option.none();
|
|
194
|
+
state = new Tabs({
|
|
195
|
+
...state,
|
|
196
|
+
seen: [.../* @__PURE__ */ new Set([...state.seen, tab.id])]
|
|
197
|
+
});
|
|
198
|
+
return Option.some(yield* become(tab));
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
current: Effect.suspend(() => state.shown === void 0 ? look : Effect.flatMap(browser.page(state.shown), Option.match({
|
|
202
|
+
onNone: () => look,
|
|
203
|
+
onSome: Effect.succeed
|
|
204
|
+
}))),
|
|
205
|
+
look,
|
|
206
|
+
tabs,
|
|
207
|
+
select
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
/** The outline's lines that are gone from `before` and new in `after`, as often as each repeats. */
|
|
211
|
+
const changed = (before, after) => {
|
|
212
|
+
const left = /* @__PURE__ */ new Map();
|
|
213
|
+
const take = (line) => {
|
|
214
|
+
const count = left.get(line) ?? 0;
|
|
215
|
+
left.set(line, count - 1);
|
|
216
|
+
return count > 0;
|
|
217
|
+
};
|
|
218
|
+
for (const line of before) left.set(line, (left.get(line) ?? 0) + 1);
|
|
219
|
+
const added = after.filter((line) => !take(line));
|
|
220
|
+
return {
|
|
221
|
+
gone: before.filter(take),
|
|
222
|
+
added
|
|
223
|
+
};
|
|
224
|
+
};
|
|
225
|
+
/** A snapshot whose outline is only what changed since `before`, or itself when that is longer. */
|
|
226
|
+
const changesOf = (snapshot, before) => {
|
|
227
|
+
const lines = snapshot.text.split("\n");
|
|
228
|
+
const { gone, added } = changed(before.split("\n"), lines);
|
|
229
|
+
if (gone.length + added.length >= lines.length) return snapshot;
|
|
230
|
+
const text = [
|
|
231
|
+
"Only what changed in the outline since the last observation:",
|
|
232
|
+
...gone.length + added.length === 0 ? ["(nothing)"] : [],
|
|
233
|
+
...gone.length === 0 ? [] : ["No longer shown:", ...gone],
|
|
234
|
+
...added.length === 0 ? [] : ["Newly shown:", ...added]
|
|
235
|
+
].join("\n");
|
|
236
|
+
return new Snapshot({
|
|
237
|
+
...snapshot,
|
|
238
|
+
text,
|
|
239
|
+
controls: snapshot.controls.filter((control) => text.includes(`[ref=${control.ref}]`))
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
const session = Effect.fnUntraced(function* (target, options) {
|
|
243
|
+
const maxChars = options.maxChars ?? 8e3;
|
|
244
|
+
const { current, look, tabs } = "page" in target ? {
|
|
245
|
+
current: Effect.succeed(target.page),
|
|
246
|
+
look: Effect.succeed(target.page),
|
|
247
|
+
tabs: void 0
|
|
248
|
+
} : yield* Effect.map(following(target.browser, target.follow ?? "select", options.initialTabs), (followed) => ({
|
|
249
|
+
current: followed.current,
|
|
250
|
+
look: followed.look,
|
|
251
|
+
tabs: followed
|
|
252
|
+
}));
|
|
253
|
+
const recording = /* @__PURE__ */ new Set();
|
|
254
|
+
const record = (page) => recording.has(page.id) ? Effect.succeed([]) : read$1(page).pipe(Effect.andThen(Effect.sync(() => recording.add(page.id))), Effect.as([]), Effect.catch((error) => Effect.succeed([`What changes on this page cannot be recorded yet: ${error.message}.`])));
|
|
255
|
+
const whole = /* @__PURE__ */ new Map();
|
|
256
|
+
const outlined = (page, scope) => Effect.map(read(page, {
|
|
257
|
+
maxChars,
|
|
258
|
+
within: scope.within,
|
|
259
|
+
...scope.query === void 0 ? {} : {
|
|
260
|
+
full: true,
|
|
261
|
+
query: scope.query
|
|
262
|
+
},
|
|
263
|
+
boxes: options.boxes
|
|
264
|
+
}), (snapshot) => {
|
|
265
|
+
if (options.changes !== true || scope.within !== void 0 || scope.query !== void 0) return snapshot;
|
|
266
|
+
const before = whole.get(page.id);
|
|
267
|
+
whole.set(page.id, {
|
|
268
|
+
url: snapshot.url,
|
|
269
|
+
text: snapshot.text
|
|
270
|
+
});
|
|
271
|
+
return scope.changes === true && before?.url === snapshot.url ? changesOf(snapshot, before.text) : snapshot;
|
|
272
|
+
});
|
|
273
|
+
const read$2 = (page, scope = {}, lines = []) => Effect.all([
|
|
274
|
+
outlined(page, scope),
|
|
275
|
+
tabs?.tabs ?? Effect.void,
|
|
276
|
+
record(page)
|
|
277
|
+
], { concurrency: "unbounded" }).pipe(Effect.map(([snapshot, open, unrecorded]) => observation(snapshot, {
|
|
278
|
+
followed: [...lines, ...unrecorded],
|
|
279
|
+
tabs: open === void 0 ? void 0 : open
|
|
280
|
+
})));
|
|
281
|
+
return {
|
|
282
|
+
current,
|
|
283
|
+
look,
|
|
284
|
+
read: read$2,
|
|
285
|
+
tabs,
|
|
286
|
+
withTask: (effect) => options.task === void 0 ? effect : Effect.provideService(effect, Task, options.task),
|
|
287
|
+
maxWait: millisOf(options.maxWait ?? Duration.seconds(5))
|
|
288
|
+
};
|
|
289
|
+
});
|
|
290
|
+
/**
|
|
291
|
+
* Run actions in order on the current tab, stopping at the first failure, then look at the page,
|
|
292
|
+
* which follows a tab they opened. Acknowledged actions are counted even if the look fails.
|
|
293
|
+
*/
|
|
294
|
+
const acting = ({ current, look, read, withTask }) => (steps, observe) => Effect.gen(function* () {
|
|
295
|
+
const page = yield* current;
|
|
296
|
+
const since = (yield* page.state).at;
|
|
297
|
+
let completed = 0;
|
|
298
|
+
let failure;
|
|
299
|
+
for (const step of steps) {
|
|
300
|
+
const done = yield* Effect.result(step(page));
|
|
301
|
+
if (Result.isFailure(done)) {
|
|
302
|
+
failure = done.failure;
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
completed += 1;
|
|
306
|
+
}
|
|
307
|
+
const dispatch = failure === void 0 ? "acknowledged" : dispatchOf(failure);
|
|
308
|
+
const lines = yield* followed(page, since);
|
|
309
|
+
const error = failure === void 0 ? null : told(failure);
|
|
310
|
+
if (!observe) return {
|
|
311
|
+
completed,
|
|
312
|
+
error,
|
|
313
|
+
observation: null,
|
|
314
|
+
dispatch
|
|
315
|
+
};
|
|
316
|
+
const seen = yield* Effect.result(Effect.flatMap(look, (next) => read(next, { changes: true }, lines)));
|
|
317
|
+
return {
|
|
318
|
+
completed,
|
|
319
|
+
error: error ?? (Result.isFailure(seen) ? `Done, but the page could not be read after it: ${told(seen.failure)}` : null),
|
|
320
|
+
observation: Result.getOrNull(seen),
|
|
321
|
+
dispatch
|
|
322
|
+
};
|
|
323
|
+
}).pipe(Effect.mapError(fromBrowserError), withTask);
|
|
324
|
+
const action = (step) => (page) => {
|
|
325
|
+
switch (step.kind) {
|
|
326
|
+
case "click": return page.perform({
|
|
327
|
+
_tag: "Click",
|
|
328
|
+
target: step.ref
|
|
329
|
+
});
|
|
330
|
+
case "fill": return page.perform({
|
|
331
|
+
_tag: "Type",
|
|
332
|
+
text: step.value,
|
|
333
|
+
options: { into: step.ref }
|
|
334
|
+
});
|
|
335
|
+
case "select": return page.perform({
|
|
336
|
+
_tag: "Select",
|
|
337
|
+
ref: step.ref,
|
|
338
|
+
values: [step.value]
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
const frameless = (operation) => invalid(`Frames are read inline here and none is listed: ${operation} without frame.`);
|
|
343
|
+
/** A condition wait, ending at the run's bound with the page as it is. */
|
|
344
|
+
const waiting = ({ current, read, withTask, maxWait }) => (request) => {
|
|
345
|
+
if (request.frame !== void 0) return frameless("wait");
|
|
346
|
+
if (request.state === "text" && request.text === void 0) return invalid("A wait for text needs the text.");
|
|
347
|
+
const millis = Math.min(request.timeoutMillis, maxWait);
|
|
348
|
+
const state = request.state === "text" ? "visible" : request.state;
|
|
349
|
+
return Effect.gen(function* () {
|
|
350
|
+
const page = yield* current;
|
|
351
|
+
const { met } = yield* until(page, {
|
|
352
|
+
selector: request.selector,
|
|
353
|
+
text: request.text,
|
|
354
|
+
state: state === "enabled" ? "enabled" : "visible"
|
|
355
|
+
}, state === "hidden" ? "none" : "some", millis);
|
|
356
|
+
return yield* read(page, {}, met ? [] : [`The wait ended after ${millis} ms unmet.`]);
|
|
357
|
+
}).pipe(Effect.mapError(fromBrowserError), withTask);
|
|
358
|
+
};
|
|
359
|
+
/** The controller's `control` over the session's current tab. */
|
|
360
|
+
const controlling = (context) => {
|
|
361
|
+
const { look, read, tabs, withTask } = context;
|
|
362
|
+
const act = acting(context);
|
|
363
|
+
return {
|
|
364
|
+
find: ({ text }) => Effect.flatMap(look, (page) => read(page, { query: text })).pipe(Effect.mapError(fromBrowserError), withTask),
|
|
365
|
+
inspect: ({ selector, frame, optionFilter }) => frame !== void 0 ? frameless("inspect") : Effect.flatMap(look, (page) => read(page, { within: selector })).pipe(Effect.map((seen) => optionFilter === void 0 ? seen : filterOptions(seen, optionFilter)), Effect.mapError(fromBrowserError), withTask),
|
|
366
|
+
navigate: ({ url }) => act([(page) => Effect.flatMap(destination("navigate", url), (address) => page.goto(address))], true),
|
|
367
|
+
scroll: ({ ref, deltaX, deltaY }) => act([(page) => page.scroll({
|
|
368
|
+
at: ref,
|
|
369
|
+
dx: deltaX,
|
|
370
|
+
dy: deltaY
|
|
371
|
+
})], true),
|
|
372
|
+
wait: waiting(context),
|
|
373
|
+
press: ({ ref, key }) => act([(page) => page.press(key, { on: ref })], true),
|
|
374
|
+
selectTab: ({ ref }) => tabs === void 0 ? invalid("These tools are pinned to one tab.") : tabs.select(ref).pipe(Effect.mapError(fromBrowserError), Effect.flatMap(Option.match({
|
|
375
|
+
onNone: () => invalid(`${ref} is not an open tab; observe for the current tabs.`),
|
|
376
|
+
onSome: (page) => read(page).pipe(Effect.mapError(fromBrowserError))
|
|
377
|
+
})), withTask)
|
|
378
|
+
};
|
|
379
|
+
};
|
|
380
|
+
/**
|
|
381
|
+
* The controller over `target`, and the tab it acts on.
|
|
382
|
+
*
|
|
383
|
+
* @stability stable
|
|
384
|
+
* @category constructors
|
|
385
|
+
* @since 0.3.0
|
|
386
|
+
*/
|
|
387
|
+
const make = Effect.fnUntraced(function* (target, options = {}) {
|
|
388
|
+
const context = yield* session(target, options);
|
|
389
|
+
const { current, look, read, withTask } = context;
|
|
390
|
+
const act = acting(context);
|
|
391
|
+
const actions = {
|
|
392
|
+
observe: Effect.flatMap(look, (page) => read(page)).pipe(Effect.mapError(fromBrowserError), withTask),
|
|
393
|
+
act: (steps, actOptions = {}) => act(steps.map(action), actOptions.observe ?? true)
|
|
394
|
+
};
|
|
395
|
+
const perform = (run) => Effect.gen(function* () {
|
|
396
|
+
const page = yield* current;
|
|
397
|
+
const since = (yield* page.state).at;
|
|
398
|
+
return {
|
|
399
|
+
value: yield* run(page),
|
|
400
|
+
followed: yield* followed(page, since)
|
|
401
|
+
};
|
|
402
|
+
}).pipe(withTask);
|
|
403
|
+
return {
|
|
404
|
+
actions,
|
|
405
|
+
control: controlling(context),
|
|
406
|
+
current,
|
|
407
|
+
look,
|
|
408
|
+
perform,
|
|
409
|
+
withTask
|
|
410
|
+
};
|
|
411
|
+
});
|
|
412
|
+
/** A select's options narrowed to those whose label holds `filter`, keeping its chosen value. */
|
|
413
|
+
const filterOptions = (seen, filter) => {
|
|
414
|
+
const wanted = filter.toLowerCase();
|
|
415
|
+
return {
|
|
416
|
+
...seen,
|
|
417
|
+
controls: seen.controls.map((control) => control.options.length === 0 ? control : {
|
|
418
|
+
...control,
|
|
419
|
+
options: control.options.filter((option) => option.toLowerCase().includes(wanted) || option === control.value)
|
|
420
|
+
})
|
|
421
|
+
};
|
|
422
|
+
};
|
|
423
|
+
//#endregion
|
|
424
|
+
export { Action, ActionResult, Observation, Ref, make, PageControl_exports as t };
|
|
425
|
+
|
|
426
|
+
//# sourceMappingURL=PageControl.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PageControl.mjs","names":["Tabs.make","follow","Tabs.Tabs","Tabs.follow","Tabs.selected","Snapshot.Snapshot","Change.read","Snapshot.read","read","Policy.Task","Snapshot.until"],"sources":["../../src/ai/PageControl.ts"],"sourcesContent":["/**\n * effect-browser pages as the controller `BrowserTools` serves: `actions`, which observe a page and\n * act on the refs it observed, and `control`, which inspects, navigates, scrolls, waits, presses\n * keys and selects tabs. Their observations and results are this module's schemas, and they fail\n * with `ToolError`. Yielded Agent defined them as its `BrowserActions` and `BrowserControl` ports\n * until 0.1.0-beta.174 replaced those with Code Mode over CDP; they keep the shapes they had there.\n *\n * Over a `page`, the controller is pinned to it: it lists no tabs, and a tab the page opens stays\n * where it is. Over a `browser`, it acts on the tab the model last saw and lists the others as tabs\n * it may select. A tab an action opens is shown at the next look as `follow` says: `\"select\"`, the\n * default, makes it current without bringing it to front, so the page on air and an operator's\n * view stay where they are; `\"front\"` also brings it to front; `\"never\"` keeps the current tab.\n *\n * An observation is the page's outline, with a ref on each control, and the controls as values. One\n * after an action begins with what followed it: a dialog and how the browser answered it, a\n * navigation, a tab it opened and what its input visibly changed. Every action goes through the\n * page's own input policy, with `task` as the user's task its judge reads, and the browser answers\n * dialogs itself. With `changes`, its outline holds only the lines that changed since the tab's last\n * whole look, when those are fewer. An action that failed before its input reached the browser is `not-dispatched`,\n * one that failed after is `possibly-dispatched`, and nothing is ever retried.\n *\n * @stability stable\n * @since 0.3.0\n */\nimport { Duration, Effect, Option, Result, Schema } from \"effect\";\n\nimport type * as Browser from \"../Browser.ts\";\nimport type { BrowserError } from \"../BrowserError.ts\";\nimport * as Change from \"../Change.ts\";\nimport { millisOf } from \"../internal/clock.ts\";\nimport type * as Page from \"../Page.ts\";\nimport * as Policy from \"../policy/Policy.ts\";\nimport * as Snapshot from \"../Snapshot.ts\";\nimport { destination, dispatchOf, followed, told } from \"./internal/receipts.ts\";\nimport * as Tabs from \"./Tabs.ts\";\nimport { fromBrowserError, ToolError } from \"./ToolError.ts\";\n\n/**\n * A control's ref in an observation, such as `e12`.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const Ref = Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9-]{0,50}$/));\n\n/**\n * An action on an observed control.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const Action = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"click\"), ref: Ref }),\n Schema.Struct({\n kind: Schema.Literal(\"fill\"),\n ref: Ref,\n value: Schema.String.check(Schema.isMaxLength(64 * 1024)),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"select\"),\n ref: Ref,\n value: Schema.String.check(Schema.isMaxLength(4_096)),\n }),\n]);\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Action = typeof Action.Type;\n\n/** A control as an observation lists it. */\nconst Control = Schema.Struct({\n ref: Ref,\n kind: Schema.String,\n name: Schema.String,\n value: Schema.String,\n options: Schema.Array(Schema.String),\n optionCount: Schema.optionalKey(Schema.Natural),\n disabled: Schema.optionalKey(Schema.Boolean),\n checked: Schema.optionalKey(Schema.Boolean),\n editable: Schema.optionalKey(Schema.Boolean),\n});\n\n/**\n * The page's outline and its controls, where the page is scrolled, and a browser's tabs.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const Observation = Schema.Struct({\n text: Schema.String,\n controls: Schema.Array(Control),\n page: Schema.Struct({\n title: Schema.String,\n scrollY: Schema.Finite,\n viewportHeight: Schema.Finite,\n documentHeight: Schema.Finite,\n }),\n truncated: Schema.Boolean,\n tabs: Schema.optionalKey(\n Schema.Array(Schema.Struct({ ref: Ref, url: Schema.String, active: Schema.Boolean })),\n ),\n});\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Observation = typeof Observation.Type;\n\nconst Dispatch = Schema.Literals([\"not-dispatched\", \"acknowledged\", \"possibly-dispatched\"]);\n\ntype Dispatch = typeof Dispatch.Type;\n\n/**\n * What actions did: how many completed, the first one's failure, the page after them unless the\n * caller asked not to look, and whether the input reached the browser. Never replay an input\n * whose dispatch is not `not-dispatched`.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const ActionResult = Schema.Struct({\n completed: Schema.Natural,\n error: Schema.NullOr(Schema.String),\n observation: Schema.NullOr(Observation),\n dispatch: Dispatch,\n});\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type ActionResult = typeof ActionResult.Type;\n\n/** What `control.wait` waits for, as the `wait` tool takes it. */\ninterface WaitRequest {\n readonly selector: string;\n readonly frame?: string | undefined;\n readonly state: \"visible\" | \"hidden\" | \"enabled\" | \"text\";\n readonly text?: string | undefined;\n readonly timeoutMillis: number;\n}\n\n/**\n * What the controller does when a tab opens: see the module's comment.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Follow = \"select\" | \"front\" | \"never\";\n\n/**\n * What the controller acts on: one page, or a browser's tabs.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Target =\n | { readonly page: Page.Page }\n | { readonly browser: Browser.Service; readonly follow?: Follow | undefined };\n\n/**\n * @stability stable\n * @category options\n * @since 0.3.0\n */\nexport interface Options {\n /** The user's task, which the input policy's judge reads as what authorizes a risky input. */\n readonly task?: string | undefined;\n /** Resume stable tab identities from a prior finished adapter state. */\n readonly initialTabs?: Tabs.Tabs | undefined;\n /** Bound on an observation's outline, in characters. Defaults to 8,000. */\n readonly maxChars?: number | undefined;\n /** Bound on a condition wait. Defaults to 5 seconds; an unmet wait returns the page as it is. */\n readonly maxWait?: Duration.Input | undefined;\n /** Give every control's box in the outline, as `WxH at (x,y)` in viewport CSS pixels. */\n readonly boxes?: boolean | undefined;\n /**\n * After an action, give only the outline's lines that are gone and new since the tab's last whole\n * look, when they are fewer than its lines. Defaults to false.\n */\n readonly changes?: boolean | undefined;\n}\n\ntype Failing<A> = Effect.Effect<A, ToolError>;\n\n/**\n * The controller, and the tab it acts on, which `BrowserTools` shares.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Controller {\n readonly actions: {\n readonly observe: Failing<Observation>;\n /** Act in order, stopping at the first failure; `observe: false` skips the look after. */\n readonly act: (\n actions: ReadonlyArray<Action>,\n options?: { readonly observe?: boolean | undefined },\n ) => Failing<ActionResult>;\n };\n readonly control: {\n /** The whole page's outline lines that hold `text`, ignoring case. */\n readonly find: (request: { readonly text: string }) => Failing<Observation>;\n readonly inspect: (request: {\n readonly selector?: string | undefined;\n readonly frame?: string | undefined;\n readonly optionFilter?: string | undefined;\n }) => Failing<Observation>;\n readonly navigate: (request: { readonly url: string }) => Failing<ActionResult>;\n readonly scroll: (request: {\n readonly ref?: string | undefined;\n readonly deltaX: number;\n readonly deltaY: number;\n }) => Failing<ActionResult>;\n readonly wait: (request: WaitRequest) => Failing<Observation>;\n readonly press: (request: {\n readonly ref: string;\n readonly key: string;\n }) => Failing<ActionResult>;\n readonly selectTab: (request: { readonly ref: string }) => Failing<Observation>;\n };\n /** The tab calls act on now: the pinned page, or the one the model last saw. */\n readonly current: Effect.Effect<Page.Page, BrowserError>;\n /** The current tab as a look finds it, following a tab an action opened. */\n readonly look: Effect.Effect<Page.Page, BrowserError>;\n /** Run `run` on the current tab with the task, and say what followed it there. */\n readonly perform: <A>(\n run: (page: Page.Page) => Effect.Effect<A, BrowserError>,\n ) => Effect.Effect<{ readonly value: A; readonly followed: ReadonlyArray<string> }, BrowserError>;\n /** Give `effect` the run's task, for the input policy's judge. */\n readonly withTask: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n}\n\nconst invalid = (message: string) => Effect.fail(new ToolError({ code: \"invalid\", message }));\n\n/** A snapshot as an observation: the outline, the controls and where the page is. */\nconst observation = (\n snapshot: Snapshot.Snapshot,\n extra: { readonly followed?: ReadonlyArray<string>; readonly tabs?: Observation[\"tabs\"] },\n): Observation => ({\n text: [...(extra.followed ?? []), snapshot.rendered].join(\"\\n\"),\n // An observation's controls leave out what a control does not have, rather than state it undefined.\n controls: snapshot.controls.map((control) => ({\n ref: control.ref,\n kind: control.kind,\n name: control.name,\n value: control.value,\n options: control.options ?? [],\n ...(control.optionCount === undefined ? {} : { optionCount: control.optionCount }),\n ...(control.disabled === undefined ? {} : { disabled: control.disabled }),\n ...(control.checked === undefined ? {} : { checked: control.checked }),\n ...(control.editable === undefined ? {} : { editable: control.editable }),\n })),\n page: {\n title: snapshot.title,\n scrollY: snapshot.scroll.y,\n viewportHeight: snapshot.viewport.height,\n documentHeight: snapshot.scroll.height,\n },\n truncated: snapshot.truncated,\n ...(extra.tabs === undefined ? {} : { tabs: extra.tabs }),\n});\n\n/** The tabs the controller follows in a browser: which one is current, and a stable ref for each. */\nconst following = (browser: Browser.Service, follow: Follow, initial?: Tabs.Tabs) =>\n Effect.gen(function* () {\n let state = initial ?? Tabs.make((yield* browser.pages).map((tab) => tab.id));\n\n const become = (tab: Page.Page) =>\n Effect.gen(function* () {\n if (follow === \"front\" && state.shown !== undefined && tab.id !== state.shown)\n yield* tab.bringToFront;\n state = new Tabs.Tabs({ ...state, shown: tab.id });\n\n return tab;\n });\n\n const look = Effect.gen(function* () {\n const open = yield* browser.pages;\n\n const next = Tabs.follow(\n state,\n open.map((tab) => tab.id),\n follow,\n );\n\n const tab = open.find((tab) => tab.id === next.selected) ?? (yield* browser.firstPage);\n\n yield* become(tab);\n state = next.state;\n\n return tab;\n });\n\n const tabs = Effect.gen(function* () {\n const open = yield* browser.pages;\n\n state = new Tabs.Tabs({\n ...state,\n refs: Tabs.follow(\n state,\n open.map((tab) => tab.id),\n \"never\",\n ).state.refs,\n });\n\n return yield* Effect.forEach(open, (tab) => {\n const ref = state.refs[tab.id];\n\n if (ref === undefined) return Effect.die(\"registered tab is missing its stable ref\");\n\n return Effect.map(tab.url, (url) => ({\n ref,\n url: url.startsWith(\"data:\") ? \"data:\" : url,\n active: tab.id === state.shown,\n }));\n });\n });\n\n const select = (ref: string) =>\n Effect.gen(function* () {\n const open = yield* browser.pages;\n\n const id = Tabs.selected(\n state,\n open.map((tab) => tab.id),\n ref,\n );\n\n const tab = open.find((tab) => tab.id === id);\n\n if (tab === undefined) return Option.none<Page.Page>();\n state = new Tabs.Tabs({ ...state, seen: [...new Set([...state.seen, tab.id])] });\n\n return Option.some(yield* become(tab));\n });\n\n return {\n current: Effect.suspend(() =>\n state.shown === undefined\n ? look\n : Effect.flatMap(\n browser.page(state.shown),\n Option.match({ onNone: () => look, onSome: Effect.succeed }),\n ),\n ),\n look,\n tabs,\n select,\n };\n });\n\n/**\n * What of a page a read outlines: what is inside `within`, the lines of the whole page that hold\n * `query`, or the viewport, which after an action may be only its `changes`.\n */\ninterface Scope {\n readonly within?: string | undefined;\n readonly query?: string | undefined;\n readonly changes?: boolean | undefined;\n}\n\n/** The outline's lines that are gone from `before` and new in `after`, as often as each repeats. */\nconst changed = (before: ReadonlyArray<string>, after: ReadonlyArray<string>) => {\n const left = new Map<string, number>();\n\n const take = (line: string) => {\n const count = left.get(line) ?? 0;\n\n left.set(line, count - 1);\n\n return count > 0;\n };\n\n for (const line of before) left.set(line, (left.get(line) ?? 0) + 1);\n const added = after.filter((line) => !take(line));\n\n return { gone: before.filter(take), added };\n};\n\n/** A snapshot whose outline is only what changed since `before`, or itself when that is longer. */\nconst changesOf = (snapshot: Snapshot.Snapshot, before: string) => {\n const lines = snapshot.text.split(\"\\n\");\n const { gone, added } = changed(before.split(\"\\n\"), lines);\n\n if (gone.length + added.length >= lines.length) return snapshot;\n\n const text = [\n \"Only what changed in the outline since the last observation:\",\n ...(gone.length + added.length === 0 ? [\"(nothing)\"] : []),\n ...(gone.length === 0 ? [] : [\"No longer shown:\", ...gone]),\n ...(added.length === 0 ? [] : [\"Newly shown:\", ...added]),\n ].join(\"\\n\");\n\n return new Snapshot.Snapshot({\n ...snapshot,\n text,\n controls: snapshot.controls.filter((control) => text.includes(`[ref=${control.ref}]`)),\n });\n};\n\n/** What the controller's parts share: the tab they act on, how they read it, and the run's task. */\ninterface Session {\n readonly current: Effect.Effect<Page.Page, BrowserError>;\n /** The current tab, following a tab an action opened; the pinned page is always the one. */\n readonly look: Effect.Effect<Page.Page, BrowserError>;\n readonly read: (\n page: Page.Page,\n scope?: Scope,\n lines?: ReadonlyArray<string>,\n ) => Effect.Effect<Observation, BrowserError>;\n readonly tabs: Effect.Success<ReturnType<typeof following>> | undefined;\n readonly withTask: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n readonly maxWait: number;\n}\n\nconst session = Effect.fnUntraced(function* (target: Target, options: Options) {\n const maxChars = options.maxChars ?? 8000;\n\n // A look follows a tab an action opened; the pinned page is always the one.\n const { current, look, tabs } =\n \"page\" in target\n ? { current: Effect.succeed(target.page), look: Effect.succeed(target.page), tabs: undefined }\n : yield* Effect.map(\n following(target.browser, target.follow ?? \"select\", options.initialTabs),\n (followed) => ({\n current: followed.current,\n look: followed.look,\n tabs: followed,\n }),\n );\n\n // The pages whose changes are recorded, from their first look, so the receipt of the first\n // action on one can say what it changed. A page whose record could not start says so, and the\n // next look tries again.\n const recording = new Set<string>();\n\n const record = (page: Page.Page) =>\n recording.has(page.id)\n ? Effect.succeed([])\n : Change.read(page).pipe(\n Effect.andThen(Effect.sync(() => recording.add(page.id))),\n Effect.as([]),\n Effect.catch((error) =>\n Effect.succeed([`What changes on this page cannot be recorded yet: ${error.message}.`]),\n ),\n );\n\n // Each tab's last whole outline, with its address, which an action's changes are taken against.\n const whole = new Map<string, { readonly url: string; readonly text: string }>();\n\n const outlined = (page: Page.Page, scope: Scope) =>\n Effect.map(\n Snapshot.read(page, {\n maxChars,\n within: scope.within,\n ...(scope.query === undefined ? {} : { full: true, query: scope.query }),\n boxes: options.boxes,\n }),\n (snapshot) => {\n if (options.changes !== true || scope.within !== undefined || scope.query !== undefined)\n return snapshot;\n const before = whole.get(page.id);\n\n whole.set(page.id, { url: snapshot.url, text: snapshot.text });\n\n return scope.changes === true && before?.url === snapshot.url\n ? changesOf(snapshot, before.text)\n : snapshot;\n },\n );\n\n const read = (page: Page.Page, scope: Scope = {}, lines: ReadonlyArray<string> = []) =>\n Effect.all([outlined(page, scope), tabs?.tabs ?? Effect.void, record(page)], {\n concurrency: \"unbounded\",\n }).pipe(\n Effect.map(([snapshot, open, unrecorded]) =>\n observation(snapshot, {\n followed: [...lines, ...unrecorded],\n tabs: open === undefined ? undefined : open,\n }),\n ),\n );\n\n return {\n current,\n look,\n read,\n tabs,\n withTask: <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n options.task === undefined\n ? effect\n : Effect.provideService(effect, Policy.Task, options.task),\n maxWait: millisOf(options.maxWait ?? Duration.seconds(5)),\n } satisfies Session;\n});\n\n/**\n * Run actions in order on the current tab, stopping at the first failure, then look at the page,\n * which follows a tab they opened. Acknowledged actions are counted even if the look fails.\n */\nconst acting =\n ({ current, look, read, withTask }: Session) =>\n (\n steps: ReadonlyArray<(page: Page.Page) => Effect.Effect<unknown, BrowserError>>,\n observe: boolean,\n ): Effect.Effect<ActionResult, ToolError> =>\n Effect.gen(function* () {\n const page = yield* current;\n const since = (yield* page.state).at;\n let completed = 0;\n let failure: BrowserError | undefined;\n\n for (const step of steps) {\n const done = yield* Effect.result(step(page));\n\n if (Result.isFailure(done)) {\n failure = done.failure;\n break;\n }\n completed += 1;\n }\n const dispatch: Dispatch = failure === undefined ? \"acknowledged\" : dispatchOf(failure);\n const lines = yield* followed(page, since);\n const error = failure === undefined ? null : told(failure);\n\n if (!observe) return { completed, error, observation: null, dispatch };\n\n const seen = yield* Effect.result(\n Effect.flatMap(look, (next) => read(next, { changes: true }, lines)),\n );\n\n return {\n completed,\n error:\n error ??\n (Result.isFailure(seen)\n ? `Done, but the page could not be read after it: ${told(seen.failure)}`\n : null),\n observation: Result.getOrNull(seen),\n dispatch,\n };\n }).pipe(Effect.mapError(fromBrowserError), withTask);\n\nconst action = (step: Action) => (page: Page.Page) => {\n switch (step.kind) {\n case \"click\":\n return page.perform({ _tag: \"Click\", target: step.ref });\n case \"fill\":\n return page.perform({ _tag: \"Type\", text: step.value, options: { into: step.ref } });\n case \"select\":\n return page.perform({ _tag: \"Select\", ref: step.ref, values: [step.value] });\n }\n};\n\nconst frameless = (operation: string) =>\n invalid(`Frames are read inline here and none is listed: ${operation} without frame.`);\n\n/** A condition wait, ending at the run's bound with the page as it is. */\nconst waiting =\n ({ current, read, withTask, maxWait }: Session) =>\n (request: WaitRequest) => {\n if (request.frame !== undefined) return frameless(\"wait\");\n if (request.state === \"text\" && request.text === undefined)\n return invalid(\"A wait for text needs the text.\");\n const millis = Math.min(request.timeoutMillis, maxWait);\n const state = request.state === \"text\" ? \"visible\" : request.state;\n\n return Effect.gen(function* () {\n const page = yield* current;\n\n const { met } = yield* Snapshot.until(\n page,\n {\n selector: request.selector,\n text: request.text,\n state: state === \"enabled\" ? \"enabled\" : \"visible\",\n },\n state === \"hidden\" ? \"none\" : \"some\",\n millis,\n );\n\n return yield* read(page, {}, met ? [] : [`The wait ended after ${millis} ms unmet.`]);\n }).pipe(Effect.mapError(fromBrowserError), withTask);\n };\n\n/** The controller's `control` over the session's current tab. */\nconst controlling = (context: Session): Controller[\"control\"] => {\n const { look, read, tabs, withTask } = context;\n const act = acting(context);\n\n return {\n find: ({ text }) =>\n Effect.flatMap(look, (page) => read(page, { query: text })).pipe(\n Effect.mapError(fromBrowserError),\n withTask,\n ),\n inspect: ({ selector, frame, optionFilter }) =>\n frame !== undefined\n ? frameless(\"inspect\")\n : Effect.flatMap(look, (page) => read(page, { within: selector })).pipe(\n Effect.map((seen) =>\n optionFilter === undefined ? seen : filterOptions(seen, optionFilter),\n ),\n Effect.mapError(fromBrowserError),\n withTask,\n ),\n navigate: ({ url }) =>\n act(\n [(page) => Effect.flatMap(destination(\"navigate\", url), (address) => page.goto(address))],\n true,\n ),\n scroll: ({ ref, deltaX, deltaY }) =>\n act([(page) => page.scroll({ at: ref, dx: deltaX, dy: deltaY })], true),\n wait: waiting(context),\n press: ({ ref, key }) => act([(page) => page.press(key, { on: ref })], true),\n selectTab: ({ ref }) =>\n tabs === undefined\n ? invalid(\"These tools are pinned to one tab.\")\n : tabs.select(ref).pipe(\n Effect.mapError(fromBrowserError),\n Effect.flatMap(\n Option.match({\n onNone: () => invalid(`${ref} is not an open tab; observe for the current tabs.`),\n onSome: (page) => read(page).pipe(Effect.mapError(fromBrowserError)),\n }),\n ),\n withTask,\n ),\n };\n};\n\n/**\n * The controller over `target`, and the tab it acts on.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const make = Effect.fnUntraced(function* (target: Target, options: Options = {}) {\n const context = yield* session(target, options);\n const { current, look, read, withTask } = context;\n const act = acting(context);\n\n const actions: Controller[\"actions\"] = {\n observe: Effect.flatMap(look, (page) => read(page)).pipe(\n Effect.mapError(fromBrowserError),\n withTask,\n ),\n act: (steps, actOptions = {}) => act(steps.map(action), actOptions.observe ?? true),\n };\n\n const perform = <A>(run: (page: Page.Page) => Effect.Effect<A, BrowserError>) =>\n Effect.gen(function* () {\n const page = yield* current;\n const since = (yield* page.state).at;\n const value = yield* run(page);\n\n return { value, followed: yield* followed(page, since) };\n }).pipe(withTask);\n\n return {\n actions,\n control: controlling(context),\n current,\n look,\n perform,\n withTask,\n } satisfies Controller;\n});\n\n/** A select's options narrowed to those whose label holds `filter`, keeping its chosen value. */\nconst filterOptions = (seen: Observation, filter: string): Observation => {\n const wanted = filter.toLowerCase();\n\n return {\n ...seen,\n controls: seen.controls.map((control) =>\n control.options.length === 0\n ? control\n : {\n ...control,\n options: control.options.filter(\n (option) => option.toLowerCase().includes(wanted) || option === control.value,\n ),\n },\n ),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,MAAM,OAAO,OAAO,MAA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,OAAO,SAAS,gBAAgB,CAAC;EACrE,CAAC,CACH,GACA,QACF;CACR;AACF;;;;;;;;AASA,MAAa,OAAO,OAAO,WAAW,WAAW,QAAgB,UAAmB,CAAC,GAAG;CACtF,MAAM,UAAU,OAAO,QAAQ,QAAQ,OAAO;CAC9C,MAAM,EAAE,SAAS,MAAM,MAAM,aAAa;CAC1C,MAAM,MAAM,OAAO,OAAO;CAE1B,MAAM,UAAiC;EACrC,SAAS,OAAO,QAAQ,OAAO,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,KAClD,OAAO,SAAS,gBAAgB,GAChC,QACF;EACA,MAAM,OAAO,aAAa,CAAC,MAAM,IAAI,MAAM,IAAI,MAAM,GAAG,WAAW,WAAW,IAAI;CACpF;CAEA,MAAM,WAAc,QAClB,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,OAAO;EACpB,MAAM,SAAS,OAAO,KAAK,MAAA,CAAO;EAGlC,OAAO;GAAE,OAAA,OAFY,IAAI,IAAI;GAEb,UAAU,OAAO,SAAS,MAAM,KAAK;EAAE;CACzD,CAAC,CAAC,CAAC,KAAK,QAAQ;CAElB,OAAO;EACL;EACA,SAAS,YAAY,OAAO;EAC5B;EACA;EACA;EACA;CACF;AACF,CAAC;;AAGD,MAAM,iBAAiB,MAAmB,WAAgC;CACxE,MAAM,SAAS,OAAO,YAAY;CAElC,OAAO;EACL,GAAG;EACH,UAAU,KAAK,SAAS,KAAK,YAC3B,QAAQ,QAAQ,WAAW,IACvB,UACA;GACE,GAAG;GACH,SAAS,QAAQ,QAAQ,QACtB,WAAW,OAAO,YAAY,CAAC,CAAC,SAAS,MAAM,KAAK,WAAW,QAAQ,KAC1E;EACF,CACN;CACF;AACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Layer } from "effect";
|
|
2
|
+
import { HttpClient } from "effect/http";
|
|
3
|
+
declare namespace PromptCache_d_exports {
|
|
4
|
+
export { layer };
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Marks the chat completions sent through the `HttpClient` it is given; other requests pass.
|
|
8
|
+
*
|
|
9
|
+
* @stability stable
|
|
10
|
+
* @category layers
|
|
11
|
+
* @since 0.3.0
|
|
12
|
+
*/
|
|
13
|
+
export declare const layer: Layer.Layer<HttpClient.HttpClient, never, HttpClient.HttpClient>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { PromptCache_d_exports as t };
|
|
16
|
+
//# sourceMappingURL=PromptCache.d.mts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { t as __exportAll } from "../internal/rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { Effect, Layer, Option, Predicate, Schema } from "effect";
|
|
3
|
+
import { HttpBody, HttpClient, HttpClientRequest } from "effect/http";
|
|
4
|
+
//#region src/ai/PromptCache.ts
|
|
5
|
+
/**
|
|
6
|
+
* Prompt caching for OpenRouter chat completions whose turns end in a picture. `BrowserTools` shows
|
|
7
|
+
* the screenshot before a turn as context the next call drops. A provider that caches at
|
|
8
|
+
* breakpoints, as OpenAI's models do on OpenRouter, sets its own at the end of the prompt, inside
|
|
9
|
+
* that picture, so no later call matches it and every call writes the whole conversation again.
|
|
10
|
+
* `layer` marks the end of each request's history instead, with OpenRouter's `cache_control`: its
|
|
11
|
+
* last tool result or, before there is one, its system message. A loop such as Yielded's builds
|
|
12
|
+
* the prompt with no cache options, and `@effect/ai-openrouter` before 4.0.6 drops them on tool results, so the
|
|
13
|
+
* mark is made on the request's JSON, in the HTTP client beneath the OpenRouter client:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* OpenRouterClient.layerConfig({ apiKey }).pipe(
|
|
17
|
+
* Layer.provide(PromptCache.layer),
|
|
18
|
+
* Layer.provide(FetchHttpClient.layer),
|
|
19
|
+
* )
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* @stability stable
|
|
23
|
+
* @since 0.3.0
|
|
24
|
+
*/
|
|
25
|
+
var PromptCache_exports = /* @__PURE__ */ __exportAll({ layer: () => layer });
|
|
26
|
+
const ephemeral = { type: "ephemeral" };
|
|
27
|
+
const marked = (content) => {
|
|
28
|
+
if (typeof content === "string") return [{
|
|
29
|
+
type: "text",
|
|
30
|
+
text: content,
|
|
31
|
+
cache_control: ephemeral
|
|
32
|
+
}];
|
|
33
|
+
if (!Array.isArray(content)) return void 0;
|
|
34
|
+
const last = content.at(-1);
|
|
35
|
+
return Predicate.hasProperty(last, "type") && last.type === "text" ? content.with(-1, {
|
|
36
|
+
...last,
|
|
37
|
+
cache_control: ephemeral
|
|
38
|
+
}) : void 0;
|
|
39
|
+
};
|
|
40
|
+
const markHistory = (messages) => {
|
|
41
|
+
const at = messages.findLastIndex((message) => Predicate.hasProperty(message, "role") && (message.role === "tool" || message.role === "system"));
|
|
42
|
+
const message = messages[at];
|
|
43
|
+
if (!Predicate.hasProperty(message, "content")) return messages;
|
|
44
|
+
const content = marked(message.content);
|
|
45
|
+
return content === void 0 ? messages : messages.with(at, {
|
|
46
|
+
...message,
|
|
47
|
+
content
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
const Completion = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
|
|
51
|
+
/**
|
|
52
|
+
* Marks the chat completions sent through the `HttpClient` it is given; other requests pass.
|
|
53
|
+
*
|
|
54
|
+
* @stability stable
|
|
55
|
+
* @category layers
|
|
56
|
+
* @since 0.3.0
|
|
57
|
+
*/
|
|
58
|
+
const layer = Layer.effect(HttpClient.HttpClient, Effect.map(HttpClient.HttpClient, (http) => HttpClient.mapRequest(http, (request) => {
|
|
59
|
+
const { body } = request;
|
|
60
|
+
if (body._tag !== "Uint8Array" || !request.url.endsWith("/chat/completions")) return request;
|
|
61
|
+
return Option.match(Schema.decodeOption(Completion)(new TextDecoder().decode(body.body)), {
|
|
62
|
+
onNone: () => request,
|
|
63
|
+
onSome: (completion) => Array.isArray(completion["messages"]) ? HttpClientRequest.setBody(request, HttpBody.jsonUnsafe({
|
|
64
|
+
...completion,
|
|
65
|
+
messages: markHistory(completion["messages"])
|
|
66
|
+
})) : request
|
|
67
|
+
});
|
|
68
|
+
})));
|
|
69
|
+
//#endregion
|
|
70
|
+
export { layer, PromptCache_exports as t };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=PromptCache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PromptCache.mjs","names":[],"sources":["../../src/ai/PromptCache.ts"],"sourcesContent":["/**\n * Prompt caching for OpenRouter chat completions whose turns end in a picture. `BrowserTools` shows\n * the screenshot before a turn as context the next call drops. A provider that caches at\n * breakpoints, as OpenAI's models do on OpenRouter, sets its own at the end of the prompt, inside\n * that picture, so no later call matches it and every call writes the whole conversation again.\n * `layer` marks the end of each request's history instead, with OpenRouter's `cache_control`: its\n * last tool result or, before there is one, its system message. A loop such as Yielded's builds\n * the prompt with no cache options, and `@effect/ai-openrouter` before 4.0.6 drops them on tool results, so the\n * mark is made on the request's JSON, in the HTTP client beneath the OpenRouter client:\n *\n * ```ts\n * OpenRouterClient.layerConfig({ apiKey }).pipe(\n * Layer.provide(PromptCache.layer),\n * Layer.provide(FetchHttpClient.layer),\n * )\n * ```\n *\n * @stability stable\n * @since 0.3.0\n */\nimport { Effect, Layer, Option, Predicate, Schema } from \"effect\";\nimport { HttpBody, HttpClient, HttpClientRequest } from \"effect/http\";\n\nconst ephemeral = { type: \"ephemeral\" } as const;\n\n// The content with a breakpoint after its last text, or undefined where it does not end in text.\nconst marked = (content: unknown) => {\n if (typeof content === \"string\")\n return [{ type: \"text\", text: content, cache_control: ephemeral }];\n if (!Array.isArray(content)) return undefined;\n\n const last: unknown = content.at(-1);\n\n return Predicate.hasProperty(last, \"type\") && last.type === \"text\"\n ? content.with(-1, { ...last, cache_control: ephemeral })\n : undefined;\n};\n\nconst markHistory = (messages: ReadonlyArray<unknown>) => {\n const at = messages.findLastIndex(\n (message) =>\n Predicate.hasProperty(message, \"role\") &&\n (message.role === \"tool\" || message.role === \"system\"),\n );\n\n const message = messages[at];\n\n if (!Predicate.hasProperty(message, \"content\")) return messages;\n\n const content = marked(message.content);\n\n return content === undefined ? messages : messages.with(at, { ...message, content });\n};\n\nconst Completion = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));\n\n/**\n * Marks the chat completions sent through the `HttpClient` it is given; other requests pass.\n *\n * @stability stable\n * @category layers\n * @since 0.3.0\n */\nexport const layer: Layer.Layer<HttpClient.HttpClient, never, HttpClient.HttpClient> = Layer.effect(\n HttpClient.HttpClient,\n Effect.map(HttpClient.HttpClient, (http) =>\n HttpClient.mapRequest(http, (request) => {\n const { body } = request;\n\n if (body._tag !== \"Uint8Array\" || !request.url.endsWith(\"/chat/completions\")) return request;\n\n return Option.match(Schema.decodeOption(Completion)(new TextDecoder().decode(body.body)), {\n onNone: () => request,\n onSome: (completion) =>\n Array.isArray(completion[\"messages\"])\n ? HttpClientRequest.setBody(\n request,\n HttpBody.jsonUnsafe({\n ...completion,\n messages: markHistory(completion[\"messages\"]),\n }),\n )\n : request,\n });\n }),\n ),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,YAAY,EAAE,MAAM,YAAY;AAGtC,MAAM,UAAU,YAAqB;CACnC,IAAI,OAAO,YAAY,UACrB,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAS,eAAe;CAAU,CAAC;CACnE,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAA;CAEpC,MAAM,OAAgB,QAAQ,GAAG,EAAE;CAEnC,OAAO,UAAU,YAAY,MAAM,MAAM,KAAK,KAAK,SAAS,SACxD,QAAQ,KAAK,IAAI;EAAE,GAAG;EAAM,eAAe;CAAU,CAAC,IACtD,KAAA;AACN;AAEA,MAAM,eAAe,aAAqC;CACxD,MAAM,KAAK,SAAS,eACjB,YACC,UAAU,YAAY,SAAS,MAAM,MACpC,QAAQ,SAAS,UAAU,QAAQ,SAAS,SACjD;CAEA,M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