@causyne/agent 1.20.10 → 1.20.12
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/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +262 -91
- package/src/providers/antigravity.ts +270 -99
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/stallGuard.js +3 -12
- package/src/stallGuard.ts +3 -12
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
|
@@ -248,6 +248,22 @@ function ensureLaunchShim(resolvedExecutable, resourceDirectory) {
|
|
|
248
248
|
}
|
|
249
249
|
return shimExecutable;
|
|
250
250
|
}
|
|
251
|
+
/** Discover existing installations only. Never downloads or uses a personal profile. */
|
|
252
|
+
export function resolveChromiumRuntime(configured) {
|
|
253
|
+
const candidates = configured ? [configured] : process.platform === 'darwin'
|
|
254
|
+
? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium']
|
|
255
|
+
: process.platform === 'win32'
|
|
256
|
+
? [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA].filter((root) => Boolean(root)).flatMap(root => [path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'), path.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe')])
|
|
257
|
+
: ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome', '/opt/google/chrome/chrome'];
|
|
258
|
+
for (const candidate of candidates) {
|
|
259
|
+
try {
|
|
260
|
+
assertExecutable(candidate);
|
|
261
|
+
return { engine: 'chromium', executablePath: candidate, installDirectory: path.dirname(candidate), resourceDirectory: path.dirname(candidate), source: configured ? 'environment' : 'system' };
|
|
262
|
+
}
|
|
263
|
+
catch { /* Try the next existing installation. */ }
|
|
264
|
+
}
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
251
267
|
export function resolveBrowserRuntime() {
|
|
252
268
|
const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
|
|
253
269
|
|| process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
|
|
@@ -255,7 +271,15 @@ export function resolveBrowserRuntime() {
|
|
|
255
271
|
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
256
272
|
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
257
273
|
const executablePath = candidates.find(existsSync);
|
|
274
|
+
if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
|
|
275
|
+
const chromium = resolveChromiumRuntime(configured);
|
|
276
|
+
if (chromium)
|
|
277
|
+
return chromium;
|
|
278
|
+
}
|
|
258
279
|
if (!executablePath) {
|
|
280
|
+
const chromium = !configured ? resolveChromiumRuntime() : null;
|
|
281
|
+
if (chromium)
|
|
282
|
+
return chromium;
|
|
259
283
|
throw new Error('Causyne Browser runtime is not installed. Causyne does not download browser binaries automatically. ' +
|
|
260
284
|
'Install a supported browser runtime separately, then set CAUSYNE_BROWSER_EXECUTABLE to its executable path.');
|
|
261
285
|
}
|
|
@@ -289,3 +313,26 @@ export function resolveBrowserRuntime() {
|
|
|
289
313
|
source: configured ? 'environment' : 'system'
|
|
290
314
|
};
|
|
291
315
|
}
|
|
316
|
+
/**
|
|
317
|
+
* Synchronously checks if a valid Causyne / Camoufox browser executable exists.
|
|
318
|
+
*/
|
|
319
|
+
export function isBrowserRuntimeInstalled() {
|
|
320
|
+
try {
|
|
321
|
+
const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
|
|
322
|
+
|| process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
|
|
323
|
+
const candidates = configured
|
|
324
|
+
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
325
|
+
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
326
|
+
return candidates.some(candidate => {
|
|
327
|
+
try {
|
|
328
|
+
return existsSync(candidate);
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
@@ -24,6 +24,7 @@ export interface PreparedBrowserRuntime {
|
|
|
24
24
|
resourceDirectory: string;
|
|
25
25
|
executablePath?: string;
|
|
26
26
|
source: 'environment' | 'system';
|
|
27
|
+
engine?: 'chromium';
|
|
27
28
|
}
|
|
28
29
|
|
|
29
30
|
function resolveCandidateExecutablePath(candidate: string): string {
|
|
@@ -295,6 +296,22 @@ function ensureLaunchShim(resolvedExecutable: string, resourceDirectory: string)
|
|
|
295
296
|
return shimExecutable;
|
|
296
297
|
}
|
|
297
298
|
|
|
299
|
+
/** Discover existing installations only. Never downloads or uses a personal profile. */
|
|
300
|
+
export function resolveChromiumRuntime(configured?: string): PreparedBrowserRuntime | null {
|
|
301
|
+
const candidates = configured ? [configured] : process.platform === 'darwin'
|
|
302
|
+
? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium']
|
|
303
|
+
: process.platform === 'win32'
|
|
304
|
+
? [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA].filter((root): root is string => Boolean(root)).flatMap(root => [path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'), path.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe')])
|
|
305
|
+
: ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome', '/opt/google/chrome/chrome'];
|
|
306
|
+
for (const candidate of candidates) {
|
|
307
|
+
try {
|
|
308
|
+
assertExecutable(candidate);
|
|
309
|
+
return { engine: 'chromium', executablePath: candidate, installDirectory: path.dirname(candidate), resourceDirectory: path.dirname(candidate), source: configured ? 'environment' : 'system' };
|
|
310
|
+
} catch { /* Try the next existing installation. */ }
|
|
311
|
+
}
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
|
|
298
315
|
export function resolveBrowserRuntime(): PreparedBrowserRuntime {
|
|
299
316
|
const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
|
|
300
317
|
|| process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
|
|
@@ -302,7 +319,13 @@ export function resolveBrowserRuntime(): PreparedBrowserRuntime {
|
|
|
302
319
|
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
303
320
|
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
304
321
|
const executablePath = candidates.find(existsSync);
|
|
322
|
+
if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
|
|
323
|
+
const chromium = resolveChromiumRuntime(configured);
|
|
324
|
+
if (chromium) return chromium;
|
|
325
|
+
}
|
|
305
326
|
if (!executablePath) {
|
|
327
|
+
const chromium = !configured ? resolveChromiumRuntime() : null;
|
|
328
|
+
if (chromium) return chromium;
|
|
306
329
|
throw new Error(
|
|
307
330
|
'Causyne Browser runtime is not installed. Causyne does not download browser binaries automatically. ' +
|
|
308
331
|
'Install a supported browser runtime separately, then set CAUSYNE_BROWSER_EXECUTABLE to its executable path.'
|
|
@@ -346,3 +369,25 @@ export function resolveBrowserRuntime(): PreparedBrowserRuntime {
|
|
|
346
369
|
source: configured ? 'environment' : 'system'
|
|
347
370
|
};
|
|
348
371
|
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Synchronously checks if a valid Causyne / Camoufox browser executable exists.
|
|
375
|
+
*/
|
|
376
|
+
export function isBrowserRuntimeInstalled(): boolean {
|
|
377
|
+
try {
|
|
378
|
+
const configured = process.env.CAUSYNE_BROWSER_EXECUTABLE?.trim()
|
|
379
|
+
|| process.env.CAMOUFOX_EXECUTABLE_PATH?.trim();
|
|
380
|
+
const candidates = configured
|
|
381
|
+
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
382
|
+
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
383
|
+
return candidates.some(candidate => {
|
|
384
|
+
try {
|
|
385
|
+
return existsSync(candidate);
|
|
386
|
+
} catch {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
} catch {
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { WorkspacePreview } from './workspacePreview.js';
|
|
1
2
|
import crypto from 'node:crypto';
|
|
2
3
|
import fs from 'node:fs/promises';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -654,6 +655,7 @@ const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
|
|
|
654
655
|
})()`;
|
|
655
656
|
export class CausyneBrowser {
|
|
656
657
|
workspace;
|
|
658
|
+
workspacePreview = new WorkspacePreview();
|
|
657
659
|
ensureBrowserCapability;
|
|
658
660
|
loadBrowserEngine;
|
|
659
661
|
resolveRuntime;
|
|
@@ -679,6 +681,8 @@ export class CausyneBrowser {
|
|
|
679
681
|
}
|
|
680
682
|
setWorkspace(workspace) {
|
|
681
683
|
if (workspace && typeof workspace === 'string') {
|
|
684
|
+
if (this.workspace !== path.resolve(workspace))
|
|
685
|
+
this.workspacePreview.clear();
|
|
682
686
|
this.workspace = path.resolve(workspace);
|
|
683
687
|
}
|
|
684
688
|
}
|
|
@@ -759,6 +763,7 @@ export class CausyneBrowser {
|
|
|
759
763
|
this.session = null;
|
|
760
764
|
this.starting = null;
|
|
761
765
|
this.tabs.clear();
|
|
766
|
+
this.workspacePreview.clear();
|
|
762
767
|
this.activeTabId = null;
|
|
763
768
|
this.contextRouteInstalled = false;
|
|
764
769
|
this.securedPages = new WeakSet();
|
|
@@ -793,26 +798,37 @@ export class CausyneBrowser {
|
|
|
793
798
|
if (!verdict.ok)
|
|
794
799
|
throw new BrowserCapabilityError(verdict.reason ?? 'Browser capability is unavailable', verdict.requiresConsent);
|
|
795
800
|
const runtime = this.resolveRuntime();
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
'
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
801
|
+
if (runtime.engine === 'chromium') {
|
|
802
|
+
const engine = await loadCapabilityPackage('playwright-core');
|
|
803
|
+
const profile = path.join(this.profileDirectory, 'chromium');
|
|
804
|
+
await fs.mkdir(profile, { recursive: true, mode: 0o700 });
|
|
805
|
+
this.session = await engine.chromium.launchPersistentContext(profile, {
|
|
806
|
+
executablePath: runtime.executablePath, headless: !this.visible, serviceWorkers: 'block', chromiumSandbox: true,
|
|
807
|
+
handleSIGTERM: false, handleSIGINT: false, handleSIGHUP: false
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
else {
|
|
811
|
+
process.env.CAMOUFOX_INSTALL_DIR = runtime.installDirectory;
|
|
812
|
+
await fs.mkdir(this.profileDirectory, { recursive: true, mode: 0o700 });
|
|
813
|
+
const module = await this.loadBrowserEngine();
|
|
814
|
+
if (!module || typeof module.Camoufox !== 'function')
|
|
815
|
+
throw new Error('Causyne Browser has no usable launcher');
|
|
816
|
+
this.session = await module.Camoufox({
|
|
817
|
+
headless: !this.visible,
|
|
818
|
+
user_data_dir: this.profileDirectory,
|
|
819
|
+
humanize: 0.35,
|
|
820
|
+
block_webrtc: true,
|
|
821
|
+
geoip: false,
|
|
822
|
+
enable_cache: true,
|
|
823
|
+
...(runtime.executablePath ? { executable_path: runtime.executablePath } : {}),
|
|
824
|
+
firefox_user_prefs: {
|
|
825
|
+
'Security.OCSP.enabled': 0
|
|
826
|
+
},
|
|
827
|
+
handleSIGTERM: false,
|
|
828
|
+
handleSIGINT: false,
|
|
829
|
+
handleSIGHUP: false
|
|
830
|
+
});
|
|
831
|
+
}
|
|
816
832
|
if (typeof this.session.route === 'function') {
|
|
817
833
|
await this.session.route('**/*', route => this.guardRoute(route));
|
|
818
834
|
this.contextRouteInstalled = true;
|
|
@@ -827,6 +843,10 @@ export class CausyneBrowser {
|
|
|
827
843
|
try {
|
|
828
844
|
await this.starting;
|
|
829
845
|
}
|
|
846
|
+
catch (error) {
|
|
847
|
+
await this.close();
|
|
848
|
+
throw error;
|
|
849
|
+
}
|
|
830
850
|
finally {
|
|
831
851
|
this.starting = null;
|
|
832
852
|
}
|
|
@@ -843,7 +863,11 @@ export class CausyneBrowser {
|
|
|
843
863
|
await page.route('**/*', route => this.guardRoute(route));
|
|
844
864
|
this.securedPages.add(page);
|
|
845
865
|
}
|
|
846
|
-
const state = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null };
|
|
866
|
+
const state = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null, runtimeErrors: [] };
|
|
867
|
+
page.on?.('pageerror', (error) => {
|
|
868
|
+
if (state.runtimeErrors.length < 5)
|
|
869
|
+
state.runtimeErrors.push(error instanceof Error ? error.message.slice(0, 400) : String(error).slice(0, 400));
|
|
870
|
+
});
|
|
847
871
|
page.on?.('crash', () => {
|
|
848
872
|
state.crashed = true;
|
|
849
873
|
});
|
|
@@ -864,6 +888,13 @@ export class CausyneBrowser {
|
|
|
864
888
|
if (/^(about:|data:|blob:|moz-extension:)/i.test(url))
|
|
865
889
|
return route.continue();
|
|
866
890
|
try {
|
|
891
|
+
const preview = await this.workspacePreview.response(url);
|
|
892
|
+
if (preview) {
|
|
893
|
+
if (!route.fulfill)
|
|
894
|
+
throw new Error('Browser engine cannot fulfill preview requests');
|
|
895
|
+
await route.fulfill(preview);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
867
898
|
const parsed = new URL(url);
|
|
868
899
|
if (parsed.protocol === 'file:') {
|
|
869
900
|
const workspace = await fs.realpath(this.workspace);
|
|
@@ -1045,6 +1076,7 @@ export class CausyneBrowser {
|
|
|
1045
1076
|
}
|
|
1046
1077
|
async navigate(state, value) {
|
|
1047
1078
|
const url = await this.validateUrl(value);
|
|
1079
|
+
state.runtimeErrors = [];
|
|
1048
1080
|
const response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1049
1081
|
const status = response?.status() ?? 0;
|
|
1050
1082
|
if (status >= 400)
|
|
@@ -1056,16 +1088,12 @@ export class CausyneBrowser {
|
|
|
1056
1088
|
state.lastStructure = null;
|
|
1057
1089
|
}
|
|
1058
1090
|
async preview(state, filePath, workspace) {
|
|
1059
|
-
|
|
1060
|
-
const
|
|
1061
|
-
|
|
1062
|
-
throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
1063
|
-
}
|
|
1064
|
-
await state.page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1091
|
+
state.runtimeErrors = [];
|
|
1092
|
+
const previewUrl = await this.workspacePreview.open(workspace, filePath);
|
|
1093
|
+
await state.page.goto(previewUrl, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1065
1094
|
await state.page.waitForLoadState('domcontentloaded', { timeout: NAVIGATION_TIMEOUT_MS });
|
|
1066
|
-
if (state.page.url() !==
|
|
1095
|
+
if (state.page.url() !== previewUrl)
|
|
1067
1096
|
throw new Error('Preview navigated away from the selected workspace file');
|
|
1068
|
-
}
|
|
1069
1097
|
state.refs.clear();
|
|
1070
1098
|
state.lastSnapshot = '';
|
|
1071
1099
|
state.lastStructure = null;
|
|
@@ -1406,7 +1434,7 @@ export class CausyneBrowser {
|
|
|
1406
1434
|
if (typeof action.filePath !== 'string')
|
|
1407
1435
|
throw new Error('preview requires filePath');
|
|
1408
1436
|
await this.preview(state, action.filePath, workspace);
|
|
1409
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
1437
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title(), 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.' };
|
|
1410
1438
|
}
|
|
1411
1439
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
1412
1440
|
const snapshot = await this.snapshot(action.offset ?? 0);
|
|
@@ -1415,9 +1443,10 @@ export class CausyneBrowser {
|
|
|
1415
1443
|
tabId: snapshot.tabId,
|
|
1416
1444
|
url: snapshot.url,
|
|
1417
1445
|
title: snapshot.title,
|
|
1418
|
-
output: snapshot.text,
|
|
1446
|
+
output: snapshot.text + (state.runtimeErrors.length ? `\nRuntime errors: ${state.runtimeErrors.join('; ')}` : ''),
|
|
1419
1447
|
...(snapshot.structure ? { structure: snapshot.structure } : {}),
|
|
1420
1448
|
data: {
|
|
1449
|
+
runtimeErrors: [...state.runtimeErrors],
|
|
1421
1450
|
refsCount: snapshot.refsCount,
|
|
1422
1451
|
truncated: snapshot.truncated,
|
|
1423
1452
|
totalChars: snapshot.totalChars,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { WorkspacePreview } from './workspacePreview.js';
|
|
1
2
|
import crypto from 'node:crypto';
|
|
2
3
|
import fs from 'node:fs/promises';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -339,6 +340,7 @@ interface BrowserRoute {
|
|
|
339
340
|
request(): { url(): string };
|
|
340
341
|
continue(): Promise<void>;
|
|
341
342
|
abort(errorCode?: string): Promise<void>;
|
|
343
|
+
fulfill?(response: { status: number; contentType: string; body: Buffer }): Promise<void>;
|
|
342
344
|
}
|
|
343
345
|
|
|
344
346
|
interface BrowserPage {
|
|
@@ -412,6 +414,7 @@ interface TabState {
|
|
|
412
414
|
lastSnapshot: string;
|
|
413
415
|
lastStructure: PageStructure | null;
|
|
414
416
|
crashed?: boolean;
|
|
417
|
+
runtimeErrors: string[];
|
|
415
418
|
}
|
|
416
419
|
|
|
417
420
|
export type BrowserActionType =
|
|
@@ -918,6 +921,7 @@ const WAIT_FOR_PAGE_READY_SCRIPT = `(() => {
|
|
|
918
921
|
|
|
919
922
|
export class CausyneBrowser {
|
|
920
923
|
private workspace: string;
|
|
924
|
+
private readonly workspacePreview = new WorkspacePreview();
|
|
921
925
|
private readonly ensureBrowserCapability: NonNullable<RuntimeOptions['ensureBrowserCapability']>;
|
|
922
926
|
private readonly loadBrowserEngine: NonNullable<RuntimeOptions['loadBrowserEngine']>;
|
|
923
927
|
private readonly resolveRuntime: NonNullable<RuntimeOptions['resolveRuntime']>;
|
|
@@ -945,6 +949,7 @@ export class CausyneBrowser {
|
|
|
945
949
|
|
|
946
950
|
setWorkspace(workspace: string): void {
|
|
947
951
|
if (workspace && typeof workspace === 'string') {
|
|
952
|
+
if (this.workspace !== path.resolve(workspace)) this.workspacePreview.clear();
|
|
948
953
|
this.workspace = path.resolve(workspace);
|
|
949
954
|
}
|
|
950
955
|
}
|
|
@@ -1025,6 +1030,7 @@ export class CausyneBrowser {
|
|
|
1025
1030
|
this.session = null;
|
|
1026
1031
|
this.starting = null;
|
|
1027
1032
|
this.tabs.clear();
|
|
1033
|
+
this.workspacePreview.clear();
|
|
1028
1034
|
this.activeTabId = null;
|
|
1029
1035
|
this.contextRouteInstalled = false;
|
|
1030
1036
|
this.securedPages = new WeakSet<object>();
|
|
@@ -1055,6 +1061,15 @@ export class CausyneBrowser {
|
|
|
1055
1061
|
const verdict = await this.ensureBrowserCapability();
|
|
1056
1062
|
if (!verdict.ok) throw new BrowserCapabilityError(verdict.reason ?? 'Browser capability is unavailable', verdict.requiresConsent);
|
|
1057
1063
|
const runtime = this.resolveRuntime();
|
|
1064
|
+
if (runtime.engine === 'chromium') {
|
|
1065
|
+
const engine = await loadCapabilityPackage('playwright-core') as { chromium: { launchPersistentContext(profile: string, options: Record<string, unknown>): Promise<BrowserSession> } };
|
|
1066
|
+
const profile = path.join(this.profileDirectory, 'chromium');
|
|
1067
|
+
await fs.mkdir(profile, { recursive: true, mode: 0o700 });
|
|
1068
|
+
this.session = await engine.chromium.launchPersistentContext(profile, {
|
|
1069
|
+
executablePath: runtime.executablePath, headless: !this.visible, serviceWorkers: 'block', chromiumSandbox: true,
|
|
1070
|
+
handleSIGTERM: false, handleSIGINT: false, handleSIGHUP: false
|
|
1071
|
+
});
|
|
1072
|
+
} else {
|
|
1058
1073
|
process.env.CAMOUFOX_INSTALL_DIR = runtime.installDirectory;
|
|
1059
1074
|
await fs.mkdir(this.profileDirectory, { recursive: true, mode: 0o700 });
|
|
1060
1075
|
const module = await this.loadBrowserEngine();
|
|
@@ -1074,6 +1089,7 @@ export class CausyneBrowser {
|
|
|
1074
1089
|
handleSIGINT: false,
|
|
1075
1090
|
handleSIGHUP: false
|
|
1076
1091
|
});
|
|
1092
|
+
}
|
|
1077
1093
|
if (typeof this.session.route === 'function') {
|
|
1078
1094
|
await this.session.route('**/*', route => this.guardRoute(route));
|
|
1079
1095
|
this.contextRouteInstalled = true;
|
|
@@ -1085,6 +1101,9 @@ export class CausyneBrowser {
|
|
|
1085
1101
|
})();
|
|
1086
1102
|
try {
|
|
1087
1103
|
await this.starting;
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
await this.close();
|
|
1106
|
+
throw error;
|
|
1088
1107
|
} finally {
|
|
1089
1108
|
this.starting = null;
|
|
1090
1109
|
}
|
|
@@ -1102,7 +1121,10 @@ export class CausyneBrowser {
|
|
|
1102
1121
|
await page.route('**/*', route => this.guardRoute(route));
|
|
1103
1122
|
this.securedPages.add(page);
|
|
1104
1123
|
}
|
|
1105
|
-
const state: TabState = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null };
|
|
1124
|
+
const state: TabState = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null, runtimeErrors: [] };
|
|
1125
|
+
page.on?.('pageerror', (error: unknown) => {
|
|
1126
|
+
if (state.runtimeErrors.length < 5) state.runtimeErrors.push(error instanceof Error ? error.message.slice(0, 400) : String(error).slice(0, 400));
|
|
1127
|
+
});
|
|
1106
1128
|
page.on?.('crash', () => {
|
|
1107
1129
|
state.crashed = true;
|
|
1108
1130
|
});
|
|
@@ -1123,6 +1145,12 @@ export class CausyneBrowser {
|
|
|
1123
1145
|
const url = route.request().url();
|
|
1124
1146
|
if (/^(about:|data:|blob:|moz-extension:)/i.test(url)) return route.continue();
|
|
1125
1147
|
try {
|
|
1148
|
+
const preview = await this.workspacePreview.response(url);
|
|
1149
|
+
if (preview) {
|
|
1150
|
+
if (!route.fulfill) throw new Error('Browser engine cannot fulfill preview requests');
|
|
1151
|
+
await route.fulfill(preview);
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1126
1154
|
const parsed = new URL(url);
|
|
1127
1155
|
if (parsed.protocol === 'file:') {
|
|
1128
1156
|
const workspace = await fs.realpath(this.workspace);
|
|
@@ -1289,6 +1317,7 @@ export class CausyneBrowser {
|
|
|
1289
1317
|
|
|
1290
1318
|
private async navigate(state: TabState, value: string): Promise<void> {
|
|
1291
1319
|
const url = await this.validateUrl(value);
|
|
1320
|
+
state.runtimeErrors = [];
|
|
1292
1321
|
const response = await state.page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1293
1322
|
const status = response?.status() ?? 0;
|
|
1294
1323
|
if (status >= 400) throw new Error(`Destination returned HTTP ${status}`);
|
|
@@ -1300,16 +1329,11 @@ export class CausyneBrowser {
|
|
|
1300
1329
|
}
|
|
1301
1330
|
|
|
1302
1331
|
private async preview(state: TabState, filePath: string, workspace: string): Promise<void> {
|
|
1303
|
-
|
|
1304
|
-
const
|
|
1305
|
-
|
|
1306
|
-
throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
1307
|
-
}
|
|
1308
|
-
await state.page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1332
|
+
state.runtimeErrors = [];
|
|
1333
|
+
const previewUrl = await this.workspacePreview.open(workspace, filePath);
|
|
1334
|
+
await state.page.goto(previewUrl, { waitUntil: 'domcontentloaded', timeout: NAVIGATION_TIMEOUT_MS });
|
|
1309
1335
|
await state.page.waitForLoadState('domcontentloaded', { timeout: NAVIGATION_TIMEOUT_MS });
|
|
1310
|
-
if (state.page.url() !==
|
|
1311
|
-
throw new Error('Preview navigated away from the selected workspace file');
|
|
1312
|
-
}
|
|
1336
|
+
if (state.page.url() !== previewUrl) throw new Error('Preview navigated away from the selected workspace file');
|
|
1313
1337
|
state.refs.clear();
|
|
1314
1338
|
state.lastSnapshot = '';
|
|
1315
1339
|
state.lastStructure = null;
|
|
@@ -1630,7 +1654,7 @@ export class CausyneBrowser {
|
|
|
1630
1654
|
if (action.type === 'preview') {
|
|
1631
1655
|
if (typeof action.filePath !== 'string') throw new Error('preview requires filePath');
|
|
1632
1656
|
await this.preview(state, action.filePath, workspace);
|
|
1633
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title() };
|
|
1657
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page.title(), 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.' };
|
|
1634
1658
|
}
|
|
1635
1659
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
1636
1660
|
const snapshot = await this.snapshot(action.offset ?? 0);
|
|
@@ -1639,9 +1663,10 @@ export class CausyneBrowser {
|
|
|
1639
1663
|
tabId: snapshot.tabId,
|
|
1640
1664
|
url: snapshot.url,
|
|
1641
1665
|
title: snapshot.title,
|
|
1642
|
-
output: snapshot.text,
|
|
1666
|
+
output: snapshot.text + (state.runtimeErrors.length ? `\nRuntime errors: ${state.runtimeErrors.join('; ')}` : ''),
|
|
1643
1667
|
...(snapshot.structure ? { structure: snapshot.structure } : {}),
|
|
1644
1668
|
data: {
|
|
1669
|
+
runtimeErrors: [...state.runtimeErrors],
|
|
1645
1670
|
refsCount: snapshot.refsCount,
|
|
1646
1671
|
truncated: snapshot.truncated,
|
|
1647
1672
|
totalChars: snapshot.totalChars,
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
const MIME = {
|
|
5
|
+
'.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
|
|
6
|
+
'.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
7
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',
|
|
8
|
+
'.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf',
|
|
9
|
+
'.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.bin': 'application/octet-stream',
|
|
10
|
+
'.wasm': 'application/wasm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.mp4': 'video/mp4'
|
|
11
|
+
};
|
|
12
|
+
const within = (root, file) => {
|
|
13
|
+
const relative = path.relative(root, file);
|
|
14
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
15
|
+
};
|
|
16
|
+
/** Serve approved workspace assets through browser interception, without a listening port. */
|
|
17
|
+
export class WorkspacePreview {
|
|
18
|
+
roots = new Map();
|
|
19
|
+
clear() { this.roots.clear(); }
|
|
20
|
+
async open(workspace, file) {
|
|
21
|
+
const root = await fs.realpath(workspace);
|
|
22
|
+
const target = await fs.realpath(path.resolve(root, file));
|
|
23
|
+
if (!within(root, target) || !/\.html?$/i.test(target))
|
|
24
|
+
throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
25
|
+
const origin = `https://${randomUUID()}.causyne-preview.invalid`;
|
|
26
|
+
this.roots.set(origin, path.dirname(target));
|
|
27
|
+
return `${origin}/${encodeURIComponent(path.basename(target))}`;
|
|
28
|
+
}
|
|
29
|
+
async response(rawUrl) {
|
|
30
|
+
const url = new URL(rawUrl);
|
|
31
|
+
const root = this.roots.get(url.origin);
|
|
32
|
+
if (!root)
|
|
33
|
+
return null;
|
|
34
|
+
const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
|
|
35
|
+
try {
|
|
36
|
+
const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
|
|
37
|
+
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(\.|$)/i.test(part)))
|
|
38
|
+
return deny;
|
|
39
|
+
const file = await fs.realpath(path.resolve(root, ...parts));
|
|
40
|
+
const contentType = MIME[path.extname(file).toLowerCase()];
|
|
41
|
+
if (!within(root, file) || !contentType)
|
|
42
|
+
return deny;
|
|
43
|
+
const stat = await fs.stat(file);
|
|
44
|
+
if (!stat.isFile() || stat.size > 25 * 1024 * 1024)
|
|
45
|
+
return deny;
|
|
46
|
+
return { status: 200, contentType, body: await fs.readFile(file) };
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return { ...deny, status: 404 };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const MIME: Record<string, string> = {
|
|
6
|
+
'.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
|
|
7
|
+
'.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
8
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',
|
|
9
|
+
'.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf',
|
|
10
|
+
'.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.bin': 'application/octet-stream',
|
|
11
|
+
'.wasm': 'application/wasm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.mp4': 'video/mp4'
|
|
12
|
+
};
|
|
13
|
+
const within = (root: string, file: string): boolean => {
|
|
14
|
+
const relative = path.relative(root, file);
|
|
15
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Serve approved workspace assets through browser interception, without a listening port. */
|
|
19
|
+
export class WorkspacePreview {
|
|
20
|
+
private readonly roots = new Map<string, string>();
|
|
21
|
+
|
|
22
|
+
clear(): void { this.roots.clear(); }
|
|
23
|
+
|
|
24
|
+
async open(workspace: string, file: string): Promise<string> {
|
|
25
|
+
const root = await fs.realpath(workspace);
|
|
26
|
+
const target = await fs.realpath(path.resolve(root, file));
|
|
27
|
+
if (!within(root, target) || !/\.html?$/i.test(target)) throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
28
|
+
const origin = `https://${randomUUID()}.causyne-preview.invalid`;
|
|
29
|
+
this.roots.set(origin, path.dirname(target));
|
|
30
|
+
return `${origin}/${encodeURIComponent(path.basename(target))}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async response(rawUrl: string): Promise<{ status: number; contentType: string; body: Buffer } | null> {
|
|
34
|
+
const url = new URL(rawUrl);
|
|
35
|
+
const root = this.roots.get(url.origin);
|
|
36
|
+
if (!root) return null;
|
|
37
|
+
const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
|
|
38
|
+
try {
|
|
39
|
+
const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
|
|
40
|
+
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(\.|$)/i.test(part))) return deny;
|
|
41
|
+
const file = await fs.realpath(path.resolve(root, ...parts));
|
|
42
|
+
const contentType = MIME[path.extname(file).toLowerCase()];
|
|
43
|
+
if (!within(root, file) || !contentType) return deny;
|
|
44
|
+
const stat = await fs.stat(file);
|
|
45
|
+
if (!stat.isFile() || stat.size > 25 * 1024 * 1024) return deny;
|
|
46
|
+
return { status: 200, contentType, body: await fs.readFile(file) };
|
|
47
|
+
} catch { return { ...deny, status: 404 }; }
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/decisionPolicy.js
CHANGED
|
@@ -41,6 +41,15 @@ export function assessDecisionRequirement(prompt) {
|
|
|
41
41
|
}
|
|
42
42
|
export function requiresImplementationPlan(prompt, archetype = '', confidence = '') {
|
|
43
43
|
const text = String(prompt ?? '').toLowerCase();
|
|
44
|
+
// A classifier can label any "create" request build_app. A single plain
|
|
45
|
+
// text/data-file operation needs no checklist or rejected mutation round trip.
|
|
46
|
+
const namedFiles = new Set([...text.matchAll(/\b[\w./-]+\.(?:txt|md|csv|json)\b/g)].map(match => match[0]));
|
|
47
|
+
const simpleFileOperation = text.length < 700 && namedFiles.size === 1
|
|
48
|
+
&& /\b(?:create|write|save)\b/.test(text)
|
|
49
|
+
&& !/\b(?:research|search|scrap\w*|codebase|migrat\w*|refactor|integrat\w*|application|website|database|security|authentication|authorization|framework|architecture|runtime)\b/.test(text)
|
|
50
|
+
&& !/\b(?:package(?:-lock)?\.json|tsconfig\w*\.json|permissions?\.json|policy\.json)\b/.test(text);
|
|
51
|
+
if (simpleFileOperation)
|
|
52
|
+
return false;
|
|
44
53
|
if (archetype === 'build_app' || archetype === 'integrate')
|
|
45
54
|
return true;
|
|
46
55
|
if (confidence === 'high' && /\b(?:implement|build|create|migrate|rewrite|refactor|integrate)\b/i.test(text)) {
|
package/src/decisionPolicy.ts
CHANGED
|
@@ -80,6 +80,14 @@ export function assessDecisionRequirement(prompt: string): DecisionRequirement {
|
|
|
80
80
|
|
|
81
81
|
export function requiresImplementationPlan(prompt: string, archetype = '', confidence = ''): boolean {
|
|
82
82
|
const text = String(prompt ?? '').toLowerCase();
|
|
83
|
+
// A classifier can label any "create" request build_app. A single plain
|
|
84
|
+
// text/data-file operation needs no checklist or rejected mutation round trip.
|
|
85
|
+
const namedFiles = new Set([...text.matchAll(/\b[\w./-]+\.(?:txt|md|csv|json)\b/g)].map(match => match[0]));
|
|
86
|
+
const simpleFileOperation = text.length < 700 && namedFiles.size === 1
|
|
87
|
+
&& /\b(?:create|write|save)\b/.test(text)
|
|
88
|
+
&& !/\b(?:research|search|scrap\w*|codebase|migrat\w*|refactor|integrat\w*|application|website|database|security|authentication|authorization|framework|architecture|runtime)\b/.test(text)
|
|
89
|
+
&& !/\b(?:package(?:-lock)?\.json|tsconfig\w*\.json|permissions?\.json|policy\.json)\b/.test(text);
|
|
90
|
+
if (simpleFileOperation) return false;
|
|
83
91
|
if (archetype === 'build_app' || archetype === 'integrate') return true;
|
|
84
92
|
if (confidence === 'high' && /\b(?:implement|build|create|migrate|rewrite|refactor|integrate)\b/i.test(text)) {
|
|
85
93
|
return true;
|