@jeffawe/understudy 0.4.0 → 0.5.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/CHANGELOG.md +127 -0
- package/README.md +69 -172
- package/REASONER.md +76 -86
- package/dist/adapters/recorder/script.d.ts +25 -2
- package/dist/adapters/recorder/script.js +126 -31
- package/dist/core/outline.d.ts +43 -0
- package/dist/core/outline.js +121 -0
- package/dist/core/recording.d.ts +19 -1
- package/dist/core/recording.js +38 -2
- package/dist/core/replay.d.ts +62 -1
- package/dist/core/replay.js +162 -106
- package/dist/entry/cli.js +110 -29
- package/dist/entry/mcp.d.ts +1 -0
- package/dist/entry/mcp.js +114 -23
- package/dist/flows/destructive.js +1 -1
- package/dist/flows/distill.js +11 -6
- package/dist/flows/emit.d.ts +7 -0
- package/dist/flows/emit.js +26 -10
- package/dist/flows/execute.d.ts +12 -0
- package/dist/flows/execute.js +23 -16
- package/dist/flows/runs.d.ts +2 -0
- package/dist/flows/runs.js +7 -3
- package/dist/flows/save.d.ts +5 -2
- package/dist/flows/save.js +38 -23
- package/dist/flows/session.d.ts +176 -0
- package/dist/flows/session.js +383 -0
- package/dist/flows/variants.d.ts +81 -0
- package/dist/flows/variants.js +139 -0
- package/dist/memory/calibrate.js +3 -1
- package/dist/memory/pages.d.ts +34 -0
- package/dist/memory/pages.js +60 -0
- package/dist/memory/recall.d.ts +56 -2
- package/dist/memory/recall.js +194 -30
- package/dist/plan/planner.d.ts +11 -1
- package/dist/plan/planner.js +36 -19
- package/dist/store/app-settings.d.ts +26 -0
- package/dist/store/app-settings.js +49 -0
- package/dist/store/db.js +8 -1
- package/dist/store/types.d.ts +18 -0
- package/package.json +3 -2
package/dist/entry/cli.js
CHANGED
|
@@ -11,22 +11,25 @@ import { parseScript } from '../adapters/recorder/script.js';
|
|
|
11
11
|
import { startExtensionRecorder, DEFAULT_PORT, extensionDir, firefoxExtensionDir } from '../adapters/recorder/extension.js';
|
|
12
12
|
import { listRecordings, loadRecording, saveRecording } from '../core/recording-store.js';
|
|
13
13
|
import { loadSession, saveSession } from '../core/auth-cache.js';
|
|
14
|
-
import { buildRecording } from '../core/recording.js';
|
|
14
|
+
import { buildRecording, rebase } from '../core/recording.js';
|
|
15
|
+
import { checkVariant, dropVariant, promoteVariant, resolveFlow, runsOf, variantDiff } from '../flows/variants.js';
|
|
15
16
|
import { execute, prove, MissingValuesError } from '../flows/execute.js';
|
|
16
17
|
import { destructiveControls, remember } from '../memory/notes.js';
|
|
18
|
+
import { commitSteps } from '../flows/destructive.js';
|
|
17
19
|
import { start, answer, runPlan } from '../plan/planner.js';
|
|
18
20
|
import { distillRequest, saveDistilled } from '../flows/distill.js';
|
|
19
21
|
import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
|
|
20
22
|
import { join, resolve as resolvePath } from 'node:path';
|
|
21
23
|
import { existsSync } from 'node:fs';
|
|
22
24
|
import { chromium } from 'playwright';
|
|
23
|
-
import { emitFlow } from '../flows/emit.js';
|
|
25
|
+
import { emitFlow, envName as emitEnvName } from '../flows/emit.js';
|
|
24
26
|
import { editFlow, recordingFrom, proveAndSave, proveByRun, proveFlow } from '../flows/save.js';
|
|
25
27
|
import { acceptPaths, recordRun } from '../flows/runs.js';
|
|
26
28
|
import { listFindings, triage } from '../flows/findings.js';
|
|
27
29
|
import { VERSION } from './version.js';
|
|
28
|
-
import { recall } from '../memory/recall.js';
|
|
30
|
+
import { recall, stepLine } from '../memory/recall.js';
|
|
29
31
|
import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
|
|
32
|
+
import { setAppTimeout, timeoutFor } from '../store/app-settings.js';
|
|
30
33
|
import * as store from '../store/db.js';
|
|
31
34
|
import { valueEnvName, readConfig, writeConfig, loadedFrom, HOME, expandHome, writeEnvValues } from '../store/settings.js';
|
|
32
35
|
// Piped into `head` and the pipe closed early: stop quietly, like other CLIs.
|
|
@@ -49,7 +52,7 @@ COMMANDS
|
|
|
49
52
|
calibrate <app> fit when recall calls a goal known, for this app and model
|
|
50
53
|
record <app> capture a flow in your own Chrome, with the extension
|
|
51
54
|
extension where the Chrome extension is, and how to load it
|
|
52
|
-
app <app> an app's settings, e.g. --placeholder email
|
|
55
|
+
app <app> an app's settings, e.g. --placeholder email, --timeout 20000
|
|
53
56
|
import <app> <file> read an existing Playwright script into a recording
|
|
54
57
|
recordings [app] list captured recordings
|
|
55
58
|
save <hash> "<name>" prove a recording by replaying it, then save it as a flow
|
|
@@ -68,6 +71,10 @@ COMMANDS
|
|
|
68
71
|
distill <app> <flow> print a saved flow's steps for an agent to name and split
|
|
69
72
|
remember <app> <file> store facts, lessons and findings from a JSON batch
|
|
70
73
|
emit <app> <flow> print a saved flow as a Playwright or Cypress test
|
|
74
|
+
promote <app> <flow> --variant <name>
|
|
75
|
+
make a variant the main flow, once its branch has merged
|
|
76
|
+
drop <app> <flow> --variant <name>
|
|
77
|
+
delete a variant's copy; that variant uses the main flow again
|
|
71
78
|
|
|
72
79
|
MCP server for agents: understudy-mcp (see REASONER.md).
|
|
73
80
|
|
|
@@ -92,6 +99,10 @@ REPLAY and SAVE
|
|
|
92
99
|
e.g. --value SECRET.password=hunter2 (repeatable)
|
|
93
100
|
--headed watch it replay
|
|
94
101
|
--allow-purchases replay a flow marked destructive (refused by default)
|
|
102
|
+
--until-commit run a destructive flow up to its commit step: checked, never pressed
|
|
103
|
+
--variant <name> a branch or deploy: use (or save) its copy of each flow, never
|
|
104
|
+
the main one — also for run, recall, prove, edit and emit
|
|
105
|
+
--base-url <url> run against the app at this address, e.g. a preview deploy
|
|
95
106
|
|
|
96
107
|
SAVE
|
|
97
108
|
--slug <name> the flow's short name (default: made from the name)
|
|
@@ -488,13 +499,22 @@ async function cmdRecordExtension(slug, flags) {
|
|
|
488
499
|
* understudy app <app> the app's settings
|
|
489
500
|
* understudy app <app> --placeholder email keep its email fields as placeholders
|
|
490
501
|
* understudy app <app> --no-placeholders stop doing that for new flows
|
|
502
|
+
* understudy app <app> --timeout <ms|default> how long a step may wait
|
|
491
503
|
*/
|
|
492
504
|
async function cmdApp(positional, flags) {
|
|
493
505
|
const app = positional[0] ?? fail('app needs an app name', 'understudy app myapp --placeholder email');
|
|
506
|
+
const timeout = str(flags.get('timeout'));
|
|
507
|
+
if (timeout !== undefined) {
|
|
508
|
+
const out = await setAppTimeout(app, timeout === 'default' ? null : Number(timeout)).catch((e) => fail(e.message));
|
|
509
|
+
console.log(`${app}: a step may wait ${out.timeoutMs ? `${out.timeoutMs} ms` : 'the default (UNDERSTUDY_TIMEOUT_MS, else 10000 ms)'}`);
|
|
510
|
+
}
|
|
494
511
|
const kinds = all(flags, 'placeholder');
|
|
495
512
|
if (!kinds.length && !flags.has('no-placeholders')) {
|
|
513
|
+
if (timeout !== undefined)
|
|
514
|
+
return;
|
|
496
515
|
const current = await appPlaceholders(app);
|
|
497
516
|
console.log(`${app}: placeholders ${current.length ? current.join(', ') : 'passwords only (the default)'}`);
|
|
517
|
+
console.log(`${app}: a step may wait ${(await timeoutFor(app)) ?? 10000} ms`);
|
|
498
518
|
return;
|
|
499
519
|
}
|
|
500
520
|
const out = await setPlaceholders(app, flags.has('no-placeholders') ? [] : kinds).catch((e) => fail(e.message));
|
|
@@ -571,7 +591,10 @@ async function cmdImport(positional, flags) {
|
|
|
571
591
|
*/
|
|
572
592
|
async function executeWithReport(recording, flags, opts) {
|
|
573
593
|
const values = valuesFromFlags(flags);
|
|
574
|
-
const x = await withLoginValues(values, (v) => execute(recording, {
|
|
594
|
+
const x = await withLoginValues(values, (v) => execute(recording, {
|
|
595
|
+
values: v, headed: flags.has('headed'), useLessons: opts.useLessons, ...personAtTerminal(),
|
|
596
|
+
...(opts.stopBefore !== undefined ? { stopBefore: opts.stopBefore } : {}),
|
|
597
|
+
}))
|
|
575
598
|
.catch((e) => fail(e.message));
|
|
576
599
|
if (x.sessionRestoredFrom)
|
|
577
600
|
console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
|
|
@@ -603,14 +626,21 @@ async function cmdReplayFlow(app, slug, flags) {
|
|
|
603
626
|
* Shared by `replay <app> <flow>` and `run <app> "<goal>"`.
|
|
604
627
|
*/
|
|
605
628
|
async function runSavedFlow(app, slug, flags, how) {
|
|
606
|
-
const
|
|
607
|
-
const flow = await
|
|
629
|
+
const variant = variantFlag(flags);
|
|
630
|
+
const flow = await resolveFlow(app, slug, variant);
|
|
608
631
|
if (!flow)
|
|
609
632
|
fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
|
|
633
|
+
if (flow.variant)
|
|
634
|
+
console.log(`variant ${flow.variant}'s copy of '${slug}'`);
|
|
635
|
+
else if (variant)
|
|
636
|
+
console.log(`variant ${variant} has no copy of '${slug}' — running the main flow`);
|
|
637
|
+
// Up to the commit: the first step that commits something, counting facts.
|
|
638
|
+
const untilCommit = flags.has('until-commit') && !flags.has('allow-purchases');
|
|
639
|
+
const commit = untilCommit ? commitSteps(flow.steps, await destructiveControls(app))[0] : undefined;
|
|
610
640
|
// The safety gate: a destructive flow does something real every time it runs.
|
|
611
|
-
if (!flags.has('allow-purchases')) {
|
|
641
|
+
if (!flags.has('allow-purchases') && !untilCommit) {
|
|
612
642
|
if (flow.destructive) {
|
|
613
|
-
fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --allow-purchases if
|
|
643
|
+
fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --until-commit to run up to that step, or --allow-purchases if running it is genuinely fine');
|
|
614
644
|
}
|
|
615
645
|
const controls = await destructiveControls(app);
|
|
616
646
|
const hit = flow.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
|
|
@@ -620,12 +650,19 @@ async function runSavedFlow(app, slug, flags, how) {
|
|
|
620
650
|
console.log(`running ${app}/${slug} — ${flow.title}\n`);
|
|
621
651
|
if (flow.proven === false)
|
|
622
652
|
console.log(`note: '${slug}' is UNPROVEN (${flow.unprovenBecause}) — this run will tell.\n`);
|
|
623
|
-
const
|
|
653
|
+
const baseUrl = str(flags.get('base-url'));
|
|
654
|
+
const recording = baseUrl ? rebase(recordingFrom(flow), baseUrl) : recordingFrom(flow);
|
|
655
|
+
if (baseUrl)
|
|
656
|
+
console.log(`against ${new URL(recording.startUrl).origin} (saved on ${new URL(flow.startUrl).origin})\n`);
|
|
657
|
+
if (commit)
|
|
658
|
+
console.log(`stopping before step ${commit.index}: ${commit.reason}\n`);
|
|
659
|
+
const result = await executeWithReport(recording, flags, { useLessons: true, ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}) });
|
|
624
660
|
printReplay(result);
|
|
625
661
|
const run = await recordRun({
|
|
626
662
|
app, flow: slug, result, steps: flow.steps, mode: how.mode, ...(how.goal ? { goal: how.goal } : {}), ...(flow.proven === false ? { unproven: true } : {}),
|
|
663
|
+
...(variant ? { variant } : {}),
|
|
627
664
|
});
|
|
628
|
-
if (await proveByRun(app, slug, result))
|
|
665
|
+
if (await proveByRun(app, slug, result, 0, variant))
|
|
629
666
|
console.log(`\nproven '${slug}' passed, so it's no longer marked unproven`);
|
|
630
667
|
printRunReport(run);
|
|
631
668
|
if (!result.ok)
|
|
@@ -638,7 +675,8 @@ function printRecall(r, showSteps = false) {
|
|
|
638
675
|
if (r.flows.length) {
|
|
639
676
|
console.log('flows');
|
|
640
677
|
for (const f of r.flows) {
|
|
641
|
-
const
|
|
678
|
+
const failedLast = f.lastFailed && (!f.lastPassed || f.lastFailed.at > f.lastPassed);
|
|
679
|
+
const marks = [f.variants?.length && `variants: ${f.variants.join(', ')}`, f.proven === false && 'UNPROVEN', failedLast && 'LAST RUN FAILED', f.pathNotAccepted && 'path not accepted', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment'].filter(Boolean).join(', ');
|
|
642
680
|
console.log(` ${f.score.toFixed(3)} ${f.slug.padEnd(32)} ${f.title}${marks ? ` [${marks}]` : ''}`);
|
|
643
681
|
}
|
|
644
682
|
}
|
|
@@ -650,13 +688,15 @@ function printRecall(r, showSteps = false) {
|
|
|
650
688
|
if (r.best && r.steps) {
|
|
651
689
|
console.log(`\n${r.best.slug}: ${r.steps.length} steps${showSteps ? '' : ' (--steps to list them)'}`);
|
|
652
690
|
if (showSteps) {
|
|
653
|
-
for (const s of r.steps)
|
|
654
|
-
|
|
655
|
-
const what = s.placeholder ? `= <${s.placeholder}>` : s.value !== undefined ? `= "${s.value}"` : '';
|
|
656
|
-
console.log(` ${String(s.n).padStart(3)} ${s.action.padEnd(7)} ${target}${s.nth !== undefined ? ` (#${s.nth})` : ''} ${what}`.trimEnd());
|
|
657
|
-
}
|
|
691
|
+
for (const s of r.steps)
|
|
692
|
+
console.log(` ${stepLine(s)}`);
|
|
658
693
|
}
|
|
659
694
|
}
|
|
695
|
+
if (r.differsFromMain?.length) {
|
|
696
|
+
console.log(`\n${r.best.slug} @${r.best.variant}, against the main flow:`);
|
|
697
|
+
for (const line of r.differsFromMain)
|
|
698
|
+
console.log(` ${line}`);
|
|
699
|
+
}
|
|
660
700
|
for (const need of r.needs ?? []) {
|
|
661
701
|
console.log(`needs ${need.placeholder} — from ${need.readFrom.join(' or ')}: ${need.set ? 'set' : 'NOT SET'}`);
|
|
662
702
|
}
|
|
@@ -666,7 +706,8 @@ async function cmdRecall(positional, flags) {
|
|
|
666
706
|
const [app, ...goalWords] = positional;
|
|
667
707
|
if (!app || !goalWords.length)
|
|
668
708
|
fail('recall needs an app and a goal', 'understudy recall myapp "log in"');
|
|
669
|
-
|
|
709
|
+
const variant = variantFlag(flags);
|
|
710
|
+
printRecall(await recall(app, goalWords.join(' '), { withSteps: true, limit: Number(str(flags.get('limit')) ?? 5), ...(variant ? { variant } : {}) }), flags.has('steps'));
|
|
670
711
|
}
|
|
671
712
|
/**
|
|
672
713
|
* Run a goal: find the flow that does it, check it's safe, run it. Only a
|
|
@@ -688,10 +729,13 @@ async function cmdRun(positional, flags) {
|
|
|
688
729
|
app, goal, subGoals,
|
|
689
730
|
...(flags.has('dry-run') ? { dryRun: true } : {}),
|
|
690
731
|
...(flags.has('allow-purchases') ? { allowPurchases: true } : {}),
|
|
732
|
+
...(flags.has('until-commit') ? { stopBeforeCommit: true } : {}),
|
|
733
|
+
...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}),
|
|
734
|
+
...(str(flags.get('base-url')) ? { baseUrl: str(flags.get('base-url')) } : {}),
|
|
691
735
|
});
|
|
692
736
|
return reportPlan(state, flags);
|
|
693
737
|
}
|
|
694
|
-
const r = await recall(app, goal);
|
|
738
|
+
const r = await recall(app, goal, variantFlag(flags) ? { variant: variantFlag(flags) } : {});
|
|
695
739
|
printRecall(r);
|
|
696
740
|
if (r.verdict !== 'known' || !r.best) {
|
|
697
741
|
console.log(r.verdict === 'unsure'
|
|
@@ -734,11 +778,13 @@ async function reportPlan(state, flags) {
|
|
|
734
778
|
}
|
|
735
779
|
console.log();
|
|
736
780
|
const values = valuesFromFlags(flags);
|
|
737
|
-
const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
|
|
781
|
+
const { executed, recorded, nowProven, commit } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
|
|
738
782
|
.catch((e) => fail(e.message));
|
|
739
783
|
if (executed.lessons?.fired)
|
|
740
784
|
console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
|
|
741
785
|
printReplay(executed.result);
|
|
786
|
+
if (commit && executed.result.stoppedBefore !== undefined)
|
|
787
|
+
console.log(`stopped before step ${commit.index} (${commit.reason}) — checked, not pressed`);
|
|
742
788
|
printRunReport(recorded);
|
|
743
789
|
for (const slug of nowProven)
|
|
744
790
|
console.log(`proven '${slug}' passed, so it's no longer marked unproven`);
|
|
@@ -860,8 +906,18 @@ async function cmdSave(positional, flags) {
|
|
|
860
906
|
values: valuesFromFlags(flags), headed: flags.has('headed'),
|
|
861
907
|
verify: !flags.has('no-verify'), force: flags.has('force'),
|
|
862
908
|
...(slug ? { slug } : {}), ...(intent ? { intent } : {}),
|
|
909
|
+
...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}),
|
|
863
910
|
});
|
|
864
911
|
}
|
|
912
|
+
/** --variant, checked. */
|
|
913
|
+
const variantFlag = (flags) => {
|
|
914
|
+
try {
|
|
915
|
+
return checkVariant(str(flags.get('variant')));
|
|
916
|
+
}
|
|
917
|
+
catch (e) {
|
|
918
|
+
return fail(e.message);
|
|
919
|
+
}
|
|
920
|
+
};
|
|
865
921
|
/** Ask a yes/no question in the terminal. No terminal (piped, scripted): the answer is no. */
|
|
866
922
|
async function askYesNo(question, byDefault = false) {
|
|
867
923
|
if (!process.stdin.isTTY)
|
|
@@ -1030,7 +1086,7 @@ async function saveAndReport(recording, title, opts) {
|
|
|
1030
1086
|
if (flow.proven === false)
|
|
1031
1087
|
console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
|
|
1032
1088
|
if (flow.destructive)
|
|
1033
|
-
console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
|
|
1089
|
+
console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --until-commit (up to it) or --allow-purchases.`);
|
|
1034
1090
|
const upTo = provenUpToNote(flow);
|
|
1035
1091
|
if (upTo)
|
|
1036
1092
|
console.log(` ${upTo}`);
|
|
@@ -1065,7 +1121,7 @@ async function cmdEdit(positional, flags) {
|
|
|
1065
1121
|
catch {
|
|
1066
1122
|
fail(`--step isn't JSON: ${raw}`);
|
|
1067
1123
|
}
|
|
1068
|
-
const flow = await editFlow(app, slug, [{ before, step: step }]).catch((e) => fail(e.message));
|
|
1124
|
+
const flow = await editFlow(app, slug, [{ before, step: step }], variantFlag(flags)).catch((e) => fail(e.message));
|
|
1069
1125
|
console.log(`added step ${before} to ${app}/${slug} (${flow.steps.length} steps now)`);
|
|
1070
1126
|
console.log(` UNPROVEN until a run passes — understudy prove ${app} ${slug}`);
|
|
1071
1127
|
}
|
|
@@ -1073,7 +1129,7 @@ async function cmdEdit(positional, flags) {
|
|
|
1073
1129
|
async function cmdProve(positional, flags) {
|
|
1074
1130
|
const app = positional[0] ?? fail('prove needs an app and a flow', 'understudy prove myapp book-a-visit');
|
|
1075
1131
|
const slug = positional[1] ?? fail('prove needs a flow', `understudy flows ${app}`);
|
|
1076
|
-
const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed') }))
|
|
1132
|
+
const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed'), ...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}) }))
|
|
1077
1133
|
.catch((e) => fail(e.message));
|
|
1078
1134
|
if (out.commit)
|
|
1079
1135
|
console.log(`stopping before step ${out.commit.index}: ${out.commit.reason}\n`);
|
|
@@ -1090,17 +1146,21 @@ async function cmdProve(positional, flags) {
|
|
|
1090
1146
|
async function cmdFlows(positional) {
|
|
1091
1147
|
const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
|
|
1092
1148
|
const { flows, runs } = await store.collections();
|
|
1093
|
-
const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1 }).toArray();
|
|
1149
|
+
const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1, variant: 1 }).toArray();
|
|
1094
1150
|
if (!rows.length) {
|
|
1095
1151
|
console.log(`no flows for '${app}' yet — record one, then \`understudy save <hash> "<name>"\``);
|
|
1096
1152
|
return;
|
|
1097
1153
|
}
|
|
1098
1154
|
for (const f of rows) {
|
|
1099
|
-
const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
|
|
1155
|
+
const last = await runs.find({ app, plan: [f.slug], ...runsOf(f.variant) }).sort({ startedAt: -1 }).limit(1).next();
|
|
1100
1156
|
const status = last ? `${last.status} ${last.startedAt.toISOString().slice(0, 16).replace('T', ' ')}` : 'never run';
|
|
1101
1157
|
const marks = [f.proven === false && 'UNPROVEN', f.provenUpTo !== undefined && `proven to step ${f.provenUpTo}`, f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
|
|
1102
1158
|
.filter(Boolean).join(', ');
|
|
1103
|
-
|
|
1159
|
+
const name = f.variant ? `${f.slug} @${f.variant}` : f.slug;
|
|
1160
|
+
console.log(` ${name.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
|
|
1161
|
+
if (f.variant)
|
|
1162
|
+
for (const line of (await variantDiff(app, f.slug, f.variant)).slice(0, 6))
|
|
1163
|
+
console.log(` ${line}`);
|
|
1104
1164
|
}
|
|
1105
1165
|
}
|
|
1106
1166
|
async function cmdFindings(positional, flags) {
|
|
@@ -1129,6 +1189,26 @@ async function cmdFindings(positional, flags) {
|
|
|
1129
1189
|
console.log(` ${f.fingerprint} ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
|
|
1130
1190
|
}
|
|
1131
1191
|
}
|
|
1192
|
+
/** promote <app> <flow> --variant <name> — the branch merged: its copy becomes the main flow. */
|
|
1193
|
+
async function cmdPromote(positional, flags) {
|
|
1194
|
+
const [app, slug] = positional;
|
|
1195
|
+
if (!app || !slug)
|
|
1196
|
+
fail('promote needs an app and a flow', 'understudy promote myapp book-a-visit --variant feature/new-intake');
|
|
1197
|
+
const variant = variantFlag(flags) ?? fail('promote needs --variant <name>: the copy to make the main flow');
|
|
1198
|
+
const out = await promoteVariant(app, slug, variant).catch((e) => fail(e.message));
|
|
1199
|
+
console.log(`promoted ${app}/${slug} @${variant} — it is the main flow now${out.replaced ? ', replacing the old one' : ''}`);
|
|
1200
|
+
if (out.staleSegments.length)
|
|
1201
|
+
console.log(` segments cut from the old flow still hold its old steps: ${out.staleSegments.join(', ')} — distill ${slug} again`);
|
|
1202
|
+
}
|
|
1203
|
+
/** drop <app> <flow> --variant <name> — delete a variant's copy of a flow. */
|
|
1204
|
+
async function cmdDrop(positional, flags) {
|
|
1205
|
+
const [app, slug] = positional;
|
|
1206
|
+
if (!app || !slug)
|
|
1207
|
+
fail('drop needs an app and a flow', 'understudy drop myapp book-a-visit --variant feature/new-intake');
|
|
1208
|
+
const variant = variantFlag(flags) ?? fail('drop needs --variant <name>: the copy to delete (the main flow is never dropped this way)');
|
|
1209
|
+
await dropVariant(app, slug, variant).catch((e) => fail(e.message));
|
|
1210
|
+
console.log(`dropped ${app}/${slug} @${variant} — runs with ${variant} use the main flow again`);
|
|
1211
|
+
}
|
|
1132
1212
|
/** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
|
|
1133
1213
|
async function cmdEmit(positional, flags) {
|
|
1134
1214
|
const [app, slug] = positional;
|
|
@@ -1137,8 +1217,7 @@ async function cmdEmit(positional, flags) {
|
|
|
1137
1217
|
const framework = (str(flags.get('framework')) ?? 'playwright-ts');
|
|
1138
1218
|
if (framework !== 'playwright-ts' && framework !== 'cypress-js')
|
|
1139
1219
|
fail('--framework must be playwright-ts or cypress-js');
|
|
1140
|
-
const
|
|
1141
|
-
const flow = await flows.findOne({ app, slug });
|
|
1220
|
+
const flow = await resolveFlow(app, slug, variantFlag(flags));
|
|
1142
1221
|
if (!flow)
|
|
1143
1222
|
fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
|
|
1144
1223
|
const out = emitFlow(flow, framework);
|
|
@@ -1152,7 +1231,7 @@ async function cmdEmit(positional, flags) {
|
|
|
1152
1231
|
for (const w of out.warnings)
|
|
1153
1232
|
console.error(`warning: ${w}`);
|
|
1154
1233
|
if (out.requiredValues.length)
|
|
1155
|
-
console.error(`reads from the environment: ${out.requiredValues.map(
|
|
1234
|
+
console.error(`reads from the environment: ${out.requiredValues.map(emitEnvName).join(', ')}`);
|
|
1156
1235
|
}
|
|
1157
1236
|
// --- recordings --------------------------------------------------------------
|
|
1158
1237
|
async function cmdRecordings(positional) {
|
|
@@ -1197,6 +1276,8 @@ async function main() {
|
|
|
1197
1276
|
case 'distill': return cmdDistill(rest, flags);
|
|
1198
1277
|
case 'remember': return cmdRemember(rest);
|
|
1199
1278
|
case 'emit': return cmdEmit(rest, flags);
|
|
1279
|
+
case 'promote': return cmdPromote(rest, flags);
|
|
1280
|
+
case 'drop': return cmdDrop(rest, flags);
|
|
1200
1281
|
default: fail(`unknown command '${command}'`, 'understudy --help');
|
|
1201
1282
|
}
|
|
1202
1283
|
}
|
package/dist/entry/mcp.d.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
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
17
|
* understudy_calibrate fit when recall calls a goal known, for one app and embedding model
|
|
18
|
+
* understudy_session explore in a browser Understudy drives; keep what worked as a flow
|
|
18
19
|
*
|
|
19
20
|
* Long-lived: reconnect (/mcp) after changing the source.
|
|
20
21
|
*/
|
package/dist/entry/mcp.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
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
17
|
* understudy_calibrate fit when recall calls a goal known, for one app and embedding model
|
|
18
|
+
* understudy_session explore in a browser Understudy drives; keep what worked as a flow
|
|
18
19
|
*
|
|
19
20
|
* Long-lived: reconnect (/mcp) after changing the source.
|
|
20
21
|
*/
|
|
@@ -31,9 +32,13 @@ import { collections } from '../store/db.js';
|
|
|
31
32
|
import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
|
|
32
33
|
import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
|
|
33
34
|
import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
|
|
35
|
+
import { dropVariant, promoteVariant } from '../flows/variants.js';
|
|
36
|
+
import { startSession, step as sessionStep, look as sessionLook, saveSession, closeSession, closeAllSessions } from '../flows/session.js';
|
|
34
37
|
import { MissingValuesError } from '../flows/execute.js';
|
|
35
|
-
import { parseScript } from '../adapters/recorder/script.js';
|
|
38
|
+
import { parseScript, parseScriptSource } from '../adapters/recorder/script.js';
|
|
39
|
+
import { join } from 'node:path';
|
|
36
40
|
import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
|
|
41
|
+
import { setAppTimeout, timeoutFor } from '../store/app-settings.js';
|
|
37
42
|
import { calibrate } from '../memory/calibrate.js';
|
|
38
43
|
import { VERSION } from './version.js';
|
|
39
44
|
/**
|
|
@@ -151,7 +156,7 @@ async function continueRun(state, opts) {
|
|
|
151
156
|
}
|
|
152
157
|
/** What a finished run tells the agent. */
|
|
153
158
|
function report(state, out) {
|
|
154
|
-
const { executed, recorded, plan, nowProven } = out;
|
|
159
|
+
const { executed, recorded, plan, nowProven, commit } = out;
|
|
155
160
|
const r = executed.result;
|
|
156
161
|
const byPerson = r.steps.filter((s) => s.viaHuman || s.viaHandoff);
|
|
157
162
|
return {
|
|
@@ -159,6 +164,7 @@ function report(state, out) {
|
|
|
159
164
|
runId: state.runId,
|
|
160
165
|
plan,
|
|
161
166
|
seams: state.seams,
|
|
167
|
+
...(commit && r.stoppedBefore !== undefined ? { stoppedBefore: `step ${commit.index}, ${commit.reason}: its control was there and ready, and was not pressed — nothing after it ran` } : {}),
|
|
162
168
|
failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
|
|
163
169
|
...(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' })) } : {}),
|
|
164
170
|
unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
|
|
@@ -175,12 +181,17 @@ function report(state, out) {
|
|
|
175
181
|
...(executed.staleSession ? { staleSession: executed.staleSession } : {}),
|
|
176
182
|
};
|
|
177
183
|
}
|
|
184
|
+
/** A branch or deploy's copy of flows, beside the main ones. */
|
|
185
|
+
/** Described once, on recall; REASONER.md says the rest. */
|
|
186
|
+
const variant = z.string().optional();
|
|
187
|
+
const baseUrl = z.string().optional();
|
|
178
188
|
const values = z.record(z.string(), z.string()).optional()
|
|
179
189
|
.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.');
|
|
180
190
|
server.registerTool('understudy_recall', {
|
|
181
191
|
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).',
|
|
182
|
-
inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional()
|
|
183
|
-
|
|
192
|
+
inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional(),
|
|
193
|
+
variant: variant.describe('A branch: its copies of flows.') },
|
|
194
|
+
}, ({ app, goal, limit, variant: v }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}), ...(v ? { variant: v } : {}) })));
|
|
184
195
|
server.registerTool('understudy_run', {
|
|
185
196
|
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.',
|
|
186
197
|
inputSchema: {
|
|
@@ -188,7 +199,8 @@ server.registerTool('understudy_run', {
|
|
|
188
199
|
subGoals: z.array(z.string()).optional().describe('Skip the decompose question.'),
|
|
189
200
|
dryRun: z.boolean().optional().describe('Plan only; open no browser.'),
|
|
190
201
|
allowPurchases: z.boolean().optional(),
|
|
191
|
-
|
|
202
|
+
stopBeforeCommit: z.boolean().optional(),
|
|
203
|
+
variant, baseUrl, values, headed: z.boolean().optional(),
|
|
192
204
|
},
|
|
193
205
|
}, (a) => wrap(async () => {
|
|
194
206
|
const state = await start({
|
|
@@ -196,6 +208,8 @@ server.registerTool('understudy_run', {
|
|
|
196
208
|
...(a.subGoals ? { subGoals: a.subGoals } : {}),
|
|
197
209
|
...(a.dryRun ? { dryRun: true } : {}),
|
|
198
210
|
...(a.allowPurchases ? { allowPurchases: true } : {}),
|
|
211
|
+
...(a.stopBeforeCommit ? { stopBeforeCommit: true } : {}),
|
|
212
|
+
...(a.variant ? { variant: a.variant } : {}), ...(a.baseUrl ? { baseUrl: a.baseUrl } : {}),
|
|
199
213
|
});
|
|
200
214
|
if (a.values)
|
|
201
215
|
valuesByRun.set(state.runId, a.values);
|
|
@@ -292,26 +306,45 @@ server.registerTool('understudy_record', {
|
|
|
292
306
|
server.registerTool('understudy_save', {
|
|
293
307
|
description: [
|
|
294
308
|
'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
|
|
296
|
-
'Understood: goto, click,
|
|
297
|
-
'
|
|
298
|
-
'Other checks come back in droppedAssertions; calls that change the steps (evaluate, hover, route…) refuse the save.',
|
|
309
|
+
'A script is read, not run: literal page calls only, no loops or runtime values.',
|
|
310
|
+
'Understood: goto, click, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; getBy*, locator(css), frameLocator, filter({hasText}), first/last/nth; inline expect() of URL, title, visible, hidden, text, value, checked; waitForURL, waitForSelector, waitForResponse, locator.waitFor().',
|
|
311
|
+
'Unkept checks come back in droppedAssertions; a call or wait it can\'t replay refuses the save.',
|
|
299
312
|
'Where only a person can act: human(\'what they do\', { untilText | untilUrl | untilResponse }).',
|
|
300
313
|
].join(' '),
|
|
301
314
|
inputSchema: {
|
|
302
315
|
app: z.string(), name: z.string().optional().describe('What the flow does, as someone would ask for it. Needed unless flow is given.'),
|
|
303
316
|
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
317
|
add: z.array(z.object({ before: z.number().int(), step: z.record(z.string(), z.unknown()) })).optional()
|
|
305
|
-
.describe('With flow: steps to add
|
|
318
|
+
.describe('With flow: steps to add, each before step n: human {value, hints:{untilText|untilUrl|untilResponse}}, wait_response {value:"/api/x", hints:{method,status,field,equals|above}}, assert {role,name,hints:{assert:"checked"}}, wait_url, wait_text.'),
|
|
306
319
|
hash: z.string().optional(),
|
|
307
320
|
script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
|
|
321
|
+
code: z.string().optional().describe('Or the code itself: e.g. the lines Playwright MCP printed for the steps that worked, as they came.'),
|
|
308
322
|
intent: z.string().optional(), slug: z.string().optional(), values,
|
|
309
|
-
|
|
323
|
+
variant: variant.describe('Save as this branch\'s copy; the main flow is untouched.'),
|
|
324
|
+
promote: z.boolean().optional().describe('With flow and variant: make the variant the main flow (the branch merged).'),
|
|
325
|
+
drop: z.boolean().optional().describe('With flow and variant: delete the copy; the variant uses the main flow again.'),
|
|
326
|
+
verify: z.boolean().optional().describe('A commit step (a purchase) is replayed only up to, never pressed. false: keep it with no replay, unproven until a run passes.'),
|
|
310
327
|
note: z.string().optional().describe('With verify false: why, e.g. what you checked yourself.'),
|
|
311
328
|
},
|
|
312
329
|
}, (a) => wrap(async () => {
|
|
313
330
|
if (a.flow) {
|
|
314
|
-
|
|
331
|
+
if (a.drop && a.promote)
|
|
332
|
+
throw new Error('drop or promote, not both');
|
|
333
|
+
if (a.drop) {
|
|
334
|
+
if (!a.variant)
|
|
335
|
+
throw new Error('drop needs the variant whose copy to delete');
|
|
336
|
+
return dropVariant(a.app, a.flow, a.variant);
|
|
337
|
+
}
|
|
338
|
+
if (a.promote) {
|
|
339
|
+
if (!a.variant)
|
|
340
|
+
throw new Error('promote needs the variant to make the main flow');
|
|
341
|
+
const p = await promoteVariant(a.app, a.flow, a.variant);
|
|
342
|
+
return {
|
|
343
|
+
...p,
|
|
344
|
+
...(p.staleSegments.length ? { note: `segments cut from the old main flow still hold its old steps: ${p.staleSegments.join(', ')} — distill '${p.flow}' again (ask the user first)` } : {}),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add, a.variant) : undefined;
|
|
315
348
|
if (edited && a.verify === false)
|
|
316
349
|
return { flow: edited.slug, steps: edited.steps.length, unproven: edited.unprovenBecause };
|
|
317
350
|
return { ...(edited ? { added: a.add.length } : {}), ...(await proveSaved(a.app, a.flow, a)) };
|
|
@@ -322,13 +355,18 @@ server.registerTool('understudy_save', {
|
|
|
322
355
|
let rec;
|
|
323
356
|
let madeBy = 'user';
|
|
324
357
|
let dropped = [];
|
|
325
|
-
if (a.script)
|
|
326
|
-
|
|
358
|
+
if (a.script && a.code)
|
|
359
|
+
throw new Error('pass script (a path) or code (the code itself), not both');
|
|
360
|
+
if (a.script || a.code) {
|
|
361
|
+
// A flow the agent drove: read its code into steps, exactly like `understudy import`.
|
|
327
362
|
const { apps } = await collections();
|
|
328
363
|
const base = (await apps.findOne({ slug: a.app }))?.urls.default;
|
|
329
|
-
|
|
364
|
+
// Inline code has no file: uploads are looked up from where the server runs.
|
|
365
|
+
const parsed = a.script
|
|
366
|
+
? await parseScript(a.script, a.app, base)
|
|
367
|
+
: parseScriptSource(a.code, join(process.cwd(), 'inline-code.ts'), a.app, base);
|
|
330
368
|
if (!parsed.recording.events.length)
|
|
331
|
-
throw new Error(`no Playwright actions found in ${a.script} — expected calls like page.getByRole(...).click()`);
|
|
369
|
+
throw new Error(`no Playwright actions found in ${a.script ?? 'the code'} — expected calls like page.getByRole(...).click()`);
|
|
332
370
|
if (parsed.warnings.length)
|
|
333
371
|
throw new Error(`these calls in the script can't be replayed, so it wasn't kept — rewrite them as plain Playwright actions:\n- ${parsed.warnings.slice(0, 10).join('\n- ')}`);
|
|
334
372
|
rec = parsed.recording;
|
|
@@ -341,7 +379,7 @@ server.registerTool('understudy_save', {
|
|
|
341
379
|
throw new Error('the user is still recording — ask them to click "Stop" in the extension first');
|
|
342
380
|
const hash = a.hash ?? finished.get(a.app)?.hash;
|
|
343
381
|
if (!hash)
|
|
344
|
-
throw new Error(`no finished recording for "${a.app}" — start one with understudy_record, pass a hash, or pass
|
|
382
|
+
throw new Error(`no finished recording for "${a.app}" — start one with understudy_record, pass a hash, or pass script or code`);
|
|
345
383
|
rec = await loadRecording(hash);
|
|
346
384
|
}
|
|
347
385
|
const hash = rec.hash;
|
|
@@ -351,6 +389,7 @@ server.registerTool('understudy_save', {
|
|
|
351
389
|
title: name, madeBy,
|
|
352
390
|
...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
|
|
353
391
|
...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
|
|
392
|
+
...(a.variant ? { variant: a.variant } : {}),
|
|
354
393
|
});
|
|
355
394
|
}
|
|
356
395
|
catch (e) {
|
|
@@ -359,6 +398,12 @@ server.registerTool('understudy_save', {
|
|
|
359
398
|
return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name }) };
|
|
360
399
|
throw e;
|
|
361
400
|
}
|
|
401
|
+
return savedReport(a.app, rec, out, { madeBy, dropped, ...(a.script || a.code ? {} : { droppedUploads: finished.get(a.app)?.droppedUploads ?? 0 }) });
|
|
402
|
+
}));
|
|
403
|
+
/** What a save tells the agent — for `understudy_save` and a session's save alike. */
|
|
404
|
+
function savedReport(app, rec, out, extra) {
|
|
405
|
+
const { madeBy, dropped = [] } = extra;
|
|
406
|
+
const hash = rec.hash;
|
|
362
407
|
const r = out.proven?.result;
|
|
363
408
|
const base = {
|
|
364
409
|
recording: hash,
|
|
@@ -370,7 +415,7 @@ server.registerTool('understudy_save', {
|
|
|
370
415
|
failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
|
|
371
416
|
signIn: out.proven.signIn,
|
|
372
417
|
} : { replayed: false }),
|
|
373
|
-
...(
|
|
418
|
+
...(extra.droppedUploads ? { droppedUploads: extra.droppedUploads } : {}),
|
|
374
419
|
};
|
|
375
420
|
if (!out.saved)
|
|
376
421
|
return { saved: false, ...base, why: 'it did not replay cleanly, so it was not kept. Fix the step, or pass verify: false to keep it unproven.' };
|
|
@@ -386,10 +431,10 @@ server.registerTool('understudy_save', {
|
|
|
386
431
|
...(out.run ? { findings: out.run.findings.map((f) => f.statement) } : {}),
|
|
387
432
|
...(out.placeholders.converted.length ? { placeholders: out.placeholders.converted } : {}),
|
|
388
433
|
};
|
|
389
|
-
}
|
|
434
|
+
}
|
|
390
435
|
/** understudy_save with `flow`: prove a saved flow — up to its commit, if it has one. Records the run. */
|
|
391
436
|
async function proveSaved(app, slug, a) {
|
|
392
|
-
const out = await proveFlow(app, slug, a.values ? { values: a.values } : {});
|
|
437
|
+
const out = await proveFlow(app, slug, { ...(a.values ? { values: a.values } : {}), ...(a.variant ? { variant: a.variant } : {}) });
|
|
393
438
|
const r = out.result;
|
|
394
439
|
return {
|
|
395
440
|
flow: out.flow.slug, passed: r.ok, newlyProven: out.newlyProven,
|
|
@@ -429,16 +474,58 @@ function provenUpTo(flow) {
|
|
|
429
474
|
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
475
|
};
|
|
431
476
|
}
|
|
477
|
+
server.registerTool('understudy_session', {
|
|
478
|
+
description: [
|
|
479
|
+
'Explore an app in a browser Understudy drives, and keep what worked as a flow.',
|
|
480
|
+
'do: start {app, url} or {app, flow, upTo} (runs a saved flow first; to repair one, it stops where it fails), step {step}, look {within?}, save {name, keep?}, close.',
|
|
481
|
+
'A step is a stored step, e.g. {"action":"click","role":"button","name":"Next"}; a password is valueRef "SECRET.password".',
|
|
482
|
+
'step returns what changed; look, the page\'s controls (no field values). save proves the kept steps in a fresh browser, up to a commit. A commit step needs allowPurchases.',
|
|
483
|
+
].join(' '),
|
|
484
|
+
inputSchema: {
|
|
485
|
+
do: z.enum(['start', 'step', 'look', 'save', 'close']),
|
|
486
|
+
session: z.string().optional(), app: z.string().optional(),
|
|
487
|
+
url: z.string().optional(), flow: z.string().optional(),
|
|
488
|
+
upTo: z.number().int().min(0).optional(),
|
|
489
|
+
headed: z.boolean().optional(), allowPurchases: z.boolean().optional(), variant, baseUrl: z.string().optional(),
|
|
490
|
+
values: z.record(z.string(), z.string()).optional().describe('Login values, as for run.'),
|
|
491
|
+
step: z.record(z.string(), z.unknown()).optional(),
|
|
492
|
+
within: z.string().optional(), name: z.string().optional(),
|
|
493
|
+
keep: z.array(z.number().int().min(0)).optional().describe('Session step numbers, in order. Default: every step that worked.'),
|
|
494
|
+
intent: z.string().optional(), slug: z.string().optional(),
|
|
495
|
+
},
|
|
496
|
+
}, (a) => wrap(async () => {
|
|
497
|
+
const need = (v, what) => {
|
|
498
|
+
if (v === undefined)
|
|
499
|
+
throw new Error(`${a.do} needs ${what}`);
|
|
500
|
+
return v;
|
|
501
|
+
};
|
|
502
|
+
switch (a.do) {
|
|
503
|
+
case 'start':
|
|
504
|
+
return startSession(defined({
|
|
505
|
+
app: need(a.app, 'app'), url: a.url, flow: a.flow, upTo: a.upTo, headed: a.headed, values: a.values, allowPurchases: a.allowPurchases,
|
|
506
|
+
variant: a.variant, baseUrl: a.baseUrl,
|
|
507
|
+
}));
|
|
508
|
+
case 'step': return sessionStep(need(a.session, 'session'), need(a.step, 'step'));
|
|
509
|
+
case 'look': return sessionLook(need(a.session, 'session'), a.within);
|
|
510
|
+
case 'save': {
|
|
511
|
+
const { recording: rec, out, suggestions } = await saveSession(need(a.session, 'session'), defined({ name: need(a.name, 'name'), keep: a.keep, intent: a.intent, slug: a.slug, variant: a.variant }));
|
|
512
|
+
return { ...savedReport(rec.appSlug, rec, out, { madeBy: 'agent' }), ...(suggestions ? { suggestions } : {}) };
|
|
513
|
+
}
|
|
514
|
+
case 'close': return closeSession(need(a.session, 'session'));
|
|
515
|
+
}
|
|
516
|
+
}));
|
|
432
517
|
server.registerTool('understudy_app', {
|
|
433
518
|
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.',
|
|
434
519
|
inputSchema: {
|
|
435
520
|
app: z.string(),
|
|
436
521
|
placeholders: z.array(z.enum(['email'])).optional().describe('[] turns it off for new flows.'),
|
|
522
|
+
timeoutMs: z.number().int().nullable().optional(),
|
|
437
523
|
},
|
|
438
|
-
}, ({ app, placeholders }) => wrap(async () => {
|
|
524
|
+
}, ({ app, placeholders, timeoutMs }) => wrap(async () => {
|
|
525
|
+
const set = timeoutMs !== undefined ? await setAppTimeout(app, timeoutMs) : undefined;
|
|
439
526
|
if (placeholders)
|
|
440
|
-
return setPlaceholders(app, placeholders);
|
|
441
|
-
return { app, placeholders: await appPlaceholders(app) };
|
|
527
|
+
return { ...(await setPlaceholders(app, placeholders)), ...(set ? { timeoutMs: set.timeoutMs ?? 'default' } : {}) };
|
|
528
|
+
return { app, placeholders: await appPlaceholders(app), timeoutMs: (await timeoutFor(app)) ?? 'default (10000)' };
|
|
442
529
|
}));
|
|
443
530
|
server.registerTool('understudy_calibrate', {
|
|
444
531
|
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.',
|
|
@@ -452,4 +539,8 @@ server.registerTool('understudy_calibrate', {
|
|
|
452
539
|
goals: { known: (known ?? []).flatMap((k) => k.goals.map((goal) => ({ flow: k.flow, goal }))), unknown: unknown ?? [] },
|
|
453
540
|
...(dryRun ? { dryRun } : {}),
|
|
454
541
|
})));
|
|
542
|
+
// Each open session is a browser: close them when the client goes.
|
|
543
|
+
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
544
|
+
process.once(signal, () => { void closeAllSessions().finally(() => process.exit(0)); });
|
|
545
|
+
process.stdin.once('end', () => { void closeAllSessions(); });
|
|
455
546
|
await server.connect(new StdioServerTransport());
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* boundaries, facts, other destructive flows). They return with the safety
|
|
13
13
|
* gate in phase 3 — see `git show legacy-cockroach:src/core/destructive.ts`.
|
|
14
14
|
*/
|
|
15
|
-
const COMMIT_WORDS = /\b(pay|purchase|buy|place order|order now|checkout|check out|confirm|delete|remove account|reset|deactivate|destroy|publish|subscribe|charge|submit order)\b/i;
|
|
15
|
+
const COMMIT_WORDS = /\b(pay|purchase|buy|book|place order|order now|checkout|check out|confirm|delete|remove account|reset|deactivate|destroy|publish|subscribe|charge|submit order)\b/i;
|
|
16
16
|
const PAYMENT_HOSTS = /(^|\.)(stripe|paypal|braintree|adyen|checkout|squareup|klarna|worldpay|authorize)\.(com|net|io)$/i;
|
|
17
17
|
/**
|
|
18
18
|
* Only these actions can commit anything. Typing into "Confirm password" or
|