@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,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
+ };
@@ -0,0 +1,137 @@
1
+ import path from 'node:path';
2
+ import type {
3
+ NativeEngineAction,
4
+ NativeEngineAdapter,
5
+ NativeEngineContext,
6
+ NativeEngineInvocation,
7
+ NativeEngineRequest,
8
+ NativeEngineStep
9
+ } from './types.js';
10
+
11
+ // Raster image engine. The binary speaks a verb-per-subcommand CLI and
12
+ // rejects any flag a subcommand does not declare, so every argument list here
13
+ // is built per verb. Nothing is appended globally.
14
+
15
+ const TIMEOUTS: Record<NativeEngineAction, number> = {
16
+ status: 10_000,
17
+ catalog: 30_000,
18
+ describe: 30_000,
19
+ inspect: 60_000,
20
+ execute: 180_000,
21
+ batch: 600_000,
22
+ export: 300_000,
23
+ render: 120_000,
24
+ probe: 60_000,
25
+ install: 600_000
26
+ };
27
+
28
+ const NEW_DOCUMENT = 'file.new';
29
+
30
+ function positional(value: string): string {
31
+ // A positional that begins with "-" would be parsed as a flag.
32
+ return value.startsWith('-') ? `.${path.sep}${value}` : value;
33
+ }
34
+
35
+ function quality(value: number | undefined): string[] {
36
+ if (value === undefined) return [];
37
+ return ['--quality', String(Math.min(100, Math.max(1, Math.round(value))))];
38
+ }
39
+
40
+ function commandArgs(steps: NativeEngineStep[]): string[] {
41
+ const args: string[] = [];
42
+ for (const step of steps) {
43
+ args.push('--cmd', step.id);
44
+ if (step.params && Object.keys(step.params).length > 0) args.push('--params', JSON.stringify(step.params));
45
+ }
46
+ return args;
47
+ }
48
+
49
+ /**
50
+ * Source for `run`: the existing project, or a new document when the first
51
+ * step is file.new. Returns the remaining steps to apply.
52
+ */
53
+ function runSource(steps: NativeEngineStep[], context: NativeEngineContext): { args: string[]; rest: NativeEngineStep[] } {
54
+ if (context.project) return { args: [positional(context.project)], rest: steps };
55
+ const [first, ...rest] = steps;
56
+ if (first?.id === NEW_DOCUMENT) {
57
+ return { args: ['--new', JSON.stringify(first.params ?? { width: 1920, height: 1080 })], rest };
58
+ }
59
+ throw new Error(`The photo engine needs project, or a first step of ${NEW_DOCUMENT} to create a document`);
60
+ }
61
+
62
+ function destination(context: NativeEngineContext): { args: string[]; artifact?: string } {
63
+ if (context.saveAs) return { args: ['--out', context.saveAs], artifact: context.saveAs };
64
+ if (context.save && context.project) return { args: ['--out', context.project], artifact: context.project };
65
+ return { args: [] };
66
+ }
67
+
68
+ function requireProject(context: NativeEngineContext, action: string): string {
69
+ if (!context.project) throw new Error(`${action} requires project`);
70
+ return positional(context.project);
71
+ }
72
+
73
+ export const photoEngine: NativeEngineAdapter = {
74
+ id: 'photo',
75
+ label: 'Causyne Photo Engine',
76
+ envVar: 'CAUSYNE_ENGINE_PHOTO',
77
+ binaryName: 'causyne-engine-photo',
78
+ actions: ['catalog', 'describe', 'inspect', 'execute', 'batch', 'export', 'render', 'probe'],
79
+ invoke(request: NativeEngineRequest, context: NativeEngineContext): NativeEngineInvocation {
80
+ if (context.demo) throw new Error('The photo engine has no demo document; use a first step of file.new');
81
+ let args: string[];
82
+ let artifacts: string[] = [];
83
+
84
+ switch (request.action) {
85
+ case 'status':
86
+ args = ['--version'];
87
+ break;
88
+ case 'catalog':
89
+ args = ['commands', '--json', ...(request.query ? ['--filter', request.query] : [])];
90
+ break;
91
+ case 'describe':
92
+ args = ['commands', '--json', '--filter', request.command ?? ''];
93
+ break;
94
+ case 'inspect':
95
+ args = ['info', requireProject(context, 'inspect'), '--compact'];
96
+ break;
97
+ case 'probe':
98
+ args = ['info', positional(request.query ?? ''), '--compact'];
99
+ break;
100
+ case 'execute':
101
+ case 'batch': {
102
+ if (context.keepGoing) throw new Error('The photo engine stops at the first failed step; keepGoing is not supported');
103
+ const steps: NativeEngineStep[] = request.action === 'execute'
104
+ ? [{ id: request.command ?? '', ...(request.params ? { params: request.params } : {}) }]
105
+ : (request.steps ?? []);
106
+ const source = runSource(steps, context);
107
+ const out = destination(context);
108
+ if (source.rest.length === 0 && out.args.length === 0) {
109
+ throw new Error('Nothing to do: add a command after file.new, or saveAs to write the new document');
110
+ }
111
+ args = ['run', ...source.args, ...commandArgs(source.rest), ...out.args];
112
+ if (out.artifact) artifacts = [out.artifact];
113
+ break;
114
+ }
115
+ case 'export': {
116
+ const output = request.output ?? '';
117
+ args = ['convert', requireProject(context, 'export'), positional(output),
118
+ ...(request.format ? ['--format', request.format] : []), ...quality(request.quality)];
119
+ artifacts = [output];
120
+ break;
121
+ }
122
+ case 'render': {
123
+ // A flattened preview. Defaults to PNG only when the output has no
124
+ // extension, so the bytes always match the file name.
125
+ const output = request.output ?? '';
126
+ const format = request.format ?? (path.extname(output) ? undefined : 'png');
127
+ args = ['convert', requireProject(context, 'render'), positional(output), ...(format ? ['--format', format] : [])];
128
+ artifacts = [output];
129
+ break;
130
+ }
131
+ default:
132
+ throw new Error(`Unsupported photo engine action: ${request.action}`);
133
+ }
134
+
135
+ return { args, artifacts: artifacts.filter(Boolean), timeoutMs: TIMEOUTS[request.action] };
136
+ }
137
+ };
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
5
+ import { filmEngine } from './film.js';
6
+ import { photoEngine } from './photo.js';
7
+ import { soundEngine } from './sound.js';
8
+ import { cadEngine } from './cad.js';
9
+ const MAX_STDOUT = 8 * 1024 * 1024;
10
+ const MAX_STDERR = 1024 * 1024;
11
+ export const NATIVE_ENGINES = {
12
+ [filmEngine.id]: filmEngine,
13
+ [photoEngine.id]: photoEngine,
14
+ [soundEngine.id]: soundEngine,
15
+ [cadEngine.id]: cadEngine
16
+ };
17
+ export function nativeEngine(id) {
18
+ return NATIVE_ENGINES[id] ?? null;
19
+ }
20
+ export function engineInstallDir(adapter) {
21
+ return path.join(causyneHome(), 'engines', adapter.id);
22
+ }
23
+ function inside(root, target) {
24
+ const relative = path.relative(root, target);
25
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
26
+ }
27
+ function currentEngineBinary(adapter) {
28
+ const root = engineInstallDir(adapter);
29
+ const suffix = process.platform === 'win32' ? '.exe' : '';
30
+ try {
31
+ const value = JSON.parse(fs.readFileSync(path.join(root, 'current.json'), 'utf8'));
32
+ if (typeof value.version !== 'string' || !/^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/.test(value.version))
33
+ return null;
34
+ if (typeof value.platform !== 'string' || !/^[a-z0-9]+-[a-z0-9]+$/.test(value.platform))
35
+ return null;
36
+ const file = path.join(root, 'versions', value.version, value.platform, `${adapter.binaryName}${suffix}`);
37
+ return inside(root, file) ? file : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ export function engineBinaryCandidates(adapter) {
44
+ const suffix = process.platform === 'win32' ? '.exe' : '';
45
+ const name = `${adapter.binaryName}${suffix}`;
46
+ const root = engineInstallDir(adapter);
47
+ return [
48
+ path.join(root, 'current', 'bin', name),
49
+ path.join(root, 'current', name),
50
+ path.join(root, 'bin', name),
51
+ path.join(root, name)
52
+ ];
53
+ }
54
+ function executable(file) {
55
+ try {
56
+ if (!fs.statSync(file).isFile())
57
+ return false;
58
+ if (process.platform === 'win32')
59
+ return true;
60
+ fs.accessSync(file, fs.constants.X_OK);
61
+ return true;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ function isShebangScript(file) {
68
+ try {
69
+ const fd = fs.openSync(file, 'r');
70
+ const buf = Buffer.alloc(2);
71
+ const read = fs.readSync(fd, buf, 0, 2, 0);
72
+ fs.closeSync(fd);
73
+ return read === 2 && buf[0] === 0x23 && buf[1] === 0x21;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ export function findEngineBinary(adapter) {
80
+ const override = process.env[adapter.envVar];
81
+ if (override && override.trim()) {
82
+ const candidate = resolveUserPath(override.trim());
83
+ const file = (() => {
84
+ try {
85
+ return fs.statSync(candidate).isDirectory();
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ })() ? path.join(candidate, adapter.binaryName + (process.platform === 'win32' ? '.exe' : '')) : candidate;
91
+ if (executable(file))
92
+ return fs.realpathSync(file);
93
+ }
94
+ const current = currentEngineBinary(adapter);
95
+ if (current && executable(current))
96
+ return fs.realpathSync(current);
97
+ for (const candidate of engineBinaryCandidates(adapter)) {
98
+ if (executable(candidate))
99
+ return fs.realpathSync(candidate);
100
+ }
101
+ return null;
102
+ }
103
+ function childEnv() {
104
+ const keys = [
105
+ 'PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'TMPDIR',
106
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME'
107
+ ];
108
+ const env = {};
109
+ for (const key of keys) {
110
+ const value = process.env[key];
111
+ if (value !== undefined)
112
+ env[key] = value;
113
+ }
114
+ env.NO_COLOR = '1';
115
+ return env;
116
+ }
117
+ export function runEngineBinary(binary, args, options) {
118
+ options.signal?.throwIfAborted();
119
+ const isScript = process.platform === 'win32' && isShebangScript(binary);
120
+ const command = isScript ? process.execPath : binary;
121
+ const commandArgs = isScript ? [binary, ...args] : args;
122
+ return new Promise((resolve, reject) => {
123
+ const child = spawn(command, commandArgs, {
124
+ cwd: options.cwd,
125
+ env: childEnv(),
126
+ stdio: ['pipe', 'pipe', 'pipe'],
127
+ windowsHide: true,
128
+ ...(options.signal ? { signal: options.signal } : {})
129
+ });
130
+ let stdout = '';
131
+ let stderr = '';
132
+ let settled = false;
133
+ let timer;
134
+ const finish = (run) => {
135
+ if (settled)
136
+ return;
137
+ settled = true;
138
+ if (timer)
139
+ clearTimeout(timer);
140
+ resolve(run);
141
+ };
142
+ const fail = (error) => {
143
+ if (settled)
144
+ return;
145
+ settled = true;
146
+ if (timer)
147
+ clearTimeout(timer);
148
+ reject(error);
149
+ };
150
+ child.stdout.on('data', (chunk) => {
151
+ if (stdout.length + chunk.length > MAX_STDOUT) {
152
+ child.kill('SIGKILL');
153
+ stderr += '\nEngine output exceeded the 8 MB limit.';
154
+ return;
155
+ }
156
+ stdout += chunk.toString('utf8');
157
+ });
158
+ child.stderr.on('data', (chunk) => {
159
+ if (stderr.length < MAX_STDERR)
160
+ stderr += chunk.toString('utf8');
161
+ });
162
+ child.on('error', fail);
163
+ if (options.stdin !== undefined) {
164
+ child.stdin.on('error', () => { });
165
+ child.stdin.end(options.stdin);
166
+ }
167
+ else {
168
+ child.stdin.end();
169
+ }
170
+ child.on('close', (code, signal) => {
171
+ const exitCode = typeof code === 'number' ? code : signal ? 1 : 0;
172
+ if (stderr.length > MAX_STDERR)
173
+ stderr = stderr.slice(0, MAX_STDERR) + '\n...(stderr truncated)';
174
+ finish({ exitCode, stdout, stderr });
175
+ });
176
+ timer = setTimeout(() => {
177
+ stderr += `\nEngine timed out after ${options.timeoutMs} ms.`;
178
+ child.kill('SIGKILL');
179
+ }, options.timeoutMs);
180
+ });
181
+ }
182
+ export async function engineVersion(binary, workspace, signal) {
183
+ const run = await runEngineBinary(binary, ['--version'], { cwd: workspace, timeoutMs: 10_000, ...(signal ? { signal } : {}) });
184
+ const match = run.stdout.match(/\b(\d+\.\d+(?:\.\d+)?)\b/);
185
+ return match?.[1] ?? null;
186
+ }
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
5
+ import { filmEngine } from './film.js';
6
+ import { photoEngine } from './photo.js';
7
+ import { soundEngine } from './sound.js';
8
+ import { cadEngine } from './cad.js';
9
+ import type { NativeEngineAdapter, NativeEngineRun } from './types.js';
10
+
11
+ const MAX_STDOUT = 8 * 1024 * 1024;
12
+ const MAX_STDERR = 1024 * 1024;
13
+
14
+ export const NATIVE_ENGINES: Record<string, NativeEngineAdapter> = {
15
+ [filmEngine.id]: filmEngine,
16
+ [photoEngine.id]: photoEngine,
17
+ [soundEngine.id]: soundEngine,
18
+ [cadEngine.id]: cadEngine
19
+ };
20
+
21
+ export function nativeEngine(id: string): NativeEngineAdapter | null {
22
+ return NATIVE_ENGINES[id] ?? null;
23
+ }
24
+
25
+ export function engineInstallDir(adapter: NativeEngineAdapter): string {
26
+ return path.join(causyneHome(), 'engines', adapter.id);
27
+ }
28
+
29
+ function inside(root: string, target: string): boolean {
30
+ const relative = path.relative(root, target);
31
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
32
+ }
33
+
34
+ function currentEngineBinary(adapter: NativeEngineAdapter): string | null {
35
+ const root = engineInstallDir(adapter);
36
+ const suffix = process.platform === 'win32' ? '.exe' : '';
37
+ try {
38
+ const value = JSON.parse(fs.readFileSync(path.join(root, 'current.json'), 'utf8')) as Record<string, unknown>;
39
+ if (typeof value.version !== 'string' || !/^[0-9A-Za-z][0-9A-Za-z._+-]{0,63}$/.test(value.version)) return null;
40
+ if (typeof value.platform !== 'string' || !/^[a-z0-9]+-[a-z0-9]+$/.test(value.platform)) return null;
41
+ const file = path.join(root, 'versions', value.version, value.platform, `${adapter.binaryName}${suffix}`);
42
+ return inside(root, file) ? file : null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ export function engineBinaryCandidates(adapter: NativeEngineAdapter): string[] {
49
+ const suffix = process.platform === 'win32' ? '.exe' : '';
50
+ const name = `${adapter.binaryName}${suffix}`;
51
+ const root = engineInstallDir(adapter);
52
+ return [
53
+ path.join(root, 'current', 'bin', name),
54
+ path.join(root, 'current', name),
55
+ path.join(root, 'bin', name),
56
+ path.join(root, name)
57
+ ];
58
+ }
59
+
60
+ function executable(file: string): boolean {
61
+ try {
62
+ if (!fs.statSync(file).isFile()) return false;
63
+ if (process.platform === 'win32') return true;
64
+ fs.accessSync(file, fs.constants.X_OK);
65
+ return true;
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ function isShebangScript(file: string): boolean {
72
+ try {
73
+ const fd = fs.openSync(file, 'r');
74
+ const buf = Buffer.alloc(2);
75
+ const read = fs.readSync(fd, buf, 0, 2, 0);
76
+ fs.closeSync(fd);
77
+ return read === 2 && buf[0] === 0x23 && buf[1] === 0x21;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ export function findEngineBinary(adapter: NativeEngineAdapter): string | null {
84
+ const override = process.env[adapter.envVar];
85
+ if (override && override.trim()) {
86
+ const candidate = resolveUserPath(override.trim());
87
+ const file = (() => {
88
+ try { return fs.statSync(candidate).isDirectory(); } catch { return false; }
89
+ })() ? path.join(candidate, adapter.binaryName + (process.platform === 'win32' ? '.exe' : '')) : candidate;
90
+ if (executable(file)) return fs.realpathSync(file);
91
+ }
92
+ const current = currentEngineBinary(adapter);
93
+ if (current && executable(current)) return fs.realpathSync(current);
94
+ for (const candidate of engineBinaryCandidates(adapter)) {
95
+ if (executable(candidate)) return fs.realpathSync(candidate);
96
+ }
97
+ return null;
98
+ }
99
+
100
+ function childEnv(): NodeJS.ProcessEnv {
101
+ const keys = [
102
+ 'PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'TMPDIR',
103
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME'
104
+ ];
105
+ const env: NodeJS.ProcessEnv = {};
106
+ for (const key of keys) {
107
+ const value = process.env[key];
108
+ if (value !== undefined) env[key] = value;
109
+ }
110
+ env.NO_COLOR = '1';
111
+ return env;
112
+ }
113
+
114
+ export function runEngineBinary(
115
+ binary: string,
116
+ args: string[],
117
+ options: { cwd: string; timeoutMs: number; stdin?: string; signal?: AbortSignal }
118
+ ): Promise<NativeEngineRun> {
119
+ options.signal?.throwIfAborted();
120
+ const isScript = process.platform === 'win32' && isShebangScript(binary);
121
+ const command = isScript ? process.execPath : binary;
122
+ const commandArgs = isScript ? [binary, ...args] : args;
123
+
124
+ return new Promise((resolve, reject) => {
125
+ const child = spawn(command, commandArgs, {
126
+ cwd: options.cwd,
127
+ env: childEnv(),
128
+ stdio: ['pipe', 'pipe', 'pipe'],
129
+ windowsHide: true,
130
+ ...(options.signal ? { signal: options.signal } : {})
131
+ });
132
+
133
+ let stdout = '';
134
+ let stderr = '';
135
+ let settled = false;
136
+ let timer: NodeJS.Timeout | undefined;
137
+ const finish = (run: NativeEngineRun): void => {
138
+ if (settled) return;
139
+ settled = true;
140
+ if (timer) clearTimeout(timer);
141
+ resolve(run);
142
+ };
143
+ const fail = (error: Error): void => {
144
+ if (settled) return;
145
+ settled = true;
146
+ if (timer) clearTimeout(timer);
147
+ reject(error);
148
+ };
149
+
150
+ child.stdout.on('data', (chunk: Buffer) => {
151
+ if (stdout.length + chunk.length > MAX_STDOUT) {
152
+ child.kill('SIGKILL');
153
+ stderr += '\nEngine output exceeded the 8 MB limit.';
154
+ return;
155
+ }
156
+ stdout += chunk.toString('utf8');
157
+ });
158
+ child.stderr.on('data', (chunk: Buffer) => {
159
+ if (stderr.length < MAX_STDERR) stderr += chunk.toString('utf8');
160
+ });
161
+ child.on('error', fail);
162
+ if (options.stdin !== undefined) {
163
+ child.stdin.on('error', () => {});
164
+ child.stdin.end(options.stdin);
165
+ } else {
166
+ child.stdin.end();
167
+ }
168
+ child.on('close', (code, signal) => {
169
+ const exitCode = typeof code === 'number' ? code : signal ? 1 : 0;
170
+ if (stderr.length > MAX_STDERR) stderr = stderr.slice(0, MAX_STDERR) + '\n...(stderr truncated)';
171
+ finish({ exitCode, stdout, stderr });
172
+ });
173
+
174
+ timer = setTimeout(() => {
175
+ stderr += `\nEngine timed out after ${options.timeoutMs} ms.`;
176
+ child.kill('SIGKILL');
177
+ }, options.timeoutMs);
178
+ });
179
+ }
180
+
181
+ export async function engineVersion(binary: string, workspace: string, signal?: AbortSignal): Promise<string | null> {
182
+ const run = await runEngineBinary(binary, ['--version'], { cwd: workspace, timeoutMs: 10_000, ...(signal ? { signal } : {}) });
183
+ const match = run.stdout.match(/\b(\d+\.\d+(?:\.\d+)?)\b/);
184
+ return match?.[1] ?? null;
185
+ }