@causyne/agent 1.20.117 → 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 +7 -2
- 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 +20 -4
- package/src/commands.js +12 -14
- 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/plugins/pluginManager.js +74 -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/reporting.js +12 -4
- package/src/skillsManager.js +3 -2
- package/src/skillsManager.ts +3 -2
- 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/pluginManager.js +17 -2
- 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/composerControls.js +16 -3
- package/src/tui/composerControls.ts +14 -3
- package/src/tui/prompt.js +122 -16
- 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/usageCard.js +119 -47
- package/src/tui/usageCard.ts +133 -49
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
- package/src/tui/workspaceSwitch.js +2 -0
- package/src/tui/workspaceSwitch.ts +1 -0
- package/src/verification/boundedExplorer.js +119 -0
- package/src/verification/cliProbe.js +116 -0
- package/src/verification/featureMap.js +78 -0
- package/src/verification/interactivePty.js +188 -0
- package/src/verification/propertyProbe.js +121 -0
- package/src/verification/ptyProbe.js +125 -0
- package/src/verification/skillCatalog.d.ts +1 -0
- package/src/verification/skillCatalog.js +60 -0
- package/src/verification/statechart.js +143 -0
- package/src/verification/uiRuntime.js +57 -0
- package/src/verificationPlan.js +1 -1
- package/src/verificationPlan.ts +1 -1
|
@@ -19,17 +19,22 @@ function decodeEntities(value) {
|
|
|
19
19
|
}
|
|
20
20
|
function cleanMarkup(value) {
|
|
21
21
|
return decodeEntities(value.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/<[^>]+>/g, ' '))
|
|
22
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
|
|
22
23
|
.replace(/\s+/g, ' ')
|
|
23
24
|
.trim();
|
|
24
25
|
}
|
|
25
|
-
function publicResultUrl(value) {
|
|
26
|
+
export function publicResultUrl(value) {
|
|
26
27
|
try {
|
|
28
|
+
if (value.length > 4_096)
|
|
29
|
+
return null;
|
|
27
30
|
const parsed = new URL(decodeEntities(value));
|
|
28
31
|
if (!['http:', 'https:'].includes(parsed.protocol))
|
|
29
32
|
return null;
|
|
30
33
|
const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
31
34
|
if (parsed.username || parsed.password || host === 'localhost' ||
|
|
32
35
|
host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
|
|
36
|
+
host.endsWith('.invalid') || host.endsWith('.test') || host.endsWith('.example') ||
|
|
37
|
+
host.endsWith('.onion') || host === 'localhost.localdomain' ||
|
|
33
38
|
(isIP(host) !== 0 && isPrivateAddress(host)))
|
|
34
39
|
return null;
|
|
35
40
|
if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname))
|
|
@@ -87,8 +92,10 @@ export function parseDuckDuckGoHtml(html) {
|
|
|
87
92
|
}
|
|
88
93
|
async function readBoundedText(response) {
|
|
89
94
|
const declared = Number(response.headers.get('content-length') ?? '0');
|
|
90
|
-
if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES)
|
|
95
|
+
if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES) {
|
|
96
|
+
await response.body?.cancel().catch(() => { });
|
|
91
97
|
throw new Error('search response is too large');
|
|
98
|
+
}
|
|
92
99
|
if (!response.body)
|
|
93
100
|
return '';
|
|
94
101
|
const reader = response.body.getReader();
|
|
@@ -117,9 +124,6 @@ export async function searchPublicWeb(query, options = {}) {
|
|
|
117
124
|
if (!cleaned || cleaned.length > 1_000)
|
|
118
125
|
throw new Error('Search query must contain 1-1000 characters');
|
|
119
126
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
120
|
-
const controller = new AbortController();
|
|
121
|
-
const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
|
|
122
|
-
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
123
127
|
const providers = [
|
|
124
128
|
{
|
|
125
129
|
engine: 'duckduckgo-html',
|
|
@@ -135,33 +139,40 @@ export async function searchPublicWeb(query, options = {}) {
|
|
|
135
139
|
}
|
|
136
140
|
];
|
|
137
141
|
const failures = [];
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
catch (error) {
|
|
159
|
-
failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
|
|
142
|
+
for (const provider of providers) {
|
|
143
|
+
if (options.signal?.aborted)
|
|
144
|
+
throw options.signal.reason ?? new Error('Search cancelled');
|
|
145
|
+
const controller = new AbortController();
|
|
146
|
+
const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
|
|
147
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
148
|
+
try {
|
|
149
|
+
const response = await fetchImpl(provider.url, {
|
|
150
|
+
method: 'GET',
|
|
151
|
+
redirect: 'error',
|
|
152
|
+
signal,
|
|
153
|
+
headers: {
|
|
154
|
+
Accept: provider.accept,
|
|
155
|
+
'Accept-Language': 'en-US,en;q=0.8',
|
|
156
|
+
'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)'
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
if (!response.ok) {
|
|
160
|
+
await response.body?.cancel().catch(() => { });
|
|
161
|
+
throw new Error(`HTTP ${response.status}`);
|
|
160
162
|
}
|
|
163
|
+
const results = provider.parse(await readBoundedText(response));
|
|
164
|
+
if (results.length > 0)
|
|
165
|
+
return results;
|
|
166
|
+
failures.push(`${provider.engine}: no results`);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (options.signal?.aborted)
|
|
170
|
+
throw error;
|
|
171
|
+
failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
clearTimeout(timeout);
|
|
161
175
|
}
|
|
162
|
-
}
|
|
163
|
-
finally {
|
|
164
|
-
clearTimeout(timeout);
|
|
165
176
|
}
|
|
166
177
|
throw new Error(`Lightweight search providers exhausted. ${failures.join('; ')}`);
|
|
167
178
|
}
|
|
@@ -33,17 +33,21 @@ function decodeEntities(value: string): string {
|
|
|
33
33
|
|
|
34
34
|
function cleanMarkup(value: string): string {
|
|
35
35
|
return decodeEntities(value.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/<[^>]+>/g, ' '))
|
|
36
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
|
|
36
37
|
.replace(/\s+/g, ' ')
|
|
37
38
|
.trim();
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
function publicResultUrl(value: string): string | null {
|
|
41
|
+
export function publicResultUrl(value: string): string | null {
|
|
41
42
|
try {
|
|
43
|
+
if (value.length > 4_096) return null;
|
|
42
44
|
const parsed = new URL(decodeEntities(value));
|
|
43
45
|
if (!['http:', 'https:'].includes(parsed.protocol)) return null;
|
|
44
46
|
const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
45
47
|
if (parsed.username || parsed.password || host === 'localhost' ||
|
|
46
48
|
host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
|
|
49
|
+
host.endsWith('.invalid') || host.endsWith('.test') || host.endsWith('.example') ||
|
|
50
|
+
host.endsWith('.onion') || host === 'localhost.localdomain' ||
|
|
47
51
|
(isIP(host) !== 0 && isPrivateAddress(host))) return null;
|
|
48
52
|
if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname)) return null;
|
|
49
53
|
return parsed.href;
|
|
@@ -96,7 +100,10 @@ export function parseDuckDuckGoHtml(html: string): SearchResult[] {
|
|
|
96
100
|
|
|
97
101
|
async function readBoundedText(response: Response): Promise<string> {
|
|
98
102
|
const declared = Number(response.headers.get('content-length') ?? '0');
|
|
99
|
-
if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES)
|
|
103
|
+
if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES) {
|
|
104
|
+
await response.body?.cancel().catch(() => {});
|
|
105
|
+
throw new Error('search response is too large');
|
|
106
|
+
}
|
|
100
107
|
if (!response.body) return '';
|
|
101
108
|
const reader = response.body.getReader();
|
|
102
109
|
const chunks: Uint8Array[] = [];
|
|
@@ -122,9 +129,6 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
|
|
|
122
129
|
const cleaned = String(query ?? '').trim();
|
|
123
130
|
if (!cleaned || cleaned.length > 1_000) throw new Error('Search query must contain 1-1000 characters');
|
|
124
131
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
125
|
-
const controller = new AbortController();
|
|
126
|
-
const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
|
|
127
|
-
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
128
132
|
const providers = [
|
|
129
133
|
{
|
|
130
134
|
engine: 'duckduckgo-html',
|
|
@@ -140,9 +144,12 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
|
|
|
140
144
|
}
|
|
141
145
|
];
|
|
142
146
|
const failures: string[] = [];
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
147
|
+
for (const provider of providers) {
|
|
148
|
+
if (options.signal?.aborted) throw options.signal.reason ?? new Error('Search cancelled');
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
|
|
151
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
152
|
+
try {
|
|
146
153
|
const response = await fetchImpl(provider.url, {
|
|
147
154
|
method: 'GET',
|
|
148
155
|
redirect: 'error',
|
|
@@ -153,16 +160,19 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
|
|
|
153
160
|
'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)'
|
|
154
161
|
}
|
|
155
162
|
});
|
|
156
|
-
if (!response.ok)
|
|
163
|
+
if (!response.ok) {
|
|
164
|
+
await response.body?.cancel().catch(() => {});
|
|
165
|
+
throw new Error(`HTTP ${response.status}`);
|
|
166
|
+
}
|
|
157
167
|
const results = provider.parse(await readBoundedText(response));
|
|
158
168
|
if (results.length > 0) return results;
|
|
159
169
|
failures.push(`${provider.engine}: no results`);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (options.signal?.aborted) throw error;
|
|
172
|
+
failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
|
|
173
|
+
} finally {
|
|
174
|
+
clearTimeout(timeout);
|
|
163
175
|
}
|
|
164
|
-
} finally {
|
|
165
|
-
clearTimeout(timeout);
|
|
166
176
|
}
|
|
167
177
|
throw new Error(`Lightweight search providers exhausted. ${failures.join('; ')}`);
|
|
168
178
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
function within(root, target) {
|
|
4
|
+
const relative = path.relative(root, target);
|
|
5
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
6
|
+
}
|
|
7
|
+
function scopedTarget(workspace, target) {
|
|
8
|
+
const root = path.resolve(workspace);
|
|
9
|
+
const resolved = path.resolve(target);
|
|
10
|
+
if (root === resolved || !within(root, resolved))
|
|
11
|
+
throw new Error('File target must stay inside the selected workspace');
|
|
12
|
+
return { root, resolved };
|
|
13
|
+
}
|
|
14
|
+
export async function ensureSafeWorkspaceOutputPath(workspace, target) {
|
|
15
|
+
const { root, resolved } = scopedTarget(workspace, target);
|
|
16
|
+
const realRoot = await fs.realpath(root);
|
|
17
|
+
const relativeParent = path.relative(root, path.dirname(resolved));
|
|
18
|
+
let current = root;
|
|
19
|
+
for (const part of relativeParent.split(path.sep).filter(Boolean)) {
|
|
20
|
+
current = path.join(current, part);
|
|
21
|
+
try {
|
|
22
|
+
await fs.lstat(current);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code !== 'ENOENT')
|
|
26
|
+
throw error;
|
|
27
|
+
await fs.mkdir(current);
|
|
28
|
+
}
|
|
29
|
+
const realCurrent = await fs.realpath(current);
|
|
30
|
+
if (!within(realRoot, realCurrent) || !(await fs.stat(current)).isDirectory()) {
|
|
31
|
+
throw new Error('Output directory resolves outside the selected workspace');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const existing = await fs.lstat(resolved).catch((error) => {
|
|
35
|
+
if (error.code === 'ENOENT')
|
|
36
|
+
return null;
|
|
37
|
+
throw error;
|
|
38
|
+
});
|
|
39
|
+
if (existing?.isSymbolicLink() || (existing && !existing.isFile())) {
|
|
40
|
+
throw new Error('Output target cannot be a symlink or directory');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export async function ensureSafeWorkspaceInputPath(workspace, target) {
|
|
44
|
+
const { root, resolved } = scopedTarget(workspace, target);
|
|
45
|
+
const realRoot = await fs.realpath(root);
|
|
46
|
+
const realTarget = await fs.realpath(resolved);
|
|
47
|
+
if (!within(realRoot, realTarget) || !(await fs.stat(realTarget)).isFile()) {
|
|
48
|
+
throw new Error('Upload file resolves outside the selected workspace or is not regular');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
function within(root: string, target: string): boolean {
|
|
5
|
+
const relative = path.relative(root, target);
|
|
6
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function scopedTarget(workspace: string, target: string): { root: string; resolved: string } {
|
|
10
|
+
const root = path.resolve(workspace);
|
|
11
|
+
const resolved = path.resolve(target);
|
|
12
|
+
if (root === resolved || !within(root, resolved)) throw new Error('File target must stay inside the selected workspace');
|
|
13
|
+
return { root, resolved };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function ensureSafeWorkspaceOutputPath(workspace: string, target: string): Promise<void> {
|
|
17
|
+
const { root, resolved } = scopedTarget(workspace, target);
|
|
18
|
+
const realRoot = await fs.realpath(root);
|
|
19
|
+
const relativeParent = path.relative(root, path.dirname(resolved));
|
|
20
|
+
let current = root;
|
|
21
|
+
for (const part of relativeParent.split(path.sep).filter(Boolean)) {
|
|
22
|
+
current = path.join(current, part);
|
|
23
|
+
try {
|
|
24
|
+
await fs.lstat(current);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
27
|
+
await fs.mkdir(current);
|
|
28
|
+
}
|
|
29
|
+
const realCurrent = await fs.realpath(current);
|
|
30
|
+
if (!within(realRoot, realCurrent) || !(await fs.stat(current)).isDirectory()) {
|
|
31
|
+
throw new Error('Output directory resolves outside the selected workspace');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const existing = await fs.lstat(resolved).catch((error: NodeJS.ErrnoException) => {
|
|
35
|
+
if (error.code === 'ENOENT') return null;
|
|
36
|
+
throw error;
|
|
37
|
+
});
|
|
38
|
+
if (existing?.isSymbolicLink() || (existing && !existing.isFile())) {
|
|
39
|
+
throw new Error('Output target cannot be a symlink or directory');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function ensureSafeWorkspaceInputPath(workspace: string, target: string): Promise<void> {
|
|
44
|
+
const { root, resolved } = scopedTarget(workspace, target);
|
|
45
|
+
const realRoot = await fs.realpath(root);
|
|
46
|
+
const realTarget = await fs.realpath(resolved);
|
|
47
|
+
if (!within(realRoot, realTarget) || !(await fs.stat(realTarget)).isFile()) {
|
|
48
|
+
throw new Error('Upload file resolves outside the selected workspace or is not regular');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -2,6 +2,27 @@ import fs from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
const MAX_ACTIVE_PREVIEWS = 128;
|
|
5
|
+
const MAX_PREVIEW_BYTES = 25 * 1024 * 1024;
|
|
6
|
+
export async function readBoundedPreviewFile(file, maxBytes = MAX_PREVIEW_BYTES, openFile = fs.open) {
|
|
7
|
+
const handle = await openFile(file, 'r');
|
|
8
|
+
try {
|
|
9
|
+
const stat = await handle.stat();
|
|
10
|
+
if (!stat.isFile() || stat.size > maxBytes || stat.size < 0)
|
|
11
|
+
return null;
|
|
12
|
+
const body = Buffer.alloc(stat.size);
|
|
13
|
+
let total = 0;
|
|
14
|
+
while (total < body.length) {
|
|
15
|
+
const { bytesRead } = await handle.read(body, total, body.length - total, total);
|
|
16
|
+
if (bytesRead === 0)
|
|
17
|
+
break;
|
|
18
|
+
total += bytesRead;
|
|
19
|
+
}
|
|
20
|
+
return total === body.length ? body : null;
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
await handle.close();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
5
26
|
const MIME = {
|
|
6
27
|
'.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
|
|
7
28
|
'.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
@@ -23,6 +44,8 @@ export class WorkspacePreview {
|
|
|
23
44
|
const target = await fs.realpath(path.resolve(root, file));
|
|
24
45
|
if (!within(root, target) || !/\.html?$/i.test(target))
|
|
25
46
|
throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
47
|
+
if (!(await fs.stat(target)).isFile())
|
|
48
|
+
throw new Error('Preview target must be a regular HTML file');
|
|
26
49
|
const origin = `https://${randomUUID()}.causyne-preview.invalid`;
|
|
27
50
|
this.roots.set(origin, path.dirname(target));
|
|
28
51
|
if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
|
|
@@ -46,16 +69,16 @@ export class WorkspacePreview {
|
|
|
46
69
|
const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
|
|
47
70
|
try {
|
|
48
71
|
const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
|
|
49
|
-
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(
|
|
72
|
+
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|private|tokens?|id_rsa|id_ed25519)([._-]|$)/i.test(part)))
|
|
50
73
|
return deny;
|
|
51
74
|
const file = await fs.realpath(path.resolve(root, ...parts));
|
|
52
75
|
const contentType = MIME[path.extname(file).toLowerCase()];
|
|
53
76
|
if (!within(root, file) || !contentType)
|
|
54
77
|
return deny;
|
|
55
|
-
const
|
|
56
|
-
if (
|
|
78
|
+
const body = await readBoundedPreviewFile(file);
|
|
79
|
+
if (body === null)
|
|
57
80
|
return deny;
|
|
58
|
-
return { status: 200, contentType, body
|
|
81
|
+
return { status: 200, contentType, body };
|
|
59
82
|
}
|
|
60
83
|
catch {
|
|
61
84
|
return { ...deny, status: 404 };
|
|
@@ -3,6 +3,29 @@ import path from 'node:path';
|
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
|
|
5
5
|
const MAX_ACTIVE_PREVIEWS = 128;
|
|
6
|
+
const MAX_PREVIEW_BYTES = 25 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
export async function readBoundedPreviewFile(
|
|
9
|
+
file: string, maxBytes = MAX_PREVIEW_BYTES, openFile: typeof fs.open = fs.open
|
|
10
|
+
): Promise<Buffer | null> {
|
|
11
|
+
const handle = await openFile(file, 'r');
|
|
12
|
+
try {
|
|
13
|
+
const stat = await handle.stat();
|
|
14
|
+
if (!stat.isFile() || stat.size > maxBytes || stat.size < 0) return null;
|
|
15
|
+
const body = Buffer.alloc(stat.size);
|
|
16
|
+
let total = 0;
|
|
17
|
+
while (total < body.length) {
|
|
18
|
+
const { bytesRead } = await handle.read(body, total, body.length - total, total);
|
|
19
|
+
if (bytesRead === 0) break;
|
|
20
|
+
total += bytesRead;
|
|
21
|
+
}
|
|
22
|
+
return total === body.length ? body : null;
|
|
23
|
+
} finally {
|
|
24
|
+
await handle.close();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
6
29
|
const MIME: Record<string, string> = {
|
|
7
30
|
'.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
|
|
8
31
|
'.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
@@ -26,6 +49,7 @@ export class WorkspacePreview {
|
|
|
26
49
|
const root = await fs.realpath(workspace);
|
|
27
50
|
const target = await fs.realpath(path.resolve(root, file));
|
|
28
51
|
if (!within(root, target) || !/\.html?$/i.test(target)) throw new Error('Preview requires an HTML file inside the selected workspace');
|
|
52
|
+
if (!(await fs.stat(target)).isFile()) throw new Error('Preview target must be a regular HTML file');
|
|
29
53
|
const origin = `https://${randomUUID()}.causyne-preview.invalid`;
|
|
30
54
|
this.roots.set(origin, path.dirname(target));
|
|
31
55
|
if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
|
|
@@ -47,13 +71,13 @@ export class WorkspacePreview {
|
|
|
47
71
|
const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
|
|
48
72
|
try {
|
|
49
73
|
const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
|
|
50
|
-
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(
|
|
74
|
+
if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|private|tokens?|id_rsa|id_ed25519)([._-]|$)/i.test(part))) return deny;
|
|
51
75
|
const file = await fs.realpath(path.resolve(root, ...parts));
|
|
52
76
|
const contentType = MIME[path.extname(file).toLowerCase()];
|
|
53
77
|
if (!within(root, file) || !contentType) return deny;
|
|
54
|
-
const
|
|
55
|
-
if (
|
|
56
|
-
return { status: 200, contentType, body
|
|
78
|
+
const body = await readBoundedPreviewFile(file);
|
|
79
|
+
if (body === null) return deny;
|
|
80
|
+
return { status: 200, contentType, body };
|
|
57
81
|
} catch { return { ...deny, status: 404 }; }
|
|
58
82
|
}
|
|
59
83
|
}
|
package/src/cliMode.js
CHANGED
|
@@ -66,6 +66,9 @@ export class LocalCLIConnection {
|
|
|
66
66
|
|
|
67
67
|
try {
|
|
68
68
|
this.renderer.handle(msg);
|
|
69
|
+
if (msg.type === 'usage_update' && typeof this.onUsageUpdate === 'function') {
|
|
70
|
+
this.onUsageUpdate(msg);
|
|
71
|
+
}
|
|
69
72
|
} catch (e) {
|
|
70
73
|
// This used to be `catch(e) {}` around the whole method, so a render bug
|
|
71
74
|
// silently ate the frame and the transcript just went quiet. Report it
|
|
@@ -377,12 +380,24 @@ export async function chatMode({ home = false } = {}) {
|
|
|
377
380
|
messageActionLoop: loop,
|
|
378
381
|
onInterrupt: () => loop.abort(),
|
|
379
382
|
getMode: () => loop.config?.autonomyMode || config.autonomyMode || 'B',
|
|
380
|
-
onOpenMode: () =>
|
|
381
|
-
|
|
382
|
-
|
|
383
|
+
onOpenMode: async () => {
|
|
384
|
+
await openModeControl(prompt, loop);
|
|
385
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
386
|
+
},
|
|
387
|
+
onOpenModel: async () => {
|
|
388
|
+
await runInteractiveModelPicker(prompt, { loadConfig, saveConfig }, { loop });
|
|
389
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
390
|
+
},
|
|
391
|
+
onOpenVariant: async () => {
|
|
392
|
+
await openVariantControl(prompt);
|
|
393
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
394
|
+
},
|
|
383
395
|
onExit: () => { if (prompt) prompt.stop(); process.exit(0); },
|
|
384
396
|
onExpand: () => conn.renderer.expandLastOutput()
|
|
385
397
|
});
|
|
398
|
+
conn.onUsageUpdate = () => {
|
|
399
|
+
if (prompt && typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(loop);
|
|
400
|
+
};
|
|
386
401
|
if (surface) prompt.attachSurface(surface);
|
|
387
402
|
prompt.attach(conn.renderer);
|
|
388
403
|
prompt.start();
|
|
@@ -580,7 +595,7 @@ export async function chatMode({ home = false } = {}) {
|
|
|
580
595
|
const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
|
|
581
596
|
await runInteractiveSessionPicker(prompt, {
|
|
582
597
|
loop,
|
|
583
|
-
workspace: loop?.workspaceRoot || process.cwd()
|
|
598
|
+
workspace: loop?.workspaceRoot || prompt?.root || process.cwd()
|
|
584
599
|
});
|
|
585
600
|
if (prompt && typeof prompt.draw === 'function') prompt.draw();
|
|
586
601
|
continue;
|
|
@@ -631,6 +646,7 @@ export async function chatMode({ home = false } = {}) {
|
|
|
631
646
|
if (commandResult.output && (commandResult.output.includes('Now using') || commandResult.output.includes('Active model switched') || commandResult.output.includes('Saved API key'))) {
|
|
632
647
|
conn.renderer.write(homeStatusLine({ config: loadConfig() }) + '\n');
|
|
633
648
|
}
|
|
649
|
+
if (prompt && typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(loop);
|
|
634
650
|
if (commandResult.effect === 'exit') { finish(); break; }
|
|
635
651
|
continue;
|
|
636
652
|
}
|
package/src/commands.js
CHANGED
|
@@ -692,7 +692,7 @@ export const COMMANDS = [
|
|
|
692
692
|
run: async (_args = [], context = {}) => {
|
|
693
693
|
const store = await import('./sessionStore.js');
|
|
694
694
|
const memory = context.loop && context.loop.memoryManager;
|
|
695
|
-
const workspace = context.loop?.workspaceRoot || process.cwd();
|
|
695
|
+
const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
|
|
696
696
|
const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
|
|
697
697
|
if (context.loop) {
|
|
698
698
|
context.loop.messages = [];
|
|
@@ -742,7 +742,7 @@ export const COMMANDS = [
|
|
|
742
742
|
const store = await import('./sessionStore.js');
|
|
743
743
|
const verb = String(args[0] || '').toLowerCase();
|
|
744
744
|
const memory = context.loop && context.loop.memoryManager;
|
|
745
|
-
const workspace = context.loop?.workspaceRoot || process.cwd();
|
|
745
|
+
const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
|
|
746
746
|
|
|
747
747
|
// If interactive TUI prompt is available and no sub-arguments are given, open interactive picker modal
|
|
748
748
|
if ((!args || args.length === 0 || (args.length === 1 && args[0] === '')) && context.prompt) {
|
|
@@ -850,19 +850,11 @@ export const COMMANDS = [
|
|
|
850
850
|
return ok('No sessions yet. This conversation becomes one as soon as you send something.');
|
|
851
851
|
}
|
|
852
852
|
|
|
853
|
-
const active = store.getActiveSessionId();
|
|
854
|
-
const
|
|
855
|
-
const lines = rows.slice(0, 20).map((s) => {
|
|
856
|
-
const when = new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ');
|
|
857
|
-
const where = s.workspace ? (home ? s.workspace.replace(home, '~') : s.workspace) : '(no workspace)';
|
|
858
|
-
const mark = s.id === active ? '*' : ' ';
|
|
859
|
-
return ` ${mark} ${s.id} ${when} ${String(s.messageCount).padStart(4)} msg ${where}\n ${s.title}`;
|
|
860
|
-
});
|
|
853
|
+
const active = memory?.sessionId || store.getActiveSessionId();
|
|
854
|
+
const { formatSessionsTextReport } = await import('./tui/sessionPicker.js');
|
|
861
855
|
|
|
862
856
|
return ok(
|
|
863
|
-
|
|
864
|
-
+ lines.join('\n')
|
|
865
|
-
+ '\n\nSwitch with /sessions switch <id>, fork with /fork [id], or run /sessions to open interactive modal picker.',
|
|
857
|
+
formatSessionsTextReport(rows, active, workspace),
|
|
866
858
|
{ effect: 'pick-session', items: rows, active }
|
|
867
859
|
);
|
|
868
860
|
}
|
|
@@ -2055,7 +2047,13 @@ export const COMMANDS = [
|
|
|
2055
2047
|
description: 'Show the current provider, autonomy mode and workspace scope',
|
|
2056
2048
|
dialogTitle: 'Status',
|
|
2057
2049
|
// One builder, shared with `causyne status`, so status output cannot drift.
|
|
2058
|
-
run: (argv, ctx) =>
|
|
2050
|
+
run: (argv, ctx = {}) => {
|
|
2051
|
+
if (ctx.prompt && typeof ctx.prompt.toggleStatusCard === 'function') {
|
|
2052
|
+
ctx.prompt.toggleStatusCard(ctx.loop);
|
|
2053
|
+
return ok('', { effect: 'silent' });
|
|
2054
|
+
}
|
|
2055
|
+
return ok(buildStatusText({ loop: ctx.loop || null }));
|
|
2056
|
+
}
|
|
2059
2057
|
},
|
|
2060
2058
|
|
|
2061
2059
|
{
|
|
@@ -704,6 +704,39 @@ export function validateGameEngineJob(value) {
|
|
|
704
704
|
}
|
|
705
705
|
return [nums[0], nums[1], nums[2]];
|
|
706
706
|
};
|
|
707
|
+
const normalizePropertyValue = (val) => {
|
|
708
|
+
if (typeof val !== 'string')
|
|
709
|
+
return val;
|
|
710
|
+
const trimmed = val.trim();
|
|
711
|
+
if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
712
|
+
try {
|
|
713
|
+
const parsed = JSON.parse(trimmed);
|
|
714
|
+
if (typeof parsed === 'string')
|
|
715
|
+
return parsed;
|
|
716
|
+
}
|
|
717
|
+
catch {
|
|
718
|
+
// Keep raw string
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
722
|
+
try {
|
|
723
|
+
return JSON.parse(trimmed);
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
return val;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (trimmed === 'true')
|
|
730
|
+
return true;
|
|
731
|
+
if (trimmed === 'false')
|
|
732
|
+
return false;
|
|
733
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
|
|
734
|
+
const num = Number(trimmed);
|
|
735
|
+
if (Number.isFinite(num))
|
|
736
|
+
return num;
|
|
737
|
+
}
|
|
738
|
+
return val;
|
|
739
|
+
};
|
|
707
740
|
return {
|
|
708
741
|
engine: engineInput,
|
|
709
742
|
canonicalEngine,
|
|
@@ -716,7 +749,7 @@ export function validateGameEngineJob(value) {
|
|
|
716
749
|
objectPath: typeof raw.objectPath === 'string' ? raw.objectPath.trim() : undefined,
|
|
717
750
|
functionName: typeof raw.functionName === 'string' ? raw.functionName.trim() : undefined,
|
|
718
751
|
propertyName: typeof raw.propertyName === 'string' ? raw.propertyName.trim() : undefined,
|
|
719
|
-
propertyValue: raw.propertyValue,
|
|
752
|
+
propertyValue: normalizePropertyValue(raw.propertyValue),
|
|
720
753
|
parameters: raw.parameters && typeof raw.parameters === 'object' && !Array.isArray(raw.parameters)
|
|
721
754
|
? raw.parameters
|
|
722
755
|
: undefined,
|
|
@@ -948,6 +948,33 @@ export function validateGameEngineJob(value: unknown): GameEngineJob {
|
|
|
948
948
|
return [nums[0]!, nums[1]!, nums[2]!];
|
|
949
949
|
};
|
|
950
950
|
|
|
951
|
+
const normalizePropertyValue = (val: unknown): unknown => {
|
|
952
|
+
if (typeof val !== 'string') return val;
|
|
953
|
+
const trimmed = val.trim();
|
|
954
|
+
if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
955
|
+
try {
|
|
956
|
+
const parsed = JSON.parse(trimmed);
|
|
957
|
+
if (typeof parsed === 'string') return parsed;
|
|
958
|
+
} catch {
|
|
959
|
+
// Keep raw string
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
963
|
+
try {
|
|
964
|
+
return JSON.parse(trimmed);
|
|
965
|
+
} catch {
|
|
966
|
+
return val;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
if (trimmed === 'true') return true;
|
|
970
|
+
if (trimmed === 'false') return false;
|
|
971
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
|
|
972
|
+
const num = Number(trimmed);
|
|
973
|
+
if (Number.isFinite(num)) return num;
|
|
974
|
+
}
|
|
975
|
+
return val;
|
|
976
|
+
};
|
|
977
|
+
|
|
951
978
|
return {
|
|
952
979
|
engine: engineInput,
|
|
953
980
|
canonicalEngine,
|
|
@@ -960,7 +987,7 @@ export function validateGameEngineJob(value: unknown): GameEngineJob {
|
|
|
960
987
|
objectPath: typeof raw.objectPath === 'string' ? raw.objectPath.trim() : undefined,
|
|
961
988
|
functionName: typeof raw.functionName === 'string' ? raw.functionName.trim() : undefined,
|
|
962
989
|
propertyName: typeof raw.propertyName === 'string' ? raw.propertyName.trim() : undefined,
|
|
963
|
-
propertyValue: raw.propertyValue,
|
|
990
|
+
propertyValue: normalizePropertyValue(raw.propertyValue),
|
|
964
991
|
parameters: raw.parameters && typeof raw.parameters === 'object' && !Array.isArray(raw.parameters)
|
|
965
992
|
? (raw.parameters as Record<string, unknown>)
|
|
966
993
|
: undefined,
|
package/src/observer/evidence.js
CHANGED
|
@@ -120,6 +120,29 @@ export function isCodePath(target) {
|
|
|
120
120
|
export function isRenderedNativeBrowserAction(tool) {
|
|
121
121
|
return ['browser_act', 'preview', 'snapshot'].includes(tool.toLowerCase());
|
|
122
122
|
}
|
|
123
|
+
/** Only inspected, successful DOM output counts as browser verification. */
|
|
124
|
+
export function inspectBrowserToolEvidence(result) {
|
|
125
|
+
if (!result || typeof result !== 'object')
|
|
126
|
+
return { verified: false, runtimeErrors: [] };
|
|
127
|
+
const data = result;
|
|
128
|
+
if (data.success !== true || !Array.isArray(data.data))
|
|
129
|
+
return { verified: false, runtimeErrors: [] };
|
|
130
|
+
const runtimeErrors = [];
|
|
131
|
+
let verified = false;
|
|
132
|
+
for (const item of data.data) {
|
|
133
|
+
if (!item || typeof item !== 'object')
|
|
134
|
+
continue;
|
|
135
|
+
const action = item;
|
|
136
|
+
if (Array.isArray(action.data?.runtimeErrors)) {
|
|
137
|
+
runtimeErrors.push(...action.data.runtimeErrors.filter((error) => typeof error === 'string'));
|
|
138
|
+
}
|
|
139
|
+
if (['snapshot', 'scrape'].includes(action.action ?? '')
|
|
140
|
+
&& typeof action.output === 'string' && action.output.trim()) {
|
|
141
|
+
verified = true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { verified: verified && runtimeErrors.length === 0, runtimeErrors };
|
|
145
|
+
}
|
|
123
146
|
export function isVerificationCommand(command) {
|
|
124
147
|
return VERIFICATION_COMMAND.test(command);
|
|
125
148
|
}
|