agentlane 0.0.0 → 0.4.0-rc.2

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 (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,29 @@
1
+ import crypto from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { perUserTemp, SUN_PATH_LIMIT } from "../driver/paths.js";
4
+ import { evidenceDir } from "../hooks/env.js";
5
+ import { laneDir } from "../up/lane-files.js";
6
+ export function browserPaths(stateDir, laneId, session, temp = perUserTemp) {
7
+ const lane = laneDir(stateDir, laneId);
8
+ const dir = path.join(lane, 'browser');
9
+ let sockets = path.join(dir, 'ab');
10
+ if (Buffer.byteLength(path.join(sockets, `${session}.sock`)) > SUN_PATH_LIMIT) {
11
+ const digest = crypto
12
+ .createHash('sha256')
13
+ .update(`${path.resolve(stateDir)}\0${laneId}`)
14
+ .digest('hex')
15
+ .slice(0, 10);
16
+ sockets = path.join(temp(), `ab-${digest}`);
17
+ }
18
+ return {
19
+ dir,
20
+ profile: path.join(dir, 'profile'),
21
+ storageState: path.join(dir, 'signin.json'),
22
+ playwrightSessions: path.join(dir, 'playwright'),
23
+ playwrightConfigHome: path.join(dir, 'config'),
24
+ agentBrowserSockets: sockets,
25
+ output: path.join(dir, 'output'),
26
+ bin: path.join(lane, 'bin'),
27
+ evidence: evidenceDir(lane),
28
+ };
29
+ }
@@ -0,0 +1,121 @@
1
+ // playwright-core carries playwright-cli itself (lib/tools/cli-client): the CLI, its daemon and the browser registry.
2
+ export const PLAYWRIGHT_RELEASE = {
3
+ version: '1.64.0',
4
+ core: {
5
+ name: 'playwright-core',
6
+ version: '1.64.0',
7
+ tarball: 'https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz',
8
+ sha512: 'T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==',
9
+ },
10
+ browsers: [
11
+ {
12
+ name: 'chromium',
13
+ revision: '1248',
14
+ archives: {
15
+ 'darwin-arm64': {
16
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/mac-arm64/chrome-mac-arm64.zip',
17
+ size: 194_831_853,
18
+ sha256: '987d2f8499c87d21676f78178550cfcbfb1bb53786821e2cff46c5a7e99b58be',
19
+ executable: ['chrome-mac-arm64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing'],
20
+ },
21
+ 'darwin-x64': {
22
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/mac-x64/chrome-mac-x64.zip',
23
+ size: 205_332_100,
24
+ sha256: '4e75da96830224185ddddc80012ad3732d6a29a4f92bac728c84c8e8ebd66c34',
25
+ executable: ['chrome-mac-x64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing'],
26
+ },
27
+ 'linux-arm64': {
28
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/linux-arm64/chrome-linux-arm64.zip',
29
+ size: 199_750_508,
30
+ sha256: '910a12fff6170202195f72ef3d353801c7063d301ab80b1f51b77d791fda60ce',
31
+ executable: ['chrome-linux-arm64', 'chrome'],
32
+ },
33
+ 'linux-x64': {
34
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/linux64/chrome-linux64.zip',
35
+ size: 200_345_244,
36
+ sha256: '43fd31766c7533a02dda2ded5ad50c2f861cd5400be7509c0abad71129f79d79',
37
+ executable: ['chrome-linux64', 'chrome'],
38
+ },
39
+ },
40
+ },
41
+ {
42
+ name: 'chromium-headless-shell',
43
+ revision: '1248',
44
+ archives: {
45
+ 'darwin-arm64': {
46
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/mac-arm64/chrome-headless-shell-mac-arm64.zip',
47
+ size: 103_778_487,
48
+ sha256: '94e4337b70cbc5638f0935fbc46b9f242bc7416f657e3fbe924baf348404b53d',
49
+ executable: ['chrome-headless-shell-mac-arm64', 'chrome-headless-shell'],
50
+ },
51
+ 'darwin-x64': {
52
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/mac-x64/chrome-headless-shell-mac-x64.zip',
53
+ size: 109_130_614,
54
+ sha256: '8a9e4a32ba5b1a796f8b16d01896e355cf6662544d9743296394fd999d782331',
55
+ executable: ['chrome-headless-shell-mac-x64', 'chrome-headless-shell'],
56
+ },
57
+ 'linux-arm64': {
58
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/linux-arm64/chrome-headless-shell-linux-arm64.zip',
59
+ size: 125_711_061,
60
+ sha256: '81ab9d4d3c301dc5fdfb6c541b9e6632b16fc819a6a854460f40a76fe2b2c476',
61
+ executable: ['chrome-headless-shell-linux-arm64', 'chrome-headless-shell'],
62
+ },
63
+ 'linux-x64': {
64
+ url: 'https://cdn.playwright.dev/builds/cft/156.0.8078.4/linux64/chrome-headless-shell-linux64.zip',
65
+ size: 125_797_539,
66
+ sha256: 'c3e50596aef52c58f8fda3c6b3411c33d34c88b177b3ed1c2243359fd3b8ba20',
67
+ executable: ['chrome-headless-shell-linux64', 'chrome-headless-shell'],
68
+ },
69
+ },
70
+ },
71
+ {
72
+ name: 'ffmpeg',
73
+ revision: '1013',
74
+ archives: {
75
+ 'darwin-arm64': {
76
+ url: 'https://cdn.playwright.dev/dbazure/download/playwright/builds/ffmpeg/1013/ffmpeg-mac-arm64.zip',
77
+ size: 1_430_308,
78
+ sha256: '63e48ce8d4a6d9d496383e5ac557b26466e719fa29126bbbd5f5f7016ac9229c',
79
+ executable: ['ffmpeg-mac'],
80
+ },
81
+ 'darwin-x64': {
82
+ url: 'https://cdn.playwright.dev/dbazure/download/playwright/builds/ffmpeg/1013/ffmpeg-mac.zip',
83
+ size: 1_549_708,
84
+ sha256: 'ffdf08ab13def2b63e81ed9782e39debc5bd498220e8e134f9a36e984db6d9db',
85
+ executable: ['ffmpeg-mac'],
86
+ },
87
+ 'linux-arm64': {
88
+ url: 'https://cdn.playwright.dev/dbazure/download/playwright/builds/ffmpeg/1013/ffmpeg-linux-arm64.zip',
89
+ size: 2_037_513,
90
+ sha256: '457360e803a7d8d5f8f7f5ecf562b2d338f6b4f7f86339d0c31938a451e8878b',
91
+ executable: ['ffmpeg-linux'],
92
+ },
93
+ 'linux-x64': {
94
+ url: 'https://cdn.playwright.dev/dbazure/download/playwright/builds/ffmpeg/1013/ffmpeg-linux.zip',
95
+ size: 2_302_701,
96
+ sha256: 'ee986434d158f74fb5d9c5ff1092026ceedb63f324fe90b5be89460926b7b679',
97
+ executable: ['ffmpeg-linux'],
98
+ },
99
+ },
100
+ },
101
+ ],
102
+ };
103
+ // agent-browser's npm package carries the native binary for every host, so the package's integrity covers it.
104
+ export const AGENT_BROWSER_RELEASE = {
105
+ version: '0.39.0',
106
+ package: {
107
+ name: 'agent-browser',
108
+ version: '0.39.0',
109
+ tarball: 'https://registry.npmjs.org/agent-browser/-/agent-browser-0.39.0.tgz',
110
+ sha512: 'VtImIqCpHC/xJFw91IAcLlBJzebCBjynOwIKnx4kuCeI2JicpPBMKykdjQ1wmnj2dL2voNKRv8iK+Joe6aHFtw==',
111
+ },
112
+ binaries: {
113
+ 'darwin-arm64': 'bin/agent-browser-darwin-arm64',
114
+ 'darwin-x64': 'bin/agent-browser-darwin-x64',
115
+ 'linux-arm64': 'bin/agent-browser-linux-arm64',
116
+ 'linux-x64': 'bin/agent-browser-linux-x64',
117
+ },
118
+ };
119
+ export function hostKey(platform = process.platform, arch = process.arch) {
120
+ return `${platform}-${arch}`;
121
+ }
@@ -0,0 +1,19 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { lookAtPage } from "./aria.js";
4
+ import { browserOfLane } from "./lane-browser.js";
5
+ import { evidenceStamp } from "../evidence/files.js";
6
+ /** Reads the page in the lane's browser through its driver, and renders it as `look` renders a device screen. */
7
+ export async function lookAtBrowser(target, options) {
8
+ const { control } = await browserOfLane(target.tools, target.stateDir, target.lane, target.env);
9
+ const page = await control.read();
10
+ return { ...lookAtPage(page, options), url: page.url, title: page.title, driver: control.driver };
11
+ }
12
+ /** A PNG of the lane's browser viewport, taken by its driver; kept with the lane's logs unless `out` names a file. */
13
+ export async function screenshotBrowser(target, out) {
14
+ const { control, setting } = await browserOfLane(target.tools, target.stateDir, target.lane, target.env);
15
+ const file = out ?? path.join(path.dirname(setting.paths.evidence), 'shots', `browser-${evidenceStamp()}.png`);
16
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
17
+ await control.screenshot(file);
18
+ return file;
19
+ }
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs';
2
+ import { STORAGE_STATE_ENV } from "../project/schema.js";
3
+ export class SignInFailed extends Error {
4
+ problems;
5
+ constructor(file, problems, fix) {
6
+ const shown = problems.slice(0, 8).map(p => ` ${p}`);
7
+ const more = problems.length > shown.length ? [` ... and ${String(problems.length - shown.length)} more`] : [];
8
+ super(`the signin hook's saved login at ${file} is not Playwright's storage-state format:\n${[...shown, ...more].join('\n')}\nto fix: ${fix}`);
9
+ this.name = 'SignInFailed';
10
+ this.problems = problems;
11
+ }
12
+ }
13
+ const SAME_SITE = ['Strict', 'Lax', 'None'];
14
+ const WRITE_IT = `write the login there as Playwright's storage state: playwright-cli state-save "$${STORAGE_STATE_ENV}" after signing in under agentlane exec, or context.storageState({ path: process.env.${STORAGE_STATE_ENV} }) in a script, or {"cookies": [...], "origins": [...]} built from the app's own login API`;
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ }
18
+ function kind(value) {
19
+ if (value === null)
20
+ return 'null';
21
+ if (Array.isArray(value))
22
+ return 'a list';
23
+ return typeof value === 'string' ? 'text' : `a ${typeof value}`;
24
+ }
25
+ function cookieProblems(raw, i) {
26
+ const at = `cookies[${String(i)}]`;
27
+ if (!isRecord(raw))
28
+ return [`${at} is ${kind(raw)}, not an object`];
29
+ const problems = [];
30
+ for (const key of ['name', 'value', 'domain', 'path']) {
31
+ if (typeof raw[key] !== 'string')
32
+ problems.push(`${at}.${key} is ${raw[key] === undefined ? 'missing' : kind(raw[key])}; it must be text`);
33
+ }
34
+ if (typeof raw.name === 'string' && raw.name === '')
35
+ problems.push(`${at}.name is empty`);
36
+ if (typeof raw.expires !== 'number')
37
+ problems.push(`${at}.expires is ${raw.expires === undefined ? 'missing' : kind(raw.expires)}; it must be a Unix time in seconds, or -1 for a session cookie`);
38
+ for (const key of ['httpOnly', 'secure']) {
39
+ if (typeof raw[key] !== 'boolean')
40
+ problems.push(`${at}.${key} is ${raw[key] === undefined ? 'missing' : kind(raw[key])}; it must be true or false`);
41
+ }
42
+ if (!SAME_SITE.includes(raw.sameSite)) {
43
+ const got = typeof raw.sameSite === 'string' ? `"${raw.sameSite}"` : raw.sameSite === undefined ? 'missing' : kind(raw.sameSite);
44
+ problems.push(`${at}.sameSite is ${got}; Playwright takes "Strict", "Lax" or "None"`);
45
+ }
46
+ return problems;
47
+ }
48
+ function originProblems(raw, i) {
49
+ const at = `origins[${String(i)}]`;
50
+ if (!isRecord(raw))
51
+ return [`${at} is ${kind(raw)}, not an object`];
52
+ const problems = [];
53
+ if (typeof raw.origin !== 'string')
54
+ problems.push(`${at}.origin is ${raw.origin === undefined ? 'missing' : kind(raw.origin)}; it must be an origin such as http://localhost:41300`);
55
+ else {
56
+ try {
57
+ if (new URL(raw.origin).origin !== raw.origin)
58
+ problems.push(`${at}.origin "${raw.origin}" is not an origin: no path, no trailing slash`);
59
+ }
60
+ catch {
61
+ problems.push(`${at}.origin "${raw.origin}" is not a URL`);
62
+ }
63
+ }
64
+ if (!Array.isArray(raw.localStorage))
65
+ problems.push(`${at}.localStorage is ${raw.localStorage === undefined ? 'missing' : kind(raw.localStorage)}; it must be a list of {"name", "value"}`);
66
+ else {
67
+ raw.localStorage.forEach((item, j) => {
68
+ if (!isRecord(item) || typeof item.name !== 'string' || typeof item.value !== 'string')
69
+ problems.push(`${at}.localStorage[${String(j)}] must be {"name": text, "value": text}`);
70
+ });
71
+ }
72
+ return problems;
73
+ }
74
+ function cookieApplies(domain, host) {
75
+ const bare = domain.startsWith('.') ? domain.slice(1) : domain;
76
+ return host === bare || host.endsWith(`.${bare}`);
77
+ }
78
+ /** The problems with a parsed storage state; none means it is a storage state the browser can start with. */
79
+ export function storageStateProblems(raw, url) {
80
+ if (!isRecord(raw))
81
+ return [`the file holds ${kind(raw)}, not an object with "cookies" and "origins"`];
82
+ const problems = [];
83
+ if (!Array.isArray(raw.cookies))
84
+ problems.push(`"cookies" is ${raw.cookies === undefined ? 'missing' : kind(raw.cookies)}; it must be a list (empty when the app keeps its login in localStorage)`);
85
+ else
86
+ raw.cookies.forEach((c, i) => problems.push(...cookieProblems(c, i)));
87
+ if (!Array.isArray(raw.origins))
88
+ problems.push(`"origins" is ${raw.origins === undefined ? 'missing' : kind(raw.origins)}; it must be a list (empty when the app keeps its login in cookies)`);
89
+ else
90
+ raw.origins.forEach((o, i) => problems.push(...originProblems(o, i)));
91
+ if (problems.length > 0 || url === null)
92
+ return problems;
93
+ const state = raw;
94
+ const app = new URL(url);
95
+ if (state.cookies.length === 0 && state.origins.length === 0)
96
+ return ['it holds no cookie and no origin, so the browser would open the web app signed out'];
97
+ const applies = state.cookies.some(c => cookieApplies(c.domain, app.hostname)) || state.origins.some(o => o.origin === app.origin);
98
+ if (!applies) {
99
+ const domains = [...new Set(state.cookies.map(c => c.domain))];
100
+ const origins = state.origins.map(o => o.origin);
101
+ return [
102
+ `none of it applies to ${app.origin}, where the browser opens the web app: its cookies are for ${domains.join(', ') || 'no domain'}${origins.length > 0 ? ` and its origins are ${origins.join(', ')}` : ''}; write cookies for ${app.hostname}, or the origin ${app.origin}`,
103
+ ];
104
+ }
105
+ return problems;
106
+ }
107
+ function jsonPosition(error) {
108
+ const position = /position (\d+)/.exec(error instanceof Error ? error.message : '')?.[1];
109
+ return position === undefined ? '' : ` (at character ${position})`;
110
+ }
111
+ /**
112
+ * Checks the saved login the signin hook wrote, makes it readable by its owner alone, and describes it without a single
113
+ * value from it. The file's text never reaches an error or a log: a JSON error names only its position.
114
+ */
115
+ export function acceptSavedLogin(file, url) {
116
+ let text;
117
+ try {
118
+ text = fs.readFileSync(file, 'utf8');
119
+ }
120
+ catch (error) {
121
+ const missing = error.code === 'ENOENT';
122
+ throw new SignInFailed(file, [
123
+ missing
124
+ ? `the signin hook exited 0 without writing it ($${STORAGE_STATE_ENV})`
125
+ : `it can't be read: ${error.code ?? 'unknown error'}`,
126
+ ], WRITE_IT);
127
+ }
128
+ fs.chmodSync(file, 0o600);
129
+ let raw;
130
+ try {
131
+ raw = JSON.parse(text);
132
+ }
133
+ catch (error) {
134
+ throw new SignInFailed(file, [`it is not JSON${jsonPosition(error)}`], WRITE_IT);
135
+ }
136
+ const problems = storageStateProblems(raw, url);
137
+ if (problems.length > 0)
138
+ throw new SignInFailed(file, problems, WRITE_IT);
139
+ const state = raw;
140
+ return {
141
+ file,
142
+ cookies: state.cookies.length,
143
+ domains: [...new Set(state.cookies.map(c => c.domain))],
144
+ origins: state.origins.map(o => o.origin),
145
+ };
146
+ }
147
+ export function describeSavedLogin(login) {
148
+ const parts = [
149
+ `${String(login.cookies)} cookie${login.cookies === 1 ? '' : 's'}${login.domains.length > 0 ? ` for ${login.domains.join(', ')}` : ''}`,
150
+ ];
151
+ if (login.origins.length > 0)
152
+ parts.push(`local storage for ${login.origins.join(', ')}`);
153
+ return parts.join(' and ');
154
+ }
@@ -0,0 +1,163 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ const SEARCH_PATH = `${process.env.PATH ?? ''}:/usr/bin:/bin`;
5
+ function readEnviron(pid) {
6
+ if (process.platform === 'linux') {
7
+ try {
8
+ return fs.readFileSync(`/proc/${String(pid)}/environ`, 'utf8').replaceAll('\0', ' ');
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
14
+ const result = spawnSync('ps', ['eww', '-o', 'command=', '-p', String(pid)], {
15
+ encoding: 'utf8',
16
+ env: { PATH: SEARCH_PATH, LC_ALL: 'C' },
17
+ timeout: 10_000,
18
+ });
19
+ return result.status === 0 ? result.stdout : undefined;
20
+ }
21
+ export const realBrowserProcesses = {
22
+ list() {
23
+ const result = spawnSync('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,args='], {
24
+ encoding: 'utf8',
25
+ env: { PATH: SEARCH_PATH, LC_ALL: 'C' },
26
+ timeout: 10_000,
27
+ maxBuffer: 64 * 1024 * 1024,
28
+ });
29
+ if (result.status !== 0)
30
+ return undefined;
31
+ const entries = [];
32
+ for (const line of result.stdout.split('\n')) {
33
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s(.*)$/.exec(line);
34
+ if (m)
35
+ entries.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]), args: m[4] ?? '' });
36
+ }
37
+ return entries;
38
+ },
39
+ environment: readEnviron,
40
+ signal(pid, signal) {
41
+ try {
42
+ process.kill(pid, signal);
43
+ }
44
+ catch {
45
+ return;
46
+ }
47
+ },
48
+ };
49
+ /** Whether a command line starts a browser on this profile: the flag with exactly this folder, not one that extends it. */
50
+ export function onProfile(args, profile) {
51
+ const flag = `--user-data-dir=${profile}`;
52
+ for (let at = args.indexOf(flag); at !== -1; at = args.indexOf(flag, at + 1)) {
53
+ const next = args[at + flag.length];
54
+ if (next === undefined || next === ' ')
55
+ return true;
56
+ }
57
+ return false;
58
+ }
59
+ function words(args) {
60
+ return args.split(/\s+/);
61
+ }
62
+ function isPlaywrightDaemon(entry, session) {
63
+ const parts = words(entry.args);
64
+ const at = parts.findIndex(p => p.endsWith(`${path.sep}cliDaemon.js`));
65
+ return at !== -1 && parts[at + 1] === session;
66
+ }
67
+ function isAgentBrowser(entry) {
68
+ return /(^|\/)agent-browser(-[a-z0-9-]+)?(\s|$)/.test(entry.args);
69
+ }
70
+ function readPid(file) {
71
+ try {
72
+ return Number(fs.readFileSync(file, 'utf8').trim());
73
+ }
74
+ catch {
75
+ return 0;
76
+ }
77
+ }
78
+ function ancestorsOf(pid, byPid) {
79
+ const seen = new Set();
80
+ let at = byPid.get(pid);
81
+ while (at && !seen.has(at.pid)) {
82
+ seen.add(at.pid);
83
+ at = byPid.get(at.ppid);
84
+ }
85
+ return seen;
86
+ }
87
+ /**
88
+ * The processes of one lane's browser, read from the process table: the browser on the lane's profile, the driver
89
+ * daemon of the lane's session (playwright-cli's by its arguments, agent-browser's by its pid file and environment),
90
+ * and every process below them. The caller and its ancestors are never among them.
91
+ */
92
+ export function browserProcesses(system, marks, self = process.pid) {
93
+ const table = system.list();
94
+ if (!table)
95
+ return undefined;
96
+ const byPid = new Map(table.map(e => [e.pid, e]));
97
+ const spared = ancestorsOf(self, byPid);
98
+ const seeds = new Set();
99
+ for (const entry of table) {
100
+ if (onProfile(entry.args, marks.paths.profile)) {
101
+ seeds.add(entry.pid);
102
+ const parent = byPid.get(entry.ppid);
103
+ if (parent && (isPlaywrightDaemon(parent, marks.session) || isAgentBrowser(parent)))
104
+ seeds.add(parent.pid);
105
+ }
106
+ if (isPlaywrightDaemon(entry, marks.session))
107
+ seeds.add(entry.pid);
108
+ }
109
+ const recorded = byPid.get(readPid(path.join(marks.paths.agentBrowserSockets, `${marks.session}.pid`)));
110
+ if (recorded && isAgentBrowser(recorded))
111
+ seeds.add(recorded.pid);
112
+ for (const entry of table) {
113
+ if (!isAgentBrowser(entry) || seeds.has(entry.pid))
114
+ continue;
115
+ const environment = system.environment(entry.pid);
116
+ if (environment?.includes(`AGENT_BROWSER_SESSION=${marks.session}`) &&
117
+ environment.includes(marks.paths.agentBrowserSockets)) {
118
+ seeds.add(entry.pid);
119
+ }
120
+ }
121
+ const found = new Set();
122
+ const visit = (pid) => {
123
+ if (found.has(pid) || spared.has(pid))
124
+ return;
125
+ found.add(pid);
126
+ for (const child of table)
127
+ if (child.ppid === pid)
128
+ visit(child.pid);
129
+ };
130
+ for (const pid of seeds)
131
+ visit(pid);
132
+ return table.filter(e => found.has(e.pid));
133
+ }
134
+ /** Stops every process of the lane's browser: SIGTERM, a grace period, then SIGKILL, and reads the table back. */
135
+ export async function stopBrowserProcesses(system, marks, clock, graceMs = 3000) {
136
+ const first = browserProcesses(system, marks);
137
+ if (first === undefined)
138
+ return { stopped: [], left: undefined };
139
+ if (first.length === 0)
140
+ return { stopped: [], left: [] };
141
+ for (const entry of first)
142
+ system.signal(entry.pid, 'SIGTERM');
143
+ const deadline = clock.now() + graceMs;
144
+ let now = browserProcesses(system, marks) ?? first;
145
+ while (now.length > 0 && clock.now() < deadline) {
146
+ await clock.sleep(100);
147
+ now = browserProcesses(system, marks) ?? now;
148
+ }
149
+ for (const entry of now)
150
+ system.signal(entry.pid, 'SIGKILL');
151
+ if (now.length > 0) {
152
+ const until = clock.now() + 2000;
153
+ while (now.length > 0 && clock.now() < until) {
154
+ await clock.sleep(100);
155
+ now = browserProcesses(system, marks) ?? now;
156
+ }
157
+ }
158
+ const left = new Set(now.map(e => e.pid));
159
+ return { stopped: first.filter(e => !left.has(e.pid)), left: now };
160
+ }
161
+ export function describeProcesses(entries) {
162
+ return entries.map(e => `pid ${String(e.pid)} (${e.args.slice(0, 80)})`).join(', ');
163
+ }
@@ -0,0 +1,25 @@
1
+ import { realServiceSystem } from "../services/system.js";
2
+ import { controlFor } from "./control.js";
3
+ import { ensureBrowserDriver, installState } from "./install.js";
4
+ import { missingLibraries, systemLdd } from "./libraries.js";
5
+ import { realBrowserProcesses } from "./stop.js";
6
+ export async function probeUrl(url) {
7
+ try {
8
+ const response = await fetch(url, { signal: AbortSignal.timeout(3000), redirect: 'manual' });
9
+ return { status: response.status, body: await response.text() };
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ export const realBrowserTools = {
16
+ install: (driver, env, log) => ensureBrowserDriver(driver, { env, log }),
17
+ state: (driver, env) => installState(env, driver),
18
+ control: controlFor,
19
+ processes: realBrowserProcesses,
20
+ probe: probeUrl,
21
+ listeners: port => realServiceSystem.listeners(port),
22
+ missingLibraries: installed => process.platform === 'linux'
23
+ ? missingLibraries([installed.chrome, installed.headlessShell], systemLdd)
24
+ : Promise.resolve(null),
25
+ };
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { liveHolder, tryLock, unlock } from "../driver/lock.js";
4
+ import { formatAge } from "../registry/format.js";
5
+ export const BUILD_WAIT_TIMEOUT_MS = 45 * 60_000;
6
+ const BUILD_WAIT_POLL_MS = 2000;
7
+ function message(error) {
8
+ return error instanceof Error ? error.message : String(error);
9
+ }
10
+ function lockWorktree(file) {
11
+ try {
12
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
13
+ return typeof parsed.worktree === 'string' ? parsed.worktree : 'another worktree';
14
+ }
15
+ catch {
16
+ return 'another worktree';
17
+ }
18
+ }
19
+ /**
20
+ * Takes the key's build lock, or, while a live process holds it, waits for that build to land in the cache. A holder
21
+ * proven gone (its pid exited or now has another start time) loses the lock; after the timeout this process builds
22
+ * without it.
23
+ */
24
+ async function takeTurn(options, wait, key) {
25
+ const { cache, variant } = options;
26
+ const file = path.join(cache.dir, '.building', key);
27
+ fs.mkdirSync(path.dirname(file), { recursive: true });
28
+ const record = { ...wait.builder, worktree: options.worktree };
29
+ const started = wait.clock.now();
30
+ const timeoutMs = wait.timeoutMs ?? BUILD_WAIT_TIMEOUT_MS;
31
+ let waited;
32
+ for (;;) {
33
+ const attempt = tryLock(file, record, wait.processes);
34
+ const found = await cache.lookup(key, variant);
35
+ const sofar = waited ? { ...waited, ms: wait.clock.now() - started } : undefined;
36
+ if (found.hit) {
37
+ if (attempt.acquired)
38
+ unlock(file, wait.builder);
39
+ return { kind: 'served', entry: found.entry, ...(sofar ? { waited: sofar } : {}) };
40
+ }
41
+ if (attempt.acquired)
42
+ return { kind: 'build', lock: file, ...(sofar ? { waited: sofar } : {}) };
43
+ const holder = attempt.holder ?? liveHolder(file, wait.processes);
44
+ if (!waited) {
45
+ waited = { worktree: lockWorktree(file), pid: holder?.pid ?? null, ms: 0 };
46
+ const by = waited.pid === null ? '' : ` (pid ${String(waited.pid)})`;
47
+ wait.log(`waiting for ${waited.worktree}'s build of ${key.slice(0, 12)}${by}; building here instead after ${formatAge(timeoutMs)}`);
48
+ }
49
+ if (wait.clock.now() - started >= timeoutMs) {
50
+ wait.log(`stopped waiting for ${waited.worktree}'s build of ${key.slice(0, 12)} after ${formatAge(wait.clock.now() - started)}; building here`);
51
+ return { kind: 'build', lock: undefined, waited: { ...waited, ms: wait.clock.now() - started } };
52
+ }
53
+ await wait.clock.sleep(wait.pollMs ?? BUILD_WAIT_POLL_MS);
54
+ }
55
+ }
56
+ export async function cachedBuild(options) {
57
+ const { cache, variant } = options;
58
+ if (!cache.isCacheable(variant) || options.mode === 'no-cache') {
59
+ await options.build();
60
+ return { source: 'build', reason: cache.isCacheable(variant) ? 'no-cache' : 'not-cacheable', stored: false, problems: [] };
61
+ }
62
+ const problems = [];
63
+ let key;
64
+ try {
65
+ key = await options.key();
66
+ }
67
+ catch (error) {
68
+ await options.build();
69
+ return { source: 'build', reason: 'no-key', stored: false, problems: [message(error)] };
70
+ }
71
+ let reason = 'refresh';
72
+ let replace = true;
73
+ let lock;
74
+ let waited;
75
+ const serve = async (entry, waitedFor) => {
76
+ try {
77
+ await options.install(entry.output);
78
+ return { source: 'cache', key, output: entry.output, origin: entry.origin, ...(waitedFor ? { waited: waitedFor } : {}) };
79
+ }
80
+ catch (error) {
81
+ problems.push(`installing the cached build failed: ${message(error)}`);
82
+ reason = 'install-failed';
83
+ return undefined;
84
+ }
85
+ };
86
+ if (options.mode === 'use') {
87
+ const found = await cache.lookup(key, variant);
88
+ if (found.hit) {
89
+ const served = await serve(found.entry);
90
+ if (served)
91
+ return served;
92
+ }
93
+ else {
94
+ reason = 'miss';
95
+ replace = found.reason === 'broken';
96
+ if (options.wait) {
97
+ const turn = await takeTurn(options, options.wait, key);
98
+ if (turn.kind === 'served') {
99
+ const served = await serve(turn.entry, turn.waited);
100
+ if (served)
101
+ return served;
102
+ }
103
+ else {
104
+ lock = turn.lock;
105
+ waited = turn.waited;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ try {
111
+ return await buildAndStore(options, { reason, key, replace, problems, ...(waited ? { waited } : {}) });
112
+ }
113
+ finally {
114
+ if (lock !== undefined && options.wait)
115
+ unlock(lock, options.wait.builder);
116
+ }
117
+ }
118
+ async function buildAndStore(options, run) {
119
+ const { cache, variant } = options;
120
+ const { problems } = run;
121
+ const output = await options.build();
122
+ const result = {
123
+ source: 'build',
124
+ reason: run.reason,
125
+ key: run.key,
126
+ stored: false,
127
+ problems,
128
+ ...(run.waited ? { waited: run.waited } : {}),
129
+ };
130
+ let storedKey;
131
+ try {
132
+ storedKey = await options.key();
133
+ }
134
+ catch (error) {
135
+ problems.push(`the key could not be recomputed after the build, so nothing was stored: ${message(error)}`);
136
+ return result;
137
+ }
138
+ try {
139
+ const stored = await cache.store({ key: storedKey, variant, output, worktree: options.worktree, replace: run.replace });
140
+ result.stored = stored.stored;
141
+ result.storedKey = storedKey;
142
+ }
143
+ catch (error) {
144
+ problems.push(`storing the build failed: ${message(error)}`);
145
+ return result;
146
+ }
147
+ try {
148
+ result.pruned = await cache.prune();
149
+ }
150
+ catch (error) {
151
+ problems.push(`pruning the cache failed: ${message(error)}`);
152
+ }
153
+ return result;
154
+ }