@jeffawe/understudy 0.2.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -19
- package/REASONER.md +31 -4
- package/dist/adapters/recorder/script.js +206 -4
- package/dist/core/distill.d.ts +12 -0
- package/dist/core/distill.js +25 -32
- package/dist/core/recording.d.ts +49 -1
- package/dist/core/recording.js +60 -0
- package/dist/core/replay.d.ts +70 -1
- package/dist/core/replay.js +251 -12
- package/dist/entry/cli.js +187 -11
- package/dist/entry/mcp.d.ts +2 -1
- package/dist/entry/mcp.js +187 -33
- package/dist/flows/destructive.d.ts +17 -1
- package/dist/flows/destructive.js +23 -5
- package/dist/flows/distill.js +2 -0
- package/dist/flows/emit.js +88 -5
- package/dist/flows/execute.d.ts +22 -2
- package/dist/flows/execute.js +19 -3
- package/dist/flows/findings.d.ts +4 -1
- package/dist/flows/findings.js +15 -3
- package/dist/flows/runs.d.ts +13 -0
- package/dist/flows/runs.js +43 -7
- package/dist/flows/save.d.ts +42 -1
- package/dist/flows/save.js +214 -14
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +258 -0
- package/dist/memory/recall.d.ts +42 -25
- package/dist/memory/recall.js +61 -21
- package/dist/memory/vocabulary.js +9 -3
- package/dist/plan/planner.d.ts +8 -4
- package/dist/plan/planner.js +77 -4
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +78 -2
- package/package.json +1 -1
package/dist/entry/mcp.js
CHANGED
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
* understudy_remember store facts, lessons, findings, goals reached by other means
|
|
13
13
|
* understudy_findings list open findings; triage them
|
|
14
14
|
* understudy_record wait for the user to record a flow in their Chrome
|
|
15
|
-
* understudy_save prove a recording by replaying it, then keep it as a flow
|
|
15
|
+
* understudy_save prove a recording by replaying it, then keep it as a flow (or prove a saved one)
|
|
16
16
|
* understudy_app an app's settings — e.g. keep email fields as placeholders
|
|
17
|
+
* understudy_calibrate fit when recall calls a goal known, for one app and embedding model
|
|
17
18
|
*
|
|
18
19
|
* Long-lived: reconnect (/mcp) after changing the source.
|
|
19
20
|
*/
|
|
@@ -25,26 +26,23 @@ import { remember } from '../memory/notes.js';
|
|
|
25
26
|
import { start, answer, runPlan } from '../plan/planner.js';
|
|
26
27
|
import { distillRequest, saveDistilled } from '../flows/distill.js';
|
|
27
28
|
import { triage, listFindings } from '../flows/findings.js';
|
|
29
|
+
import { acceptPaths } from '../flows/runs.js';
|
|
28
30
|
import { collections } from '../store/db.js';
|
|
29
31
|
import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
|
|
30
32
|
import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
|
|
31
|
-
import { proveAndSave } from '../flows/save.js';
|
|
33
|
+
import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
|
|
32
34
|
import { MissingValuesError } from '../flows/execute.js';
|
|
33
35
|
import { parseScript } from '../adapters/recorder/script.js';
|
|
34
36
|
import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
|
|
37
|
+
import { calibrate } from '../memory/calibrate.js';
|
|
35
38
|
import { VERSION } from './version.js';
|
|
36
39
|
/**
|
|
37
|
-
* Sent to the agent when it connects
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
+
* Sent to the agent when it connects. EVERY session pays for this, used or not,
|
|
41
|
+
* so it says only what Understudy is and where to start. Everything else lives
|
|
42
|
+
* on the tool it is about: a client that loads tools on demand pays for those
|
|
43
|
+
* words only when the tool is used.
|
|
40
44
|
*/
|
|
41
|
-
const INSTRUCTIONS = `Understudy
|
|
42
|
-
- Recall first: free, runs nothing. A known flow comes with its steps and the login values it needs. Run it with understudy_run, or drive it yourself — say which.
|
|
43
|
-
- Runs ask before a browser opens. decompose: subGoals in the order the app does them, in the words of its flows. seam: one click or goto, or [] unless you know — answers are reused forever. Start with dryRun.
|
|
44
|
-
- Never ask for a password in chat. Values come from the user's settings (UNDERSTUDY_<NAME>), or pass ones you fetched yourself.
|
|
45
|
-
- No flow for it? understudy_record (the user records) then understudy_save — or save a Playwright script of what you drove (understudy_save with script). Save what's worth testing again.
|
|
46
|
-
- Ask the user before each distill. Gather facts, lessons and findings, get approval, then one understudy_remember.
|
|
47
|
-
Full guide: REASONER.md in the package.`;
|
|
45
|
+
const INSTRUCTIONS = `Understudy runs end-to-end tests of the user's web apps from flows it remembers; it calls no model. Start with understudy_recall.`;
|
|
48
46
|
const server = new McpServer({ name: 'understudy', version: VERSION }, { instructions: INSTRUCTIONS });
|
|
49
47
|
/** Credentials passed to `run`, kept in memory (never stored) until the run executes. */
|
|
50
48
|
const valuesByRun = new Map();
|
|
@@ -74,27 +72,103 @@ const missingValues = (e, retry) => ({
|
|
|
74
72
|
});
|
|
75
73
|
/** Drop undefined fields: the zod types allow them, the functions here don't. */
|
|
76
74
|
const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
75
|
+
class LiveRun {
|
|
76
|
+
queue = [];
|
|
77
|
+
waiter;
|
|
78
|
+
/** The question waiting for an answer, if any. */
|
|
79
|
+
pending;
|
|
80
|
+
push(e) {
|
|
81
|
+
const w = this.waiter;
|
|
82
|
+
if (w) {
|
|
83
|
+
this.waiter = undefined;
|
|
84
|
+
w(e);
|
|
85
|
+
}
|
|
86
|
+
else
|
|
87
|
+
this.queue.push(e);
|
|
88
|
+
}
|
|
89
|
+
/** The page showed the step done: nobody needs to answer that question now. */
|
|
90
|
+
withdraw(seq) {
|
|
91
|
+
this.queue = this.queue.filter((e) => !(e.kind === 'question' && e.seq === seq));
|
|
92
|
+
if (this.pending?.seq === seq)
|
|
93
|
+
this.pending = undefined;
|
|
94
|
+
}
|
|
95
|
+
next() {
|
|
96
|
+
const e = this.queue.shift();
|
|
97
|
+
return e ? Promise.resolve(e) : new Promise((r) => { this.waiter = r; });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const liveRuns = new Map();
|
|
101
|
+
const HUMAN_HOW = 'A step only a person can do. Tell the user exactly what to do, then answer {"done": true} when they say it is done, or {"abort": "why"}.';
|
|
102
|
+
const STUCK_HOW = 'This step failed, and the run\'s browser is open on screen. Ask the user to do just this step by hand in that window, then answer {"done": true} — or {"abort": "why"}. Then suggest re-recording, so it works next time.';
|
|
103
|
+
function personSaid(reply) {
|
|
104
|
+
const r = reply;
|
|
105
|
+
if (r?.done === true)
|
|
106
|
+
return { done: true };
|
|
107
|
+
if (typeof r?.abort === 'string' && r.abort.trim())
|
|
108
|
+
return { abort: r.abort.trim() };
|
|
109
|
+
throw new Error('answer {"done": true} once they have done it, or {"abort": "why"}');
|
|
110
|
+
}
|
|
111
|
+
/** Wait for the live run's next question, or its result. */
|
|
112
|
+
async function nextFrom(runId) {
|
|
113
|
+
const run = liveRuns.get(runId);
|
|
114
|
+
const e = await run.next();
|
|
115
|
+
if (e.kind === 'question')
|
|
116
|
+
return { status: 'waiting', runId, question: e.question };
|
|
117
|
+
liveRuns.delete(runId);
|
|
118
|
+
valuesByRun.delete(runId);
|
|
119
|
+
if (e.kind === 'error')
|
|
120
|
+
throw e.error;
|
|
121
|
+
return e.result;
|
|
122
|
+
}
|
|
77
123
|
/** After planning: run it now, unless it was a dry run or is waiting/blocked. */
|
|
78
124
|
async function continueRun(state, opts) {
|
|
79
125
|
if (state.status !== 'planned' || state.dryRun)
|
|
80
126
|
return state;
|
|
81
|
-
const
|
|
82
|
-
const
|
|
83
|
-
|
|
127
|
+
const runId = state.runId;
|
|
128
|
+
const live = new LiveRun();
|
|
129
|
+
liveRuns.set(runId, live);
|
|
130
|
+
const ask = (seq, question) => new Promise((resolve) => {
|
|
131
|
+
live.pending = { seq, resolve };
|
|
132
|
+
live.push({ kind: 'question', seq, question });
|
|
133
|
+
});
|
|
134
|
+
runPlan(runId, {
|
|
135
|
+
values: valuesByRun.get(runId) ?? {}, ...opts,
|
|
136
|
+
onHuman: async (req, signal) => {
|
|
137
|
+
signal.addEventListener('abort', () => live.withdraw(req.seq));
|
|
138
|
+
const said = await ask(req.seq, {
|
|
139
|
+
kind: 'human', step: req.seq, ask: req.instruction, page: req.url,
|
|
140
|
+
...(req.until ? { doneWhen: req.until, carriesOnWhen: 'the page shows doneWhen — it checks that after your answer too' } : {}),
|
|
141
|
+
how: HUMAN_HOW,
|
|
142
|
+
});
|
|
143
|
+
return 'done' in said ? { action: 'done' } : { action: 'abort', reason: said.abort };
|
|
144
|
+
},
|
|
145
|
+
onStuck: async (stuck) => {
|
|
146
|
+
const said = await ask(stuck.seq, { kind: 'handoff', step: stuck.seq, failed: { action: stuck.action, target: stuck.target, error: stuck.error }, page: stuck.url, how: STUCK_HOW });
|
|
147
|
+
return 'done' in said ? 'done' : 'abort';
|
|
148
|
+
},
|
|
149
|
+
}).then((out) => live.push({ kind: 'done', result: report(state, out) }), (error) => live.push({ kind: 'error', error }));
|
|
150
|
+
return nextFrom(runId);
|
|
151
|
+
}
|
|
152
|
+
/** What a finished run tells the agent. */
|
|
153
|
+
function report(state, out) {
|
|
154
|
+
const { executed, recorded, plan, nowProven } = out;
|
|
84
155
|
const r = executed.result;
|
|
156
|
+
const byPerson = r.steps.filter((s) => s.viaHuman || s.viaHandoff);
|
|
85
157
|
return {
|
|
86
158
|
status: r.ok ? 'passed' : 'failed',
|
|
87
159
|
runId: state.runId,
|
|
88
160
|
plan,
|
|
89
161
|
seams: state.seams,
|
|
90
162
|
failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
|
|
163
|
+
...(byPerson.length ? { doneByAPerson: byPerson.map((s) => ({ seq: s.seq, how: s.viaHuman ? `human step, ${s.viaHuman === 'page' ? 'the page showed it done' : 'they said it was done'}` : 'a failed step they did by hand' })) } : {}),
|
|
91
164
|
unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
|
|
92
165
|
path: r.sigSequence,
|
|
93
166
|
drift: recorded.drift.notCompared ? `not compared: ${recorded.drift.notCompared}`
|
|
94
167
|
: recorded.drift.firstRun ? 'first passed run of this plan — now the baseline' : recorded.drift.changed
|
|
95
168
|
? { added: recorded.drift.added, removed: recorded.drift.removed, stateChanged: recorded.drift.stateChanged }
|
|
96
169
|
: 'same path',
|
|
97
|
-
findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement })),
|
|
170
|
+
findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement, fingerprint: f.fingerprint })),
|
|
171
|
+
...(recorded.pending ? { pathNotAccepted: 'it passed on a changed path, so it isn\'t history yet: ask the user if the change is right, then understudy_findings triage its flow_drift finding as expected (or issue)' } : {}),
|
|
98
172
|
...(executed.lessons?.fired ? { lessons: executed.lessons } : {}),
|
|
99
173
|
...(nowProven.length ? { nowProven } : {}),
|
|
100
174
|
...(executed.missingValues.length ? { missingValues: executed.missingValues } : {}),
|
|
@@ -102,13 +176,13 @@ async function continueRun(state, opts) {
|
|
|
102
176
|
};
|
|
103
177
|
}
|
|
104
178
|
const values = z.record(z.string(), z.string()).optional()
|
|
105
|
-
.describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from settings. Never stored.');
|
|
179
|
+
.describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from the user\'s settings. Never stored. Never ask the user to paste one into chat.');
|
|
106
180
|
server.registerTool('understudy_recall', {
|
|
107
|
-
description: '
|
|
181
|
+
description: 'Call first: what memory knows about a goal — closest flows, notes, a verdict. Free; nothing runs. A known flow comes with its steps and needed login values: run it with understudy_run or drive it yourself, and tell the user which. Unknown: the user records it (understudy_record), or you drive it and save the script (understudy_save).',
|
|
108
182
|
inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional() },
|
|
109
183
|
}, ({ app, goal, limit }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}) })));
|
|
110
184
|
server.registerTool('understudy_run', {
|
|
111
|
-
description: 'Plan a goal and run it headless. Returns a question
|
|
185
|
+
description: 'Plan a goal and run it headless (visible when a step needs a person). Start with dryRun. Returns a question for understudy_answer, "blocked" with why, or the result.',
|
|
112
186
|
inputSchema: {
|
|
113
187
|
app: z.string(), goal: z.string(),
|
|
114
188
|
subGoals: z.array(z.string()).optional().describe('Skip the decompose question.'),
|
|
@@ -128,9 +202,18 @@ server.registerTool('understudy_run', {
|
|
|
128
202
|
return continueRun(state, a.headed ? { headed: true } : {});
|
|
129
203
|
}));
|
|
130
204
|
server.registerTool('understudy_answer', {
|
|
131
|
-
description: 'Answer a waiting run\'s question
|
|
205
|
+
description: 'Answer a waiting run\'s question, as its "how" says. Returns the next question, or the result.',
|
|
132
206
|
inputSchema: { runId: z.string(), answer: z.record(z.string(), z.unknown()), values, headed: z.boolean().optional() },
|
|
133
207
|
}, (a) => wrap(async () => {
|
|
208
|
+
// A run waiting on a person, browser open: answer it where it is.
|
|
209
|
+
const live = liveRuns.get(a.runId);
|
|
210
|
+
if (live) {
|
|
211
|
+
const said = personSaid(a.answer);
|
|
212
|
+
const waiting = live.pending;
|
|
213
|
+
live.pending = undefined;
|
|
214
|
+
waiting?.resolve(said); // none: the page showed it done, and it carried on
|
|
215
|
+
return nextFrom(a.runId);
|
|
216
|
+
}
|
|
134
217
|
if (a.values)
|
|
135
218
|
valuesByRun.set(a.runId, a.values);
|
|
136
219
|
return continueRun(await answer(a.runId, a.answer), a.headed ? { headed: true } : {});
|
|
@@ -144,7 +227,7 @@ server.registerTool('understudy_save_distilled', {
|
|
|
144
227
|
inputSchema: { app: z.string(), flow: z.string(), distilled: z.record(z.string(), z.unknown()) },
|
|
145
228
|
}, ({ app, flow, distilled }) => wrap(() => saveDistilled(app, flow, distilled)));
|
|
146
229
|
server.registerTool('understudy_remember', {
|
|
147
|
-
description: 'Store what you learned, as one approved
|
|
230
|
+
description: 'Store what you learned, as one batch the user has approved: facts (change plans), lessons (change one step; trigger never empty), findings (the app is broken), and goals you reached without understudy_run.',
|
|
148
231
|
inputSchema: {
|
|
149
232
|
app: z.string(),
|
|
150
233
|
facts: z.array(z.object({ text: z.string(), marksDestructive: z.string().optional() })).optional(),
|
|
@@ -159,18 +242,20 @@ server.registerTool('understudy_remember', {
|
|
|
159
242
|
reached: reached?.map((r) => defined(r)),
|
|
160
243
|
}))));
|
|
161
244
|
server.registerTool('understudy_findings', {
|
|
162
|
-
description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson or
|
|
245
|
+
description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson, noise — or, for a changed path (flow_drift), expected: the app changed on purpose and the new path becomes the normal one. Ask the user before expected.',
|
|
163
246
|
inputSchema: {
|
|
164
247
|
app: z.string(),
|
|
165
|
-
triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise']) })).optional(),
|
|
248
|
+
triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise', 'expected']) })).optional(),
|
|
166
249
|
all: z.boolean().optional().describe('Include already-triaged findings.'),
|
|
167
250
|
},
|
|
168
251
|
}, ({ app, triage: items, all }) => wrap(async () => {
|
|
169
252
|
const { findings } = await collections();
|
|
170
253
|
const routed = items?.length ? await triage(findings, app, items) : undefined;
|
|
254
|
+
const accepted = routed?.expected.length ? await acceptPaths(app, routed.expected) : undefined;
|
|
171
255
|
const rows = await listFindings(findings, app, { ...(all ? { all } : {}), limit: 40 });
|
|
172
256
|
return {
|
|
173
|
-
...(routed ? { triaged: routed } : {}),
|
|
257
|
+
...(routed ? { triaged: { routed: routed.routed, problems: routed.problems } } : {}),
|
|
258
|
+
...(accepted ? { acceptedPath: accepted } : {}),
|
|
174
259
|
findings: rows.map((f) => ({ fingerprint: f.fingerprint, kind: f.kind, severity: f.severity, occurrences: f.occurrences, status: f.status, statement: f.statement })),
|
|
175
260
|
};
|
|
176
261
|
}));
|
|
@@ -206,21 +291,34 @@ server.registerTool('understudy_record', {
|
|
|
206
291
|
}));
|
|
207
292
|
server.registerTool('understudy_save', {
|
|
208
293
|
description: [
|
|
209
|
-
'
|
|
210
|
-
'A script is
|
|
211
|
-
'
|
|
212
|
-
'
|
|
213
|
-
'
|
|
294
|
+
'Keep a flow, proven by replaying it: the user\'s latest recording, a recording hash, or a Playwright script of a flow you drove.',
|
|
295
|
+
'A script is read, not run — literal page calls only: no loops, no values computed at runtime (a code from an email is a human step).',
|
|
296
|
+
'Understood: goto, click, dblclick, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; getBy* locators, locator(css), frameLocator, filter({hasText}), first/last/nth;',
|
|
297
|
+
'inline expect(page | locator) checks of URL, title, visible, hidden, text, value, checked; page.waitForURL, waitForSelector, waitForResponse.',
|
|
298
|
+
'Other checks come back in droppedAssertions; calls that change the steps (evaluate, hover, route…) refuse the save.',
|
|
299
|
+
'Where only a person can act: human(\'what they do\', { untilText | untilUrl | untilResponse }).',
|
|
214
300
|
].join(' '),
|
|
215
301
|
inputSchema: {
|
|
216
|
-
app: z.string(), name: z.string().describe('What the flow does, as someone would ask for it.'),
|
|
302
|
+
app: z.string(), name: z.string().optional().describe('What the flow does, as someone would ask for it. Needed unless flow is given.'),
|
|
303
|
+
flow: z.string().optional().describe('A saved flow to prove where it stands (e.g. one kept with verify false), instead of saving a new one.'),
|
|
304
|
+
add: z.array(z.object({ before: z.number().int(), step: z.record(z.string(), z.unknown()) })).optional()
|
|
305
|
+
.describe('With flow: steps to add first, each before step n. {"action":"human","value":"what they do","hints":{"untilText":"…"}}, {"action":"wait_response","value":"/api/visits","hints":{"method":"POST","status":201,"field":"commission.amount","above":0}}, {"action":"assert","role":"checkbox","name":"…","hints":{"assert":"checked"}}; also wait_url, wait_text.'),
|
|
217
306
|
hash: z.string().optional(),
|
|
218
307
|
script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
|
|
219
308
|
intent: z.string().optional(), slug: z.string().optional(), values,
|
|
220
|
-
verify: z.boolean().optional().describe('
|
|
309
|
+
verify: z.boolean().optional().describe('A flow that commits something real (a purchase, a submission) is replayed only up to that step, which is checked and never pressed. false: keep it without replaying at all; saved as unproven until a run passes.'),
|
|
221
310
|
note: z.string().optional().describe('With verify false: why, e.g. what you checked yourself.'),
|
|
222
311
|
},
|
|
223
312
|
}, (a) => wrap(async () => {
|
|
313
|
+
if (a.flow) {
|
|
314
|
+
const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add) : undefined;
|
|
315
|
+
if (edited && a.verify === false)
|
|
316
|
+
return { flow: edited.slug, steps: edited.steps.length, unproven: edited.unprovenBecause };
|
|
317
|
+
return { ...(edited ? { added: a.add.length } : {}), ...(await proveSaved(a.app, a.flow, a)) };
|
|
318
|
+
}
|
|
319
|
+
if (!a.name)
|
|
320
|
+
throw new Error('name is required — what the flow does, as someone would ask for it (or pass flow to prove a saved one)');
|
|
321
|
+
const name = a.name;
|
|
224
322
|
let rec;
|
|
225
323
|
let madeBy = 'user';
|
|
226
324
|
let dropped = [];
|
|
@@ -250,7 +348,7 @@ server.registerTool('understudy_save', {
|
|
|
250
348
|
let out;
|
|
251
349
|
try {
|
|
252
350
|
out = await proveAndSave(rec, {
|
|
253
|
-
title:
|
|
351
|
+
title: name, madeBy,
|
|
254
352
|
...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
|
|
255
353
|
...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
|
|
256
354
|
});
|
|
@@ -258,7 +356,7 @@ server.registerTool('understudy_save', {
|
|
|
258
356
|
catch (e) {
|
|
259
357
|
// The recording is kept; saving it again by hash needs nothing re-recorded.
|
|
260
358
|
if (e instanceof MissingValuesError)
|
|
261
|
-
return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name
|
|
359
|
+
return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name }) };
|
|
262
360
|
throw e;
|
|
263
361
|
}
|
|
264
362
|
const r = out.proven?.result;
|
|
@@ -283,10 +381,54 @@ server.registerTool('understudy_save', {
|
|
|
283
381
|
proveIt: `when it should pass: understudy_run with subGoals ["${out.flow.slug}"] — a passing run proves it`,
|
|
284
382
|
} : {}),
|
|
285
383
|
...(out.flow.destructive ? { destructive: out.flow.destructiveBecause } : {}),
|
|
384
|
+
...provenUpTo(out.flow),
|
|
385
|
+
...endChecks(out.flow, r?.endChecks),
|
|
286
386
|
...(out.run ? { findings: out.run.findings.map((f) => f.statement) } : {}),
|
|
287
387
|
...(out.placeholders.converted.length ? { placeholders: out.placeholders.converted } : {}),
|
|
288
388
|
};
|
|
289
389
|
}));
|
|
390
|
+
/** understudy_save with `flow`: prove a saved flow — up to its commit, if it has one. Records the run. */
|
|
391
|
+
async function proveSaved(app, slug, a) {
|
|
392
|
+
const out = await proveFlow(app, slug, a.values ? { values: a.values } : {});
|
|
393
|
+
const r = out.result;
|
|
394
|
+
return {
|
|
395
|
+
flow: out.flow.slug, passed: r.ok, newlyProven: out.newlyProven,
|
|
396
|
+
proven: out.flow.proven !== false,
|
|
397
|
+
...(out.flow.proven === false ? { unproven: out.flow.unprovenBecause } : {}),
|
|
398
|
+
...provenUpTo(out.flow),
|
|
399
|
+
...(out.commit && !r.ok ? { wouldStopBefore: `step ${out.commit.index}: ${out.commit.reason}` } : {}),
|
|
400
|
+
failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
|
|
401
|
+
findings: out.run.findings.map((f) => f.statement),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* How the flow ended, offered as checks to add — never added unasked. A
|
|
406
|
+
* person's own recording is the best word on how it should end; an agent's
|
|
407
|
+
* may have taken a path the user wouldn't, so the user says either way.
|
|
408
|
+
*/
|
|
409
|
+
function endChecks(flow, checks) {
|
|
410
|
+
if (!checks?.length)
|
|
411
|
+
return {};
|
|
412
|
+
return {
|
|
413
|
+
endChecks: {
|
|
414
|
+
suggest: checks.map((step) => ({ before: flow.steps.length, step })),
|
|
415
|
+
how: (flow.madeBy === 'agent'
|
|
416
|
+
? 'You drove this, so ask the user how it should end: '
|
|
417
|
+
: 'From the user\'s own recording — ask them: ')
|
|
418
|
+
+ 'which of these say it ended right? Add those with understudy_save { flow, add }. Without them the flow only checks that each step could be done.',
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
/** What "proven up to its commit" means, for a flow that is. */
|
|
423
|
+
function provenUpTo(flow) {
|
|
424
|
+
if (flow.provenUpTo === undefined)
|
|
425
|
+
return {};
|
|
426
|
+
const s = flow.steps[flow.provenUpTo];
|
|
427
|
+
return {
|
|
428
|
+
provenUpTo: flow.provenUpTo,
|
|
429
|
+
stoppedBefore: `step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit: the control was there and ready, and was not pressed — nothing after it has run`,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
290
432
|
server.registerTool('understudy_app', {
|
|
291
433
|
description: 'An app\'s settings. placeholders ["email"] keeps email addresses out of memory: they become placeholders, and the values move to the user\'s env file.',
|
|
292
434
|
inputSchema: {
|
|
@@ -298,4 +440,16 @@ server.registerTool('understudy_app', {
|
|
|
298
440
|
return setPlaceholders(app, placeholders);
|
|
299
441
|
return { app, placeholders: await appPlaceholders(app) };
|
|
300
442
|
}));
|
|
443
|
+
server.registerTool('understudy_calibrate', {
|
|
444
|
+
description: 'Fit when recall calls a goal "known", for this app and embedding model — needed after switching models, or when recall calls the wrong things known (its `cutoffs.source` says "uncalibrated"). Give 2–3 rewordings per flow (not its own title) and 5+ goals that sound like the app but that it has no flow for; they are kept, so later calls and `understudy reembed` re-fit from them. Tell the user the before/after and any mistakes.',
|
|
445
|
+
inputSchema: {
|
|
446
|
+
app: z.string(),
|
|
447
|
+
known: z.array(z.object({ flow: z.string().describe('the flow\'s slug'), goals: z.array(z.string()) })).optional(),
|
|
448
|
+
unknown: z.array(z.string()).optional(),
|
|
449
|
+
dryRun: z.boolean().optional().describe('fit and report, keep nothing'),
|
|
450
|
+
},
|
|
451
|
+
}, ({ app, known, unknown, dryRun }) => wrap(() => calibrate(app, {
|
|
452
|
+
goals: { known: (known ?? []).flatMap((k) => k.goals.map((goal) => ({ flow: k.flow, goal }))), unknown: unknown ?? [] },
|
|
453
|
+
...(dryRun ? { dryRun } : {}),
|
|
454
|
+
})));
|
|
301
455
|
await server.connect(new StdioServerTransport());
|
|
@@ -15,5 +15,21 @@
|
|
|
15
15
|
import type { Step } from '../store/types.js';
|
|
16
16
|
/** Why this step is destructive, or null if nothing says it is. */
|
|
17
17
|
export declare function destructiveReason(step: Pick<Step, 'action' | 'name' | 'url'>): string | null;
|
|
18
|
-
/**
|
|
18
|
+
/** A step that commits something real, and why. */
|
|
19
|
+
export interface CommitStep {
|
|
20
|
+
index: number;
|
|
21
|
+
reason: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* EVERY step that commits something, in order — not just the first.
|
|
25
|
+
*
|
|
26
|
+
* A booking flow often has two: "Confirm & Submit" creates the visit, "Pay
|
|
27
|
+
* Now" charges for it. Naming only the first hid the payment, and proving a
|
|
28
|
+
* flow up to its commit needs the first one exactly (flows/save.ts).
|
|
29
|
+
*
|
|
30
|
+
* `controls` are names a fact says commit something (notes.destructiveControls),
|
|
31
|
+
* matched the same way the run's safety gate matches them.
|
|
32
|
+
*/
|
|
33
|
+
export declare function commitSteps(steps: Pick<Step, 'action' | 'name' | 'url'>[], controls?: ReadonlyMap<string, string>): CommitStep[];
|
|
34
|
+
/** Why the flow is destructive — every step that makes it so — or null. */
|
|
19
35
|
export declare function flowDestructiveReason(steps: Pick<Step, 'action' | 'name' | 'url'>[]): string | null;
|
|
@@ -37,12 +37,30 @@ export function destructiveReason(step) {
|
|
|
37
37
|
}
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
/**
|
|
41
|
+
* EVERY step that commits something, in order — not just the first.
|
|
42
|
+
*
|
|
43
|
+
* A booking flow often has two: "Confirm & Submit" creates the visit, "Pay
|
|
44
|
+
* Now" charges for it. Naming only the first hid the payment, and proving a
|
|
45
|
+
* flow up to its commit needs the first one exactly (flows/save.ts).
|
|
46
|
+
*
|
|
47
|
+
* `controls` are names a fact says commit something (notes.destructiveControls),
|
|
48
|
+
* matched the same way the run's safety gate matches them.
|
|
49
|
+
*/
|
|
50
|
+
export function commitSteps(steps, controls = new Map()) {
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const [index, s] of steps.entries()) {
|
|
43
53
|
const why = destructiveReason(s);
|
|
54
|
+
const fact = s.name && COMMITTING_ACTIONS.has(s.action) ? controls.get(s.name.toLowerCase()) : undefined;
|
|
44
55
|
if (why)
|
|
45
|
-
|
|
56
|
+
out.push({ index, reason: why });
|
|
57
|
+
else if (fact)
|
|
58
|
+
out.push({ index, reason: `"${s.name}" — a fact says it commits something: ${fact}` });
|
|
46
59
|
}
|
|
47
|
-
return
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
/** Why the flow is destructive — every step that makes it so — or null. */
|
|
63
|
+
export function flowDestructiveReason(steps) {
|
|
64
|
+
const found = commitSteps(steps);
|
|
65
|
+
return found.length ? found.map((c) => `step ${c.index}: ${c.reason}`).join('; ') : null;
|
|
48
66
|
}
|
package/dist/flows/distill.js
CHANGED
|
@@ -55,6 +55,7 @@ export async function saveDistilled(app, slug, answer) {
|
|
|
55
55
|
await c.flows.updateOne({ app, slug }, {
|
|
56
56
|
$set: {
|
|
57
57
|
intent: d.intent, outcome: d.outcome, preconditions: d.preconditions,
|
|
58
|
+
requires: d.requires ?? [], establishes: d.establishes ?? [],
|
|
58
59
|
corrections: (d.corrections ?? []).map((x) => `${x.rule}: ${x.detail}${x.stepIndex !== undefined ? ` (step ${x.stepIndex})` : ''}`),
|
|
59
60
|
searchText: parentText, ...(vectors[0] ? { embedding: vectors[0] } : {}), updatedAt: now,
|
|
60
61
|
},
|
|
@@ -95,6 +96,7 @@ function segmentFrom(parent, s) {
|
|
|
95
96
|
madeBy: parent.madeBy ?? 'user',
|
|
96
97
|
from: { flow: parent.slug, steps: [start, end] },
|
|
97
98
|
preconditions: (s.preconditions ?? []),
|
|
99
|
+
requires: s.requires ?? [], establishes: s.establishes ?? [],
|
|
98
100
|
outcome: s.outcome ?? '',
|
|
99
101
|
destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}),
|
|
100
102
|
corrections: [], recording: parent.recording,
|
package/dist/flows/emit.js
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
*
|
|
12
12
|
* Ported from the old emit.ts; it now reads the flow document directly.
|
|
13
13
|
*/
|
|
14
|
+
import { forced, humanUntil, responseCheckOf, valueRefsOf } from '../core/recording.js';
|
|
15
|
+
import { urlGlob } from '../core/replay.js';
|
|
14
16
|
import { valueEnvName } from '../store/settings.js';
|
|
15
17
|
const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
|
|
16
18
|
/** SECRET.password → UNDERSTUDY_SECRET_PASSWORD: the same variable replay reads, so one setting serves both. */
|
|
@@ -77,6 +79,30 @@ function assertion(s, loc, value, pw, warn) {
|
|
|
77
79
|
warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
|
|
78
80
|
return `// TODO: assert ${kind}`;
|
|
79
81
|
}
|
|
82
|
+
/** `r => r.url().includes('/api/visits') && r.request().method() === 'POST' && r.status() === 201` */
|
|
83
|
+
function responsePredicate(c) {
|
|
84
|
+
const url = c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
|
|
85
|
+
return `(r) => ${[url, c.method && `r.request().method() === ${quote(c.method)}`, c.status !== undefined && `r.status() === ${c.status}`].filter(Boolean).join(' && ')}`;
|
|
86
|
+
}
|
|
87
|
+
/** `body.items[0].id` as optional chaining, so a missing field fails the expect, not the line. */
|
|
88
|
+
const fieldPath = (root, path) => root + path.split('.').map((k) => (/^\d+$/.test(k) ? `?.[${k}]` : `?.${k}`)).join('');
|
|
89
|
+
function playwrightResponseCheck(c, name) {
|
|
90
|
+
if (!c.field)
|
|
91
|
+
return [`await ${name};`];
|
|
92
|
+
const v = fieldPath(`(await (await ${name}).json())`, c.field);
|
|
93
|
+
return [`expect(${v})${c.equals !== undefined ? `.toBe(${JSON.stringify(c.equals)})` : c.above !== undefined ? `.toBeGreaterThan(${c.above})` : '.toBeDefined()'};`];
|
|
94
|
+
}
|
|
95
|
+
function cypressIntercept(c, name) {
|
|
96
|
+
const url = c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
|
|
97
|
+
return `cy.intercept({ ${c.method ? `method: ${quote(c.method)}, ` : ''}url: ${url} }).as(${quote(name)});`;
|
|
98
|
+
}
|
|
99
|
+
function cypressResponseCheck(c, name) {
|
|
100
|
+
const checks = [
|
|
101
|
+
c.status !== undefined && `expect(response?.statusCode).to.eq(${c.status});`,
|
|
102
|
+
c.field && `expect(${fieldPath('response?.body', c.field)})${c.equals !== undefined ? `.to.eq(${JSON.stringify(c.equals)})` : c.above !== undefined ? '.to.be.greaterThan(' + c.above + ')' : '.to.exist'};`,
|
|
103
|
+
].filter(Boolean);
|
|
104
|
+
return checks.length ? [`cy.wait(${quote('@' + name)}).then(({ response }) => { ${checks.join(' ')} });`] : [`cy.wait(${quote('@' + name)});`];
|
|
105
|
+
}
|
|
80
106
|
/** Best locator first — the same order replay tries, so the code fails where replay would. */
|
|
81
107
|
function playwrightLocator(s, warn) {
|
|
82
108
|
const scope = s.frameHint ? `page.frameLocator(${quote(`[id$="${s.frameHint}"]`)})` : 'page';
|
|
@@ -119,12 +145,18 @@ export function emitFlow(flow, framework = 'playwright-ts') {
|
|
|
119
145
|
if (flow.requiresSession)
|
|
120
146
|
warnings.push('this flow starts signed in; the generated test starts signed out — add a login first');
|
|
121
147
|
const lines = [];
|
|
122
|
-
|
|
148
|
+
/** Where the last action's code starts: a response wait is set up just before it. */
|
|
149
|
+
let lastActionAt = -1;
|
|
150
|
+
for (const [i, s] of flow.steps.entries()) {
|
|
123
151
|
if (s.action === 'snapshot')
|
|
124
152
|
continue;
|
|
125
|
-
const
|
|
153
|
+
const startsAt = lines.length;
|
|
154
|
+
const pageLevel = ['goto', 'wait_url', 'wait_text', 'wait_response', 'human'].includes(s.action) || (s.action === 'assert' && s.hints?.assert === 'title');
|
|
126
155
|
const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
|
|
127
|
-
const
|
|
156
|
+
const ref = valueRefsOf([s])[0];
|
|
157
|
+
const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
|
|
158
|
+
// Both frameworks spell it the same way.
|
|
159
|
+
const force = forced(s) ? '{ force: true }' : '';
|
|
128
160
|
switch (s.action) {
|
|
129
161
|
case 'goto':
|
|
130
162
|
lines.push(pw ? `await page.goto(${value});` : `cy.visit(${value});`);
|
|
@@ -136,7 +168,10 @@ export function emitFlow(flow, framework = 'playwright-ts') {
|
|
|
136
168
|
lines.push(pw ? `await ${loc}.selectOption(${value});` : `${loc}.select(${value});`);
|
|
137
169
|
break;
|
|
138
170
|
case 'check':
|
|
139
|
-
lines.push(pw ? `await ${loc}.check();` : `${loc}.check();`);
|
|
171
|
+
lines.push(pw ? `await ${loc}.check(${force});` : `${loc}.check(${force});`);
|
|
172
|
+
break;
|
|
173
|
+
case 'uncheck':
|
|
174
|
+
lines.push(pw ? `await ${loc}.uncheck(${force});` : `${loc}.uncheck(${force});`);
|
|
140
175
|
break;
|
|
141
176
|
case 'press':
|
|
142
177
|
lines.push(pw ? `await ${loc}.press(${value});` : `${loc}.type(${value});`);
|
|
@@ -161,11 +196,59 @@ export function emitFlow(flow, framework = 'playwright-ts') {
|
|
|
161
196
|
case 'assert':
|
|
162
197
|
lines.push(assertion(s, loc, value, pw, warn));
|
|
163
198
|
break;
|
|
199
|
+
case 'human': {
|
|
200
|
+
// A person's step: say what, then wait for its sign — or pause.
|
|
201
|
+
lines.push(`// A PERSON DOES THIS: ${(s.value ?? '').replace(/\n/g, ' ')}`);
|
|
202
|
+
const t = typeof s.hints?.untilText === 'string' ? s.hints.untilText : undefined;
|
|
203
|
+
const u = typeof s.hints?.untilUrl === 'string' ? s.hints.untilUrl : undefined;
|
|
204
|
+
const r = humanUntil(s)?.response;
|
|
205
|
+
if (r) {
|
|
206
|
+
// The person acts after this line, so waiting here misses nothing.
|
|
207
|
+
if (pw)
|
|
208
|
+
lines.push(`const response${i} = page.waitForResponse(${responsePredicate(r)}, { timeout: 15 * 60_000 });`, ...playwrightResponseCheck(r, `response${i}`));
|
|
209
|
+
else
|
|
210
|
+
lines.push(cypressIntercept(r, `response${i}`), ...cypressResponseCheck(r, `response${i}`).map((l) => l.replace(/\)\.then/, ', { timeout: 15 * 60_000 }).then')));
|
|
211
|
+
}
|
|
212
|
+
if (pw) {
|
|
213
|
+
if (u)
|
|
214
|
+
lines.push(`await page.waitForURL(${u.includes('*') ? quote(u) : `(u) => u.href.includes(${quote(u)})`}, { timeout: 15 * 60_000 });`);
|
|
215
|
+
if (t)
|
|
216
|
+
lines.push(`await page.getByText(${quote(t)}).first().waitFor({ timeout: 15 * 60_000 });`);
|
|
217
|
+
if (!u && !t && !r)
|
|
218
|
+
lines.push('await page.pause();');
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
if (u)
|
|
222
|
+
lines.push(`cy.url({ timeout: 15 * 60_000 }).should('include', ${quote(u)});`);
|
|
223
|
+
if (t)
|
|
224
|
+
lines.push(`cy.contains(${quote(t)}, { timeout: 15 * 60_000 });`);
|
|
225
|
+
if (!u && !t && !r)
|
|
226
|
+
lines.push('cy.pause();');
|
|
227
|
+
}
|
|
228
|
+
warn(`step "${s.value ?? 'human'}" needs a person — run this test headed, with someone there`);
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
164
231
|
case 'wait_text':
|
|
165
232
|
lines.push(pw ? `await page.getByText(${value}).waitFor();` : `cy.contains(${value});`);
|
|
166
233
|
break;
|
|
167
|
-
|
|
234
|
+
case 'wait_response': {
|
|
235
|
+
const check = responseCheckOf(s.value, s.hints);
|
|
236
|
+
if (!check)
|
|
237
|
+
break;
|
|
238
|
+
// Set up BEFORE the action that triggers it, or a fast answer is missed.
|
|
239
|
+
const name = `response${i}`;
|
|
240
|
+
const setup = pw ? `const ${name} = page.waitForResponse(${responsePredicate(check)});` : cypressIntercept(check, name);
|
|
241
|
+
const at = lastActionAt >= 0 ? lastActionAt : lines.length;
|
|
242
|
+
lines.splice(at, 0, setup);
|
|
243
|
+
if (lastActionAt >= 0)
|
|
244
|
+
lastActionAt++;
|
|
245
|
+
lines.push(...(pw ? playwrightResponseCheck(check, name) : cypressResponseCheck(check, name)));
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
default: lines.push(pw ? `await ${loc}.click(${force});` : `${loc}.click(${force});`);
|
|
168
249
|
}
|
|
250
|
+
if (!['wait_url', 'wait_text', 'wait_response', 'assert', 'human'].includes(s.action))
|
|
251
|
+
lastActionAt = startsAt;
|
|
169
252
|
}
|
|
170
253
|
const refs = [...required];
|
|
171
254
|
// Values come from the environment, never the file.
|
package/dist/flows/execute.d.ts
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* the MCP server. Throws with a readable message instead of printing, so each
|
|
10
10
|
* caller decides how to show it.
|
|
11
11
|
*/
|
|
12
|
-
import type
|
|
13
|
-
import { type ReplayResult } from '../core/replay.js';
|
|
12
|
+
import { type RawRecording } from '../core/recording.js';
|
|
13
|
+
import { type ReplayOptions, type ReplayResult } from '../core/replay.js';
|
|
14
14
|
/** A login value a recording needs, and where it may be set. */
|
|
15
15
|
export interface MissingValue {
|
|
16
16
|
placeholder: string;
|
|
@@ -38,6 +38,26 @@ export interface ExecuteOptions {
|
|
|
38
38
|
* what gets saved is what the recording does on its own.
|
|
39
39
|
*/
|
|
40
40
|
useLessons?: boolean;
|
|
41
|
+
/** Stop before this step: look at its control, don't use it (see replay's `stopBefore`). */
|
|
42
|
+
stopBefore?: number;
|
|
43
|
+
/** Someone to ask at a `human` step. Without it, a flow with one fails there. */
|
|
44
|
+
onHuman?: ReplayOptions['onHuman'];
|
|
45
|
+
/**
|
|
46
|
+
* Someone to ask when a step fails: do it by hand in the open browser, then
|
|
47
|
+
* say so. Only offered when the browser is visible — nobody can do a step in
|
|
48
|
+
* a window they can't see.
|
|
49
|
+
*/
|
|
50
|
+
onStuck?: (stuck: StuckStep) => Promise<'done' | 'abort'>;
|
|
51
|
+
/** Read the last page into `result.endChecks`, after a full pass. */
|
|
52
|
+
endChecks?: boolean;
|
|
53
|
+
}
|
|
54
|
+
/** A step that failed, put to a person who can see the browser. */
|
|
55
|
+
export interface StuckStep {
|
|
56
|
+
seq: number;
|
|
57
|
+
action: string;
|
|
58
|
+
target?: string;
|
|
59
|
+
error: string;
|
|
60
|
+
url: string;
|
|
41
61
|
}
|
|
42
62
|
export interface Executed {
|
|
43
63
|
result: ReplayResult;
|