@causyne/agent 1.11.0 → 1.12.0
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/docs/THIRD_PARTY_NOTICES.md +12 -0
- package/package.json +1 -1
- package/src/acp/protocol.js +1 -0
- package/src/acp/protocol.ts +22 -0
- package/src/acp/server.js +158 -21
- package/src/acp/server.ts +167 -21
- package/src/agentLoop.d.ts +22 -1
- package/src/agentLoop.js +15 -5
- package/src/approvalGrants.js +33 -0
- package/src/approvalGrants.ts +50 -0
- package/src/decisionPolicy.js +2 -0
- package/src/decisionPolicy.ts +1 -0
- package/src/engines/cad.js +113 -0
- package/src/engines/cad.ts +128 -0
- package/src/engines/film.js +108 -0
- package/src/engines/film.ts +104 -0
- package/src/engines/installer.js +226 -0
- package/src/engines/installer.ts +248 -0
- package/src/engines/photo.js +126 -0
- package/src/engines/photo.ts +137 -0
- package/src/engines/registry.js +186 -0
- package/src/engines/registry.ts +185 -0
- package/src/engines/sound.js +117 -0
- package/src/engines/sound.ts +130 -0
- package/src/engines/types.js +1 -0
- package/src/engines/types.ts +73 -0
- package/src/memoryManager.js +9 -3
- package/src/promptMentions.js +1 -1
- package/src/promptMentions.ts +1 -1
- package/src/sandbox.js +8 -0
- package/src/sessionJournal.js +12 -2
- package/src/sessionJournal.ts +12 -2
- package/src/toolPacks.js +15 -7
- package/src/tools/generateMediaViaApi.js +1 -1
- package/src/tools/nativeEngine.js +464 -0
- package/src/tools/nativeEngine.ts +433 -0
- package/src/tools/openSourceToolProvisioner.js +510 -0
- package/src/tools/openSourceToolProvisioner.ts +590 -0
- package/src/tools/registry.js +4 -1
- package/src/tui/completion.js +2 -2
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { engineInstallDir } from './registry.js';
|
|
6
|
+
const MANIFEST_LIMIT = 1024 * 1024;
|
|
7
|
+
const ASSET_LIMIT = 512 * 1024 * 1024;
|
|
8
|
+
const DEFAULT_MANIFEST = 'https://github.com/ikbal-causyne/causyne-engines/releases/latest/download/engines.json';
|
|
9
|
+
export function defaultEngineManifestUrl() {
|
|
10
|
+
const override = process.env['CAUSYNE_ENGINE_MANIFEST'];
|
|
11
|
+
return override && override.trim() ? override.trim() : DEFAULT_MANIFEST;
|
|
12
|
+
}
|
|
13
|
+
function platformKey() {
|
|
14
|
+
return `${process.platform}-${process.arch}`;
|
|
15
|
+
}
|
|
16
|
+
function validVersion(value) {
|
|
17
|
+
return /^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/.test(value);
|
|
18
|
+
}
|
|
19
|
+
function validPlatform(value) {
|
|
20
|
+
return /^[a-z0-9]+-[a-z0-9]+$/.test(value);
|
|
21
|
+
}
|
|
22
|
+
function timeoutSignal(timeoutMs, signal) {
|
|
23
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
24
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
25
|
+
}
|
|
26
|
+
async function readLocation(location, limit, signal) {
|
|
27
|
+
if (/^http:/i.test(location))
|
|
28
|
+
throw new Error('Engine manifest must use HTTPS or a local file');
|
|
29
|
+
if (/^https:/i.test(location)) {
|
|
30
|
+
const response = await fetch(location, {
|
|
31
|
+
redirect: 'follow',
|
|
32
|
+
headers: { accept: 'application/json', 'user-agent': 'Causyne-Agent' },
|
|
33
|
+
signal: timeoutSignal(20_000, signal)
|
|
34
|
+
});
|
|
35
|
+
if (!response.ok)
|
|
36
|
+
throw new Error(`Manifest request failed with HTTP ${response.status}`);
|
|
37
|
+
if (new URL(response.url || location).protocol !== 'https:')
|
|
38
|
+
throw new Error('Engine manifest redirect left HTTPS');
|
|
39
|
+
const text = await response.text();
|
|
40
|
+
if (Buffer.byteLength(text) > limit)
|
|
41
|
+
throw new Error('Manifest is larger than 1 MB');
|
|
42
|
+
return { text, base: response.url || location };
|
|
43
|
+
}
|
|
44
|
+
const file = location.startsWith('file:') ? fileURLToPath(location) : path.resolve(location);
|
|
45
|
+
const stat = await fs.stat(file);
|
|
46
|
+
if (!stat.isFile() || stat.size > limit)
|
|
47
|
+
throw new Error('Manifest is missing or larger than 1 MB');
|
|
48
|
+
const text = await fs.readFile(file, 'utf8');
|
|
49
|
+
return { text, base: location.startsWith('file:') ? location : pathToFileURL(file).href };
|
|
50
|
+
}
|
|
51
|
+
async function readManifest(location, signal) {
|
|
52
|
+
const { text, base } = await readLocation(location, MANIFEST_LIMIT, signal);
|
|
53
|
+
let value;
|
|
54
|
+
try {
|
|
55
|
+
value = JSON.parse(text);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new Error('Engine manifest is not valid JSON');
|
|
59
|
+
}
|
|
60
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
61
|
+
throw new Error('Engine manifest must be an object');
|
|
62
|
+
const record = value;
|
|
63
|
+
if (record.schema !== 1)
|
|
64
|
+
throw new Error('Unsupported engine manifest schema');
|
|
65
|
+
if (!record.engines || typeof record.engines !== 'object' || Array.isArray(record.engines)) {
|
|
66
|
+
throw new Error('Engine manifest has no engines map');
|
|
67
|
+
}
|
|
68
|
+
return { manifest: record, base };
|
|
69
|
+
}
|
|
70
|
+
function releaseFor(manifest, adapter) {
|
|
71
|
+
const release = manifest.engines[adapter.id];
|
|
72
|
+
if (!release || typeof release !== 'object')
|
|
73
|
+
throw new Error(`No release for engine ${adapter.id}`);
|
|
74
|
+
if (typeof release.version !== 'string' || !validVersion(release.version))
|
|
75
|
+
throw new Error('Invalid engine release version');
|
|
76
|
+
if (release.license !== undefined && (typeof release.license !== 'string' || release.license.length > 200)) {
|
|
77
|
+
throw new Error('Invalid engine release license');
|
|
78
|
+
}
|
|
79
|
+
if (!release.platforms || typeof release.platforms !== 'object' || Array.isArray(release.platforms)) {
|
|
80
|
+
throw new Error('Engine release has no platform map');
|
|
81
|
+
}
|
|
82
|
+
return release;
|
|
83
|
+
}
|
|
84
|
+
function assetFor(release, base) {
|
|
85
|
+
const platform = platformKey();
|
|
86
|
+
if (!validPlatform(platform))
|
|
87
|
+
throw new Error(`Unsupported platform: ${platform}`);
|
|
88
|
+
const asset = release.platforms[platform];
|
|
89
|
+
if (!asset || typeof asset !== 'object')
|
|
90
|
+
throw new Error(`No release asset for ${platform}`);
|
|
91
|
+
if (typeof asset.url !== 'string' || !asset.url.trim())
|
|
92
|
+
throw new Error('Engine asset has no URL');
|
|
93
|
+
if (typeof asset.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(asset.sha256))
|
|
94
|
+
throw new Error('Engine asset has no valid SHA-256');
|
|
95
|
+
if (asset.size !== undefined && (!Number.isInteger(asset.size) || asset.size < 1 || asset.size > ASSET_LIMIT)) {
|
|
96
|
+
throw new Error('Engine asset size is invalid');
|
|
97
|
+
}
|
|
98
|
+
const url = new URL(asset.url, base).href;
|
|
99
|
+
const protocol = new URL(url).protocol;
|
|
100
|
+
const localManifest = base.startsWith('file:');
|
|
101
|
+
if (protocol !== 'https:' && !(localManifest && protocol === 'file:')) {
|
|
102
|
+
throw new Error('Engine asset must use HTTPS, or a local file URL from a local manifest');
|
|
103
|
+
}
|
|
104
|
+
return { platform, asset, url };
|
|
105
|
+
}
|
|
106
|
+
async function assetBytes(url, signal) {
|
|
107
|
+
if (url.startsWith('file:')) {
|
|
108
|
+
const file = fileURLToPath(url);
|
|
109
|
+
const stat = await fs.stat(file);
|
|
110
|
+
if (!stat.isFile() || stat.size > ASSET_LIMIT)
|
|
111
|
+
throw new Error('Engine asset is missing or too large');
|
|
112
|
+
return await fs.readFile(file);
|
|
113
|
+
}
|
|
114
|
+
const response = await fetch(url, {
|
|
115
|
+
redirect: 'follow',
|
|
116
|
+
headers: { accept: 'application/octet-stream', 'user-agent': 'Causyne-Agent' },
|
|
117
|
+
signal: timeoutSignal(600_000, signal)
|
|
118
|
+
});
|
|
119
|
+
if (!response.ok)
|
|
120
|
+
throw new Error(`Engine download failed with HTTP ${response.status}`);
|
|
121
|
+
if (new URL(response.url || url).protocol !== 'https:')
|
|
122
|
+
throw new Error('Engine download redirect left HTTPS');
|
|
123
|
+
const declared = Number(response.headers.get('content-length') || 0);
|
|
124
|
+
if (declared > ASSET_LIMIT)
|
|
125
|
+
throw new Error('Engine asset is larger than 512 MB');
|
|
126
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
127
|
+
if (bytes.length > ASSET_LIMIT)
|
|
128
|
+
throw new Error('Engine asset is larger than 512 MB');
|
|
129
|
+
return bytes;
|
|
130
|
+
}
|
|
131
|
+
async function currentVersion(adapter) {
|
|
132
|
+
try {
|
|
133
|
+
const value = JSON.parse(await fs.readFile(path.join(engineInstallDir(adapter), 'current.json'), 'utf8'));
|
|
134
|
+
if (typeof value.version !== 'string' || !validVersion(value.version))
|
|
135
|
+
return null;
|
|
136
|
+
if (typeof value.platform !== 'string' || !validPlatform(value.platform))
|
|
137
|
+
return null;
|
|
138
|
+
return { version: value.version, platform: value.platform };
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export async function installNativeEngine(adapter, options) {
|
|
145
|
+
const manifestUrl = defaultEngineManifestUrl();
|
|
146
|
+
const base = { success: false, engine: adapter.id, manifestUrl };
|
|
147
|
+
try {
|
|
148
|
+
const { manifest, base: location } = await readManifest(manifestUrl, options.signal);
|
|
149
|
+
const release = releaseFor(manifest, adapter);
|
|
150
|
+
const { platform, asset, url } = assetFor(release, location);
|
|
151
|
+
const root = engineInstallDir(adapter);
|
|
152
|
+
const suffix = process.platform === 'win32' ? '.exe' : '';
|
|
153
|
+
const target = path.join(root, 'versions', release.version, platform, `${adapter.binaryName}${suffix}`);
|
|
154
|
+
const current = await currentVersion(adapter);
|
|
155
|
+
if (current?.version === release.version && current.platform === platform) {
|
|
156
|
+
try {
|
|
157
|
+
await fs.access(target, fs.constants.X_OK);
|
|
158
|
+
return {
|
|
159
|
+
...base,
|
|
160
|
+
success: true,
|
|
161
|
+
installed: true,
|
|
162
|
+
alreadyInstalled: true,
|
|
163
|
+
version: release.version,
|
|
164
|
+
platform,
|
|
165
|
+
path: target,
|
|
166
|
+
...(release.license ? { license: release.license } : {}),
|
|
167
|
+
...(asset.size ? { size: asset.size } : {})
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
catch { /* stale pointer: reinstall below */ }
|
|
171
|
+
}
|
|
172
|
+
const details = {
|
|
173
|
+
...base,
|
|
174
|
+
version: release.version,
|
|
175
|
+
platform,
|
|
176
|
+
...(release.license ? { license: release.license } : {}),
|
|
177
|
+
...(asset.size ? { size: asset.size } : {})
|
|
178
|
+
};
|
|
179
|
+
if (!options.confirm)
|
|
180
|
+
return { ...details, requiresConsent: true };
|
|
181
|
+
const bytes = await assetBytes(url, options.signal);
|
|
182
|
+
if (asset.size && bytes.length !== asset.size)
|
|
183
|
+
throw new Error('Engine asset size does not match the manifest');
|
|
184
|
+
const digest = createHash('sha256').update(bytes).digest('hex');
|
|
185
|
+
if (digest.toLowerCase() !== asset.sha256.toLowerCase())
|
|
186
|
+
throw new Error('Engine asset SHA-256 does not match the manifest');
|
|
187
|
+
await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
188
|
+
const temp = path.join(path.dirname(target), `.${path.basename(target)}.download-${process.pid}-${Date.now()}`);
|
|
189
|
+
try {
|
|
190
|
+
await fs.writeFile(temp, bytes, { mode: 0o600 });
|
|
191
|
+
await fs.chmod(temp, 0o755);
|
|
192
|
+
await fs.rm(target, { force: true });
|
|
193
|
+
await fs.rename(temp, target);
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
await fs.rm(temp, { force: true }).catch(() => { });
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
const pointer = path.join(root, 'current.json');
|
|
200
|
+
const pointerTemp = `${pointer}.tmp-${process.pid}-${Date.now()}`;
|
|
201
|
+
await fs.writeFile(pointerTemp, JSON.stringify({
|
|
202
|
+
engine: adapter.id,
|
|
203
|
+
version: release.version,
|
|
204
|
+
platform,
|
|
205
|
+
sha256: asset.sha256.toLowerCase(),
|
|
206
|
+
installedAt: new Date().toISOString()
|
|
207
|
+
}), { mode: 0o600 });
|
|
208
|
+
try {
|
|
209
|
+
await fs.rename(pointerTemp, pointer);
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
await fs.rm(pointerTemp, { force: true }).catch(() => { });
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
...details,
|
|
217
|
+
success: true,
|
|
218
|
+
installed: true,
|
|
219
|
+
alreadyInstalled: false,
|
|
220
|
+
path: target
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
return { ...base, error: error instanceof Error ? error.message : String(error) };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { engineInstallDir } from './registry.js';
|
|
6
|
+
import type { NativeEngineAdapter } from './types.js';
|
|
7
|
+
|
|
8
|
+
const MANIFEST_LIMIT = 1024 * 1024;
|
|
9
|
+
const ASSET_LIMIT = 512 * 1024 * 1024;
|
|
10
|
+
const DEFAULT_MANIFEST = 'https://github.com/ikbal-causyne/causyne-engines/releases/latest/download/engines.json';
|
|
11
|
+
|
|
12
|
+
interface EngineAsset {
|
|
13
|
+
url: string;
|
|
14
|
+
sha256: string;
|
|
15
|
+
size?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface EngineRelease {
|
|
19
|
+
version: string;
|
|
20
|
+
license?: string;
|
|
21
|
+
platforms: Record<string, EngineAsset>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface EngineManifest {
|
|
25
|
+
schema: 1;
|
|
26
|
+
engines: Record<string, EngineRelease>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface EngineInstallOptions {
|
|
30
|
+
confirm: boolean;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface EngineInstallResult {
|
|
35
|
+
success: boolean;
|
|
36
|
+
engine: string;
|
|
37
|
+
manifestUrl: string;
|
|
38
|
+
requiresConsent?: boolean;
|
|
39
|
+
installed?: boolean;
|
|
40
|
+
alreadyInstalled?: boolean;
|
|
41
|
+
version?: string;
|
|
42
|
+
platform?: string;
|
|
43
|
+
path?: string;
|
|
44
|
+
license?: string;
|
|
45
|
+
size?: number;
|
|
46
|
+
error?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function defaultEngineManifestUrl(): string {
|
|
50
|
+
const override = process.env['CAUSYNE_ENGINE_MANIFEST'];
|
|
51
|
+
return override && override.trim() ? override.trim() : DEFAULT_MANIFEST;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function platformKey(): string {
|
|
55
|
+
return `${process.platform}-${process.arch}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function validVersion(value: string): boolean {
|
|
59
|
+
return /^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/.test(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function validPlatform(value: string): boolean {
|
|
63
|
+
return /^[a-z0-9]+-[a-z0-9]+$/.test(value);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function timeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {
|
|
67
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
68
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function readLocation(location: string, limit: number, signal?: AbortSignal): Promise<{ text: string; base: string }> {
|
|
72
|
+
if (/^http:/i.test(location)) throw new Error('Engine manifest must use HTTPS or a local file');
|
|
73
|
+
if (/^https:/i.test(location)) {
|
|
74
|
+
const response = await fetch(location, {
|
|
75
|
+
redirect: 'follow',
|
|
76
|
+
headers: { accept: 'application/json', 'user-agent': 'Causyne-Agent' },
|
|
77
|
+
signal: timeoutSignal(20_000, signal)
|
|
78
|
+
});
|
|
79
|
+
if (!response.ok) throw new Error(`Manifest request failed with HTTP ${response.status}`);
|
|
80
|
+
if (new URL(response.url || location).protocol !== 'https:') throw new Error('Engine manifest redirect left HTTPS');
|
|
81
|
+
const text = await response.text();
|
|
82
|
+
if (Buffer.byteLength(text) > limit) throw new Error('Manifest is larger than 1 MB');
|
|
83
|
+
return { text, base: response.url || location };
|
|
84
|
+
}
|
|
85
|
+
const file = location.startsWith('file:') ? fileURLToPath(location) : path.resolve(location);
|
|
86
|
+
const stat = await fs.stat(file);
|
|
87
|
+
if (!stat.isFile() || stat.size > limit) throw new Error('Manifest is missing or larger than 1 MB');
|
|
88
|
+
const text = await fs.readFile(file, 'utf8');
|
|
89
|
+
return { text, base: location.startsWith('file:') ? location : pathToFileURL(file).href };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function readManifest(location: string, signal?: AbortSignal): Promise<{ manifest: EngineManifest; base: string }> {
|
|
93
|
+
const { text, base } = await readLocation(location, MANIFEST_LIMIT, signal);
|
|
94
|
+
let value: unknown;
|
|
95
|
+
try { value = JSON.parse(text); } catch { throw new Error('Engine manifest is not valid JSON'); }
|
|
96
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Engine manifest must be an object');
|
|
97
|
+
const record = value as Record<string, unknown>;
|
|
98
|
+
if (record.schema !== 1) throw new Error('Unsupported engine manifest schema');
|
|
99
|
+
if (!record.engines || typeof record.engines !== 'object' || Array.isArray(record.engines)) {
|
|
100
|
+
throw new Error('Engine manifest has no engines map');
|
|
101
|
+
}
|
|
102
|
+
return { manifest: record as unknown as EngineManifest, base };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function releaseFor(manifest: EngineManifest, adapter: NativeEngineAdapter): EngineRelease {
|
|
106
|
+
const release = manifest.engines[adapter.id];
|
|
107
|
+
if (!release || typeof release !== 'object') throw new Error(`No release for engine ${adapter.id}`);
|
|
108
|
+
if (typeof release.version !== 'string' || !validVersion(release.version)) throw new Error('Invalid engine release version');
|
|
109
|
+
if (release.license !== undefined && (typeof release.license !== 'string' || release.license.length > 200)) {
|
|
110
|
+
throw new Error('Invalid engine release license');
|
|
111
|
+
}
|
|
112
|
+
if (!release.platforms || typeof release.platforms !== 'object' || Array.isArray(release.platforms)) {
|
|
113
|
+
throw new Error('Engine release has no platform map');
|
|
114
|
+
}
|
|
115
|
+
return release;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function assetFor(release: EngineRelease, base: string): { platform: string; asset: EngineAsset; url: string } {
|
|
119
|
+
const platform = platformKey();
|
|
120
|
+
if (!validPlatform(platform)) throw new Error(`Unsupported platform: ${platform}`);
|
|
121
|
+
const asset = release.platforms[platform];
|
|
122
|
+
if (!asset || typeof asset !== 'object') throw new Error(`No release asset for ${platform}`);
|
|
123
|
+
if (typeof asset.url !== 'string' || !asset.url.trim()) throw new Error('Engine asset has no URL');
|
|
124
|
+
if (typeof asset.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(asset.sha256)) throw new Error('Engine asset has no valid SHA-256');
|
|
125
|
+
if (asset.size !== undefined && (!Number.isInteger(asset.size) || asset.size < 1 || asset.size > ASSET_LIMIT)) {
|
|
126
|
+
throw new Error('Engine asset size is invalid');
|
|
127
|
+
}
|
|
128
|
+
const url = new URL(asset.url, base).href;
|
|
129
|
+
const protocol = new URL(url).protocol;
|
|
130
|
+
const localManifest = base.startsWith('file:');
|
|
131
|
+
if (protocol !== 'https:' && !(localManifest && protocol === 'file:')) {
|
|
132
|
+
throw new Error('Engine asset must use HTTPS, or a local file URL from a local manifest');
|
|
133
|
+
}
|
|
134
|
+
return { platform, asset, url };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function assetBytes(url: string, signal?: AbortSignal): Promise<Buffer> {
|
|
138
|
+
if (url.startsWith('file:')) {
|
|
139
|
+
const file = fileURLToPath(url);
|
|
140
|
+
const stat = await fs.stat(file);
|
|
141
|
+
if (!stat.isFile() || stat.size > ASSET_LIMIT) throw new Error('Engine asset is missing or too large');
|
|
142
|
+
return await fs.readFile(file);
|
|
143
|
+
}
|
|
144
|
+
const response = await fetch(url, {
|
|
145
|
+
redirect: 'follow',
|
|
146
|
+
headers: { accept: 'application/octet-stream', 'user-agent': 'Causyne-Agent' },
|
|
147
|
+
signal: timeoutSignal(600_000, signal)
|
|
148
|
+
});
|
|
149
|
+
if (!response.ok) throw new Error(`Engine download failed with HTTP ${response.status}`);
|
|
150
|
+
if (new URL(response.url || url).protocol !== 'https:') throw new Error('Engine download redirect left HTTPS');
|
|
151
|
+
const declared = Number(response.headers.get('content-length') || 0);
|
|
152
|
+
if (declared > ASSET_LIMIT) throw new Error('Engine asset is larger than 512 MB');
|
|
153
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
154
|
+
if (bytes.length > ASSET_LIMIT) throw new Error('Engine asset is larger than 512 MB');
|
|
155
|
+
return bytes;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function currentVersion(adapter: NativeEngineAdapter): Promise<{ version: string; platform: string } | null> {
|
|
159
|
+
try {
|
|
160
|
+
const value = JSON.parse(await fs.readFile(path.join(engineInstallDir(adapter), 'current.json'), 'utf8')) as Record<string, unknown>;
|
|
161
|
+
if (typeof value.version !== 'string' || !validVersion(value.version)) return null;
|
|
162
|
+
if (typeof value.platform !== 'string' || !validPlatform(value.platform)) return null;
|
|
163
|
+
return { version: value.version, platform: value.platform };
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function installNativeEngine(adapter: NativeEngineAdapter, options: EngineInstallOptions): Promise<EngineInstallResult> {
|
|
170
|
+
const manifestUrl = defaultEngineManifestUrl();
|
|
171
|
+
const base: EngineInstallResult = { success: false, engine: adapter.id, manifestUrl };
|
|
172
|
+
try {
|
|
173
|
+
const { manifest, base: location } = await readManifest(manifestUrl, options.signal);
|
|
174
|
+
const release = releaseFor(manifest, adapter);
|
|
175
|
+
const { platform, asset, url } = assetFor(release, location);
|
|
176
|
+
const root = engineInstallDir(adapter);
|
|
177
|
+
const suffix = process.platform === 'win32' ? '.exe' : '';
|
|
178
|
+
const target = path.join(root, 'versions', release.version, platform, `${adapter.binaryName}${suffix}`);
|
|
179
|
+
const current = await currentVersion(adapter);
|
|
180
|
+
if (current?.version === release.version && current.platform === platform) {
|
|
181
|
+
try {
|
|
182
|
+
await fs.access(target, fs.constants.X_OK);
|
|
183
|
+
return {
|
|
184
|
+
...base,
|
|
185
|
+
success: true,
|
|
186
|
+
installed: true,
|
|
187
|
+
alreadyInstalled: true,
|
|
188
|
+
version: release.version,
|
|
189
|
+
platform,
|
|
190
|
+
path: target,
|
|
191
|
+
...(release.license ? { license: release.license } : {}),
|
|
192
|
+
...(asset.size ? { size: asset.size } : {})
|
|
193
|
+
};
|
|
194
|
+
} catch { /* stale pointer: reinstall below */ }
|
|
195
|
+
}
|
|
196
|
+
const details = {
|
|
197
|
+
...base,
|
|
198
|
+
version: release.version,
|
|
199
|
+
platform,
|
|
200
|
+
...(release.license ? { license: release.license } : {}),
|
|
201
|
+
...(asset.size ? { size: asset.size } : {})
|
|
202
|
+
};
|
|
203
|
+
if (!options.confirm) return { ...details, requiresConsent: true };
|
|
204
|
+
|
|
205
|
+
const bytes = await assetBytes(url, options.signal);
|
|
206
|
+
if (asset.size && bytes.length !== asset.size) throw new Error('Engine asset size does not match the manifest');
|
|
207
|
+
const digest = createHash('sha256').update(bytes).digest('hex');
|
|
208
|
+
if (digest.toLowerCase() !== asset.sha256.toLowerCase()) throw new Error('Engine asset SHA-256 does not match the manifest');
|
|
209
|
+
|
|
210
|
+
await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
211
|
+
const temp = path.join(path.dirname(target), `.${path.basename(target)}.download-${process.pid}-${Date.now()}`);
|
|
212
|
+
try {
|
|
213
|
+
await fs.writeFile(temp, bytes, { mode: 0o600 });
|
|
214
|
+
await fs.chmod(temp, 0o755);
|
|
215
|
+
await fs.rm(target, { force: true });
|
|
216
|
+
await fs.rename(temp, target);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
await fs.rm(temp, { force: true }).catch(() => {});
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const pointer = path.join(root, 'current.json');
|
|
223
|
+
const pointerTemp = `${pointer}.tmp-${process.pid}-${Date.now()}`;
|
|
224
|
+
await fs.writeFile(pointerTemp, JSON.stringify({
|
|
225
|
+
engine: adapter.id,
|
|
226
|
+
version: release.version,
|
|
227
|
+
platform,
|
|
228
|
+
sha256: asset.sha256.toLowerCase(),
|
|
229
|
+
installedAt: new Date().toISOString()
|
|
230
|
+
}), { mode: 0o600 });
|
|
231
|
+
try {
|
|
232
|
+
await fs.rename(pointerTemp, pointer);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
await fs.rm(pointerTemp, { force: true }).catch(() => {});
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
...details,
|
|
240
|
+
success: true,
|
|
241
|
+
installed: true,
|
|
242
|
+
alreadyInstalled: false,
|
|
243
|
+
path: target
|
|
244
|
+
};
|
|
245
|
+
} catch (error) {
|
|
246
|
+
return { ...base, error: error instanceof Error ? error.message : String(error) };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
// Raster image engine. The binary speaks a verb-per-subcommand CLI and
|
|
3
|
+
// rejects any flag a subcommand does not declare, so every argument list here
|
|
4
|
+
// is built per verb. Nothing is appended globally.
|
|
5
|
+
const TIMEOUTS = {
|
|
6
|
+
status: 10_000,
|
|
7
|
+
catalog: 30_000,
|
|
8
|
+
describe: 30_000,
|
|
9
|
+
inspect: 60_000,
|
|
10
|
+
execute: 180_000,
|
|
11
|
+
batch: 600_000,
|
|
12
|
+
export: 300_000,
|
|
13
|
+
render: 120_000,
|
|
14
|
+
probe: 60_000,
|
|
15
|
+
install: 600_000
|
|
16
|
+
};
|
|
17
|
+
const NEW_DOCUMENT = 'file.new';
|
|
18
|
+
function positional(value) {
|
|
19
|
+
// A positional that begins with "-" would be parsed as a flag.
|
|
20
|
+
return value.startsWith('-') ? `.${path.sep}${value}` : value;
|
|
21
|
+
}
|
|
22
|
+
function quality(value) {
|
|
23
|
+
if (value === undefined)
|
|
24
|
+
return [];
|
|
25
|
+
return ['--quality', String(Math.min(100, Math.max(1, Math.round(value))))];
|
|
26
|
+
}
|
|
27
|
+
function commandArgs(steps) {
|
|
28
|
+
const args = [];
|
|
29
|
+
for (const step of steps) {
|
|
30
|
+
args.push('--cmd', step.id);
|
|
31
|
+
if (step.params && Object.keys(step.params).length > 0)
|
|
32
|
+
args.push('--params', JSON.stringify(step.params));
|
|
33
|
+
}
|
|
34
|
+
return args;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Source for `run`: the existing project, or a new document when the first
|
|
38
|
+
* step is file.new. Returns the remaining steps to apply.
|
|
39
|
+
*/
|
|
40
|
+
function runSource(steps, context) {
|
|
41
|
+
if (context.project)
|
|
42
|
+
return { args: [positional(context.project)], rest: steps };
|
|
43
|
+
const [first, ...rest] = steps;
|
|
44
|
+
if (first?.id === NEW_DOCUMENT) {
|
|
45
|
+
return { args: ['--new', JSON.stringify(first.params ?? { width: 1920, height: 1080 })], rest };
|
|
46
|
+
}
|
|
47
|
+
throw new Error(`The photo engine needs project, or a first step of ${NEW_DOCUMENT} to create a document`);
|
|
48
|
+
}
|
|
49
|
+
function destination(context) {
|
|
50
|
+
if (context.saveAs)
|
|
51
|
+
return { args: ['--out', context.saveAs], artifact: context.saveAs };
|
|
52
|
+
if (context.save && context.project)
|
|
53
|
+
return { args: ['--out', context.project], artifact: context.project };
|
|
54
|
+
return { args: [] };
|
|
55
|
+
}
|
|
56
|
+
function requireProject(context, action) {
|
|
57
|
+
if (!context.project)
|
|
58
|
+
throw new Error(`${action} requires project`);
|
|
59
|
+
return positional(context.project);
|
|
60
|
+
}
|
|
61
|
+
export const photoEngine = {
|
|
62
|
+
id: 'photo',
|
|
63
|
+
label: 'Causyne Photo Engine',
|
|
64
|
+
envVar: 'CAUSYNE_ENGINE_PHOTO',
|
|
65
|
+
binaryName: 'causyne-engine-photo',
|
|
66
|
+
actions: ['catalog', 'describe', 'inspect', 'execute', 'batch', 'export', 'render', 'probe'],
|
|
67
|
+
invoke(request, context) {
|
|
68
|
+
if (context.demo)
|
|
69
|
+
throw new Error('The photo engine has no demo document; use a first step of file.new');
|
|
70
|
+
let args;
|
|
71
|
+
let artifacts = [];
|
|
72
|
+
switch (request.action) {
|
|
73
|
+
case 'status':
|
|
74
|
+
args = ['--version'];
|
|
75
|
+
break;
|
|
76
|
+
case 'catalog':
|
|
77
|
+
args = ['commands', '--json', ...(request.query ? ['--filter', request.query] : [])];
|
|
78
|
+
break;
|
|
79
|
+
case 'describe':
|
|
80
|
+
args = ['commands', '--json', '--filter', request.command ?? ''];
|
|
81
|
+
break;
|
|
82
|
+
case 'inspect':
|
|
83
|
+
args = ['info', requireProject(context, 'inspect'), '--compact'];
|
|
84
|
+
break;
|
|
85
|
+
case 'probe':
|
|
86
|
+
args = ['info', positional(request.query ?? ''), '--compact'];
|
|
87
|
+
break;
|
|
88
|
+
case 'execute':
|
|
89
|
+
case 'batch': {
|
|
90
|
+
if (context.keepGoing)
|
|
91
|
+
throw new Error('The photo engine stops at the first failed step; keepGoing is not supported');
|
|
92
|
+
const steps = request.action === 'execute'
|
|
93
|
+
? [{ id: request.command ?? '', ...(request.params ? { params: request.params } : {}) }]
|
|
94
|
+
: (request.steps ?? []);
|
|
95
|
+
const source = runSource(steps, context);
|
|
96
|
+
const out = destination(context);
|
|
97
|
+
if (source.rest.length === 0 && out.args.length === 0) {
|
|
98
|
+
throw new Error('Nothing to do: add a command after file.new, or saveAs to write the new document');
|
|
99
|
+
}
|
|
100
|
+
args = ['run', ...source.args, ...commandArgs(source.rest), ...out.args];
|
|
101
|
+
if (out.artifact)
|
|
102
|
+
artifacts = [out.artifact];
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
case 'export': {
|
|
106
|
+
const output = request.output ?? '';
|
|
107
|
+
args = ['convert', requireProject(context, 'export'), positional(output),
|
|
108
|
+
...(request.format ? ['--format', request.format] : []), ...quality(request.quality)];
|
|
109
|
+
artifacts = [output];
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
case 'render': {
|
|
113
|
+
// A flattened preview. Defaults to PNG only when the output has no
|
|
114
|
+
// extension, so the bytes always match the file name.
|
|
115
|
+
const output = request.output ?? '';
|
|
116
|
+
const format = request.format ?? (path.extname(output) ? undefined : 'png');
|
|
117
|
+
args = ['convert', requireProject(context, 'render'), positional(output), ...(format ? ['--format', format] : [])];
|
|
118
|
+
artifacts = [output];
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
default:
|
|
122
|
+
throw new Error(`Unsupported photo engine action: ${request.action}`);
|
|
123
|
+
}
|
|
124
|
+
return { args, artifacts: artifacts.filter(Boolean), timeoutMs: TIMEOUTS[request.action] };
|
|
125
|
+
}
|
|
126
|
+
};
|