@jeffawe/understudy 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +166 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1016 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +76 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Planning a goal that may need several flows, pausing to ask an agent when
3
+ * it can't decide alone.
4
+ *
5
+ * start(goal) ─▶ decompose? ─▶ bind each sub-goal ─▶ safety ─▶ seams ─▶ planned
6
+ * (ask) (recall) (ask if stuck)
7
+ *
8
+ * Every question is asked BEFORE a browser opens. Once a plan is complete it
9
+ * runs to the end without pausing; anything odd on the way becomes a finding.
10
+ * So a paused run holds nothing open: its progress lives on its run document,
11
+ * and `answer()` picks it up from there.
12
+ *
13
+ * Questions:
14
+ * decompose { subGoals: ["log in as a member", "open the cart"] }
15
+ * seam { steps: [{ action: "click", role: "link", name: "Cart" }] } — or [] if unknown
16
+ */
17
+ import { ObjectId } from 'mongodb';
18
+ import { collections } from '../store/db.js';
19
+ import { recall } from '../memory/recall.js';
20
+ import { vocabulary } from '../memory/vocabulary.js';
21
+ import { destructiveControls } from '../memory/notes.js';
22
+ import { resolveSeam, acceptSeamAnswer } from './seams.js';
23
+ import { execute } from '../flows/execute.js';
24
+ import { recordRun } from '../flows/runs.js';
25
+ import { proveByRun } from '../flows/save.js';
26
+ const DECOMPOSE_HOW = [
27
+ 'Split the goal into the things that must HAPPEN, in the order the app does them.',
28
+ 'Phrase each sub-goal in the words of a flow listed below — near-verbatim where one does the thing. Each sub-goal is a search.',
29
+ 'Include prerequisites the goal leaves implicit (e.g. log in first, if the next flow needs it).',
30
+ 'If one recorded flow already covers the whole goal, one sub-goal naming it beats several naming its parts.',
31
+ ].join(' ');
32
+ const SEAM_HOW = [
33
+ 'How do you get from where the first flow ends to where the next begins?',
34
+ 'Answer { "steps": [...] } with one click ({action:"click",role,name}) or a goto ({action:"goto",url}).',
35
+ 'Answer { "steps": [] } unless you actually KNOW — a one-click answer is saved and reused for every future plan, so a guess becomes a wrong fact.',
36
+ 'You can check first: open the app, or look at knownLinksFromHere.',
37
+ ].join(' ');
38
+ export async function start(req) {
39
+ const { runs } = await collections();
40
+ const now = new Date();
41
+ const run = {
42
+ app: req.app, goal: req.goal, mode: 'run', status: 'waiting', plan: [], steps: [], sigSequence: [],
43
+ events: [], findings: [], durationMs: 0, startedAt: now,
44
+ planning: {
45
+ ...(req.subGoals?.length ? { subGoals: req.subGoals } : {}),
46
+ ...(req.dryRun ? { dryRun: true } : {}),
47
+ ...(req.allowPurchases ? { allowPurchases: true } : {}),
48
+ },
49
+ };
50
+ const { insertedId } = await runs.insertOne(run);
51
+ return advance({ ...run, _id: insertedId });
52
+ }
53
+ /** Answer the run's open question, and carry on planning. */
54
+ export async function answer(runId, reply) {
55
+ const { runs, flows } = await collections();
56
+ const run = await runs.findOne({ _id: new ObjectId(runId) });
57
+ if (!run)
58
+ throw new Error(`no run ${runId}`);
59
+ if (run.status !== 'waiting' || !run.question)
60
+ throw new Error(`run ${runId} isn't waiting for an answer (it is ${run.status})`);
61
+ const planning = run.planning ?? {};
62
+ const q = run.question;
63
+ if (q.kind === 'decompose') {
64
+ const subGoals = reply?.subGoals;
65
+ if (!Array.isArray(subGoals) || !subGoals.length || subGoals.some((g) => typeof g !== 'string' || !g.trim())) {
66
+ throw new Error('answer must be { "subGoals": ["…", "…"] } — at least one, in order');
67
+ }
68
+ planning.subGoals = subGoals.map((g) => g.trim());
69
+ }
70
+ else if (q.kind === 'seam') {
71
+ const i = q.before;
72
+ const [from, to] = await Promise.all([
73
+ flows.findOne({ app: run.app, slug: planning.bound[i - 1] }),
74
+ flows.findOne({ app: run.app, slug: planning.bound[i] }),
75
+ ]);
76
+ const accepted = await acceptSeamAnswer(run.app, from, to, reply);
77
+ if ('problems' in accepted)
78
+ throw new Error(accepted.problems.join('; '));
79
+ if (!accepted.steps.length) {
80
+ return block(run, `no known way from ${from.slug} to ${to.slug} — record the step between them, or plan with different sub-goals`);
81
+ }
82
+ planning.seams = { ...planning.seams, [String(i)]: { steps: accepted.steps, how: 'answered by the agent' } };
83
+ }
84
+ await runs.updateOne({ _id: run._id }, { $set: { planning }, $unset: { question: '' } });
85
+ return advance({ ...run, planning });
86
+ }
87
+ async function ask(run, question) {
88
+ const { runs } = await collections();
89
+ await runs.updateOne({ _id: run._id }, { $set: { status: 'waiting', question, planning: run.planning } });
90
+ return { status: 'waiting', runId: run._id.toHexString(), question };
91
+ }
92
+ async function block(run, why, detail) {
93
+ const { runs } = await collections();
94
+ await runs.updateOne({ _id: run._id }, { $set: { status: 'blocked', blockedBecause: why, endedAt: new Date(), planning: run.planning }, $unset: { question: '' } });
95
+ return { status: 'blocked', runId: run._id.toHexString(), why, ...(detail ? { detail } : {}) };
96
+ }
97
+ /** Do as much planning as possible without help; stop at the first question. */
98
+ async function advance(run) {
99
+ const planning = (run.planning ??= {});
100
+ const { flows } = await collections();
101
+ // 1. Split the goal.
102
+ if (!planning.subGoals) {
103
+ return ask(run, { kind: 'decompose', goal: run.goal, how: DECOMPOSE_HOW, vocabulary: await vocabulary(run.app) });
104
+ }
105
+ // 2. Bind each sub-goal to the flow that does it. Only a KNOWN match binds.
106
+ if (!planning.bound) {
107
+ const bound = [];
108
+ for (const sub of planning.subGoals) {
109
+ const r = await recall(run.app, sub);
110
+ if (r.verdict !== 'known' || !r.best) {
111
+ const close = r.flows.slice(0, 3).map((f) => ({ slug: f.slug, title: f.title, score: Number(f.score.toFixed(3)) }));
112
+ return block(run, `no flow clearly does "${sub}" (${r.why}) — rephrase it in the app's words, or record it`, { subGoal: sub, closest: close });
113
+ }
114
+ // Two sub-goals that bind the same flow back to back are one step of the plan.
115
+ if (bound.at(-1) !== r.best.slug)
116
+ bound.push(r.best.slug);
117
+ }
118
+ planning.bound = bound;
119
+ }
120
+ const plan = await Promise.all(planning.bound.map((slug) => flows.findOne({ app: run.app, slug })));
121
+ if (plan.some((f) => !f))
122
+ return block(run, 'a bound flow no longer exists — plan again');
123
+ const chain = plan;
124
+ // 3. Safety: refuse anything that commits something real, unless allowed.
125
+ if (!planning.allowPurchases) {
126
+ const risky = chain.find((f) => f.destructive);
127
+ if (risky)
128
+ return block(run, `${risky.slug} is destructive (${risky.destructiveBecause}) — allow purchases to run it`);
129
+ const controls = await destructiveControls(run.app);
130
+ for (const f of chain) {
131
+ const hit = f.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
132
+ if (hit)
133
+ return block(run, `${f.slug} clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())}`);
134
+ }
135
+ }
136
+ // 4. The first flow must be able to start from a cold browser (or a saved session).
137
+ const first = chain[0];
138
+ if (first.preconditions.includes('authenticated') && !first.requiresSession) {
139
+ return block(run, `${first.slug} needs a signed-in browser — add a sub-goal that logs in, before it`);
140
+ }
141
+ // 5. Seams between consecutive flows.
142
+ planning.seams ??= {};
143
+ for (let i = 1; i < chain.length; i++) {
144
+ if (planning.seams[String(i)])
145
+ continue;
146
+ const seam = await resolveSeam(run.app, chain[i - 1], chain[i]);
147
+ if (!seam.resolved) {
148
+ return ask(run, { kind: 'seam', before: i, how: SEAM_HOW, ...seam.evidence });
149
+ }
150
+ planning.seams[String(i)] = { steps: seam.steps, how: seam.how };
151
+ }
152
+ // Planned.
153
+ const { runs } = await collections();
154
+ await runs.updateOne({ _id: run._id }, { $set: { status: 'planned', plan: planning.bound, planning }, $unset: { question: '' } });
155
+ return {
156
+ status: 'planned',
157
+ runId: run._id.toHexString(),
158
+ plan: planning.bound,
159
+ seams: Object.entries(planning.seams).map(([i, s]) => ({ before: planning.bound[Number(i)], how: s.how })),
160
+ dryRun: Boolean(planning.dryRun),
161
+ };
162
+ }
163
+ /** One recording for the whole plan: each flow's steps, joined by its seam. */
164
+ export async function recordingForPlan(runId) {
165
+ const { runs, flows } = await collections();
166
+ const run = await runs.findOne({ _id: new ObjectId(runId) });
167
+ if (!run || run.status !== 'planned')
168
+ throw new Error(`run ${runId} isn't planned (it is ${run?.status ?? 'missing'})`);
169
+ const chain = (await Promise.all(run.plan.map((slug) => flows.findOne({ app: run.app, slug }))));
170
+ const first = chain[0];
171
+ const steps = [];
172
+ const starts = [];
173
+ chain.forEach((flow, i) => {
174
+ if (i > 0)
175
+ steps.push(...(run.planning?.seams?.[String(i)]?.steps ?? []));
176
+ // A segment cut from the middle of a recording doesn't open its own page.
177
+ if (i === 0 && flow.steps[0]?.action !== 'goto' && flow.steps[0]?.url) {
178
+ steps.push({ action: 'goto', value: flow.steps[0].url, url: flow.steps[0].url, resolution: 'synthesized' });
179
+ }
180
+ starts.push(steps.length);
181
+ steps.push(...flow.steps);
182
+ });
183
+ const recording = {
184
+ version: 1, source: 'import', origin: `plan:${run.plan.join('+')}`, appSlug: run.app,
185
+ startUrl: first.startUrl, createdAt: new Date().toISOString(), hash: `plan-${runId}`,
186
+ ...(first.requiresSession
187
+ ? { entry: { requiresSession: true, ...(first.startState ? { startState: first.startState } : {}), ...(first.session ? { session: first.session } : {}) } }
188
+ : {}),
189
+ events: steps.map((s, seq) => ({ ...s, seq, ts: seq })),
190
+ };
191
+ return { run, recording, steps, starts, unproven: chain.some((f) => f.proven === false) };
192
+ }
193
+ /**
194
+ * Run a planned run: one recording for the whole plan, with lessons, and the
195
+ * outcome written onto the same run document.
196
+ */
197
+ export async function runPlan(runId, opts = {}) {
198
+ const { run, recording, steps, starts, unproven } = await recordingForPlan(runId);
199
+ const executed = await execute(recording, { ...opts, useLessons: true });
200
+ const recorded = await recordRun({
201
+ app: run.app, flow: run.plan.join('+'), plan: run.plan, goal: run.goal, mode: 'run',
202
+ result: executed.result, steps, runId: run._id, ...(unproven ? { unproven: true } : {}),
203
+ });
204
+ // Each unproven flow in a plan that passed is proven now.
205
+ const nowProven = [];
206
+ for (const [i, slug] of run.plan.entries()) {
207
+ if (await proveByRun(run.app, slug, executed.result, starts[i]))
208
+ nowProven.push(slug);
209
+ }
210
+ return { executed, recorded, plan: run.plan, nowProven };
211
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Seams: how to get from where one flow ends to where the next begins.
3
+ *
4
+ * Two flows bound for one goal often came from different recordings, so no
5
+ * recording ever went from one to the other. Three ways to bridge them, tried
6
+ * in order, cheapest first — and if none works, ASK (never guess):
7
+ *
8
+ * 1. no bridge needed the next flow opens its own page, or the first
9
+ * already ends exactly where the next starts
10
+ * 2. the page map a run once clicked something on this page that led
11
+ * to that one — click it again
12
+ * 3. navigate same site, plain address (no ids in it) — go there
13
+ *
14
+ * An agent's answer to a seam question is saved to the page map, so the same
15
+ * seam is bridged at step 2 next time without asking.
16
+ */
17
+ import type { Flow, Step } from '../store/types.js';
18
+ export type Seam = {
19
+ resolved: true;
20
+ steps: Step[];
21
+ how: string;
22
+ } | {
23
+ resolved: false;
24
+ evidence: SeamEvidence;
25
+ };
26
+ /** What the agent is shown, so it doesn't have to go digging to answer. */
27
+ export interface SeamEvidence {
28
+ from: {
29
+ slug: string;
30
+ endsOn?: string;
31
+ lastSteps: Pick<Step, 'action' | 'role' | 'name'>[];
32
+ };
33
+ to: {
34
+ slug: string;
35
+ startsOn?: string;
36
+ firstSteps: Pick<Step, 'action' | 'role' | 'name'>[];
37
+ firstUrl?: string;
38
+ };
39
+ /** Every known way out of the page `from` ends on. Empty = the page map has never left it. */
40
+ knownLinksFromHere: {
41
+ to: string;
42
+ via: {
43
+ role: string;
44
+ name: string;
45
+ };
46
+ }[];
47
+ }
48
+ export declare function resolveSeam(app: string, from: Flow, to: Flow): Promise<Seam>;
49
+ /**
50
+ * Turn an agent's seam answer into steps, and remember a one-click answer in
51
+ * the page map so the next plan doesn't need to ask. Returns the problems
52
+ * instead if the answer isn't usable.
53
+ */
54
+ export declare function acceptSeamAnswer(app: string, from: Flow, to: Flow, answer: unknown): Promise<{
55
+ steps: Step[];
56
+ } | {
57
+ problems: string[];
58
+ }>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Seams: how to get from where one flow ends to where the next begins.
3
+ *
4
+ * Two flows bound for one goal often came from different recordings, so no
5
+ * recording ever went from one to the other. Three ways to bridge them, tried
6
+ * in order, cheapest first — and if none works, ASK (never guess):
7
+ *
8
+ * 1. no bridge needed the next flow opens its own page, or the first
9
+ * already ends exactly where the next starts
10
+ * 2. the page map a run once clicked something on this page that led
11
+ * to that one — click it again
12
+ * 3. navigate same site, plain address (no ids in it) — go there
13
+ *
14
+ * An agent's answer to a seam question is saved to the page map, so the same
15
+ * seam is bridged at step 2 next time without asking.
16
+ */
17
+ import { collections } from '../store/db.js';
18
+ /** `/inventory.html#bf3dd322` → `/inventory.html` */
19
+ const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
20
+ const brief = (s) => ({ action: s.action, ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}) });
21
+ export async function resolveSeam(app, from, to) {
22
+ const first = to.steps[0];
23
+ // 1. No bridge needed.
24
+ if (first?.action === 'goto')
25
+ return { resolved: true, steps: [], how: `${to.slug} opens its own page` };
26
+ const end = from.endState;
27
+ const start = to.startState;
28
+ if (end && start && end === start)
29
+ return { resolved: true, steps: [], how: `${from.slug} ends where ${to.slug} starts` };
30
+ // 2. The page map knows a control on this page that leads there.
31
+ const { pages } = await collections();
32
+ const here = end ? await pages.findOne({ app, sig: end }) : null;
33
+ const link = start ? here?.links.find((l) => l.to === start) : undefined;
34
+ const lastUrl = from.steps.at(-1)?.url ?? from.startUrl;
35
+ if (link) {
36
+ return {
37
+ resolved: true,
38
+ steps: [{ action: 'click', role: link.via.role, name: link.via.name, url: lastUrl, resolution: 'synthesized' }],
39
+ how: `the page map: "${link.via.name}" leads from ${pageOf(end)} to ${pageOf(start)}`,
40
+ };
41
+ }
42
+ // 3. Same site, and the start page has a plain address: go straight there.
43
+ const target = start ? pageOf(start) : undefined;
44
+ if (target && !target.includes(':') && first?.url) {
45
+ const origin = new URL(lastUrl).origin;
46
+ if (new URL(first.url).origin === origin) {
47
+ const url = origin + target;
48
+ return {
49
+ resolved: true,
50
+ steps: [{ action: 'goto', value: url, url, resolution: 'synthesized' }],
51
+ how: `navigate to ${target}`,
52
+ };
53
+ }
54
+ }
55
+ return {
56
+ resolved: false,
57
+ evidence: {
58
+ from: { slug: from.slug, ...(end ? { endsOn: end } : {}), lastSteps: from.steps.slice(-3).map(brief) },
59
+ to: { slug: to.slug, ...(start ? { startsOn: start } : {}), firstSteps: to.steps.slice(0, 3).map(brief), ...(first?.url ? { firstUrl: first.url } : {}) },
60
+ knownLinksFromHere: here?.links ?? [],
61
+ },
62
+ };
63
+ }
64
+ /**
65
+ * Turn an agent's seam answer into steps, and remember a one-click answer in
66
+ * the page map so the next plan doesn't need to ask. Returns the problems
67
+ * instead if the answer isn't usable.
68
+ */
69
+ export async function acceptSeamAnswer(app, from, to, answer) {
70
+ const raw = answer?.steps;
71
+ if (!Array.isArray(raw))
72
+ return { problems: ['answer must be { "steps": [...] } — [] if you do not know'] };
73
+ const lastUrl = from.steps.at(-1)?.url ?? from.startUrl;
74
+ const steps = [];
75
+ const problems = [];
76
+ raw.forEach((s, i) => {
77
+ if (s?.action === 'click' && typeof s.role === 'string' && typeof s.name === 'string' && s.role && s.name) {
78
+ steps.push({ action: 'click', role: s.role, name: s.name, url: lastUrl, resolution: 'synthesized' });
79
+ }
80
+ else if (s?.action === 'goto' && typeof s.url === 'string' && /^https?:\/\//.test(s.url)) {
81
+ steps.push({ action: 'goto', value: s.url, url: s.url, resolution: 'synthesized' });
82
+ }
83
+ else {
84
+ problems.push(`steps[${i}] must be {"action":"click","role":"…","name":"…"} or {"action":"goto","url":"https://…"}`);
85
+ }
86
+ });
87
+ if (problems.length)
88
+ return { problems };
89
+ const only = steps[0];
90
+ if (steps.length === 1 && only?.action === 'click' && from.endState && to.startState) {
91
+ const { pages } = await collections();
92
+ const now = new Date();
93
+ await pages.updateOne({ app, sig: from.endState }, {
94
+ $addToSet: { links: { to: to.startState, via: { role: only.role, name: only.name } } },
95
+ $setOnInsert: { app, sig: from.endState, urlPattern: pageOf(from.endState), firstSeen: now, lastSeen: now },
96
+ }, { upsert: true });
97
+ }
98
+ return { steps };
99
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Connecting to MongoDB, and making sure every collection and index exists.
3
+ *
4
+ * One setting: MONGODB_URI. Local Community Edition and Atlas use the same
5
+ * driver and the same queries, so switching between them is only a change of
6
+ * connection string. MONGODB_DB picks the database name (default `understudy`).
7
+ */
8
+ import './settings.js';
9
+ import { type Db, type Collection, type Document } from 'mongodb';
10
+ import type { App, Flow, Page, Note, Finding, Run, EmbedderMeta } from './types.js';
11
+ export declare function mongoUri(): string;
12
+ /** Host only, never credentials — safe to print. */
13
+ export declare function describeUri(uri?: string): string;
14
+ export declare function connect(): Promise<Db>;
15
+ export declare function close(): Promise<void>;
16
+ /** Typed handles to the six collections. */
17
+ export declare function collections(): Promise<{
18
+ apps: Collection<App>;
19
+ flows: Collection<Flow>;
20
+ pages: Collection<Page>;
21
+ notes: Collection<Note>;
22
+ findings: Collection<Finding>;
23
+ runs: Collection<Run>;
24
+ meta: Collection<EmbedderMeta>;
25
+ }>;
26
+ /**
27
+ * Vector indexes: flows and notes are what recall searches. `app` and `kind`
28
+ * are filter fields so a search never crosses apps. The free Atlas tier allows
29
+ * three search indexes per cluster; these are two.
30
+ */
31
+ export declare const VECTOR_INDEX = "embedding";
32
+ /**
33
+ * One embedding model per database. The first time a model is configured it is
34
+ * recorded; after that, a different configured model stops everything with a clear
35
+ * message instead of silently mixing two incomparable kinds of vector.
36
+ * Returns the vector length the indexes should use.
37
+ */
38
+ export declare function checkEmbedder(): Promise<number>;
39
+ /**
40
+ * Create anything missing. Safe to call on every start: existing collections
41
+ * and indexes are left alone, and a vector index whose length no longer
42
+ * matches the model is updated in place.
43
+ */
44
+ export declare function ensureSchema(): Promise<void>;
45
+ export interface VectorIndexState {
46
+ collection: string;
47
+ status: string;
48
+ queryable: boolean;
49
+ }
50
+ export declare function vectorIndexStates(): Promise<VectorIndexState[]>;
51
+ /** Wait until both vector indexes can be queried. A new index takes ~20s locally. */
52
+ export declare function waitForVectorIndexes(timeoutMs?: number): Promise<VectorIndexState[]>;
53
+ /**
54
+ * Nearest documents to `vector` within one app. `score` is cosine similarity
55
+ * rescaled by MongoDB to 0–1, where 1 is identical.
56
+ */
57
+ export declare function vectorSearch<T extends Document>(coll: Collection<T>, app: string, vector: number[], opts?: {
58
+ limit?: number;
59
+ kind?: string;
60
+ }): Promise<(T & {
61
+ score: number;
62
+ })[]>;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Connecting to MongoDB, and making sure every collection and index exists.
3
+ *
4
+ * One setting: MONGODB_URI. Local Community Edition and Atlas use the same
5
+ * driver and the same queries, so switching between them is only a change of
6
+ * connection string. MONGODB_DB picks the database name (default `understudy`).
7
+ */
8
+ import './settings.js'; // loads settings before anything reads them
9
+ import { MongoClient } from 'mongodb';
10
+ import { embedderConfig } from './embed.js';
11
+ /** Vector length when no model has ever been configured. */
12
+ const DEFAULT_DIMS = 1024;
13
+ let client;
14
+ let db;
15
+ export function mongoUri() {
16
+ const uri = process.env.MONGODB_URI;
17
+ if (!uri) {
18
+ throw new Error('MONGODB_URI is not set. Run: understudy config set MONGODB_URI="…" ' +
19
+ '(or set it in the env block of your MCP config) — e.g. ' +
20
+ 'mongodb://localhost:27017/?directConnection=true for local Community, ' +
21
+ 'or your Atlas mongodb+srv://… string.');
22
+ }
23
+ return uri;
24
+ }
25
+ /** Host only, never credentials — safe to print. */
26
+ export function describeUri(uri = mongoUri()) {
27
+ return uri.replace(/^mongodb(\+srv)?:\/\/(?:[^@/]*@)?([^/?]+).*$/, 'mongodb$1://$2');
28
+ }
29
+ export async function connect() {
30
+ if (db)
31
+ return db;
32
+ client = new MongoClient(mongoUri(), { serverSelectionTimeoutMS: 8000 });
33
+ await client.connect();
34
+ db = client.db(process.env.MONGODB_DB ?? 'understudy');
35
+ return db;
36
+ }
37
+ export async function close() {
38
+ await client?.close();
39
+ client = undefined;
40
+ db = undefined;
41
+ }
42
+ /** Typed handles to the six collections. */
43
+ export async function collections() {
44
+ const d = await connect();
45
+ return {
46
+ apps: d.collection('apps'),
47
+ flows: d.collection('flows'),
48
+ pages: d.collection('pages'),
49
+ notes: d.collection('notes'),
50
+ findings: d.collection('findings'),
51
+ runs: d.collection('runs'),
52
+ meta: d.collection('meta'),
53
+ };
54
+ }
55
+ /** Ordinary indexes: the lookups every command does. */
56
+ const INDEXES = {
57
+ apps: [{ key: { slug: 1 }, unique: true }],
58
+ flows: [{ key: { app: 1, slug: 1 }, unique: true }],
59
+ pages: [{ key: { app: 1, sig: 1 }, unique: true }],
60
+ notes: [{ key: { app: 1, kind: 1 } }],
61
+ findings: [{ key: { app: 1, fingerprint: 1 }, unique: true }, { key: { app: 1, status: 1 } }],
62
+ runs: [{ key: { app: 1, startedAt: -1 } }],
63
+ };
64
+ /**
65
+ * Vector indexes: flows and notes are what recall searches. `app` and `kind`
66
+ * are filter fields so a search never crosses apps. The free Atlas tier allows
67
+ * three search indexes per cluster; these are two.
68
+ */
69
+ export const VECTOR_INDEX = 'embedding';
70
+ const VECTOR_COLLECTIONS = ['flows', 'notes'];
71
+ async function vectorIndexInfo(coll) {
72
+ return (await coll.listSearchIndexes(VECTOR_INDEX).toArray())[0];
73
+ }
74
+ function vectorDefinition(dims) {
75
+ return {
76
+ fields: [
77
+ { type: 'vector', path: 'embedding', numDimensions: dims, similarity: 'cosine' },
78
+ { type: 'filter', path: 'app' },
79
+ { type: 'filter', path: 'kind' },
80
+ ],
81
+ };
82
+ }
83
+ /**
84
+ * One embedding model per database. The first time a model is configured it is
85
+ * recorded; after that, a different configured model stops everything with a clear
86
+ * message instead of silently mixing two incomparable kinds of vector.
87
+ * Returns the vector length the indexes should use.
88
+ */
89
+ export async function checkEmbedder() {
90
+ const { meta } = await collections();
91
+ const cfg = embedderConfig();
92
+ const stored = await meta.findOne({ _id: 'embedder' });
93
+ if (!cfg)
94
+ return stored?.dims ?? DEFAULT_DIMS; // no model: name matching only
95
+ if (!stored) {
96
+ await meta.insertOne({ _id: 'embedder', model: cfg.model, dims: cfg.dims, setAt: new Date() });
97
+ return cfg.dims;
98
+ }
99
+ if (stored.model !== cfg.model || stored.dims !== cfg.dims) {
100
+ throw new Error(`this database was embedded with ${stored.model} (${stored.dims} numbers per vector), ` +
101
+ `but .env says ${cfg.model} (${cfg.dims}). Vectors from different models can't be compared. ` +
102
+ `Either set EMBED_MODEL back, or run \`understudy reembed\` to rebuild everything with the new model.`);
103
+ }
104
+ return cfg.dims;
105
+ }
106
+ /**
107
+ * Create anything missing. Safe to call on every start: existing collections
108
+ * and indexes are left alone, and a vector index whose length no longer
109
+ * matches the model is updated in place.
110
+ */
111
+ export async function ensureSchema() {
112
+ const d = await connect();
113
+ const dims = await checkEmbedder();
114
+ const existing = new Set((await d.listCollections({}, { nameOnly: true }).toArray()).map((c) => c.name));
115
+ for (const [name, indexes] of Object.entries(INDEXES)) {
116
+ // A search index can only be created on a collection that exists.
117
+ if (!existing.has(name))
118
+ await d.createCollection(name);
119
+ for (const ix of indexes) {
120
+ await d.collection(name).createIndex(ix.key, ix.unique ? { unique: true } : {});
121
+ }
122
+ }
123
+ for (const name of VECTOR_COLLECTIONS) {
124
+ const coll = d.collection(name);
125
+ const current = await vectorIndexInfo(coll);
126
+ const wanted = vectorDefinition(dims);
127
+ if (!current) {
128
+ await coll.createSearchIndex({ name: VECTOR_INDEX, type: 'vectorSearch', definition: wanted });
129
+ }
130
+ else if (JSON.stringify(current.latestDefinition) !== JSON.stringify(wanted)) {
131
+ await coll.updateSearchIndex(VECTOR_INDEX, wanted);
132
+ }
133
+ }
134
+ }
135
+ export async function vectorIndexStates() {
136
+ const d = await connect();
137
+ const out = [];
138
+ for (const name of VECTOR_COLLECTIONS) {
139
+ const ix = await vectorIndexInfo(d.collection(name));
140
+ out.push({ collection: name, status: ix?.status ?? 'MISSING', queryable: ix?.queryable === true });
141
+ }
142
+ return out;
143
+ }
144
+ /** Wait until both vector indexes can be queried. A new index takes ~20s locally. */
145
+ export async function waitForVectorIndexes(timeoutMs = 120_000) {
146
+ const deadline = Date.now() + timeoutMs;
147
+ for (;;) {
148
+ const states = await vectorIndexStates();
149
+ if (states.every((s) => s.queryable))
150
+ return states;
151
+ if (Date.now() > deadline) {
152
+ const stuck = states.filter((s) => !s.queryable).map((s) => `${s.collection}=${s.status}`);
153
+ throw new Error(`vector indexes not ready after ${timeoutMs / 1000}s: ${stuck.join(', ')}`);
154
+ }
155
+ await new Promise((r) => setTimeout(r, 1000));
156
+ }
157
+ }
158
+ /**
159
+ * Nearest documents to `vector` within one app. `score` is cosine similarity
160
+ * rescaled by MongoDB to 0–1, where 1 is identical.
161
+ */
162
+ export async function vectorSearch(coll, app, vector, opts = {}) {
163
+ const limit = opts.limit ?? 5;
164
+ const filter = { app };
165
+ if (opts.kind)
166
+ filter.kind = opts.kind;
167
+ return coll
168
+ .aggregate([
169
+ {
170
+ $vectorSearch: {
171
+ index: VECTOR_INDEX,
172
+ path: 'embedding',
173
+ queryVector: vector,
174
+ numCandidates: Math.max(limit * 20, 100),
175
+ limit,
176
+ filter,
177
+ },
178
+ },
179
+ { $set: { score: { $meta: 'vectorSearchScore' } } },
180
+ { $project: { embedding: 0 } },
181
+ ])
182
+ .toArray();
183
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Turning text into vectors, with any embedding model you like.
3
+ *
4
+ * Most providers speak the same format: POST `{ model, input: [texts] }` to
5
+ * `/v1/embeddings`, get back `{ data: [{ index, embedding }] }`. That covers
6
+ * Voyage, OpenAI, Mistral, Together, and local Ollama / LM Studio. So this is
7
+ * one adapter configured by four settings, not one adapter per vendor:
8
+ *
9
+ * EMBED_URL e.g. https://api.voyageai.com/v1/embeddings
10
+ * http://localhost:11434/v1/embeddings (Ollama, free, offline)
11
+ * EMBED_MODEL e.g. voyage-4-lite
12
+ * EMBED_KEY API key, if the endpoint needs one
13
+ * EMBED_DIMS vector length the model returns (default 1024)
14
+ *
15
+ * Just EMBED_KEY, and nothing else, means Voyage's voyage-4-lite — the default.
16
+ * Set none of them to run with no model at all: search
17
+ * then falls back to matching names.
18
+ */
19
+ import './settings.js';
20
+ export interface EmbedderConfig {
21
+ url: string;
22
+ model: string;
23
+ key?: string;
24
+ dims: number;
25
+ }
26
+ /** What you get with only EMBED_KEY set: Voyage's cheapest model. */
27
+ export declare const VOYAGE_DEFAULT: {
28
+ url: string;
29
+ model: string;
30
+ };
31
+ /**
32
+ * The configured embedder, or null if none is set. Only EMBED_KEY set means
33
+ * Voyage (the default); a different model needs EMBED_URL and EMBED_MODEL.
34
+ */
35
+ export declare function embedderConfig(): EmbedderConfig | null;
36
+ /**
37
+ * Voyage (directly, or through MongoDB's endpoint) embeds a search query
38
+ * differently from a stored document, and is told which by `input_type`.
39
+ * Other providers reject fields they don't know, so it is sent only to Voyage.
40
+ */
41
+ export declare function sendsInputType(url: string): boolean;
42
+ /**
43
+ * Embed many texts, in as few requests as possible. `purpose` is 'query' for
44
+ * text you search WITH and 'document' for text being stored.
45
+ */
46
+ export declare function embed(texts: string[], purpose: 'query' | 'document', cfg?: EmbedderConfig | null): Promise<number[][]>;