@causyne/agent 1.20.118 → 1.20.120
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/package.json +1 -1
- package/src/agentLoop.js +29 -12
- package/src/agentLoop.ts +29 -16
- package/src/browser/causyneBrowser.js +231 -136
- package/src/browser/causyneBrowser.ts +229 -140
- package/src/browser/searchProviders.js +41 -30
- package/src/browser/searchProviders.ts +24 -14
- package/src/browser/workspacePathSafety.js +50 -0
- package/src/browser/workspacePathSafety.ts +50 -0
- package/src/browser/workspacePreview.js +27 -4
- package/src/browser/workspacePreview.ts +28 -4
- package/src/cliMode.js +1 -1
- package/src/commands.js +5 -13
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/providers/anthropic.js +33 -17
- package/src/providers/base.js +14 -0
- package/src/providers/dashscope-byok.js +13 -7
- package/src/providers/deepseek.js +13 -18
- package/src/providers/gemini.js +33 -25
- package/src/providers/moonshot.js +13 -12
- package/src/providers/ollama.js +21 -21
- package/src/providers/openai-compatible.js +12 -19
- package/src/providers/openrouter.js +20 -90
- package/src/providers/openrouter.ts +31 -94
- package/src/providers/qwen-byok.js +13 -7
- package/src/providers/toolContracts.js +9 -3
- package/src/providers/toolContracts.ts +9 -3
- package/src/providers/wireNormalizer.js +238 -0
- package/src/providers/wireNormalizer.ts +279 -0
- package/src/providers/xai.js +13 -12
- package/src/tools/browserAutomator.js +13 -1
- package/src/tools/browserAutomator.ts +13 -0
- package/src/tools/creativeApps.js +2 -1
- package/src/tools/creativeApps.ts +2 -1
- package/src/tools/gameAssetFetcher.js +130 -26
- package/src/tools/gameAssetHarvester.js +80 -58
- package/src/tools/nativeEngine.js +1 -1
- package/src/tools/nativeEngine.ts +1 -1
- package/src/tools/registry.js +13 -0
- package/src/tools/toolScanner.js +596 -140
- package/src/tools/toolScanner.ts +665 -147
- package/src/tools/toolSelfRepair.js +243 -114
- package/src/tools/toolSelfRepair.ts +262 -111
- package/src/tools/webFetch.js +161 -24
- package/src/tools/webFetch.ts +157 -22
- package/src/tools/webSearch.js +33 -4
- package/src/tools/webSearch.ts +27 -4
- package/src/tui/sessionPicker.js +132 -35
- package/src/tui/sessionPicker.ts +153 -32
- package/src/tui/sessionPickerView.js +277 -34
- package/src/tui/sessionPickerView.ts +328 -34
- package/src/tui/statusLine.js +3 -0
- package/src/tui/statusLine.ts +5 -0
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
|
@@ -5,13 +5,18 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
6
|
import { capabilityDirectory, ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
|
|
7
7
|
import { resolveBrowserRuntime } from './browserRuntime.js';
|
|
8
|
-
import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
|
|
8
|
+
import { assertPublicWebUrl, assertBrowserNavigableUrl, isLoopbackHost } from './urlPolicy.js';
|
|
9
|
+
import { ensureSafeWorkspaceInputPath, ensureSafeWorkspaceOutputPath } from './workspacePathSafety.js';
|
|
9
10
|
import { windowSnapshot } from './snapshotWindow.js';
|
|
10
|
-
import { searchPublicWeb } from './searchProviders.js';
|
|
11
|
+
import { searchPublicWeb, publicResultUrl } from './searchProviders.js';
|
|
11
12
|
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
12
13
|
const ACTION_TIMEOUT_MS = 12_000;
|
|
13
14
|
const IFRAME_SNAPSHOT_TIMEOUT_MS = 3_000;
|
|
14
15
|
const IDLE_CLOSE_MS = 120 * 60_000;
|
|
16
|
+
function workspaceProfileDirectory(workspace) {
|
|
17
|
+
const id = crypto.createHash('sha256').update(path.resolve(workspace)).digest('hex');
|
|
18
|
+
return path.join(capabilityDirectory(), 'browser-profiles', id);
|
|
19
|
+
}
|
|
15
20
|
const MAX_SEARCH_RESULTS = 10;
|
|
16
21
|
const MAX_EXTRACT_CHARS = 80_000;
|
|
17
22
|
const MAX_DOWNLOAD_BYTES = 250 * 1024 * 1024;
|
|
@@ -254,6 +259,18 @@ export class BrowserCapabilityError extends Error {
|
|
|
254
259
|
this.requiresConsent = requiresConsent;
|
|
255
260
|
}
|
|
256
261
|
}
|
|
262
|
+
export class BrowserBatchError extends Error {
|
|
263
|
+
completedActions;
|
|
264
|
+
failedActionIndex;
|
|
265
|
+
failedActionType;
|
|
266
|
+
constructor(error, completedActions, index, actionType) {
|
|
267
|
+
super(`Browser action ${index + 1} (${actionType}) failed: ${errorMessage(error)}`);
|
|
268
|
+
this.name = 'BrowserBatchError';
|
|
269
|
+
this.completedActions = [...completedActions];
|
|
270
|
+
this.failedActionIndex = index;
|
|
271
|
+
this.failedActionType = actionType;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
257
274
|
function errorMessage(error) {
|
|
258
275
|
return error instanceof Error ? error.message : String(error);
|
|
259
276
|
}
|
|
@@ -588,9 +605,12 @@ const SEARCH_EXTRACT_SCRIPT = `(() => {
|
|
|
588
605
|
const LINKS_EXTRACT_SCRIPT = `(opts) => {
|
|
589
606
|
const scope = opts && opts.selector ? document.querySelector(opts.selector) : document;
|
|
590
607
|
if (!scope) return { links: [], totalLinks: 0 };
|
|
591
|
-
const anchors =
|
|
608
|
+
const anchors = scope.querySelectorAll('a[href]');
|
|
592
609
|
const seen = new Set();
|
|
593
|
-
const
|
|
610
|
+
const links = [];
|
|
611
|
+
const start = (opts && opts.offset) || 0;
|
|
612
|
+
const max = (opts && opts.limit) || 50;
|
|
613
|
+
let totalLinks = 0;
|
|
594
614
|
for (const a of anchors) {
|
|
595
615
|
let href;
|
|
596
616
|
try {
|
|
@@ -602,20 +622,22 @@ const LINKS_EXTRACT_SCRIPT = `(opts) => {
|
|
|
602
622
|
if (seen.has(href)) continue;
|
|
603
623
|
seen.add(href);
|
|
604
624
|
const text = (a.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 200);
|
|
605
|
-
|
|
625
|
+
if (totalLinks >= start && links.length < max) links.push({ url: href, text: text || undefined });
|
|
626
|
+
totalLinks++;
|
|
606
627
|
}
|
|
607
|
-
|
|
608
|
-
const max = (opts && opts.limit) || 50;
|
|
609
|
-
return { links: all.slice(start, start + max), totalLinks: all.length };
|
|
628
|
+
return { links, totalLinks };
|
|
610
629
|
}`;
|
|
611
|
-
const IMAGES_EXTRACT_SCRIPT = `(opts) => {
|
|
630
|
+
export const IMAGES_EXTRACT_SCRIPT = `(opts) => {
|
|
612
631
|
const max = Math.min(Math.max(Number(opts && opts.limit) || 100, 1), 300);
|
|
613
632
|
const imgs = Array.from(document.querySelectorAll('img'));
|
|
614
633
|
const seen = new Set();
|
|
615
634
|
const out = [];
|
|
616
635
|
for (const img of imgs) {
|
|
617
636
|
const src = img.currentSrc || img.src || '';
|
|
618
|
-
if (!src || src.
|
|
637
|
+
if (!src || src.length > 4096 || seen.has(src)) continue;
|
|
638
|
+
let parsed;
|
|
639
|
+
try { parsed = new URL(src, document.baseURI); } catch { continue; }
|
|
640
|
+
if (!['http:', 'https:', 'blob:'].includes(parsed.protocol) || parsed.username || parsed.password) continue;
|
|
619
641
|
const width = Number(img.naturalWidth || img.width || 0);
|
|
620
642
|
const height = Number(img.naturalHeight || img.height || 0);
|
|
621
643
|
seen.add(src);
|
|
@@ -629,8 +651,7 @@ const IMAGES_EXTRACT_SCRIPT = `(opts) => {
|
|
|
629
651
|
}
|
|
630
652
|
return out;
|
|
631
653
|
}`;
|
|
632
|
-
const
|
|
633
|
-
const selectors = [
|
|
654
|
+
const CONSENT_DISMISS_SELECTORS = [
|
|
634
655
|
'#onetrust-accept-btn-handler',
|
|
635
656
|
'.onetrust-close-btn-handler',
|
|
636
657
|
'#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll',
|
|
@@ -640,19 +661,7 @@ const DISMISS_CONSENT_SCRIPT = `(() => {
|
|
|
640
661
|
'button[class*="cookie"][class*="accept" i]',
|
|
641
662
|
'button[aria-label*="Accept all" i]',
|
|
642
663
|
'button[aria-label*="Accept cookies" i]'
|
|
643
|
-
|
|
644
|
-
for (const sel of selectors) {
|
|
645
|
-
const el = document.querySelector(sel);
|
|
646
|
-
if (el && typeof el.click === 'function') {
|
|
647
|
-
const rect = el.getBoundingClientRect?.();
|
|
648
|
-
if (!rect || (rect.width > 0 && rect.height > 0)) {
|
|
649
|
-
el.click();
|
|
650
|
-
return true;
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
return false;
|
|
655
|
-
})()`;
|
|
664
|
+
];
|
|
656
665
|
const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
|
|
657
666
|
return new Promise(resolve => {
|
|
658
667
|
if (document.readyState === 'complete') {
|
|
@@ -672,65 +681,121 @@ export class CausyneBrowser {
|
|
|
672
681
|
loadBrowserEngine;
|
|
673
682
|
resolveRuntime;
|
|
674
683
|
profileDirectory;
|
|
684
|
+
pinnedProfileDirectory;
|
|
685
|
+
queuedOperations = 0;
|
|
675
686
|
visible;
|
|
676
687
|
validateUrl;
|
|
677
688
|
session = null;
|
|
678
689
|
starting = null;
|
|
690
|
+
operationTail = Promise.resolve();
|
|
679
691
|
tabs = new Map();
|
|
680
692
|
activeTabId = null;
|
|
681
693
|
idleTimer = null;
|
|
694
|
+
idleGeneration = 0;
|
|
682
695
|
securedPages = new WeakSet();
|
|
683
696
|
pageStates = new WeakMap();
|
|
684
697
|
contextRouteInstalled = false;
|
|
698
|
+
approvedLoopbackOrigins = new Set();
|
|
699
|
+
pendingLocalNavigation = null;
|
|
685
700
|
lastTarget = null;
|
|
686
701
|
constructor(options = {}) {
|
|
687
702
|
this.workspace = path.resolve(options.workspace ?? process.cwd());
|
|
688
703
|
this.ensureBrowserCapability = options.ensureBrowserCapability ?? (() => ensureCapability('browser'));
|
|
689
704
|
this.loadBrowserEngine = options.loadBrowserEngine ?? (async () => await loadCapabilityPackage('camoufox-js'));
|
|
690
705
|
this.resolveRuntime = options.resolveRuntime ?? resolveBrowserRuntime;
|
|
691
|
-
this.
|
|
706
|
+
this.pinnedProfileDirectory = options.profileDirectory !== undefined;
|
|
707
|
+
this.profileDirectory = path.resolve(options.profileDirectory ?? workspaceProfileDirectory(this.workspace));
|
|
692
708
|
this.visible = options.visible ?? process.env.CAUSYNE_BROWSER_VISIBLE === '1';
|
|
693
709
|
this.validateUrl = options.validateUrl ?? assertBrowserNavigableUrl;
|
|
694
710
|
}
|
|
695
711
|
setWorkspace(workspace) {
|
|
696
|
-
if (workspace
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
712
|
+
if (!workspace || typeof workspace !== 'string')
|
|
713
|
+
return;
|
|
714
|
+
const next = path.resolve(workspace);
|
|
715
|
+
if (next === this.workspace)
|
|
716
|
+
return;
|
|
717
|
+
if (this.session || this.starting || this.queuedOperations > 0) {
|
|
718
|
+
throw new Error('Cannot switch the workspace of an active browser session; use a workspace-scoped browser');
|
|
719
|
+
}
|
|
720
|
+
if (this.pinnedProfileDirectory) {
|
|
721
|
+
throw new Error('Cannot switch workspaces with an explicitly configured browser profile');
|
|
702
722
|
}
|
|
723
|
+
this.workspacePreview.clear();
|
|
724
|
+
this.lastTarget = null;
|
|
725
|
+
this.approvedLoopbackOrigins.clear();
|
|
726
|
+
this.pendingLocalNavigation = null;
|
|
727
|
+
this.workspace = next;
|
|
728
|
+
this.profileDirectory = workspaceProfileDirectory(next);
|
|
703
729
|
}
|
|
704
730
|
getWorkspace() {
|
|
705
731
|
return this.workspace;
|
|
706
732
|
}
|
|
733
|
+
async enqueueOperation(operation) {
|
|
734
|
+
this.queuedOperations++;
|
|
735
|
+
const previous = this.operationTail;
|
|
736
|
+
let release;
|
|
737
|
+
this.operationTail = new Promise(resolve => { release = resolve; });
|
|
738
|
+
await previous;
|
|
739
|
+
try {
|
|
740
|
+
return await operation();
|
|
741
|
+
}
|
|
742
|
+
finally {
|
|
743
|
+
this.queuedOperations--;
|
|
744
|
+
release();
|
|
745
|
+
}
|
|
746
|
+
}
|
|
707
747
|
async run(actions, options = {}) {
|
|
748
|
+
return this.enqueueOperation(() => this.runUnlocked(actions, options));
|
|
749
|
+
}
|
|
750
|
+
async runUnlocked(actions, options = {}) {
|
|
708
751
|
if (!Array.isArray(actions) || actions.length === 0 || actions.length > 40) {
|
|
709
752
|
throw new Error('Browser actions must contain between 1 and 40 operations');
|
|
710
753
|
}
|
|
711
754
|
const activeWorkspace = options.workspace ? path.resolve(options.workspace) : this.workspace;
|
|
755
|
+
if (activeWorkspace !== this.workspace) {
|
|
756
|
+
throw new Error('Browser action workspace must match the isolated browser session workspace');
|
|
757
|
+
}
|
|
712
758
|
await this.start();
|
|
713
759
|
const results = [];
|
|
714
|
-
for (
|
|
760
|
+
for (let index = 0; index < actions.length; index++) {
|
|
761
|
+
const action = actions[index];
|
|
715
762
|
try {
|
|
716
763
|
results.push(await this.runAction(action, activeWorkspace));
|
|
717
764
|
}
|
|
718
765
|
catch (error) {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
766
|
+
try {
|
|
767
|
+
if (isDeadContextError(error) && ['goto', 'open', 'navigate', 'preview', 'snapshot', 'scrape', 'search', 'links', 'images', 'extract', 'listTabs', 'list_tabs'].includes(action.type)) {
|
|
768
|
+
await this.close();
|
|
769
|
+
await this.start();
|
|
770
|
+
results.push(await this.runAction(action, activeWorkspace));
|
|
771
|
+
}
|
|
772
|
+
else {
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
723
775
|
}
|
|
724
|
-
|
|
725
|
-
throw
|
|
776
|
+
catch (finalError) {
|
|
777
|
+
throw new BrowserBatchError(finalError, results, index, action.type);
|
|
726
778
|
}
|
|
727
779
|
}
|
|
728
780
|
}
|
|
729
781
|
this.touch();
|
|
730
782
|
return results;
|
|
731
783
|
}
|
|
732
|
-
async search(query) {
|
|
733
|
-
|
|
784
|
+
async search(query, options = {}) {
|
|
785
|
+
return this.enqueueOperation(async () => {
|
|
786
|
+
try {
|
|
787
|
+
return await this.searchUnlocked(query, options);
|
|
788
|
+
}
|
|
789
|
+
finally {
|
|
790
|
+
if (this.session)
|
|
791
|
+
this.touch();
|
|
792
|
+
}
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
async searchUnlocked(query, options = {}) {
|
|
796
|
+
if (typeof query !== 'string')
|
|
797
|
+
throw new Error('Browser search query must be a string');
|
|
798
|
+
const cleaned = query.trim();
|
|
734
799
|
if (!cleaned || cleaned.length > 1_000)
|
|
735
800
|
throw new Error('Search query must contain 1-1000 characters');
|
|
736
801
|
const failures = [];
|
|
@@ -748,7 +813,9 @@ export class CausyneBrowser {
|
|
|
748
813
|
await state.page.waitForTimeout(500);
|
|
749
814
|
const extracted = await state.page.evaluate(SEARCH_EXTRACT_SCRIPT);
|
|
750
815
|
if (Array.isArray(extracted) && extracted.length > 0) {
|
|
751
|
-
|
|
816
|
+
const safe = extracted.filter(result => typeof result?.url === 'string' && publicResultUrl(result.url));
|
|
817
|
+
if (safe.length > 0)
|
|
818
|
+
return safe.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
|
|
752
819
|
}
|
|
753
820
|
failures.push(`${target.engine}: no organic results`);
|
|
754
821
|
}
|
|
@@ -760,6 +827,9 @@ export class CausyneBrowser {
|
|
|
760
827
|
catch (browserErr) {
|
|
761
828
|
failures.push(`browser_session: ${errorMessage(browserErr)}`);
|
|
762
829
|
}
|
|
830
|
+
if (options.skipPublicFallback) {
|
|
831
|
+
throw new Error(`Rendered search providers exhausted. ${failures.join('; ')}`);
|
|
832
|
+
}
|
|
763
833
|
// High-reliability search fallback: query lightweight search providers (DuckDuckGo HTML / Bing RSS) directly
|
|
764
834
|
try {
|
|
765
835
|
const publicResults = await searchPublicWeb(cleaned);
|
|
@@ -774,6 +844,9 @@ export class CausyneBrowser {
|
|
|
774
844
|
throw new Error(`Search providers exhausted. ${failures.join('; ')}`);
|
|
775
845
|
}
|
|
776
846
|
async snapshot(offset = 0) {
|
|
847
|
+
return this.enqueueOperation(() => this.snapshotUnlocked(offset));
|
|
848
|
+
}
|
|
849
|
+
async snapshotUnlocked(offset = 0) {
|
|
777
850
|
await this.start();
|
|
778
851
|
const state = await this.activeTab();
|
|
779
852
|
await this.restoreLastTargetIfBlank(state);
|
|
@@ -788,6 +861,7 @@ export class CausyneBrowser {
|
|
|
788
861
|
};
|
|
789
862
|
}
|
|
790
863
|
async close() {
|
|
864
|
+
this.idleGeneration++;
|
|
791
865
|
if (this.idleTimer)
|
|
792
866
|
clearTimeout(this.idleTimer);
|
|
793
867
|
this.idleTimer = null;
|
|
@@ -798,6 +872,8 @@ export class CausyneBrowser {
|
|
|
798
872
|
this.workspacePreview.clear();
|
|
799
873
|
this.activeTabId = null;
|
|
800
874
|
this.contextRouteInstalled = false;
|
|
875
|
+
this.approvedLoopbackOrigins.clear();
|
|
876
|
+
this.pendingLocalNavigation = null;
|
|
801
877
|
this.securedPages = new WeakSet();
|
|
802
878
|
this.pageStates = new WeakMap();
|
|
803
879
|
if (session)
|
|
@@ -945,20 +1021,28 @@ export class CausyneBrowser {
|
|
|
945
1021
|
}
|
|
946
1022
|
const parsed = new URL(url);
|
|
947
1023
|
if (parsed.protocol === 'file:') {
|
|
948
|
-
|
|
949
|
-
const file = await fs.realpath(fileURLToPath(parsed));
|
|
950
|
-
if (!isWithin(workspace, file))
|
|
951
|
-
throw new Error('File is outside the selected workspace');
|
|
952
|
-
await route.continue();
|
|
953
|
-
return;
|
|
1024
|
+
throw new Error('Direct file requests are not allowed; use an isolated workspace preview');
|
|
954
1025
|
}
|
|
955
1026
|
if (parsed.protocol === 'ws:' || parsed.protocol === 'wss:') {
|
|
956
1027
|
parsed.protocol = parsed.protocol === 'wss:' ? 'https:' : 'http:';
|
|
957
|
-
await this.validateUrl(parsed.href);
|
|
958
1028
|
}
|
|
959
|
-
|
|
960
|
-
|
|
1029
|
+
if (isLoopbackHost(parsed.hostname)) {
|
|
1030
|
+
const request = route.request();
|
|
1031
|
+
let sameOriginFrame = false;
|
|
1032
|
+
try {
|
|
1033
|
+
const frameUrl = request.frame?.().url();
|
|
1034
|
+
sameOriginFrame = Boolean(frameUrl && new URL(frameUrl).origin === parsed.origin);
|
|
1035
|
+
}
|
|
1036
|
+
catch { /* Navigation requests can have no active frame. */ }
|
|
1037
|
+
const explicitlyNavigating = this.pendingLocalNavigation === parsed.origin
|
|
1038
|
+
&& request.isNavigationRequest?.() === true;
|
|
1039
|
+
const trustedSubresource = sameOriginFrame
|
|
1040
|
+
&& (this.approvedLoopbackOrigins.has(parsed.origin) || this.pendingLocalNavigation === parsed.origin);
|
|
1041
|
+
if (!explicitlyNavigating && !trustedSubresource) {
|
|
1042
|
+
throw new Error('A public page cannot request local services without explicit navigation');
|
|
1043
|
+
}
|
|
961
1044
|
}
|
|
1045
|
+
await this.validateUrl(parsed.href);
|
|
962
1046
|
await route.continue();
|
|
963
1047
|
}
|
|
964
1048
|
catch {
|
|
@@ -1125,7 +1209,17 @@ export class CausyneBrowser {
|
|
|
1125
1209
|
async navigate(state, value) {
|
|
1126
1210
|
const url = await this.validateUrl(value);
|
|
1127
1211
|
state.runtimeErrors = [];
|
|
1128
|
-
|
|
1212
|
+
if (isLoopbackHost(url.hostname))
|
|
1213
|
+
this.pendingLocalNavigation = url.origin;
|
|
1214
|
+
let response;
|
|
1215
|
+
try {
|
|
1216
|
+
response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1217
|
+
}
|
|
1218
|
+
finally {
|
|
1219
|
+
this.pendingLocalNavigation = null;
|
|
1220
|
+
}
|
|
1221
|
+
if (isLoopbackHost(url.hostname))
|
|
1222
|
+
this.approvedLoopbackOrigins.add(url.origin);
|
|
1129
1223
|
const status = response?.status() ?? 0;
|
|
1130
1224
|
if (status >= 400)
|
|
1131
1225
|
throw new Error(`Destination returned HTTP ${status}`);
|
|
@@ -1299,50 +1393,39 @@ export class CausyneBrowser {
|
|
|
1299
1393
|
throw new Error(check.reason);
|
|
1300
1394
|
}
|
|
1301
1395
|
}
|
|
1302
|
-
async performClick(
|
|
1303
|
-
if (doubleClick
|
|
1396
|
+
async performClick(_state, locator, doubleClick = false) {
|
|
1397
|
+
if (doubleClick) {
|
|
1398
|
+
if (typeof locator.dblclick !== 'function') {
|
|
1399
|
+
throw new Error('Browser engine does not support double-click actions');
|
|
1400
|
+
}
|
|
1304
1401
|
await locator.dblclick({ timeout: ACTION_TIMEOUT_MS });
|
|
1305
1402
|
return;
|
|
1306
1403
|
}
|
|
1307
|
-
|
|
1404
|
+
// A failed actionability check must not become a forced or synthetic click.
|
|
1405
|
+
// Retrying mutating actions could also submit the same form twice.
|
|
1406
|
+
await locator.click({ timeout: ACTION_TIMEOUT_MS });
|
|
1407
|
+
}
|
|
1408
|
+
async dismissConsentBanner(state) {
|
|
1409
|
+
for (const selector of CONSENT_DISMISS_SELECTORS) {
|
|
1410
|
+
const locator = state.page.locator(selector).first();
|
|
1411
|
+
if (typeof locator.isVisible !== 'function')
|
|
1412
|
+
continue;
|
|
1413
|
+
if (!await locator.isVisible().catch(() => false))
|
|
1414
|
+
continue;
|
|
1415
|
+
// Do not bypass actionability or retry a potentially mutating click.
|
|
1308
1416
|
await locator.click({ timeout: ACTION_TIMEOUT_MS });
|
|
1417
|
+
state.refs.clear();
|
|
1418
|
+
return true;
|
|
1309
1419
|
}
|
|
1310
|
-
|
|
1311
|
-
const msg = errorMessage(clickError);
|
|
1312
|
-
if (msg.includes('intercepts pointer events') || msg.includes('Timeout')) {
|
|
1313
|
-
try {
|
|
1314
|
-
await locator.click({ timeout: 5_000, force: true });
|
|
1315
|
-
return;
|
|
1316
|
-
}
|
|
1317
|
-
catch {
|
|
1318
|
-
if (typeof locator.boundingBox === 'function' &&
|
|
1319
|
-
typeof state.page.mouse.move === 'function' &&
|
|
1320
|
-
typeof state.page.mouse.down === 'function' &&
|
|
1321
|
-
typeof state.page.mouse.up === 'function') {
|
|
1322
|
-
const box = await locator.boundingBox({ timeout: 2_000 }).catch(() => null);
|
|
1323
|
-
if (box && box.width > 0 && box.height > 0) {
|
|
1324
|
-
const cx = box.x + box.width / 2;
|
|
1325
|
-
const cy = box.y + box.height / 2;
|
|
1326
|
-
await state.page.mouse.move(cx, cy);
|
|
1327
|
-
await state.page.waitForTimeout(30);
|
|
1328
|
-
await state.page.mouse.down();
|
|
1329
|
-
await state.page.waitForTimeout(30);
|
|
1330
|
-
await state.page.mouse.up();
|
|
1331
|
-
return;
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
throw clickError;
|
|
1337
|
-
}
|
|
1420
|
+
return false;
|
|
1338
1421
|
}
|
|
1339
1422
|
async performType(state, locator, action) {
|
|
1340
|
-
if (action.text
|
|
1341
|
-
throw new Error(`${action.type} requires text`);
|
|
1423
|
+
if (typeof action.text !== 'string')
|
|
1424
|
+
throw new Error(`${action.type} requires text as a string`);
|
|
1342
1425
|
await this.assertFillable(locator);
|
|
1343
1426
|
if (action.mode === 'keyboard' && typeof state.page.keyboard.type === 'function') {
|
|
1344
1427
|
await this.performClick(state, locator, false);
|
|
1345
|
-
const delay =
|
|
1428
|
+
const delay = boundedFiniteInteger(action.delay, 20, 0, 500);
|
|
1346
1429
|
await state.page.keyboard.type(action.text, { delay });
|
|
1347
1430
|
}
|
|
1348
1431
|
else {
|
|
@@ -1358,8 +1441,9 @@ export class CausyneBrowser {
|
|
|
1358
1441
|
if (!Array.isArray(selected) || selected.length > 0)
|
|
1359
1442
|
return;
|
|
1360
1443
|
}
|
|
1361
|
-
catch {
|
|
1362
|
-
|
|
1444
|
+
catch (error) {
|
|
1445
|
+
if (!/no option|option.*not found|did not match/i.test(errorMessage(error)))
|
|
1446
|
+
throw error;
|
|
1363
1447
|
}
|
|
1364
1448
|
await locator.selectOption({ label: value }, { timeout: ACTION_TIMEOUT_MS });
|
|
1365
1449
|
}
|
|
@@ -1371,7 +1455,9 @@ export class CausyneBrowser {
|
|
|
1371
1455
|
const list = Array.isArray(rawPaths) ? rawPaths : [rawPaths];
|
|
1372
1456
|
const resolvedFiles = [];
|
|
1373
1457
|
for (const item of list) {
|
|
1374
|
-
|
|
1458
|
+
if (typeof item !== 'string' || !item.trim())
|
|
1459
|
+
throw new Error('upload requires non-empty filePath strings');
|
|
1460
|
+
const resolved = path.resolve(workspace, item);
|
|
1375
1461
|
if (!isWithin(workspace, resolved)) {
|
|
1376
1462
|
throw new Error('Upload file must stay inside the selected workspace');
|
|
1377
1463
|
}
|
|
@@ -1379,23 +1465,19 @@ export class CausyneBrowser {
|
|
|
1379
1465
|
if (!stat || !stat.isFile()) {
|
|
1380
1466
|
throw new Error(`Upload file does not exist or is not a regular file: ${resolved}`);
|
|
1381
1467
|
}
|
|
1468
|
+
await ensureSafeWorkspaceInputPath(workspace, resolved);
|
|
1382
1469
|
resolvedFiles.push(resolved);
|
|
1383
1470
|
}
|
|
1384
1471
|
const locator = await this.locatorFor(state, action);
|
|
1385
1472
|
if (typeof locator.setInputFiles === 'function') {
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
};
|
|
1395
|
-
}
|
|
1396
|
-
catch {
|
|
1397
|
-
// Fall through to filechooser event
|
|
1398
|
-
}
|
|
1473
|
+
await locator.setInputFiles(resolvedFiles, { timeout: ACTION_TIMEOUT_MS });
|
|
1474
|
+
state.refs.clear();
|
|
1475
|
+
return {
|
|
1476
|
+
action: action.type,
|
|
1477
|
+
tabId: state.id,
|
|
1478
|
+
url: state.page.url(),
|
|
1479
|
+
output: `Uploaded ${resolvedFiles.length} file(s)`
|
|
1480
|
+
};
|
|
1399
1481
|
}
|
|
1400
1482
|
const [chooser] = await Promise.all([
|
|
1401
1483
|
state.page.waitForEvent('filechooser', { timeout: ACTION_TIMEOUT_MS }),
|
|
@@ -1411,11 +1493,12 @@ export class CausyneBrowser {
|
|
|
1411
1493
|
};
|
|
1412
1494
|
}
|
|
1413
1495
|
async saveDownload(state, action, workspace) {
|
|
1414
|
-
if (!action.outputFile)
|
|
1415
|
-
throw new Error('download requires outputFile');
|
|
1496
|
+
if (typeof action.outputFile !== 'string' || !action.outputFile.trim())
|
|
1497
|
+
throw new Error('download requires non-empty outputFile string');
|
|
1416
1498
|
const target = path.resolve(workspace, action.outputFile);
|
|
1417
1499
|
if (!isWithin(workspace, target))
|
|
1418
1500
|
throw new Error('Download target must stay inside the selected workspace');
|
|
1501
|
+
await ensureSafeWorkspaceOutputPath(workspace, target);
|
|
1419
1502
|
const locator = await this.locatorFor(state, action);
|
|
1420
1503
|
const [download] = await Promise.all([
|
|
1421
1504
|
state.page.waitForEvent('download', { timeout: NAVIGATION_TIMEOUT_MS }),
|
|
@@ -1425,7 +1508,6 @@ export class CausyneBrowser {
|
|
|
1425
1508
|
// filename alter the caller's workspace-scoped target.
|
|
1426
1509
|
const finalTarget = target;
|
|
1427
1510
|
const temporary = `${finalTarget}.part-${crypto.randomUUID()}`;
|
|
1428
|
-
await fs.mkdir(path.dirname(finalTarget), { recursive: true });
|
|
1429
1511
|
try {
|
|
1430
1512
|
await download.saveAs(temporary);
|
|
1431
1513
|
const failure = await download.failure();
|
|
@@ -1442,14 +1524,15 @@ export class CausyneBrowser {
|
|
|
1442
1524
|
}
|
|
1443
1525
|
}
|
|
1444
1526
|
async saveScreenshot(state, action, workspace) {
|
|
1445
|
-
if (!action.outputFile)
|
|
1446
|
-
throw new Error('screenshot requires outputFile');
|
|
1527
|
+
if (typeof action.outputFile !== 'string' || !action.outputFile.trim())
|
|
1528
|
+
throw new Error('screenshot requires non-empty outputFile string');
|
|
1447
1529
|
const target = path.resolve(workspace, action.outputFile);
|
|
1448
1530
|
if (!isWithin(workspace, target))
|
|
1449
1531
|
throw new Error('Screenshot target must stay inside the selected workspace');
|
|
1450
1532
|
const extension = path.extname(target).toLowerCase();
|
|
1451
1533
|
if (!['.png', '.jpg', '.jpeg'].includes(extension))
|
|
1452
1534
|
throw new Error('Screenshot outputFile must end in .png, .jpg, or .jpeg');
|
|
1535
|
+
await ensureSafeWorkspaceOutputPath(workspace, target);
|
|
1453
1536
|
const bytes = await state.page.screenshot({
|
|
1454
1537
|
fullPage: action.fullPage ?? false,
|
|
1455
1538
|
type: extension === '.png' ? 'png' : 'jpeg'
|
|
@@ -1457,7 +1540,6 @@ export class CausyneBrowser {
|
|
|
1457
1540
|
if (bytes.byteLength > MAX_SCREENSHOT_BYTES)
|
|
1458
1541
|
throw new Error(`Screenshot exceeds ${MAX_SCREENSHOT_BYTES} bytes`);
|
|
1459
1542
|
const temporary = `${target}.part-${crypto.randomUUID()}`;
|
|
1460
|
-
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
1461
1543
|
try {
|
|
1462
1544
|
await fs.writeFile(temporary, bytes, { mode: 0o600 });
|
|
1463
1545
|
await fs.rename(temporary, target);
|
|
@@ -1472,9 +1554,11 @@ export class CausyneBrowser {
|
|
|
1472
1554
|
throw new Error('Every browser action needs a type');
|
|
1473
1555
|
if (action.type === 'newTab' || action.type === 'new_tab') {
|
|
1474
1556
|
const initialUrl = action.macro
|
|
1475
|
-
?
|
|
1557
|
+
? expandSearchMacro(action.macro, action.query ?? action.text ?? '')
|
|
1476
1558
|
: action.url;
|
|
1477
|
-
|
|
1559
|
+
if (action.macro && !initialUrl)
|
|
1560
|
+
throw new Error(`Unsupported search macro: ${action.macro}`);
|
|
1561
|
+
const state = await this.createTab(initialUrl ?? undefined);
|
|
1478
1562
|
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1479
1563
|
}
|
|
1480
1564
|
if (action.type === 'listTabs' || action.type === 'list_tabs') {
|
|
@@ -1496,7 +1580,7 @@ export class CausyneBrowser {
|
|
|
1496
1580
|
return { action: action.type, tabId: state.id, output: 'Tab closed' };
|
|
1497
1581
|
}
|
|
1498
1582
|
if (action.type === 'search') {
|
|
1499
|
-
const results = await this.
|
|
1583
|
+
const results = await this.searchUnlocked(action.query ?? action.text ?? '');
|
|
1500
1584
|
const active = await this.activeTab();
|
|
1501
1585
|
return { action: action.type, tabId: active.id, url: active.page.url(), data: results };
|
|
1502
1586
|
}
|
|
@@ -1511,7 +1595,7 @@ export class CausyneBrowser {
|
|
|
1511
1595
|
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
|
|
1512
1596
|
}
|
|
1513
1597
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
1514
|
-
const snapshot = await this.
|
|
1598
|
+
const snapshot = await this.snapshotUnlocked(action.offset ?? 0);
|
|
1515
1599
|
return {
|
|
1516
1600
|
action: action.type,
|
|
1517
1601
|
tabId: snapshot.tabId,
|
|
@@ -1541,7 +1625,7 @@ export class CausyneBrowser {
|
|
|
1541
1625
|
await locator.hover({ timeout: ACTION_TIMEOUT_MS });
|
|
1542
1626
|
}
|
|
1543
1627
|
else {
|
|
1544
|
-
|
|
1628
|
+
throw new Error('Browser engine cannot hover this element');
|
|
1545
1629
|
}
|
|
1546
1630
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Element hovered' };
|
|
1547
1631
|
}
|
|
@@ -1552,20 +1636,25 @@ export class CausyneBrowser {
|
|
|
1552
1636
|
}
|
|
1553
1637
|
if (action.type === 'selectOption' || action.type === 'select') {
|
|
1554
1638
|
const value = action.value ?? action.option ?? action.text;
|
|
1555
|
-
if (value
|
|
1556
|
-
throw new Error(`${action.type} requires value`);
|
|
1639
|
+
if (typeof value !== 'string')
|
|
1640
|
+
throw new Error(`${action.type} requires a string value`);
|
|
1557
1641
|
const locator = await this.locatorFor(state, action);
|
|
1558
1642
|
await this.performSelectOption(locator, value);
|
|
1559
1643
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Option selected' };
|
|
1560
1644
|
}
|
|
1561
1645
|
if (action.type === 'keyPress' || action.type === 'press') {
|
|
1562
|
-
|
|
1646
|
+
if (typeof action.key !== 'string' || !action.key.trim()) {
|
|
1647
|
+
throw new Error('keyPress requires a non-empty key');
|
|
1648
|
+
}
|
|
1649
|
+
const normalizedKey = normalizeBrowserKey(action.key);
|
|
1563
1650
|
await state.page.keyboard.press(normalizedKey);
|
|
1564
1651
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: `Pressed ${normalizedKey}` };
|
|
1565
1652
|
}
|
|
1566
1653
|
if (action.type === 'scroll') {
|
|
1567
1654
|
const amount = boundedFiniteInteger(action.amount, 700, 1, 10_000);
|
|
1568
1655
|
const direction = action.direction ?? 'down';
|
|
1656
|
+
if (!['up', 'down', 'left', 'right'].includes(direction))
|
|
1657
|
+
throw new Error('Unsupported scroll direction');
|
|
1569
1658
|
const x = direction === 'left' ? -amount : direction === 'right' ? amount : 0;
|
|
1570
1659
|
const y = direction === 'up' ? -amount : direction === 'down' ? amount : 0;
|
|
1571
1660
|
await state.page.mouse.wheel(x, y);
|
|
@@ -1586,21 +1675,19 @@ export class CausyneBrowser {
|
|
|
1586
1675
|
await loc.waitFor({ timeout: waitTimeout });
|
|
1587
1676
|
}
|
|
1588
1677
|
else {
|
|
1589
|
-
|
|
1678
|
+
throw new Error('Browser engine cannot wait for selectors');
|
|
1590
1679
|
}
|
|
1591
1680
|
}
|
|
1592
1681
|
}
|
|
1593
1682
|
else {
|
|
1594
1683
|
if (action.waitForNetwork) {
|
|
1595
|
-
await state.page.waitForLoadState('networkidle', { timeout: waitTimeout })
|
|
1684
|
+
await state.page.waitForLoadState('networkidle', { timeout: waitTimeout });
|
|
1596
1685
|
}
|
|
1597
1686
|
await state.page.evaluate(WAIT_FOR_PAGE_READY_SCRIPT).catch(() => { });
|
|
1598
1687
|
await state.page.waitForTimeout(Math.min(waitTimeout, 2_000));
|
|
1599
1688
|
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
}
|
|
1603
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), output: 'Wait completed' };
|
|
1689
|
+
const dismissed = action.dismissConsent ? await this.dismissConsentBanner(state) : false;
|
|
1690
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), output: dismissed ? 'Wait completed; consent banner dismissed' : 'Wait completed' };
|
|
1604
1691
|
}
|
|
1605
1692
|
if (action.type === 'viewport') {
|
|
1606
1693
|
const width = Math.floor(Number(action.width ?? 1280));
|
|
@@ -1608,9 +1695,10 @@ export class CausyneBrowser {
|
|
|
1608
1695
|
if (!Number.isFinite(width) || !Number.isFinite(height) || width < 100 || width > 4000 || height < 100 || height > 4000) {
|
|
1609
1696
|
throw new Error('viewport width and height must be between 100 and 4000 pixels');
|
|
1610
1697
|
}
|
|
1611
|
-
if (typeof state.page.setViewportSize
|
|
1612
|
-
|
|
1698
|
+
if (typeof state.page.setViewportSize !== 'function') {
|
|
1699
|
+
throw new Error('Browser engine does not support viewport resizing');
|
|
1613
1700
|
}
|
|
1701
|
+
await state.page.setViewportSize({ width, height });
|
|
1614
1702
|
return { action: action.type, tabId: state.id, url: state.page.url(), output: `Viewport set to ${width}x${height}` };
|
|
1615
1703
|
}
|
|
1616
1704
|
if (action.type === 'back') {
|
|
@@ -1664,7 +1752,7 @@ export class CausyneBrowser {
|
|
|
1664
1752
|
if (validationErr)
|
|
1665
1753
|
throw new Error(validationErr);
|
|
1666
1754
|
}
|
|
1667
|
-
const data = await state.page.evaluate(LINKS_EXTRACT_SCRIPT, { selector: action.selector, offset: action.offset
|
|
1755
|
+
const data = await state.page.evaluate(LINKS_EXTRACT_SCRIPT, { selector: action.selector, offset: boundedFiniteInteger(action.offset, 0, 0, 100_000), limit: boundedFiniteInteger(action.limit, 50, 1, 200) });
|
|
1668
1756
|
return { action: action.type, tabId: state.id, url: state.page.url(), data };
|
|
1669
1757
|
}
|
|
1670
1758
|
else if (action.type === 'images') {
|
|
@@ -1704,25 +1792,32 @@ export class CausyneBrowser {
|
|
|
1704
1792
|
}
|
|
1705
1793
|
}
|
|
1706
1794
|
touch() {
|
|
1795
|
+
const generation = ++this.idleGeneration;
|
|
1707
1796
|
if (this.idleTimer)
|
|
1708
1797
|
clearTimeout(this.idleTimer);
|
|
1709
|
-
this.idleTimer = setTimeout(() => {
|
|
1798
|
+
this.idleTimer = setTimeout(() => {
|
|
1799
|
+
void this.enqueueOperation(async () => {
|
|
1800
|
+
if (generation === this.idleGeneration)
|
|
1801
|
+
await this.close();
|
|
1802
|
+
});
|
|
1803
|
+
}, IDLE_CLOSE_MS);
|
|
1710
1804
|
this.idleTimer.unref?.();
|
|
1711
1805
|
}
|
|
1712
1806
|
}
|
|
1713
|
-
|
|
1807
|
+
const sharedBrowsers = new Map();
|
|
1714
1808
|
export function causyneBrowser(options) {
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1809
|
+
const workspace = path.resolve(options?.workspace ?? process.cwd());
|
|
1810
|
+
let browser = sharedBrowsers.get(workspace);
|
|
1811
|
+
if (!browser) {
|
|
1812
|
+
browser = new CausyneBrowser({ workspace });
|
|
1813
|
+
sharedBrowsers.set(workspace, browser);
|
|
1718
1814
|
}
|
|
1719
|
-
return
|
|
1815
|
+
return browser;
|
|
1720
1816
|
}
|
|
1721
1817
|
export async function closeCausyneBrowser() {
|
|
1722
|
-
const
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
await browser.close();
|
|
1818
|
+
const browsers = [...sharedBrowsers.values()];
|
|
1819
|
+
sharedBrowsers.clear();
|
|
1820
|
+
await Promise.all(browsers.map(browser => browser.close()));
|
|
1726
1821
|
}
|
|
1727
1822
|
const INTERACTIVE_BROWSER_ACTIONS = new Set([
|
|
1728
1823
|
'click', 'clickIndex',
|
|
@@ -1791,7 +1886,7 @@ export function validateBrowserActSandbox(args, workspaceRoot, isInternalUrl, is
|
|
|
1791
1886
|
if (hasDownload) {
|
|
1792
1887
|
return { allowed: true, risk: 'extreme', reason: 'Writes browser content to the selected workspace' };
|
|
1793
1888
|
}
|
|
1794
|
-
if (actions.some(action => typeof action?.type === 'string' && INTERACTIVE_BROWSER_ACTIONS.has(action.type))) {
|
|
1889
|
+
if (actions.some(action => typeof action?.type === 'string' && (INTERACTIVE_BROWSER_ACTIONS.has(action.type) || (action.type === 'wait' && action.dismissConsent === true)))) {
|
|
1795
1890
|
return { allowed: true, risk: 'dangerous', reason: 'Interacts with a website through the dedicated agent browser' };
|
|
1796
1891
|
}
|
|
1797
1892
|
return { allowed: true, risk: 'safe' };
|