@jeffawe/understudy 0.0.0-stage → 0.2.1
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 +201 -0
- package/README.md +166 -2
- package/REASONER.md +67 -0
- package/build/extension/firefox/background.js +186 -0
- package/build/extension/firefox/icons/icon-128.png +0 -0
- package/build/extension/firefox/icons/icon-16.png +0 -0
- package/build/extension/firefox/icons/icon-32.png +0 -0
- package/build/extension/firefox/icons/icon-48.png +0 -0
- package/build/extension/firefox/manifest.json +54 -0
- package/build/extension/firefox/popup.html +52 -0
- package/build/extension/firefox/popup.js +106 -0
- package/build/extension/firefox/recorder.js +362 -0
- package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
- package/dist/adapters/recorder/accname-bundle.js +12 -0
- package/dist/adapters/recorder/extension.d.ts +57 -0
- package/dist/adapters/recorder/extension.js +146 -0
- package/dist/adapters/recorder/injected.d.ts +21 -0
- package/dist/adapters/recorder/injected.js +352 -0
- package/dist/adapters/recorder/live.d.ts +105 -0
- package/dist/adapters/recorder/live.js +317 -0
- package/dist/adapters/recorder/script.d.ts +43 -0
- package/dist/adapters/recorder/script.js +530 -0
- package/dist/adapters/recorder/wire.d.ts +42 -0
- package/dist/adapters/recorder/wire.js +51 -0
- package/dist/core/auth-cache.d.ts +119 -0
- package/dist/core/auth-cache.js +216 -0
- package/dist/core/browser.d.ts +47 -0
- package/dist/core/browser.js +82 -0
- package/dist/core/distill.d.ts +118 -0
- package/dist/core/distill.js +197 -0
- package/dist/core/fingerprint.d.ts +15 -0
- package/dist/core/fingerprint.js +21 -0
- package/dist/core/recording-store.d.ts +34 -0
- package/dist/core/recording-store.js +64 -0
- package/dist/core/recording.d.ts +185 -0
- package/dist/core/recording.js +100 -0
- package/dist/core/replay.d.ts +307 -0
- package/dist/core/replay.js +804 -0
- package/dist/core/sig.d.ts +70 -0
- package/dist/core/sig.js +0 -0
- package/dist/core/trigger.d.ts +18 -0
- package/dist/core/trigger.js +35 -0
- package/dist/core/types.d.ts +28 -0
- package/dist/core/types.js +8 -0
- package/dist/core/visual.d.ts +80 -0
- package/dist/core/visual.js +111 -0
- package/dist/entry/cli.d.ts +9 -0
- package/dist/entry/cli.js +1016 -0
- package/dist/entry/mcp.d.ts +20 -0
- package/dist/entry/mcp.js +288 -0
- package/dist/flows/destructive.d.ts +19 -0
- package/dist/flows/destructive.js +48 -0
- package/dist/flows/distill.d.ts +28 -0
- package/dist/flows/distill.js +109 -0
- package/dist/flows/drift.d.ts +43 -0
- package/dist/flows/drift.js +116 -0
- package/dist/flows/emit.d.ts +23 -0
- package/dist/flows/emit.js +133 -0
- package/dist/flows/execute.d.ts +75 -0
- package/dist/flows/execute.js +133 -0
- package/dist/flows/findings.d.ts +38 -0
- package/dist/flows/findings.js +136 -0
- package/dist/flows/runs.d.ts +42 -0
- package/dist/flows/runs.js +93 -0
- package/dist/flows/save.d.ts +74 -0
- package/dist/flows/save.js +171 -0
- package/dist/memory/notes.d.ts +89 -0
- package/dist/memory/notes.js +163 -0
- package/dist/memory/placeholders.d.ts +41 -0
- package/dist/memory/placeholders.js +139 -0
- package/dist/memory/recall.d.ts +118 -0
- package/dist/memory/recall.js +147 -0
- package/dist/memory/vocabulary.d.ts +9 -0
- package/dist/memory/vocabulary.js +24 -0
- package/dist/plan/planner.d.ts +69 -0
- package/dist/plan/planner.js +211 -0
- package/dist/plan/seams.d.ts +58 -0
- package/dist/plan/seams.js +99 -0
- package/dist/store/db.d.ts +62 -0
- package/dist/store/db.js +183 -0
- package/dist/store/embed.d.ts +46 -0
- package/dist/store/embed.js +100 -0
- package/dist/store/reembed.d.ts +13 -0
- package/dist/store/reembed.js +32 -0
- package/dist/store/settings.d.ts +67 -0
- package/dist/store/settings.js +151 -0
- package/dist/store/types.d.ts +220 -0
- package/dist/store/types.js +14 -0
- package/extension/README.md +76 -0
- package/extension/background.js +186 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +38 -0
- package/extension/popup.html +52 -0
- package/extension/popup.js +106 -0
- package/extension/recorder.js +362 -0
- package/package.json +68 -4
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved browser sessions, keyed by the credentials that produced them.
|
|
3
|
+
*
|
|
4
|
+
* THE PROBLEM THIS SOLVES IS MEASURED, NOT THEORETICAL. Every replay does a
|
|
5
|
+
* cold login and `distill` replays again, so verify-then-ingest costs 2–3
|
|
6
|
+
* logins per recording — against an app that locks the account for 15 minutes
|
|
7
|
+
* after a handful of attempts (REASONER.md, "Logins are often rate limited").
|
|
8
|
+
* A restored session skips the login entirely.
|
|
9
|
+
*
|
|
10
|
+
* IT IS A CACHE, NEVER A SUBSTITUTE FOR PROOF. A saved session may satisfy a
|
|
11
|
+
* PRELUDE — the part we deliberately did not record — and must never satisfy
|
|
12
|
+
* the steps under verification. If a recording's own steps are the login, they
|
|
13
|
+
* have to run, or ingest "proves" a flow it never executed. Callers enforce
|
|
14
|
+
* that by choosing what to pass `storageState` to; nothing here can.
|
|
15
|
+
*
|
|
16
|
+
* ON DISK, NOT IN THE DATABASE. `storageState` holds live session cookies and
|
|
17
|
+
* tokens — a credential in every meaningful sense. A gitignored local file at
|
|
18
|
+
* 0600 is a materially smaller blast radius than a row in a cloud cluster, and
|
|
19
|
+
* follows the same reasoning that already keeps `.understudy/recordings/` out
|
|
20
|
+
* of git.
|
|
21
|
+
*/
|
|
22
|
+
import type { BrowserContext } from 'playwright';
|
|
23
|
+
export declare const SESSIONS_DIR: string;
|
|
24
|
+
/** Playwright's storageState payload. Opaque to us — we store and replay it. */
|
|
25
|
+
export type StorageState = Awaited<ReturnType<BrowserContext['storageState']>>;
|
|
26
|
+
export interface CachedSession {
|
|
27
|
+
version: 1;
|
|
28
|
+
appSlug: string;
|
|
29
|
+
/** The credential fingerprint this session belongs to. */
|
|
30
|
+
key: string;
|
|
31
|
+
savedAt: string;
|
|
32
|
+
/**
|
|
33
|
+
* The page fingerprint observed when this session was saved.
|
|
34
|
+
*
|
|
35
|
+
* This is the staleness oracle. An expired session does not announce itself —
|
|
36
|
+
* the app simply serves the login page at a URL that used to be the account
|
|
37
|
+
* page, which is exactly the case `sig()` exists to distinguish and a URL
|
|
38
|
+
* check cannot (REASONER: `/inventory.html` served the login page when
|
|
39
|
+
* unauthenticated).
|
|
40
|
+
*/
|
|
41
|
+
expectedSig?: string;
|
|
42
|
+
storageState: StorageState;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Fingerprint the credentials a session was established with.
|
|
46
|
+
*
|
|
47
|
+
* KEYED ON ALL SUPPLIED VALUES, deliberately. Narrowing this to the refs that
|
|
48
|
+
* "look like" credentials would be a heuristic, and the two failure directions
|
|
49
|
+
* are wildly asymmetric: an over-broad key costs one unnecessary login, while a
|
|
50
|
+
* key missing a component that actually distinguishes two users hands you
|
|
51
|
+
* SOMEONE ELSE'S SESSION. So it fails toward fragmentation.
|
|
52
|
+
*
|
|
53
|
+
* Only the hash is ever written down — the values themselves are customer data
|
|
54
|
+
* on a real app, and the point of `valueRef` is that they never reach disk.
|
|
55
|
+
*/
|
|
56
|
+
export declare function authKey(appSlug: string, values: Record<string, string>, prelude?: string[]): string | undefined;
|
|
57
|
+
export declare function sessionPath(appSlug: string, key: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Load the session saved for these exact credentials, if one is still worth
|
|
60
|
+
* trying. Age is the only thing checked here; liveness needs a browser.
|
|
61
|
+
*/
|
|
62
|
+
export declare function loadSession(appSlug: string, values: Record<string, string>, prelude?: string[]): Promise<CachedSession | undefined>;
|
|
63
|
+
/**
|
|
64
|
+
* Save the context's current session under these credentials.
|
|
65
|
+
*
|
|
66
|
+
* Returns the path so the caller can SAY where it went. Writing live tokens to
|
|
67
|
+
* disk silently would be the wrong kind of convenience.
|
|
68
|
+
*/
|
|
69
|
+
export declare function saveSession(context: BrowserContext, appSlug: string, values: Record<string, string>, expectedSig?: string, prelude?: string[]): Promise<string | undefined>;
|
|
70
|
+
/**
|
|
71
|
+
* Drop a saved session once it proves stale.
|
|
72
|
+
*
|
|
73
|
+
* There is no `isSessionLive` here on purpose. Liveness is already answered by
|
|
74
|
+
* machinery that exists: a late-armed recording carries the arming fingerprint
|
|
75
|
+
* as step 0's `expectedSig`, so replay's ordinary "am I where I expected to
|
|
76
|
+
* be?" check reports a dead session as an unexpected page. A second, private
|
|
77
|
+
* probe would be a duplicate oracle that could disagree with the first.
|
|
78
|
+
*/
|
|
79
|
+
export declare function forgetSession(appSlug: string, values: Record<string, string>, prelude?: string[]): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* Park a paused run's browser state so a human can pick it up in another window.
|
|
82
|
+
*
|
|
83
|
+
* SEPARATE FROM THE CREDENTIAL CACHE, and keyed by RUN rather than by
|
|
84
|
+
* credentials, because it is not a cache: it is a one-shot handover of a
|
|
85
|
+
* specific paused browser, valid only until that run finishes. Reusing the
|
|
86
|
+
* credential key would let a handoff overwrite the session cache with a
|
|
87
|
+
* mid-flow state, which is the cross-contamination the prelude salt exists to
|
|
88
|
+
* prevent.
|
|
89
|
+
*
|
|
90
|
+
* The PATH is what gets handed to the reasoner, never the state. `storageState`
|
|
91
|
+
* holds live tokens, and `context_requests.payload` is a JSONB column in a
|
|
92
|
+
* cluster that may be hosted — a credential must not make that trip.
|
|
93
|
+
*/
|
|
94
|
+
export declare function saveHandoffSession(storageState: StorageState, runId: string, meta: {
|
|
95
|
+
url: string;
|
|
96
|
+
sig?: string;
|
|
97
|
+
}): Promise<string>;
|
|
98
|
+
export interface HandoffSession {
|
|
99
|
+
version: 1;
|
|
100
|
+
runId: string;
|
|
101
|
+
savedAt: string;
|
|
102
|
+
url: string;
|
|
103
|
+
sig?: string;
|
|
104
|
+
storageState: StorageState;
|
|
105
|
+
}
|
|
106
|
+
export declare function handoffPath(runId: string): string;
|
|
107
|
+
export declare function loadHandoffSession(path: string): Promise<HandoffSession | undefined>;
|
|
108
|
+
/** Handoff state is one-shot; leaving live tokens on disk after the run is not. */
|
|
109
|
+
export declare function forgetHandoffSession(runId: string): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* A session named by id rather than by credentials — the Chrome extension
|
|
112
|
+
* captures the signed-in tab it records from, with no --value to key it on.
|
|
113
|
+
* Same file format and the same 0600 file as every other saved session.
|
|
114
|
+
*/
|
|
115
|
+
export declare function saveSessionById(appSlug: string, id: string, storageState: StorageState, expectedSig?: string): Promise<string>;
|
|
116
|
+
/** Load a session saved by id, if it exists and is young enough to be worth trying. */
|
|
117
|
+
export declare function loadSessionById(appSlug: string, id: string): Promise<CachedSession | undefined>;
|
|
118
|
+
/** Drop a session saved by id. */
|
|
119
|
+
export declare function forgetSessionById(appSlug: string, id: string): Promise<void>;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved browser sessions, keyed by the credentials that produced them.
|
|
3
|
+
*
|
|
4
|
+
* THE PROBLEM THIS SOLVES IS MEASURED, NOT THEORETICAL. Every replay does a
|
|
5
|
+
* cold login and `distill` replays again, so verify-then-ingest costs 2–3
|
|
6
|
+
* logins per recording — against an app that locks the account for 15 minutes
|
|
7
|
+
* after a handful of attempts (REASONER.md, "Logins are often rate limited").
|
|
8
|
+
* A restored session skips the login entirely.
|
|
9
|
+
*
|
|
10
|
+
* IT IS A CACHE, NEVER A SUBSTITUTE FOR PROOF. A saved session may satisfy a
|
|
11
|
+
* PRELUDE — the part we deliberately did not record — and must never satisfy
|
|
12
|
+
* the steps under verification. If a recording's own steps are the login, they
|
|
13
|
+
* have to run, or ingest "proves" a flow it never executed. Callers enforce
|
|
14
|
+
* that by choosing what to pass `storageState` to; nothing here can.
|
|
15
|
+
*
|
|
16
|
+
* ON DISK, NOT IN THE DATABASE. `storageState` holds live session cookies and
|
|
17
|
+
* tokens — a credential in every meaningful sense. A gitignored local file at
|
|
18
|
+
* 0600 is a materially smaller blast radius than a row in a cloud cluster, and
|
|
19
|
+
* follows the same reasoning that already keeps `.understudy/recordings/` out
|
|
20
|
+
* of git.
|
|
21
|
+
*/
|
|
22
|
+
import { createHash } from 'node:crypto';
|
|
23
|
+
import { chmod, mkdir, readFile, writeFile, unlink } from 'node:fs/promises';
|
|
24
|
+
import { existsSync } from 'node:fs';
|
|
25
|
+
import { join, resolve } from 'node:path';
|
|
26
|
+
export const SESSIONS_DIR = process.env.UNDERSTUDY_SESSIONS_DIR ?? resolve('.understudy/sessions');
|
|
27
|
+
/**
|
|
28
|
+
* How long a saved session is worth trying at all.
|
|
29
|
+
*
|
|
30
|
+
* A cheap pre-filter, not the real check — `sessionIsLive` is what actually
|
|
31
|
+
* decides. This only avoids launching a browser around state that is certainly
|
|
32
|
+
* dead. Deliberately shorter than a typical "remember me" cookie: the cost of
|
|
33
|
+
* being wrong is one extra login, and the cost of being right is nothing.
|
|
34
|
+
*/
|
|
35
|
+
const MAX_AGE_MS = 12 * 60 * 60 * 1000;
|
|
36
|
+
/**
|
|
37
|
+
* Fingerprint the credentials a session was established with.
|
|
38
|
+
*
|
|
39
|
+
* KEYED ON ALL SUPPLIED VALUES, deliberately. Narrowing this to the refs that
|
|
40
|
+
* "look like" credentials would be a heuristic, and the two failure directions
|
|
41
|
+
* are wildly asymmetric: an over-broad key costs one unnecessary login, while a
|
|
42
|
+
* key missing a component that actually distinguishes two users hands you
|
|
43
|
+
* SOMEONE ELSE'S SESSION. So it fails toward fragmentation.
|
|
44
|
+
*
|
|
45
|
+
* Only the hash is ever written down — the values themselves are customer data
|
|
46
|
+
* on a real app, and the point of `valueRef` is that they never reach disk.
|
|
47
|
+
*/
|
|
48
|
+
export function authKey(appSlug, values, prelude = []) {
|
|
49
|
+
const refs = Object.keys(values).sort();
|
|
50
|
+
// Nothing to key on. A session shared by every credential-free run would be
|
|
51
|
+
// indistinguishable from "whoever logged in last", which is not a cache.
|
|
52
|
+
if (!refs.length)
|
|
53
|
+
return undefined;
|
|
54
|
+
const material = refs.map((ref) => `${ref}=${values[ref]}`).join('\n');
|
|
55
|
+
// THE PRELUDE IS PART OF THE KEY, for the same fail-toward-fragmentation
|
|
56
|
+
// reason the credentials are. A session banked after `--after complete-intake`
|
|
57
|
+
// holds a browser that is mid-wizard; a plain `--arm-manually` run for the
|
|
58
|
+
// same credentials would restore it and land somewhere the operator never
|
|
59
|
+
// asked to be. Keyed separately, that is a cache miss and one honest login.
|
|
60
|
+
// Empty prelude appends nothing, so every key written before this existed is
|
|
61
|
+
// unchanged.
|
|
62
|
+
const salt = prelude.length ? `\nprelude=${prelude.join('>')}` : '';
|
|
63
|
+
return createHash('sha256').update(`${appSlug}\n${material}${salt}`).digest('hex').slice(0, 16);
|
|
64
|
+
}
|
|
65
|
+
export function sessionPath(appSlug, key) {
|
|
66
|
+
return join(SESSIONS_DIR, `${appSlug}-${key}.json`);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Load the session saved for these exact credentials, if one is still worth
|
|
70
|
+
* trying. Age is the only thing checked here; liveness needs a browser.
|
|
71
|
+
*/
|
|
72
|
+
export async function loadSession(appSlug, values, prelude) {
|
|
73
|
+
const key = authKey(appSlug, values, prelude);
|
|
74
|
+
if (!key)
|
|
75
|
+
return undefined;
|
|
76
|
+
const path = sessionPath(appSlug, key);
|
|
77
|
+
if (!existsSync(path))
|
|
78
|
+
return undefined;
|
|
79
|
+
try {
|
|
80
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
81
|
+
if (parsed.version !== 1)
|
|
82
|
+
return undefined;
|
|
83
|
+
if (Date.now() - Date.parse(parsed.savedAt) > MAX_AGE_MS)
|
|
84
|
+
return undefined;
|
|
85
|
+
return parsed;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// A corrupt cache entry is not an error worth stopping for — the fallback
|
|
89
|
+
// is logging in, which is what would have happened anyway.
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Save the context's current session under these credentials.
|
|
95
|
+
*
|
|
96
|
+
* Returns the path so the caller can SAY where it went. Writing live tokens to
|
|
97
|
+
* disk silently would be the wrong kind of convenience.
|
|
98
|
+
*/
|
|
99
|
+
export async function saveSession(context, appSlug, values, expectedSig, prelude) {
|
|
100
|
+
const key = authKey(appSlug, values, prelude);
|
|
101
|
+
if (!key)
|
|
102
|
+
return undefined;
|
|
103
|
+
const state = await context.storageState();
|
|
104
|
+
await mkdir(SESSIONS_DIR, { recursive: true, mode: 0o700 });
|
|
105
|
+
const path = sessionPath(appSlug, key);
|
|
106
|
+
const entry = {
|
|
107
|
+
version: 1,
|
|
108
|
+
appSlug,
|
|
109
|
+
key,
|
|
110
|
+
savedAt: new Date().toISOString(),
|
|
111
|
+
...(expectedSig ? { expectedSig } : {}),
|
|
112
|
+
storageState: state,
|
|
113
|
+
};
|
|
114
|
+
await writeFile(path, JSON.stringify(entry, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
115
|
+
// `writeFile`'s mode applies only when it CREATES the file, so an entry
|
|
116
|
+
// written before this line existed would keep its old permissions forever.
|
|
117
|
+
// Setting them explicitly makes the guarantee hold on every save.
|
|
118
|
+
await chmod(path, 0o600).catch(() => { });
|
|
119
|
+
return path;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Drop a saved session once it proves stale.
|
|
123
|
+
*
|
|
124
|
+
* There is no `isSessionLive` here on purpose. Liveness is already answered by
|
|
125
|
+
* machinery that exists: a late-armed recording carries the arming fingerprint
|
|
126
|
+
* as step 0's `expectedSig`, so replay's ordinary "am I where I expected to
|
|
127
|
+
* be?" check reports a dead session as an unexpected page. A second, private
|
|
128
|
+
* probe would be a duplicate oracle that could disagree with the first.
|
|
129
|
+
*/
|
|
130
|
+
export async function forgetSession(appSlug, values, prelude) {
|
|
131
|
+
const key = authKey(appSlug, values, prelude);
|
|
132
|
+
if (!key)
|
|
133
|
+
return;
|
|
134
|
+
await unlink(sessionPath(appSlug, key)).catch(() => { });
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Park a paused run's browser state so a human can pick it up in another window.
|
|
138
|
+
*
|
|
139
|
+
* SEPARATE FROM THE CREDENTIAL CACHE, and keyed by RUN rather than by
|
|
140
|
+
* credentials, because it is not a cache: it is a one-shot handover of a
|
|
141
|
+
* specific paused browser, valid only until that run finishes. Reusing the
|
|
142
|
+
* credential key would let a handoff overwrite the session cache with a
|
|
143
|
+
* mid-flow state, which is the cross-contamination the prelude salt exists to
|
|
144
|
+
* prevent.
|
|
145
|
+
*
|
|
146
|
+
* The PATH is what gets handed to the reasoner, never the state. `storageState`
|
|
147
|
+
* holds live tokens, and `context_requests.payload` is a JSONB column in a
|
|
148
|
+
* cluster that may be hosted — a credential must not make that trip.
|
|
149
|
+
*/
|
|
150
|
+
export async function saveHandoffSession(storageState, runId, meta) {
|
|
151
|
+
await mkdir(SESSIONS_DIR, { recursive: true, mode: 0o700 });
|
|
152
|
+
const path = handoffPath(runId);
|
|
153
|
+
const payload = {
|
|
154
|
+
version: 1,
|
|
155
|
+
runId,
|
|
156
|
+
savedAt: new Date().toISOString(),
|
|
157
|
+
url: meta.url,
|
|
158
|
+
...(meta.sig ? { sig: meta.sig } : {}),
|
|
159
|
+
storageState,
|
|
160
|
+
};
|
|
161
|
+
await writeFile(path, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
162
|
+
await chmod(path, 0o600).catch(() => { });
|
|
163
|
+
return path;
|
|
164
|
+
}
|
|
165
|
+
export function handoffPath(runId) {
|
|
166
|
+
return join(SESSIONS_DIR, `handoff-${runId}.json`);
|
|
167
|
+
}
|
|
168
|
+
export async function loadHandoffSession(path) {
|
|
169
|
+
try {
|
|
170
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
171
|
+
return parsed.version === 1 ? parsed : undefined;
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** Handoff state is one-shot; leaving live tokens on disk after the run is not. */
|
|
178
|
+
export async function forgetHandoffSession(runId) {
|
|
179
|
+
await unlink(handoffPath(runId)).catch(() => { });
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* A session named by id rather than by credentials — the Chrome extension
|
|
183
|
+
* captures the signed-in tab it records from, with no --value to key it on.
|
|
184
|
+
* Same file format and the same 0600 file as every other saved session.
|
|
185
|
+
*/
|
|
186
|
+
export async function saveSessionById(appSlug, id, storageState, expectedSig) {
|
|
187
|
+
await mkdir(SESSIONS_DIR, { recursive: true, mode: 0o700 });
|
|
188
|
+
const path = sessionPath(appSlug, id);
|
|
189
|
+
const entry = {
|
|
190
|
+
version: 1, appSlug, key: id, savedAt: new Date().toISOString(),
|
|
191
|
+
...(expectedSig ? { expectedSig } : {}),
|
|
192
|
+
storageState,
|
|
193
|
+
};
|
|
194
|
+
await writeFile(path, JSON.stringify(entry, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
195
|
+
await chmod(path, 0o600).catch(() => { });
|
|
196
|
+
return path;
|
|
197
|
+
}
|
|
198
|
+
/** Load a session saved by id, if it exists and is young enough to be worth trying. */
|
|
199
|
+
export async function loadSessionById(appSlug, id) {
|
|
200
|
+
const path = sessionPath(appSlug, id);
|
|
201
|
+
if (!existsSync(path))
|
|
202
|
+
return undefined;
|
|
203
|
+
try {
|
|
204
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
205
|
+
if (parsed.version !== 1 || Date.now() - Date.parse(parsed.savedAt) > MAX_AGE_MS)
|
|
206
|
+
return undefined;
|
|
207
|
+
return parsed;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/** Drop a session saved by id. */
|
|
214
|
+
export async function forgetSessionById(appSlug, id) {
|
|
215
|
+
await unlink(sessionPath(appSlug, id)).catch(() => { });
|
|
216
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A browser someone else may own.
|
|
3
|
+
*
|
|
4
|
+
* Replay and the live recorder each used to launch their own Chromium and close
|
|
5
|
+
* it unconditionally. That is correct when they are the only thing running, and
|
|
6
|
+
* it is exactly what blocks the two flows this module exists for:
|
|
7
|
+
*
|
|
8
|
+
* - REPLAY A PRELUDE, THEN CAPTURE. Wizard progress is server-side, so it is
|
|
9
|
+
* not in `storageState` and cannot be restored the way a login can. The only
|
|
10
|
+
* way past an intake is to actually walk it — in the SAME context the
|
|
11
|
+
* recorder is about to capture from. Two browsers cannot share that state.
|
|
12
|
+
*
|
|
13
|
+
* - HAND A STUCK RUN TO A HUMAN. The run's context must stay alive and paused
|
|
14
|
+
* while something else drives.
|
|
15
|
+
*
|
|
16
|
+
* So ownership becomes explicit: whoever launched the browser closes it, and a
|
|
17
|
+
* borrower closes nothing. Getting this wrong in either direction is quiet —
|
|
18
|
+
* a double close throws into a `.catch(() => {})`, and a missing close leaks a
|
|
19
|
+
* Chromium per run until the box runs out of memory.
|
|
20
|
+
*/
|
|
21
|
+
import { type Browser, type BrowserContext, type Page } from 'playwright';
|
|
22
|
+
import type { StorageState } from './auth-cache.js';
|
|
23
|
+
export interface BrowserLease {
|
|
24
|
+
browser: Browser;
|
|
25
|
+
context: BrowserContext;
|
|
26
|
+
page: Page;
|
|
27
|
+
/** True when this lease launched the browser and is therefore responsible for it. */
|
|
28
|
+
owned: boolean;
|
|
29
|
+
/** Close the browser — a no-op for a borrowed lease. */
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Replace cookies and origin storage in place.
|
|
33
|
+
*
|
|
34
|
+
* Playwright has no `context.setStorageState()`, so this is the closest thing:
|
|
35
|
+
* it restores what a fresh `newContext({ storageState })` would have, on a
|
|
36
|
+
* context that already exists. It cannot restore in-page JS state — an open
|
|
37
|
+
* modal, an unsaved form — because that lives in a document this does not
|
|
38
|
+
* touch. Callers navigate afterwards and verify with `sig()`.
|
|
39
|
+
*/
|
|
40
|
+
reseed(state: StorageState): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export declare function openLease(opts?: {
|
|
43
|
+
headless?: boolean;
|
|
44
|
+
storageState?: StorageState;
|
|
45
|
+
}): Promise<BrowserLease>;
|
|
46
|
+
/** Borrow a context someone else opened. Closing it is their business, not ours. */
|
|
47
|
+
export declare function adoptLease(context: BrowserContext, page: Page): BrowserLease;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A browser someone else may own.
|
|
3
|
+
*
|
|
4
|
+
* Replay and the live recorder each used to launch their own Chromium and close
|
|
5
|
+
* it unconditionally. That is correct when they are the only thing running, and
|
|
6
|
+
* it is exactly what blocks the two flows this module exists for:
|
|
7
|
+
*
|
|
8
|
+
* - REPLAY A PRELUDE, THEN CAPTURE. Wizard progress is server-side, so it is
|
|
9
|
+
* not in `storageState` and cannot be restored the way a login can. The only
|
|
10
|
+
* way past an intake is to actually walk it — in the SAME context the
|
|
11
|
+
* recorder is about to capture from. Two browsers cannot share that state.
|
|
12
|
+
*
|
|
13
|
+
* - HAND A STUCK RUN TO A HUMAN. The run's context must stay alive and paused
|
|
14
|
+
* while something else drives.
|
|
15
|
+
*
|
|
16
|
+
* So ownership becomes explicit: whoever launched the browser closes it, and a
|
|
17
|
+
* borrower closes nothing. Getting this wrong in either direction is quiet —
|
|
18
|
+
* a double close throws into a `.catch(() => {})`, and a missing close leaks a
|
|
19
|
+
* Chromium per run until the box runs out of memory.
|
|
20
|
+
*/
|
|
21
|
+
import { chromium } from 'playwright';
|
|
22
|
+
/**
|
|
23
|
+
* Restore origin storage on the next document, since it cannot be set from here.
|
|
24
|
+
*
|
|
25
|
+
* AUTHORED AS A STRING, for the reason `injected.ts` opens with: tsx/esbuild
|
|
26
|
+
* rewrites function declarations to preserve their names via a `__name()`
|
|
27
|
+
* helper, `addInitScript` serializes a closure with `.toString()`, and the
|
|
28
|
+
* injected body then references a helper the browser does not have. It fails
|
|
29
|
+
* silently — no storage restored, nothing logged.
|
|
30
|
+
*/
|
|
31
|
+
async function seedOriginStorage(context, state) {
|
|
32
|
+
const origins = state.origins ?? [];
|
|
33
|
+
if (!origins.length)
|
|
34
|
+
return;
|
|
35
|
+
// U+2028/U+2029 are legal in JSON strings; escaping them keeps the embedded
|
|
36
|
+
// literal valid JavaScript regardless of how the script is later parsed.
|
|
37
|
+
const payload = JSON.stringify(origins)
|
|
38
|
+
.replace(/\u2028/g, '\\u2028')
|
|
39
|
+
.replace(/\u2029/g, '\\u2029');
|
|
40
|
+
await context.addInitScript(`
|
|
41
|
+
(() => {
|
|
42
|
+
var origins = ${payload};
|
|
43
|
+
var here = window.location.origin;
|
|
44
|
+
for (var i = 0; i < origins.length; i++) {
|
|
45
|
+
if (origins[i].origin !== here) continue;
|
|
46
|
+
var items = origins[i].localStorage || [];
|
|
47
|
+
for (var j = 0; j < items.length; j++) {
|
|
48
|
+
try { window.localStorage.setItem(items[j].name, items[j].value); } catch (e) {}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
})();
|
|
52
|
+
`);
|
|
53
|
+
}
|
|
54
|
+
function leaseFor(browser, context, page, owned) {
|
|
55
|
+
return {
|
|
56
|
+
browser,
|
|
57
|
+
context,
|
|
58
|
+
page,
|
|
59
|
+
owned,
|
|
60
|
+
async close() {
|
|
61
|
+
if (!owned)
|
|
62
|
+
return;
|
|
63
|
+
await browser.close().catch(() => { });
|
|
64
|
+
},
|
|
65
|
+
async reseed(state) {
|
|
66
|
+
await context.clearCookies();
|
|
67
|
+
if (state.cookies?.length)
|
|
68
|
+
await context.addCookies(state.cookies);
|
|
69
|
+
await seedOriginStorage(context, state);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export async function openLease(opts = {}) {
|
|
74
|
+
const browser = await chromium.launch({ headless: opts.headless ?? true });
|
|
75
|
+
const context = await browser.newContext(opts.storageState ? { storageState: opts.storageState } : {});
|
|
76
|
+
const page = await context.newPage();
|
|
77
|
+
return leaseFor(browser, context, page, true);
|
|
78
|
+
}
|
|
79
|
+
/** Borrow a context someone else opened. Closing it is their business, not ours. */
|
|
80
|
+
export function adoptLease(context, page) {
|
|
81
|
+
return leaseFor(context.browser(), context, page, false);
|
|
82
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Distillation — an agent annotates a saved flow and splits it into segments.
|
|
3
|
+
*
|
|
4
|
+
* Optional. A flow is stored and runnable without it; distilling adds what a
|
|
5
|
+
* person would say the flow is FOR (intent, preconditions, outcome), cuts it
|
|
6
|
+
* into reusable segments (e.g. "log in as a member" out of a checkout
|
|
7
|
+
* recording, so other goals can reuse it), and may suggest lessons.
|
|
8
|
+
*
|
|
9
|
+
* THE AGENT ANNOTATES; IT DOES NOT AUTHOR STEPS. The steps were captured by
|
|
10
|
+
* the recorder and proven by replay; the request numbers them and the answer
|
|
11
|
+
* may only refer to them BY INDEX. It can partition and name, never fabricate.
|
|
12
|
+
* That constraint is what makes it safe to let an agent do this at all.
|
|
13
|
+
*
|
|
14
|
+
* This file is the contract: the request, the answer's schema, and the
|
|
15
|
+
* validator. src/flows/distill.ts builds requests from MongoDB and saves answers.
|
|
16
|
+
*/
|
|
17
|
+
import type { RawRecording } from './recording.js';
|
|
18
|
+
import type { ReplayResult } from './replay.js';
|
|
19
|
+
/**
|
|
20
|
+
* What the app already knows, handed to the distiller so it reuses existing
|
|
21
|
+
* segment slugs instead of inventing synonyms. Built from MongoDB in phase 4.
|
|
22
|
+
*/
|
|
23
|
+
export interface Vocabulary {
|
|
24
|
+
/** Reusable segments — the primary vocabulary, what a sub-goal binds to. */
|
|
25
|
+
segments: Array<{
|
|
26
|
+
slug: string;
|
|
27
|
+
title: string;
|
|
28
|
+
intent: string;
|
|
29
|
+
steps: number;
|
|
30
|
+
preconditions: string[];
|
|
31
|
+
outcome: string | null;
|
|
32
|
+
}>;
|
|
33
|
+
/** Whole recorded flows, for coarser matches. */
|
|
34
|
+
flows: Array<{
|
|
35
|
+
slug: string;
|
|
36
|
+
title: string;
|
|
37
|
+
intent: string;
|
|
38
|
+
}>;
|
|
39
|
+
/** What is known to be true about the app, phrased as the corpus phrases it. */
|
|
40
|
+
facts: string[];
|
|
41
|
+
}
|
|
42
|
+
/** One verified step, as handed to the distiller. */
|
|
43
|
+
export interface DistillStep {
|
|
44
|
+
index: number;
|
|
45
|
+
action: string;
|
|
46
|
+
role?: string;
|
|
47
|
+
name?: string;
|
|
48
|
+
value?: string;
|
|
49
|
+
valueRef?: string;
|
|
50
|
+
/** Page fingerprint after this step — the state boundary segments cut on. */
|
|
51
|
+
sigAfter?: string;
|
|
52
|
+
url: string;
|
|
53
|
+
}
|
|
54
|
+
export interface DistillRequest {
|
|
55
|
+
recordingHash: string;
|
|
56
|
+
appSlug: string;
|
|
57
|
+
startUrl: string;
|
|
58
|
+
steps: DistillStep[];
|
|
59
|
+
/**
|
|
60
|
+
* What this app already calls things.
|
|
61
|
+
*
|
|
62
|
+
* Without it, a second recording of the same login block gets a synonym
|
|
63
|
+
* instead of the existing name, and the two compete for the same bind slot
|
|
64
|
+
* forever after. The distiller is told to REUSE these words where the same
|
|
65
|
+
* thing recurs.
|
|
66
|
+
*/
|
|
67
|
+
vocabulary: Vocabulary;
|
|
68
|
+
/** Human-readable instructions. The schema below is the contract. */
|
|
69
|
+
instructions: string;
|
|
70
|
+
schema: Record<string, unknown>;
|
|
71
|
+
}
|
|
72
|
+
/** What the distiller must return. Validated before anything is written. */
|
|
73
|
+
export interface Distilled {
|
|
74
|
+
intent: string;
|
|
75
|
+
preconditions: string[];
|
|
76
|
+
outcome: string;
|
|
77
|
+
segments: Array<{
|
|
78
|
+
slug: string;
|
|
79
|
+
title: string;
|
|
80
|
+
intent: string;
|
|
81
|
+
/** Inclusive start, exclusive end, into the steps array handed over. */
|
|
82
|
+
stepRange: [number, number];
|
|
83
|
+
preconditions?: string[];
|
|
84
|
+
outcome?: string;
|
|
85
|
+
}>;
|
|
86
|
+
candidateLessons?: Array<{
|
|
87
|
+
kind: string;
|
|
88
|
+
title: string;
|
|
89
|
+
body: string;
|
|
90
|
+
trigger: Record<string, unknown>;
|
|
91
|
+
}>;
|
|
92
|
+
corrections?: Array<{
|
|
93
|
+
rule: string;
|
|
94
|
+
detail: string;
|
|
95
|
+
stepIndex?: number;
|
|
96
|
+
}>;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Build the payload handed to whoever is distilling.
|
|
100
|
+
*
|
|
101
|
+
* Only steps that REPLAYED are included — an unverified step must never reach
|
|
102
|
+
* the model, or it can end up named, segmented, and bound like a real one.
|
|
103
|
+
*/
|
|
104
|
+
export declare function buildDistillRequest(recording: RawRecording, replayResult: ReplayResult, vocabulary?: Vocabulary): DistillRequest;
|
|
105
|
+
export interface ValidationResult {
|
|
106
|
+
ok: boolean;
|
|
107
|
+
errors: string[];
|
|
108
|
+
value?: Distilled;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Validate a distillation before ANY of it is written.
|
|
112
|
+
*
|
|
113
|
+
* The server validates, not the agent — PLAN.md is explicit that a mismatch
|
|
114
|
+
* returns errors and the agent retries. This is the only thing standing between
|
|
115
|
+
* a malformed or hallucinated distillation and the corpus, so it checks
|
|
116
|
+
* structure AND the index arithmetic that keeps segments honest.
|
|
117
|
+
*/
|
|
118
|
+
export declare function validateDistilled(input: unknown, stepCount: number): ValidationResult;
|