@causyne/agent 1.10.21 → 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.
Files changed (82) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +12 -0
  2. package/native-skills/media/professional-document-publishing/SKILL.md +44 -0
  3. package/native-skills/media/screenplay-and-shotlist-forge/SKILL.md +42 -0
  4. package/package.json +1 -1
  5. package/src/acp/client.js +235 -0
  6. package/src/acp/client.ts +282 -0
  7. package/src/acp/peerProfiles.js +122 -0
  8. package/src/acp/peerProfiles.ts +128 -0
  9. package/src/acp/protocol.js +55 -0
  10. package/src/acp/protocol.ts +456 -0
  11. package/src/acp/server.js +746 -0
  12. package/src/acp/server.ts +822 -0
  13. package/src/agentLoop.d.ts +64 -0
  14. package/src/agentLoop.js +156 -12
  15. package/src/approvalGrants.js +33 -0
  16. package/src/approvalGrants.ts +50 -0
  17. package/src/commands.js +203 -0
  18. package/src/compiledSkills.js +10 -0
  19. package/src/decisionPolicy.js +2 -0
  20. package/src/decisionPolicy.ts +1 -0
  21. package/src/documentEngine/antiSlopAuditor.js +156 -0
  22. package/src/documentEngine/antiSlopAuditor.ts +221 -0
  23. package/src/documentEngine/documentForge.js +443 -0
  24. package/src/documentEngine/documentForge.ts +519 -0
  25. package/src/documentEngine/screenplayFormatter.js +336 -0
  26. package/src/documentEngine/screenplayFormatter.ts +407 -0
  27. package/src/engines/cad.js +113 -0
  28. package/src/engines/cad.ts +128 -0
  29. package/src/engines/film.js +108 -0
  30. package/src/engines/film.ts +104 -0
  31. package/src/engines/installer.js +226 -0
  32. package/src/engines/installer.ts +248 -0
  33. package/src/engines/photo.js +126 -0
  34. package/src/engines/photo.ts +137 -0
  35. package/src/engines/registry.js +186 -0
  36. package/src/engines/registry.ts +185 -0
  37. package/src/engines/sound.js +117 -0
  38. package/src/engines/sound.ts +130 -0
  39. package/src/engines/types.js +1 -0
  40. package/src/engines/types.ts +73 -0
  41. package/src/entrypoint.js +13 -0
  42. package/src/execSafe.js +10 -13
  43. package/src/execSafe.ts +25 -0
  44. package/src/memoryManager.js +9 -3
  45. package/src/modelRouter.js +56 -123
  46. package/src/modelRouter.ts +134 -0
  47. package/src/observer/advisory.js +164 -0
  48. package/src/observer/advisory.ts +171 -0
  49. package/src/observer/coldObserver.js +462 -0
  50. package/src/observer/coldObserver.ts +540 -0
  51. package/src/observer/evidence.js +435 -0
  52. package/src/observer/evidence.ts +499 -0
  53. package/src/perception.js +303 -118
  54. package/src/perception.ts +387 -0
  55. package/src/procSignal.js +15 -16
  56. package/src/procSignal.ts +31 -0
  57. package/src/promptMentions.js +170 -0
  58. package/src/promptMentions.ts +212 -0
  59. package/src/sandbox.js +9 -1
  60. package/src/sessionJournal.js +12 -2
  61. package/src/sessionJournal.ts +12 -2
  62. package/src/textDiff.js +117 -109
  63. package/src/textDiff.ts +169 -0
  64. package/src/toolPacks.js +19 -8
  65. package/src/tools/documentForge.js +215 -0
  66. package/src/tools/documentForge.ts +265 -0
  67. package/src/tools/generateMediaViaApi.js +1 -1
  68. package/src/tools/nativeEngine.js +464 -0
  69. package/src/tools/nativeEngine.ts +433 -0
  70. package/src/tools/openSourceToolProvisioner.js +510 -0
  71. package/src/tools/openSourceToolProvisioner.ts +590 -0
  72. package/src/tools/peerAgent.js +102 -0
  73. package/src/tools/peerAgent.ts +116 -0
  74. package/src/tools/registry.js +6 -1
  75. package/src/tui/completion.js +98 -42
  76. package/src/tui/prompt.js +17 -17
  77. package/src/uncertainty.js +93 -205
  78. package/src/uncertainty.ts +255 -0
  79. package/src/utils/paths.js +15 -18
  80. package/src/utils/paths.ts +36 -0
  81. package/src/vfeTracker.js +122 -181
  82. package/src/vfeTracker.ts +242 -0
@@ -0,0 +1,108 @@
1
+ const TIMEOUTS = {
2
+ status: 10_000,
3
+ catalog: 30_000,
4
+ describe: 20_000,
5
+ inspect: 60_000,
6
+ execute: 120_000,
7
+ batch: 300_000,
8
+ export: 900_000,
9
+ render: 300_000,
10
+ probe: 120_000,
11
+ install: 600_000
12
+ };
13
+ function baseArgs(request, context) {
14
+ const args = [];
15
+ if (context.demo)
16
+ args.push('--demo');
17
+ if (context.project)
18
+ args.push('--project', context.project);
19
+ if (context.saveAs)
20
+ args.push('--save-as', context.saveAs);
21
+ else if (context.save)
22
+ args.push('--save');
23
+ return args;
24
+ }
25
+ function outputArgs(request) {
26
+ const args = [];
27
+ if (request.preset)
28
+ args.push('--preset', request.preset);
29
+ if (request.format)
30
+ args.push('--format', request.format);
31
+ if (request.range)
32
+ args.push('--range', request.range);
33
+ if (request.start !== undefined)
34
+ args.push('--start', String(request.start));
35
+ if (request.end !== undefined)
36
+ args.push('--end', String(request.end));
37
+ if (request.scale !== undefined)
38
+ args.push('--scale', String(request.scale));
39
+ if (request.quality !== undefined)
40
+ args.push('--quality', String(request.quality));
41
+ if (request.allowOffline)
42
+ args.push('--allow-offline');
43
+ return args;
44
+ }
45
+ export const filmEngine = {
46
+ id: 'film',
47
+ label: 'Causyne Film Engine',
48
+ envVar: 'CAUSYNE_ENGINE_FILM',
49
+ binaryName: 'causyne-engine-film',
50
+ actions: ['catalog', 'describe', 'inspect', 'execute', 'batch', 'export', 'render', 'probe'],
51
+ invoke(request, context) {
52
+ const args = baseArgs(request, context);
53
+ let stdin;
54
+ let artifacts = [];
55
+ switch (request.action) {
56
+ case 'catalog':
57
+ args.push('commands');
58
+ if (request.query)
59
+ args.push(request.query);
60
+ args.push('--json');
61
+ break;
62
+ case 'describe':
63
+ args.push('describe', request.command ?? '');
64
+ break;
65
+ case 'inspect':
66
+ args.push('inspect', request.query || 'all');
67
+ break;
68
+ case 'execute':
69
+ args.push('exec', request.command ?? '', JSON.stringify(request.params ?? {}));
70
+ break;
71
+ case 'batch':
72
+ args.push('run', '-');
73
+ if (context.keepGoing)
74
+ args.push('--keep-going');
75
+ stdin = (request.steps ?? []).map(step => JSON.stringify(step)).join('\n') + '\n';
76
+ break;
77
+ case 'export':
78
+ args.push('export', request.output ?? '', ...outputArgs(request));
79
+ artifacts = [request.output ?? ''];
80
+ break;
81
+ case 'render':
82
+ args.push('render', '--seconds', String(request.seconds ?? 0), '--out', request.output ?? '');
83
+ if (request.scale !== undefined)
84
+ args.push('--scale', String(request.scale));
85
+ if (request.allowOffline)
86
+ args.push('--allow-offline');
87
+ artifacts = [request.output ?? ''];
88
+ break;
89
+ case 'probe':
90
+ args.push('probe', request.query ?? '');
91
+ break;
92
+ case 'status':
93
+ args.push('--version');
94
+ break;
95
+ }
96
+ args.push('--compact');
97
+ if (request.saveAs)
98
+ artifacts = [request.saveAs];
99
+ else if (request.save && context.project)
100
+ artifacts = [context.project];
101
+ return {
102
+ args,
103
+ ...(stdin === undefined ? {} : { stdin }),
104
+ artifacts: artifacts.filter(Boolean),
105
+ timeoutMs: TIMEOUTS[request.action]
106
+ };
107
+ }
108
+ };
@@ -0,0 +1,104 @@
1
+ import type {
2
+ NativeEngineAction,
3
+ NativeEngineAdapter,
4
+ NativeEngineContext,
5
+ NativeEngineInvocation,
6
+ NativeEngineRequest
7
+ } from './types.js';
8
+
9
+ const TIMEOUTS: Record<NativeEngineAction, number> = {
10
+ status: 10_000,
11
+ catalog: 30_000,
12
+ describe: 20_000,
13
+ inspect: 60_000,
14
+ execute: 120_000,
15
+ batch: 300_000,
16
+ export: 900_000,
17
+ render: 300_000,
18
+ probe: 120_000,
19
+ install: 600_000
20
+ };
21
+
22
+ function baseArgs(request: NativeEngineRequest, context: NativeEngineContext): string[] {
23
+ const args: string[] = [];
24
+ if (context.demo) args.push('--demo');
25
+ if (context.project) args.push('--project', context.project);
26
+ if (context.saveAs) args.push('--save-as', context.saveAs);
27
+ else if (context.save) args.push('--save');
28
+ return args;
29
+ }
30
+
31
+ function outputArgs(request: NativeEngineRequest): string[] {
32
+ const args: string[] = [];
33
+ if (request.preset) args.push('--preset', request.preset);
34
+ if (request.format) args.push('--format', request.format);
35
+ if (request.range) args.push('--range', request.range);
36
+ if (request.start !== undefined) args.push('--start', String(request.start));
37
+ if (request.end !== undefined) args.push('--end', String(request.end));
38
+ if (request.scale !== undefined) args.push('--scale', String(request.scale));
39
+ if (request.quality !== undefined) args.push('--quality', String(request.quality));
40
+ if (request.allowOffline) args.push('--allow-offline');
41
+ return args;
42
+ }
43
+
44
+ export const filmEngine: NativeEngineAdapter = {
45
+ id: 'film',
46
+ label: 'Causyne Film Engine',
47
+ envVar: 'CAUSYNE_ENGINE_FILM',
48
+ binaryName: 'causyne-engine-film',
49
+ actions: ['catalog', 'describe', 'inspect', 'execute', 'batch', 'export', 'render', 'probe'],
50
+ invoke(request: NativeEngineRequest, context: NativeEngineContext): NativeEngineInvocation {
51
+ const args = baseArgs(request, context);
52
+ let stdin: string | undefined;
53
+ let artifacts: string[] = [];
54
+
55
+ switch (request.action) {
56
+ case 'catalog':
57
+ args.push('commands');
58
+ if (request.query) args.push(request.query);
59
+ args.push('--json');
60
+ break;
61
+ case 'describe':
62
+ args.push('describe', request.command ?? '');
63
+ break;
64
+ case 'inspect':
65
+ args.push('inspect', request.query || 'all');
66
+ break;
67
+ case 'execute':
68
+ args.push('exec', request.command ?? '', JSON.stringify(request.params ?? {}));
69
+ break;
70
+ case 'batch':
71
+ args.push('run', '-');
72
+ if (context.keepGoing) args.push('--keep-going');
73
+ stdin = (request.steps ?? []).map(step => JSON.stringify(step)).join('\n') + '\n';
74
+ break;
75
+ case 'export':
76
+ args.push('export', request.output ?? '', ...outputArgs(request));
77
+ artifacts = [request.output ?? ''];
78
+ break;
79
+ case 'render':
80
+ args.push('render', '--seconds', String(request.seconds ?? 0), '--out', request.output ?? '');
81
+ if (request.scale !== undefined) args.push('--scale', String(request.scale));
82
+ if (request.allowOffline) args.push('--allow-offline');
83
+ artifacts = [request.output ?? ''];
84
+ break;
85
+ case 'probe':
86
+ args.push('probe', request.query ?? '');
87
+ break;
88
+ case 'status':
89
+ args.push('--version');
90
+ break;
91
+ }
92
+
93
+ args.push('--compact');
94
+ if (request.saveAs) artifacts = [request.saveAs];
95
+ else if (request.save && context.project) artifacts = [context.project];
96
+
97
+ return {
98
+ args,
99
+ ...(stdin === undefined ? {} : { stdin }),
100
+ artifacts: artifacts.filter(Boolean),
101
+ timeoutMs: TIMEOUTS[request.action]
102
+ };
103
+ }
104
+ };
@@ -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
+ }