@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,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning text into vectors, with any embedding model you like.
|
|
3
|
+
*
|
|
4
|
+
* Most providers speak the same format: POST `{ model, input: [texts] }` to
|
|
5
|
+
* `/v1/embeddings`, get back `{ data: [{ index, embedding }] }`. That covers
|
|
6
|
+
* Voyage, OpenAI, Mistral, Together, and local Ollama / LM Studio. So this is
|
|
7
|
+
* one adapter configured by four settings, not one adapter per vendor:
|
|
8
|
+
*
|
|
9
|
+
* EMBED_URL e.g. https://api.voyageai.com/v1/embeddings
|
|
10
|
+
* http://localhost:11434/v1/embeddings (Ollama, free, offline)
|
|
11
|
+
* EMBED_MODEL e.g. voyage-4-lite
|
|
12
|
+
* EMBED_KEY API key, if the endpoint needs one
|
|
13
|
+
* EMBED_DIMS vector length the model returns (default 1024)
|
|
14
|
+
*
|
|
15
|
+
* Just EMBED_KEY, and nothing else, means Voyage's voyage-4-lite — the default.
|
|
16
|
+
* Set none of them to run with no model at all: search
|
|
17
|
+
* then falls back to matching names.
|
|
18
|
+
*/
|
|
19
|
+
import './settings.js'; // loads settings before anything reads them
|
|
20
|
+
/** What you get with only EMBED_KEY set: Voyage's cheapest model. */
|
|
21
|
+
export const VOYAGE_DEFAULT = { url: 'https://api.voyageai.com/v1/embeddings', model: 'voyage-4-lite' };
|
|
22
|
+
/**
|
|
23
|
+
* The configured embedder, or null if none is set. Only EMBED_KEY set means
|
|
24
|
+
* Voyage (the default); a different model needs EMBED_URL and EMBED_MODEL.
|
|
25
|
+
*/
|
|
26
|
+
export function embedderConfig() {
|
|
27
|
+
let url = process.env.EMBED_URL?.trim();
|
|
28
|
+
let model = process.env.EMBED_MODEL?.trim();
|
|
29
|
+
if (!url && !model) {
|
|
30
|
+
if (!process.env.EMBED_KEY?.trim())
|
|
31
|
+
return null;
|
|
32
|
+
({ url, model } = VOYAGE_DEFAULT);
|
|
33
|
+
}
|
|
34
|
+
if (!url || !model)
|
|
35
|
+
throw new Error('set both EMBED_URL and EMBED_MODEL for a non-Voyage model, or neither (just EMBED_KEY means Voyage)');
|
|
36
|
+
const dims = Number(process.env.EMBED_DIMS ?? 1024);
|
|
37
|
+
if (!Number.isInteger(dims) || dims <= 0)
|
|
38
|
+
throw new Error(`EMBED_DIMS must be a positive whole number, got '${process.env.EMBED_DIMS}'`);
|
|
39
|
+
const key = process.env.EMBED_KEY?.trim();
|
|
40
|
+
return key ? { url, model, dims, key } : { url, model, dims };
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Voyage (directly, or through MongoDB's endpoint) embeds a search query
|
|
44
|
+
* differently from a stored document, and is told which by `input_type`.
|
|
45
|
+
* Other providers reject fields they don't know, so it is sent only to Voyage.
|
|
46
|
+
*/
|
|
47
|
+
export function sendsInputType(url) {
|
|
48
|
+
const host = new URL(url).hostname;
|
|
49
|
+
return host.endsWith('voyageai.com') || host === 'ai.mongodb.com';
|
|
50
|
+
}
|
|
51
|
+
/** Texts per request. Fewer requests matters: Voyage without a card allows 3 a minute. */
|
|
52
|
+
const BATCH = 128;
|
|
53
|
+
const MAX_TRIES = 4;
|
|
54
|
+
/**
|
|
55
|
+
* Embed many texts, in as few requests as possible. `purpose` is 'query' for
|
|
56
|
+
* text you search WITH and 'document' for text being stored.
|
|
57
|
+
*/
|
|
58
|
+
export async function embed(texts, purpose, cfg = embedderConfig()) {
|
|
59
|
+
if (!cfg)
|
|
60
|
+
throw new Error('no embedding model configured — set EMBED_KEY (Voyage), or EMBED_URL and EMBED_MODEL for another model');
|
|
61
|
+
const out = [];
|
|
62
|
+
for (let i = 0; i < texts.length; i += BATCH) {
|
|
63
|
+
out.push(...(await embedBatch(texts.slice(i, i + BATCH), purpose, cfg)));
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
async function embedBatch(input, purpose, cfg) {
|
|
68
|
+
const body = { model: cfg.model, input };
|
|
69
|
+
if (sendsInputType(cfg.url))
|
|
70
|
+
body.input_type = purpose;
|
|
71
|
+
const headers = { 'content-type': 'application/json' };
|
|
72
|
+
if (cfg.key)
|
|
73
|
+
headers.authorization = `Bearer ${cfg.key}`;
|
|
74
|
+
for (let attempt = 1;; attempt++) {
|
|
75
|
+
const res = await fetch(cfg.url, { method: 'POST', headers, body: JSON.stringify(body) });
|
|
76
|
+
// Rate limited or a server hiccup: wait (as told, if told) and try again.
|
|
77
|
+
if ((res.status === 429 || res.status >= 500) && attempt < MAX_TRIES) {
|
|
78
|
+
const told = Number(res.headers.get('retry-after'));
|
|
79
|
+
const waitMs = Number.isFinite(told) && res.headers.has('retry-after') ? told * 1000 : 5000 * 2 ** (attempt - 1);
|
|
80
|
+
await new Promise((r) => setTimeout(r, waitMs));
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
const detail = (await res.text()).slice(0, 300);
|
|
85
|
+
throw new Error(`embedding request failed: ${res.status} ${res.statusText} — ${detail}`);
|
|
86
|
+
}
|
|
87
|
+
const json = (await res.json());
|
|
88
|
+
const data = json.data;
|
|
89
|
+
if (!Array.isArray(data) || data.length !== input.length) {
|
|
90
|
+
throw new Error(`embedding endpoint returned ${data?.length ?? 'no'} vectors for ${input.length} texts`);
|
|
91
|
+
}
|
|
92
|
+
// Providers may return them out of order; `index` says where each belongs.
|
|
93
|
+
const vectors = [...data].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((d) => d.embedding);
|
|
94
|
+
const wrong = vectors.find((v) => v.length !== cfg.dims);
|
|
95
|
+
if (wrong) {
|
|
96
|
+
throw new Error(`${cfg.model} returns ${wrong.length}-number vectors but EMBED_DIMS is ${cfg.dims} — set EMBED_DIMS=${wrong.length}`);
|
|
97
|
+
}
|
|
98
|
+
return vectors;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebuild every vector with the model now configured.
|
|
3
|
+
*
|
|
4
|
+
* Needed after changing EMBED_MODEL or EMBED_DIMS, because vectors from two
|
|
5
|
+
* models can't be compared. Also fills in vectors for anything stored while no
|
|
6
|
+
* model was configured. A corpus is a few hundred short texts, so this is a
|
|
7
|
+
* handful of requests.
|
|
8
|
+
*/
|
|
9
|
+
export declare function reembed(): Promise<{
|
|
10
|
+
flows: number;
|
|
11
|
+
notes: number;
|
|
12
|
+
model: string;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebuild every vector with the model now configured.
|
|
3
|
+
*
|
|
4
|
+
* Needed after changing EMBED_MODEL or EMBED_DIMS, because vectors from two
|
|
5
|
+
* models can't be compared. Also fills in vectors for anything stored while no
|
|
6
|
+
* model was configured. A corpus is a few hundred short texts, so this is a
|
|
7
|
+
* handful of requests.
|
|
8
|
+
*/
|
|
9
|
+
import { collections, ensureSchema } from './db.js';
|
|
10
|
+
import { embed, embedderConfig } from './embed.js';
|
|
11
|
+
export async function reembed() {
|
|
12
|
+
const cfg = embedderConfig();
|
|
13
|
+
if (!cfg)
|
|
14
|
+
throw new Error('no embedding model configured — set EMBED_KEY (Voyage), or EMBED_URL and EMBED_MODEL for another model');
|
|
15
|
+
const c = await collections();
|
|
16
|
+
// Record the new model first, so ensureSchema accepts it and resizes the indexes.
|
|
17
|
+
await c.meta.replaceOne({ _id: 'embedder' }, { model: cfg.model, dims: cfg.dims, setAt: new Date() }, { upsert: true });
|
|
18
|
+
await ensureSchema();
|
|
19
|
+
return {
|
|
20
|
+
flows: await reembedCollection(c.flows),
|
|
21
|
+
notes: await reembedCollection(c.notes),
|
|
22
|
+
model: cfg.model,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
async function reembedCollection(coll) {
|
|
26
|
+
const docs = await coll.find({}, { projection: { searchText: 1 } }).toArray();
|
|
27
|
+
if (!docs.length)
|
|
28
|
+
return 0;
|
|
29
|
+
const vectors = await embed(docs.map((d) => d.searchText), 'document');
|
|
30
|
+
await coll.bulkWrite(docs.map((d, i) => ({ updateOne: { filter: { _id: d._id }, update: { $set: { embedding: vectors[i] } } } })));
|
|
31
|
+
return docs.length;
|
|
32
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where settings come from — MONGODB_URI, EMBED_*, and login values.
|
|
3
|
+
*
|
|
4
|
+
* Understudy is installed, not cloned, so it can't rely on a .env beside its
|
|
5
|
+
* code. Highest wins:
|
|
6
|
+
*
|
|
7
|
+
* 1. real environment variables (e.g. the `env` block of an MCP config)
|
|
8
|
+
* 2. --env-file <path> on the command line, CLI or MCP server
|
|
9
|
+
* 3. the env file saved with `understudy config --env-file <path>`
|
|
10
|
+
* (none saved: ~/.understudy/understudy.env)
|
|
11
|
+
* 4. .env in the current folder (handy when developing in the repo)
|
|
12
|
+
*
|
|
13
|
+
* Files never override what's already set, so (1) always wins. Loaded once, on
|
|
14
|
+
* first import, before anything reads process.env.
|
|
15
|
+
*/
|
|
16
|
+
/** ~/.understudy, or UNDERSTUDY_HOME. */
|
|
17
|
+
export declare const HOME: string;
|
|
18
|
+
export interface SavedConfig {
|
|
19
|
+
/** An env file to read settings from. */
|
|
20
|
+
envFile?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function readConfig(): SavedConfig;
|
|
23
|
+
export declare function writeConfig(cfg: SavedConfig): Promise<string>;
|
|
24
|
+
/** `~/x` → the home folder. Shells expand `~`, but a path in an MCP JSON config arrives as-is. */
|
|
25
|
+
export declare const expandHome: (p: string) => string;
|
|
26
|
+
/** `--env-file <path>` or `--env-file=<path>` from argv, if given. */
|
|
27
|
+
export declare function envFileFlag(argv?: string[]): string | undefined;
|
|
28
|
+
/** Which files were read, in order, so `understudy config` can say. */
|
|
29
|
+
export declare const loadedFrom: string[];
|
|
30
|
+
/**
|
|
31
|
+
* Read the env files again, filling in only what isn't set yet — so a login
|
|
32
|
+
* value the user just added to their env file is seen without a restart (the
|
|
33
|
+
* MCP server runs for a whole session).
|
|
34
|
+
*/
|
|
35
|
+
export declare function reloadEnvFiles(): void;
|
|
36
|
+
/**
|
|
37
|
+
* The environment variable that holds a login value. A recording never stores
|
|
38
|
+
* passwords; it stores a reference like `SECRET.password`, and the value comes
|
|
39
|
+
* from `UNDERSTUDY_SECRET_PASSWORD` — so nobody has to type it into a command,
|
|
40
|
+
* and an agent never has to see it.
|
|
41
|
+
*/
|
|
42
|
+
export declare function valueEnvName(ref: string): string;
|
|
43
|
+
/** The per-app variable: `UNDERSTUDY_SHOP_USER_EMAIL` for app `shop`, ref `USER.email`. */
|
|
44
|
+
export declare function appValueEnvName(app: string, ref: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* Where a reference's value may be set, in the order they're tried: the
|
|
47
|
+
* per-app variable first (so two apps can use different test accounts), then
|
|
48
|
+
* the shared one. `ENV.X` came from a script that read `process.env.X`, so `X`
|
|
49
|
+
* itself works too.
|
|
50
|
+
*/
|
|
51
|
+
export declare function valueEnvNames(ref: string, app?: string): string[];
|
|
52
|
+
/** Values for these references found in the environment. */
|
|
53
|
+
export declare function valuesFromEnv(refs: Iterable<string>, app?: string): Record<string, string>;
|
|
54
|
+
/** The env file Understudy writes to: the one given with --env-file, else the saved one, else ~/.understudy/understudy.env. */
|
|
55
|
+
export declare function writableEnvFile(): string;
|
|
56
|
+
/**
|
|
57
|
+
* Quote a value so dotenv reads it back EXACTLY. dotenv doesn't undo escapes
|
|
58
|
+
* like \" — a password with quotes in it would come back mangled — so pick a
|
|
59
|
+
* quote character the value doesn't contain: single quotes are fully literal.
|
|
60
|
+
*/
|
|
61
|
+
export declare function envFileQuote(key: string, value: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* Write KEY=value lines into the env file (replacing a key already there),
|
|
64
|
+
* readable only by you, and apply them to this process too. If no env file was
|
|
65
|
+
* chosen yet, ~/.understudy/understudy.env becomes the saved one.
|
|
66
|
+
*/
|
|
67
|
+
export declare function writeEnvValues(pairs: Record<string, string>): Promise<string>;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where settings come from — MONGODB_URI, EMBED_*, and login values.
|
|
3
|
+
*
|
|
4
|
+
* Understudy is installed, not cloned, so it can't rely on a .env beside its
|
|
5
|
+
* code. Highest wins:
|
|
6
|
+
*
|
|
7
|
+
* 1. real environment variables (e.g. the `env` block of an MCP config)
|
|
8
|
+
* 2. --env-file <path> on the command line, CLI or MCP server
|
|
9
|
+
* 3. the env file saved with `understudy config --env-file <path>`
|
|
10
|
+
* (none saved: ~/.understudy/understudy.env)
|
|
11
|
+
* 4. .env in the current folder (handy when developing in the repo)
|
|
12
|
+
*
|
|
13
|
+
* Files never override what's already set, so (1) always wins. Loaded once, on
|
|
14
|
+
* first import, before anything reads process.env.
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
17
|
+
import { mkdir, writeFile, chmod } from 'node:fs/promises';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { join, resolve } from 'node:path';
|
|
20
|
+
import { config as loadEnvFile } from 'dotenv';
|
|
21
|
+
/** ~/.understudy, or UNDERSTUDY_HOME. */
|
|
22
|
+
export const HOME = process.env.UNDERSTUDY_HOME ?? join(homedir(), '.understudy');
|
|
23
|
+
const CONFIG = join(HOME, 'config.json');
|
|
24
|
+
export function readConfig() {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(CONFIG, 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return {};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export async function writeConfig(cfg) {
|
|
33
|
+
await mkdir(HOME, { recursive: true, mode: 0o700 });
|
|
34
|
+
await writeFile(CONFIG, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
|
|
35
|
+
await chmod(CONFIG, 0o600).catch(() => { });
|
|
36
|
+
return CONFIG;
|
|
37
|
+
}
|
|
38
|
+
/** `~/x` → the home folder. Shells expand `~`, but a path in an MCP JSON config arrives as-is. */
|
|
39
|
+
export const expandHome = (p) => (p === '~' || p.startsWith('~/') ? join(homedir(), p.slice(1)) : p);
|
|
40
|
+
/** `--env-file <path>` or `--env-file=<path>` from argv, if given. */
|
|
41
|
+
export function envFileFlag(argv = process.argv) {
|
|
42
|
+
for (let i = 0; i < argv.length; i++) {
|
|
43
|
+
const a = argv[i];
|
|
44
|
+
if (a === '--env-file')
|
|
45
|
+
return argv[i + 1] && expandHome(argv[i + 1]);
|
|
46
|
+
if (a.startsWith('--env-file='))
|
|
47
|
+
return expandHome(a.slice('--env-file='.length));
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
/** Which files were read, in order, so `understudy config` can say. */
|
|
52
|
+
export const loadedFrom = [];
|
|
53
|
+
function load() {
|
|
54
|
+
const saved = readConfig().envFile;
|
|
55
|
+
// No env file saved yet: the default one, which is where we tell people to put things.
|
|
56
|
+
const candidates = [envFileFlag(), saved ? expandHome(saved) : join(HOME, 'understudy.env'), resolve('.env')].filter((p) => Boolean(p));
|
|
57
|
+
for (const path of candidates) {
|
|
58
|
+
if (!existsSync(path))
|
|
59
|
+
continue;
|
|
60
|
+
loadEnvFile({ path, override: false, quiet: true });
|
|
61
|
+
loadedFrom.push(path);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
load();
|
|
65
|
+
/**
|
|
66
|
+
* Read the env files again, filling in only what isn't set yet — so a login
|
|
67
|
+
* value the user just added to their env file is seen without a restart (the
|
|
68
|
+
* MCP server runs for a whole session).
|
|
69
|
+
*/
|
|
70
|
+
export function reloadEnvFiles() {
|
|
71
|
+
loadedFrom.length = 0;
|
|
72
|
+
load();
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The environment variable that holds a login value. A recording never stores
|
|
76
|
+
* passwords; it stores a reference like `SECRET.password`, and the value comes
|
|
77
|
+
* from `UNDERSTUDY_SECRET_PASSWORD` — so nobody has to type it into a command,
|
|
78
|
+
* and an agent never has to see it.
|
|
79
|
+
*/
|
|
80
|
+
export function valueEnvName(ref) {
|
|
81
|
+
return `UNDERSTUDY_${ref.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_|_$/g, '').toUpperCase()}`;
|
|
82
|
+
}
|
|
83
|
+
/** The per-app variable: `UNDERSTUDY_SHOP_USER_EMAIL` for app `shop`, ref `USER.email`. */
|
|
84
|
+
export function appValueEnvName(app, ref) {
|
|
85
|
+
return valueEnvName(`${app}.${ref}`);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Where a reference's value may be set, in the order they're tried: the
|
|
89
|
+
* per-app variable first (so two apps can use different test accounts), then
|
|
90
|
+
* the shared one. `ENV.X` came from a script that read `process.env.X`, so `X`
|
|
91
|
+
* itself works too.
|
|
92
|
+
*/
|
|
93
|
+
export function valueEnvNames(ref, app) {
|
|
94
|
+
const names = [...(app ? [appValueEnvName(app, ref)] : []), valueEnvName(ref)];
|
|
95
|
+
if (ref.startsWith('ENV.'))
|
|
96
|
+
names.push(ref.slice(4));
|
|
97
|
+
return names;
|
|
98
|
+
}
|
|
99
|
+
/** Values for these references found in the environment. */
|
|
100
|
+
export function valuesFromEnv(refs, app) {
|
|
101
|
+
const out = {};
|
|
102
|
+
for (const ref of refs) {
|
|
103
|
+
const name = valueEnvNames(ref, app).find((n) => process.env[n] !== undefined);
|
|
104
|
+
if (name)
|
|
105
|
+
out[ref] = process.env[name];
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** The env file Understudy writes to: the one given with --env-file, else the saved one, else ~/.understudy/understudy.env. */
|
|
110
|
+
export function writableEnvFile() {
|
|
111
|
+
return envFileFlag() ?? (readConfig().envFile && expandHome(readConfig().envFile)) ?? join(HOME, 'understudy.env');
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Quote a value so dotenv reads it back EXACTLY. dotenv doesn't undo escapes
|
|
115
|
+
* like \" — a password with quotes in it would come back mangled — so pick a
|
|
116
|
+
* quote character the value doesn't contain: single quotes are fully literal.
|
|
117
|
+
*/
|
|
118
|
+
export function envFileQuote(key, value) {
|
|
119
|
+
if (/[\r\n]/.test(value))
|
|
120
|
+
throw new Error(`${key}: values can't contain line breaks`);
|
|
121
|
+
for (const q of ["'", '"', '`']) {
|
|
122
|
+
if (!value.includes(q))
|
|
123
|
+
return q + value + q;
|
|
124
|
+
}
|
|
125
|
+
throw new Error(`${key}: the value contains ', " and \` — put it in the env file by hand, or set it in the environment`);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Write KEY=value lines into the env file (replacing a key already there),
|
|
129
|
+
* readable only by you, and apply them to this process too. If no env file was
|
|
130
|
+
* chosen yet, ~/.understudy/understudy.env becomes the saved one.
|
|
131
|
+
*/
|
|
132
|
+
export async function writeEnvValues(pairs) {
|
|
133
|
+
const file = writableEnvFile();
|
|
134
|
+
const cfg = readConfig();
|
|
135
|
+
if (!envFileFlag() && !cfg.envFile)
|
|
136
|
+
await writeConfig({ ...cfg, envFile: file });
|
|
137
|
+
await mkdir(HOME, { recursive: true, mode: 0o700 }).catch(() => { });
|
|
138
|
+
const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [];
|
|
139
|
+
for (const [key, value] of Object.entries(pairs)) {
|
|
140
|
+
const line = `${key}=${envFileQuote(key, value)}`;
|
|
141
|
+
const at = lines.findIndex((l) => l.startsWith(`${key}=`));
|
|
142
|
+
if (at >= 0)
|
|
143
|
+
lines[at] = line;
|
|
144
|
+
else
|
|
145
|
+
lines.push(line);
|
|
146
|
+
process.env[key] = value;
|
|
147
|
+
}
|
|
148
|
+
await writeFile(file, lines.filter((l, i) => l || i < lines.length - 1).join('\n').replace(/\n*$/, '\n'), { mode: 0o600 });
|
|
149
|
+
await chmod(file, 0o600).catch(() => { });
|
|
150
|
+
return file;
|
|
151
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of every document Understudy stores. One collection per idea:
|
|
3
|
+
*
|
|
4
|
+
* apps a website you test
|
|
5
|
+
* flows a sequence of steps that does one thing (recordings + segments)
|
|
6
|
+
* pages a fingerprint of a page state, and the links out of it
|
|
7
|
+
* notes something learned: a fact (changes the plan) or a lesson (changes a step)
|
|
8
|
+
* findings "the app is broken here"
|
|
9
|
+
* runs one attempt at a goal
|
|
10
|
+
*
|
|
11
|
+
* Steps live inside their flow, because you never want one without the other.
|
|
12
|
+
*/
|
|
13
|
+
import type { ObjectId } from 'mongodb';
|
|
14
|
+
import type { RawEvent } from '../core/recording.js';
|
|
15
|
+
export type Precondition = 'authenticated' | 'not authenticated';
|
|
16
|
+
/** Kinds of typed value an app can choose to keep as placeholders. Just email, for now. */
|
|
17
|
+
export declare const PLACEHOLDER_KINDS: readonly ["email"];
|
|
18
|
+
export type PlaceholderKind = (typeof PLACEHOLDER_KINDS)[number];
|
|
19
|
+
/**
|
|
20
|
+
* One action in a flow. Exactly the shape the recorder emits, minus its
|
|
21
|
+
* bookkeeping (`seq` is the array position here; `ts` is not needed).
|
|
22
|
+
*/
|
|
23
|
+
export type Step = Omit<RawEvent, 'seq' | 'ts'>;
|
|
24
|
+
export interface App {
|
|
25
|
+
_id?: ObjectId;
|
|
26
|
+
slug: string;
|
|
27
|
+
name: string;
|
|
28
|
+
/** Base URL per environment, e.g. { local: 'http://localhost:3000' }. */
|
|
29
|
+
urls: Record<string, string>;
|
|
30
|
+
/**
|
|
31
|
+
* Kinds of typed value to keep out of memory as placeholders, beyond the
|
|
32
|
+
* passwords that always are. `email`: email fields become `USER.email`, the
|
|
33
|
+
* value moves to the user's env file. See memory/placeholders.ts.
|
|
34
|
+
*/
|
|
35
|
+
placeholders?: PlaceholderKind[];
|
|
36
|
+
createdAt: Date;
|
|
37
|
+
}
|
|
38
|
+
export interface Flow {
|
|
39
|
+
_id?: ObjectId;
|
|
40
|
+
app: string;
|
|
41
|
+
slug: string;
|
|
42
|
+
title: string;
|
|
43
|
+
/** What the flow is FOR, phrased the way someone would ask for it. */
|
|
44
|
+
intent: string;
|
|
45
|
+
/** A recording is captured whole; a segment is cut from one so others can reuse it. */
|
|
46
|
+
kind: 'recording' | 'segment';
|
|
47
|
+
/**
|
|
48
|
+
* Who made it: 'user' recorded it; 'agent' drove it itself and handed over
|
|
49
|
+
* the script. Both are proven by replay before they're kept. Missing = 'user'
|
|
50
|
+
* (flows saved before this field existed were all recordings).
|
|
51
|
+
*/
|
|
52
|
+
madeBy?: 'user' | 'agent';
|
|
53
|
+
/**
|
|
54
|
+
* False when it was kept without a passing replay (skipped, or kept after
|
|
55
|
+
* failing). Missing = proven. The first run that passes sets it back, and
|
|
56
|
+
* fills in what a replay records: the page each step lands on.
|
|
57
|
+
*/
|
|
58
|
+
proven?: boolean;
|
|
59
|
+
/** Why it's unproven, e.g. "saved without a replay". */
|
|
60
|
+
unprovenBecause?: string;
|
|
61
|
+
/** Segments only: the flow it was cut from, and which of its steps ([start, end)). */
|
|
62
|
+
from?: {
|
|
63
|
+
flow: string;
|
|
64
|
+
steps: [number, number];
|
|
65
|
+
};
|
|
66
|
+
preconditions: Precondition[];
|
|
67
|
+
outcome: string;
|
|
68
|
+
/** True if running it commits something real (a purchase, a submission). */
|
|
69
|
+
destructive: boolean;
|
|
70
|
+
/** Where a capture deliberately stops, and why. Read by whoever picks it up next. */
|
|
71
|
+
corrections: string[];
|
|
72
|
+
/** Why it was marked destructive, e.g. 'commit-shaped control "Place order"'. */
|
|
73
|
+
destructiveBecause?: string;
|
|
74
|
+
/** The recording this flow was saved from (its hash), so it can be traced back. */
|
|
75
|
+
recording: string;
|
|
76
|
+
/** Where replay starts. */
|
|
77
|
+
startUrl: string;
|
|
78
|
+
/** True if the first step needs a signed-in browser (recorded with --arm-manually, or from a signed-in tab). */
|
|
79
|
+
requiresSession: boolean;
|
|
80
|
+
/** The saved session to restore, by id (recorded from a signed-in tab by the Chrome extension). */
|
|
81
|
+
session?: string;
|
|
82
|
+
/** Page fingerprint before the first step / after the last — how flows join up. */
|
|
83
|
+
startState?: string;
|
|
84
|
+
endState?: string;
|
|
85
|
+
/** Each step's `expectedSig` is the page seen after it when the flow was proven. */
|
|
86
|
+
steps: Step[];
|
|
87
|
+
/** The text that gets embedded and searched: title + intent + outcome. */
|
|
88
|
+
searchText: string;
|
|
89
|
+
embedding?: number[];
|
|
90
|
+
createdAt: Date;
|
|
91
|
+
updatedAt: Date;
|
|
92
|
+
}
|
|
93
|
+
export interface Page {
|
|
94
|
+
_id?: ObjectId;
|
|
95
|
+
app: string;
|
|
96
|
+
/** sig(): `<url pattern>#<8 hex>`. */
|
|
97
|
+
sig: string;
|
|
98
|
+
urlPattern: string;
|
|
99
|
+
/** Known ways out of this page. */
|
|
100
|
+
links: {
|
|
101
|
+
to: string;
|
|
102
|
+
via: {
|
|
103
|
+
role: string;
|
|
104
|
+
name: string;
|
|
105
|
+
};
|
|
106
|
+
}[];
|
|
107
|
+
firstSeen: Date;
|
|
108
|
+
lastSeen: Date;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* When a lesson fires: every field present must equal the step's exactly, and
|
|
112
|
+
* an absent field matches anything. Never empty — that would match every step.
|
|
113
|
+
*/
|
|
114
|
+
export interface Trigger {
|
|
115
|
+
/** The page the step is on, as a URL pattern like `/login` or `/orders/:id`. */
|
|
116
|
+
url_pattern?: string;
|
|
117
|
+
action?: string;
|
|
118
|
+
role?: string;
|
|
119
|
+
name?: string;
|
|
120
|
+
}
|
|
121
|
+
export interface Note {
|
|
122
|
+
_id?: ObjectId;
|
|
123
|
+
app: string;
|
|
124
|
+
/** fact: changes what you plan. lesson: has a trigger and changes one step. */
|
|
125
|
+
kind: 'fact' | 'lesson';
|
|
126
|
+
text: string;
|
|
127
|
+
/** Lessons only: a short name, unique per app (re-adding one doesn't duplicate it). */
|
|
128
|
+
title?: string;
|
|
129
|
+
/** Lessons only: what kind of fix — `wait`/`timing` make replay settle the page first. */
|
|
130
|
+
lessonKind?: string;
|
|
131
|
+
/** Lessons only. */
|
|
132
|
+
trigger?: Trigger;
|
|
133
|
+
/** Facts only: a control whose click commits something real — flows clicking it are destructive. */
|
|
134
|
+
marksDestructive?: string;
|
|
135
|
+
timesApplied: number;
|
|
136
|
+
/** Fired on a step whose fingerprint has failed before, and the step passed. */
|
|
137
|
+
timesHelped: number;
|
|
138
|
+
searchText: string;
|
|
139
|
+
embedding?: number[];
|
|
140
|
+
createdAt: Date;
|
|
141
|
+
}
|
|
142
|
+
export interface Finding {
|
|
143
|
+
_id?: ObjectId;
|
|
144
|
+
app: string;
|
|
145
|
+
kind: string;
|
|
146
|
+
severity: 'low' | 'medium' | 'high';
|
|
147
|
+
statement: string;
|
|
148
|
+
evidence: Record<string, unknown>;
|
|
149
|
+
/** Same problem across runs → same fingerprint → one finding, more occurrences. */
|
|
150
|
+
fingerprint: string;
|
|
151
|
+
occurrences: number;
|
|
152
|
+
firstSeen: Date;
|
|
153
|
+
lastSeen: Date;
|
|
154
|
+
/** open until someone triages it: a real bug (issue), a workaround (lesson), or noise. */
|
|
155
|
+
status: 'open' | 'issue' | 'lesson' | 'noise';
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Which embedding model filled this database. Vectors from two models can't be
|
|
159
|
+
* compared, so Understudy refuses to start if .env names a different one.
|
|
160
|
+
* Lives in the one-document `meta` collection.
|
|
161
|
+
*/
|
|
162
|
+
export interface EmbedderMeta {
|
|
163
|
+
_id: 'embedder';
|
|
164
|
+
model: string;
|
|
165
|
+
dims: number;
|
|
166
|
+
setAt: Date;
|
|
167
|
+
}
|
|
168
|
+
export interface Run {
|
|
169
|
+
_id?: ObjectId;
|
|
170
|
+
app: string;
|
|
171
|
+
goal: string;
|
|
172
|
+
/**
|
|
173
|
+
* run: planned from a goal. replay: one flow, verbatim.
|
|
174
|
+
* attributed: an agent reached the goal by other means and reported it.
|
|
175
|
+
*/
|
|
176
|
+
mode: 'run' | 'replay' | 'attributed';
|
|
177
|
+
/**
|
|
178
|
+
* waiting: planning paused on a question for the agent (`question` says what).
|
|
179
|
+
* planned: a dry run — the plan is complete, nothing ran.
|
|
180
|
+
* blocked: the plan can't be completed (a sub-goal with no flow, a gap between flows).
|
|
181
|
+
*/
|
|
182
|
+
status: 'waiting' | 'planned' | 'passed' | 'failed' | 'blocked';
|
|
183
|
+
/** The flow slugs bound, in order. */
|
|
184
|
+
plan: string[];
|
|
185
|
+
/** One line per step: what it did and where it ended up. `fingerprint` identifies the step across runs. */
|
|
186
|
+
steps: {
|
|
187
|
+
seq: number;
|
|
188
|
+
action: string;
|
|
189
|
+
ok: boolean;
|
|
190
|
+
sig?: string;
|
|
191
|
+
error?: string;
|
|
192
|
+
fingerprint?: string;
|
|
193
|
+
}[];
|
|
194
|
+
/** The page fingerprints actually passed through — compared across runs for drift. */
|
|
195
|
+
sigSequence: string[];
|
|
196
|
+
/** Console errors, failed requests, non-2xx responses (first 200). */
|
|
197
|
+
events: Record<string, unknown>[];
|
|
198
|
+
/** Fingerprints of the findings this run raised. */
|
|
199
|
+
findings: string[];
|
|
200
|
+
durationMs: number;
|
|
201
|
+
/** Set while status is 'waiting': the question the agent must answer. */
|
|
202
|
+
question?: Record<string, unknown>;
|
|
203
|
+
/** Why the run is blocked, in one line. */
|
|
204
|
+
blockedBecause?: string;
|
|
205
|
+
/** Planning progress, so a run can pause for a question and pick up where it left off. */
|
|
206
|
+
planning?: {
|
|
207
|
+
subGoals?: string[];
|
|
208
|
+
/** Flow slug bound to each sub-goal, in order. */
|
|
209
|
+
bound?: string[];
|
|
210
|
+
/** Steps to insert BEFORE plan[i], for i ≥ 1. Missing entry = not resolved yet. */
|
|
211
|
+
seams?: Record<string, {
|
|
212
|
+
steps: Step[];
|
|
213
|
+
how: string;
|
|
214
|
+
}>;
|
|
215
|
+
dryRun?: boolean;
|
|
216
|
+
allowPurchases?: boolean;
|
|
217
|
+
};
|
|
218
|
+
startedAt: Date;
|
|
219
|
+
endedAt?: Date;
|
|
220
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of every document Understudy stores. One collection per idea:
|
|
3
|
+
*
|
|
4
|
+
* apps a website you test
|
|
5
|
+
* flows a sequence of steps that does one thing (recordings + segments)
|
|
6
|
+
* pages a fingerprint of a page state, and the links out of it
|
|
7
|
+
* notes something learned: a fact (changes the plan) or a lesson (changes a step)
|
|
8
|
+
* findings "the app is broken here"
|
|
9
|
+
* runs one attempt at a goal
|
|
10
|
+
*
|
|
11
|
+
* Steps live inside their flow, because you never want one without the other.
|
|
12
|
+
*/
|
|
13
|
+
/** Kinds of typed value an app can choose to keep as placeholders. Just email, for now. */
|
|
14
|
+
export const PLACEHOLDER_KINDS = ['email'];
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Understudy recorder (browser extension)
|
|
2
|
+
|
|
3
|
+
Record a flow in the browser you already use — on the tab you're already on,
|
|
4
|
+
signed in or not — instead of a fresh browser that Understudy opens.
|
|
5
|
+
|
|
6
|
+
## Install (once)
|
|
7
|
+
|
|
8
|
+
**Chrome, Brave, Arc, Opera, Vivaldi, Edge:** install it from the
|
|
9
|
+
[Chrome Web Store](https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf), then pin it (puzzle-piece icon → pin
|
|
10
|
+
**Understudy recorder**) so it's one click away. Edge asks you to allow
|
|
11
|
+
extensions from other stores first.
|
|
12
|
+
|
|
13
|
+
**Or load it by hand**= — `understudy extension`
|
|
14
|
+
prints where this folder is:
|
|
15
|
+
|
|
16
|
+
1. Open your browser's extensions page and turn on **Developer mode**:
|
|
17
|
+
| Browser | Extensions page |
|
|
18
|
+
|---|---|
|
|
19
|
+
| Chrome | `chrome://extensions` |
|
|
20
|
+
| Edge | `edge://extensions` |
|
|
21
|
+
| Brave | `brave://extensions` |
|
|
22
|
+
| Arc, Opera, Vivaldi | their extensions page (all accept Chrome extensions) |
|
|
23
|
+
2. Click **Load unpacked** and choose this `extension/` folder.
|
|
24
|
+
3. Pin it (puzzle-piece icon → pin **Understudy recorder**) so it's one click away.
|
|
25
|
+
|
|
26
|
+
**Safari (and anywhere else the extension won't run):** record in a fresh
|
|
27
|
+
browser that Understudy opens instead. It's a one-time extra download — the
|
|
28
|
+
full Chromium browser, about 350 MB:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx playwright install chromium
|
|
32
|
+
understudy record <app> --new-browser --url https://your-app.example
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
A Chromium window opens on that address. Click through the flow, then close
|
|
36
|
+
the window to stop; the terminal prints the recording's hash for `understudy
|
|
37
|
+
save`. The address is remembered, so next time `--new-browser` alone is
|
|
38
|
+
enough. Signed-in flows: add `--arm-manually`, sign in first, then press Enter
|
|
39
|
+
in the terminal to start recording from there.
|
|
40
|
+
|
|
41
|
+
## Record
|
|
42
|
+
|
|
43
|
+
1. In a terminal: `understudy record <app>`. It waits for the extension.
|
|
44
|
+
2. In your browser, go to the page where the flow starts.
|
|
45
|
+
3. Click the Understudy icon → **Record from this page**. The first time on a
|
|
46
|
+
site, the browser asks to let Understudy access it — that's the only site
|
|
47
|
+
it gets.
|
|
48
|
+
- **I'm signed in here:** tick it if the flow starts signed in, and replay
|
|
49
|
+
will start signed in too. Not sure? Leave it: Understudy copies the tab's
|
|
50
|
+
sign-in anyway, then when you `save` it tries the flow without it first,
|
|
51
|
+
and deletes the copy if it wasn't needed. Either way it's a file on your
|
|
52
|
+
machine (`.understudy/sessions/`, readable only by you), never sent
|
|
53
|
+
anywhere else.
|
|
54
|
+
4. Use the page as normal. The icon shows **REC**.
|
|
55
|
+
5. Click the icon → say what the flow does → **Stop**. With **Save as a flow
|
|
56
|
+
when I stop** ticked (the default), the terminal replays it headless to
|
|
57
|
+
prove it works, then keeps it.
|
|
58
|
+
6. Unticked, it's only recorded: the popup shows the command to save it later,
|
|
59
|
+
`understudy save <hash> "<what it does>"`. (Ctrl+C in the terminal also
|
|
60
|
+
stops.) If an agent started the recording, the agent saves it.
|
|
61
|
+
|
|
62
|
+
If the replay fails — say the page started in a state the replay can't repeat —
|
|
63
|
+
the terminal asks whether to keep it anyway. Kept, it's marked **unproven**
|
|
64
|
+
until a run of it passes.
|
|
65
|
+
|
|
66
|
+
## What it can't record
|
|
67
|
+
|
|
68
|
+
- **File uploads.** A page can see that a file was picked, never which one, so
|
|
69
|
+
it can't be replayed. Write that part as a Playwright script and
|
|
70
|
+
`understudy import` it.
|
|
71
|
+
- **Other sites mid-flow** (a payment provider's page, say) unless you've
|
|
72
|
+
allowed them too. Steps there aren't recorded.
|
|
73
|
+
- **The browser's own pages** (`chrome://`, `edge://`…) **and its extension store.** Browsers don't allow it.
|
|
74
|
+
|
|
75
|
+
Passwords are never recorded: a password field is stored as a reference like
|
|
76
|
+
`SECRET.password`, and you supply the value when replaying.
|