@jeffawe/understudy 0.0.0-stage → 0.2.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.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +171 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1008 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +79 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Live recorder — a human drives a headed browser, we capture intent.
3
+ *
4
+ * This replaces `playwright codegen` rather than wrapping it. Codegen's only
5
+ * output is source code in one of five languages; it never exposes the
6
+ * structured actions it derives internally. We want the data, so we listen for
7
+ * it ourselves.
8
+ *
9
+ * DIVISION OF LABOUR:
10
+ * the injected script what happened, on which element, AND what that element
11
+ * is — role and accessible name, computed in-page and
12
+ * synchronously by a spec-compliant accname bundle
13
+ * Playwright fallback only, when that bundle failed to load
14
+ *
15
+ * Resolving from Node is a LAST RESORT because it loses a race it cannot win:
16
+ * clicking usually destroys the element clicked ("Add to cart" becomes
17
+ * "Remove"; a submit re-renders the page), and an async exposeBinding call
18
+ * cannot block the page's default action. codegen gets correct names precisely
19
+ * by computing them in-page at event time; this does the same.
20
+ */
21
+ import {} from 'playwright';
22
+ import { createHash } from 'node:crypto';
23
+ import { existsSync } from 'node:fs';
24
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
25
+ import { basename, join, relative, resolve } from 'node:path';
26
+ import { openLease } from '../../core/browser.js';
27
+ import { computeSig, parseAria } from '../../core/sig.js';
28
+ import { buildRecording, } from '../../core/recording.js';
29
+ import { INJECTED_LISTENER, STAMP_ATTR } from './injected.js';
30
+ import { ACCNAME_BUNDLE } from './accname-bundle.js';
31
+ import { toRawEvent } from './wire.js';
32
+ /**
33
+ * Ask Playwright what the stamped element actually is.
34
+ *
35
+ * Returns undefined when the element is gone — a click that navigates can tear
36
+ * it down before we get here. That is not a failure: the event still records,
37
+ * flagged `unresolved`, carrying the in-page hints, and the replay stage can
38
+ * upgrade it by looking at the live element. Recording a step with a weaker
39
+ * name beats dropping the step.
40
+ */
41
+ async function resolveStamped(page, stamp) {
42
+ try {
43
+ const locator = page.locator(`[${STAMP_ATTR}="${stamp}"]`).first();
44
+ if ((await locator.count()) === 0)
45
+ return undefined;
46
+ const snapshot = await locator.ariaSnapshot({ timeout: 1000 });
47
+ return parseAria(snapshot)[0];
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ // Read per call, not once at import. A module-level constant would freeze the
54
+ // override before any caller could set it, which is a footgun for anything that
55
+ // wants its own directory — a check, or a run recording into a scratch corpus.
56
+ const fixturesDir = () => process.env.UNDERSTUDY_FIXTURES_DIR ?? resolve('.understudy/fixtures');
57
+ /**
58
+ * One CDP session per page, reused.
59
+ *
60
+ * `DOM.getFileInfo` lives in the DOM domain and answers nothing until it is
61
+ * enabled, and opening a session per uploaded file would be wasteful on a form
62
+ * that takes several.
63
+ */
64
+ const cdpSessions = new WeakMap();
65
+ async function cdpFor(page) {
66
+ let session = cdpSessions.get(page);
67
+ if (!session) {
68
+ session = page
69
+ .context()
70
+ .newCDPSession(page)
71
+ .then(async (opened) => {
72
+ await opened.send('DOM.enable').catch(() => { });
73
+ return opened;
74
+ });
75
+ cdpSessions.set(page, session);
76
+ }
77
+ return session;
78
+ }
79
+ /**
80
+ * The real paths behind a file input.
81
+ *
82
+ * THIS IS THE ONE THING THE PAGE CANNOT TELL US. The DOM masks a file input's
83
+ * value to `C:\fakepath\<name>` and `File` exposes only `.name`, both
84
+ * deliberately, so that a page cannot learn where a person keeps their files.
85
+ * The recorder is not a page, though — it owns the browser, and Chrome will
86
+ * answer the question over the DevTools protocol.
87
+ *
88
+ * Chromium-only, which costs nothing here: every browser Understudy opens is
89
+ * Chromium. Returns [] rather than throwing, because an upload we cannot
90
+ * resolve should drop one step, not kill a recording someone is halfway
91
+ * through.
92
+ */
93
+ async function uploadedPaths(page, stamp) {
94
+ try {
95
+ const cdp = await cdpFor(page);
96
+ const handle = await cdp.send('Runtime.evaluate', {
97
+ expression: `document.querySelector('[${STAMP_ATTR}="${stamp}"]').files`,
98
+ });
99
+ const objectId = handle?.result?.objectId;
100
+ if (!objectId)
101
+ return [];
102
+ const props = await cdp.send('Runtime.getProperties', { objectId, ownProperties: true });
103
+ const paths = [];
104
+ for (const prop of props?.result ?? []) {
105
+ // A FileList's own properties are its numeric indices plus 'length'.
106
+ if (!/^\d+$/.test(prop.name))
107
+ continue;
108
+ const fileId = prop.value?.objectId;
109
+ if (!fileId)
110
+ continue;
111
+ const info = (await cdp.send('DOM.getFileInfo', { objectId: fileId }));
112
+ if (info?.path)
113
+ paths.push(info.path);
114
+ }
115
+ return paths;
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ }
121
+ /**
122
+ * Copy an uploaded file into the corpus and return the path to store.
123
+ *
124
+ * A recording that points at `/Users/someone/Desktop/photo.png` replays
125
+ * exactly once, on one machine — which contradicts the rule that a recording
126
+ * must replay. Copying the file in makes the recording self-contained. Naming
127
+ * it by content hash means the same photo recorded ten times is stored once,
128
+ * and two different files that share a basename cannot collide.
129
+ */
130
+ async function stashFixture(absolute) {
131
+ const bytes = await readFile(absolute);
132
+ const digest = createHash('sha256').update(bytes).digest('hex').slice(0, 12);
133
+ const dir = fixturesDir();
134
+ const target = join(dir, `${digest}-${basename(absolute)}`);
135
+ await mkdir(dir, { recursive: true });
136
+ if (!existsSync(target))
137
+ await writeFile(target, bytes);
138
+ // Relative, so the value means the same thing from the repo root whoever
139
+ // replays it.
140
+ return relative(process.cwd(), target);
141
+ }
142
+ export async function recordLive(opts) {
143
+ const { appSlug, startUrl, maxMinutes = 30, drive, storageState, armWhen, beforeArm, preludeSlugs, onArmed,
144
+ // A driven capture needs no window; a human one is the whole point of a window.
145
+ headless = Boolean(drive), source = drive ? 'script' : 'live', origin = drive ? 'driven' : 'headed-browser', } = opts;
146
+ const ownsLease = !opts.lease;
147
+ const lease = opts.lease ?? (await openLease({ headless, ...(storageState ? { storageState } : {}) }));
148
+ const { browser, context } = lease;
149
+ const events = [];
150
+ const startedAt = Date.now();
151
+ let closed = false;
152
+ // The capture gate. Armed immediately unless the caller wants to reach a
153
+ // starting point first — see `armWhen`. Events that arrive while this is
154
+ // false are dropped, which is what makes "record the tail, not the whole
155
+ // journey" possible without touching the injected listener at all.
156
+ let armed = !(armWhen || beforeArm);
157
+ // The binding must exist before the init script runs, or the page calls a
158
+ // function that isn't there.
159
+ await context.exposeBinding('__understudyEmit', async ({ page }, wire) => {
160
+ // Dropped, not merely unrecorded: the listener keeps computing names and
161
+ // stamping elements throughout, so arming costs nothing and cannot half-work.
162
+ if (!armed)
163
+ return;
164
+ // The page computes role and name with a spec-compliant accname
165
+ // implementation, synchronously, while the element still exists. That is
166
+ // authoritative — Playwright's own answer is only consulted when the page
167
+ // had to fall back to its heuristic.
168
+ const resolved = wire.resolvedBy === 'accname' ? undefined : await resolveStamped(page, wire.stamp);
169
+ // AN UPLOAD'S VALUE IS A PATH, read from the live input and stashed as a
170
+ // fixture. Nothing resolvable: drop the step — recording an upload we
171
+ // cannot point at is exactly the silent corruption this exists to end.
172
+ let uploaded;
173
+ if (wire.action === 'upload') {
174
+ const paths = await uploadedPaths(page, wire.stamp);
175
+ if (!paths.length)
176
+ return;
177
+ uploaded = (await Promise.all(paths.map(stashFixture))).join('\n');
178
+ }
179
+ const event = toRawEvent(wire, Date.now() - startedAt, {
180
+ ...(resolved ? { resolved } : {}),
181
+ ...(uploaded !== undefined ? { value: uploaded } : {}),
182
+ });
183
+ events.push({ ...event, seq: events.length });
184
+ });
185
+ // Order matters: the accname bundle must exist before the listener runs, or
186
+ // the listener silently falls back to its heuristic for the first page.
187
+ await context.addInitScript(ACCNAME_BUNDLE);
188
+ await context.addInitScript(INJECTED_LISTENER);
189
+ const page = lease.page;
190
+ // The opening navigation is a step in its own right — a replay has to start
191
+ // somewhere, and it is not implied by any click. When capture is armed later,
192
+ // the opening step is wherever the operator armed it, so it is pushed there
193
+ // instead of here.
194
+ if (armed) {
195
+ events.push({
196
+ seq: 0,
197
+ ts: 0,
198
+ action: 'goto',
199
+ value: startUrl,
200
+ url: startUrl,
201
+ resolution: 'script-literal',
202
+ });
203
+ }
204
+ // A prelude's own first step is a goto, so navigating here as well would be a
205
+ // second navigation racing the first for no purpose.
206
+ if (!beforeArm)
207
+ await page.goto(startUrl, { waitUntil: 'domcontentloaded' });
208
+ let entry;
209
+ // THE PRELUDE RUNS HERE: after the listener and the accname bundle are
210
+ // installed, before the gate opens. Its events are dropped exactly as a
211
+ // human's are while driving to a starting point by hand.
212
+ if (beforeArm)
213
+ await beforeArm(lease);
214
+ if (armWhen || beforeArm) {
215
+ // Closing the window is the stop signal everywhere else, so it has to be
216
+ // one here too. Without this race, shutting the browser while we are still
217
+ // waiting to be armed leaves the arm promise pending forever and the
218
+ // process hanging with nothing on screen to explain why.
219
+ const abandoned = new Promise((resolve) => {
220
+ const give = () => resolve('abandoned');
221
+ page.once('close', give);
222
+ context.once('close', give);
223
+ browser.once('disconnected', give);
224
+ });
225
+ const outcome = await Promise.race([
226
+ (armWhen ? armWhen(page) : Promise.resolve()).then(() => 'armed'),
227
+ abandoned,
228
+ ]);
229
+ if (outcome === 'abandoned') {
230
+ if (ownsLease)
231
+ await lease.close();
232
+ // No events at all — the caller's "nothing was recorded" guard reports
233
+ // it and refuses to save, which is exactly right.
234
+ return buildRecording({ source, origin, appSlug, startUrl }, []);
235
+ }
236
+ // Drain before arming, not after. Events dispatched in the page just before
237
+ // the operator armed are still in flight over the binding, and a gate read
238
+ // at handler time would let them through — capturing the last click of the
239
+ // journey we were trying not to record.
240
+ await page
241
+ .evaluate('window.__understudyFlush && window.__understudyFlush()')
242
+ .catch(() => { });
243
+ await page.waitForTimeout(300).catch(() => { });
244
+ const here = page.url();
245
+ const { sig } = await computeSig(page);
246
+ armed = true;
247
+ events.push({
248
+ seq: 0,
249
+ ts: 0,
250
+ action: 'goto',
251
+ value: here,
252
+ url: here,
253
+ // The arming fingerprint rides on step 0 as an ordinary expectation, so
254
+ // replay's existing "am I where I expected to be?" check catches a stale
255
+ // or missing session for free — and escalates it like any other
256
+ // unexpected page, instead of failing later on a locator with no
257
+ // explanation. An expired session serves the login page at the URL that
258
+ // used to be the account page, which is precisely the case a URL
259
+ // comparison cannot see and sig() can.
260
+ expectedSig: sig,
261
+ resolution: 'script-literal',
262
+ });
263
+ const armedInfo = onArmed ? await onArmed({ context, page, sig }) : undefined;
264
+ // `requiresSession` is a claim about REPLAY: can a cold browser reach step
265
+ // 0 by itself? Restoring a session says no. So does SAVING one — the caller
266
+ // only banks a session when credentials were supplied and a login happened,
267
+ // which is the manual-login case and replays no better than the restored
268
+ // one. Arming on a page reachable without either needs nothing, and saying
269
+ // it does would block replay for no reason.
270
+ const needsSession = Boolean(storageState) || Boolean(armedInfo?.sessionSaved);
271
+ entry = {
272
+ startState: sig,
273
+ ...(needsSession ? { requiresSession: true } : {}),
274
+ ...(preludeSlugs?.length ? { prelude: preludeSlugs } : {}),
275
+ };
276
+ }
277
+ if (drive) {
278
+ await drive(page);
279
+ // Bindings resolve asynchronously; a final action can still be in flight.
280
+ await page.waitForTimeout(400);
281
+ }
282
+ else {
283
+ console.log('recording — drive the app in the browser window.');
284
+ console.log('close the browser when you are done.\n');
285
+ // Closing the window is the stop signal. There is no "done" button to click
286
+ // because any such control would itself be recorded.
287
+ await new Promise((resolve) => {
288
+ const finish = () => {
289
+ if (closed)
290
+ return;
291
+ closed = true;
292
+ resolve();
293
+ };
294
+ page.on('close', finish);
295
+ context.on('close', finish);
296
+ browser.on('disconnected', finish);
297
+ setTimeout(finish, maxMinutes * 60_000);
298
+ });
299
+ }
300
+ // Flush any field still holding an unemitted value — typically the last one
301
+ // typed, which nothing ever blurred.
302
+ for (const p of context.pages()) {
303
+ // A string, not a closure: no DOM lib needed in a Node project, and no
304
+ // esbuild __name helper to be serialized into the page.
305
+ await p.evaluate('window.__understudyFlush && window.__understudyFlush()').catch(() => { });
306
+ }
307
+ await page.waitForTimeout(250).catch(() => { });
308
+ if (ownsLease)
309
+ await lease.close();
310
+ // seq is reassigned densely: events arrive over a binding and a slow
311
+ // resolution can land out of order relative to a fast one.
312
+ const ordered = events
313
+ .slice()
314
+ .sort((a, b) => a.ts - b.ts)
315
+ .map((e, i) => ({ ...e, seq: i }));
316
+ return buildRecording({ source, origin, appSlug, startUrl, ...(entry ? { entry } : {}) }, ordered);
317
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Script source — turn an existing Playwright script into a RawRecording.
3
+ *
4
+ * Handles both `playwright codegen` output and hand-written `.spec.ts` suites,
5
+ * because they are the same thing: codegen just produces an unusually regular
6
+ * subset. This is what makes the input side open — a team with an existing
7
+ * suite can import it without recording anything by hand.
8
+ *
9
+ * WHY A REAL AST, NOT REGEX:
10
+ * codegen output is regular enough to regex, but hand-written tests are not —
11
+ * chains split across lines, strings contain parentheses, comments contain
12
+ * code-shaped text, and TypeScript syntax sits in the middle of it. The
13
+ * TypeScript compiler is already a dependency and parses all of that correctly.
14
+ *
15
+ * WHY STATIC PARSING RATHER THAN EXECUTION:
16
+ * running someone's suite needs their fixtures, auth, environment and a live
17
+ * app. Reading it needs none of those. The tradeoff is that a static read
18
+ * cannot know runtime values or which page it is on — see `url` below.
19
+ *
20
+ * A DELIBERATE WIN: a non-literal argument becomes a `valueRef` rather than a
21
+ * value. `page.getByRole('textbox', {name: 'Email'}).fill(MEMBER.email)`
22
+ * records `valueRef: 'MEMBER.email'` — which is exactly the parameterised shape
23
+ * the IR wants, arrived at for free.
24
+ */
25
+ import { type RawRecording } from '../../core/recording.js';
26
+ export interface ParsedScript {
27
+ recording: RawRecording;
28
+ /** Calls that looked like Playwright actions but could not be mapped. */
29
+ warnings: string[];
30
+ }
31
+ /**
32
+ * A text constraint, which Playwright lets you write either way.
33
+ *
34
+ * `{ name: 'Sign in' }` and `{ name: /^Sign in$/ }` mean different things — the
35
+ * first is a substring match, the second is anchored — so the regex-ness has to
36
+ * survive into the IR rather than being flattened to its source text.
37
+ */
38
+ export interface TextMatch {
39
+ source: string;
40
+ regex: boolean;
41
+ flags: string;
42
+ }
43
+ export declare function parseScript(filePath: string, appSlug: string, fallbackUrl?: string): Promise<ParsedScript>;