@peakflo/agent-harness 0.2.20-rc.1 → 0.2.20

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 (34) hide show
  1. package/README.md +78 -0
  2. package/dist/browser-broker/agent-actions.mjs +799 -0
  3. package/dist/browser-broker/browsers.mjs +1699 -0
  4. package/dist/browser-broker/credentials.mjs +211 -0
  5. package/dist/browser-broker/disk-guard.mjs +84 -0
  6. package/dist/browser-broker/egress.mjs +183 -0
  7. package/dist/browser-broker/input.mjs +270 -0
  8. package/dist/browser-broker/lease.mjs +547 -0
  9. package/dist/browser-broker/local-network.mjs +173 -0
  10. package/dist/browser-broker/local.mjs +158 -0
  11. package/dist/browser-broker/log.mjs +28 -0
  12. package/dist/browser-broker/network-policy.mjs +144 -0
  13. package/dist/browser-broker/os-users.mjs +493 -0
  14. package/dist/browser-broker/package.json +1 -0
  15. package/dist/browser-broker/protocol.mjs +321 -0
  16. package/dist/browser-broker/queue.mjs +37 -0
  17. package/dist/browser-broker/recorder-scripts.mjs +221 -0
  18. package/dist/browser-broker/recorder.mjs +438 -0
  19. package/dist/browser-broker/recording-store.mjs +493 -0
  20. package/dist/browser-broker/relay.mjs +399 -0
  21. package/dist/browser-broker/screencast.mjs +198 -0
  22. package/dist/browser-broker/state-store.mjs +112 -0
  23. package/dist/browser-broker/transfers.mjs +460 -0
  24. package/dist/control-plane.d.ts +6 -0
  25. package/dist/control-plane.js +10 -0
  26. package/dist/github-workspace.d.ts +2 -0
  27. package/dist/github-workspace.js +4 -0
  28. package/dist/harness.d.ts +1 -0
  29. package/dist/harness.js +24 -0
  30. package/dist/runtime/knowledge-tools.d.ts +1 -0
  31. package/dist/runtime/knowledge-tools.js +3 -0
  32. package/dist/runtime/local-browser.d.ts +33 -0
  33. package/dist/runtime/local-browser.js +135 -0
  34. package/package.json +5 -3
@@ -0,0 +1,158 @@
1
+ /** Local preview adapter. Uses the same lease, actions, CDP stream and recorder. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { BrowserManager } from './browsers.mjs';
5
+ import { Relay } from './relay.mjs';
6
+ import { StateStore } from './state-store.mjs';
7
+ import { RecordingStore } from './recording-store.mjs';
8
+ import { BrokerError } from './protocol.mjs';
9
+ import { localNetwork } from './local-network.mjs';
10
+
11
+ let activeBrowsers = 0;
12
+
13
+ export async function startLocalBrowser(options) {
14
+ const { sessionId, root, executablePath } = options;
15
+ const network = await localNetwork({ deniedPorts: options.deniedPorts });
16
+ const user = {
17
+ name: sessionId,
18
+ home: root,
19
+ profile: path.join(root, 'profile'),
20
+ downloads: path.join(root, 'downloads'),
21
+ tmp: path.join(root, 'tmp')
22
+ };
23
+ for (const dir of [root, user.profile, user.downloads, user.tmp])
24
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
25
+ let manager;
26
+ const relay = new Relay({
27
+ ...options,
28
+ sandboxId: options.routeId,
29
+ brokerVersion: 'local-preview-1',
30
+ hello: async () => ({ browsers: manager.states(), features: [] }),
31
+ onRequest: async (msg) => {
32
+ if (msg.sessionId && msg.sessionId !== sessionId)
33
+ throw new BrokerError(
34
+ 'forbidden',
35
+ 'This browser belongs to another chat.'
36
+ );
37
+ if (
38
+ [
39
+ 'upload_begin',
40
+ 'upload_commit',
41
+ 'download_path',
42
+ 'recording_files'
43
+ ].includes(msg.t)
44
+ )
45
+ throw new BrokerError(
46
+ 'invalid_args',
47
+ 'File transfer is not available for local previews.'
48
+ );
49
+ if (
50
+ msg.t === 'command' &&
51
+ msg.name === 'navigate' &&
52
+ !network.permits(msg.args?.url)
53
+ )
54
+ throw new BrokerError(
55
+ 'invalid_args',
56
+ 'Use browser_preview_local with the port of the server you started. Do not try LAN addresses.'
57
+ );
58
+ const result = await manager.handleRequest(msg);
59
+ if (msg.t === 'close') network.revoke();
60
+ return result;
61
+ },
62
+ onPush: (msg) => {
63
+ if (msg.sessionId === sessionId) manager.handlePush(msg);
64
+ },
65
+ onDisconnect: () => manager.relayLost()
66
+ });
67
+ const unavailable = () => {
68
+ throw new BrokerError(
69
+ 'invalid_args',
70
+ 'File transfer is not available for local previews.'
71
+ );
72
+ };
73
+ manager = new BrowserManager({
74
+ relay,
75
+ maxBrowsers: 1,
76
+ trustEgressCa: null,
77
+ osUsers: {
78
+ ensure: async () => user,
79
+ lookup: () => user,
80
+ wipe: async () => {
81
+ for (const dir of [user.profile, user.downloads, user.tmp])
82
+ fs.rmSync(dir, { recursive: true, force: true });
83
+ }
84
+ },
85
+ store: new RecordingStore(path.join(root, 'recordings')),
86
+ stateStore: new StateStore(path.join(root, 'state')),
87
+ transfers: {
88
+ listDownloads: async () => [],
89
+ saveDownload: unavailable,
90
+ stageDownload: unavailable,
91
+ cancelChooser: () => {}
92
+ },
93
+ disk: { low: () => false },
94
+ previewLocal: (port) => network.allow(port),
95
+ launchContext: async (base) => {
96
+ const { chromium } = await import('playwright-core');
97
+ if (activeBrowsers >= 6)
98
+ throw new BrokerError(
99
+ 'browser_limit',
100
+ 'Close another local preview first. This runner permits six browsers.'
101
+ );
102
+ activeBrowsers++;
103
+ try {
104
+ const context = await chromium.launchPersistentContext(user.profile, {
105
+ ...base,
106
+ executablePath,
107
+ chromiumSandbox: true,
108
+ proxy: network.proxy,
109
+ env: { PATH: process.env.PATH, HOME: user.home, TMPDIR: user.tmp },
110
+ args: [
111
+ '--proxy-bypass-list=<-loopback>',
112
+ '--disable-quic',
113
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp'
114
+ ],
115
+ acceptDownloads: false
116
+ });
117
+ context.once('close', () => {
118
+ activeBrowsers--;
119
+ });
120
+ return context;
121
+ } catch (error) {
122
+ activeBrowsers--;
123
+ throw error;
124
+ }
125
+ },
126
+ configureContext: async (context) => {
127
+ await context.route('**/*', (route) =>
128
+ network.permits(route.request().url())
129
+ ? route.continue()
130
+ : route.abort('blockedbyclient')
131
+ );
132
+ // A page cannot use WebSockets to reach a second local port.
133
+ await context.routeWebSocket('**/*', (socket) => {
134
+ if (network.permits(socket.url())) socket.connectToServer();
135
+ else socket.close();
136
+ });
137
+ }
138
+ });
139
+ manager.restore();
140
+ relay.connect();
141
+ return {
142
+ updateToken: (token) => relay.setToken(token),
143
+ async close() {
144
+ relay.stop();
145
+ await network.close();
146
+ // Closing the context interrupts a long wait before draining its queue.
147
+ await Promise.all(
148
+ manager.states().map((state) =>
149
+ manager
150
+ .get(state.sessionId)
151
+ ?.context?.close()
152
+ .catch(() => undefined)
153
+ )
154
+ );
155
+ await manager.shutdown();
156
+ }
157
+ };
158
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * JSON lines on stderr. NEVER pass typed text, key names, input events,
3
+ * command args, tokens, cookies or URLs with query strings to these
4
+ * functions: the call sites log ids, codes and counts only.
5
+ */
6
+ function write(level, msg, fields) {
7
+ const line = { at: new Date().toISOString(), level, msg, ...fields };
8
+ try {
9
+ process.stderr.write(JSON.stringify(line) + '\n');
10
+ } catch {
11
+ /* stderr closed: nothing useful to do */
12
+ }
13
+ }
14
+
15
+ const DEBUG = process.env.PF_BROWSER_DEBUG === '1';
16
+
17
+ export const log = {
18
+ debug: (msg, fields = {}) => DEBUG && write('debug', msg, fields),
19
+ info: (msg, fields = {}) => write('info', msg, fields),
20
+ warn: (msg, fields = {}) => write('warn', msg, fields),
21
+ error: (msg, fields = {}) => write('error', msg, fields)
22
+ };
23
+
24
+ /** First line of an error message, bounded. Playwright appends call logs. */
25
+ export function errorText(error) {
26
+ const text = error instanceof Error ? error.message : String(error);
27
+ return text.split('\n')[0].slice(0, 300);
28
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * What a chat browser may connect to, and the clear error when it cannot start.
3
+ *
4
+ * The broker adds NO egress proxy and NO firewall of its own (owner decision);
5
+ * Daytona's restricted egress, when on, is outside the sandbox (its CA is
6
+ * trusted per chat user, see egress.mjs). Two layers keep a page in a chat
7
+ * browser away from the sandbox's own loopback services:
8
+ *
9
+ * 1. LANDLOCK (the boundary). chromium-as-user execs Chromium through
10
+ * /usr/local/bin/pf-landlock-exec, as root and BEFORE setpriv drops to the
11
+ * chat's uid, so every Chromium process (browser, network service,
12
+ * renderers) inherits a Landlock domain that refuses TCP connect() to
13
+ * BROWSER_DENIED_TCP_PORTS on every address, plus a seccomp filter for the
14
+ * known bypasses (TCP Fast Open sends, io_uring, MPTCP, non-native ABIs).
15
+ * It needs Landlock ABI >= 4 (Linux 6.7). Without it the browser does NOT
16
+ * start (fail closed): the helper exits 78 and the API gets
17
+ * LANDLOCK_UNAVAILABLE_MESSAGE.
18
+ *
19
+ * 2. CHROMIUM LOCAL NETWORK ACCESS (best effort, every port). Playwright's
20
+ * chrome-headless-shell has no enterprise-policy support at all (it reads
21
+ * no /etc/.../policies/managed file; checked on 153.0.8010.12), so the LNA
22
+ * and URLBlocklist policies cannot be used. Its LNA feature flags can:
23
+ * with LOCAL_NETWORK_ACCESS_FEATURES a page from a PUBLIC address cannot
24
+ * reach a loopback or private address (127.0.0.1, 169.254.169.254, ...)
25
+ * by fetch, no-cors, img, WebSocket, iframe/form or top-level navigation
26
+ * it starts itself; no LNA permission is ever granted (the broker sets no
27
+ * `permissions`). A page served from a private or loopback address is
28
+ * not restricted by LNA, and navigations the agent asks for are not
29
+ * page-initiated: only Landlock covers those.
30
+ *
31
+ * Keep BROWSER_DENIED_TCP_PORTS in step with bin/pf-bootstrap (the Daytona
32
+ * daemon list and the harness's fixed ports).
33
+ */
34
+
35
+ /**
36
+ * TCP ports no chat browser may connect to, on any address.
37
+ * 2280 Daytona toolbox API (runs commands as root)
38
+ * 5901, 6080 Daytona computer-use VNC / noVNC
39
+ * 22220 Daytona SSH (accepts any public key)
40
+ * 22222 Daytona web terminal (websocket to a pty)
41
+ * 33333 Daytona recording dashboard
42
+ * 7777 harness health server
43
+ * 7780 harness GitHub CONNECT proxy
44
+ * 7781 harness MCP auth proxy (PF_MCP_PROXY_PORT in pf-bootstrap)
45
+ * 7782 harness knowledge host (PF_KNOWLEDGE_PORT in pf-bootstrap)
46
+ * 7790 the broker's own credential proxy (cred-proxy.mjs, 0.15.0):
47
+ * root, substitutes secret values; a page must never reach it
48
+ */
49
+ /**
50
+ * Daytona daemon ports (v0.190.0 source). pf-bootstrap denies the SAME list to
51
+ * the harness tree (`DAYTONA_DAEMON_TCP_PORTS` there; a test keeps them equal).
52
+ */
53
+ export const DAYTONA_DAEMON_TCP_PORTS = Object.freeze([
54
+ 2280, 5901, 6080, 22220, 22222, 33333
55
+ ]);
56
+ /**
57
+ * The agent-side loopback services (harness health, GitHub proxy, MCP auth
58
+ * proxy, knowledge host, and the broker's credential proxy 7790). Denied to
59
+ * the browser only (the harness tree needs them); pf-bootstrap fixes
60
+ * 7781/7782, cred-proxy.mjs listens on 7790 (CRED_PROXY_PORT).
61
+ */
62
+ export const HARNESS_LOOPBACK_TCP_PORTS = Object.freeze([
63
+ 7777, 7780, 7781, 7782, 7790
64
+ ]);
65
+ export const BROWSER_DENIED_TCP_PORTS = Object.freeze([
66
+ ...DAYTONA_DAEMON_TCP_PORTS,
67
+ ...HARNESS_LOOPBACK_TCP_PORTS
68
+ ]);
69
+
70
+ /** The value chromium-as-user passes to `pf-landlock-exec --deny-tcp-connect`. */
71
+ export const BROWSER_DENY_TCP_ARG = BROWSER_DENIED_TCP_PORTS.join(',');
72
+
73
+ /** Exit code of pf-landlock-exec when the kernel lacks Landlock network rules. */
74
+ export const LANDLOCK_UNAVAILABLE_EXIT = 78;
75
+
76
+ export const LANDLOCK_UNAVAILABLE_MESSAGE =
77
+ "The browser cannot start: this sandbox's kernel lacks Landlock network rules (ABI 4+).";
78
+ export const LAUNCH_FAILED_MESSAGE = 'The browser could not start.';
79
+
80
+ /**
81
+ * Chromium features turned on for every chat browser. ONE --enable-features
82
+ * flag: Chromium keeps only the last one, and Playwright passes its own
83
+ * (CDPScreenshotNewSurface), which is repeated here so it is not lost.
84
+ */
85
+ export const LOCAL_NETWORK_ACCESS_FEATURES = Object.freeze([
86
+ 'LocalNetworkAccessChecks',
87
+ 'LocalNetworkAccessChecksWebSockets',
88
+ 'LocalNetworkAccessForNavigations',
89
+ 'LocalNetworkAccessForSubframeNavigations',
90
+ 'LocalNetworkAccessForWorkers'
91
+ ]);
92
+ const PLAYWRIGHT_ENABLED_FEATURES = ['CDPScreenshotNewSurface'];
93
+
94
+ export function enableFeaturesArg() {
95
+ return `--enable-features=${[...PLAYWRIGHT_ENABLED_FEATURES, ...LOCAL_NETWORK_ACCESS_FEATURES].join(',')}`;
96
+ }
97
+
98
+ /**
99
+ * The lastError for a failed launch. Playwright's launch error carries the
100
+ * browser process's stderr and `exitCode=N`; pf-landlock-exec's refusal is
101
+ * exit 78 with "Landlock network rules unavailable" on stderr.
102
+ */
103
+ export function launchFailureMessage(error) {
104
+ const text = String(error?.message ?? error ?? '');
105
+ if (
106
+ new RegExp(`exitCode=${LANDLOCK_UNAVAILABLE_EXIT}\\b`).test(text) ||
107
+ /Landlock network rules unavailable/.test(text)
108
+ ) {
109
+ return LANDLOCK_UNAVAILABLE_MESSAGE;
110
+ }
111
+ return LAUNCH_FAILED_MESSAGE;
112
+ }
113
+
114
+ /**
115
+ * For LOGGING only (nothing is blocked here): the host of a request that
116
+ * targets this machine or a link-local/private address, else null.
117
+ */
118
+ export function localTarget(url) {
119
+ let parsed;
120
+ try {
121
+ parsed = new URL(url);
122
+ } catch {
123
+ return null;
124
+ }
125
+ if (!/^(https?|wss?):$/.test(parsed.protocol)) return null;
126
+ const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase();
127
+ const local =
128
+ host === 'localhost' ||
129
+ host.endsWith('.localhost') ||
130
+ host === '::1' ||
131
+ host === '::' ||
132
+ /^0+\.\d+\.\d+\.\d+$/.test(host) ||
133
+ /^127\.\d+\.\d+\.\d+$/.test(host) ||
134
+ /^10\.\d+\.\d+\.\d+$/.test(host) ||
135
+ /^169\.254\.\d+\.\d+$/.test(host) ||
136
+ /^192\.168\.\d+\.\d+$/.test(host) ||
137
+ /^172\.(1[6-9]|2\d|3[01])\.\d+\.\d+$/.test(host) ||
138
+ /^f[cd][0-9a-f]{2}:/.test(host) ||
139
+ /^fe[89ab][0-9a-f]:/.test(host) ||
140
+ host.startsWith('::ffff:');
141
+ return local
142
+ ? `${host}:${parsed.port || (/^(https|wss):$/.test(parsed.protocol) ? 443 : 80)}`
143
+ : null;
144
+ }