@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,1016 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* understudy — command line. Agents use the MCP server (entry/mcp.ts) instead;
|
|
4
|
+
* both call the same functions underneath.
|
|
5
|
+
*
|
|
6
|
+
* Argument parsing is hand-rolled on purpose: the surface is small, and a
|
|
7
|
+
* parser library would be more code than it saves.
|
|
8
|
+
*/
|
|
9
|
+
import { recordLive } from '../adapters/recorder/live.js';
|
|
10
|
+
import { parseScript } from '../adapters/recorder/script.js';
|
|
11
|
+
import { startExtensionRecorder, DEFAULT_PORT, extensionDir, firefoxExtensionDir } from '../adapters/recorder/extension.js';
|
|
12
|
+
import { listRecordings, loadRecording, saveRecording } from '../core/recording-store.js';
|
|
13
|
+
import { loadSession, saveSession } from '../core/auth-cache.js';
|
|
14
|
+
import { buildRecording } from '../core/recording.js';
|
|
15
|
+
import { execute, prove, MissingValuesError } from '../flows/execute.js';
|
|
16
|
+
import { destructiveControls, remember } from '../memory/notes.js';
|
|
17
|
+
import { start, answer, runPlan } from '../plan/planner.js';
|
|
18
|
+
import { distillRequest, saveDistilled } from '../flows/distill.js';
|
|
19
|
+
import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
|
|
20
|
+
import { join, resolve as resolvePath } from 'node:path';
|
|
21
|
+
import { existsSync } from 'node:fs';
|
|
22
|
+
import { chromium } from 'playwright';
|
|
23
|
+
import { emitFlow } from '../flows/emit.js';
|
|
24
|
+
import { recordingFrom, proveAndSave, proveByRun } from '../flows/save.js';
|
|
25
|
+
import { recordRun } from '../flows/runs.js';
|
|
26
|
+
import { recall } from '../memory/recall.js';
|
|
27
|
+
import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
|
|
28
|
+
import * as store from '../store/db.js';
|
|
29
|
+
import { valueEnvName, readConfig, writeConfig, loadedFrom, HOME, expandHome, writeEnvValues } from '../store/settings.js';
|
|
30
|
+
// Piped into `head` and the pipe closed early: stop quietly, like other CLIs.
|
|
31
|
+
process.stdout.on('error', (e) => {
|
|
32
|
+
if (e.code === 'EPIPE')
|
|
33
|
+
process.exit(0);
|
|
34
|
+
throw e;
|
|
35
|
+
});
|
|
36
|
+
const USAGE = `understudy — learn a web app, then test it by intent
|
|
37
|
+
|
|
38
|
+
USAGE
|
|
39
|
+
understudy <command> [options]
|
|
40
|
+
|
|
41
|
+
COMMANDS
|
|
42
|
+
config where settings come from; set them, or point at an env file
|
|
43
|
+
doctor check the MongoDB connection, vector search and embedder
|
|
44
|
+
reembed rebuild every vector with the model now configured
|
|
45
|
+
record <app> capture a flow in your own Chrome, with the extension
|
|
46
|
+
extension where the Chrome extension is, and how to load it
|
|
47
|
+
app <app> an app's settings, e.g. --placeholder email
|
|
48
|
+
import <app> <file> read an existing Playwright script into a recording
|
|
49
|
+
recordings [app] list captured recordings
|
|
50
|
+
save <hash> "<name>" prove a recording by replaying it, then save it as a flow
|
|
51
|
+
flows <app> list an app's saved flows and how each last ran
|
|
52
|
+
replay <hash> re-run a recording file headless
|
|
53
|
+
replay <app> <flow> re-run a saved flow; records the run, drift and findings
|
|
54
|
+
findings <app> what looked broken, most frequent first
|
|
55
|
+
recall <app> "<goal>" what memory knows about a goal — nothing runs
|
|
56
|
+
run <app> "<goal>" find the flow that does the goal, and run it
|
|
57
|
+
answer <runId> <json> answer a question a planned run stopped on
|
|
58
|
+
distill <app> <flow> print a saved flow's steps for an agent to name and split
|
|
59
|
+
remember <app> <file> store facts, lessons and findings from a JSON batch
|
|
60
|
+
emit <app> <flow> print a saved flow as a Playwright or Cypress test
|
|
61
|
+
|
|
62
|
+
MCP server for agents: understudy-mcp (see REASONER.md).
|
|
63
|
+
|
|
64
|
+
RECORD (in your own Chrome — load extension/ unpacked once, see extension/README.md)
|
|
65
|
+
--port <n> port the extension talks to (default 7397)
|
|
66
|
+
|
|
67
|
+
RECORD --new-browser (opt-in: a fresh browser Understudy opens; needs
|
|
68
|
+
"npx playwright install chromium", ~350 MB)
|
|
69
|
+
--url <baseUrl> required the first time you use an app; remembered after
|
|
70
|
+
--max-minutes <n> stop recording after n minutes (default 30)
|
|
71
|
+
--arm-manually drive to the starting point yourself, unrecorded, then
|
|
72
|
+
press Enter to start capturing — e.g. to skip the login
|
|
73
|
+
--value REF=value credentials the saved session is keyed on (repeatable)
|
|
74
|
+
--fresh ignore any saved session and sign in again
|
|
75
|
+
|
|
76
|
+
IMPORT
|
|
77
|
+
--url <baseUrl> resolves goto('/') when the script relies on a baseURL
|
|
78
|
+
--until <n> keep only the first n steps (stop before a real purchase)
|
|
79
|
+
|
|
80
|
+
REPLAY and SAVE
|
|
81
|
+
--value REF=value supply a value the recording deliberately doesn't store,
|
|
82
|
+
e.g. --value SECRET.password=hunter2 (repeatable)
|
|
83
|
+
--headed watch it replay
|
|
84
|
+
--allow-purchases replay a flow marked destructive (refused by default)
|
|
85
|
+
|
|
86
|
+
SAVE
|
|
87
|
+
--slug <name> the flow's short name (default: made from the name)
|
|
88
|
+
--intent <text> what the flow is for, if different from its name
|
|
89
|
+
--force save even though the proving replay failed
|
|
90
|
+
|
|
91
|
+
FINDINGS
|
|
92
|
+
--all include findings already triaged
|
|
93
|
+
|
|
94
|
+
RUN
|
|
95
|
+
--sub-goal <text> plan across several flows, in this order (repeatable)
|
|
96
|
+
--flow <slug> skip matching and run this flow (for an UNSURE match)
|
|
97
|
+
--dry-run say which flow would run, and run nothing
|
|
98
|
+
plus --value, --headed, --allow-purchases as for replay
|
|
99
|
+
|
|
100
|
+
EMIT
|
|
101
|
+
--framework <name> playwright-ts (default) or cypress-js
|
|
102
|
+
--out <file> write to a file instead of printing
|
|
103
|
+
|
|
104
|
+
DISTILL
|
|
105
|
+
--save <file> store the agent's answer (validated first)
|
|
106
|
+
|
|
107
|
+
RECALL
|
|
108
|
+
--limit <n> how many flows and notes to show (default 5)
|
|
109
|
+
--steps list the known flow's steps
|
|
110
|
+
|
|
111
|
+
SETTINGS — from the environment, --env-file <path>, the file saved with
|
|
112
|
+
"understudy config", or ./.env (first wins)
|
|
113
|
+
MONGODB_URI local Community or your Atlas mongodb+srv:// string
|
|
114
|
+
EMBED_URL, EMBED_MODEL, EMBED_KEY, EMBED_DIMS optional embedding model
|
|
115
|
+
UNDERSTUDY_<REF> login values: a recording's SECRET.password reads
|
|
116
|
+
UNDERSTUDY_SECRET_PASSWORD (or pass --value)
|
|
117
|
+
`;
|
|
118
|
+
function parseArgs(argv) {
|
|
119
|
+
const flags = new Map();
|
|
120
|
+
const positional = [];
|
|
121
|
+
for (let i = 0; i < argv.length; i++) {
|
|
122
|
+
const arg = argv[i];
|
|
123
|
+
if (!arg.startsWith('-')) {
|
|
124
|
+
positional.push(arg);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const key = arg.replace(/^--?/, '');
|
|
128
|
+
const next = argv[i + 1];
|
|
129
|
+
const value = next !== undefined && !next.startsWith('-') ? next : true;
|
|
130
|
+
if (typeof value === 'string')
|
|
131
|
+
i++;
|
|
132
|
+
flags.set(key, [...(flags.get(key) ?? []), value]);
|
|
133
|
+
}
|
|
134
|
+
return { flags, positional };
|
|
135
|
+
}
|
|
136
|
+
/** Last string value for a flag. */
|
|
137
|
+
const str = (v) => (v ?? []).filter((x) => typeof x === 'string').at(-1);
|
|
138
|
+
/** Every string value for a repeatable flag. */
|
|
139
|
+
const all = (flags, key) => (flags.get(key) ?? []).filter((x) => typeof x === 'string');
|
|
140
|
+
function fail(message, hint) {
|
|
141
|
+
console.error(`error: ${message}`);
|
|
142
|
+
if (hint)
|
|
143
|
+
console.error(` ${hint}`);
|
|
144
|
+
process.exit(1);
|
|
145
|
+
}
|
|
146
|
+
/** --value REF=value, repeatable → { REF: value }. */
|
|
147
|
+
function valuesFromFlags(flags) {
|
|
148
|
+
const values = {};
|
|
149
|
+
for (const v of all(flags, 'value')) {
|
|
150
|
+
const eq = v.indexOf('=');
|
|
151
|
+
if (eq < 0)
|
|
152
|
+
fail('--value must be REF=value');
|
|
153
|
+
values[v.slice(0, eq)] = v.slice(eq + 1);
|
|
154
|
+
}
|
|
155
|
+
return values;
|
|
156
|
+
}
|
|
157
|
+
// --- apps --------------------------------------------------------------------
|
|
158
|
+
/**
|
|
159
|
+
* An app's base URL, remembered in MongoDB after first use so the app name
|
|
160
|
+
* alone is enough next time. Without MONGODB_URI it simply uses --url.
|
|
161
|
+
*/
|
|
162
|
+
async function resolveBaseUrl(slug, flag) {
|
|
163
|
+
if (!process.env.MONGODB_URI) {
|
|
164
|
+
return flag ?? fail(`no base URL for '${slug}'`, 'pass --url (or set MONGODB_URI so it is remembered)');
|
|
165
|
+
}
|
|
166
|
+
const { apps } = await store.collections();
|
|
167
|
+
if (flag) {
|
|
168
|
+
await apps.updateOne({ slug }, { $set: { 'urls.default': flag }, $setOnInsert: { slug, name: slug, createdAt: new Date() } }, { upsert: true });
|
|
169
|
+
return flag;
|
|
170
|
+
}
|
|
171
|
+
const known = (await apps.findOne({ slug }))?.urls.default;
|
|
172
|
+
return known ?? fail(`no base URL for '${slug}'`, 'pass --url the first time you use an app');
|
|
173
|
+
}
|
|
174
|
+
// --- doctor / reembed --------------------------------------------------------
|
|
175
|
+
/**
|
|
176
|
+
* Is everything connected? Connects to MongoDB, creates any missing
|
|
177
|
+
* collections and indexes, checks the embedding model with one real request,
|
|
178
|
+
* and reports whether vector search is ready. Same against local and Atlas.
|
|
179
|
+
*/
|
|
180
|
+
async function cmdDoctor() {
|
|
181
|
+
console.log(`MongoDB ${store.describeUri()} (database: ${process.env.MONGODB_DB ?? 'understudy'})`);
|
|
182
|
+
const db = await store.connect();
|
|
183
|
+
console.log(`server ${(await db.admin().serverInfo()).version}`);
|
|
184
|
+
await store.ensureSchema();
|
|
185
|
+
console.log('schema collections and indexes present');
|
|
186
|
+
const { embedderConfig, embed } = await import('../store/embed.js');
|
|
187
|
+
const cfg = embedderConfig();
|
|
188
|
+
if (!cfg) {
|
|
189
|
+
console.log('embedder none configured — search will match names only (set EMBED_KEY for Voyage)');
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const [v] = await embed(['understudy doctor'], 'query', cfg);
|
|
193
|
+
console.log(`embedder ${cfg.model} at ${new URL(cfg.url).host} — ok, ${v.length} numbers per vector`);
|
|
194
|
+
}
|
|
195
|
+
// Replay needs the headless browser; recording happens in your own Chrome.
|
|
196
|
+
try {
|
|
197
|
+
const b = await chromium.launch({ headless: true });
|
|
198
|
+
await b.close();
|
|
199
|
+
console.log('browser headless Chromium ready (replay)');
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
console.log('browser headless Chromium MISSING — replay needs it: npx playwright install --only-shell chromium');
|
|
203
|
+
process.exitCode = 1;
|
|
204
|
+
}
|
|
205
|
+
if (!existsSync(chromium.executablePath())) {
|
|
206
|
+
console.log(' (full Chromium not installed — only needed for record --new-browser and --headed)');
|
|
207
|
+
}
|
|
208
|
+
const states = await store.waitForVectorIndexes(60_000).catch(() => store.vectorIndexStates());
|
|
209
|
+
for (const s of states) {
|
|
210
|
+
console.log(`vector ${s.collection.padEnd(6)} ${s.queryable ? 'ready' : `NOT READY (${s.status})`}`);
|
|
211
|
+
}
|
|
212
|
+
if (!states.every((s) => s.queryable)) {
|
|
213
|
+
console.log('\nvector search is not ready yet — a new index can take a minute; run doctor again.');
|
|
214
|
+
process.exitCode = 1;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
async function cmdReembed() {
|
|
218
|
+
const { reembed } = await import('../store/reembed.js');
|
|
219
|
+
const r = await reembed();
|
|
220
|
+
console.log(`re-embedded ${r.flows} flows and ${r.notes} notes with ${r.model}`);
|
|
221
|
+
}
|
|
222
|
+
// --- config ------------------------------------------------------------------
|
|
223
|
+
/**
|
|
224
|
+
* understudy config where settings come from (no secrets shown)
|
|
225
|
+
* understudy config --env-file <path> read settings from this env file from now on
|
|
226
|
+
* understudy config set KEY=value [...] write settings into that env file
|
|
227
|
+
* understudy config --clear forget the saved env file
|
|
228
|
+
*/
|
|
229
|
+
async function cmdConfig(positional, flags) {
|
|
230
|
+
const [sub, ...pairs] = positional;
|
|
231
|
+
const cfg = readConfig();
|
|
232
|
+
if (flags.has('clear')) {
|
|
233
|
+
delete cfg.envFile;
|
|
234
|
+
console.log(`saved ${await writeConfig(cfg)} — no env file remembered`);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const chosen = str(flags.get('env-file'));
|
|
238
|
+
if (chosen) {
|
|
239
|
+
cfg.envFile = resolvePath(expandHome(chosen));
|
|
240
|
+
console.log(`saved ${await writeConfig(cfg)} — settings will be read from ${cfg.envFile}`);
|
|
241
|
+
if (!existsSync(cfg.envFile))
|
|
242
|
+
console.log(' (that file does not exist yet — create it, or use `understudy config set KEY=value`)');
|
|
243
|
+
}
|
|
244
|
+
if (sub === 'set') {
|
|
245
|
+
if (!pairs.length || pairs.some((p) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(p))) {
|
|
246
|
+
fail('config set needs KEY=value pairs', 'understudy config set MONGODB_URI="mongodb+srv://…" EMBED_KEY=…');
|
|
247
|
+
}
|
|
248
|
+
const values = Object.fromEntries(pairs.map((p) => [p.slice(0, p.indexOf('=')), p.slice(p.indexOf('=') + 1)]));
|
|
249
|
+
const file = await writeEnvValues(values).catch((e) => fail(e.message));
|
|
250
|
+
console.log(`wrote ${pairs.map((p) => p.slice(0, p.indexOf('='))).join(', ')} to ${file}`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (sub)
|
|
254
|
+
fail(`unknown: config ${sub}`, 'understudy config [set KEY=value …] [--env-file <path>] [--clear]');
|
|
255
|
+
if (chosen)
|
|
256
|
+
return;
|
|
257
|
+
// Show where everything comes from — never the secrets themselves.
|
|
258
|
+
const shown = (k) => (process.env[k] ? 'set' : 'not set');
|
|
259
|
+
console.log(`config file ${join(HOME, 'config.json')}${existsSync(join(HOME, 'config.json')) ? '' : ' (none yet)'}`);
|
|
260
|
+
console.log(`env file ${cfg.envFile ?? 'none saved — use --env-file <path> or `config set`'}`);
|
|
261
|
+
console.log(`read now ${loadedFrom.length ? loadedFrom.join(', ') : 'no env files (only the environment)'}`);
|
|
262
|
+
console.log(`MONGODB_URI ${process.env.MONGODB_URI ? store.describeUri() : 'not set'}`);
|
|
263
|
+
const defaulted = !process.env.EMBED_URL && !process.env.EMBED_MODEL && process.env.EMBED_KEY;
|
|
264
|
+
console.log(`EMBED_URL ${process.env.EMBED_URL || (defaulted ? 'not set — Voyage, the default' : 'not set (goals match flow names, not meaning)')}`);
|
|
265
|
+
console.log(`EMBED_MODEL ${process.env.EMBED_MODEL || (defaulted ? 'not set — voyage-4-lite, the default' : 'not set')}`);
|
|
266
|
+
console.log(`EMBED_KEY ${shown('EMBED_KEY')}`);
|
|
267
|
+
const logins = Object.keys(process.env).filter((k) => k.startsWith('UNDERSTUDY_') && !['UNDERSTUDY_HOME'].includes(k) && !k.endsWith('_DIR'));
|
|
268
|
+
console.log(`login values ${logins.length ? logins.join(', ') : 'none (a recording\'s SECRET.password reads UNDERSTUDY_SECRET_PASSWORD)'}`);
|
|
269
|
+
}
|
|
270
|
+
// --- record ------------------------------------------------------------------
|
|
271
|
+
/**
|
|
272
|
+
* Wait for Enter in the terminal. Deliberately not anything on the page: an
|
|
273
|
+
* in-page control would itself be recorded as the first step.
|
|
274
|
+
*/
|
|
275
|
+
function waitForEnter(prompt) {
|
|
276
|
+
if (!process.stdin.isTTY) {
|
|
277
|
+
fail('--arm-manually needs a terminal to read the Enter keypress from');
|
|
278
|
+
}
|
|
279
|
+
return new Promise((resolve) => {
|
|
280
|
+
console.log(prompt);
|
|
281
|
+
const finish = () => {
|
|
282
|
+
process.stdin.off('data', finish);
|
|
283
|
+
process.stdin.off('end', finish);
|
|
284
|
+
process.stdin.pause();
|
|
285
|
+
resolve();
|
|
286
|
+
};
|
|
287
|
+
process.stdin.resume();
|
|
288
|
+
process.stdin.once('data', finish);
|
|
289
|
+
process.stdin.once('end', finish);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
function printEvents(recording) {
|
|
293
|
+
for (const e of recording.events) {
|
|
294
|
+
const value = e.value !== undefined ? ` = "${e.value}"` : e.valueRef ? ` = <${e.valueRef}>` : '';
|
|
295
|
+
console.log(` ${String(e.seq).padStart(2)} ${e.action.padEnd(7)} ${(e.role ?? '').padEnd(9)} ${e.name ?? ''}${value}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function cmdRecord(positional, flags) {
|
|
299
|
+
const slug = positional[0] ?? fail('record needs an app name', 'understudy record myapp');
|
|
300
|
+
// The extension is the recorder. The fresh-browser one is opt-in, because it
|
|
301
|
+
// needs Playwright's full Chromium (~350 MB), which isn't installed by default
|
|
302
|
+
// — replay only needs the headless build.
|
|
303
|
+
if (!flags.has('new-browser'))
|
|
304
|
+
return cmdRecordExtension(slug, flags);
|
|
305
|
+
if (!existsSync(chromium.executablePath())) {
|
|
306
|
+
fail("--new-browser needs Playwright's full Chromium (~350 MB), which isn't installed", 'install it with: npx playwright install chromium — or record in your own Chrome with the extension (the default)');
|
|
307
|
+
}
|
|
308
|
+
const baseUrl = await resolveBaseUrl(slug, str(flags.get('url')));
|
|
309
|
+
const values = valuesFromFlags(flags);
|
|
310
|
+
const armManually = flags.has('arm-manually');
|
|
311
|
+
console.log(`recording ${slug} at ${baseUrl}`);
|
|
312
|
+
// A saved session only makes sense when capture starts late: if the login is
|
|
313
|
+
// part of what we're recording, restoring one would skip the very steps the
|
|
314
|
+
// recording exists to capture.
|
|
315
|
+
const cached = armManually && !flags.has('fresh') ? await loadSession(slug, values) : undefined;
|
|
316
|
+
if (cached)
|
|
317
|
+
console.log(`session: restored (saved ${cached.savedAt})`);
|
|
318
|
+
else if (armManually)
|
|
319
|
+
console.log('session: none — sign in yourself before pressing Enter');
|
|
320
|
+
console.log();
|
|
321
|
+
const recording = await recordLive({
|
|
322
|
+
appSlug: slug,
|
|
323
|
+
startUrl: baseUrl,
|
|
324
|
+
...(cached ? { storageState: cached.storageState } : {}),
|
|
325
|
+
...(flags.has('max-minutes') ? { maxMinutes: Number(str(flags.get('max-minutes'))) } : {}),
|
|
326
|
+
...(armManually
|
|
327
|
+
? {
|
|
328
|
+
armWhen: () => waitForEnter('drive to the point you want to start from — nothing is being recorded yet.\n' +
|
|
329
|
+
'press Enter here to begin capturing.'),
|
|
330
|
+
// Saved at arm time: this is the state the recording claims to start
|
|
331
|
+
// from, and the steps that follow may well log out of it.
|
|
332
|
+
onArmed: async ({ context, sig }) => {
|
|
333
|
+
console.log(`\narmed at ${sig}\n`);
|
|
334
|
+
const path = await saveSession(context, slug, values, sig);
|
|
335
|
+
if (path)
|
|
336
|
+
console.log(`session saved ${path}`);
|
|
337
|
+
return { sessionSaved: Boolean(path) };
|
|
338
|
+
},
|
|
339
|
+
}
|
|
340
|
+
: {}),
|
|
341
|
+
});
|
|
342
|
+
if (!recording.events.some((e) => e.action !== 'goto')) {
|
|
343
|
+
console.error('\nnothing was recorded — no actions beyond the opening navigation. Not saved.');
|
|
344
|
+
process.exitCode = 2;
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const { path, existed } = await saveRecording(recording);
|
|
348
|
+
console.log(`\ncaptured ${recording.events.length} events`);
|
|
349
|
+
printEvents(recording);
|
|
350
|
+
const approximate = recording.events.filter((e) => e.resolution === 'unresolved').length;
|
|
351
|
+
if (approximate)
|
|
352
|
+
console.log(`\n${approximate} step(s) have approximate role/name — replay will resolve them.`);
|
|
353
|
+
if (recording.entry?.requiresSession) {
|
|
354
|
+
console.log(`\nthis recording starts from a signed-in browser (${recording.entry.startState}).`);
|
|
355
|
+
console.log(' replay restores the saved session for these --value credentials.');
|
|
356
|
+
}
|
|
357
|
+
console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
|
|
358
|
+
console.log(`saved ${path}`);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Record in the Chrome you already have open: this waits for the Understudy
|
|
362
|
+
* extension, which records the tab you start it on (see extension/README.md).
|
|
363
|
+
*/
|
|
364
|
+
async function cmdRecordExtension(slug, flags) {
|
|
365
|
+
const port = Number(str(flags.get('port')) ?? DEFAULT_PORT);
|
|
366
|
+
const rec = await startExtensionRecorder({ appSlug: slug, port }).catch((e) => fail(`couldn't listen on port ${port}: ${e.message}`, 'another recording may be waiting — or pass --port and set the same port in the extension'));
|
|
367
|
+
console.log(`waiting for the Understudy extension (${rec.url})`);
|
|
368
|
+
console.log(` in Chrome: go to where the flow starts, click the Understudy icon, then "Record from this page".`);
|
|
369
|
+
console.log(` (extension not loaded yet? understudy extension — it says where it is and how)`);
|
|
370
|
+
console.log(` stop from the extension when you're done (or press Ctrl+C here to stop and keep what was recorded).\n`);
|
|
371
|
+
const onSigint = () => rec.stop();
|
|
372
|
+
process.once('SIGINT', onSigint);
|
|
373
|
+
const out = await rec.done;
|
|
374
|
+
process.off('SIGINT', onSigint);
|
|
375
|
+
if (!out.started || !out.recording.events.some((e) => e.action !== 'goto')) {
|
|
376
|
+
console.error('nothing was recorded — no actions beyond opening the page. Not saved.');
|
|
377
|
+
process.exitCode = 2;
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const { path, existed } = await saveRecording(out.recording);
|
|
381
|
+
console.log(`captured ${out.recording.events.length} events`);
|
|
382
|
+
printEvents(out.recording);
|
|
383
|
+
if (out.droppedUploads) {
|
|
384
|
+
console.log(`\n${out.droppedUploads} file upload(s) NOT recorded — a page can't say which file was chosen.`);
|
|
385
|
+
console.log(' write that part as a Playwright script and `understudy import` it instead.');
|
|
386
|
+
}
|
|
387
|
+
if (out.saveAs) {
|
|
388
|
+
// Ticked "Save as a flow when I stop": prove and save it now, here.
|
|
389
|
+
console.log(`\nsaving it as "${out.saveAs}" (you ticked "Save as a flow when I stop")\n`);
|
|
390
|
+
await saveAndReport(out.recording, out.saveAs, { values: valuesFromFlags(flags) });
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (out.sessionPath) {
|
|
394
|
+
console.log(out.recording.entry?.requiresSession
|
|
395
|
+
? '\nyou said you were signed in: replay starts from your sign-in (saved locally, 0600).'
|
|
396
|
+
: '\nthe tab\'s sign-in was copied; `save` keeps it only if the flow turns out to need it.');
|
|
397
|
+
}
|
|
398
|
+
console.log(`\nhash ${out.recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
|
|
399
|
+
console.log(`saved ${path}`);
|
|
400
|
+
console.log(`\nnext: understudy save ${out.recording.hash} "<what this flow does>"`);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* understudy app <app> the app's settings
|
|
404
|
+
* understudy app <app> --placeholder email keep its email fields as placeholders
|
|
405
|
+
* understudy app <app> --no-placeholders stop doing that for new flows
|
|
406
|
+
*/
|
|
407
|
+
async function cmdApp(positional, flags) {
|
|
408
|
+
const app = positional[0] ?? fail('app needs an app name', 'understudy app myapp --placeholder email');
|
|
409
|
+
const kinds = all(flags, 'placeholder');
|
|
410
|
+
if (!kinds.length && !flags.has('no-placeholders')) {
|
|
411
|
+
const current = await appPlaceholders(app);
|
|
412
|
+
console.log(`${app}: placeholders ${current.length ? current.join(', ') : 'passwords only (the default)'}`);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const out = await setPlaceholders(app, flags.has('no-placeholders') ? [] : kinds).catch((e) => fail(e.message));
|
|
416
|
+
console.log(`${app}: placeholders ${out.placeholders.length ? out.placeholders.join(', ') + ' (and passwords)' : 'passwords only'}`);
|
|
417
|
+
for (const c of out.converted) {
|
|
418
|
+
console.log(` ${c.placeholder.padEnd(14)} now used by ${c.flows.length} flow(s): ${c.flows.slice(0, 4).join(', ')}${c.flows.length > 4 ? ', …' : ''}`);
|
|
419
|
+
console.log(` ${''.padEnd(14)} value in ${c.valueIn}`);
|
|
420
|
+
}
|
|
421
|
+
if (out.envFile)
|
|
422
|
+
console.log(`moved the address(es) into ${out.envFile} — memory no longer holds them`);
|
|
423
|
+
else if (out.placeholders.includes('email') && !out.converted.length)
|
|
424
|
+
console.log('no email fields with stored addresses in its flows — new ones will be converted when saved');
|
|
425
|
+
}
|
|
426
|
+
/** Where the Chrome extension is, and how to load it — it ships inside the package. */
|
|
427
|
+
function cmdExtension() {
|
|
428
|
+
console.log('Chrome, Edge, Brave and other Chromium browsers — install it from the Chrome Web Store:');
|
|
429
|
+
console.log(' https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf\n');
|
|
430
|
+
console.log(`or load it by hand from:\n ${extensionDir()}\n`);
|
|
431
|
+
console.log(' 1. open the extensions page (chrome://extensions, edge://extensions, …) and turn on Developer mode');
|
|
432
|
+
console.log(' 2. click "Load unpacked" and choose the folder above');
|
|
433
|
+
console.log(' 3. pin it (puzzle-piece icon) so it is one click away');
|
|
434
|
+
const firefox = firefoxExtensionDir();
|
|
435
|
+
if (existsSync(join(firefox, 'manifest.json'))) {
|
|
436
|
+
console.log(`\nFirefox:\n ${firefox}\n`);
|
|
437
|
+
console.log(' open about:debugging#/runtime/this-firefox → "Load Temporary Add-on…" → choose manifest.json in that folder');
|
|
438
|
+
console.log(' (Firefox removes temporary add-ons when it restarts)');
|
|
439
|
+
}
|
|
440
|
+
console.log('\nSafari: use `understudy record <app> --new-browser` instead (needs: npx playwright install chromium)');
|
|
441
|
+
console.log('\nthen record with: understudy record <app>');
|
|
442
|
+
}
|
|
443
|
+
// --- import ------------------------------------------------------------------
|
|
444
|
+
async function cmdImport(positional, flags) {
|
|
445
|
+
const slug = positional[0] ?? fail('import needs an app name', 'understudy import myapp tests/login.spec.ts');
|
|
446
|
+
const file = positional[1] ?? fail('import needs a script path');
|
|
447
|
+
// A script may rely on a baseURL from playwright.config, so goto('/') has no
|
|
448
|
+
// origin. The app's remembered base URL fills that in.
|
|
449
|
+
const fallback = str(flags.get('url')) ?? (await resolveBaseUrl(slug, undefined).catch(() => undefined));
|
|
450
|
+
const { recording: parsed, warnings } = await parseScript(file, slug, fallback);
|
|
451
|
+
// --until keeps the proven prefix — e.g. everything before a real purchase.
|
|
452
|
+
const until = str(flags.get('until'));
|
|
453
|
+
const recording = until
|
|
454
|
+
? buildRecording({ source: parsed.source, origin: parsed.origin, appSlug: parsed.appSlug, startUrl: parsed.startUrl }, parsed.events.slice(0, Number(until)))
|
|
455
|
+
: parsed;
|
|
456
|
+
if (until)
|
|
457
|
+
console.log(`kept ${recording.events.length} of ${parsed.events.length} steps (--until ${until})\n`);
|
|
458
|
+
if (!recording.events.length) {
|
|
459
|
+
console.error(`no Playwright actions found in ${file} — expected calls like page.getByRole(...).click()`);
|
|
460
|
+
process.exitCode = 2;
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
console.log(`parsed ${recording.events.length} events from ${file}\n`);
|
|
464
|
+
printEvents(recording);
|
|
465
|
+
// A clean import with warnings is NOT a clean import: each one is a step
|
|
466
|
+
// that was dropped, and replay will fail somewhere after it.
|
|
467
|
+
if (warnings.length) {
|
|
468
|
+
console.log(`\n${warnings.length} call(s) could not be mapped:`);
|
|
469
|
+
for (const w of warnings.slice(0, 10))
|
|
470
|
+
console.log(` ${w}`);
|
|
471
|
+
}
|
|
472
|
+
const { path, existed } = await saveRecording(recording);
|
|
473
|
+
console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
|
|
474
|
+
console.log(`saved ${path}`);
|
|
475
|
+
}
|
|
476
|
+
// --- replay ------------------------------------------------------------------
|
|
477
|
+
/**
|
|
478
|
+
* Run a recording with everything around it (saved session, lessons, stale
|
|
479
|
+
* sessions) via flows/execute.ts, and say what's worth knowing as it goes.
|
|
480
|
+
*/
|
|
481
|
+
async function executeWithReport(recording, flags, opts) {
|
|
482
|
+
const values = valuesFromFlags(flags);
|
|
483
|
+
const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons }))
|
|
484
|
+
.catch((e) => fail(e.message));
|
|
485
|
+
if (x.sessionRestoredFrom)
|
|
486
|
+
console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
|
|
487
|
+
if (x.staleSession) {
|
|
488
|
+
console.log('the restored session did not land where it was recorded, and has been discarded.');
|
|
489
|
+
console.log(` expected ${x.staleSession.expected}, saw ${x.staleSession.observed}`);
|
|
490
|
+
console.log(' re-record with --arm-manually to refresh it.\n');
|
|
491
|
+
}
|
|
492
|
+
if (x.lessons?.fired)
|
|
493
|
+
console.log(`lessons ${x.lessons.fired} fired, ${x.lessons.helped} on steps that have failed before\n`);
|
|
494
|
+
return x.result;
|
|
495
|
+
}
|
|
496
|
+
/** `replay <hash>` runs a recording file; `replay <app> <flow>` runs a saved flow and records the run. */
|
|
497
|
+
async function cmdReplay(positional, flags) {
|
|
498
|
+
if (positional.length >= 2)
|
|
499
|
+
return cmdReplayFlow(positional[0], positional[1], flags);
|
|
500
|
+
const hash = positional[0] ?? fail('replay needs a recording hash, or an app and a flow', 'understudy recordings · understudy flows <app>');
|
|
501
|
+
const recording = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
|
|
502
|
+
const result = await executeWithReport(recording, flags, { useLessons: false });
|
|
503
|
+
printReplay(result);
|
|
504
|
+
if (!result.ok)
|
|
505
|
+
process.exitCode = 3;
|
|
506
|
+
}
|
|
507
|
+
async function cmdReplayFlow(app, slug, flags) {
|
|
508
|
+
await runSavedFlow(app, slug, flags, { mode: 'replay' });
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Run one saved flow: the safety gate, the replay, and recording the run.
|
|
512
|
+
* Shared by `replay <app> <flow>` and `run <app> "<goal>"`.
|
|
513
|
+
*/
|
|
514
|
+
async function runSavedFlow(app, slug, flags, how) {
|
|
515
|
+
const { flows } = await store.collections();
|
|
516
|
+
const flow = await flows.findOne({ app, slug });
|
|
517
|
+
if (!flow)
|
|
518
|
+
fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
|
|
519
|
+
// The safety gate: a destructive flow does something real every time it runs.
|
|
520
|
+
if (!flags.has('allow-purchases')) {
|
|
521
|
+
if (flow.destructive) {
|
|
522
|
+
fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --allow-purchases if that is genuinely fine');
|
|
523
|
+
}
|
|
524
|
+
const controls = await destructiveControls(app);
|
|
525
|
+
const hit = flow.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
|
|
526
|
+
if (hit)
|
|
527
|
+
fail(`'${slug}' clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())}`, 'pass --allow-purchases if that is genuinely fine');
|
|
528
|
+
}
|
|
529
|
+
console.log(`running ${app}/${slug} — ${flow.title}\n`);
|
|
530
|
+
if (flow.proven === false)
|
|
531
|
+
console.log(`note: '${slug}' is UNPROVEN (${flow.unprovenBecause}) — this run will tell.\n`);
|
|
532
|
+
const result = await executeWithReport(recordingFrom(flow), flags, { useLessons: true });
|
|
533
|
+
printReplay(result);
|
|
534
|
+
const run = await recordRun({
|
|
535
|
+
app, flow: slug, result, steps: flow.steps, mode: how.mode, ...(how.goal ? { goal: how.goal } : {}), ...(flow.proven === false ? { unproven: true } : {}),
|
|
536
|
+
});
|
|
537
|
+
if (await proveByRun(app, slug, result))
|
|
538
|
+
console.log(`\nproven '${slug}' passed, so it's no longer marked unproven`);
|
|
539
|
+
printRunReport(run);
|
|
540
|
+
if (!result.ok)
|
|
541
|
+
process.exitCode = 3;
|
|
542
|
+
}
|
|
543
|
+
// --- recall / run ------------------------------------------------------------
|
|
544
|
+
function printRecall(r, showSteps = false) {
|
|
545
|
+
const verdict = { known: 'KNOWN', unsure: 'UNSURE', unknown: "DON'T KNOW" }[r.verdict];
|
|
546
|
+
console.log(`${verdict} — ${r.why} (matched by ${r.method})\n`);
|
|
547
|
+
if (r.flows.length) {
|
|
548
|
+
console.log('flows');
|
|
549
|
+
for (const f of r.flows) {
|
|
550
|
+
const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment'].filter(Boolean).join(', ');
|
|
551
|
+
console.log(` ${f.score.toFixed(3)} ${f.slug.padEnd(32)} ${f.title}${marks ? ` [${marks}]` : ''}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (r.notes.length) {
|
|
555
|
+
console.log('\nnotes');
|
|
556
|
+
for (const n of r.notes)
|
|
557
|
+
console.log(` ${n.score.toFixed(3)} ${n.kind.padEnd(6)} ${n.text.slice(0, 100)}`);
|
|
558
|
+
}
|
|
559
|
+
if (r.best && r.steps) {
|
|
560
|
+
console.log(`\n${r.best.slug}: ${r.steps.length} steps${showSteps ? '' : ' (--steps to list them)'}`);
|
|
561
|
+
if (showSteps) {
|
|
562
|
+
for (const s of r.steps) {
|
|
563
|
+
const target = s.role && s.name ? `${s.role} "${s.name}"` : s.testId ? `[test id ${s.testId}]` : s.css ? `[${s.css}]` : '';
|
|
564
|
+
const what = s.placeholder ? `= <${s.placeholder}>` : s.value !== undefined ? `= "${s.value}"` : '';
|
|
565
|
+
console.log(` ${String(s.n).padStart(3)} ${s.action.padEnd(7)} ${target}${s.nth !== undefined ? ` (#${s.nth})` : ''} ${what}`.trimEnd());
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
for (const need of r.needs ?? []) {
|
|
570
|
+
console.log(`needs ${need.placeholder} — from ${need.readFrom.join(' or ')}: ${need.set ? 'set' : 'NOT SET'}`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
/** What memory knows about a goal. A database query: no browser, nothing runs. */
|
|
574
|
+
async function cmdRecall(positional, flags) {
|
|
575
|
+
const [app, ...goalWords] = positional;
|
|
576
|
+
if (!app || !goalWords.length)
|
|
577
|
+
fail('recall needs an app and a goal', 'understudy recall myapp "log in"');
|
|
578
|
+
printRecall(await recall(app, goalWords.join(' '), { withSteps: true, limit: Number(str(flags.get('limit')) ?? 5) }), flags.has('steps'));
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Run a goal: find the flow that does it, check it's safe, run it. Only a
|
|
582
|
+
* KNOWN match runs on its own — an unsure one is shown so you can pick, and an
|
|
583
|
+
* unknown one is a cue to record it, never a guess.
|
|
584
|
+
*/
|
|
585
|
+
async function cmdRun(positional, flags) {
|
|
586
|
+
const [app, ...goalWords] = positional;
|
|
587
|
+
if (!app || !goalWords.length)
|
|
588
|
+
fail('run needs an app and a goal', 'understudy run myapp "log in"');
|
|
589
|
+
const goal = goalWords.join(' ');
|
|
590
|
+
const picked = str(flags.get('flow'));
|
|
591
|
+
if (picked)
|
|
592
|
+
return runSavedFlow(app, picked, flags, { mode: 'run', goal });
|
|
593
|
+
// Several sub-goals: plan across flows, bridging the seams between them.
|
|
594
|
+
const subGoals = all(flags, 'sub-goal');
|
|
595
|
+
if (subGoals.length) {
|
|
596
|
+
const state = await start({
|
|
597
|
+
app, goal, subGoals,
|
|
598
|
+
...(flags.has('dry-run') ? { dryRun: true } : {}),
|
|
599
|
+
...(flags.has('allow-purchases') ? { allowPurchases: true } : {}),
|
|
600
|
+
});
|
|
601
|
+
return reportPlan(state, flags);
|
|
602
|
+
}
|
|
603
|
+
const r = await recall(app, goal);
|
|
604
|
+
printRecall(r);
|
|
605
|
+
if (r.verdict !== 'known' || !r.best) {
|
|
606
|
+
console.log(r.verdict === 'unsure'
|
|
607
|
+
? `\nnot running — no flow is clearly this goal, and it may not be in memory at all.\n` +
|
|
608
|
+
` if one of the flows above IS it: understudy run ${app} "${goal}" --flow <slug>\n` +
|
|
609
|
+
` if none is: understudy record ${app}`
|
|
610
|
+
: `\nnot running — nothing in memory does this. Record it: understudy record ${app}`);
|
|
611
|
+
process.exitCode = 4;
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if (flags.has('dry-run')) {
|
|
615
|
+
console.log(`\ndry run — would run ${r.best.slug}${r.best.destructive ? ' (DESTRUCTIVE: needs --allow-purchases)' : ''}`);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
console.log();
|
|
619
|
+
await runSavedFlow(app, r.best.slug, flags, { mode: 'run', goal });
|
|
620
|
+
}
|
|
621
|
+
/** Show where planning got to, and run it if it's complete. */
|
|
622
|
+
async function reportPlan(state, flags) {
|
|
623
|
+
if (state.status === 'waiting') {
|
|
624
|
+
console.log(`run ${state.runId} is waiting for an answer:\n`);
|
|
625
|
+
console.log(JSON.stringify(state.question, null, 1));
|
|
626
|
+
console.log(`\nanswer it: understudy answer ${state.runId} '<json>'`);
|
|
627
|
+
process.exitCode = 5;
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
if (state.status === 'blocked') {
|
|
631
|
+
console.log(`BLOCKED — ${state.why}`);
|
|
632
|
+
if (state.detail)
|
|
633
|
+
console.log(JSON.stringify(state.detail, null, 1));
|
|
634
|
+
process.exitCode = 4;
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
console.log(`plan ${state.plan.join(' → ')}`);
|
|
638
|
+
for (const s of state.seams)
|
|
639
|
+
console.log(`seam before ${s.before}: ${s.how}`);
|
|
640
|
+
if (state.dryRun) {
|
|
641
|
+
console.log('\ndry run — nothing ran');
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
console.log();
|
|
645
|
+
const values = valuesFromFlags(flags);
|
|
646
|
+
const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed') }))
|
|
647
|
+
.catch((e) => fail(e.message));
|
|
648
|
+
if (executed.lessons?.fired)
|
|
649
|
+
console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
|
|
650
|
+
printReplay(executed.result);
|
|
651
|
+
printRunReport(recorded);
|
|
652
|
+
for (const slug of nowProven)
|
|
653
|
+
console.log(`proven '${slug}' passed, so it's no longer marked unproven`);
|
|
654
|
+
if (!executed.result.ok)
|
|
655
|
+
process.exitCode = 3;
|
|
656
|
+
}
|
|
657
|
+
/** Answer a planning question: understudy answer <runId> '{"steps":[…]}' */
|
|
658
|
+
async function cmdAnswer(positional, flags) {
|
|
659
|
+
const [runId, json] = positional;
|
|
660
|
+
if (!runId || !json)
|
|
661
|
+
fail('answer needs a run id and a JSON answer', `understudy answer <runId> '{"subGoals":["…"]}'`);
|
|
662
|
+
let reply;
|
|
663
|
+
try {
|
|
664
|
+
reply = JSON.parse(json);
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
fail('the answer must be JSON');
|
|
668
|
+
}
|
|
669
|
+
await reportPlan(await answer(runId, reply).catch((e) => fail(e.message)), flags);
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* distill <app> <flow> print the request for an agent to answer
|
|
673
|
+
* distill <app> <flow> --save <file> store the agent's answer from a JSON file
|
|
674
|
+
*/
|
|
675
|
+
async function cmdDistill(positional, flags) {
|
|
676
|
+
const [app, flow] = positional;
|
|
677
|
+
if (!app || !flow)
|
|
678
|
+
fail('distill needs an app and a saved flow', 'understudy distill myapp checkout');
|
|
679
|
+
const file = str(flags.get('save'));
|
|
680
|
+
if (!file) {
|
|
681
|
+
console.log(JSON.stringify(await distillRequest(app, flow).catch((e) => fail(e.message)), null, 1));
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
const saved = await saveDistilled(app, flow, JSON.parse(await readFile(file, 'utf8'))).catch((e) => fail(e.message));
|
|
685
|
+
console.log(`distilled ${app}/${saved.flow}`);
|
|
686
|
+
for (const s of saved.segments)
|
|
687
|
+
console.log(` segment ${s.slug.padEnd(32)} ${s.steps} steps${s.replaced ? ' (replaced the existing one)' : ''}`);
|
|
688
|
+
if (saved.lessons.written || saved.lessons.alreadyKnown)
|
|
689
|
+
console.log(` lessons ${saved.lessons.written} new, ${saved.lessons.alreadyKnown} already known`);
|
|
690
|
+
}
|
|
691
|
+
/** remember <app> <file.json> — a batch of { facts, lessons, findings, reached }. */
|
|
692
|
+
async function cmdRemember(positional) {
|
|
693
|
+
const [app, file] = positional;
|
|
694
|
+
if (!app || !file)
|
|
695
|
+
fail('remember needs an app and a JSON file', 'understudy remember myapp learned.json');
|
|
696
|
+
const r = await remember(app, JSON.parse(await readFile(file, 'utf8'))).catch((e) => fail(e.message));
|
|
697
|
+
console.log(`facts ${r.facts.written} new, ${r.facts.alreadyKnown} already known`);
|
|
698
|
+
console.log(`lessons ${r.lessons.written} new, ${r.lessons.alreadyKnown} already known`);
|
|
699
|
+
console.log(`findings ${r.findings}`);
|
|
700
|
+
console.log(`reached ${r.reached}`);
|
|
701
|
+
}
|
|
702
|
+
function printReplay(result) {
|
|
703
|
+
console.log(`replay ${result.ok ? 'PASSED' : 'FAILED'} in ${(result.durationMs / 1000).toFixed(1)}s\n`);
|
|
704
|
+
for (const s of result.steps) {
|
|
705
|
+
const notes = [
|
|
706
|
+
s.ambiguousByName && `ambiguous: ${s.ambiguousByName.matched} by name, resolved via ${s.ambiguousByName.disambiguatedBy}`,
|
|
707
|
+
s.roleHadNoMatch && `role matched nothing, fell back to ${s.roleHadNoMatch.fellBackTo}`,
|
|
708
|
+
s.roundTripMismatch && `value did not survive: wrote "${s.roundTripMismatch.expected}", read "${s.roundTripMismatch.actual}"`,
|
|
709
|
+
s.error,
|
|
710
|
+
].filter(Boolean).join('; ');
|
|
711
|
+
console.log(` ${String(s.seq).padStart(2)} ${s.ok ? 'ok ' : 'FAIL'} ${s.action.padEnd(7)} ${(s.sig ?? '').padEnd(28)} ${notes}`);
|
|
712
|
+
}
|
|
713
|
+
console.log(`\npath: ${result.sigSequence.join(' -> ')}`);
|
|
714
|
+
if (result.signals.length) {
|
|
715
|
+
console.log(`\n${result.signals.length} signal(s) captured:`);
|
|
716
|
+
for (const g of result.signals.slice(0, 12)) {
|
|
717
|
+
console.log(` [step ${g.duringStep}] ${g.kind}${g.status ? ' ' + g.status : ''} ${g.text.slice(0, 90)}`);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/** What recording the run added: drift against earlier runs, and findings. */
|
|
722
|
+
function printRunReport(run) {
|
|
723
|
+
const { drift } = run;
|
|
724
|
+
if (drift.firstRun)
|
|
725
|
+
console.log('\ndrift first passed run — this path is now the baseline');
|
|
726
|
+
else if (!drift.changed)
|
|
727
|
+
console.log('\ndrift same path as recent runs');
|
|
728
|
+
else {
|
|
729
|
+
console.log('\ndrift PATH CHANGED');
|
|
730
|
+
for (const s of drift.added)
|
|
731
|
+
console.log(` new ${s}`);
|
|
732
|
+
for (const s of drift.removed)
|
|
733
|
+
console.log(` gone ${s}`);
|
|
734
|
+
for (const s of drift.stateChanged)
|
|
735
|
+
console.log(` state ${s}`);
|
|
736
|
+
}
|
|
737
|
+
console.log(`findings ${run.findings.length ? `${run.findings.length} raised or seen again (understudy findings <app>)` : 'none'}`);
|
|
738
|
+
console.log(`run ${run.runId.toHexString()}`);
|
|
739
|
+
}
|
|
740
|
+
// --- save / flows / findings -------------------------------------------------
|
|
741
|
+
/** What proving found out about signing in, for a recording made from a tab. */
|
|
742
|
+
function signInNote(recording, signIn) {
|
|
743
|
+
if (!recording.entry?.session)
|
|
744
|
+
return undefined;
|
|
745
|
+
if (recording.entry.requiresSession)
|
|
746
|
+
return 'used, as you said you were signed in when recording';
|
|
747
|
+
if (signIn === 'needed')
|
|
748
|
+
return 'needed — it failed in an empty browser and passed signed in, so it keeps your session';
|
|
749
|
+
return 'not needed — the session copied when you started recording was deleted';
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Prove a recording by replaying it, then save it as a flow. A recording that
|
|
753
|
+
* doesn't replay cleanly is refused — memory only holds flows known to work.
|
|
754
|
+
*/
|
|
755
|
+
async function cmdSave(positional, flags) {
|
|
756
|
+
const [hash, ...titleWords] = positional;
|
|
757
|
+
if (!hash || !titleWords.length) {
|
|
758
|
+
fail('save needs a recording hash and a name', 'understudy save <hash> "log in as a member"');
|
|
759
|
+
}
|
|
760
|
+
const recording = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
|
|
761
|
+
const slug = str(flags.get('slug'));
|
|
762
|
+
const intent = str(flags.get('intent'));
|
|
763
|
+
await saveAndReport(recording, titleWords.join(' '), {
|
|
764
|
+
values: valuesFromFlags(flags), headed: flags.has('headed'),
|
|
765
|
+
verify: !flags.has('no-verify'), force: flags.has('force'),
|
|
766
|
+
...(slug ? { slug } : {}), ...(intent ? { intent } : {}),
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
/** Ask a yes/no question in the terminal. No terminal (piped, scripted): the answer is no. */
|
|
770
|
+
async function askYesNo(question, byDefault = false) {
|
|
771
|
+
if (!process.stdin.isTTY)
|
|
772
|
+
return false;
|
|
773
|
+
const answer = (await ask(`${question} ${byDefault ? '[Y/n]' : '[y/N]'} `)).trim();
|
|
774
|
+
return answer ? /^y(es)?$/i.test(answer) : byDefault;
|
|
775
|
+
}
|
|
776
|
+
/** Ask for a line in the terminal. */
|
|
777
|
+
async function ask(question) {
|
|
778
|
+
const { createInterface } = await import('node:readline/promises');
|
|
779
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
780
|
+
try {
|
|
781
|
+
return await rl.question(question);
|
|
782
|
+
}
|
|
783
|
+
finally {
|
|
784
|
+
rl.close();
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
/** Ask for a line without showing it (a password): each key shows as *. */
|
|
788
|
+
function askHidden(question) {
|
|
789
|
+
const stdin = process.stdin;
|
|
790
|
+
process.stdout.write(question);
|
|
791
|
+
stdin.setRawMode(true);
|
|
792
|
+
stdin.setEncoding('utf8');
|
|
793
|
+
stdin.resume();
|
|
794
|
+
return new Promise((resolve) => {
|
|
795
|
+
let typed = '';
|
|
796
|
+
const done = () => {
|
|
797
|
+
stdin.off('data', onData);
|
|
798
|
+
stdin.setRawMode(false);
|
|
799
|
+
stdin.pause();
|
|
800
|
+
process.stdout.write('\n');
|
|
801
|
+
resolve(typed);
|
|
802
|
+
};
|
|
803
|
+
const onData = (chunk) => {
|
|
804
|
+
for (const ch of chunk) {
|
|
805
|
+
if (ch === '\r' || ch === '\n')
|
|
806
|
+
return done();
|
|
807
|
+
if (ch === '\u0003') { // Ctrl+C
|
|
808
|
+
stdin.setRawMode(false);
|
|
809
|
+
process.stdout.write('\n');
|
|
810
|
+
process.exit(130);
|
|
811
|
+
}
|
|
812
|
+
if (ch === '\u007f' || ch === '\b') {
|
|
813
|
+
if (typed) {
|
|
814
|
+
typed = typed.slice(0, -1);
|
|
815
|
+
process.stdout.write('\b \b');
|
|
816
|
+
}
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (ch < ' ')
|
|
820
|
+
continue;
|
|
821
|
+
typed += ch;
|
|
822
|
+
process.stdout.write('*');
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
stdin.on('data', onData);
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Run something that needs login values; if some are missing (nothing ran
|
|
830
|
+
* yet), ask for them in the terminal and run it again. Each one can be typed
|
|
831
|
+
* — hidden if it's a secret — or put in the env file, then Enter. Typed
|
|
832
|
+
* values can be saved to the env file so they aren't asked for again.
|
|
833
|
+
* No terminal: the error says where to put them, and nothing is asked.
|
|
834
|
+
*/
|
|
835
|
+
async function withLoginValues(values, attempt) {
|
|
836
|
+
for (;;) {
|
|
837
|
+
try {
|
|
838
|
+
return await attempt(values);
|
|
839
|
+
}
|
|
840
|
+
catch (e) {
|
|
841
|
+
if (!(e instanceof MissingValuesError) || !process.stdin.isTTY)
|
|
842
|
+
throw e;
|
|
843
|
+
values = { ...values, ...(await askForValues(e)) };
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
async function askForValues(e) {
|
|
848
|
+
console.log(`\n${e.missing.length === 1 ? 'a login value is' : 'login values are'} needed to replay this, and not set — nothing has run yet.`);
|
|
849
|
+
console.log(`type it, or add it to ${e.envFile} and press Enter. (Ctrl+C to stop)\n`);
|
|
850
|
+
const typed = {};
|
|
851
|
+
const toSave = {};
|
|
852
|
+
for (const m of e.missing) {
|
|
853
|
+
const secret = /^SECRET\./i.test(m.placeholder) || /pass|secret|token|key/i.test(m.placeholder);
|
|
854
|
+
const question = ` ${m.placeholder}${secret ? ' (hidden)' : ''}: `;
|
|
855
|
+
const value = secret ? await askHidden(question) : (await ask(question)).trim();
|
|
856
|
+
if (!value)
|
|
857
|
+
continue; // they put it in the env file — the retry re-reads it
|
|
858
|
+
typed[m.placeholder] = value;
|
|
859
|
+
toSave[m.setOneOf[0]] = value;
|
|
860
|
+
}
|
|
861
|
+
if (Object.keys(toSave).length) {
|
|
862
|
+
const keys = Object.keys(toSave).join(', ');
|
|
863
|
+
if (await askYesNo(`\n save ${keys} to ${e.envFile} so you're not asked again?`, true)) {
|
|
864
|
+
const file = await writeEnvValues(toSave).catch((err) => {
|
|
865
|
+
console.log(` couldn't save it: ${err.message} — using it for this run only`);
|
|
866
|
+
});
|
|
867
|
+
if (file)
|
|
868
|
+
console.log(` saved to ${file} (readable only by you)`);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
console.log();
|
|
872
|
+
return typed;
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Prove a recording and keep it as a flow, saying what happened. Used by
|
|
876
|
+
* `save`, and by `record` when the extension's "Save as a flow when I stop" is ticked.
|
|
877
|
+
*/
|
|
878
|
+
async function saveAndReport(recording, title, opts) {
|
|
879
|
+
if (opts.verify === false)
|
|
880
|
+
console.log('saving without a replay — it will be marked unproven until a run passes\n');
|
|
881
|
+
else
|
|
882
|
+
console.log(`proving ${recording.hash} by replaying it…\n`);
|
|
883
|
+
// No lessons: what gets saved is what the recording does on its own. Proving
|
|
884
|
+
// also works out whether it needs to start signed in (flows/execute.ts: prove).
|
|
885
|
+
let printed = false;
|
|
886
|
+
const out = await withLoginValues(opts.values ?? {}, (values) => proveAndSave(recording, {
|
|
887
|
+
title, ...opts, values,
|
|
888
|
+
keepIfFailed: async (proven) => {
|
|
889
|
+
printReplay(proven.result);
|
|
890
|
+
printed = true;
|
|
891
|
+
console.log('\nthe replay failed, so this would not normally be kept.');
|
|
892
|
+
return askYesNo('keep it anyway, marked unproven (the first run that passes proves it)?');
|
|
893
|
+
},
|
|
894
|
+
})).catch((e) => fail(e.message));
|
|
895
|
+
if (out.proven && !printed)
|
|
896
|
+
printReplay(out.proven.result);
|
|
897
|
+
const note = out.proven ? signInNote(recording, out.proven.signIn) : undefined;
|
|
898
|
+
if (note)
|
|
899
|
+
console.log(`\nsign-in ${note}`);
|
|
900
|
+
if (!out.saved) {
|
|
901
|
+
console.error('\nnot saved — the recording did not replay cleanly' + (recording.entry?.session ? ', signed in or not' : '') + '.');
|
|
902
|
+
console.error(' fix it or re-record; or keep it anyway with --force (or --no-verify to skip the replay), marked unproven.');
|
|
903
|
+
process.exitCode = 3;
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
const { flow } = out;
|
|
907
|
+
for (const c of out.placeholders.converted)
|
|
908
|
+
console.log(`\nemail uses ${c.placeholder} (value in ${c.valueIn}) — this app keeps emails out of memory`);
|
|
909
|
+
console.log(`\nsaved ${flow.app}/${flow.slug} (${flow.steps.length} steps${flow.embedding ? ', searchable by meaning' : ''})`);
|
|
910
|
+
if (flow.proven === false)
|
|
911
|
+
console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
|
|
912
|
+
if (flow.destructive)
|
|
913
|
+
console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
|
|
914
|
+
if (out.run)
|
|
915
|
+
printRunReport(out.run);
|
|
916
|
+
console.log(`\nreplay it any time: understudy replay ${flow.app} ${flow.slug}`);
|
|
917
|
+
}
|
|
918
|
+
async function cmdFlows(positional) {
|
|
919
|
+
const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
|
|
920
|
+
const { flows, runs } = await store.collections();
|
|
921
|
+
const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1 }).toArray();
|
|
922
|
+
if (!rows.length) {
|
|
923
|
+
console.log(`no flows for '${app}' yet — record one, then \`understudy save <hash> "<name>"\``);
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
for (const f of rows) {
|
|
927
|
+
const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
|
|
928
|
+
const status = last ? `${last.status} ${last.startedAt.toISOString().slice(0, 16).replace('T', ' ')}` : 'never run';
|
|
929
|
+
const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
|
|
930
|
+
.filter(Boolean).join(', ');
|
|
931
|
+
console.log(` ${f.slug.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
async function cmdFindings(positional, flags) {
|
|
935
|
+
const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
|
|
936
|
+
const { findings } = await store.collections();
|
|
937
|
+
const filter = flags.has('all') ? { app } : { app, status: 'open' };
|
|
938
|
+
const rows = await findings.find(filter).sort({ occurrences: -1, lastSeen: -1 }).limit(50).toArray();
|
|
939
|
+
if (!rows.length) {
|
|
940
|
+
console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
for (const f of rows) {
|
|
944
|
+
console.log(` ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
/** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
|
|
948
|
+
async function cmdEmit(positional, flags) {
|
|
949
|
+
const [app, slug] = positional;
|
|
950
|
+
if (!app || !slug)
|
|
951
|
+
fail('emit needs an app and a flow', 'understudy emit myapp log-in --framework cypress-js');
|
|
952
|
+
const framework = (str(flags.get('framework')) ?? 'playwright-ts');
|
|
953
|
+
if (framework !== 'playwright-ts' && framework !== 'cypress-js')
|
|
954
|
+
fail('--framework must be playwright-ts or cypress-js');
|
|
955
|
+
const { flows } = await store.collections();
|
|
956
|
+
const flow = await flows.findOne({ app, slug });
|
|
957
|
+
if (!flow)
|
|
958
|
+
fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
|
|
959
|
+
const out = emitFlow(flow, framework);
|
|
960
|
+
const file = str(flags.get('out'));
|
|
961
|
+
if (file) {
|
|
962
|
+
await writeFile(file, out.code);
|
|
963
|
+
console.log(`wrote ${file}`);
|
|
964
|
+
}
|
|
965
|
+
else
|
|
966
|
+
console.log(out.code);
|
|
967
|
+
for (const w of out.warnings)
|
|
968
|
+
console.error(`warning: ${w}`);
|
|
969
|
+
if (out.requiredValues.length)
|
|
970
|
+
console.error(`reads from the environment: ${out.requiredValues.map(valueEnvName).join(', ')}`);
|
|
971
|
+
}
|
|
972
|
+
// --- recordings --------------------------------------------------------------
|
|
973
|
+
async function cmdRecordings(positional) {
|
|
974
|
+
const rows = await listRecordings(positional[0]);
|
|
975
|
+
if (!rows.length)
|
|
976
|
+
console.log('no recordings yet — try `understudy record <app>`');
|
|
977
|
+
for (const r of rows) {
|
|
978
|
+
console.log(` ${r.hash} ${r.appSlug.padEnd(14)} ${String(r.events).padStart(3)} events ${r.source.padEnd(6)} ${r.createdAt}`);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
// --- main --------------------------------------------------------------------
|
|
982
|
+
async function main() {
|
|
983
|
+
const { flags, positional } = parseArgs(process.argv.slice(2));
|
|
984
|
+
const [command, ...rest] = positional;
|
|
985
|
+
if (!command || flags.has('help') || flags.has('h')) {
|
|
986
|
+
console.log(USAGE);
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
switch (command) {
|
|
990
|
+
case 'doctor': return cmdDoctor();
|
|
991
|
+
case 'config': return cmdConfig(rest, flags);
|
|
992
|
+
case 'extension': return cmdExtension();
|
|
993
|
+
case 'app': return cmdApp(rest, flags);
|
|
994
|
+
case 'reembed': return cmdReembed();
|
|
995
|
+
case 'record': return cmdRecord(rest, flags);
|
|
996
|
+
case 'import': return cmdImport(rest, flags);
|
|
997
|
+
case 'recordings': return cmdRecordings(rest);
|
|
998
|
+
case 'replay': return cmdReplay(rest, flags);
|
|
999
|
+
case 'save': return cmdSave(rest, flags);
|
|
1000
|
+
case 'flows': return cmdFlows(rest);
|
|
1001
|
+
case 'findings': return cmdFindings(rest, flags);
|
|
1002
|
+
case 'recall': return cmdRecall(rest, flags);
|
|
1003
|
+
case 'run': return cmdRun(rest, flags);
|
|
1004
|
+
case 'answer': return cmdAnswer(rest, flags);
|
|
1005
|
+
case 'distill': return cmdDistill(rest, flags);
|
|
1006
|
+
case 'remember': return cmdRemember(rest);
|
|
1007
|
+
case 'emit': return cmdEmit(rest, flags);
|
|
1008
|
+
default: fail(`unknown command '${command}'`, 'understudy --help');
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
main()
|
|
1012
|
+
.catch((err) => {
|
|
1013
|
+
console.error(`\nfailed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1014
|
+
process.exitCode = 1;
|
|
1015
|
+
})
|
|
1016
|
+
.finally(() => store.close());
|