@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,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeping more typed values out of memory, per app.
|
|
3
|
+
*
|
|
4
|
+
* Passwords are always placeholders. An app can also choose `email`: every
|
|
5
|
+
* email field in its flows stops storing the address it was recorded with and
|
|
6
|
+
* uses a placeholder instead — `USER.email`, read from the user's env file —
|
|
7
|
+
* so a test account can be swapped per run and personal data doesn't sit in a
|
|
8
|
+
* (possibly shared) database.
|
|
9
|
+
*
|
|
10
|
+
* Turning it on converts the app's existing flows and MOVES each address into
|
|
11
|
+
* the env file, so nothing breaks and nothing needs setting up. New flows are
|
|
12
|
+
* converted when they're saved, after they've been proven with the real value.
|
|
13
|
+
*
|
|
14
|
+
* Several different addresses in one app (several test accounts) each get
|
|
15
|
+
* their own placeholder — the most used is USER.email, then USER.email_2 … —
|
|
16
|
+
* because merging them would quietly log some flows in as the wrong account.
|
|
17
|
+
*/
|
|
18
|
+
import { collections } from '../store/db.js';
|
|
19
|
+
import { appValueEnvName, valueEnvName, writeEnvValues } from '../store/settings.js';
|
|
20
|
+
import { PLACEHOLDER_KINDS } from '../store/types.js';
|
|
21
|
+
const EMAIL_IN_NAME = /e-?mail/i;
|
|
22
|
+
const LOOKS_LIKE_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
23
|
+
/** Is this a step that types an email address the recording stored as-is? */
|
|
24
|
+
export function isEmailStep(s) {
|
|
25
|
+
if (s.action !== 'fill' || s.valueRef || !s.value)
|
|
26
|
+
return false;
|
|
27
|
+
const named = [s.name, s.testId, s.css].some((x) => x && EMAIL_IN_NAME.test(x));
|
|
28
|
+
return named || s.hints?.inputType === 'email' || LOOKS_LIKE_EMAIL.test(s.value);
|
|
29
|
+
}
|
|
30
|
+
/** The app's chosen kinds (validated). */
|
|
31
|
+
export async function appPlaceholders(app) {
|
|
32
|
+
const { apps } = await collections();
|
|
33
|
+
return (await apps.findOne({ slug: app }))?.placeholders ?? [];
|
|
34
|
+
}
|
|
35
|
+
/** Choose which kinds of value an app keeps as placeholders, and apply it to its flows now. */
|
|
36
|
+
export async function setPlaceholders(app, kinds) {
|
|
37
|
+
const bad = kinds.filter((k) => !PLACEHOLDER_KINDS.includes(k));
|
|
38
|
+
if (bad.length)
|
|
39
|
+
throw new Error(`unknown placeholder kind(s): ${bad.join(', ')} — available: ${PLACEHOLDER_KINDS.join(', ')}`);
|
|
40
|
+
const { apps, flows } = await collections();
|
|
41
|
+
if (!(await flows.findOne({ app })) && !(await apps.findOne({ slug: app })))
|
|
42
|
+
throw new Error(`no app '${app}' — save a flow for it first`);
|
|
43
|
+
const chosen = [...new Set(kinds)];
|
|
44
|
+
await apps.updateOne({ slug: app }, { $set: { placeholders: chosen }, $setOnInsert: { slug: app, name: app, urls: {}, createdAt: new Date() } }, { upsert: true });
|
|
45
|
+
return applyPlaceholders(app, chosen);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Convert the app's flows (or just `onlyFlow`) to placeholders for the chosen
|
|
49
|
+
* kinds, moving each value into the env file unless the environment already has it.
|
|
50
|
+
*/
|
|
51
|
+
export async function applyPlaceholders(app, kinds, onlyFlow) {
|
|
52
|
+
const chosen = kinds ?? (await appPlaceholders(app));
|
|
53
|
+
const out = { app, placeholders: chosen, converted: [] };
|
|
54
|
+
if (!chosen.includes('email'))
|
|
55
|
+
return out;
|
|
56
|
+
const { flows } = await collections();
|
|
57
|
+
const all = await flows.find({ app }).toArray();
|
|
58
|
+
const targets = onlyFlow ? all.filter((f) => f.slug === onlyFlow) : all;
|
|
59
|
+
// Which addresses these flows type, most-used first. (An address that was
|
|
60
|
+
// moved before keeps its placeholder: found below by its value.)
|
|
61
|
+
const uses = new Map();
|
|
62
|
+
for (const f of targets)
|
|
63
|
+
for (const s of f.steps)
|
|
64
|
+
if (isEmailStep(s))
|
|
65
|
+
uses.set(s.value, (uses.get(s.value) ?? 0) + 1);
|
|
66
|
+
if (!uses.size)
|
|
67
|
+
return out;
|
|
68
|
+
const env = process.env;
|
|
69
|
+
const refFor = new Map();
|
|
70
|
+
const write = {};
|
|
71
|
+
const where = new Map();
|
|
72
|
+
// An address already moved earlier keeps its placeholder: find it by value.
|
|
73
|
+
const takenRefs = new Set();
|
|
74
|
+
for (const f of all)
|
|
75
|
+
for (const s of f.steps)
|
|
76
|
+
if (s.valueRef?.startsWith('USER.email'))
|
|
77
|
+
takenRefs.add(s.valueRef);
|
|
78
|
+
for (const ref of takenRefs) {
|
|
79
|
+
for (const name of [appValueEnvName(app, ref), valueEnvName(ref)]) {
|
|
80
|
+
const v = env[name];
|
|
81
|
+
if (v !== undefined && uses.has(v) && !refFor.has(v)) {
|
|
82
|
+
refFor.set(v, ref);
|
|
83
|
+
where.set(ref, name);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
let n = 1;
|
|
88
|
+
const nextRef = () => {
|
|
89
|
+
for (;;) {
|
|
90
|
+
const ref = n === 1 ? 'USER.email' : `USER.email_${n}`;
|
|
91
|
+
n++;
|
|
92
|
+
if (!takenRefs.has(ref))
|
|
93
|
+
return ref;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
for (const value of [...uses.keys()].sort((a, b) => uses.get(b) - uses.get(a))) {
|
|
97
|
+
if (refFor.has(value))
|
|
98
|
+
continue;
|
|
99
|
+
const ref = nextRef();
|
|
100
|
+
refFor.set(value, ref);
|
|
101
|
+
takenRefs.add(ref);
|
|
102
|
+
// The shared variable if it's free (or already this address); otherwise this
|
|
103
|
+
// app's own, so two apps can use different accounts.
|
|
104
|
+
const shared = valueEnvName(ref);
|
|
105
|
+
const own = appValueEnvName(app, ref);
|
|
106
|
+
if (env[own] === value)
|
|
107
|
+
where.set(ref, own);
|
|
108
|
+
else if (env[shared] === value || (env[shared] === undefined && write[shared] === undefined)) {
|
|
109
|
+
where.set(ref, shared);
|
|
110
|
+
if (env[shared] === undefined)
|
|
111
|
+
write[shared] = value;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
where.set(ref, own);
|
|
115
|
+
write[own] = value;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (Object.keys(write).length)
|
|
119
|
+
out.envFile = await writeEnvValues(write);
|
|
120
|
+
const flowsUsing = new Map();
|
|
121
|
+
for (const f of targets) {
|
|
122
|
+
let changed = false;
|
|
123
|
+
const steps = f.steps.map((s) => {
|
|
124
|
+
if (!isEmailStep(s))
|
|
125
|
+
return s;
|
|
126
|
+
const ref = refFor.get(s.value);
|
|
127
|
+
const { value: _gone, ...rest } = s;
|
|
128
|
+
changed = true;
|
|
129
|
+
(flowsUsing.get(ref) ?? flowsUsing.set(ref, new Set()).get(ref)).add(f.slug);
|
|
130
|
+
return { ...rest, valueRef: ref };
|
|
131
|
+
});
|
|
132
|
+
if (changed)
|
|
133
|
+
await flows.updateOne({ _id: f._id }, { $set: { steps, updatedAt: new Date() } });
|
|
134
|
+
}
|
|
135
|
+
out.converted = [...flowsUsing.entries()].map(([placeholder, slugs]) => ({
|
|
136
|
+
placeholder, flows: [...slugs].sort(), valueIn: where.get(placeholder),
|
|
137
|
+
}));
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* recall: what does memory know about a goal?
|
|
3
|
+
*
|
|
4
|
+
* A database query — no browser, no model call beyond embedding the goal — so
|
|
5
|
+
* it is cheap enough to run before every action. It returns the closest flows
|
|
6
|
+
* and notes, and a verdict:
|
|
7
|
+
*
|
|
8
|
+
* known one flow clearly does this — safe to run it
|
|
9
|
+
* unsure something is close, but not clearly the answer — show, don't run
|
|
10
|
+
* unknown nothing does this — record it rather than guess
|
|
11
|
+
*
|
|
12
|
+
* Two ways to match, depending on whether an embedding model is configured:
|
|
13
|
+
* meaning embed the goal and search by vector (any wording works)
|
|
14
|
+
* words no model: match the goal's words against flow names
|
|
15
|
+
* Either way, a goal that IS a flow's name or slug matches exactly.
|
|
16
|
+
*/
|
|
17
|
+
import type { Flow, Note } from '../store/types.js';
|
|
18
|
+
export interface FlowMatch {
|
|
19
|
+
slug: string;
|
|
20
|
+
title: string;
|
|
21
|
+
kind: Flow['kind'];
|
|
22
|
+
madeBy: 'user' | 'agent';
|
|
23
|
+
/** False: kept without a passing replay — may not work. */
|
|
24
|
+
proven: boolean;
|
|
25
|
+
/** Why it's unproven, when it is. */
|
|
26
|
+
unprovenBecause?: string;
|
|
27
|
+
score: number;
|
|
28
|
+
destructive: boolean;
|
|
29
|
+
requiresSession: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** One step of the flow to run, in a form an agent can drive from directly. */
|
|
32
|
+
export interface BriefStep {
|
|
33
|
+
n: number;
|
|
34
|
+
action: string;
|
|
35
|
+
role?: string;
|
|
36
|
+
name?: string;
|
|
37
|
+
/** How to find it when there's no role + name. */
|
|
38
|
+
testId?: string;
|
|
39
|
+
css?: string;
|
|
40
|
+
/** Which of several matching elements (0-based). */
|
|
41
|
+
nth?: number;
|
|
42
|
+
/** A literal value to type or select, or the address for a goto. */
|
|
43
|
+
value?: string;
|
|
44
|
+
/** A login value that was never stored — see `needs` for where it is. */
|
|
45
|
+
placeholder?: string;
|
|
46
|
+
}
|
|
47
|
+
/** A login value the flow needs: where it's set, and whether it is — never the value. */
|
|
48
|
+
export interface Need {
|
|
49
|
+
placeholder: string;
|
|
50
|
+
/** Environment variables Understudy reads it from, in order. */
|
|
51
|
+
readFrom: string[];
|
|
52
|
+
set: boolean;
|
|
53
|
+
}
|
|
54
|
+
export interface NoteMatch {
|
|
55
|
+
kind: Note['kind'];
|
|
56
|
+
text: string;
|
|
57
|
+
score: number;
|
|
58
|
+
}
|
|
59
|
+
export type Verdict = 'known' | 'unsure' | 'unknown';
|
|
60
|
+
export interface Recall {
|
|
61
|
+
goal: string;
|
|
62
|
+
method: 'exact' | 'meaning' | 'words';
|
|
63
|
+
verdict: Verdict;
|
|
64
|
+
/** The flow to run, when the verdict is 'known'. */
|
|
65
|
+
best?: FlowMatch;
|
|
66
|
+
/** When known: the best flow's steps, so an agent can drive it itself. */
|
|
67
|
+
steps?: BriefStep[];
|
|
68
|
+
/** When known: the login values those steps need. */
|
|
69
|
+
needs?: Need[];
|
|
70
|
+
/** Why the verdict, in one line a person can read. */
|
|
71
|
+
why: string;
|
|
72
|
+
flows: FlowMatch[];
|
|
73
|
+
notes: NoteMatch[];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* When a match by MEANING is good enough to act on. Calibrated 2026-11-18 on
|
|
77
|
+
* a real 28-flow corpus with voyage-4-lite (15 known goals, 14 plausible
|
|
78
|
+
* unknown ones): no single score separates them, because a
|
|
79
|
+
* goal the app doesn't have still lands near something. What does separate
|
|
80
|
+
* them is how far the top match is ahead of the runner-up. A different
|
|
81
|
+
* embedding model needs recalibrating.
|
|
82
|
+
*/
|
|
83
|
+
export declare const MEANING: {
|
|
84
|
+
/** At or above this, the top flow is the answer. */
|
|
85
|
+
strong: number;
|
|
86
|
+
/** At or above this, the top flow is the answer IF it clearly beats the runner-up… */
|
|
87
|
+
good: number;
|
|
88
|
+
/** …by at least this much. */
|
|
89
|
+
margin: number;
|
|
90
|
+
};
|
|
91
|
+
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
92
|
+
export declare const WORDS: {
|
|
93
|
+
strong: number;
|
|
94
|
+
good: number;
|
|
95
|
+
margin: number;
|
|
96
|
+
};
|
|
97
|
+
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
98
|
+
export declare function judge(scores: number[], rule: {
|
|
99
|
+
strong: number;
|
|
100
|
+
good: number;
|
|
101
|
+
margin: number;
|
|
102
|
+
}): {
|
|
103
|
+
verdict: Verdict;
|
|
104
|
+
why: string;
|
|
105
|
+
};
|
|
106
|
+
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
107
|
+
export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title' | 'intent'>): number;
|
|
108
|
+
/** Highest score first; on a tie, a proven flow ahead of an unproven one. */
|
|
109
|
+
export declare function rank(matches: FlowMatch[]): FlowMatch[];
|
|
110
|
+
/**
|
|
111
|
+
* `withSteps`: when the verdict is known, also return the best flow's steps and
|
|
112
|
+
* the login values it needs — what an agent driving the flow itself wants. Off
|
|
113
|
+
* for the planner, which only needs to know which flow.
|
|
114
|
+
*/
|
|
115
|
+
export declare function recall(app: string, goal: string, opts?: {
|
|
116
|
+
limit?: number;
|
|
117
|
+
withSteps?: boolean;
|
|
118
|
+
}): Promise<Recall>;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* recall: what does memory know about a goal?
|
|
3
|
+
*
|
|
4
|
+
* A database query — no browser, no model call beyond embedding the goal — so
|
|
5
|
+
* it is cheap enough to run before every action. It returns the closest flows
|
|
6
|
+
* and notes, and a verdict:
|
|
7
|
+
*
|
|
8
|
+
* known one flow clearly does this — safe to run it
|
|
9
|
+
* unsure something is close, but not clearly the answer — show, don't run
|
|
10
|
+
* unknown nothing does this — record it rather than guess
|
|
11
|
+
*
|
|
12
|
+
* Two ways to match, depending on whether an embedding model is configured:
|
|
13
|
+
* meaning embed the goal and search by vector (any wording works)
|
|
14
|
+
* words no model: match the goal's words against flow names
|
|
15
|
+
* Either way, a goal that IS a flow's name or slug matches exactly.
|
|
16
|
+
*/
|
|
17
|
+
import { collections, vectorSearch } from '../store/db.js';
|
|
18
|
+
import { embed, embedderConfig } from '../store/embed.js';
|
|
19
|
+
import { valuesFromEnv, valueEnvNames } from '../store/settings.js';
|
|
20
|
+
/**
|
|
21
|
+
* When a match by MEANING is good enough to act on. Calibrated 2026-11-18 on
|
|
22
|
+
* a real 28-flow corpus with voyage-4-lite (15 known goals, 14 plausible
|
|
23
|
+
* unknown ones): no single score separates them, because a
|
|
24
|
+
* goal the app doesn't have still lands near something. What does separate
|
|
25
|
+
* them is how far the top match is ahead of the runner-up. A different
|
|
26
|
+
* embedding model needs recalibrating.
|
|
27
|
+
*/
|
|
28
|
+
export const MEANING = {
|
|
29
|
+
/** At or above this, the top flow is the answer. */
|
|
30
|
+
strong: 0.78,
|
|
31
|
+
/** At or above this, the top flow is the answer IF it clearly beats the runner-up… */
|
|
32
|
+
good: 0.7,
|
|
33
|
+
/** …by at least this much. */
|
|
34
|
+
margin: 0.08,
|
|
35
|
+
};
|
|
36
|
+
/** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
|
|
37
|
+
export const WORDS = { strong: 1, good: 0.6, margin: 0.2 };
|
|
38
|
+
/** Pure: the verdict for a ranked list of scores. Exported for tests. */
|
|
39
|
+
export function judge(scores, rule) {
|
|
40
|
+
const [top, second] = scores;
|
|
41
|
+
if (top === undefined)
|
|
42
|
+
return { verdict: 'unknown', why: 'this app has no flows yet' };
|
|
43
|
+
const f = (n) => n.toFixed(2);
|
|
44
|
+
if (top >= rule.strong)
|
|
45
|
+
return { verdict: 'known', why: `strong match (${f(top)})` };
|
|
46
|
+
if (top >= rule.good) {
|
|
47
|
+
// With only one flow there's no runner-up to beat, so only a strong match counts.
|
|
48
|
+
if (second === undefined)
|
|
49
|
+
return { verdict: 'unsure', why: `good match (${f(top)}), but only one flow to compare with` };
|
|
50
|
+
if (top - second >= rule.margin)
|
|
51
|
+
return { verdict: 'known', why: `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
|
|
52
|
+
return { verdict: 'unsure', why: `good match (${f(top)}), but the next is close (${f(second)})` };
|
|
53
|
+
}
|
|
54
|
+
return { verdict: 'unknown', why: `nothing matches well (best ${f(top)})` };
|
|
55
|
+
}
|
|
56
|
+
const STOP = new Set(['a', 'an', 'the', 'to', 'my', 'of', 'for', 'and', 'in', 'on', 'as', 'i', 'me', 'it', 'is', 'with', 'at', 'up', 'out']);
|
|
57
|
+
const words = (s) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w)));
|
|
58
|
+
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
59
|
+
export function wordScore(goal, flow) {
|
|
60
|
+
const g = words(goal);
|
|
61
|
+
if (!g.size)
|
|
62
|
+
return 0;
|
|
63
|
+
const f = words(`${flow.title} ${flow.slug} ${flow.intent}`);
|
|
64
|
+
let hit = 0;
|
|
65
|
+
for (const w of g)
|
|
66
|
+
if (f.has(w))
|
|
67
|
+
hit++;
|
|
68
|
+
return hit / g.size;
|
|
69
|
+
}
|
|
70
|
+
const toMatch = (f, score) => ({
|
|
71
|
+
slug: f.slug, title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
|
|
72
|
+
...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}), score,
|
|
73
|
+
destructive: f.destructive, requiresSession: f.requiresSession,
|
|
74
|
+
});
|
|
75
|
+
/** Scores this close are a tie. */
|
|
76
|
+
const TIE = 0.005;
|
|
77
|
+
/** Highest score first; on a tie, a proven flow ahead of an unproven one. */
|
|
78
|
+
export function rank(matches) {
|
|
79
|
+
return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || b.score - a.score : b.score - a.score));
|
|
80
|
+
}
|
|
81
|
+
/** The verdict's reason, plus a warning when the flow it picked may not work. */
|
|
82
|
+
const withProven = (why, best) => best && !best.proven ? `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it` : why;
|
|
83
|
+
/** The best flow's steps and the login values they need, for an agent driving it itself. */
|
|
84
|
+
async function plan(app, slug) {
|
|
85
|
+
const { flows } = await collections();
|
|
86
|
+
const flow = await flows.findOne({ app, slug }, { projection: { steps: 1 } });
|
|
87
|
+
if (!flow)
|
|
88
|
+
return {};
|
|
89
|
+
const steps = flow.steps.map((s, n) => {
|
|
90
|
+
const nth = typeof s.hints?.nth === 'number' ? s.hints.nth : undefined;
|
|
91
|
+
const addressed = Boolean(s.role && s.name);
|
|
92
|
+
return {
|
|
93
|
+
n, action: s.action,
|
|
94
|
+
...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
|
|
95
|
+
...(!addressed && s.testId ? { testId: s.testId } : {}),
|
|
96
|
+
...(!addressed && !s.testId && s.css ? { css: s.css } : {}),
|
|
97
|
+
...(nth !== undefined ? { nth } : {}),
|
|
98
|
+
...(s.valueRef ? { placeholder: s.valueRef } : s.value !== undefined ? { value: s.value } : s.action === 'goto' ? { value: s.url } : {}),
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
const refs = [...new Set(flow.steps.map((s) => s.valueRef).filter((r) => Boolean(r)))];
|
|
102
|
+
const found = valuesFromEnv(refs, app);
|
|
103
|
+
const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
|
|
104
|
+
return { steps, ...(needs.length ? { needs } : {}) };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `withSteps`: when the verdict is known, also return the best flow's steps and
|
|
108
|
+
* the login values it needs — what an agent driving the flow itself wants. Off
|
|
109
|
+
* for the planner, which only needs to know which flow.
|
|
110
|
+
*/
|
|
111
|
+
export async function recall(app, goal, opts = {}) {
|
|
112
|
+
const limit = opts.limit ?? 5;
|
|
113
|
+
const c = await collections();
|
|
114
|
+
const needle = goal.trim().toLowerCase();
|
|
115
|
+
// 1. The goal names a flow exactly: no search needed, and no doubt.
|
|
116
|
+
const exact = await c.flows.findOne({ app, $or: [{ slug: needle }, { title: { $regex: `^${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' } }] }, { projection: { embedding: 0, steps: 0 } });
|
|
117
|
+
if (exact) {
|
|
118
|
+
const best = toMatch(exact, 1);
|
|
119
|
+
return { goal, method: 'exact', verdict: 'known', best, why: withProven('named exactly', best), flows: [best], notes: [], ...(opts.withSteps ? await plan(app, best.slug) : {}) };
|
|
120
|
+
}
|
|
121
|
+
// 2. By meaning, if there's a model.
|
|
122
|
+
if (embedderConfig()) {
|
|
123
|
+
const [vector] = await embed([goal], 'query');
|
|
124
|
+
const [flows, notes] = await Promise.all([
|
|
125
|
+
vectorSearch(c.flows, app, vector, { limit }),
|
|
126
|
+
vectorSearch(c.notes, app, vector, { limit }),
|
|
127
|
+
]);
|
|
128
|
+
const matches = rank(flows.map((f) => toMatch(f, f.score)));
|
|
129
|
+
const { verdict, why } = judge(matches.map((m) => m.score), MEANING);
|
|
130
|
+
return {
|
|
131
|
+
goal, method: 'meaning', verdict, why: verdict === 'known' ? withProven(why, matches[0]) : why, flows: matches,
|
|
132
|
+
...(verdict === 'known' ? { best: matches[0], ...(opts.withSteps ? await plan(app, matches[0].slug) : {}) } : {}),
|
|
133
|
+
notes: notes.map((n) => ({ kind: n.kind, text: n.text, score: n.score })),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
// 3. By words, with no model. Corpora are small, so scoring every flow is fine.
|
|
137
|
+
const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, destructive: 1, requiresSession: 1 } }).toArray();
|
|
138
|
+
const matches = all
|
|
139
|
+
.map((f) => toMatch(f, wordScore(goal, f)))
|
|
140
|
+
.filter((m) => m.score > 0);
|
|
141
|
+
const ranked = rank(matches).slice(0, limit);
|
|
142
|
+
const { verdict, why } = judge(ranked.map((m) => m.score), WORDS);
|
|
143
|
+
return {
|
|
144
|
+
goal, method: 'words', verdict, why: verdict === 'known' ? withProven(why, ranked[0]) : why, flows: ranked, notes: [],
|
|
145
|
+
...(verdict === 'known' ? { best: ranked[0], ...(opts.withSteps ? await plan(app, ranked[0].slug) : {}) } : {}),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app's vocabulary: every flow and fact, in the words the app's memory
|
|
3
|
+
* already uses. Handed to an agent when it splits a goal into sub-goals or
|
|
4
|
+
* splits a recording into segments, so it reuses those words instead of
|
|
5
|
+
* inventing synonyms — a sub-goal is a search, and it only finds what is
|
|
6
|
+
* phrased like something stored.
|
|
7
|
+
*/
|
|
8
|
+
import type { Vocabulary } from '../core/distill.js';
|
|
9
|
+
export declare function vocabulary(app: string): Promise<Vocabulary>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app's vocabulary: every flow and fact, in the words the app's memory
|
|
3
|
+
* already uses. Handed to an agent when it splits a goal into sub-goals or
|
|
4
|
+
* splits a recording into segments, so it reuses those words instead of
|
|
5
|
+
* inventing synonyms — a sub-goal is a search, and it only finds what is
|
|
6
|
+
* phrased like something stored.
|
|
7
|
+
*/
|
|
8
|
+
import { collections } from '../store/db.js';
|
|
9
|
+
export async function vocabulary(app) {
|
|
10
|
+
const { flows, notes } = await collections();
|
|
11
|
+
const rows = await flows
|
|
12
|
+
.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, preconditions: 1, outcome: 1, steps: 1 } })
|
|
13
|
+
.sort({ kind: -1, slug: 1 })
|
|
14
|
+
.toArray();
|
|
15
|
+
const facts = await notes.find({ app, kind: 'fact' }, { projection: { text: 1 } }).toArray();
|
|
16
|
+
return {
|
|
17
|
+
segments: rows.filter((f) => f.kind === 'segment').map((f) => ({
|
|
18
|
+
slug: f.slug, title: f.title, intent: f.intent, steps: f.steps.length,
|
|
19
|
+
preconditions: f.preconditions, outcome: f.outcome || null,
|
|
20
|
+
})),
|
|
21
|
+
flows: rows.filter((f) => f.kind === 'recording').map((f) => ({ slug: f.slug, title: f.title, intent: f.intent })),
|
|
22
|
+
facts: facts.map((n) => n.text),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Planning a goal that may need several flows, pausing to ask an agent when
|
|
3
|
+
* it can't decide alone.
|
|
4
|
+
*
|
|
5
|
+
* start(goal) ─▶ decompose? ─▶ bind each sub-goal ─▶ safety ─▶ seams ─▶ planned
|
|
6
|
+
* (ask) (recall) (ask if stuck)
|
|
7
|
+
*
|
|
8
|
+
* Every question is asked BEFORE a browser opens. Once a plan is complete it
|
|
9
|
+
* runs to the end without pausing; anything odd on the way becomes a finding.
|
|
10
|
+
* So a paused run holds nothing open: its progress lives on its run document,
|
|
11
|
+
* and `answer()` picks it up from there.
|
|
12
|
+
*
|
|
13
|
+
* Questions:
|
|
14
|
+
* decompose { subGoals: ["log in as a member", "open the cart"] }
|
|
15
|
+
* seam { steps: [{ action: "click", role: "link", name: "Cart" }] } — or [] if unknown
|
|
16
|
+
*/
|
|
17
|
+
import type { Run, Step } from '../store/types.js';
|
|
18
|
+
import type { RawRecording } from '../core/recording.js';
|
|
19
|
+
export interface PlanRequest {
|
|
20
|
+
app: string;
|
|
21
|
+
goal: string;
|
|
22
|
+
/** Supply the split yourself and skip the decompose question. */
|
|
23
|
+
subGoals?: string[];
|
|
24
|
+
dryRun?: boolean;
|
|
25
|
+
allowPurchases?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export type PlanState = {
|
|
28
|
+
status: 'waiting';
|
|
29
|
+
runId: string;
|
|
30
|
+
question: Record<string, unknown>;
|
|
31
|
+
} | {
|
|
32
|
+
status: 'blocked';
|
|
33
|
+
runId: string;
|
|
34
|
+
why: string;
|
|
35
|
+
detail?: unknown;
|
|
36
|
+
} | {
|
|
37
|
+
status: 'planned';
|
|
38
|
+
runId: string;
|
|
39
|
+
plan: string[];
|
|
40
|
+
seams: {
|
|
41
|
+
before: string;
|
|
42
|
+
how: string;
|
|
43
|
+
}[];
|
|
44
|
+
dryRun: boolean;
|
|
45
|
+
};
|
|
46
|
+
export declare function start(req: PlanRequest): Promise<PlanState>;
|
|
47
|
+
/** Answer the run's open question, and carry on planning. */
|
|
48
|
+
export declare function answer(runId: string, reply: unknown): Promise<PlanState>;
|
|
49
|
+
/** One recording for the whole plan: each flow's steps, joined by its seam. */
|
|
50
|
+
export declare function recordingForPlan(runId: string): Promise<{
|
|
51
|
+
run: Run;
|
|
52
|
+
recording: RawRecording;
|
|
53
|
+
steps: Step[];
|
|
54
|
+
starts: number[];
|
|
55
|
+
unproven: boolean;
|
|
56
|
+
}>;
|
|
57
|
+
/**
|
|
58
|
+
* Run a planned run: one recording for the whole plan, with lessons, and the
|
|
59
|
+
* outcome written onto the same run document.
|
|
60
|
+
*/
|
|
61
|
+
export declare function runPlan(runId: string, opts?: {
|
|
62
|
+
values?: Record<string, string>;
|
|
63
|
+
headed?: boolean;
|
|
64
|
+
}): Promise<{
|
|
65
|
+
executed: import("../flows/execute.js").Executed;
|
|
66
|
+
recorded: import("../flows/runs.js").RecordedRun;
|
|
67
|
+
plan: string[];
|
|
68
|
+
nowProven: string[];
|
|
69
|
+
}>;
|