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/flows.js ADDED
@@ -0,0 +1,294 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { browserPaths as paths } from "turno-core/paths";
4
+ import { assertIdentityId } from "./ids.js";
5
+ /**
6
+ * Saved flows: the browser actions a session made on an identity, stored so that
7
+ * `browser_replay` (and `turno browser replay`) can run them again without the model working
8
+ * the page out a second time. One JSON file per flow, under `<data>/browser/flows/<id>/`, next
9
+ * to the identity's other files and never inside its Chrome profile.
10
+ *
11
+ * What a flow file holds, and what it never holds:
12
+ *
13
+ * - Each step names a browser tool and its arguments. An element is kept as several
14
+ * locators (Playwright's own pick, role and accessible name, visible text, a CSS path), tried
15
+ * in that order on replay, plus the snapshot ref it had (for reading only: refs change with
16
+ * every snapshot, so replay never uses one).
17
+ * - Text typed into a field is a parameter (`{ "$param": "email" }`). A non-sensitive one keeps
18
+ * what was typed as its default; a sensitive one (a password field, a one-time code, a card
19
+ * number, a value the agent marked) keeps no value at all, so replay needs it again.
20
+ * - A vault sign-in is a `browser_login` step with the site's name only: the values stay in
21
+ * the secret store and are read again at replay.
22
+ */
23
+ /** The flow file format this package writes and reads. */
24
+ export const FLOW_FORMAT_VERSION = 1;
25
+ /** Most steps one flow holds. */
26
+ export const MAX_FLOW_STEPS = 200;
27
+ const FLOW_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
28
+ /** The prefix of the flows an identity records by itself (`record.flows`). */
29
+ export const AUTO_PREFIX = "auto-";
30
+ export class FlowError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "FlowError";
34
+ }
35
+ }
36
+ function isValidFlowName(name) {
37
+ return FLOW_NAME.test(name);
38
+ }
39
+ export function assertFlowName(name) {
40
+ if (!isValidFlowName(name))
41
+ throw new FlowError(`invalid flow name "${name}": use up to 64 lowercase letters, digits, "-" and "_", starting with a letter or digit`);
42
+ }
43
+ /** Where an identity's flows live: `<data>/browser/flows/<id>`. */
44
+ export function flowsDir(id, env = process.env) {
45
+ assertIdentityId(id);
46
+ return join(paths(env).browserDir, "flows", id);
47
+ }
48
+ export function flowPath(id, name, env = process.env) {
49
+ assertFlowName(name);
50
+ return join(flowsDir(id, env), `${name}.json`);
51
+ }
52
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
53
+ function isParamRef(v) {
54
+ return isObject(v) && typeof v.$param === "string" && Object.keys(v).length === 1;
55
+ }
56
+ /** Everything wrong with a parsed flow file; empty when it is valid. */
57
+ export function flowProblems(raw) {
58
+ if (!isObject(raw))
59
+ return ["must be a JSON object"];
60
+ const out = [];
61
+ if (typeof raw.version !== "number" || !Number.isInteger(raw.version) || raw.version < 1)
62
+ out.push("version must be a positive integer");
63
+ else if (raw.version > FLOW_FORMAT_VERSION)
64
+ return [`is format ${raw.version}, from a newer turno-browser (this one reads ${FLOW_FORMAT_VERSION}); update it`];
65
+ if (typeof raw.name !== "string" || !isValidFlowName(raw.name))
66
+ out.push("name must be a flow name");
67
+ if (typeof raw.identity !== "string")
68
+ out.push("identity must be a string");
69
+ if (raw.description !== undefined && typeof raw.description !== "string")
70
+ out.push("description must be a string");
71
+ const names = new Set();
72
+ if (!Array.isArray(raw.params))
73
+ out.push("params must be a list");
74
+ else
75
+ raw.params.forEach((p, i) => {
76
+ if (!isObject(p) || typeof p.name !== "string" || typeof p.sensitive !== "boolean")
77
+ out.push(`params[${i}] needs a name and sensitive`);
78
+ else {
79
+ names.add(p.name);
80
+ if (p.sensitive && p.default !== undefined)
81
+ out.push(`params[${i}] is sensitive and must not keep a default`);
82
+ if (p.default !== undefined && typeof p.default !== "string")
83
+ out.push(`params[${i}].default must be a string`);
84
+ }
85
+ });
86
+ if (!Array.isArray(raw.steps))
87
+ out.push("steps must be a list");
88
+ else {
89
+ if (raw.steps.length > MAX_FLOW_STEPS)
90
+ out.push(`steps holds more than ${MAX_FLOW_STEPS} steps`);
91
+ raw.steps.forEach((s, i) => {
92
+ if (!isObject(s) || typeof s.tool !== "string" || !isObject(s.args)) {
93
+ out.push(`steps[${i}] needs a tool and args`);
94
+ return;
95
+ }
96
+ for (const ref of paramRefs(s.args))
97
+ if (!names.has(ref))
98
+ out.push(`steps[${i}] uses parameter "${ref}", which params does not list`);
99
+ if (s.targets !== undefined) {
100
+ if (!isObject(s.targets))
101
+ out.push(`steps[${i}].targets must be an object`);
102
+ else
103
+ for (const [path, t] of Object.entries(s.targets)) {
104
+ if (!isObject(t) ||
105
+ !Array.isArray(t.locators) ||
106
+ t.locators.some((l) => !isObject(l) || typeof l.selector !== "string"))
107
+ out.push(`steps[${i}].targets.${path} needs a list of locators`);
108
+ }
109
+ }
110
+ });
111
+ }
112
+ return out;
113
+ }
114
+ /** The parameter names a value uses, at any depth. */
115
+ export function paramRefs(value) {
116
+ if (isParamRef(value))
117
+ return [value.$param];
118
+ if (Array.isArray(value))
119
+ return value.flatMap(paramRefs);
120
+ if (isObject(value))
121
+ return Object.values(value).flatMap(paramRefs);
122
+ return [];
123
+ }
124
+ /** A copy of `value` with every parameter slot replaced by its value. */
125
+ export function fillParams(value, values) {
126
+ if (isParamRef(value))
127
+ return values[value.$param];
128
+ if (Array.isArray(value))
129
+ return value.map((v) => fillParams(v, values));
130
+ if (isObject(value))
131
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fillParams(v, values)]));
132
+ return value;
133
+ }
134
+ /** Reads `a.b.0.c` of an object. */
135
+ export function getPath(obj, path) {
136
+ let cur = obj;
137
+ for (const key of path.split(".")) {
138
+ if (Array.isArray(cur))
139
+ cur = cur[Number(key)];
140
+ else if (isObject(cur))
141
+ cur = cur[key];
142
+ else
143
+ return undefined;
144
+ }
145
+ return cur;
146
+ }
147
+ /** Sets `a.b.0.c` of an object that already has every level but the last. */
148
+ export function setPath(obj, path, value) {
149
+ const keys = path.split(".");
150
+ let cur = obj;
151
+ for (const key of keys.slice(0, -1))
152
+ cur = Array.isArray(cur) ? cur[Number(key)] : cur[key];
153
+ const last = keys[keys.length - 1];
154
+ if (Array.isArray(cur))
155
+ cur[Number(last)] = value;
156
+ else if (isObject(cur))
157
+ cur[last] = value;
158
+ }
159
+ /**
160
+ * The parameter values a replay runs with: the given ones, then the defaults. `missing` lists
161
+ * the parameters with neither (every sensitive one not given), `unknown` the given names the
162
+ * flow does not have.
163
+ */
164
+ export function resolveParams(flow, given = {}) {
165
+ const values = {};
166
+ const missing = [];
167
+ for (const p of flow.params) {
168
+ const v = given[p.name] ?? p.default;
169
+ if (v === undefined)
170
+ missing.push(p);
171
+ else
172
+ values[p.name] = v;
173
+ }
174
+ const known = new Set(flow.params.map((p) => p.name));
175
+ return { values, missing, unknown: Object.keys(given).filter((k) => !known.has(k)) };
176
+ }
177
+ /** A step in a few words: `browser_click "Sign in" button`, `browser_navigate https://...`. */
178
+ export function describeStep(step) {
179
+ const t = step.targets?.target ?? step.targets?.startTarget;
180
+ const a = step.args;
181
+ if (step.tool === "browser_login")
182
+ return `browser_login site "${String(a.site)}"`;
183
+ if (step.tool === "browser_replay")
184
+ return `browser_replay flow "${String(a.flow)}"`;
185
+ if (step.tool === "browser_fill_form") {
186
+ const fields = Array.isArray(a.fields) ? a.fields.map((f) => f.name ?? "?") : [];
187
+ return `browser_fill_form ${fields.join(", ")}`;
188
+ }
189
+ const what = t ? (t.description ?? t.locators[0]?.selector) : (a.url ?? a.key ?? a.action ?? a.text ?? a.time);
190
+ const typed = isParamRef(a.text) ? ` with {${a.text.$param}}` : "";
191
+ return `${step.tool}${what === undefined ? "" : ` ${clip(String(what), 80)}`}${typed}`;
192
+ }
193
+ function clip(text, max) {
194
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
195
+ }
196
+ /** Writes a flow (mode 600, through a rename). Validates first. */
197
+ export function writeFlow(id, flow, env = process.env) {
198
+ const problems = flowProblems(flow);
199
+ if (problems.length)
200
+ throw new FlowError(`flow "${flow.name}" ${problems.join("; ")}`);
201
+ const path = flowPath(id, flow.name, env);
202
+ mkdirSync(flowsDir(id, env), { recursive: true, mode: 0o700 });
203
+ const tmp = `${path}.${process.pid}.tmp`;
204
+ writeFileSync(tmp, `${JSON.stringify(flow, null, 2)}\n`, { mode: 0o600 });
205
+ renameSync(tmp, path);
206
+ return path;
207
+ }
208
+ /** A saved flow; throws a FlowError when there is none or it cannot be used. */
209
+ export function readFlow(id, name, env = process.env) {
210
+ const path = flowPath(id, name, env);
211
+ let text;
212
+ try {
213
+ text = readFileSync(path, "utf8");
214
+ }
215
+ catch (err) {
216
+ if (err.code === "ENOENT") {
217
+ const known = listFlows(id, env).map((f) => f.name);
218
+ throw new FlowError(`identity "${id}" has no flow "${name}"${known.length ? ` (saved: ${known.join(", ")})` : " (it has no saved flows)"}`);
219
+ }
220
+ throw new FlowError(`cannot read flow "${name}": ${err.message}`);
221
+ }
222
+ let raw;
223
+ try {
224
+ raw = JSON.parse(text);
225
+ }
226
+ catch {
227
+ throw new FlowError(`flow "${name}" (${path}) is not valid JSON`);
228
+ }
229
+ const problems = flowProblems(raw);
230
+ if (problems.length)
231
+ throw new FlowError(`flow "${name}" (${path}) ${problems.join("; ")}`);
232
+ return raw;
233
+ }
234
+ /** The identity's saved flows, newest first. Files that cannot be read are left out. */
235
+ export function listFlows(id, env = process.env) {
236
+ const dir = flowsDir(id, env);
237
+ if (!existsSync(dir))
238
+ return [];
239
+ const out = [];
240
+ for (const file of readdirSync(dir)) {
241
+ if (!file.endsWith(".json"))
242
+ continue;
243
+ const name = file.slice(0, -5);
244
+ if (!isValidFlowName(name))
245
+ continue;
246
+ let flow;
247
+ try {
248
+ flow = JSON.parse(readFileSync(join(dir, file), "utf8"));
249
+ if (flowProblems(flow).length)
250
+ continue;
251
+ }
252
+ catch {
253
+ continue;
254
+ }
255
+ const nav = flow.steps.find((s) => s.tool === "browser_navigate");
256
+ out.push({
257
+ name,
258
+ ...(flow.description ? { description: flow.description } : {}),
259
+ steps: flow.steps.length,
260
+ params: flow.params.map((p) => ({ name: p.name, sensitive: p.sensitive, hasDefault: p.default !== undefined })),
261
+ ...(nav && typeof nav.args.url === "string" ? { start: nav.args.url } : {}),
262
+ auto: name.startsWith(AUTO_PREFIX),
263
+ updated: flow.updated,
264
+ file: join(dir, file),
265
+ });
266
+ }
267
+ return out.sort((a, b) => b.updated.localeCompare(a.updated) || a.name.localeCompare(b.name));
268
+ }
269
+ /** Deletes a flow; false when there was none. */
270
+ export function removeFlow(id, name, env = process.env) {
271
+ const path = flowPath(id, name, env);
272
+ if (!existsSync(path))
273
+ return false;
274
+ rmSync(path, { force: true });
275
+ return true;
276
+ }
277
+ /** Keeps the newest `keep` flows the identity recorded by itself; returns how many went. */
278
+ export function rotateAutoFlows(id, keep, env = process.env) {
279
+ const dir = flowsDir(id, env);
280
+ if (!existsSync(dir))
281
+ return 0;
282
+ const auto = readdirSync(dir)
283
+ .filter((f) => f.startsWith(AUTO_PREFIX) && f.endsWith(".json"))
284
+ .map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
285
+ .sort((a, b) => b.t - a.t || b.f.localeCompare(a.f));
286
+ for (const { f } of auto.slice(keep))
287
+ rmSync(join(dir, f), { force: true });
288
+ return Math.max(0, auto.length - keep);
289
+ }
290
+ /** Removes every flow of an identity (when the identity goes). */
291
+ export function removeFlows(id, env = process.env) {
292
+ rmSync(flowsDir(id, env), { recursive: true, force: true });
293
+ }
294
+ //# sourceMappingURL=flows.js.map
@@ -17,17 +17,40 @@ import type { TabPolicy } from "./tuning.js";
17
17
  * A page counts as used when it is the current tab at the end of a tool call, and when its main
18
18
  * frame navigates (a person using a headed window). The current tab is never parked or closed,
19
19
  * and neither is the last page.
20
+ *
21
+ * With `"sharing": "tabs"` several sessions work in one browser: the cap counts each session's
22
+ * pages apart (`owner`) and closes only that session's least recently used page, no session's
23
+ * current tab is parked or closed (`protected`), and each note goes to the session whose page it
24
+ * is about.
25
+ *
26
+ * With `ownedOnly` (attach mode, the user's own Chrome) it governs only the agent's pages:
27
+ * the ones handed to `own` and the ones that open during a tool call or in the moments after
28
+ * one. Pages that were open before, or that open between calls, are the user's: never counted,
29
+ * parked or closed, and no popup is closed.
20
30
  */
21
31
  /** A popup that opens this long after a tool call ended still counts as the call's. */
22
32
  export declare const POPUP_GRACE_MS = 2000;
23
- export interface GovernorOptions {
33
+ /** One session's view of the tabs: its current tab and the indexes `browser_tabs` uses. */
34
+ export interface TabView {
24
35
  /** The page the stock tools act on (upstream's current tab), if any. */
25
36
  current(): Page | undefined;
26
37
  /** The pages in upstream's tab order (the indexes `browser_tabs` uses). */
27
38
  tabs(): Page[];
39
+ }
40
+ export interface GovernorOptions extends TabView {
41
+ /** Pages never parked or closed: every session's current tab (default: `current()`). */
42
+ protected?(): Page[];
43
+ /** The session that holds a page; the cap counts each owner's pages apart (default: one group). */
44
+ owner?(page: Page): string | undefined;
45
+ /** Runs first for each page Chrome opens, before the popup check and the cap. */
46
+ adopt?(page: Page): Promise<void>;
28
47
  now?: () => number;
29
48
  /** Sweep for unused pages on a timer (the default); tests call `sweep()` themselves. */
30
49
  timer?: boolean;
50
+ /** Govern only the agent's pages (see the class comment). */
51
+ ownedOnly?: boolean;
52
+ /** Told about each page counted as the agent's, with `ownedOnly`. */
53
+ onOwn?(page: Page): void;
31
54
  }
32
55
  export declare class TabGovernor {
33
56
  private readonly context;
@@ -36,6 +59,7 @@ export declare class TabGovernor {
36
59
  private readonly pages;
37
60
  private calls;
38
61
  private lastCallEnd;
62
+ /** Notes for the next result, per owner of the page they are about (undefined: whoever calls next). */
39
63
  private notes;
40
64
  private timer;
41
65
  private sweeping;
@@ -57,23 +81,34 @@ export declare class TabGovernor {
57
81
  afterCall(): Promise<void>;
58
82
  /** A tool call starts: nothing is swept and popups count as asked for until it ends. */
59
83
  beginCall(): void;
60
- /** A tool call ended: its current tab was used now. */
61
- endCall(): void;
62
- /** What the governor did since the last call, one line each, for the next tool result. */
63
- takeNotes(): string[];
84
+ /**
85
+ * Resolves once nothing the governor started before the call is still in flight: a popup
86
+ * check or a sweep may be closing a page right now, and upstream reads every tab (title,
87
+ * console) to build a result, so a page closing under the call fails it with "Target page,
88
+ * context or browser has been closed". Call after `beginCall`, which keeps new work from
89
+ * starting.
90
+ */
91
+ quiet(): Promise<void>;
92
+ /** A tool call ended: its current tab (of `view`, by default the governor's) was used now. */
93
+ endCall(view?: TabView): void;
94
+ /** Counts a page as the agent's (attach mode: the tab the host opens at connect). */
95
+ own(page: Page): void;
96
+ /** What the governor did since the last call, one line each, for the next tool result of `owner`. */
97
+ takeNotes(owner?: string): string[];
64
98
  /** The URL a parked page will load again, or undefined when it is not parked. */
65
99
  parkedUrl(page: Page): string | undefined;
66
100
  /**
67
101
  * Before a stock tool runs: when the page it is about to use is parked, load its URL again.
68
102
  * That page is the tab `browser_tabs` is about to select, else the current tab.
69
103
  */
70
- prepare(name: string, args: Record<string, unknown>): Promise<void>;
104
+ prepare(name: string, args: Record<string, unknown>, view?: TabView): Promise<void>;
71
105
  /** Marks parked tabs in a tab list of a tool result (`- 2: [](about:blank)`). */
72
- annotateTabs(text: string): string;
106
+ annotateTabs(text: string, view?: TabView): string;
73
107
  /** Parks and closes pages that went unused too long. Never while a tool call runs. */
74
108
  sweep(): Promise<void>;
75
109
  private sweepOnce;
76
110
  private openPages;
111
+ private protectedPages;
77
112
  private track;
78
113
  /** A page Chrome just opened. */
79
114
  private adopt;
package/dist/governor.js CHANGED
@@ -15,6 +15,16 @@
15
15
  * A page counts as used when it is the current tab at the end of a tool call, and when its main
16
16
  * frame navigates (a person using a headed window). The current tab is never parked or closed,
17
17
  * and neither is the last page.
18
+ *
19
+ * With `"sharing": "tabs"` several sessions work in one browser: the cap counts each session's
20
+ * pages apart (`owner`) and closes only that session's least recently used page, no session's
21
+ * current tab is parked or closed (`protected`), and each note goes to the session whose page it
22
+ * is about.
23
+ *
24
+ * With `ownedOnly` (attach mode, the user's own Chrome) it governs only the agent's pages:
25
+ * the ones handed to `own` and the ones that open during a tool call or in the moments after
26
+ * one. Pages that were open before, or that open between calls, are the user's: never counted,
27
+ * parked or closed, and no popup is closed.
18
28
  */
19
29
  /** A popup that opens this long after a tool call ended still counts as the call's. */
20
30
  export const POPUP_GRACE_MS = 2_000;
@@ -35,7 +45,8 @@ export class TabGovernor {
35
45
  pages = new Map();
36
46
  calls = 0;
37
47
  lastCallEnd = Number.NEGATIVE_INFINITY;
38
- notes = [];
48
+ /** Notes for the next result, per owner of the page they are about (undefined: whoever calls next). */
49
+ notes = new Map();
39
50
  timer;
40
51
  sweeping;
41
52
  now;
@@ -55,8 +66,9 @@ export class TabGovernor {
55
66
  this.now = options.now ?? Date.now;
56
67
  }
57
68
  start() {
58
- for (const page of this.context.pages())
59
- this.track(page);
69
+ if (!this.options.ownedOnly)
70
+ for (const page of this.context.pages())
71
+ this.track(page);
60
72
  this.context.on("page", this.onPage);
61
73
  const stages = [this.policy.parkMs, this.policy.closeMs].filter((ms) => ms > 0);
62
74
  if (stages.length && this.options.timer !== false) {
@@ -91,18 +103,38 @@ export class TabGovernor {
91
103
  beginCall() {
92
104
  this.calls++;
93
105
  }
94
- /** A tool call ended: its current tab was used now. */
95
- endCall() {
106
+ /**
107
+ * Resolves once nothing the governor started before the call is still in flight: a popup
108
+ * check or a sweep may be closing a page right now, and upstream reads every tab (title,
109
+ * console) to build a result, so a page closing under the call fails it with "Target page,
110
+ * context or browser has been closed". Call after `beginCall`, which keeps new work from
111
+ * starting.
112
+ */
113
+ async quiet() {
114
+ await Promise.all([...this.adopting, this.sweeping]);
115
+ }
116
+ /** A tool call ended: its current tab (of `view`, by default the governor's) was used now. */
117
+ endCall(view = this.options) {
96
118
  this.calls = Math.max(0, this.calls - 1);
97
119
  this.lastCallEnd = this.now();
98
- const current = this.options.current();
99
- if (current && !current.isClosed())
100
- this.track(current).lastUsed = this.now();
120
+ const current = view.current();
121
+ if (!current || current.isClosed())
122
+ return;
123
+ // A tab of the user's that the agent selected stays the user's.
124
+ if (this.options.ownedOnly && !this.pages.has(current))
125
+ return;
126
+ this.track(current).lastUsed = this.now();
127
+ }
128
+ /** Counts a page as the agent's (attach mode: the tab the host opens at connect). */
129
+ own(page) {
130
+ this.track(page);
131
+ this.options.onOwn?.(page);
101
132
  }
102
- /** What the governor did since the last call, one line each, for the next tool result. */
103
- takeNotes() {
104
- const out = this.notes;
105
- this.notes = [];
133
+ /** What the governor did since the last call, one line each, for the next tool result of `owner`. */
134
+ takeNotes(owner) {
135
+ const out = [...(this.notes.get(owner) ?? []), ...(owner === undefined ? [] : (this.notes.get(undefined) ?? []))];
136
+ this.notes.delete(owner);
137
+ this.notes.delete(undefined);
106
138
  return out;
107
139
  }
108
140
  /** The URL a parked page will load again, or undefined when it is not parked. */
@@ -113,16 +145,16 @@ export class TabGovernor {
113
145
  * Before a stock tool runs: when the page it is about to use is parked, load its URL again.
114
146
  * That page is the tab `browser_tabs` is about to select, else the current tab.
115
147
  */
116
- async prepare(name, args) {
148
+ async prepare(name, args, view = this.options) {
117
149
  if (name === "browser_tabs") {
118
150
  if (args.action !== "select" || typeof args.index !== "number")
119
151
  return;
120
- const page = this.options.tabs()[args.index];
152
+ const page = view.tabs()[args.index];
121
153
  if (page)
122
154
  await this.restore(page);
123
155
  return;
124
156
  }
125
- const current = this.options.current();
157
+ const current = view.current();
126
158
  if (!current)
127
159
  return;
128
160
  if (name === "browser_navigate") {
@@ -135,10 +167,10 @@ export class TabGovernor {
135
167
  await this.restore(current);
136
168
  }
137
169
  /** Marks parked tabs in a tab list of a tool result (`- 2: [](about:blank)`). */
138
- annotateTabs(text) {
170
+ annotateTabs(text, view = this.options) {
139
171
  if (!text.includes("](about:blank)"))
140
172
  return text;
141
- const tabs = this.options.tabs();
173
+ const tabs = view.tabs();
142
174
  return text.replace(/^(- (\d+):.*\]\(about:blank\))$/gm, (line, _all, index) => {
143
175
  const page = tabs[Number(index)];
144
176
  const url = page ? this.parkedUrl(page) : undefined;
@@ -156,17 +188,18 @@ export class TabGovernor {
156
188
  }
157
189
  async sweepOnce() {
158
190
  const { parkMs, closeMs } = this.policy;
159
- const current = this.options.current();
191
+ const kept = this.protectedPages();
160
192
  for (const [page, state] of [...this.pages]) {
161
193
  if (this.calls > 0)
162
194
  return;
163
- if (page === current || page.isClosed() || state.moving)
195
+ if (kept.includes(page) || page.isClosed() || state.moving)
164
196
  continue;
165
197
  const unused = this.now() - state.lastUsed;
166
198
  if (closeMs > 0 && unused >= closeMs && this.openPages().length > 1) {
167
199
  const url = state.parkedUrl ?? page.url();
200
+ const owner = this.options.owner?.(page);
168
201
  await page.close().catch(() => { });
169
- this.note(`closed a tab unused for ${minutes(unused)} (${shortUrl(url)})`);
202
+ this.note(`closed a tab unused for ${minutes(unused)} (${shortUrl(url)})`, owner);
170
203
  continue;
171
204
  }
172
205
  if (parkMs > 0 && unused >= parkMs && state.parkedUrl === undefined)
@@ -176,6 +209,12 @@ export class TabGovernor {
176
209
  openPages() {
177
210
  return [...this.pages.keys()].filter((p) => !p.isClosed());
178
211
  }
212
+ protectedPages() {
213
+ if (this.options.protected)
214
+ return this.options.protected();
215
+ const current = this.options.current();
216
+ return current ? [current] : [];
217
+ }
179
218
  track(page) {
180
219
  let state = this.pages.get(page);
181
220
  if (state)
@@ -195,8 +234,16 @@ export class TabGovernor {
195
234
  }
196
235
  /** A page Chrome just opened. */
197
236
  async adopt(page) {
198
- this.track(page);
199
237
  const asked = this.calls > 0 || this.now() - this.lastCallEnd < POPUP_GRACE_MS;
238
+ if (this.options.ownedOnly) {
239
+ if (!asked)
240
+ return;
241
+ this.own(page);
242
+ }
243
+ else
244
+ this.track(page);
245
+ if (this.options.adopt)
246
+ await this.options.adopt(page);
200
247
  if (this.policy.popups === "close" && !asked) {
201
248
  const opener = await page.opener().catch(() => null);
202
249
  if (opener) {
@@ -214,20 +261,21 @@ export class TabGovernor {
214
261
  const { max } = this.policy;
215
262
  if (max <= 0)
216
263
  return;
217
- const open = this.openPages();
264
+ const owner = this.options.owner?.(added);
265
+ const open = this.openPages().filter((p) => this.options.owner?.(p) === owner);
218
266
  const excess = open.length - max;
219
267
  if (excess <= 0)
220
268
  return;
221
- const current = this.options.current();
269
+ const kept = this.protectedPages();
222
270
  const lastUsed = (p) => this.pages.get(p)?.lastUsed ?? 0;
223
271
  const victims = open
224
- .filter((p) => p !== current && p !== added)
272
+ .filter((p) => !kept.includes(p) && p !== added)
225
273
  .sort((a, b) => lastUsed(a) - lastUsed(b))
226
274
  .slice(0, excess);
227
275
  for (const page of victims) {
228
276
  const url = this.pages.get(page)?.parkedUrl ?? page.url();
229
277
  await page.close().catch(() => { });
230
- this.note(`closed the least recently used tab (${shortUrl(url)}): more than ${max} were open; tab numbers changed, list them again before selecting one`);
278
+ this.note(`closed the least recently used tab (${shortUrl(url)}): more than ${max} were open; tab numbers changed, list them again before selecting one`, owner);
231
279
  }
232
280
  }
233
281
  async park(page, state, unused) {
@@ -238,7 +286,7 @@ export class TabGovernor {
238
286
  try {
239
287
  await page.goto("about:blank", { timeout: 5_000 });
240
288
  state.parkedUrl = url;
241
- this.note(`parked a tab unused for ${minutes(unused)} on about:blank (${shortUrl(url)}); using it again loads that page`);
289
+ this.note(`parked a tab unused for ${minutes(unused)} on about:blank (${shortUrl(url)}); using it again loads that page`, this.options.owner?.(page));
242
290
  }
243
291
  catch {
244
292
  /* the page would not leave (a slow unload): try again on the next sweep */
@@ -255,10 +303,10 @@ export class TabGovernor {
255
303
  state.moving = true;
256
304
  try {
257
305
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30_000 });
258
- this.note(`loaded ${shortUrl(url)} again in a tab that was parked`);
306
+ this.note(`loaded ${shortUrl(url)} again in a tab that was parked`, this.options.owner?.(page));
259
307
  }
260
308
  catch (error) {
261
- this.note(`could not load ${shortUrl(url)} again in a parked tab: ${String(error.message ?? error).split("\n")[0]}`);
309
+ this.note(`could not load ${shortUrl(url)} again in a parked tab: ${String(error.message ?? error).split("\n")[0]}`, this.options.owner?.(page));
262
310
  }
263
311
  finally {
264
312
  state.moving = false;
@@ -266,10 +314,12 @@ export class TabGovernor {
266
314
  state.lastUsed = this.now();
267
315
  }
268
316
  }
269
- note(text) {
270
- this.notes.push(text);
271
- if (this.notes.length > 20)
272
- this.notes.splice(0, this.notes.length - 20);
317
+ note(text, owner) {
318
+ const list = this.notes.get(owner) ?? [];
319
+ list.push(text);
320
+ if (list.length > 20)
321
+ list.splice(0, list.length - 20);
322
+ this.notes.set(owner, list);
273
323
  }
274
324
  }
275
325
  //# sourceMappingURL=governor.js.map
package/dist/health.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { identityStateDir } from "./ids.js";
4
+ import { names } from "./names.js";
4
5
  /** A passing check is trusted this long before the next launch checks again. */
5
6
  const HEALTH_TTL_MS = 30 * 60_000;
6
7
  /** After NEEDS_AUTH, calls fail without launching Chrome for this long (no window per call). */
@@ -41,7 +42,7 @@ export function healthDue(record, check, now = new Date()) {
41
42
  /** The tool error for an identity that is not signed in. Written for the agent to relay. */
42
43
  export function needsAuthMessage(id, record) {
43
44
  return (`NEEDS_AUTH: browser identity "${id}" is not signed in: ${record.detail ?? "the check failed"} at ${record.url} (checked ${record.checkedAt}). ` +
44
- `Ask the user to run \`turno browser login ${id}\`, sign in and close the window, then call this tool again.`);
45
+ `Ask the user to run \`${names().browser} login ${id}\`, sign in and close the window, then call this tool again.`);
45
46
  }
46
47
  const firstLine = (e) => String(e.message ?? e).split("\n")[0];
47
48
  /** Runs the check in a new tab of the identity's browser and closes the tab. */