@abubakarsiddiik/substrate 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ # @abubakarsiddiik/substrate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The four-method browser adapter. It is the only place the runtime touches a
4
+ rendering engine.
5
+
6
+ ```ts
7
+ const engine = await PlaywrightEngine.launch({ executablePath });
8
+ await engine.navigate(url);
9
+ const snapshot = await engine.snapshot(); // raw accessibility tree
10
+ await engine.dispatch({ do: "click", backendNodeId });
11
+ await engine.evaluate<string>("document.title");
12
+ await engine.close();
13
+ ```
14
+
15
+ ## Methods
16
+
17
+ | Method | Returns |
18
+ |---|---|
19
+ | `navigate(url)` | `{ url, title, status }` |
20
+ | `snapshot()` | `{ url, title, nodes }`, each node with role, name, bounds, and visibility |
21
+ | `dispatch(action)` | `{ ok, url, title }` for click / fill / select / check / uncheck / press |
22
+ | `evaluate(expression)` | the page's value |
23
+ | `close()` | idempotent |
24
+
25
+ `dispatch` takes a CDP `backendNodeId`, which `snapshot` provides on every node
26
+ that has a DOM counterpart. Clicks use a real mouse event at the centre of the
27
+ node's client rect; fills focus the node and insert text; selects and checkbox
28
+ toggles go through the element's own setters and dispatch `input` and `change`.
29
+
30
+ ## Chrome
31
+
32
+ `playwright-core` does not download a browser. Set `CHROME_PATH`, or the adapter
33
+ looks in the usual macOS and Linux locations. `findChrome()` returns `undefined`
34
+ when none is installed, and the contract tests skip.
35
+
36
+ `snapshot` merges `Accessibility.getFullAXTree` with
37
+ `DOMSnapshot.captureSnapshot`: role and name come from the accessibility
38
+ tree, bounds and computed style from the DOM snapshot, joined on
39
+ `backendNodeId`. A node is `visible` only when it is not ignored, has a
40
+ non-zero box, and is not `display: none`, `visibility: hidden`, or
41
+ `opacity: 0`.
42
+
43
+ ## Affordances
44
+
45
+ `rankAffordances(nodes)` filters the capture to visible, actionable,
46
+ measurable nodes, adds the nearest named ancestor or landmark as `ctx`, and
47
+ ranks by role weight, name presence, and document order. `renderAffordances`
48
+ fits the list into a token budget (default 800) and reports what it dropped.
49
+
50
+ The fixture tests capture every page the benchmark tasks touch — store
51
+ catalog and product, all three wizard steps, portal login and ledger — and
52
+ assert the required interactions are present within the budget.
53
+
54
+ ## Refs
55
+
56
+ `buildRefMap(nodes, doc)` assigns each node a document-scoped ref: `e` plus a
57
+ base36 hash of `role|name|framePath|ordinal`. Collisions extend the prefix by
58
+ one character until unique.
59
+
60
+ `RefRegistry` keeps the current and previous maps, so a missing ref resolves to
61
+ `stale_ref` with the current document and, when role and name still match, a
62
+ `new_ref`. A ref is only valid for the document that produced it;
63
+ `snapshot.doc` increments on every committed main-frame navigation.
64
+
65
+ ## Act
66
+
67
+ `Substrate` composes capture and refs into the two fallback verbs:
68
+
69
+ ```ts
70
+ const { refs } = await substrate.view();
71
+ await substrate.act({ ref, do: "fill", value: "tee" });
72
+ await substrate.act({ ref, do: "click" });
73
+ ```
74
+
75
+ `act` resolves the ref, dispatches through the engine, and returns a typed
76
+ result: `ok`, `stale_ref` (with `new_ref` when the node moved), `not_interactive`
77
+ (with `blocker_ref` when something covers the target), or `invalid_request`.
78
+
79
+ The engine hit-tests the click point with `DOM.getNodeForLocation` before
80
+ dispatching real mouse input, accepting the target, its descendants, and its
81
+ ancestors. After a click, check, or press it waits up to 250ms for a main-frame
82
+ navigation, then for load and a short network-idle window. A long poll or
83
+ animation does not block the caller.
84
+
85
+ ## Effects and delta
86
+
87
+ `act` returns what the action changed:
88
+
89
+ - **`effects`**: `navigation`, `network`, and `value`.
90
+ - A `network` effect carries the method, URL, status, resource type, MIME
91
+ type, and parsed JSON request and response bodies. Only requests that
92
+ started during the action are included, so each one is attributed to the
93
+ action that caused it. Bodies over 256 KB are dropped.
94
+ - **`delta`**: `{ navigation, entries[] }`, where entries are `added`,
95
+ `removed`, or `changed` nodes by ref.
96
+
97
+ After an action the substrate re-captures the document and diffs the ref maps.
98
+ A navigation returns `{ navigation: true, entries: [] }` because the caller
99
+ should re-read. Non-navigation actions return a small diff; the fixture test
100
+ asserts it stays under 15% of the document.
101
+
102
+ ## Network capture
103
+
104
+ `PlaywrightEngine` listens to CDP `Network` events. `requestWillBeSent`
105
+ records the method, URL, resource type, and JSON request body; a body CDP did
106
+ not inline is fetched with `Network.getRequestPostData`. `responseReceived`
107
+ adds the status and MIME type, and `loadingFinished` fetches a JSON response
108
+ body with `Network.getResponseBody` before it is evicted.
109
+
110
+ `dispatch` awaits the captures for the action's requests before returning, so
111
+ the effects it reports are complete, not a promise of a body that arrives
112
+ later. This is what makes a trace usable for lifting an `http` op: the
113
+ request body is the template, and the response body is what `returns` can be
114
+ inferred from.
115
+
116
+ ## Egress policy
117
+
118
+ `loadPolicy(site)` reads `policies/<site>.json`. Pass it to the substrate:
119
+
120
+ ```ts
121
+ const substrate = new Substrate(engine, {
122
+ policy: loadPolicy("store"),
123
+ onBlocked: (event) => log.warn(event),
124
+ });
125
+ ```
126
+
127
+ The guard is default-deny. `fetch` (the in-page `http` tier and fallback) and
128
+ `goto` (the `url` tier) are checked before they reach the page. The guard also
129
+ resolves an allowlisted hostname and refuses a private, loopback, link-local,
130
+ CGNAT, or reserved address (`reason: "private_address"`). `fetch` checks the
131
+ final URL after a redirect too; an off-allowlist redirect throws with
132
+ `reason: "redirect"`. A blocked request throws `EgressBlockedError`, is kept in
133
+ `blockedRequests()`, and is passed to `onBlocked`. A page's own navigation is
134
+ not intercepted by this layer.
135
+
136
+ The address check is a pre-flight lookup, not address pinning: the browser
137
+ resolves the name again when it connects. A name that changes between the two
138
+ lookups can still reach a private address.
139
+
140
+ ## Crash recovery
141
+
142
+ Pass `instanceId` when launching an engine:
143
+
144
+ ```ts
145
+ const engine = await PlaywrightEngine.launch({
146
+ executablePath,
147
+ instanceId: "portolan-local",
148
+ });
149
+ ```
150
+
151
+ The engine adds `--portolan-instance=<id>` to Chromium's command line. If the
152
+ runtime dies without closing (SIGKILL, a crashed container), the browser is
153
+ reparented and keeps running. The next process with the same id can kill it:
154
+
155
+ ```ts
156
+ import { reapOrphans } from "@abubakarsiddiik/substrate";
157
+
158
+ const pids = reapOrphans("portolan-local");
159
+ ```
160
+
161
+ `reapOrphans` reads `ps`, matches only processes carrying the marker, skips
162
+ itself, and sends `SIGKILL`. It returns the pids it killed. It is POSIX only
163
+ and returns `[]` on Windows. An empty id throws, so a missing configuration
164
+ cannot kill every Chromium on the machine.
165
+
166
+ Use one id per runtime instance file, and reuse it across restarts so the new
167
+ process can find the old process's browsers.
168
+
169
+ ## Not here yet
170
+
171
+ This package is the transport, the capture, the addressing layer, and the
172
+ fallback verbs. The op runtime and the compiler are separate packages.
@@ -0,0 +1,56 @@
1
+ import type { Bounds, SemanticNode } from "./engine.js";
2
+ import type { RefMap } from "./refs.js";
3
+ export type Affordance = {
4
+ /** Document-scoped handle, when a ref map was supplied. */
5
+ ref?: string;
6
+ /** CDP backend node id; stable within one document. */
7
+ backendNodeId: number;
8
+ role: string;
9
+ name: string;
10
+ /** Zero-based position among affordances with the same role and name. */
11
+ ordinal: number;
12
+ /** Nearest named ancestor or landmark, for disambiguation. */
13
+ ctx?: string;
14
+ bounds: Bounds;
15
+ properties: Record<string, string | number | boolean>;
16
+ /** Ranking weight; higher is more useful to an agent. */
17
+ score: number;
18
+ };
19
+ export type RankOptions = {
20
+ /** Maximum number of affordances. Default 60. */
21
+ limit?: number;
22
+ /** Attach a ref from this document's map. */
23
+ refs?: RefMap;
24
+ };
25
+ export type RankedAffordances = {
26
+ affordances: Affordance[];
27
+ omitted: number;
28
+ };
29
+ export type RenderOptions = {
30
+ /** Estimated token budget. Default 800. */
31
+ tokenBudget?: number;
32
+ };
33
+ export type RenderedAffordances = {
34
+ text: string;
35
+ tokens: number;
36
+ included: number;
37
+ omitted: number;
38
+ };
39
+ /**
40
+ * Filter, rank, and cap the actionable nodes in a semantic capture.
41
+ *
42
+ * Ranking is deliberately simple and deterministic: role weight, then a
43
+ * name, then context, then document order. The point is a stable short list,
44
+ * not a model's opinion.
45
+ */
46
+ export declare function rankAffordances(nodes: SemanticNode[], options?: RankOptions): RankedAffordances;
47
+ /**
48
+ * Render affordances as compact lines under a token budget.
49
+ *
50
+ * The estimate is four characters per token, which is good enough for a
51
+ * budget check and avoids a tokenizer in the hot path. Refs are not in the
52
+ * text yet; T2.12 adds them.
53
+ */
54
+ export declare function renderAffordances(affordances: Affordance[], options?: RenderOptions): RenderedAffordances;
55
+ export declare function estimateTokens(text: string): number;
56
+ //# sourceMappingURL=affordances.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"affordances.d.ts","sourceRoot":"","sources":["../src/affordances.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExC,MAAM,MAAM,UAAU,GAAG;IACvB,2DAA2D;IAC3D,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,8DAA8D;IAC9D,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;IACtD,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,iDAAiD;IACjD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,2CAA2C;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AA8DF;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,EAAE,EACrB,OAAO,GAAE,WAAgB,GACxB,iBAAiB,CAgDnB;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,WAAW,EAAE,UAAU,EAAE,EACzB,OAAO,GAAE,aAAkB,GAC1B,mBAAmB,CAuBrB;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD"}
@@ -0,0 +1,201 @@
1
+ /** Roles an agent can act on. Structure roles are not affordances. */
2
+ const ACTIONABLE_ROLES = new Set([
3
+ "button",
4
+ "link",
5
+ "textbox",
6
+ "searchbox",
7
+ "combobox",
8
+ "listbox",
9
+ "checkbox",
10
+ "radio",
11
+ "switch",
12
+ "slider",
13
+ "spinbutton",
14
+ "tab",
15
+ "menuitem",
16
+ "menuitemcheckbox",
17
+ "menuitemradio",
18
+ "option",
19
+ "treeitem",
20
+ "gridcell",
21
+ ]);
22
+ const ROLE_WEIGHT = {
23
+ button: 10,
24
+ link: 9,
25
+ textbox: 9,
26
+ searchbox: 9,
27
+ combobox: 8,
28
+ checkbox: 8,
29
+ radio: 8,
30
+ switch: 8,
31
+ spinbutton: 8,
32
+ slider: 7,
33
+ tab: 7,
34
+ menuitem: 7,
35
+ option: 6,
36
+ treeitem: 6,
37
+ gridcell: 5,
38
+ };
39
+ const LANDMARK_ROLES = new Set([
40
+ "main",
41
+ "form",
42
+ "region",
43
+ "dialog",
44
+ "navigation",
45
+ "table",
46
+ "article",
47
+ "list",
48
+ "listitem",
49
+ "tabpanel",
50
+ "search",
51
+ "complementary",
52
+ "banner",
53
+ "contentinfo",
54
+ ]);
55
+ /** Their names are page titles or nothing useful as context. */
56
+ const STRUCTURAL_ROLES = new Set(["RootWebArea", "WebArea", "document", "generic"]);
57
+ /**
58
+ * Filter, rank, and cap the actionable nodes in a semantic capture.
59
+ *
60
+ * Ranking is deliberately simple and deterministic: role weight, then a
61
+ * name, then context, then document order. The point is a stable short list,
62
+ * not a model's opinion.
63
+ */
64
+ export function rankAffordances(nodes, options = {}) {
65
+ const limit = options.limit ?? 100;
66
+ const byId = new Map(nodes.map((node) => [node.nodeId, node]));
67
+ const parents = buildParents(nodes);
68
+ const order = new Map(nodes.map((node, index) => [node.nodeId, index]));
69
+ const candidates = [];
70
+ for (const node of nodes) {
71
+ if (!isActionable(node))
72
+ continue;
73
+ const ctx = contextFor(node, byId, parents);
74
+ const affordance = {
75
+ backendNodeId: node.backendNodeId,
76
+ role: node.role,
77
+ name: node.name,
78
+ ordinal: 0,
79
+ bounds: node.bounds,
80
+ properties: node.properties,
81
+ score: weightOf(node, ctx),
82
+ };
83
+ if (ctx !== undefined)
84
+ affordance.ctx = ctx;
85
+ const ref = options.refs?.byNode.get(node.nodeId)?.ref;
86
+ if (ref !== undefined)
87
+ affordance.ref = ref;
88
+ candidates.push({ affordance, index: order.get(node.nodeId) ?? 0 });
89
+ }
90
+ candidates.sort((a, b) => b.affordance.score - a.affordance.score || a.index - b.index);
91
+ const selected = candidates.slice(0, limit).map((candidate) => candidate.affordance);
92
+ // Duplicate names are common (six "Add application" buttons, several
93
+ // "Continue" links). An ordinal lets a caller name the one it means.
94
+ const seen = new Map();
95
+ for (const affordance of selected) {
96
+ const key = `${affordance.role}\u0000${affordance.name}`;
97
+ const ordinal = seen.get(key) ?? 0;
98
+ affordance.ordinal = ordinal;
99
+ seen.set(key, ordinal + 1);
100
+ }
101
+ return {
102
+ affordances: selected,
103
+ omitted: candidates.length - selected.length,
104
+ };
105
+ }
106
+ /**
107
+ * Render affordances as compact lines under a token budget.
108
+ *
109
+ * The estimate is four characters per token, which is good enough for a
110
+ * budget check and avoids a tokenizer in the hot path. Refs are not in the
111
+ * text yet; T2.12 adds them.
112
+ */
113
+ export function renderAffordances(affordances, options = {}) {
114
+ // Accuracy first: render every ranked affordance unless the caller asks
115
+ // for a cap. A silent 800-token cut can drop the one element a task needs.
116
+ const budget = options.tokenBudget ?? Number.POSITIVE_INFINITY;
117
+ const lines = [];
118
+ let tokens = 0;
119
+ for (const affordance of affordances) {
120
+ const line = formatAffordance(affordance);
121
+ const cost = estimateTokens(line);
122
+ if (lines.length > 0 && tokens + cost > budget)
123
+ break;
124
+ lines.push(line);
125
+ tokens += cost;
126
+ }
127
+ return {
128
+ text: lines.join("\n"),
129
+ tokens,
130
+ included: lines.length,
131
+ omitted: affordances.length - lines.length,
132
+ };
133
+ }
134
+ export function estimateTokens(text) {
135
+ return Math.ceil(text.length / 4);
136
+ }
137
+ function isActionable(node) {
138
+ return (node.visible &&
139
+ node.backendNodeId !== undefined &&
140
+ node.bounds !== undefined &&
141
+ ACTIONABLE_ROLES.has(node.role));
142
+ }
143
+ function buildParents(nodes) {
144
+ const parents = new Map();
145
+ for (const node of nodes) {
146
+ for (const childId of node.childIds) {
147
+ parents.set(childId, node.nodeId);
148
+ }
149
+ }
150
+ return parents;
151
+ }
152
+ function contextFor(node, byId, parents) {
153
+ let current = parents.get(node.nodeId);
154
+ let depth = 0;
155
+ let landmark;
156
+ while (current !== undefined && depth < 8) {
157
+ const ancestor = byId.get(current);
158
+ if (ancestor === undefined)
159
+ break;
160
+ if (ancestor.name.length > 0 && !STRUCTURAL_ROLES.has(ancestor.role)) {
161
+ return `${ancestor.role} ${JSON.stringify(ancestor.name)}`;
162
+ }
163
+ if (landmark === undefined && LANDMARK_ROLES.has(ancestor.role)) {
164
+ landmark = ancestor.role;
165
+ }
166
+ current = parents.get(current);
167
+ depth += 1;
168
+ }
169
+ return landmark;
170
+ }
171
+ /**
172
+ * A form's own submit outranks a same-named button elsewhere on the page.
173
+ *
174
+ * The careerkor run ranked the header "Sign In" button above the sign-in
175
+ * form's "Login" submit; acting on the wrong one re-navigated instead of
176
+ * submitting. When a submit-verb button sits inside a form or search
177
+ * landmark, it is the form's primary action, so it ranks as one.
178
+ */
179
+ const SUBMIT_VERBS = /^(log ?in|sign ?in|signin|submit|save|continue|create|search|checkout|apply|send|next|done)[!.,]?$/i;
180
+ function weightOf(node, ctx) {
181
+ let weight = ROLE_WEIGHT[node.role] ?? 1;
182
+ if (node.name.length > 0)
183
+ weight += 3;
184
+ if (ctx !== undefined)
185
+ weight += 1;
186
+ if (node.role === "button" &&
187
+ ctx !== undefined &&
188
+ /\bform\b|^search\b/.test(ctx) &&
189
+ SUBMIT_VERBS.test(node.name)) {
190
+ weight += 3;
191
+ }
192
+ return weight;
193
+ }
194
+ function formatAffordance(affordance) {
195
+ const ref = affordance.ref !== undefined ? `${affordance.ref} ` : "";
196
+ const name = affordance.name.length > 0 ? JSON.stringify(affordance.name) : "(unnamed)";
197
+ const ordinal = affordance.ordinal > 0 ? ` #${affordance.ordinal + 1}` : "";
198
+ const ctx = affordance.ctx !== undefined ? ` in ${affordance.ctx}` : "";
199
+ return `${ref}${affordance.role} ${name}${ordinal}${ctx}`;
200
+ }
201
+ //# sourceMappingURL=affordances.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"affordances.js","sourceRoot":"","sources":["../src/affordances.ts"],"names":[],"mappings":"AA4CA,sEAAsE;AACtE,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,QAAQ;IACR,MAAM;IACN,SAAS;IACT,WAAW;IACX,UAAU;IACV,SAAS;IACT,UAAU;IACV,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CAAC;AAED,SAAS,gBAAgB,CAAC,UAAsB;IAC9C,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IACrE,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;IACxF,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,OAAO,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5E,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACxE,OAAO,GAAG,GAAG,GAAG,UAAU,CAAC,IAAI,IAAI,IAAI,GAAG,OAAO,GAAG,GAAG,EAAE,CAAC;AAC5D,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Find a Chrome or Chromium binary.
3
+ *
4
+ * `playwright-core` does not download a browser, so the adapter needs one on
5
+ * the machine. `CHROME_PATH` wins when set; otherwise the usual install
6
+ * locations are tried. Tests skip when this returns undefined.
7
+ */
8
+ export declare function findChrome(): string | undefined;
9
+ //# sourceMappingURL=chrome.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chrome.d.ts","sourceRoot":"","sources":["../src/chrome.ts"],"names":[],"mappings":"AAWA;;;;;;GAMG;AACH,wBAAgB,UAAU,IAAI,MAAM,GAAG,SAAS,CAO/C"}