@causyne/agent 1.20.78 → 1.20.79
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 +75 -94
- package/src/agentLoop.ts +86 -106
- package/src/cliMode.js +7 -2
- package/src/reliability/assetEvidence.js +112 -0
- package/src/reliability/assetEvidence.ts +109 -0
- package/src/reliability/networkHostGuard.js +56 -0
- package/src/reliability/networkHostGuard.ts +68 -0
- package/src/reliability/visualEvidence.js +21 -0
- package/src/reliability/visualEvidence.ts +35 -0
- package/src/tools/fsWrite.js +131 -22
- package/src/tools/fsWrite.ts +129 -26
|
@@ -0,0 +1,112 @@
|
|
|
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}`)
|
|
6
|
+
&& !path.isAbsolute(relative));
|
|
7
|
+
}
|
|
8
|
+
function imageRequirement(prompt) {
|
|
9
|
+
const text = String(prompt || '').toLowerCase();
|
|
10
|
+
const isImageTask = /\b(real|actual|authentic|stock|travel)\b.{0,45}\b(images?|photos?|pictures?)\b|\b(images?|photos?|pictures?)\b.{0,45}\b(real|actual|authentic)\b/i.test(text);
|
|
11
|
+
const asksForAcquisition = /\b(download(?:ed|ing|s)?|fetch(?:ed|ing)?|grab(?:bed|bing)?|source(?:d|s)?|search(?:ing)?|online|from the web|web grab)\b|osnwload|downlaod/i.test(text);
|
|
12
|
+
return isImageTask && asksForAcquisition;
|
|
13
|
+
}
|
|
14
|
+
function extractImageReferences(text) {
|
|
15
|
+
const references = new Set();
|
|
16
|
+
// Prefer evidence from actual HTML/CSS references over files merely present
|
|
17
|
+
// somewhere in a workspace. Remote URLs are not downloaded image assets.
|
|
18
|
+
for (const match of String(text).matchAll(/\b(?:src|poster)\s*=\s*["']([^"']+)["']|url\(\s*["']?([^"')]+)["']?\s*\)/gi)) {
|
|
19
|
+
const ref = (match[1] || match[2] || '').trim();
|
|
20
|
+
if (/\.(?:png|jpe?g|webp|gif|avif|bmp|svg)(?:[?#].*)?$/i.test(ref))
|
|
21
|
+
references.add(ref);
|
|
22
|
+
}
|
|
23
|
+
return [...references];
|
|
24
|
+
}
|
|
25
|
+
function magicImage(buffer, extension) {
|
|
26
|
+
if (!buffer?.length)
|
|
27
|
+
return false;
|
|
28
|
+
switch (extension) {
|
|
29
|
+
case '.jpg':
|
|
30
|
+
case '.jpeg': return buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
|
|
31
|
+
case '.png': return buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
|
32
|
+
case '.gif': return buffer.subarray(0, 6).toString('ascii') === 'GIF89a' || buffer.subarray(0, 6).toString('ascii') === 'GIF87a';
|
|
33
|
+
case '.webp': return buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP';
|
|
34
|
+
case '.bmp': return buffer.subarray(0, 2).toString('ascii') === 'BM';
|
|
35
|
+
case '.avif': return buffer.subarray(4, 12).toString('ascii').includes('ftypavif');
|
|
36
|
+
default: return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Narrow, deterministic completion gate. Only invoked for a request explicitly
|
|
41
|
+
* asking for real downloaded pictures in a generated web project.
|
|
42
|
+
* It does not claim that images are legally licensed, appropriate, or pretty.
|
|
43
|
+
*/
|
|
44
|
+
export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webArtifacts }) {
|
|
45
|
+
if (!imageRequirement(prompt))
|
|
46
|
+
return { ok: true, required: false };
|
|
47
|
+
const workspace = await fs.realpath(workspaceRoot).catch(() => null);
|
|
48
|
+
if (!workspace)
|
|
49
|
+
return { ok: false, required: true, reason: 'The selected workspace could not be read to verify downloaded images.' };
|
|
50
|
+
const paths = [...new Set(Array.isArray(webArtifacts) ? webArtifacts : [])];
|
|
51
|
+
const candidates = [];
|
|
52
|
+
for (const candidate of paths) {
|
|
53
|
+
if (typeof candidate !== 'string' || !/\.(html?|css)$/i.test(candidate))
|
|
54
|
+
continue;
|
|
55
|
+
const physical = await fs.realpath(path.resolve(candidate)).catch(() => null);
|
|
56
|
+
if (!physical || !within(workspace, physical))
|
|
57
|
+
continue;
|
|
58
|
+
const stat = await fs.stat(physical).catch(() => null);
|
|
59
|
+
if (stat?.isFile() && stat.size <= 1_000_000)
|
|
60
|
+
candidates.push(physical);
|
|
61
|
+
if (candidates.length >= 30)
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
if (!candidates.length) {
|
|
65
|
+
return { ok: false, required: true, reason: 'The request requires downloaded real images, but no verifiable HTML/CSS artifacts were recorded.' };
|
|
66
|
+
}
|
|
67
|
+
let refsSeen = 0;
|
|
68
|
+
let localValid = 0;
|
|
69
|
+
for (const sourceFile of candidates) {
|
|
70
|
+
const body = await fs.readFile(sourceFile, 'utf8');
|
|
71
|
+
for (const ref of extractImageReferences(body)) {
|
|
72
|
+
refsSeen++;
|
|
73
|
+
if (/^(?:https?:|data:|\/\/|blob:)/i.test(ref))
|
|
74
|
+
continue;
|
|
75
|
+
let decoded;
|
|
76
|
+
try {
|
|
77
|
+
decoded = decodeURIComponent(ref.split(/[?#]/)[0] ?? '');
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const image = path.resolve(path.dirname(sourceFile), decoded);
|
|
83
|
+
try {
|
|
84
|
+
const physical = await fs.realpath(image);
|
|
85
|
+
if (!within(workspace, physical))
|
|
86
|
+
continue;
|
|
87
|
+
const stat = await fs.stat(physical);
|
|
88
|
+
if (!stat.isFile() || stat.size < 24 || stat.size > 25 * 1024 * 1024)
|
|
89
|
+
continue;
|
|
90
|
+
const handle = await fs.open(physical, 'r');
|
|
91
|
+
try {
|
|
92
|
+
const buffer = Buffer.alloc(1500);
|
|
93
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
94
|
+
if (magicImage(buffer.subarray(0, bytesRead), path.extname(physical).toLowerCase())) {
|
|
95
|
+
localValid++;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
await handle.close();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch { /* Missing or invalid asset is not completion evidence. */ }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (localValid > 0)
|
|
106
|
+
return { ok: true, required: true, checkedReferences: refsSeen, validImages: localValid };
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
required: true,
|
|
110
|
+
reason: `The user requested real pictures downloaded and applied to the website, but ${refsSeen} image reference(s) produced no verified local image file. Source/download attempts failed or the assets were not connected to HTML/CSS. Report the website as partial until a valid downloaded image is integrated.`
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
export interface ImageAssetCheck {
|
|
5
|
+
readonly ok: boolean;
|
|
6
|
+
readonly required: boolean;
|
|
7
|
+
readonly reason?: string;
|
|
8
|
+
readonly checkedReferences?: number;
|
|
9
|
+
readonly validImages?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface InspectImageAssetsInput {
|
|
13
|
+
prompt: string;
|
|
14
|
+
workspaceRoot: string;
|
|
15
|
+
webArtifacts: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function within(root: string, target: string): boolean {
|
|
19
|
+
const relative = path.relative(root, target);
|
|
20
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`)
|
|
21
|
+
&& !path.isAbsolute(relative));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function imageRequirement(prompt: string): boolean {
|
|
25
|
+
const text = String(prompt || '').toLowerCase();
|
|
26
|
+
const isImageTask = /\b(real|actual|authentic|stock|travel)\b.{0,45}\b(images?|photos?|pictures?)\b|\b(images?|photos?|pictures?)\b.{0,45}\b(real|actual|authentic)\b/i.test(text);
|
|
27
|
+
const asksForAcquisition = /\b(download(?:ed|ing|s)?|fetch(?:ed|ing)?|grab(?:bed|bing)?|source(?:d|s)?|search(?:ing)?|online|from the web|web grab)\b|osnwload|downlaod/i.test(text);
|
|
28
|
+
return isImageTask && asksForAcquisition;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function extractImageReferences(text: string): string[] {
|
|
32
|
+
const references = new Set<string>();
|
|
33
|
+
// Prefer evidence from actual HTML/CSS references over files merely present
|
|
34
|
+
// somewhere in a workspace. Remote URLs are not downloaded image assets.
|
|
35
|
+
for (const match of String(text).matchAll(/\b(?:src|poster)\s*=\s*["']([^"']+)["']|url\(\s*["']?([^"')]+)["']?\s*\)/gi)) {
|
|
36
|
+
const ref = (match[1] || match[2] || '').trim();
|
|
37
|
+
if (/\.(?:png|jpe?g|webp|gif|avif|bmp|svg)(?:[?#].*)?$/i.test(ref)) references.add(ref);
|
|
38
|
+
}
|
|
39
|
+
return [...references];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function magicImage(buffer: Buffer | undefined, extension: string): boolean {
|
|
43
|
+
if (!buffer?.length) return false;
|
|
44
|
+
switch (extension) {
|
|
45
|
+
case '.jpg': case '.jpeg': return buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
|
|
46
|
+
case '.png': return buffer.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
|
|
47
|
+
case '.gif': return buffer.subarray(0, 6).toString('ascii') === 'GIF89a' || buffer.subarray(0, 6).toString('ascii') === 'GIF87a';
|
|
48
|
+
case '.webp': return buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP';
|
|
49
|
+
case '.bmp': return buffer.subarray(0, 2).toString('ascii') === 'BM';
|
|
50
|
+
case '.avif': return buffer.subarray(4, 12).toString('ascii').includes('ftypavif');
|
|
51
|
+
default: return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Narrow, deterministic completion gate. Only invoked for a request explicitly
|
|
57
|
+
* asking for real downloaded pictures in a generated web project.
|
|
58
|
+
* It does not claim that images are legally licensed, appropriate, or pretty.
|
|
59
|
+
*/
|
|
60
|
+
export async function inspectRequestedImageAssets({ prompt, workspaceRoot, webArtifacts }: InspectImageAssetsInput): Promise<ImageAssetCheck> {
|
|
61
|
+
if (!imageRequirement(prompt)) return { ok: true, required: false };
|
|
62
|
+
const workspace = await fs.realpath(workspaceRoot).catch(() => null);
|
|
63
|
+
if (!workspace) return { ok: false, required: true, reason: 'The selected workspace could not be read to verify downloaded images.' };
|
|
64
|
+
const paths = [...new Set(Array.isArray(webArtifacts) ? webArtifacts : [])];
|
|
65
|
+
const candidates: string[] = [];
|
|
66
|
+
for (const candidate of paths) {
|
|
67
|
+
if (typeof candidate !== 'string' || !/\.(html?|css)$/i.test(candidate)) continue;
|
|
68
|
+
const physical = await fs.realpath(path.resolve(candidate)).catch(() => null);
|
|
69
|
+
if (!physical || !within(workspace, physical)) continue;
|
|
70
|
+
const stat = await fs.stat(physical).catch(() => null);
|
|
71
|
+
if (stat?.isFile() && stat.size <= 1_000_000) candidates.push(physical);
|
|
72
|
+
if (candidates.length >= 30) break;
|
|
73
|
+
}
|
|
74
|
+
if (!candidates.length) {
|
|
75
|
+
return { ok: false, required: true, reason: 'The request requires downloaded real images, but no verifiable HTML/CSS artifacts were recorded.' };
|
|
76
|
+
}
|
|
77
|
+
let refsSeen = 0;
|
|
78
|
+
let localValid = 0;
|
|
79
|
+
for (const sourceFile of candidates) {
|
|
80
|
+
const body = await fs.readFile(sourceFile, 'utf8');
|
|
81
|
+
for (const ref of extractImageReferences(body)) {
|
|
82
|
+
refsSeen++;
|
|
83
|
+
if (/^(?:https?:|data:|\/\/|blob:)/i.test(ref)) continue;
|
|
84
|
+
let decoded: string;
|
|
85
|
+
try { decoded = decodeURIComponent(ref.split(/[?#]/)[0] ?? ''); } catch { continue; }
|
|
86
|
+
const image = path.resolve(path.dirname(sourceFile), decoded);
|
|
87
|
+
try {
|
|
88
|
+
const physical = await fs.realpath(image);
|
|
89
|
+
if (!within(workspace, physical)) continue;
|
|
90
|
+
const stat = await fs.stat(physical);
|
|
91
|
+
if (!stat.isFile() || stat.size < 24 || stat.size > 25 * 1024 * 1024) continue;
|
|
92
|
+
const handle = await fs.open(physical, 'r');
|
|
93
|
+
try {
|
|
94
|
+
const buffer = Buffer.alloc(1500);
|
|
95
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
96
|
+
if (magicImage(buffer.subarray(0, bytesRead), path.extname(physical).toLowerCase())) {
|
|
97
|
+
localValid++;
|
|
98
|
+
}
|
|
99
|
+
} finally { await handle.close(); }
|
|
100
|
+
} catch { /* Missing or invalid asset is not completion evidence. */ }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (localValid > 0) return { ok: true, required: true, checkedReferences: refsSeen, validImages: localValid };
|
|
104
|
+
return {
|
|
105
|
+
ok: false,
|
|
106
|
+
required: true,
|
|
107
|
+
reason: `The user requested real pictures downloaded and applied to the website, but ${refsSeen} image reference(s) produced no verified local image file. Source/download attempts failed or the assets were not connected to HTML/CSS. Report the website as partial until a valid downloaded image is integrated.`
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Per-task host circuit breaker for repeated failed downloads through sysRun. */
|
|
2
|
+
export class NetworkHostGuard {
|
|
3
|
+
maxFailures;
|
|
4
|
+
failures = new Map();
|
|
5
|
+
constructor(maxFailures = 2) {
|
|
6
|
+
this.maxFailures = maxFailures;
|
|
7
|
+
this.reset();
|
|
8
|
+
}
|
|
9
|
+
reset() {
|
|
10
|
+
this.failures = new Map();
|
|
11
|
+
}
|
|
12
|
+
host(toolName, args) {
|
|
13
|
+
if (!['sysRun', 'sysRunBg'].includes(toolName))
|
|
14
|
+
return null;
|
|
15
|
+
const command = typeof args?.command === 'string' ? args.command : '';
|
|
16
|
+
// A command with no HTTP URL is outside this guard. It is not a security
|
|
17
|
+
// parser and must never be substituted for the existing sandbox policy.
|
|
18
|
+
const match = command.match(/https?:\/\/[^\s'"<>\\]+/i);
|
|
19
|
+
if (!match)
|
|
20
|
+
return null;
|
|
21
|
+
try {
|
|
22
|
+
const url = new URL(match[0].replace(/[),;]+$/, ''));
|
|
23
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
24
|
+
return null;
|
|
25
|
+
return url.hostname.toLowerCase();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
before(toolName, args) {
|
|
32
|
+
const host = this.host(toolName, args);
|
|
33
|
+
if (!host || (this.failures.get(host) ?? 0) < this.maxFailures) {
|
|
34
|
+
return { allowed: true, host };
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
allowed: false,
|
|
38
|
+
host,
|
|
39
|
+
error: `NETWORK_HOST_UNAVAILABLE: ${host} failed ${this.maxFailures} consecutive requests in this task. Do not call the same host again. Use a genuinely different source, or explain the missing download instead of claiming success.`
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
after(toolName, args, result) {
|
|
43
|
+
const host = this.host(toolName, args);
|
|
44
|
+
if (!host)
|
|
45
|
+
return;
|
|
46
|
+
const success = result?.success === true && !result?.error;
|
|
47
|
+
if (success) {
|
|
48
|
+
this.failures.delete(host);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const message = String(result?.error || result?.output || '');
|
|
52
|
+
if (/timed?\s*out|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|could not resolve|connection refused|ECONNREFUSED|connection reset|network unreachable/i.test(message)) {
|
|
53
|
+
this.failures.set(host, (this.failures.get(host) ?? 0) + 1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export interface NetworkHostGuardDecision {
|
|
2
|
+
allowed: boolean;
|
|
3
|
+
host: string | null;
|
|
4
|
+
error?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface ToolExecutionResult {
|
|
8
|
+
success?: boolean;
|
|
9
|
+
error?: string;
|
|
10
|
+
output?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Per-task host circuit breaker for repeated failed downloads through sysRun. */
|
|
14
|
+
export class NetworkHostGuard {
|
|
15
|
+
private readonly maxFailures: number;
|
|
16
|
+
private failures = new Map<string, number>();
|
|
17
|
+
|
|
18
|
+
constructor(maxFailures = 2) {
|
|
19
|
+
this.maxFailures = maxFailures;
|
|
20
|
+
this.reset();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
reset(): void {
|
|
24
|
+
this.failures = new Map();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
host(toolName: string, args?: { command?: string }): string | null {
|
|
28
|
+
if (!['sysRun', 'sysRunBg'].includes(toolName)) return null;
|
|
29
|
+
const command = typeof args?.command === 'string' ? args.command : '';
|
|
30
|
+
// A command with no HTTP URL is outside this guard. It is not a security
|
|
31
|
+
// parser and must never be substituted for the existing sandbox policy.
|
|
32
|
+
const match = command.match(/https?:\/\/[^\s'"<>\\]+/i);
|
|
33
|
+
if (!match) return null;
|
|
34
|
+
try {
|
|
35
|
+
const url = new URL(match[0].replace(/[),;]+$/, ''));
|
|
36
|
+
if (!['http:', 'https:'].includes(url.protocol)) return null;
|
|
37
|
+
return url.hostname.toLowerCase();
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
before(toolName: string, args?: { command?: string }): NetworkHostGuardDecision {
|
|
44
|
+
const host = this.host(toolName, args);
|
|
45
|
+
if (!host || (this.failures.get(host) ?? 0) < this.maxFailures) {
|
|
46
|
+
return { allowed: true, host };
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
allowed: false,
|
|
50
|
+
host,
|
|
51
|
+
error: `NETWORK_HOST_UNAVAILABLE: ${host} failed ${this.maxFailures} consecutive requests in this task. Do not call the same host again. Use a genuinely different source, or explain the missing download instead of claiming success.`
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
after(toolName: string, args?: { command?: string }, result?: ToolExecutionResult): void {
|
|
56
|
+
const host = this.host(toolName, args);
|
|
57
|
+
if (!host) return;
|
|
58
|
+
const success = result?.success === true && !result?.error;
|
|
59
|
+
if (success) {
|
|
60
|
+
this.failures.delete(host);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const message = String(result?.error || result?.output || '');
|
|
64
|
+
if (/timed?\s*out|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|could not resolve|connection refused|ECONNREFUSED|connection reset|network unreachable/i.test(message)) {
|
|
65
|
+
this.failures.set(host, (this.failures.get(host) ?? 0) + 1);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** A rendered DOM is not proof that a user-requested 3D scene was visually inspected. */
|
|
2
|
+
export function inspect3DVisualEvidence(prompt, outcomes = []) {
|
|
3
|
+
const text = String(prompt || '');
|
|
4
|
+
const needs3DVisual = /\b(?:build|create|make|design|render|implement)\b[^\n]{0,150}\b(?:3[ -]?d|three\.?js|webgl)\b/i.test(text);
|
|
5
|
+
if (!needs3DVisual)
|
|
6
|
+
return { ok: true, required: false };
|
|
7
|
+
// The host observer sets observedImage only when image bytes actually reached
|
|
8
|
+
// a vision-capable provider. A file named screenshot.png or a browser
|
|
9
|
+
// snapshot does not satisfy this condition.
|
|
10
|
+
const latestMutation = outcomes.findLastIndex(item => item?.success === true &&
|
|
11
|
+
/^(fs_write|fs_edit|MultiEdit|write_file|edit_file)$/i.test(String(item.tool || '')));
|
|
12
|
+
const afterMutation = latestMutation < 0 ? outcomes : outcomes.slice(latestMutation + 1);
|
|
13
|
+
if (afterMutation.some(item => item?.success === true && item?.observedImage === true)) {
|
|
14
|
+
return { ok: true, required: true };
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
ok: false,
|
|
18
|
+
required: true,
|
|
19
|
+
reason: 'The user requested a Three.js/WebGL 3D deliverable, but no rendered image was actually inspected by a vision-capable model after the last change. A browser preview or DOM snapshot alone does not verify the 3D result. Report the scene as visually unverified, or capture and inspect an image before claiming completion.'
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface VisualEvidenceResult {
|
|
2
|
+
readonly ok: boolean;
|
|
3
|
+
readonly required: boolean;
|
|
4
|
+
readonly reason?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface ObservedToolOutcome {
|
|
8
|
+
tool?: string;
|
|
9
|
+
success?: boolean;
|
|
10
|
+
observedImage?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A rendered DOM is not proof that a user-requested 3D scene was visually inspected. */
|
|
14
|
+
export function inspect3DVisualEvidence(
|
|
15
|
+
prompt: string,
|
|
16
|
+
outcomes: readonly ObservedToolOutcome[] = []
|
|
17
|
+
): VisualEvidenceResult {
|
|
18
|
+
const text = String(prompt || '');
|
|
19
|
+
const needs3DVisual = /\b(?:build|create|make|design|render|implement)\b[^\n]{0,150}\b(?:3[ -]?d|three\.?js|webgl)\b/i.test(text);
|
|
20
|
+
if (!needs3DVisual) return { ok: true, required: false };
|
|
21
|
+
// The host observer sets observedImage only when image bytes actually reached
|
|
22
|
+
// a vision-capable provider. A file named screenshot.png or a browser
|
|
23
|
+
// snapshot does not satisfy this condition.
|
|
24
|
+
const latestMutation = outcomes.findLastIndex(item => item?.success === true &&
|
|
25
|
+
/^(fs_write|fs_edit|MultiEdit|write_file|edit_file)$/i.test(String(item.tool || '')));
|
|
26
|
+
const afterMutation = latestMutation < 0 ? outcomes : outcomes.slice(latestMutation + 1);
|
|
27
|
+
if (afterMutation.some(item => item?.success === true && item?.observedImage === true)) {
|
|
28
|
+
return { ok: true, required: true };
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
ok: false,
|
|
32
|
+
required: true,
|
|
33
|
+
reason: 'The user requested a Three.js/WebGL 3D deliverable, but no rendered image was actually inspected by a vision-capable model after the last change. A browser preview or DOM snapshot alone does not verify the 3D result. Report the scene as visually unverified, or capture and inspect an image before claiming completion.'
|
|
34
|
+
};
|
|
35
|
+
}
|
package/src/tools/fsWrite.js
CHANGED
|
@@ -1,10 +1,69 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
function expandHome(value) {
|
|
6
|
+
return value === '~' ? os.homedir()
|
|
7
|
+
: value.startsWith('~/') || value.startsWith('~\\')
|
|
8
|
+
? path.join(os.homedir(), value.slice(2))
|
|
9
|
+
: value;
|
|
10
|
+
}
|
|
11
|
+
function inside(root, target) {
|
|
12
|
+
const relative = path.relative(root, target);
|
|
13
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`)
|
|
14
|
+
&& !path.isAbsolute(relative));
|
|
15
|
+
}
|
|
16
|
+
async function physicalTarget(target) {
|
|
17
|
+
// Resolves symlinks in the longest existing ancestor, including a symlinked
|
|
18
|
+
// parent of a new file. It is not a substitute for OS-level isolation.
|
|
19
|
+
let current = target;
|
|
20
|
+
const missing = [];
|
|
21
|
+
while (true) {
|
|
22
|
+
try {
|
|
23
|
+
const resolved = await fs.realpath(current);
|
|
24
|
+
return path.join(resolved, ...missing.reverse());
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error?.code !== 'ENOENT')
|
|
28
|
+
throw error;
|
|
29
|
+
const parent = path.dirname(current);
|
|
30
|
+
if (parent === current)
|
|
31
|
+
throw new Error('Could not resolve target ancestry');
|
|
32
|
+
missing.push(path.basename(current));
|
|
33
|
+
current = parent;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function checkScope(target, context) {
|
|
38
|
+
if (!context || context.grantAllAccess === true)
|
|
39
|
+
return;
|
|
40
|
+
const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
|
|
41
|
+
? context.workspacePaths
|
|
42
|
+
: [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter((value) => typeof value === 'string' && value.length > 0);
|
|
43
|
+
if (roots.length === 0)
|
|
44
|
+
return;
|
|
45
|
+
const physical = await physicalTarget(target);
|
|
46
|
+
for (const root of roots) {
|
|
47
|
+
try {
|
|
48
|
+
const resolvedRoot = await fs.realpath(path.resolve(expandHome(root)));
|
|
49
|
+
if (inside(resolvedRoot, physical))
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
catch { /* A non-existent authorized root is not permission to escape. */ }
|
|
53
|
+
}
|
|
54
|
+
throw new Error(`Target resolves outside the selected workspace: ${target}`);
|
|
55
|
+
}
|
|
56
|
+
function writeError(error, target) {
|
|
57
|
+
const code = error?.code;
|
|
58
|
+
if (code === 'EISDIR' || code === 'ENOTEMPTY') {
|
|
59
|
+
return `Cannot write file: "${target}" is an existing directory. Supply a filename inside it, such as ${path.join(target, 'index.html')}.`;
|
|
60
|
+
}
|
|
61
|
+
return `Atomic file write failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
62
|
+
}
|
|
4
63
|
export const fsWrite = {
|
|
5
64
|
schema: {
|
|
6
65
|
name: 'fs.write',
|
|
7
|
-
description: '
|
|
66
|
+
description: 'Write a complete UTF-8 file using atomic rename. Path must be a file, not a directory.',
|
|
8
67
|
parameters: {
|
|
9
68
|
type: 'object',
|
|
10
69
|
properties: {
|
|
@@ -15,36 +74,86 @@ export const fsWrite = {
|
|
|
15
74
|
required: ['path', 'content']
|
|
16
75
|
}
|
|
17
76
|
},
|
|
18
|
-
async execute(args) {
|
|
77
|
+
async execute(args, context) {
|
|
78
|
+
if (!args || typeof args.path !== 'string' || !args.path.trim()) {
|
|
79
|
+
return { success: false, error: 'fs_write requires a nonempty path pointing to a FILE.' };
|
|
80
|
+
}
|
|
81
|
+
if (typeof args.content !== 'string') {
|
|
82
|
+
return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
|
|
83
|
+
}
|
|
84
|
+
if (args.path.endsWith('/') || args.path.endsWith('\\')) {
|
|
85
|
+
return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
|
|
86
|
+
}
|
|
87
|
+
const target = path.resolve(expandHome(args.path.trim()));
|
|
88
|
+
let temporary = '';
|
|
19
89
|
try {
|
|
20
|
-
|
|
21
|
-
|
|
90
|
+
await checkScope(target, context);
|
|
91
|
+
let originalMode;
|
|
22
92
|
try {
|
|
23
|
-
const stat = await fs.
|
|
93
|
+
const stat = await fs.lstat(target);
|
|
24
94
|
if (stat.isDirectory()) {
|
|
25
|
-
return {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
};
|
|
95
|
+
return { success: false, error: `Cannot write file: "${target}" is an existing directory. Specify a target file path inside this directory (e.g. "${path.join(target, 'index.html')}").` };
|
|
96
|
+
}
|
|
97
|
+
if (stat.isSymbolicLink()) {
|
|
98
|
+
return { success: false, error: `Refusing to replace symbolic link ${target}; use a regular file in the selected workspace.` };
|
|
29
99
|
}
|
|
100
|
+
if (!stat.isFile()) {
|
|
101
|
+
return { success: false, error: `Target ${target} is not a regular file.` };
|
|
102
|
+
}
|
|
103
|
+
originalMode = stat.mode & 0o777;
|
|
30
104
|
}
|
|
31
|
-
catch {
|
|
32
|
-
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error?.code !== 'ENOENT')
|
|
107
|
+
throw error;
|
|
33
108
|
}
|
|
34
109
|
if (args.createDirectories !== false) {
|
|
35
110
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
36
111
|
}
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
await fs.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
112
|
+
// Re-check after creating parents: an existing parent might be a symlink.
|
|
113
|
+
await checkScope(target, context);
|
|
114
|
+
temporary = path.join(path.dirname(target), `.${path.basename(target)}.causyne-${randomUUID()}.tmp`);
|
|
115
|
+
const file = await fs.open(temporary, 'wx', originalMode ?? 0o600);
|
|
116
|
+
try {
|
|
117
|
+
await file.writeFile(args.content, { encoding: 'utf8' });
|
|
118
|
+
await file.sync();
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
await file.close();
|
|
122
|
+
}
|
|
123
|
+
// Never reinterpret a directory as a file if the destination changed.
|
|
124
|
+
const destinationStat = await fs.lstat(target).catch((error) => {
|
|
125
|
+
if (error.code === 'ENOENT')
|
|
126
|
+
return null;
|
|
127
|
+
throw error;
|
|
128
|
+
});
|
|
129
|
+
if (destinationStat && !destinationStat.isFile()) {
|
|
130
|
+
throw new Error(`Destination is no longer a regular file: ${target}`);
|
|
131
|
+
}
|
|
132
|
+
await checkScope(target, context);
|
|
133
|
+
await fs.rename(temporary, target);
|
|
134
|
+
temporary = '';
|
|
135
|
+
// Flushing the parent directory is best effort: some platforms disallow it.
|
|
136
|
+
try {
|
|
137
|
+
const directory = await fs.open(path.dirname(target), 'r');
|
|
138
|
+
try {
|
|
139
|
+
await directory.sync();
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await directory.close();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
catch { /* Do not claim crash-durable guarantees on unsupported FS. */ }
|
|
146
|
+
return {
|
|
147
|
+
success: true,
|
|
148
|
+
output: `Wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${target}`
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
return { success: false, error: writeError(error, target) };
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
if (temporary)
|
|
156
|
+
await fs.unlink(temporary).catch(() => { });
|
|
48
157
|
}
|
|
49
158
|
}
|
|
50
159
|
};
|