@9l/playwright 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/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ 9lives
2
+ Copyright 2026 QualityMax
3
+
4
+ Licensed under the Apache License, Version 2.0.
5
+ See LICENSE for the full license terms.
package/README.md CHANGED
@@ -1,3 +1,62 @@
1
- # Temporary Holding Version
1
+ # @9l/playwright
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
+ Local Playwright fixtures for the [9lives runner](https://github.com/Quality-Max/9lives-runner).
4
+ The `n9l` fixture provides `step` and bounded natural-language `goal` methods.
5
+ Keep ordinary Playwright assertions to establish the expected behavior. A goal
6
+ completing does not verify that behavior.
7
+
8
+ ## Install
9
+
10
+ Published on [npm](https://www.npmjs.com/package/@9l/playwright):
11
+
12
+ ```sh
13
+ npm install --save-dev @9l/playwright@0.0.0 @playwright/test@1.61.1
14
+ npm exec playwright install chromium
15
+ ```
16
+
17
+ Use Node 24 for the qualified runtime (Node 22 minimum), Playwright 1.61.1,
18
+ and Chromium. macOS and Linux on amd64/arm64 are the qualified runner targets.
19
+ The peer range is `@playwright/test` `>=1.61.1 <2`; versions in it other than
20
+ 1.61.1, and other browser engines, install but are unqualified.
21
+
22
+ The Go `9l` executable is also required. Use the
23
+ [CLI installation guide](https://github.com/Quality-Max/9lives-runner/blob/main/docs/install.md)
24
+ for release availability or install from source with Go 1.25.13 or newer.
25
+ This npm package does not install Go or
26
+ bundle the runner, browsers or a hosted service. No platform account is needed.
27
+
28
+ ## Use
29
+
30
+ ```ts
31
+ import {test, expect} from '@9l/playwright';
32
+
33
+ test('checkout confirms one order', async ({page, n9l}) => {
34
+ await page.goto('http://localhost:3000/checkout');
35
+ await n9l.step('place order', async () => {
36
+ await page.getByRole('button', {name: 'Place order'}).click();
37
+ await expect(page.getByRole('status')).toHaveText('Order confirmed');
38
+ });
39
+ });
40
+ ```
41
+
42
+ Start the example application, then run the selected spec through the Go engine:
43
+
44
+ ```sh
45
+ 9l run tests/checkout.spec.ts --sdk --format json
46
+ ```
47
+
48
+ Use `--pass-env NAME` for explicitly approved application settings. Browser
49
+ handles and goal parameter values stay in the worker; provider credentials stay
50
+ in Go. The `n9l` fixture requires the engine identity supplied by `--sdk`.
51
+ Existing Playwright specs and configuration remain usable independently.
52
+
53
+ Natural-language goals use finite observed controls and typed actions, with
54
+ budgets and a conservative stop policy. See the
55
+ [goal contract](https://github.com/Quality-Max/9lives-runner/blob/main/docs/goals.md)
56
+ and [SDK bridge](https://github.com/Quality-Max/9lives-runner/blob/main/docs/sdk-bridge.md).
57
+ Live provider accuracy, independent behavioral verification, verified replay
58
+ and native mobile support are not qualified features.
59
+
60
+ ## License
61
+
62
+ Apache-2.0. The package includes `LICENSE` and `NOTICE`.
package/dist/goal.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { Page } from '@playwright/test';
2
+ export type GoalOptions = {
3
+ /** Values stay in the browser worker; only parameter names reach the provider. */
4
+ params?: Record<string, string>;
5
+ maxActions?: number;
6
+ maxDecisions?: number;
7
+ maxTokens?: number;
8
+ timeoutMs?: number;
9
+ signal?: AbortSignal;
10
+ };
11
+ export type GoalResult = {
12
+ goalId: string;
13
+ status: 'completed';
14
+ verified: false;
15
+ };
16
+ export declare function redactLabel(text: string): string;
17
+ /** Redacts the test's parameter values, including whitespace-collapsed forms, then bounds the label. */
18
+ export declare function valueRedactor(params: Record<string, string>): (text: string) => string;
19
+ /** Up to eight heading/status labels, redacted before they are cut to size. */
20
+ export declare function observeState(page: Page, redact: (text: string) => string): Promise<string[]>;
21
+ export declare function executeGoal(page: Page, instruction: string, options?: GoalOptions): Promise<GoalResult>;
package/dist/goal.js ADDED
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.redactLabel = redactLabel;
4
+ exports.valueRedactor = valueRedactor;
5
+ exports.observeState = observeState;
6
+ exports.executeGoal = executeGoal;
7
+ const node_http_1 = require("node:http");
8
+ const protocol_1 = require("./protocol");
9
+ const version = '9l.goal/1';
10
+ const risky = /\b(send|resend|invite|publish|broadcast|notify|share|post|reply|comment|buy|purchase|pay|payment|checkout|check out|place (your |my )?order|submit order|order now|complete (order|purchase|checkout|booking|payment)|confirm (order|purchase|payment|booking)|book now|reserve|donate|subscribe|upgrade|start (subscription|trial)|delete|remove|destroy|erase|discard|trash|deactivate|revoke|close account|cancel (account|subscription))\b/i;
11
+ const fail = (status) => { throw new Error(`9lives goal stopped: ${status}`); };
12
+ // Bounded semantic labels, never input values, HTML, URLs or entire page text.
13
+ function redactLabel(text) {
14
+ const redacted = text.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '[redacted]')
15
+ .replace(/\b(?:sk-|ghp_|github_pat_|eyJ)[A-Za-z0-9_./+-]{12,}/g, '[redacted]')
16
+ .replace(/\b[A-Za-z0-9_+-]{32,}\b/g, '[redacted]')
17
+ .replace(/\b(?:password|token|secret|api[_ -]?key)\s*[:=]\s*\S+/gi, '[redacted]')
18
+ .replace(/\s+/g, ' ').trim();
19
+ let bounded = '';
20
+ for (const char of redacted) {
21
+ if (Buffer.byteLength(bounded + char) > 160)
22
+ break;
23
+ bounded += char;
24
+ }
25
+ return bounded;
26
+ }
27
+ async function metadata(handle) {
28
+ return handle.evaluate(element => {
29
+ const input = element;
30
+ const tag = element.tagName.toLowerCase();
31
+ const type = tag === 'input' ? input.type : '';
32
+ const roles = { button: 'button', a: 'link', textarea: 'textbox', select: 'combobox' };
33
+ let role = element.getAttribute('role') || roles[tag] || '';
34
+ if (tag === 'input') {
35
+ if (['password', 'file', 'hidden'].includes(type))
36
+ return null;
37
+ role = { checkbox: 'checkbox', radio: 'radio', button: 'button', submit: 'button', reset: 'button', search: 'searchbox', number: 'spinbutton' }[type] || 'textbox';
38
+ }
39
+ // Contenteditable and arbitrary custom roles are outside this first executor.
40
+ const mapping = { button: ['click'], link: ['click'], tab: ['click'], menuitem: ['click'], radio: ['click'], switch: ['click'], textbox: ['fill'], searchbox: ['fill'], spinbutton: ['fill'], combobox: ['select'], checkbox: ['check'] };
41
+ const actions = mapping[role];
42
+ if (!actions || !element.isConnected || element.closest('[inert]') || element.getAttribute('aria-disabled') === 'true' || input.disabled)
43
+ return null;
44
+ const labelled = (element.getAttribute('aria-labelledby') || '').split(/\s+/).map(id => document.getElementById(id)?.textContent || '').join(' ');
45
+ const label = element.getAttribute('aria-label') || labelled.trim() || Array.from(input.labels || []).map(label => label.textContent || '').join(' ') || (tag === 'input' ? input.getAttribute('placeholder') || (['submit', 'button', 'reset'].includes(type) ? input.value : '') : element.textContent || '');
46
+ // Only same-origin links are offered. The URL stays in the worker fingerprint.
47
+ const href = role === 'link' ? element.getAttribute('href') || '' : '';
48
+ if (role === 'link') {
49
+ try {
50
+ const url = new URL(href, document.baseURI);
51
+ if (!['http:', 'https:'].includes(url.protocol) || url.origin !== location.origin)
52
+ return null;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ const policyText = [element.getAttribute('aria-label'), labelled, Array.from(input.labels || []).map(label => label.textContent || '').join(' '), element.textContent, ['submit', 'button', 'reset'].includes(type) ? input.value : ''].filter(Boolean).join(' ');
59
+ return { role, label, policyText, actions, fingerprint: JSON.stringify([tag, type, role, label, href, policyText]) };
60
+ });
61
+ }
62
+ /** Redacts the test's parameter values, including whitespace-collapsed forms, then bounds the label. */
63
+ function valueRedactor(params) {
64
+ const values = Object.values(params).flatMap(value => [value, value.replace(/\s+/g, ' ').trim()]).filter(Boolean);
65
+ return text => redactLabel(values.reduce((result, value) => result.split(value).join('[redacted]'), text));
66
+ }
67
+ /** Up to eight heading/status labels, redacted before they are cut to size. */
68
+ async function observeState(page, redact) {
69
+ // Collapse whitespace before bounding, and keep enough text that any value
70
+ // overlapping the 160-byte label lies wholly inside it: parameters are
71
+ // redacted before the label is cut, never after.
72
+ const state = await page.locator('h1,h2,[role="status"]').evaluateAll(elements => elements.slice(0, 8).map(element => (element.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 8192)));
73
+ return state.map(redact);
74
+ }
75
+ async function observe(page, redact) {
76
+ const locator = page.locator('button,a[href],input,textarea,select,[role="button"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="radio"],[role="switch"]');
77
+ const handles = [];
78
+ try {
79
+ for (let index = 0, count = Math.min(100, await locator.count()); index < count; index++) {
80
+ const handle = await locator.nth(index).elementHandle({ timeout: 500 });
81
+ if (handle)
82
+ handles.push(handle);
83
+ }
84
+ const targets = new Map();
85
+ // Bound traversal as well as the transmitted set.
86
+ for (const handle of handles.slice(0, 100)) {
87
+ if (targets.size >= 25 || !await handle.isVisible() || !await handle.isEnabled())
88
+ continue;
89
+ const data = await metadata(handle);
90
+ if (!data)
91
+ continue;
92
+ const id = `target-${targets.size + 1}`;
93
+ targets.set(id, { handle, fingerprint: data.fingerprint, control: { id, role: data.role, label: redact(data.label), actions: data.actions, blocked: risky.test(data.policyText) } });
94
+ }
95
+ const state = await observeState(page, redact);
96
+ return { targets, state, dispose: async () => { await Promise.allSettled(handles.map(handle => handle.dispose())); } };
97
+ }
98
+ catch {
99
+ await Promise.allSettled(handles.map(handle => handle.dispose()));
100
+ return fail('observation_failed');
101
+ }
102
+ }
103
+ async function executeGoal(page, instruction, options = {}) {
104
+ const identity = { ...(0, protocol_1.engineIdentity)(), version };
105
+ const socketPath = process.env.NINELIVES_GOAL_SOCKET;
106
+ if (!socketPath)
107
+ return fail('provider_required; use --goal-provider or --goal-script');
108
+ const params = options.params || {};
109
+ if (typeof instruction !== 'string' || Buffer.byteLength(instruction) > 4096 || !instruction.trim() || Object.keys(params).length > 16 || Object.entries(params).some(([key, value]) => !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(key) || typeof value !== 'string' || value.length > 4096))
110
+ return fail('invalid_options');
111
+ const redact = valueRedactor(params);
112
+ // Only caps the test sets are sent. Go applies them below the CLI budgets;
113
+ // an omitted cap keeps the attempt's, so SDK defaults never override the CLI.
114
+ const limits = Object.fromEntries(['maxActions', 'maxDecisions', 'maxTokens', 'timeoutMs'].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
115
+ if (Object.values(limits).some(value => !Number.isSafeInteger(value) || value <= 0))
116
+ return fail('invalid_options');
117
+ const controller = new AbortController();
118
+ let stopReason = 'canceled';
119
+ const stop = (reason) => {
120
+ if (controller.signal.aborted)
121
+ return;
122
+ stopReason = reason;
123
+ controller.abort();
124
+ // Playwright actions have no AbortSignal option. Closing this owned page
125
+ // cancels an in-flight action rather than allowing it to fire after abort.
126
+ void page.close({ runBeforeUnload: false }).catch(() => { });
127
+ };
128
+ const abort = () => stop('canceled');
129
+ if (options.signal?.aborted)
130
+ return fail('canceled');
131
+ options.signal?.addEventListener('abort', abort, { once: true });
132
+ page.once('close', abort);
133
+ // Until Go returns the goal's effective time budget, bound only the start call.
134
+ const startMs = options.timeoutMs ?? 60000;
135
+ let deadline = Date.now() + startMs;
136
+ let deadlineTimer = setTimeout(() => stop('budget_exhausted'), startMs);
137
+ const call = async (body) => {
138
+ if (controller.signal.aborted)
139
+ return fail(stopReason);
140
+ const raw = JSON.stringify({ ...identity, ...body });
141
+ if (Buffer.byteLength(raw) > 24000)
142
+ return fail('observation_too_large');
143
+ return new Promise((resolve, reject) => {
144
+ const req = (0, node_http_1.request)({ socketPath, path: '/goal', method: 'POST', headers: { 'content-type': 'application/json' }, signal: controller.signal }, res => {
145
+ let output = '';
146
+ res.setEncoding('utf8');
147
+ res.on('data', chunk => { output += chunk; if (Buffer.byteLength(output) > 4096)
148
+ req.destroy(new Error('invalid_reply')); });
149
+ res.on('error', () => reject(new Error(`9lives goal stopped: ${controller.signal.aborted ? stopReason : 'transport_failed'}`)));
150
+ res.on('end', () => {
151
+ try {
152
+ const reply = JSON.parse(output);
153
+ if (res.statusCode !== 200 || typeof reply.status !== 'string')
154
+ throw new Error();
155
+ resolve(reply);
156
+ }
157
+ catch {
158
+ reject(new Error('9lives goal stopped: invalid_reply'));
159
+ }
160
+ });
161
+ });
162
+ const timer = setTimeout(() => req.destroy(new Error('deadline')), Math.max(1, deadline - Date.now()));
163
+ req.on('close', () => clearTimeout(timer));
164
+ req.on('error', () => reject(new Error(`9lives goal stopped: ${controller.signal.aborted ? stopReason : 'transport_failed'}`)));
165
+ req.end(raw);
166
+ });
167
+ };
168
+ try {
169
+ const start = await call({ op: 'start', instruction: Object.values(params).filter(Boolean).reduce((result, value) => result.split(value).join('[redacted]'), instruction), parameters: Object.keys(params), ...(Object.keys(limits).length ? { limits } : {}) });
170
+ if (start.status !== 'active' || !start.goalId || !start.timeoutMs)
171
+ return fail(start.status);
172
+ const goalId = start.goalId;
173
+ deadline = Date.now() + start.timeoutMs;
174
+ clearTimeout(deadlineTimer);
175
+ deadlineTimer = setTimeout(() => stop('budget_exhausted'), start.timeoutMs);
176
+ while (Date.now() < deadline && !controller.signal.aborted) {
177
+ const observation = await observe(page, redact);
178
+ try {
179
+ const reply = await call({ op: 'decide', goalId, candidates: [...observation.targets.values()].map(target => target.control), state: observation.state });
180
+ if (reply.status === 'completed')
181
+ return { goalId, status: 'completed', verified: false };
182
+ if (reply.status !== 'active' || !reply.decision || !reply.decisionId)
183
+ return fail(reply.status);
184
+ const decision = reply.decision;
185
+ const ack = async (outcome) => call({ op: 'ack', goalId, decisionId: reply.decisionId, outcome });
186
+ if (decision.action === 'wait') {
187
+ await new Promise(resolve => setTimeout(resolve, Math.min(200, Math.max(1, deadline - Date.now()))));
188
+ await ack('done');
189
+ continue;
190
+ }
191
+ const target = observation.targets.get(decision.targetId || '');
192
+ // Go never decides on a blocked target; refusing one here costs nothing.
193
+ if (!target || target.control.blocked || !target.control.actions.includes(decision.action))
194
+ return fail('invalid_target');
195
+ // The fingerprint includes the raw stop-policy text, so a fresh match
196
+ // proves the policy verdict observed above still holds.
197
+ let fresh = false;
198
+ try {
199
+ fresh = await target.handle.isVisible() && await target.handle.isEnabled() && (await metadata(target.handle))?.fingerprint === target.fingerprint;
200
+ }
201
+ catch { /* Detached before issuing an action: safe to reobserve. */ }
202
+ if (!fresh) {
203
+ await ack('stale');
204
+ continue;
205
+ }
206
+ const timeout = Math.min(3000, Math.max(1, deadline - Date.now()));
207
+ // After issuing a mutation, any error has an uncertain effect. Never retry it.
208
+ try {
209
+ if (controller.signal.aborted)
210
+ return fail(stopReason);
211
+ switch (decision.action) {
212
+ case 'click':
213
+ await target.handle.click({ timeout });
214
+ break;
215
+ case 'check':
216
+ await target.handle.setChecked(true, { timeout });
217
+ break;
218
+ case 'fill':
219
+ if (!Object.hasOwn(params, decision.parameter || ''))
220
+ return fail('invalid_parameter');
221
+ await target.handle.fill(params[decision.parameter], { timeout });
222
+ break;
223
+ case 'select':
224
+ if (!Object.hasOwn(params, decision.parameter || ''))
225
+ return fail('invalid_parameter');
226
+ await target.handle.selectOption(params[decision.parameter], { timeout });
227
+ break;
228
+ default: return fail('invalid_action');
229
+ }
230
+ }
231
+ catch {
232
+ await ack('unknown').catch(() => { });
233
+ return fail('unknown_effect');
234
+ }
235
+ const result = await ack('done');
236
+ if (result.status !== 'active')
237
+ return fail(result.status);
238
+ }
239
+ finally {
240
+ await observation.dispose();
241
+ }
242
+ }
243
+ return fail(controller.signal.aborted ? stopReason : 'budget_exhausted');
244
+ }
245
+ catch (error) {
246
+ if (controller.signal.aborted)
247
+ return fail(stopReason);
248
+ throw error;
249
+ }
250
+ finally {
251
+ clearTimeout(deadlineTimer);
252
+ options.signal?.removeEventListener('abort', abort);
253
+ page.removeListener('close', abort);
254
+ }
255
+ }
@@ -0,0 +1,13 @@
1
+ import { expect } from '@playwright/test';
2
+ import { type GoalOptions, type GoalResult } from './goal';
3
+ export type { GoalOptions, GoalResult } from './goal';
4
+ export type NineLives = {
5
+ /** Execute a named step; assertions and browser handles remain ordinary Playwright. */
6
+ goal(instruction: string, options?: GoalOptions): Promise<GoalResult>;
7
+ step<T>(name: string, body: () => Promise<T>): Promise<T>;
8
+ };
9
+ export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
10
+ n9l: NineLives;
11
+ }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
12
+ export { expect };
13
+ export { protocolVersion } from './protocol';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.protocolVersion = exports.expect = exports.test = void 0;
4
+ const test_1 = require("@playwright/test");
5
+ Object.defineProperty(exports, "expect", { enumerable: true, get: function () { return test_1.expect; } });
6
+ const protocol_1 = require("./protocol");
7
+ const goal_1 = require("./goal");
8
+ exports.test = test_1.test.extend({
9
+ n9l: async ({ page }, use, testInfo) => {
10
+ (0, protocol_1.engineIdentity)();
11
+ await use({ goal: (instruction, options) => test_1.test.step('9l goal', () => {
12
+ if (testInfo.retry > 0)
13
+ throw new Error('9lives goal stopped: automatic goal retries disabled');
14
+ return (0, goal_1.executeGoal)(page, instruction, options);
15
+ }), step: (name, body) => test_1.test.step(name, body) });
16
+ },
17
+ });
18
+ var protocol_2 = require("./protocol");
19
+ Object.defineProperty(exports, "protocolVersion", { enumerable: true, get: function () { return protocol_2.protocolVersion; } });
@@ -0,0 +1,12 @@
1
+ export declare const protocolVersion = "9l.engine/1";
2
+ export declare const maxFrameBytes: number;
3
+ export declare const maxEvents = 10000;
4
+ export declare const capabilities: readonly ["steps", "artifact-metadata", "terminal-outcomes"];
5
+ export declare function engineIdentity(env?: NodeJS.ProcessEnv): {
6
+ version: string;
7
+ runId: string;
8
+ jobId: string;
9
+ attemptId: string;
10
+ };
11
+ export declare function engineEventsPath(env?: NodeJS.ProcessEnv): string;
12
+ export declare function skipPinKey(titlePath: readonly string[], separator?: "\\" | "/"): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.capabilities = exports.maxEvents = exports.maxFrameBytes = exports.protocolVersion = void 0;
4
+ exports.engineIdentity = engineIdentity;
5
+ exports.engineEventsPath = engineEventsPath;
6
+ exports.skipPinKey = skipPinKey;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_path_1 = require("node:path");
9
+ exports.protocolVersion = '9l.engine/1';
10
+ exports.maxFrameBytes = 16 * 1024;
11
+ exports.maxEvents = 10000;
12
+ exports.capabilities = ['steps', 'artifact-metadata', 'terminal-outcomes'];
13
+ function engineIdentity(env = process.env) {
14
+ if (env.NINELIVES_ENGINE_PROTOCOL !== exports.protocolVersion) {
15
+ throw new Error('9lives SDK requires a supported Go engine; run this spec with 9l run --sdk');
16
+ }
17
+ const runId = env.NINELIVES_RUN_ID;
18
+ const jobId = env.NINELIVES_JOB_ID;
19
+ const attemptId = env.NINELIVES_ATTEMPT_ID;
20
+ const valid = (value) => !!value && /^[a-zA-Z0-9_-]{1,128}$/.test(value);
21
+ if (!valid(runId) || !valid(jobId) || !valid(attemptId)) {
22
+ throw new Error('9lives SDK requires complete engine attempt identity');
23
+ }
24
+ return { version: exports.protocolVersion, runId, jobId, attemptId };
25
+ }
26
+ // Go creates a private per-attempt directory and names the evidence file in it.
27
+ // Configuration, hooks and dependencies own stdout, so evidence never uses it.
28
+ function engineEventsPath(env = process.env) {
29
+ const path = env.NINELIVES_ENGINE_EVENTS;
30
+ if (!path || !(0, node_path_1.isAbsolute)(path)) {
31
+ throw new Error('9lives SDK requires an engine evidence channel; run this spec with 9l run --sdk');
32
+ }
33
+ return path;
34
+ }
35
+ // A skip pin names a test as "<file> › <describe>... › <title>": Playwright's
36
+ // title path without the root and project suites, with / separators. Only this
37
+ // digest crosses the bridge; Go compares it with SkipPinKey of each --pin-skip.
38
+ function skipPinKey(titlePath, separator = node_path_1.sep) {
39
+ const [, , file = '', ...titles] = titlePath;
40
+ return (0, node_crypto_1.createHash)('sha256').update([file.split(separator).join('/'), ...titles].join(' › ')).digest('hex');
41
+ }
@@ -0,0 +1,21 @@
1
+ import type { Reporter, FullConfig, Suite, TestCase, TestResult, TestStep, FullResult } from '@playwright/test/reporter';
2
+ export default class EngineReporter implements Reporter {
3
+ private identity;
4
+ private events;
5
+ private seq;
6
+ private stepSeq;
7
+ private suite?;
8
+ private terminal;
9
+ private overflow;
10
+ printsToStdio(): boolean;
11
+ private testId;
12
+ private emit;
13
+ onBegin(_config: FullConfig, suite: Suite): void;
14
+ onTestBegin(test: TestCase, result: TestResult): void;
15
+ onStepEnd(test: TestCase, result: TestResult, step: TestStep): void;
16
+ onTestEnd(test: TestCase, result: TestResult): void;
17
+ onError(): void;
18
+ onStdOut(): void;
19
+ onStdErr(): void;
20
+ onEnd(result: FullResult): void;
21
+ }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_crypto_1 = require("node:crypto");
4
+ const node_fs_1 = require("node:fs");
5
+ const protocol_1 = require("./protocol");
6
+ // Worker logs, error messages, step titles, URLs and attachment bodies never enter
7
+ // the protocol. IDs are hashes; Go persists only this bounded metadata stream.
8
+ class EngineReporter {
9
+ identity = (0, protocol_1.engineIdentity)();
10
+ // Exclusive create: the file must be new for this attempt, never appended to.
11
+ events = (0, node_fs_1.openSync)((0, protocol_1.engineEventsPath)(), 'wx', 0o600);
12
+ seq = 0;
13
+ stepSeq = 0;
14
+ suite;
15
+ terminal = false;
16
+ overflow = false;
17
+ printsToStdio() { return true; }
18
+ testId(test) { return (0, node_crypto_1.createHash)('sha256').update(test.id).digest('hex'); }
19
+ emit(type, fields = {}) {
20
+ if (this.terminal || this.overflow)
21
+ return;
22
+ if (this.seq >= protocol_1.maxEvents - 1) {
23
+ this.overflow = true;
24
+ (0, node_fs_1.writeSync)(this.events, JSON.stringify({ ...this.identity, seq: ++this.seq, type: 'engine_error' }) + '\n');
25
+ return;
26
+ }
27
+ const frame = JSON.stringify({ ...this.identity, seq: ++this.seq, type, ...fields }) + '\n';
28
+ if (Buffer.byteLength(frame) > protocol_1.maxFrameBytes) {
29
+ this.overflow = true;
30
+ (0, node_fs_1.writeSync)(this.events, JSON.stringify({ ...this.identity, seq: this.seq, type: 'engine_error' }) + '\n');
31
+ return;
32
+ }
33
+ (0, node_fs_1.writeSync)(this.events, frame);
34
+ }
35
+ onBegin(_config, suite) {
36
+ this.suite = suite;
37
+ this.emit('hello', { capabilities: protocol_1.capabilities, totalTests: suite.allTests().length });
38
+ }
39
+ onTestBegin(test, result) {
40
+ this.emit('test_begin', { testId: this.testId(test), retry: result.retry });
41
+ }
42
+ onStepEnd(test, result, step) {
43
+ const categories = { 'test.step': 'action', expect: 'assertion', 'pw:api': 'browser', fixture: 'fixture' };
44
+ this.emit('step_end', {
45
+ testId: this.testId(test), retry: result.retry, stepId: `step-${++this.stepSeq}`,
46
+ category: step.category === 'test.step' && step.title === '9l goal' ? 'goal' : categories[step.category] ?? 'other', status: step.error ? 'failed' : 'passed',
47
+ });
48
+ }
49
+ onTestEnd(test, result) {
50
+ if (result.attachments.length > 32) {
51
+ this.emit('engine_error');
52
+ return;
53
+ }
54
+ this.emit('test_end', {
55
+ testId: this.testId(test), retry: result.retry, status: result.status, expectedStatus: test.expectedStatus,
56
+ artifacts: result.attachments.map((attachment, index) => ({
57
+ id: `artifact-${index + 1}`,
58
+ kind: attachment.contentType.startsWith('image/') ? 'image' : attachment.contentType === 'application/json' ? 'json' : 'other',
59
+ retained: false,
60
+ })),
61
+ });
62
+ }
63
+ onError() { this.emit('engine_error'); }
64
+ onStdOut() { } // Do not mix test logs with evidence or retain arbitrary payloads.
65
+ onStdErr() { }
66
+ onEnd(result) {
67
+ // Individual outcomes are separate bounded frames, even for large suites.
68
+ for (const test of this.suite?.allTests() ?? []) {
69
+ const outcome = test.outcome();
70
+ this.emit('test_result', { testId: this.testId(test), outcome, ...(outcome === 'skipped' ? { skipKey: (0, protocol_1.skipPinKey)(test.titlePath()) } : {}) });
71
+ }
72
+ this.emit('end', { status: result.status });
73
+ this.terminal = true;
74
+ (0, node_fs_1.closeSync)(this.events);
75
+ }
76
+ }
77
+ exports.default = EngineReporter;
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@9l/playwright",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Playwright fixtures and the versioned 9lives Go engine bridge",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://github.com/Quality-Max/9lives-runner#local-playwright-sdk",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Quality-Max/9lives-runner.git",
10
+ "directory": "packages/playwright"
11
+ },
12
+ "bugs": {"url": "https://github.com/Quality-Max/9lives-runner/issues"},
13
+ "type": "commonjs",
14
+ "main": "dist/index.js",
15
+ "types": "dist/index.d.ts",
16
+ "exports": {
17
+ ".": {"types": "./dist/index.d.ts", "default": "./dist/index.js"},
18
+ "./reporter": {"types": "./dist/reporter.d.ts", "default": "./dist/reporter.js"}
19
+ },
20
+ "files": ["dist", "LICENSE", "NOTICE", "README.md"],
21
+ "scripts": {"build": "tsc -p tsconfig.json"},
22
+ "peerDependencies": {"@playwright/test": ">=1.61.1 <2"},
23
+ "engines": {"node": ">=22"},
24
+ "publishConfig": {"access": "public"}
25
+ }