@causyne/agent 1.20.76 → 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 +155 -115
- package/src/agentLoop.ts +143 -109
- package/src/cliMode.js +19 -2
- package/src/entrypoint.js +9 -0
- package/src/licensing/entitlements.d.ts +14 -0
- package/src/licensing/entitlements.js +264 -0
- package/src/licensing/policy.js +9 -0
- 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 +156 -38
- package/src/tools/fsWrite.ts +169 -0
- package/src/tools/toolSelfRepair.js +66 -5
- package/src/tools/toolSelfRepair.ts +63 -5
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { causyneHome } from '../utils/paths.js';
|
|
5
|
+
import { LICENSE_API_BASE, LICENSE_ENFORCEMENT_ENABLED, LICENSE_PLAN_KEYS } from './policy.js';
|
|
6
|
+
|
|
7
|
+
const TOKEN_FILE = 'installation-identity.json';
|
|
8
|
+
const USER_AGENT = 'Causyne-Agent/entitlements-v1';
|
|
9
|
+
const AUTH_TIMEOUT_MS = 10000;
|
|
10
|
+
|
|
11
|
+
export class EntitlementAccessError extends Error {
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'EntitlementAccessError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function base64url(input) { return Buffer.from(input).toString('base64url'); }
|
|
20
|
+
function digest(input) { return base64url(crypto.createHash('sha256').update(input).digest()); }
|
|
21
|
+
function sign(text, privateKey) { return base64url(crypto.sign(null, Buffer.from(text), privateKey)); }
|
|
22
|
+
function requestText(method, pathname, timestamp, nonce, hash) {
|
|
23
|
+
return ['CAUSYNE_API_V1', method.toUpperCase(), pathname, timestamp, nonce, hash].join('\n');
|
|
24
|
+
}
|
|
25
|
+
function registrationText(key, nonce) { return ['CAUSYNE_REGISTER_V1', key, nonce].join('\n'); }
|
|
26
|
+
|
|
27
|
+
function requireIdentityFields(value) {
|
|
28
|
+
if (!value || typeof value !== 'object' ||
|
|
29
|
+
typeof value.privateKeyPem !== 'string' || typeof value.publicKey !== 'string') {
|
|
30
|
+
throw new EntitlementAccessError('IDENTITY_CORRUPT',
|
|
31
|
+
'The local Causyne installation identity is damaged. Contact support; do not delete it while recovering a paid license.');
|
|
32
|
+
}
|
|
33
|
+
const key = crypto.createPrivateKey(value.privateKeyPem);
|
|
34
|
+
const derived = base64url(crypto.createPublicKey(key).export({ type: 'spki', format: 'der' }));
|
|
35
|
+
if (derived !== value.publicKey) throw new EntitlementAccessError('IDENTITY_CORRUPT', 'Installation public/private keys disagree.');
|
|
36
|
+
if (value.installationId && !/^[\da-f-]{36}$/i.test(value.installationId)) {
|
|
37
|
+
throw new EntitlementAccessError('IDENTITY_CORRUPT', 'Installation ID is invalid.');
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** No hardware serials, MAC addresses, device fingerprint or email required. */
|
|
43
|
+
export function loadInstallationIdentity(stateRoot = causyneHome()) {
|
|
44
|
+
fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
|
|
45
|
+
const file = path.join(stateRoot, TOKEN_FILE);
|
|
46
|
+
try {
|
|
47
|
+
const value = requireIdentityFields(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
48
|
+
return { ...value, file };
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (error.code !== 'ENOENT') throw error;
|
|
51
|
+
}
|
|
52
|
+
const pair = crypto.generateKeyPairSync('ed25519');
|
|
53
|
+
const privateKeyPem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
|
54
|
+
const publicKey = base64url(pair.publicKey.export({ type: 'spki', format: 'der' }));
|
|
55
|
+
const identity = { version: 1, publicKey, privateKeyPem, installationId: null };
|
|
56
|
+
// Exclusive create prevents a second running CLI from replacing this identity.
|
|
57
|
+
let fd;
|
|
58
|
+
try {
|
|
59
|
+
fd = fs.openSync(file, 'wx', 0o600);
|
|
60
|
+
fs.writeFileSync(fd, JSON.stringify(identity), 'utf8');
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error.code === 'EEXIST') return loadInstallationIdentity(stateRoot);
|
|
63
|
+
throw error;
|
|
64
|
+
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
65
|
+
return { ...identity, file };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function saveInstallationIdentity(identity) {
|
|
69
|
+
const value = { version: 1, privateKeyPem: identity.privateKeyPem,
|
|
70
|
+
publicKey: identity.publicKey, installationId: identity.installationId };
|
|
71
|
+
const file = identity.file;
|
|
72
|
+
const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
73
|
+
try {
|
|
74
|
+
fs.writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });
|
|
75
|
+
fs.renameSync(temp, file);
|
|
76
|
+
try { fs.chmodSync(file, 0o600); } catch { /* Windows ACLs differ */ }
|
|
77
|
+
} finally { try { fs.unlinkSync(temp); } catch { /* rename removed it */ } }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export class EntitlementClient {
|
|
81
|
+
constructor({ apiBase = LICENSE_API_BASE, stateRoot = causyneHome(), fetchFn = globalThis.fetch } = {}) {
|
|
82
|
+
const url = new URL(apiBase);
|
|
83
|
+
if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') {
|
|
84
|
+
throw new Error('Entitlement service requires HTTPS.');
|
|
85
|
+
}
|
|
86
|
+
this.apiBase = url.origin;
|
|
87
|
+
this.stateRoot = stateRoot;
|
|
88
|
+
this.fetchFn = fetchFn;
|
|
89
|
+
this.identity = null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async call(pathname, body, { register = false } = {}) {
|
|
93
|
+
const identity = this.identity ||= loadInstallationIdentity(this.stateRoot);
|
|
94
|
+
const method = body === undefined ? 'GET' : 'POST';
|
|
95
|
+
const raw = body === undefined ? '' : JSON.stringify(body);
|
|
96
|
+
const headers = { 'user-agent': USER_AGENT, 'accept': 'application/json',
|
|
97
|
+
'content-type': 'application/json' };
|
|
98
|
+
if (!register) {
|
|
99
|
+
if (!identity.installationId) await this.register();
|
|
100
|
+
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
101
|
+
const nonce = crypto.randomBytes(24).toString('base64url');
|
|
102
|
+
headers['x-causyne-installation'] = identity.installationId;
|
|
103
|
+
headers['x-causyne-timestamp'] = timestamp;
|
|
104
|
+
headers['x-causyne-nonce'] = nonce;
|
|
105
|
+
headers['x-causyne-signature'] = sign(requestText(method, pathname, timestamp, nonce, digest(raw)), identity.privateKeyPem);
|
|
106
|
+
}
|
|
107
|
+
const controller = new AbortController();
|
|
108
|
+
const timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
|
109
|
+
timeout.unref?.();
|
|
110
|
+
try {
|
|
111
|
+
const response = await this.fetchFn(`${this.apiBase}${pathname}`, {
|
|
112
|
+
method, headers, ...(body !== undefined ? { body: raw } : {}), signal: controller.signal
|
|
113
|
+
});
|
|
114
|
+
const parsed = await response.json().catch(() => ({}));
|
|
115
|
+
if (!response.ok) {
|
|
116
|
+
throw new EntitlementAccessError(parsed?.error || 'SERVICE_ERROR',
|
|
117
|
+
typeof parsed?.message === 'string' ? parsed.message : `Entitlement service returned HTTP ${response.status}.`);
|
|
118
|
+
}
|
|
119
|
+
return parsed;
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error instanceof EntitlementAccessError) throw error;
|
|
122
|
+
throw new EntitlementAccessError('NETWORK_UNAVAILABLE',
|
|
123
|
+
'Cannot reach the Causyne licensing service. The current task is preserved; retry when connected.');
|
|
124
|
+
} finally { clearTimeout(timeout); }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async register() {
|
|
128
|
+
const identity = this.identity ||= loadInstallationIdentity(this.stateRoot);
|
|
129
|
+
if (identity.installationId) return identity.installationId;
|
|
130
|
+
const nonce = crypto.randomBytes(24).toString('base64url');
|
|
131
|
+
const response = await this.call('/v1/installations', {
|
|
132
|
+
publicKey: identity.publicKey, nonce,
|
|
133
|
+
proof: sign(registrationText(identity.publicKey, nonce), identity.privateKeyPem)
|
|
134
|
+
}, { register: true });
|
|
135
|
+
if (!/^[\da-f-]{36}$/i.test(response.installationId || '')) {
|
|
136
|
+
throw new EntitlementAccessError('REGISTRATION_ERROR', 'Licensing service returned an invalid installation ID.');
|
|
137
|
+
}
|
|
138
|
+
identity.installationId = response.installationId;
|
|
139
|
+
saveInstallationIdentity(identity);
|
|
140
|
+
return identity.installationId;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
status() { return this.call('/v1/status'); }
|
|
144
|
+
lease(requestId, sessionId) { return this.call('/v1/leases', { requestId, sessionId }); }
|
|
145
|
+
async checkout(plan) {
|
|
146
|
+
if (!LICENSE_PLAN_KEYS.includes(plan)) throw new EntitlementAccessError('INVALID_PLAN', 'Unknown Causyne plan.');
|
|
147
|
+
const result = await this.call('/v1/checkout', { plan });
|
|
148
|
+
const url = new URL(result.url);
|
|
149
|
+
if (url.protocol !== 'https:' || !/(^|\.)lemonsqueezy\.com$/i.test(url.hostname)) {
|
|
150
|
+
throw new EntitlementAccessError('BAD_CHECKOUT_URL', 'Invalid checkout destination returned by server.');
|
|
151
|
+
}
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Process-local gate. All AgentLoop instances in this process share one session. */
|
|
157
|
+
export class EntitlementGate {
|
|
158
|
+
constructor({ enabled = LICENSE_ENFORCEMENT_ENABLED, client = new EntitlementClient() } = {}) {
|
|
159
|
+
this.enabled = enabled;
|
|
160
|
+
this.client = client;
|
|
161
|
+
this.sessionId = crypto.randomUUID();
|
|
162
|
+
this.activeRuns = 0;
|
|
163
|
+
this.pausedRuns = 0;
|
|
164
|
+
this.leaseUntil = 0;
|
|
165
|
+
this.leasePlan = null;
|
|
166
|
+
this.blockedError = null;
|
|
167
|
+
this.timer = null;
|
|
168
|
+
this.pending = null;
|
|
169
|
+
this.listeners = new Set();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async ensureLease() {
|
|
173
|
+
if (!this.enabled) return { plan: 'development-disabled' };
|
|
174
|
+
if (this.blockedError) throw this.blockedError;
|
|
175
|
+
if (Date.now() + 500 < this.leaseUntil) return { plan: this.leasePlan };
|
|
176
|
+
if (this.pending) return this.pending;
|
|
177
|
+
this.pending = (async () => {
|
|
178
|
+
const requestId = crypto.randomUUID();
|
|
179
|
+
const result = await this.client.lease(requestId, this.sessionId);
|
|
180
|
+
const expiration = Date.parse(result.expiresAt || '');
|
|
181
|
+
if (!Number.isFinite(expiration) || expiration <= Date.now()) {
|
|
182
|
+
throw new EntitlementAccessError('INVALID_LEASE', 'Licensing service returned an expired or invalid lease.');
|
|
183
|
+
}
|
|
184
|
+
this.leaseUntil = expiration;
|
|
185
|
+
this.leasePlan = result.plan;
|
|
186
|
+
this.blockedError = null;
|
|
187
|
+
return result;
|
|
188
|
+
})().finally(() => { this.pending = null; });
|
|
189
|
+
return this.pending;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async begin(onBlocked = () => {}) {
|
|
193
|
+
if (!this.enabled) return;
|
|
194
|
+
await this.ensureLease();
|
|
195
|
+
this.activeRuns++;
|
|
196
|
+
this.listeners.add(onBlocked);
|
|
197
|
+
if (this.activeRuns === 1) {
|
|
198
|
+
// In-process only while tasks run. No daemon or remotely accessible port.
|
|
199
|
+
this.timer = setInterval(async () => {
|
|
200
|
+
if (this.pausedRuns >= this.activeRuns || Date.now() < this.leaseUntil) return;
|
|
201
|
+
try { await this.ensureLease(); }
|
|
202
|
+
catch (error) {
|
|
203
|
+
this.blockedError = error;
|
|
204
|
+
for (const listener of this.listeners) {
|
|
205
|
+
try { listener(error); } catch { /* do not crash current tool */ }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}, 1000);
|
|
209
|
+
this.timer.unref?.();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
pause() { if (this.enabled) this.pausedRuns++; }
|
|
214
|
+
resume() { if (this.enabled) this.pausedRuns = Math.max(0, this.pausedRuns - 1); }
|
|
215
|
+
|
|
216
|
+
async beforeStep() {
|
|
217
|
+
if (!this.enabled) return;
|
|
218
|
+
await this.ensureLease();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
end(onBlocked) {
|
|
222
|
+
if (!this.enabled) return;
|
|
223
|
+
this.listeners.delete(onBlocked);
|
|
224
|
+
this.activeRuns = Math.max(0, this.activeRuns - 1);
|
|
225
|
+
this.pausedRuns = Math.min(this.pausedRuns, this.activeRuns);
|
|
226
|
+
if (this.activeRuns === 0 && this.timer) {
|
|
227
|
+
clearInterval(this.timer);
|
|
228
|
+
this.timer = null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let processGate;
|
|
234
|
+
export function getProcessEntitlementGate() {
|
|
235
|
+
return processGate ||= new EntitlementGate();
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export async function runLicenseCommand(action = 'status', plan = '') {
|
|
239
|
+
const client = new EntitlementClient();
|
|
240
|
+
if (action === 'plans') {
|
|
241
|
+
console.log('Causyne Go plans: monthly, annual, two_month_pass, two_year_pass');
|
|
242
|
+
console.log('Paid access does not include paid model inference.');
|
|
243
|
+
console.log('One-time passes are non-recurring; pricing is shown at merchant checkout.');
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (action === 'status') {
|
|
247
|
+
const data = await client.status();
|
|
248
|
+
console.log(`Causyne software entitlement: ${data.entitlement}`);
|
|
249
|
+
if (data.paidUntil) console.log(`Paid through: ${data.paidUntil}`);
|
|
250
|
+
else {
|
|
251
|
+
console.log(`Free allowance remaining: ${Math.floor(data.remainingSeconds / 60)} of ${Math.floor(data.dailySeconds / 60)} minutes`);
|
|
252
|
+
console.log(`UTC reset: ${data.resetsAt}`);
|
|
253
|
+
}
|
|
254
|
+
console.log('Model-provider inference has separate limits and costs.');
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (action === 'buy') {
|
|
258
|
+
const result = await client.checkout(plan);
|
|
259
|
+
console.log(`Checkout: ${result.url}`);
|
|
260
|
+
console.log('Your entitlement activates only after the provider confirms payment.');
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
throw new EntitlementAccessError('UNKNOWN_COMMAND', 'Use: causyne license status | plans | buy <plan>.');
|
|
264
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Release-switch. Keep FALSE in development until the licensing terms, backend,
|
|
2
|
+
// payment provider, recovery process, and staged release have been approved.
|
|
3
|
+
// Changing this client flag is not a DRM boundary: the authoritative quota is
|
|
4
|
+
// enforced by the private service when the client connects.
|
|
5
|
+
export const LICENSE_ENFORCEMENT_ENABLED = false;
|
|
6
|
+
export const LICENSE_API_BASE = 'https://license.causyne.com';
|
|
7
|
+
export const LICENSE_PLAN_KEYS = Object.freeze([
|
|
8
|
+
'monthly', 'annual', 'two_month_pass', 'two_year_pass'
|
|
9
|
+
]);
|
|
@@ -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
|
+
}
|