@flowriki/agent 0.1.0-beta.5 → 0.1.0-beta.50

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/dist/cli.js CHANGED
@@ -1,17 +1,2372 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ AGENT_LATEST_URL,
3
4
  AGENT_VERSION,
5
+ agentUpdateFor,
6
+ authenticationResolver,
7
+ checkAssertion,
8
+ closeRunSession,
4
9
  connect,
10
+ connectionFor,
11
+ dataDir,
5
12
  disconnect,
6
13
  doctor,
14
+ executeStep,
15
+ fieldNames,
16
+ helperRunner,
17
+ openRunSession,
7
18
  prepareBrowsers,
19
+ replayCase,
20
+ replayFlow,
8
21
  resolveCheckouts,
22
+ resolveService,
23
+ runtimeValue,
9
24
  start,
10
25
  status
11
- } from "./chunk-QJOMJVCO.js";
26
+ } from "./chunk-KRWHHKSS.js";
27
+ import {
28
+ CLOUD_PROVIDERS,
29
+ CLOUD_PROVIDER_NAME,
30
+ CODEBASE_TAG_NAME,
31
+ MobileLane,
32
+ RecordedStepSchema,
33
+ checkMobileAssertion,
34
+ codebaseIndexOf,
35
+ isMobile,
36
+ listDevices,
37
+ locate,
38
+ mirrorCheckTargets,
39
+ mobileDoctor,
40
+ mobileOf,
41
+ mobileSetup,
42
+ openMobileSession,
43
+ parseGherkin,
44
+ performMobileStep,
45
+ platformsOf,
46
+ replayMobileCase,
47
+ runMobileSteps,
48
+ screenLines,
49
+ stepRefusedOn,
50
+ targetFor
51
+ } from "./chunk-GLZFHC64.js";
12
52
 
13
53
  // src/cli.ts
14
54
  import { parseArgs } from "util";
55
+
56
+ // src/mcp/protocol.ts
57
+ import readline from "readline";
58
+ var PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
59
+ async function handle(message, tools, info) {
60
+ const reply = (result) => ({ jsonrpc: "2.0", id: message.id ?? null, result });
61
+ const fail = (code, text2) => ({ jsonrpc: "2.0", id: message.id ?? null, error: { code, message: text2 } });
62
+ if (message.id === void 0 || message.id === null) return null;
63
+ switch (message.method) {
64
+ case "initialize": {
65
+ const asked = String(message.params?.["protocolVersion"] ?? "");
66
+ const version = PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0];
67
+ return reply({
68
+ protocolVersion: version,
69
+ capabilities: { tools: { listChanged: true } },
70
+ serverInfo: { name: info.name, version: info.version },
71
+ instructions: info.instructions
72
+ });
73
+ }
74
+ case "ping":
75
+ return reply({});
76
+ case "tools/list":
77
+ return reply({
78
+ tools: tools.map(({ name, title, description, inputSchema, annotations }) => ({
79
+ name,
80
+ ...title ? { title } : {},
81
+ description,
82
+ inputSchema,
83
+ ...annotations ? { annotations } : {}
84
+ }))
85
+ });
86
+ case "tools/call": {
87
+ const name = String(message.params?.["name"] ?? "");
88
+ const tool = tools.find((t) => t.name === name);
89
+ if (!tool) return fail(-32602, `no tool named ${name}`);
90
+ const args = message.params?.["arguments"] ?? {};
91
+ try {
92
+ return reply(await tool.run(args));
93
+ } catch (error) {
94
+ return reply({ content: [{ type: "text", text: error.message }], isError: true });
95
+ }
96
+ }
97
+ default:
98
+ return fail(-32601, `method not found: ${message.method}`);
99
+ }
100
+ }
101
+ function serve(tools, info, io = {}) {
102
+ const input = io.input ?? process.stdin;
103
+ const output = io.output ?? process.stdout;
104
+ if (!io.output) {
105
+ console.log = console.info = console.warn = console.debug = (...args) => {
106
+ process.stderr.write(`${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
107
+ `);
108
+ };
109
+ }
110
+ const lines = readline.createInterface({ input, crlfDelay: Infinity });
111
+ const pending = /* @__PURE__ */ new Set();
112
+ lines.on("line", (line) => {
113
+ if (!line.trim()) return;
114
+ let message;
115
+ try {
116
+ message = JSON.parse(line);
117
+ } catch {
118
+ output.write(`${JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } })}
119
+ `);
120
+ return;
121
+ }
122
+ const task = handle(message, tools, info).then((answer) => {
123
+ if (answer) output.write(`${JSON.stringify(answer)}
124
+ `);
125
+ if (message.method === "notifications/initialized") {
126
+ output.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })}
127
+ `);
128
+ }
129
+ });
130
+ pending.add(task);
131
+ void task.finally(() => pending.delete(task));
132
+ });
133
+ return new Promise((resolve) => lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve())));
134
+ }
135
+
136
+ // src/mcp/service-client.ts
137
+ var ServiceClient = class {
138
+ constructor(connection, fetcher = fetch) {
139
+ this.connection = connection;
140
+ this.fetcher = fetcher;
141
+ }
142
+ connection;
143
+ fetcher;
144
+ get origin() {
145
+ return this.connection.service;
146
+ }
147
+ async call(path2, init = {}) {
148
+ const res = await this.fetcher(`${this.connection.service}${path2}`, {
149
+ ...init,
150
+ headers: {
151
+ "x-flowriki-device": this.connection.deviceId,
152
+ "x-flowriki-device-secret": this.connection.secret,
153
+ "content-type": "application/json"
154
+ }
155
+ });
156
+ const text2 = await res.text();
157
+ let body = {};
158
+ try {
159
+ body = text2 ? JSON.parse(text2) : {};
160
+ } catch {
161
+ }
162
+ if (!res.ok) {
163
+ if (res.status === 404 && !("error" in body)) {
164
+ throw new Error("the Flowriki service does not offer this yet \u2014 it may need updating");
165
+ }
166
+ throw new Error(String(body["error"] ?? `the service answered ${res.status}`));
167
+ }
168
+ return body;
169
+ }
170
+ projects() {
171
+ return this.call("/api/agent/projects");
172
+ }
173
+ createProject(name, repository, baseUrl) {
174
+ return this.call("/api/agent/projects", {
175
+ method: "POST",
176
+ body: JSON.stringify({ name, repository, ...baseUrl ? { baseUrl } : {} })
177
+ });
178
+ }
179
+ catalog(projectId) {
180
+ return this.call(`/api/agent/catalog?projectId=${encodeURIComponent(projectId)}`);
181
+ }
182
+ /** `cloud` asks for that device farm's access key too, for a flow written
183
+ * on one of its phones. */
184
+ prepare(projectId, steps, signIn, extra = {}) {
185
+ return this.call(`/api/agent/prepare?projectId=${encodeURIComponent(projectId)}`, {
186
+ method: "POST",
187
+ body: JSON.stringify({ steps, ...signIn ? { signIn } : {}, ...extra.cloud ? { cloud: extra.cloud } : {} })
188
+ });
189
+ }
190
+ /** This person's open branches that Claude wrote on this project. */
191
+ agentChanges(projectId) {
192
+ return this.call(
193
+ `/api/agent/changes?projectId=${encodeURIComponent(projectId)}`
194
+ );
195
+ }
196
+ /** Delete one — refused by the service unless it is all Claude's own,
197
+ * unedited, unpublished work. */
198
+ discardChange(projectId, changeId) {
199
+ return this.call(
200
+ `/api/agent/changes/${encodeURIComponent(changeId)}?projectId=${encodeURIComponent(projectId)}`,
201
+ { method: "DELETE" }
202
+ );
203
+ }
204
+ saveFlow(projectId, title, flow, where = {}, secretValues = {}) {
205
+ return this.call(
206
+ `/api/agent/flows?projectId=${encodeURIComponent(projectId)}`,
207
+ { method: "POST", body: JSON.stringify({ title, flow, ...where, secretValues }) }
208
+ );
209
+ }
210
+ /** A sign-in made from a recorded login flow. */
211
+ createSignIn(projectId, input) {
212
+ return this.call(
213
+ `/api/agent/sign-ins?projectId=${encodeURIComponent(projectId)}`,
214
+ { method: "POST", body: JSON.stringify(input) }
215
+ );
216
+ }
217
+ /** An account for a sign-in; secret values are sealed by the service and
218
+ * never come back. */
219
+ createAccount(projectId, input) {
220
+ return this.call(
221
+ `/api/agent/accounts?projectId=${encodeURIComponent(projectId)}`,
222
+ { method: "POST", body: JSON.stringify(input) }
223
+ );
224
+ }
225
+ /** A helper, its secrets sealed by the service. */
226
+ createHelper(projectId, input) {
227
+ return this.call(
228
+ `/api/agent/helpers?projectId=${encodeURIComponent(projectId)}`,
229
+ { method: "POST", body: JSON.stringify(input) }
230
+ );
231
+ }
232
+ /** What a new flow starts after: the flows, in run order, and their steps. */
233
+ flowsAfter(projectId, after) {
234
+ return this.call(
235
+ `/api/agent/flows/after?projectId=${encodeURIComponent(projectId)}`,
236
+ { method: "POST", body: JSON.stringify({ after }) }
237
+ );
238
+ }
239
+ /** Build a test case from flows — as a dry run, or saved. */
240
+ buildCase(projectId, spec, dryRun) {
241
+ return this.call(`/api/agent/cases?projectId=${encodeURIComponent(projectId)}`, { method: "POST", body: JSON.stringify({ ...spec, dryRun }) });
242
+ }
243
+ /** The test library, on Claude's working branch when it has one. */
244
+ library(projectId, opts = {}) {
245
+ const query = new URLSearchParams({ projectId, ...opts.q ? { q: opts.q } : {}, ...opts.featureId ? { featureId: opts.featureId } : {} });
246
+ return this.call(`/api/agent/library?${query}`);
247
+ }
248
+ /** Test cases written, edited or linked in one commit; duplicates skipped. */
249
+ importPart(projectId, draftId, part) {
250
+ return this.call(
251
+ `/api/agent/import-drafts/${encodeURIComponent(draftId)}?projectId=${encodeURIComponent(projectId)}&part=${part}`
252
+ );
253
+ }
254
+ saveImportCases(projectId, draftId, body) {
255
+ return this.call(
256
+ `/api/agent/import-drafts/${encodeURIComponent(draftId)}/cases?projectId=${encodeURIComponent(projectId)}`,
257
+ { method: "POST", body: JSON.stringify(body) }
258
+ );
259
+ }
260
+ updateRequest(projectId, id) {
261
+ return this.call(
262
+ `/api/agent/update-requests/${encodeURIComponent(id)}?projectId=${encodeURIComponent(projectId)}`
263
+ );
264
+ }
265
+ proposeUpdates(projectId, id, body) {
266
+ return this.call(
267
+ `/api/agent/update-requests/${encodeURIComponent(id)}/proposals?projectId=${encodeURIComponent(projectId)}`,
268
+ { method: "POST", body: JSON.stringify(body) }
269
+ );
270
+ }
271
+ readCases(projectId, refs) {
272
+ const ids = refs.filter((r) => /^tc_/.test(r.trim()));
273
+ const names = refs.filter((r) => !/^tc_/.test(r.trim()));
274
+ const q = new URLSearchParams({ projectId, ...ids.length ? { ids: ids.join(",") } : {}, ...names.length ? { names: names.join("|") } : {} });
275
+ return this.call(`/api/agent/cases/read?${q}`);
276
+ }
277
+ /** Test cases written down — business steps, no flows yet — on Claude's
278
+ * working branch. */
279
+ writeCases(projectId, groups, changeId) {
280
+ return this.call(
281
+ `/api/agent/cases/batch?projectId=${encodeURIComponent(projectId)}`,
282
+ { method: "POST", body: JSON.stringify({ groups, ...changeId ? { changeId } : {} }) }
283
+ );
284
+ }
285
+ saveLibrary(projectId, input) {
286
+ return this.call(`/api/agent/library?projectId=${encodeURIComponent(projectId)}`, { method: "POST", body: JSON.stringify(input) });
287
+ }
288
+ // ── Manual cycles and bugs: the dashboard's own routes, behind this
289
+ // machine's credential, so the assistant can do what a person can. ──────
290
+ scoped(path2, projectId, extra = {}) {
291
+ const query = new URLSearchParams({ projectId, ...extra });
292
+ return `/api/agent${path2}?${query}`;
293
+ }
294
+ cycles(projectId) {
295
+ return this.call(this.scoped("/cycles", projectId));
296
+ }
297
+ cycle(projectId, id) {
298
+ return this.call(this.scoped(`/cycles/${encodeURIComponent(id)}`, projectId));
299
+ }
300
+ createCycle(projectId, body, changeId) {
301
+ return this.call(this.scoped("/cycles", projectId, changeId ? { changeId } : {}), { method: "POST", body: JSON.stringify(body) });
302
+ }
303
+ updateCycle(projectId, id, body, changeId) {
304
+ return this.call(this.scoped(`/cycles/${encodeURIComponent(id)}`, projectId, changeId ? { changeId } : {}), { method: "PATCH", body: JSON.stringify(body) });
305
+ }
306
+ deleteCycle(projectId, id) {
307
+ return this.call(this.scoped(`/cycles/${encodeURIComponent(id)}`, projectId), { method: "DELETE" });
308
+ }
309
+ recordResult(projectId, id, caseId, body) {
310
+ return this.call(this.scoped(`/cycles/${encodeURIComponent(id)}/results/${encodeURIComponent(caseId)}`, projectId), { method: "PUT", body: JSON.stringify(body) });
311
+ }
312
+ addEvidenceLink(projectId, id, caseId, body) {
313
+ return this.call(this.scoped(`/cycles/${encodeURIComponent(id)}/results/${encodeURIComponent(caseId)}/evidence`, projectId), {
314
+ method: "POST",
315
+ body: JSON.stringify({ kind: "link", ...body })
316
+ });
317
+ }
318
+ bugs(projectId) {
319
+ return this.call(this.scoped("/bugs", projectId));
320
+ }
321
+ createBug(projectId, body) {
322
+ return this.call(this.scoped("/bugs", projectId), { method: "POST", body: JSON.stringify(body) });
323
+ }
324
+ updateBug(projectId, id, body) {
325
+ return this.call(this.scoped(`/bugs/${encodeURIComponent(id)}`, projectId), { method: "PATCH", body: JSON.stringify(body) });
326
+ }
327
+ // ── Knowledge, sources, requirements ──────────────────────
328
+ knowledgePages(projectId) {
329
+ return this.call(this.scoped("/knowledge", projectId));
330
+ }
331
+ knowledgePage(projectId, path2) {
332
+ return this.call(this.scoped("/knowledge/page", projectId, { path: path2 }));
333
+ }
334
+ writeKnowledge(projectId, body) {
335
+ return this.call(`/api/agent/knowledge?projectId=${encodeURIComponent(projectId)}`, { method: "POST", body: JSON.stringify(body) });
336
+ }
337
+ search(projectId, q) {
338
+ return this.call(this.scoped("/search", projectId, { q }));
339
+ }
340
+ sources(projectId) {
341
+ return this.call(this.scoped("/sources", projectId));
342
+ }
343
+ source(projectId, id) {
344
+ return this.call(this.scoped(`/sources/${encodeURIComponent(id)}`, projectId));
345
+ }
346
+ addSource(projectId, body, sourceId) {
347
+ return this.call(
348
+ this.scoped(sourceId ? `/sources/${encodeURIComponent(sourceId)}/versions` : "/sources", projectId),
349
+ { method: "POST", body: JSON.stringify(body) }
350
+ );
351
+ }
352
+ requirements(projectId, opts = {}) {
353
+ return this.call(
354
+ this.scoped("/requirements", projectId, { ...opts.sourceId ? { sourceId: opts.sourceId } : {}, ...opts.state ? { state: opts.state } : {} })
355
+ );
356
+ }
357
+ deleteSource(projectId, id) {
358
+ return this.call(this.scoped(`/sources/${encodeURIComponent(id)}`, projectId), { method: "DELETE" });
359
+ }
360
+ updateRequirement(projectId, id, body) {
361
+ return this.call(this.scoped(`/requirements/${encodeURIComponent(id)}`, projectId), { method: "PATCH", body: JSON.stringify(body) });
362
+ }
363
+ /** Gather Claude's open branches here into one. */
364
+ gatherChanges(projectId, opts = {}) {
365
+ return this.call(
366
+ `/api/agent/changes/gather?projectId=${encodeURIComponent(projectId)}`,
367
+ { method: "POST", body: JSON.stringify(opts) }
368
+ );
369
+ }
370
+ };
371
+
372
+ // src/mcp/session.ts
373
+ var MAX_TREE = 14e3;
374
+ var MAX_STEP_VIEW = 6e3;
375
+ function topLevelBlocks(tree) {
376
+ const blocks = [];
377
+ for (const line of tree.split("\n")) {
378
+ if (line.startsWith("- ") || blocks.length === 0) blocks.push([line]);
379
+ else blocks[blocks.length - 1].push(line);
380
+ }
381
+ const named = (b, kinds) => kinds.some((k) => b[0].startsWith(`- ${k}`));
382
+ return {
383
+ dialogs: blocks.filter((b) => named(b, ["dialog", "alertdialog"])).map((b) => b.join("\n")),
384
+ navigation: blocks.find((b) => named(b, ["navigation", "banner"]))?.join("\n") ?? null
385
+ };
386
+ }
387
+ var STEP_TIMEOUT_MS = 1e4;
388
+ var SECRET_WORDS = /password|passwd|pass[-_\s]?code|pwd|secret|otp|one[-_\s]?time[-_\s]?(code|pass)|security[-_\s]?(code|answer)|cvv|cvc|\bpin\b/i;
389
+ var TYPED = "typed_";
390
+ var withoutTyped = (steps) => steps.map((st) => st.secretRef?.startsWith(TYPED) ? (({ secretRef: _, ...rest }) => rest)(st) : st);
391
+ var ACTIONS = [
392
+ "click",
393
+ "dblclick",
394
+ "rightclick",
395
+ "hover",
396
+ "fill",
397
+ "select",
398
+ "check",
399
+ "press",
400
+ "navigate",
401
+ "back",
402
+ "forward",
403
+ // On a phone: a tap is a click, and these have no web equivalent.
404
+ "tap",
405
+ "longPress",
406
+ "swipe",
407
+ "scroll",
408
+ "hideKeyboard",
409
+ "launchApp",
410
+ "terminateApp",
411
+ "resetApp",
412
+ "background",
413
+ "rotate",
414
+ "permission"
415
+ ];
416
+ var isAction = (value) => ACTIONS.includes(String(value));
417
+ var LANDMARKS = /* @__PURE__ */ new Set(["main", "navigation", "banner", "contentinfo", "complementary", "search", "form", "dialog", "alertdialog", "region", "group", "list", "table", "menu", "toolbar", "tablist"]);
418
+ function scopeOf(within) {
419
+ const said = within?.trim() ?? "";
420
+ if (!said) return { scope: "" };
421
+ return LANDMARKS.has(said.toLowerCase()) ? { scope: "", scopeRole: said.toLowerCase() } : { scope: said };
422
+ }
423
+ function asLabelled(target, fields) {
424
+ const field = fields.find((f) => f.role === target.role && (f.label === target.name || f.hint === target.name));
425
+ if (!field) return target;
426
+ return {
427
+ ...target,
428
+ name: field.label,
429
+ nameFrom: "adjacent-label",
430
+ ...field.hintFrom === "name" ? {} : { candidates: [{ strategy: field.hintFrom, value: field.hint }] }
431
+ };
432
+ }
433
+ function labelTree(tree, fields) {
434
+ let out = tree;
435
+ for (const f of fields) out = out.split(`- ${f.role} ${JSON.stringify(f.hint)}`).join(`- ${f.role} ${JSON.stringify(f.label)}`);
436
+ return out;
437
+ }
438
+ function numberDuplicates(tree) {
439
+ const line = /^(\s*- )([\w-]+) "((?:[^"\\]|\\.)*)"(.*)$/;
440
+ const totals = /* @__PURE__ */ new Map();
441
+ const lines = tree.split("\n");
442
+ for (const l of lines) {
443
+ const m = line.exec(l);
444
+ if (m) totals.set(`${m[2]}|${m[3]}`, (totals.get(`${m[2]}|${m[3]}`) ?? 0) + 1);
445
+ }
446
+ const seen = /* @__PURE__ */ new Map();
447
+ return lines.map((l) => {
448
+ const m = line.exec(l);
449
+ if (!m) return l;
450
+ const key = `${m[2]}|${m[3]}`;
451
+ const total = totals.get(key) ?? 1;
452
+ if (total < 2) return l;
453
+ const at = seen.get(key) ?? 0;
454
+ seen.set(key, at + 1);
455
+ return `${l} [nth ${at} of ${total} with this name]`;
456
+ }).join("\n");
457
+ }
458
+ function deviceFrom(said, platform, devices, mobile) {
459
+ const want = said?.trim();
460
+ if (!want) return mobile?.devices[platform];
461
+ const lower = want.toLowerCase();
462
+ const mine = devices.filter((d) => d.platform === platform);
463
+ const local = mine.find((d) => d.id.toLowerCase() === lower || d.name.toLowerCase() === lower) ?? mine.find((d) => d.name.toLowerCase().includes(lower));
464
+ if (local) return { kind: "local", id: local.id, name: local.name };
465
+ const farm = /^([^:]+):\s*(.+?)(?:\s+(\d+(?:\.\d+)*))?$/.exec(want);
466
+ const provider = farm && CLOUD_PROVIDERS.find((p) => p === farm[1].trim().toLowerCase().replace(/\s+/g, "") || CLOUD_PROVIDER_NAME[p].toLowerCase() === farm[1].trim().toLowerCase());
467
+ if (farm && provider) {
468
+ if (!mobile?.cloud.some((c) => c.provider === provider)) throw new Error(`${CLOUD_PROVIDER_NAME[provider]} is not connected to this project \u2014 add it in Settings \u2192 Mobile`);
469
+ return { kind: "cloud", provider, device: farm[2].trim(), ...farm[3] ? { osVersion: farm[3] } : {} };
470
+ }
471
+ throw new Error(`no ${platform === "ios" ? "iOS" : "Android"} device called "${want}" \u2014 connected: ${mine.map((d) => d.name).join(", ") || "none"}`);
472
+ }
473
+ async function devicesSummary() {
474
+ return listDevices().catch(() => []);
475
+ }
476
+ function describeRows(rows) {
477
+ return rows.map((r) => [
478
+ `Row ${r.row}: "${r.flow}" (${r.browser})`,
479
+ ...r.checks.length ? r.checks.map((c) => ` ${c.on ? "[on] " : "[off]"} ${c.n}. ${c.check}`) : [" (no checks in this flow)"]
480
+ ].join("\n")).join("\n");
481
+ }
482
+ function describe(step) {
483
+ const target = (step.name ? `${step.role || "element"} "${step.name}"` : step.role || "") + (step.nth !== void 0 ? ` (nth ${step.nth})` : "");
484
+ const where = step.scope ? ` in "${step.scope}"` : step.scopeRole ? ` in the ${step.scopeRole}` : "";
485
+ switch (step.type) {
486
+ case "fill":
487
+ return step.secret ? `type a secret (\u2022\u2022\u2022\u2022\u2022\u2022) into ${target}${where}` : `type "${step.value}" into ${target}${where}`;
488
+ case "select":
489
+ return `choose "${step.value}" in ${target}${where}`;
490
+ case "check":
491
+ return `${step.value === "false" ? "untick" : "tick"} ${target}${where}`;
492
+ case "press":
493
+ return `press ${step.value}${target ? ` in ${target}` : ""}`;
494
+ case "navigate":
495
+ return `go to ${step.value}`;
496
+ case "back":
497
+ case "forward":
498
+ return `browser ${step.type}`;
499
+ case "assert":
500
+ return `check ${step.proposals.map((p) => `${p.kind}${p.op && p.op !== "equals" ? ` ${p.op}` : ""} "${String(p.value)}"${p.target?.name ? ` on ${p.target.role} "${p.target.name}"` : ""}`).join(", ")}`;
501
+ case "useHelper":
502
+ return `use helper ${step.name || step.helper?.helperId} \u2192 {{${step.helper?.saveAs}}}${step.helper?.then === "open" ? ", then open it" : ""}`;
503
+ case "swipe":
504
+ return `swipe ${step.value}${target ? ` on ${target}` : ""}`;
505
+ case "scroll":
506
+ return target ? `scroll to ${target}` : `scroll ${step.value}`;
507
+ case "longPress":
508
+ return `long-press ${target}${where}`;
509
+ case "hideKeyboard":
510
+ return "hide the keyboard";
511
+ case "launchApp":
512
+ return "open the app";
513
+ case "terminateApp":
514
+ return "close the app";
515
+ case "resetApp":
516
+ return "clear the app's data and open it";
517
+ case "background":
518
+ return `send the app to the background for ${step.value || 3}s`;
519
+ case "rotate":
520
+ return `rotate to ${step.value}`;
521
+ case "permission":
522
+ return `${step.value === "deny" ? "deny" : "allow"} the permission prompt`;
523
+ default:
524
+ return `${step.type} ${target}${where}`;
525
+ }
526
+ }
527
+ var AuthoringSession = class {
528
+ constructor(service, opts = {}) {
529
+ this.service = service;
530
+ this.opts = opts;
531
+ }
532
+ service;
533
+ opts;
534
+ run = null;
535
+ page = null;
536
+ /** The phone, when the flow being written runs on one. */
537
+ mobile = null;
538
+ values = /* @__PURE__ */ new Map();
539
+ resolvers = null;
540
+ lastTree = null;
541
+ /** Values typed into secret fields, by their `typed:` reference. */
542
+ typed = /* @__PURE__ */ new Map();
543
+ draft = null;
544
+ catalog = null;
545
+ /** Text going back to Claude, with every secret typed here masked — a
546
+ * password box's value is in the page's tree, and a careless form puts it
547
+ * in the address. */
548
+ redact(text2) {
549
+ let out = text2;
550
+ for (const value of this.typed.values()) {
551
+ if (value.length < 3) continue;
552
+ out = out.split(value).join("\u2022\u2022\u2022\u2022\u2022\u2022");
553
+ const encoded = encodeURIComponent(value);
554
+ if (encoded !== value) out = out.split(encoded).join("\u2022\u2022\u2022\u2022\u2022\u2022");
555
+ }
556
+ return out;
557
+ }
558
+ get open() {
559
+ return this.run !== null || this.mobile !== null;
560
+ }
561
+ requireMobile() {
562
+ if (!this.mobile || !this.draft) throw new Error("no flow is being written \u2014 call start_flow first");
563
+ return { mobile: this.mobile, draft: this.draft };
564
+ }
565
+ requireOpen() {
566
+ if (!this.run || !this.page || !this.draft) throw new Error("no flow is being written \u2014 call start_flow first");
567
+ return { page: this.page, draft: this.draft, run: this.run };
568
+ }
569
+ /** What the steps so far, plus any about to run, need from the service:
570
+ * sign-ins, helpers, and their secret values. Asked again whenever a new
571
+ * helper or sign-in appears, never kept beyond this process. */
572
+ async prepare(extra = []) {
573
+ const draft = this.draft;
574
+ const prepared = await this.service.prepare(
575
+ draft.projectId,
576
+ withoutTyped([...draft.preparation ?? [], ...draft.steps, ...extra]),
577
+ draft.signIn ?? null,
578
+ draft.device?.kind === "cloud" ? { cloud: draft.device.provider } : {}
579
+ );
580
+ const runHelper = helperRunner(prepared.helpers, prepared.secrets);
581
+ this.resolvers = {
582
+ resolveAuth: authenticationResolver(prepared.authentications),
583
+ resolveSecret: (ref) => this.typed.get(ref) ?? prepared.secrets[ref],
584
+ ...runHelper ? { runHelper } : {}
585
+ };
586
+ return this.resolvers;
587
+ }
588
+ baseUrl() {
589
+ const base = this.catalog?.baseUrl ?? "";
590
+ if (!base) throw new Error("this project has no base URL \u2014 set one in the project's settings first");
591
+ return base;
592
+ }
593
+ /** Open a browser for a new flow, signed in first if asked. */
594
+ async start(input, catalog) {
595
+ await this.close();
596
+ this.catalog = catalog;
597
+ this.draft = { ...input, steps: [] };
598
+ this.values = /* @__PURE__ */ new Map();
599
+ this.typed = /* @__PURE__ */ new Map();
600
+ this.lastTree = null;
601
+ if (isMobile(input.platform)) return this.startMobile(input.platform, catalog);
602
+ const base = this.baseUrl();
603
+ this.run = await openRunSession({ steps: [], headless: this.opts.headless ?? false });
604
+ this.page = this.run.page;
605
+ if (input.signIn) {
606
+ const resolvers = await this.prepare();
607
+ const signIn = {
608
+ id: "sign-in",
609
+ type: "signIn",
610
+ auth: { ...input.signIn, from: "loginPage" },
611
+ role: "",
612
+ name: "Sign in",
613
+ scope: "",
614
+ value: "",
615
+ secret: false,
616
+ legacySelector: "",
617
+ proposals: []
618
+ };
619
+ this.page = await executeStep(this.page, signIn, {
620
+ pages: this.run.pages,
621
+ ...resolvers,
622
+ values: this.values,
623
+ baseUrl: base,
624
+ timeoutMs: 2e4,
625
+ navigationTimeoutMs: 45e3
626
+ });
627
+ } else {
628
+ await this.page.goto(new URL(input.startPath || "/", base).href, { waitUntil: "domcontentloaded", timeout: 45e3 });
629
+ }
630
+ if (input.preparation?.length) {
631
+ const resolvers = await this.prepare(input.preparation);
632
+ for (const step of input.preparation) {
633
+ try {
634
+ this.page = await executeStep(this.page, step, {
635
+ pages: this.run.pages,
636
+ ...resolvers,
637
+ values: this.values,
638
+ baseUrl: base,
639
+ timeoutMs: 2e4,
640
+ navigationTimeoutMs: 45e3
641
+ });
642
+ } catch (error) {
643
+ throw new Error(`The flows this one starts after did not finish, at "${step.name || step.type}": ${error.message.split("\n")[0]}`);
644
+ }
645
+ }
646
+ await this.settle();
647
+ }
648
+ return this.snapshot();
649
+ }
650
+ /** The page as Claude reads it: where it is, and what is on it by role and name. */
651
+ async snapshot() {
652
+ return this.view(true);
653
+ }
654
+ /** WHAT CHANGED, after a step — not the whole page again.
655
+ *
656
+ * Every step used to answer with the full tree, which on a long storefront
657
+ * is twenty thousand characters repeated forty times to say "the box now
658
+ * has text in it". So a step answers with what it is about: an open dialog
659
+ * (with the navigation, which says who is signed in), or the lines that
660
+ * appeared and disappeared — and only after a real navigation, when most of
661
+ * the page is new, the page itself, capped. read_page is always the whole
662
+ * thing. */
663
+ async view(full) {
664
+ const { tree, head } = this.mobile ? await this.mobileTree() : await this.webTree();
665
+ const before = this.lastTree;
666
+ this.lastTree = tree;
667
+ const cap = (t, max) => t.length > max ? `${t.slice(0, max)}
668
+ \u2026 (cut \u2014 read_page shows the whole page)` : t;
669
+ if (full || before === null) return head + cap(tree, MAX_TREE);
670
+ const { dialogs, navigation } = topLevelBlocks(tree);
671
+ if (dialogs.length) {
672
+ return head + cap([...navigation ? [navigation] : [], ...dialogs].join("\n"), MAX_STEP_VIEW) + "\n(only the open dialog and the navigation \u2014 read_page shows the whole page)";
673
+ }
674
+ const was = new Set(before.split("\n"));
675
+ const now = new Set(tree.split("\n"));
676
+ const added = tree.split("\n").filter((l) => !was.has(l));
677
+ const removed = before.split("\n").filter((l) => !now.has(l));
678
+ if (added.length === 0 && removed.length === 0) return head + "(the page did not change \u2014 read_page shows it)";
679
+ if (added.length + removed.length > 120) return head + cap(tree, MAX_STEP_VIEW);
680
+ return head + [
681
+ ...navigation ? [navigation, ""] : [],
682
+ added.length ? `Appeared:
683
+ ${added.join("\n")}` : "",
684
+ removed.length ? `Gone:
685
+ ${removed.join("\n")}` : "",
686
+ "(changes since the last step \u2014 read_page shows the whole page)"
687
+ ].filter(Boolean).join("\n");
688
+ }
689
+ async webTree() {
690
+ const { page, draft } = this.requireOpen();
691
+ await page.waitForLoadState("domcontentloaded", { timeout: 1e4 }).catch(() => void 0);
692
+ const tree = numberDuplicates(labelTree(
693
+ await page.locator("body").ariaSnapshot({ timeout: 8e3 }).catch((e) => `(could not read the page: ${e.message})`),
694
+ await fieldNames(page)
695
+ ));
696
+ const title = await page.title().catch(() => "");
697
+ return { tree, head: `Page: ${page.url()}${title ? ` \u2014 "${title}"` : ""}
698
+ Steps so far: ${draft.steps.length}
699
+
700
+ ` };
701
+ }
702
+ /** Do one thing on the page, and keep it as a step if it worked. */
703
+ async act(input) {
704
+ if (this.mobile) return this.mobileAct(input);
705
+ const refused = stepRefusedOn(input.action === "tap" ? "click" : input.action, "web");
706
+ if (refused) throw new Error(refused);
707
+ const { page, draft, run } = this.requireOpen();
708
+ const navigating = input.action === "navigate" || input.action === "back" || input.action === "forward";
709
+ if (!navigating && input.action !== "press" && !(input.role && input.name)) {
710
+ throw new Error(`${input.action} needs the element's role and name, exactly as read_page shows them`);
711
+ }
712
+ if ((input.action === "fill" || input.action === "select" || input.action === "press" || input.action === "navigate") && input.value === void 0) {
713
+ throw new Error(`${input.action} needs a value`);
714
+ }
715
+ const target = navigating ? { role: "", name: "" } : asLabelled({ role: input.role ?? "", name: input.name ?? "" }, await fieldNames(page));
716
+ const secret = input.action === "fill" && (input.secret ?? (SECRET_WORDS.test(input.name ?? "") || SECRET_WORDS.test(target.name)));
717
+ const id = `s${draft.steps.length + 1}_${Date.now().toString(36)}`;
718
+ if (secret) this.typed.set(`${TYPED}${id}`, input.value ?? "");
719
+ const step = RecordedStepSchema.parse({
720
+ id,
721
+ type: input.action,
722
+ ...target,
723
+ ...scopeOf(input.within),
724
+ ...input.nth !== void 0 ? { nth: input.nth } : {},
725
+ value: secret ? "" : input.action === "check" ? input.value === "false" ? "false" : "true" : input.value ?? "",
726
+ secret,
727
+ ...secret ? { secretRef: `${TYPED}${id}` } : {},
728
+ legacySelector: "",
729
+ proposals: [],
730
+ // A path is the application's own, so the step replays on whichever
731
+ // environment the run is pointed at rather than the one written on.
732
+ ...input.action === "navigate" && input.value?.startsWith("/") ? { navigationBase: "application" } : {}
733
+ });
734
+ try {
735
+ this.page = await executeStep(page, step, {
736
+ pages: run.pages,
737
+ values: this.values,
738
+ baseUrl: this.baseUrl(),
739
+ ...this.resolvers ?? {},
740
+ resolveSecret: (ref) => this.typed.get(ref) ?? this.resolvers?.resolveSecret(ref),
741
+ timeoutMs: STEP_TIMEOUT_MS,
742
+ navigationTimeoutMs: 45e3
743
+ });
744
+ } catch (error) {
745
+ if (secret) this.typed.delete(`${TYPED}${id}`);
746
+ const said = error.message.split("\n")[0] ?? "";
747
+ const several = /strict mode violation|resolved to \d+ elements|\d+ elements match/i.test(said) ? "\nSeveral elements share this role and name. Pass nth (0 = the first, in the order read_page lists them \u2014 each shared name is marked [nth N of M]) to say which one." : "";
748
+ throw new Error(`That did not work, and was not kept: ${said}${several}
749
+
750
+ ${await this.view(false)}`);
751
+ }
752
+ await this.settle();
753
+ draft.steps.push(step);
754
+ return `Step ${draft.steps.length} kept: ${describe(step)}.
755
+
756
+ ${await this.view(false)}`;
757
+ }
758
+ /** Check something about the page now, and keep the check if it holds. */
759
+ async check(input) {
760
+ if (this.mobile) return this.mobileCheck(input);
761
+ const { page, draft } = this.requireOpen();
762
+ if ((input.kind === "heading" || input.kind === "message" || input.kind === "screen") && input.op && input.op !== "equals" && !input.role) {
763
+ throw new Error(`a ${input.kind} check without role and name matches the whole ${input.kind} \u2014 give its full text with op equals, or name the element (role + name) and use kind "text" with op ${input.op}`);
764
+ }
765
+ const assertion = RecordedStepSchema.shape.proposals.element.parse({
766
+ kind: input.kind,
767
+ value: input.value,
768
+ enabled: true,
769
+ ...input.op && input.op !== "equals" ? { op: input.op } : {},
770
+ ...input.role ? { target: { ...asLabelled({ role: input.role, name: input.name ?? "" }, await fieldNames(page)), ...scopeOf(input.within), ...input.nth !== void 0 ? { nth: input.nth } : {} } } : {}
771
+ });
772
+ const filled = (text2) => text2.replace(/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g, (_, name) => runtimeValue(this.values, name));
773
+ const expected = Array.isArray(assertion.value) ? assertion.value.map(filled) : filled(assertion.value);
774
+ try {
775
+ await checkAssertion(page, assertion.kind, expected, 5e3, { ...assertion, value: expected });
776
+ } catch (error) {
777
+ throw new Error(`That is not true of the page right now, so it was not kept: ${error.message.split("\n")[0]}`);
778
+ }
779
+ const step = RecordedStepSchema.parse(mirrorCheckTargets([{
780
+ id: `c${draft.steps.length + 1}_${Date.now().toString(36)}`,
781
+ type: "assert",
782
+ role: "",
783
+ name: "",
784
+ scope: "",
785
+ value: "",
786
+ secret: false,
787
+ legacySelector: "",
788
+ proposals: [assertion]
789
+ }])[0]);
790
+ draft.steps.push(step);
791
+ return `Step ${draft.steps.length} kept: ${describe(step)}.`;
792
+ }
793
+ /** Get a value from outside the page — an email code, a 2FA code, a text,
794
+ * an API reply — and keep the step that gets it. */
795
+ async useHelper(input) {
796
+ if (this.mobile) return this.mobileHelper(input);
797
+ const { page, draft, run } = this.requireOpen();
798
+ const helper = this.catalog?.helpers.find((h) => h.id === input.helperId || h.name.toLowerCase() === input.helperId.toLowerCase());
799
+ if (!helper) throw new Error(`no helper "${input.helperId}" \u2014 project_catalog lists them; one can be made on the Helpers screen`);
800
+ const missing = helper.inputs.filter((name) => !(input.inputs ?? {})[name]);
801
+ if (missing.length) throw new Error(`${helper.name} needs ${missing.map((n) => `{{${n}}}`).join(", ")} in inputs`);
802
+ const step = RecordedStepSchema.parse({
803
+ id: `h${draft.steps.length + 1}_${Date.now().toString(36)}`,
804
+ type: "useHelper",
805
+ role: "",
806
+ name: helper.name,
807
+ scope: "",
808
+ value: "",
809
+ secret: false,
810
+ legacySelector: "",
811
+ proposals: [],
812
+ helper: { helperId: helper.id, inputs: input.inputs ?? {}, saveAs: input.saveAs || (helper.kind === "mailbox" ? "code" : "value"), then: input.then ?? "remember" }
813
+ });
814
+ const resolvers = await this.prepare([step]);
815
+ let got = { value: "", detail: "" };
816
+ try {
817
+ this.page = await executeStep(page, step, {
818
+ pages: run.pages,
819
+ values: this.values,
820
+ baseUrl: this.baseUrl(),
821
+ ...resolvers,
822
+ timeoutMs: STEP_TIMEOUT_MS,
823
+ navigationTimeoutMs: 45e3,
824
+ onHelper: (answer) => {
825
+ got = answer;
826
+ }
827
+ });
828
+ } catch (error) {
829
+ throw new Error(`The helper did not get a value, and the step was not kept: ${error.message}`);
830
+ }
831
+ await this.settle();
832
+ draft.steps.push(step);
833
+ return `Step ${draft.steps.length} kept: ${describe(step)}. It got "${got.value}" (${got.detail}). Use {{${step.helper.saveAs}}} as the value of a later step.` + (step.helper.then === "open" ? `
834
+
835
+ ${await this.view(false)}` : "");
836
+ }
837
+ list() {
838
+ const draft = this.draft;
839
+ if (!draft) return "No flow is being written.";
840
+ const head = `"${draft.name}"${draft.signIn ? ", signed in first" : ""}, starting at ${draft.startPath}`;
841
+ if (draft.steps.length === 0) return `${head}. No steps yet.`;
842
+ return `${head}:
843
+ ${draft.steps.map((s, i) => `${i + 1}. ${describe(s)}`).join("\n")}`;
844
+ }
845
+ /** Drop a step from the draft. The browser is not wound back — replay to
846
+ * see the flow as it now stands. */
847
+ remove(number) {
848
+ const draft = this.draft;
849
+ if (!draft || !this.open) throw new Error("no flow is being written \u2014 call start_flow first");
850
+ if (!Number.isInteger(number) || number < 1 || number > draft.steps.length) throw new Error(`there is no step ${number}`);
851
+ const [gone] = draft.steps.splice(number - 1, 1);
852
+ return `Removed step ${number} (${describe(gone)}). The browser was not undone \u2014 replay_flow shows the flow as it now stands.
853
+
854
+ ${this.list()}`;
855
+ }
856
+ /** Run the whole draft from the start, in a browser of its own, the way a
857
+ * run will — the proof the steps work together, not just one at a time. */
858
+ async replay() {
859
+ if (this.mobile) return this.mobileReplay();
860
+ const { draft } = this.requireOpen();
861
+ if (draft.steps.length === 0) throw new Error("there are no steps to replay yet");
862
+ const resolvers = await this.prepare();
863
+ const steps = [
864
+ ...draft.signIn ? [RecordedStepSchema.parse({ id: "sign-in", type: "signIn", auth: { ...draft.signIn, from: "loginPage" }, role: "", name: "Sign in", scope: "", value: "", secret: false, legacySelector: "", proposals: [] })] : [],
865
+ ...draft.preparation ?? [],
866
+ ...draft.steps
867
+ ];
868
+ const outcome = await replayFlow({ steps, baseUrl: this.baseUrl(), startPath: draft.startPath, headless: true, ...resolvers });
869
+ const lines = outcome.steps.map((s) => `${s.status === "passed" ? "\u2713" : s.status === "failed" ? "\u2717" : "\xB7"} ${s.name || s.type}${s.status === "failed" && s.detail ? ` \u2014 ${s.detail}` : ""}`);
870
+ return `${outcome.status === "passed" ? "The whole flow passed from the start." : `The flow ${outcome.status}${outcome.error ? `: ${outcome.error}` : ""}.`}
871
+ ${lines.join("\n")}`;
872
+ }
873
+ /** Save the draft as a flow on a new branch, for a person to review. */
874
+ async save(title, where = {}) {
875
+ const draft = this.draft;
876
+ if (!draft || !this.open) throw new Error("no flow is being written \u2014 call start_flow first");
877
+ if (draft.steps.length === 0) throw new Error("there are no steps to save yet");
878
+ if (!draft.steps.some((s) => s.type === "assert" || s.proposals.length > 0)) {
879
+ throw new Error("the flow checks nothing \u2014 add at least one check (add_check) that proves it worked, then save");
880
+ }
881
+ const checksOff = draft.steps.map((step) => step.type === "assert" ? { ...step, proposals: step.proposals.map((p) => ({ ...p, enabled: false })) } : step);
882
+ const checkCount = checksOff.filter((step) => step.type === "assert").length;
883
+ const secretValues = {};
884
+ for (const step of checksOff) {
885
+ const value = step.secretRef ? this.typed.get(step.secretRef) : void 0;
886
+ if (value !== void 0) secretValues[step.id] = value;
887
+ }
888
+ const saved = await this.service.saveFlow(draft.projectId, title || "Tests written with Claude", {
889
+ name: draft.name,
890
+ ...draft.featureId ? { featureId: draft.featureId } : { featureName: draft.featureName },
891
+ startPath: draft.startPath,
892
+ ...isMobile(draft.platform) ? { platform: draft.platform } : {},
893
+ steps: withoutTyped(checksOff),
894
+ ...draft.signIn ? { signIn: draft.signIn } : {},
895
+ ...draft.after?.length ? { prerequisites: draft.after.map((a) => ({ flowId: a.flowId })) } : {}
896
+ }, where, secretValues);
897
+ const review = `${this.service.origin}/projects/${draft.projectId}/changes/${saved.changeId}`;
898
+ const what = saved.replaced ? `Replaced the earlier "${draft.name}"` : `Saved "${draft.name}"`;
899
+ const sealed = Object.keys(secretValues).length;
900
+ const vault = sealed ? ` ${sealed} secret value${sealed === 1 ? " was" : "s were"} put in the project's vault, not the flow.` : "";
901
+ const where_ = saved.newBranch ? `on a new branch, ${saved.branch}` : `on Claude's working branch, ${saved.branch}`;
902
+ const others = await this.service.agentChanges(draft.projectId).then((r) => r.changes.filter((c) => c.id !== saved.changeId)).catch(() => []);
903
+ const note = others.length ? `
904
+ Claude has ${others.length} other open branch${others.length === 1 ? "" : "es"} on this project \u2014 gather_branches puts them into this one, for one review.` : "";
905
+ const after = draft.after?.length ? ` It starts after ${draft.after.map((a) => `"${a.name}"`).join(", ")}.` : "";
906
+ return `${what} ${where_}.${after}${vault} Its ${checkCount} check${checkCount === 1 ? " is" : "s are"} saved switched off \u2014 a test case switches on the ones it is about. Nothing is published yet.
907
+ Review and publish it here: ${review}${note}`;
908
+ }
909
+ /** A test case built from flows, without saving: its rows and every check,
910
+ * numbered, with which are on — what save_case's `checks` refer to. */
911
+ async previewCase(projectId, spec) {
912
+ const built = await this.service.buildCase(projectId, spec, true);
913
+ return `"${spec.name}" in ${spec.folder} would be:
914
+ ${describeRows(built.rows)}`;
915
+ }
916
+ /** RUN THE CASE, THEN SAVE IT. Built as a dry run, replayed in a fresh
917
+ * browser exactly as a test run does it, and saved onto Claude's working
918
+ * branch only when every row passed. */
919
+ async saveCase(projectId, spec, catalog) {
920
+ const built = await this.service.buildCase(projectId, spec, true);
921
+ const testCase = built.testCase;
922
+ const steps = testCase.occurrences.flatMap((o) => o.steps);
923
+ const prepared = await this.service.prepare(projectId, steps, null);
924
+ const runHelper = helperRunner(prepared.helpers, prepared.secrets);
925
+ const base = catalog.baseUrl;
926
+ const phoneRows = testCase.occurrences.filter((o) => isMobile(o.platform));
927
+ if (!base && phoneRows.length < testCase.occurrences.length) throw new Error("this project has no base URL \u2014 set one in the project's settings first");
928
+ const laneOptions = {
929
+ mobile: catalog.mobile ?? mobileOf(null),
930
+ resolveSecret: (ref) => prepared.secrets[ref],
931
+ resolveAuth: authenticationResolver(prepared.authentications),
932
+ ...runHelper ? { runHelper } : {}
933
+ };
934
+ const lane = phoneRows.length ? new MobileLane(laneOptions) : null;
935
+ const opened = /* @__PURE__ */ new Set();
936
+ const outcome = phoneRows.length === testCase.occurrences.length ? await replayMobileCase({ ...laneOptions, occurrences: testCase.occurrences, ...testCase.defaultActorId ? { defaultActorId: testCase.defaultActorId } : {} }) : await replayCase({
937
+ ...lane ? {
938
+ runElsewhere: (occurrence, ctx) => {
939
+ if (!isMobile(occurrence.platform)) return null;
940
+ const key = occurrence.actorId ?? testCase.defaultActorId ?? "default";
941
+ const first = !opened.has(key);
942
+ opened.add(key);
943
+ return lane.run(occurrence, { deviceKey: key, first, ...ctx });
944
+ }
945
+ } : {},
946
+ occurrences: testCase.occurrences,
947
+ ...testCase.actors ? { actors: testCase.actors } : {},
948
+ ...testCase.defaultActorId ? { defaultActorId: testCase.defaultActorId } : {},
949
+ baseUrl: base,
950
+ headless: true,
951
+ resolveAuth: authenticationResolver(prepared.authentications),
952
+ resolveSecret: (ref) => prepared.secrets[ref],
953
+ ...runHelper ? { runHelper } : {}
954
+ }).finally(() => lane?.close());
955
+ const lines = outcome.occurrences.map((o, i) => {
956
+ const failed = o.steps.find((st) => st.status === "failed");
957
+ const why = o.status === "failed" ? `: ${failed ? `step "${failed.name || failed.type}" \u2014 ${(failed.detail ?? "").split("\n")[0]}` : (o.error ?? "").split("\n")[0]}` : "";
958
+ return `${o.status === "passed" ? "\u2713" : o.status === "failed" ? "\u2717" : "\xB7"} row ${i + 1} \u2014 ${o.name}${why}`;
959
+ });
960
+ if (outcome.status !== "passed") {
961
+ return `The case did not pass, so it was NOT saved.
962
+ ${lines.join("\n")}
963
+
964
+ ${describeRows(built.rows)}`;
965
+ }
966
+ const saved = await this.service.buildCase(projectId, spec, false);
967
+ const review = `${this.service.origin}${saved.path}`;
968
+ return `The case passed from the start${saved.replaced ? " and replaced the earlier version" : ""}, and is saved on ${saved.newBranch ? "a new branch" : "Claude's working branch"}. Nothing is published yet.
969
+ ${lines.join("\n")}
970
+ Review and publish it here: ${review}`;
971
+ }
972
+ async close() {
973
+ const run = this.run;
974
+ const mobile = this.mobile;
975
+ this.run = null;
976
+ this.page = null;
977
+ this.mobile = null;
978
+ this.resolvers = null;
979
+ if (mobile) await mobile.close().catch(() => void 0);
980
+ if (run) await closeRunSession(run, { passed: true }).catch(() => void 0);
981
+ }
982
+ // ── On a phone ────────────────────────────────────────────────────────
983
+ /** Open the project's app on the chosen phone, signed in and brought to
984
+ * where the flow starts, as on the web. */
985
+ async startMobile(platform, catalog) {
986
+ const draft = this.draft;
987
+ const mobile = catalog.mobile;
988
+ if (!mobile) throw new Error("this project has no phone apps set up \u2014 turn on Android or iOS in Settings \u2192 Mobile");
989
+ const resolvers = draft.signIn || draft.device?.kind === "cloud" ? await this.prepare() : null;
990
+ this.mobile = await openMobileSession({
991
+ platform,
992
+ mobile,
993
+ ...catalog.runWhere ? { where: catalog.runWhere[platform] } : {},
994
+ ...draft.device ? { device: draft.device } : {},
995
+ ...resolvers ? { resolveSecret: resolvers.resolveSecret } : {}
996
+ });
997
+ const opening = [
998
+ ...draft.signIn ? [RecordedStepSchema.parse({ id: "sign-in", type: "signIn", auth: draft.signIn, role: "", name: "Sign in", scope: "", value: "", secret: false, legacySelector: "", proposals: [] })] : [],
999
+ ...draft.preparation ?? []
1000
+ ];
1001
+ if (/^[a-z][\w+.-]*:\/\//i.test(draft.startPath)) await this.mobile.openLink(draft.startPath);
1002
+ if (opening.length) {
1003
+ const ready = await this.prepare(draft.preparation ?? []);
1004
+ const done = await runMobileSteps(this.mobile, opening, { values: this.values, ...ready });
1005
+ if (done.status !== "passed") throw new Error(`The app could not be brought to where this flow starts: ${done.error}`);
1006
+ }
1007
+ return this.snapshot();
1008
+ }
1009
+ async mobileTree() {
1010
+ const { mobile, draft } = this.requireMobile();
1011
+ mobile.changed();
1012
+ let screen = await mobile.screen();
1013
+ if (screen.nodes.length === 0) screen = await mobile.settle(8e3);
1014
+ const where = await mobile.currentScreenName();
1015
+ const tree = numberDuplicates(screenLines(screen)) || "(nothing on the screen can be read \u2014 the app may still be loading, or draws without accessibility labels)";
1016
+ return { tree, head: `Screen: ${screen.app || mobile.appId} on ${mobile.deviceName}${where ? ` \u2014 ${where}` : ""}
1017
+ Steps so far: ${draft.steps.length}
1018
+
1019
+ ` };
1020
+ }
1021
+ mobileResolvers() {
1022
+ return {
1023
+ values: this.values,
1024
+ ...this.resolvers ?? {},
1025
+ resolveSecret: (ref) => this.typed.get(ref) ?? this.resolvers?.resolveSecret(ref)
1026
+ };
1027
+ }
1028
+ async mobileAct(input) {
1029
+ const { mobile, draft } = this.requireMobile();
1030
+ const type = input.action === "tap" ? "click" : input.action;
1031
+ const refused = stepRefusedOn(type, mobile.platform);
1032
+ if (refused) throw new Error(refused);
1033
+ const needsElement = ["click", "longPress", "fill", "select", "check"].includes(type);
1034
+ if (needsElement && !(input.role && (input.name || input.nth !== void 0))) {
1035
+ throw new Error(`${input.action} needs the element's role and name, exactly as read_page shows them`);
1036
+ }
1037
+ if ((type === "fill" || type === "select" || type === "navigate") && input.value === void 0) throw new Error(`${input.action} needs a value`);
1038
+ let target = { role: "", name: "" };
1039
+ let password = false;
1040
+ if (input.role) {
1041
+ const asked = { role: input.role, name: input.name ?? "", ...scopeOf(input.within), ...input.nth !== void 0 ? { nth: input.nth } : {} };
1042
+ try {
1043
+ const found = await locate(mobile, asked, STEP_TIMEOUT_MS, { scroll: type !== "swipe" });
1044
+ target = { ...targetFor(found.screen, found.node), ...asked };
1045
+ password = found.node.password;
1046
+ } catch (error) {
1047
+ const said = error.message.split("\n")[0] ?? "";
1048
+ const several = /elements match/.test(said) ? "\nSeveral elements share this role and name. Pass nth (0 = the first, in the order read_page lists them) to say which one." : "";
1049
+ throw new Error(`That did not work, and was not kept: ${said}${several}
1050
+
1051
+ ${await this.view(false)}`);
1052
+ }
1053
+ }
1054
+ const secret = type === "fill" && (input.secret ?? (password || SECRET_WORDS.test(input.name ?? "")));
1055
+ const id = `s${draft.steps.length + 1}_${Date.now().toString(36)}`;
1056
+ if (secret) this.typed.set(`${TYPED}${id}`, input.value ?? "");
1057
+ const value = secret ? "" : type === "check" ? input.value === "false" ? "false" : "true" : type === "swipe" || type === "scroll" && !input.role ? (input.value || "up").toLowerCase() : input.value ?? "";
1058
+ const step = RecordedStepSchema.parse({
1059
+ id,
1060
+ type,
1061
+ ...target,
1062
+ value,
1063
+ secret,
1064
+ ...secret ? { secretRef: `${TYPED}${id}` } : {},
1065
+ legacySelector: "",
1066
+ proposals: []
1067
+ });
1068
+ try {
1069
+ await performMobileStep(mobile, step, this.mobileResolvers());
1070
+ } catch (error) {
1071
+ if (secret) this.typed.delete(`${TYPED}${id}`);
1072
+ throw new Error(`That did not work, and was not kept: ${error.message.split("\n")[0]}
1073
+
1074
+ ${await this.view(false)}`);
1075
+ }
1076
+ await new Promise((r) => setTimeout(r, 600));
1077
+ draft.steps.push(step);
1078
+ return `Step ${draft.steps.length} kept: ${describe(step)}.
1079
+
1080
+ ${await this.view(false)}`;
1081
+ }
1082
+ async mobileCheck(input) {
1083
+ const { mobile, draft } = this.requireMobile();
1084
+ if (input.kind === "url" || input.kind === "title") throw new Error(`a phone app has no ${input.kind === "url" ? "address" : "page title"} \u2014 check text on the screen (message), a heading's text, or an element`);
1085
+ const assertion = RecordedStepSchema.shape.proposals.element.parse({
1086
+ kind: input.kind,
1087
+ value: input.value,
1088
+ enabled: true,
1089
+ ...input.op && input.op !== "equals" ? { op: input.op } : {},
1090
+ ...input.role ? { target: { role: input.role, name: input.name ?? "", ...scopeOf(input.within), ...input.nth !== void 0 ? { nth: input.nth } : {} } } : {}
1091
+ });
1092
+ const filled = (text2) => text2.replace(/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g, (_, name) => runtimeValue(this.values, name));
1093
+ const expected = Array.isArray(assertion.value) ? assertion.value.map(filled) : filled(assertion.value);
1094
+ try {
1095
+ await checkMobileAssertion(mobile, { ...assertion, value: expected }, 5e3);
1096
+ } catch (error) {
1097
+ throw new Error(`That is not true of the screen right now, so it was not kept: ${error.message.split("\n")[0]}`);
1098
+ }
1099
+ const step = RecordedStepSchema.parse(mirrorCheckTargets([{
1100
+ id: `c${draft.steps.length + 1}_${Date.now().toString(36)}`,
1101
+ type: "assert",
1102
+ role: "",
1103
+ name: "",
1104
+ scope: "",
1105
+ value: "",
1106
+ secret: false,
1107
+ legacySelector: "",
1108
+ proposals: [assertion]
1109
+ }])[0]);
1110
+ draft.steps.push(step);
1111
+ return `Step ${draft.steps.length} kept: ${describe(step)}.`;
1112
+ }
1113
+ async mobileHelper(input) {
1114
+ const { mobile, draft } = this.requireMobile();
1115
+ const helper = this.catalog?.helpers.find((h) => h.id === input.helperId || h.name.toLowerCase() === input.helperId.toLowerCase());
1116
+ if (!helper) throw new Error(`no helper "${input.helperId}" \u2014 project_catalog lists them; one can be made on the Helpers screen`);
1117
+ const missing = helper.inputs.filter((name) => !(input.inputs ?? {})[name]);
1118
+ if (missing.length) throw new Error(`${helper.name} needs ${missing.map((n) => `{{${n}}}`).join(", ")} in inputs`);
1119
+ const step = RecordedStepSchema.parse({
1120
+ id: `h${draft.steps.length + 1}_${Date.now().toString(36)}`,
1121
+ type: "useHelper",
1122
+ role: "",
1123
+ name: helper.name,
1124
+ scope: "",
1125
+ value: "",
1126
+ secret: false,
1127
+ legacySelector: "",
1128
+ proposals: [],
1129
+ helper: { helperId: helper.id, inputs: input.inputs ?? {}, saveAs: input.saveAs || (helper.kind === "mailbox" ? "code" : "value"), then: input.then ?? "remember" }
1130
+ });
1131
+ await this.prepare([step]);
1132
+ let got;
1133
+ try {
1134
+ got = await performMobileStep(mobile, step, this.mobileResolvers());
1135
+ } catch (error) {
1136
+ throw new Error(`The helper did not get a value, and the step was not kept: ${error.message}`);
1137
+ }
1138
+ draft.steps.push(step);
1139
+ return `Step ${draft.steps.length} kept: ${describe(step)}. It got "${got?.value ?? ""}" (${got?.detail ?? ""}). Use {{${step.helper.saveAs}}} as the value of a later step.` + (step.helper.then === "open" ? `
1140
+
1141
+ ${await this.view(false)}` : "");
1142
+ }
1143
+ /** The whole flow again from the app's start, on the same phone — a phone
1144
+ * holds one session at a time, so the app is closed and opened rather than
1145
+ * a second device started. */
1146
+ async mobileReplay() {
1147
+ const { mobile, draft } = this.requireMobile();
1148
+ if (draft.steps.length === 0) throw new Error("there are no steps to replay yet");
1149
+ const resolvers = await this.prepare();
1150
+ const steps = [
1151
+ ...draft.signIn ? [RecordedStepSchema.parse({ id: "sign-in", type: "signIn", auth: draft.signIn, role: "", name: "Sign in", scope: "", value: "", secret: false, legacySelector: "", proposals: [] })] : [],
1152
+ ...draft.preparation ?? [],
1153
+ ...draft.steps
1154
+ ];
1155
+ await mobile.terminateApp().catch(() => void 0);
1156
+ await mobile.launchApp();
1157
+ await mobile.settle();
1158
+ if (/^[a-z][\w+.-]*:\/\//i.test(draft.startPath)) await mobile.openLink(draft.startPath);
1159
+ const outcome = await runMobileSteps(mobile, steps, { values: /* @__PURE__ */ new Map(), ...resolvers, resolveSecret: (ref) => this.typed.get(ref) ?? resolvers.resolveSecret(ref) });
1160
+ this.lastTree = null;
1161
+ const lines = outcome.results.map((s) => `${s.status === "passed" ? "\u2713" : s.status === "failed" ? "\u2717" : "\xB7"} ${s.name || s.type}${s.status === "failed" && s.detail ? ` \u2014 ${s.detail}` : ""}`);
1162
+ return `${outcome.status === "passed" ? "The whole flow passed from the app's start." : `The flow ${outcome.status}${outcome.error ? `: ${outcome.error}` : ""}.`}
1163
+ ${lines.join("\n")}`;
1164
+ }
1165
+ /** Let a click's consequences land before the page is read again. */
1166
+ async settle() {
1167
+ const page = this.page;
1168
+ if (!page) return;
1169
+ await page.waitForLoadState("domcontentloaded", { timeout: 1e4 }).catch(() => void 0);
1170
+ await page.waitForTimeout(300);
1171
+ }
1172
+ };
1173
+
1174
+ // src/mcp/tools.ts
1175
+ var INSTRUCTIONS = `Flowriki tools write UI tests by driving a real browser on this computer.
1176
+ Every step you take is performed first and kept only if it worked, so what you
1177
+ save already ran once. Everything goes to ONE working branch per project that a
1178
+ person reviews and publishes in the Flowriki dashboard \u2014 nothing you do is
1179
+ published.
1180
+
1181
+ A new project \u2014 "set up Flowriki for this site, in this repository" \u2014 is made
1182
+ with create_project; it then becomes the project the other tools work on.
1183
+
1184
+ THE MODEL \u2014 get this right before recording anything:
1185
+ - A FLOW is a reusable building block: one piece of a journey ("Open the account
1186
+ dialog", "Fill the sign-up form", "Sign in with a wrong password"). A flow can
1187
+ START AFTER other flows (start_flow's "after"), so it holds only its own new
1188
+ steps and links to the ones before it. A path that behaves differently \u2014 a
1189
+ wrong password, a duplicate email \u2014 is its own flow, because the page does
1190
+ something different.
1191
+ - A flow records checks (add_check) that prove each thing happened, but they
1192
+ are SAVED SWITCHED OFF: which ones matter depends on the test.
1193
+ - A TEST CASE is the test. It strings flows together as rows (in the same
1194
+ browser, or a new one for a second person) and switches on the checks it is
1195
+ about. Build it with preview_case, then save_case \u2014 which runs it first.
1196
+ - A test case can be WRITTEN BEFORE IT IS AUTOMATED: business steps (Given /
1197
+ When / Then) and no flows \u2014 imported from a spreadsheet, or written with
1198
+ write_test_cases. To automate one, record the flows its steps need, then
1199
+ save_case with the SAME name in the SAME folder: that fills it, and its
1200
+ business steps stay. Its Then lines are the checks to switch on.
1201
+ - SIGN-IN is shared setup: a flow or case that needs somebody signed in uses a
1202
+ sign-in profile from the catalog (start_flow's signIn), never typed login steps.
1203
+ None yet? Make it: record the login as a flow that ends with a check proving
1204
+ it worked (the account menu, a heading, the URL), then create_sign_in from it
1205
+ and create_account for each person who signs in (a customer, an admin). The
1206
+ login flow types into its fields; the account supplies the values.
1207
+ - HELPERS (an inbox for email codes, an authenticator, SMS, an API call) are made
1208
+ with create_helper when the catalog has none that fits.
1209
+ - SEVERAL ELEMENTS WITH THE SAME NAME (two "Proceed to Checkout" buttons, twelve
1210
+ "Select & Customize") are told apart by POSITION, like an XPath index: read_page
1211
+ marks each one [nth N of M], and act / add_check take nth (0 = the first). Use it
1212
+ as soon as a name is shared \u2014 there is no need to look for another way round.
1213
+ - PASSWORDS AND KEYS never go into a flow or a reply. Typed into a password
1214
+ field, a value is kept as a secret and saved to the project's vault; given to
1215
+ create_account or create_helper, it is sealed there too and never shown back.
1216
+ Only use credentials the person gave you or that the app itself shows for
1217
+ testing (a demo login) \u2014 never guess or reuse anyone's real password.
1218
+ - FOLDERS do not nest. Name each one after the product area and what is in it,
1219
+ the way a tester would look for it \u2014 "Account \u2013 Sign up", "Account \u2013 Sign in",
1220
+ "Ordering \u2013 Pizza builder", "Checkout \u2013 Payment". Flows (features) and the
1221
+ cases built from them use the same names. Keep one area per folder.
1222
+
1223
+ KNOWLEDGE: project_brief is the project's memory \u2014 read it first. Search the
1224
+ knowledge pages with knowledge_search; read one with knowledge_read.
1225
+ product.md is "About the product": the person's own description of
1226
+ the product, in their words, as long as they like \u2014 read it first. Beside it,
1227
+ product/web.md, product/android.md and product/ios.md hold what is particular
1228
+ to that platform's app, when the project tests more than one. They
1229
+ write them, often with you in a conversation beside it; propose text there and
1230
+ let them decide, rather than writing product pages unless they ask you to.
1231
+ A linked codebase folder is learned into
1232
+ codebase/<folder>.md, which must start "# <folder>", then "Commit: <full sha>"
1233
+ and "Learned: <yyyy-mm-dd>" lines: that is how the Knowledge screen shows it
1234
+ as learned. codebase.json says which platform's code each folder holds (Web,
1235
+ Android, iOS, Mobile, All combined, Other): read the web folder's page for a
1236
+ website test and the phone folder's for an app test. Keep what you learn with write_knowledge (features/<name>.md,
1237
+ memory/decisions.md, a session summary), on Claude's branch for review \u2014
1238
+ never a password, key or token.
1239
+
1240
+ UPDATING TEST CASES: when asked to update test cases (upd_\u2026), read the
1241
+ request with read_update_request, then propose_case_updates with each changed
1242
+ case's complete new steps \u2014 keep what the change does not touch word for
1243
+ word, so the person sees exactly what moved. Leave out cases that need no
1244
+ change. You never change a test case yourself; the person accepts.
1245
+
1246
+ CONVERTING A SPREADSHEET: when asked to convert an import (imp_\u2026), read
1247
+ every part with read_import_file, then save_import_cases in batches. Group
1248
+ cases into features by product area (a sheet or section usually is one). Each
1249
+ case is one scenario: name it after what it proves. Steps: preconditions and
1250
+ setup as Given; ONE action per When / And \u2014 split steps that do several
1251
+ things; each expected result as Then / And, after the action it follows.
1252
+ Keep every case and every step's meaning, and its id from the file in row \u2014
1253
+ that id is how a later import of the same file knows the case is already
1254
+ there; never invent a step or drop one. A case found in several sheets is
1255
+ converted once. Use the project's existing feature names (project_catalog)
1256
+ when a case belongs in one, rather than a new look-alike. Rows that are not test cases (titles,
1257
+ notes, empty) are left out. Say in note what you could not convert.
1258
+
1259
+ PHONE APPS (Android, iOS): a project can test its Android and iOS apps as well
1260
+ as, or instead of, a website \u2014 project_catalog says which, names the app, and
1261
+ lists the phones connected to this computer. start_flow with platform
1262
+ "android" or "ios" opens the app on a phone (device: a name from the catalog,
1263
+ "BrowserStack: Samsung Galaxy S23", or nothing for whatever is connected).
1264
+ read_page then reads the SCREEN as roles and names, just like a page, and act
1265
+ and add_check work the same way. On a phone: tap (= click) a button, fill a
1266
+ textbox, swipe up/down/left/right (value; on an element, or the screen), scroll
1267
+ to an element (role + name) or by direction, longPress, back (Android only),
1268
+ hideKeyboard, permission (value "allow" or "deny") for a system prompt, and
1269
+ launchApp / terminateApp / resetApp / background (value: seconds) / rotate
1270
+ (value: portrait or landscape). navigate opens a deep link. Never tap by
1271
+ position \u2014 use the role and name; [id=\u2026] on a line is the app's own id for it,
1272
+ and is used automatically. A phone app has no URL or page title: check a
1273
+ message (text on the screen), an element's text, or that something is visible.
1274
+ The app keeps its data between runs unless the project says otherwise, so a
1275
+ sign-in step is skipped when the app is already signed in. A test case can
1276
+ mix rows on a phone with rows in a browser (a customer orders in the app, an
1277
+ admin approves on the website).
1278
+
1279
+ HOW TO WORK:
1280
+ 1. Call project_catalog. Reuse what exists \u2014 published, and on Claude's working
1281
+ branch \u2014 rather than writing it again.
1282
+ 2. Before recording, say the plan to the person: the folders, the building-block
1283
+ flows (and what each starts after), and the test cases (rows + what each
1284
+ checks). Then record the blocks, earliest first.
1285
+ 3. Record with start_flow (pass "after" for the flows it continues from), read
1286
+ the page with read_page, and act using the role and name EXACTLY as the page
1287
+ shows them. If a name appears more than once, pass "within" with the name of
1288
+ the region, dialog or form \u2014 or "dialog" / "navigation".
1289
+ 4. For things outside the page \u2014 an emailed code or link, an authenticator
1290
+ code, a text message, an API call \u2014 use use_helper with a helper from the
1291
+ catalog, then type {{its saveAs name}} into the field that needs it.
1292
+ 5. Add checks for what each step proves (a heading, a message, a value, the
1293
+ URL). replay_flow, then save_flow. A flow must record at least one check.
1294
+ 6. Build each test case: preview_case lists its rows and every check, numbered;
1295
+ save_case with the numbers to switch on runs the whole case and saves it only
1296
+ if it passed. Give the person the review link.
1297
+ 7. Saving the same name again replaces it on the working branch. Old branches
1298
+ of yours? gather_branches puts them into one; discard_branch deletes one \u2014
1299
+ only after the person asks or agrees.
1300
+ Test data you invent (a new user's email or password for a sign-up) is fine to
1301
+ type. For anything that must be NEW on every run \u2014 a sign-up's email or
1302
+ username \u2014 use {{unique}}: it is different on every run and the same within
1303
+ one, e.g. qa+{{unique}}@ the domain of the project's mailbox helper, so the
1304
+ helper can read that address's verification email with {"email": "qa+{{unique}}@\u2026"}.
1305
+ A test that types a fixed new email passes once and fails every run after.`;
1306
+ var CASE_INPUT = {
1307
+ type: "object",
1308
+ properties: {
1309
+ name: { type: "string", description: 'The test case: the scenario it proves, e.g. "Wrong password is refused".' },
1310
+ folder: { type: "string", description: 'The case folder \u2014 area and topic, e.g. "Account \u2013 Sign in". Made if new.' },
1311
+ description: { type: "string" },
1312
+ rows: {
1313
+ type: "array",
1314
+ description: "The flows to run, in order. Each row runs in the same browser as the row above unless newBrowser is true (a second person).",
1315
+ items: {
1316
+ type: "object",
1317
+ properties: {
1318
+ flow: { type: "string", description: "A flow's name or id from project_catalog." },
1319
+ newBrowser: { type: "boolean" },
1320
+ checks: {
1321
+ description: `Which of this row's checks to switch on: their numbers from preview_case, or "all". The rest stay off.`,
1322
+ anyOf: [{ type: "array", items: { type: "number" } }, { type: "string", enum: ["all"] }]
1323
+ }
1324
+ },
1325
+ required: ["flow"],
1326
+ additionalProperties: false
1327
+ }
1328
+ },
1329
+ branch: { type: "string", description: "Optional: save onto this branch (chg_\u2026) instead of the working one." },
1330
+ projectId: { type: "string" }
1331
+ },
1332
+ required: ["name", "folder", "rows"],
1333
+ additionalProperties: false
1334
+ };
1335
+ var caseSpec = (args) => ({
1336
+ name: String(args["name"] ?? ""),
1337
+ folder: String(args["folder"] ?? ""),
1338
+ ...args["description"] ? { description: String(args["description"]) } : {},
1339
+ rows: Array.isArray(args["rows"]) ? args["rows"] : [],
1340
+ ...args["branch"] ? { changeId: String(args["branch"]) } : {}
1341
+ });
1342
+ var text = (value, isError = false) => ({ content: [{ type: "text", text: value }], ...isError ? { isError } : {} });
1343
+ var str = (value) => typeof value === "string" ? value : value === void 0 || value === null ? void 0 : String(value);
1344
+ function authoringTools(service, session) {
1345
+ let defaultProject = null;
1346
+ const catalogs = /* @__PURE__ */ new Map();
1347
+ const projectFor = async (asked) => {
1348
+ const named = str(asked);
1349
+ if (named) return defaultProject = named;
1350
+ if (session.draft) return session.draft.projectId;
1351
+ if (defaultProject) return defaultProject;
1352
+ const { projects } = await service.projects();
1353
+ if (projects.length === 1) return defaultProject = projects[0].id;
1354
+ if (projects.length === 0) throw new Error("this account is not on any Flowriki project yet \u2014 create one in the dashboard");
1355
+ throw new Error(`which project? Pass projectId \u2014 one of: ${projects.map((p) => `${p.name} (${p.id})`).join(", ")}`);
1356
+ };
1357
+ const catalogOf = async (projectId, fresh = false) => {
1358
+ if (!fresh && catalogs.has(projectId)) return catalogs.get(projectId);
1359
+ const catalog = await service.catalog(projectId);
1360
+ catalogs.set(projectId, catalog);
1361
+ return catalog;
1362
+ };
1363
+ const tools = [
1364
+ {
1365
+ name: "list_projects",
1366
+ title: "List Flowriki projects",
1367
+ description: "The Flowriki projects you can write tests for, with your role on each. Only needed when you are on more than one.",
1368
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1369
+ annotations: { readOnlyHint: true },
1370
+ run: async () => {
1371
+ const { projects } = await service.projects();
1372
+ return text(projects.length ? projects.map((p) => `${p.name} \u2014 id ${p.id}, you are ${p.role}`).join("\n") : "You are not on any project yet.");
1373
+ }
1374
+ },
1375
+ {
1376
+ name: "create_project",
1377
+ title: "Create a Flowriki project",
1378
+ description: "Create a new Flowriki project, connected to a git repository where its tests will be stored, and pointed at the app to test. The repository must already exist and must not hold another Flowriki project. You become its owner.",
1379
+ inputSchema: {
1380
+ type: "object",
1381
+ properties: {
1382
+ name: { type: "string", description: `The project's name, e.g. "Pizza Romano".` },
1383
+ repository: { type: "string", description: "owner/name, or the repository's address, e.g. https://github.com/acme/shop-tests.git" },
1384
+ baseUrl: { type: "string", description: "The app's address, e.g. https://shop.example.com/" }
1385
+ },
1386
+ required: ["name", "repository"],
1387
+ additionalProperties: false
1388
+ },
1389
+ run: async (args) => {
1390
+ const made = await service.createProject(str(args["name"]) ?? "", str(args["repository"]) ?? "", str(args["baseUrl"]));
1391
+ defaultProject = made.id;
1392
+ catalogs.delete(made.id);
1393
+ return text(`Created "${made.name}" (id ${made.id}), stored in ${made.repository}${made.baseUrl ? `, testing ${made.baseUrl}` : " \u2014 no base URL yet; set one in its settings"}.${made.note ? `
1394
+ Note: ${made.note}` : ""}
1395
+ It is now the project these tools work on. Open it: ${service.origin}/projects/${made.id}`);
1396
+ }
1397
+ },
1398
+ {
1399
+ name: "project_catalog",
1400
+ title: "What a test can be built from",
1401
+ description: "The project's base URL, features (folders for flows), existing flows, sign-in profiles with their accounts, and helpers (email codes, 2FA, SMS, API calls). Read this before starting a flow.",
1402
+ inputSchema: { type: "object", properties: { projectId: { type: "string", description: "Optional when you are on one project." } }, additionalProperties: false },
1403
+ annotations: { readOnlyHint: true },
1404
+ run: async (args) => {
1405
+ const projectId = await projectFor(args["projectId"]);
1406
+ const c = await catalogOf(projectId, true);
1407
+ const flowsBy = (featureId) => c.flows.filter((f) => f.featureId === featureId).map((f) => ` - ${f.name} (${f.steps} steps${isMobile(f.platform) ? `, ${f.platform}` : ""})`).join("\n");
1408
+ const platforms = platformsOf(c);
1409
+ const phones = platforms.android || platforms.ios ? await devicesSummary() : [];
1410
+ const phoneLines = ["android", "ios"].filter((p) => platforms[p]).map((p) => {
1411
+ const app = p === "android" ? c.mobile?.android?.appPackage : c.mobile?.ios?.bundleId;
1412
+ const here = phones.filter((d) => d.platform === p);
1413
+ const farms = (c.mobile?.cloud ?? []).map((f) => CLOUD_PROVIDER_NAME[f.provider]);
1414
+ const chosen = c.mobile?.devices[p];
1415
+ return `${p === "android" ? "Android" : "iOS"} app: ${app ?? "(not set up \u2014 Settings \u2192 Mobile)"}
1416
+ Phones on this computer: ${here.length ? here.map((d) => `${d.name}${d.state === "ready" ? "" : ` (${d.state})`}`).join(", ") : "none"}` + (farms.length ? `
1417
+ Cloud device farms: ${farms.join(", ")}` : "") + `
1418
+ Runs: ${c.runWhere?.[p] === "cloud" ? "in the cloud" : "on this computer"}` + (chosen ? ` \u2014 ${chosen.kind === "local" ? chosen.name || chosen.id : `${CLOUD_PROVIDER_NAME[chosen.provider]}: ${chosen.device}`}` : "");
1419
+ });
1420
+ return text([
1421
+ `Project ${projectId}. Tests: ${[platforms.web && "web", platforms.android && "Android app", platforms.ios && "iOS app"].filter(Boolean).join(", ")}.`,
1422
+ platforms.web ? `Base URL: ${c.baseUrl || "(not set)"}${c.runWhere?.web === "cloud" ? " \u2014 test runs use a cloud browser; recording is on this computer" : ""}` : "",
1423
+ ...phoneLines,
1424
+ c.environments.length ? `Environments: ${c.environments.map((e) => `${e.name} ${e.baseUrl}`).join(", ")}` : "",
1425
+ `
1426
+ Features:${c.features.length ? "" : " none yet"}`,
1427
+ ...c.features.map((f) => ` - ${f.name} (id ${f.id})${f.description ? ` \u2014 ${f.description}` : ""}
1428
+ ${flowsBy(f.id)}`),
1429
+ ...c.draft ? [
1430
+ `
1431
+ On Claude's working branch "${c.draft.title}" (${c.draft.changeId}), not yet published:`,
1432
+ ...c.draft.features.length ? [` New features: ${c.draft.features.map((f) => `${f.name} (id ${f.id})`).join(", ")}`] : [],
1433
+ ...c.draft.flows.length ? c.draft.flows.map((f) => ` - flow: ${f.name} (${f.steps} steps, feature ${f.featureId}${f.after?.length ? `, after ${f.after.map((a) => `"${a}"`).join(", ")}` : ""})`) : [" (no flows yet)"],
1434
+ ...c.draft.caseFolders?.length ? [` New case folders: ${c.draft.caseFolders.map((f) => f.name).join(", ")}`] : [],
1435
+ ...(c.draft.cases ?? []).map((t) => ` - case: ${t.name} (folder ${t.folderId}) \u2014 rows: ${t.rows.join(" \u2192 ")}`)
1436
+ ] : [],
1437
+ `
1438
+ Test cases:${(c.cases ?? []).length ? "" : " none published"}`,
1439
+ ...(c.caseFolders ?? []).map((f) => ` - ${f.name} (id ${f.id})
1440
+ ${(c.cases ?? []).filter((t) => t.folderId === f.id).map((t) => ` - ${t.name} \u2014 rows: ${t.rows.join(" \u2192 ")}`).join("\n")}`),
1441
+ `
1442
+ Sign-in profiles:${c.signIns.length ? "" : " none"}`,
1443
+ ...c.signIns.map((s) => ` - ${s.name} (profileId ${s.profileId})${s.fields?.length ? ` \u2014 fields ${s.fields.map((f) => `"${f}"`).join(", ")}` : ""}: ${s.accounts.map((a) => `${a.name} (accountId ${a.accountId})`).join(", ") || "no accounts yet"}`),
1444
+ `
1445
+ Helpers:${c.helpers.length ? "" : " none \u2014 create_helper makes one"}`,
1446
+ ...c.helpers.map((h) => ` - ${h.name} (id ${h.id}) \u2014 ${h.what}${h.inputs.length ? `; needs ${h.inputs.map((n) => `{{${n}}}`).join(", ")}` : ""}${h.description ? ` \u2014 ${h.description}` : ""}`)
1447
+ ].filter(Boolean).join("\n"));
1448
+ }
1449
+ },
1450
+ {
1451
+ name: "start_flow",
1452
+ title: "Start writing a flow",
1453
+ description: "Open a browser on this computer at the project's app \u2014 or, with platform android or ios, the project's phone app on a phone \u2014 and start a new flow. Returns the page or screen. Closes any flow that was being written.",
1454
+ inputSchema: {
1455
+ type: "object",
1456
+ properties: {
1457
+ name: { type: "string", description: `The flow's name: the user journey, e.g. "Sign up and verify email".` },
1458
+ feature: { type: "string", description: "The feature it belongs to: an existing feature's id or name, or a new name." },
1459
+ startPath: { type: "string", description: `Where it starts, relative to the base URL. Default "/". On a phone: a deep link to open, or leave out for the app's first screen.` },
1460
+ platform: { type: "string", enum: ["web", "android", "ios"], description: "Where the flow runs. Default: web, or the project's only platform." },
1461
+ device: { type: "string", description: `Phones only: a phone from project_catalog by name, or a cloud farm's as "BrowserStack: Samsung Galaxy S23". Default: the project's choice, then whatever is connected.` },
1462
+ after: {
1463
+ type: "array",
1464
+ items: { type: "string" },
1465
+ description: "Flows this one starts after (names or ids from project_catalog). They are replayed first, so recording begins where they end; what THEY start after is added too. The saved flow links to them."
1466
+ },
1467
+ signIn: {
1468
+ type: "object",
1469
+ description: "Start signed in, with a profile (and optionally an account) from project_catalog.",
1470
+ properties: { profileId: { type: "string" }, accountId: { type: "string" } },
1471
+ required: ["profileId"],
1472
+ additionalProperties: false
1473
+ },
1474
+ projectId: { type: "string" }
1475
+ },
1476
+ required: ["name", "feature"],
1477
+ additionalProperties: false
1478
+ },
1479
+ annotations: { openWorldHint: true },
1480
+ run: async (args) => {
1481
+ const projectId = await projectFor(args["projectId"]);
1482
+ const catalog = await catalogOf(projectId, true);
1483
+ const featureAsked = str(args["feature"]) ?? "";
1484
+ const feature = catalog.features.find((f) => f.id === featureAsked || f.name.toLowerCase() === featureAsked.toLowerCase());
1485
+ const signIn = args["signIn"];
1486
+ if (signIn && !catalog.signIns.some((s) => s.profileId === signIn.profileId)) {
1487
+ throw new Error(`no sign-in profile ${signIn.profileId} \u2014 project_catalog lists them`);
1488
+ }
1489
+ const asked = Array.isArray(args["after"]) ? args["after"].map(String).filter(Boolean) : [];
1490
+ const plan = asked.length ? await service.flowsAfter(projectId, asked) : null;
1491
+ const platforms = platformsOf(catalog);
1492
+ const enabled = ["web", "android", "ios"].filter((p) => platforms[p]);
1493
+ const platform = str(args["platform"]) ?? (enabled.length === 1 ? enabled[0] : enabled.includes("web") ? "web" : void 0);
1494
+ if (!platform) throw new Error(`this project tests ${enabled.join(" and ")} \u2014 say which with platform`);
1495
+ if (!platforms[platform]) throw new Error(`this project does not test ${platform === "web" ? "a website" : `an ${platform === "ios" ? "iOS" : "Android"} app`} \u2014 turn it on in Settings first`);
1496
+ const device = isMobile(platform) ? deviceFrom(str(args["device"]), platform, await devicesSummary(), catalog.mobile) : void 0;
1497
+ const page = await session.start({
1498
+ projectId,
1499
+ ...isMobile(platform) ? { platform, ...device ? { device } : {} } : {},
1500
+ ...plan ? { after: plan.prerequisites, preparation: plan.steps } : {},
1501
+ name: str(args["name"]) ?? "Untitled flow",
1502
+ ...feature ? { featureId: feature.id } : { featureName: featureAsked },
1503
+ startPath: str(args["startPath"]) || (isMobile(platform) ? "" : "/"),
1504
+ ...signIn?.profileId ? { signIn: { profileId: signIn.profileId, ...signIn.accountId ? { accountId: signIn.accountId } : {} } } : {}
1505
+ }, catalog);
1506
+ const after = plan?.prerequisites.length ? ` It starts after ${plan.prerequisites.map((p) => `"${p.name}"`).join(" \u2192 ")}, which ran first.` : "";
1507
+ return text(`Started "${str(args["name"])}"${feature ? ` in ${feature.name}` : ` in a new feature, ${featureAsked}`}.${after} ${isMobile(platform) ? "The app is open on the phone." : "The browser is open."}
1508
+
1509
+ ${page}`);
1510
+ }
1511
+ },
1512
+ {
1513
+ name: "read_page",
1514
+ title: "Read the page",
1515
+ description: "The current page \u2014 or phone screen \u2014 as its accessibility tree: each element's role and name, which is exactly what act and add_check refer to.",
1516
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1517
+ annotations: { readOnlyHint: true },
1518
+ run: async () => text(await session.snapshot())
1519
+ },
1520
+ {
1521
+ name: "act",
1522
+ title: "Do one thing on the page",
1523
+ description: `Perform one step and keep it in the flow if it worked. Returns the page afterwards. click/dblclick/rightclick/hover: role + name. fill: role + name + value (may use {{values}} from helpers). select: role + name + the option's label as value. check: role + name, value "true" or "false". press: a key such as "Enter" as value, optionally role + name of where. navigate: a path such as "/settings" or a full URL as value (on a phone, a deep link). back/forward: nothing. PHONE ONLY: tap (role + name), longPress (role + name), swipe (value up/down/left/right, optionally on role + name), scroll (to role + name, or value up/down), hideKeyboard, permission (value allow/deny), launchApp, terminateApp, resetApp, background (value: seconds), rotate (value portrait/landscape).`,
1524
+ inputSchema: {
1525
+ type: "object",
1526
+ properties: {
1527
+ action: { type: "string", enum: ["click", "dblclick", "rightclick", "hover", "fill", "select", "check", "press", "navigate", "back", "forward", "tap", "longPress", "swipe", "scroll", "hideKeyboard", "permission", "launchApp", "terminateApp", "resetApp", "background", "rotate"] },
1528
+ role: { type: "string", description: "The element's role as read_page shows it, e.g. button, link, textbox, checkbox, combobox." },
1529
+ name: { type: "string", description: "The element's accessible name, exactly as read_page shows it." },
1530
+ within: { type: "string", description: "When the name is not unique: the name of the region, dialog, form or navigation that holds it." },
1531
+ nth: { type: "integer", minimum: 0, description: "Which one, when several elements share this role and name: 0 is the first in the order read_page lists them (each shared name is marked [nth N of M]). Leave it out when the name is unique." },
1532
+ value: { type: "string" },
1533
+ secret: { type: "boolean", description: "fill only: the value is a secret (a password, PIN, key) \u2014 kept out of the flow and saved to the vault. Fields named like a password are secret without this." }
1534
+ },
1535
+ required: ["action"],
1536
+ additionalProperties: false
1537
+ },
1538
+ run: async (args) => {
1539
+ if (!isAction(args["action"])) throw new Error("action must be one of click, dblclick, rightclick, hover, fill, select, check, press, navigate, back, forward \u2014 or on a phone tap, longPress, swipe, scroll, hideKeyboard, permission, launchApp, terminateApp, resetApp, background, rotate");
1540
+ return text(await session.act({
1541
+ action: args["action"],
1542
+ ...str(args["role"]) ? { role: str(args["role"]) } : {},
1543
+ ...str(args["name"]) !== void 0 ? { name: str(args["name"]) } : {},
1544
+ ...str(args["within"]) ? { within: str(args["within"]) } : {},
1545
+ ...Number.isInteger(args["nth"]) && args["nth"] >= 0 ? { nth: args["nth"] } : {},
1546
+ ...str(args["value"]) !== void 0 ? { value: str(args["value"]) } : {},
1547
+ ...typeof args["secret"] === "boolean" ? { secret: args["secret"] } : {}
1548
+ }));
1549
+ }
1550
+ },
1551
+ {
1552
+ name: "add_check",
1553
+ title: "Add a check",
1554
+ description: "Assert something about the page (or phone screen) as it is now, and keep it in the flow if it holds. Page checks need only kind + value: heading, url (a path), title, message (text shown anywhere \u2014 on a phone, the way to check a screen). Element checks also need role + name: text, value, visible, hidden, checked, count. op: equals (default), contains or matches.",
1555
+ inputSchema: {
1556
+ type: "object",
1557
+ properties: {
1558
+ kind: { type: "string", enum: ["heading", "url", "title", "message", "screen", "text", "value", "visible", "hidden", "checked", "enabled", "count"] },
1559
+ value: { type: "string", description: `What it should be: the heading's words, the path, "true" for a state, a number for count.` },
1560
+ op: { type: "string", enum: ["equals", "contains", "matches"] },
1561
+ role: { type: "string" },
1562
+ name: { type: "string" },
1563
+ within: { type: "string" },
1564
+ nth: { type: "integer", minimum: 0, description: "Which one, when several elements share this role and name: 0 is the first in the order read_page lists them (each shared name is marked [nth N of M])." }
1565
+ },
1566
+ required: ["kind", "value"],
1567
+ additionalProperties: false
1568
+ },
1569
+ run: async (args) => text(await session.check({
1570
+ kind: str(args["kind"]),
1571
+ value: str(args["value"]) ?? "",
1572
+ ...str(args["op"]) ? { op: str(args["op"]) } : {},
1573
+ ...str(args["role"]) ? { role: str(args["role"]), name: str(args["name"]) ?? "" } : {},
1574
+ ...str(args["within"]) ? { within: str(args["within"]) } : {},
1575
+ ...Number.isInteger(args["nth"]) && args["nth"] >= 0 ? { nth: args["nth"] } : {}
1576
+ }))
1577
+ },
1578
+ {
1579
+ name: "use_helper",
1580
+ title: "Use a helper",
1581
+ description: `Get a value from outside the page with one of the project's helpers \u2014 the code or link from a verification email, an authenticator code, an SMS code, a field of an API reply \u2014 and keep the step. Later steps use it as {{saveAs}}. then: "open" goes to the value as a link (for verification links).`,
1582
+ inputSchema: {
1583
+ type: "object",
1584
+ properties: {
1585
+ helperId: { type: "string", description: "The helper's id or name from project_catalog." },
1586
+ inputs: { type: "object", additionalProperties: { type: "string" }, description: `Values for the helper's {{names}}, e.g. {"email": "qa+signup1@example.com"}.` },
1587
+ saveAs: { type: "string", description: "What to call the value, e.g. code. Default: code for a mailbox, value otherwise." },
1588
+ then: { type: "string", enum: ["remember", "open"] }
1589
+ },
1590
+ required: ["helperId"],
1591
+ additionalProperties: false
1592
+ },
1593
+ run: async (args) => text(await session.useHelper({
1594
+ helperId: str(args["helperId"]),
1595
+ ...args["inputs"] && typeof args["inputs"] === "object" ? { inputs: Object.fromEntries(Object.entries(args["inputs"]).map(([k, v]) => [k, String(v)])) } : {},
1596
+ ...str(args["saveAs"]) ? { saveAs: str(args["saveAs"]) } : {},
1597
+ ...args["then"] === "open" ? { then: "open" } : {}
1598
+ }))
1599
+ },
1600
+ {
1601
+ name: "list_steps",
1602
+ title: "List the flow's steps",
1603
+ description: "The flow being written, step by step.",
1604
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1605
+ annotations: { readOnlyHint: true },
1606
+ run: async () => text(session.list())
1607
+ },
1608
+ {
1609
+ name: "remove_step",
1610
+ title: "Remove a step",
1611
+ description: "Remove one step by its number in list_steps. The browser is not wound back; use replay_flow to see the flow as it now stands.",
1612
+ inputSchema: { type: "object", properties: { number: { type: "integer", minimum: 1 } }, required: ["number"], additionalProperties: false },
1613
+ annotations: { destructiveHint: true },
1614
+ run: async (args) => text(session.remove(Number(args["number"])))
1615
+ },
1616
+ {
1617
+ name: "replay_flow",
1618
+ title: "Replay the flow from the start",
1619
+ description: "Run the whole flow from the beginning in a fresh browser, exactly as a test run will, and report each step. Do this before saving.",
1620
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1621
+ annotations: { readOnlyHint: true, openWorldHint: true },
1622
+ run: async () => text(await session.replay())
1623
+ },
1624
+ {
1625
+ name: "save_flow",
1626
+ title: "Save the flow to a branch",
1627
+ description: "Save the flow onto Claude's working branch for this project (made on the first save), for a person to review and publish. Saving the same name again replaces the earlier version there. Returns the review link. Refused if the flow checks nothing.",
1628
+ inputSchema: {
1629
+ type: "object",
1630
+ properties: {
1631
+ title: { type: "string", description: "The branch's title, used only when a new branch is started." },
1632
+ branch: { type: "string", description: "Optional: a branch id (chg_\u2026) from list_my_branches to save onto instead." },
1633
+ newBranch: { type: "boolean", description: "Start a separate branch instead of the working one. Only when the person asks for separate reviews." }
1634
+ },
1635
+ additionalProperties: false
1636
+ },
1637
+ run: async (args) => text(await session.save(str(args["title"]), {
1638
+ ...str(args["branch"]) ? { changeId: str(args["branch"]) } : {},
1639
+ ...args["newBranch"] === true ? { newBranch: true } : {}
1640
+ }))
1641
+ },
1642
+ {
1643
+ name: "list_my_branches",
1644
+ title: "List Claude's open branches",
1645
+ description: "The project's open, unpublished branches that Claude wrote for this person, newest first, with review links. Use it to find a superseded branch to discard.",
1646
+ inputSchema: { type: "object", properties: { projectId: { type: "string", description: "Optional when you are on one project." } }, additionalProperties: false },
1647
+ annotations: { readOnlyHint: true },
1648
+ run: async (args) => {
1649
+ const projectId = await projectFor(args["projectId"]);
1650
+ const { changes } = await service.agentChanges(projectId);
1651
+ if (!changes.length) return text("Claude has no open branches on this project.");
1652
+ return text(changes.map((c) => `- ${c.id} \u2014 "${c.title}" (${new Date(c.createdAt).toISOString().slice(0, 16).replace("T", " ")}) ${service.origin}${c.path}`).join("\n"));
1653
+ }
1654
+ },
1655
+ {
1656
+ name: "gather_branches",
1657
+ title: "Gather Claude's branches into one",
1658
+ description: "Move the flows from Claude's open branches on this project into one branch, and delete the emptied ones \u2014 so the person reviews and publishes once. Only Claude's own, unedited branches; anything a person touched stops it.",
1659
+ inputSchema: {
1660
+ type: "object",
1661
+ properties: {
1662
+ into: { type: "string", description: "The branch to gather into (chg_\u2026). Default: Claude's oldest open branch." },
1663
+ title: { type: "string", description: 'A title for the gathered branch, e.g. "Sign in and sign up tests".' },
1664
+ projectId: { type: "string" }
1665
+ },
1666
+ additionalProperties: false
1667
+ },
1668
+ annotations: { destructiveHint: true },
1669
+ run: async (args) => {
1670
+ const projectId = await projectFor(args["projectId"]);
1671
+ const done = await service.gatherChanges(projectId, {
1672
+ ...str(args["into"]) ? { into: str(args["into"]) } : {},
1673
+ ...str(args["title"]) ? { title: str(args["title"]) } : {}
1674
+ });
1675
+ catalogs.delete(projectId);
1676
+ return text(`Gathered ${done.gathered.length} branch${done.gathered.length === 1 ? "" : "es"} into "${done.title}" (${done.changeId}). Review and publish it here: ${service.origin}${done.path}`);
1677
+ }
1678
+ },
1679
+ {
1680
+ name: "discard_branch",
1681
+ title: "Delete one of Claude's branches",
1682
+ description: "Delete an open branch Claude wrote, with the flows on it \u2014 e.g. one a redo replaced. Only after the person asked for it or agreed. Refused for a branch a person started, edited, or published; those are deleted in the dashboard.",
1683
+ inputSchema: {
1684
+ type: "object",
1685
+ properties: { changeId: { type: "string", description: "The branch's id from list_my_branches (chg_\u2026)." }, projectId: { type: "string" } },
1686
+ required: ["changeId"],
1687
+ additionalProperties: false
1688
+ },
1689
+ annotations: { destructiveHint: true },
1690
+ run: async (args) => {
1691
+ const projectId = await projectFor(args["projectId"]);
1692
+ const changeId = str(args["changeId"]) ?? "";
1693
+ const { deleted } = await service.discardChange(projectId, changeId);
1694
+ return text(`Deleted ${changeId} and its branch ${deleted}.`);
1695
+ }
1696
+ },
1697
+ {
1698
+ name: "preview_case",
1699
+ title: "Preview a test case",
1700
+ description: "Build a test case from flows without saving or running it: its rows (each flow with what it starts after folded in, and which browser it runs in) and every check, numbered, with which are on. Use the numbers in save_case.",
1701
+ inputSchema: CASE_INPUT,
1702
+ annotations: { readOnlyHint: true },
1703
+ run: async (args) => {
1704
+ const projectId = await projectFor(args["projectId"]);
1705
+ return text(await session.previewCase(projectId, caseSpec(args)));
1706
+ }
1707
+ },
1708
+ {
1709
+ name: "save_case",
1710
+ title: "Run and save a test case",
1711
+ description: "Build the test case, run it from the start in a fresh browser exactly as a test run will, and \u2014 only if every row passed \u2014 save it onto Claude's working branch. Saving the same name in the same folder again replaces it. Refused if it switches on no checks.",
1712
+ inputSchema: CASE_INPUT,
1713
+ annotations: { openWorldHint: true },
1714
+ run: async (args) => {
1715
+ const projectId = await projectFor(args["projectId"]);
1716
+ const out = await session.saveCase(projectId, caseSpec(args), await catalogOf(projectId, true));
1717
+ catalogs.delete(projectId);
1718
+ return text(out);
1719
+ }
1720
+ },
1721
+ {
1722
+ name: "read_import_file",
1723
+ title: "Read a spreadsheet waiting to be converted",
1724
+ description: "Read one part of a spreadsheet the person is importing (its id is imp_\u2026): every sheet's rows, each as a JSON array of its cells, numbered as the spreadsheet numbers them. Part 1 says how many parts there are; read every one.",
1725
+ inputSchema: {
1726
+ type: "object",
1727
+ properties: { projectId: { type: "string" }, file: { type: "string", description: "The import's id, imp_\u2026" }, part: { type: "number", description: "Which part, from 1." } },
1728
+ required: ["file", "part"],
1729
+ additionalProperties: false
1730
+ },
1731
+ annotations: { readOnlyHint: true },
1732
+ run: async (args) => {
1733
+ const projectId = await projectFor(args["projectId"]);
1734
+ const got = await service.importPart(projectId, str(args["file"]) ?? "", Number(args["part"] ?? 1));
1735
+ return text(`${got.file} \u2014 part ${got.part} of ${got.of}${got.part < got.of ? " (read the rest too)" : " (the last)"}
1736
+
1737
+ ${got.text}`);
1738
+ }
1739
+ },
1740
+ {
1741
+ name: "save_import_cases",
1742
+ title: "Save the test cases a spreadsheet becomes",
1743
+ description: "Save test cases converted from a spreadsheet being imported (its id is imp_\u2026), in batches as you go: features, each with cases \u2014 name (the scenario it proves), steps as Given / When / Then / And lines, row (its id or row in the file), description (optional). They are shown to the person to import; nothing is written to the project until they do. done: true with the last batch; note: anything you could not convert, and why. restart: true replaces what was saved before.",
1744
+ inputSchema: {
1745
+ type: "object",
1746
+ properties: {
1747
+ projectId: { type: "string" },
1748
+ file: { type: "string", description: "The import's id, imp_\u2026" },
1749
+ features: {
1750
+ type: "array",
1751
+ items: {
1752
+ type: "object",
1753
+ properties: {
1754
+ feature: { type: "string" },
1755
+ cases: {
1756
+ type: "array",
1757
+ items: {
1758
+ type: "object",
1759
+ properties: { name: { type: "string" }, description: { type: "string" }, steps: { type: "array", items: { type: "string" } }, row: { type: "string" } },
1760
+ required: ["name", "steps"],
1761
+ additionalProperties: false
1762
+ }
1763
+ }
1764
+ },
1765
+ required: ["feature", "cases"],
1766
+ additionalProperties: false
1767
+ }
1768
+ },
1769
+ done: { type: "boolean" },
1770
+ note: { type: "string" },
1771
+ restart: { type: "boolean" }
1772
+ },
1773
+ required: ["file", "features"],
1774
+ additionalProperties: false
1775
+ },
1776
+ run: async (args) => {
1777
+ const projectId = await projectFor(args["projectId"]);
1778
+ const features = Array.isArray(args["features"]) ? args["features"] : [];
1779
+ const saved = await service.saveImportCases(projectId, str(args["file"]) ?? "", {
1780
+ features,
1781
+ ...args["done"] === true ? { done: true } : {},
1782
+ ...typeof args["note"] === "string" ? { note: args["note"] } : {},
1783
+ ...args["restart"] === true ? { restart: true } : {}
1784
+ });
1785
+ return text(`Saved ${saved.added} more \u2014 ${saved.total} test cases so far.${saved.done ? " Done: the person can now look them over and import them." : " Keep going, and pass done: true with the last batch."}`);
1786
+ }
1787
+ },
1788
+ {
1789
+ name: "read_update_request",
1790
+ title: "Read what should change in some test cases",
1791
+ description: "Read a request to update test cases (its id is upd_\u2026): what the person wants changed, and each test case as it is now \u2014 its id, feature, name and business steps.",
1792
+ inputSchema: { type: "object", properties: { projectId: { type: "string" }, request: { type: "string", description: "upd_\u2026" } }, required: ["request"], additionalProperties: false },
1793
+ annotations: { readOnlyHint: true },
1794
+ run: async (args) => {
1795
+ const projectId = await projectFor(args["projectId"]);
1796
+ const r = await service.updateRequest(projectId, str(args["request"]) ?? "");
1797
+ return text([
1798
+ `What should change: ${r.instruction}`,
1799
+ ...r.cases.map((c) => [`
1800
+ ${c.feature} \u203A ${c.name} (${c.id})`, ...c.businessSteps.length ? c.businessSteps.map((s) => ` ${s.keyword} ${s.text}`) : [" (no steps written)"]].join("\n"))
1801
+ ].join("\n"));
1802
+ }
1803
+ },
1804
+ {
1805
+ name: "propose_case_updates",
1806
+ title: "Propose new steps for test cases",
1807
+ description: "Propose the new business steps for test cases in an update request (upd_\u2026): for each case changed, its id and ALL its steps as Given / When / Then / And lines (the whole case, not only what changed). Cases that need no change are left out. The person sees each before and after and accepts the ones they want; nothing changes until they do. done: true with the last batch; note: anything you could not do.",
1808
+ inputSchema: {
1809
+ type: "object",
1810
+ properties: {
1811
+ projectId: { type: "string" },
1812
+ request: { type: "string", description: "upd_\u2026" },
1813
+ updates: {
1814
+ type: "array",
1815
+ items: {
1816
+ type: "object",
1817
+ properties: { case: { type: "string", description: "The test case's id, tc_\u2026" }, steps: { type: "array", items: { type: "string" } }, note: { type: "string", description: "Why, in a few words." } },
1818
+ required: ["case", "steps"],
1819
+ additionalProperties: false
1820
+ }
1821
+ },
1822
+ done: { type: "boolean" },
1823
+ note: { type: "string" }
1824
+ },
1825
+ required: ["request", "updates"],
1826
+ additionalProperties: false
1827
+ },
1828
+ run: async (args) => {
1829
+ const projectId = await projectFor(args["projectId"]);
1830
+ const updates = Array.isArray(args["updates"]) ? args["updates"] : [];
1831
+ const r = await service.proposeUpdates(projectId, str(args["request"]) ?? "", { updates, ...args["done"] === true ? { done: true } : {}, ...typeof args["note"] === "string" ? { note: args["note"] } : {} });
1832
+ return text(`Proposed new steps for ${r.proposed} of ${r.of} test cases.${r.done ? " Done: the person can now accept them." : " Pass done: true with the last batch."}`);
1833
+ }
1834
+ },
1835
+ {
1836
+ name: "read_test_cases",
1837
+ title: "Read test cases",
1838
+ description: "Read test cases by id (tc_\u2026) or exact name: their feature, business steps (Given / When / Then), whether they are automated, and the flows they run. Read a case's steps before automating it.",
1839
+ inputSchema: {
1840
+ type: "object",
1841
+ properties: { projectId: { type: "string" }, cases: { type: "array", items: { type: "string" }, description: "Ids or names." } },
1842
+ required: ["cases"],
1843
+ additionalProperties: false
1844
+ },
1845
+ annotations: { readOnlyHint: true },
1846
+ run: async (args) => {
1847
+ const projectId = await projectFor(args["projectId"]);
1848
+ const refs = Array.isArray(args["cases"]) ? args["cases"].map(String) : [];
1849
+ const { cases, missing } = await service.readCases(projectId, refs);
1850
+ const parts = cases.map((c) => [
1851
+ `${c.folder} \u203A ${c.name} (${c.id}) \u2014 ${c.automated ? `automated, rows: ${c.rows.join(" \u2192 ")}` : "not automated yet"}`,
1852
+ ...c.description ? [` ${c.description}`] : [],
1853
+ ...c.businessSteps.length ? c.businessSteps.map((s) => ` ${s.keyword} ${s.text}`) : [" (no business steps written)"]
1854
+ ].join("\n"));
1855
+ if (missing.length) parts.push(`Not found: ${missing.join(", ")} \u2014 project_catalog lists the test cases.`);
1856
+ return text(parts.join("\n\n") || "No test cases found.");
1857
+ }
1858
+ },
1859
+ {
1860
+ name: "write_test_cases",
1861
+ title: "Write test cases down, before automating them",
1862
+ description: "Write test cases as business steps \u2014 Given / When / Then \u2014 with no flows yet, grouped by feature (the case folder), on Claude's working branch for review. They show as not automated until a test case with the same name is saved into the same folder with save_case, which keeps these steps. A case its folder already has is skipped. Use it when asked to write, plan or list test cases; record and save_case only when asked to automate.",
1863
+ inputSchema: {
1864
+ type: "object",
1865
+ properties: {
1866
+ projectId: { type: "string" },
1867
+ features: {
1868
+ type: "array",
1869
+ description: 'One entry per feature (case folder), e.g. "Account \u2013 Sign up".',
1870
+ items: {
1871
+ type: "object",
1872
+ properties: {
1873
+ feature: { type: "string" },
1874
+ cases: {
1875
+ type: "array",
1876
+ items: {
1877
+ type: "object",
1878
+ properties: {
1879
+ name: { type: "string", description: 'The scenario it proves, e.g. "A taken email is refused".' },
1880
+ description: { type: "string" },
1881
+ steps: { type: "array", description: `Given / When / Then lines, e.g. "Given the sign-up form is open", "When I sign up with a taken email", "Then I see 'That email is taken'". And / But continue the line above.`, items: { type: "string" } }
1882
+ },
1883
+ required: ["name", "steps"],
1884
+ additionalProperties: false
1885
+ }
1886
+ }
1887
+ },
1888
+ required: ["feature", "cases"],
1889
+ additionalProperties: false
1890
+ }
1891
+ },
1892
+ branch: { type: "string", description: "Optional: the id of one of Claude's open branches to write to (list_my_branches). Default: the working branch." }
1893
+ },
1894
+ required: ["features"],
1895
+ additionalProperties: false
1896
+ },
1897
+ run: async (args) => {
1898
+ const projectId = await projectFor(args["projectId"]);
1899
+ const features = Array.isArray(args["features"]) ? args["features"] : [];
1900
+ const groups = features.map((f) => ({
1901
+ folder: String(f.feature ?? "").trim(),
1902
+ cases: (Array.isArray(f.cases) ? f.cases : []).map((c) => {
1903
+ const lines = Array.isArray(c.steps) ? c.steps.map(String) : [];
1904
+ const steps = parseGherkin(lines.join("\n"));
1905
+ if (!steps) throw new Error(`the steps of "${String(c.name ?? "")}" must each start with Given, When, Then, And or But`);
1906
+ return { name: String(c.name ?? "").trim(), ...typeof c.description === "string" ? { description: c.description } : {}, businessSteps: steps };
1907
+ })
1908
+ }));
1909
+ const done = await service.writeCases(projectId, groups, str(args["branch"]));
1910
+ catalogs.delete(projectId);
1911
+ const skipped = done.skipped.length ? ` Skipped ${done.skipped.length} the folder already had: ${done.skipped.map((s) => `"${s.name}"`).join(", ")}.` : "";
1912
+ return text(`Wrote ${done.created.length} test case${done.created.length === 1 ? "" : "s"}, not automated yet, on Claude's working branch ${done.branch}.${skipped}`);
1913
+ }
1914
+ },
1915
+ {
1916
+ name: "create_sign_in",
1917
+ title: "Make a sign-in profile",
1918
+ description: "Turn a saved login flow into a sign-in profile that flows and test cases can start signed in with. The flow must not itself sign in or start after other flows, and must end with a check proving the login worked \u2014 its last check is switched on here. Returns the fields an account fills in. Making the same name again replaces Claude's earlier one.",
1919
+ inputSchema: {
1920
+ type: "object",
1921
+ properties: {
1922
+ projectId: { type: "string" },
1923
+ flow: { type: "string", description: "The login flow's name or id (project_catalog)." },
1924
+ name: { type: "string", description: `What a tester calls this way of signing in, e.g. "Customer sign-in". Default: the flow's name.` },
1925
+ description: { type: "string" },
1926
+ signOutFlow: { type: "string", description: "Optional: a flow that signs out, by name or id." },
1927
+ branch: { type: "string", description: "Optional: the id of one of Claude's open branches to write to (list_my_branches). Default: the working branch." }
1928
+ },
1929
+ required: ["flow"],
1930
+ additionalProperties: false
1931
+ },
1932
+ run: async (args) => {
1933
+ const projectId = await projectFor(args["projectId"]);
1934
+ const made = await service.createSignIn(projectId, {
1935
+ flow: str(args["flow"]) ?? "",
1936
+ ...str(args["name"]) ? { name: str(args["name"]) } : {},
1937
+ ...str(args["description"]) ? { description: str(args["description"]) } : {},
1938
+ ...str(args["signOutFlow"]) ? { signOutFlow: str(args["signOutFlow"]) } : {},
1939
+ ...str(args["branch"]) ? { changeId: str(args["branch"]) } : {}
1940
+ });
1941
+ catalogs.delete(projectId);
1942
+ return text(`${made.replaced ? "Replaced" : "Made"} the sign-in "${made.name}" (profileId ${made.profileId}) from "${made.flow}", on ${made.newBranch ? "a new branch" : "Claude's working branch"} ${made.branch}.
1943
+ An account fills in: ${made.fields.map((f) => `"${f.label}"${f.secret ? " (secret)" : ""}`).join(", ") || "nothing \u2014 the flow types no values"}.
1944
+ Next: create_account for each person who signs in this way.`);
1945
+ }
1946
+ },
1947
+ {
1948
+ name: "create_account",
1949
+ title: "Make a sign-in account",
1950
+ description: "An account for a sign-in profile: who signs in, and the values its login flow types, by field label (create_sign_in and project_catalog list them). Secret fields are sealed in the project's vault and never shown again. Then start_flow / test cases can use signIn {profileId, accountId}. Making the same name again updates Claude's earlier one.",
1951
+ inputSchema: {
1952
+ type: "object",
1953
+ properties: {
1954
+ projectId: { type: "string" },
1955
+ signIn: { type: "string", description: "The sign-in profile's name or id." },
1956
+ name: { type: "string", description: 'Who this is, e.g. "Demo customer", "Kitchen admin".' },
1957
+ values: { type: "object", additionalProperties: { type: "string" }, description: 'Field label \u2192 value, e.g. {"Email": "demo@example.com", "Password": "\u2026"}.' },
1958
+ environments: { type: "array", items: { type: "string" }, description: "Optional: the environments this account exists on. Default: all." },
1959
+ branch: { type: "string", description: "Optional: the id of one of Claude's open branches to write to (list_my_branches). Default: the working branch." }
1960
+ },
1961
+ required: ["signIn", "name", "values"],
1962
+ additionalProperties: false
1963
+ },
1964
+ run: async (args) => {
1965
+ const projectId = await projectFor(args["projectId"]);
1966
+ const values = Object.fromEntries(Object.entries(args["values"] && typeof args["values"] === "object" ? args["values"] : {}).map(([k, v]) => [k, String(v)]));
1967
+ const made = await service.createAccount(projectId, {
1968
+ signIn: str(args["signIn"]) ?? "",
1969
+ name: str(args["name"]) ?? "",
1970
+ values,
1971
+ ...Array.isArray(args["environments"]) ? { environments: args["environments"].map(String) } : {},
1972
+ ...str(args["branch"]) ? { changeId: str(args["branch"]) } : {}
1973
+ });
1974
+ catalogs.delete(projectId);
1975
+ return text(`${made.replaced ? "Updated" : "Made"} the account "${made.name}" (accountId ${made.accountId}) for "${made.signIn}", on Claude's working branch ${made.branch}. Filled: ${made.filled.join(", ")} \u2014 secrets are in the vault, not the repository.
1976
+ Use it with start_flow signIn {"profileId": "\u2026", "accountId": "${made.accountId}"}.`);
1977
+ }
1978
+ },
1979
+ {
1980
+ name: "create_helper",
1981
+ title: "Make a helper",
1982
+ description: `A helper for things outside the page, as the Helpers screen makes one. config by kind \u2014 mailbox: {kind, host, port?, secure?, username, folder?, match?: {to, from, subject}, extract?: {take: code|link|subject|body, pattern}, waitSeconds?} with secretValues {passwordRef: the mailbox password}. totp: {kind, digits?, period?, algorithm?} with secretValues {secretRef: the base32 secret}. sms: {kind, accountSid, to, match?, extract?} with secretValues {authTokenRef: the Twilio token}. http: {kind, method, url, headers?, secretHeaders?: {name: ""}, body?, expectStatus?, extract?: {take: json|pattern|status|nothing, path, pattern}} with secretValues {"header:<name>": value}. Use {{name}} in fields for inputs a step supplies. Secrets are sealed in the vault and never shown again. Making the same name again updates Claude's earlier one.`,
1983
+ inputSchema: {
1984
+ type: "object",
1985
+ properties: {
1986
+ projectId: { type: "string" },
1987
+ name: { type: "string", description: 'e.g. "QA inbox", "Admin authenticator".' },
1988
+ description: { type: "string" },
1989
+ config: { type: "object", description: "The helper's settings, by kind (see above). Never put a secret here." },
1990
+ secretValues: { type: "object", additionalProperties: { type: "string" }, description: "The secret for the kind, keyed as above." },
1991
+ branch: { type: "string", description: "Optional: the id of one of Claude's open branches to write to (list_my_branches). Default: the working branch." }
1992
+ },
1993
+ required: ["name", "config"],
1994
+ additionalProperties: false
1995
+ },
1996
+ run: async (args) => {
1997
+ const projectId = await projectFor(args["projectId"]);
1998
+ const made = await service.createHelper(projectId, {
1999
+ name: str(args["name"]) ?? "",
2000
+ ...str(args["description"]) ? { description: str(args["description"]) } : {},
2001
+ config: args["config"] && typeof args["config"] === "object" ? args["config"] : {},
2002
+ ...args["secretValues"] && typeof args["secretValues"] === "object" ? { secretValues: Object.fromEntries(Object.entries(args["secretValues"]).map(([k, v]) => [k, String(v)])) } : {},
2003
+ ...str(args["branch"]) ? { changeId: str(args["branch"]) } : {}
2004
+ });
2005
+ catalogs.delete(projectId);
2006
+ return text(`${made.replaced ? "Updated" : "Made"} the ${made.kind} helper "${made.name}" (id ${made.helperId}) on Claude's working branch ${made.branch}.${made.inputs.length ? ` A step supplies ${made.inputs.map((n) => `{{${n}}}`).join(", ")}.` : ""} Use it with use_helper.`);
2007
+ }
2008
+ },
2009
+ {
2010
+ name: "project_brief",
2011
+ title: "Read the project's memory",
2012
+ description: "The project's own knowledge, in one call: About the product (product.md, and product/<web|android|ios>.md where a platform differs), memory/decisions.md, what each linked codebase folder was learned as and which platform's code it holds, and the list of feature pages and session summaries. Call it first in every conversation.",
2013
+ inputSchema: { type: "object", properties: { projectId: { type: "string" } }, additionalProperties: false },
2014
+ annotations: { readOnlyHint: true },
2015
+ run: async (args) => {
2016
+ const projectId = await projectFor(args["projectId"]);
2017
+ const { pages } = await service.knowledgePages(projectId);
2018
+ const read = async (path2) => pages.some((p) => p.path === path2) ? (await service.knowledgePage(projectId, path2)).content : null;
2019
+ const [product, glossary, decisions, web, android, ios, tagged] = await Promise.all(["product.md", "glossary.md", "memory/decisions.md", "product/web.md", "product/android.md", "product/ios.md", "codebase.json"].map(read));
2020
+ const codebases = pages.filter((p) => p.path.startsWith("codebase/"));
2021
+ const tags = codebaseIndexOf(tagged).folders;
2022
+ const headers = await Promise.all(codebases.map(async (p) => {
2023
+ const holds = tags[p.path.slice("codebase/".length, -".md".length)]?.tags ?? [];
2024
+ return `- ${p.path}${holds.length ? ` (${holds.map((t) => CODEBASE_TAG_NAME[t]).join(", ")} code)` : ""}: ${(await read(p.path))?.split("\n").filter((l) => l.trim()).slice(0, 3).join(" \xB7 ") ?? ""}`;
2025
+ }));
2026
+ const shown = /* @__PURE__ */ new Set(["product.md", "glossary.md", "memory/decisions.md", "product/web.md", "product/android.md", "product/ios.md", "codebase.json", ...codebases.map((p) => p.path)]);
2027
+ const parts = [
2028
+ product ? `## About the product (product.md)
2029
+ ${product}` : "No About the product yet \u2014 the person writes it on the Knowledge screen; offer to help draft it.",
2030
+ web ? `## About the website (product/web.md)
2031
+ ${web}` : "",
2032
+ android ? `## About the Android app (product/android.md)
2033
+ ${android}` : "",
2034
+ ios ? `## About the iOS app (product/ios.md)
2035
+ ${ios}` : "",
2036
+ glossary ? `## glossary.md (older page; terms now belong in product.md)
2037
+ ${glossary}` : "",
2038
+ decisions ? `## memory/decisions.md
2039
+ ${decisions}` : "",
2040
+ codebases.length ? `## Codebase, as learned
2041
+ ${headers.join("\n")}` : "No codebase learned yet.",
2042
+ `## Other pages
2043
+ ${pages.filter((p) => !shown.has(p.path)).map((p) => `- ${p.path}`).join("\n") || "none"}`
2044
+ ];
2045
+ return text(parts.filter(Boolean).join("\n\n"));
2046
+ }
2047
+ },
2048
+ {
2049
+ name: "knowledge_search",
2050
+ title: "Search everything the project knows",
2051
+ description: "Search knowledge pages, source documents, requirements and test cases at once. Returns where each hit is, so it can be cited ([[knowledge:path]], [[source:id@vN]], [[requirement:id]], [[testCase:TC-n]]).",
2052
+ inputSchema: { type: "object", properties: { projectId: { type: "string" }, q: { type: "string" } }, required: ["q"], additionalProperties: false },
2053
+ annotations: { readOnlyHint: true },
2054
+ run: async (args) => {
2055
+ const projectId = await projectFor(args["projectId"]);
2056
+ const { hits } = await service.search(projectId, str(args["q"]) ?? "");
2057
+ if (!hits.length) return text("Nothing found.");
2058
+ return text(hits.map((h) => `[[${h.kind}:${h.ref}]] ${h.title}
2059
+ ${h.snippet}`).join("\n"));
2060
+ }
2061
+ },
2062
+ {
2063
+ name: "knowledge_read",
2064
+ title: "Read a knowledge page",
2065
+ description: "Read one knowledge page by path (product.md, product/<web|android|ios>.md, codebase/<folder>.md, features/<name>.md, memory/\u2026).",
2066
+ inputSchema: { type: "object", properties: { projectId: { type: "string" }, path: { type: "string" } }, required: ["path"], additionalProperties: false },
2067
+ annotations: { readOnlyHint: true },
2068
+ run: async (args) => {
2069
+ const projectId = await projectFor(args["projectId"]);
2070
+ const page = await service.knowledgePage(projectId, str(args["path"]) ?? "");
2071
+ return text(page.content);
2072
+ }
2073
+ },
2074
+ {
2075
+ name: "write_knowledge",
2076
+ title: "Write a knowledge page",
2077
+ description: `Write what the project should remember, on Claude's working branch for review: product.md (About the product \u2014 the person's own description; write it only when they ask) and product/<web|android|ios>.md (what is particular to that platform's app), codebase/<folder>.md (what a linked folder holds \u2014 starting with "# <folder>", "Commit: <sha>" and "Learned: <yyyy-mm-dd>" lines, then routes, screens, forms and their validation, roles, APIs, flags; summarised, never copied code), features/<name>.md (screens, rules, quirks), memory/decisions.md (decisions and conventions), memory/sessions/<yyyy-mm-dd>-<topic>.md (what a job did). append: true adds to the end instead of replacing. Never a password, key or token \u2014 those are refused.`,
2078
+ inputSchema: {
2079
+ type: "object",
2080
+ properties: { projectId: { type: "string" }, path: { type: "string" }, content: { type: "string" }, append: { type: "boolean" }, branch: { type: "string" } },
2081
+ required: ["path", "content"],
2082
+ additionalProperties: false
2083
+ },
2084
+ run: async (args) => {
2085
+ const projectId = await projectFor(args["projectId"]);
2086
+ const saved = await service.writeKnowledge(projectId, {
2087
+ path: str(args["path"]) ?? "",
2088
+ content: String(args["content"] ?? ""),
2089
+ ...args["append"] === true ? { append: true } : {},
2090
+ ...str(args["branch"]) ? { changeId: str(args["branch"]) } : {}
2091
+ });
2092
+ return text(`Wrote ${saved.path} (${saved.length} characters) on Claude's working branch ${saved.branch}.`);
2093
+ }
2094
+ },
2095
+ {
2096
+ name: "close_browser",
2097
+ title: "Close the browser",
2098
+ description: "Close the browser \u2014 or the app on the phone \u2014 and drop the flow being written, unsaved.",
2099
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
2100
+ annotations: { destructiveHint: true },
2101
+ run: async () => {
2102
+ await session.close();
2103
+ session.draft = null;
2104
+ return text("Closed.");
2105
+ }
2106
+ }
2107
+ ];
2108
+ return tools.map((tool) => ({
2109
+ ...tool,
2110
+ run: async (args) => {
2111
+ let result;
2112
+ try {
2113
+ result = await tool.run(args);
2114
+ } catch (error) {
2115
+ throw new Error(session.redact(error.message));
2116
+ }
2117
+ return { ...result, content: result.content.map((c) => c.type === "text" && c.text !== void 0 ? { ...c, text: session.redact(c.text) } : c) };
2118
+ }
2119
+ }));
2120
+ }
2121
+
2122
+ // src/mcp/upgrade.ts
2123
+ import { spawn } from "child_process";
2124
+ import readline2 from "readline";
2125
+ var PRIVATE = "flowriki-upgrade";
2126
+ var startWithNpx = (version) => spawn(process.platform === "win32" ? "npx.cmd" : "npx", ["-y", `@flowriki/agent@${version}`, "mcp"], {
2127
+ env: { ...process.env, FLOWRIKI_MCP_CHILD: "1" },
2128
+ stdio: ["pipe", "pipe", "inherit"]
2129
+ });
2130
+ var toolShape = (tools) => JSON.stringify(tools.map((t) => [t.name, t.description ?? "", t.inputSchema ?? null]).sort());
2131
+ function serveWithUpgrades(tools, info, opts) {
2132
+ const input = opts.input ?? process.stdin;
2133
+ const output = opts.output ?? process.stdout;
2134
+ const log = opts.log ?? ((line) => process.stderr.write(`flowriki: ${line}
2135
+ `));
2136
+ const send = (m) => output.write(`${JSON.stringify(m)}
2137
+ `);
2138
+ if (!opts.output) {
2139
+ console.log = console.info = console.warn = console.debug = (...args) => {
2140
+ process.stderr.write(`${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
2141
+ `);
2142
+ };
2143
+ }
2144
+ let initialize = null;
2145
+ let localCalls = 0;
2146
+ let ready = null;
2147
+ let active = null;
2148
+ let preparing = false;
2149
+ let notice = null;
2150
+ const forwarded = /* @__PURE__ */ new Set();
2151
+ let timer = null;
2152
+ const withNotice = (answer) => {
2153
+ if (!notice || !answer.result || typeof answer.result !== "object") return answer;
2154
+ const result = answer.result;
2155
+ if (!Array.isArray(result.content)) return answer;
2156
+ const text2 = notice;
2157
+ notice = null;
2158
+ return { ...answer, result: { ...result, content: [{ type: "text", text: text2 }, ...result.content] } };
2159
+ };
2160
+ const prepare = async (version) => {
2161
+ if (preparing || ready || active || !initialize) return;
2162
+ preparing = true;
2163
+ let child = null;
2164
+ try {
2165
+ child = (opts.start ?? startWithNpx)(version);
2166
+ const c = child;
2167
+ const lines2 = readline2.createInterface({ input: c.stdout, crlfDelay: Infinity });
2168
+ const waiting = /* @__PURE__ */ new Map();
2169
+ const exited = new Promise((_, reject) => c.once("exit", (code) => reject(new Error(`it stopped while starting (exit ${code})`))));
2170
+ exited.catch(() => void 0);
2171
+ c.once("error", (e) => waiting.forEach((resolve) => resolve({ jsonrpc: "2.0", error: { message: e.message } })));
2172
+ lines2.on("line", (line) => {
2173
+ let m;
2174
+ try {
2175
+ m = JSON.parse(line);
2176
+ } catch {
2177
+ return;
2178
+ }
2179
+ if (typeof m.id === "string" && m.id.startsWith(PRIVATE)) {
2180
+ waiting.get(m.id)?.(m);
2181
+ waiting.delete(m.id);
2182
+ return;
2183
+ }
2184
+ if (active?.child !== c) return;
2185
+ if (m.id !== void 0 && m.id !== null) forwarded.delete(m.id);
2186
+ send(m.id !== void 0 && m.id !== null && "result" in m ? withNotice(m) : m);
2187
+ });
2188
+ const ask = (method, params, id) => new Promise((resolve, reject) => {
2189
+ waiting.set(id, resolve);
2190
+ c.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, ...params ? { params } : {} })}
2191
+ `);
2192
+ setTimeout(() => reject(new Error("it did not answer in time")), opts.readyWithinMs ?? 18e4).unref();
2193
+ });
2194
+ const hello = await Promise.race([ask("initialize", initialize.params, `${PRIVATE}-init`), exited]);
2195
+ if (hello.error) throw new Error(JSON.stringify(hello.error));
2196
+ c.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}
2197
+ `);
2198
+ const listed = await Promise.race([ask("tools/list", void 0, `${PRIVATE}-tools`), exited]);
2199
+ const theirs = listed.result?.tools ?? [];
2200
+ ready = { child: c, version, lines: lines2, toolsChanged: toolShape(theirs) !== toolShape(tools) };
2201
+ c.once("exit", () => {
2202
+ if (ready?.child === c) ready = null;
2203
+ if (active?.child === c) {
2204
+ active = null;
2205
+ for (const id of forwarded) send({ jsonrpc: "2.0", id, error: { code: -32603, message: "the updated Flowriki stopped \u2014 ask again" } });
2206
+ forwarded.clear();
2207
+ notice = `The updated Flowriki (${version}) stopped, so this connection carries on with ${opts.current}.`;
2208
+ log(`updated server ${version} exited; back on ${opts.current}`);
2209
+ }
2210
+ });
2211
+ log(`${version} is ready to take over from ${opts.current}`);
2212
+ } catch (error) {
2213
+ child?.kill();
2214
+ log(`could not start ${version}: ${error.message}`);
2215
+ notice ??= `Flowriki ${version} is out (this connection runs ${opts.current}) and could not switch over by itself: ${error.message}. A new Claude session starts the new version.`;
2216
+ } finally {
2217
+ preparing = false;
2218
+ }
2219
+ };
2220
+ const maybeSwitch = async (incomingTool) => {
2221
+ if (!ready || active || localCalls > 0) return false;
2222
+ if (!opts.idle() && incomingTool !== "start_flow") return false;
2223
+ const next = ready;
2224
+ ready = null;
2225
+ await opts.handOff().catch(() => void 0);
2226
+ active = next;
2227
+ if (timer) clearInterval(timer);
2228
+ notice = `Flowriki updated itself from ${opts.current} to ${next.version} \u2014 the new version is answering now.` + (next.toolsChanged ? " It brings new or changed tools; if Claude does not offer them yet, start a new Claude session (in the terminal version of Claude Code, /mcp then Reconnect also works)." : "");
2229
+ send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
2230
+ log(`switched to ${next.version}`);
2231
+ return true;
2232
+ };
2233
+ const look = async () => {
2234
+ if (active || ready || preparing) return;
2235
+ const version = await opts.check().catch(() => null);
2236
+ if (version) {
2237
+ await prepare(version);
2238
+ await maybeSwitch();
2239
+ }
2240
+ };
2241
+ setTimeout(() => void look(), opts.firstCheckMs ?? 15e3).unref();
2242
+ timer = setInterval(() => void look(), opts.everyMs ?? 30 * 6e4);
2243
+ timer.unref();
2244
+ const lines = readline2.createInterface({ input, crlfDelay: Infinity });
2245
+ const pending = /* @__PURE__ */ new Set();
2246
+ lines.on("line", (line) => {
2247
+ if (!line.trim()) return;
2248
+ let message;
2249
+ try {
2250
+ message = JSON.parse(line);
2251
+ } catch {
2252
+ send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } });
2253
+ return;
2254
+ }
2255
+ if (message.method === "initialize") initialize = message;
2256
+ const task = (async () => {
2257
+ const tool = message.method === "tools/call" ? String(message.params?.["name"] ?? "") : void 0;
2258
+ if (!active && tool) await maybeSwitch(tool);
2259
+ if (active) {
2260
+ if (message.id !== void 0 && message.id !== null) forwarded.add(message.id);
2261
+ active.child.stdin.write(`${line}
2262
+ `);
2263
+ return;
2264
+ }
2265
+ if (tool) localCalls++;
2266
+ try {
2267
+ const answer = await handle(message, tools, info);
2268
+ if (answer) send(tool ? withNotice(answer) : answer);
2269
+ if (message.method === "notifications/initialized") send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
2270
+ } finally {
2271
+ if (tool) localCalls--;
2272
+ }
2273
+ if (tool && ready) await maybeSwitch();
2274
+ })();
2275
+ pending.add(task);
2276
+ void task.finally(() => pending.delete(task));
2277
+ });
2278
+ return new Promise((resolve) => lines.on("close", () => {
2279
+ void Promise.allSettled([...pending]).then(() => {
2280
+ if (timer) clearInterval(timer);
2281
+ const child = active?.child ?? ready?.child;
2282
+ if (!child) return resolve();
2283
+ child.stdin?.end();
2284
+ const done = () => resolve();
2285
+ child.once("exit", done);
2286
+ setTimeout(() => {
2287
+ child.kill();
2288
+ done();
2289
+ }, 5e3).unref();
2290
+ });
2291
+ }));
2292
+ }
2293
+
2294
+ // src/updates.ts
2295
+ import fs from "fs";
2296
+ import path from "path";
2297
+ var CACHE_MS = 30 * 60 * 1e3;
2298
+ async function latestPublished(opts = {}) {
2299
+ const file = path.join(dataDir(), "latest-agent.json");
2300
+ if (!opts.fresh) {
2301
+ try {
2302
+ const kept = JSON.parse(fs.readFileSync(file, "utf8"));
2303
+ if (kept.version && kept.at && Date.now() - kept.at < CACHE_MS) return kept.version;
2304
+ } catch {
2305
+ }
2306
+ }
2307
+ try {
2308
+ const res = await fetch(AGENT_LATEST_URL, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
2309
+ if (!res.ok) return null;
2310
+ const version = (await res.json()).version ?? null;
2311
+ if (version) {
2312
+ try {
2313
+ fs.mkdirSync(path.dirname(file), { recursive: true });
2314
+ fs.writeFileSync(file, JSON.stringify({ version, at: Date.now() }));
2315
+ } catch {
2316
+ }
2317
+ }
2318
+ return version;
2319
+ } catch {
2320
+ return null;
2321
+ }
2322
+ }
2323
+ async function updateFor(running) {
2324
+ const latest = await latestPublished();
2325
+ return agentUpdateFor(running, latest) ? latest : null;
2326
+ }
2327
+
2328
+ // src/mcp/index.ts
2329
+ async function runMcp(opts) {
2330
+ let service;
2331
+ try {
2332
+ service = resolveService(opts.service);
2333
+ } catch (error) {
2334
+ process.stderr.write(`${error.message}
2335
+ `);
2336
+ return 2;
2337
+ }
2338
+ const connection = connectionFor(service);
2339
+ const session = connection ? new AuthoringSession(new ServiceClient(connection), opts.headless ? { headless: true } : {}) : null;
2340
+ let tools = connection && session ? authoringTools(new ServiceClient(connection), session) : authoringTools(null, null);
2341
+ if (!connection) {
2342
+ const why = `This computer is not connected to Flowriki at ${service}. Run \`flowriki-agent connect\` in a terminal, approve it in your browser, then restart Claude.`;
2343
+ tools = tools.map((tool) => ({ ...tool, run: async () => ({ content: [{ type: "text", text: why }], isError: true }) }));
2344
+ }
2345
+ const closing = async () => {
2346
+ await session?.close();
2347
+ process.exit(0);
2348
+ };
2349
+ process.on("SIGINT", () => void closing());
2350
+ process.on("SIGTERM", () => void closing());
2351
+ const info = { name: "flowriki", version: opts.version, instructions: INSTRUCTIONS };
2352
+ if (process.env["FLOWRIKI_MCP_CHILD"] === "1" || process.env["FLOWRIKI_NO_UPDATE"] === "1" || !/^\d+\.\d+\.\d+/.test(opts.version)) {
2353
+ await serve(tools, info);
2354
+ } else {
2355
+ await serveWithUpgrades(tools, info, {
2356
+ current: opts.version,
2357
+ check: () => updateFor(opts.version),
2358
+ idle: () => !session?.open,
2359
+ handOff: async () => {
2360
+ await session?.close();
2361
+ if (session) session.draft = null;
2362
+ }
2363
+ });
2364
+ }
2365
+ await session?.close();
2366
+ return 0;
2367
+ }
2368
+
2369
+ // src/cli.ts
15
2370
  var paint = (code) => (s) => `\x1B[${code}m${s}\x1B[0m`;
16
2371
  var bold = paint("1");
17
2372
  var dim = paint("2");
@@ -30,6 +2385,13 @@ ${bold("USAGE")}
30
2385
  flowriki-agent doctor diagnose setup problems
31
2386
  flowriki-agent prepare download the browser recording needs
32
2387
  flowriki-agent disconnect forget this computer's credential
2388
+ flowriki-agent mobile setup install what testing Android and iOS apps
2389
+ needs (Appium and its drivers)
2390
+ flowriki-agent mobile doctor is this computer ready to test phones
2391
+ flowriki-agent mobile devices the phones, emulators and simulators here
2392
+ flowriki-agent mcp Flowriki as tools for Claude \u2014 started by
2393
+ Claude Code or Claude Desktop, not by you:
2394
+ claude mcp add flowriki -- flowriki-agent mcp
33
2395
 
34
2396
  ${bold("OPTIONS")}
35
2397
  --project <dir> a checkout to serve; repeat for several.
@@ -37,6 +2399,7 @@ ${bold("OPTIONS")}
37
2399
  --name <label> how this computer appears in your dashboard
38
2400
  --service <url> advanced: a self-hosted Flowriki. Defaults to the
39
2401
  hosted service, which is what you want.
2402
+ --no-open print the approval link without opening a browser
40
2403
  --json machine-readable output for status and doctor
41
2404
  -h, --help this
42
2405
  -v, --version version
@@ -56,6 +2419,7 @@ async function main(argv) {
56
2419
  name: { type: "string" },
57
2420
  service: { type: "string" },
58
2421
  json: { type: "boolean" },
2422
+ "no-open": { type: "boolean" },
59
2423
  help: { type: "boolean", short: "h" },
60
2424
  version: { type: "boolean", short: "v" }
61
2425
  }
@@ -79,8 +2443,13 @@ Run \`flowriki-agent --help\`.`);
79
2443
  const service = values.service ? String(values.service) : void 0;
80
2444
  const projects = (values.project ?? []).map(String);
81
2445
  switch (command) {
2446
+ // FIRST, and before anything writes to stdout: in this mode stdout is the
2447
+ // protocol, and one stray line of output is a message Claude rejects.
2448
+ case "mcp":
2449
+ return runMcp({ ...service ? { service } : {}, version: AGENT_VERSION });
82
2450
  case "connect": {
83
2451
  const result = await connect({
2452
+ open: !values["no-open"],
84
2453
  ...service ? { service } : {},
85
2454
  ...values.name ? { machineName: String(values.name) } : {},
86
2455
  onProgress: (note) => {
@@ -91,7 +2460,7 @@ Run \`flowriki-agent --help\`.`);
91
2460
  console.log(` ${url}
92
2461
  `);
93
2462
  if (note.detail?.["canOpen"] === false) {
94
- console.log(dim(" No graphical session here \u2014 open that link on a computer that has one.\n"));
2463
+ console.log(dim(" Open the approval link in your browser.\n"));
95
2464
  } else {
96
2465
  console.log(dim(" Opening it for you. If nothing happens, use the link above.\n"));
97
2466
  }
@@ -108,6 +2477,11 @@ Run \`flowriki-agent --help\`.`);
108
2477
  return 0;
109
2478
  }
110
2479
  case "start": {
2480
+ process.on("unhandledRejection", (reason) => {
2481
+ const said = reason instanceof Error ? reason.stack ?? reason.message : String(reason);
2482
+ console.error(red(`! a command failed without being handled \u2014 the agent is still running`));
2483
+ console.error(dim(said.split("\n").slice(0, 4).join("\n")));
2484
+ });
111
2485
  const started = await start({
112
2486
  ...service ? { service } : {},
113
2487
  ...projects.length ? { projects } : {},
@@ -137,6 +2511,17 @@ Run \`flowriki-agent --help\`.`);
137
2511
  console.log(dim(` project ${project.name} (${project.root})`));
138
2512
  }
139
2513
  console.log(dim("\n Running in the foreground. Ctrl-C to stop.\n"));
2514
+ let told = null;
2515
+ const tellIfBehind = async () => {
2516
+ const newer = await updateFor(AGENT_VERSION).catch(() => null);
2517
+ if (!newer || newer === told) return;
2518
+ told = newer;
2519
+ console.log(yellow(` ! Flowriki agent ${newer} is out \u2014 this is ${AGENT_VERSION}.`));
2520
+ console.log(dim(` Update: npm install -g @flowriki/agent@latest then stop (Ctrl-C) and start again
2521
+ `));
2522
+ };
2523
+ void tellIfBehind();
2524
+ setInterval(() => void tellIfBehind(), 6 * 60 * 6e4).unref();
140
2525
  let stopping = false;
141
2526
  const shutdown = async (signal) => {
142
2527
  if (stopping) return;
@@ -188,7 +2573,11 @@ Run \`flowriki-agent --help\`.`);
188
2573
  console.log(` node ${found.node} ${dim(`${found.platform}/${found.arch}`)}`);
189
2574
  console.log(` protocol ${found.protocolVersion}`);
190
2575
  console.log(` data ${found.dataDir}`);
191
- console.log(` service ${found.service} ${found.reachable ? green("reachable") : red("unreachable")}`);
2576
+ console.log(
2577
+ ` service ${found.service} ${found.reachable ? green("reachable") : red("unreachable")}` + // WHICH FLOWRIKI, from the service's own mouth. Not the site being
2578
+ // tested — that is a project setting and changes nothing here.
2579
+ (found.environment ? dim(` [${found.environment}]`) : "")
2580
+ );
192
2581
  console.log(` credential ${found.credentialFingerprint ?? dim("none stored")}`);
193
2582
  console.log(
194
2583
  ` browsers ${found.playwright.chromiumInstalled ? green("chromium ready") : yellow("chromium not installed")} ${dim(found.playwright.browsersPath ?? "")}`
@@ -206,6 +2595,42 @@ Run \`flowriki-agent --help\`.`);
206
2595
  }
207
2596
  return 0;
208
2597
  }
2598
+ case "mobile": {
2599
+ const sub = positionals[1] ?? "doctor";
2600
+ const report = (found) => {
2601
+ for (const [title, lines] of [["Appium", found.appium], ["Android", found.android], ["iOS", found.ios]]) {
2602
+ console.log(bold(title));
2603
+ for (const line of lines) {
2604
+ console.log(` ${line.ok ? green("\u2713") : line.optional ? yellow("\u2013") : red("\u2717")} ${line.item.padEnd(15)} ${line.ok ? dim(line.detail) : line.detail}`);
2605
+ if (!line.ok && line.fix) console.log(` ${yellow("\u2192")} ${line.fix}`);
2606
+ }
2607
+ }
2608
+ console.log(`
2609
+ Android ${found.androidReady ? green("ready") : yellow("not ready")} iOS ${found.iosReady ? green("ready") : yellow("not ready")}`);
2610
+ return found.androidReady || found.iosReady ? 0 : 1;
2611
+ };
2612
+ if (sub === "setup") return report(await mobileSetup((line) => console.log(dim(` ${line}`))));
2613
+ if (sub === "doctor") {
2614
+ const found = await mobileDoctor();
2615
+ if (values.json) {
2616
+ console.log(JSON.stringify(found, null, 2));
2617
+ return found.androidReady || found.iosReady ? 0 : 1;
2618
+ }
2619
+ return report(found);
2620
+ }
2621
+ if (sub === "devices") {
2622
+ const found = await listDevices();
2623
+ if (values.json) {
2624
+ console.log(JSON.stringify(found, null, 2));
2625
+ return 0;
2626
+ }
2627
+ if (!found.length) console.log(yellow(" No phones, emulators or simulators found."));
2628
+ for (const d of found) console.log(` ${d.state === "ready" ? green("\u25CF") : dim("\u25CB")} ${d.name.padEnd(28)} ${dim(`${d.platform === "ios" ? "iOS" : "Android"} ${d.osVersion} \xB7 ${d.kind}${d.state === "ready" ? "" : ` \xB7 ${d.state}`}`)}`);
2629
+ return 0;
2630
+ }
2631
+ console.error(`unknown: mobile ${sub} \u2014 use setup, doctor or devices`);
2632
+ return 2;
2633
+ }
209
2634
  case "projects": {
210
2635
  const { projects: found, skipped } = resolveCheckouts(projects.length ? projects : [process.cwd()]);
211
2636
  for (const p of found) console.log(` ${p.name} ${dim(p.root)}`);