turno-browser 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +95 -123
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +117 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +600 -0
  7. package/dist/api.d.ts +90 -2
  8. package/dist/api.js +41 -4
  9. package/dist/argv.d.ts +16 -2
  10. package/dist/argv.js +100 -3
  11. package/dist/background-state.d.ts +54 -0
  12. package/dist/background-state.js +97 -0
  13. package/dist/background.d.ts +69 -0
  14. package/dist/background.js +458 -0
  15. package/dist/batch.d.ts +5 -0
  16. package/dist/batch.js +3 -3
  17. package/dist/bin/mcp.js +103 -6
  18. package/dist/captcha.d.ts +77 -0
  19. package/dist/captcha.js +334 -0
  20. package/dist/cdp-relay.d.ts +20 -0
  21. package/dist/cdp-relay.js +101 -0
  22. package/dist/chrome-features.d.ts +23 -0
  23. package/dist/chrome-features.js +44 -0
  24. package/dist/cli/background.d.ts +11 -0
  25. package/dist/cli/background.js +132 -0
  26. package/dist/cli/commands.d.ts +16 -0
  27. package/dist/cli/commands.js +515 -0
  28. package/dist/cli/context.d.ts +75 -0
  29. package/dist/cli/context.js +44 -0
  30. package/dist/cli/do-background.d.ts +27 -0
  31. package/dist/cli/do-background.js +212 -0
  32. package/dist/cli/do.d.ts +85 -0
  33. package/dist/cli/do.js +558 -0
  34. package/dist/cli/flows.d.ts +28 -0
  35. package/dist/cli/flows.js +303 -0
  36. package/dist/cli/identity.d.ts +37 -0
  37. package/dist/cli/identity.js +906 -0
  38. package/dist/cli/live.d.ts +7 -0
  39. package/dist/cli/live.js +99 -0
  40. package/dist/cli/main.d.ts +16 -0
  41. package/dist/cli/main.js +171 -0
  42. package/dist/cli/secret.d.ts +4 -0
  43. package/dist/cli/secret.js +151 -0
  44. package/dist/cli/session.d.ts +6 -0
  45. package/dist/cli/session.js +106 -0
  46. package/dist/cli/setup.d.ts +7 -0
  47. package/dist/cli/setup.js +180 -0
  48. package/dist/cli/vault.d.ts +5 -0
  49. package/dist/cli/vault.js +192 -0
  50. package/dist/client.d.ts +82 -0
  51. package/dist/client.js +303 -0
  52. package/dist/diagnose.d.ts +7 -0
  53. package/dist/diagnose.js +61 -6
  54. package/dist/doctor.d.ts +37 -3
  55. package/dist/doctor.js +264 -6
  56. package/dist/engine-attach.d.ts +27 -0
  57. package/dist/engine-attach.js +165 -0
  58. package/dist/engine-camoufox.d.ts +32 -0
  59. package/dist/engine-camoufox.js +271 -0
  60. package/dist/engine-lightpanda.d.ts +72 -0
  61. package/dist/engine-lightpanda.js +293 -0
  62. package/dist/engine.d.ts +63 -11
  63. package/dist/engine.js +106 -29
  64. package/dist/flows.d.ts +127 -0
  65. package/dist/flows.js +294 -0
  66. package/dist/governor.d.ts +42 -7
  67. package/dist/governor.js +82 -32
  68. package/dist/health.js +2 -1
  69. package/dist/host.d.ts +38 -2
  70. package/dist/host.js +689 -52
  71. package/dist/human-input.d.ts +84 -0
  72. package/dist/human-input.js +448 -0
  73. package/dist/humanize.d.ts +123 -0
  74. package/dist/humanize.js +241 -0
  75. package/dist/identities.js +4 -1
  76. package/dist/idle-timer.d.ts +12 -0
  77. package/dist/idle-timer.js +25 -0
  78. package/dist/index.d.ts +13 -4
  79. package/dist/index.js +7 -1
  80. package/dist/lifecycle.d.ts +11 -1
  81. package/dist/lifecycle.js +11 -2
  82. package/dist/live-client.d.ts +22 -0
  83. package/dist/live-client.js +95 -0
  84. package/dist/live-page.d.ts +4 -0
  85. package/dist/live-page.js +144 -0
  86. package/dist/live-server.d.ts +173 -0
  87. package/dist/live-server.js +643 -0
  88. package/dist/live.d.ts +120 -0
  89. package/dist/live.js +204 -0
  90. package/dist/login-tool.d.ts +13 -0
  91. package/dist/login-tool.js +8 -3
  92. package/dist/login.d.ts +4 -1
  93. package/dist/login.js +12 -2
  94. package/dist/names.d.ts +28 -0
  95. package/dist/names.js +25 -0
  96. package/dist/network-chrome.d.ts +74 -0
  97. package/dist/network-chrome.js +178 -0
  98. package/dist/network.d.ts +125 -0
  99. package/dist/network.js +264 -0
  100. package/dist/opt-in-settings.d.ts +69 -0
  101. package/dist/opt-in-settings.js +152 -0
  102. package/dist/recorder.d.ts +88 -0
  103. package/dist/recorder.js +538 -0
  104. package/dist/recordings.d.ts +116 -0
  105. package/dist/recordings.js +474 -0
  106. package/dist/redact.d.ts +7 -0
  107. package/dist/redact.js +18 -0
  108. package/dist/replay.d.ts +20 -0
  109. package/dist/replay.js +383 -0
  110. package/dist/reputation.d.ts +24 -2
  111. package/dist/reputation.js +63 -17
  112. package/dist/runtime-lock.js +3 -2
  113. package/dist/session-export.js +1 -1
  114. package/dist/session.d.ts +10 -2
  115. package/dist/session.js +10 -2
  116. package/dist/settings.d.ts +104 -2
  117. package/dist/settings.js +204 -6
  118. package/dist/sharing.d.ts +96 -0
  119. package/dist/sharing.js +269 -0
  120. package/dist/snippet.d.ts +8 -2
  121. package/dist/snippet.js +10 -4
  122. package/dist/tab-locks.d.ts +63 -0
  123. package/dist/tab-locks.js +179 -0
  124. package/dist/tools.d.ts +38 -0
  125. package/dist/tools.js +20 -1
  126. package/dist/tuning.d.ts +14 -0
  127. package/dist/tuning.js +9 -0
  128. package/dist/upstream.d.ts +11 -0
  129. package/dist/vault.js +5 -4
  130. package/npm-shrinkwrap.json +6 -5
  131. package/package.json +13 -7
package/dist/replay.js ADDED
@@ -0,0 +1,383 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { secretStore } from "turno-core/secrets";
3
+ import { FlowError, describeStep, fillParams, listFlows, paramRefs, readFlow, resolveParams, setPath, } from "./flows.js";
4
+ import { loginTool } from "./login-tool.js";
5
+ import { upstream } from "./upstream.js";
6
+ import { names } from "./names.js";
7
+ /**
8
+ * `browser_replay` and `browser_flows`: run a saved flow again, and list the saved ones.
9
+ *
10
+ * Each step runs through the same path as a call of its own (tab governor, click diagnosis,
11
+ * recordings), with the element found again from the step's locators, in order: the first that
12
+ * matches exactly one visible element is passed to the stock tool as its target. When a step
13
+ * fails, the replay stops and says which step, every locator it tried and why each did not
14
+ * fit, which steps did not run, and how to continue (`from`), with a fresh snapshot of the page:
15
+ * the agent does that step by hand and lets the replay go on.
16
+ *
17
+ * Parameters: a sensitive one (no stored value) must be given. A value written
18
+ * `keychain:<item>` is read from the secret store (`turno secret set <item>`), so the model
19
+ * never sees it; every sensitive or secret-store value joins the redactor, and before one goes
20
+ * into a page the recording stops its trace and holds the page like a vault fill.
21
+ */
22
+ /** Longest wait for one step's element, in seconds. */
23
+ const MAX_WAIT_S = 30;
24
+ const DEFAULT_WAIT_S = 5;
25
+ /** How deep a flow may replay other flows. */
26
+ const MAX_DEPTH = 3;
27
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
+ function textOf(result) {
29
+ return result.content
30
+ .filter((c) => c.type === "text")
31
+ .map((c) => c.text)
32
+ .join("\n");
33
+ }
34
+ /** The sections of an upstream result text (`### Title` then the body). */
35
+ function sections(text) {
36
+ const out = new Map();
37
+ for (const part of text.split(/^### /m).slice(1)) {
38
+ const nl = part.indexOf("\n");
39
+ if (nl < 0)
40
+ continue;
41
+ out.set(part.slice(0, nl), part.slice(nl + 1).trim());
42
+ }
43
+ return out;
44
+ }
45
+ /** The first locator of a target that finds exactly one visible element, waiting up to `ms`. */
46
+ async function findTarget(stock, target, ms, signal) {
47
+ const end = Date.now() + ms;
48
+ for (;;) {
49
+ const page = stock.currentPage();
50
+ const tried = [];
51
+ let unchecked;
52
+ for (const l of target.locators) {
53
+ if (!page)
54
+ break;
55
+ const locator = page.locator(l.selector);
56
+ const n = await locator.count().catch(() => -1);
57
+ if (n === 1 && (await locator.isVisible().catch(() => false)))
58
+ return { selector: l.selector, kind: l.kind };
59
+ if (n < 0 && l.kind === "generated")
60
+ unchecked ??= { selector: l.selector, kind: l.kind };
61
+ tried.push(`${l.kind} ${l.selector}: ${n < 0 ? "not a selector this page can check" : n === 0 ? "no element" : n === 1 ? "not visible" : `${n} elements`}`);
62
+ }
63
+ // A locator the agent wrote in Playwright's JavaScript syntax: upstream parses it itself.
64
+ if (unchecked && tried.length === target.locators.length && tried.every((t) => !t.endsWith("not visible")))
65
+ return unchecked;
66
+ if (!page)
67
+ tried.push("no page is open");
68
+ if (Date.now() >= end || signal?.aborted)
69
+ return { tried };
70
+ await sleep(250);
71
+ }
72
+ }
73
+ /** Whether a step puts a sensitive value into the page. */
74
+ function typesSecret(step, secret) {
75
+ return paramRefs(step.args).some((name) => secret.has(name));
76
+ }
77
+ async function runStep(run, step, values, secret) {
78
+ const { ctx, stock } = run;
79
+ if (step.tool === "browser_login") {
80
+ try {
81
+ const result = await loginTool().handle(ctx, { site: step.args.site });
82
+ if (result.isError)
83
+ return { ok: false, message: sections(textOf(result)).get("Error") ?? textOf(result) };
84
+ return { ok: true };
85
+ }
86
+ catch (error) {
87
+ return { ok: false, message: error.message ?? String(error) };
88
+ }
89
+ }
90
+ if (step.tool === "browser_replay") {
91
+ if (run.depth >= MAX_DEPTH)
92
+ return { ok: false, message: `flows replay other flows at most ${MAX_DEPTH} deep` };
93
+ const vault = ctx.vault;
94
+ let inner;
95
+ try {
96
+ inner = readFlow(vault.identity.id, String(step.args.flow), vault.identity.env);
97
+ }
98
+ catch (error) {
99
+ return { ok: false, message: error.message };
100
+ }
101
+ const given = fillParams(step.args.params ?? {}, values);
102
+ const prepared = await prepareParams(ctx, inner, given);
103
+ if ("error" in prepared)
104
+ return { ok: false, message: prepared.error };
105
+ const state = await runSteps({ ...run, depth: run.depth + 1 }, inner, prepared.values, prepared.secret, 1);
106
+ if (state.failure)
107
+ return {
108
+ ok: false,
109
+ message: `step ${state.failure.n} of flow "${inner.name}" (${describeStep(state.failure.step)}) failed: ${state.failure.message}`,
110
+ };
111
+ return { ok: true, note: `${inner.steps.length} steps` };
112
+ }
113
+ const args = fillParams(step.args, values);
114
+ const used = [];
115
+ for (const [path, target] of Object.entries(step.targets ?? {})) {
116
+ const found = await findTarget(stock, target, run.waitMs, ctx.signal);
117
+ if ("tried" in found) {
118
+ const what = target.description ? `"${target.description}"` : "the element";
119
+ return {
120
+ ok: false,
121
+ message: `no locator of ${what} found exactly one visible element within ${run.waitMs / 1000}s:\n${found.tried.map((t) => `- ${t}`).join("\n")}`,
122
+ };
123
+ }
124
+ setPath(args, path, found.selector);
125
+ used.push(found.kind);
126
+ const element = path === "target"
127
+ ? "element"
128
+ : path === "startTarget"
129
+ ? "startElement"
130
+ : path === "endTarget"
131
+ ? "endElement"
132
+ : undefined;
133
+ if (element && target.description && args[element] === undefined)
134
+ args[element] = target.description;
135
+ }
136
+ const schema = stock.schemas.get(step.tool);
137
+ if (!schema)
138
+ return { ok: false, message: `this server does not offer ${step.tool} (its capability is off)` };
139
+ const parsed = schema.safeParse(args);
140
+ if (!parsed.success)
141
+ return { ok: false, message: `invalid arguments: ${stock.formatError(parsed.error)}` };
142
+ if (typesSecret(step, secret))
143
+ await ctx.recording?.pauseForSecret(stock.currentPage());
144
+ const result = await stock.call(step.tool, args, { snapshot: false });
145
+ if (result.isError)
146
+ return { ok: false, message: sections(textOf(result)).get("Error") ?? textOf(result) };
147
+ return { ok: true, ...(used.length ? { note: `found by ${used.join(", ")}` } : {}) };
148
+ }
149
+ async function runSteps(run, flow, values, secret, from) {
150
+ const state = { lines: [] };
151
+ const total = flow.steps.length;
152
+ for (let i = from - 1; i < total; i++) {
153
+ const step = flow.steps[i];
154
+ const done = await runStep(run, step, values, secret);
155
+ if (!done.ok) {
156
+ state.lines.push(`${i + 1}. ${describeStep(step)}: failed`);
157
+ state.failure = { n: i + 1, total, step, message: done.message };
158
+ return state;
159
+ }
160
+ state.lines.push(`${i + 1}. ${describeStep(step)}: ok${done.note ? ` (${done.note})` : ""}`);
161
+ }
162
+ return state;
163
+ }
164
+ /**
165
+ * The values a flow runs with: given ones (a `keychain:<item>` read from the secret store),
166
+ * then defaults. Sensitive and secret-store values join the redactor first.
167
+ */
168
+ async function prepareParams(ctx, flow, given) {
169
+ const vault = ctx.vault;
170
+ const { values, missing, unknown } = resolveParams(flow, given);
171
+ if (unknown.length)
172
+ return {
173
+ error: `flow "${flow.name}" has no parameter ${unknown.map((u) => `"${u}"`).join(", ")} (its parameters: ${flow.params.map((p) => p.name).join(", ") || "none"})`,
174
+ };
175
+ if (missing.length)
176
+ return {
177
+ error: `flow "${flow.name}" needs ${missing.map((p) => `"${p.name}"${p.sensitive ? " (sensitive)" : ""}`).join(", ")}: pass them in params; a value written keychain:<item> is read from the secret store (${names().secretSet("<item>")}) so it never passes through you.`,
178
+ };
179
+ const secret = new Set();
180
+ const refs = new Set();
181
+ for (const p of flow.params) {
182
+ let v = values[p.name];
183
+ if (v.startsWith("keychain:")) {
184
+ const item = v.slice("keychain:".length);
185
+ const store = vault.store ?? secretStore(vault.identity.env);
186
+ if (!store)
187
+ return { error: `parameter "${p.name}" names ${v}, but this machine has no secret store` };
188
+ const read = await store.get(item).catch(() => undefined);
189
+ if (read === undefined)
190
+ return {
191
+ error: `parameter "${p.name}": the secret store has no item "${item}" (store it with: ${names().secretSet(item)})`,
192
+ };
193
+ v = read;
194
+ values[p.name] = v;
195
+ refs.add(p.name);
196
+ secret.add(p.name);
197
+ }
198
+ else if (p.sensitive)
199
+ secret.add(p.name);
200
+ if (secret.has(p.name))
201
+ vault.redactor.add(v, `sensitive parameter ${p.name}`);
202
+ }
203
+ return { values, secret, refs };
204
+ }
205
+ function replaySchema() {
206
+ const z = upstream().utils.z;
207
+ return {
208
+ name: "browser_replay",
209
+ title: "Replay a saved browser flow",
210
+ description: [
211
+ "Run a flow saved with browser_record (list them with browser_flows) on this browser identity, step by step, finding each element again by its saved locators.",
212
+ "Pass the flow's parameters in params; sensitive ones have no saved value and must be given. Write a value as keychain:<item> to have it read from the secret store instead of passing it yourself.",
213
+ "When a step fails it stops and reports the step, the locators it tried and a fresh snapshot: do that step yourself, then call browser_replay again with from set to the next step.",
214
+ ].join(" "),
215
+ inputSchema: z.object({
216
+ flow: z.string().describe("The flow name"),
217
+ params: z.record(z.string(), z.string()).optional().describe("Parameter values by name"),
218
+ from: z
219
+ .number()
220
+ .optional()
221
+ .describe("Start at this step (1 is the first), to continue after a step done by hand"),
222
+ wait: z
223
+ .number()
224
+ .optional()
225
+ .describe(`Seconds to wait for each step's element (default ${DEFAULT_WAIT_S}, at most ${MAX_WAIT_S})`),
226
+ snapshot: z.boolean().optional().describe("Return a snapshot of the page after the last step (default true)"),
227
+ }),
228
+ type: "action",
229
+ };
230
+ }
231
+ /** The snapshot sections of a stock result, for the end of a replay's result. */
232
+ async function pageSections(stock, snapshot) {
233
+ if (!snapshot) {
234
+ const page = await stock.page();
235
+ return page ? ["### Page", `- Page URL: ${page.url}`, ...(page.title ? [`- Page Title: ${page.title}`] : [])] : [];
236
+ }
237
+ const snap = sections(textOf(await stock.call("browser_snapshot", {}, { snapshot: true })));
238
+ const out = [];
239
+ for (const title of ["Open tabs", "Page", "Modal state", "Snapshot", "Tab governor"]) {
240
+ const body = snap.get(title);
241
+ if (body)
242
+ out.push(`### ${title}`, body);
243
+ }
244
+ return out;
245
+ }
246
+ /** `browser_replay`. */
247
+ export function replayTool() {
248
+ let built;
249
+ return {
250
+ get schema() {
251
+ built ??= replaySchema();
252
+ return built;
253
+ },
254
+ async handle(ctx, params) {
255
+ const vault = ctx.vault;
256
+ const stock = ctx.stock;
257
+ if (!vault || !stock)
258
+ throw new FlowError("browser_replay needs a browser identity: this server runs without --identity");
259
+ const flow = readFlow(vault.identity.id, String(params.flow), vault.identity.env);
260
+ const from = params.from === undefined ? 1 : Number(params.from);
261
+ if (!Number.isInteger(from) || from < 1 || from > flow.steps.length)
262
+ throw new FlowError(`from must be a step number from 1 to ${flow.steps.length}`);
263
+ const wait = Math.min(MAX_WAIT_S, Math.max(0, Number(params.wait ?? DEFAULT_WAIT_S)));
264
+ const given = params.params ?? {};
265
+ const prepared = await prepareParams(ctx, flow, given);
266
+ if ("error" in prepared)
267
+ return { content: [{ type: "text", text: `### Error\nNothing ran: ${prepared.error}` }], isError: true };
268
+ const run = { ctx, stock, waitMs: wait * 1000, depth: 0 };
269
+ const exec = () => runSteps(run, flow, prepared.values, prepared.secret, from);
270
+ const state = ctx.recorder ? await ctx.recorder.suspend(exec) : await exec();
271
+ const out = [];
272
+ if (state.failure) {
273
+ const { n, total, step, message } = state.failure;
274
+ const left = total - n;
275
+ out.push("### Error", `Step ${n} of ${total} (${describeStep(step)}) failed: ${message}`, left
276
+ ? `Steps ${n + 1} to ${total} did not run. Do step ${n} yourself on the page below, then continue with browser_replay {"flow": "${flow.name}", "from": ${n + 1}} and the same params.`
277
+ : `It was the last step: do it yourself on the page below.`);
278
+ }
279
+ out.push("### Replay", `Flow "${flow.name}"${from > 1 ? ` from step ${from}` : ""}:`, ...state.lines);
280
+ if (state.failure && state.failure.n < flow.steps.length)
281
+ out.push("### Remaining steps", ...flow.steps.slice(state.failure.n).map((s, i) => `${state.failure.n + i + 1}. ${describeStep(s)}`));
282
+ out.push(...(await pageSections(stock, params.snapshot !== false || state.failure !== undefined)));
283
+ if (!state.failure && from === 1 && ctx.recorder) {
284
+ // A recording session keeps the replay as one step; a value read from the secret store
285
+ // keeps its keychain: reference, which is not a secret.
286
+ const slots = flow.params.map((p) => {
287
+ const raw = given[p.name];
288
+ const ref = raw?.startsWith("keychain:");
289
+ return {
290
+ path: `params.${p.name}`,
291
+ value: ref ? raw : prepared.values[p.name],
292
+ sensitive: !ref && prepared.secret.has(p.name),
293
+ label: p.name,
294
+ };
295
+ });
296
+ ctx.recorder.record("browser_replay", { flow: flow.name, params: Object.fromEntries(flow.params.map((p) => [p.name, ""])) }, slots);
297
+ }
298
+ return { content: [{ type: "text", text: out.join("\n") }], ...(state.failure ? { isError: true } : {}) };
299
+ },
300
+ };
301
+ }
302
+ function flowsSchema() {
303
+ const z = upstream().utils.z;
304
+ return {
305
+ name: "browser_flows",
306
+ title: "List saved browser flows",
307
+ description: "List the flows saved for this browser identity (browser_record saves them), with their steps and parameters; name one to see its steps.",
308
+ inputSchema: z.object({ name: z.string().optional().describe("A flow name, to see its steps") }),
309
+ type: "readOnly",
310
+ };
311
+ }
312
+ /** `browser_flows`. */
313
+ export function flowsTool() {
314
+ let built;
315
+ return {
316
+ get schema() {
317
+ built ??= flowsSchema();
318
+ return built;
319
+ },
320
+ browser: false,
321
+ async handle(ctx, params) {
322
+ const vault = ctx.vault;
323
+ if (!vault)
324
+ throw new FlowError("browser_flows needs a browser identity: this server runs without --identity");
325
+ const { id, env } = vault.identity;
326
+ const describeParam = (p) => `${p.name}${p.sensitive ? " (sensitive, required)" : p.hasDefault ? "" : " (required)"}`;
327
+ if (typeof params.name === "string") {
328
+ const flow = readFlow(id, params.name, env);
329
+ const lines = [
330
+ `### Flow ${flow.name}`,
331
+ ...(flow.description ? [flow.description] : []),
332
+ ...flow.steps.map((s, i) => `${i + 1}. ${describeStep(s)}`),
333
+ "### Parameters",
334
+ ...(flow.params.length
335
+ ? flow.params.map((p) => `- ${describeParam({ name: p.name, sensitive: p.sensitive, hasDefault: p.default !== undefined })}`)
336
+ : ["(none)"]),
337
+ ];
338
+ return { content: [{ type: "text", text: lines.join("\n") }] };
339
+ }
340
+ const flows = listFlows(id, env);
341
+ const lines = flows.length
342
+ ? flows.map((f) => `- ${f.name}: ${f.steps} step${f.steps === 1 ? "" : "s"}${f.start ? `, starts at ${f.start}` : ""}${f.params.length ? `; params ${f.params.map(describeParam).join(", ")}` : ""}${f.description ? `. ${f.description}` : ""}`)
343
+ : [`Identity "${id}" has no saved flows yet: record one with browser_record.`];
344
+ return { content: [{ type: "text", text: ["### Flows", ...lines].join("\n") }] };
345
+ },
346
+ };
347
+ }
348
+ /**
349
+ * Replays a flow outside an agent (`turno browser replay`): starts this package's MCP server
350
+ * on the identity and calls `browser_replay`, so the run goes through exactly the path an agent's
351
+ * does (lock, vault, redaction, recordings). Parameter values travel over the server's stdin.
352
+ */
353
+ export async function replayFlow(id, flow, options = {}) {
354
+ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
355
+ const { StdioClientTransport } = await import("@modelcontextprotocol/sdk/client/stdio.js");
356
+ const env = options.env ?? process.env;
357
+ const bin = fileURLToPath(new URL("./bin/mcp.js", import.meta.url));
358
+ const transport = new StdioClientTransport({
359
+ command: process.execPath,
360
+ args: [bin, "--identity", id, ...(options.headless ? ["--headless"] : [])],
361
+ env: Object.fromEntries(Object.entries(env).filter((e) => e[1] !== undefined)),
362
+ stderr: "pipe",
363
+ });
364
+ const client = new Client({ name: `${names().browser} replay`, version: "1" });
365
+ await client.connect(transport);
366
+ try {
367
+ const result = await client.callTool({
368
+ name: "browser_replay",
369
+ arguments: {
370
+ flow,
371
+ ...(options.params ? { params: options.params } : {}),
372
+ ...(options.from ? { from: options.from } : {}),
373
+ snapshot: false,
374
+ },
375
+ }, undefined, { timeout: 10 * 60_000 });
376
+ const text = (result.content ?? []).map((c) => c.text ?? "").join("\n");
377
+ return { ok: !result.isError, text };
378
+ }
379
+ finally {
380
+ await client.close().catch(() => { });
381
+ }
382
+ }
383
+ //# sourceMappingURL=replay.js.map
@@ -9,6 +9,13 @@ import { type ChallengeKind } from "./detectors.js";
9
9
  * no query, no page content. A site's reputation is not a score a test page gives; it is how
10
10
  * often the site stops the identity, and whether that goes up or down. `turno browser
11
11
  * reputation` shows the counts and the trend of the last 7 days against the 7 before.
12
+ *
13
+ * With captcha solving on (identity.json `captcha`), each attempt of `browser_solve_captcha`
14
+ * is a line of its own, with the widget kind, the provider and whether it worked:
15
+ *
16
+ * {"ts":"2026-11-19T16:00:00.000Z","site":"shop.example.com","kind":"solve","widget":"recaptcha","provider":"task-api","ok":true}
17
+ *
18
+ * An older turno-browser skips those lines when it reads the log.
12
19
  */
13
20
  export interface ChallengeEvent {
14
21
  ts: string;
@@ -16,9 +23,20 @@ export interface ChallengeEvent {
16
23
  kind: ChallengeKind;
17
24
  markers: string[];
18
25
  }
26
+ /** One `browser_solve_captcha` attempt. Never the token, the key or the page's path. */
27
+ export interface SolveEvent {
28
+ ts: string;
29
+ site: string;
30
+ kind: "solve";
31
+ widget: string;
32
+ provider: string;
33
+ ok: boolean;
34
+ }
19
35
  export interface SiteSummary {
20
36
  site: string;
21
37
  total: number;
38
+ /** Captchas a solver answered (identity.json `captcha`); not counted in `total`. */
39
+ solved: number;
22
40
  captcha: number;
23
41
  verify: number;
24
42
  block: number;
@@ -35,10 +53,14 @@ export interface IdentityReputation {
35
53
  }
36
54
  export declare function reputationPath(id: string, env?: NodeJS.ProcessEnv): string;
37
55
  export declare function recordChallenge(id: string, env: NodeJS.ProcessEnv, event: Omit<ChallengeEvent, "ts">, now?: Date): void;
38
- /** Every event of the identity's log, oldest first. Lines that do not parse are skipped. */
56
+ /** Logs one captcha solving attempt. */
57
+ export declare function recordSolve(id: string, env: NodeJS.ProcessEnv, event: Omit<SolveEvent, "ts" | "kind">, now?: Date): void;
58
+ /** Every challenge of the identity's log, oldest first. Lines that do not parse are skipped. */
39
59
  export declare function readChallenges(id: string, env?: NodeJS.ProcessEnv): ChallengeEvent[];
60
+ /** Every captcha solving attempt of the identity's log, oldest first. */
61
+ export declare function readSolves(id: string, env?: NodeJS.ProcessEnv): SolveEvent[];
40
62
  /** Counts per site, most recent first, with the trend of the last 7 days against the 7 before. */
41
- export declare function summarizeChallenges(events: readonly ChallengeEvent[], now?: Date): SiteSummary[];
63
+ export declare function summarizeChallenges(events: readonly ChallengeEvent[], now?: Date, solves?: readonly SolveEvent[]): SiteSummary[];
42
64
  /** The report of `turno browser reputation`: the identities asked for, or every one. */
43
65
  export declare function reputationReport(env?: NodeJS.ProcessEnv, ids?: readonly string[], now?: Date): {
44
66
  identities: IdentityReputation[];
@@ -10,9 +10,23 @@ export function reputationPath(id, env = process.env) {
10
10
  return join(identityStateDir(id, env), "reputation.jsonl");
11
11
  }
12
12
  export function recordChallenge(id, env, event, now = new Date()) {
13
+ appendLine(id, env, { ts: now.toISOString(), site: event.site, kind: event.kind, markers: event.markers });
14
+ }
15
+ /** Logs one captcha solving attempt. */
16
+ export function recordSolve(id, env, event, now = new Date()) {
17
+ const line = {
18
+ ts: now.toISOString(),
19
+ site: event.site,
20
+ kind: "solve",
21
+ widget: event.widget,
22
+ provider: event.provider,
23
+ ok: event.ok,
24
+ };
25
+ appendLine(id, env, line);
26
+ }
27
+ function appendLine(id, env, line) {
13
28
  const file = reputationPath(id, env);
14
29
  mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 });
15
- const line = { ts: now.toISOString(), site: event.site, kind: event.kind, markers: event.markers };
16
30
  appendFileSync(file, `${JSON.stringify(line)}\n`, { mode: 0o600 });
17
31
  try {
18
32
  if (statSync(file).size > MAX_BYTES) {
@@ -33,8 +47,16 @@ function isEvent(v) {
33
47
  (e.kind === "captcha" || e.kind === "verify" || e.kind === "block") &&
34
48
  Array.isArray(e.markers));
35
49
  }
36
- /** Every event of the identity's log, oldest first. Lines that do not parse are skipped. */
37
- export function readChallenges(id, env = process.env) {
50
+ function isSolve(v) {
51
+ const e = v;
52
+ return (typeof e === "object" &&
53
+ e !== null &&
54
+ e.kind === "solve" &&
55
+ typeof e.ts === "string" &&
56
+ typeof e.site === "string" &&
57
+ typeof e.ok === "boolean");
58
+ }
59
+ function readLines(id, env, keep) {
38
60
  let text;
39
61
  try {
40
62
  text = readFileSync(reputationPath(id, env), "utf8");
@@ -48,7 +70,7 @@ export function readChallenges(id, env = process.env) {
48
70
  continue;
49
71
  try {
50
72
  const v = JSON.parse(line);
51
- if (isEvent(v))
73
+ if (keep(v))
52
74
  out.push(v);
53
75
  }
54
76
  catch {
@@ -57,22 +79,32 @@ export function readChallenges(id, env = process.env) {
57
79
  }
58
80
  return out;
59
81
  }
82
+ /** Every challenge of the identity's log, oldest first. Lines that do not parse are skipped. */
83
+ export function readChallenges(id, env = process.env) {
84
+ return readLines(id, env, isEvent);
85
+ }
86
+ /** Every captcha solving attempt of the identity's log, oldest first. */
87
+ export function readSolves(id, env = process.env) {
88
+ return readLines(id, env, isSolve);
89
+ }
60
90
  /** Counts per site, most recent first, with the trend of the last 7 days against the 7 before. */
61
- export function summarizeChallenges(events, now = new Date()) {
91
+ export function summarizeChallenges(events, now = new Date(), solves = []) {
62
92
  const bySite = new Map();
63
93
  const t = now.getTime();
94
+ const empty = (site, ts) => ({
95
+ site,
96
+ total: 0,
97
+ solved: 0,
98
+ captcha: 0,
99
+ verify: 0,
100
+ block: 0,
101
+ last7d: 0,
102
+ prev7d: 0,
103
+ trend: "flat",
104
+ lastSeen: ts,
105
+ });
64
106
  for (const e of events) {
65
- const s = bySite.get(e.site) ?? {
66
- site: e.site,
67
- total: 0,
68
- captcha: 0,
69
- verify: 0,
70
- block: 0,
71
- last7d: 0,
72
- prev7d: 0,
73
- trend: "flat",
74
- lastSeen: e.ts,
75
- };
107
+ const s = bySite.get(e.site) ?? empty(e.site, e.ts);
76
108
  s.total++;
77
109
  s[e.kind]++;
78
110
  const age = t - Date.parse(e.ts);
@@ -84,6 +116,15 @@ export function summarizeChallenges(events, now = new Date()) {
84
116
  s.lastSeen = e.ts;
85
117
  bySite.set(e.site, s);
86
118
  }
119
+ for (const e of solves) {
120
+ if (!e.ok)
121
+ continue;
122
+ const s = bySite.get(e.site) ?? empty(e.site, e.ts);
123
+ s.solved++;
124
+ if (e.ts > s.lastSeen)
125
+ s.lastSeen = e.ts;
126
+ bySite.set(e.site, s);
127
+ }
87
128
  for (const s of bySite.values())
88
129
  s.trend = s.last7d > s.prev7d ? "up" : s.last7d < s.prev7d ? "down" : "flat";
89
130
  return [...bySite.values()].sort((a, b) => b.lastSeen.localeCompare(a.lastSeen) || a.site.localeCompare(b.site));
@@ -97,7 +138,12 @@ export function reputationReport(env = process.env, ids, now = new Date()) {
97
138
  return {
98
139
  identities: list.map((id) => {
99
140
  const events = readChallenges(id, env);
100
- return { id, file: reputationPath(id, env), total: events.length, sites: summarizeChallenges(events, now) };
141
+ return {
142
+ id,
143
+ file: reputationPath(id, env),
144
+ total: events.length,
145
+ sites: summarizeChallenges(events, now, readSolves(id, env)),
146
+ };
101
147
  }),
102
148
  };
103
149
  }
@@ -2,6 +2,7 @@ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node
2
2
  import { join } from "node:path";
3
3
  import { pidAlive } from "turno-core/process";
4
4
  import { IdentityError, identityStateDir } from "./ids.js";
5
+ import { names } from "./names.js";
5
6
  export class IdentityInUseError extends IdentityError {
6
7
  lock;
7
8
  constructor(message, lock) {
@@ -42,10 +43,10 @@ export function runtimeLockAlive(lock) {
42
43
  export function inUseMessage(id, lock) {
43
44
  const pids = `pid ${lock.nodePid}${lock.chromePid ? `, Chrome pid ${lock.chromePid}` : ""}`;
44
45
  if (lock.holder === "login") {
45
- return `browser identity "${id}" is in use by turno browser login (${pids}) since ${lock.startedAt}. Close that Chrome window to finish the login, then try again.`;
46
+ return `browser identity "${id}" is in use by ${names().browser} login (${pids}) since ${lock.startedAt}. Close that Chrome window to finish the login, then try again.`;
46
47
  }
47
48
  if (lock.holder === "export" || lock.holder === "import") {
48
- return `browser identity "${id}" is in use by turno browser ${lock.holder} (${pids}) since ${lock.startedAt}. Wait for it to finish, then try again.`;
49
+ return `browser identity "${id}" is in use by ${names().browser} ${lock.holder} (${pids}) since ${lock.startedAt}. Wait for it to finish, then try again.`;
49
50
  }
50
51
  return (`browser identity "${id}" is in use by turno-browser-mcp (${pids}) since ${lock.startedAt}. ` +
51
52
  "One identity drives one Chrome at a time: wait for that session to end (mcpd stops the server after its lease or idle time), " +
@@ -95,7 +95,7 @@ export function profileOrigins(profileDir, cookies) {
95
95
  catch {
96
96
  continue;
97
97
  }
98
- for (const m of text.matchAll(/(?:META:|_)(https?:\/\/[a-z0-9.\-]+(?::\d{1,5})?|https?:\/\/\[[0-9a-f:]+\](?::\d{1,5})?)/gi))
98
+ for (const m of text.matchAll(/(?:META:|_)(https?:\/\/[a-z0-9.-]+(?::\d{1,5})?|https?:\/\/\[[0-9a-f:]+\](?::\d{1,5})?)/gi))
99
99
  add(originOf(m[1]));
100
100
  }
101
101
  for (const c of cookies) {
package/dist/session.d.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  /**
2
2
  * The client session mcpd relays a call for. mcpd puts an opaque id, stable for one
3
3
  * client session and different for every other, in the `_meta` of each `tools/call` it
4
- * forwards, under this key. The host reads it and hands it to turno tools; nothing else
5
- * depends on it yet (a later stage keys per-tab locks on it).
4
+ * forwards, under this key. The host hands it to turno tools, and with `"sharing": "tabs"`
5
+ * keys each session's backend and tab locks on it (`sharing.ts`).
6
6
  */
7
7
  export declare const SESSION_META_KEY = "io.turno/session";
8
+ /**
9
+ * The experimental capability a server declares in `initialize` to hear when a client session
10
+ * ends: mcpd then sends it `SESSION_ENDED_METHOD` with `{ session: <the id above> }` for each
11
+ * session that made a call and went away. A server without it never gets the notification.
12
+ */
13
+ export declare const SESSION_CAPABILITY = "io.turno/sessions";
14
+ /** The notification mcpd sends when a client session ends (see `SESSION_CAPABILITY`). */
15
+ export declare const SESSION_ENDED_METHOD = "notifications/io.turno/session_ended";
8
16
  /**
9
17
  * The session id in a request's `_meta`, or undefined when there is none or it is not a short
10
18
  * printable string (a client talking to the server directly may send anything there).
package/dist/session.js CHANGED
@@ -1,10 +1,18 @@
1
1
  /**
2
2
  * The client session mcpd relays a call for. mcpd puts an opaque id, stable for one
3
3
  * client session and different for every other, in the `_meta` of each `tools/call` it
4
- * forwards, under this key. The host reads it and hands it to turno tools; nothing else
5
- * depends on it yet (a later stage keys per-tab locks on it).
4
+ * forwards, under this key. The host hands it to turno tools, and with `"sharing": "tabs"`
5
+ * keys each session's backend and tab locks on it (`sharing.ts`).
6
6
  */
7
7
  export const SESSION_META_KEY = "io.turno/session";
8
+ /**
9
+ * The experimental capability a server declares in `initialize` to hear when a client session
10
+ * ends: mcpd then sends it `SESSION_ENDED_METHOD` with `{ session: <the id above> }` for each
11
+ * session that made a call and went away. A server without it never gets the notification.
12
+ */
13
+ export const SESSION_CAPABILITY = "io.turno/sessions";
14
+ /** The notification mcpd sends when a client session ends (see `SESSION_CAPABILITY`). */
15
+ export const SESSION_ENDED_METHOD = "notifications/io.turno/session_ended";
8
16
  /** Longest session id accepted; mcpd sends a UUID. */
9
17
  const MAX_SESSION = 128;
10
18
  /**