pi-agent-browser-native 0.6.5 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.md +20 -5
- package/dist/extensions/agent-browser/index.js +138 -75
- package/dist/extensions/agent-browser/lib/command-taxonomy.js +6 -5
- package/dist/extensions/agent-browser/lib/electron/cleanup.js +10 -1
- package/dist/extensions/agent-browser/lib/input-modes/params.js +20 -7
- package/dist/extensions/agent-browser/lib/launch-scoped-flags.js +0 -1
- package/dist/extensions/agent-browser/lib/managed-session-restore.js +13 -12
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/click-dispatch.js +6 -25
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result.js +2 -3
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/index.js +10 -3
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-policy.js +4 -1
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/wait-timeouts.js +1 -1
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare.js +104 -117
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output.js +61 -35
- package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state.js +100 -135
- package/dist/extensions/agent-browser/lib/orchestration/electron-host/index.js +3 -1
- package/dist/extensions/agent-browser/lib/orchestration/input-plan.js +3 -1
- package/dist/extensions/agent-browser/lib/page-target-validation.js +10 -10
- package/dist/extensions/agent-browser/lib/parsing.js +7 -0
- package/dist/extensions/agent-browser/lib/playbook.js +5 -8
- package/dist/extensions/agent-browser/lib/process-identity.js +10 -2
- package/dist/extensions/agent-browser/lib/process.js +23 -7
- package/dist/extensions/agent-browser/lib/recording-reservations.js +3 -1
- package/dist/extensions/agent-browser/lib/results/envelope.js +4 -1
- package/dist/extensions/agent-browser/lib/results/presentation/artifacts.js +45 -43
- package/dist/extensions/agent-browser/lib/results/recovery-actions.js +4 -4
- package/dist/extensions/agent-browser/lib/runtime.js +18 -2
- package/dist/extensions/agent-browser/lib/session-page-state.js +29 -10
- package/docs/ARCHITECTURE.md +7 -4
- package/docs/COMMAND_REFERENCE.md +22 -15
- package/docs/ELECTRON.md +6 -6
- package/docs/RELEASE.md +14 -5
- package/docs/REQUIREMENTS.md +1 -1
- package/docs/SUPPORT_MATRIX.md +13 -3
- package/docs/TOOL_CONTRACT.md +33 -22
- package/package.json +1 -1
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { rm } from "node:fs/promises";
|
|
2
|
-
import { getAgentBrowserSessionIdentityKey
|
|
2
|
+
import { getAgentBrowserSessionIdentityKey } from "../../argv-grammar.js";
|
|
3
|
+
import { parseArgvDescriptor } from "../../argv-descriptor.js";
|
|
4
|
+
import { needsManagedSession } from "../../command-policy.js";
|
|
3
5
|
import { runAgentBrowserProcess } from "../../process.js";
|
|
4
6
|
import { buildAgentBrowserNextActions } from "../../results/action-recommendations.js";
|
|
5
7
|
import { parseAgentBrowserEnvelope } from "../../results/envelope.js";
|
|
6
8
|
import { buildNextToolAction, withOptionalNamespaceArgs, withOptionalSessionArgs } from "../../results/next-actions.js";
|
|
7
|
-
import { getSessionPageStateKey, isAboutBlankUrl, normalizeComparableUrl,
|
|
8
|
-
import { isCloseCommand, isElectronPostCommandHealthCommand, isNavigationObservableCommandName, isRefGuardedCommand, isRefInvalidatingBatchCommand, isSessionTabPinningExcludedCommand, isSessionTabPostCommandCorrectionExcludedCommand, } from "../../command-taxonomy.js";
|
|
9
|
+
import { getSessionPageStateKey, isAboutBlankUrl, normalizeComparableUrl, targetsMatch, } from "../../session-page-state.js";
|
|
10
|
+
import { isCloseCommand, isElectronPostCommandHealthCommand, isNavigationObservableCommandName, isOpenNavigationCommand, isRefGuardedCommand, isRefInvalidatingBatchCommand, isRecordPageTransitionCommand, isSessionTabPinningExcludedCommand, isSessionTabPostCommandCorrectionExcludedCommand, isWindowOrDiffPageTransitionCommand, } from "../../command-taxonomy.js";
|
|
9
11
|
import { chooseOpenResultTabCorrection } from "../../runtime.js";
|
|
10
|
-
import { isRecord } from "../../parsing.js";
|
|
11
|
-
import { getUpstreamEffectiveBatchSteps
|
|
12
|
-
|
|
12
|
+
import { isRecord, parseRefId } from "../../parsing.js";
|
|
13
|
+
import { getUpstreamEffectiveBatchSteps } from "../batch-stdin.js";
|
|
14
|
+
import { findFirstPositionalArgument } from "./prepare/wait-timeouts.js";
|
|
13
15
|
export function applyBrowserRunStatePatch(state, patch) {
|
|
14
16
|
if (!patch)
|
|
15
17
|
return;
|
|
@@ -278,39 +280,57 @@ export function getStaleRefArgs(commandTokens, stdin) {
|
|
|
278
280
|
const steps = getUpstreamEffectiveBatchSteps(commandTokens, stdin);
|
|
279
281
|
return steps.length > 0 ? steps.flatMap((step) => step) : commandTokens;
|
|
280
282
|
}
|
|
281
|
-
//
|
|
282
|
-
// (--text, --baseline, --name, and similar) are literal text or paths that may merely look like refs,
|
|
283
|
-
// per upstream parsing. Boolean flags such as --new-tab or --full do not consume the following token,
|
|
284
|
-
// so a ref after them is a genuine positional selector and must stay guarded.
|
|
285
|
-
const SELECTOR_FLAG_TOKENS = new Set(["--selector", "-s"]);
|
|
286
|
-
const SHORT_VALUE_FLAG_TOKENS = new Set(["-b", "-o", "-t"]);
|
|
287
|
-
function isNonSelectorValueFlagToken(token) {
|
|
288
|
-
if (token === undefined || SELECTOR_FLAG_TOKENS.has(token))
|
|
289
|
-
return false;
|
|
290
|
-
return VALUE_FLAGS.has(token) || SHORT_VALUE_FLAG_TOKENS.has(token);
|
|
291
|
-
}
|
|
283
|
+
// Inspect only upstream's selector slots: fill text, file paths and key data are not refs.
|
|
292
284
|
function collectRefsFromTokens(tokens) {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
285
|
+
if (!isRefGuardedCommand(tokens[0]) || (tokens[0] === "diff" && tokens[1] !== "screenshot"))
|
|
286
|
+
return [];
|
|
287
|
+
let selectors;
|
|
288
|
+
switch (tokens[0]) {
|
|
289
|
+
case "click":
|
|
290
|
+
selectors = [tokens.slice(1).find((token) => token !== "--new-tab")];
|
|
291
|
+
break;
|
|
292
|
+
case "drag":
|
|
293
|
+
selectors = tokens.slice(1, 3);
|
|
294
|
+
break;
|
|
295
|
+
case "get":
|
|
296
|
+
selectors = [!["url", "title", "cdp-url", "count"].includes(tokens[1]) ? tokens[2] : undefined];
|
|
297
|
+
break;
|
|
298
|
+
case "is":
|
|
299
|
+
selectors = [tokens[2]];
|
|
300
|
+
break;
|
|
301
|
+
case "screenshot":
|
|
302
|
+
selectors = [tokens.slice(1).find((token) => !["--full", "-f"].includes(token))];
|
|
303
|
+
break;
|
|
304
|
+
case "diff":
|
|
305
|
+
case "scroll": {
|
|
306
|
+
let selector;
|
|
307
|
+
for (let index = tokens[0] === "diff" ? 2 : 1; index < tokens.length; index += 1) {
|
|
308
|
+
const token = tokens[index];
|
|
309
|
+
if (token === "--selector" || token === "-s")
|
|
310
|
+
selector = tokens[++index];
|
|
311
|
+
else if (tokens[0] === "diff" && ["--baseline", "-b", "--output", "-o", "--threshold", "-t", "--depth", "-d"].includes(token))
|
|
312
|
+
index += 1;
|
|
313
|
+
}
|
|
314
|
+
selectors = [selector];
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
default: selectors = [tokens[1]];
|
|
300
318
|
}
|
|
301
|
-
return
|
|
319
|
+
return selectors.flatMap((selector) => {
|
|
320
|
+
const ref = selector === undefined ? undefined : parseRefId(selector);
|
|
321
|
+
return ref === undefined ? [] : [ref];
|
|
322
|
+
});
|
|
302
323
|
}
|
|
303
324
|
export function getGuardedRefUsage(commandTokens, stdin, options = {}) {
|
|
304
|
-
const collectFromStep = (step) => isRefGuardedCommand(step[0]) ? collectRefsFromTokens(step) : [];
|
|
305
325
|
if (commandTokens[0] !== "batch") {
|
|
306
|
-
return
|
|
326
|
+
return collectRefsFromTokens(commandTokens);
|
|
307
327
|
}
|
|
308
328
|
const steps = getUpstreamEffectiveBatchSteps(commandTokens, stdin);
|
|
309
329
|
const refsBeforeInBatchSnapshot = [];
|
|
310
330
|
for (const step of steps) {
|
|
311
331
|
if (!options.includeRefsAfterBatchSnapshot && (step[0] ?? "") === "snapshot")
|
|
312
332
|
break;
|
|
313
|
-
refsBeforeInBatchSnapshot.push(...
|
|
333
|
+
refsBeforeInBatchSnapshot.push(...collectRefsFromTokens(step));
|
|
314
334
|
}
|
|
315
335
|
return refsBeforeInBatchSnapshot;
|
|
316
336
|
}
|
|
@@ -395,61 +415,41 @@ export function buildStaleRefPreflight(options) {
|
|
|
395
415
|
}
|
|
396
416
|
return undefined;
|
|
397
417
|
}
|
|
398
|
-
function
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
return false;
|
|
418
|
+
export function commandChoosesSessionTabTarget(args) {
|
|
419
|
+
const tokens = parseArgvDescriptor(args).upstreamCommandTokens;
|
|
420
|
+
const [command, subcommand] = tokens;
|
|
421
|
+
return isOpenNavigationCommand(command) || isCloseCommand(command) || command === "connect"
|
|
422
|
+
|| (command === "state" && subcommand === "load")
|
|
423
|
+
|| (command === "tab" && subcommand !== undefined && subcommand !== "list")
|
|
424
|
+
|| isWindowOrDiffPageTransitionCommand(command, subcommand)
|
|
425
|
+
|| (command === "a11y" && findFirstPositionalArgument(tokens) !== undefined)
|
|
426
|
+
|| (["vitals", "web-vitals"].includes(command) && tokens.slice(1).some((token) => !token.startsWith("--")))
|
|
427
|
+
|| (isRecordPageTransitionCommand(tokens) && tokens[3] !== undefined);
|
|
409
428
|
}
|
|
410
429
|
export function shouldPinSessionTabForCommand(options) {
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
if (parsed.error) {
|
|
433
|
-
return { error: parsed.error };
|
|
434
|
-
}
|
|
435
|
-
return {
|
|
436
|
-
includeNavigationSummary: false,
|
|
437
|
-
steps: [tabSelectionStep, ...(parsed.steps ?? [])],
|
|
438
|
-
unwrapMode: "user-batch",
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
if (options.commandTokens.length === 0) {
|
|
442
|
-
return undefined;
|
|
430
|
+
if (!options.pinningRequired || !options.sessionName || !options.command)
|
|
431
|
+
return false;
|
|
432
|
+
const steps = options.command === "batch" ? getUpstreamEffectiveBatchSteps(options.commandTokens, options.stdin) : [options.commandTokens];
|
|
433
|
+
for (const step of steps) {
|
|
434
|
+
const descriptor = parseArgvDescriptor(step);
|
|
435
|
+
const tokens = descriptor.upstreamCommandTokens;
|
|
436
|
+
const [command, subcommand] = tokens;
|
|
437
|
+
// A later page action uses the explicit destination, not the remembered tab.
|
|
438
|
+
if (commandChoosesSessionTabTarget(tokens))
|
|
439
|
+
return false;
|
|
440
|
+
if (!needsManagedSession(descriptor) || isSessionTabPinningExcludedCommand(command))
|
|
441
|
+
continue;
|
|
442
|
+
if (command === "get" && subcommand === "url" && !options.reopenPending)
|
|
443
|
+
continue;
|
|
444
|
+
if (command === "read" && findFirstPositionalArgument(tokens) !== undefined)
|
|
445
|
+
continue;
|
|
446
|
+
if (["console", "errors"].includes(command))
|
|
447
|
+
continue;
|
|
448
|
+
if (command === "network" && !(subcommand === "requests" && tokens.some((token) => ["--current-page", "--current-origin", "--current-url"].includes(token))))
|
|
449
|
+
continue;
|
|
450
|
+
return true;
|
|
443
451
|
}
|
|
444
|
-
|
|
445
|
-
const tabSelectionStep = ["tab", options.selectedTab];
|
|
446
|
-
const commandStep = options.commandTokens;
|
|
447
|
-
const navigationSummarySteps = includeNavigationSummary ? [["eval", NAVIGATION_SUMMARY_EVAL]] : [];
|
|
448
|
-
return {
|
|
449
|
-
includeNavigationSummary,
|
|
450
|
-
steps: [tabSelectionStep, commandStep, ...navigationSummarySteps],
|
|
451
|
-
unwrapMode: "single-command",
|
|
452
|
-
};
|
|
452
|
+
return false;
|
|
453
453
|
}
|
|
454
454
|
export function shouldCorrectSessionTabAfterCommand(options) {
|
|
455
455
|
return (options.pinningRequired === true &&
|
|
@@ -477,59 +477,11 @@ function selectAnySessionTargetTab(options) {
|
|
|
477
477
|
return undefined;
|
|
478
478
|
const matchingTabs = options.tabs.filter((tab) => normalizeComparableUrl(tab.url ?? "") === targetUrl);
|
|
479
479
|
const targetTitle = options.target.title?.trim() ?? "";
|
|
480
|
-
const
|
|
480
|
+
const titledTabs = targetTitle ? matchingTabs.filter((tab) => tab.title?.trim() === targetTitle) : [];
|
|
481
|
+
const selectedTab = titledTabs.find((tab) => tab.active) ?? titledTabs[0] ?? matchingTabs.find((tab) => tab.active) ?? matchingTabs[0];
|
|
481
482
|
const selection = selectedTab ? getTabSelection(selectedTab) : undefined;
|
|
482
483
|
return selection ? { ...selection, ...(targetTitle ? { targetTitle } : {}), targetUrl } : undefined;
|
|
483
484
|
}
|
|
484
|
-
export function unwrapPinnedSessionBatchEnvelope(options) {
|
|
485
|
-
if (!options.envelope) {
|
|
486
|
-
return {};
|
|
487
|
-
}
|
|
488
|
-
if (!Array.isArray(options.envelope.data)) {
|
|
489
|
-
return {
|
|
490
|
-
parseError: "agent-browser returned an unexpected response while applying the wrapper's tab-pinning batch.",
|
|
491
|
-
};
|
|
492
|
-
}
|
|
493
|
-
const steps = options.envelope.data.filter(isRecord);
|
|
494
|
-
const tabSelectionStep = steps[0];
|
|
495
|
-
const commandStep = steps[1];
|
|
496
|
-
if (tabSelectionStep?.success === false) {
|
|
497
|
-
return {
|
|
498
|
-
envelope: {
|
|
499
|
-
success: false,
|
|
500
|
-
error: tabSelectionStep.error ?? "agent-browser could not re-select the intended tab before running the command.",
|
|
501
|
-
},
|
|
502
|
-
};
|
|
503
|
-
}
|
|
504
|
-
if (options.mode === "user-batch") {
|
|
505
|
-
const userSteps = steps.slice(1);
|
|
506
|
-
return {
|
|
507
|
-
envelope: {
|
|
508
|
-
success: userSteps.every((step) => step.success !== false),
|
|
509
|
-
data: userSteps,
|
|
510
|
-
error: userSteps.find((step) => step.success === false)?.error,
|
|
511
|
-
},
|
|
512
|
-
};
|
|
513
|
-
}
|
|
514
|
-
if (!commandStep) {
|
|
515
|
-
return {
|
|
516
|
-
envelope: {
|
|
517
|
-
success: false,
|
|
518
|
-
error: "agent-browser did not return the corrected command result.",
|
|
519
|
-
},
|
|
520
|
-
};
|
|
521
|
-
}
|
|
522
|
-
const navigationSummaryStep = options.includeNavigationSummary ? steps[2] : undefined;
|
|
523
|
-
const navigationSummary = normalizeSessionTabTarget(extractNavigationSummaryFromData(navigationSummaryStep?.result));
|
|
524
|
-
return {
|
|
525
|
-
envelope: {
|
|
526
|
-
success: commandStep.success !== false,
|
|
527
|
-
data: commandStep.result,
|
|
528
|
-
error: commandStep.success === false ? commandStep.error : undefined,
|
|
529
|
-
},
|
|
530
|
-
navigationSummary,
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
485
|
export async function runSessionCommandData(options) {
|
|
534
486
|
const { args, cwd, namespace, pinNamespace, sessionName, signal, stdin, throwOnFailure, timeoutMs } = options;
|
|
535
487
|
if (!sessionName)
|
|
@@ -542,6 +494,7 @@ export async function runSessionCommandData(options) {
|
|
|
542
494
|
timeoutMs,
|
|
543
495
|
});
|
|
544
496
|
try {
|
|
497
|
+
options.onProcessResult?.(processResult);
|
|
545
498
|
if (processResult.aborted || processResult.spawnError || processResult.exitCode !== 0) {
|
|
546
499
|
if (throwOnFailure) {
|
|
547
500
|
const reason = processResult.aborted
|
|
@@ -604,11 +557,23 @@ export async function collectSessionTabSelection(options) {
|
|
|
604
557
|
const tabs = mapTabData(tabData);
|
|
605
558
|
return tabs ? selectSessionTargetTab({ tabs, target }) : undefined;
|
|
606
559
|
}
|
|
607
|
-
export async function
|
|
608
|
-
const {
|
|
609
|
-
const
|
|
610
|
-
const
|
|
611
|
-
|
|
560
|
+
export async function ensureSessionTabTarget(options) {
|
|
561
|
+
const readTabs = async () => mapTabData(await runSessionCommandData({ ...options, args: ["tab", "list"] }));
|
|
562
|
+
const tabs = await readTabs();
|
|
563
|
+
const active = tabs?.find((tab) => tab.active);
|
|
564
|
+
const correction = tabs && selectAnySessionTargetTab({ tabs, target: options.target });
|
|
565
|
+
const error = "agent-browser could not re-select and verify the intended tab before running the command. Run tab list and select the intended tab, then snapshot -i before retrying.";
|
|
566
|
+
if (!correction)
|
|
567
|
+
return { error };
|
|
568
|
+
// Native tab selection clears refs and frame scope even when selecting the current tab.
|
|
569
|
+
if (active && getTabSelection(active)?.selectedTab === correction.selectedTab)
|
|
570
|
+
return {};
|
|
571
|
+
if (!await applyOpenResultTabCorrection({ ...options, correction }))
|
|
572
|
+
return { correction, error };
|
|
573
|
+
const selected = (await readTabs())?.find((tab) => tab.active);
|
|
574
|
+
return selected && getTabSelection(selected)?.selectedTab === correction.selectedTab && normalizeComparableUrl(selected.url ?? "") === normalizeComparableUrl(options.target.url)
|
|
575
|
+
? { correction }
|
|
576
|
+
: { correction, error };
|
|
612
577
|
}
|
|
613
578
|
export async function applyOpenResultTabCorrection(options) {
|
|
614
579
|
const { correction, cwd, namespace, sessionName, signal } = options;
|
|
@@ -174,7 +174,9 @@ function formatElectronStatusVisibleText(statuses, records, mismatches = [], man
|
|
|
174
174
|
const sessionName = record?.sessionName;
|
|
175
175
|
const appName = record?.appName ?? "Electron launch";
|
|
176
176
|
const sessionText = sessionName ? `, sessionName ${sessionName}` : "";
|
|
177
|
-
|
|
177
|
+
const historyText = status.cleanupState === "cleaned" ? "; historical cleaned launch record" : "";
|
|
178
|
+
lines.push(`- ${status.launchId}: ${appName}${sessionText}${historyText}; ${status.portAlive ? "debug port alive" : "debug port dead"}${status.pidAlive === undefined ? "" : status.pidAlive ? ", pid alive" : ", pid dead"} (port ${status.port})`);
|
|
179
|
+
lines.push(` Tracked profile path: ${status.userDataDirState}.`);
|
|
178
180
|
lines.push(` Identifiers: launchId ${status.launchId}; sessionName ${sessionName ?? "not attached"}.`);
|
|
179
181
|
for (const targetLine of formatElectronTargetLines(status.targets, 4))
|
|
180
182
|
lines.push(` ${targetLine}`);
|
|
@@ -114,7 +114,9 @@ export function resolveAgentBrowserInput(options) {
|
|
|
114
114
|
const timeoutMsError = params.timeoutMs !== undefined && (typeof params.timeoutMs !== "number" || !Number.isSafeInteger(params.timeoutMs) || params.timeoutMs <= 0)
|
|
115
115
|
? "timeoutMs must be a positive integer when provided."
|
|
116
116
|
: compiledElectron && params.timeoutMs !== undefined
|
|
117
|
-
?
|
|
117
|
+
? compiledElectron.action === "list"
|
|
118
|
+
? "electron.list has no configurable timeout; remove top-level timeoutMs."
|
|
119
|
+
: "Use electron.timeoutMs for this action; top-level timeoutMs applies only to browser CLI subprocess calls."
|
|
118
120
|
: compiledScript && params.timeoutMs !== undefined && params.timeoutMs > AGENT_BROWSER_SCRIPT_MAX_TIMEOUT_MS
|
|
119
121
|
? `script timeoutMs must be ${AGENT_BROWSER_SCRIPT_MAX_TIMEOUT_MS} or less.`
|
|
120
122
|
: undefined;
|
|
@@ -38,6 +38,10 @@ function getExplicitNavigationTarget(args) {
|
|
|
38
38
|
return positionals[0];
|
|
39
39
|
if (descriptor.commandInfo.command === "tab" && descriptor.commandInfo.subcommand === "new")
|
|
40
40
|
return positionals[1];
|
|
41
|
+
if (descriptor.commandInfo.command === "window" && descriptor.commandInfo.subcommand === "new")
|
|
42
|
+
return "about:blank";
|
|
43
|
+
if (descriptor.commandInfo.command === "diff" && descriptor.commandInfo.subcommand === "url")
|
|
44
|
+
return descriptor.upstreamCommandTokens[3];
|
|
41
45
|
return undefined;
|
|
42
46
|
}
|
|
43
47
|
function getResultingExplicitNavigationTarget(args, currentPageUrl) {
|
|
@@ -149,17 +153,11 @@ export function getResultingPageTargetState(options) {
|
|
|
149
153
|
|| isUnverifiedPageTransitionCommand(descriptor.commandInfo.command, descriptor.commandInfo.subcommand);
|
|
150
154
|
return { ...getResultingPageState({ ...state, args: options.args, trustedBatchTabSelection: false }), pageTargetMayHaveChanged };
|
|
151
155
|
}
|
|
152
|
-
const
|
|
153
|
-
if (batch.error)
|
|
154
|
-
return { pageTargetMayHaveChanged: true, pageUrlUnknown: true };
|
|
155
|
-
for (let index = 0; index < batch.steps.length; index += 1) {
|
|
156
|
-
const step = batch.steps[index];
|
|
157
|
-
const trustedBatchTabSelection = options.trustedFirstBatchTabSelection === true && index === 0;
|
|
156
|
+
for (const step of options.executedBatchSteps) {
|
|
158
157
|
const stepDescriptor = parseArgvDescriptor(step);
|
|
159
158
|
pageTargetMayHaveChanged ||= getExplicitNavigationTarget(step) !== undefined
|
|
160
|
-
||
|
|
161
|
-
|
|
162
|
-
state = getResultingPageState({ ...state, args: step, trustedBatchTabSelection });
|
|
159
|
+
|| isUnverifiedPageTransitionCommand(stepDescriptor.commandInfo.command, stepDescriptor.commandInfo.subcommand);
|
|
160
|
+
state = getResultingPageState({ ...state, args: step, trustedBatchTabSelection: false });
|
|
163
161
|
}
|
|
164
162
|
return { ...state, pageTargetMayHaveChanged };
|
|
165
163
|
}
|
|
@@ -189,6 +187,9 @@ export function getPageTargetValidationError(options) {
|
|
|
189
187
|
if (["close", "exit", "quit"].includes(command ?? ""))
|
|
190
188
|
return undefined;
|
|
191
189
|
if (command === "batch") {
|
|
190
|
+
if (descriptor.upstreamCommandTokens.slice(1).some((token) => token.startsWith("--bail="))) {
|
|
191
|
+
return "Use exact batch --bail for fail-fast, or omit it to continue after errors. --bail=<value> is a raw command upstream; stdin is ignored when raw batch arguments are present.";
|
|
192
|
+
}
|
|
192
193
|
const batch = getBatchCommandSteps(options.args, options.stdin);
|
|
193
194
|
if (batch.error)
|
|
194
195
|
return batch.error.startsWith("agent_browser batch stdin") || batch.error === NESTED_BATCH_ARGUMENT_MESSAGE
|
|
@@ -262,7 +263,6 @@ export function getExplicitSessionPageVerificationRequirement(options) {
|
|
|
262
263
|
pageUrlUnknown: true,
|
|
263
264
|
stdin: options.stdin,
|
|
264
265
|
allowUnverifiedPageTransitions: true,
|
|
265
|
-
trustedFirstBatchTabSelection: options.trustedFirstBatchTabSelection,
|
|
266
266
|
});
|
|
267
267
|
return validationError === UNVERIFIED_PAGE_MESSAGE || validationError === BATCH_UNVERIFIED_PAGE_MESSAGE || validationError === NON_BAIL_BATCH_NAVIGATION_MESSAGE
|
|
268
268
|
? UNVERIFIED_PAGE_MESSAGE
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
export function isRecord(value) {
|
|
2
2
|
return typeof value === "object" && value !== null;
|
|
3
3
|
}
|
|
4
|
+
/** Upstream native element::parse_ref accepts @eN, ref=eN and bare eN. */
|
|
5
|
+
export function parseRefId(selector) {
|
|
6
|
+
const trimmed = selector.trim();
|
|
7
|
+
const prefixed = trimmed.startsWith("@") || trimmed.startsWith("ref=");
|
|
8
|
+
const candidate = trimmed.startsWith("@") ? trimmed.slice(1) : trimmed.startsWith("ref=") ? trimmed.slice(4) : trimmed;
|
|
9
|
+
return (prefixed ? /^e\d*$/ : /^e\d+$/).test(candidate) ? candidate : undefined;
|
|
10
|
+
}
|
|
4
11
|
export function parsePositiveInteger(rawValue) {
|
|
5
12
|
if (typeof rawValue !== "string")
|
|
6
13
|
return undefined;
|
|
@@ -13,7 +13,7 @@ export const QUICK_START_GUIDELINES = [
|
|
|
13
13
|
"Common first calls (first-call recipe): { args: [\"open\", \"<url>\"] } → { args: [\"snapshot\", \"-i\"] } → { args: [\"click\", \"@eN\"] } or { args: [\"fill\", \"@eN\", \"<text>\"] } using @refs and visible labels from that snapshot, then { args: [\"snapshot\", \"-i\"] } after navigation or DOM changes. On https://example.com/ the main link label is Learn more (use exact snapshot text, not guessed link copy).",
|
|
14
14
|
"Locator-first clicks/fills and native select changes without hand-building argv: { semanticAction: { action: \"click\", locator: \"text\", value: \"Close\" } }, { semanticAction: { action: \"fill\", locator: \"label\", value: \"Email\", text: \"user@example.com\" } }, direct current targets such as { semanticAction: { action: \"fill\", selector: \"@e1\", text: \"prompt\" } }, or { semanticAction: { action: \"select\", selector: \"#flavor\", value: \"chocolate\" } }; add semanticAction.session when targeting a named upstream browser session; details.compiledSemanticAction shows the semantic target, while details.effectiveArgs may show a resolved current @ref for active-session role/name click/check/fill actions to avoid hidden duplicate matches; semanticAction does not expose uncheck while upstream find ... uncheck is not runtime-supported, so use raw uncheck with a stable selector or current ref; selector-not-found failures may append bounded click try-*-candidate next actions or, for fill misses with current editable refs, details.richInputRecovery with focus/click actions that do not copy fill text; stale-ref failures can return retry-semantic-action-after-stale-ref for compiled find actions when retry safety is provable.",
|
|
15
15
|
`Common advanced calls: { args: ["batch", "--bail"], stdin: "[[\"open\",\"https://example.com\"],[\"snapshot\",\"-i\"]]" }, { job: { steps: [{ action: "open", url: "https://example.com" }, { action: "assertText", text: "Example Domain" }, { action: "screenshot", path: ".dogfood/example.png" }] } }, { qa: { url: "https://example.com", expectedText: "Example Domain", screenshotPath: ".dogfood/qa-example.png" } } (example.com smoke only; elsewhere match exact visible text from snapshot -i), { electron: { action: "list", query: "code" } }, { electron: { action: "launch", appName: "Visual Studio Code", handoff: "snapshot" } }, { electron: { action: "probe" } }, { qa: { attached: true, expectedText: "Explorer" } }, { args: ["eval", "--stdin"], stdin: "document.title", outputPath: "logs/page-title.json" }, { args: ["auth", "save", "name", "--password-stdin"], stdin: "<password from user-approved secret source>" }, { args: ["--profile", "Default", "open", "https://example.com/account"], sessionMode: "fresh" }, and { args: ["open", "--enable", "react-devtools", "https://example.com"], sessionMode: "fresh" }. For app pages with a native dropdown, job steps can include { action: "select", selector: "#flavor", value: "chocolate" } before the dependent assertion; for locator-friendly pages, job click/fill steps can use semantic locator fields such as { action: "fill", locator: "role", role: "searchbox", name: "Search", text: "agent browser" }; for human-paced input, job type steps can use { action: "type", selector: "#prompt", text: "hello", delayMs: 20, press: "Enter" }; delayed typing is capped at 200 characters per step, and generated per-character rows are compacted in visible batch prose while full rows remain in details.batchSteps.`,
|
|
16
|
-
"Constrained job navigation is explicit only: click (and select/submit flows that may navigate) does not prove the next page loaded; add an assertUrl that does not already match the starting page and/or assertText for new page state after navigation-prone steps before screenshot or later interactions. Keep jobs short around navigation, click, and rerender boundaries on dynamic React/product apps; avoid a whole checkout in one job. If a long job times out and details.timeoutPartialProgress shows a mutating incomplete step, inspect current page state and continue with a shorter job or single action instead of blindly retrying the mutating step. Example: { job: { steps: [{ action: \"open\", url: \"https://shop.example/checkout\" }, { action: \"fill\", selector: \"#email\", text: \"user@example.com\" }, { action: \"click\", selector: \"#continue\" }, { action: \"assertUrl\", url: \"**/shipping\" }, { action: \"assertText\", text: \"Shipping address\" }, { action: \"screenshot\", path: \".dogfood/shipping.png\" }] } }. Top-level click may add pageChangeSummary hints, but job never auto-inserts post-click asserts.",
|
|
16
|
+
"Constrained job navigation is explicit only: click (and select/submit flows that may navigate) does not prove the next page loaded; add an assertUrl that does not already match the starting page and/or assertText for new page state after navigation-prone steps before screenshot or later interactions. assertText takes only text, not selector or locator fields. Clicks can stale subsequent @refs: split the job and re-snapshot before using those refs. Keep jobs short around navigation, click, and rerender boundaries on dynamic React/product apps; avoid a whole checkout in one job. If a long job times out and details.timeoutPartialProgress shows a mutating incomplete step, inspect current page state and continue with a shorter job or single action instead of blindly retrying the mutating step. Example: { job: { steps: [{ action: \"open\", url: \"https://shop.example/checkout\" }, { action: \"fill\", selector: \"#email\", text: \"user@example.com\" }, { action: \"click\", selector: \"#continue\" }, { action: \"assertUrl\", url: \"**/shipping\" }, { action: \"assertText\", text: \"Shipping address\" }, { action: \"screenshot\", path: \".dogfood/shipping.png\" }] } }. Top-level click may add pageChangeSummary hints, but job never auto-inserts post-click asserts.",
|
|
17
17
|
"High-value command reference: click <selector> --new-tab opens link-like targets in a new tab; select <selector> <value...> changes native dropdown values; wrapper-handled scroll <dir> [px|percent] and scroll to end/top target document scrolling before upstream fallback, while scroll <selector> <dir> [px|percent] targets nested scrollers; download <selector> <path> saves a file triggered by a click; read [url] returns agent-readable text (explicit URLs prefer markdown without requiring a Chrome page; omit the URL for rendered active-tab DOM); get title/url need no selector; get text/html/value/count <selector> and get attr <selector> <name> read elements/page state (use body for whole-page text/html); screenshot [selector] [path] captures a page or element image; pdf <path> saves a PDF; tab list and tab <tab-id-or-label> inspect or recover the active tab; react tree, react inspect <fiberId>, react renders start/stop, and react suspense introspect React after --enable react-devtools; vitals [url] measures Core Web Vitals; pushstate <url> performs SPA navigation; tap <selector> and swipe <direction> [distance] support iOS/provider touch flows.",
|
|
18
18
|
"For artifact-producing commands, read the visible artifact block and details.artifactVerification before using files: check requested path, absolute path, existence, size bytes, artifact kind, optional mediaType, status, optional limitation, and verified/missing/pending/unverified counts. details.artifacts contains per-file metadata; record start rows are pending/openRecording until record stop writes the target. Upstream record start uses a fresh active page for video capture, so prior in-page DOM and JavaScript state does not carry over; the wrapper blocks prior @e… refs as stale-ref even when the start fails as already-active, and record restart with a URL navigates and invalidates the same way (plain record restart keeps the page), so take a fresh snapshot before continuing. The wrapper creates parent directories for direct artifact paths and can save simple loopback HTTP(S) anchor downloads directly to the requested path before upstream download fallback. Browser close does not delete explicit saved files; if close reports details.artifactCleanup, use host file tools to remove paths listed in explicitArtifactPaths (when non-empty) after inspection. If close fails with details.promptGuard.reason=requested-artifacts-missing-before-close, save the exact required artifact path before closing. A bare inbound image/video path is not a requested output artifact and does not block close. For annotated screenshots inside batch, put --annotate in top-level args (for example { args: [\"--annotate\", \"batch\"], stdin: \"[[\\\"screenshot\\\",\\\"/tmp/page.png\\\"]]\" }) rather than inside the screenshot step; if annotation labels crowd a dense page, use a scoped or non-annotated screenshot plus snapshot refs instead.",
|
|
19
19
|
"When failure output shows Next actions, prefer those exact native agent_browser follow-up payloads over guessed commands. The same actions are available in details.nextActions to callers that expose structured details; short stdin is shown inline, while long stdin stays details-only.",
|
|
@@ -46,11 +46,11 @@ export const SHARED_BROWSER_PLAYBOOK_GUIDELINES = [
|
|
|
46
46
|
"For Electron desktop apps, prefer top-level electron for wrapper-owned discovery, isolated launch, status, compact probe, and cleanup: list first, treat likely-sensitive annotations as hints rather than enforcement, launch with the default snapshot handoff unless handoff: \"tabs\" is the safer diagnostic starting point, use electron.probe or snapshot -i/qa.attached for current-session state, and always cleanup the returned launchId when done. electron.launch uses an isolated temporary profile; it does not reuse the app's normal signed-in profile or attach to an already-running authenticated app. For signed-in local app state, host-launch the normal app with --remote-debugging-port when appropriate, then use raw args connect <port|url>; after connect, run get url to verify the active target before page-content reads, inspect tab list, select the stable tab id such as tab t2, verify it again with get url, then run a condition wait or snapshot -i before using refs. close commands (`close`, `quit`, or `exit`) only close the browser/CDP session; leave manually launched app shutdown, profile cleanup, and explicit artifacts to the host owner.",
|
|
47
47
|
"For provider or specialized app workflows, load version-matched upstream guidance with skills get agentcore|electron|slack|dogfood|vercel-sandbox|derive-client through the native tool; add --full when you need references/templates, and use skills get --all only for broad skill audits. Use derive-client when recording HAR traffic to generate a standalone API client; prefer network har start (text bodies by default) or network har start --content all|none before multi-step capture. For accessibility audits use a11y or a11y --tags wcag2a,wcag2aa (CDP browsers only). Hosted sandbox workflows should use upstream @agent-browser/sandbox helpers outside this wrapper. Provider launches such as -p ios, --provider browserbase/kernel/browseruse/browserless/agentcore, and iOS --device are upstream-owned setup paths; use sessionMode fresh when switching providers and expect external credentials or local Appium/Xcode setup to be required.",
|
|
48
48
|
"For dialogs and frames, use dialog status/accept/dismiss and frame <selector|main> through native args; dialog commands and eval snippets that look like alert/confirm/prompt/dialog triggers are shorter-bounded than normal browser calls, and timed-out dialog-like interactions may add inspect-dialog-after-timeout, dismiss-dialog-after-timeout, or recover-fresh-session-after-dialog-timeout nextActions. When --confirm-actions produces a pending confirmation, use details.nextActions or exact confirm <id> / deny <id> calls instead of inventing ids.",
|
|
49
|
-
"If a session lands on the wrong page or tab, an interaction changes origin unexpectedly, or an open call returns blocked, blank, or otherwise unexpected results, use tab list / tab <tab-id-or-label> / snapshot -i to recover state before retrying different URLs or fallback strategies. For headed demos, put --headed on the first launch with sessionMode=fresh and verify with screenshot/tab/get-url evidence because tool success cannot prove the OS window is visible to the user. For desktop readiness, prefer real conditions first: wait --text, wait --url, wait --fn, wait --load <state>, wait --download, or qa.attached; for disappearance checks, use wait --fn predicates instead of stale upstream-help examples like wait <selector> --state hidden. Use electron.probe/status for wrapper-owned launch health or target mismatch. Fixed waits are a last resort:
|
|
49
|
+
"If a session lands on the wrong page or tab, an interaction changes origin unexpectedly, or an open call returns blocked, blank, or otherwise unexpected results, use tab list / tab <tab-id-or-label> / snapshot -i to recover state before retrying different URLs or fallback strategies. For headed demos, put --headed on the first launch with sessionMode=fresh and verify with screenshot/tab/get-url evidence because tool success cannot prove the OS window is visible to the user. For desktop readiness, prefer real conditions first: wait --text, wait --url, wait --fn, wait --load <state>, wait --download, or qa.attached; for disappearance checks, use wait --fn predicates instead of stale upstream-help examples like wait <selector> --state hidden. Use electron.probe/status for wrapper-owned launch health or target mismatch. Fixed waits are a last resort: their duration is positional (wait <ms>, not wait --time <ms>). Use explicit --timeout or top-level timeoutMs for legitimately slow waits, and treat a successful payload like \"waited\":\"timeout\" as elapsed time only—verify completion with an observed condition, fresh snapshot, or screenshot.",
|
|
50
50
|
"For feed, timeline, or inbox reading tasks, focus on the main timeline/list region and read the first item there rather than unrelated composer or sidebar content.",
|
|
51
51
|
"For read-only browsing tasks, use read <url> for documentation or other unstructured text without requiring a Chrome page, or read with no URL for rendered active-tab DOM. Prefer the current snapshot, structured ref labels, getters, or scoped eval --stdin when you need interactive structure or targeted page state. Only click into media viewers, detail routes, or new pages when the current view does not contain the needed information.",
|
|
52
52
|
"For downloads, prefer download <selector> <path> when an element click should save a file; simple loopback anchor downloads are saved to the requested path when the wrapper can resolve an HTTP(S) href. Do not rely on click alone when you need the downloaded file on disk.",
|
|
53
|
-
"On dashboards with nested scroll containers, verify scroll with a screenshot or fresh snapshot -i; if the viewport did not move, details.data.scrolled may be false/noMovement true and you should prefer scrollintoview <@ref> or target the actual scrollable region with scroll <selector> <dir> [px|percent]. For native selects, use select <selector> <value...> (or semanticAction/job select) instead of clicking option refs; for custom comboboxes, a click/semanticAction may only focus the field, so re-snapshot and
|
|
53
|
+
"On dashboards with nested scroll containers, verify scroll with a screenshot or fresh snapshot -i; if the viewport did not move, details.data.scrolled may be false/noMovement true and you should prefer scrollintoview <@ref> or target the actual scrollable region with scroll <selector> <dir> [px|percent]. For native selects, use select <selector> <value...> (or semanticAction/job select) instead of clicking option refs; for custom comboboxes, a click/semanticAction may only focus the field, so re-snapshot and use keyboard type <text> for focused input, press ArrowDown or press Enter, or visible option refs. Raw type requires both <selector> and <text>.",
|
|
54
54
|
"When using eval --stdin, scope checks and actions to the target element or route whenever possible instead of relying on broad page-wide text heuristics.",
|
|
55
55
|
"When using eval --stdin for extraction, pass the JavaScript through the native tool stdin field, not as an extra args token after --stdin, and return the value you want instead of relying on console.log as the primary result channel. Prefer plain expressions like ({ title: document.title }) or explicitly invoked functions like (() => ({ title: document.title }))(); use outputPath when the eval/get/snapshot data should be saved as a durable local file, but never reuse a screenshot, download, recording, or other browser artifact destination as outputPath. If a function-shaped snippet returns {}, details.evalStdinHint may warn that the function was serialized instead of called. Local file pages and caller-selected output paths are supported when upstream allows them. If get text on a broad CSS selector surfaces details.selectorTextVisibility or selectorTextVisibilityAll, prefer a visible @ref, a more specific selector, or the inspect-visible-text-candidates nextAction over hidden tab content.",
|
|
56
56
|
"When details.pageChangeSummary is present, use changeType and summary as a compact signal for navigation, DOM mutation, confirmations, or artifacts; when nextActionIds is set, match those ids to entries in details.nextActions (or per-step nextActions inside batch) for concrete follow-up payloads instead of inferring from prose alone. If details.clickDispatch reports a click-dispatch miss, refresh/inspect/retry the real click first; for static local fixtures only, an explicit eval --stdin programmatic .click() can exercise app handlers, but treat it as an untrusted scripted workaround and never use it to bypass stop-before-submit/order/purchase boundaries. If a no-navigation click surfaces details.overlayBlockers, inspect the fresh snapshot evidence before using a close/dismiss candidate nextAction; ordinary page chrome without dialog/alertdialog evidence should not trigger this diagnostic.",
|
|
@@ -62,10 +62,6 @@ export const SHARED_BROWSER_PLAYBOOK_GUIDELINES = [
|
|
|
62
62
|
];
|
|
63
63
|
export const TOOL_PROMPT_GUIDELINES_SUFFIX = [
|
|
64
64
|
"Prefer agent_browser over bash, osascript, AppleScript, or generic browser shell for sites, docs, clicks, fills, screenshots, eval, and batch.",
|
|
65
|
-
"Pass exact agent-browser CLI arguments in agent_browser args when you are not using script, semanticAction, job, or qa, excluding the binary name and --json (agent_browser injects --json automatically).",
|
|
66
|
-
"Use top-level agent_browser stdin only for eval --stdin, batch, auth save --password-stdin, or wrapper-generated job/qa batches instead of shell heredocs or password args; script puts any inner stdin on browser({ stdin }), and other command/stdin combinations are rejected before launch.",
|
|
67
|
-
`Let the agent_browser extension-managed session handle the common path unless you explicitly need a fresh launch for launch-scoped flags (${LAUNCH_SCOPED_FLAG_LABEL}).`,
|
|
68
|
-
"Use agent_browser sessionMode=fresh when switching from an existing implicit session to a new profile/browser executable/debug/init-script/provider launch without inventing a fixed explicit session name; later auto calls will follow that new session.",
|
|
69
65
|
];
|
|
70
66
|
export const INSPECTION_TOOL_CALL_EXAMPLES = [
|
|
71
67
|
'{ "args": ["--help"] }',
|
|
@@ -73,7 +69,8 @@ export const INSPECTION_TOOL_CALL_EXAMPLES = [
|
|
|
73
69
|
];
|
|
74
70
|
export const WRAPPER_TAB_RECOVERY_BEHAVIOR = [
|
|
75
71
|
"After open/goto/navigate calls with --profile, --restore, --session-name, or --state, agent_browser best-effort re-selects the tab whose URL matches the returned page when restored tabs steal focus during launch or reconnect.",
|
|
76
|
-
"After
|
|
72
|
+
"After confirmed shutdown of an automatically restored managed session, the wrapper retains its complete recorded URL, including the fragment, until the first current-page operation (including get url and reload). Non-page calls such as tab list or read <url> may start a daemon without fulfilling that reopen. The wrapper uses native open once, verifies the observed tab, and discards old refs/frame scope; it does not restore unsaved forms, JavaScript memory, or history. Explicit navigation, caller-owned/attached sessions, and restore-disabled sessions are not auto-reopened.",
|
|
73
|
+
"For a still-live browser after tab drift or resume, the wrapper verifies/selects the intended tab before ref/semantic helpers and page commands; failed selection stops the call without navigating. Local commands, read <url>, URL a11y/vitals, diff url, window new, and explicit tab/navigation/connection/state recovery do not require the prior tab. Batch checks follow effective rows past non-page prefixes and stop at explicit context changes, preserving caller argv/stdin and continue-on-error behavior. Same-tab reselection is avoided because it clears refs. Use exact batch --bail for fail-fast, not --bail=<value>. Routine same-session calls skip tab-list preflights.",
|
|
77
74
|
"For sessions with observed tab-drift risk, after a successful command on a known target tab, agent_browser also best-effort restores that intended tab if a restored/background tab steals focus after the command completes. Routine same-session commands skip this post-command tab-list probe.",
|
|
78
75
|
"If a known session target unexpectedly reports about:blank, agent_browser best-effort re-selects the prior intended target when it still exists; if recovery fails, it records the observed about:blank target and reports exact recovery guidance instead of treating the prior page as active.",
|
|
79
76
|
"If upstream reports tab_gone, the pinned bound tab is gone; use details.nextActions (tab list / tab new) instead of assuming another tab is yours.",
|
|
@@ -31,10 +31,18 @@ export function buildProcessStartIdentityCommands(pid, platform = process.platfo
|
|
|
31
31
|
return [];
|
|
32
32
|
return platform === "win32"
|
|
33
33
|
? [primary]
|
|
34
|
-
: [
|
|
34
|
+
: [
|
|
35
|
+
primary,
|
|
36
|
+
...(platform === "android"
|
|
37
|
+
? [{ ...primary, file: "/bin/ps" }, { ...primary, file: "/usr/bin/ps" }]
|
|
38
|
+
: [{ ...primary, file: "/usr/bin/ps" }, { ...primary, file: "ps" }]),
|
|
39
|
+
];
|
|
35
40
|
}
|
|
36
41
|
export function normalizeProcessStartIdentity(stdout) {
|
|
37
|
-
|
|
42
|
+
const trimmed = stdout.trim();
|
|
43
|
+
if (!trimmed || trimmed.includes("\0") || /[\r\n]/.test(trimmed))
|
|
44
|
+
return undefined;
|
|
45
|
+
return trimmed.replace(/\s+/g, " ");
|
|
38
46
|
}
|
|
39
47
|
let currentProcessStartIdentityPromise;
|
|
40
48
|
async function executeProcessStartIdentityCommand(command) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
3
|
+
import { lstat, mkdir, readdir, readlink, stat } from "node:fs/promises";
|
|
4
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
5
5
|
import { env as processEnv, platform as processPlatform } from "node:process";
|
|
6
6
|
import { parseArgvDescriptor } from "./argv-descriptor.js";
|
|
@@ -252,13 +252,30 @@ export function isTrustedSocketDirAncestor(metadata, uid, platform = processPlat
|
|
|
252
252
|
return (mode & 0o022) === 0;
|
|
253
253
|
return metadata.uid === 0 && ((mode & 0o022) === 0 || (mode & 0o1000) !== 0);
|
|
254
254
|
}
|
|
255
|
-
async function hasTrustedSocketDirAncestry(socketDir, uid) {
|
|
255
|
+
async function hasTrustedSocketDirAncestry(socketDir, uid, visited = new Set()) {
|
|
256
256
|
for (let current = dirname(socketDir);;) {
|
|
257
|
+
current = current.replace(/\/+$/, "") || "/";
|
|
258
|
+
if (visited.has(current))
|
|
259
|
+
return true;
|
|
260
|
+
visited.add(current);
|
|
257
261
|
const metadata = await lstat(current);
|
|
262
|
+
// The operating environment supplies /; its reported owner may be unmapped in a user namespace.
|
|
263
|
+
if (current === "/" && metadata.isDirectory() && (metadata.mode & 0o022) === 0)
|
|
264
|
+
return true;
|
|
258
265
|
if (isTrustedAndroidAppDataRoot(current, metadata, uid))
|
|
259
266
|
return true;
|
|
260
267
|
if (!isTrustedSocketDirAncestor(metadata, uid))
|
|
261
268
|
return false;
|
|
269
|
+
if (metadata.isSymbolicLink()) {
|
|
270
|
+
// Native stat rejects broken/cyclic links before walking their destination ancestry.
|
|
271
|
+
if (!isTrustedSocketDirAncestor(await stat(current), uid))
|
|
272
|
+
return false;
|
|
273
|
+
const target = await readlink(current);
|
|
274
|
+
const targetPath = isAbsolute(target) ? target : `${dirname(current)}/${target}`;
|
|
275
|
+
// Keep '..' after symlinks intact; '/.' includes the target itself in the parent walk.
|
|
276
|
+
if (!await hasTrustedSocketDirAncestry(`${targetPath}/.`, uid, visited))
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
262
279
|
const parent = dirname(current);
|
|
263
280
|
if (parent === current)
|
|
264
281
|
return true;
|
|
@@ -364,7 +381,7 @@ export function buildAgentBrowserProcessEnv(baseEnv = processEnv, overrides = un
|
|
|
364
381
|
clampUpstreamDefaultTimeout(childEnv);
|
|
365
382
|
return childEnv;
|
|
366
383
|
}
|
|
367
|
-
function getManagedPreSpawnPolicyError(options, currentPageUrl, pageUrlUnknown = false
|
|
384
|
+
function getManagedPreSpawnPolicyError(options, currentPageUrl, pageUrlUnknown = false) {
|
|
368
385
|
if (!validateManagedSessionRestoreContextForSpawn(options)) {
|
|
369
386
|
return "Managed session restore policy, storage, or checkout identity changed after planning; refusing to start agent-browser.";
|
|
370
387
|
}
|
|
@@ -373,11 +390,10 @@ function getManagedPreSpawnPolicyError(options, currentPageUrl, pageUrlUnknown =
|
|
|
373
390
|
currentPageUrl,
|
|
374
391
|
pageUrlUnknown,
|
|
375
392
|
stdin: options.stdin,
|
|
376
|
-
trustedFirstBatchTabSelection,
|
|
377
393
|
});
|
|
378
394
|
}
|
|
379
395
|
export async function runAgentBrowserProcess(options) {
|
|
380
|
-
const { cwd, env, managedSessionRestoreState, managedStateCurrentPageUrl, managedStatePageUrlUnknown, signal, stdin
|
|
396
|
+
const { cwd, env, managedSessionRestoreState, managedStateCurrentPageUrl, managedStatePageUrlUnknown, signal, stdin } = options;
|
|
381
397
|
const preserveAttachedBrowserSession = options.preserveAttachedBrowserSession === true || attachedBrowserSessionContext.getStore() === true;
|
|
382
398
|
const ownedManagedSession = options.ownedManagedSession === true || isOwnedManagedSessionTarget(options.args);
|
|
383
399
|
const args = options.args;
|
|
@@ -395,7 +411,7 @@ export async function runAgentBrowserProcess(options) {
|
|
|
395
411
|
restoreState: managedSessionRestoreState,
|
|
396
412
|
stdin,
|
|
397
413
|
};
|
|
398
|
-
const planningPolicyError = getManagedPreSpawnPolicyError(managedSessionRestoreOptions, managedStateCurrentPageUrl, managedStatePageUrlUnknown
|
|
414
|
+
const planningPolicyError = getManagedPreSpawnPolicyError(managedSessionRestoreOptions, managedStateCurrentPageUrl, managedStatePageUrlUnknown);
|
|
399
415
|
if (planningPolicyError) {
|
|
400
416
|
return {
|
|
401
417
|
aborted: false,
|
|
@@ -548,7 +564,7 @@ export async function runAgentBrowserProcess(options) {
|
|
|
548
564
|
});
|
|
549
565
|
};
|
|
550
566
|
const childEnv = buildAgentBrowserProcessEnv(parentEnv, effectiveEnv);
|
|
551
|
-
const spawnPolicyError = getManagedPreSpawnPolicyError(managedSessionRestoreOptions, managedStateCurrentPageUrl, managedStatePageUrlUnknown
|
|
567
|
+
const spawnPolicyError = getManagedPreSpawnPolicyError(managedSessionRestoreOptions, managedStateCurrentPageUrl, managedStatePageUrlUnknown);
|
|
552
568
|
if (spawnPolicyError) {
|
|
553
569
|
resolve({ aborted: false, agentBrowserStarted: false, exitCode: 1, spawnError: new Error(spawnPolicyError), stderr: "", stdout: "", timedOut: false });
|
|
554
570
|
return;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
1
2
|
import { getAgentBrowserSessionIdentityKey } from "./argv-grammar.js";
|
|
2
3
|
import { isRecord } from "./parsing.js";
|
|
3
4
|
import { isPendingRecordingArtifact } from "./results/artifact-manifest.js";
|
|
@@ -80,7 +81,8 @@ function parseReservationTransition(data) {
|
|
|
80
81
|
state: "closed",
|
|
81
82
|
};
|
|
82
83
|
}
|
|
83
|
-
if (typeof data.absolutePath !== "string" ||
|
|
84
|
+
if (typeof data.absolutePath !== "string" || !isAbsolute(data.absolutePath)
|
|
85
|
+
|| typeof data.cwd !== "string" || !isAbsolute(data.cwd) || typeof data.path !== "string")
|
|
84
86
|
return undefined;
|
|
85
87
|
return {
|
|
86
88
|
reservation: {
|
|
@@ -48,7 +48,8 @@ export async function parseAgentBrowserEnvelope(options) {
|
|
|
48
48
|
return { parseError: error instanceof Error ? error.message : String(error) };
|
|
49
49
|
}
|
|
50
50
|
const trimmed = stdout.trim();
|
|
51
|
-
|
|
51
|
+
const plainText = typeof options !== "string" && options.plainText === true;
|
|
52
|
+
if (trimmed.length === 0 && !plainText) {
|
|
52
53
|
return { parseError: "agent-browser returned no JSON output." };
|
|
53
54
|
}
|
|
54
55
|
try {
|
|
@@ -81,6 +82,8 @@ export async function parseAgentBrowserEnvelope(options) {
|
|
|
81
82
|
return { envelope: parsed };
|
|
82
83
|
}
|
|
83
84
|
catch (error) {
|
|
85
|
+
if (plainText)
|
|
86
|
+
return { envelope: { success: true, data: trimmed } };
|
|
84
87
|
const message = error instanceof Error ? error.message : String(error);
|
|
85
88
|
return { parseError: `agent-browser returned invalid JSON: ${message}` };
|
|
86
89
|
}
|