@jeffawe/understudy 0.3.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -160
  3. package/REASONER.md +76 -86
  4. package/dist/adapters/recorder/script.d.ts +25 -2
  5. package/dist/adapters/recorder/script.js +126 -31
  6. package/dist/core/outline.d.ts +43 -0
  7. package/dist/core/outline.js +121 -0
  8. package/dist/core/recording.d.ts +19 -1
  9. package/dist/core/recording.js +38 -2
  10. package/dist/core/replay.d.ts +62 -1
  11. package/dist/core/replay.js +162 -106
  12. package/dist/entry/cli.js +185 -30
  13. package/dist/entry/mcp.d.ts +2 -0
  14. package/dist/entry/mcp.js +128 -23
  15. package/dist/flows/destructive.js +1 -1
  16. package/dist/flows/distill.js +11 -6
  17. package/dist/flows/emit.d.ts +7 -0
  18. package/dist/flows/emit.js +26 -10
  19. package/dist/flows/execute.d.ts +12 -0
  20. package/dist/flows/execute.js +23 -16
  21. package/dist/flows/runs.d.ts +2 -0
  22. package/dist/flows/runs.js +7 -3
  23. package/dist/flows/save.d.ts +5 -2
  24. package/dist/flows/save.js +38 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +383 -0
  27. package/dist/flows/variants.d.ts +81 -0
  28. package/dist/flows/variants.js +139 -0
  29. package/dist/memory/calibrate.d.ts +114 -0
  30. package/dist/memory/calibrate.js +260 -0
  31. package/dist/memory/pages.d.ts +34 -0
  32. package/dist/memory/pages.js +60 -0
  33. package/dist/memory/recall.d.ts +87 -25
  34. package/dist/memory/recall.js +242 -45
  35. package/dist/plan/planner.d.ts +11 -1
  36. package/dist/plan/planner.js +36 -19
  37. package/dist/store/app-settings.d.ts +26 -0
  38. package/dist/store/app-settings.js +49 -0
  39. package/dist/store/db.js +8 -1
  40. package/dist/store/reembed.js +18 -7
  41. package/dist/store/types.d.ts +50 -0
  42. package/package.json +3 -2
@@ -23,6 +23,8 @@ export declare function stepsFrom(recording: RawRecording, result?: ReplayResult
23
23
  export declare function recordingFrom(flow: Flow): RawRecording;
24
24
  export interface SaveOptions {
25
25
  title: string;
26
+ /** Save it as this variant's copy, beside the main flow (flows/variants.ts). */
27
+ variant?: string;
26
28
  /** Defaults to slugify(title). */
27
29
  slug?: string;
28
30
  /** What the flow is for, if different from the title. */
@@ -75,7 +77,7 @@ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave
75
77
  * A run that stopped before the flow's commit step proves it that far
76
78
  * (`provenUpTo`); a full run that passes proves the rest, and clears it.
77
79
  */
78
- export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number): Promise<boolean>;
80
+ export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number, variant?: string): Promise<boolean>;
79
81
  export interface ProvedFlow extends Executed {
80
82
  flow: Flow;
81
83
  /** The commit step it stopped before, when the flow has one. */
@@ -93,6 +95,7 @@ export interface ProvedFlow extends Executed {
93
95
  export declare function proveFlow(app: string, slug: string, opts?: {
94
96
  values?: Record<string, string>;
95
97
  headed?: boolean;
98
+ variant?: string;
96
99
  }): Promise<ProvedFlow>;
97
100
  export interface StepToAdd {
98
101
  /** Goes in front of the step at this index; the flow's length appends. */
@@ -112,4 +115,4 @@ export declare function checkAdditions(flow: Pick<Flow, 'steps' | 'startUrl'>, a
112
115
  * Add steps to a saved flow. It is unproven afterwards — a run that passes
113
116
  * proves it again — and segments cut from it keep pointing at the same steps.
114
117
  */
115
- export declare function editFlow(app: string, slug: string, adds: StepToAdd[]): Promise<Flow>;
118
+ export declare function editFlow(app: string, slug: string, adds: StepToAdd[], variant?: string): Promise<Flow>;
@@ -8,6 +8,7 @@
8
8
  *
9
9
  * Saving the same name again replaces the flow — re-record, re-save, done.
10
10
  */
11
+ import { checkVariant, flowKey, MAIN, resolveFlow } from './variants.js';
11
12
  import { collections, ensureSchema } from '../store/db.js';
12
13
  import { embed, embedderConfig } from '../store/embed.js';
13
14
  import { commitSteps, flowDestructiveReason } from './destructive.js';
@@ -71,6 +72,8 @@ export async function saveFlow(recording, result, opts) {
71
72
  const slug = opts.slug ?? slugify(opts.title);
72
73
  if (!slug)
73
74
  throw new Error(`can't make a flow name from "${opts.title}" — pass --slug`);
75
+ const variant = checkVariant(opts.variant);
76
+ const key = flowKey(app, slug, variant);
74
77
  const steps = stepsFrom(recording, result);
75
78
  const why = flowDestructiveReason(steps);
76
79
  const upTo = stoppedAt(recording, result);
@@ -81,6 +84,7 @@ export async function saveFlow(recording, result, opts) {
81
84
  const flow = {
82
85
  app,
83
86
  slug,
87
+ ...(variant ? { variant } : {}),
84
88
  title: opts.title,
85
89
  intent,
86
90
  kind: 'recording',
@@ -121,10 +125,10 @@ export async function saveFlow(recording, result, opts) {
121
125
  unset.provenUpTo = '';
122
126
  if (upTo !== undefined)
123
127
  unset.endState = '';
124
- await flows.updateOne({ app, slug }, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
128
+ await flows.updateOne(key, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
125
129
  // Make sure the app exists, remembering where it lives.
126
130
  await apps.updateOne({ slug: app }, { $setOnInsert: { slug: app, name: app, urls: { default: new URL(recording.startUrl).origin }, createdAt: now } }, { upsert: true });
127
- return (await flows.findOne({ app, slug }));
131
+ return (await flows.findOne(key));
128
132
  }
129
133
  /**
130
134
  * What `save` does, for the CLI and the MCP server alike: prove the recording
@@ -168,7 +172,7 @@ export async function proveAndSave(recording, opts) {
168
172
  }
169
173
  const saved = await saveFlow(proven.recording, proven.result, { ...opts, ...(unproven ? { unproven } : {}) });
170
174
  const { flow, placeholders } = await withPlaceholders(saved);
171
- const run = await recordRun({ app: flow.app, flow: flow.slug, result: proven.result, steps: flow.steps, ...(flow.proven === false ? { unproven: true } : {}) });
175
+ const run = await recordRun({ app: flow.app, flow: flow.slug, result: proven.result, steps: flow.steps, ...(flow.variant ? { variant: flow.variant } : {}), ...(flow.proven === false ? { unproven: true } : {}) });
172
176
  return { saved: true, verified: proven.result.ok, proven, flow, run, placeholders };
173
177
  }
174
178
  /** The app keeps email fields as placeholders? Convert now — after proving, which used the real address. */
@@ -198,13 +202,15 @@ async function firstStop(app, steps) {
198
202
  * A run that stopped before the flow's commit step proves it that far
199
203
  * (`provenUpTo`); a full run that passes proves the rest, and clears it.
200
204
  */
201
- export async function proveByRun(app, slug, result, offset = 0) {
205
+ export async function proveByRun(app, slug, result, offset = 0, variant) {
202
206
  if (!result.ok)
203
207
  return false;
204
208
  const { flows } = await collections();
205
- const flow = await flows.findOne({ app, slug, $or: [{ proven: false }, { provenUpTo: { $exists: true } }] });
206
- if (!flow)
209
+ // The flow the run used: the variant's copy if it has one, else the main flow.
210
+ const ran = await resolveFlow(app, slug, variant);
211
+ if (!ran || (ran.proven !== false && ran.provenUpTo === undefined))
207
212
  return false;
213
+ const flow = ran;
208
214
  const stopped = result.stoppedBefore === undefined ? undefined : result.stoppedBefore - offset;
209
215
  // Stopped before this flow began: none of it ran.
210
216
  if (stopped !== undefined && stopped < 0)
@@ -238,21 +244,22 @@ export async function proveByRun(app, slug, result, offset = 0) {
238
244
  */
239
245
  export async function proveFlow(app, slug, opts = {}) {
240
246
  const { flows } = await collections();
241
- const flow = await flows.findOne({ app, slug });
247
+ const { variant, ...run } = opts;
248
+ const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
242
249
  if (!flow)
243
- throw new Error(`no flow '${slug}' for app '${app}'`);
250
+ throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
244
251
  const commit = await firstStop(app, flow.steps);
245
252
  const recording = recordingFrom(flow);
246
253
  const executed = await execute(recording, {
247
- ...opts, useLessons: true,
254
+ ...run, useLessons: true,
248
255
  ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}),
249
256
  });
250
- const run = await recordRun({
257
+ const recorded = await recordRun({
251
258
  app, flow: slug, result: executed.result, steps: flow.steps, mode: 'replay',
252
- ...(flow.proven === false ? { unproven: true } : {}),
259
+ ...(flow.variant ? { variant: flow.variant } : {}), ...(flow.proven === false ? { unproven: true } : {}),
253
260
  });
254
- const newlyProven = await proveByRun(app, slug, executed.result);
255
- return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run, newlyProven };
261
+ const newlyProven = await proveByRun(app, slug, executed.result, 0, flow.variant);
262
+ return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run: recorded, newlyProven };
256
263
  }
257
264
  /**
258
265
  * Steps that can be added to a saved flow by hand — mostly to fix up flows
@@ -263,11 +270,13 @@ const ADDABLE = {
263
270
  human: ['untilText', 'untilUrl', 'untilResponse'],
264
271
  // A check of what the page shows — how a flow should end. Addressed by
265
272
  // role + name, which is a look, not a click.
266
- assert: ['assert'],
267
- wait_response: ['method', 'status', 'field', 'equals', 'above'],
268
- wait_url: [],
269
- wait_text: [],
273
+ assert: ['assert', 'timeoutMs'],
274
+ wait_response: ['method', 'status', 'field', 'equals', 'above', 'urlRegex', 'urlFlags', 'timeoutMs'],
275
+ wait_url: ['timeoutMs'],
276
+ wait_text: ['timeoutMs'],
270
277
  };
278
+ /** What an added assert may check: no expected value, or text to expect. */
279
+ const ADDABLE_CHECKS = ['visible', 'hidden', 'checked', 'unchecked', 'enabled', 'disabled', 'editable', 'focused', 'text', 'contains'];
271
280
  /** Every problem with these additions at once, or the steps to insert. */
272
281
  export function checkAdditions(flow, adds) {
273
282
  const problems = [];
@@ -287,8 +296,12 @@ export function checkAdditions(flow, adds) {
287
296
  if (isAssert) {
288
297
  if (typeof role !== 'string' || typeof name !== 'string' || !name.trim())
289
298
  problems.push(`${at}.step: an assert needs role and name, e.g. {"role":"heading","name":"Visit booked"}`);
290
- if (!['visible', 'hidden', 'checked', 'unchecked', 'text', 'contains'].includes(String(kind)))
291
- problems.push(`${at}.step.hints.assert must be visible, hidden, checked, unchecked, text or contains`);
299
+ if (!ADDABLE_CHECKS.includes(String(kind)))
300
+ problems.push(`${at}.step.hints.assert must be one of ${ADDABLE_CHECKS.join(', ')}`);
301
+ }
302
+ const ms = hints?.timeoutMs;
303
+ if (ms !== undefined && (!Number.isInteger(ms) || ms < 1000 || ms > 600_000)) {
304
+ problems.push(`${at}.step.hints.timeoutMs must be a whole number of ms from 1000 to 600000`);
292
305
  }
293
306
  const needsValue = !isAssert || kind === 'text' || kind === 'contains';
294
307
  if (needsValue && (typeof value !== 'string' || !value.trim())) {
@@ -317,11 +330,11 @@ export function checkAdditions(flow, adds) {
317
330
  * Add steps to a saved flow. It is unproven afterwards — a run that passes
318
331
  * proves it again — and segments cut from it keep pointing at the same steps.
319
332
  */
320
- export async function editFlow(app, slug, adds) {
333
+ export async function editFlow(app, slug, adds, variant) {
321
334
  const { flows } = await collections();
322
- const flow = await flows.findOne({ app, slug });
335
+ const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
323
336
  if (!flow)
324
- throw new Error(`no flow '${slug}' for app '${app}'`);
337
+ throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
325
338
  if (flow.kind !== 'recording')
326
339
  throw new Error(`'${slug}' is a segment — add the steps to the flow it was cut from (${flow.from?.flow})`);
327
340
  if (!adds.length)
@@ -345,7 +358,9 @@ export async function editFlow(app, slug, adds) {
345
358
  });
346
359
  // A segment AFTER an insertion moves along; one an insertion lands INSIDE
347
360
  // gets the step too, and must be proven again like its parent.
348
- for (const seg of await flows.find({ app, kind: 'segment', 'from.flow': slug }).toArray()) {
361
+ // Segments are cut from main flows only, so a variant's edit moves none.
362
+ const segments = flow.variant ? [] : await flows.find({ app, kind: 'segment', 'from.flow': slug, ...MAIN }).toArray();
363
+ for (const seg of segments) {
349
364
  let [start, end] = seg.from.steps;
350
365
  const segSteps = [...seg.steps];
351
366
  let changed = false;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Agent sessions: an agent explores an app THROUGH Understudy, one step at a
3
+ * time, and keeps the steps that worked as a flow.
4
+ *
5
+ * Before this, an agent explored with throwaway Playwright scripts (page
6
+ * dumps, "which question appears after this answer?"), then rewrote the path
7
+ * that worked in the format `understudy_save` reads, then had it replayed.
8
+ * Most of its tokens went on the first part, and everything it learned there
9
+ * was lost. Here exploring IS recording:
10
+ *
11
+ * start open a browser — at an address, or partway along a saved flow
12
+ * (`upTo`), which is also how a stale flow is repaired: replay it to
13
+ * the step that fails and explore from there
14
+ * step one click, fill, pick… run by the same Stepper replay uses, so a
15
+ * step that works here works when the flow replays. Returns only
16
+ * what changed: controls that appeared or went, the address, errors,
17
+ * API calls
18
+ * look the page's controls — role, name, state, options; no field values
19
+ * save the steps the agent keeps, PROVEN BY A REPLAY IN A FRESH BROWSER
20
+ * (up to a commit, as any save). One pass in a warm, slow session
21
+ * proves little: the agent paused to think between steps, which
22
+ * hides every wait the flow really needs.
23
+ *
24
+ * No model here either: the agent decides what to do; this does it and keeps
25
+ * the record. Sessions live in this process (the MCP server); a restart loses
26
+ * them, and one left alone closes after IDLE_MS.
27
+ */
28
+ import { type StepOutcome } from '../core/replay.js';
29
+ import { type RawRecording } from '../core/recording.js';
30
+ import { type SaveOutcome } from './save.js';
31
+ import type { Step } from '../store/types.js';
32
+ /** A session nobody has used for this long is closed. */
33
+ export declare const IDLE_MS: number;
34
+ interface Tried {
35
+ n: number;
36
+ step: Step;
37
+ ok: boolean;
38
+ error?: string;
39
+ /** From the flow it started along, rather than tried by the agent. */
40
+ fromFlow?: true;
41
+ /** Controls it revealed on the same page — a follow-up question, a hidden field. */
42
+ revealed?: string[];
43
+ }
44
+ export interface PageNow {
45
+ url: string;
46
+ title: string;
47
+ /** The page's controls, one line each. */
48
+ controls: string[];
49
+ /** Set when the outline was cut at OUTLINE_MAX. */
50
+ more?: true;
51
+ }
52
+ export interface StartOptions {
53
+ app: string;
54
+ /** Open this address. */
55
+ url?: string;
56
+ /** Or start along this saved flow… */
57
+ flow?: string;
58
+ /** …running its steps before this one (default: all of them). */
59
+ upTo?: number;
60
+ headed?: boolean;
61
+ values?: Record<string, string>;
62
+ /** Let a step that commits something real (pay, book, delete) run. */
63
+ allowPurchases?: boolean;
64
+ /** Use this variant's copy of the flow, if it has one — and save to it. */
65
+ variant?: string;
66
+ /** With flow: run it against the app at this address (a branch's preview deploy). */
67
+ baseUrl?: string;
68
+ }
69
+ export declare function startSession(opts: StartOptions): Promise<{
70
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
71
+ page: PageNow;
72
+ how?: string;
73
+ session: string;
74
+ ran: number;
75
+ stoppedAt: {
76
+ step: string;
77
+ foundBy?: string;
78
+ matched?: number;
79
+ saw?: string;
80
+ error?: string;
81
+ ok: boolean;
82
+ n: number;
83
+ };
84
+ } | {
85
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
86
+ session: string;
87
+ ran: number;
88
+ page: PageNow;
89
+ }>;
90
+ export declare function step(id: string, raw: Record<string, unknown>): Promise<{
91
+ ok: boolean;
92
+ refused: string;
93
+ how: string;
94
+ } | {
95
+ errors?: string[];
96
+ responses?: string[];
97
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
98
+ changed?: string[];
99
+ gone?: string[];
100
+ appeared?: string[];
101
+ newPage?: boolean;
102
+ ms: number;
103
+ url: string;
104
+ foundBy?: string;
105
+ matched?: number;
106
+ saw?: string;
107
+ error?: string;
108
+ ok: boolean;
109
+ n: number;
110
+ refused?: never;
111
+ how?: never;
112
+ }>;
113
+ export declare function look(id: string, within?: string): Promise<{
114
+ steps: string[];
115
+ url: string;
116
+ title: string;
117
+ /** The page's controls, one line each. */
118
+ controls: string[];
119
+ /** Set when the outline was cut at OUTLINE_MAX. */
120
+ more?: true;
121
+ }>;
122
+ export interface SaveFromSession {
123
+ name: string;
124
+ /** Session step numbers to keep, in order. Default: every step that worked. */
125
+ keep?: number[];
126
+ intent?: string;
127
+ slug?: string;
128
+ /** Save as this variant's copy. Default: the variant the session started with, if any. */
129
+ variant?: string;
130
+ }
131
+ /**
132
+ * Keep the session's steps as a flow — proven by replaying them in a fresh
133
+ * browser first, exactly as `understudy_save` proves a recording.
134
+ */
135
+ export declare function saveSession(id: string, opts: SaveFromSession): Promise<{
136
+ recording: RawRecording;
137
+ out: SaveOutcome;
138
+ suggestions?: Suggestions;
139
+ }>;
140
+ /** What a session noticed, for the agent to put to the user. Nothing here is written by itself. */
141
+ export interface Suggestions {
142
+ /** Checks to add before a step that needed the page to be ready: `understudy_save { flow, add }`. */
143
+ waits?: {
144
+ before: number;
145
+ step: Record<string, unknown>;
146
+ why: string;
147
+ }[];
148
+ /** Facts worth remembering: `understudy_remember`. */
149
+ facts?: {
150
+ text: string;
151
+ why: string;
152
+ }[];
153
+ /** Controls that stayed disabled: maybe an app state the flow needs (`requires`, when distilling). */
154
+ states?: {
155
+ control: string;
156
+ why: string;
157
+ }[];
158
+ how: string;
159
+ }
160
+ /**
161
+ * Pure: what the session's own record says the saved flow may need. Exported
162
+ * for tests.
163
+ *
164
+ * a step that failed at first and worked when tried again → the page wasn't ready: a wait before it
165
+ * a step that took over half the time a step may wait, in
166
+ * the fresh-browser replay → a wait before it, with room to spare
167
+ * a kept step that revealed controls on the same page → a fact: "picking Yes shows Which bundle?"
168
+ * a step that failed "not enabled", never done after → a control that stayed disabled: an app state?
169
+ */
170
+ export declare function suggest(tried: Tried[], kept: Tried[], offset: number, proof: Pick<StepOutcome, 'seq' | 'durationMs'>[], timeoutMs: number): Suggestions | undefined;
171
+ export declare function closeSession(id: string): Promise<{
172
+ closed: boolean;
173
+ }>;
174
+ /** Close every session — on shutdown, and in tests. */
175
+ export declare function closeAllSessions(): Promise<void>;
176
+ export {};